Origin and Evolution

The pytest project was initially created by Holger Krekel in 2004. At its inception, pytest aimed to provide a more agile and less verbose testing framework compared to what was available at the time, such as Python’s built-in unittest module. Krekel sought to create a tool that would support simple test writing, with the ability to scale up to support complex functional testing for applications and libraries.

Key Features and Philosophy

pytest introduced several innovative features that set it apart from other testing frameworks. Its use of simple assert statements, without requiring special syntax, made tests more readable and intuitive. The framework’s powerful fixture model provided a flexible approach to setup and teardown operations, enhancing test modularity and reuse. Additionally, pytest offered extensive support for parameterised testing, allowing developers to easily execute a test function with different input values.

The philosophy behind pytest has always been to facilitate easy test writing and execution, promoting test-driven development (TDD) and behavior-driven development (BDD) methodologies. Its design principles include minimal boilerplate code, the ability to run tests in parallel, and a rich plugin architecture.


Run specific tests

Run all tests in a project

$ pytest

Run tests in a Single Directory

To run all the tests from one directory, use the directory as a parameter to pytest:

$ pytest tests/my-directory

Run tests in a Single Test File/Module

To run a file full of tests, list the file with the relative path as a parameter to pytest:

$ pytest tests/my-directory/

Run a Single Test Function

To run a single test function, add :: and the test function name:

$ pytest -v tests/my-directory/

-v is used so you can see which function was run.

Run a Single Test Class

To run just a class, do like we did with functions and add ::, then the class name to the file parameter:

$ pytest -v tests/my-directory/

Run a Single Test Method of a Test Class

If you don’t want to run all of a test class, just one method, just add another :: and the method name:

pytest -v tests/my-directory/

Run a Set of Tests Based on Test Name

The -k option enables you to pass in an expression to run tests that have certain names specified by the expression as a substring of the test name. It is possible to use and, or, and not to create complex expressions. For example, to run all of the functions that have _raises in their name:

$ pytest -v -k _raises