-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathtest_units.py
137 lines (110 loc) · 3.24 KB
/
test_units.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
"""
Test for filip.models.units
"""
import unittest
import functools
from filip.models.ngsi_v2.units import \
Unit, \
Units, \
UnitCode, \
UnitText, \
load_units
class TestUnitCodes(unittest.TestCase):
def setUp(self):
self.units_data = load_units()
self.units = Units()
self.unit = {"code": "C58",
"name": "newton second per metre"}
def test_unit_code(self):
"""
test unit code model
Returns:
None
"""
for index, row in self.units_data.iterrows():
UnitCode(value=row.CommonCode)
def test_unit_text(self):
"""
test unit text/name model
Returns:
None
"""
for index, row in self.units_data.iterrows():
UnitText(value=row.Name)
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
"""
units = Units()
self.assertEqual(self.units_data.Name.to_list(), units.keys())
self.assertEqual(self.units_data.Name.to_list(), units.names)
self.assertEqual(self.units_data.CommonCode.to_list(),
units.keys(by_code=True))
self.assertEqual(self.units_data.CommonCode.to_list(), units.codes)
# check get or __getitem__, respectively
for k in units.keys():
units.get(k)
for k in units.keys(by_code=True):
units.get(k)
# check serialization
for v in units.values():
v.json(indent=2)
def test_unit_validator(self):
"""
Test if unit hints are given for typos
Returns:
None
"""
unit_data = self.unit.copy()
unit_data['name'] = "celcius"
with self.assertRaises(ValueError):
Unit(**unit_data)
def tearDown(self):
"""
clean up
"""
# 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()
if __name__ == '__main__':
unittest.main()