[e988c2]: / tests / unit / utils / test_functools_utils.py

Download this file

51 lines (36 with data), 1.2 kB

 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
import pytest
from ehrql.utils.functools_utils import singledispatchmethod_with_cache
@pytest.fixture
def TestClass():
COUNTER = 0
class TestClass:
@singledispatchmethod_with_cache
def test(self, value):
assert False
@test.register(str)
def test_str(self, value):
# Use a shared counter to give different results for each call
nonlocal COUNTER
COUNTER += 1
return value, COUNTER
return TestClass
def test_results_are_cached(TestClass):
obj = TestClass()
assert obj.test("hello") is obj.test("hello")
def test_cache_is_unique_to_instances(TestClass):
obj1 = TestClass()
obj2 = TestClass()
assert obj1.test("hello") is not obj2.test("hello")
def test_cache_can_be_cleared(TestClass):
obj = TestClass()
result = obj.test("hello")
obj.test.cache_clear()
assert result is not obj.test("hello")
def test_clearing_cache_only_affects_single_instance(TestClass):
obj1 = TestClass()
obj2 = TestClass()
result1 = obj1.test("hello")
result2 = obj2.test("hello")
obj1.test.cache_clear()
assert result1 is not obj1.test("hello")
assert result2 is obj2.test("hello")