A collection of examples for testing python code using pytest.
demo-python-testing-examples/
├── examples/
│ ├── example_1.py
│ ├── ...
│ ├── example_N.py
│ └── further_examples/
│ ├── example_Nplus1.py
│ └── ...
├── tests/
│ ├── conftest.py
│ ├── test_example_1.py
│ ├── ...
│ ├── test_example_N.py
│ └── further_examples/
│ ├── test_example_Nplus1.py
│ └── ...
├── pyproject.toml
└── ...
Consider in the file example/further_examples/example_Nplus1.py
there is a function named complex_function_15
. All the tests concerning this function will be found in the file named tests/further_examples/test_example_Nplus1.py
in a class named TestComplexFunction15
.
By structuring your code and tests in this manner it is trivial for anyone looking at the code to be able to locate all the tests for any part of the code with ease.
A basic example which demonstrates how a test suite for a function should be structured.
This example demonstrates how to test a function which has a known raise statement within it. The example contains 2 functions:
raise_runtime_error
simply raises aRuntimeError
and the corresponding tests ensure that this is the raised exceptionraise_value_error
can raise two differentValueError
s depending on the value passed to the function. To ensure that the wrong excepction isn't being raised for each case, the tests make use of thematch
parameter in thepytest.raises
context manager This ensures that not only the specified excpetion is raised, but also with the matching message.
(See also the pytest documentation on expected exceptions)
This example shows how a single function can be tested with more than one set of inputs in a succinct DRY manner. The test code demonstrates using
- the built in pytest
parametrize
functionality - the use of custom
parametrize_cases
andCase
code which is kept inconftest.py
The benefit of using option 2 is that it provides more readable test cases compared to the built in functionality.
This example demonstrates how to combine the reusability of fixtures with parameterised tests. In particular using built in functionality as well as an additional pytest add in helper to simplify the usage.
See this for an example of using the built in usage in more detail.
- Positive and negative
- skipped test
- xfail test
- passing xfail test
- test coverage
- pytest output