Mojo struct
assert_raises
struct assert_raises
Context manager that asserts that the block raises an exception.
You can use this to test expected error cases, and to test that the correct
errors are raised. Works with Error and any custom Writable error type.
For instance:
from std.testing import assert_raises
# Good! Caught the raised error, test passes
with assert_raises():
raise Error("SomeError")
# Also good!
with assert_raises(contains="Some"):
raise Error("SomeError")
# This will assert, we didn't raise
with assert_raises():
pass
# This will let the underlying error propagate, failing the test
with assert_raises(contains="Some"):
raise Error("OtherError")Fields
- message_contains (
Optional[String]): If present, check that the error message contains this literal string. - call_location (
SourceLocation): Assigned the value returned by call_locations() at Self.init.
Implemented traits
AnyType,
ImplicitlyDestructible
Methods
__init__
__init__(out self, *, location: Optional[SourceLocation] = None)
Construct a context manager with no message pattern.
Args:
- location (
Optional): The location of the error (defaults tocall_location).
__init__(out self, *, contains: String, location: Optional[SourceLocation] = None)
Construct a context manager matching specific errors.
Args:
__enter__
__enter__(self)
Enter the context manager.
__exit__
__exit__(self)
Exit the context manager with no error.
Raises:
AssertionError: Always. The block must raise to pass the test.
__exit__[E: AnyType](self, error: E) -> Bool
Exit the context manager with an error.
Works with Error and any custom Writable error type. When
contains is specified, the error type must be Writable so
it can be converted to a string for matching.
Parameters:
- E (
AnyType): The error type.
Args:
- error (
E): The error raised.
Returns:
Bool: True if the error was successfully caught and matched.
Raises:
Error: If contains is set and the error message doesn't
include the expected string, or if contains is set
but the error type is not Writable.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!