Search RU
Tasks / pytest / Snapshot tests with snapshot updates
Statement medium

Snapshot tests with snapshot updates

`assert_snapshot(actual, expected, update=False)` compares a structure with a
stored snapshot.

Modes:

- `update=True` — update mode: the function does **not compare**; it returns a
deep copy of `actual` as the new snapshot. `expected=None` is allowed here.
- `update=False` and `expected is None` — there is no snapshot yet:
`SnapshotMissing` (subclass of `AssertionError`), the message contains
`snapshot is missing`, and the `path` attribute is `"$"`.
- `update=False` and the structures match, including types — return `None`.
- `update=False` and they differ — `SnapshotMismatch` (subclass of
`AssertionError`) with the `path`, `expected`, and `actual` attributes and the
message:

```
snapshot mismatch at {path}: expected {expected!r}, got {actual!r}
```

How the first difference is found:

- types are compared strictly: `1`, `1.0`, and `True` are different values;
- `dict`: first the snapshot's keys in alphabetical order; a key missing from
`actual` yields `actual="<missing>"`; then extra keys of `actual` in
alphabetical order yield `expected="<missing>"`;
- `list`: compared by index; when the lengths differ, the missing element is
`"<missing>"`;
- scalars: values are compared;
- the path to a node: `$`, `$.user.name`, `$.items[0].sku`.

**Example:**

```python
assert_snapshot({"id": 1}, {"id": 1})
→ None

assert_snapshot({"user": {"name": "Ann"}}, {"user": {"name": "Bob"}})
→ SnapshotMismatch(path="$.user.name", expected="Bob", actual="Ann")

assert_snapshot({"id": 1, "debug": True}, {"id": 1})
→ SnapshotMismatch(path="$.debug", expected="<missing>", actual=True)

assert_snapshot({"id": 1}, None)
→ SnapshotMissing(path="$")

assert_snapshot({"id": 1}, {"id": 2}, update=True)
→ {"id": 1}
```

The function does not mutate `actual` or `expected`. Write tests for a match, a
mismatch, nested structures, list order, an extra and a missing key, a missing
snapshot, strict type checks, and update mode.

Python
pytestsnapshotdiffassertions
test_solution.py Python 3.14
AI mentor

The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.

Log in and ask
Hints 1 of 3 unlocked · attempts: 0
Hint 1

What should happen on the first run, when there is no snapshot yet? And who owns the structure that `update=True` returns?

Hint 2 — unlocks after 1 attempt
Hint 3 — unlocks after 3 attempts