Total Complexity | 3 |
Total Lines | 64 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | import typing as t |
||
2 | |||
3 | import pytest |
||
4 | |||
5 | from software_patterns import Singleton |
||
6 | |||
7 | |||
8 | def test_singleton(assert_same_objects): |
||
9 | class MySingleton(metaclass=Singleton): |
||
10 | def __init__(self, data: t.MutableMapping): |
||
11 | self.data = data |
||
12 | |||
13 | instance_1 = MySingleton({'a': 1}) |
||
14 | instance_2 = MySingleton({'b': 2}) |
||
15 | |||
16 | assert_same_objects(instance_1, instance_2) |
||
17 | |||
18 | assert instance_1.data['a'] == instance_2.data['a'] == 1 |
||
19 | assert 'b' not in instance_1.data |
||
20 | assert 'b' not in instance_2.data |
||
21 | |||
22 | instance_1.data['c'] = 0 |
||
23 | |||
24 | assert instance_2.data['c'] == 0 |
||
25 | |||
26 | |||
27 | @pytest.fixture |
||
28 | def assert_same_objects(): |
||
29 | def _assert_same_objects(obj1, obj2): |
||
30 | assert id(obj1) == id(obj2) |
||
31 | attributes_1 = list(dir(obj1)) |
||
32 | attributes_2 = list(dir(obj2)) |
||
33 | assert attributes_1 == attributes_2 |
||
34 | for attr_name in set(attributes_1).difference( |
||
35 | { |
||
36 | '__delattr__', |
||
37 | '__init__', |
||
38 | '__gt__', |
||
39 | '__ne__', |
||
40 | '__dir__', |
||
41 | '__repr__', |
||
42 | '__setattr__', |
||
43 | '__le__', |
||
44 | '__subclasshook__', |
||
45 | '__str__', |
||
46 | '__format__', |
||
47 | '__lt__', |
||
48 | '__eq__', |
||
49 | '__reduce_ex__', |
||
50 | '__getattribute__', |
||
51 | '__reduce__', |
||
52 | '__init_subclass__', |
||
53 | '__hash__', |
||
54 | '__sizeof__', |
||
55 | '__ge__', |
||
56 | '__getstate__', |
||
57 | } |
||
58 | ): |
||
59 | print(attr_name) |
||
60 | assert getattr(obj1, attr_name) == getattr(obj2, attr_name) |
||
61 | assert id(getattr(obj1, attr_name)) == id(getattr(obj2, attr_name)) |
||
62 | |||
63 | return _assert_same_objects |
||
64 |