Table of Contents
Introduction to Pytest
Pytest is a robust Python testing framework that facilitates the creation of straightforward and expandable tests. It has many features that make writing, planning, and administering tests easier. Since its launch, Pytest has become incredibly well-liked and widely used in the Python community. This article will walk you through the 10 awesome Pytest features.
Pytest Acceptance and Popularity
Pytest testing framework has become very popular and widely accepted by Python developers. Here are some reasons:
Readability and Simplicity: Pytest provides a straightforward test writing syntax that makes it simple for both novice and seasoned engineers to create and manage test suites. Because of its simple test code design, it promotes clear and understandable test cases, which improves the overall quality of the code.
Extensive Feature Set: Pytest is pre-installed with a wide range of functionalities to meet different testing requirements. With pytest, developers can write comprehensive and effective tests for their Python programs, covering everything from fixture management and parameterization to robust assertion introspection and plugin support. In this blog post, we will share 10 awesome features of pytest.
Extensions: Pytest’s ability to be extended via plugins is one of its best features. With so many plugins available to expand its functionality, the pytest ecosystem enables developers to tailor and improve their testing experience to meet their unique needs. There is probably a pytest plugin out there to meet the demand, be it for creating test reports, adding support for new testing paradigms, or connecting with other tools.
Test Execution and Discovery: Finding and running tests within a project is a breeze because of Pytest’s clever test discovery mechanism. Pytest does not require explicit configuration because it automatically finds and runs test functions by using normal Python naming conventions. Furthermore, pytest provides a number of test execution options, such as parallel test execution, selective test execution, and integration with continuous integration (CI) systems.
Support and Documentation from the Community: Pytest has a thriving and helpful developer community that actively participates in its upkeep and growth. The official Pytest documentation is extensive and kept up-to-date, with detailed instructions on how to get started, write tests, and take advantage of additional capabilities. In addition, the responsiveness of the community on forums, mailing lists, and social media platforms guarantees that developers may ask questions and exchange experiences with pytest with ease.
Pytest Environment Setup:
- Download and install Python as per your system operating system if python is not available in your system. Here is the link: https://www.python.org/downloads/ Please follow the steps which are coming during installation of the python application.
- There are multiple editor and IDE supported for python code development like PyCharm, Visual Studio Code, and Eclipse. Please use any one for your development.
- Install pytest framework from the command line.
# pip install -U pytest - Verify pytest installation by checking pytest version using a command.
- # pytest –version
10 Wonderful Pytest Features:
Test Discovery: All the test files and functions in your project directory and its subdirectories are immediately found by Pytest, this facilitates the organization and execution of your tests without the need for explicit configuration. The default name of the script file should start with ‘test’ or end with the ‘_test.py’ suffix for the automatic discovery of the Python files to be executed.
We can also change the default discovery to some other word; in that case, the custom name should be mentioned in the ‘Pytest.ini’ file. Let’s change the default discovery word from ‘test’ to ‘verify’. In this case, the developer needs to declare the configuration file as below:
[pytest]
python_files = verify _*.py
python_classes = verify
python_functions = *_ verify
Simple Syntax: Pytest offers an easy-to-use syntax for creating tests. Assert statements are used to verify conditions in tests, which are expressed as Python functions. Let’s create a simple case of addition using pytest.
import pytest
def test_add():
assert 3+4 == 7
Output
C: \pytest>python -m pytest test_sample.py
================================================= test session starts =================================================
platform win32 -- Python 3.8.2, pytest-8.1.1, pluggy-1.4.0
rootdir: C: \pytest
collected 1 item
test_sample.py . [100%]
================================================== 1 passed in 0.00s ==================================================
Markers: Pytest enables you to execute or skip tests depending on specific markers. You can also mark tests with custom markers. This is helpful for setting up and managing the tests that are run in various scenarios. Please visit https://dasfascination.com/enhance-testing-pytest-marker/ to learn more about markers.
Parameterized Testing: Tests with various sets of input parameters can be executed simultaneously with Pytest’s support due to the feature parameterized testing. This makes it easier to test a function with different inputs without having to create unique test cases for every input.
import pytest
@pytest.mark.parametrize("input_val, output", [(1,3),(3,5),(5,7)])
def test_add(input_val, output):
assert input_val + 2 == output
Output
C:\ pytest>python -m pytest -s test_marker.py -m parametrize -v -s --disable-pytest-warnings
================================================= test session starts =================================================
platform win32 -- Python 3.8.2, pytest-8.1.1, pluggy-1.4.0 -- C:\Program Files\Python38\python.exe
cachedir: .pytest_cache
rootdir: C: \pytest
collected 7 items / 4 deselected / 3 selected
test_marker.py::test_add[1-3] PASSED
test_marker.py::test_add[3-5] PASSED
test_marker.py::test_add[5-7] PASSED
===================================== 3 passed, 4 deselected, 4 warnings in 0.00s =====================================
Fixture Feature: You can specify setup and teardown code that can be reused across tests with Pytest’s robust fixture framework. There are various levels at which fixtures can be scoped, including function, module, class, and session. Please visit https://dasfascination.com/pytest-fixtures-test-setup-teardown/ for details.
Assertions: A wide range of conditions and expectations may be easily expressed in tests with Pytest’s broad set of assertion aids. Basic assertion methods, such as assert, assertEqual, assertTrue, assertFalse, etc., allow developers to make simple assertions about the state of their code. pytest provides comparison assertions for verifying numerical values, sequences, etc.
def test_comp_assertions():
assert 6 > 5
assert [1, 2, 3] == [3, 2, 1]
In order to write assertions about raised exceptions, pytest.raises() is used
def test_zero_division():
with pytest.raises(ZeroDivisionError):
1 / 0
To learn in detail, please browse https://docs.pytest.org/en/7.1.x/how-to/assert.html
Command line Test Execution: Pytest offers a convenient command-line interface for locating and executing tests within a Python project. This is another very good pytest feature.
To run all tests in the current directory and its subdirectories, simply navigate to the project directory containing your test and type.
# pytest -v #-v for verbosity
To run specific tests or test files,
# pytest test_module.py # Run tests in a specific test module
# pytest test_module.py::test_function #Run specific test within a module
Test names, markers, expressions, and other criteria can all be used to choose and run tests with Pytest. To specify a substring match for test names, use the -k option:
$ pytest -k login # Run tests with add in their names.
Reporting: Pytest supports xml reporting with the details of all the test execution. Jenkins and other CI/CD systems can read the XML file. You need to add ‘–junitxml=path_of xml_report’ in
your command-line execution. After running a single test case, which is described in the parametrized testing section, the report xml looks as follows:
Plugin System: Pytest’s capabilities can be expanded through a robust ecosystem of plugins. For functions like test data generation, test parallelization, code coverage analysis, and many more, plugins are provided.
- pytest-cov: Pytest can generate coverage reports using this plugin, which shows which parts of your code are covered by tests and which are not.
- pytest-xdist: Xdist is a popular plug-in that enables Pytest to run tests in parallel, significantly reducing the time taken to execute tests,
There are many more plugins supported by pytest framework.
Unittest Compatibility: With Pytest’s high degree of compatibility with Python’s integrated unittest framework, developers may switch between the two testing frameworks with ease and without compromising on ease of use or functionality. Because of this compatibility, developers may take advantage of all of pytest’s robust features while still getting the familiarity and structure of unittest.
2 Replies to “The Power of Pytest: 10 fantastic pytest features”