PyTestSnapshotTest#
- 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.
This plugin will be automatically registered when you install tpcp. It adds the
snapshot
fixture to your tests. Further, it will register the--snapshot-update
commandline flag, which you can use to update the snapshots. You can also run pytest with the--snapshot-only-check
flag to fail if a snapshot file is not found. Without that flag, missing snapshots will be automatically created.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 calledsnapshot
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.Methods
assert_match
(value[, name])Assert that the value matches the snapshot.
- 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.- Parameters:
- value
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.
- name
Optional name suffix of the snapshot-file. If not provided the name will be suffixed with a number, starting at 0.
- kwargs
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
andassert_array_almost_equal
respectively.