-
Notifications
You must be signed in to change notification settings - Fork 4
/
test_sentinel.py
192 lines (146 loc) · 5.26 KB
/
test_sentinel.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import copy
import pickle
from pathlib import Path
import pytest
import sentinel
try:
import varname # type: ignore
except ImportError:
HAS_VARNAME = False
else:
HAS_VARNAME = True
# Must be defined at module-level due to limitations in how the pickle module works :/
Pickleable = sentinel.create("Pickleable")
PACKAGE_ROOT = Path(__file__).parent.resolve()
def test_basic_usage():
"""
Tests basic things in the README
"""
Nothing = sentinel.create("Nothing")
assert str(Nothing) == repr(Nothing) == "Nothing"
MissingEntry = sentinel.create("MissingEntry")
d = {"stdout": None, "stdin": 0}
assert d.get("stderr", MissingEntry) is MissingEntry
def test_adding_methods():
"""
From the README -- adding methods to the Leaf singleton.
"""
def _search_leaf(self, key):
raise KeyError(key)
Leaf = sentinel.create(
"Leaf",
cls_dict={"search": _search_leaf, "is_leaf": property(lambda self: True)},
)
class Node(object):
is_leaf = False
def __init__(self, key, payload, left=Leaf, right=Leaf):
self.left = left
self.right = right
self.key = key
self.payload = payload
def search(self, key):
if key < self.key:
return self.left.search(key)
elif key > self.key:
return self.right.search(key)
else:
return self.payload
tree = Node(2, "bar", Node(1, "foo"), Node(3, "baz"))
assert tree.search(1) == "foo"
with pytest.raises(KeyError):
tree.search(4) == "foo"
def test_always_greater():
"""
From README -- test overriding dunder methods.
"""
# When I wrote this in 2014 I thought it was a brilliant idea, but now it seems like
# this hack would probably invalidate assumptions made by a lot of code :/
IntInfinity = sentinel.create(
"IntInfinity",
(int,),
cls_dict={
"__lt__": lambda self, other: False,
"__gt__": lambda self, other: True,
"__ge__": lambda self, other: True,
"__le__": lambda self, other: True if self is other else False,
},
)
assert isinstance(IntInfinity, int)
assert IntInfinity > 10 ** 1000
assert (10 ** 1000 > IntInfinity) == False
# uh, okay, this is wild and also bad:
assert IntInfinity == 0
assert bool(IntInfinity) == False
assert IntInfinity + 8 == 8
# This is less wild but still weird
arg = (IntInfinity, None, None)
AlwaysGreater = sentinel.create("AlwaysGreater", (tuple,), {}, arg)
assert (1, ..., ...) < AlwaysGreater
assert (AlwaysGreater < (1, ..., ...)) == False
def test_new_returns_singleton():
"""
Tests that getting the class and calling it returns the same singleton instance.
"""
ExistingSentinel = sentinel.create("ExistingSentinel")
Constructor = type(ExistingSentinel)
assert Constructor() is ExistingSentinel
def test_pickle(tmp_path):
"""
Save a singleton to a pickle and get it back out.
"""
# Just put it everywhere:
arbitrary_data_structure = {Pickleable: (Pickleable, [Pickleable])}
pickle_path = tmp_path / "data.pickle"
with pickle_path.open(mode="wb") as fp:
pickle.dump(arbitrary_data_structure, fp)
with pickle_path.open(mode="rb") as fp:
unpickled = pickle.load(fp)
# Open up the data structure
assert Pickleable in unpickled
assert unpickled[Pickleable][0] is Pickleable
assert unpickled[Pickleable][1][0] is Pickleable
def test_copy():
"""
Tests that copy.deepcopy() works.
"""
Copyable = sentinel.create("Copyable")
arbitrary_data_structure = {Copyable: (Copyable, [Copyable])}
copied = copy.deepcopy(arbitrary_data_structure)
assert copied is not arbitrary_data_structure
assert copied == arbitrary_data_structure
# Check that the structure is the same
assert Copyable in copied
assert copied[Copyable][0] is Copyable
assert copied[Copyable][1][0] is Copyable
# Check that the objects are different
assert copied[Copyable][1] is not arbitrary_data_structure[Copyable][1]
@pytest.mark.skipif(not HAS_VARNAME, reason="varname PyPI package not installed")
def test_varname():
"""
Tests inferring the variable name. Requires varname library be installed.
"""
Dark = sentinel.create()
Magicks = sentinel.create()
assert repr(Dark) == "Dark"
assert repr(Magicks) == "Magicks"
def test_can_get_instance_from_class():
"""
Tests whether you can retrieve the instance from the class. I literally
don't remember why this is a feature of this package, but it'll be a
regression if I remove it, so here we are!
"""
MySentinel = sentinel.create("MySentinel")
MySenintelType = type(MySentinel)
assert MySenintelType.instance is MySentinel
def test_version_number():
"""
Ensure the version number in the package matches what's in the pyproject.toml.
"""
import toml # type: ignore
from sentinel import __version__ as version
config_file = PACKAGE_ROOT / "pyproject.toml"
assert config_file.exists()
pyproject = toml.load(config_file)
assert pyproject["tool"]["poetry"]["version"] == version