From a0c26cecf66c54d1f210ab52c424b28889154291 Mon Sep 17 00:00:00 2001 From: Bert Blommers Date: Mon, 1 Apr 2024 12:39:53 +0000 Subject: [PATCH] API: add snapshot.match_object() --- localstack_snapshot/snapshots/prototype.py | 14 ++++++++++ tests/test_snapshots.py | 31 ++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/localstack_snapshot/snapshots/prototype.py b/localstack_snapshot/snapshots/prototype.py index 04221e6..9f46966 100644 --- a/localstack_snapshot/snapshots/prototype.py +++ b/localstack_snapshot/snapshots/prototype.py @@ -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( diff --git a/tests/test_snapshots.py b/tests/test_snapshots.py index 2801741..b34d9d1 100644 --- a/tests/test_snapshots.py +++ b/tests/test_snapshots.py @@ -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"))