Pytest Explained

Pytest
Pytest
Logo Size:200px
Author:Krekel et al.
Programming Language:Python
Platform:macOS, Windows, POSIX
Genre:Framework for software testing
License:MIT License

Pytest is a Python testing framework that originated from the PyPy project. It can be used to write various types of software tests, including unit tests, integration tests, end-to-end tests, and functional tests. Its features include parametrized testing, fixtures, and assert re-writing.

Pytest fixtures provide the contexts for tests by passing in parameter names in test cases; its parametrization eliminates duplicate code for testing multiple sets of input and output; and its rewritten assert statements provide detailed output for causes of failures.

History

Pytest was developed as part of an effort by third-party packages to address Python's built-in module unittest's shortcomings. It originated as part of PyPy, an alternative implementation of Python to the standard CPython. Since its creation in early 2003, PyPy has had a heavy emphasis on testing. PyPy had unit tests for newly written code, regression tests for bugs, and integration tests using CPython's test suite.[1]

In mid 2004, a testing framework called utest emerged and contributors to PyPy began converting existing test cases to utest. Meanwhile, at EuroPython 2004 a complementary standard library for testing, named std, was invented. This package laid out the principles, such as assert rewriting, of what would later become pytest. In late 2004, the std project was renamed to py, std.utest became py.test, and the py library was separated from PyPy. In November 2010, pytest 2.0.0 was released as a package separate from py. It was still called py.test until August 2016, but following the release of pytest 3.0.0 the recommended command line entry point became pytest.[2]

Pytest has been classified by developer security platform Snyk as one of the key ecosystem projects in Python due to its popularity. Some well-known projects who switched to pytest from unittest and nose (another testing package) include those of Mozilla and Dropbox.[3] [4] [5] [6]

Features

Parametrized testing

It is a common pattern in software testing to send values through test functions and check for correct output. In many cases, in order to thoroughly test functionalities, one needs to test multiple sets of input/output, and writing such cases separately would cause duplicate code as most of the actions would remain the same, only differing in input/output values. Pytest's parametrized testing feature eliminates such duplicate code by combining different iterations into one test case, then running these iterations and displaying each test's result separately.[7]

Parametrized tests in pytest are marked by the decorator, where the first parameter,, is a string of comma-separated names, and is a list of values to pass into . When there are multiple names in, would be a list of tuples where values in each tuple corresponds to the names in by index. The names in are then passed into the test function marked by the decorator as parameters. When pytest runs such decorated tests, each pair of and would constitute a separate run with its own test output and unique identifier. The identifier can then be used to run individual data pairs.[8]

Assert rewriting

When writing software tests, the assert statement is a primary means for communicating test failure, where expected values are compared to actual values. While Python's built-in assert keyword would only raise AssertionError with no details in cases of failure, pytest rewrites Python's assert keyword and provides detailed output for the causes of failures, such as what expressions in the assert statement evaluate to. A comparison can be made with unittest (Python's built-in module for testing)'s assert statements:

pytestunittest
assert x

y

assert x <= y

adheres to a more verbose syntax because it is inspired by the Java programming language's JUnit, as are most unit testing libraries; pytest achieves the same while intercepting Python's built-in assert calls, making the approach more concise.

Pytest fixtures

Pytest's tests verify that computer code performs as expected[9] using tests that are structured in an arrange, act and assert sequence known as AAA. Its fixtures provide the context for tests. They can be used to put a system into a known state and to pass data into test functions. Fixtures practically constitute the arrange phase in the anatomy of a test (AAA, short for arrange, act, assert).[10] [9] Pytest fixtures can run before test cases as setup or after test cases for clean up, but are different from unittest and nose (another third-party Python testing framework)'s setups and teardowns. Functions declared as pytest fixtures are marked by the decorator, whose names can then be passed into test functions as parameters.[11] When pytest finds the fixtures' names in test functions' parameters, it first searches in the same module for such fixtures, and if not found, it searches for such fixtures in the conftest.py file.

For example:

import pytest

@pytest.fixturedef dataset: """Return some data to test functions""" return

def test_dataset(dataset): """test and confirm fixture value""" assert dataset

In the above example, pytest fixture returns a dictionary, which is then passed into test function for assertion. In addition to fixture detection within the same file as test cases, pytest fixtures can also be placed in the conftest.py file in the tests directory. There can be multiple conftest.py files, each placed within a tests directory for fixtures to be detected for each subset of tests.

Fixture scopes

In pytest, fixture scopes let the user define when a fixture should be called. There are four fixture scopes: function scope, class scope, module scope, and session scope. Function-scoped fixtures are default for all pytest fixtures, which are called every time a function having the fixture as a parameter runs. The goal of specifying a broader fixture scope is to eliminate repeated fixture calls, which could slow down test execution. Class-scoped fixtures are called once per test class, regardless of the number of times they are called, and the same logic goes for all other scopes. When changing fixture scope, one need only add the scope parameter to fixture decorators, for example, .[12]

Test filtering

Another feature of pytest is its ability to filter through tests, where only desired tests are selected to run, or behave in a certain way as desired by the developer. With the "k" option (e.g.), pytest would only run tests whose names include . The opposite is true, where one can run, and pytest will run all tests whose names do not include .[13]

Pytest's markers can, in addition to altering test behaviour, also filter tests. Pytest's markers are Python decorators starting with the syntax placed on top of test functions. With different arbitrarily named markers, running on the command line will only run those tests decorated with such markers. All available markers can be listed by the along with their descriptions; custom markers can also be defined by users and registered in pytest.ini, in which case will also list those custom markers along with builtin markers.

See also

External links

Notes and References

  1. Web site: Bolz-Tereick . Carl Friedrich . PyPy Status Blog . PyPy . 9 September 2018 . 12 May 2022 . 6 July 2022 . https://web.archive.org/web/20220706195902/https://morepypy.blogspot.com/2018/09/the-first-15-years-of-pypy.html#continuous-integration . live .
  2. Web site: History . pytest . 13 April 2022 . 16 May 2022 . https://web.archive.org/web/20220516211537/https://docs.pytest.org/en/latest/history.html . live .
  3. Web site: Project examples . Pytest . 1 February 2022 . 1 February 2022 . https://web.archive.org/web/20220201223344/https://docs.pytest.org/en/6.2.x/projects.html . live .
  4. Web site: Koorapati . Nipunn . Open Sourcing Pytest Tools . . 1 February 2022 . 11 June 2024 . https://web.archive.org/web/20240611042915/https://dropbox.tech/application/open-sourcing-pytest-tools . live .
  5. Book: Oliveira . Bruno . pytest Quick Start Guide . August 2018 . . 978-1-78934-756-2 . 1 February 2022 . 1 February 2022 . https://web.archive.org/web/20220201231057/https://www.packtpub.com/product/pytest-quick-start-guide/9781789347562 . live .
  6. Web site: pytest . Snyk . 12 May 2022 . 27 June 2022 . https://web.archive.org/web/20220627024337/https://snyk.io/advisor/python/pytest . live .
  7. Book: Okken . Brian . Python Testing with Pytest . September 2017 . The Pragmatic Bookshelf . 9781680502404 . 1st . 22 January 2022 . 20 January 2022 . https://web.archive.org/web/20220120135726/https://pragprog.com/titles/bopytest/python-testing-with-pytest/ . live .
  8. Web site: Parametrizing fixtures and test functions . pytest.org . 24 May 2022 . 4 June 2022 . https://web.archive.org/web/20220604202736/https://docs.pytest.org/en/6.2.x/parametrize.html . live .
  9. Book: Viafore . Patrick . Robust Python . 12 July 2021 . O'Reilly Media, Inc. . 978-1-0981-0061-2 . 3 July 2022 . en . "Tests verify that what you build is performing as you expect." . 3 July 2022 . https://web.archive.org/web/20220703205741/https://books.google.com/books?id=mO43EAAAQBAJ&pg=PT313 . live .
  10. Book: Khorikov . Vladimir . Unit Testing Principles, Practices, and Patterns . January 2020 . Published by Manning Publications . 9781617296277 . 4 June 2022 . 4 June 2022 . https://web.archive.org/web/20220604130844/https://www.oreilly.com/library/view/unit-testing-principles/9781617296277/ . live .
  11. Web site: About fixtures . Pytest . 7 February 2022 . 7 February 2022 . https://web.archive.org/web/20220207024326/https://docs.pytest.org/en/latest/explanation/fixtures.html . live .
  12. Book: Ashwin . Pajankar . Python Unit Test Automation: Practical Techniques for Python Developers and Testers . 27 February 2017 . Apress . 9781484226766 . 7 March 2022 . 7 March 2022 . https://web.archive.org/web/20220307035055/https://www.oreilly.com/library/view/python-unit-test/9781484226766/ . live .
  13. Book: Molina . Alessandro . Crafting Test-Driven Software with Python . February 2021 . Publisher(s): Packt Publishing . 9781838642655 . 8 March 2022 . 8 March 2022 . https://web.archive.org/web/20220308025240/https://www.oreilly.com/library/view/crafting-test-driven-software/9781838642655/ . live .