Skip to main content
Log in

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. For instance:

from testing import assert_raises

# Good! Caught the raised error, test passes
with assert_raises():
raise "SomeError"

# Also good!
with assert_raises(contains="Some"):
raise "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 "OtherError"
from testing import assert_raises

# Good! Caught the raised error, test passes
with assert_raises():
raise "SomeError"

# Also good!
with assert_raises(contains="Some"):
raise "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 "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, UnknownDestructibility

Methods

__init__

__init__(out self, *, location: Optional[_SourceLocation] = Optional(None))

Construct a context manager with no message pattern.

Args:

  • location (Optional[_SourceLocation]): The location of the error (default to the __call_location).

__init__(out self, *, contains: String, location: Optional[_SourceLocation] = Optional(None))

Construct a context manager matching specific errors.

Args:

  • contains (String): The test will only pass if the error message includes the literal text passed.
  • location (Optional[_SourceLocation]): The location of the error (default to the __call_location).

__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__(self, error: Error) -> Bool

Exit the context manager with an error.

Args:

  • error (Error): The error raised.

Returns:

True if the error message contained the expected string.

Raises:

Error: If the error raised doesn't include the expected string.