How to write and report assertions in tests¶
Asserting with the assert statement¶
pytest allows you to use the standard Python assert for verifying expectations and values in Python tests. For example, you can write the following:
to assert that your function returns a certain value. If this assertion fails you will see the return value of the function call:
pytest has support for showing the values of the most common subexpressions including calls, attributes, comparisons, and binary and unary operators. (See Demo of Python failure reports with pytest). This allows you to use the idiomatic python constructs without boilerplate code while not losing introspection information.
If a message is specified with the assertion like this:
it is printed alongside the assertion introspection in the traceback.
See Assertion introspection details for more information on assertion introspection.
Assertions about approximate equality¶
When comparing floating point values (or arrays of floats), small rounding errors are common. Instead of using assert abs(a - b) < tol or numpy.isclose, you can use pytest.approx():
pytest.approx works with scalars, lists, dictionaries, and NumPy arrays. It also supports comparisons involving NaNs.
See pytest.approx() for details.
Assertions about expected exceptions¶
In order to write assertions about raised exceptions, you can use pytest.raises() as a context manager like this:
and if you need to have access to the actual exception info you may use:
excinfo is an ExceptionInfo instance, which is a wrapper around the actual exception raised. The main attributes of interest are .type, .value and .traceback.
Note that pytest.raises will match the exception type or any subclasses (like the standard except statement). If you want to check if a block of code is raising an exact exception type, you need to check that explicitly:
The pytest.raises() call will succeed, even though the function raises NotImplementedError, because NotImplementedError is a subclass of RuntimeError; however the following assert statement will catch the problem.
Matching exception messages¶
You can pass a match keyword parameter to the context-manager to test that a regular expression matches on the string representation of an exception (similar to the TestCase.assertRaisesRegex method from unittest):
Notes:
The match parameter is matched with the re.search() function, so in the above example match='123' would have worked as well.
The match parameter also matches against PEP-678 __notes__.
Assertions about expected exception groups¶
When expecting a BaseExceptionGroup or ExceptionGroup you can use pytest.RaisesGroup:
It accepts a match parameter, that checks against the group message, and a check parameter that takes an arbitrary callable which it passes the group to, and only succeeds if the callable returns True.
It is strict about structure and unwrapped exceptions, unlike except*, so you might want to set the flatten_subgroups and/or allow_unwrapped parameters.
To specify more details about the contained exception you can use pytest.RaisesExc
They both supply a method pytest.RaisesGroup.matches() pytest.RaisesExc.matches() if you want to do matching outside of using it as a context manager. This can be helpful when checking .__context__ or .__cause__.
Check the documentation on pytest.RaisesGroup and pytest.RaisesExc for more details and examples.
ExceptionInfo.group_contains()¶
Warning
This helper makes it easy to check for the presence of specific exceptions, but it is very bad for checking that the group does not contain any other exceptions. So this will pass:
There is no good way of using excinfo.group_contains() to ensure you’re not getting any other exceptions than the one you expected. You should instead use pytest.RaisesGroup, see Assertions about expected exception groups.
You can also use the excinfo.group_contains() method to test for exceptions returned as part of an ExceptionGroup:
The optional match keyword parameter works the same way as for pytest.raises().
By default group_contains() will recursively search for a matching exception at any level of nested ExceptionGroup instances. You can specify a depth keyword parameter if you only want to match an exception at a specific level; exceptions contained directly in the top ExceptionGroup would match depth=1.
Alternate pytest.raises form (legacy)¶
There is an alternate form of pytest.raises() where you pass a function that will be executed, along with *args and **kwargs. pytest.raises() will then execute the function with those arguments and assert that the given exception is raised:
The reporter will provide you with helpful output in case of failures such as no exception or wrong exception.
This form was the original pytest.raises() API, developed before the with statement was added to the Python language. Nowadays, this form is rarely used, with the context-manager form (using with) being considered more readable. Nonetheless, this form is fully supported and not deprecated in any way.
xfail mark and pytest.raises¶
It is also possible to specify a raises argument to pytest.mark.xfail, which checks that the test is failing in a more specific way than just having any exception raised:
This will only “xfail” if the test fails by raising IndexError or subclasses.
Using pytest.mark.xfail with the raises parameter is probably better for something like documenting unfixed bugs (where the test describes what “should” happen) or bugs in dependencies.
Using pytest.raises() is likely to be better for cases where you are testing exceptions your own code is deliberately raising, which is the majority of cases.
You can also use pytest.RaisesGroup:
Assertions about expected warnings¶
You can check that code raises a particular warning using pytest.warns.
Making use of context-sensitive comparisons¶
pytest has rich support for providing context-sensitive information when it encounters comparisons. For example:
if you run this module:
Special comparisons are done for a number of cases:
comparing long strings: a context diff is shown
comparing long sequences: first failing indices
comparing dicts: different entries
In string context diffs, lines prefixed with - come from the left-hand side of assert left == right, while lines prefixed with + come from the right-hand side.
See the reporting demo for many more examples.
Defining your own explanation for failed assertions¶
It is possible to add your own detailed explanations by implementing the pytest_assertrepr_compare hook.
pytest_assertrepr_compare(config, op, left, right)[source]Return explanation for comparisons in failing assert expressions.
Return None for no custom explanation, otherwise return a list of strings. The strings will be joined by newlines but any newlines in a string will be escaped. Note that all but the first line will be indented slightly, the intention is for the first line to be a summary.
Parameters:config (Config) – The pytest config object.
op (str) – The operator, e.g. "==", "!=", "not in".
left (object) – The left operand.
right (object) – The right operand.
Use in conftest plugins¶
Any conftest file can implement this hook. For a given item, only conftest files in the item’s directory and its parent directories are consulted.
As an example consider adding the following hook in a conftest.py file which provides an alternative explanation for Foo objects:
now, given this test module:
you can run the test module and get the custom output defined in the conftest file:
Returning non-None value in test functions¶
A pytest.PytestReturnNotNoneWarning is emitted when a test function returns a value other than None.
This helps prevent a common mistake made by beginners who assume that returning a bool (e.g., True or False) will determine whether a test passes or fails.
Example:
Since pytest ignores return values, it might be surprising that the test will never fail based on the returned value.
The correct fix is to replace the return statement with an assert:
Assertion introspection details¶
Reporting details about a failing assertion is achieved by rewriting assert statements before they are run. Rewritten assert statements put introspection information into the assertion failure message. pytest only rewrites test modules directly discovered by its test collection process, so asserts in supporting modules which are not themselves test modules will not be rewritten.
You can manually enable assertion rewriting for an imported module by calling register_assert_rewrite before you import it (a good place to do that is in your root conftest.py).
For further information, Benjamin Peterson wrote up Behind the scenes of pytest’s new assertion rewriting.
Assertion rewriting caches files on disk¶
pytest will write back the rewritten modules to disk for caching. You can disable this behavior (for example to avoid leaving stale .pyc files around in projects that move files around a lot) by adding this to the top of your conftest.py file:
Note that you still get the benefits of assertion introspection, the only change is that the .pyc files won’t be cached on disk.
Additionally, rewriting will silently skip caching if it cannot write new .pyc files, e.g. in a read-only filesystem or a zipfile.
Disabling assert rewriting¶
pytest rewrites test modules on import by using an import hook to write new pyc files. Most of the time this works transparently. However, if you are working with the import machinery yourself, the import hook may interfere.
If this is the case you have two options:
Disable rewriting for a specific module by adding the string PYTEST_DONT_REWRITE to its docstring.
Disable rewriting for all modules by using --assert=plain.