stubtest.py 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891
  1. """Tests for stubs.
  2. Verify that various things in stubs are consistent with how things behave at runtime.
  3. """
  4. from __future__ import annotations
  5. import argparse
  6. import collections.abc
  7. import copy
  8. import enum
  9. import importlib
  10. import inspect
  11. import os
  12. import pkgutil
  13. import re
  14. import symtable
  15. import sys
  16. import traceback
  17. import types
  18. import typing
  19. import typing_extensions
  20. import warnings
  21. from contextlib import redirect_stderr, redirect_stdout
  22. from functools import singledispatch
  23. from pathlib import Path
  24. from typing import Any, Generic, Iterator, TypeVar, Union
  25. from typing_extensions import get_origin, is_typeddict
  26. import mypy.build
  27. import mypy.modulefinder
  28. import mypy.nodes
  29. import mypy.state
  30. import mypy.types
  31. import mypy.version
  32. from mypy import nodes
  33. from mypy.config_parser import parse_config_file
  34. from mypy.evalexpr import UNKNOWN, evaluate_expression
  35. from mypy.options import Options
  36. from mypy.util import FancyFormatter, bytes_to_human_readable_repr, is_dunder, plural_s
  37. class Missing:
  38. """Marker object for things that are missing (from a stub or the runtime)."""
  39. def __repr__(self) -> str:
  40. return "MISSING"
  41. MISSING: typing_extensions.Final = Missing()
  42. T = TypeVar("T")
  43. MaybeMissing: typing_extensions.TypeAlias = Union[T, Missing]
  44. _formatter: typing_extensions.Final = FancyFormatter(sys.stdout, sys.stderr, False)
  45. def _style(message: str, **kwargs: Any) -> str:
  46. """Wrapper around mypy.util for fancy formatting."""
  47. kwargs.setdefault("color", "none")
  48. return _formatter.style(message, **kwargs)
  49. def _truncate(message: str, length: int) -> str:
  50. if len(message) > length:
  51. return message[: length - 3] + "..."
  52. return message
  53. class StubtestFailure(Exception):
  54. pass
  55. class Error:
  56. def __init__(
  57. self,
  58. object_path: list[str],
  59. message: str,
  60. stub_object: MaybeMissing[nodes.Node],
  61. runtime_object: MaybeMissing[Any],
  62. *,
  63. stub_desc: str | None = None,
  64. runtime_desc: str | None = None,
  65. ) -> None:
  66. """Represents an error found by stubtest.
  67. :param object_path: Location of the object with the error,
  68. e.g. ``["module", "Class", "method"]``
  69. :param message: Error message
  70. :param stub_object: The mypy node representing the stub
  71. :param runtime_object: Actual object obtained from the runtime
  72. :param stub_desc: Specialised description for the stub object, should you wish
  73. :param runtime_desc: Specialised description for the runtime object, should you wish
  74. """
  75. self.object_path = object_path
  76. self.object_desc = ".".join(object_path)
  77. self.message = message
  78. self.stub_object = stub_object
  79. self.runtime_object = runtime_object
  80. self.stub_desc = stub_desc or str(getattr(stub_object, "type", stub_object))
  81. self.runtime_desc = runtime_desc or _truncate(repr(runtime_object), 100)
  82. def is_missing_stub(self) -> bool:
  83. """Whether or not the error is for something missing from the stub."""
  84. return isinstance(self.stub_object, Missing)
  85. def is_positional_only_related(self) -> bool:
  86. """Whether or not the error is for something being (or not being) positional-only."""
  87. # TODO: This is hacky, use error codes or something more resilient
  88. return "leading double underscore" in self.message
  89. def get_description(self, concise: bool = False) -> str:
  90. """Returns a description of the error.
  91. :param concise: Whether to return a concise, one-line description
  92. """
  93. if concise:
  94. return _style(self.object_desc, bold=True) + " " + self.message
  95. stub_line = None
  96. stub_file = None
  97. if not isinstance(self.stub_object, Missing):
  98. stub_line = self.stub_object.line
  99. stub_node = get_stub(self.object_path[0])
  100. if stub_node is not None:
  101. stub_file = stub_node.path or None
  102. stub_loc_str = ""
  103. if stub_file:
  104. stub_loc_str += f" in file {Path(stub_file)}"
  105. if stub_line:
  106. stub_loc_str += f"{':' if stub_file else ' at line '}{stub_line}"
  107. runtime_line = None
  108. runtime_file = None
  109. if not isinstance(self.runtime_object, Missing):
  110. try:
  111. runtime_line = inspect.getsourcelines(self.runtime_object)[1]
  112. except (OSError, TypeError, SyntaxError):
  113. pass
  114. try:
  115. runtime_file = inspect.getsourcefile(self.runtime_object)
  116. except TypeError:
  117. pass
  118. runtime_loc_str = ""
  119. if runtime_file:
  120. runtime_loc_str += f" in file {Path(runtime_file)}"
  121. if runtime_line:
  122. runtime_loc_str += f"{':' if runtime_file else ' at line '}{runtime_line}"
  123. output = [
  124. _style("error: ", color="red", bold=True),
  125. _style(self.object_desc, bold=True),
  126. " ",
  127. self.message,
  128. "\n",
  129. "Stub:",
  130. _style(stub_loc_str, dim=True),
  131. "\n",
  132. _style(self.stub_desc + "\n", color="blue", dim=True),
  133. "Runtime:",
  134. _style(runtime_loc_str, dim=True),
  135. "\n",
  136. _style(self.runtime_desc + "\n", color="blue", dim=True),
  137. ]
  138. return "".join(output)
  139. # ====================
  140. # Core logic
  141. # ====================
  142. def silent_import_module(module_name: str) -> types.ModuleType:
  143. with open(os.devnull, "w") as devnull:
  144. with warnings.catch_warnings(), redirect_stdout(devnull), redirect_stderr(devnull):
  145. warnings.simplefilter("ignore")
  146. runtime = importlib.import_module(module_name)
  147. # Also run the equivalent of `from module import *`
  148. # This could have the additional effect of loading not-yet-loaded submodules
  149. # mentioned in __all__
  150. __import__(module_name, fromlist=["*"])
  151. return runtime
  152. def test_module(module_name: str) -> Iterator[Error]:
  153. """Tests a given module's stub against introspecting it at runtime.
  154. Requires the stub to have been built already, accomplished by a call to ``build_stubs``.
  155. :param module_name: The module to test
  156. """
  157. stub = get_stub(module_name)
  158. if stub is None:
  159. if not is_probably_private(module_name.split(".")[-1]):
  160. runtime_desc = repr(sys.modules[module_name]) if module_name in sys.modules else "N/A"
  161. yield Error(
  162. [module_name], "failed to find stubs", MISSING, None, runtime_desc=runtime_desc
  163. )
  164. return
  165. try:
  166. runtime = silent_import_module(module_name)
  167. except KeyboardInterrupt:
  168. raise
  169. except BaseException as e:
  170. note = ""
  171. if isinstance(e, ModuleNotFoundError):
  172. note = " Maybe install the runtime package or alter PYTHONPATH?"
  173. yield Error(
  174. [module_name], f"failed to import.{note} {type(e).__name__}: {e}", stub, MISSING
  175. )
  176. return
  177. with warnings.catch_warnings():
  178. warnings.simplefilter("ignore")
  179. try:
  180. yield from verify(stub, runtime, [module_name])
  181. except Exception as e:
  182. bottom_frame = list(traceback.walk_tb(e.__traceback__))[-1][0]
  183. bottom_module = bottom_frame.f_globals.get("__name__", "")
  184. # Pass on any errors originating from stubtest or mypy
  185. # These can occur expectedly, e.g. StubtestFailure
  186. if bottom_module == "__main__" or bottom_module.split(".")[0] == "mypy":
  187. raise
  188. yield Error(
  189. [module_name],
  190. f"encountered unexpected error, {type(e).__name__}: {e}",
  191. stub,
  192. runtime,
  193. stub_desc="N/A",
  194. runtime_desc=(
  195. "This is most likely the fault of something very dynamic in your library. "
  196. "It's also possible this is a bug in stubtest.\nIf in doubt, please "
  197. "open an issue at https://github.com/python/mypy\n\n"
  198. + traceback.format_exc().strip()
  199. ),
  200. )
  201. @singledispatch
  202. def verify(
  203. stub: MaybeMissing[nodes.Node], runtime: MaybeMissing[Any], object_path: list[str]
  204. ) -> Iterator[Error]:
  205. """Entry point for comparing a stub to a runtime object.
  206. We use single dispatch based on the type of ``stub``.
  207. :param stub: The mypy node representing a part of the stub
  208. :param runtime: The runtime object corresponding to ``stub``
  209. """
  210. yield Error(object_path, "is an unknown mypy node", stub, runtime)
  211. def _verify_exported_names(
  212. object_path: list[str], stub: nodes.MypyFile, runtime_all_as_set: set[str]
  213. ) -> Iterator[Error]:
  214. # note that this includes the case the stub simply defines `__all__: list[str]`
  215. assert "__all__" in stub.names
  216. public_names_in_stub = {m for m, o in stub.names.items() if o.module_public}
  217. names_in_stub_not_runtime = sorted(public_names_in_stub - runtime_all_as_set)
  218. names_in_runtime_not_stub = sorted(runtime_all_as_set - public_names_in_stub)
  219. if not (names_in_runtime_not_stub or names_in_stub_not_runtime):
  220. return
  221. yield Error(
  222. object_path + ["__all__"],
  223. (
  224. "names exported from the stub do not correspond to the names exported at runtime. "
  225. "This is probably due to things being missing from the stub or an inaccurate `__all__` in the stub"
  226. ),
  227. # Pass in MISSING instead of the stub and runtime objects, as the line numbers aren't very
  228. # relevant here, and it makes for a prettier error message
  229. # This means this error will be ignored when using `--ignore-missing-stub`, which is
  230. # desirable in at least the `names_in_runtime_not_stub` case
  231. stub_object=MISSING,
  232. runtime_object=MISSING,
  233. stub_desc=(
  234. f"Names exported in the stub but not at runtime: " f"{names_in_stub_not_runtime}"
  235. ),
  236. runtime_desc=(
  237. f"Names exported at runtime but not in the stub: " f"{names_in_runtime_not_stub}"
  238. ),
  239. )
  240. def _get_imported_symbol_names(runtime: types.ModuleType) -> frozenset[str] | None:
  241. """Retrieve the names in the global namespace which are known to be imported.
  242. 1). Use inspect to retrieve the source code of the module
  243. 2). Use symtable to parse the source and retrieve names that are known to be imported
  244. from other modules.
  245. If either of the above steps fails, return `None`.
  246. Note that if a set of names is returned,
  247. it won't include names imported via `from foo import *` imports.
  248. """
  249. try:
  250. source = inspect.getsource(runtime)
  251. except (OSError, TypeError, SyntaxError):
  252. return None
  253. if not source.strip():
  254. # The source code for the module was an empty file,
  255. # no point in parsing it with symtable
  256. return frozenset()
  257. try:
  258. module_symtable = symtable.symtable(source, runtime.__name__, "exec")
  259. except SyntaxError:
  260. return None
  261. return frozenset(sym.get_name() for sym in module_symtable.get_symbols() if sym.is_imported())
  262. @verify.register(nodes.MypyFile)
  263. def verify_mypyfile(
  264. stub: nodes.MypyFile, runtime: MaybeMissing[types.ModuleType], object_path: list[str]
  265. ) -> Iterator[Error]:
  266. if isinstance(runtime, Missing):
  267. yield Error(object_path, "is not present at runtime", stub, runtime)
  268. return
  269. if not isinstance(runtime, types.ModuleType):
  270. yield Error(object_path, "is not a module", stub, runtime)
  271. return
  272. runtime_all_as_set: set[str] | None
  273. if hasattr(runtime, "__all__"):
  274. runtime_all_as_set = set(runtime.__all__)
  275. if "__all__" in stub.names:
  276. # Only verify the contents of the stub's __all__
  277. # if the stub actually defines __all__
  278. yield from _verify_exported_names(object_path, stub, runtime_all_as_set)
  279. else:
  280. runtime_all_as_set = None
  281. # Check things in the stub
  282. to_check = {
  283. m
  284. for m, o in stub.names.items()
  285. if not o.module_hidden and (not is_probably_private(m) or hasattr(runtime, m))
  286. }
  287. imported_symbols = _get_imported_symbol_names(runtime)
  288. def _belongs_to_runtime(r: types.ModuleType, attr: str) -> bool:
  289. """Heuristics to determine whether a name originates from another module."""
  290. obj = getattr(r, attr)
  291. if isinstance(obj, types.ModuleType):
  292. return False
  293. if callable(obj):
  294. # It's highly likely to be a class or a function if it's callable,
  295. # so the __module__ attribute will give a good indication of which module it comes from
  296. try:
  297. obj_mod = obj.__module__
  298. except Exception:
  299. pass
  300. else:
  301. if isinstance(obj_mod, str):
  302. return bool(obj_mod == r.__name__)
  303. if imported_symbols is not None:
  304. return attr not in imported_symbols
  305. return True
  306. runtime_public_contents = (
  307. runtime_all_as_set
  308. if runtime_all_as_set is not None
  309. else {
  310. m
  311. for m in dir(runtime)
  312. if not is_probably_private(m)
  313. # Filter out objects that originate from other modules (best effort). Note that in the
  314. # absence of __all__, we don't have a way to detect explicit / intentional re-exports
  315. # at runtime
  316. and _belongs_to_runtime(runtime, m)
  317. }
  318. )
  319. # Check all things declared in module's __all__, falling back to our best guess
  320. to_check.update(runtime_public_contents)
  321. to_check.difference_update(IGNORED_MODULE_DUNDERS)
  322. for entry in sorted(to_check):
  323. stub_entry = stub.names[entry].node if entry in stub.names else MISSING
  324. if isinstance(stub_entry, nodes.MypyFile):
  325. # Don't recursively check exported modules, since that leads to infinite recursion
  326. continue
  327. assert stub_entry is not None
  328. try:
  329. runtime_entry = getattr(runtime, entry, MISSING)
  330. except Exception:
  331. # Catch all exceptions in case the runtime raises an unexpected exception
  332. # from __getattr__ or similar.
  333. continue
  334. yield from verify(stub_entry, runtime_entry, object_path + [entry])
  335. def _verify_final(
  336. stub: nodes.TypeInfo, runtime: type[Any], object_path: list[str]
  337. ) -> Iterator[Error]:
  338. try:
  339. class SubClass(runtime): # type: ignore[misc]
  340. pass
  341. except TypeError:
  342. # Enum classes are implicitly @final
  343. if not stub.is_final and not issubclass(runtime, enum.Enum):
  344. yield Error(
  345. object_path,
  346. "cannot be subclassed at runtime, but isn't marked with @final in the stub",
  347. stub,
  348. runtime,
  349. stub_desc=repr(stub),
  350. )
  351. except Exception:
  352. # The class probably wants its subclasses to do something special.
  353. # Examples: ctypes.Array, ctypes._SimpleCData
  354. pass
  355. # Runtime class might be annotated with `@final`:
  356. try:
  357. runtime_final = getattr(runtime, "__final__", False)
  358. except Exception:
  359. runtime_final = False
  360. if runtime_final and not stub.is_final:
  361. yield Error(
  362. object_path,
  363. "has `__final__` attribute, but isn't marked with @final in the stub",
  364. stub,
  365. runtime,
  366. stub_desc=repr(stub),
  367. )
  368. def _verify_metaclass(
  369. stub: nodes.TypeInfo, runtime: type[Any], object_path: list[str], *, is_runtime_typeddict: bool
  370. ) -> Iterator[Error]:
  371. # We exclude protocols, because of how complex their implementation is in different versions of
  372. # python. Enums are also hard, as are runtime TypedDicts; ignoring.
  373. # TODO: check that metaclasses are identical?
  374. if not stub.is_protocol and not stub.is_enum and not is_runtime_typeddict:
  375. runtime_metaclass = type(runtime)
  376. if runtime_metaclass is not type and stub.metaclass_type is None:
  377. # This means that runtime has a custom metaclass, but a stub does not.
  378. yield Error(
  379. object_path,
  380. "is inconsistent, metaclass differs",
  381. stub,
  382. runtime,
  383. stub_desc="N/A",
  384. runtime_desc=f"{runtime_metaclass}",
  385. )
  386. elif (
  387. runtime_metaclass is type
  388. and stub.metaclass_type is not None
  389. # We ignore extra `ABCMeta` metaclass on stubs, this might be typing hack.
  390. # We also ignore `builtins.type` metaclass as an implementation detail in mypy.
  391. and not mypy.types.is_named_instance(
  392. stub.metaclass_type, ("abc.ABCMeta", "builtins.type")
  393. )
  394. ):
  395. # This means that our stub has a metaclass that is not present at runtime.
  396. yield Error(
  397. object_path,
  398. "metaclass mismatch",
  399. stub,
  400. runtime,
  401. stub_desc=f"{stub.metaclass_type.type.fullname}",
  402. runtime_desc="N/A",
  403. )
  404. @verify.register(nodes.TypeInfo)
  405. def verify_typeinfo(
  406. stub: nodes.TypeInfo, runtime: MaybeMissing[type[Any]], object_path: list[str]
  407. ) -> Iterator[Error]:
  408. if isinstance(runtime, Missing):
  409. yield Error(object_path, "is not present at runtime", stub, runtime, stub_desc=repr(stub))
  410. return
  411. if not isinstance(runtime, type):
  412. yield Error(object_path, "is not a type", stub, runtime, stub_desc=repr(stub))
  413. return
  414. yield from _verify_final(stub, runtime, object_path)
  415. is_runtime_typeddict = stub.typeddict_type is not None and is_typeddict(runtime)
  416. yield from _verify_metaclass(
  417. stub, runtime, object_path, is_runtime_typeddict=is_runtime_typeddict
  418. )
  419. # Check everything already defined on the stub class itself (i.e. not inherited)
  420. #
  421. # Filter out non-identifier names, as these are (hopefully always?) whacky/fictional things
  422. # (like __mypy-replace or __mypy-post_init, etc.) that don't exist at runtime,
  423. # and exist purely for internal mypy reasons
  424. to_check = {name for name in stub.names if name.isidentifier()}
  425. # Check all public things on the runtime class
  426. to_check.update(
  427. m for m in vars(runtime) if not is_probably_private(m) and m not in IGNORABLE_CLASS_DUNDERS
  428. )
  429. # Special-case the __init__ method for Protocols and the __new__ method for TypedDicts
  430. #
  431. # TODO: On Python <3.11, __init__ methods on Protocol classes
  432. # are silently discarded and replaced.
  433. # However, this is not the case on Python 3.11+.
  434. # Ideally, we'd figure out a good way of validating Protocol __init__ methods on 3.11+.
  435. if stub.is_protocol:
  436. to_check.discard("__init__")
  437. if is_runtime_typeddict:
  438. to_check.discard("__new__")
  439. for entry in sorted(to_check):
  440. mangled_entry = entry
  441. if entry.startswith("__") and not entry.endswith("__"):
  442. mangled_entry = f"_{stub.name.lstrip('_')}{entry}"
  443. stub_to_verify = next((t.names[entry].node for t in stub.mro if entry in t.names), MISSING)
  444. assert stub_to_verify is not None
  445. try:
  446. try:
  447. runtime_attr = getattr(runtime, mangled_entry)
  448. except AttributeError:
  449. runtime_attr = inspect.getattr_static(runtime, mangled_entry, MISSING)
  450. except Exception:
  451. # Catch all exceptions in case the runtime raises an unexpected exception
  452. # from __getattr__ or similar.
  453. continue
  454. # Do not error for an object missing from the stub
  455. # If the runtime object is a types.WrapperDescriptorType object
  456. # and has a non-special dunder name.
  457. # The vast majority of these are false positives.
  458. if not (
  459. isinstance(stub_to_verify, Missing)
  460. and isinstance(runtime_attr, types.WrapperDescriptorType)
  461. and is_dunder(mangled_entry, exclude_special=True)
  462. ):
  463. yield from verify(stub_to_verify, runtime_attr, object_path + [entry])
  464. def _static_lookup_runtime(object_path: list[str]) -> MaybeMissing[Any]:
  465. static_runtime = importlib.import_module(object_path[0])
  466. for entry in object_path[1:]:
  467. try:
  468. static_runtime = inspect.getattr_static(static_runtime, entry)
  469. except AttributeError:
  470. # This can happen with mangled names, ignore for now.
  471. # TODO: pass more information about ancestors of nodes/objects to verify, so we don't
  472. # have to do this hacky lookup. Would be useful in several places.
  473. return MISSING
  474. return static_runtime
  475. def _verify_static_class_methods(
  476. stub: nodes.FuncBase, runtime: Any, static_runtime: MaybeMissing[Any], object_path: list[str]
  477. ) -> Iterator[str]:
  478. if stub.name in ("__new__", "__init_subclass__", "__class_getitem__"):
  479. # Special cased by Python, so don't bother checking
  480. return
  481. if inspect.isbuiltin(runtime):
  482. # The isinstance checks don't work reliably for builtins, e.g. datetime.datetime.now, so do
  483. # something a little hacky that seems to work well
  484. probably_class_method = isinstance(getattr(runtime, "__self__", None), type)
  485. if probably_class_method and not stub.is_class:
  486. yield "runtime is a classmethod but stub is not"
  487. if not probably_class_method and stub.is_class:
  488. yield "stub is a classmethod but runtime is not"
  489. return
  490. if static_runtime is MISSING:
  491. return
  492. if isinstance(static_runtime, classmethod) and not stub.is_class:
  493. yield "runtime is a classmethod but stub is not"
  494. if not isinstance(static_runtime, classmethod) and stub.is_class:
  495. yield "stub is a classmethod but runtime is not"
  496. if isinstance(static_runtime, staticmethod) and not stub.is_static:
  497. yield "runtime is a staticmethod but stub is not"
  498. if not isinstance(static_runtime, staticmethod) and stub.is_static:
  499. yield "stub is a staticmethod but runtime is not"
  500. def _verify_arg_name(
  501. stub_arg: nodes.Argument, runtime_arg: inspect.Parameter, function_name: str
  502. ) -> Iterator[str]:
  503. """Checks whether argument names match."""
  504. # Ignore exact names for most dunder methods
  505. if is_dunder(function_name, exclude_special=True):
  506. return
  507. def strip_prefix(s: str, prefix: str) -> str:
  508. return s[len(prefix) :] if s.startswith(prefix) else s
  509. if strip_prefix(stub_arg.variable.name, "__") == runtime_arg.name:
  510. return
  511. def names_approx_match(a: str, b: str) -> bool:
  512. a = a.strip("_")
  513. b = b.strip("_")
  514. return a.startswith(b) or b.startswith(a) or len(a) == 1 or len(b) == 1
  515. # Be more permissive about names matching for positional-only arguments
  516. if runtime_arg.kind == inspect.Parameter.POSITIONAL_ONLY and names_approx_match(
  517. stub_arg.variable.name, runtime_arg.name
  518. ):
  519. return
  520. # This comes up with namedtuples, so ignore
  521. if stub_arg.variable.name == "_self":
  522. return
  523. yield (
  524. f'stub argument "{stub_arg.variable.name}" '
  525. f'differs from runtime argument "{runtime_arg.name}"'
  526. )
  527. def _verify_arg_default_value(
  528. stub_arg: nodes.Argument, runtime_arg: inspect.Parameter
  529. ) -> Iterator[str]:
  530. """Checks whether argument default values are compatible."""
  531. if runtime_arg.default != inspect.Parameter.empty:
  532. if stub_arg.kind.is_required():
  533. yield (
  534. f'runtime argument "{runtime_arg.name}" '
  535. "has a default value but stub argument does not"
  536. )
  537. else:
  538. runtime_type = get_mypy_type_of_runtime_value(runtime_arg.default)
  539. # Fallback to the type annotation type if var type is missing. The type annotation
  540. # is an UnboundType, but I don't know enough to know what the pros and cons here are.
  541. # UnboundTypes have ugly question marks following them, so default to var type.
  542. # Note we do this same fallback when constructing signatures in from_overloadedfuncdef
  543. stub_type = stub_arg.variable.type or stub_arg.type_annotation
  544. if isinstance(stub_type, mypy.types.TypeVarType):
  545. stub_type = stub_type.upper_bound
  546. if (
  547. runtime_type is not None
  548. and stub_type is not None
  549. # Avoid false positives for marker objects
  550. and type(runtime_arg.default) != object
  551. # And ellipsis
  552. and runtime_arg.default is not ...
  553. and not is_subtype_helper(runtime_type, stub_type)
  554. ):
  555. yield (
  556. f'runtime argument "{runtime_arg.name}" '
  557. f"has a default value of type {runtime_type}, "
  558. f"which is incompatible with stub argument type {stub_type}"
  559. )
  560. if stub_arg.initializer is not None:
  561. stub_default = evaluate_expression(stub_arg.initializer)
  562. if (
  563. stub_default is not UNKNOWN
  564. and stub_default is not ...
  565. and (
  566. stub_default != runtime_arg.default
  567. # We want the types to match exactly, e.g. in case the stub has
  568. # True and the runtime has 1 (or vice versa).
  569. or type(stub_default) is not type(runtime_arg.default) # noqa: E721
  570. )
  571. ):
  572. yield (
  573. f'runtime argument "{runtime_arg.name}" '
  574. f"has a default value of {runtime_arg.default!r}, "
  575. f"which is different from stub argument default {stub_default!r}"
  576. )
  577. else:
  578. if stub_arg.kind.is_optional():
  579. yield (
  580. f'stub argument "{stub_arg.variable.name}" has a default value '
  581. f"but runtime argument does not"
  582. )
  583. def maybe_strip_cls(name: str, args: list[nodes.Argument]) -> list[nodes.Argument]:
  584. if args and name in ("__init_subclass__", "__class_getitem__"):
  585. # These are implicitly classmethods. If the stub chooses not to have @classmethod, we
  586. # should remove the cls argument
  587. if args[0].variable.name == "cls":
  588. return args[1:]
  589. return args
  590. class Signature(Generic[T]):
  591. def __init__(self) -> None:
  592. self.pos: list[T] = []
  593. self.kwonly: dict[str, T] = {}
  594. self.varpos: T | None = None
  595. self.varkw: T | None = None
  596. def __str__(self) -> str:
  597. def get_name(arg: Any) -> str:
  598. if isinstance(arg, inspect.Parameter):
  599. return arg.name
  600. if isinstance(arg, nodes.Argument):
  601. return arg.variable.name
  602. raise AssertionError
  603. def get_type(arg: Any) -> str | None:
  604. if isinstance(arg, inspect.Parameter):
  605. return None
  606. if isinstance(arg, nodes.Argument):
  607. return str(arg.variable.type or arg.type_annotation)
  608. raise AssertionError
  609. def has_default(arg: Any) -> bool:
  610. if isinstance(arg, inspect.Parameter):
  611. return bool(arg.default != inspect.Parameter.empty)
  612. if isinstance(arg, nodes.Argument):
  613. return arg.kind.is_optional()
  614. raise AssertionError
  615. def get_desc(arg: Any) -> str:
  616. arg_type = get_type(arg)
  617. return (
  618. get_name(arg)
  619. + (f": {arg_type}" if arg_type else "")
  620. + (" = ..." if has_default(arg) else "")
  621. )
  622. kw_only = sorted(self.kwonly.values(), key=lambda a: (has_default(a), get_name(a)))
  623. ret = "def ("
  624. ret += ", ".join(
  625. [get_desc(arg) for arg in self.pos]
  626. + (["*" + get_name(self.varpos)] if self.varpos else (["*"] if self.kwonly else []))
  627. + [get_desc(arg) for arg in kw_only]
  628. + (["**" + get_name(self.varkw)] if self.varkw else [])
  629. )
  630. ret += ")"
  631. return ret
  632. @staticmethod
  633. def from_funcitem(stub: nodes.FuncItem) -> Signature[nodes.Argument]:
  634. stub_sig: Signature[nodes.Argument] = Signature()
  635. stub_args = maybe_strip_cls(stub.name, stub.arguments)
  636. for stub_arg in stub_args:
  637. if stub_arg.kind.is_positional():
  638. stub_sig.pos.append(stub_arg)
  639. elif stub_arg.kind.is_named():
  640. stub_sig.kwonly[stub_arg.variable.name] = stub_arg
  641. elif stub_arg.kind == nodes.ARG_STAR:
  642. stub_sig.varpos = stub_arg
  643. elif stub_arg.kind == nodes.ARG_STAR2:
  644. stub_sig.varkw = stub_arg
  645. else:
  646. raise AssertionError
  647. return stub_sig
  648. @staticmethod
  649. def from_inspect_signature(signature: inspect.Signature) -> Signature[inspect.Parameter]:
  650. runtime_sig: Signature[inspect.Parameter] = Signature()
  651. for runtime_arg in signature.parameters.values():
  652. if runtime_arg.kind in (
  653. inspect.Parameter.POSITIONAL_ONLY,
  654. inspect.Parameter.POSITIONAL_OR_KEYWORD,
  655. ):
  656. runtime_sig.pos.append(runtime_arg)
  657. elif runtime_arg.kind == inspect.Parameter.KEYWORD_ONLY:
  658. runtime_sig.kwonly[runtime_arg.name] = runtime_arg
  659. elif runtime_arg.kind == inspect.Parameter.VAR_POSITIONAL:
  660. runtime_sig.varpos = runtime_arg
  661. elif runtime_arg.kind == inspect.Parameter.VAR_KEYWORD:
  662. runtime_sig.varkw = runtime_arg
  663. else:
  664. raise AssertionError
  665. return runtime_sig
  666. @staticmethod
  667. def from_overloadedfuncdef(stub: nodes.OverloadedFuncDef) -> Signature[nodes.Argument]:
  668. """Returns a Signature from an OverloadedFuncDef.
  669. If life were simple, to verify_overloadedfuncdef, we'd just verify_funcitem for each of its
  670. items. Unfortunately, life isn't simple and overloads are pretty deceitful. So instead, we
  671. try and combine the overload's items into a single signature that is compatible with any
  672. lies it might try to tell.
  673. """
  674. # For most dunder methods, just assume all args are positional-only
  675. assume_positional_only = is_dunder(stub.name, exclude_special=True)
  676. all_args: dict[str, list[tuple[nodes.Argument, int]]] = {}
  677. for func in map(_resolve_funcitem_from_decorator, stub.items):
  678. assert func is not None
  679. args = maybe_strip_cls(stub.name, func.arguments)
  680. for index, arg in enumerate(args):
  681. # For positional-only args, we allow overloads to have different names for the same
  682. # argument. To accomplish this, we just make up a fake index-based name.
  683. name = (
  684. f"__{index}"
  685. if arg.variable.name.startswith("__") or assume_positional_only
  686. else arg.variable.name
  687. )
  688. all_args.setdefault(name, []).append((arg, index))
  689. def get_position(arg_name: str) -> int:
  690. # We just need this to return the positional args in the correct order.
  691. return max(index for _, index in all_args[arg_name])
  692. def get_type(arg_name: str) -> mypy.types.ProperType:
  693. with mypy.state.state.strict_optional_set(True):
  694. all_types = [
  695. arg.variable.type or arg.type_annotation for arg, _ in all_args[arg_name]
  696. ]
  697. return mypy.typeops.make_simplified_union([t for t in all_types if t])
  698. def get_kind(arg_name: str) -> nodes.ArgKind:
  699. kinds = {arg.kind for arg, _ in all_args[arg_name]}
  700. if nodes.ARG_STAR in kinds:
  701. return nodes.ARG_STAR
  702. if nodes.ARG_STAR2 in kinds:
  703. return nodes.ARG_STAR2
  704. # The logic here is based on two tenets:
  705. # 1) If an arg is ever optional (or unspecified), it is optional
  706. # 2) If an arg is ever positional, it is positional
  707. is_opt = (
  708. len(all_args[arg_name]) < len(stub.items)
  709. or nodes.ARG_OPT in kinds
  710. or nodes.ARG_NAMED_OPT in kinds
  711. )
  712. is_pos = nodes.ARG_OPT in kinds or nodes.ARG_POS in kinds
  713. if is_opt:
  714. return nodes.ARG_OPT if is_pos else nodes.ARG_NAMED_OPT
  715. return nodes.ARG_POS if is_pos else nodes.ARG_NAMED
  716. sig: Signature[nodes.Argument] = Signature()
  717. for arg_name in sorted(all_args, key=get_position):
  718. # example_arg_name gives us a real name (in case we had a fake index-based name)
  719. example_arg_name = all_args[arg_name][0][0].variable.name
  720. arg = nodes.Argument(
  721. nodes.Var(example_arg_name, get_type(arg_name)),
  722. type_annotation=None,
  723. initializer=None,
  724. kind=get_kind(arg_name),
  725. )
  726. if arg.kind.is_positional():
  727. sig.pos.append(arg)
  728. elif arg.kind.is_named():
  729. sig.kwonly[arg.variable.name] = arg
  730. elif arg.kind == nodes.ARG_STAR:
  731. sig.varpos = arg
  732. elif arg.kind == nodes.ARG_STAR2:
  733. sig.varkw = arg
  734. else:
  735. raise AssertionError
  736. return sig
  737. def _verify_signature(
  738. stub: Signature[nodes.Argument], runtime: Signature[inspect.Parameter], function_name: str
  739. ) -> Iterator[str]:
  740. # Check positional arguments match up
  741. for stub_arg, runtime_arg in zip(stub.pos, runtime.pos):
  742. yield from _verify_arg_name(stub_arg, runtime_arg, function_name)
  743. yield from _verify_arg_default_value(stub_arg, runtime_arg)
  744. if (
  745. runtime_arg.kind == inspect.Parameter.POSITIONAL_ONLY
  746. and not stub_arg.pos_only
  747. and not stub_arg.variable.name.startswith("__")
  748. and not stub_arg.variable.name.strip("_") == "self"
  749. and not is_dunder(function_name, exclude_special=True) # noisy for dunder methods
  750. ):
  751. yield (
  752. f'stub argument "{stub_arg.variable.name}" should be positional-only '
  753. f'(rename with a leading double underscore, i.e. "__{runtime_arg.name}")'
  754. )
  755. if (
  756. runtime_arg.kind != inspect.Parameter.POSITIONAL_ONLY
  757. and (stub_arg.pos_only or stub_arg.variable.name.startswith("__"))
  758. and not is_dunder(function_name, exclude_special=True) # noisy for dunder methods
  759. ):
  760. yield (
  761. f'stub argument "{stub_arg.variable.name}" should be positional or keyword '
  762. "(remove leading double underscore)"
  763. )
  764. # Check unmatched positional args
  765. if len(stub.pos) > len(runtime.pos):
  766. # There are cases where the stub exhaustively lists out the extra parameters the function
  767. # would take through *args. Hence, a) if runtime accepts *args, we don't check whether the
  768. # runtime has all of the stub's parameters, b) below, we don't enforce that the stub takes
  769. # *args, since runtime logic may prevent arbitrary arguments from actually being accepted.
  770. if runtime.varpos is None:
  771. for stub_arg in stub.pos[len(runtime.pos) :]:
  772. # If the variable is in runtime.kwonly, it's just mislabelled as not a
  773. # keyword-only argument
  774. if stub_arg.variable.name not in runtime.kwonly:
  775. yield f'runtime does not have argument "{stub_arg.variable.name}"'
  776. else:
  777. yield f'stub argument "{stub_arg.variable.name}" is not keyword-only'
  778. if stub.varpos is not None:
  779. yield f'runtime does not have *args argument "{stub.varpos.variable.name}"'
  780. elif len(stub.pos) < len(runtime.pos):
  781. for runtime_arg in runtime.pos[len(stub.pos) :]:
  782. if runtime_arg.name not in stub.kwonly:
  783. yield f'stub does not have argument "{runtime_arg.name}"'
  784. else:
  785. yield f'runtime argument "{runtime_arg.name}" is not keyword-only'
  786. # Checks involving *args
  787. if len(stub.pos) <= len(runtime.pos) or runtime.varpos is None:
  788. if stub.varpos is None and runtime.varpos is not None:
  789. yield f'stub does not have *args argument "{runtime.varpos.name}"'
  790. if stub.varpos is not None and runtime.varpos is None:
  791. yield f'runtime does not have *args argument "{stub.varpos.variable.name}"'
  792. # Check keyword-only args
  793. for arg in sorted(set(stub.kwonly) & set(runtime.kwonly)):
  794. stub_arg, runtime_arg = stub.kwonly[arg], runtime.kwonly[arg]
  795. yield from _verify_arg_name(stub_arg, runtime_arg, function_name)
  796. yield from _verify_arg_default_value(stub_arg, runtime_arg)
  797. # Check unmatched keyword-only args
  798. if runtime.varkw is None or not set(runtime.kwonly).issubset(set(stub.kwonly)):
  799. # There are cases where the stub exhaustively lists out the extra parameters the function
  800. # would take through **kwargs. Hence, a) if runtime accepts **kwargs (and the stub hasn't
  801. # exhaustively listed out params), we don't check whether the runtime has all of the stub's
  802. # parameters, b) below, we don't enforce that the stub takes **kwargs, since runtime logic
  803. # may prevent arbitrary keyword arguments from actually being accepted.
  804. for arg in sorted(set(stub.kwonly) - set(runtime.kwonly)):
  805. if arg in {runtime_arg.name for runtime_arg in runtime.pos}:
  806. # Don't report this if we've reported it before
  807. if arg not in {runtime_arg.name for runtime_arg in runtime.pos[len(stub.pos) :]}:
  808. yield f'runtime argument "{arg}" is not keyword-only'
  809. else:
  810. yield f'runtime does not have argument "{arg}"'
  811. for arg in sorted(set(runtime.kwonly) - set(stub.kwonly)):
  812. if arg in {stub_arg.variable.name for stub_arg in stub.pos}:
  813. # Don't report this if we've reported it before
  814. if not (
  815. runtime.varpos is None
  816. and arg in {stub_arg.variable.name for stub_arg in stub.pos[len(runtime.pos) :]}
  817. ):
  818. yield f'stub argument "{arg}" is not keyword-only'
  819. else:
  820. yield f'stub does not have argument "{arg}"'
  821. # Checks involving **kwargs
  822. if stub.varkw is None and runtime.varkw is not None:
  823. # As mentioned above, don't enforce that the stub takes **kwargs.
  824. # Also check against positional parameters, to avoid a nitpicky message when an argument
  825. # isn't marked as keyword-only
  826. stub_pos_names = {stub_arg.variable.name for stub_arg in stub.pos}
  827. # Ideally we'd do a strict subset check, but in practice the errors from that aren't useful
  828. if not set(runtime.kwonly).issubset(set(stub.kwonly) | stub_pos_names):
  829. yield f'stub does not have **kwargs argument "{runtime.varkw.name}"'
  830. if stub.varkw is not None and runtime.varkw is None:
  831. yield f'runtime does not have **kwargs argument "{stub.varkw.variable.name}"'
  832. @verify.register(nodes.FuncItem)
  833. def verify_funcitem(
  834. stub: nodes.FuncItem, runtime: MaybeMissing[Any], object_path: list[str]
  835. ) -> Iterator[Error]:
  836. if isinstance(runtime, Missing):
  837. yield Error(object_path, "is not present at runtime", stub, runtime)
  838. return
  839. if not is_probably_a_function(runtime):
  840. yield Error(object_path, "is not a function", stub, runtime)
  841. if not callable(runtime):
  842. return
  843. # Look the object up statically, to avoid binding by the descriptor protocol
  844. static_runtime = _static_lookup_runtime(object_path)
  845. if isinstance(stub, nodes.FuncDef):
  846. for error_text in _verify_abstract_status(stub, runtime):
  847. yield Error(object_path, error_text, stub, runtime)
  848. for error_text in _verify_final_method(stub, runtime, static_runtime):
  849. yield Error(object_path, error_text, stub, runtime)
  850. for message in _verify_static_class_methods(stub, runtime, static_runtime, object_path):
  851. yield Error(object_path, "is inconsistent, " + message, stub, runtime)
  852. signature = safe_inspect_signature(runtime)
  853. runtime_is_coroutine = inspect.iscoroutinefunction(runtime)
  854. if signature:
  855. stub_sig = Signature.from_funcitem(stub)
  856. runtime_sig = Signature.from_inspect_signature(signature)
  857. runtime_sig_desc = f'{"async " if runtime_is_coroutine else ""}def {signature}'
  858. stub_desc = str(stub_sig)
  859. else:
  860. runtime_sig_desc, stub_desc = None, None
  861. # Don't raise an error if the stub is a coroutine, but the runtime isn't.
  862. # That results in false positives.
  863. # See https://github.com/python/typeshed/issues/7344
  864. if runtime_is_coroutine and not stub.is_coroutine:
  865. yield Error(
  866. object_path,
  867. 'is an "async def" function at runtime, but not in the stub',
  868. stub,
  869. runtime,
  870. stub_desc=stub_desc,
  871. runtime_desc=runtime_sig_desc,
  872. )
  873. if not signature:
  874. return
  875. for message in _verify_signature(stub_sig, runtime_sig, function_name=stub.name):
  876. yield Error(
  877. object_path,
  878. "is inconsistent, " + message,
  879. stub,
  880. runtime,
  881. runtime_desc=runtime_sig_desc,
  882. )
  883. @verify.register(Missing)
  884. def verify_none(
  885. stub: Missing, runtime: MaybeMissing[Any], object_path: list[str]
  886. ) -> Iterator[Error]:
  887. yield Error(object_path, "is not present in stub", stub, runtime)
  888. @verify.register(nodes.Var)
  889. def verify_var(
  890. stub: nodes.Var, runtime: MaybeMissing[Any], object_path: list[str]
  891. ) -> Iterator[Error]:
  892. if isinstance(runtime, Missing):
  893. # Don't always yield an error here, because we often can't find instance variables
  894. if len(object_path) <= 2:
  895. yield Error(object_path, "is not present at runtime", stub, runtime)
  896. return
  897. if (
  898. stub.is_initialized_in_class
  899. and is_read_only_property(runtime)
  900. and (stub.is_settable_property or not stub.is_property)
  901. ):
  902. yield Error(object_path, "is read-only at runtime but not in the stub", stub, runtime)
  903. runtime_type = get_mypy_type_of_runtime_value(runtime)
  904. if (
  905. runtime_type is not None
  906. and stub.type is not None
  907. and not is_subtype_helper(runtime_type, stub.type)
  908. ):
  909. should_error = True
  910. # Avoid errors when defining enums, since runtime_type is the enum itself, but we'd
  911. # annotate it with the type of runtime.value
  912. if isinstance(runtime, enum.Enum):
  913. runtime_type = get_mypy_type_of_runtime_value(runtime.value)
  914. if runtime_type is not None and is_subtype_helper(runtime_type, stub.type):
  915. should_error = False
  916. if should_error:
  917. yield Error(
  918. object_path, f"variable differs from runtime type {runtime_type}", stub, runtime
  919. )
  920. @verify.register(nodes.OverloadedFuncDef)
  921. def verify_overloadedfuncdef(
  922. stub: nodes.OverloadedFuncDef, runtime: MaybeMissing[Any], object_path: list[str]
  923. ) -> Iterator[Error]:
  924. if isinstance(runtime, Missing):
  925. yield Error(object_path, "is not present at runtime", stub, runtime)
  926. return
  927. if stub.is_property:
  928. # Any property with a setter is represented as an OverloadedFuncDef
  929. if is_read_only_property(runtime):
  930. yield Error(object_path, "is read-only at runtime but not in the stub", stub, runtime)
  931. return
  932. if not is_probably_a_function(runtime):
  933. yield Error(object_path, "is not a function", stub, runtime)
  934. if not callable(runtime):
  935. return
  936. # mypy doesn't allow overloads where one overload is abstract but another isn't,
  937. # so it should be okay to just check whether the first overload is abstract or not.
  938. #
  939. # TODO: Mypy *does* allow properties where e.g. the getter is abstract but the setter is not;
  940. # and any property with a setter is represented as an OverloadedFuncDef internally;
  941. # not sure exactly what (if anything) we should do about that.
  942. first_part = stub.items[0]
  943. if isinstance(first_part, nodes.Decorator) and first_part.is_overload:
  944. for msg in _verify_abstract_status(first_part.func, runtime):
  945. yield Error(object_path, msg, stub, runtime)
  946. # Look the object up statically, to avoid binding by the descriptor protocol
  947. static_runtime = _static_lookup_runtime(object_path)
  948. for message in _verify_static_class_methods(stub, runtime, static_runtime, object_path):
  949. yield Error(object_path, "is inconsistent, " + message, stub, runtime)
  950. # TODO: Should call _verify_final_method here,
  951. # but overloaded final methods in stubs cause a stubtest crash: see #14950
  952. signature = safe_inspect_signature(runtime)
  953. if not signature:
  954. return
  955. stub_sig = Signature.from_overloadedfuncdef(stub)
  956. runtime_sig = Signature.from_inspect_signature(signature)
  957. for message in _verify_signature(stub_sig, runtime_sig, function_name=stub.name):
  958. # TODO: This is a little hacky, but the addition here is super useful
  959. if "has a default value of type" in message:
  960. message += (
  961. ". This is often caused by overloads failing to account for explicitly passing "
  962. "in the default value."
  963. )
  964. yield Error(
  965. object_path,
  966. "is inconsistent, " + message,
  967. stub,
  968. runtime,
  969. stub_desc=(str(stub.type)) + f"\nInferred signature: {stub_sig}",
  970. runtime_desc="def " + str(signature),
  971. )
  972. @verify.register(nodes.TypeVarExpr)
  973. def verify_typevarexpr(
  974. stub: nodes.TypeVarExpr, runtime: MaybeMissing[Any], object_path: list[str]
  975. ) -> Iterator[Error]:
  976. if isinstance(runtime, Missing):
  977. # We seem to insert these typevars into NamedTuple stubs, but they
  978. # don't exist at runtime. Just ignore!
  979. if stub.name == "_NT":
  980. return
  981. yield Error(object_path, "is not present at runtime", stub, runtime)
  982. return
  983. if not isinstance(runtime, TypeVar):
  984. yield Error(object_path, "is not a TypeVar", stub, runtime)
  985. return
  986. @verify.register(nodes.ParamSpecExpr)
  987. def verify_paramspecexpr(
  988. stub: nodes.ParamSpecExpr, runtime: MaybeMissing[Any], object_path: list[str]
  989. ) -> Iterator[Error]:
  990. if isinstance(runtime, Missing):
  991. yield Error(object_path, "is not present at runtime", stub, runtime)
  992. return
  993. maybe_paramspec_types = (
  994. getattr(typing, "ParamSpec", None),
  995. getattr(typing_extensions, "ParamSpec", None),
  996. )
  997. paramspec_types = tuple(t for t in maybe_paramspec_types if t is not None)
  998. if not paramspec_types or not isinstance(runtime, paramspec_types):
  999. yield Error(object_path, "is not a ParamSpec", stub, runtime)
  1000. return
  1001. def _verify_readonly_property(stub: nodes.Decorator, runtime: Any) -> Iterator[str]:
  1002. assert stub.func.is_property
  1003. if isinstance(runtime, property):
  1004. yield from _verify_final_method(stub.func, runtime.fget, MISSING)
  1005. return
  1006. if inspect.isdatadescriptor(runtime):
  1007. # It's enough like a property...
  1008. return
  1009. # Sometimes attributes pretend to be properties, for instance, to express that they
  1010. # are read only. So allowlist if runtime_type matches the return type of stub.
  1011. runtime_type = get_mypy_type_of_runtime_value(runtime)
  1012. func_type = (
  1013. stub.func.type.ret_type if isinstance(stub.func.type, mypy.types.CallableType) else None
  1014. )
  1015. if (
  1016. runtime_type is not None
  1017. and func_type is not None
  1018. and is_subtype_helper(runtime_type, func_type)
  1019. ):
  1020. return
  1021. yield "is inconsistent, cannot reconcile @property on stub with runtime object"
  1022. def _verify_abstract_status(stub: nodes.FuncDef, runtime: Any) -> Iterator[str]:
  1023. stub_abstract = stub.abstract_status == nodes.IS_ABSTRACT
  1024. runtime_abstract = getattr(runtime, "__isabstractmethod__", False)
  1025. # The opposite can exist: some implementations omit `@abstractmethod` decorators
  1026. if runtime_abstract and not stub_abstract:
  1027. item_type = "property" if stub.is_property else "method"
  1028. yield f"is inconsistent, runtime {item_type} is abstract but stub is not"
  1029. def _verify_final_method(
  1030. stub: nodes.FuncDef, runtime: Any, static_runtime: MaybeMissing[Any]
  1031. ) -> Iterator[str]:
  1032. if stub.is_final:
  1033. return
  1034. if getattr(runtime, "__final__", False) or (
  1035. static_runtime is not MISSING and getattr(static_runtime, "__final__", False)
  1036. ):
  1037. yield "is decorated with @final at runtime, but not in the stub"
  1038. def _resolve_funcitem_from_decorator(dec: nodes.OverloadPart) -> nodes.FuncItem | None:
  1039. """Returns a FuncItem that corresponds to the output of the decorator.
  1040. Returns None if we can't figure out what that would be. For convenience, this function also
  1041. accepts FuncItems.
  1042. """
  1043. if isinstance(dec, nodes.FuncItem):
  1044. return dec
  1045. if dec.func.is_property:
  1046. return None
  1047. def apply_decorator_to_funcitem(
  1048. decorator: nodes.Expression, func: nodes.FuncItem
  1049. ) -> nodes.FuncItem | None:
  1050. if not isinstance(decorator, nodes.RefExpr):
  1051. return None
  1052. if not decorator.fullname:
  1053. # Happens with namedtuple
  1054. return None
  1055. if (
  1056. decorator.fullname in ("builtins.staticmethod", "abc.abstractmethod")
  1057. or decorator.fullname in mypy.types.OVERLOAD_NAMES
  1058. ):
  1059. return func
  1060. if decorator.fullname == "builtins.classmethod":
  1061. if func.arguments[0].variable.name not in ("cls", "mcs", "metacls"):
  1062. raise StubtestFailure(
  1063. f"unexpected class argument name {func.arguments[0].variable.name!r} "
  1064. f"in {dec.fullname}"
  1065. )
  1066. # FuncItem is written so that copy.copy() actually works, even when compiled
  1067. ret = copy.copy(func)
  1068. # Remove the cls argument, since it's not present in inspect.signature of classmethods
  1069. ret.arguments = ret.arguments[1:]
  1070. return ret
  1071. # Just give up on any other decorators. After excluding properties, we don't run into
  1072. # anything else when running on typeshed's stdlib.
  1073. return None
  1074. func: nodes.FuncItem = dec.func
  1075. for decorator in dec.original_decorators:
  1076. resulting_func = apply_decorator_to_funcitem(decorator, func)
  1077. if resulting_func is None:
  1078. return None
  1079. func = resulting_func
  1080. return func
  1081. @verify.register(nodes.Decorator)
  1082. def verify_decorator(
  1083. stub: nodes.Decorator, runtime: MaybeMissing[Any], object_path: list[str]
  1084. ) -> Iterator[Error]:
  1085. if isinstance(runtime, Missing):
  1086. yield Error(object_path, "is not present at runtime", stub, runtime)
  1087. return
  1088. if stub.func.is_property:
  1089. for message in _verify_readonly_property(stub, runtime):
  1090. yield Error(object_path, message, stub, runtime)
  1091. for message in _verify_abstract_status(stub.func, runtime):
  1092. yield Error(object_path, message, stub, runtime)
  1093. return
  1094. func = _resolve_funcitem_from_decorator(stub)
  1095. if func is not None:
  1096. yield from verify(func, runtime, object_path)
  1097. @verify.register(nodes.TypeAlias)
  1098. def verify_typealias(
  1099. stub: nodes.TypeAlias, runtime: MaybeMissing[Any], object_path: list[str]
  1100. ) -> Iterator[Error]:
  1101. stub_target = mypy.types.get_proper_type(stub.target)
  1102. stub_desc = f"Type alias for {stub_target}"
  1103. if isinstance(runtime, Missing):
  1104. yield Error(object_path, "is not present at runtime", stub, runtime, stub_desc=stub_desc)
  1105. return
  1106. runtime_origin = get_origin(runtime) or runtime
  1107. if isinstance(stub_target, mypy.types.Instance):
  1108. if not isinstance(runtime_origin, type):
  1109. yield Error(
  1110. object_path,
  1111. "is inconsistent, runtime is not a type",
  1112. stub,
  1113. runtime,
  1114. stub_desc=stub_desc,
  1115. )
  1116. return
  1117. stub_origin = stub_target.type
  1118. # Do our best to figure out the fullname of the runtime object...
  1119. runtime_name: object
  1120. try:
  1121. runtime_name = runtime_origin.__qualname__
  1122. except AttributeError:
  1123. runtime_name = getattr(runtime_origin, "__name__", MISSING)
  1124. if isinstance(runtime_name, str):
  1125. runtime_module: object = getattr(runtime_origin, "__module__", MISSING)
  1126. if isinstance(runtime_module, str):
  1127. if runtime_module == "collections.abc" or (
  1128. runtime_module == "re" and runtime_name in {"Match", "Pattern"}
  1129. ):
  1130. runtime_module = "typing"
  1131. runtime_fullname = f"{runtime_module}.{runtime_name}"
  1132. if re.fullmatch(rf"_?{re.escape(stub_origin.fullname)}", runtime_fullname):
  1133. # Okay, we're probably fine.
  1134. return
  1135. # Okay, either we couldn't construct a fullname
  1136. # or the fullname of the stub didn't match the fullname of the runtime.
  1137. # Fallback to a full structural check of the runtime vis-a-vis the stub.
  1138. yield from verify(stub_origin, runtime_origin, object_path)
  1139. return
  1140. if isinstance(stub_target, mypy.types.UnionType):
  1141. # complain if runtime is not a Union or UnionType
  1142. if runtime_origin is not Union and (
  1143. not (sys.version_info >= (3, 10) and isinstance(runtime, types.UnionType))
  1144. ):
  1145. yield Error(object_path, "is not a Union", stub, runtime, stub_desc=str(stub_target))
  1146. # could check Union contents here...
  1147. return
  1148. if isinstance(stub_target, mypy.types.TupleType):
  1149. if tuple not in getattr(runtime_origin, "__mro__", ()):
  1150. yield Error(
  1151. object_path, "is not a subclass of tuple", stub, runtime, stub_desc=stub_desc
  1152. )
  1153. # could check Tuple contents here...
  1154. return
  1155. if isinstance(stub_target, mypy.types.CallableType):
  1156. if runtime_origin is not collections.abc.Callable:
  1157. yield Error(
  1158. object_path, "is not a type alias for Callable", stub, runtime, stub_desc=stub_desc
  1159. )
  1160. # could check Callable contents here...
  1161. return
  1162. if isinstance(stub_target, mypy.types.AnyType):
  1163. return
  1164. yield Error(object_path, "is not a recognised type alias", stub, runtime, stub_desc=stub_desc)
  1165. # ====================
  1166. # Helpers
  1167. # ====================
  1168. IGNORED_MODULE_DUNDERS: typing_extensions.Final = frozenset(
  1169. {
  1170. "__file__",
  1171. "__doc__",
  1172. "__name__",
  1173. "__builtins__",
  1174. "__package__",
  1175. "__cached__",
  1176. "__loader__",
  1177. "__spec__",
  1178. "__annotations__",
  1179. "__path__", # mypy adds __path__ to packages, but C packages don't have it
  1180. "__getattr__", # resulting behaviour might be typed explicitly
  1181. # Created by `warnings.warn`, does not make much sense to have in stubs:
  1182. "__warningregistry__",
  1183. # TODO: remove the following from this list
  1184. "__author__",
  1185. "__version__",
  1186. "__copyright__",
  1187. }
  1188. )
  1189. IGNORABLE_CLASS_DUNDERS: typing_extensions.Final = frozenset(
  1190. {
  1191. # Special attributes
  1192. "__dict__",
  1193. "__annotations__",
  1194. "__text_signature__",
  1195. "__weakref__",
  1196. "__del__", # Only ever called when an object is being deleted, who cares?
  1197. "__hash__",
  1198. "__getattr__", # resulting behaviour might be typed explicitly
  1199. "__setattr__", # defining this on a class can cause worse type checking
  1200. "__vectorcalloffset__", # undocumented implementation detail of the vectorcall protocol
  1201. # isinstance/issubclass hooks that type-checkers don't usually care about
  1202. "__instancecheck__",
  1203. "__subclasshook__",
  1204. "__subclasscheck__",
  1205. # python2 only magic methods:
  1206. "__cmp__",
  1207. "__nonzero__",
  1208. "__unicode__",
  1209. "__div__",
  1210. # cython methods
  1211. "__pyx_vtable__",
  1212. # Pickle methods
  1213. "__setstate__",
  1214. "__getstate__",
  1215. "__getnewargs__",
  1216. "__getinitargs__",
  1217. "__reduce_ex__",
  1218. "__reduce__",
  1219. # ctypes weirdness
  1220. "__ctype_be__",
  1221. "__ctype_le__",
  1222. "__ctypes_from_outparam__",
  1223. # mypy limitations
  1224. "__abstractmethods__", # Classes with metaclass=ABCMeta inherit this attribute
  1225. "__new_member__", # If an enum defines __new__, the method is renamed as __new_member__
  1226. "__dataclass_fields__", # Generated by dataclasses
  1227. "__dataclass_params__", # Generated by dataclasses
  1228. "__doc__", # mypy's semanal for namedtuples assumes this is str, not Optional[str]
  1229. # Added to all protocol classes on 3.12+ (or if using typing_extensions.Protocol)
  1230. "__protocol_attrs__",
  1231. "__callable_proto_members_only__",
  1232. # typing implementation details, consider removing some of these:
  1233. "__parameters__",
  1234. "__origin__",
  1235. "__args__",
  1236. "__orig_bases__",
  1237. "__final__", # Has a specialized check
  1238. # Consider removing __slots__?
  1239. "__slots__",
  1240. }
  1241. )
  1242. def is_probably_private(name: str) -> bool:
  1243. return name.startswith("_") and not is_dunder(name)
  1244. def is_probably_a_function(runtime: Any) -> bool:
  1245. return (
  1246. isinstance(runtime, (types.FunctionType, types.BuiltinFunctionType))
  1247. or isinstance(runtime, (types.MethodType, types.BuiltinMethodType))
  1248. or (inspect.ismethoddescriptor(runtime) and callable(runtime))
  1249. )
  1250. def is_read_only_property(runtime: object) -> bool:
  1251. return isinstance(runtime, property) and runtime.fset is None
  1252. def safe_inspect_signature(runtime: Any) -> inspect.Signature | None:
  1253. try:
  1254. return inspect.signature(runtime)
  1255. except Exception:
  1256. # inspect.signature throws ValueError all the time
  1257. # catch RuntimeError because of https://bugs.python.org/issue39504
  1258. # catch TypeError because of https://github.com/python/typeshed/pull/5762
  1259. # catch AttributeError because of inspect.signature(_curses.window.border)
  1260. return None
  1261. def is_subtype_helper(left: mypy.types.Type, right: mypy.types.Type) -> bool:
  1262. """Checks whether ``left`` is a subtype of ``right``."""
  1263. left = mypy.types.get_proper_type(left)
  1264. right = mypy.types.get_proper_type(right)
  1265. if (
  1266. isinstance(left, mypy.types.LiteralType)
  1267. and isinstance(left.value, int)
  1268. and left.value in (0, 1)
  1269. and mypy.types.is_named_instance(right, "builtins.bool")
  1270. ):
  1271. # Pretend Literal[0, 1] is a subtype of bool to avoid unhelpful errors.
  1272. return True
  1273. if isinstance(right, mypy.types.TypedDictType) and mypy.types.is_named_instance(
  1274. left, "builtins.dict"
  1275. ):
  1276. # Special case checks against TypedDicts
  1277. return True
  1278. with mypy.state.state.strict_optional_set(True):
  1279. return mypy.subtypes.is_subtype(left, right)
  1280. def get_mypy_type_of_runtime_value(runtime: Any) -> mypy.types.Type | None:
  1281. """Returns a mypy type object representing the type of ``runtime``.
  1282. Returns None if we can't find something that works.
  1283. """
  1284. if runtime is None:
  1285. return mypy.types.NoneType()
  1286. if isinstance(runtime, property):
  1287. # Give up on properties to avoid issues with things that are typed as attributes.
  1288. return None
  1289. def anytype() -> mypy.types.AnyType:
  1290. return mypy.types.AnyType(mypy.types.TypeOfAny.unannotated)
  1291. if isinstance(
  1292. runtime,
  1293. (types.FunctionType, types.BuiltinFunctionType, types.MethodType, types.BuiltinMethodType),
  1294. ):
  1295. builtins = get_stub("builtins")
  1296. assert builtins is not None
  1297. type_info = builtins.names["function"].node
  1298. assert isinstance(type_info, nodes.TypeInfo)
  1299. fallback = mypy.types.Instance(type_info, [anytype()])
  1300. signature = safe_inspect_signature(runtime)
  1301. if signature:
  1302. arg_types = []
  1303. arg_kinds = []
  1304. arg_names = []
  1305. for arg in signature.parameters.values():
  1306. arg_types.append(anytype())
  1307. arg_names.append(
  1308. None if arg.kind == inspect.Parameter.POSITIONAL_ONLY else arg.name
  1309. )
  1310. has_default = arg.default == inspect.Parameter.empty
  1311. if arg.kind == inspect.Parameter.POSITIONAL_ONLY:
  1312. arg_kinds.append(nodes.ARG_POS if has_default else nodes.ARG_OPT)
  1313. elif arg.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD:
  1314. arg_kinds.append(nodes.ARG_POS if has_default else nodes.ARG_OPT)
  1315. elif arg.kind == inspect.Parameter.KEYWORD_ONLY:
  1316. arg_kinds.append(nodes.ARG_NAMED if has_default else nodes.ARG_NAMED_OPT)
  1317. elif arg.kind == inspect.Parameter.VAR_POSITIONAL:
  1318. arg_kinds.append(nodes.ARG_STAR)
  1319. elif arg.kind == inspect.Parameter.VAR_KEYWORD:
  1320. arg_kinds.append(nodes.ARG_STAR2)
  1321. else:
  1322. raise AssertionError
  1323. else:
  1324. arg_types = [anytype(), anytype()]
  1325. arg_kinds = [nodes.ARG_STAR, nodes.ARG_STAR2]
  1326. arg_names = [None, None]
  1327. return mypy.types.CallableType(
  1328. arg_types,
  1329. arg_kinds,
  1330. arg_names,
  1331. ret_type=anytype(),
  1332. fallback=fallback,
  1333. is_ellipsis_args=True,
  1334. )
  1335. # Try and look up a stub for the runtime object
  1336. stub = get_stub(type(runtime).__module__)
  1337. if stub is None:
  1338. return None
  1339. type_name = type(runtime).__name__
  1340. if type_name not in stub.names:
  1341. return None
  1342. type_info = stub.names[type_name].node
  1343. if isinstance(type_info, nodes.Var):
  1344. return type_info.type
  1345. if not isinstance(type_info, nodes.TypeInfo):
  1346. return None
  1347. if isinstance(runtime, tuple):
  1348. # Special case tuples so we construct a valid mypy.types.TupleType
  1349. optional_items = [get_mypy_type_of_runtime_value(v) for v in runtime]
  1350. items = [(i if i is not None else anytype()) for i in optional_items]
  1351. fallback = mypy.types.Instance(type_info, [anytype()])
  1352. return mypy.types.TupleType(items, fallback)
  1353. fallback = mypy.types.Instance(type_info, [anytype() for _ in type_info.type_vars])
  1354. value: bool | int | str
  1355. if isinstance(runtime, bytes):
  1356. value = bytes_to_human_readable_repr(runtime)
  1357. elif isinstance(runtime, enum.Enum):
  1358. value = runtime.name
  1359. elif isinstance(runtime, (bool, int, str)):
  1360. value = runtime
  1361. else:
  1362. return fallback
  1363. return mypy.types.LiteralType(value=value, fallback=fallback)
  1364. # ====================
  1365. # Build and entrypoint
  1366. # ====================
  1367. _all_stubs: dict[str, nodes.MypyFile] = {}
  1368. def build_stubs(modules: list[str], options: Options, find_submodules: bool = False) -> list[str]:
  1369. """Uses mypy to construct stub objects for the given modules.
  1370. This sets global state that ``get_stub`` can access.
  1371. Returns all modules we might want to check. If ``find_submodules`` is False, this is equal
  1372. to ``modules``.
  1373. :param modules: List of modules to build stubs for.
  1374. :param options: Mypy options for finding and building stubs.
  1375. :param find_submodules: Whether to attempt to find submodules of the given modules as well.
  1376. """
  1377. data_dir = mypy.build.default_data_dir()
  1378. search_path = mypy.modulefinder.compute_search_paths([], options, data_dir)
  1379. find_module_cache = mypy.modulefinder.FindModuleCache(
  1380. search_path, fscache=None, options=options
  1381. )
  1382. all_modules = []
  1383. sources = []
  1384. for module in modules:
  1385. all_modules.append(module)
  1386. if not find_submodules:
  1387. module_path = find_module_cache.find_module(module)
  1388. if not isinstance(module_path, str):
  1389. # test_module will yield an error later when it can't find stubs
  1390. continue
  1391. sources.append(mypy.modulefinder.BuildSource(module_path, module, None))
  1392. else:
  1393. found_sources = find_module_cache.find_modules_recursive(module)
  1394. sources.extend(found_sources)
  1395. # find submodules via mypy
  1396. all_modules.extend(s.module for s in found_sources if s.module not in all_modules)
  1397. # find submodules via pkgutil
  1398. try:
  1399. runtime = silent_import_module(module)
  1400. all_modules.extend(
  1401. m.name
  1402. for m in pkgutil.walk_packages(runtime.__path__, runtime.__name__ + ".")
  1403. if m.name not in all_modules
  1404. )
  1405. except KeyboardInterrupt:
  1406. raise
  1407. except BaseException:
  1408. pass
  1409. if sources:
  1410. try:
  1411. res = mypy.build.build(sources=sources, options=options)
  1412. except mypy.errors.CompileError as e:
  1413. raise StubtestFailure(f"failed mypy compile:\n{e}") from e
  1414. if res.errors:
  1415. raise StubtestFailure("mypy build errors:\n" + "\n".join(res.errors))
  1416. global _all_stubs
  1417. _all_stubs = res.files
  1418. return all_modules
  1419. def get_stub(module: str) -> nodes.MypyFile | None:
  1420. """Returns a stub object for the given module, if we've built one."""
  1421. return _all_stubs.get(module)
  1422. def get_typeshed_stdlib_modules(
  1423. custom_typeshed_dir: str | None, version_info: tuple[int, int] | None = None
  1424. ) -> list[str]:
  1425. """Returns a list of stdlib modules in typeshed (for current Python version)."""
  1426. stdlib_py_versions = mypy.modulefinder.load_stdlib_py_versions(custom_typeshed_dir)
  1427. if version_info is None:
  1428. version_info = sys.version_info[0:2]
  1429. def exists_in_version(module: str) -> bool:
  1430. assert version_info is not None
  1431. parts = module.split(".")
  1432. for i in range(len(parts), 0, -1):
  1433. current_module = ".".join(parts[:i])
  1434. if current_module in stdlib_py_versions:
  1435. minver, maxver = stdlib_py_versions[current_module]
  1436. return version_info >= minver and (maxver is None or version_info <= maxver)
  1437. return False
  1438. if custom_typeshed_dir:
  1439. typeshed_dir = Path(custom_typeshed_dir)
  1440. else:
  1441. typeshed_dir = Path(mypy.build.default_data_dir()) / "typeshed"
  1442. stdlib_dir = typeshed_dir / "stdlib"
  1443. modules = []
  1444. for path in stdlib_dir.rglob("*.pyi"):
  1445. if path.stem == "__init__":
  1446. path = path.parent
  1447. module = ".".join(path.relative_to(stdlib_dir).parts[:-1] + (path.stem,))
  1448. if exists_in_version(module):
  1449. modules.append(module)
  1450. return sorted(modules)
  1451. def get_allowlist_entries(allowlist_file: str) -> Iterator[str]:
  1452. def strip_comments(s: str) -> str:
  1453. try:
  1454. return s[: s.index("#")].strip()
  1455. except ValueError:
  1456. return s.strip()
  1457. with open(allowlist_file) as f:
  1458. for line in f:
  1459. entry = strip_comments(line)
  1460. if entry:
  1461. yield entry
  1462. class _Arguments:
  1463. modules: list[str]
  1464. concise: bool
  1465. ignore_missing_stub: bool
  1466. ignore_positional_only: bool
  1467. allowlist: list[str]
  1468. generate_allowlist: bool
  1469. ignore_unused_allowlist: bool
  1470. mypy_config_file: str
  1471. custom_typeshed_dir: str
  1472. check_typeshed: bool
  1473. version: str
  1474. def test_stubs(args: _Arguments, use_builtins_fixtures: bool = False) -> int:
  1475. """This is stubtest! It's time to test the stubs!"""
  1476. # Load the allowlist. This is a series of strings corresponding to Error.object_desc
  1477. # Values in the dict will store whether we used the allowlist entry or not.
  1478. allowlist = {
  1479. entry: False
  1480. for allowlist_file in args.allowlist
  1481. for entry in get_allowlist_entries(allowlist_file)
  1482. }
  1483. allowlist_regexes = {entry: re.compile(entry) for entry in allowlist}
  1484. # If we need to generate an allowlist, we store Error.object_desc for each error here.
  1485. generated_allowlist = set()
  1486. modules = args.modules
  1487. if args.check_typeshed:
  1488. if args.modules:
  1489. print(
  1490. _style("error:", color="red", bold=True),
  1491. "cannot pass both --check-typeshed and a list of modules",
  1492. )
  1493. return 1
  1494. modules = get_typeshed_stdlib_modules(args.custom_typeshed_dir)
  1495. # typeshed added a stub for __main__, but that causes stubtest to check itself
  1496. annoying_modules = {"antigravity", "this", "__main__"}
  1497. modules = [m for m in modules if m not in annoying_modules]
  1498. if not modules:
  1499. print(_style("error:", color="red", bold=True), "no modules to check")
  1500. return 1
  1501. options = Options()
  1502. options.incremental = False
  1503. options.custom_typeshed_dir = args.custom_typeshed_dir
  1504. if options.custom_typeshed_dir:
  1505. options.abs_custom_typeshed_dir = os.path.abspath(args.custom_typeshed_dir)
  1506. options.config_file = args.mypy_config_file
  1507. options.use_builtins_fixtures = use_builtins_fixtures
  1508. if options.config_file:
  1509. def set_strict_flags() -> None: # not needed yet
  1510. return
  1511. parse_config_file(options, set_strict_flags, options.config_file, sys.stdout, sys.stderr)
  1512. try:
  1513. modules = build_stubs(modules, options, find_submodules=not args.check_typeshed)
  1514. except StubtestFailure as stubtest_failure:
  1515. print(
  1516. _style("error:", color="red", bold=True),
  1517. f"not checking stubs due to {stubtest_failure}",
  1518. )
  1519. return 1
  1520. exit_code = 0
  1521. error_count = 0
  1522. for module in modules:
  1523. for error in test_module(module):
  1524. # Filter errors
  1525. if args.ignore_missing_stub and error.is_missing_stub():
  1526. continue
  1527. if args.ignore_positional_only and error.is_positional_only_related():
  1528. continue
  1529. if error.object_desc in allowlist:
  1530. allowlist[error.object_desc] = True
  1531. continue
  1532. is_allowlisted = False
  1533. for w in allowlist:
  1534. if allowlist_regexes[w].fullmatch(error.object_desc):
  1535. allowlist[w] = True
  1536. is_allowlisted = True
  1537. break
  1538. if is_allowlisted:
  1539. continue
  1540. # We have errors, so change exit code, and output whatever necessary
  1541. exit_code = 1
  1542. if args.generate_allowlist:
  1543. generated_allowlist.add(error.object_desc)
  1544. continue
  1545. print(error.get_description(concise=args.concise))
  1546. error_count += 1
  1547. # Print unused allowlist entries
  1548. if not args.ignore_unused_allowlist:
  1549. for w in allowlist:
  1550. # Don't consider an entry unused if it regex-matches the empty string
  1551. # This lets us allowlist errors that don't manifest at all on some systems
  1552. if not allowlist[w] and not allowlist_regexes[w].fullmatch(""):
  1553. exit_code = 1
  1554. error_count += 1
  1555. print(f"note: unused allowlist entry {w}")
  1556. # Print the generated allowlist
  1557. if args.generate_allowlist:
  1558. for e in sorted(generated_allowlist):
  1559. print(e)
  1560. exit_code = 0
  1561. elif not args.concise:
  1562. if error_count:
  1563. print(
  1564. _style(
  1565. f"Found {error_count} error{plural_s(error_count)}"
  1566. f" (checked {len(modules)} module{plural_s(modules)})",
  1567. color="red",
  1568. bold=True,
  1569. )
  1570. )
  1571. else:
  1572. print(
  1573. _style(
  1574. f"Success: no issues found in {len(modules)} module{plural_s(modules)}",
  1575. color="green",
  1576. bold=True,
  1577. )
  1578. )
  1579. return exit_code
  1580. def parse_options(args: list[str]) -> _Arguments:
  1581. parser = argparse.ArgumentParser(
  1582. description="Compares stubs to objects introspected from the runtime."
  1583. )
  1584. parser.add_argument("modules", nargs="*", help="Modules to test")
  1585. parser.add_argument(
  1586. "--concise",
  1587. action="store_true",
  1588. help="Makes stubtest's output more concise, one line per error",
  1589. )
  1590. parser.add_argument(
  1591. "--ignore-missing-stub",
  1592. action="store_true",
  1593. help="Ignore errors for stub missing things that are present at runtime",
  1594. )
  1595. parser.add_argument(
  1596. "--ignore-positional-only",
  1597. action="store_true",
  1598. help="Ignore errors for whether an argument should or shouldn't be positional-only",
  1599. )
  1600. parser.add_argument(
  1601. "--allowlist",
  1602. "--whitelist",
  1603. action="append",
  1604. metavar="FILE",
  1605. default=[],
  1606. help=(
  1607. "Use file as an allowlist. Can be passed multiple times to combine multiple "
  1608. "allowlists. Allowlists can be created with --generate-allowlist. Allowlists "
  1609. "support regular expressions."
  1610. ),
  1611. )
  1612. parser.add_argument(
  1613. "--generate-allowlist",
  1614. "--generate-whitelist",
  1615. action="store_true",
  1616. help="Print an allowlist (to stdout) to be used with --allowlist",
  1617. )
  1618. parser.add_argument(
  1619. "--ignore-unused-allowlist",
  1620. "--ignore-unused-whitelist",
  1621. action="store_true",
  1622. help="Ignore unused allowlist entries",
  1623. )
  1624. parser.add_argument(
  1625. "--mypy-config-file",
  1626. metavar="FILE",
  1627. help=("Use specified mypy config file to determine mypy plugins and mypy path"),
  1628. )
  1629. parser.add_argument(
  1630. "--custom-typeshed-dir", metavar="DIR", help="Use the custom typeshed in DIR"
  1631. )
  1632. parser.add_argument(
  1633. "--check-typeshed", action="store_true", help="Check all stdlib modules in typeshed"
  1634. )
  1635. parser.add_argument(
  1636. "--version", action="version", version="%(prog)s " + mypy.version.__version__
  1637. )
  1638. return parser.parse_args(args, namespace=_Arguments())
  1639. def main() -> int:
  1640. mypy.util.check_python_version("stubtest")
  1641. return test_stubs(parse_options(sys.argv[1:]))
  1642. if __name__ == "__main__":
  1643. sys.exit(main())