/
test_backends_lru_cache.py
89 lines (68 loc) · 2.21 KB
/
test_backends_lru_cache.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
from typing import Any
from unittest import mock
import pytest
from xarray.backends.lru_cache import LRUCache
def test_simple() -> None:
cache: LRUCache[Any, Any] = LRUCache(maxsize=2)
cache["x"] = 1
cache["y"] = 2
assert cache["x"] == 1
assert cache["y"] == 2
assert len(cache) == 2
assert dict(cache) == {"x": 1, "y": 2}
assert list(cache.keys()) == ["x", "y"]
assert list(cache.items()) == [("x", 1), ("y", 2)]
cache["z"] = 3
assert len(cache) == 2
assert list(cache.items()) == [("y", 2), ("z", 3)]
def test_trivial() -> None:
cache: LRUCache[Any, Any] = LRUCache(maxsize=0)
cache["x"] = 1
assert len(cache) == 0
def test_invalid() -> None:
with pytest.raises(TypeError):
LRUCache(maxsize=None) # type: ignore
with pytest.raises(ValueError):
LRUCache(maxsize=-1)
def test_update_priority() -> None:
cache: LRUCache[Any, Any] = LRUCache(maxsize=2)
cache["x"] = 1
cache["y"] = 2
assert list(cache) == ["x", "y"]
assert "x" in cache # contains
assert list(cache) == ["y", "x"]
assert cache["y"] == 2 # getitem
assert list(cache) == ["x", "y"]
cache["x"] = 3 # setitem
assert list(cache.items()) == [("y", 2), ("x", 3)]
def test_del() -> None:
cache: LRUCache[Any, Any] = LRUCache(maxsize=2)
cache["x"] = 1
cache["y"] = 2
del cache["x"]
assert dict(cache) == {"y": 2}
def test_on_evict() -> None:
on_evict = mock.Mock()
cache = LRUCache(maxsize=1, on_evict=on_evict)
cache["x"] = 1
cache["y"] = 2
on_evict.assert_called_once_with("x", 1)
def test_on_evict_trivial() -> None:
on_evict = mock.Mock()
cache = LRUCache(maxsize=0, on_evict=on_evict)
cache["x"] = 1
on_evict.assert_called_once_with("x", 1)
def test_resize() -> None:
cache: LRUCache[Any, Any] = LRUCache(maxsize=2)
assert cache.maxsize == 2
cache["w"] = 0
cache["x"] = 1
cache["y"] = 2
assert list(cache.items()) == [("x", 1), ("y", 2)]
cache.maxsize = 10
cache["z"] = 3
assert list(cache.items()) == [("x", 1), ("y", 2), ("z", 3)]
cache.maxsize = 1
assert list(cache.items()) == [("z", 3)]
with pytest.raises(ValueError):
cache.maxsize = -1