Skip to content

Commit

Permalink
API: add snapshot.match_object()
Browse files Browse the repository at this point in the history
  • Loading branch information
bblommers committed Apr 1, 2024
1 parent 1a22848 commit a0c26ce
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
14 changes: 14 additions & 0 deletions localstack_snapshot/snapshots/prototype.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,20 @@ def _load_state(self) -> dict:
def _update(self, key: str, obj_state: dict) -> None:
self.observed_state[key] = obj_state

def match_object(self, key: str, obj: object) -> None:
def _convert_object_to_dict(obj_):
if isinstance(obj_, dict):
for key in list(obj_.keys()):
obj_[key] = _convert_object_to_dict(obj_[key])
elif isinstance(obj_, list):
for idx, val in enumerate(obj_):
obj_[idx] = _convert_object_to_dict(val)
elif hasattr(obj_, "__dict__"):
return _convert_object_to_dict(obj_.__dict__)
return obj_

return self.match(key, _convert_object_to_dict(obj))

def match(self, key: str, obj: dict) -> None:
if key in self.called_keys:
raise Exception(
Expand Down
31 changes: 31 additions & 0 deletions tests/test_snapshots.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,37 @@ def test_context_replacement(self):
sm.match("key_a", {"aaa": "something", "bbb": "something hello"})
sm._assert_all()

def test_match_object_nochange(self):
class CustomObject:
def __init__(self, name, nested=False):
self.name = name
if nested:
self.nested = CustomObject(f"nested{name}")
self.listed = [CustomObject(f"listed{name}"), "otherobj"]

sm = SnapshotSession(scope_key="A", verify=True, base_file_path="", update=False)
sm.recorded_state = {
"key_a": {
"name": "myname",
"nested": {"name": "nestedmyname"},
"listed": [{"name": "listedmyname"}, "otherobj"],
}
}
sm.match_object("key_a", CustomObject(name="myname", nested=True))
sm._assert_all()

def test_match_object_change(self):
class CustomObject:
def __init__(self, name):
self.name = name

sm = SnapshotSession(scope_key="A", verify=True, base_file_path="", update=False)
sm.recorded_state = {"key_a": {"name": "myname"}}
sm.match_object("key_a", CustomObject(name="diffname"))
with pytest.raises(Exception) as ctx:
sm._assert_all()
ctx.match("Parity snapshot failed")

# def test_context_replacement_no_change(self):
# sm = SnapshotSession(scope_key="A", verify=True, base_file_path="", update=False)
# sm.add_transformer(TransformerUtility.key_value("name"))
Expand Down

0 comments on commit a0c26ce

Please sign in to comment.