-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_pool.py
More file actions
80 lines (53 loc) · 2.33 KB
/
Copy pathtest_pool.py
File metadata and controls
80 lines (53 loc) · 2.33 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
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
"""Behavioral tests for the InternPool building block."""
from __future__ import annotations
from dataclasses import dataclass
import pytest
from patterns.structural.flyweight.pattern import InternPool
@dataclass(frozen=True)
class Color:
name: str
def test_same_key_yields_the_identical_object() -> None:
pool: InternPool[str, Color] = InternPool(Color)
assert pool.get("red") is pool.get("red")
def test_distinct_keys_stay_distinct() -> None:
pool: InternPool[str, Color] = InternPool(Color)
assert pool.get("red") is not pool.get("blue")
assert len(pool) == 2
def test_build_runs_once_per_key() -> None:
built: list[str] = []
def build(name: str) -> Color:
built.append(name)
return Color(name)
pool = InternPool(build)
pool.get("red"), pool.get("red"), pool.get("red")
assert built == ["red"]
def test_contains_reflects_what_was_interned() -> None:
pool: InternPool[str, Color] = InternPool(Color)
pool.get("red")
assert "red" in pool
assert "blue" not in pool
def test_strict_pool_accepts_frozen_values() -> None:
pool: InternPool[str, Color] = InternPool(Color, strict=True)
assert pool.get("red") is pool.get("red")
def test_strict_pool_refuses_mutable_values() -> None:
pool: InternPool[str, list[str]] = InternPool(lambda k: [k], strict=True)
with pytest.raises(TypeError, match="must be immutable"):
pool.get("red")
def test_strict_pool_refuses_a_tuple_holding_a_mutable() -> None:
# A tuple is only as frozen as its elements: mutating the inner list
# would corrupt every holder of the shared value.
pool: InternPool[str, tuple[list[str]]] = InternPool(lambda k: ([k],), strict=True)
with pytest.raises(TypeError, match="must be immutable"):
pool.get("red")
def test_strict_pool_accepts_deeply_frozen_nesting() -> None:
pool: InternPool[str, tuple[object, ...]] = InternPool(
lambda k: (k, frozenset({(k, 1)}), Color(k)), strict=True
)
assert pool.get("red") is pool.get("red")
def test_strict_pool_refuses_a_frozen_dataclass_with_a_mutable_field() -> None:
@dataclass(frozen=True)
class Palette:
names: list[str]
pool: InternPool[str, Palette] = InternPool(lambda k: Palette([k]), strict=True)
with pytest.raises(TypeError, match="must be immutable"):
pool.get("red")