0
# Core Snapshot Assertions
1
2
Primary snapshot assertion functionality providing the main interface for snapshot testing in pytest. The SnapshotAssertion class offers a fluent interface for configuration and supports various assertion patterns.
3
4
## Capabilities
5
6
### Basic Snapshot Assertion
7
8
Core assertion functionality using equality comparison with automatic snapshot generation and validation.
9
10
```python { .api }
11
class SnapshotAssertion:
12
def __eq__(self, other: SerializableData) -> bool:
13
"""
14
Compare data against stored snapshot using equality operator.
15
16
Parameters:
17
- other: Any data to compare against snapshot
18
19
Returns:
20
bool: True if data matches snapshot, False otherwise
21
22
Raises:
23
AssertionError: When snapshot doesn't match or doesn't exist
24
"""
25
26
def __call__(self, *,
27
diff: Optional[SnapshotIndex] = None,
28
exclude: Optional[PropertyFilter] = None,
29
include: Optional[PropertyFilter] = None,
30
extension_class: Optional[Type[AbstractSyrupyExtension]] = None,
31
matcher: Optional[PropertyMatcher] = None,
32
name: Optional[SnapshotIndex] = None) -> 'SnapshotAssertion':
33
"""
34
Configure snapshot assertion with options.
35
36
Parameters:
37
- diff: Index for snapshot diff (deprecated)
38
- exclude: Function to exclude specific properties
39
- include: Function to include specific properties
40
- extension_class: Custom extension class for serialization
41
- matcher: Function to transform values during comparison
42
- name: Specific name for the snapshot
43
44
Returns:
45
SnapshotAssertion: Configured assertion instance for chaining
46
"""
47
```
48
49
Usage examples:
50
51
```python
52
def test_basic_assertion(snapshot):
53
# Simple equality assertion - creates snapshot on first run
54
actual = {"name": "Alice", "age": 30}
55
assert actual == snapshot
56
57
def test_configured_assertion(snapshot):
58
from syrupy.matchers import path_type
59
60
data = {"timestamp": "2023-12-01", "value": 42}
61
62
# Configure with matcher to handle dynamic timestamp
63
assert data == snapshot(matcher=path_type({
64
"timestamp": (str, "<timestamp>")
65
}))
66
67
def test_multiple_snapshots(snapshot):
68
# Multiple snapshots in one test - automatically indexed
69
assert "first result" == snapshot
70
assert "second result" == snapshot
71
assert {"data": "third"} == snapshot
72
```
73
74
### Extension Configuration
75
76
Methods for configuring custom serialization extensions and setting default behaviors.
77
78
```python { .api }
79
def use_extension(self, extension_class: Type[AbstractSyrupyExtension]) -> 'SnapshotAssertion':
80
"""
81
Configure snapshot to use specific extension.
82
83
Parameters:
84
- extension_class: Extension class for custom serialization
85
86
Returns:
87
SnapshotAssertion: New instance with specified extension
88
"""
89
90
def with_defaults(self, **kwargs) -> 'SnapshotAssertion':
91
"""
92
Create snapshot assertion with default configuration.
93
94
Parameters:
95
- **kwargs: Default options (matcher, include, exclude, extension_class)
96
97
Returns:
98
SnapshotAssertion: New instance with default configuration
99
"""
100
```
101
102
Usage examples:
103
104
```python
105
def test_json_extension(snapshot):
106
from syrupy.extensions.json import JSONSnapshotExtension
107
108
data = {"users": [{"id": 1, "name": "Alice"}]}
109
110
# Use JSON extension for clean JSON output
111
assert data == snapshot.use_extension(JSONSnapshotExtension)
112
113
def test_image_snapshot(snapshot):
114
from syrupy.extensions.image import PNGImageSnapshotExtension
115
116
# Binary image data
117
image_bytes = b"\\x89PNG\\r\\n\\x1a\\n..."
118
119
assert image_bytes == snapshot.use_extension(PNGImageSnapshotExtension)
120
121
def test_default_config(snapshot):
122
from syrupy.filters import props
123
124
# Create snapshot with default exclusions
125
configured_snapshot = snapshot.with_defaults(
126
exclude=props("private_field", "internal_data")
127
)
128
129
data = {
130
"public": "visible",
131
"private_field": "hidden",
132
"internal_data": "secret"
133
}
134
135
assert data == configured_snapshot
136
```
137
138
### Assertion Result Handling
139
140
Internal result handling and metadata access for assertion outcomes.
141
142
```python { .api }
143
class AssertionResult:
144
def __init__(self,
145
snapshot_location: str,
146
snapshot_name: str,
147
success: bool = False,
148
assertion_success: bool = False,
149
recalled_data: SerializedData = "",
150
snapshot_data: SerializedData = "",
151
exception: Exception = None):
152
"""
153
Result of snapshot assertion operation.
154
155
Parameters:
156
- snapshot_location: File path of snapshot
157
- snapshot_name: Name identifier for snapshot
158
- success: Whether snapshot operation succeeded
159
- assertion_success: Whether assertion passed
160
- recalled_data: Data retrieved from snapshot
161
- snapshot_data: Data being compared
162
- exception: Any exception that occurred
163
"""
164
165
def assert_match(self, data: Any) -> AssertionResult:
166
"""
167
Perform snapshot assertion and return detailed result.
168
169
Parameters:
170
- data: Data to compare against snapshot
171
172
Returns:
173
AssertionResult: Detailed assertion outcome
174
"""
175
176
@property
177
def num_executions(self) -> int:
178
"""
179
Number of times this snapshot assertion has been executed.
180
181
Returns:
182
int: Execution count
183
"""
184
185
@property
186
def executions(self) -> Dict[int, AssertionResult]:
187
"""
188
Dictionary of execution results indexed by execution number.
189
190
Returns:
191
Dict[int, AssertionResult]: Mapping of execution index to results
192
"""
193
194
@property
195
def index(self) -> SnapshotIndex:
196
"""
197
Current snapshot index (auto-incremented or custom name).
198
199
Returns:
200
SnapshotIndex: Current snapshot identifier
201
"""
202
203
@property
204
def name(self) -> str:
205
"""
206
Name of the current snapshot for file storage.
207
208
Returns:
209
str: Snapshot name used in file system
210
"""
211
```
212
213
### Diff Mode Configuration
214
215
Control how snapshot differences are displayed when assertions fail.
216
217
```python { .api }
218
class DiffMode(Enum):
219
DETAILED = "detailed" # Show full diff with context
220
DISABLED = "disabled" # Disable diff display
221
222
def get_assert_diff(self, diff_mode: DiffMode = DiffMode.DETAILED) -> List[str]:
223
"""
224
Generate diff representation for assertion failure.
225
226
Parameters:
227
- diff_mode: How to display differences
228
229
Returns:
230
List[str]: Lines of diff output for display
231
"""
232
```
233
234
Usage with CLI:
235
236
```bash
237
# Enable detailed diffs (default)
238
pytest --snapshot-diff-mode=detailed
239
240
# Disable diffs for performance with large snapshots
241
pytest --snapshot-diff-mode=disabled
242
```