From 4c2d94b056094aa79ef528ee20d25e4b50f1a3ce Mon Sep 17 00:00:00 2001 From: "thomas.storek" <20579672+tstorek@users.noreply.github.com> Date: Wed, 31 May 2023 15:16:12 +0200 Subject: [PATCH] chore: added missing test For #186 --- filip/models/ngsi_v2/units.py | 3 ++- tests/models/test_units.py | 44 +++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/filip/models/ngsi_v2/units.py b/filip/models/ngsi_v2/units.py index 4410952f..e55ccf8f 100644 --- a/filip/models/ngsi_v2/units.py +++ b/filip/models/ngsi_v2/units.py @@ -205,6 +205,7 @@ def __getattr__(self, item): Return unit as attribute by name or code. Notes: Underscores will be substituted with whitespaces + Args: item: if len(row) == 0: @@ -223,7 +224,7 @@ def quantities(self): """ raise NotImplementedError("The used dataset does currently not " "contain the information about quantity") - + @lru_cache() def __getitem__(self, item: str) -> Unit: """ Get unit by name or code diff --git a/tests/models/test_units.py b/tests/models/test_units.py index ace974dc..af1cb219 100644 --- a/tests/models/test_units.py +++ b/tests/models/test_units.py @@ -2,6 +2,7 @@ Test for filip.models.units """ from unittest import TestCase +import functools from filip.models.ngsi_v2.units import \ Unit, \ Units, \ @@ -39,16 +40,47 @@ def test_unit_text(self): def test_unit_model(self): """ Test unit model + Returns: None """ + # test creation unit = Unit(**self.unit) unit_from_json = Unit.parse_raw(unit.json(by_alias=True)) self.assertEqual(unit, unit_from_json) + def test_unit_model_caching(self): + """ + Test caching of unit model + + Returns: + None + """ + + unit = Unit(**self.unit) + # testing hashing and caching + from functools import lru_cache + from time import perf_counter_ns + + self.assertEqual(unit.__hash__(), unit.__hash__()) + + @functools.lru_cache + def cache_unit(unit: Unit): + return Unit(name=unit.name) + + timers = [] + for i in range(5): + start = perf_counter_ns() + cache_unit(unit) + stop = perf_counter_ns() + timers.append(stop - start) + if i > 0: + self.assertLess(timers[i], timers[0]) + def test_units(self): """ Test units api + Returns: None """ @@ -69,6 +101,18 @@ def test_unit_validator(self): Returns: None """ + # using garbage collector to clean up all caches + import gc + gc.collect() + + # All objects collected + objects = [i for i in gc.get_objects() + if isinstance(i, functools._lru_cache_wrapper)] + + # All objects cleared + for object in objects: + object.cache_clear() + unit_data = self.unit.copy() unit_data['name'] = "celcius" with self.assertRaises(ValueError):