The pytest Framework
Learn how to use pytest in Python to perform unit testing.
We'll cover the following
One great testing framework is pytest
, which can be installed via pip install pytest
. One difference with respect to unittest
is that, while it's still possible to classify test scenarios in classes and create object-oriented models of our tests, this is not actually mandatory, and it's possible to write unit tests with less boilerplate by just checking the conditions we want to verify in simple functions with the assert
statement.
By default, making comparisons with an assert
statement will be enough for pytest
to identify a unit test and report its result accordingly. More advanced uses are also possible, but they require the use of specific functions from the package.
A nice feature is that the pytest
command will run all the tests that it can discover, even if they were written with unittest
. This compatibility makes it easier to transition from unittest
to pytest
gradually.
Basic test cases with pytest
The conditions we tested with unittest
can be rewritten in simple functions with pytest
.
Some examples with simple assertions are:
Get hands-on with 1400+ tech skills courses.