Skip to content

Commit

Permalink
feat(amber): change serialization to be py syntax like (#505)
Browse files Browse the repository at this point in the history
BREAKING CHANGE: update to serialization requires regeneration of snapshots

Migration Guide
* `pytest --snapshot-update` to regenerate amber snapshots
  • Loading branch information
iamogbz authored and noahnu committed Feb 20, 2022
1 parent e783187 commit b64b965
Show file tree
Hide file tree
Showing 15 changed files with 336 additions and 345 deletions.
34 changes: 17 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,13 +164,13 @@ def test_bar(snapshot):
}))
```

```ambr
```py
# name: test_bar
<class 'dict'> {
'date_created': <class 'datetime'>,
dict({
'date_created': datetime,
'value': 'Some computed value!!',
}
---
})
# ---
```

#### `exclude`
Expand Down Expand Up @@ -206,15 +206,15 @@ def test_bar(snapshot):
assert actual == snapshot(exclude=props("id", "1"))
```

```ambr
```py
# name: test_bar
<class 'dict'> {
'list': <class 'list'> [
dict({
'list': list([
1,
3,
],
}
---
]),
})
# ---
```

###### `paths(path_string, *path_strings)`
Expand All @@ -234,15 +234,15 @@ def test_bar(snapshot):
assert actual == snapshot(exclude=paths("date", "list.1"))
```

```ambr
```py
# name: test_bar
<class 'dict'> {
'list': <class 'list'> [
dict({
'list': list([
1,
3,
],
}
---
]),
})
# ---
```

#### `extension_class`
Expand Down
47 changes: 19 additions & 28 deletions src/syrupy/extensions/amber/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ class DataSerializer:
_indent: str = " "
_max_depth: int = 99
_marker_comment: str = "# "
_marker_divider: str = "---"
_marker_divider: str = f"{_marker_comment}---"
_marker_name: str = f"{_marker_comment}name:"
_marker_crn: str = "\r\n"

Expand Down Expand Up @@ -189,8 +189,8 @@ def serialize_string(cls, data: str, *, depth: int = 0, **kwargs: Any) -> str:
for line in str(data).splitlines(keepends=True)
),
depth=depth,
open_tag="'",
close_tag="'",
open_tag="'''",
close_tag="'''",
include_type=False,
ends="",
)
Expand All @@ -199,21 +199,16 @@ def serialize_string(cls, data: str, *, depth: int = 0, **kwargs: Any) -> str:
def serialize_iterable(
cls, data: Iterable["SerializableData"], **kwargs: Any
) -> str:
open_paren, close_paren = next(
parens
for iter_type, parens in {
GeneratorType: ("(", ")"),
list: ("[", "]"),
tuple: ("(", ")"),
}.items()
if isinstance(data, iter_type)
)
open_paren, close_paren = (None, None)
if isinstance(data, list):
open_paren, close_paren = ("[", "]")

values = list(data)
return cls.__serialize_iterable(
data=data,
resolve_entries=(range(len(values)), item_getter, None),
open_tag=open_paren,
close_tag=close_paren,
open_paren=open_paren,
close_paren=close_paren,
**kwargs,
)

Expand All @@ -222,8 +217,8 @@ def serialize_set(cls, data: Set["SerializableData"], **kwargs: Any) -> str:
return cls.__serialize_iterable(
data=data,
resolve_entries=(cls.sort(data), lambda _, p: p, None),
open_tag="{",
close_tag="}",
open_paren="{",
close_paren="}",
**kwargs,
)

Expand All @@ -232,8 +227,6 @@ def serialize_namedtuple(cls, data: NamedTuple, **kwargs: Any) -> str:
return cls.__serialize_iterable(
data=data,
resolve_entries=(cls.sort(data._fields), attr_getter, None),
open_tag="(",
close_tag=")",
separator="=",
**kwargs,
)
Expand All @@ -245,8 +238,8 @@ def serialize_dict(
return cls.__serialize_iterable(
data=data,
resolve_entries=(cls.sort(data.keys()), item_getter, None),
open_tag="{",
close_tag="}",
open_paren="{",
close_paren="}",
separator=": ",
serialize_key=True,
**kwargs,
Expand All @@ -265,8 +258,6 @@ def serialize_unknown(cls, data: Any, *, depth: int = 0, **kwargs: Any) -> str:
lambda v: not callable(v),
),
depth=depth,
open_tag="{",
close_tag="}",
separator="=",
**kwargs,
)
Expand All @@ -284,7 +275,7 @@ def sort(cls, iterable: Iterable[Any]) -> Iterable[Any]:

@classmethod
def object_type(cls, data: "SerializableData") -> str:
return f"<class '{data.__class__.__name__}'>"
return f"{data.__class__.__name__}"

@classmethod
def __is_namedtuple(cls, obj: Any) -> bool:
Expand All @@ -307,8 +298,8 @@ def __serialize_iterable(
*,
data: "SerializableData",
resolve_entries: "IterableEntries",
open_tag: str,
close_tag: str,
open_paren: Optional[str] = None,
close_paren: Optional[str] = None,
depth: int = 0,
exclude: Optional["PropertyFilter"] = None,
path: "PropertyPath" = (),
Expand Down Expand Up @@ -349,8 +340,8 @@ def value_str(key: "PropertyName", value: "SerializableData") -> str:
data=data,
lines=(f"{key_str(key)}{value_str(key, value)}," for key, value in entries),
depth=depth,
open_tag=open_tag,
close_tag=close_tag,
open_tag=f"({open_paren or ''}",
close_tag=f"{close_paren or ''})",
)

@classmethod
Expand All @@ -367,7 +358,7 @@ def __serialize_lines(
) -> str:
lines = ends.join(lines)
lines_end = "\n" if lines else ""
maybe_obj_type = f"{cls.object_type(data)} " if include_type else ""
maybe_obj_type = f"{cls.object_type(data)}" if include_type else ""
formatted_open_tag = cls.with_indent(f"{maybe_obj_type}{open_tag}", depth)
formatted_close_tag = cls.with_indent(close_tag, depth)
return f"{formatted_open_tag}\n{lines}{lines_end}{formatted_close_tag}"
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# name: test_case_1
'Syrupy is amazing!'
---
# ---
12 changes: 6 additions & 6 deletions tests/examples/__snapshots__/test_custom_object_repr.ambr
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
# name: test_snapshot_custom_class
<class 'MyCustomClass'> {
MyCustomClass(
prop1=1,
prop2='a',
prop3=<class 'set'> {
prop3=set({
1,
2,
3,
},
}
---
}),
)
# ---
# name: test_snapshot_custom_repr_class
MyCustomReprClass(
prop1=1,
prop2='a',
prop3={1, 2, 3},
)
---
# ---
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# name: test_canadian_name🇨🇦
'Name should be test_canadian_name🇨🇦.'
---
# ---
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# name: test_snapshot_custom_snapshot_name_suffix[test_is_amazing]
'Syrupy is amazing!'
---
# ---
# name: test_snapshot_custom_snapshot_name_suffix[test_is_awesome]
'Syrupy is awesome!'
---
# ---
6 changes: 3 additions & 3 deletions tests/integration/test_snapshot_option_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def test_update_failure_shows_snapshot_diff(run_testcases, testcases_updated):
(
r".*assert snapshot == \['this', 'will', 'not', 'match'\]",
r".*AssertionError: assert \[- snapshot\] == \[\+ received\]",
r".* <class 'list'> \[",
r".* list\(\[",
r".* ...",
r".* 'will',",
r".* - 'be',",
Expand All @@ -138,7 +138,7 @@ def test_update_failure_shows_snapshot_diff(run_testcases, testcases_updated):
r".* \]",
r".*assert \['this', 'will', 'fail'\] == snapshot",
r".*AssertionError: assert \[\+ received\] == \[- snapshot\]",
r".* <class 'list'> \[",
r".* list\(\[",
r".* ...",
r".* 'will',",
r".* - 'be',",
Expand All @@ -147,7 +147,7 @@ def test_update_failure_shows_snapshot_diff(run_testcases, testcases_updated):
r".* \]",
r".*assert snapshot == \['this', 'will', 'be', 'too', 'much'\]",
r".*AssertionError: assert \[- snapshot\] == \[\+ received\]",
r".* <class 'list'> \[",
r".* list\(\[",
r".* ...",
r".* 'be',",
r".* - 'updated',",
Expand Down
36 changes: 18 additions & 18 deletions tests/syrupy/extensions/__snapshots__/test_base.ambr
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
# name: TestSnapshotReporter.test_diff_lines[-0-SnapshotReporterNoContext]
'
'''
...
- line 2
+ line 02
...
- line 04
+ line 4
...
'
---
'''
# ---
# name: TestSnapshotReporter.test_diff_lines[-0-SnapshotReporter]
'
'''
line 0
line 1
- line 2
Expand All @@ -21,18 +21,18 @@
line 5
...
line 7
'
---
'''
# ---
# name: TestSnapshotReporter.test_diff_lines[-1-SnapshotReporterNoContext]
'
'''
...
- line 3
+ line 3
...
'
---
'''
# ---
# name: TestSnapshotReporter.test_diff_lines[-1-SnapshotReporter]
'
'''
line 0
...
line 2
Expand All @@ -41,10 +41,10 @@
line 4
...
line 7
'
---
'''
# ---
# name: TestSnapshotReporter.test_diff_lines[-2-SnapshotReporterNoContext]
'
'''
- line 0␍
+ line 0␤
...
Expand All @@ -53,10 +53,10 @@
- line 3␤
+ line 3␍␤
...
'
---
'''
# ---
# name: TestSnapshotReporter.test_diff_lines[-2-SnapshotReporter]
'
'''
- line 0␍
+ line 0␤
line 1
Expand All @@ -67,5 +67,5 @@
line 4
...
line 7
'
---
'''
# ---
Loading

0 comments on commit b64b965

Please sign in to comment.