Pytest is a software testing framework - it’s a CLI tool that can automatically find tests, run then and report the results.

Can be extended with your own or 3rd-party plugins.

Different ways to call pytest

SubsetSyntax
Single test methodpytest path/test_module.py::TestClass::test_method
All tests in a classpytest path/test_module.py::TestClass
Single test functionpytest path/test_module.py::test_function
All tests in a modulepytest path/test_module.py
All tests in a directorypytest path
Tests matching a name patternpytest -k pattern

Notable CLI flags

  • -v|vv|vvv - verbosity

Assertion helper functions

from cards import Card
import pytest
 
 
def assert_identical(c1: Card, c2: Card):
    __tracebackhide__ = True
    assert c1 == c2
    if c1.id != c2.id:
        pytest.fail(f"id's don't match. {c1.id} != {c2.id}")
 
 
def test_identical():
    c1 = Card("foo", id=123)
    c2 = Card("foo", id=123)
    assert_identical(c1, c2)
 
 
def test_identical_fail():
    c1 = Card("foo", id=123)
    c2 = Card("foo", id=456)
    assert_identical(c1, c2)

Match exception message

import pytest
import cards
 
 
def test_no_path_raises():
    with pytest.raises(TypeError):
        cards.CardsDB()
 
 
def test_raises_with_info():
    match_regex = "missing 1 .* positional argument"
    with pytest.raises(TypeError, match=match_regex):
        cards.CardsDB()
 
 
def test_raises_with_info_alt():
    with pytest.raises(TypeError) as exc_info:
        cards.CardsDB()
    expected = "missing 1 required positional argument"
    assert expected in str(exc_info.value)

Fixtures

pytest treats exceptions differently during fixtures compared to during a test function. An exception (or assert failure or call to pytest.fail()) that happens during the test code proper results in a “Fail” result. However, during a fixture, the test function is reported as “Error.” This distinction is helpful when debugging why a test didn’t pass. If a test results in “Fail,” the failure is somewhere in the test function (or something the function called). If a test results in “Error,” the failure is somewhere in a fixture.