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
exception
parameter is set to exception type, thewith
block is expected to raise an exception of the provided type. - If the
exception
parameter is set to an instance ofExceptionMatch
class, thewith
block 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 seematch
parameter of thepytest.raises
. - If the
exception
parameter is NOT set or is set toNone
, thewith
block 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
result
parameter is set, its value is expected to be equal to the result of thewith
block. - The
with
block result is set using theset
method of an object yielded by the context manager. - The comparison is performed using the
==
operator, with theresult
argument on the left side. - If the
result
parameter is NOT set, theset
method 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
behaviour
is set to an exception type orExceptionMatch
instance, it is equivalent to settingexception
to the same value and leavingresult
unset. - If
behaviour
is set to any other value, it is treated as the value ofresult
, and theexception
parameter remains unset.
Examples#
Code not raising any exceptions:
Python | |
---|---|
Code raising exceptions: