Pytest is a
Python testing framework that originated from the
PyPy
PyPy () is an implementation of the Python programming language. PyPy often runs faster than the standard implementation CPython because PyPy uses a just-in-time compiler. Most Python code runs well on PyPy except for code that depends on CPyt ...
project. It can be used to write various types of software tests, including
unit tests
In computer programming, unit testing is a software testing method by which individual units of source code—sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures&m ...
,
integration tests
Integration testing (sometimes called integration and testing, abbreviated I&T) is the phase in software testing in which individual software modules are combined and tested as a group. Integration testing is conducted to evaluate the compliance ...
,
end-to-end tests, and
functional tests. Its features include
parametrized testing,
fixtures
A fixture can refer to:
* Test fixture, used to control and automate testing
* Light fixture
* Plumbing fixture
* Fixture (tool), a tool used in manufacturing
* Fixture (property law)
* A type of sporting event
Sport pertains to any f ...
, and
assert
Assertion or assert may refer to:
Computing
* Assertion (software development), a computer programming technique
* assert.h, a header file in the standard library of the C programming language
* Assertion definition language, a specification lan ...
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
CPython is the reference implementation of the Python programming language. Written in C and Python, CPython is the default and most widely used implementation of the Python language.
CPython can be defined as both an interpreter and a compi ...
. 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.
In mid 2004, a testing framework called utest emerged and contributors to PyPy began converting existing
test case
In software engineering, a test case is a specification of the inputs, execution conditions, testing procedure, and expected results that define a single test to be executed to achieve a particular software testing objective, such as to exercise ...
s 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
A library is a collection of materials, books or media that are accessible for use and not just for display purposes. A library provides physical (hard copies) or digital access (soft copies) materials, and may be a physical location or a vi ...
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
A command-line interpreter or command-line processor uses a command-line interface (CLI) to receive commands from a user in the form of lines of text. This provides a means of setting parameters for the environment, invoking executables and pro ...
entry point
In computer programming, an entry point is the place in a program where the execution of a program begins, and where the program has access to command line arguments.
To start a program's execution, the loader or operating system passes c ...
became pytest.
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
Mozilla (stylized as moz://a) is a free software community founded in 1998 by members of Netscape. The Mozilla community uses, develops, spreads and supports Mozilla products, thereby promoting exclusively free software and open standards, w ...
and
Dropbox
Dropbox is a file hosting service operated by the American company Dropbox, Inc., headquartered in San Francisco, California, U.S. that offers cloud storage, file synchronization, personal cloud, and client software. Dropbox was founded in 2 ...
.
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 In computer programming, duplicate code is a sequence of source code that occurs more than once, either within a program or across different programs owned or maintained by the same entity. Duplicate code is generally considered undesirable for a nu ...
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.
Parametrized tests in pytest are marked by the
decorator, where the first
parameter
A parameter (), generally, is any characteristic that can help in defining or classifying a particular system (meaning an event, project, object, situation, etc.). That is, a parameter is an element of a system that is useful, or critical, when ...
, , 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.
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:
adheres to a more verbose syntax because it is inspired by the
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
programming language's
JUnit
JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test-driven development, and is one of a family of unit testing frameworks which is collectively known as xUnit that originated ...
, 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
using tests that are structured in an arrange, act and assert sequence known as AAA.
Its
fixtures
A fixture can refer to:
* Test fixture, used to control and automate testing
* Light fixture
* Plumbing fixture
* Fixture (tool), a tool used in manufacturing
* Fixture (property law)
* A type of sporting event
Sport pertains to any f ...
provide the context for tests. They can be used to put a system into a known
state
State may refer to:
Arts, entertainment, and media Literature
* ''State Magazine'', a monthly magazine published by the U.S. Department of State
* ''The State'' (newspaper), a daily newspaper in Columbia, South Carolina, United States
* '' Our ...
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'').
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.
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.fixture
def 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
Function or functionality may refer to:
Computing
* Function key, a type of key on computer keyboards
* Function model, a structured representation of processes in a system
* Function object or functor or functionoid, a concept of object-orie ...
scope,
class
Class or The Class may refer to:
Common uses not otherwise categorized
* Class (biology), a taxonomic rank
* Class (knowledge representation), a collection of individuals or objects
* Class (philosophy), an analytical concept used differently ...
scope,
module
Module, modular and modularity may refer to the concept of modularity. They may also refer to:
Computing and engineering
* Modular design, the engineering discipline of designing complex devices using separately designed sub-components
* Mo ...
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, .
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
Option or Options may refer to:
Computing
*Option key, a key on Apple computer keyboards
*Option type, a polymorphic data type in programming languages
*Command-line option, an optional parameter to a command
*OPTIONS, an HTTP request method
...
(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 .
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
*
JUnit
JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test-driven development, and is one of a family of unit testing frameworks which is collectively known as xUnit that originated ...
, well-known software testing framework based on
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
*
Doctest
doctest is a module included in the Python programming language's standard library that allows the easy generation of tests based on output from the standard Python interpreter shell, cut and pasted into docstrings.
Implementation specifics
Doc ...
, well-known testing framework in
Python for
docstring
In programming, a docstring is a string literal specified in source code that is used, like a comment, to document a specific segment of code. Unlike conventional source code comments, or even specifically formatted comments like docblocks, docs ...
s
*
List of unit testing frameworks
This article is a list of tables of code-driven unit testing frameworks for various programming languages. Some, but not all, of these are based on xUnit.
Columns (classification)
* Name: This column contains the name of the framework and wi ...
References
External links
* {{Official website
https://pypi.python.org/pypi/pytesthttps://docs.pytest.org
Python (programming language) development tools
Free software testing tools
Unit testing frameworks