rewrite.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  1. """Rewrite assertion AST to produce nice error messages."""
  2. import ast
  3. import errno
  4. import functools
  5. import importlib.abc
  6. import importlib.machinery
  7. import importlib.util
  8. import io
  9. import itertools
  10. import marshal
  11. import os
  12. import struct
  13. import sys
  14. import tokenize
  15. import types
  16. from pathlib import Path
  17. from pathlib import PurePath
  18. from typing import Callable
  19. from typing import Dict
  20. from typing import IO
  21. from typing import Iterable
  22. from typing import Iterator
  23. from typing import List
  24. from typing import Optional
  25. from typing import Sequence
  26. from typing import Set
  27. from typing import Tuple
  28. from typing import TYPE_CHECKING
  29. from typing import Union
  30. from _pytest._io.saferepr import DEFAULT_REPR_MAX_SIZE
  31. from _pytest._io.saferepr import saferepr
  32. from _pytest._version import version
  33. from _pytest.assertion import util
  34. from _pytest.assertion.util import ( # noqa: F401
  35. format_explanation as _format_explanation,
  36. )
  37. from _pytest.config import Config
  38. from _pytest.main import Session
  39. from _pytest.pathlib import absolutepath
  40. from _pytest.pathlib import fnmatch_ex
  41. from _pytest.stash import StashKey
  42. if TYPE_CHECKING:
  43. from _pytest.assertion import AssertionState
  44. assertstate_key = StashKey["AssertionState"]()
  45. # pytest caches rewritten pycs in pycache dirs
  46. PYTEST_TAG = f"{sys.implementation.cache_tag}-pytest-{version}"
  47. PYC_EXT = ".py" + (__debug__ and "c" or "o")
  48. PYC_TAIL = "." + PYTEST_TAG + PYC_EXT
  49. class AssertionRewritingHook(importlib.abc.MetaPathFinder, importlib.abc.Loader):
  50. """PEP302/PEP451 import hook which rewrites asserts."""
  51. def __init__(self, config: Config) -> None:
  52. self.config = config
  53. try:
  54. self.fnpats = config.getini("python_files")
  55. except ValueError:
  56. self.fnpats = ["test_*.py", "*_test.py"]
  57. self.session: Optional[Session] = None
  58. self._rewritten_names: Dict[str, Path] = {}
  59. self._must_rewrite: Set[str] = set()
  60. # flag to guard against trying to rewrite a pyc file while we are already writing another pyc file,
  61. # which might result in infinite recursion (#3506)
  62. self._writing_pyc = False
  63. self._basenames_to_check_rewrite = {"conftest"}
  64. self._marked_for_rewrite_cache: Dict[str, bool] = {}
  65. self._session_paths_checked = False
  66. def set_session(self, session: Optional[Session]) -> None:
  67. self.session = session
  68. self._session_paths_checked = False
  69. # Indirection so we can mock calls to find_spec originated from the hook during testing
  70. _find_spec = importlib.machinery.PathFinder.find_spec
  71. def find_spec(
  72. self,
  73. name: str,
  74. path: Optional[Sequence[Union[str, bytes]]] = None,
  75. target: Optional[types.ModuleType] = None,
  76. ) -> Optional[importlib.machinery.ModuleSpec]:
  77. if self._writing_pyc:
  78. return None
  79. state = self.config.stash[assertstate_key]
  80. if self._early_rewrite_bailout(name, state):
  81. return None
  82. state.trace("find_module called for: %s" % name)
  83. # Type ignored because mypy is confused about the `self` binding here.
  84. spec = self._find_spec(name, path) # type: ignore
  85. if (
  86. # the import machinery could not find a file to import
  87. spec is None
  88. # this is a namespace package (without `__init__.py`)
  89. # there's nothing to rewrite there
  90. # python3.6: `namespace`
  91. # python3.7+: `None`
  92. or spec.origin == "namespace"
  93. or spec.origin is None
  94. # we can only rewrite source files
  95. or not isinstance(spec.loader, importlib.machinery.SourceFileLoader)
  96. # if the file doesn't exist, we can't rewrite it
  97. or not os.path.exists(spec.origin)
  98. ):
  99. return None
  100. else:
  101. fn = spec.origin
  102. if not self._should_rewrite(name, fn, state):
  103. return None
  104. return importlib.util.spec_from_file_location(
  105. name,
  106. fn,
  107. loader=self,
  108. submodule_search_locations=spec.submodule_search_locations,
  109. )
  110. def create_module(
  111. self, spec: importlib.machinery.ModuleSpec
  112. ) -> Optional[types.ModuleType]:
  113. return None # default behaviour is fine
  114. def exec_module(self, module: types.ModuleType) -> None:
  115. assert module.__spec__ is not None
  116. assert module.__spec__.origin is not None
  117. fn = Path(module.__spec__.origin)
  118. state = self.config.stash[assertstate_key]
  119. self._rewritten_names[module.__name__] = fn
  120. # The requested module looks like a test file, so rewrite it. This is
  121. # the most magical part of the process: load the source, rewrite the
  122. # asserts, and load the rewritten source. We also cache the rewritten
  123. # module code in a special pyc. We must be aware of the possibility of
  124. # concurrent pytest processes rewriting and loading pycs. To avoid
  125. # tricky race conditions, we maintain the following invariant: The
  126. # cached pyc is always a complete, valid pyc. Operations on it must be
  127. # atomic. POSIX's atomic rename comes in handy.
  128. write = not sys.dont_write_bytecode
  129. cache_dir = get_cache_dir(fn)
  130. if write:
  131. ok = try_makedirs(cache_dir)
  132. if not ok:
  133. write = False
  134. state.trace(f"read only directory: {cache_dir}")
  135. cache_name = fn.name[:-3] + PYC_TAIL
  136. pyc = cache_dir / cache_name
  137. # Notice that even if we're in a read-only directory, I'm going
  138. # to check for a cached pyc. This may not be optimal...
  139. co = _read_pyc(fn, pyc, state.trace)
  140. if co is None:
  141. state.trace(f"rewriting {fn!r}")
  142. source_stat, co = _rewrite_test(fn, self.config)
  143. if write:
  144. self._writing_pyc = True
  145. try:
  146. _write_pyc(state, co, source_stat, pyc)
  147. finally:
  148. self._writing_pyc = False
  149. else:
  150. state.trace(f"found cached rewritten pyc for {fn}")
  151. exec(co, module.__dict__)
  152. def _early_rewrite_bailout(self, name: str, state: "AssertionState") -> bool:
  153. """A fast way to get out of rewriting modules.
  154. Profiling has shown that the call to PathFinder.find_spec (inside of
  155. the find_spec from this class) is a major slowdown, so, this method
  156. tries to filter what we're sure won't be rewritten before getting to
  157. it.
  158. """
  159. if self.session is not None and not self._session_paths_checked:
  160. self._session_paths_checked = True
  161. for initial_path in self.session._initialpaths:
  162. # Make something as c:/projects/my_project/path.py ->
  163. # ['c:', 'projects', 'my_project', 'path.py']
  164. parts = str(initial_path).split(os.path.sep)
  165. # add 'path' to basenames to be checked.
  166. self._basenames_to_check_rewrite.add(os.path.splitext(parts[-1])[0])
  167. # Note: conftest already by default in _basenames_to_check_rewrite.
  168. parts = name.split(".")
  169. if parts[-1] in self._basenames_to_check_rewrite:
  170. return False
  171. # For matching the name it must be as if it was a filename.
  172. path = PurePath(os.path.sep.join(parts) + ".py")
  173. for pat in self.fnpats:
  174. # if the pattern contains subdirectories ("tests/**.py" for example) we can't bail out based
  175. # on the name alone because we need to match against the full path
  176. if os.path.dirname(pat):
  177. return False
  178. if fnmatch_ex(pat, path):
  179. return False
  180. if self._is_marked_for_rewrite(name, state):
  181. return False
  182. state.trace(f"early skip of rewriting module: {name}")
  183. return True
  184. def _should_rewrite(self, name: str, fn: str, state: "AssertionState") -> bool:
  185. # always rewrite conftest files
  186. if os.path.basename(fn) == "conftest.py":
  187. state.trace(f"rewriting conftest file: {fn!r}")
  188. return True
  189. if self.session is not None:
  190. if self.session.isinitpath(absolutepath(fn)):
  191. state.trace(f"matched test file (was specified on cmdline): {fn!r}")
  192. return True
  193. # modules not passed explicitly on the command line are only
  194. # rewritten if they match the naming convention for test files
  195. fn_path = PurePath(fn)
  196. for pat in self.fnpats:
  197. if fnmatch_ex(pat, fn_path):
  198. state.trace(f"matched test file {fn!r}")
  199. return True
  200. return self._is_marked_for_rewrite(name, state)
  201. def _is_marked_for_rewrite(self, name: str, state: "AssertionState") -> bool:
  202. try:
  203. return self._marked_for_rewrite_cache[name]
  204. except KeyError:
  205. for marked in self._must_rewrite:
  206. if name == marked or name.startswith(marked + "."):
  207. state.trace(f"matched marked file {name!r} (from {marked!r})")
  208. self._marked_for_rewrite_cache[name] = True
  209. return True
  210. self._marked_for_rewrite_cache[name] = False
  211. return False
  212. def mark_rewrite(self, *names: str) -> None:
  213. """Mark import names as needing to be rewritten.
  214. The named module or package as well as any nested modules will
  215. be rewritten on import.
  216. """
  217. already_imported = (
  218. set(names).intersection(sys.modules).difference(self._rewritten_names)
  219. )
  220. for name in already_imported:
  221. mod = sys.modules[name]
  222. if not AssertionRewriter.is_rewrite_disabled(
  223. mod.__doc__ or ""
  224. ) and not isinstance(mod.__loader__, type(self)):
  225. self._warn_already_imported(name)
  226. self._must_rewrite.update(names)
  227. self._marked_for_rewrite_cache.clear()
  228. def _warn_already_imported(self, name: str) -> None:
  229. from _pytest.warning_types import PytestAssertRewriteWarning
  230. self.config.issue_config_time_warning(
  231. PytestAssertRewriteWarning(
  232. "Module already imported so cannot be rewritten: %s" % name
  233. ),
  234. stacklevel=5,
  235. )
  236. def get_data(self, pathname: Union[str, bytes]) -> bytes:
  237. """Optional PEP302 get_data API."""
  238. with open(pathname, "rb") as f:
  239. return f.read()
  240. if sys.version_info >= (3, 9):
  241. def get_resource_reader(self, name: str) -> importlib.abc.TraversableResources: # type: ignore
  242. from types import SimpleNamespace
  243. from importlib.readers import FileReader
  244. return FileReader(SimpleNamespace(path=self._rewritten_names[name]))
  245. def _write_pyc_fp(
  246. fp: IO[bytes], source_stat: os.stat_result, co: types.CodeType
  247. ) -> None:
  248. # Technically, we don't have to have the same pyc format as
  249. # (C)Python, since these "pycs" should never be seen by builtin
  250. # import. However, there's little reason to deviate.
  251. fp.write(importlib.util.MAGIC_NUMBER)
  252. # https://www.python.org/dev/peps/pep-0552/
  253. if sys.version_info >= (3, 7):
  254. flags = b"\x00\x00\x00\x00"
  255. fp.write(flags)
  256. # as of now, bytecode header expects 32-bit numbers for size and mtime (#4903)
  257. mtime = int(source_stat.st_mtime) & 0xFFFFFFFF
  258. size = source_stat.st_size & 0xFFFFFFFF
  259. # "<LL" stands for 2 unsigned longs, little-endian.
  260. fp.write(struct.pack("<LL", mtime, size))
  261. fp.write(marshal.dumps(co))
  262. if sys.platform == "win32":
  263. from atomicwrites import atomic_write
  264. def _write_pyc(
  265. state: "AssertionState",
  266. co: types.CodeType,
  267. source_stat: os.stat_result,
  268. pyc: Path,
  269. ) -> bool:
  270. try:
  271. with atomic_write(os.fspath(pyc), mode="wb", overwrite=True) as fp:
  272. _write_pyc_fp(fp, source_stat, co)
  273. except OSError as e:
  274. state.trace(f"error writing pyc file at {pyc}: {e}")
  275. # we ignore any failure to write the cache file
  276. # there are many reasons, permission-denied, pycache dir being a
  277. # file etc.
  278. return False
  279. return True
  280. else:
  281. def _write_pyc(
  282. state: "AssertionState",
  283. co: types.CodeType,
  284. source_stat: os.stat_result,
  285. pyc: Path,
  286. ) -> bool:
  287. proc_pyc = f"{pyc}.{os.getpid()}"
  288. try:
  289. fp = open(proc_pyc, "wb")
  290. except OSError as e:
  291. state.trace(f"error writing pyc file at {proc_pyc}: errno={e.errno}")
  292. return False
  293. try:
  294. _write_pyc_fp(fp, source_stat, co)
  295. os.rename(proc_pyc, pyc)
  296. except OSError as e:
  297. state.trace(f"error writing pyc file at {pyc}: {e}")
  298. # we ignore any failure to write the cache file
  299. # there are many reasons, permission-denied, pycache dir being a
  300. # file etc.
  301. return False
  302. finally:
  303. fp.close()
  304. return True
  305. def _rewrite_test(fn: Path, config: Config) -> Tuple[os.stat_result, types.CodeType]:
  306. """Read and rewrite *fn* and return the code object."""
  307. stat = os.stat(fn)
  308. source = fn.read_bytes()
  309. strfn = str(fn)
  310. tree = ast.parse(source, filename=strfn)
  311. rewrite_asserts(tree, source, strfn, config)
  312. co = compile(tree, strfn, "exec", dont_inherit=True)
  313. return stat, co
  314. def _read_pyc(
  315. source: Path, pyc: Path, trace: Callable[[str], None] = lambda x: None
  316. ) -> Optional[types.CodeType]:
  317. """Possibly read a pytest pyc containing rewritten code.
  318. Return rewritten code if successful or None if not.
  319. """
  320. try:
  321. fp = open(pyc, "rb")
  322. except OSError:
  323. return None
  324. with fp:
  325. # https://www.python.org/dev/peps/pep-0552/
  326. has_flags = sys.version_info >= (3, 7)
  327. try:
  328. stat_result = os.stat(source)
  329. mtime = int(stat_result.st_mtime)
  330. size = stat_result.st_size
  331. data = fp.read(16 if has_flags else 12)
  332. except OSError as e:
  333. trace(f"_read_pyc({source}): OSError {e}")
  334. return None
  335. # Check for invalid or out of date pyc file.
  336. if len(data) != (16 if has_flags else 12):
  337. trace("_read_pyc(%s): invalid pyc (too short)" % source)
  338. return None
  339. if data[:4] != importlib.util.MAGIC_NUMBER:
  340. trace("_read_pyc(%s): invalid pyc (bad magic number)" % source)
  341. return None
  342. if has_flags and data[4:8] != b"\x00\x00\x00\x00":
  343. trace("_read_pyc(%s): invalid pyc (unsupported flags)" % source)
  344. return None
  345. mtime_data = data[8 if has_flags else 4 : 12 if has_flags else 8]
  346. if int.from_bytes(mtime_data, "little") != mtime & 0xFFFFFFFF:
  347. trace("_read_pyc(%s): out of date" % source)
  348. return None
  349. size_data = data[12 if has_flags else 8 : 16 if has_flags else 12]
  350. if int.from_bytes(size_data, "little") != size & 0xFFFFFFFF:
  351. trace("_read_pyc(%s): invalid pyc (incorrect size)" % source)
  352. return None
  353. try:
  354. co = marshal.load(fp)
  355. except Exception as e:
  356. trace(f"_read_pyc({source}): marshal.load error {e}")
  357. return None
  358. if not isinstance(co, types.CodeType):
  359. trace("_read_pyc(%s): not a code object" % source)
  360. return None
  361. return co
  362. def rewrite_asserts(
  363. mod: ast.Module,
  364. source: bytes,
  365. module_path: Optional[str] = None,
  366. config: Optional[Config] = None,
  367. ) -> None:
  368. """Rewrite the assert statements in mod."""
  369. AssertionRewriter(module_path, config, source).run(mod)
  370. def _saferepr(obj: object) -> str:
  371. r"""Get a safe repr of an object for assertion error messages.
  372. The assertion formatting (util.format_explanation()) requires
  373. newlines to be escaped since they are a special character for it.
  374. Normally assertion.util.format_explanation() does this but for a
  375. custom repr it is possible to contain one of the special escape
  376. sequences, especially '\n{' and '\n}' are likely to be present in
  377. JSON reprs.
  378. """
  379. maxsize = _get_maxsize_for_saferepr(util._config)
  380. return saferepr(obj, maxsize=maxsize).replace("\n", "\\n")
  381. def _get_maxsize_for_saferepr(config: Optional[Config]) -> Optional[int]:
  382. """Get `maxsize` configuration for saferepr based on the given config object."""
  383. verbosity = config.getoption("verbose") if config is not None else 0
  384. if verbosity >= 2:
  385. return None
  386. if verbosity >= 1:
  387. return DEFAULT_REPR_MAX_SIZE * 10
  388. return DEFAULT_REPR_MAX_SIZE
  389. def _format_assertmsg(obj: object) -> str:
  390. r"""Format the custom assertion message given.
  391. For strings this simply replaces newlines with '\n~' so that
  392. util.format_explanation() will preserve them instead of escaping
  393. newlines. For other objects saferepr() is used first.
  394. """
  395. # reprlib appears to have a bug which means that if a string
  396. # contains a newline it gets escaped, however if an object has a
  397. # .__repr__() which contains newlines it does not get escaped.
  398. # However in either case we want to preserve the newline.
  399. replaces = [("\n", "\n~"), ("%", "%%")]
  400. if not isinstance(obj, str):
  401. obj = saferepr(obj)
  402. replaces.append(("\\n", "\n~"))
  403. for r1, r2 in replaces:
  404. obj = obj.replace(r1, r2)
  405. return obj
  406. def _should_repr_global_name(obj: object) -> bool:
  407. if callable(obj):
  408. return False
  409. try:
  410. return not hasattr(obj, "__name__")
  411. except Exception:
  412. return True
  413. def _format_boolop(explanations: Iterable[str], is_or: bool) -> str:
  414. explanation = "(" + (is_or and " or " or " and ").join(explanations) + ")"
  415. return explanation.replace("%", "%%")
  416. def _call_reprcompare(
  417. ops: Sequence[str],
  418. results: Sequence[bool],
  419. expls: Sequence[str],
  420. each_obj: Sequence[object],
  421. ) -> str:
  422. for i, res, expl in zip(range(len(ops)), results, expls):
  423. try:
  424. done = not res
  425. except Exception:
  426. done = True
  427. if done:
  428. break
  429. if util._reprcompare is not None:
  430. custom = util._reprcompare(ops[i], each_obj[i], each_obj[i + 1])
  431. if custom is not None:
  432. return custom
  433. return expl
  434. def _call_assertion_pass(lineno: int, orig: str, expl: str) -> None:
  435. if util._assertion_pass is not None:
  436. util._assertion_pass(lineno, orig, expl)
  437. def _check_if_assertion_pass_impl() -> bool:
  438. """Check if any plugins implement the pytest_assertion_pass hook
  439. in order not to generate explanation unnecessarily (might be expensive)."""
  440. return True if util._assertion_pass else False
  441. UNARY_MAP = {ast.Not: "not %s", ast.Invert: "~%s", ast.USub: "-%s", ast.UAdd: "+%s"}
  442. BINOP_MAP = {
  443. ast.BitOr: "|",
  444. ast.BitXor: "^",
  445. ast.BitAnd: "&",
  446. ast.LShift: "<<",
  447. ast.RShift: ">>",
  448. ast.Add: "+",
  449. ast.Sub: "-",
  450. ast.Mult: "*",
  451. ast.Div: "/",
  452. ast.FloorDiv: "//",
  453. ast.Mod: "%%", # escaped for string formatting
  454. ast.Eq: "==",
  455. ast.NotEq: "!=",
  456. ast.Lt: "<",
  457. ast.LtE: "<=",
  458. ast.Gt: ">",
  459. ast.GtE: ">=",
  460. ast.Pow: "**",
  461. ast.Is: "is",
  462. ast.IsNot: "is not",
  463. ast.In: "in",
  464. ast.NotIn: "not in",
  465. ast.MatMult: "@",
  466. }
  467. def traverse_node(node: ast.AST) -> Iterator[ast.AST]:
  468. """Recursively yield node and all its children in depth-first order."""
  469. yield node
  470. for child in ast.iter_child_nodes(node):
  471. yield from traverse_node(child)
  472. @functools.lru_cache(maxsize=1)
  473. def _get_assertion_exprs(src: bytes) -> Dict[int, str]:
  474. """Return a mapping from {lineno: "assertion test expression"}."""
  475. ret: Dict[int, str] = {}
  476. depth = 0
  477. lines: List[str] = []
  478. assert_lineno: Optional[int] = None
  479. seen_lines: Set[int] = set()
  480. def _write_and_reset() -> None:
  481. nonlocal depth, lines, assert_lineno, seen_lines
  482. assert assert_lineno is not None
  483. ret[assert_lineno] = "".join(lines).rstrip().rstrip("\\")
  484. depth = 0
  485. lines = []
  486. assert_lineno = None
  487. seen_lines = set()
  488. tokens = tokenize.tokenize(io.BytesIO(src).readline)
  489. for tp, source, (lineno, offset), _, line in tokens:
  490. if tp == tokenize.NAME and source == "assert":
  491. assert_lineno = lineno
  492. elif assert_lineno is not None:
  493. # keep track of depth for the assert-message `,` lookup
  494. if tp == tokenize.OP and source in "([{":
  495. depth += 1
  496. elif tp == tokenize.OP and source in ")]}":
  497. depth -= 1
  498. if not lines:
  499. lines.append(line[offset:])
  500. seen_lines.add(lineno)
  501. # a non-nested comma separates the expression from the message
  502. elif depth == 0 and tp == tokenize.OP and source == ",":
  503. # one line assert with message
  504. if lineno in seen_lines and len(lines) == 1:
  505. offset_in_trimmed = offset + len(lines[-1]) - len(line)
  506. lines[-1] = lines[-1][:offset_in_trimmed]
  507. # multi-line assert with message
  508. elif lineno in seen_lines:
  509. lines[-1] = lines[-1][:offset]
  510. # multi line assert with escapd newline before message
  511. else:
  512. lines.append(line[:offset])
  513. _write_and_reset()
  514. elif tp in {tokenize.NEWLINE, tokenize.ENDMARKER}:
  515. _write_and_reset()
  516. elif lines and lineno not in seen_lines:
  517. lines.append(line)
  518. seen_lines.add(lineno)
  519. return ret
  520. class AssertionRewriter(ast.NodeVisitor):
  521. """Assertion rewriting implementation.
  522. The main entrypoint is to call .run() with an ast.Module instance,
  523. this will then find all the assert statements and rewrite them to
  524. provide intermediate values and a detailed assertion error. See
  525. http://pybites.blogspot.be/2011/07/behind-scenes-of-pytests-new-assertion.html
  526. for an overview of how this works.
  527. The entry point here is .run() which will iterate over all the
  528. statements in an ast.Module and for each ast.Assert statement it
  529. finds call .visit() with it. Then .visit_Assert() takes over and
  530. is responsible for creating new ast statements to replace the
  531. original assert statement: it rewrites the test of an assertion
  532. to provide intermediate values and replace it with an if statement
  533. which raises an assertion error with a detailed explanation in
  534. case the expression is false and calls pytest_assertion_pass hook
  535. if expression is true.
  536. For this .visit_Assert() uses the visitor pattern to visit all the
  537. AST nodes of the ast.Assert.test field, each visit call returning
  538. an AST node and the corresponding explanation string. During this
  539. state is kept in several instance attributes:
  540. :statements: All the AST statements which will replace the assert
  541. statement.
  542. :variables: This is populated by .variable() with each variable
  543. used by the statements so that they can all be set to None at
  544. the end of the statements.
  545. :variable_counter: Counter to create new unique variables needed
  546. by statements. Variables are created using .variable() and
  547. have the form of "@py_assert0".
  548. :expl_stmts: The AST statements which will be executed to get
  549. data from the assertion. This is the code which will construct
  550. the detailed assertion message that is used in the AssertionError
  551. or for the pytest_assertion_pass hook.
  552. :explanation_specifiers: A dict filled by .explanation_param()
  553. with %-formatting placeholders and their corresponding
  554. expressions to use in the building of an assertion message.
  555. This is used by .pop_format_context() to build a message.
  556. :stack: A stack of the explanation_specifiers dicts maintained by
  557. .push_format_context() and .pop_format_context() which allows
  558. to build another %-formatted string while already building one.
  559. This state is reset on every new assert statement visited and used
  560. by the other visitors.
  561. """
  562. def __init__(
  563. self, module_path: Optional[str], config: Optional[Config], source: bytes
  564. ) -> None:
  565. super().__init__()
  566. self.module_path = module_path
  567. self.config = config
  568. if config is not None:
  569. self.enable_assertion_pass_hook = config.getini(
  570. "enable_assertion_pass_hook"
  571. )
  572. else:
  573. self.enable_assertion_pass_hook = False
  574. self.source = source
  575. def run(self, mod: ast.Module) -> None:
  576. """Find all assert statements in *mod* and rewrite them."""
  577. if not mod.body:
  578. # Nothing to do.
  579. return
  580. # We'll insert some special imports at the top of the module, but after any
  581. # docstrings and __future__ imports, so first figure out where that is.
  582. doc = getattr(mod, "docstring", None)
  583. expect_docstring = doc is None
  584. if doc is not None and self.is_rewrite_disabled(doc):
  585. return
  586. pos = 0
  587. lineno = 1
  588. for item in mod.body:
  589. if (
  590. expect_docstring
  591. and isinstance(item, ast.Expr)
  592. and isinstance(item.value, ast.Str)
  593. ):
  594. doc = item.value.s
  595. if self.is_rewrite_disabled(doc):
  596. return
  597. expect_docstring = False
  598. elif (
  599. isinstance(item, ast.ImportFrom)
  600. and item.level == 0
  601. and item.module == "__future__"
  602. ):
  603. pass
  604. else:
  605. break
  606. pos += 1
  607. # Special case: for a decorated function, set the lineno to that of the
  608. # first decorator, not the `def`. Issue #4984.
  609. if isinstance(item, ast.FunctionDef) and item.decorator_list:
  610. lineno = item.decorator_list[0].lineno
  611. else:
  612. lineno = item.lineno
  613. # Now actually insert the special imports.
  614. if sys.version_info >= (3, 10):
  615. aliases = [
  616. ast.alias("builtins", "@py_builtins", lineno=lineno, col_offset=0),
  617. ast.alias(
  618. "_pytest.assertion.rewrite",
  619. "@pytest_ar",
  620. lineno=lineno,
  621. col_offset=0,
  622. ),
  623. ]
  624. else:
  625. aliases = [
  626. ast.alias("builtins", "@py_builtins"),
  627. ast.alias("_pytest.assertion.rewrite", "@pytest_ar"),
  628. ]
  629. imports = [
  630. ast.Import([alias], lineno=lineno, col_offset=0) for alias in aliases
  631. ]
  632. mod.body[pos:pos] = imports
  633. # Collect asserts.
  634. nodes: List[ast.AST] = [mod]
  635. while nodes:
  636. node = nodes.pop()
  637. for name, field in ast.iter_fields(node):
  638. if isinstance(field, list):
  639. new: List[ast.AST] = []
  640. for i, child in enumerate(field):
  641. if isinstance(child, ast.Assert):
  642. # Transform assert.
  643. new.extend(self.visit(child))
  644. else:
  645. new.append(child)
  646. if isinstance(child, ast.AST):
  647. nodes.append(child)
  648. setattr(node, name, new)
  649. elif (
  650. isinstance(field, ast.AST)
  651. # Don't recurse into expressions as they can't contain
  652. # asserts.
  653. and not isinstance(field, ast.expr)
  654. ):
  655. nodes.append(field)
  656. @staticmethod
  657. def is_rewrite_disabled(docstring: str) -> bool:
  658. return "PYTEST_DONT_REWRITE" in docstring
  659. def variable(self) -> str:
  660. """Get a new variable."""
  661. # Use a character invalid in python identifiers to avoid clashing.
  662. name = "@py_assert" + str(next(self.variable_counter))
  663. self.variables.append(name)
  664. return name
  665. def assign(self, expr: ast.expr) -> ast.Name:
  666. """Give *expr* a name."""
  667. name = self.variable()
  668. self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr))
  669. return ast.Name(name, ast.Load())
  670. def display(self, expr: ast.expr) -> ast.expr:
  671. """Call saferepr on the expression."""
  672. return self.helper("_saferepr", expr)
  673. def helper(self, name: str, *args: ast.expr) -> ast.expr:
  674. """Call a helper in this module."""
  675. py_name = ast.Name("@pytest_ar", ast.Load())
  676. attr = ast.Attribute(py_name, name, ast.Load())
  677. return ast.Call(attr, list(args), [])
  678. def builtin(self, name: str) -> ast.Attribute:
  679. """Return the builtin called *name*."""
  680. builtin_name = ast.Name("@py_builtins", ast.Load())
  681. return ast.Attribute(builtin_name, name, ast.Load())
  682. def explanation_param(self, expr: ast.expr) -> str:
  683. """Return a new named %-formatting placeholder for expr.
  684. This creates a %-formatting placeholder for expr in the
  685. current formatting context, e.g. ``%(py0)s``. The placeholder
  686. and expr are placed in the current format context so that it
  687. can be used on the next call to .pop_format_context().
  688. """
  689. specifier = "py" + str(next(self.variable_counter))
  690. self.explanation_specifiers[specifier] = expr
  691. return "%(" + specifier + ")s"
  692. def push_format_context(self) -> None:
  693. """Create a new formatting context.
  694. The format context is used for when an explanation wants to
  695. have a variable value formatted in the assertion message. In
  696. this case the value required can be added using
  697. .explanation_param(). Finally .pop_format_context() is used
  698. to format a string of %-formatted values as added by
  699. .explanation_param().
  700. """
  701. self.explanation_specifiers: Dict[str, ast.expr] = {}
  702. self.stack.append(self.explanation_specifiers)
  703. def pop_format_context(self, expl_expr: ast.expr) -> ast.Name:
  704. """Format the %-formatted string with current format context.
  705. The expl_expr should be an str ast.expr instance constructed from
  706. the %-placeholders created by .explanation_param(). This will
  707. add the required code to format said string to .expl_stmts and
  708. return the ast.Name instance of the formatted string.
  709. """
  710. current = self.stack.pop()
  711. if self.stack:
  712. self.explanation_specifiers = self.stack[-1]
  713. keys = [ast.Str(key) for key in current.keys()]
  714. format_dict = ast.Dict(keys, list(current.values()))
  715. form = ast.BinOp(expl_expr, ast.Mod(), format_dict)
  716. name = "@py_format" + str(next(self.variable_counter))
  717. if self.enable_assertion_pass_hook:
  718. self.format_variables.append(name)
  719. self.expl_stmts.append(ast.Assign([ast.Name(name, ast.Store())], form))
  720. return ast.Name(name, ast.Load())
  721. def generic_visit(self, node: ast.AST) -> Tuple[ast.Name, str]:
  722. """Handle expressions we don't have custom code for."""
  723. assert isinstance(node, ast.expr)
  724. res = self.assign(node)
  725. return res, self.explanation_param(self.display(res))
  726. def visit_Assert(self, assert_: ast.Assert) -> List[ast.stmt]:
  727. """Return the AST statements to replace the ast.Assert instance.
  728. This rewrites the test of an assertion to provide
  729. intermediate values and replace it with an if statement which
  730. raises an assertion error with a detailed explanation in case
  731. the expression is false.
  732. """
  733. if isinstance(assert_.test, ast.Tuple) and len(assert_.test.elts) >= 1:
  734. from _pytest.warning_types import PytestAssertRewriteWarning
  735. import warnings
  736. # TODO: This assert should not be needed.
  737. assert self.module_path is not None
  738. warnings.warn_explicit(
  739. PytestAssertRewriteWarning(
  740. "assertion is always true, perhaps remove parentheses?"
  741. ),
  742. category=None,
  743. filename=self.module_path,
  744. lineno=assert_.lineno,
  745. )
  746. self.statements: List[ast.stmt] = []
  747. self.variables: List[str] = []
  748. self.variable_counter = itertools.count()
  749. if self.enable_assertion_pass_hook:
  750. self.format_variables: List[str] = []
  751. self.stack: List[Dict[str, ast.expr]] = []
  752. self.expl_stmts: List[ast.stmt] = []
  753. self.push_format_context()
  754. # Rewrite assert into a bunch of statements.
  755. top_condition, explanation = self.visit(assert_.test)
  756. negation = ast.UnaryOp(ast.Not(), top_condition)
  757. if self.enable_assertion_pass_hook: # Experimental pytest_assertion_pass hook
  758. msg = self.pop_format_context(ast.Str(explanation))
  759. # Failed
  760. if assert_.msg:
  761. assertmsg = self.helper("_format_assertmsg", assert_.msg)
  762. gluestr = "\n>assert "
  763. else:
  764. assertmsg = ast.Str("")
  765. gluestr = "assert "
  766. err_explanation = ast.BinOp(ast.Str(gluestr), ast.Add(), msg)
  767. err_msg = ast.BinOp(assertmsg, ast.Add(), err_explanation)
  768. err_name = ast.Name("AssertionError", ast.Load())
  769. fmt = self.helper("_format_explanation", err_msg)
  770. exc = ast.Call(err_name, [fmt], [])
  771. raise_ = ast.Raise(exc, None)
  772. statements_fail = []
  773. statements_fail.extend(self.expl_stmts)
  774. statements_fail.append(raise_)
  775. # Passed
  776. fmt_pass = self.helper("_format_explanation", msg)
  777. orig = _get_assertion_exprs(self.source)[assert_.lineno]
  778. hook_call_pass = ast.Expr(
  779. self.helper(
  780. "_call_assertion_pass",
  781. ast.Num(assert_.lineno),
  782. ast.Str(orig),
  783. fmt_pass,
  784. )
  785. )
  786. # If any hooks implement assert_pass hook
  787. hook_impl_test = ast.If(
  788. self.helper("_check_if_assertion_pass_impl"),
  789. self.expl_stmts + [hook_call_pass],
  790. [],
  791. )
  792. statements_pass = [hook_impl_test]
  793. # Test for assertion condition
  794. main_test = ast.If(negation, statements_fail, statements_pass)
  795. self.statements.append(main_test)
  796. if self.format_variables:
  797. variables = [
  798. ast.Name(name, ast.Store()) for name in self.format_variables
  799. ]
  800. clear_format = ast.Assign(variables, ast.NameConstant(None))
  801. self.statements.append(clear_format)
  802. else: # Original assertion rewriting
  803. # Create failure message.
  804. body = self.expl_stmts
  805. self.statements.append(ast.If(negation, body, []))
  806. if assert_.msg:
  807. assertmsg = self.helper("_format_assertmsg", assert_.msg)
  808. explanation = "\n>assert " + explanation
  809. else:
  810. assertmsg = ast.Str("")
  811. explanation = "assert " + explanation
  812. template = ast.BinOp(assertmsg, ast.Add(), ast.Str(explanation))
  813. msg = self.pop_format_context(template)
  814. fmt = self.helper("_format_explanation", msg)
  815. err_name = ast.Name("AssertionError", ast.Load())
  816. exc = ast.Call(err_name, [fmt], [])
  817. raise_ = ast.Raise(exc, None)
  818. body.append(raise_)
  819. # Clear temporary variables by setting them to None.
  820. if self.variables:
  821. variables = [ast.Name(name, ast.Store()) for name in self.variables]
  822. clear = ast.Assign(variables, ast.NameConstant(None))
  823. self.statements.append(clear)
  824. # Fix locations (line numbers/column offsets).
  825. for stmt in self.statements:
  826. for node in traverse_node(stmt):
  827. ast.copy_location(node, assert_)
  828. return self.statements
  829. def visit_Name(self, name: ast.Name) -> Tuple[ast.Name, str]:
  830. # Display the repr of the name if it's a local variable or
  831. # _should_repr_global_name() thinks it's acceptable.
  832. locs = ast.Call(self.builtin("locals"), [], [])
  833. inlocs = ast.Compare(ast.Str(name.id), [ast.In()], [locs])
  834. dorepr = self.helper("_should_repr_global_name", name)
  835. test = ast.BoolOp(ast.Or(), [inlocs, dorepr])
  836. expr = ast.IfExp(test, self.display(name), ast.Str(name.id))
  837. return name, self.explanation_param(expr)
  838. def visit_BoolOp(self, boolop: ast.BoolOp) -> Tuple[ast.Name, str]:
  839. res_var = self.variable()
  840. expl_list = self.assign(ast.List([], ast.Load()))
  841. app = ast.Attribute(expl_list, "append", ast.Load())
  842. is_or = int(isinstance(boolop.op, ast.Or))
  843. body = save = self.statements
  844. fail_save = self.expl_stmts
  845. levels = len(boolop.values) - 1
  846. self.push_format_context()
  847. # Process each operand, short-circuiting if needed.
  848. for i, v in enumerate(boolop.values):
  849. if i:
  850. fail_inner: List[ast.stmt] = []
  851. # cond is set in a prior loop iteration below
  852. self.expl_stmts.append(ast.If(cond, fail_inner, [])) # noqa
  853. self.expl_stmts = fail_inner
  854. self.push_format_context()
  855. res, expl = self.visit(v)
  856. body.append(ast.Assign([ast.Name(res_var, ast.Store())], res))
  857. expl_format = self.pop_format_context(ast.Str(expl))
  858. call = ast.Call(app, [expl_format], [])
  859. self.expl_stmts.append(ast.Expr(call))
  860. if i < levels:
  861. cond: ast.expr = res
  862. if is_or:
  863. cond = ast.UnaryOp(ast.Not(), cond)
  864. inner: List[ast.stmt] = []
  865. self.statements.append(ast.If(cond, inner, []))
  866. self.statements = body = inner
  867. self.statements = save
  868. self.expl_stmts = fail_save
  869. expl_template = self.helper("_format_boolop", expl_list, ast.Num(is_or))
  870. expl = self.pop_format_context(expl_template)
  871. return ast.Name(res_var, ast.Load()), self.explanation_param(expl)
  872. def visit_UnaryOp(self, unary: ast.UnaryOp) -> Tuple[ast.Name, str]:
  873. pattern = UNARY_MAP[unary.op.__class__]
  874. operand_res, operand_expl = self.visit(unary.operand)
  875. res = self.assign(ast.UnaryOp(unary.op, operand_res))
  876. return res, pattern % (operand_expl,)
  877. def visit_BinOp(self, binop: ast.BinOp) -> Tuple[ast.Name, str]:
  878. symbol = BINOP_MAP[binop.op.__class__]
  879. left_expr, left_expl = self.visit(binop.left)
  880. right_expr, right_expl = self.visit(binop.right)
  881. explanation = f"({left_expl} {symbol} {right_expl})"
  882. res = self.assign(ast.BinOp(left_expr, binop.op, right_expr))
  883. return res, explanation
  884. def visit_Call(self, call: ast.Call) -> Tuple[ast.Name, str]:
  885. new_func, func_expl = self.visit(call.func)
  886. arg_expls = []
  887. new_args = []
  888. new_kwargs = []
  889. for arg in call.args:
  890. res, expl = self.visit(arg)
  891. arg_expls.append(expl)
  892. new_args.append(res)
  893. for keyword in call.keywords:
  894. res, expl = self.visit(keyword.value)
  895. new_kwargs.append(ast.keyword(keyword.arg, res))
  896. if keyword.arg:
  897. arg_expls.append(keyword.arg + "=" + expl)
  898. else: # **args have `arg` keywords with an .arg of None
  899. arg_expls.append("**" + expl)
  900. expl = "{}({})".format(func_expl, ", ".join(arg_expls))
  901. new_call = ast.Call(new_func, new_args, new_kwargs)
  902. res = self.assign(new_call)
  903. res_expl = self.explanation_param(self.display(res))
  904. outer_expl = f"{res_expl}\n{{{res_expl} = {expl}\n}}"
  905. return res, outer_expl
  906. def visit_Starred(self, starred: ast.Starred) -> Tuple[ast.Starred, str]:
  907. # A Starred node can appear in a function call.
  908. res, expl = self.visit(starred.value)
  909. new_starred = ast.Starred(res, starred.ctx)
  910. return new_starred, "*" + expl
  911. def visit_Attribute(self, attr: ast.Attribute) -> Tuple[ast.Name, str]:
  912. if not isinstance(attr.ctx, ast.Load):
  913. return self.generic_visit(attr)
  914. value, value_expl = self.visit(attr.value)
  915. res = self.assign(ast.Attribute(value, attr.attr, ast.Load()))
  916. res_expl = self.explanation_param(self.display(res))
  917. pat = "%s\n{%s = %s.%s\n}"
  918. expl = pat % (res_expl, res_expl, value_expl, attr.attr)
  919. return res, expl
  920. def visit_Compare(self, comp: ast.Compare) -> Tuple[ast.expr, str]:
  921. self.push_format_context()
  922. left_res, left_expl = self.visit(comp.left)
  923. if isinstance(comp.left, (ast.Compare, ast.BoolOp)):
  924. left_expl = f"({left_expl})"
  925. res_variables = [self.variable() for i in range(len(comp.ops))]
  926. load_names = [ast.Name(v, ast.Load()) for v in res_variables]
  927. store_names = [ast.Name(v, ast.Store()) for v in res_variables]
  928. it = zip(range(len(comp.ops)), comp.ops, comp.comparators)
  929. expls = []
  930. syms = []
  931. results = [left_res]
  932. for i, op, next_operand in it:
  933. next_res, next_expl = self.visit(next_operand)
  934. if isinstance(next_operand, (ast.Compare, ast.BoolOp)):
  935. next_expl = f"({next_expl})"
  936. results.append(next_res)
  937. sym = BINOP_MAP[op.__class__]
  938. syms.append(ast.Str(sym))
  939. expl = f"{left_expl} {sym} {next_expl}"
  940. expls.append(ast.Str(expl))
  941. res_expr = ast.Compare(left_res, [op], [next_res])
  942. self.statements.append(ast.Assign([store_names[i]], res_expr))
  943. left_res, left_expl = next_res, next_expl
  944. # Use pytest.assertion.util._reprcompare if that's available.
  945. expl_call = self.helper(
  946. "_call_reprcompare",
  947. ast.Tuple(syms, ast.Load()),
  948. ast.Tuple(load_names, ast.Load()),
  949. ast.Tuple(expls, ast.Load()),
  950. ast.Tuple(results, ast.Load()),
  951. )
  952. if len(comp.ops) > 1:
  953. res: ast.expr = ast.BoolOp(ast.And(), load_names)
  954. else:
  955. res = load_names[0]
  956. return res, self.explanation_param(self.pop_format_context(expl_call))
  957. def try_makedirs(cache_dir: Path) -> bool:
  958. """Attempt to create the given directory and sub-directories exist.
  959. Returns True if successful or if it already exists.
  960. """
  961. try:
  962. os.makedirs(cache_dir, exist_ok=True)
  963. except (FileNotFoundError, NotADirectoryError, FileExistsError):
  964. # One of the path components was not a directory:
  965. # - we're in a zip file
  966. # - it is a file
  967. return False
  968. except PermissionError:
  969. return False
  970. except OSError as e:
  971. # as of now, EROFS doesn't have an equivalent OSError-subclass
  972. if e.errno == errno.EROFS:
  973. return False
  974. raise
  975. return True
  976. def get_cache_dir(file_path: Path) -> Path:
  977. """Return the cache directory to write .pyc files for the given .py file path."""
  978. if sys.version_info >= (3, 8) and sys.pycache_prefix:
  979. # given:
  980. # prefix = '/tmp/pycs'
  981. # path = '/home/user/proj/test_app.py'
  982. # we want:
  983. # '/tmp/pycs/home/user/proj'
  984. return Path(sys.pycache_prefix) / Path(*file_path.parts[1:-1])
  985. else:
  986. # classic pycache directory
  987. return file_path.parent / "__pycache__"