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