From 6a894b61542a3e58628ba6b88df57e79aa3b12e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mose=20M=C3=BCller?= Date: Tue, 21 May 2024 13:39:41 +0200 Subject: [PATCH] adds test for dict/list garbage collection --- .../observable/test_observable_object.py | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/tests/observer_pattern/observable/test_observable_object.py b/tests/observer_pattern/observable/test_observable_object.py index 6c9eb29..74c8a47 100644 --- a/tests/observer_pattern/observable/test_observable_object.py +++ b/tests/observer_pattern/observable/test_observable_object.py @@ -311,3 +311,51 @@ def test_list_remove(caplog: pytest.LogCaptureFixture) -> None: # checks if observer key was updated correctly (was index 1) other_observable_instance_2.greeting = "Ciao" assert "'my_list[0].greeting' changed to 'Ciao'" in caplog.text + + +def test_list_garbage_collection() -> None: + """Makes sure that the GC collects lists that are not referenced anymore.""" + + import gc + import json + + list_json = """ + [1] + """ + + class MyObservable(Observable): + def __init__(self) -> None: + super().__init__() + self.list_attr = json.loads(list_json) + + observable = MyObservable() + list_mapping_length = len(observable._list_mapping) + observable.list_attr = json.loads(list_json) + + gc.collect() + assert len(observable._list_mapping) <= list_mapping_length + + +def test_dict_garbage_collection() -> None: + """Makes sure that the GC collects dicts that are not referenced anymore.""" + + import gc + import json + + dict_json = """ + { + "foo": "bar" + } + """ + + class MyObservable(Observable): + def __init__(self) -> None: + super().__init__() + self.dict_attr = json.loads(dict_json) + + observable = MyObservable() + dict_mapping_length = len(observable._dict_mapping) + observable.dict_attr = json.loads(dict_json) + + gc.collect() + assert len(observable._dict_mapping) <= dict_mapping_length