10 Awesome Features of Pytest
Pytest for the win!
Join the DZone community and get the full member experience.
Join For FreePytest is a test automation framework that lets you write simple to complex functional tests. This tutorial will walk you through the great features of Pytest, including:
- Easy to start with and simple syntax.
- Open Source.
- Build-in support for test discovery.
- Command-line support.
- Extensibility: Plug-ins, hooks.
- Fixtures.
- Works with built-in unit tests.
- Large community support.
To install Pytest, run the following command:
pip install pytest
1. Auto-Discovery of Tests
Pytest's default finds tests with the file name with the preface, "test," or the suffix "_test.py." However, we can configure Pytest to discover custom names by changing the Pytest configuration file “pytest.ini.” By adding the following extension, Pytest automatically discovers tests with the filename “check.” However, in this tutorial, we stick to the default extension "test."
[pytest]
python_files = check_*.py
python_classes = Check
python_functions = *_check
2. Creating Tests
It’s very easy to get started creating tests. Create a file, test_demo.py
, and write the following code — this will create our first test.
import pytest
def test_addition():
assert 2+5 ==7
Output: 'pytest -v' runs test
3. Command Line Execution
Pytest provides several options to run tests from the command line.
pytest -v -s #verbosity and execution time of test
e.g:pytest –v –s
pytest <file_name> #run tests in module/file
e.g:pytest test_demo.py
pytest <path> #run all tests below path
e.g:pytest c:/dev/pytestdemo
pytest –k <name> #run all the test with matching name
e.g:pytest –k add #runs all the test with add
pytest filename::testName #runs only one test
e.g:pytest test_demo::test_addition
4. Parameterization
Pytest supports parametrization. To enable parameterization, we need to import mark
and annotate tests with a parameter marker. Parameterization tests look cleaner with large sets of data.
import pytest
from pytest import mark
@mark.parametrize("num1, num2 ,expected",
[(2, 5, 7),
(3, 7, 10)])
def test_addition(num1, num2, expected):
assert num1 + num2 == expected
Output:
5. Fixtures
Fixtures are functions that run before each test function. Generally, fixtures are great to use to set up data to run tests. Common usages are to set up a database connection, URLs, and input data. Instead of running the same code, we can attach fixtures.
The following code uses input value 15 and verifies both test cases, division by 3 and division by 5.
import pytest
@pytest.fixture
def input_value():
input = 15
return input
def test_div_3(input_value):
input_value % 3 == 0
def test_div_5(input_value):
input_value % 5 == 0
6. Hooks
While we are running tests, it's quite common to run a test setup, tear down, and log events of test. Pytest allows users to customize these events using hooks.
Here are sample hooks defined on conftest.py.
import pytest
def pytest_runtest_setup(item):
print("pytest_runtest_setup")
def pytest_runtest_logreport(report):
print(f'Log Report:{report}')
def pytest_sessionstart(session):
print("pytest_session start")
def pytest_sessionfinish(session):
print("pytest_session finish")
def pytest_collection_modifyitems(session, config, items):
for item in items:
print(f"pytest_collection_modify items{item}", item)
def pytest_collection_finish(session):
print('pytest_collection_finish')
Output:
7. Markers: Grouping Tests
Markers are a great way to add meta-information to our tests. For example, there is an instance to run all P0 test cases, slow test, flaky test, or skipping a test
Example of marking regression test:
@mark.parametrize("num1, num2 ,expected",
[(2, 5, 7),
(3, 7, 10)])
@pytest.mark.regression
def test_addition(num1, num2, expected):
assert num1 + num2 == expected
Skip a test:
@pytest.mark.skip
def test_skip():
pass
Output:
8. Plug-ins
The Pytest community has a rich test of plug-ins to extend the module's functionality.
8.1 Xdist
Xdist is a popular plug-in enables Pytest to tests in parallel
#installs plug-in
pip install pytest-xdist
#runs tests in parallel
pytest –n <numberof CPU cycles>
Output:
9. Reporting
Pytest supports generating reports in JUnit format. By creating the XML file CI/CD systems like Jenkins can read the log files.
pytest --junitxml=path
Output:
10. Unittest Compatibility
Pytest supporting running unittest based test out of the box. To run the existing unittest style test suite using Pytest.
pytest tests
Pytest is very popular in the Python community, and it's growing year over year. Now, you should be able to take advantage of these features while creating tests. There is plug-in pytest-Django supports Django web applications.
List of third party plug-ins: https://pytest.readthedocs.io/en/2.7.3/plugins_index/index.html.
The following examples explain the above tutorial are shared on GitHub: https://github.com/gmadhusureshn/pytestdemo.
Further Reading
Opinions expressed by DZone contributors are their own.
Comments