Pytest Snapshot Testing
pytest-snapshot is a plugin for snapshot testing with pytest. It enables developers to compare current test outputs (e.g., data structures, HTML, JSON) against a pre-recorded 'snapshot', failing tests if a mismatch occurs. The current version is 0.9.0, and it maintains an active release schedule with regular minor and patch updates.
Warnings
- gotcha To create or update snapshots, you MUST explicitly run pytest with the `--snapshot-update` CLI flag. Without this flag, tests will fail if snapshots are missing or do not match, but new snapshots will not be generated or updated.
- breaking Python 2 support was officially dropped in version 0.5.0. pytest-snapshot now requires Python 3.5 or newer to function.
- breaking Beginning with version 0.5.0, all snapshot files are saved using UTF-8 encoding. If you have existing snapshots created with an older version that might have used a different encoding, they could lead to comparison errors after upgrading.
- gotcha Attempting to snapshot test certain unsupported values, such as strings containing the carriage return character ('\r'), will raise a `ValueError`. This behavior was introduced to clarify unsupported inputs.
- gotcha In versions prior to 0.8.1, `snapshot.assert_match` might not correctly raise exceptions when running pytest with both `--assert=plain` and without `--snapshot-update`. This could mask actual failures.
Install
-
pip install pytest-snapshot
Imports
- snapshot
def test_example(snapshot): # ... use snapshot.assert_match(data, 'snapshot_name.json') ...
Quickstart
import pytest
def test_data_structure(snapshot):
# Simulate some data generated by your application
data = {
"id": 101,
"name": "Sample Product",
"config": {
"enabled": True,
"features": ["search", "filter"]
}
}
# The snapshot file (e.g., my_product_snapshot.json) will be created
# or updated relative to the test file's directory.
snapshot.assert_match(data, "my_product_snapshot.json")
# To run this test:
# 1. Save the code as `test_product.py`.
# 2. Run `pytest --snapshot-update` in your terminal to create or update the initial snapshot.
# 3. Subsequent runs of `pytest` (without `--snapshot-update`) will compare against the saved snapshot.