Repository navigation
Expand file tree
/
Copy pathtyping_api_test.py
More file actions
200 lines (171 loc) · 9.15 KB
/
Copy pathtyping_api_test.py
File metadata and controls
200 lines (171 loc) · 9.15 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
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
193
194
195
196
197
198
199
200
"""Type-stub and signature test for the espp python bindings.
The installed package ships the type stubs generated from the built module
(lib/generate_stubs.py), so this checks that they are present next to the
extension and describe it (every name the package exports is in a stub). It
also covers the bindings whose signatures the stubs made visible:
- FtpServer's root directory is a std::filesystem::path: it accepts a str or
an os.PathLike (it could not be constructed from python before), and rejects
anything else;
- Vector2d's comparisons all come from its operator<=> (operator== is not bound
a second time): ==, != and < work, and comparing with another type raises
TypeError (the stubs type == with the class itself);
- Rgb and Hsv convert to each other;
- an empty callback property is None and takes None, and stream_frame's
binary parameters take bytes (two of the stub fixes rest on this);
- signatures name python types, not C++ ones (`espp::...`, `std::...`), apart
from the few the stub generator knows how to fix (KNOWN_CPP_NAMES): a new one
means a header is bound before a type its signatures use (see the header
order in lib/autogenerate_bindings.py).
No network: FtpServer is constructed, never started.
Exit code 0 on full pass, 1 on any failure.
"""
import ast
import inspect
import pathlib
import re
import sys
import tempfile
import espp
failures = 0
# (qualified function, C++ name) pairs pybind11 cannot write as python, each fixed up in the
# stubs by lib/generate_stubs.py. std::__1:: is libc++'s namespace; see _cpp_names().
KNOWN_CPP_NAMES = {
("Rgb.__init__", "espp::Hsv"), # Rgb and Hsv convert to each other: one is bound first
("Rgb.hsv", "espp::Hsv"),
("Task.Config.__init__", "std::mutex"), # the task-owned mutex / condition variable callback
("Task.Config.__init__", "std::condition_variable"),
("Task.Config.callback", "std::mutex"),
("Task.Config.callback", "std::condition_variable"),
("Task.get_id", "std::thread::id"),
("Task.get_current_id", "std::thread::id"),
}
_CPP_NAME = re.compile(r"\b(?:espp|std|fmt)::[\w:<>]+")
def _cpp_names():
"""(qualified function, C++ name) for every signature line that names a C++ type."""
found = set()
def normalize(name):
name = name.replace("std::__1::", "std::")
return "std::thread::id" if name in ("std::__thread_id", "std::thread::id") else name
def visit(obj, prefix, depth):
for attr, value in vars(obj).items():
if attr.startswith("__") and attr not in ("__init__", "__eq__", "__ne__", "__call__"):
continue
target = value.fget if isinstance(value, property) else value
if isinstance(target, (staticmethod, classmethod)):
target = target.__func__
if isinstance(value, type) and value.__module__.startswith("espp") and depth < 3:
visit(value, f"{prefix}{attr}.", depth + 1)
elif callable(target) or isinstance(value, property):
doc = getattr(target, "__doc__", None) or ""
for line in doc.splitlines():
if "(" in line and ") ->" in line: # a signature line
for cpp in _CPP_NAME.findall(line):
if not cpp.startswith("std::function"):
found.add((f"{prefix}{attr}", normalize(cpp.rstrip(">,"))))
visit(espp._espp, "", 0)
return found
def check(condition, what):
global failures
if condition:
print(f"PASS {what}")
else:
failures += 1
print(f"FAIL {what}")
def raises(exc, fn):
try:
fn()
except exc:
return True
return False
def stub_names(path: pathlib.Path) -> set:
tree = ast.parse(path.read_text())
names = set()
for node in tree.body:
if isinstance(node, (ast.ClassDef, ast.FunctionDef)):
names.add(node.name)
elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
names.add(node.target.id)
elif isinstance(node, ast.Assign):
names.update(t.id for t in node.targets if isinstance(t, ast.Name))
elif isinstance(node, (ast.Import, ast.ImportFrom)):
names.update((a.asname or a.name).split(".")[0] for a in node.names)
return names
def main() -> int:
package = pathlib.Path(espp.__file__).parent
stubs = {name: package / name for name in
["__init__.pyi", "_espp/__init__.pyi", "_espp/wdi.pyi", "_espp/stream_frame.pyi"]}
for name, path in stubs.items():
check(path.is_file(), f"the package ships {name}")
check((package / "py.typed").is_file(), "the package ships py.typed")
if stubs["_espp/__init__.pyi"].is_file():
described = stub_names(stubs["_espp/__init__.pyi"])
missing = sorted(n for n in dir(espp._espp) if not n.startswith("_") and n not in described)
check(not missing, f"every name in espp._espp has a stub (missing: {missing})")
text = stubs["_espp/__init__.pyi"].read_text()
check("def hsv(self) -> Hsv:" in text, "the stub types Rgb.hsv() as Hsv")
if stubs["__init__.pyi"].is_file():
described = stub_names(stubs["__init__.pyi"])
# espp has no __all__: its public names are what `from ._espp import *` and the
# explicit imports put there
exported = getattr(espp, "__all__", [n for n in dir(espp) if not n.startswith("_")])
check(len(exported) > 50, f"espp exports its API ({len(exported)} names)")
missing = sorted(n for n in exported if n not in described)
check(not missing, f"every name espp exports has a stub (missing: {missing})")
# FtpServer: root is a std::filesystem::path
root = tempfile.mkdtemp()
check(isinstance(espp.FtpServer("127.0.0.1", 0, root), espp.FtpServer), "FtpServer(root=str)")
check(isinstance(espp.FtpServer("127.0.0.1", 0, pathlib.Path(root)), espp.FtpServer),
"FtpServer(root=pathlib.Path)")
check(raises(TypeError, lambda: espp.FtpServer("127.0.0.1", 0, 5)), "FtpServer(root=int) raises")
check("os.PathLike" in (espp.FtpServer.__init__.__doc__ or ""),
"FtpServer's signature names os.PathLike, not std::filesystem::path")
# Vector2d comparisons, all from operator<=>
a, b = espp.Vector2d_int(1, 2), espp.Vector2d_int(2, 0)
check(a == espp.Vector2d_int(1, 2) and not (a == b), "Vector2d_int ==")
check(a != b and not (a != espp.Vector2d_int(1, 2)), "Vector2d_int !=")
a2, b2 = espp.Vector2d_int(1, 2), espp.Vector2d_int(2, 0) # equal values, other objects
# one bound operator per check (each is the binding under test, not arithmetic)
check(a < b, "Vector2d_int <")
check(not b < a, "Vector2d_int < (false)")
check(a <= a2, "Vector2d_int <=")
check(b > a, "Vector2d_int >")
check(b >= b2, "Vector2d_int >=")
check(raises(TypeError, lambda: a == "x"), "Vector2d_int == str raises TypeError")
check(espp.Vector2d_float(0.5, 1.0) == espp.Vector2d_float(0.5, 1.0), "Vector2d_float ==")
check(len(espp.Vector2d_int.__eq__.__doc__.strip().splitlines()) >= 1 and
"2. " not in espp.Vector2d_int.__eq__.__doc__, "Vector2d_int.__eq__ has one overload")
# Rgb <-> Hsv
red = espp.Rgb(1.0, 0.0, 0.0)
hsv = red.hsv()
check(isinstance(hsv, espp.Hsv), "Rgb.hsv() returns an Hsv")
check(espp.Rgb(hsv) == red, "Rgb(Hsv) round trip")
# what two stub fixes rely on: std::function members are None while empty and take None,
# and the binary std::string parameters take bytes (a frame round-trips through them)
config = espp.Timer.Config()
check(config.callback is None, "an empty callback property reads back None")
config.callback = lambda: False
config.callback = None
check(config.callback is None, "a callback property can be cleared with None")
frame = espp.stream_frame.build_frame(4, 1, b"\x00\xff")
parsed = espp.stream_frame.StreamParser().feed(frame)
check(isinstance(frame, bytes) and len(parsed) == 1 and parsed[0].payload == b"\x00\xff",
"stream_frame: build_frame(bytes) -> feed(bytes) round trip")
check(espp.stream_frame.crc32(b"\x01\x02") == espp.stream_frame.crc32("\x01\x02"),
"stream_frame.crc32 takes bytes")
# signatures name python types, apart from the known few
for fn, what in [(espp.BaseComponent.get_log_level, "BaseComponent.get_log_level"),
(espp.UdpSocket.start_receiving, "UdpSocket.start_receiving"),
(espp.EventManager.add_subscriber, "EventManager.add_subscriber"),
(espp.JpegFrame.get_header, "JpegFrame.get_header")]:
doc = inspect.getdoc(fn) or ""
check(doc and "espp::" not in doc, f"{what}'s signature names python types")
cpp = _cpp_names()
check(not (cpp - KNOWN_CPP_NAMES),
f"no new C++ names in signatures (new: {sorted(cpp - KNOWN_CPP_NAMES)})")
check(not (KNOWN_CPP_NAMES - cpp),
f"every known C++ name is still there (gone: {sorted(KNOWN_CPP_NAMES - cpp)}; "
"drop them here and their fix in lib/generate_stubs.py)")
print(f"typing api: {'all passed' if failures == 0 else f'{failures} failed'}")
return 0 if failures == 0 else 1
if __name__ == "__main__":
sys.exit(main())