Skip to content

Pytest

Testing framework

Assertions

Action Code Details
Assert warning
with pytest.warns(UserWarning):
Assert any error
with pytest.raises(Exception) as excinfo:
Assert specific exception e
with pytest.raises(e) as excinfo:
Assert either exception e1 or e2
with pytest.raises((e1, e2)):

Test control flow

Skip tests

Action Code Details
Skip test
@pytest.mark.skip(reason='no way to currently test this')
Conditional skip
@pytest.mark.skipif(cond, reason)
Skip for Python version below x.y
@pytest.mark.skipif(sys.version_info < (x, y))
Skip if on Windows
@pytest.mark.skipif(sys.platform == 'win32')
Skip if module is missing
@pytest.importorskip('pandas')
Skip rest of the test if module is missing
docutils = pytest.importorskip('docutils')

Test expectations

Alternative definitions of success

Action Code Details
Expect test to fail
@pytest.mark.xfail()
Expect test to fail with exception e
@pytest.mark.xfail(raises=e)
Fail test if not completed within n seconds
@pytest.mark.timeout(n)
Fail test on Windows
@pytest.mark.xfail(sys.platform == 'win32')

Parameterized tests

Action Code Details
Parameterize test for argument x with list of options
@pytest.mark.parametrize('x', [1, 2, 3])
Parameterize test for multiple arguments
@pytest.mark.parametrize('length', [1, 2, 3])
@pytest.mark.parametrize('value', [0, 1])
Parameterize for combination of arguments
@pytest.mark.parametrize('length,value', [(1, 0), (2, 1), (3, 1)])
Parameterize using parameterized fixture
@pytest.mark.parametrize('large_dynamic_data_file',
    ['big.csv', 'big2.csv'], indirect=True)

Fixtures

Action Code Details
Define fixture
@pytest.fixture
def first_entry():
    return 'a'
Define fixture with module scope
@pytest.fixture(scope='module')
Define fixture with cleanup
# fixture code
yield 'a'
# cleanup code
Define fixture for use in every test
@pytest.fixture(autouse=True)
Define parameterized fixture, resulting in multiple tests
@pytest.fixture(params=[1, 2, 3, 4, 5])
def number(request):
    return request.param
Function signature must match the example
Disable GC for every test, collect in-between
@pytest.fixture(autouse=True)
def cleanup():
    gc.collect()
    gc.disable()
Parameterize tests with a dynamic list of file paths
@fixture(params = glob.glob(r'data\*.csv')
def file_paths(request)
    return request.param
Parameterize tests with a dynamic list of file names
@fixture(params = fnmatch.filter(os.listdir('data'), '*.csv')
def file_names(request)
    return request.param
Parameterized test using a parameterizable fixture
@pytest.fixture
def tester(request):
    return MyTester(request.param)

@pytest.mark.parametrize('tester', [['var1', 'var2']], indirect=True)
def test_tc1(self, tester):
    tester.dothis()