Debian Codegraph @

src/trio/_tests/test_exports.py

raw
1 from __future__ import annotations # isort: split
2
3 import __future__ # Regular import, not special!
4
5 import enum
6 import functools
7 import importlib
8 import inspect
9 import json
10 import socket as stdlib_socket
11 import sys
12 import types
13 from pathlib import Path, PurePath
14 from types import ModuleType
15 from typing import TYPE_CHECKING, Any, Protocol
16
17 import attrs
18 import pytest
19
20 import trio
21 import trio.testing
22 from trio._tests.pytest_plugin import RUN_SLOW, skip_if_optional_else_raise
23
24 from .. import _core, _util
25 from .._core._tests.tutil import slow
26
27 if TYPE_CHECKING:
28 from collections.abc import Iterable, Iterator
29
30 mypy_cache_updated = False
31
32
33 try: # If installed, check both versions of this class.
34 from typing_extensions import Protocol as Protocol_ext
35 except ImportError: # pragma: no cover
36 Protocol_ext = Protocol
37
38
39 def _ensure_mypy_cache_updated() -> None:
40 # This pollutes the `empty` dir. Should this be changed?
41 try:
42 from mypy.api import run
43 except ImportError as error:
44 skip_if_optional_else_raise(error)
45
46 global mypy_cache_updated
47 if not mypy_cache_updated:
48 # mypy cache was *probably* already updated by the other tests,
49 # but `pytest -k ...` might run just this test on its own
50 result = run(
51 [
52 "--config-file=",
53 "--cache-dir=./.mypy_cache",
54 "--no-error-summary",
55 # TODO: update our tests to use the exposed APIs
56 # instead of reading JSON... or use dmypy?
57 "--no-fixed-format-cache",
58 "--no-sqlite-cache",
59 "-c",
60 "import trio",
61 ],
62 )
63 assert not result[1] # stderr
64 assert not result[0] # stdout
65 mypy_cache_updated = True
66
67
68 def test_core_is_properly_reexported() -> None:
69 # Each export from _core should be re-exported by exactly one of these
70 # three modules:
71 sources = [trio, trio.lowlevel, trio.testing]
72 for symbol in dir(_core):
73 if symbol.startswith("_"):
74 continue
75 found = 0
76 for source in sources:
77 if symbol in dir(source) and getattr(source, symbol) is getattr(
78 _core,
79 symbol,
80 ):
81 found += 1
82 print(symbol, found)
83 assert found == 1
84
85
86 def class_is_final(cls: type) -> bool:
87 """Check if a class cannot be subclassed."""
88 try:
89 # new_class() handles metaclasses properly, type(...) does not.
90 types.new_class("SubclassTester", (cls,))
91 except TypeError:
92 return True
93 else:
94 return False
95
96
97 def iter_modules(
98 module: types.ModuleType,
99 only_public: bool,
100 ) -> Iterator[types.ModuleType]:
101 yield module
102 for name, class_ in module.__dict__.items():
103 if name.startswith("_") and only_public:
104 continue
105 if not isinstance(class_, ModuleType):
106 continue
107 if not class_.__name__.startswith(module.__name__): # pragma: no cover
108 continue
109 if class_ is module: # pragma: no cover
110 continue
111 yield from iter_modules(class_, only_public)
112
113
114 PUBLIC_MODULES = list(iter_modules(trio, only_public=True))
115 ALL_MODULES = list(iter_modules(trio, only_public=False))
116 PUBLIC_MODULE_NAMES = [m.__name__ for m in PUBLIC_MODULES]
117
118
119 # It doesn't make sense for downstream redistributors to run this test, since
120 # they might be using a newer version of Python with additional symbols which
121 # won't be reflected in trio.socket, and this shouldn't cause downstream test
122 # runs to start failing.
123 @pytest.mark.redistributors_should_skip
124 @pytest.mark.skipif(
125 sys.version_info[:4] == (3, 14, 0, "beta"),
126 # 12 pass, 16 fail
127 reason="several tools don't support 3.14",
128 )
129 # Static analysis tools often have trouble with alpha releases, where Python's
130 # internals are in flux, grammar may not have settled down, etc.
131 @pytest.mark.skipif(
132 sys.version_info.releaselevel == "alpha",
133 reason="skip static introspection tools on Python dev/alpha releases",
134 )
135 @pytest.mark.parametrize("modname", PUBLIC_MODULE_NAMES)
136 @pytest.mark.parametrize("tool", ["pylint", "jedi", "mypy", "pyright_verifytypes"])
137 @pytest.mark.filterwarnings(
138 # https://github.com/pypa/setuptools/issues/3274
139 "ignore:module 'sre_constants' is deprecated:DeprecationWarning",
140 )
141 def test_static_tool_sees_all_symbols(tool: str, modname: str, tmp_path: Path) -> None:
142 module = importlib.import_module(modname)
143
144 def no_underscores(symbols: Iterable[str]) -> set[str]:
145 return {symbol for symbol in symbols if not symbol.startswith("_")}
146
147 runtime_names = no_underscores(dir(module))
148
149 # ignore deprecated module `tests` being invisible
150 if modname == "trio":
151 runtime_names.discard("tests")
152
153 # Ignore any __future__ feature objects, if imported under that name.
154 for name in __future__.all_feature_names:
155 if getattr(module, name, None) is getattr(__future__, name):
156 runtime_names.remove(name)
157
158 if tool == "pylint":
159 try:
160 from pylint.lint import PyLinter
161 except ImportError as error:
162 skip_if_optional_else_raise(error)
163
164 linter = PyLinter()
165 assert module.__file__ is not None
166 ast = linter.get_ast(module.__file__, modname)
167 static_names = no_underscores(ast) # type: ignore[arg-type]
168 elif tool == "jedi":
169 if sys.implementation.name != "cpython":
170 pytest.skip("jedi does not support pypy")
171
172 try:
173 import jedi
174 except ImportError as error:
175 skip_if_optional_else_raise(error)
176
177 # Simulate typing "import trio; trio.<TAB>"
178 script = jedi.Script(f"import {modname}; {modname}.")
179 completions = script.complete()
180 static_names = no_underscores(c.name for c in completions)
181 elif tool == "mypy":
182 if sys.implementation.name != "cpython":
183 # https://github.com/python/mypy/issues/20329
184 pytest.skip("mypy does not support pypy")
185
186 if not RUN_SLOW: # pragma: no cover
187 pytest.skip("use --run-slow to check against mypy")
188
189 cache = Path.cwd() / ".mypy_cache"
190
191 _ensure_mypy_cache_updated()
192
193 trio_cache = next(cache.glob("*/trio"))
194 _, modname = (modname + ".").split(".", 1)
195 modname = modname[:-1]
196 mod_cache = trio_cache / modname if modname else trio_cache
197 if mod_cache.is_dir(): # pragma: no coverage
198 mod_cache = mod_cache / "__init__.data.json"
199 else:
200 mod_cache = trio_cache / (modname + ".data.json")
201
202 assert mod_cache.exists()
203 assert mod_cache.is_file()
204 with mod_cache.open() as cache_file:
205 cache_json = json.loads(cache_file.read())
206 static_names = no_underscores(
207 key
208 for key, value in cache_json["names"].items()
209 if not key.startswith(".") and value["kind"] == "Gdef"
210 )
211 elif tool == "pyright_verifytypes":
212 if not RUN_SLOW: # pragma: no cover
213 pytest.skip("use --run-slow to check against pyright")
214
215 try:
216 import pyright # noqa: F401
217 except ImportError as error:
218 skip_if_optional_else_raise(error)
219 import subprocess
220
221 res = subprocess.run(
222 ["pyright", f"--verifytypes={modname}", "--outputjson"],
223 capture_output=True,
224 )
225 current_result = json.loads(res.stdout)
226
227 static_names = {
228 x["name"][len(modname) + 1 :]
229 for x in current_result["typeCompleteness"]["symbols"]
230 if x["name"].startswith(modname)
231 }
232 else: # pragma: no cover
233 raise AssertionError()
234
235 # It's expected that the static set will contain more names than the
236 # runtime set:
237 # - static tools are sometimes sloppy and include deleted names
238 # - some symbols are platform-specific at runtime, but always show up in
239 # static analysis (e.g. in trio.socket or trio.lowlevel)
240 # So we check that the runtime names are a subset of the static names.
241 missing_names = runtime_names - static_names
242
243 # ignore warnings about deprecated module tests
244 missing_names -= {"tests"}
245
246 if missing_names: # pragma: no cover
247 print(f"{tool} can't see the following names in {modname}:")
248 print()
249 for name in sorted(missing_names):
250 print(f" {name}")
251 raise AssertionError()
252
253
254 @slow
255 # see comment on test_static_tool_sees_all_symbols
256 @pytest.mark.redistributors_should_skip
257 # Static analysis tools often have trouble with alpha releases, where Python's
258 # internals are in flux, grammar may not have settled down, etc.
259 @pytest.mark.skipif(
260 sys.version_info.releaselevel == "alpha",
261 reason="skip static introspection tools on Python dev/alpha releases",
262 )
263 @pytest.mark.parametrize("module_name", PUBLIC_MODULE_NAMES)
264 @pytest.mark.parametrize("tool", ["jedi", "mypy"])
265 def test_static_tool_sees_class_members(
266 tool: str,
267 module_name: str,
268 tmp_path: Path,
269 ) -> None:
270 module = PUBLIC_MODULES[PUBLIC_MODULE_NAMES.index(module_name)]
271
272 # ignore hidden, but not dunder, symbols
273 def no_hidden(symbols: Iterable[str]) -> set[str]:
274 return {
275 symbol
276 for symbol in symbols
277 if (not symbol.startswith("_")) or symbol.startswith("__")
278 }
279
280 if tool == "jedi" and sys.implementation.name != "cpython":
281 pytest.skip("jedi does not support pypy")
282
283 if tool == "mypy" and sys.implementation.name != "cpython":
284 # https://github.com/python/mypy/issues/20329
285 pytest.skip("mypy does not support pypy")
286
287 if tool == "mypy":
288 cache = Path.cwd() / ".mypy_cache"
289
290 _ensure_mypy_cache_updated()
291
292 trio_cache = next(cache.glob("*/trio"))
293 modname = module_name
294 _, modname = (modname + ".").split(".", 1)
295 modname = modname[:-1]
296 mod_cache = trio_cache / modname if modname else trio_cache
297 if mod_cache.is_dir():
298 mod_cache = mod_cache / "__init__.data.json"
299 else:
300 mod_cache = trio_cache / (modname + ".data.json")
301
302 assert mod_cache.exists()
303 assert mod_cache.is_file()
304 with mod_cache.open() as cache_file:
305 cache_json = json.loads(cache_file.read())
306
307 # skip a bunch of file-system activity (probably can un-memoize?)
308 @functools.lru_cache
309 def lookup_symbol(symbol: str) -> dict[str, Any]: # type: ignore[misc, explicit-any]
310 topname, *modname, name = symbol.split(".")
311 version = next(cache.glob("3.*/"))
312 mod_cache = version / topname
313 if not mod_cache.is_dir():
314 mod_cache = version / (topname + ".data.json")
315
316 if modname:
317 for piece in modname[:-1]:
318 mod_cache /= piece
319 next_cache = mod_cache / modname[-1]
320 if next_cache.is_dir(): # pragma: no coverage
321 mod_cache = next_cache / "__init__.data.json"
322 else:
323 mod_cache = mod_cache / (modname[-1] + ".data.json")
324 elif mod_cache.is_dir():
325 mod_cache /= "__init__.data.json"
326 with mod_cache.open() as f:
327 return json.loads(f.read())["names"][name] # type: ignore[no-any-return]
328
329 errors: dict[str, object] = {}
330 for class_name, class_ in module.__dict__.items():
331 if not isinstance(class_, type):
332 continue
333 if module_name == "trio.socket" and class_name in dir(stdlib_socket):
334 continue
335
336 # Ignore classes that don't use attrs, they only define their members once
337 # __init__ is called (and reason they don't use attrs is because they're going
338 # to be reimplemented in pytest).
339 # Not 100% that's the case, and it works locally, so whatever /shrug
340 if module_name == "trio.testing" and class_name in ("_RaisesGroup", "_Matcher"):
341 continue
342
343 # dir() and inspect.getmembers doesn't display properties from the metaclass
344 # also ignore some dunder methods that tend to differ but are of no consequence
345 ignore_names = set(dir(type(class_))) | {
346 "__annotations__",
347 "__attrs_attrs__",
348 "__attrs_own_setattr__",
349 "__callable_proto_members_only__",
350 "__class_getitem__",
351 "__final__",
352 "__getstate__",
353 "__match_args__",
354 "__order__",
355 "__orig_bases__",
356 "__parameters__",
357 "__protocol_attrs__",
358 "__setstate__",
359 "__slots__",
360 "__weakref__",
361 # ignore errors about dunders inherited from stdlib that tools might
362 # not see
363 "__copy__",
364 "__deepcopy__",
365 }
366
367 if type(class_) is type:
368 # C extension classes don't have these dunders, but Python classes do
369 ignore_names.add("__firstlineno__")
370 ignore_names.add("__static_attributes__")
371
372 # inspect.getmembers sees `name` and `value` in Enums, otherwise
373 # it behaves the same way as `dir`
374 # runtime_names = no_underscores(dir(class_))
375 runtime_names = (
376 no_hidden(x[0] for x in inspect.getmembers(class_)) - ignore_names
377 )
378
379 if tool == "jedi":
380 try:
381 import jedi
382 except ImportError as error:
383 skip_if_optional_else_raise(error)
384
385 script = jedi.Script(
386 f"from {module_name} import {class_name}; {class_name}.",
387 )
388 completions = script.complete()
389 static_names = no_hidden(c.name for c in completions) - ignore_names
390
391 elif tool == "mypy":
392 # load the cached type information
393 cached_type_info = cache_json["names"][class_name]
394 assert (
395 "node" not in cached_type_info
396 ), "previously this was an 'if' but it seems it's no longer possible for this cache to contain 'node', if this assert raises for you please let us know!"
397 cached_type_info = lookup_symbol(cached_type_info["cross_ref"])
398
399 assert "node" in cached_type_info
400 node = cached_type_info["node"]
401 static_names = no_hidden(
402 k for k in node.get("names", ()) if not k.startswith(".")
403 )
404 for symbol in node["mro"][1:]:
405 node = lookup_symbol(symbol)["node"]
406 static_names |= no_hidden(
407 k for k in node.get("names", ()) if not k.startswith(".")
408 )
409 static_names -= ignore_names
410
411 else: # pragma: no cover
412 raise AssertionError("unknown tool")
413
414 missing = runtime_names - static_names
415 extra = static_names - runtime_names
416
417 # using .remove() instead of .delete() to get an error in case they start not
418 # being missing
419
420 if BaseException in class_.__mro__ and sys.version_info >= (3, 11):
421 extra.remove("__notes__")
422
423 if tool == "mypy" and attrs.has(class_):
424 # e.g. __trio__core__run_CancelScope_AttrsAttributes__
425 before = len(extra)
426 extra = {e for e in extra if not e.endswith("AttrsAttributes__")}
427 assert len(extra) == before - 1
428
429 if (
430 tool == "jedi"
431 and issubclass(class_, trio.Path)
432 and sys.version_info >= (3, 15)
433 ):
434 # needs a typeshed update for https://github.com/python/typeshed/pull/15737
435 extra.remove("is_reserved")
436
437 if attrs.has(class_):
438 # dynamically created attribute by attrs?
439 missing.remove("__attrs_props__")
440
441 # dir does not see `__signature__` on enums until 3.14
442 if (
443 enum.Enum in class_.__mro__
444 and sys.version_info >= (3, 12)
445 and sys.version_info < (3, 14)
446 ):
447 extra.remove("__signature__")
448
449 # TODO: this *should* be visible via `dir`!!
450 if tool == "mypy" and class_ == trio.Nursery:
451 extra.remove("cancel_scope")
452
453 # These are (mostly? solely?) *runtime* attributes, often set in
454 # __init__, which doesn't show up with dir() or inspect.getmembers,
455 # but we get them in the way we query mypy & jedi
456 EXTRAS = {
457 trio.DTLSChannel: {"peer_address", "endpoint"},
458 trio.DTLSEndpoint: {"socket", "incoming_packets_buffer"},
459 trio.Process: {"args", "pid", "stderr", "stdin", "stdio", "stdout"},
460 trio.SSLListener: {"transport_listener"},
461 trio.SSLStream: {"transport_stream"},
462 trio.SocketListener: {"socket"},
463 trio.SocketStream: {"socket"},
464 trio.testing.MemoryReceiveStream: {"close_hook", "receive_some_hook"},
465 trio.testing.MemorySendStream: {
466 "close_hook",
467 "send_all_hook",
468 "wait_send_all_might_not_block_hook",
469 },
470 }
471 if tool == "mypy" and class_ in EXTRAS:
472 before = len(extra)
473 extra -= EXTRAS[class_]
474 assert len(extra) == before - len(EXTRAS[class_])
475
476 # TODO: why is this? Is it a problem?
477 # see https://github.com/python-trio/trio/pull/2631#discussion_r1185615916
478 if class_ == trio.StapledStream:
479 extra.remove("receive_stream")
480 extra.remove("send_stream")
481
482 # I have not researched why these are missing, should maybe create an issue
483 # upstream with jedi
484 if tool == "jedi" and sys.version_info >= (3, 11):
485 if class_ in (
486 trio.DTLSChannel,
487 trio.MemoryReceiveChannel,
488 trio.MemorySendChannel,
489 trio.SSLListener,
490 trio.SocketListener,
491 ):
492 missing.remove("__aenter__")
493 missing.remove("__aexit__")
494 if class_ in (trio.DTLSChannel, trio.MemoryReceiveChannel):
495 missing.remove("__aiter__")
496 missing.remove("__anext__")
497
498 if class_ in (trio.Path, trio.WindowsPath, trio.PosixPath):
499 # These are from inherited subclasses.
500 missing -= PurePath.__dict__.keys()
501 # These are unix-only.
502 if tool == "mypy" and sys.platform == "win32":
503 missing -= {"owner", "is_mount", "group"}
504 if tool == "jedi" and sys.platform == "win32":
505 extra -= {"owner", "is_mount", "group"}
506
507 # tuple subclasses are weird
508 if tool == "mypy" and issubclass(class_, tuple):
509 extra.remove("__reversed__")
510 missing.remove("__getnewargs__")
511
512 if sys.version_info >= (3, 13) and attrs.has(class_):
513 missing.remove("__replace__")
514
515 if sys.version_info >= (3, 14):
516 # these depend on whether a class has processed deferred annotations.
517 # (which might or might not happen and we don't know)
518 missing.discard("__annotate_func__")
519 missing.discard("__annotations_cache__")
520
521 if tool == "jedi" and class_ == trio.open_memory_channel:
522 # something is seriously wrong with jedi's understanding of open_memory_channel...
523 for attrib in (
524 "__add__",
525 "__contains__",
526 "__getitem__",
527 "__getnewargs__",
528 "__iter__",
529 "__len__",
530 "__mul__",
531 "__rmul__",
532 "count",
533 "index",
534 ):
535 missing.remove(attrib)
536
537 if missing or extra: # pragma: no cover
538 errors[f"{module_name}.{class_name}"] = {
539 "missing": missing,
540 "extra": extra,
541 }
542
543 # `assert not errors` will not print the full content of errors, even with
544 # `--verbose`, so we manually print it
545 if errors: # pragma: no cover
546 from pprint import pprint
547
548 print(f"\n{tool} can't see the following symbols in {module_name}:")
549 pprint(errors)
550 assert not errors
551
552
553 def test_nopublic_is_final() -> None:
554 """Check all NoPublicConstructor classes are also @final."""
555 assert class_is_final(_util.NoPublicConstructor) # This is itself final.
556
557 for module in ALL_MODULES:
558 for class_ in module.__dict__.values():
559 if isinstance(class_, _util.NoPublicConstructor):
560 assert class_is_final(class_)
561
562
563 def test_classes_are_final() -> None:
564 # Sanity checks.
565 assert not class_is_final(object)
566 assert class_is_final(bool)
567
568 for module in PUBLIC_MODULES:
569 for name, class_ in module.__dict__.items():
570 if not isinstance(class_, type):
571 continue
572 # Deprecated classes are exported with a leading underscore
573 if name.startswith("_"): # pragma: no cover
574 continue
575
576 # Abstract classes can be subclassed, because that's the whole
577 # point of ABCs
578 if inspect.isabstract(class_):
579 continue
580 # Same with protocols, but only direct children.
581 if Protocol in class_.__bases__ or Protocol_ext in class_.__bases__:
582 continue
583 # Exceptions are allowed to be subclassed, because exception
584 # subclassing isn't used to inherit behavior.
585 if issubclass(class_, BaseException):
586 continue
587 # These are classes that are conceptually abstract, but
588 # inspect.isabstract returns False for boring reasons.
589 if class_ is trio.abc.Instrument or class_ is trio.socket.SocketType:
590 continue
591 # ... insert other special cases here ...
592
593 # The `Path` class needs to support inheritance to allow `WindowsPath` and `PosixPath`.
594 if class_ is trio.Path:
595 continue
596 # don't care about the *Statistics classes
597 if name.endswith("Statistics"):
598 continue
599
600 assert class_is_final(class_)
601
602
603 # Plugin might not be running, especially if running from an installed version.
604 @pytest.mark.skipif(
605 not hasattr(attrs.field, "trio_modded"),
606 reason="Pytest plugin not installed.",
607 )
608 def test_pyright_recognizes_init_attributes() -> None:
609 """Check whether we provide `alias` for all underscore prefixed attributes.
610
611 Attrs always sets the `alias` attribute on fields, so a pytest plugin is used
612 to monkeypatch `field()` to record whether an alias was defined in the metadata.
613 See `_trio_check_attrs_aliases`.
614 """
615 for module in PUBLIC_MODULES:
616 for class_ in module.__dict__.values():
617 if not attrs.has(class_):
618 continue
619 if isinstance(class_, _util.NoPublicConstructor):
620 continue
621
622 attributes = [
623 attr
624 for attr in attrs.fields(class_)
625 if attr.init
626 if attr.alias
627 not in (
628 attr.name,
629 # trio_original_args may not be present in autoattribs
630 attr.metadata.get("trio_original_args", {}).get("alias"),
631 )
632 ]
633
634 assert attributes == [], class_