pytest
The pytest framework makes it easy to write small tests, yet scales to support complex functional testing
Pytest is a Python testing framework that automatically discovers and runs test functions, produces clear failure messages from plain assert statements, and supports over 1300 plugins for coverage, parallelism, and more.
Pytest is a testing framework for Python. When you write software in Python, you also write small scripts that check whether your code does what it is supposed to do. Pytest runs those check scripts, reports which ones pass and which ones fail, and gives you enough detail to understand what went wrong.
The main thing that sets pytest apart from Python's built-in testing tools is how it handles failure messages. You write checks using plain Python "assert" statements, nothing special, and pytest figures out what both sides of the comparison were, then prints them clearly when the check fails. Other testing libraries require you to use specific method names like "assertEquals" or "assertIn" to get useful error output; pytest does not.
Pytest finds your test files and functions automatically. By convention, test files start with "test_" and test functions also start with "test_". When you run the "pytest" command from your project directory, it scans for those files and runs what it finds, with no extra configuration required for basic use. It can also run tests written for Python's older built-in unittest format, so you do not have to rewrite existing tests to adopt it.
One of pytest's more advanced features is its fixture system. Fixtures are reusable pieces of setup code, such as a database connection or a temporary directory, that tests can share. You define a fixture once and pytest injects it into any test that declares it needs it, cleaning up afterward if the fixture is set up to do so.
The project has a large ecosystem of add-ons: over 1300 external plugins are listed in the docs. These cover things like running tests in parallel, generating HTML reports, measuring test coverage, and integrating with other frameworks. Pytest runs on Python 3.10 and above, and PyPy3 is also supported.
Where it fits
- Write and run automated tests for a Python project using plain assert statements with no special method names required.
- Share reusable setup code between tests, like database connections or temporary directories, using pytest fixtures.
- Run existing unittest-style tests in a project without rewriting them to adopt pytest.
- Add plugins to run tests in parallel, generate HTML reports, or measure code coverage.