pytest is one of the most popular testing frameworks in Python.
It makes writing and running tests simple and efficient.
See the official documentation for more details:
https://docs.pytest.org/en/stable/index.html
Installing pytest:
To install
pytest for the current user:
Alternatively, to install it globally on Ubuntu:
To verify the installation:
Output:
pytest.ini:
The pytest.ini file is used to configure pytest behavior.
It takes precedence, even when empty, over other config files.
You may also use a hidden version named .pytest.ini.
Create a pytest.ini file in your project's root directory:
Assertions:
Assertions are used to validate conditions in unit tests.
-
Basic assertions:
-
Collection assertions:
-
Numeric assertions:
-
Type assertions:
-
Exception assertions:
Simple unit test:
-
Create a file hello.py that contains a simple function 'hello':
-
Create a unit test file test_hello.py:
-
To execute the unit test, open a terminal and run 'pytest' command from the project folder:
Output:
-
If the test encounters a failed assertion or an unexpected exception, pytest will report the test as failed or errored.
Here's an example of a unit test that will fail:
Running pytest on this test will produce the following errors:
Using Fixtures:
Fixtures (
@pytest.fixture) in pytest provide a flexible way to
set up test data,
create and inject mock objects into unit tests,
and establish reusable test environments across multiple test functions.
-
Create a file addition.py that contains a simple class 'Addition':
-
Create a unit test file test_addition.py:
-
To execute the unit test, open a terminal and run 'pytest' command from the project folder:
Fixture Scopes:
Fixtures can have different scopes to optimize test execution.
-
Fixtures recreated for each test (default):
-
Fixtures shared across all tests in a class:
-
Fixtures shared across all tests in a module:
-
Fixtures shared across entire test session: