Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: exit serialization early on detection of a cycle #78

Merged
merged 7 commits into from
Dec 29, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 57 additions & 20 deletions src/syrupy/serializers/amber.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
Any,
Dict,
Iterable,
List,
Set,
)

Expand All @@ -17,6 +18,8 @@


class DataSerializer:
_max_depth: int = 99
_max_depth_value: str = "..."
indent: str = " "
name_marker: str = "# name:"
divider: str = "---"
Expand Down Expand Up @@ -89,7 +92,9 @@ def object_type(cls, data: "SerializableData") -> str:
return f"<class '{data.__class__.__name__}'>"

@classmethod
def serialize_string(cls, data: "SerializableData", indent: int = 0) -> str:
def serialize_string(
cls, data: "SerializableData", *, indent: int = 0, visited: List[Any] = []
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can remove the unused visited kwarg if we do **_, not sure how mypy handles that though?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it complained last I tried, will attempt again but treating as non blocking

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Too much refactoring needed to satisfy mypy and ignore the argument, leaving as is

) -> str:
if "\n" in data:
return (
cls.with_indent("'\n", indent)
Expand All @@ -99,27 +104,40 @@ def serialize_string(cls, data: "SerializableData", indent: int = 0) -> str:
return cls.with_indent(repr(data), indent)

@classmethod
def serialize_number(cls, data: "SerializableData", indent: int = 0) -> str:
def serialize_number(
cls, data: "SerializableData", *, indent: int = 0, visited: List[Any] = []
) -> str:
return cls.with_indent(repr(data), indent)

@classmethod
def serialize_set(cls, data: "SerializableData", indent: int = 0) -> str:
def serialize_set(
cls, data: "SerializableData", *, indent: int = 0, visited: List[Any] = []
) -> str:
return (
cls.with_indent(f"{cls.object_type(data)} {{\n", indent)
+ "".join([f"{cls.serialize(d, indent + 1)},\n" for d in cls.sort(data)])
+ "".join(
[
f"{cls.serialize(d, indent=indent + 1, visited=visited)},\n"
for d in cls.sort(data)
]
)
+ cls.with_indent("}", indent)
)

@classmethod
def serialize_dict(cls, data: "SerializableData", indent: int = 0) -> str:
def serialize_dict(
cls, data: "SerializableData", *, indent: int = 0, visited: List[Any] = []
) -> str:
return (
cls.with_indent(f"{cls.object_type(data)} {{\n", indent)
+ "".join(
[
(
cls.serialize(key, indent + 1)
cls.serialize(key, indent=indent + 1)
+ ": "
+ cls.serialize(data[key], indent + 1).lstrip(cls.indent)
+ cls.serialize(
data[key], indent=indent + 1, visited=visited
).lstrip(cls.indent)
+ ",\n"
)
for key in cls.sort(data.keys())
Expand All @@ -129,31 +147,52 @@ def serialize_dict(cls, data: "SerializableData", indent: int = 0) -> str:
)

@classmethod
def serialize_iterable(cls, data: "SerializableData", indent: int = 0) -> str:
def serialize_iterable(
cls, data: "SerializableData", *, indent: int = 0, visited: List[Any] = []
) -> str:
open_paren, close_paren = next(
paren[1]
for paren in {list: "[]", tuple: "()", GeneratorType: "()"}.items()
if isinstance(data, paren[0])
)
return (
cls.with_indent(f"{cls.object_type(data)} {open_paren}\n", indent)
+ "".join([f"{cls.serialize(d, indent + 1)},\n" for d in data])
+ "".join(
[
f"{cls.serialize(d, indent=indent + 1, visited=visited)},\n"
for d in data
]
)
+ cls.with_indent(close_paren, indent)
)

@classmethod
def serialize(cls, data: "SerializableData", indent: int = 0) -> str:
def serialize_unknown(
cls, data: Any, *, indent: int = 0, visited: List[Any] = []
) -> str:
return cls.with_indent(repr(data), indent)

@classmethod
def serialize(
cls, data: "SerializableData", *, indent: int = 0, visited: List[Any] = []
) -> str:
if indent > cls._max_depth or data in visited:
data = cls._max_depth_value

serialize_kwargs = dict(data=data, indent=indent, visited=[*visited, data])
if isinstance(data, str):
return cls.serialize_string(data, indent)
serialize_method = cls.serialize_string
elif isinstance(data, (int, float)):
return cls.serialize_number(data, indent)
serialize_method = cls.serialize_number
elif isinstance(data, (set, frozenset)):
return cls.serialize_set(data, indent)
serialize_method = cls.serialize_set
elif isinstance(data, dict):
return cls.serialize_dict(data, indent)
serialize_method = cls.serialize_dict
elif isinstance(data, (list, tuple, GeneratorType)):
return cls.serialize_iterable(data, indent)
return cls.with_indent(repr(data), indent)
serialize_method = cls.serialize_iterable
else:
serialize_method = cls.serialize_unknown
return serialize_method(**serialize_kwargs)


class AmberSnapshotSerializer(AbstractSnapshotSerializer):
Expand All @@ -162,12 +201,10 @@ class AmberSnapshotSerializer(AbstractSnapshotSerializer):

```
# name: test_name_1

data
data
---
# name: test_name_2

data
data
```
"""

Expand Down
16 changes: 16 additions & 0 deletions tests/__snapshots__/test_amber_serializer.ambr
Original file line number Diff line number Diff line change
@@ -1,6 +1,22 @@
# name: TestClass.test_name
'this is in a test class'
---
# name: test_cycle[cyclic0]
<class 'list'> [
1,
2,
3,
'...',
]
---
# name: test_cycle[cyclic1]
<class 'dict'> {
'a': 1,
'b': 2,
'c': 3,
'd': '...',
}
---
# name: test_dict[actual0]
<class 'dict'> {
'a': <class 'dict'> {
Expand Down
12 changes: 12 additions & 0 deletions tests/test_amber_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,18 @@ def test_list(snapshot):
assert snapshot == [1, 2, "string", {"key": "value"}]


list_cycle = [1, 2, 3]
list_cycle.append(list_cycle)

dict_cycle = {"a": 1, "b": 2, "c": 3}
dict_cycle.update(d=dict_cycle)


@pytest.mark.parametrize("cyclic", [list_cycle, dict_cycle])
def test_cycle(cyclic, snapshot):
assert cyclic == snapshot


class TestClass:
def test_name(self, snapshot):
assert snapshot == "this is in a test class"