Testing with pytest
Explore how to create automated tests in Python using the pytest framework. Learn to write simple test functions with assert statements, manage resources with fixtures and yield for setup and teardown, and use parameterized tests to avoid duplicating code. This lesson helps you understand pytest's test discovery, detailed failure reports, and how it streamlines testing to improve code reliability and maintainability.
We have seen that unittest is a powerful testing framework, but it comes with a fair amount of structure. Writing tests often requires creating classes, inheriting from TestCase, and remembering specialized assertion methods. For simple checks, this boilerplate can distract from the core testing logic.
pytest follows a different testing approach. It treats tests as standard Python code. It does not require base classes or custom assertion methods. Tests are written as simple functions that use Python’s built-in assert statement. pytest functions as a test runner that automatically discovers test files and functions, executes them, and generates detailed failure reports. This approach keeps tests concise and focused on program behavior rather than framework details.
Writing tests with plain assertions
Before writing tests with pytest, the framework must be installed. Because it is not included in Python’s standard library, it is installed using the package manager:
pip install pytest
Once installed, we do not run tests by invoking python directly. Instead, we use the pytest command itself. For example, to run tests in a specific file, we execute:
pytest name_of_file.py
Pytest also supports running all tests in a project simply by running pytest in the project directory.