assert_context#
The assert_context module exposes a context manager that verifies whether code within a with block behaves as expected. It checks whether a exception of a specific type matching specific value was (or wasn't) raised within the block and whether the result of the block (settable by the user) matches the expected value.
Module exposes ExceptionMatch class which allows to specify not only type of expected exception, but also a string which shall match raised exception value.
Additionally, it provides the AssertContext class, which can be useful for typing in more complex scenarios, as it is the type returned by the __enter__ method.
Basic Example#
The following code snippet demonstrates how to use assert_context. It asserts that the result of fun() will be 'something' and that bar() will raise a ValueError.
| Python | |
|---|---|
Parameters#
The context manager defines three optional keyword parameters: exception, result, and behaviour. The pair of parameters (exception, result) is mutually exclusive with the behaviour parameter. If behaviour is set, the other parameters must remain unset.
exception Parameter#
- If the
exceptionparameter is set to exception type, thewithblock is expected to raise an exception of the provided type. - If the
exceptionparameter is set to an instance ofExceptionMatchclass, thewithblock is expected to raise an exception of type specified intype_field and the value that matches the string specified inmatch_field. For exact matching logic seematchparameter of thepytest.raises. - If the
exceptionparameter is NOT set or is set toNone, thewithblock is expected NOT to raise any exceptions.
Examples#
Code not raising any exceptions:
| Python | |
|---|---|
Code raising a ValueError:
| Python | |
|---|---|
Code calling pytest.fail (equivalent to pytest.raises(ValueError)):
result Parameter#
- If the
resultparameter is set, its value is expected to be equal to the result of thewithblock. - The
withblock result is set using thesetmethod of an object yielded by the context manager. - The comparison is performed using the
==operator, with theresultargument on the left side. - If the
resultparameter is NOT set, thesetmethod of the yielded object is expected not to be called at all.
Examples#
Code not raising any exceptions:
| Python | |
|---|---|
Code raising an AssertionError:
| Python | |
|---|---|
Combining exception and result Parameters#
Both exception and result parameters can be set simultaneously to check more complex code.
Example#
Code not raising any exceptions:
| Python | |
|---|---|
behaviour Parameter#
- If
behaviouris set to an exception type orExceptionMatchinstance, it is equivalent to settingexceptionto the same value and leavingresultunset. - If
behaviouris set to any other value, it is treated as the value ofresult, and theexceptionparameter remains unset.
Examples#
Code not raising any exceptions:
| Python | |
|---|---|
Code raising exceptions: