class tpcp.testing.PyTestSnapshotTest(request=None)[source]#

Perform snapshot tests in pytest.

This supports standard datatypes and scientific datatypes like numpy arrays and pandas DataFrames.

To use this in your tests, add the following lines to your

def snapshot(request):
    with PyTestSnapshotTest(request) as snapshot_test:
        yield snapshot_test

def pytest_addoption(parser):
    group = parser.getgroup("snapshottest")
        help="Update the snapshots."

This will register the snapshot fixture that you can use in your tests. Further, it will register the --snapshot-update commandline flag, which you can use to update the snapshots.

To use the fixture in your tests, simply add it as a parameter to your test function:

def test_my_test(snapshot):
    result = my_calculation()
    snapshot.assert_match(result, "my_result_1")

This will store the result of my_calculation() in a snapshot file in a folder called snapshot in the same folder as the test file. The name of the snapshot file will be the name of the test function, suffixed with _my_result_1. When the test is run again, the result will be compared to the stored snapshot.

To update a snapshot, either delete the snapshot file and manually run the test again or run pytest with the --snapshot-update flag.


assert_match(value[, name])

Assert that the value matches the snapshot.

__init__(request=None) None[source]#
assert_match(value: str | DataFrame | ndarray, name: str | None = None, **kwargs)[source]#

Assert that the value matches the snapshot.

This compares the value with a stored snapshot of the same name. If no snapshot exists, it will be created.

The snapshot name is automatically generated from the test name and the name parameter passed to this function. If no name is passed, the name will be suffixed with a number, starting at 0. If you have multiple snapshots in one test, we highly recommend to pass a name to this function. Otherwise, changing the order of the snapshots will break your tests.


The value to compare with the snapshot. We support strings, numpy arrays and pandas DataFrames. For other datatypes like floats or short lists, we recommend to just use the standard pytest assertions and hardcode the expected value.


Optional name suffix of the snapshot-file. If not provided the name will be suffixed with a number, starting at 0.


Additional keyword arguments passed to the comparison function. This is only supported for DataFrames and numpy arrays. There they will be passed to assert_frame_equal and assert_array_almost_equal respectively.