Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +4 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/_version.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/cacheprovider.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/capture.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/deprecated.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/doctest.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/fixtures.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/helpconfig.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/hookspec.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/junitxml.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/logging.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/outcomes.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/pastebin.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/pytester.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/python_api.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/recwarn.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/reports.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/runner.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/setuponly.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/setupplan.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/terminal.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/tmpdir.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/warning_types.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/__pycache__/warnings.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/_code/__init__.py +26 -0
- vllm/lib/python3.10/site-packages/_pytest/_code/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/_code/__pycache__/code.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/_code/__pycache__/source.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/_code/code.py +1409 -0
- vllm/lib/python3.10/site-packages/_pytest/_code/source.py +215 -0
- vllm/lib/python3.10/site-packages/_pytest/_io/__init__.py +10 -0
- vllm/lib/python3.10/site-packages/_pytest/_io/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/_io/__pycache__/pprint.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/_io/__pycache__/saferepr.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/_io/__pycache__/terminalwriter.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/_io/__pycache__/wcwidth.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/_io/wcwidth.py +57 -0
- vllm/lib/python3.10/site-packages/_pytest/_py/__init__.py +0 -0
- vllm/lib/python3.10/site-packages/_pytest/_py/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/_py/__pycache__/error.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/_py/__pycache__/path.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/_py/error.py +111 -0
- vllm/lib/python3.10/site-packages/_pytest/_py/path.py +1475 -0
- vllm/lib/python3.10/site-packages/_pytest/assertion/__init__.py +192 -0
- vllm/lib/python3.10/site-packages/_pytest/assertion/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/assertion/__pycache__/rewrite.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/assertion/__pycache__/truncate.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/assertion/__pycache__/util.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/_pytest/assertion/rewrite.py +1211 -0
- vllm/lib/python3.10/site-packages/_pytest/assertion/truncate.py +117 -0
.gitattributes
CHANGED
|
@@ -1561,3 +1561,7 @@ vllm/lib/python3.10/site-packages/triton/backends/nvidia/bin/ptxas filter=lfs di
|
|
| 1561 |
vllm/lib/python3.10/site-packages/triton/backends/amd/lib/ockl.bc filter=lfs diff=lfs merge=lfs -text
|
| 1562 |
vllm/lib/python3.10/site-packages/triton/backends/nvidia/bin/nvdisasm filter=lfs diff=lfs merge=lfs -text
|
| 1563 |
vllm/lib/python3.10/site-packages/torio/lib/libtorio_ffmpeg5.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1561 |
vllm/lib/python3.10/site-packages/triton/backends/amd/lib/ockl.bc filter=lfs diff=lfs merge=lfs -text
|
| 1562 |
vllm/lib/python3.10/site-packages/triton/backends/nvidia/bin/nvdisasm filter=lfs diff=lfs merge=lfs -text
|
| 1563 |
vllm/lib/python3.10/site-packages/torio/lib/libtorio_ffmpeg5.so filter=lfs diff=lfs merge=lfs -text
|
| 1564 |
+
vllm/lib/python3.10/site-packages/torio/lib/libtorio_ffmpeg4.so filter=lfs diff=lfs merge=lfs -text
|
| 1565 |
+
vllm/lib/python3.10/site-packages/torio/lib/libtorio_ffmpeg6.so filter=lfs diff=lfs merge=lfs -text
|
| 1566 |
+
vllm/lib/python3.10/site-packages/torio/lib/_torio_ffmpeg5.so filter=lfs diff=lfs merge=lfs -text
|
| 1567 |
+
vllm/lib/python3.10/site-packages/torio/lib/_torio_ffmpeg4.so filter=lfs diff=lfs merge=lfs -text
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/_version.cpython-310.pyc
ADDED
|
Binary file (480 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/cacheprovider.cpython-310.pyc
ADDED
|
Binary file (20.3 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/capture.cpython-310.pyc
ADDED
|
Binary file (35.4 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/deprecated.cpython-310.pyc
ADDED
|
Binary file (2.39 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/doctest.cpython-310.pyc
ADDED
|
Binary file (23.3 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/fixtures.cpython-310.pyc
ADDED
|
Binary file (54 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/helpconfig.cpython-310.pyc
ADDED
|
Binary file (7.81 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/hookspec.cpython-310.pyc
ADDED
|
Binary file (43.8 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/junitxml.cpython-310.pyc
ADDED
|
Binary file (21.3 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/logging.cpython-310.pyc
ADDED
|
Binary file (31.5 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/outcomes.cpython-310.pyc
ADDED
|
Binary file (9.95 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/pastebin.cpython-310.pyc
ADDED
|
Binary file (3.65 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/pytester.cpython-310.pyc
ADDED
|
Binary file (60.9 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/python_api.cpython-310.pyc
ADDED
|
Binary file (34.3 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/recwarn.cpython-310.pyc
ADDED
|
Binary file (11.9 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/reports.cpython-310.pyc
ADDED
|
Binary file (18 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/runner.cpython-310.pyc
ADDED
|
Binary file (15.8 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/setuponly.cpython-310.pyc
ADDED
|
Binary file (3.18 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/setupplan.cpython-310.pyc
ADDED
|
Binary file (1.42 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/terminal.cpython-310.pyc
ADDED
|
Binary file (46.8 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/tmpdir.cpython-310.pyc
ADDED
|
Binary file (9.03 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/warning_types.cpython-310.pyc
ADDED
|
Binary file (5.49 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/__pycache__/warnings.cpython-310.pyc
ADDED
|
Binary file (4.32 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/_code/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Python inspection/code generation API."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from .code import Code
|
| 6 |
+
from .code import ExceptionInfo
|
| 7 |
+
from .code import filter_traceback
|
| 8 |
+
from .code import Frame
|
| 9 |
+
from .code import getfslineno
|
| 10 |
+
from .code import Traceback
|
| 11 |
+
from .code import TracebackEntry
|
| 12 |
+
from .source import getrawcode
|
| 13 |
+
from .source import Source
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
__all__ = [
|
| 17 |
+
"Code",
|
| 18 |
+
"ExceptionInfo",
|
| 19 |
+
"filter_traceback",
|
| 20 |
+
"Frame",
|
| 21 |
+
"getfslineno",
|
| 22 |
+
"getrawcode",
|
| 23 |
+
"Traceback",
|
| 24 |
+
"TracebackEntry",
|
| 25 |
+
"Source",
|
| 26 |
+
]
|
vllm/lib/python3.10/site-packages/_pytest/_code/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (644 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/_code/__pycache__/code.cpython-310.pyc
ADDED
|
Binary file (43.1 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/_code/__pycache__/source.cpython-310.pyc
ADDED
|
Binary file (7.4 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/_code/code.py
ADDED
|
@@ -0,0 +1,1409 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import ast
|
| 5 |
+
import dataclasses
|
| 6 |
+
import inspect
|
| 7 |
+
from inspect import CO_VARARGS
|
| 8 |
+
from inspect import CO_VARKEYWORDS
|
| 9 |
+
from io import StringIO
|
| 10 |
+
import os
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
import re
|
| 13 |
+
import sys
|
| 14 |
+
import traceback
|
| 15 |
+
from traceback import format_exception_only
|
| 16 |
+
from types import CodeType
|
| 17 |
+
from types import FrameType
|
| 18 |
+
from types import TracebackType
|
| 19 |
+
from typing import Any
|
| 20 |
+
from typing import Callable
|
| 21 |
+
from typing import ClassVar
|
| 22 |
+
from typing import Final
|
| 23 |
+
from typing import final
|
| 24 |
+
from typing import Generic
|
| 25 |
+
from typing import Iterable
|
| 26 |
+
from typing import List
|
| 27 |
+
from typing import Literal
|
| 28 |
+
from typing import Mapping
|
| 29 |
+
from typing import overload
|
| 30 |
+
from typing import Pattern
|
| 31 |
+
from typing import Sequence
|
| 32 |
+
from typing import SupportsIndex
|
| 33 |
+
from typing import Tuple
|
| 34 |
+
from typing import Type
|
| 35 |
+
from typing import TypeVar
|
| 36 |
+
from typing import Union
|
| 37 |
+
|
| 38 |
+
import pluggy
|
| 39 |
+
|
| 40 |
+
import _pytest
|
| 41 |
+
from _pytest._code.source import findsource
|
| 42 |
+
from _pytest._code.source import getrawcode
|
| 43 |
+
from _pytest._code.source import getstatementrange_ast
|
| 44 |
+
from _pytest._code.source import Source
|
| 45 |
+
from _pytest._io import TerminalWriter
|
| 46 |
+
from _pytest._io.saferepr import safeformat
|
| 47 |
+
from _pytest._io.saferepr import saferepr
|
| 48 |
+
from _pytest.compat import get_real_func
|
| 49 |
+
from _pytest.deprecated import check_ispytest
|
| 50 |
+
from _pytest.pathlib import absolutepath
|
| 51 |
+
from _pytest.pathlib import bestrelpath
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
if sys.version_info < (3, 11):
|
| 55 |
+
from exceptiongroup import BaseExceptionGroup
|
| 56 |
+
|
| 57 |
+
TracebackStyle = Literal["long", "short", "line", "no", "native", "value", "auto"]
|
| 58 |
+
|
| 59 |
+
EXCEPTION_OR_MORE = Union[Type[BaseException], Tuple[Type[BaseException], ...]]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class Code:
|
| 63 |
+
"""Wrapper around Python code objects."""
|
| 64 |
+
|
| 65 |
+
__slots__ = ("raw",)
|
| 66 |
+
|
| 67 |
+
def __init__(self, obj: CodeType) -> None:
|
| 68 |
+
self.raw = obj
|
| 69 |
+
|
| 70 |
+
@classmethod
|
| 71 |
+
def from_function(cls, obj: object) -> Code:
|
| 72 |
+
return cls(getrawcode(obj))
|
| 73 |
+
|
| 74 |
+
def __eq__(self, other):
|
| 75 |
+
return self.raw == other.raw
|
| 76 |
+
|
| 77 |
+
# Ignore type because of https://github.com/python/mypy/issues/4266.
|
| 78 |
+
__hash__ = None # type: ignore
|
| 79 |
+
|
| 80 |
+
@property
|
| 81 |
+
def firstlineno(self) -> int:
|
| 82 |
+
return self.raw.co_firstlineno - 1
|
| 83 |
+
|
| 84 |
+
@property
|
| 85 |
+
def name(self) -> str:
|
| 86 |
+
return self.raw.co_name
|
| 87 |
+
|
| 88 |
+
@property
|
| 89 |
+
def path(self) -> Path | str:
|
| 90 |
+
"""Return a path object pointing to source code, or an ``str`` in
|
| 91 |
+
case of ``OSError`` / non-existing file."""
|
| 92 |
+
if not self.raw.co_filename:
|
| 93 |
+
return ""
|
| 94 |
+
try:
|
| 95 |
+
p = absolutepath(self.raw.co_filename)
|
| 96 |
+
# maybe don't try this checking
|
| 97 |
+
if not p.exists():
|
| 98 |
+
raise OSError("path check failed.")
|
| 99 |
+
return p
|
| 100 |
+
except OSError:
|
| 101 |
+
# XXX maybe try harder like the weird logic
|
| 102 |
+
# in the standard lib [linecache.updatecache] does?
|
| 103 |
+
return self.raw.co_filename
|
| 104 |
+
|
| 105 |
+
@property
|
| 106 |
+
def fullsource(self) -> Source | None:
|
| 107 |
+
"""Return a _pytest._code.Source object for the full source file of the code."""
|
| 108 |
+
full, _ = findsource(self.raw)
|
| 109 |
+
return full
|
| 110 |
+
|
| 111 |
+
def source(self) -> Source:
|
| 112 |
+
"""Return a _pytest._code.Source object for the code object's source only."""
|
| 113 |
+
# return source only for that part of code
|
| 114 |
+
return Source(self.raw)
|
| 115 |
+
|
| 116 |
+
def getargs(self, var: bool = False) -> tuple[str, ...]:
|
| 117 |
+
"""Return a tuple with the argument names for the code object.
|
| 118 |
+
|
| 119 |
+
If 'var' is set True also return the names of the variable and
|
| 120 |
+
keyword arguments when present.
|
| 121 |
+
"""
|
| 122 |
+
# Handy shortcut for getting args.
|
| 123 |
+
raw = self.raw
|
| 124 |
+
argcount = raw.co_argcount
|
| 125 |
+
if var:
|
| 126 |
+
argcount += raw.co_flags & CO_VARARGS
|
| 127 |
+
argcount += raw.co_flags & CO_VARKEYWORDS
|
| 128 |
+
return raw.co_varnames[:argcount]
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class Frame:
|
| 132 |
+
"""Wrapper around a Python frame holding f_locals and f_globals
|
| 133 |
+
in which expressions can be evaluated."""
|
| 134 |
+
|
| 135 |
+
__slots__ = ("raw",)
|
| 136 |
+
|
| 137 |
+
def __init__(self, frame: FrameType) -> None:
|
| 138 |
+
self.raw = frame
|
| 139 |
+
|
| 140 |
+
@property
|
| 141 |
+
def lineno(self) -> int:
|
| 142 |
+
return self.raw.f_lineno - 1
|
| 143 |
+
|
| 144 |
+
@property
|
| 145 |
+
def f_globals(self) -> dict[str, Any]:
|
| 146 |
+
return self.raw.f_globals
|
| 147 |
+
|
| 148 |
+
@property
|
| 149 |
+
def f_locals(self) -> dict[str, Any]:
|
| 150 |
+
return self.raw.f_locals
|
| 151 |
+
|
| 152 |
+
@property
|
| 153 |
+
def code(self) -> Code:
|
| 154 |
+
return Code(self.raw.f_code)
|
| 155 |
+
|
| 156 |
+
@property
|
| 157 |
+
def statement(self) -> Source:
|
| 158 |
+
"""Statement this frame is at."""
|
| 159 |
+
if self.code.fullsource is None:
|
| 160 |
+
return Source("")
|
| 161 |
+
return self.code.fullsource.getstatement(self.lineno)
|
| 162 |
+
|
| 163 |
+
def eval(self, code, **vars):
|
| 164 |
+
"""Evaluate 'code' in the frame.
|
| 165 |
+
|
| 166 |
+
'vars' are optional additional local variables.
|
| 167 |
+
|
| 168 |
+
Returns the result of the evaluation.
|
| 169 |
+
"""
|
| 170 |
+
f_locals = self.f_locals.copy()
|
| 171 |
+
f_locals.update(vars)
|
| 172 |
+
return eval(code, self.f_globals, f_locals)
|
| 173 |
+
|
| 174 |
+
def repr(self, object: object) -> str:
|
| 175 |
+
"""Return a 'safe' (non-recursive, one-line) string repr for 'object'."""
|
| 176 |
+
return saferepr(object)
|
| 177 |
+
|
| 178 |
+
def getargs(self, var: bool = False):
|
| 179 |
+
"""Return a list of tuples (name, value) for all arguments.
|
| 180 |
+
|
| 181 |
+
If 'var' is set True, also include the variable and keyword arguments
|
| 182 |
+
when present.
|
| 183 |
+
"""
|
| 184 |
+
retval = []
|
| 185 |
+
for arg in self.code.getargs(var):
|
| 186 |
+
try:
|
| 187 |
+
retval.append((arg, self.f_locals[arg]))
|
| 188 |
+
except KeyError:
|
| 189 |
+
pass # this can occur when using Psyco
|
| 190 |
+
return retval
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class TracebackEntry:
|
| 194 |
+
"""A single entry in a Traceback."""
|
| 195 |
+
|
| 196 |
+
__slots__ = ("_rawentry", "_repr_style")
|
| 197 |
+
|
| 198 |
+
def __init__(
|
| 199 |
+
self,
|
| 200 |
+
rawentry: TracebackType,
|
| 201 |
+
repr_style: Literal["short", "long"] | None = None,
|
| 202 |
+
) -> None:
|
| 203 |
+
self._rawentry: Final = rawentry
|
| 204 |
+
self._repr_style: Final = repr_style
|
| 205 |
+
|
| 206 |
+
def with_repr_style(
|
| 207 |
+
self, repr_style: Literal["short", "long"] | None
|
| 208 |
+
) -> TracebackEntry:
|
| 209 |
+
return TracebackEntry(self._rawentry, repr_style)
|
| 210 |
+
|
| 211 |
+
@property
|
| 212 |
+
def lineno(self) -> int:
|
| 213 |
+
return self._rawentry.tb_lineno - 1
|
| 214 |
+
|
| 215 |
+
@property
|
| 216 |
+
def frame(self) -> Frame:
|
| 217 |
+
return Frame(self._rawentry.tb_frame)
|
| 218 |
+
|
| 219 |
+
@property
|
| 220 |
+
def relline(self) -> int:
|
| 221 |
+
return self.lineno - self.frame.code.firstlineno
|
| 222 |
+
|
| 223 |
+
def __repr__(self) -> str:
|
| 224 |
+
return "<TracebackEntry %s:%d>" % (self.frame.code.path, self.lineno + 1)
|
| 225 |
+
|
| 226 |
+
@property
|
| 227 |
+
def statement(self) -> Source:
|
| 228 |
+
"""_pytest._code.Source object for the current statement."""
|
| 229 |
+
source = self.frame.code.fullsource
|
| 230 |
+
assert source is not None
|
| 231 |
+
return source.getstatement(self.lineno)
|
| 232 |
+
|
| 233 |
+
@property
|
| 234 |
+
def path(self) -> Path | str:
|
| 235 |
+
"""Path to the source code."""
|
| 236 |
+
return self.frame.code.path
|
| 237 |
+
|
| 238 |
+
@property
|
| 239 |
+
def locals(self) -> dict[str, Any]:
|
| 240 |
+
"""Locals of underlying frame."""
|
| 241 |
+
return self.frame.f_locals
|
| 242 |
+
|
| 243 |
+
def getfirstlinesource(self) -> int:
|
| 244 |
+
return self.frame.code.firstlineno
|
| 245 |
+
|
| 246 |
+
def getsource(
|
| 247 |
+
self, astcache: dict[str | Path, ast.AST] | None = None
|
| 248 |
+
) -> Source | None:
|
| 249 |
+
"""Return failing source code."""
|
| 250 |
+
# we use the passed in astcache to not reparse asttrees
|
| 251 |
+
# within exception info printing
|
| 252 |
+
source = self.frame.code.fullsource
|
| 253 |
+
if source is None:
|
| 254 |
+
return None
|
| 255 |
+
key = astnode = None
|
| 256 |
+
if astcache is not None:
|
| 257 |
+
key = self.frame.code.path
|
| 258 |
+
if key is not None:
|
| 259 |
+
astnode = astcache.get(key, None)
|
| 260 |
+
start = self.getfirstlinesource()
|
| 261 |
+
try:
|
| 262 |
+
astnode, _, end = getstatementrange_ast(
|
| 263 |
+
self.lineno, source, astnode=astnode
|
| 264 |
+
)
|
| 265 |
+
except SyntaxError:
|
| 266 |
+
end = self.lineno + 1
|
| 267 |
+
else:
|
| 268 |
+
if key is not None and astcache is not None:
|
| 269 |
+
astcache[key] = astnode
|
| 270 |
+
return source[start:end]
|
| 271 |
+
|
| 272 |
+
source = property(getsource)
|
| 273 |
+
|
| 274 |
+
def ishidden(self, excinfo: ExceptionInfo[BaseException] | None) -> bool:
|
| 275 |
+
"""Return True if the current frame has a var __tracebackhide__
|
| 276 |
+
resolving to True.
|
| 277 |
+
|
| 278 |
+
If __tracebackhide__ is a callable, it gets called with the
|
| 279 |
+
ExceptionInfo instance and can decide whether to hide the traceback.
|
| 280 |
+
|
| 281 |
+
Mostly for internal use.
|
| 282 |
+
"""
|
| 283 |
+
tbh: bool | Callable[[ExceptionInfo[BaseException] | None], bool] = False
|
| 284 |
+
for maybe_ns_dct in (self.frame.f_locals, self.frame.f_globals):
|
| 285 |
+
# in normal cases, f_locals and f_globals are dictionaries
|
| 286 |
+
# however via `exec(...)` / `eval(...)` they can be other types
|
| 287 |
+
# (even incorrect types!).
|
| 288 |
+
# as such, we suppress all exceptions while accessing __tracebackhide__
|
| 289 |
+
try:
|
| 290 |
+
tbh = maybe_ns_dct["__tracebackhide__"]
|
| 291 |
+
except Exception:
|
| 292 |
+
pass
|
| 293 |
+
else:
|
| 294 |
+
break
|
| 295 |
+
if tbh and callable(tbh):
|
| 296 |
+
return tbh(excinfo)
|
| 297 |
+
return tbh
|
| 298 |
+
|
| 299 |
+
def __str__(self) -> str:
|
| 300 |
+
name = self.frame.code.name
|
| 301 |
+
try:
|
| 302 |
+
line = str(self.statement).lstrip()
|
| 303 |
+
except KeyboardInterrupt:
|
| 304 |
+
raise
|
| 305 |
+
except BaseException:
|
| 306 |
+
line = "???"
|
| 307 |
+
# This output does not quite match Python's repr for traceback entries,
|
| 308 |
+
# but changing it to do so would break certain plugins. See
|
| 309 |
+
# https://github.com/pytest-dev/pytest/pull/7535/ for details.
|
| 310 |
+
return " File %r:%d in %s\n %s\n" % (
|
| 311 |
+
str(self.path),
|
| 312 |
+
self.lineno + 1,
|
| 313 |
+
name,
|
| 314 |
+
line,
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
@property
|
| 318 |
+
def name(self) -> str:
|
| 319 |
+
"""co_name of underlying code."""
|
| 320 |
+
return self.frame.code.raw.co_name
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
class Traceback(List[TracebackEntry]):
|
| 324 |
+
"""Traceback objects encapsulate and offer higher level access to Traceback entries."""
|
| 325 |
+
|
| 326 |
+
def __init__(
|
| 327 |
+
self,
|
| 328 |
+
tb: TracebackType | Iterable[TracebackEntry],
|
| 329 |
+
) -> None:
|
| 330 |
+
"""Initialize from given python traceback object and ExceptionInfo."""
|
| 331 |
+
if isinstance(tb, TracebackType):
|
| 332 |
+
|
| 333 |
+
def f(cur: TracebackType) -> Iterable[TracebackEntry]:
|
| 334 |
+
cur_: TracebackType | None = cur
|
| 335 |
+
while cur_ is not None:
|
| 336 |
+
yield TracebackEntry(cur_)
|
| 337 |
+
cur_ = cur_.tb_next
|
| 338 |
+
|
| 339 |
+
super().__init__(f(tb))
|
| 340 |
+
else:
|
| 341 |
+
super().__init__(tb)
|
| 342 |
+
|
| 343 |
+
def cut(
|
| 344 |
+
self,
|
| 345 |
+
path: os.PathLike[str] | str | None = None,
|
| 346 |
+
lineno: int | None = None,
|
| 347 |
+
firstlineno: int | None = None,
|
| 348 |
+
excludepath: os.PathLike[str] | None = None,
|
| 349 |
+
) -> Traceback:
|
| 350 |
+
"""Return a Traceback instance wrapping part of this Traceback.
|
| 351 |
+
|
| 352 |
+
By providing any combination of path, lineno and firstlineno, the
|
| 353 |
+
first frame to start the to-be-returned traceback is determined.
|
| 354 |
+
|
| 355 |
+
This allows cutting the first part of a Traceback instance e.g.
|
| 356 |
+
for formatting reasons (removing some uninteresting bits that deal
|
| 357 |
+
with handling of the exception/traceback).
|
| 358 |
+
"""
|
| 359 |
+
path_ = None if path is None else os.fspath(path)
|
| 360 |
+
excludepath_ = None if excludepath is None else os.fspath(excludepath)
|
| 361 |
+
for x in self:
|
| 362 |
+
code = x.frame.code
|
| 363 |
+
codepath = code.path
|
| 364 |
+
if path is not None and str(codepath) != path_:
|
| 365 |
+
continue
|
| 366 |
+
if (
|
| 367 |
+
excludepath is not None
|
| 368 |
+
and isinstance(codepath, Path)
|
| 369 |
+
and excludepath_ in (str(p) for p in codepath.parents) # type: ignore[operator]
|
| 370 |
+
):
|
| 371 |
+
continue
|
| 372 |
+
if lineno is not None and x.lineno != lineno:
|
| 373 |
+
continue
|
| 374 |
+
if firstlineno is not None and x.frame.code.firstlineno != firstlineno:
|
| 375 |
+
continue
|
| 376 |
+
return Traceback(x._rawentry)
|
| 377 |
+
return self
|
| 378 |
+
|
| 379 |
+
@overload
|
| 380 |
+
def __getitem__(self, key: SupportsIndex) -> TracebackEntry: ...
|
| 381 |
+
|
| 382 |
+
@overload
|
| 383 |
+
def __getitem__(self, key: slice) -> Traceback: ...
|
| 384 |
+
|
| 385 |
+
def __getitem__(self, key: SupportsIndex | slice) -> TracebackEntry | Traceback:
|
| 386 |
+
if isinstance(key, slice):
|
| 387 |
+
return self.__class__(super().__getitem__(key))
|
| 388 |
+
else:
|
| 389 |
+
return super().__getitem__(key)
|
| 390 |
+
|
| 391 |
+
def filter(
|
| 392 |
+
self,
|
| 393 |
+
excinfo_or_fn: ExceptionInfo[BaseException] | Callable[[TracebackEntry], bool],
|
| 394 |
+
/,
|
| 395 |
+
) -> Traceback:
|
| 396 |
+
"""Return a Traceback instance with certain items removed.
|
| 397 |
+
|
| 398 |
+
If the filter is an `ExceptionInfo`, removes all the ``TracebackEntry``s
|
| 399 |
+
which are hidden (see ishidden() above).
|
| 400 |
+
|
| 401 |
+
Otherwise, the filter is a function that gets a single argument, a
|
| 402 |
+
``TracebackEntry`` instance, and should return True when the item should
|
| 403 |
+
be added to the ``Traceback``, False when not.
|
| 404 |
+
"""
|
| 405 |
+
if isinstance(excinfo_or_fn, ExceptionInfo):
|
| 406 |
+
fn = lambda x: not x.ishidden(excinfo_or_fn) # noqa: E731
|
| 407 |
+
else:
|
| 408 |
+
fn = excinfo_or_fn
|
| 409 |
+
return Traceback(filter(fn, self))
|
| 410 |
+
|
| 411 |
+
def recursionindex(self) -> int | None:
|
| 412 |
+
"""Return the index of the frame/TracebackEntry where recursion originates if
|
| 413 |
+
appropriate, None if no recursion occurred."""
|
| 414 |
+
cache: dict[tuple[Any, int, int], list[dict[str, Any]]] = {}
|
| 415 |
+
for i, entry in enumerate(self):
|
| 416 |
+
# id for the code.raw is needed to work around
|
| 417 |
+
# the strange metaprogramming in the decorator lib from pypi
|
| 418 |
+
# which generates code objects that have hash/value equality
|
| 419 |
+
# XXX needs a test
|
| 420 |
+
key = entry.frame.code.path, id(entry.frame.code.raw), entry.lineno
|
| 421 |
+
values = cache.setdefault(key, [])
|
| 422 |
+
# Since Python 3.13 f_locals is a proxy, freeze it.
|
| 423 |
+
loc = dict(entry.frame.f_locals)
|
| 424 |
+
if values:
|
| 425 |
+
for otherloc in values:
|
| 426 |
+
if otherloc == loc:
|
| 427 |
+
return i
|
| 428 |
+
values.append(loc)
|
| 429 |
+
return None
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
E = TypeVar("E", bound=BaseException, covariant=True)
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
@final
|
| 436 |
+
@dataclasses.dataclass
|
| 437 |
+
class ExceptionInfo(Generic[E]):
|
| 438 |
+
"""Wraps sys.exc_info() objects and offers help for navigating the traceback."""
|
| 439 |
+
|
| 440 |
+
_assert_start_repr: ClassVar = "AssertionError('assert "
|
| 441 |
+
|
| 442 |
+
_excinfo: tuple[type[E], E, TracebackType] | None
|
| 443 |
+
_striptext: str
|
| 444 |
+
_traceback: Traceback | None
|
| 445 |
+
|
| 446 |
+
def __init__(
|
| 447 |
+
self,
|
| 448 |
+
excinfo: tuple[type[E], E, TracebackType] | None,
|
| 449 |
+
striptext: str = "",
|
| 450 |
+
traceback: Traceback | None = None,
|
| 451 |
+
*,
|
| 452 |
+
_ispytest: bool = False,
|
| 453 |
+
) -> None:
|
| 454 |
+
check_ispytest(_ispytest)
|
| 455 |
+
self._excinfo = excinfo
|
| 456 |
+
self._striptext = striptext
|
| 457 |
+
self._traceback = traceback
|
| 458 |
+
|
| 459 |
+
@classmethod
|
| 460 |
+
def from_exception(
|
| 461 |
+
cls,
|
| 462 |
+
# Ignoring error: "Cannot use a covariant type variable as a parameter".
|
| 463 |
+
# This is OK to ignore because this class is (conceptually) readonly.
|
| 464 |
+
# See https://github.com/python/mypy/issues/7049.
|
| 465 |
+
exception: E, # type: ignore[misc]
|
| 466 |
+
exprinfo: str | None = None,
|
| 467 |
+
) -> ExceptionInfo[E]:
|
| 468 |
+
"""Return an ExceptionInfo for an existing exception.
|
| 469 |
+
|
| 470 |
+
The exception must have a non-``None`` ``__traceback__`` attribute,
|
| 471 |
+
otherwise this function fails with an assertion error. This means that
|
| 472 |
+
the exception must have been raised, or added a traceback with the
|
| 473 |
+
:py:meth:`~BaseException.with_traceback()` method.
|
| 474 |
+
|
| 475 |
+
:param exprinfo:
|
| 476 |
+
A text string helping to determine if we should strip
|
| 477 |
+
``AssertionError`` from the output. Defaults to the exception
|
| 478 |
+
message/``__str__()``.
|
| 479 |
+
|
| 480 |
+
.. versionadded:: 7.4
|
| 481 |
+
"""
|
| 482 |
+
assert exception.__traceback__, (
|
| 483 |
+
"Exceptions passed to ExcInfo.from_exception(...)"
|
| 484 |
+
" must have a non-None __traceback__."
|
| 485 |
+
)
|
| 486 |
+
exc_info = (type(exception), exception, exception.__traceback__)
|
| 487 |
+
return cls.from_exc_info(exc_info, exprinfo)
|
| 488 |
+
|
| 489 |
+
@classmethod
|
| 490 |
+
def from_exc_info(
|
| 491 |
+
cls,
|
| 492 |
+
exc_info: tuple[type[E], E, TracebackType],
|
| 493 |
+
exprinfo: str | None = None,
|
| 494 |
+
) -> ExceptionInfo[E]:
|
| 495 |
+
"""Like :func:`from_exception`, but using old-style exc_info tuple."""
|
| 496 |
+
_striptext = ""
|
| 497 |
+
if exprinfo is None and isinstance(exc_info[1], AssertionError):
|
| 498 |
+
exprinfo = getattr(exc_info[1], "msg", None)
|
| 499 |
+
if exprinfo is None:
|
| 500 |
+
exprinfo = saferepr(exc_info[1])
|
| 501 |
+
if exprinfo and exprinfo.startswith(cls._assert_start_repr):
|
| 502 |
+
_striptext = "AssertionError: "
|
| 503 |
+
|
| 504 |
+
return cls(exc_info, _striptext, _ispytest=True)
|
| 505 |
+
|
| 506 |
+
@classmethod
|
| 507 |
+
def from_current(cls, exprinfo: str | None = None) -> ExceptionInfo[BaseException]:
|
| 508 |
+
"""Return an ExceptionInfo matching the current traceback.
|
| 509 |
+
|
| 510 |
+
.. warning::
|
| 511 |
+
|
| 512 |
+
Experimental API
|
| 513 |
+
|
| 514 |
+
:param exprinfo:
|
| 515 |
+
A text string helping to determine if we should strip
|
| 516 |
+
``AssertionError`` from the output. Defaults to the exception
|
| 517 |
+
message/``__str__()``.
|
| 518 |
+
"""
|
| 519 |
+
tup = sys.exc_info()
|
| 520 |
+
assert tup[0] is not None, "no current exception"
|
| 521 |
+
assert tup[1] is not None, "no current exception"
|
| 522 |
+
assert tup[2] is not None, "no current exception"
|
| 523 |
+
exc_info = (tup[0], tup[1], tup[2])
|
| 524 |
+
return ExceptionInfo.from_exc_info(exc_info, exprinfo)
|
| 525 |
+
|
| 526 |
+
@classmethod
|
| 527 |
+
def for_later(cls) -> ExceptionInfo[E]:
|
| 528 |
+
"""Return an unfilled ExceptionInfo."""
|
| 529 |
+
return cls(None, _ispytest=True)
|
| 530 |
+
|
| 531 |
+
def fill_unfilled(self, exc_info: tuple[type[E], E, TracebackType]) -> None:
|
| 532 |
+
"""Fill an unfilled ExceptionInfo created with ``for_later()``."""
|
| 533 |
+
assert self._excinfo is None, "ExceptionInfo was already filled"
|
| 534 |
+
self._excinfo = exc_info
|
| 535 |
+
|
| 536 |
+
@property
|
| 537 |
+
def type(self) -> type[E]:
|
| 538 |
+
"""The exception class."""
|
| 539 |
+
assert (
|
| 540 |
+
self._excinfo is not None
|
| 541 |
+
), ".type can only be used after the context manager exits"
|
| 542 |
+
return self._excinfo[0]
|
| 543 |
+
|
| 544 |
+
@property
|
| 545 |
+
def value(self) -> E:
|
| 546 |
+
"""The exception value."""
|
| 547 |
+
assert (
|
| 548 |
+
self._excinfo is not None
|
| 549 |
+
), ".value can only be used after the context manager exits"
|
| 550 |
+
return self._excinfo[1]
|
| 551 |
+
|
| 552 |
+
@property
|
| 553 |
+
def tb(self) -> TracebackType:
|
| 554 |
+
"""The exception raw traceback."""
|
| 555 |
+
assert (
|
| 556 |
+
self._excinfo is not None
|
| 557 |
+
), ".tb can only be used after the context manager exits"
|
| 558 |
+
return self._excinfo[2]
|
| 559 |
+
|
| 560 |
+
@property
|
| 561 |
+
def typename(self) -> str:
|
| 562 |
+
"""The type name of the exception."""
|
| 563 |
+
assert (
|
| 564 |
+
self._excinfo is not None
|
| 565 |
+
), ".typename can only be used after the context manager exits"
|
| 566 |
+
return self.type.__name__
|
| 567 |
+
|
| 568 |
+
@property
|
| 569 |
+
def traceback(self) -> Traceback:
|
| 570 |
+
"""The traceback."""
|
| 571 |
+
if self._traceback is None:
|
| 572 |
+
self._traceback = Traceback(self.tb)
|
| 573 |
+
return self._traceback
|
| 574 |
+
|
| 575 |
+
@traceback.setter
|
| 576 |
+
def traceback(self, value: Traceback) -> None:
|
| 577 |
+
self._traceback = value
|
| 578 |
+
|
| 579 |
+
def __repr__(self) -> str:
|
| 580 |
+
if self._excinfo is None:
|
| 581 |
+
return "<ExceptionInfo for raises contextmanager>"
|
| 582 |
+
return f"<{self.__class__.__name__} {saferepr(self._excinfo[1])} tblen={len(self.traceback)}>"
|
| 583 |
+
|
| 584 |
+
def exconly(self, tryshort: bool = False) -> str:
|
| 585 |
+
"""Return the exception as a string.
|
| 586 |
+
|
| 587 |
+
When 'tryshort' resolves to True, and the exception is an
|
| 588 |
+
AssertionError, only the actual exception part of the exception
|
| 589 |
+
representation is returned (so 'AssertionError: ' is removed from
|
| 590 |
+
the beginning).
|
| 591 |
+
"""
|
| 592 |
+
lines = format_exception_only(self.type, self.value)
|
| 593 |
+
text = "".join(lines)
|
| 594 |
+
text = text.rstrip()
|
| 595 |
+
if tryshort:
|
| 596 |
+
if text.startswith(self._striptext):
|
| 597 |
+
text = text[len(self._striptext) :]
|
| 598 |
+
return text
|
| 599 |
+
|
| 600 |
+
def errisinstance(self, exc: EXCEPTION_OR_MORE) -> bool:
|
| 601 |
+
"""Return True if the exception is an instance of exc.
|
| 602 |
+
|
| 603 |
+
Consider using ``isinstance(excinfo.value, exc)`` instead.
|
| 604 |
+
"""
|
| 605 |
+
return isinstance(self.value, exc)
|
| 606 |
+
|
| 607 |
+
def _getreprcrash(self) -> ReprFileLocation | None:
|
| 608 |
+
# Find last non-hidden traceback entry that led to the exception of the
|
| 609 |
+
# traceback, or None if all hidden.
|
| 610 |
+
for i in range(-1, -len(self.traceback) - 1, -1):
|
| 611 |
+
entry = self.traceback[i]
|
| 612 |
+
if not entry.ishidden(self):
|
| 613 |
+
path, lineno = entry.frame.code.raw.co_filename, entry.lineno
|
| 614 |
+
exconly = self.exconly(tryshort=True)
|
| 615 |
+
return ReprFileLocation(path, lineno + 1, exconly)
|
| 616 |
+
return None
|
| 617 |
+
|
| 618 |
+
def getrepr(
|
| 619 |
+
self,
|
| 620 |
+
showlocals: bool = False,
|
| 621 |
+
style: TracebackStyle = "long",
|
| 622 |
+
abspath: bool = False,
|
| 623 |
+
tbfilter: bool
|
| 624 |
+
| Callable[[ExceptionInfo[BaseException]], _pytest._code.code.Traceback] = True,
|
| 625 |
+
funcargs: bool = False,
|
| 626 |
+
truncate_locals: bool = True,
|
| 627 |
+
truncate_args: bool = True,
|
| 628 |
+
chain: bool = True,
|
| 629 |
+
) -> ReprExceptionInfo | ExceptionChainRepr:
|
| 630 |
+
"""Return str()able representation of this exception info.
|
| 631 |
+
|
| 632 |
+
:param bool showlocals:
|
| 633 |
+
Show locals per traceback entry.
|
| 634 |
+
Ignored if ``style=="native"``.
|
| 635 |
+
|
| 636 |
+
:param str style:
|
| 637 |
+
long|short|line|no|native|value traceback style.
|
| 638 |
+
|
| 639 |
+
:param bool abspath:
|
| 640 |
+
If paths should be changed to absolute or left unchanged.
|
| 641 |
+
|
| 642 |
+
:param tbfilter:
|
| 643 |
+
A filter for traceback entries.
|
| 644 |
+
|
| 645 |
+
* If false, don't hide any entries.
|
| 646 |
+
* If true, hide internal entries and entries that contain a local
|
| 647 |
+
variable ``__tracebackhide__ = True``.
|
| 648 |
+
* If a callable, delegates the filtering to the callable.
|
| 649 |
+
|
| 650 |
+
Ignored if ``style`` is ``"native"``.
|
| 651 |
+
|
| 652 |
+
:param bool funcargs:
|
| 653 |
+
Show fixtures ("funcargs" for legacy purposes) per traceback entry.
|
| 654 |
+
|
| 655 |
+
:param bool truncate_locals:
|
| 656 |
+
With ``showlocals==True``, make sure locals can be safely represented as strings.
|
| 657 |
+
|
| 658 |
+
:param bool truncate_args:
|
| 659 |
+
With ``showargs==True``, make sure args can be safely represented as strings.
|
| 660 |
+
|
| 661 |
+
:param bool chain:
|
| 662 |
+
If chained exceptions in Python 3 should be shown.
|
| 663 |
+
|
| 664 |
+
.. versionchanged:: 3.9
|
| 665 |
+
|
| 666 |
+
Added the ``chain`` parameter.
|
| 667 |
+
"""
|
| 668 |
+
if style == "native":
|
| 669 |
+
return ReprExceptionInfo(
|
| 670 |
+
reprtraceback=ReprTracebackNative(
|
| 671 |
+
traceback.format_exception(
|
| 672 |
+
self.type,
|
| 673 |
+
self.value,
|
| 674 |
+
self.traceback[0]._rawentry if self.traceback else None,
|
| 675 |
+
)
|
| 676 |
+
),
|
| 677 |
+
reprcrash=self._getreprcrash(),
|
| 678 |
+
)
|
| 679 |
+
|
| 680 |
+
fmt = FormattedExcinfo(
|
| 681 |
+
showlocals=showlocals,
|
| 682 |
+
style=style,
|
| 683 |
+
abspath=abspath,
|
| 684 |
+
tbfilter=tbfilter,
|
| 685 |
+
funcargs=funcargs,
|
| 686 |
+
truncate_locals=truncate_locals,
|
| 687 |
+
truncate_args=truncate_args,
|
| 688 |
+
chain=chain,
|
| 689 |
+
)
|
| 690 |
+
return fmt.repr_excinfo(self)
|
| 691 |
+
|
| 692 |
+
def _stringify_exception(self, exc: BaseException) -> str:
|
| 693 |
+
try:
|
| 694 |
+
notes = getattr(exc, "__notes__", [])
|
| 695 |
+
except KeyError:
|
| 696 |
+
# Workaround for https://github.com/python/cpython/issues/98778 on
|
| 697 |
+
# Python <= 3.9, and some 3.10 and 3.11 patch versions.
|
| 698 |
+
HTTPError = getattr(sys.modules.get("urllib.error", None), "HTTPError", ())
|
| 699 |
+
if sys.version_info < (3, 12) and isinstance(exc, HTTPError):
|
| 700 |
+
notes = []
|
| 701 |
+
else:
|
| 702 |
+
raise
|
| 703 |
+
|
| 704 |
+
return "\n".join(
|
| 705 |
+
[
|
| 706 |
+
str(exc),
|
| 707 |
+
*notes,
|
| 708 |
+
]
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
def match(self, regexp: str | Pattern[str]) -> Literal[True]:
|
| 712 |
+
"""Check whether the regular expression `regexp` matches the string
|
| 713 |
+
representation of the exception using :func:`python:re.search`.
|
| 714 |
+
|
| 715 |
+
If it matches `True` is returned, otherwise an `AssertionError` is raised.
|
| 716 |
+
"""
|
| 717 |
+
__tracebackhide__ = True
|
| 718 |
+
value = self._stringify_exception(self.value)
|
| 719 |
+
msg = f"Regex pattern did not match.\n Regex: {regexp!r}\n Input: {value!r}"
|
| 720 |
+
if regexp == value:
|
| 721 |
+
msg += "\n Did you mean to `re.escape()` the regex?"
|
| 722 |
+
assert re.search(regexp, value), msg
|
| 723 |
+
# Return True to allow for "assert excinfo.match()".
|
| 724 |
+
return True
|
| 725 |
+
|
| 726 |
+
def _group_contains(
|
| 727 |
+
self,
|
| 728 |
+
exc_group: BaseExceptionGroup[BaseException],
|
| 729 |
+
expected_exception: EXCEPTION_OR_MORE,
|
| 730 |
+
match: str | Pattern[str] | None,
|
| 731 |
+
target_depth: int | None = None,
|
| 732 |
+
current_depth: int = 1,
|
| 733 |
+
) -> bool:
|
| 734 |
+
"""Return `True` if a `BaseExceptionGroup` contains a matching exception."""
|
| 735 |
+
if (target_depth is not None) and (current_depth > target_depth):
|
| 736 |
+
# already descended past the target depth
|
| 737 |
+
return False
|
| 738 |
+
for exc in exc_group.exceptions:
|
| 739 |
+
if isinstance(exc, BaseExceptionGroup):
|
| 740 |
+
if self._group_contains(
|
| 741 |
+
exc, expected_exception, match, target_depth, current_depth + 1
|
| 742 |
+
):
|
| 743 |
+
return True
|
| 744 |
+
if (target_depth is not None) and (current_depth != target_depth):
|
| 745 |
+
# not at the target depth, no match
|
| 746 |
+
continue
|
| 747 |
+
if not isinstance(exc, expected_exception):
|
| 748 |
+
continue
|
| 749 |
+
if match is not None:
|
| 750 |
+
value = self._stringify_exception(exc)
|
| 751 |
+
if not re.search(match, value):
|
| 752 |
+
continue
|
| 753 |
+
return True
|
| 754 |
+
return False
|
| 755 |
+
|
| 756 |
+
def group_contains(
|
| 757 |
+
self,
|
| 758 |
+
expected_exception: EXCEPTION_OR_MORE,
|
| 759 |
+
*,
|
| 760 |
+
match: str | Pattern[str] | None = None,
|
| 761 |
+
depth: int | None = None,
|
| 762 |
+
) -> bool:
|
| 763 |
+
"""Check whether a captured exception group contains a matching exception.
|
| 764 |
+
|
| 765 |
+
:param Type[BaseException] | Tuple[Type[BaseException]] expected_exception:
|
| 766 |
+
The expected exception type, or a tuple if one of multiple possible
|
| 767 |
+
exception types are expected.
|
| 768 |
+
|
| 769 |
+
:param str | Pattern[str] | None match:
|
| 770 |
+
If specified, a string containing a regular expression,
|
| 771 |
+
or a regular expression object, that is tested against the string
|
| 772 |
+
representation of the exception and its `PEP-678 <https://peps.python.org/pep-0678/>` `__notes__`
|
| 773 |
+
using :func:`re.search`.
|
| 774 |
+
|
| 775 |
+
To match a literal string that may contain :ref:`special characters
|
| 776 |
+
<re-syntax>`, the pattern can first be escaped with :func:`re.escape`.
|
| 777 |
+
|
| 778 |
+
:param Optional[int] depth:
|
| 779 |
+
If `None`, will search for a matching exception at any nesting depth.
|
| 780 |
+
If >= 1, will only match an exception if it's at the specified depth (depth = 1 being
|
| 781 |
+
the exceptions contained within the topmost exception group).
|
| 782 |
+
|
| 783 |
+
.. versionadded:: 8.0
|
| 784 |
+
"""
|
| 785 |
+
msg = "Captured exception is not an instance of `BaseExceptionGroup`"
|
| 786 |
+
assert isinstance(self.value, BaseExceptionGroup), msg
|
| 787 |
+
msg = "`depth` must be >= 1 if specified"
|
| 788 |
+
assert (depth is None) or (depth >= 1), msg
|
| 789 |
+
return self._group_contains(self.value, expected_exception, match, depth)
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
@dataclasses.dataclass
|
| 793 |
+
class FormattedExcinfo:
|
| 794 |
+
"""Presenting information about failing Functions and Generators."""
|
| 795 |
+
|
| 796 |
+
# for traceback entries
|
| 797 |
+
flow_marker: ClassVar = ">"
|
| 798 |
+
fail_marker: ClassVar = "E"
|
| 799 |
+
|
| 800 |
+
showlocals: bool = False
|
| 801 |
+
style: TracebackStyle = "long"
|
| 802 |
+
abspath: bool = True
|
| 803 |
+
tbfilter: bool | Callable[[ExceptionInfo[BaseException]], Traceback] = True
|
| 804 |
+
funcargs: bool = False
|
| 805 |
+
truncate_locals: bool = True
|
| 806 |
+
truncate_args: bool = True
|
| 807 |
+
chain: bool = True
|
| 808 |
+
astcache: dict[str | Path, ast.AST] = dataclasses.field(
|
| 809 |
+
default_factory=dict, init=False, repr=False
|
| 810 |
+
)
|
| 811 |
+
|
| 812 |
+
def _getindent(self, source: Source) -> int:
|
| 813 |
+
# Figure out indent for the given source.
|
| 814 |
+
try:
|
| 815 |
+
s = str(source.getstatement(len(source) - 1))
|
| 816 |
+
except KeyboardInterrupt:
|
| 817 |
+
raise
|
| 818 |
+
except BaseException:
|
| 819 |
+
try:
|
| 820 |
+
s = str(source[-1])
|
| 821 |
+
except KeyboardInterrupt:
|
| 822 |
+
raise
|
| 823 |
+
except BaseException:
|
| 824 |
+
return 0
|
| 825 |
+
return 4 + (len(s) - len(s.lstrip()))
|
| 826 |
+
|
| 827 |
+
def _getentrysource(self, entry: TracebackEntry) -> Source | None:
|
| 828 |
+
source = entry.getsource(self.astcache)
|
| 829 |
+
if source is not None:
|
| 830 |
+
source = source.deindent()
|
| 831 |
+
return source
|
| 832 |
+
|
| 833 |
+
def repr_args(self, entry: TracebackEntry) -> ReprFuncArgs | None:
|
| 834 |
+
if self.funcargs:
|
| 835 |
+
args = []
|
| 836 |
+
for argname, argvalue in entry.frame.getargs(var=True):
|
| 837 |
+
if self.truncate_args:
|
| 838 |
+
str_repr = saferepr(argvalue)
|
| 839 |
+
else:
|
| 840 |
+
str_repr = saferepr(argvalue, maxsize=None)
|
| 841 |
+
args.append((argname, str_repr))
|
| 842 |
+
return ReprFuncArgs(args)
|
| 843 |
+
return None
|
| 844 |
+
|
| 845 |
+
def get_source(
|
| 846 |
+
self,
|
| 847 |
+
source: Source | None,
|
| 848 |
+
line_index: int = -1,
|
| 849 |
+
excinfo: ExceptionInfo[BaseException] | None = None,
|
| 850 |
+
short: bool = False,
|
| 851 |
+
) -> list[str]:
|
| 852 |
+
"""Return formatted and marked up source lines."""
|
| 853 |
+
lines = []
|
| 854 |
+
if source is not None and line_index < 0:
|
| 855 |
+
line_index += len(source)
|
| 856 |
+
if source is None or line_index >= len(source.lines) or line_index < 0:
|
| 857 |
+
# `line_index` could still be outside `range(len(source.lines))` if
|
| 858 |
+
# we're processing AST with pathological position attributes.
|
| 859 |
+
source = Source("???")
|
| 860 |
+
line_index = 0
|
| 861 |
+
space_prefix = " "
|
| 862 |
+
if short:
|
| 863 |
+
lines.append(space_prefix + source.lines[line_index].strip())
|
| 864 |
+
else:
|
| 865 |
+
for line in source.lines[:line_index]:
|
| 866 |
+
lines.append(space_prefix + line)
|
| 867 |
+
lines.append(self.flow_marker + " " + source.lines[line_index])
|
| 868 |
+
for line in source.lines[line_index + 1 :]:
|
| 869 |
+
lines.append(space_prefix + line)
|
| 870 |
+
if excinfo is not None:
|
| 871 |
+
indent = 4 if short else self._getindent(source)
|
| 872 |
+
lines.extend(self.get_exconly(excinfo, indent=indent, markall=True))
|
| 873 |
+
return lines
|
| 874 |
+
|
| 875 |
+
def get_exconly(
|
| 876 |
+
self,
|
| 877 |
+
excinfo: ExceptionInfo[BaseException],
|
| 878 |
+
indent: int = 4,
|
| 879 |
+
markall: bool = False,
|
| 880 |
+
) -> list[str]:
|
| 881 |
+
lines = []
|
| 882 |
+
indentstr = " " * indent
|
| 883 |
+
# Get the real exception information out.
|
| 884 |
+
exlines = excinfo.exconly(tryshort=True).split("\n")
|
| 885 |
+
failindent = self.fail_marker + indentstr[1:]
|
| 886 |
+
for line in exlines:
|
| 887 |
+
lines.append(failindent + line)
|
| 888 |
+
if not markall:
|
| 889 |
+
failindent = indentstr
|
| 890 |
+
return lines
|
| 891 |
+
|
| 892 |
+
def repr_locals(self, locals: Mapping[str, object]) -> ReprLocals | None:
|
| 893 |
+
if self.showlocals:
|
| 894 |
+
lines = []
|
| 895 |
+
keys = [loc for loc in locals if loc[0] != "@"]
|
| 896 |
+
keys.sort()
|
| 897 |
+
for name in keys:
|
| 898 |
+
value = locals[name]
|
| 899 |
+
if name == "__builtins__":
|
| 900 |
+
lines.append("__builtins__ = <builtins>")
|
| 901 |
+
else:
|
| 902 |
+
# This formatting could all be handled by the
|
| 903 |
+
# _repr() function, which is only reprlib.Repr in
|
| 904 |
+
# disguise, so is very configurable.
|
| 905 |
+
if self.truncate_locals:
|
| 906 |
+
str_repr = saferepr(value)
|
| 907 |
+
else:
|
| 908 |
+
str_repr = safeformat(value)
|
| 909 |
+
# if len(str_repr) < 70 or not isinstance(value, (list, tuple, dict)):
|
| 910 |
+
lines.append(f"{name:<10} = {str_repr}")
|
| 911 |
+
# else:
|
| 912 |
+
# self._line("%-10s =\\" % (name,))
|
| 913 |
+
# # XXX
|
| 914 |
+
# pprint.pprint(value, stream=self.excinfowriter)
|
| 915 |
+
return ReprLocals(lines)
|
| 916 |
+
return None
|
| 917 |
+
|
| 918 |
+
def repr_traceback_entry(
|
| 919 |
+
self,
|
| 920 |
+
entry: TracebackEntry | None,
|
| 921 |
+
excinfo: ExceptionInfo[BaseException] | None = None,
|
| 922 |
+
) -> ReprEntry:
|
| 923 |
+
lines: list[str] = []
|
| 924 |
+
style = (
|
| 925 |
+
entry._repr_style
|
| 926 |
+
if entry is not None and entry._repr_style is not None
|
| 927 |
+
else self.style
|
| 928 |
+
)
|
| 929 |
+
if style in ("short", "long") and entry is not None:
|
| 930 |
+
source = self._getentrysource(entry)
|
| 931 |
+
if source is None:
|
| 932 |
+
source = Source("???")
|
| 933 |
+
line_index = 0
|
| 934 |
+
else:
|
| 935 |
+
line_index = entry.lineno - entry.getfirstlinesource()
|
| 936 |
+
short = style == "short"
|
| 937 |
+
reprargs = self.repr_args(entry) if not short else None
|
| 938 |
+
s = self.get_source(source, line_index, excinfo, short=short)
|
| 939 |
+
lines.extend(s)
|
| 940 |
+
if short:
|
| 941 |
+
message = f"in {entry.name}"
|
| 942 |
+
else:
|
| 943 |
+
message = excinfo and excinfo.typename or ""
|
| 944 |
+
entry_path = entry.path
|
| 945 |
+
path = self._makepath(entry_path)
|
| 946 |
+
reprfileloc = ReprFileLocation(path, entry.lineno + 1, message)
|
| 947 |
+
localsrepr = self.repr_locals(entry.locals)
|
| 948 |
+
return ReprEntry(lines, reprargs, localsrepr, reprfileloc, style)
|
| 949 |
+
elif style == "value":
|
| 950 |
+
if excinfo:
|
| 951 |
+
lines.extend(str(excinfo.value).split("\n"))
|
| 952 |
+
return ReprEntry(lines, None, None, None, style)
|
| 953 |
+
else:
|
| 954 |
+
if excinfo:
|
| 955 |
+
lines.extend(self.get_exconly(excinfo, indent=4))
|
| 956 |
+
return ReprEntry(lines, None, None, None, style)
|
| 957 |
+
|
| 958 |
+
def _makepath(self, path: Path | str) -> str:
|
| 959 |
+
if not self.abspath and isinstance(path, Path):
|
| 960 |
+
try:
|
| 961 |
+
np = bestrelpath(Path.cwd(), path)
|
| 962 |
+
except OSError:
|
| 963 |
+
return str(path)
|
| 964 |
+
if len(np) < len(str(path)):
|
| 965 |
+
return np
|
| 966 |
+
return str(path)
|
| 967 |
+
|
| 968 |
+
def repr_traceback(self, excinfo: ExceptionInfo[BaseException]) -> ReprTraceback:
|
| 969 |
+
traceback = excinfo.traceback
|
| 970 |
+
if callable(self.tbfilter):
|
| 971 |
+
traceback = self.tbfilter(excinfo)
|
| 972 |
+
elif self.tbfilter:
|
| 973 |
+
traceback = traceback.filter(excinfo)
|
| 974 |
+
|
| 975 |
+
if isinstance(excinfo.value, RecursionError):
|
| 976 |
+
traceback, extraline = self._truncate_recursive_traceback(traceback)
|
| 977 |
+
else:
|
| 978 |
+
extraline = None
|
| 979 |
+
|
| 980 |
+
if not traceback:
|
| 981 |
+
if extraline is None:
|
| 982 |
+
extraline = "All traceback entries are hidden. Pass `--full-trace` to see hidden and internal frames."
|
| 983 |
+
entries = [self.repr_traceback_entry(None, excinfo)]
|
| 984 |
+
return ReprTraceback(entries, extraline, style=self.style)
|
| 985 |
+
|
| 986 |
+
last = traceback[-1]
|
| 987 |
+
if self.style == "value":
|
| 988 |
+
entries = [self.repr_traceback_entry(last, excinfo)]
|
| 989 |
+
return ReprTraceback(entries, None, style=self.style)
|
| 990 |
+
|
| 991 |
+
entries = [
|
| 992 |
+
self.repr_traceback_entry(entry, excinfo if last == entry else None)
|
| 993 |
+
for entry in traceback
|
| 994 |
+
]
|
| 995 |
+
return ReprTraceback(entries, extraline, style=self.style)
|
| 996 |
+
|
| 997 |
+
def _truncate_recursive_traceback(
|
| 998 |
+
self, traceback: Traceback
|
| 999 |
+
) -> tuple[Traceback, str | None]:
|
| 1000 |
+
"""Truncate the given recursive traceback trying to find the starting
|
| 1001 |
+
point of the recursion.
|
| 1002 |
+
|
| 1003 |
+
The detection is done by going through each traceback entry and
|
| 1004 |
+
finding the point in which the locals of the frame are equal to the
|
| 1005 |
+
locals of a previous frame (see ``recursionindex()``).
|
| 1006 |
+
|
| 1007 |
+
Handle the situation where the recursion process might raise an
|
| 1008 |
+
exception (for example comparing numpy arrays using equality raises a
|
| 1009 |
+
TypeError), in which case we do our best to warn the user of the
|
| 1010 |
+
error and show a limited traceback.
|
| 1011 |
+
"""
|
| 1012 |
+
try:
|
| 1013 |
+
recursionindex = traceback.recursionindex()
|
| 1014 |
+
except Exception as e:
|
| 1015 |
+
max_frames = 10
|
| 1016 |
+
extraline: str | None = (
|
| 1017 |
+
"!!! Recursion error detected, but an error occurred locating the origin of recursion.\n"
|
| 1018 |
+
" The following exception happened when comparing locals in the stack frame:\n"
|
| 1019 |
+
f" {type(e).__name__}: {e!s}\n"
|
| 1020 |
+
f" Displaying first and last {max_frames} stack frames out of {len(traceback)}."
|
| 1021 |
+
)
|
| 1022 |
+
# Type ignored because adding two instances of a List subtype
|
| 1023 |
+
# currently incorrectly has type List instead of the subtype.
|
| 1024 |
+
traceback = traceback[:max_frames] + traceback[-max_frames:] # type: ignore
|
| 1025 |
+
else:
|
| 1026 |
+
if recursionindex is not None:
|
| 1027 |
+
extraline = "!!! Recursion detected (same locals & position)"
|
| 1028 |
+
traceback = traceback[: recursionindex + 1]
|
| 1029 |
+
else:
|
| 1030 |
+
extraline = None
|
| 1031 |
+
|
| 1032 |
+
return traceback, extraline
|
| 1033 |
+
|
| 1034 |
+
def repr_excinfo(self, excinfo: ExceptionInfo[BaseException]) -> ExceptionChainRepr:
|
| 1035 |
+
repr_chain: list[tuple[ReprTraceback, ReprFileLocation | None, str | None]] = []
|
| 1036 |
+
e: BaseException | None = excinfo.value
|
| 1037 |
+
excinfo_: ExceptionInfo[BaseException] | None = excinfo
|
| 1038 |
+
descr = None
|
| 1039 |
+
seen: set[int] = set()
|
| 1040 |
+
while e is not None and id(e) not in seen:
|
| 1041 |
+
seen.add(id(e))
|
| 1042 |
+
|
| 1043 |
+
if excinfo_:
|
| 1044 |
+
# Fall back to native traceback as a temporary workaround until
|
| 1045 |
+
# full support for exception groups added to ExceptionInfo.
|
| 1046 |
+
# See https://github.com/pytest-dev/pytest/issues/9159
|
| 1047 |
+
if isinstance(e, BaseExceptionGroup):
|
| 1048 |
+
reprtraceback: ReprTracebackNative | ReprTraceback = (
|
| 1049 |
+
ReprTracebackNative(
|
| 1050 |
+
traceback.format_exception(
|
| 1051 |
+
type(excinfo_.value),
|
| 1052 |
+
excinfo_.value,
|
| 1053 |
+
excinfo_.traceback[0]._rawentry,
|
| 1054 |
+
)
|
| 1055 |
+
)
|
| 1056 |
+
)
|
| 1057 |
+
else:
|
| 1058 |
+
reprtraceback = self.repr_traceback(excinfo_)
|
| 1059 |
+
reprcrash = excinfo_._getreprcrash()
|
| 1060 |
+
else:
|
| 1061 |
+
# Fallback to native repr if the exception doesn't have a traceback:
|
| 1062 |
+
# ExceptionInfo objects require a full traceback to work.
|
| 1063 |
+
reprtraceback = ReprTracebackNative(
|
| 1064 |
+
traceback.format_exception(type(e), e, None)
|
| 1065 |
+
)
|
| 1066 |
+
reprcrash = None
|
| 1067 |
+
repr_chain += [(reprtraceback, reprcrash, descr)]
|
| 1068 |
+
|
| 1069 |
+
if e.__cause__ is not None and self.chain:
|
| 1070 |
+
e = e.__cause__
|
| 1071 |
+
excinfo_ = ExceptionInfo.from_exception(e) if e.__traceback__ else None
|
| 1072 |
+
descr = "The above exception was the direct cause of the following exception:"
|
| 1073 |
+
elif (
|
| 1074 |
+
e.__context__ is not None and not e.__suppress_context__ and self.chain
|
| 1075 |
+
):
|
| 1076 |
+
e = e.__context__
|
| 1077 |
+
excinfo_ = ExceptionInfo.from_exception(e) if e.__traceback__ else None
|
| 1078 |
+
descr = "During handling of the above exception, another exception occurred:"
|
| 1079 |
+
else:
|
| 1080 |
+
e = None
|
| 1081 |
+
repr_chain.reverse()
|
| 1082 |
+
return ExceptionChainRepr(repr_chain)
|
| 1083 |
+
|
| 1084 |
+
|
| 1085 |
+
@dataclasses.dataclass(eq=False)
|
| 1086 |
+
class TerminalRepr:
|
| 1087 |
+
def __str__(self) -> str:
|
| 1088 |
+
# FYI this is called from pytest-xdist's serialization of exception
|
| 1089 |
+
# information.
|
| 1090 |
+
io = StringIO()
|
| 1091 |
+
tw = TerminalWriter(file=io)
|
| 1092 |
+
self.toterminal(tw)
|
| 1093 |
+
return io.getvalue().strip()
|
| 1094 |
+
|
| 1095 |
+
def __repr__(self) -> str:
|
| 1096 |
+
return f"<{self.__class__} instance at {id(self):0x}>"
|
| 1097 |
+
|
| 1098 |
+
def toterminal(self, tw: TerminalWriter) -> None:
|
| 1099 |
+
raise NotImplementedError()
|
| 1100 |
+
|
| 1101 |
+
|
| 1102 |
+
# This class is abstract -- only subclasses are instantiated.
|
| 1103 |
+
@dataclasses.dataclass(eq=False)
|
| 1104 |
+
class ExceptionRepr(TerminalRepr):
|
| 1105 |
+
# Provided by subclasses.
|
| 1106 |
+
reprtraceback: ReprTraceback
|
| 1107 |
+
reprcrash: ReprFileLocation | None
|
| 1108 |
+
sections: list[tuple[str, str, str]] = dataclasses.field(
|
| 1109 |
+
init=False, default_factory=list
|
| 1110 |
+
)
|
| 1111 |
+
|
| 1112 |
+
def addsection(self, name: str, content: str, sep: str = "-") -> None:
|
| 1113 |
+
self.sections.append((name, content, sep))
|
| 1114 |
+
|
| 1115 |
+
def toterminal(self, tw: TerminalWriter) -> None:
|
| 1116 |
+
for name, content, sep in self.sections:
|
| 1117 |
+
tw.sep(sep, name)
|
| 1118 |
+
tw.line(content)
|
| 1119 |
+
|
| 1120 |
+
|
| 1121 |
+
@dataclasses.dataclass(eq=False)
|
| 1122 |
+
class ExceptionChainRepr(ExceptionRepr):
|
| 1123 |
+
chain: Sequence[tuple[ReprTraceback, ReprFileLocation | None, str | None]]
|
| 1124 |
+
|
| 1125 |
+
def __init__(
|
| 1126 |
+
self,
|
| 1127 |
+
chain: Sequence[tuple[ReprTraceback, ReprFileLocation | None, str | None]],
|
| 1128 |
+
) -> None:
|
| 1129 |
+
# reprcrash and reprtraceback of the outermost (the newest) exception
|
| 1130 |
+
# in the chain.
|
| 1131 |
+
super().__init__(
|
| 1132 |
+
reprtraceback=chain[-1][0],
|
| 1133 |
+
reprcrash=chain[-1][1],
|
| 1134 |
+
)
|
| 1135 |
+
self.chain = chain
|
| 1136 |
+
|
| 1137 |
+
def toterminal(self, tw: TerminalWriter) -> None:
|
| 1138 |
+
for element in self.chain:
|
| 1139 |
+
element[0].toterminal(tw)
|
| 1140 |
+
if element[2] is not None:
|
| 1141 |
+
tw.line("")
|
| 1142 |
+
tw.line(element[2], yellow=True)
|
| 1143 |
+
super().toterminal(tw)
|
| 1144 |
+
|
| 1145 |
+
|
| 1146 |
+
@dataclasses.dataclass(eq=False)
|
| 1147 |
+
class ReprExceptionInfo(ExceptionRepr):
|
| 1148 |
+
reprtraceback: ReprTraceback
|
| 1149 |
+
reprcrash: ReprFileLocation | None
|
| 1150 |
+
|
| 1151 |
+
def toterminal(self, tw: TerminalWriter) -> None:
|
| 1152 |
+
self.reprtraceback.toterminal(tw)
|
| 1153 |
+
super().toterminal(tw)
|
| 1154 |
+
|
| 1155 |
+
|
| 1156 |
+
@dataclasses.dataclass(eq=False)
|
| 1157 |
+
class ReprTraceback(TerminalRepr):
|
| 1158 |
+
reprentries: Sequence[ReprEntry | ReprEntryNative]
|
| 1159 |
+
extraline: str | None
|
| 1160 |
+
style: TracebackStyle
|
| 1161 |
+
|
| 1162 |
+
entrysep: ClassVar = "_ "
|
| 1163 |
+
|
| 1164 |
+
def toterminal(self, tw: TerminalWriter) -> None:
|
| 1165 |
+
# The entries might have different styles.
|
| 1166 |
+
for i, entry in enumerate(self.reprentries):
|
| 1167 |
+
if entry.style == "long":
|
| 1168 |
+
tw.line("")
|
| 1169 |
+
entry.toterminal(tw)
|
| 1170 |
+
if i < len(self.reprentries) - 1:
|
| 1171 |
+
next_entry = self.reprentries[i + 1]
|
| 1172 |
+
if (
|
| 1173 |
+
entry.style == "long"
|
| 1174 |
+
or entry.style == "short"
|
| 1175 |
+
and next_entry.style == "long"
|
| 1176 |
+
):
|
| 1177 |
+
tw.sep(self.entrysep)
|
| 1178 |
+
|
| 1179 |
+
if self.extraline:
|
| 1180 |
+
tw.line(self.extraline)
|
| 1181 |
+
|
| 1182 |
+
|
| 1183 |
+
class ReprTracebackNative(ReprTraceback):
|
| 1184 |
+
def __init__(self, tblines: Sequence[str]) -> None:
|
| 1185 |
+
self.reprentries = [ReprEntryNative(tblines)]
|
| 1186 |
+
self.extraline = None
|
| 1187 |
+
self.style = "native"
|
| 1188 |
+
|
| 1189 |
+
|
| 1190 |
+
@dataclasses.dataclass(eq=False)
|
| 1191 |
+
class ReprEntryNative(TerminalRepr):
|
| 1192 |
+
lines: Sequence[str]
|
| 1193 |
+
|
| 1194 |
+
style: ClassVar[TracebackStyle] = "native"
|
| 1195 |
+
|
| 1196 |
+
def toterminal(self, tw: TerminalWriter) -> None:
|
| 1197 |
+
tw.write("".join(self.lines))
|
| 1198 |
+
|
| 1199 |
+
|
| 1200 |
+
@dataclasses.dataclass(eq=False)
|
| 1201 |
+
class ReprEntry(TerminalRepr):
|
| 1202 |
+
lines: Sequence[str]
|
| 1203 |
+
reprfuncargs: ReprFuncArgs | None
|
| 1204 |
+
reprlocals: ReprLocals | None
|
| 1205 |
+
reprfileloc: ReprFileLocation | None
|
| 1206 |
+
style: TracebackStyle
|
| 1207 |
+
|
| 1208 |
+
def _write_entry_lines(self, tw: TerminalWriter) -> None:
|
| 1209 |
+
"""Write the source code portions of a list of traceback entries with syntax highlighting.
|
| 1210 |
+
|
| 1211 |
+
Usually entries are lines like these:
|
| 1212 |
+
|
| 1213 |
+
" x = 1"
|
| 1214 |
+
"> assert x == 2"
|
| 1215 |
+
"E assert 1 == 2"
|
| 1216 |
+
|
| 1217 |
+
This function takes care of rendering the "source" portions of it (the lines without
|
| 1218 |
+
the "E" prefix) using syntax highlighting, taking care to not highlighting the ">"
|
| 1219 |
+
character, as doing so might break line continuations.
|
| 1220 |
+
"""
|
| 1221 |
+
if not self.lines:
|
| 1222 |
+
return
|
| 1223 |
+
|
| 1224 |
+
if self.style == "value":
|
| 1225 |
+
# Using tw.write instead of tw.line for testing purposes due to TWMock implementation;
|
| 1226 |
+
# lines written with TWMock.line and TWMock._write_source cannot be distinguished
|
| 1227 |
+
# from each other, whereas lines written with TWMock.write are marked with TWMock.WRITE
|
| 1228 |
+
for line in self.lines:
|
| 1229 |
+
tw.write(line)
|
| 1230 |
+
tw.write("\n")
|
| 1231 |
+
return
|
| 1232 |
+
|
| 1233 |
+
# separate indents and source lines that are not failures: we want to
|
| 1234 |
+
# highlight the code but not the indentation, which may contain markers
|
| 1235 |
+
# such as "> assert 0"
|
| 1236 |
+
fail_marker = f"{FormattedExcinfo.fail_marker} "
|
| 1237 |
+
indent_size = len(fail_marker)
|
| 1238 |
+
indents: list[str] = []
|
| 1239 |
+
source_lines: list[str] = []
|
| 1240 |
+
failure_lines: list[str] = []
|
| 1241 |
+
for index, line in enumerate(self.lines):
|
| 1242 |
+
is_failure_line = line.startswith(fail_marker)
|
| 1243 |
+
if is_failure_line:
|
| 1244 |
+
# from this point on all lines are considered part of the failure
|
| 1245 |
+
failure_lines.extend(self.lines[index:])
|
| 1246 |
+
break
|
| 1247 |
+
else:
|
| 1248 |
+
indents.append(line[:indent_size])
|
| 1249 |
+
source_lines.append(line[indent_size:])
|
| 1250 |
+
|
| 1251 |
+
tw._write_source(source_lines, indents)
|
| 1252 |
+
|
| 1253 |
+
# failure lines are always completely red and bold
|
| 1254 |
+
for line in failure_lines:
|
| 1255 |
+
tw.line(line, bold=True, red=True)
|
| 1256 |
+
|
| 1257 |
+
def toterminal(self, tw: TerminalWriter) -> None:
|
| 1258 |
+
if self.style == "short":
|
| 1259 |
+
if self.reprfileloc:
|
| 1260 |
+
self.reprfileloc.toterminal(tw)
|
| 1261 |
+
self._write_entry_lines(tw)
|
| 1262 |
+
if self.reprlocals:
|
| 1263 |
+
self.reprlocals.toterminal(tw, indent=" " * 8)
|
| 1264 |
+
return
|
| 1265 |
+
|
| 1266 |
+
if self.reprfuncargs:
|
| 1267 |
+
self.reprfuncargs.toterminal(tw)
|
| 1268 |
+
|
| 1269 |
+
self._write_entry_lines(tw)
|
| 1270 |
+
|
| 1271 |
+
if self.reprlocals:
|
| 1272 |
+
tw.line("")
|
| 1273 |
+
self.reprlocals.toterminal(tw)
|
| 1274 |
+
if self.reprfileloc:
|
| 1275 |
+
if self.lines:
|
| 1276 |
+
tw.line("")
|
| 1277 |
+
self.reprfileloc.toterminal(tw)
|
| 1278 |
+
|
| 1279 |
+
def __str__(self) -> str:
|
| 1280 |
+
return "{}\n{}\n{}".format(
|
| 1281 |
+
"\n".join(self.lines), self.reprlocals, self.reprfileloc
|
| 1282 |
+
)
|
| 1283 |
+
|
| 1284 |
+
|
| 1285 |
+
@dataclasses.dataclass(eq=False)
|
| 1286 |
+
class ReprFileLocation(TerminalRepr):
|
| 1287 |
+
path: str
|
| 1288 |
+
lineno: int
|
| 1289 |
+
message: str
|
| 1290 |
+
|
| 1291 |
+
def __post_init__(self) -> None:
|
| 1292 |
+
self.path = str(self.path)
|
| 1293 |
+
|
| 1294 |
+
def toterminal(self, tw: TerminalWriter) -> None:
|
| 1295 |
+
# Filename and lineno output for each entry, using an output format
|
| 1296 |
+
# that most editors understand.
|
| 1297 |
+
msg = self.message
|
| 1298 |
+
i = msg.find("\n")
|
| 1299 |
+
if i != -1:
|
| 1300 |
+
msg = msg[:i]
|
| 1301 |
+
tw.write(self.path, bold=True, red=True)
|
| 1302 |
+
tw.line(f":{self.lineno}: {msg}")
|
| 1303 |
+
|
| 1304 |
+
|
| 1305 |
+
@dataclasses.dataclass(eq=False)
|
| 1306 |
+
class ReprLocals(TerminalRepr):
|
| 1307 |
+
lines: Sequence[str]
|
| 1308 |
+
|
| 1309 |
+
def toterminal(self, tw: TerminalWriter, indent="") -> None:
|
| 1310 |
+
for line in self.lines:
|
| 1311 |
+
tw.line(indent + line)
|
| 1312 |
+
|
| 1313 |
+
|
| 1314 |
+
@dataclasses.dataclass(eq=False)
|
| 1315 |
+
class ReprFuncArgs(TerminalRepr):
|
| 1316 |
+
args: Sequence[tuple[str, object]]
|
| 1317 |
+
|
| 1318 |
+
def toterminal(self, tw: TerminalWriter) -> None:
|
| 1319 |
+
if self.args:
|
| 1320 |
+
linesofar = ""
|
| 1321 |
+
for name, value in self.args:
|
| 1322 |
+
ns = f"{name} = {value}"
|
| 1323 |
+
if len(ns) + len(linesofar) + 2 > tw.fullwidth:
|
| 1324 |
+
if linesofar:
|
| 1325 |
+
tw.line(linesofar)
|
| 1326 |
+
linesofar = ns
|
| 1327 |
+
else:
|
| 1328 |
+
if linesofar:
|
| 1329 |
+
linesofar += ", " + ns
|
| 1330 |
+
else:
|
| 1331 |
+
linesofar = ns
|
| 1332 |
+
if linesofar:
|
| 1333 |
+
tw.line(linesofar)
|
| 1334 |
+
tw.line("")
|
| 1335 |
+
|
| 1336 |
+
|
| 1337 |
+
def getfslineno(obj: object) -> tuple[str | Path, int]:
|
| 1338 |
+
"""Return source location (path, lineno) for the given object.
|
| 1339 |
+
|
| 1340 |
+
If the source cannot be determined return ("", -1).
|
| 1341 |
+
|
| 1342 |
+
The line number is 0-based.
|
| 1343 |
+
"""
|
| 1344 |
+
# xxx let decorators etc specify a sane ordering
|
| 1345 |
+
# NOTE: this used to be done in _pytest.compat.getfslineno, initially added
|
| 1346 |
+
# in 6ec13a2b9. It ("place_as") appears to be something very custom.
|
| 1347 |
+
obj = get_real_func(obj)
|
| 1348 |
+
if hasattr(obj, "place_as"):
|
| 1349 |
+
obj = obj.place_as
|
| 1350 |
+
|
| 1351 |
+
try:
|
| 1352 |
+
code = Code.from_function(obj)
|
| 1353 |
+
except TypeError:
|
| 1354 |
+
try:
|
| 1355 |
+
fn = inspect.getsourcefile(obj) or inspect.getfile(obj) # type: ignore[arg-type]
|
| 1356 |
+
except TypeError:
|
| 1357 |
+
return "", -1
|
| 1358 |
+
|
| 1359 |
+
fspath = fn and absolutepath(fn) or ""
|
| 1360 |
+
lineno = -1
|
| 1361 |
+
if fspath:
|
| 1362 |
+
try:
|
| 1363 |
+
_, lineno = findsource(obj)
|
| 1364 |
+
except OSError:
|
| 1365 |
+
pass
|
| 1366 |
+
return fspath, lineno
|
| 1367 |
+
|
| 1368 |
+
return code.path, code.firstlineno
|
| 1369 |
+
|
| 1370 |
+
|
| 1371 |
+
# Relative paths that we use to filter traceback entries from appearing to the user;
|
| 1372 |
+
# see filter_traceback.
|
| 1373 |
+
# note: if we need to add more paths than what we have now we should probably use a list
|
| 1374 |
+
# for better maintenance.
|
| 1375 |
+
|
| 1376 |
+
_PLUGGY_DIR = Path(pluggy.__file__.rstrip("oc"))
|
| 1377 |
+
# pluggy is either a package or a single module depending on the version
|
| 1378 |
+
if _PLUGGY_DIR.name == "__init__.py":
|
| 1379 |
+
_PLUGGY_DIR = _PLUGGY_DIR.parent
|
| 1380 |
+
_PYTEST_DIR = Path(_pytest.__file__).parent
|
| 1381 |
+
|
| 1382 |
+
|
| 1383 |
+
def filter_traceback(entry: TracebackEntry) -> bool:
|
| 1384 |
+
"""Return True if a TracebackEntry instance should be included in tracebacks.
|
| 1385 |
+
|
| 1386 |
+
We hide traceback entries of:
|
| 1387 |
+
|
| 1388 |
+
* dynamically generated code (no code to show up for it);
|
| 1389 |
+
* internal traceback from pytest or its internal libraries, py and pluggy.
|
| 1390 |
+
"""
|
| 1391 |
+
# entry.path might sometimes return a str object when the entry
|
| 1392 |
+
# points to dynamically generated code.
|
| 1393 |
+
# See https://bitbucket.org/pytest-dev/py/issues/71.
|
| 1394 |
+
raw_filename = entry.frame.code.raw.co_filename
|
| 1395 |
+
is_generated = "<" in raw_filename and ">" in raw_filename
|
| 1396 |
+
if is_generated:
|
| 1397 |
+
return False
|
| 1398 |
+
|
| 1399 |
+
# entry.path might point to a non-existing file, in which case it will
|
| 1400 |
+
# also return a str object. See #1133.
|
| 1401 |
+
p = Path(entry.path)
|
| 1402 |
+
|
| 1403 |
+
parents = p.parents
|
| 1404 |
+
if _PLUGGY_DIR in parents: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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import ast
|
| 5 |
+
from bisect import bisect_right
|
| 6 |
+
import inspect
|
| 7 |
+
import textwrap
|
| 8 |
+
import tokenize
|
| 9 |
+
import types
|
| 10 |
+
from typing import Iterable
|
| 11 |
+
from typing import Iterator
|
| 12 |
+
from typing import overload
|
| 13 |
+
import warnings
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class Source:
|
| 17 |
+
"""An immutable object holding a source code fragment.
|
| 18 |
+
|
| 19 |
+
When using Source(...), the source lines are deindented.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(self, obj: object = None) -> None:
|
| 23 |
+
if not obj:
|
| 24 |
+
self.lines: list[str] = []
|
| 25 |
+
elif isinstance(obj, Source):
|
| 26 |
+
self.lines = obj.lines
|
| 27 |
+
elif isinstance(obj, (tuple, list)):
|
| 28 |
+
self.lines = deindent(x.rstrip("\n") for x in obj)
|
| 29 |
+
elif isinstance(obj, str):
|
| 30 |
+
self.lines = deindent(obj.split("\n"))
|
| 31 |
+
else:
|
| 32 |
+
try:
|
| 33 |
+
rawcode = getrawcode(obj)
|
| 34 |
+
src = inspect.getsource(rawcode)
|
| 35 |
+
except TypeError:
|
| 36 |
+
src = inspect.getsource(obj) # type: ignore[arg-type]
|
| 37 |
+
self.lines = deindent(src.split("\n"))
|
| 38 |
+
|
| 39 |
+
def __eq__(self, other: object) -> bool:
|
| 40 |
+
if not isinstance(other, Source):
|
| 41 |
+
return NotImplemented
|
| 42 |
+
return self.lines == other.lines
|
| 43 |
+
|
| 44 |
+
# Ignore type because of https://github.com/python/mypy/issues/4266.
|
| 45 |
+
__hash__ = None # type: ignore
|
| 46 |
+
|
| 47 |
+
@overload
|
| 48 |
+
def __getitem__(self, key: int) -> str: ...
|
| 49 |
+
|
| 50 |
+
@overload
|
| 51 |
+
def __getitem__(self, key: slice) -> Source: ...
|
| 52 |
+
|
| 53 |
+
def __getitem__(self, key: int | slice) -> str | Source:
|
| 54 |
+
if isinstance(key, int):
|
| 55 |
+
return self.lines[key]
|
| 56 |
+
else:
|
| 57 |
+
if key.step not in (None, 1):
|
| 58 |
+
raise IndexError("cannot slice a Source with a step")
|
| 59 |
+
newsource = Source()
|
| 60 |
+
newsource.lines = self.lines[key.start : key.stop]
|
| 61 |
+
return newsource
|
| 62 |
+
|
| 63 |
+
def __iter__(self) -> Iterator[str]:
|
| 64 |
+
return iter(self.lines)
|
| 65 |
+
|
| 66 |
+
def __len__(self) -> int:
|
| 67 |
+
return len(self.lines)
|
| 68 |
+
|
| 69 |
+
def strip(self) -> Source:
|
| 70 |
+
"""Return new Source object with trailing and leading blank lines removed."""
|
| 71 |
+
start, end = 0, len(self)
|
| 72 |
+
while start < end and not self.lines[start].strip():
|
| 73 |
+
start += 1
|
| 74 |
+
while end > start and not self.lines[end - 1].strip():
|
| 75 |
+
end -= 1
|
| 76 |
+
source = Source()
|
| 77 |
+
source.lines[:] = self.lines[start:end]
|
| 78 |
+
return source
|
| 79 |
+
|
| 80 |
+
def indent(self, indent: str = " " * 4) -> Source:
|
| 81 |
+
"""Return a copy of the source object with all lines indented by the
|
| 82 |
+
given indent-string."""
|
| 83 |
+
newsource = Source()
|
| 84 |
+
newsource.lines = [(indent + line) for line in self.lines]
|
| 85 |
+
return newsource
|
| 86 |
+
|
| 87 |
+
def getstatement(self, lineno: int) -> Source:
|
| 88 |
+
"""Return Source statement which contains the given linenumber
|
| 89 |
+
(counted from 0)."""
|
| 90 |
+
start, end = self.getstatementrange(lineno)
|
| 91 |
+
return self[start:end]
|
| 92 |
+
|
| 93 |
+
def getstatementrange(self, lineno: int) -> tuple[int, int]:
|
| 94 |
+
"""Return (start, end) tuple which spans the minimal statement region
|
| 95 |
+
which containing the given lineno."""
|
| 96 |
+
if not (0 <= lineno < len(self)):
|
| 97 |
+
raise IndexError("lineno out of range")
|
| 98 |
+
ast, start, end = getstatementrange_ast(lineno, self)
|
| 99 |
+
return start, end
|
| 100 |
+
|
| 101 |
+
def deindent(self) -> Source:
|
| 102 |
+
"""Return a new Source object deindented."""
|
| 103 |
+
newsource = Source()
|
| 104 |
+
newsource.lines[:] = deindent(self.lines)
|
| 105 |
+
return newsource
|
| 106 |
+
|
| 107 |
+
def __str__(self) -> str:
|
| 108 |
+
return "\n".join(self.lines)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
#
|
| 112 |
+
# helper functions
|
| 113 |
+
#
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def findsource(obj) -> tuple[Source | None, int]:
|
| 117 |
+
try:
|
| 118 |
+
sourcelines, lineno = inspect.findsource(obj)
|
| 119 |
+
except Exception:
|
| 120 |
+
return None, -1
|
| 121 |
+
source = Source()
|
| 122 |
+
source.lines = [line.rstrip() for line in sourcelines]
|
| 123 |
+
return source, lineno
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def getrawcode(obj: object, trycall: bool = True) -> types.CodeType:
|
| 127 |
+
"""Return code object for given function."""
|
| 128 |
+
try:
|
| 129 |
+
return obj.__code__ # type: ignore[attr-defined,no-any-return]
|
| 130 |
+
except AttributeError:
|
| 131 |
+
pass
|
| 132 |
+
if trycall:
|
| 133 |
+
call = getattr(obj, "__call__", None)
|
| 134 |
+
if call and not isinstance(obj, type):
|
| 135 |
+
return getrawcode(call, trycall=False)
|
| 136 |
+
raise TypeError(f"could not get code object for {obj!r}")
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def deindent(lines: Iterable[str]) -> list[str]:
|
| 140 |
+
return textwrap.dedent("\n".join(lines)).splitlines()
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def get_statement_startend2(lineno: int, node: ast.AST) -> tuple[int, int | None]:
|
| 144 |
+
# Flatten all statements and except handlers into one lineno-list.
|
| 145 |
+
# AST's line numbers start indexing at 1.
|
| 146 |
+
values: list[int] = []
|
| 147 |
+
for x in ast.walk(node):
|
| 148 |
+
if isinstance(x, (ast.stmt, ast.ExceptHandler)):
|
| 149 |
+
# The lineno points to the class/def, so need to include the decorators.
|
| 150 |
+
if isinstance(x, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
|
| 151 |
+
for d in x.decorator_list:
|
| 152 |
+
values.append(d.lineno - 1)
|
| 153 |
+
values.append(x.lineno - 1)
|
| 154 |
+
for name in ("finalbody", "orelse"):
|
| 155 |
+
val: list[ast.stmt] | None = getattr(x, name, None)
|
| 156 |
+
if val:
|
| 157 |
+
# Treat the finally/orelse part as its own statement.
|
| 158 |
+
values.append(val[0].lineno - 1 - 1)
|
| 159 |
+
values.sort()
|
| 160 |
+
insert_index = bisect_right(values, lineno)
|
| 161 |
+
start = values[insert_index - 1]
|
| 162 |
+
if insert_index >= len(values):
|
| 163 |
+
end = None
|
| 164 |
+
else:
|
| 165 |
+
end = values[insert_index]
|
| 166 |
+
return start, end
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def getstatementrange_ast(
|
| 170 |
+
lineno: int,
|
| 171 |
+
source: Source,
|
| 172 |
+
assertion: bool = False,
|
| 173 |
+
astnode: ast.AST | None = None,
|
| 174 |
+
) -> tuple[ast.AST, int, int]:
|
| 175 |
+
if astnode is None:
|
| 176 |
+
content = str(source)
|
| 177 |
+
# See #4260:
|
| 178 |
+
# Don't produce duplicate warnings when compiling source to find AST.
|
| 179 |
+
with warnings.catch_warnings():
|
| 180 |
+
warnings.simplefilter("ignore")
|
| 181 |
+
astnode = ast.parse(content, "source", "exec")
|
| 182 |
+
|
| 183 |
+
start, end = get_statement_startend2(lineno, astnode)
|
| 184 |
+
# We need to correct the end:
|
| 185 |
+
# - ast-parsing strips comments
|
| 186 |
+
# - there might be empty lines
|
| 187 |
+
# - we might have lesser indented code blocks at the end
|
| 188 |
+
if end is None:
|
| 189 |
+
end = len(source.lines)
|
| 190 |
+
|
| 191 |
+
if end > start + 1:
|
| 192 |
+
# Make sure we don't span differently indented code blocks
|
| 193 |
+
# by using the BlockFinder helper used which inspect.getsource() uses itself.
|
| 194 |
+
block_finder = inspect.BlockFinder()
|
| 195 |
+
# If we start with an indented line, put blockfinder to "started" mode.
|
| 196 |
+
block_finder.started = (
|
| 197 |
+
bool(source.lines[start]) and source.lines[start][0].isspace()
|
| 198 |
+
)
|
| 199 |
+
it = ((x + "\n") for x in source.lines[start:end])
|
| 200 |
+
try:
|
| 201 |
+
for tok in tokenize.generate_tokens(lambda: next(it)):
|
| 202 |
+
block_finder.tokeneater(*tok)
|
| 203 |
+
except (inspect.EndOfBlock, IndentationError):
|
| 204 |
+
end = block_finder.last + start
|
| 205 |
+
except Exception:
|
| 206 |
+
pass
|
| 207 |
+
|
| 208 |
+
# The end might still point to a comment or empty line, correct it.
|
| 209 |
+
while end:
|
| 210 |
+
line = source.lines[end - 1].lstrip()
|
| 211 |
+
if line.startswith("#") or not line:
|
| 212 |
+
end -= 1
|
| 213 |
+
else:
|
| 214 |
+
break
|
| 215 |
+
return astnode, start, end
|
vllm/lib/python3.10/site-packages/_pytest/_io/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from .terminalwriter import get_terminal_width
|
| 4 |
+
from .terminalwriter import TerminalWriter
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
"TerminalWriter",
|
| 9 |
+
"get_terminal_width",
|
| 10 |
+
]
|
vllm/lib/python3.10/site-packages/_pytest/_io/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (339 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/_io/__pycache__/pprint.cpython-310.pyc
ADDED
|
Binary file (13.1 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/_io/__pycache__/saferepr.cpython-310.pyc
ADDED
|
Binary file (4.47 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/_io/__pycache__/terminalwriter.cpython-310.pyc
ADDED
|
Binary file (7.88 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/_io/__pycache__/wcwidth.cpython-310.pyc
ADDED
|
Binary file (1.33 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/_io/wcwidth.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from functools import lru_cache
|
| 4 |
+
import unicodedata
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@lru_cache(100)
|
| 8 |
+
def wcwidth(c: str) -> int:
|
| 9 |
+
"""Determine how many columns are needed to display a character in a terminal.
|
| 10 |
+
|
| 11 |
+
Returns -1 if the character is not printable.
|
| 12 |
+
Returns 0, 1 or 2 for other characters.
|
| 13 |
+
"""
|
| 14 |
+
o = ord(c)
|
| 15 |
+
|
| 16 |
+
# ASCII fast path.
|
| 17 |
+
if 0x20 <= o < 0x07F:
|
| 18 |
+
return 1
|
| 19 |
+
|
| 20 |
+
# Some Cf/Zp/Zl characters which should be zero-width.
|
| 21 |
+
if (
|
| 22 |
+
o == 0x0000
|
| 23 |
+
or 0x200B <= o <= 0x200F
|
| 24 |
+
or 0x2028 <= o <= 0x202E
|
| 25 |
+
or 0x2060 <= o <= 0x2063
|
| 26 |
+
):
|
| 27 |
+
return 0
|
| 28 |
+
|
| 29 |
+
category = unicodedata.category(c)
|
| 30 |
+
|
| 31 |
+
# Control characters.
|
| 32 |
+
if category == "Cc":
|
| 33 |
+
return -1
|
| 34 |
+
|
| 35 |
+
# Combining characters with zero width.
|
| 36 |
+
if category in ("Me", "Mn"):
|
| 37 |
+
return 0
|
| 38 |
+
|
| 39 |
+
# Full/Wide east asian characters.
|
| 40 |
+
if unicodedata.east_asian_width(c) in ("F", "W"):
|
| 41 |
+
return 2
|
| 42 |
+
|
| 43 |
+
return 1
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def wcswidth(s: str) -> int:
|
| 47 |
+
"""Determine how many columns are needed to display a string in a terminal.
|
| 48 |
+
|
| 49 |
+
Returns -1 if the string contains non-printable characters.
|
| 50 |
+
"""
|
| 51 |
+
width = 0
|
| 52 |
+
for c in unicodedata.normalize("NFC", s):
|
| 53 |
+
wc = wcwidth(c)
|
| 54 |
+
if wc < 0:
|
| 55 |
+
return -1
|
| 56 |
+
width += wc
|
| 57 |
+
return width
|
vllm/lib/python3.10/site-packages/_pytest/_py/__init__.py
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/_pytest/_py/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (161 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/_py/__pycache__/error.cpython-310.pyc
ADDED
|
Binary file (3.21 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/_py/__pycache__/path.cpython-310.pyc
ADDED
|
Binary file (43.1 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/_py/error.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""create errno-specific classes for IO or os calls."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import errno
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
from typing import Callable
|
| 9 |
+
from typing import TYPE_CHECKING
|
| 10 |
+
from typing import TypeVar
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
if TYPE_CHECKING:
|
| 14 |
+
from typing_extensions import ParamSpec
|
| 15 |
+
|
| 16 |
+
P = ParamSpec("P")
|
| 17 |
+
|
| 18 |
+
R = TypeVar("R")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class Error(EnvironmentError):
|
| 22 |
+
def __repr__(self) -> str:
|
| 23 |
+
return "{}.{} {!r}: {} ".format(
|
| 24 |
+
self.__class__.__module__,
|
| 25 |
+
self.__class__.__name__,
|
| 26 |
+
self.__class__.__doc__,
|
| 27 |
+
" ".join(map(str, self.args)),
|
| 28 |
+
# repr(self.args)
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
def __str__(self) -> str:
|
| 32 |
+
s = "[{}]: {}".format(
|
| 33 |
+
self.__class__.__doc__,
|
| 34 |
+
" ".join(map(str, self.args)),
|
| 35 |
+
)
|
| 36 |
+
return s
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
_winerrnomap = {
|
| 40 |
+
2: errno.ENOENT,
|
| 41 |
+
3: errno.ENOENT,
|
| 42 |
+
17: errno.EEXIST,
|
| 43 |
+
18: errno.EXDEV,
|
| 44 |
+
13: errno.EBUSY, # empty cd drive, but ENOMEDIUM seems unavailable
|
| 45 |
+
22: errno.ENOTDIR,
|
| 46 |
+
20: errno.ENOTDIR,
|
| 47 |
+
267: errno.ENOTDIR,
|
| 48 |
+
5: errno.EACCES, # anything better?
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class ErrorMaker:
|
| 53 |
+
"""lazily provides Exception classes for each possible POSIX errno
|
| 54 |
+
(as defined per the 'errno' module). All such instances
|
| 55 |
+
subclass EnvironmentError.
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
_errno2class: dict[int, type[Error]] = {}
|
| 59 |
+
|
| 60 |
+
def __getattr__(self, name: str) -> type[Error]:
|
| 61 |
+
if name[0] == "_":
|
| 62 |
+
raise AttributeError(name)
|
| 63 |
+
eno = getattr(errno, name)
|
| 64 |
+
cls = self._geterrnoclass(eno)
|
| 65 |
+
setattr(self, name, cls)
|
| 66 |
+
return cls
|
| 67 |
+
|
| 68 |
+
def _geterrnoclass(self, eno: int) -> type[Error]:
|
| 69 |
+
try:
|
| 70 |
+
return self._errno2class[eno]
|
| 71 |
+
except KeyError:
|
| 72 |
+
clsname = errno.errorcode.get(eno, "UnknownErrno%d" % (eno,))
|
| 73 |
+
errorcls = type(
|
| 74 |
+
clsname,
|
| 75 |
+
(Error,),
|
| 76 |
+
{"__module__": "py.error", "__doc__": os.strerror(eno)},
|
| 77 |
+
)
|
| 78 |
+
self._errno2class[eno] = errorcls
|
| 79 |
+
return errorcls
|
| 80 |
+
|
| 81 |
+
def checked_call(
|
| 82 |
+
self, func: Callable[P, R], *args: P.args, **kwargs: P.kwargs
|
| 83 |
+
) -> R:
|
| 84 |
+
"""Call a function and raise an errno-exception if applicable."""
|
| 85 |
+
__tracebackhide__ = True
|
| 86 |
+
try:
|
| 87 |
+
return func(*args, **kwargs)
|
| 88 |
+
except Error:
|
| 89 |
+
raise
|
| 90 |
+
except OSError as value:
|
| 91 |
+
if not hasattr(value, "errno"):
|
| 92 |
+
raise
|
| 93 |
+
errno = value.errno
|
| 94 |
+
if sys.platform == "win32":
|
| 95 |
+
try:
|
| 96 |
+
cls = self._geterrnoclass(_winerrnomap[errno])
|
| 97 |
+
except KeyError:
|
| 98 |
+
raise value
|
| 99 |
+
else:
|
| 100 |
+
# we are not on Windows, or we got a proper OSError
|
| 101 |
+
cls = self._geterrnoclass(errno)
|
| 102 |
+
|
| 103 |
+
raise cls(f"{func.__name__}{args!r}")
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
_error_maker = ErrorMaker()
|
| 107 |
+
checked_call = _error_maker.checked_call
|
| 108 |
+
|
| 109 |
+
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""local path implementation."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import atexit
|
| 7 |
+
from contextlib import contextmanager
|
| 8 |
+
import fnmatch
|
| 9 |
+
import importlib.util
|
| 10 |
+
import io
|
| 11 |
+
import os
|
| 12 |
+
from os.path import abspath
|
| 13 |
+
from os.path import dirname
|
| 14 |
+
from os.path import exists
|
| 15 |
+
from os.path import isabs
|
| 16 |
+
from os.path import isdir
|
| 17 |
+
from os.path import isfile
|
| 18 |
+
from os.path import islink
|
| 19 |
+
from os.path import normpath
|
| 20 |
+
import posixpath
|
| 21 |
+
from stat import S_ISDIR
|
| 22 |
+
from stat import S_ISLNK
|
| 23 |
+
from stat import S_ISREG
|
| 24 |
+
import sys
|
| 25 |
+
from typing import Any
|
| 26 |
+
from typing import Callable
|
| 27 |
+
from typing import cast
|
| 28 |
+
from typing import Literal
|
| 29 |
+
from typing import overload
|
| 30 |
+
from typing import TYPE_CHECKING
|
| 31 |
+
import uuid
|
| 32 |
+
import warnings
|
| 33 |
+
|
| 34 |
+
from . import error
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# Moved from local.py.
|
| 38 |
+
iswin32 = sys.platform == "win32" or (getattr(os, "_name", False) == "nt")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Checkers:
|
| 42 |
+
_depend_on_existence = "exists", "link", "dir", "file"
|
| 43 |
+
|
| 44 |
+
def __init__(self, path):
|
| 45 |
+
self.path = path
|
| 46 |
+
|
| 47 |
+
def dotfile(self):
|
| 48 |
+
return self.path.basename.startswith(".")
|
| 49 |
+
|
| 50 |
+
def ext(self, arg):
|
| 51 |
+
if not arg.startswith("."):
|
| 52 |
+
arg = "." + arg
|
| 53 |
+
return self.path.ext == arg
|
| 54 |
+
|
| 55 |
+
def basename(self, arg):
|
| 56 |
+
return self.path.basename == arg
|
| 57 |
+
|
| 58 |
+
def basestarts(self, arg):
|
| 59 |
+
return self.path.basename.startswith(arg)
|
| 60 |
+
|
| 61 |
+
def relto(self, arg):
|
| 62 |
+
return self.path.relto(arg)
|
| 63 |
+
|
| 64 |
+
def fnmatch(self, arg):
|
| 65 |
+
return self.path.fnmatch(arg)
|
| 66 |
+
|
| 67 |
+
def endswith(self, arg):
|
| 68 |
+
return str(self.path).endswith(arg)
|
| 69 |
+
|
| 70 |
+
def _evaluate(self, kw):
|
| 71 |
+
from .._code.source import getrawcode
|
| 72 |
+
|
| 73 |
+
for name, value in kw.items():
|
| 74 |
+
invert = False
|
| 75 |
+
meth = None
|
| 76 |
+
try:
|
| 77 |
+
meth = getattr(self, name)
|
| 78 |
+
except AttributeError:
|
| 79 |
+
if name[:3] == "not":
|
| 80 |
+
invert = True
|
| 81 |
+
try:
|
| 82 |
+
meth = getattr(self, name[3:])
|
| 83 |
+
except AttributeError:
|
| 84 |
+
pass
|
| 85 |
+
if meth is None:
|
| 86 |
+
raise TypeError(f"no {name!r} checker available for {self.path!r}")
|
| 87 |
+
try:
|
| 88 |
+
if getrawcode(meth).co_argcount > 1:
|
| 89 |
+
if (not meth(value)) ^ invert:
|
| 90 |
+
return False
|
| 91 |
+
else:
|
| 92 |
+
if bool(value) ^ bool(meth()) ^ invert:
|
| 93 |
+
return False
|
| 94 |
+
except (error.ENOENT, error.ENOTDIR, error.EBUSY):
|
| 95 |
+
# EBUSY feels not entirely correct,
|
| 96 |
+
# but its kind of necessary since ENOMEDIUM
|
| 97 |
+
# is not accessible in python
|
| 98 |
+
for name in self._depend_on_existence:
|
| 99 |
+
if name in kw:
|
| 100 |
+
if kw.get(name):
|
| 101 |
+
return False
|
| 102 |
+
name = "not" + name
|
| 103 |
+
if name in kw:
|
| 104 |
+
if not kw.get(name):
|
| 105 |
+
return False
|
| 106 |
+
return True
|
| 107 |
+
|
| 108 |
+
_statcache: Stat
|
| 109 |
+
|
| 110 |
+
def _stat(self) -> Stat:
|
| 111 |
+
try:
|
| 112 |
+
return self._statcache
|
| 113 |
+
except AttributeError:
|
| 114 |
+
try:
|
| 115 |
+
self._statcache = self.path.stat()
|
| 116 |
+
except error.ELOOP:
|
| 117 |
+
self._statcache = self.path.lstat()
|
| 118 |
+
return self._statcache
|
| 119 |
+
|
| 120 |
+
def dir(self):
|
| 121 |
+
return S_ISDIR(self._stat().mode)
|
| 122 |
+
|
| 123 |
+
def file(self):
|
| 124 |
+
return S_ISREG(self._stat().mode)
|
| 125 |
+
|
| 126 |
+
def exists(self):
|
| 127 |
+
return self._stat()
|
| 128 |
+
|
| 129 |
+
def link(self):
|
| 130 |
+
st = self.path.lstat()
|
| 131 |
+
return S_ISLNK(st.mode)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class NeverRaised(Exception):
|
| 135 |
+
pass
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class Visitor:
|
| 139 |
+
def __init__(self, fil, rec, ignore, bf, sort):
|
| 140 |
+
if isinstance(fil, str):
|
| 141 |
+
fil = FNMatcher(fil)
|
| 142 |
+
if isinstance(rec, str):
|
| 143 |
+
self.rec: Callable[[LocalPath], bool] = FNMatcher(rec)
|
| 144 |
+
elif not hasattr(rec, "__call__") and rec:
|
| 145 |
+
self.rec = lambda path: True
|
| 146 |
+
else:
|
| 147 |
+
self.rec = rec
|
| 148 |
+
self.fil = fil
|
| 149 |
+
self.ignore = ignore
|
| 150 |
+
self.breadthfirst = bf
|
| 151 |
+
self.optsort = cast(Callable[[Any], Any], sorted) if sort else (lambda x: x)
|
| 152 |
+
|
| 153 |
+
def gen(self, path):
|
| 154 |
+
try:
|
| 155 |
+
entries = path.listdir()
|
| 156 |
+
except self.ignore:
|
| 157 |
+
return
|
| 158 |
+
rec = self.rec
|
| 159 |
+
dirs = self.optsort(
|
| 160 |
+
[p for p in entries if p.check(dir=1) and (rec is None or rec(p))]
|
| 161 |
+
)
|
| 162 |
+
if not self.breadthfirst:
|
| 163 |
+
for subdir in dirs:
|
| 164 |
+
yield from self.gen(subdir)
|
| 165 |
+
for p in self.optsort(entries):
|
| 166 |
+
if self.fil is None or self.fil(p):
|
| 167 |
+
yield p
|
| 168 |
+
if self.breadthfirst:
|
| 169 |
+
for subdir in dirs:
|
| 170 |
+
yield from self.gen(subdir)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class FNMatcher:
|
| 174 |
+
def __init__(self, pattern):
|
| 175 |
+
self.pattern = pattern
|
| 176 |
+
|
| 177 |
+
def __call__(self, path):
|
| 178 |
+
pattern = self.pattern
|
| 179 |
+
|
| 180 |
+
if (
|
| 181 |
+
pattern.find(path.sep) == -1
|
| 182 |
+
and iswin32
|
| 183 |
+
and pattern.find(posixpath.sep) != -1
|
| 184 |
+
):
|
| 185 |
+
# Running on Windows, the pattern has no Windows path separators,
|
| 186 |
+
# and the pattern has one or more Posix path separators. Replace
|
| 187 |
+
# the Posix path separators with the Windows path separator.
|
| 188 |
+
pattern = pattern.replace(posixpath.sep, path.sep)
|
| 189 |
+
|
| 190 |
+
if pattern.find(path.sep) == -1:
|
| 191 |
+
name = path.basename
|
| 192 |
+
else:
|
| 193 |
+
name = str(path) # path.strpath # XXX svn?
|
| 194 |
+
if not os.path.isabs(pattern):
|
| 195 |
+
pattern = "*" + path.sep + pattern
|
| 196 |
+
return fnmatch.fnmatch(name, pattern)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def map_as_list(func, iter):
|
| 200 |
+
return list(map(func, iter))
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class Stat:
|
| 204 |
+
if TYPE_CHECKING:
|
| 205 |
+
|
| 206 |
+
@property
|
| 207 |
+
def size(self) -> int: ...
|
| 208 |
+
|
| 209 |
+
@property
|
| 210 |
+
def mtime(self) -> float: ...
|
| 211 |
+
|
| 212 |
+
def __getattr__(self, name: str) -> Any:
|
| 213 |
+
return getattr(self._osstatresult, "st_" + name)
|
| 214 |
+
|
| 215 |
+
def __init__(self, path, osstatresult):
|
| 216 |
+
self.path = path
|
| 217 |
+
self._osstatresult = osstatresult
|
| 218 |
+
|
| 219 |
+
@property
|
| 220 |
+
def owner(self):
|
| 221 |
+
if iswin32:
|
| 222 |
+
raise NotImplementedError("XXX win32")
|
| 223 |
+
import pwd
|
| 224 |
+
|
| 225 |
+
entry = error.checked_call(pwd.getpwuid, self.uid) # type:ignore[attr-defined,unused-ignore]
|
| 226 |
+
return entry[0]
|
| 227 |
+
|
| 228 |
+
@property
|
| 229 |
+
def group(self):
|
| 230 |
+
"""Return group name of file."""
|
| 231 |
+
if iswin32:
|
| 232 |
+
raise NotImplementedError("XXX win32")
|
| 233 |
+
import grp
|
| 234 |
+
|
| 235 |
+
entry = error.checked_call(grp.getgrgid, self.gid) # type:ignore[attr-defined,unused-ignore]
|
| 236 |
+
return entry[0]
|
| 237 |
+
|
| 238 |
+
def isdir(self):
|
| 239 |
+
return S_ISDIR(self._osstatresult.st_mode)
|
| 240 |
+
|
| 241 |
+
def isfile(self):
|
| 242 |
+
return S_ISREG(self._osstatresult.st_mode)
|
| 243 |
+
|
| 244 |
+
def islink(self):
|
| 245 |
+
self.path.lstat()
|
| 246 |
+
return S_ISLNK(self._osstatresult.st_mode)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def getuserid(user):
|
| 250 |
+
import pwd
|
| 251 |
+
|
| 252 |
+
if not isinstance(user, int):
|
| 253 |
+
user = pwd.getpwnam(user)[2] # type:ignore[attr-defined,unused-ignore]
|
| 254 |
+
return user
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def getgroupid(group):
|
| 258 |
+
import grp
|
| 259 |
+
|
| 260 |
+
if not isinstance(group, int):
|
| 261 |
+
group = grp.getgrnam(group)[2] # type:ignore[attr-defined,unused-ignore]
|
| 262 |
+
return group
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
class LocalPath:
|
| 266 |
+
"""Object oriented interface to os.path and other local filesystem
|
| 267 |
+
related information.
|
| 268 |
+
"""
|
| 269 |
+
|
| 270 |
+
class ImportMismatchError(ImportError):
|
| 271 |
+
"""raised on pyimport() if there is a mismatch of __file__'s"""
|
| 272 |
+
|
| 273 |
+
sep = os.sep
|
| 274 |
+
|
| 275 |
+
def __init__(self, path=None, expanduser=False):
|
| 276 |
+
"""Initialize and return a local Path instance.
|
| 277 |
+
|
| 278 |
+
Path can be relative to the current directory.
|
| 279 |
+
If path is None it defaults to the current working directory.
|
| 280 |
+
If expanduser is True, tilde-expansion is performed.
|
| 281 |
+
Note that Path instances always carry an absolute path.
|
| 282 |
+
Note also that passing in a local path object will simply return
|
| 283 |
+
the exact same path object. Use new() to get a new copy.
|
| 284 |
+
"""
|
| 285 |
+
if path is None:
|
| 286 |
+
self.strpath = error.checked_call(os.getcwd)
|
| 287 |
+
else:
|
| 288 |
+
try:
|
| 289 |
+
path = os.fspath(path)
|
| 290 |
+
except TypeError:
|
| 291 |
+
raise ValueError(
|
| 292 |
+
"can only pass None, Path instances "
|
| 293 |
+
"or non-empty strings to LocalPath"
|
| 294 |
+
)
|
| 295 |
+
if expanduser:
|
| 296 |
+
path = os.path.expanduser(path)
|
| 297 |
+
self.strpath = abspath(path)
|
| 298 |
+
|
| 299 |
+
if sys.platform != "win32":
|
| 300 |
+
|
| 301 |
+
def chown(self, user, group, rec=0):
|
| 302 |
+
"""Change ownership to the given user and group.
|
| 303 |
+
user and group may be specified by a number or
|
| 304 |
+
by a name. if rec is True change ownership
|
| 305 |
+
recursively.
|
| 306 |
+
"""
|
| 307 |
+
uid = getuserid(user)
|
| 308 |
+
gid = getgroupid(group)
|
| 309 |
+
if rec:
|
| 310 |
+
for x in self.visit(rec=lambda x: x.check(link=0)):
|
| 311 |
+
if x.check(link=0):
|
| 312 |
+
error.checked_call(os.chown, str(x), uid, gid)
|
| 313 |
+
error.checked_call(os.chown, str(self), uid, gid)
|
| 314 |
+
|
| 315 |
+
def readlink(self) -> str:
|
| 316 |
+
"""Return value of a symbolic link."""
|
| 317 |
+
# https://github.com/python/mypy/issues/12278
|
| 318 |
+
return error.checked_call(os.readlink, self.strpath) # type: ignore[arg-type,return-value,unused-ignore]
|
| 319 |
+
|
| 320 |
+
def mklinkto(self, oldname):
|
| 321 |
+
"""Posix style hard link to another name."""
|
| 322 |
+
error.checked_call(os.link, str(oldname), str(self))
|
| 323 |
+
|
| 324 |
+
def mksymlinkto(self, value, absolute=1):
|
| 325 |
+
"""Create a symbolic link with the given value (pointing to another name)."""
|
| 326 |
+
if absolute:
|
| 327 |
+
error.checked_call(os.symlink, str(value), self.strpath)
|
| 328 |
+
else:
|
| 329 |
+
base = self.common(value)
|
| 330 |
+
# with posix local paths '/' is always a common base
|
| 331 |
+
relsource = self.__class__(value).relto(base)
|
| 332 |
+
reldest = self.relto(base)
|
| 333 |
+
n = reldest.count(self.sep)
|
| 334 |
+
target = self.sep.join(("..",) * n + (relsource,))
|
| 335 |
+
error.checked_call(os.symlink, target, self.strpath)
|
| 336 |
+
|
| 337 |
+
def __div__(self, other):
|
| 338 |
+
return self.join(os.fspath(other))
|
| 339 |
+
|
| 340 |
+
__truediv__ = __div__ # py3k
|
| 341 |
+
|
| 342 |
+
@property
|
| 343 |
+
def basename(self):
|
| 344 |
+
"""Basename part of path."""
|
| 345 |
+
return self._getbyspec("basename")[0]
|
| 346 |
+
|
| 347 |
+
@property
|
| 348 |
+
def dirname(self):
|
| 349 |
+
"""Dirname part of path."""
|
| 350 |
+
return self._getbyspec("dirname")[0]
|
| 351 |
+
|
| 352 |
+
@property
|
| 353 |
+
def purebasename(self):
|
| 354 |
+
"""Pure base name of the path."""
|
| 355 |
+
return self._getbyspec("purebasename")[0]
|
| 356 |
+
|
| 357 |
+
@property
|
| 358 |
+
def ext(self):
|
| 359 |
+
"""Extension of the path (including the '.')."""
|
| 360 |
+
return self._getbyspec("ext")[0]
|
| 361 |
+
|
| 362 |
+
def read_binary(self):
|
| 363 |
+
"""Read and return a bytestring from reading the path."""
|
| 364 |
+
with self.open("rb") as f:
|
| 365 |
+
return f.read()
|
| 366 |
+
|
| 367 |
+
def read_text(self, encoding):
|
| 368 |
+
"""Read and return a Unicode string from reading the path."""
|
| 369 |
+
with self.open("r", encoding=encoding) as f:
|
| 370 |
+
return f.read()
|
| 371 |
+
|
| 372 |
+
def read(self, mode="r"):
|
| 373 |
+
"""Read and return a bytestring from reading the path."""
|
| 374 |
+
with self.open(mode) as f:
|
| 375 |
+
return f.read()
|
| 376 |
+
|
| 377 |
+
def readlines(self, cr=1):
|
| 378 |
+
"""Read and return a list of lines from the path. if cr is False, the
|
| 379 |
+
newline will be removed from the end of each line."""
|
| 380 |
+
mode = "r"
|
| 381 |
+
|
| 382 |
+
if not cr:
|
| 383 |
+
content = self.read(mode)
|
| 384 |
+
return content.split("\n")
|
| 385 |
+
else:
|
| 386 |
+
f = self.open(mode)
|
| 387 |
+
try:
|
| 388 |
+
return f.readlines()
|
| 389 |
+
finally:
|
| 390 |
+
f.close()
|
| 391 |
+
|
| 392 |
+
def load(self):
|
| 393 |
+
"""(deprecated) return object unpickled from self.read()"""
|
| 394 |
+
f = self.open("rb")
|
| 395 |
+
try:
|
| 396 |
+
import pickle
|
| 397 |
+
|
| 398 |
+
return error.checked_call(pickle.load, f)
|
| 399 |
+
finally:
|
| 400 |
+
f.close()
|
| 401 |
+
|
| 402 |
+
def move(self, target):
|
| 403 |
+
"""Move this path to target."""
|
| 404 |
+
if target.relto(self):
|
| 405 |
+
raise error.EINVAL(target, "cannot move path into a subdirectory of itself")
|
| 406 |
+
try:
|
| 407 |
+
self.rename(target)
|
| 408 |
+
except error.EXDEV: # invalid cross-device link
|
| 409 |
+
self.copy(target)
|
| 410 |
+
self.remove()
|
| 411 |
+
|
| 412 |
+
def fnmatch(self, pattern):
|
| 413 |
+
"""Return true if the basename/fullname matches the glob-'pattern'.
|
| 414 |
+
|
| 415 |
+
valid pattern characters::
|
| 416 |
+
|
| 417 |
+
* matches everything
|
| 418 |
+
? matches any single character
|
| 419 |
+
[seq] matches any character in seq
|
| 420 |
+
[!seq] matches any char not in seq
|
| 421 |
+
|
| 422 |
+
If the pattern contains a path-separator then the full path
|
| 423 |
+
is used for pattern matching and a '*' is prepended to the
|
| 424 |
+
pattern.
|
| 425 |
+
|
| 426 |
+
if the pattern doesn't contain a path-separator the pattern
|
| 427 |
+
is only matched against the basename.
|
| 428 |
+
"""
|
| 429 |
+
return FNMatcher(pattern)(self)
|
| 430 |
+
|
| 431 |
+
def relto(self, relpath):
|
| 432 |
+
"""Return a string which is the relative part of the path
|
| 433 |
+
to the given 'relpath'.
|
| 434 |
+
"""
|
| 435 |
+
if not isinstance(relpath, (str, LocalPath)):
|
| 436 |
+
raise TypeError(f"{relpath!r}: not a string or path object")
|
| 437 |
+
strrelpath = str(relpath)
|
| 438 |
+
if strrelpath and strrelpath[-1] != self.sep:
|
| 439 |
+
strrelpath += self.sep
|
| 440 |
+
# assert strrelpath[-1] == self.sep
|
| 441 |
+
# assert strrelpath[-2] != self.sep
|
| 442 |
+
strself = self.strpath
|
| 443 |
+
if sys.platform == "win32" or getattr(os, "_name", None) == "nt":
|
| 444 |
+
if os.path.normcase(strself).startswith(os.path.normcase(strrelpath)):
|
| 445 |
+
return strself[len(strrelpath) :]
|
| 446 |
+
elif strself.startswith(strrelpath):
|
| 447 |
+
return strself[len(strrelpath) :]
|
| 448 |
+
return ""
|
| 449 |
+
|
| 450 |
+
def ensure_dir(self, *args):
|
| 451 |
+
"""Ensure the path joined with args is a directory."""
|
| 452 |
+
return self.ensure(*args, dir=True)
|
| 453 |
+
|
| 454 |
+
def bestrelpath(self, dest):
|
| 455 |
+
"""Return a string which is a relative path from self
|
| 456 |
+
(assumed to be a directory) to dest such that
|
| 457 |
+
self.join(bestrelpath) == dest and if not such
|
| 458 |
+
path can be determined return dest.
|
| 459 |
+
"""
|
| 460 |
+
try:
|
| 461 |
+
if self == dest:
|
| 462 |
+
return os.curdir
|
| 463 |
+
base = self.common(dest)
|
| 464 |
+
if not base: # can be the case on windows
|
| 465 |
+
return str(dest)
|
| 466 |
+
self2base = self.relto(base)
|
| 467 |
+
reldest = dest.relto(base)
|
| 468 |
+
if self2base:
|
| 469 |
+
n = self2base.count(self.sep) + 1
|
| 470 |
+
else:
|
| 471 |
+
n = 0
|
| 472 |
+
lst = [os.pardir] * n
|
| 473 |
+
if reldest:
|
| 474 |
+
lst.append(reldest)
|
| 475 |
+
target = dest.sep.join(lst)
|
| 476 |
+
return target
|
| 477 |
+
except AttributeError:
|
| 478 |
+
return str(dest)
|
| 479 |
+
|
| 480 |
+
def exists(self):
|
| 481 |
+
return self.check()
|
| 482 |
+
|
| 483 |
+
def isdir(self):
|
| 484 |
+
return self.check(dir=1)
|
| 485 |
+
|
| 486 |
+
def isfile(self):
|
| 487 |
+
return self.check(file=1)
|
| 488 |
+
|
| 489 |
+
def parts(self, reverse=False):
|
| 490 |
+
"""Return a root-first list of all ancestor directories
|
| 491 |
+
plus the path itself.
|
| 492 |
+
"""
|
| 493 |
+
current = self
|
| 494 |
+
lst = [self]
|
| 495 |
+
while 1:
|
| 496 |
+
last = current
|
| 497 |
+
current = current.dirpath()
|
| 498 |
+
if last == current:
|
| 499 |
+
break
|
| 500 |
+
lst.append(current)
|
| 501 |
+
if not reverse:
|
| 502 |
+
lst.reverse()
|
| 503 |
+
return lst
|
| 504 |
+
|
| 505 |
+
def common(self, other):
|
| 506 |
+
"""Return the common part shared with the other path
|
| 507 |
+
or None if there is no common part.
|
| 508 |
+
"""
|
| 509 |
+
last = None
|
| 510 |
+
for x, y in zip(self.parts(), other.parts()):
|
| 511 |
+
if x != y:
|
| 512 |
+
return last
|
| 513 |
+
last = x
|
| 514 |
+
return last
|
| 515 |
+
|
| 516 |
+
def __add__(self, other):
|
| 517 |
+
"""Return new path object with 'other' added to the basename"""
|
| 518 |
+
return self.new(basename=self.basename + str(other))
|
| 519 |
+
|
| 520 |
+
def visit(self, fil=None, rec=None, ignore=NeverRaised, bf=False, sort=False):
|
| 521 |
+
"""Yields all paths below the current one
|
| 522 |
+
|
| 523 |
+
fil is a filter (glob pattern or callable), if not matching the
|
| 524 |
+
path will not be yielded, defaulting to None (everything is
|
| 525 |
+
returned)
|
| 526 |
+
|
| 527 |
+
rec is a filter (glob pattern or callable) that controls whether
|
| 528 |
+
a node is descended, defaulting to None
|
| 529 |
+
|
| 530 |
+
ignore is an Exception class that is ignoredwhen calling dirlist()
|
| 531 |
+
on any of the paths (by default, all exceptions are reported)
|
| 532 |
+
|
| 533 |
+
bf if True will cause a breadthfirst search instead of the
|
| 534 |
+
default depthfirst. Default: False
|
| 535 |
+
|
| 536 |
+
sort if True will sort entries within each directory level.
|
| 537 |
+
"""
|
| 538 |
+
yield from Visitor(fil, rec, ignore, bf, sort).gen(self)
|
| 539 |
+
|
| 540 |
+
def _sortlist(self, res, sort):
|
| 541 |
+
if sort:
|
| 542 |
+
if hasattr(sort, "__call__"):
|
| 543 |
+
warnings.warn(
|
| 544 |
+
DeprecationWarning(
|
| 545 |
+
"listdir(sort=callable) is deprecated and breaks on python3"
|
| 546 |
+
),
|
| 547 |
+
stacklevel=3,
|
| 548 |
+
)
|
| 549 |
+
res.sort(sort)
|
| 550 |
+
else:
|
| 551 |
+
res.sort()
|
| 552 |
+
|
| 553 |
+
def __fspath__(self):
|
| 554 |
+
return self.strpath
|
| 555 |
+
|
| 556 |
+
def __hash__(self):
|
| 557 |
+
s = self.strpath
|
| 558 |
+
if iswin32:
|
| 559 |
+
s = s.lower()
|
| 560 |
+
return hash(s)
|
| 561 |
+
|
| 562 |
+
def __eq__(self, other):
|
| 563 |
+
s1 = os.fspath(self)
|
| 564 |
+
try:
|
| 565 |
+
s2 = os.fspath(other)
|
| 566 |
+
except TypeError:
|
| 567 |
+
return False
|
| 568 |
+
if iswin32:
|
| 569 |
+
s1 = s1.lower()
|
| 570 |
+
try:
|
| 571 |
+
s2 = s2.lower()
|
| 572 |
+
except AttributeError:
|
| 573 |
+
return False
|
| 574 |
+
return s1 == s2
|
| 575 |
+
|
| 576 |
+
def __ne__(self, other):
|
| 577 |
+
return not (self == other)
|
| 578 |
+
|
| 579 |
+
def __lt__(self, other):
|
| 580 |
+
return os.fspath(self) < os.fspath(other)
|
| 581 |
+
|
| 582 |
+
def __gt__(self, other):
|
| 583 |
+
return os.fspath(self) > os.fspath(other)
|
| 584 |
+
|
| 585 |
+
def samefile(self, other):
|
| 586 |
+
"""Return True if 'other' references the same file as 'self'."""
|
| 587 |
+
other = os.fspath(other)
|
| 588 |
+
if not isabs(other):
|
| 589 |
+
other = abspath(other)
|
| 590 |
+
if self == other:
|
| 591 |
+
return True
|
| 592 |
+
if not hasattr(os.path, "samefile"):
|
| 593 |
+
return False
|
| 594 |
+
return error.checked_call(os.path.samefile, self.strpath, other)
|
| 595 |
+
|
| 596 |
+
def remove(self, rec=1, ignore_errors=False):
|
| 597 |
+
"""Remove a file or directory (or a directory tree if rec=1).
|
| 598 |
+
if ignore_errors is True, errors while removing directories will
|
| 599 |
+
be ignored.
|
| 600 |
+
"""
|
| 601 |
+
if self.check(dir=1, link=0):
|
| 602 |
+
if rec:
|
| 603 |
+
# force remove of readonly files on windows
|
| 604 |
+
if iswin32:
|
| 605 |
+
self.chmod(0o700, rec=1)
|
| 606 |
+
import shutil
|
| 607 |
+
|
| 608 |
+
error.checked_call(
|
| 609 |
+
shutil.rmtree, self.strpath, ignore_errors=ignore_errors
|
| 610 |
+
)
|
| 611 |
+
else:
|
| 612 |
+
error.checked_call(os.rmdir, self.strpath)
|
| 613 |
+
else:
|
| 614 |
+
if iswin32:
|
| 615 |
+
self.chmod(0o700)
|
| 616 |
+
error.checked_call(os.remove, self.strpath)
|
| 617 |
+
|
| 618 |
+
def computehash(self, hashtype="md5", chunksize=524288):
|
| 619 |
+
"""Return hexdigest of hashvalue for this file."""
|
| 620 |
+
try:
|
| 621 |
+
try:
|
| 622 |
+
import hashlib as mod
|
| 623 |
+
except ImportError:
|
| 624 |
+
if hashtype == "sha1":
|
| 625 |
+
hashtype = "sha"
|
| 626 |
+
mod = __import__(hashtype)
|
| 627 |
+
hash = getattr(mod, hashtype)()
|
| 628 |
+
except (AttributeError, ImportError):
|
| 629 |
+
raise ValueError(f"Don't know how to compute {hashtype!r} hash")
|
| 630 |
+
f = self.open("rb")
|
| 631 |
+
try:
|
| 632 |
+
while 1:
|
| 633 |
+
buf = f.read(chunksize)
|
| 634 |
+
if not buf:
|
| 635 |
+
return hash.hexdigest()
|
| 636 |
+
hash.update(buf)
|
| 637 |
+
finally:
|
| 638 |
+
f.close()
|
| 639 |
+
|
| 640 |
+
def new(self, **kw):
|
| 641 |
+
"""Create a modified version of this path.
|
| 642 |
+
the following keyword arguments modify various path parts::
|
| 643 |
+
|
| 644 |
+
a:/some/path/to/a/file.ext
|
| 645 |
+
xx drive
|
| 646 |
+
xxxxxxxxxxxxxxxxx dirname
|
| 647 |
+
xxxxxxxx basename
|
| 648 |
+
xxxx purebasename
|
| 649 |
+
xxx ext
|
| 650 |
+
"""
|
| 651 |
+
obj = object.__new__(self.__class__)
|
| 652 |
+
if not kw:
|
| 653 |
+
obj.strpath = self.strpath
|
| 654 |
+
return obj
|
| 655 |
+
drive, dirname, basename, purebasename, ext = self._getbyspec(
|
| 656 |
+
"drive,dirname,basename,purebasename,ext"
|
| 657 |
+
)
|
| 658 |
+
if "basename" in kw:
|
| 659 |
+
if "purebasename" in kw or "ext" in kw:
|
| 660 |
+
raise ValueError(f"invalid specification {kw!r}")
|
| 661 |
+
else:
|
| 662 |
+
pb = kw.setdefault("purebasename", purebasename)
|
| 663 |
+
try:
|
| 664 |
+
ext = kw["ext"]
|
| 665 |
+
except KeyError:
|
| 666 |
+
pass
|
| 667 |
+
else:
|
| 668 |
+
if ext and not ext.startswith("."):
|
| 669 |
+
ext = "." + ext
|
| 670 |
+
kw["basename"] = pb + ext
|
| 671 |
+
|
| 672 |
+
if "dirname" in kw and not kw["dirname"]:
|
| 673 |
+
kw["dirname"] = drive
|
| 674 |
+
else:
|
| 675 |
+
kw.setdefault("dirname", dirname)
|
| 676 |
+
kw.setdefault("sep", self.sep)
|
| 677 |
+
obj.strpath = normpath("{dirname}{sep}{basename}".format(**kw))
|
| 678 |
+
return obj
|
| 679 |
+
|
| 680 |
+
def _getbyspec(self, spec: str) -> list[str]:
|
| 681 |
+
"""See new for what 'spec' can be."""
|
| 682 |
+
res = []
|
| 683 |
+
parts = self.strpath.split(self.sep)
|
| 684 |
+
|
| 685 |
+
args = filter(None, spec.split(","))
|
| 686 |
+
for name in args:
|
| 687 |
+
if name == "drive":
|
| 688 |
+
res.append(parts[0])
|
| 689 |
+
elif name == "dirname":
|
| 690 |
+
res.append(self.sep.join(parts[:-1]))
|
| 691 |
+
else:
|
| 692 |
+
basename = parts[-1]
|
| 693 |
+
if name == "basename":
|
| 694 |
+
res.append(basename)
|
| 695 |
+
else:
|
| 696 |
+
i = basename.rfind(".")
|
| 697 |
+
if i == -1:
|
| 698 |
+
purebasename, ext = basename, ""
|
| 699 |
+
else:
|
| 700 |
+
purebasename, ext = basename[:i], basename[i:]
|
| 701 |
+
if name == "purebasename":
|
| 702 |
+
res.append(purebasename)
|
| 703 |
+
elif name == "ext":
|
| 704 |
+
res.append(ext)
|
| 705 |
+
else:
|
| 706 |
+
raise ValueError(f"invalid part specification {name!r}")
|
| 707 |
+
return res
|
| 708 |
+
|
| 709 |
+
def dirpath(self, *args, **kwargs):
|
| 710 |
+
"""Return the directory path joined with any given path arguments."""
|
| 711 |
+
if not kwargs:
|
| 712 |
+
path = object.__new__(self.__class__)
|
| 713 |
+
path.strpath = dirname(self.strpath)
|
| 714 |
+
if args:
|
| 715 |
+
path = path.join(*args)
|
| 716 |
+
return path
|
| 717 |
+
return self.new(basename="").join(*args, **kwargs)
|
| 718 |
+
|
| 719 |
+
def join(self, *args: os.PathLike[str], abs: bool = False) -> LocalPath:
|
| 720 |
+
"""Return a new path by appending all 'args' as path
|
| 721 |
+
components. if abs=1 is used restart from root if any
|
| 722 |
+
of the args is an absolute path.
|
| 723 |
+
"""
|
| 724 |
+
sep = self.sep
|
| 725 |
+
strargs = [os.fspath(arg) for arg in args]
|
| 726 |
+
strpath = self.strpath
|
| 727 |
+
if abs:
|
| 728 |
+
newargs: list[str] = []
|
| 729 |
+
for arg in reversed(strargs):
|
| 730 |
+
if isabs(arg):
|
| 731 |
+
strpath = arg
|
| 732 |
+
strargs = newargs
|
| 733 |
+
break
|
| 734 |
+
newargs.insert(0, arg)
|
| 735 |
+
# special case for when we have e.g. strpath == "/"
|
| 736 |
+
actual_sep = "" if strpath.endswith(sep) else sep
|
| 737 |
+
for arg in strargs:
|
| 738 |
+
arg = arg.strip(sep)
|
| 739 |
+
if iswin32:
|
| 740 |
+
# allow unix style paths even on windows.
|
| 741 |
+
arg = arg.strip("/")
|
| 742 |
+
arg = arg.replace("/", sep)
|
| 743 |
+
strpath = strpath + actual_sep + arg
|
| 744 |
+
actual_sep = sep
|
| 745 |
+
obj = object.__new__(self.__class__)
|
| 746 |
+
obj.strpath = normpath(strpath)
|
| 747 |
+
return obj
|
| 748 |
+
|
| 749 |
+
def open(self, mode="r", ensure=False, encoding=None):
|
| 750 |
+
"""Return an opened file with the given mode.
|
| 751 |
+
|
| 752 |
+
If ensure is True, create parent directories if needed.
|
| 753 |
+
"""
|
| 754 |
+
if ensure:
|
| 755 |
+
self.dirpath().ensure(dir=1)
|
| 756 |
+
if encoding:
|
| 757 |
+
return error.checked_call(
|
| 758 |
+
io.open,
|
| 759 |
+
self.strpath,
|
| 760 |
+
mode,
|
| 761 |
+
encoding=encoding,
|
| 762 |
+
)
|
| 763 |
+
return error.checked_call(open, self.strpath, mode)
|
| 764 |
+
|
| 765 |
+
def _fastjoin(self, name):
|
| 766 |
+
child = object.__new__(self.__class__)
|
| 767 |
+
child.strpath = self.strpath + self.sep + name
|
| 768 |
+
return child
|
| 769 |
+
|
| 770 |
+
def islink(self):
|
| 771 |
+
return islink(self.strpath)
|
| 772 |
+
|
| 773 |
+
def check(self, **kw):
|
| 774 |
+
"""Check a path for existence and properties.
|
| 775 |
+
|
| 776 |
+
Without arguments, return True if the path exists, otherwise False.
|
| 777 |
+
|
| 778 |
+
valid checkers::
|
| 779 |
+
|
| 780 |
+
file = 1 # is a file
|
| 781 |
+
file = 0 # is not a file (may not even exist)
|
| 782 |
+
dir = 1 # is a dir
|
| 783 |
+
link = 1 # is a link
|
| 784 |
+
exists = 1 # exists
|
| 785 |
+
|
| 786 |
+
You can specify multiple checker definitions, for example::
|
| 787 |
+
|
| 788 |
+
path.check(file=1, link=1) # a link pointing to a file
|
| 789 |
+
"""
|
| 790 |
+
if not kw:
|
| 791 |
+
return exists(self.strpath)
|
| 792 |
+
if len(kw) == 1:
|
| 793 |
+
if "dir" in kw:
|
| 794 |
+
return not kw["dir"] ^ isdir(self.strpath)
|
| 795 |
+
if "file" in kw:
|
| 796 |
+
return not kw["file"] ^ isfile(self.strpath)
|
| 797 |
+
if not kw:
|
| 798 |
+
kw = {"exists": 1}
|
| 799 |
+
return Checkers(self)._evaluate(kw)
|
| 800 |
+
|
| 801 |
+
_patternchars = set("*?[" + os.sep)
|
| 802 |
+
|
| 803 |
+
def listdir(self, fil=None, sort=None):
|
| 804 |
+
"""List directory contents, possibly filter by the given fil func
|
| 805 |
+
and possibly sorted.
|
| 806 |
+
"""
|
| 807 |
+
if fil is None and sort is None:
|
| 808 |
+
names = error.checked_call(os.listdir, self.strpath)
|
| 809 |
+
return map_as_list(self._fastjoin, names)
|
| 810 |
+
if isinstance(fil, str):
|
| 811 |
+
if not self._patternchars.intersection(fil):
|
| 812 |
+
child = self._fastjoin(fil)
|
| 813 |
+
if exists(child.strpath):
|
| 814 |
+
return [child]
|
| 815 |
+
return []
|
| 816 |
+
fil = FNMatcher(fil)
|
| 817 |
+
names = error.checked_call(os.listdir, self.strpath)
|
| 818 |
+
res = []
|
| 819 |
+
for name in names:
|
| 820 |
+
child = self._fastjoin(name)
|
| 821 |
+
if fil is None or fil(child):
|
| 822 |
+
res.append(child)
|
| 823 |
+
self._sortlist(res, sort)
|
| 824 |
+
return res
|
| 825 |
+
|
| 826 |
+
def size(self) -> int:
|
| 827 |
+
"""Return size of the underlying file object"""
|
| 828 |
+
return self.stat().size
|
| 829 |
+
|
| 830 |
+
def mtime(self) -> float:
|
| 831 |
+
"""Return last modification time of the path."""
|
| 832 |
+
return self.stat().mtime
|
| 833 |
+
|
| 834 |
+
def copy(self, target, mode=False, stat=False):
|
| 835 |
+
"""Copy path to target.
|
| 836 |
+
|
| 837 |
+
If mode is True, will copy permission from path to target.
|
| 838 |
+
If stat is True, copy permission, last modification
|
| 839 |
+
time, last access time, and flags from path to target.
|
| 840 |
+
"""
|
| 841 |
+
if self.check(file=1):
|
| 842 |
+
if target.check(dir=1):
|
| 843 |
+
target = target.join(self.basename)
|
| 844 |
+
assert self != target
|
| 845 |
+
copychunked(self, target)
|
| 846 |
+
if mode:
|
| 847 |
+
copymode(self.strpath, target.strpath)
|
| 848 |
+
if stat:
|
| 849 |
+
copystat(self, target)
|
| 850 |
+
else:
|
| 851 |
+
|
| 852 |
+
def rec(p):
|
| 853 |
+
return p.check(link=0)
|
| 854 |
+
|
| 855 |
+
for x in self.visit(rec=rec):
|
| 856 |
+
relpath = x.relto(self)
|
| 857 |
+
newx = target.join(relpath)
|
| 858 |
+
newx.dirpath().ensure(dir=1)
|
| 859 |
+
if x.check(link=1):
|
| 860 |
+
newx.mksymlinkto(x.readlink())
|
| 861 |
+
continue
|
| 862 |
+
elif x.check(file=1):
|
| 863 |
+
copychunked(x, newx)
|
| 864 |
+
elif x.check(dir=1):
|
| 865 |
+
newx.ensure(dir=1)
|
| 866 |
+
if mode:
|
| 867 |
+
copymode(x.strpath, newx.strpath)
|
| 868 |
+
if stat:
|
| 869 |
+
copystat(x, newx)
|
| 870 |
+
|
| 871 |
+
def rename(self, target):
|
| 872 |
+
"""Rename this path to target."""
|
| 873 |
+
target = os.fspath(target)
|
| 874 |
+
return error.checked_call(os.rename, self.strpath, target)
|
| 875 |
+
|
| 876 |
+
def dump(self, obj, bin=1):
|
| 877 |
+
"""Pickle object into path location"""
|
| 878 |
+
f = self.open("wb")
|
| 879 |
+
import pickle
|
| 880 |
+
|
| 881 |
+
try:
|
| 882 |
+
error.checked_call(pickle.dump, obj, f, bin)
|
| 883 |
+
finally:
|
| 884 |
+
f.close()
|
| 885 |
+
|
| 886 |
+
def mkdir(self, *args):
|
| 887 |
+
"""Create & return the directory joined with args."""
|
| 888 |
+
p = self.join(*args)
|
| 889 |
+
error.checked_call(os.mkdir, os.fspath(p))
|
| 890 |
+
return p
|
| 891 |
+
|
| 892 |
+
def write_binary(self, data, ensure=False):
|
| 893 |
+
"""Write binary data into path. If ensure is True create
|
| 894 |
+
missing parent directories.
|
| 895 |
+
"""
|
| 896 |
+
if ensure:
|
| 897 |
+
self.dirpath().ensure(dir=1)
|
| 898 |
+
with self.open("wb") as f:
|
| 899 |
+
f.write(data)
|
| 900 |
+
|
| 901 |
+
def write_text(self, data, encoding, ensure=False):
|
| 902 |
+
"""Write text data into path using the specified encoding.
|
| 903 |
+
If ensure is True create missing parent directories.
|
| 904 |
+
"""
|
| 905 |
+
if ensure:
|
| 906 |
+
self.dirpath().ensure(dir=1)
|
| 907 |
+
with self.open("w", encoding=encoding) as f:
|
| 908 |
+
f.write(data)
|
| 909 |
+
|
| 910 |
+
def write(self, data, mode="w", ensure=False):
|
| 911 |
+
"""Write data into path. If ensure is True create
|
| 912 |
+
missing parent directories.
|
| 913 |
+
"""
|
| 914 |
+
if ensure:
|
| 915 |
+
self.dirpath().ensure(dir=1)
|
| 916 |
+
if "b" in mode:
|
| 917 |
+
if not isinstance(data, bytes):
|
| 918 |
+
raise ValueError("can only process bytes")
|
| 919 |
+
else:
|
| 920 |
+
if not isinstance(data, str):
|
| 921 |
+
if not isinstance(data, bytes):
|
| 922 |
+
data = str(data)
|
| 923 |
+
else:
|
| 924 |
+
data = data.decode(sys.getdefaultencoding())
|
| 925 |
+
f = self.open(mode)
|
| 926 |
+
try:
|
| 927 |
+
f.write(data)
|
| 928 |
+
finally:
|
| 929 |
+
f.close()
|
| 930 |
+
|
| 931 |
+
def _ensuredirs(self):
|
| 932 |
+
parent = self.dirpath()
|
| 933 |
+
if parent == self:
|
| 934 |
+
return self
|
| 935 |
+
if parent.check(dir=0):
|
| 936 |
+
parent._ensuredirs()
|
| 937 |
+
if self.check(dir=0):
|
| 938 |
+
try:
|
| 939 |
+
self.mkdir()
|
| 940 |
+
except error.EEXIST:
|
| 941 |
+
# race condition: file/dir created by another thread/process.
|
| 942 |
+
# complain if it is not a dir
|
| 943 |
+
if self.check(dir=0):
|
| 944 |
+
raise
|
| 945 |
+
return self
|
| 946 |
+
|
| 947 |
+
def ensure(self, *args, **kwargs):
|
| 948 |
+
"""Ensure that an args-joined path exists (by default as
|
| 949 |
+
a file). if you specify a keyword argument 'dir=True'
|
| 950 |
+
then the path is forced to be a directory path.
|
| 951 |
+
"""
|
| 952 |
+
p = self.join(*args)
|
| 953 |
+
if kwargs.get("dir", 0):
|
| 954 |
+
return p._ensuredirs()
|
| 955 |
+
else:
|
| 956 |
+
p.dirpath()._ensuredirs()
|
| 957 |
+
if not p.check(file=1):
|
| 958 |
+
p.open("wb").close()
|
| 959 |
+
return p
|
| 960 |
+
|
| 961 |
+
@overload
|
| 962 |
+
def stat(self, raising: Literal[True] = ...) -> Stat: ...
|
| 963 |
+
|
| 964 |
+
@overload
|
| 965 |
+
def stat(self, raising: Literal[False]) -> Stat | None: ...
|
| 966 |
+
|
| 967 |
+
def stat(self, raising: bool = True) -> Stat | None:
|
| 968 |
+
"""Return an os.stat() tuple."""
|
| 969 |
+
if raising:
|
| 970 |
+
return Stat(self, error.checked_call(os.stat, self.strpath))
|
| 971 |
+
try:
|
| 972 |
+
return Stat(self, os.stat(self.strpath))
|
| 973 |
+
except KeyboardInterrupt:
|
| 974 |
+
raise
|
| 975 |
+
except Exception:
|
| 976 |
+
return None
|
| 977 |
+
|
| 978 |
+
def lstat(self) -> Stat:
|
| 979 |
+
"""Return an os.lstat() tuple."""
|
| 980 |
+
return Stat(self, error.checked_call(os.lstat, self.strpath))
|
| 981 |
+
|
| 982 |
+
def setmtime(self, mtime=None):
|
| 983 |
+
"""Set modification time for the given path. if 'mtime' is None
|
| 984 |
+
(the default) then the file's mtime is set to current time.
|
| 985 |
+
|
| 986 |
+
Note that the resolution for 'mtime' is platform dependent.
|
| 987 |
+
"""
|
| 988 |
+
if mtime is None:
|
| 989 |
+
return error.checked_call(os.utime, self.strpath, mtime)
|
| 990 |
+
try:
|
| 991 |
+
return error.checked_call(os.utime, self.strpath, (-1, mtime))
|
| 992 |
+
except error.EINVAL:
|
| 993 |
+
return error.checked_call(os.utime, self.strpath, (self.atime(), mtime))
|
| 994 |
+
|
| 995 |
+
def chdir(self):
|
| 996 |
+
"""Change directory to self and return old current directory"""
|
| 997 |
+
try:
|
| 998 |
+
old = self.__class__()
|
| 999 |
+
except error.ENOENT:
|
| 1000 |
+
old = None
|
| 1001 |
+
error.checked_call(os.chdir, self.strpath)
|
| 1002 |
+
return old
|
| 1003 |
+
|
| 1004 |
+
@contextmanager
|
| 1005 |
+
def as_cwd(self):
|
| 1006 |
+
"""
|
| 1007 |
+
Return a context manager, which changes to the path's dir during the
|
| 1008 |
+
managed "with" context.
|
| 1009 |
+
On __enter__ it returns the old dir, which might be ``None``.
|
| 1010 |
+
"""
|
| 1011 |
+
old = self.chdir()
|
| 1012 |
+
try:
|
| 1013 |
+
yield old
|
| 1014 |
+
finally:
|
| 1015 |
+
if old is not None:
|
| 1016 |
+
old.chdir()
|
| 1017 |
+
|
| 1018 |
+
def realpath(self):
|
| 1019 |
+
"""Return a new path which contains no symbolic links."""
|
| 1020 |
+
return self.__class__(os.path.realpath(self.strpath))
|
| 1021 |
+
|
| 1022 |
+
def atime(self):
|
| 1023 |
+
"""Return last access time of the path."""
|
| 1024 |
+
return self.stat().atime
|
| 1025 |
+
|
| 1026 |
+
def __repr__(self):
|
| 1027 |
+
return f"local({self.strpath!r})"
|
| 1028 |
+
|
| 1029 |
+
def __str__(self):
|
| 1030 |
+
"""Return string representation of the Path."""
|
| 1031 |
+
return self.strpath
|
| 1032 |
+
|
| 1033 |
+
def chmod(self, mode, rec=0):
|
| 1034 |
+
"""Change permissions to the given mode. If mode is an
|
| 1035 |
+
integer it directly encodes the os-specific modes.
|
| 1036 |
+
if rec is True perform recursively.
|
| 1037 |
+
"""
|
| 1038 |
+
if not isinstance(mode, int):
|
| 1039 |
+
raise TypeError(f"mode {mode!r} must be an integer")
|
| 1040 |
+
if rec:
|
| 1041 |
+
for x in self.visit(rec=rec):
|
| 1042 |
+
error.checked_call(os.chmod, str(x), mode)
|
| 1043 |
+
error.checked_call(os.chmod, self.strpath, mode)
|
| 1044 |
+
|
| 1045 |
+
def pypkgpath(self):
|
| 1046 |
+
"""Return the Python package path by looking for the last
|
| 1047 |
+
directory upwards which still contains an __init__.py.
|
| 1048 |
+
Return None if a pkgpath cannot be determined.
|
| 1049 |
+
"""
|
| 1050 |
+
pkgpath = None
|
| 1051 |
+
for parent in self.parts(reverse=True):
|
| 1052 |
+
if parent.isdir():
|
| 1053 |
+
if not parent.join("__init__.py").exists():
|
| 1054 |
+
break
|
| 1055 |
+
if not isimportable(parent.basename):
|
| 1056 |
+
break
|
| 1057 |
+
pkgpath = parent
|
| 1058 |
+
return pkgpath
|
| 1059 |
+
|
| 1060 |
+
def _ensuresyspath(self, ensuremode, path):
|
| 1061 |
+
if ensuremode:
|
| 1062 |
+
s = str(path)
|
| 1063 |
+
if ensuremode == "append":
|
| 1064 |
+
if s not in sys.path:
|
| 1065 |
+
sys.path.append(s)
|
| 1066 |
+
else:
|
| 1067 |
+
if s != sys.path[0]:
|
| 1068 |
+
sys.path.insert(0, s)
|
| 1069 |
+
|
| 1070 |
+
def pyimport(self, modname=None, ensuresyspath=True):
|
| 1071 |
+
"""Return path as an imported python module.
|
| 1072 |
+
|
| 1073 |
+
If modname is None, look for the containing package
|
| 1074 |
+
and construct an according module name.
|
| 1075 |
+
The module will be put/looked up in sys.modules.
|
| 1076 |
+
if ensuresyspath is True then the root dir for importing
|
| 1077 |
+
the file (taking __init__.py files into account) will
|
| 1078 |
+
be prepended to sys.path if it isn't there already.
|
| 1079 |
+
If ensuresyspath=="append" the root dir will be appended
|
| 1080 |
+
if it isn't already contained in sys.path.
|
| 1081 |
+
if ensuresyspath is False no modification of syspath happens.
|
| 1082 |
+
|
| 1083 |
+
Special value of ensuresyspath=="importlib" is intended
|
| 1084 |
+
purely for using in pytest, it is capable only of importing
|
| 1085 |
+
separate .py files outside packages, e.g. for test suite
|
| 1086 |
+
without any __init__.py file. It effectively allows having
|
| 1087 |
+
same-named test modules in different places and offers
|
| 1088 |
+
mild opt-in via this option. Note that it works only in
|
| 1089 |
+
recent versions of python.
|
| 1090 |
+
"""
|
| 1091 |
+
if not self.check():
|
| 1092 |
+
raise error.ENOENT(self)
|
| 1093 |
+
|
| 1094 |
+
if ensuresyspath == "importlib":
|
| 1095 |
+
if modname is None:
|
| 1096 |
+
modname = self.purebasename
|
| 1097 |
+
spec = importlib.util.spec_from_file_location(modname, str(self))
|
| 1098 |
+
if spec is None or spec.loader is None:
|
| 1099 |
+
raise ImportError(f"Can't find module {modname} at location {self!s}")
|
| 1100 |
+
mod = importlib.util.module_from_spec(spec)
|
| 1101 |
+
spec.loader.exec_module(mod)
|
| 1102 |
+
return mod
|
| 1103 |
+
|
| 1104 |
+
pkgpath = None
|
| 1105 |
+
if modname is None:
|
| 1106 |
+
pkgpath = self.pypkgpath()
|
| 1107 |
+
if pkgpath is not None:
|
| 1108 |
+
pkgroot = pkgpath.dirpath()
|
| 1109 |
+
names = self.new(ext="").relto(pkgroot).split(self.sep)
|
| 1110 |
+
if names[-1] == "__init__":
|
| 1111 |
+
names.pop()
|
| 1112 |
+
modname = ".".join(names)
|
| 1113 |
+
else:
|
| 1114 |
+
pkgroot = self.dirpath()
|
| 1115 |
+
modname = self.purebasename
|
| 1116 |
+
|
| 1117 |
+
self._ensuresyspath(ensuresyspath, pkgroot)
|
| 1118 |
+
__import__(modname)
|
| 1119 |
+
mod = sys.modules[modname]
|
| 1120 |
+
if self.basename == "__init__.py":
|
| 1121 |
+
return mod # we don't check anything as we might
|
| 1122 |
+
# be in a namespace package ... too icky to check
|
| 1123 |
+
modfile = mod.__file__
|
| 1124 |
+
assert modfile is not None
|
| 1125 |
+
if modfile[-4:] in (".pyc", ".pyo"):
|
| 1126 |
+
modfile = modfile[:-1]
|
| 1127 |
+
elif modfile.endswith("$py.class"):
|
| 1128 |
+
modfile = modfile[:-9] + ".py"
|
| 1129 |
+
if modfile.endswith(os.sep + "__init__.py"):
|
| 1130 |
+
if self.basename != "__init__.py":
|
| 1131 |
+
modfile = modfile[:-12]
|
| 1132 |
+
try:
|
| 1133 |
+
issame = self.samefile(modfile)
|
| 1134 |
+
except error.ENOENT:
|
| 1135 |
+
issame = False
|
| 1136 |
+
if not issame:
|
| 1137 |
+
ignore = os.getenv("PY_IGNORE_IMPORTMISMATCH")
|
| 1138 |
+
if ignore != "1":
|
| 1139 |
+
raise self.ImportMismatchError(modname, modfile, self)
|
| 1140 |
+
return mod
|
| 1141 |
+
else:
|
| 1142 |
+
try:
|
| 1143 |
+
return sys.modules[modname]
|
| 1144 |
+
except KeyError:
|
| 1145 |
+
# we have a custom modname, do a pseudo-import
|
| 1146 |
+
import types
|
| 1147 |
+
|
| 1148 |
+
mod = types.ModuleType(modname)
|
| 1149 |
+
mod.__file__ = str(self)
|
| 1150 |
+
sys.modules[modname] = mod
|
| 1151 |
+
try:
|
| 1152 |
+
with open(str(self), "rb") as f:
|
| 1153 |
+
exec(f.read(), mod.__dict__)
|
| 1154 |
+
except BaseException:
|
| 1155 |
+
del sys.modules[modname]
|
| 1156 |
+
raise
|
| 1157 |
+
return mod
|
| 1158 |
+
|
| 1159 |
+
def sysexec(self, *argv: os.PathLike[str], **popen_opts: Any) -> str:
|
| 1160 |
+
"""Return stdout text from executing a system child process,
|
| 1161 |
+
where the 'self' path points to executable.
|
| 1162 |
+
The process is directly invoked and not through a system shell.
|
| 1163 |
+
"""
|
| 1164 |
+
from subprocess import PIPE
|
| 1165 |
+
from subprocess import Popen
|
| 1166 |
+
|
| 1167 |
+
popen_opts.pop("stdout", None)
|
| 1168 |
+
popen_opts.pop("stderr", None)
|
| 1169 |
+
proc = Popen(
|
| 1170 |
+
[str(self)] + [str(arg) for arg in argv],
|
| 1171 |
+
**popen_opts,
|
| 1172 |
+
stdout=PIPE,
|
| 1173 |
+
stderr=PIPE,
|
| 1174 |
+
)
|
| 1175 |
+
stdout: str | bytes
|
| 1176 |
+
stdout, stderr = proc.communicate()
|
| 1177 |
+
ret = proc.wait()
|
| 1178 |
+
if isinstance(stdout, bytes):
|
| 1179 |
+
stdout = stdout.decode(sys.getdefaultencoding())
|
| 1180 |
+
if ret != 0:
|
| 1181 |
+
if isinstance(stderr, bytes):
|
| 1182 |
+
stderr = stderr.decode(sys.getdefaultencoding())
|
| 1183 |
+
raise RuntimeError(
|
| 1184 |
+
ret,
|
| 1185 |
+
ret,
|
| 1186 |
+
str(self),
|
| 1187 |
+
stdout,
|
| 1188 |
+
stderr,
|
| 1189 |
+
)
|
| 1190 |
+
return stdout
|
| 1191 |
+
|
| 1192 |
+
@classmethod
|
| 1193 |
+
def sysfind(cls, name, checker=None, paths=None):
|
| 1194 |
+
"""Return a path object found by looking at the systems
|
| 1195 |
+
underlying PATH specification. If the checker is not None
|
| 1196 |
+
it will be invoked to filter matching paths. If a binary
|
| 1197 |
+
cannot be found, None is returned
|
| 1198 |
+
Note: This is probably not working on plain win32 systems
|
| 1199 |
+
but may work on cygwin.
|
| 1200 |
+
"""
|
| 1201 |
+
if isabs(name):
|
| 1202 |
+
p = local(name)
|
| 1203 |
+
if p.check(file=1):
|
| 1204 |
+
return p
|
| 1205 |
+
else:
|
| 1206 |
+
if paths is None:
|
| 1207 |
+
if iswin32:
|
| 1208 |
+
paths = os.environ["Path"].split(";")
|
| 1209 |
+
if "" not in paths and "." not in paths:
|
| 1210 |
+
paths.append(".")
|
| 1211 |
+
try:
|
| 1212 |
+
systemroot = os.environ["SYSTEMROOT"]
|
| 1213 |
+
except KeyError:
|
| 1214 |
+
pass
|
| 1215 |
+
else:
|
| 1216 |
+
paths = [
|
| 1217 |
+
path.replace("%SystemRoot%", systemroot) for path in paths
|
| 1218 |
+
]
|
| 1219 |
+
else:
|
| 1220 |
+
paths = os.environ["PATH"].split(":")
|
| 1221 |
+
tryadd = []
|
| 1222 |
+
if iswin32:
|
| 1223 |
+
tryadd += os.environ["PATHEXT"].split(os.pathsep)
|
| 1224 |
+
tryadd.append("")
|
| 1225 |
+
|
| 1226 |
+
for x in paths:
|
| 1227 |
+
for addext in tryadd:
|
| 1228 |
+
p = local(x).join(name, abs=True) + addext
|
| 1229 |
+
try:
|
| 1230 |
+
if p.check(file=1):
|
| 1231 |
+
if checker:
|
| 1232 |
+
if not checker(p):
|
| 1233 |
+
continue
|
| 1234 |
+
return p
|
| 1235 |
+
except error.EACCES:
|
| 1236 |
+
pass
|
| 1237 |
+
return None
|
| 1238 |
+
|
| 1239 |
+
@classmethod
|
| 1240 |
+
def _gethomedir(cls):
|
| 1241 |
+
try:
|
| 1242 |
+
x = os.environ["HOME"]
|
| 1243 |
+
except KeyError:
|
| 1244 |
+
try:
|
| 1245 |
+
x = os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"]
|
| 1246 |
+
except KeyError:
|
| 1247 |
+
return None
|
| 1248 |
+
return cls(x)
|
| 1249 |
+
|
| 1250 |
+
# """
|
| 1251 |
+
# special class constructors for local filesystem paths
|
| 1252 |
+
# """
|
| 1253 |
+
@classmethod
|
| 1254 |
+
def get_temproot(cls):
|
| 1255 |
+
"""Return the system's temporary directory
|
| 1256 |
+
(where tempfiles are usually created in)
|
| 1257 |
+
"""
|
| 1258 |
+
import tempfile
|
| 1259 |
+
|
| 1260 |
+
return local(tempfile.gettempdir())
|
| 1261 |
+
|
| 1262 |
+
@classmethod
|
| 1263 |
+
def mkdtemp(cls, rootdir=None):
|
| 1264 |
+
"""Return a Path object pointing to a fresh new temporary directory
|
| 1265 |
+
(which we created ourselves).
|
| 1266 |
+
"""
|
| 1267 |
+
import tempfile
|
| 1268 |
+
|
| 1269 |
+
if rootdir is None:
|
| 1270 |
+
rootdir = cls.get_temproot()
|
| 1271 |
+
path = error.checked_call(tempfile.mkdtemp, dir=str(rootdir))
|
| 1272 |
+
return cls(path)
|
| 1273 |
+
|
| 1274 |
+
@classmethod
|
| 1275 |
+
def make_numbered_dir(
|
| 1276 |
+
cls, prefix="session-", rootdir=None, keep=3, lock_timeout=172800
|
| 1277 |
+
): # two days
|
| 1278 |
+
"""Return unique directory with a number greater than the current
|
| 1279 |
+
maximum one. The number is assumed to start directly after prefix.
|
| 1280 |
+
if keep is true directories with a number less than (maxnum-keep)
|
| 1281 |
+
will be removed. If .lock files are used (lock_timeout non-zero),
|
| 1282 |
+
algorithm is multi-process safe.
|
| 1283 |
+
"""
|
| 1284 |
+
if rootdir is None:
|
| 1285 |
+
rootdir = cls.get_temproot()
|
| 1286 |
+
|
| 1287 |
+
nprefix = prefix.lower()
|
| 1288 |
+
|
| 1289 |
+
def parse_num(path):
|
| 1290 |
+
"""Parse the number out of a path (if it matches the prefix)"""
|
| 1291 |
+
nbasename = path.basename.lower()
|
| 1292 |
+
if nbasename.startswith(nprefix):
|
| 1293 |
+
try:
|
| 1294 |
+
return int(nbasename[len(nprefix) :])
|
| 1295 |
+
except ValueError:
|
| 1296 |
+
pass
|
| 1297 |
+
|
| 1298 |
+
def create_lockfile(path):
|
| 1299 |
+
"""Exclusively create lockfile. Throws when failed"""
|
| 1300 |
+
mypid = os.getpid()
|
| 1301 |
+
lockfile = path.join(".lock")
|
| 1302 |
+
if hasattr(lockfile, "mksymlinkto"):
|
| 1303 |
+
lockfile.mksymlinkto(str(mypid))
|
| 1304 |
+
else:
|
| 1305 |
+
fd = error.checked_call(
|
| 1306 |
+
os.open, str(lockfile), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644
|
| 1307 |
+
)
|
| 1308 |
+
with os.fdopen(fd, "w") as f:
|
| 1309 |
+
f.write(str(mypid))
|
| 1310 |
+
return lockfile
|
| 1311 |
+
|
| 1312 |
+
def atexit_remove_lockfile(lockfile):
|
| 1313 |
+
"""Ensure lockfile is removed at process exit"""
|
| 1314 |
+
mypid = os.getpid()
|
| 1315 |
+
|
| 1316 |
+
def try_remove_lockfile():
|
| 1317 |
+
# in a fork() situation, only the last process should
|
| 1318 |
+
# remove the .lock, otherwise the other processes run the
|
| 1319 |
+
# risk of seeing their temporary dir disappear. For now
|
| 1320 |
+
# we remove the .lock in the parent only (i.e. we assume
|
| 1321 |
+
# that the children finish before the parent).
|
| 1322 |
+
if os.getpid() != mypid:
|
| 1323 |
+
return
|
| 1324 |
+
try:
|
| 1325 |
+
lockfile.remove()
|
| 1326 |
+
except error.Error:
|
| 1327 |
+
pass
|
| 1328 |
+
|
| 1329 |
+
atexit.register(try_remove_lockfile)
|
| 1330 |
+
|
| 1331 |
+
# compute the maximum number currently in use with the prefix
|
| 1332 |
+
lastmax = None
|
| 1333 |
+
while True:
|
| 1334 |
+
maxnum = -1
|
| 1335 |
+
for path in rootdir.listdir():
|
| 1336 |
+
num = parse_num(path)
|
| 1337 |
+
if num is not None:
|
| 1338 |
+
maxnum = max(maxnum, num)
|
| 1339 |
+
|
| 1340 |
+
# make the new directory
|
| 1341 |
+
try:
|
| 1342 |
+
udir = rootdir.mkdir(prefix + str(maxnum + 1))
|
| 1343 |
+
if lock_timeout:
|
| 1344 |
+
lockfile = create_lockfile(udir)
|
| 1345 |
+
atexit_remove_lockfile(lockfile)
|
| 1346 |
+
except (error.EEXIST, error.ENOENT, error.EBUSY):
|
| 1347 |
+
# race condition (1): another thread/process created the dir
|
| 1348 |
+
# in the meantime - try again
|
| 1349 |
+
# race condition (2): another thread/process spuriously acquired
|
| 1350 |
+
# lock treating empty directory as candidate
|
| 1351 |
+
# for removal - try again
|
| 1352 |
+
# race condition (3): another thread/process tried to create the lock at
|
| 1353 |
+
# the same time (happened in Python 3.3 on Windows)
|
| 1354 |
+
# https://ci.appveyor.com/project/pytestbot/py/build/1.0.21/job/ffi85j4c0lqwsfwa
|
| 1355 |
+
if lastmax == maxnum:
|
| 1356 |
+
raise
|
| 1357 |
+
lastmax = maxnum
|
| 1358 |
+
continue
|
| 1359 |
+
break
|
| 1360 |
+
|
| 1361 |
+
def get_mtime(path):
|
| 1362 |
+
"""Read file modification time"""
|
| 1363 |
+
try:
|
| 1364 |
+
return path.lstat().mtime
|
| 1365 |
+
except error.Error:
|
| 1366 |
+
pass
|
| 1367 |
+
|
| 1368 |
+
garbage_prefix = prefix + "garbage-"
|
| 1369 |
+
|
| 1370 |
+
def is_garbage(path):
|
| 1371 |
+
"""Check if path denotes directory scheduled for removal"""
|
| 1372 |
+
bn = path.basename
|
| 1373 |
+
return bn.startswith(garbage_prefix)
|
| 1374 |
+
|
| 1375 |
+
# prune old directories
|
| 1376 |
+
udir_time = get_mtime(udir)
|
| 1377 |
+
if keep and udir_time:
|
| 1378 |
+
for path in rootdir.listdir():
|
| 1379 |
+
num = parse_num(path)
|
| 1380 |
+
if num is not None and num <= (maxnum - keep):
|
| 1381 |
+
try:
|
| 1382 |
+
# try acquiring lock to remove directory as exclusive user
|
| 1383 |
+
if lock_timeout:
|
| 1384 |
+
create_lockfile(path)
|
| 1385 |
+
except (error.EEXIST, error.ENOENT, error.EBUSY):
|
| 1386 |
+
path_time = get_mtime(path)
|
| 1387 |
+
if not path_time:
|
| 1388 |
+
# assume directory doesn't exist now
|
| 1389 |
+
continue
|
| 1390 |
+
if abs(udir_time - path_time) < lock_timeout:
|
| 1391 |
+
# assume directory with lockfile exists
|
| 1392 |
+
# and lock timeout hasn't expired yet
|
| 1393 |
+
continue
|
| 1394 |
+
|
| 1395 |
+
# path dir locked for exclusive use
|
| 1396 |
+
# and scheduled for removal to avoid another thread/process
|
| 1397 |
+
# treating it as a new directory or removal candidate
|
| 1398 |
+
garbage_path = rootdir.join(garbage_prefix + str(uuid.uuid4()))
|
| 1399 |
+
try:
|
| 1400 |
+
path.rename(garbage_path)
|
| 1401 |
+
garbage_path.remove(rec=1)
|
| 1402 |
+
except KeyboardInterrupt:
|
| 1403 |
+
raise
|
| 1404 |
+
except Exception: # this might be error.Error, WindowsError ...
|
| 1405 |
+
pass
|
| 1406 |
+
if is_garbage(path):
|
| 1407 |
+
try:
|
| 1408 |
+
path.remove(rec=1)
|
| 1409 |
+
except KeyboardInterrupt:
|
| 1410 |
+
raise
|
| 1411 |
+
except Exception: # this might be error.Error, WindowsError ...
|
| 1412 |
+
pass
|
| 1413 |
+
|
| 1414 |
+
# make link...
|
| 1415 |
+
try:
|
| 1416 |
+
username = os.environ["USER"] # linux, et al
|
| 1417 |
+
except KeyError:
|
| 1418 |
+
try:
|
| 1419 |
+
username = os.environ["USERNAME"] # windows
|
| 1420 |
+
except KeyError:
|
| 1421 |
+
username = "current"
|
| 1422 |
+
|
| 1423 |
+
src = str(udir)
|
| 1424 |
+
dest = src[: src.rfind("-")] + "-" + username
|
| 1425 |
+
try:
|
| 1426 |
+
os.unlink(dest)
|
| 1427 |
+
except OSError:
|
| 1428 |
+
pass
|
| 1429 |
+
try:
|
| 1430 |
+
os.symlink(src, dest)
|
| 1431 |
+
except (OSError, AttributeError, NotImplementedError):
|
| 1432 |
+
pass
|
| 1433 |
+
|
| 1434 |
+
return udir
|
| 1435 |
+
|
| 1436 |
+
|
| 1437 |
+
def copymode(src, dest):
|
| 1438 |
+
"""Copy permission from src to dst."""
|
| 1439 |
+
import shutil
|
| 1440 |
+
|
| 1441 |
+
shutil.copymode(src, dest)
|
| 1442 |
+
|
| 1443 |
+
|
| 1444 |
+
def copystat(src, dest):
|
| 1445 |
+
"""Copy permission, last modification time,
|
| 1446 |
+
last access time, and flags from src to dst."""
|
| 1447 |
+
import shutil
|
| 1448 |
+
|
| 1449 |
+
shutil.copystat(str(src), str(dest))
|
| 1450 |
+
|
| 1451 |
+
|
| 1452 |
+
def copychunked(src, dest):
|
| 1453 |
+
chunksize = 524288 # half a meg of bytes
|
| 1454 |
+
fsrc = src.open("rb")
|
| 1455 |
+
try:
|
| 1456 |
+
fdest = dest.open("wb")
|
| 1457 |
+
try:
|
| 1458 |
+
while 1:
|
| 1459 |
+
buf = fsrc.read(chunksize)
|
| 1460 |
+
if not buf:
|
| 1461 |
+
break
|
| 1462 |
+
fdest.write(buf)
|
| 1463 |
+
finally:
|
| 1464 |
+
fdest.close()
|
| 1465 |
+
finally:
|
| 1466 |
+
fsrc.close()
|
| 1467 |
+
|
| 1468 |
+
|
| 1469 |
+
def isimportable(name):
|
| 1470 |
+
if name and (name[0].isalpha() or name[0] == "_"):
|
| 1471 |
+
name = name.replace("_", "")
|
| 1472 |
+
return not name or name.isalnum()
|
| 1473 |
+
|
| 1474 |
+
|
| 1475 |
+
local = LocalPath
|
vllm/lib/python3.10/site-packages/_pytest/assertion/__init__.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""Support for presenting detailed information in failing assertions."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import sys
|
| 7 |
+
from typing import Any
|
| 8 |
+
from typing import Generator
|
| 9 |
+
from typing import TYPE_CHECKING
|
| 10 |
+
|
| 11 |
+
from _pytest.assertion import rewrite
|
| 12 |
+
from _pytest.assertion import truncate
|
| 13 |
+
from _pytest.assertion import util
|
| 14 |
+
from _pytest.assertion.rewrite import assertstate_key
|
| 15 |
+
from _pytest.config import Config
|
| 16 |
+
from _pytest.config import hookimpl
|
| 17 |
+
from _pytest.config.argparsing import Parser
|
| 18 |
+
from _pytest.nodes import Item
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if TYPE_CHECKING:
|
| 22 |
+
from _pytest.main import Session
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def pytest_addoption(parser: Parser) -> None:
|
| 26 |
+
group = parser.getgroup("debugconfig")
|
| 27 |
+
group.addoption(
|
| 28 |
+
"--assert",
|
| 29 |
+
action="store",
|
| 30 |
+
dest="assertmode",
|
| 31 |
+
choices=("rewrite", "plain"),
|
| 32 |
+
default="rewrite",
|
| 33 |
+
metavar="MODE",
|
| 34 |
+
help=(
|
| 35 |
+
"Control assertion debugging tools.\n"
|
| 36 |
+
"'plain' performs no assertion debugging.\n"
|
| 37 |
+
"'rewrite' (the default) rewrites assert statements in test modules"
|
| 38 |
+
" on import to provide assert expression information."
|
| 39 |
+
),
|
| 40 |
+
)
|
| 41 |
+
parser.addini(
|
| 42 |
+
"enable_assertion_pass_hook",
|
| 43 |
+
type="bool",
|
| 44 |
+
default=False,
|
| 45 |
+
help="Enables the pytest_assertion_pass hook. "
|
| 46 |
+
"Make sure to delete any previously generated pyc cache files.",
|
| 47 |
+
)
|
| 48 |
+
Config._add_verbosity_ini(
|
| 49 |
+
parser,
|
| 50 |
+
Config.VERBOSITY_ASSERTIONS,
|
| 51 |
+
help=(
|
| 52 |
+
"Specify a verbosity level for assertions, overriding the main level. "
|
| 53 |
+
"Higher levels will provide more detailed explanation when an assertion fails."
|
| 54 |
+
),
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def register_assert_rewrite(*names: str) -> None:
|
| 59 |
+
"""Register one or more module names to be rewritten on import.
|
| 60 |
+
|
| 61 |
+
This function will make sure that this module or all modules inside
|
| 62 |
+
the package will get their assert statements rewritten.
|
| 63 |
+
Thus you should make sure to call this before the module is
|
| 64 |
+
actually imported, usually in your __init__.py if you are a plugin
|
| 65 |
+
using a package.
|
| 66 |
+
|
| 67 |
+
:param names: The module names to register.
|
| 68 |
+
"""
|
| 69 |
+
for name in names:
|
| 70 |
+
if not isinstance(name, str):
|
| 71 |
+
msg = "expected module names as *args, got {0} instead" # type: ignore[unreachable]
|
| 72 |
+
raise TypeError(msg.format(repr(names)))
|
| 73 |
+
for hook in sys.meta_path:
|
| 74 |
+
if isinstance(hook, rewrite.AssertionRewritingHook):
|
| 75 |
+
importhook = hook
|
| 76 |
+
break
|
| 77 |
+
else:
|
| 78 |
+
# TODO(typing): Add a protocol for mark_rewrite() and use it
|
| 79 |
+
# for importhook and for PytestPluginManager.rewrite_hook.
|
| 80 |
+
importhook = DummyRewriteHook() # type: ignore
|
| 81 |
+
importhook.mark_rewrite(*names)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class DummyRewriteHook:
|
| 85 |
+
"""A no-op import hook for when rewriting is disabled."""
|
| 86 |
+
|
| 87 |
+
def mark_rewrite(self, *names: str) -> None:
|
| 88 |
+
pass
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class AssertionState:
|
| 92 |
+
"""State for the assertion plugin."""
|
| 93 |
+
|
| 94 |
+
def __init__(self, config: Config, mode) -> None:
|
| 95 |
+
self.mode = mode
|
| 96 |
+
self.trace = config.trace.root.get("assertion")
|
| 97 |
+
self.hook: rewrite.AssertionRewritingHook | None = None
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def install_importhook(config: Config) -> rewrite.AssertionRewritingHook:
|
| 101 |
+
"""Try to install the rewrite hook, raise SystemError if it fails."""
|
| 102 |
+
config.stash[assertstate_key] = AssertionState(config, "rewrite")
|
| 103 |
+
config.stash[assertstate_key].hook = hook = rewrite.AssertionRewritingHook(config)
|
| 104 |
+
sys.meta_path.insert(0, hook)
|
| 105 |
+
config.stash[assertstate_key].trace("installed rewrite import hook")
|
| 106 |
+
|
| 107 |
+
def undo() -> None:
|
| 108 |
+
hook = config.stash[assertstate_key].hook
|
| 109 |
+
if hook is not None and hook in sys.meta_path:
|
| 110 |
+
sys.meta_path.remove(hook)
|
| 111 |
+
|
| 112 |
+
config.add_cleanup(undo)
|
| 113 |
+
return hook
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def pytest_collection(session: Session) -> None:
|
| 117 |
+
# This hook is only called when test modules are collected
|
| 118 |
+
# so for example not in the managing process of pytest-xdist
|
| 119 |
+
# (which does not collect test modules).
|
| 120 |
+
assertstate = session.config.stash.get(assertstate_key, None)
|
| 121 |
+
if assertstate:
|
| 122 |
+
if assertstate.hook is not None:
|
| 123 |
+
assertstate.hook.set_session(session)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
@hookimpl(wrapper=True, tryfirst=True)
|
| 127 |
+
def pytest_runtest_protocol(item: Item) -> Generator[None, object, object]:
|
| 128 |
+
"""Setup the pytest_assertrepr_compare and pytest_assertion_pass hooks.
|
| 129 |
+
|
| 130 |
+
The rewrite module will use util._reprcompare if it exists to use custom
|
| 131 |
+
reporting via the pytest_assertrepr_compare hook. This sets up this custom
|
| 132 |
+
comparison for the test.
|
| 133 |
+
"""
|
| 134 |
+
ihook = item.ihook
|
| 135 |
+
|
| 136 |
+
def callbinrepr(op, left: object, right: object) -> str | None:
|
| 137 |
+
"""Call the pytest_assertrepr_compare hook and prepare the result.
|
| 138 |
+
|
| 139 |
+
This uses the first result from the hook and then ensures the
|
| 140 |
+
following:
|
| 141 |
+
* Overly verbose explanations are truncated unless configured otherwise
|
| 142 |
+
(eg. if running in verbose mode).
|
| 143 |
+
* Embedded newlines are escaped to help util.format_explanation()
|
| 144 |
+
later.
|
| 145 |
+
* If the rewrite mode is used embedded %-characters are replaced
|
| 146 |
+
to protect later % formatting.
|
| 147 |
+
|
| 148 |
+
The result can be formatted by util.format_explanation() for
|
| 149 |
+
pretty printing.
|
| 150 |
+
"""
|
| 151 |
+
hook_result = ihook.pytest_assertrepr_compare(
|
| 152 |
+
config=item.config, op=op, left=left, right=right
|
| 153 |
+
)
|
| 154 |
+
for new_expl in hook_result:
|
| 155 |
+
if new_expl:
|
| 156 |
+
new_expl = truncate.truncate_if_required(new_expl, item)
|
| 157 |
+
new_expl = [line.replace("\n", "\\n") for line in new_expl]
|
| 158 |
+
res = "\n~".join(new_expl)
|
| 159 |
+
if item.config.getvalue("assertmode") == "rewrite":
|
| 160 |
+
res = res.replace("%", "%%")
|
| 161 |
+
return res
|
| 162 |
+
return None
|
| 163 |
+
|
| 164 |
+
saved_assert_hooks = util._reprcompare, util._assertion_pass
|
| 165 |
+
util._reprcompare = callbinrepr
|
| 166 |
+
util._config = item.config
|
| 167 |
+
|
| 168 |
+
if ihook.pytest_assertion_pass.get_hookimpls():
|
| 169 |
+
|
| 170 |
+
def call_assertion_pass_hook(lineno: int, orig: str, expl: str) -> None:
|
| 171 |
+
ihook.pytest_assertion_pass(item=item, lineno=lineno, orig=orig, expl=expl)
|
| 172 |
+
|
| 173 |
+
util._assertion_pass = call_assertion_pass_hook
|
| 174 |
+
|
| 175 |
+
try:
|
| 176 |
+
return (yield)
|
| 177 |
+
finally:
|
| 178 |
+
util._reprcompare, util._assertion_pass = saved_assert_hooks
|
| 179 |
+
util._config = None
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def pytest_sessionfinish(session: Session) -> None:
|
| 183 |
+
assertstate = session.config.stash.get(assertstate_key, None)
|
| 184 |
+
if assertstate:
|
| 185 |
+
if assertstate.hook is not None:
|
| 186 |
+
assertstate.hook.set_session(None)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def pytest_assertrepr_compare(
|
| 190 |
+
config: Config, op: str, left: Any, right: Any
|
| 191 |
+
) -> list[str] | None:
|
| 192 |
+
return util.assertrepr_compare(config=config, op=op, left=left, right=right)
|
vllm/lib/python3.10/site-packages/_pytest/assertion/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (7.13 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/assertion/__pycache__/rewrite.cpython-310.pyc
ADDED
|
Binary file (35.8 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/assertion/__pycache__/truncate.cpython-310.pyc
ADDED
|
Binary file (2.79 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/assertion/__pycache__/util.cpython-310.pyc
ADDED
|
Binary file (15.3 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/_pytest/assertion/rewrite.py
ADDED
|
@@ -0,0 +1,1211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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errno
|
| 8 |
+
import functools
|
| 9 |
+
import importlib.abc
|
| 10 |
+
import importlib.machinery
|
| 11 |
+
import importlib.util
|
| 12 |
+
import io
|
| 13 |
+
import itertools
|
| 14 |
+
import marshal
|
| 15 |
+
import os
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from pathlib import PurePath
|
| 18 |
+
import struct
|
| 19 |
+
import sys
|
| 20 |
+
import tokenize
|
| 21 |
+
import types
|
| 22 |
+
from typing import Callable
|
| 23 |
+
from typing import IO
|
| 24 |
+
from typing import Iterable
|
| 25 |
+
from typing import Iterator
|
| 26 |
+
from typing import Sequence
|
| 27 |
+
from typing import TYPE_CHECKING
|
| 28 |
+
|
| 29 |
+
from _pytest._io.saferepr import DEFAULT_REPR_MAX_SIZE
|
| 30 |
+
from _pytest._io.saferepr import saferepr
|
| 31 |
+
from _pytest._version import version
|
| 32 |
+
from _pytest.assertion import util
|
| 33 |
+
from _pytest.config import Config
|
| 34 |
+
from _pytest.main import Session
|
| 35 |
+
from _pytest.pathlib import absolutepath
|
| 36 |
+
from _pytest.pathlib import fnmatch_ex
|
| 37 |
+
from _pytest.stash import StashKey
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# fmt: off
|
| 41 |
+
from _pytest.assertion.util import format_explanation as _format_explanation # noqa:F401, isort:skip
|
| 42 |
+
# fmt:on
|
| 43 |
+
|
| 44 |
+
if TYPE_CHECKING:
|
| 45 |
+
from _pytest.assertion import AssertionState
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class Sentinel:
|
| 49 |
+
pass
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
assertstate_key = StashKey["AssertionState"]()
|
| 53 |
+
|
| 54 |
+
# pytest caches rewritten pycs in pycache dirs
|
| 55 |
+
PYTEST_TAG = f"{sys.implementation.cache_tag}-pytest-{version}"
|
| 56 |
+
PYC_EXT = ".py" + (__debug__ and "c" or "o")
|
| 57 |
+
PYC_TAIL = "." + PYTEST_TAG + PYC_EXT
|
| 58 |
+
|
| 59 |
+
# Special marker that denotes we have just left a scope definition
|
| 60 |
+
_SCOPE_END_MARKER = Sentinel()
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class AssertionRewritingHook(importlib.abc.MetaPathFinder, importlib.abc.Loader):
|
| 64 |
+
"""PEP302/PEP451 import hook which rewrites asserts."""
|
| 65 |
+
|
| 66 |
+
def __init__(self, config: Config) -> None:
|
| 67 |
+
self.config = config
|
| 68 |
+
try:
|
| 69 |
+
self.fnpats = config.getini("python_files")
|
| 70 |
+
except ValueError:
|
| 71 |
+
self.fnpats = ["test_*.py", "*_test.py"]
|
| 72 |
+
self.session: Session | None = None
|
| 73 |
+
self._rewritten_names: dict[str, Path] = {}
|
| 74 |
+
self._must_rewrite: set[str] = set()
|
| 75 |
+
# flag to guard against trying to rewrite a pyc file while we are already writing another pyc file,
|
| 76 |
+
# which might result in infinite recursion (#3506)
|
| 77 |
+
self._writing_pyc = False
|
| 78 |
+
self._basenames_to_check_rewrite = {"conftest"}
|
| 79 |
+
self._marked_for_rewrite_cache: dict[str, bool] = {}
|
| 80 |
+
self._session_paths_checked = False
|
| 81 |
+
|
| 82 |
+
def set_session(self, session: Session | None) -> None:
|
| 83 |
+
self.session = session
|
| 84 |
+
self._session_paths_checked = False
|
| 85 |
+
|
| 86 |
+
# Indirection so we can mock calls to find_spec originated from the hook during testing
|
| 87 |
+
_find_spec = importlib.machinery.PathFinder.find_spec
|
| 88 |
+
|
| 89 |
+
def find_spec(
|
| 90 |
+
self,
|
| 91 |
+
name: str,
|
| 92 |
+
path: Sequence[str | bytes] | None = None,
|
| 93 |
+
target: types.ModuleType | None = None,
|
| 94 |
+
) -> importlib.machinery.ModuleSpec | None:
|
| 95 |
+
if self._writing_pyc:
|
| 96 |
+
return None
|
| 97 |
+
state = self.config.stash[assertstate_key]
|
| 98 |
+
if self._early_rewrite_bailout(name, state):
|
| 99 |
+
return None
|
| 100 |
+
state.trace(f"find_module called for: {name}")
|
| 101 |
+
|
| 102 |
+
# Type ignored because mypy is confused about the `self` binding here.
|
| 103 |
+
spec = self._find_spec(name, path) # type: ignore
|
| 104 |
+
|
| 105 |
+
if spec is None and path is not None:
|
| 106 |
+
# With --import-mode=importlib, PathFinder cannot find spec without modifying `sys.path`,
|
| 107 |
+
# causing inability to assert rewriting (#12659).
|
| 108 |
+
# At this point, try using the file path to find the module spec.
|
| 109 |
+
for _path_str in path:
|
| 110 |
+
spec = importlib.util.spec_from_file_location(name, _path_str)
|
| 111 |
+
if spec is not None:
|
| 112 |
+
break
|
| 113 |
+
|
| 114 |
+
if (
|
| 115 |
+
# the import machinery could not find a file to import
|
| 116 |
+
spec is None
|
| 117 |
+
# this is a namespace package (without `__init__.py`)
|
| 118 |
+
# there's nothing to rewrite there
|
| 119 |
+
or spec.origin is None
|
| 120 |
+
# we can only rewrite source files
|
| 121 |
+
or not isinstance(spec.loader, importlib.machinery.SourceFileLoader)
|
| 122 |
+
# if the file doesn't exist, we can't rewrite it
|
| 123 |
+
or not os.path.exists(spec.origin)
|
| 124 |
+
):
|
| 125 |
+
return None
|
| 126 |
+
else:
|
| 127 |
+
fn = spec.origin
|
| 128 |
+
|
| 129 |
+
if not self._should_rewrite(name, fn, state):
|
| 130 |
+
return None
|
| 131 |
+
|
| 132 |
+
return importlib.util.spec_from_file_location(
|
| 133 |
+
name,
|
| 134 |
+
fn,
|
| 135 |
+
loader=self,
|
| 136 |
+
submodule_search_locations=spec.submodule_search_locations,
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
def create_module(
|
| 140 |
+
self, spec: importlib.machinery.ModuleSpec
|
| 141 |
+
) -> types.ModuleType | None:
|
| 142 |
+
return None # default behaviour is fine
|
| 143 |
+
|
| 144 |
+
def exec_module(self, module: types.ModuleType) -> None:
|
| 145 |
+
assert module.__spec__ is not None
|
| 146 |
+
assert module.__spec__.origin is not None
|
| 147 |
+
fn = Path(module.__spec__.origin)
|
| 148 |
+
state = self.config.stash[assertstate_key]
|
| 149 |
+
|
| 150 |
+
self._rewritten_names[module.__name__] = fn
|
| 151 |
+
|
| 152 |
+
# The requested module looks like a test file, so rewrite it. This is
|
| 153 |
+
# the most magical part of the process: load the source, rewrite the
|
| 154 |
+
# asserts, and load the rewritten source. We also cache the rewritten
|
| 155 |
+
# module code in a special pyc. We must be aware of the possibility of
|
| 156 |
+
# concurrent pytest processes rewriting and loading pycs. To avoid
|
| 157 |
+
# tricky race conditions, we maintain the following invariant: The
|
| 158 |
+
# cached pyc is always a complete, valid pyc. Operations on it must be
|
| 159 |
+
# atomic. POSIX's atomic rename comes in handy.
|
| 160 |
+
write = not sys.dont_write_bytecode
|
| 161 |
+
cache_dir = get_cache_dir(fn)
|
| 162 |
+
if write:
|
| 163 |
+
ok = try_makedirs(cache_dir)
|
| 164 |
+
if not ok:
|
| 165 |
+
write = False
|
| 166 |
+
state.trace(f"read only directory: {cache_dir}")
|
| 167 |
+
|
| 168 |
+
cache_name = fn.name[:-3] + PYC_TAIL
|
| 169 |
+
pyc = cache_dir / cache_name
|
| 170 |
+
# Notice that even if we're in a read-only directory, I'm going
|
| 171 |
+
# to check for a cached pyc. This may not be optimal...
|
| 172 |
+
co = _read_pyc(fn, pyc, state.trace)
|
| 173 |
+
if co is None:
|
| 174 |
+
state.trace(f"rewriting {fn!r}")
|
| 175 |
+
source_stat, co = _rewrite_test(fn, self.config)
|
| 176 |
+
if write:
|
| 177 |
+
self._writing_pyc = True
|
| 178 |
+
try:
|
| 179 |
+
_write_pyc(state, co, source_stat, pyc)
|
| 180 |
+
finally:
|
| 181 |
+
self._writing_pyc = False
|
| 182 |
+
else:
|
| 183 |
+
state.trace(f"found cached rewritten pyc for {fn}")
|
| 184 |
+
exec(co, module.__dict__)
|
| 185 |
+
|
| 186 |
+
def _early_rewrite_bailout(self, name: str, state: AssertionState) -> bool:
|
| 187 |
+
"""A fast way to get out of rewriting modules.
|
| 188 |
+
|
| 189 |
+
Profiling has shown that the call to PathFinder.find_spec (inside of
|
| 190 |
+
the find_spec from this class) is a major slowdown, so, this method
|
| 191 |
+
tries to filter what we're sure won't be rewritten before getting to
|
| 192 |
+
it.
|
| 193 |
+
"""
|
| 194 |
+
if self.session is not None and not self._session_paths_checked:
|
| 195 |
+
self._session_paths_checked = True
|
| 196 |
+
for initial_path in self.session._initialpaths:
|
| 197 |
+
# Make something as c:/projects/my_project/path.py ->
|
| 198 |
+
# ['c:', 'projects', 'my_project', 'path.py']
|
| 199 |
+
parts = str(initial_path).split(os.sep)
|
| 200 |
+
# add 'path' to basenames to be checked.
|
| 201 |
+
self._basenames_to_check_rewrite.add(os.path.splitext(parts[-1])[0])
|
| 202 |
+
|
| 203 |
+
# Note: conftest already by default in _basenames_to_check_rewrite.
|
| 204 |
+
parts = name.split(".")
|
| 205 |
+
if parts[-1] in self._basenames_to_check_rewrite:
|
| 206 |
+
return False
|
| 207 |
+
|
| 208 |
+
# For matching the name it must be as if it was a filename.
|
| 209 |
+
path = PurePath(*parts).with_suffix(".py")
|
| 210 |
+
|
| 211 |
+
for pat in self.fnpats:
|
| 212 |
+
# if the pattern contains subdirectories ("tests/**.py" for example) we can't bail out based
|
| 213 |
+
# on the name alone because we need to match against the full path
|
| 214 |
+
if os.path.dirname(pat):
|
| 215 |
+
return False
|
| 216 |
+
if fnmatch_ex(pat, path):
|
| 217 |
+
return False
|
| 218 |
+
|
| 219 |
+
if self._is_marked_for_rewrite(name, state):
|
| 220 |
+
return False
|
| 221 |
+
|
| 222 |
+
state.trace(f"early skip of rewriting module: {name}")
|
| 223 |
+
return True
|
| 224 |
+
|
| 225 |
+
def _should_rewrite(self, name: str, fn: str, state: AssertionState) -> bool:
|
| 226 |
+
# always rewrite conftest files
|
| 227 |
+
if os.path.basename(fn) == "conftest.py":
|
| 228 |
+
state.trace(f"rewriting conftest file: {fn!r}")
|
| 229 |
+
return True
|
| 230 |
+
|
| 231 |
+
if self.session is not None:
|
| 232 |
+
if self.session.isinitpath(absolutepath(fn)):
|
| 233 |
+
state.trace(f"matched test file (was specified on cmdline): {fn!r}")
|
| 234 |
+
return True
|
| 235 |
+
|
| 236 |
+
# modules not passed explicitly on the command line are only
|
| 237 |
+
# rewritten if they match the naming convention for test files
|
| 238 |
+
fn_path = PurePath(fn)
|
| 239 |
+
for pat in self.fnpats:
|
| 240 |
+
if fnmatch_ex(pat, fn_path):
|
| 241 |
+
state.trace(f"matched test file {fn!r}")
|
| 242 |
+
return True
|
| 243 |
+
|
| 244 |
+
return self._is_marked_for_rewrite(name, state)
|
| 245 |
+
|
| 246 |
+
def _is_marked_for_rewrite(self, name: str, state: AssertionState) -> bool:
|
| 247 |
+
try:
|
| 248 |
+
return self._marked_for_rewrite_cache[name]
|
| 249 |
+
except KeyError:
|
| 250 |
+
for marked in self._must_rewrite:
|
| 251 |
+
if name == marked or name.startswith(marked + "."):
|
| 252 |
+
state.trace(f"matched marked file {name!r} (from {marked!r})")
|
| 253 |
+
self._marked_for_rewrite_cache[name] = True
|
| 254 |
+
return True
|
| 255 |
+
|
| 256 |
+
self._marked_for_rewrite_cache[name] = False
|
| 257 |
+
return False
|
| 258 |
+
|
| 259 |
+
def mark_rewrite(self, *names: str) -> None:
|
| 260 |
+
"""Mark import names as needing to be rewritten.
|
| 261 |
+
|
| 262 |
+
The named module or package as well as any nested modules will
|
| 263 |
+
be rewritten on import.
|
| 264 |
+
"""
|
| 265 |
+
already_imported = (
|
| 266 |
+
set(names).intersection(sys.modules).difference(self._rewritten_names)
|
| 267 |
+
)
|
| 268 |
+
for name in already_imported:
|
| 269 |
+
mod = sys.modules[name]
|
| 270 |
+
if not AssertionRewriter.is_rewrite_disabled(
|
| 271 |
+
mod.__doc__ or ""
|
| 272 |
+
) and not isinstance(mod.__loader__, type(self)):
|
| 273 |
+
self._warn_already_imported(name)
|
| 274 |
+
self._must_rewrite.update(names)
|
| 275 |
+
self._marked_for_rewrite_cache.clear()
|
| 276 |
+
|
| 277 |
+
def _warn_already_imported(self, name: str) -> None:
|
| 278 |
+
from _pytest.warning_types import PytestAssertRewriteWarning
|
| 279 |
+
|
| 280 |
+
self.config.issue_config_time_warning(
|
| 281 |
+
PytestAssertRewriteWarning(
|
| 282 |
+
f"Module already imported so cannot be rewritten: {name}"
|
| 283 |
+
),
|
| 284 |
+
stacklevel=5,
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
def get_data(self, pathname: str | bytes) -> bytes:
|
| 288 |
+
"""Optional PEP302 get_data API."""
|
| 289 |
+
with open(pathname, "rb") as f:
|
| 290 |
+
return f.read()
|
| 291 |
+
|
| 292 |
+
if sys.version_info >= (3, 10):
|
| 293 |
+
if sys.version_info >= (3, 12):
|
| 294 |
+
from importlib.resources.abc import TraversableResources
|
| 295 |
+
else:
|
| 296 |
+
from importlib.abc import TraversableResources
|
| 297 |
+
|
| 298 |
+
def get_resource_reader(self, name: str) -> TraversableResources:
|
| 299 |
+
if sys.version_info < (3, 11):
|
| 300 |
+
from importlib.readers import FileReader
|
| 301 |
+
else:
|
| 302 |
+
from importlib.resources.readers import FileReader
|
| 303 |
+
|
| 304 |
+
return FileReader(types.SimpleNamespace(path=self._rewritten_names[name]))
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def _write_pyc_fp(
|
| 308 |
+
fp: IO[bytes], source_stat: os.stat_result, co: types.CodeType
|
| 309 |
+
) -> None:
|
| 310 |
+
# Technically, we don't have to have the same pyc format as
|
| 311 |
+
# (C)Python, since these "pycs" should never be seen by builtin
|
| 312 |
+
# import. However, there's little reason to deviate.
|
| 313 |
+
fp.write(importlib.util.MAGIC_NUMBER)
|
| 314 |
+
# https://www.python.org/dev/peps/pep-0552/
|
| 315 |
+
flags = b"\x00\x00\x00\x00"
|
| 316 |
+
fp.write(flags)
|
| 317 |
+
# as of now, bytecode header expects 32-bit numbers for size and mtime (#4903)
|
| 318 |
+
mtime = int(source_stat.st_mtime) & 0xFFFFFFFF
|
| 319 |
+
size = source_stat.st_size & 0xFFFFFFFF
|
| 320 |
+
# "<LL" stands for 2 unsigned longs, little-endian.
|
| 321 |
+
fp.write(struct.pack("<LL", mtime, size))
|
| 322 |
+
fp.write(marshal.dumps(co))
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def _write_pyc(
|
| 326 |
+
state: AssertionState,
|
| 327 |
+
co: types.CodeType,
|
| 328 |
+
source_stat: os.stat_result,
|
| 329 |
+
pyc: Path,
|
| 330 |
+
) -> bool:
|
| 331 |
+
proc_pyc = f"{pyc}.{os.getpid()}"
|
| 332 |
+
try:
|
| 333 |
+
with open(proc_pyc, "wb") as fp:
|
| 334 |
+
_write_pyc_fp(fp, source_stat, co)
|
| 335 |
+
except OSError as e:
|
| 336 |
+
state.trace(f"error writing pyc file at {proc_pyc}: errno={e.errno}")
|
| 337 |
+
return False
|
| 338 |
+
|
| 339 |
+
try:
|
| 340 |
+
os.replace(proc_pyc, pyc)
|
| 341 |
+
except OSError as e:
|
| 342 |
+
state.trace(f"error writing pyc file at {pyc}: {e}")
|
| 343 |
+
# we ignore any failure to write the cache file
|
| 344 |
+
# there are many reasons, permission-denied, pycache dir being a
|
| 345 |
+
# file etc.
|
| 346 |
+
return False
|
| 347 |
+
return True
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def _rewrite_test(fn: Path, config: Config) -> tuple[os.stat_result, types.CodeType]:
|
| 351 |
+
"""Read and rewrite *fn* and return the code object."""
|
| 352 |
+
stat = os.stat(fn)
|
| 353 |
+
source = fn.read_bytes()
|
| 354 |
+
strfn = str(fn)
|
| 355 |
+
tree = ast.parse(source, filename=strfn)
|
| 356 |
+
rewrite_asserts(tree, source, strfn, config)
|
| 357 |
+
co = compile(tree, strfn, "exec", dont_inherit=True)
|
| 358 |
+
return stat, co
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def _read_pyc(
|
| 362 |
+
source: Path, pyc: Path, trace: Callable[[str], None] = lambda x: None
|
| 363 |
+
) -> types.CodeType | None:
|
| 364 |
+
"""Possibly read a pytest pyc containing rewritten code.
|
| 365 |
+
|
| 366 |
+
Return rewritten code if successful or None if not.
|
| 367 |
+
"""
|
| 368 |
+
try:
|
| 369 |
+
fp = open(pyc, "rb")
|
| 370 |
+
except OSError:
|
| 371 |
+
return None
|
| 372 |
+
with fp:
|
| 373 |
+
try:
|
| 374 |
+
stat_result = os.stat(source)
|
| 375 |
+
mtime = int(stat_result.st_mtime)
|
| 376 |
+
size = stat_result.st_size
|
| 377 |
+
data = fp.read(16)
|
| 378 |
+
except OSError as e:
|
| 379 |
+
trace(f"_read_pyc({source}): OSError {e}")
|
| 380 |
+
return None
|
| 381 |
+
# Check for invalid or out of date pyc file.
|
| 382 |
+
if len(data) != (16):
|
| 383 |
+
trace(f"_read_pyc({source}): invalid pyc (too short)")
|
| 384 |
+
return None
|
| 385 |
+
if data[:4] != importlib.util.MAGIC_NUMBER:
|
| 386 |
+
trace(f"_read_pyc({source}): invalid pyc (bad magic number)")
|
| 387 |
+
return None
|
| 388 |
+
if data[4:8] != b"\x00\x00\x00\x00":
|
| 389 |
+
trace(f"_read_pyc({source}): invalid pyc (unsupported flags)")
|
| 390 |
+
return None
|
| 391 |
+
mtime_data = data[8:12]
|
| 392 |
+
if int.from_bytes(mtime_data, "little") != mtime & 0xFFFFFFFF:
|
| 393 |
+
trace(f"_read_pyc({source}): out of date")
|
| 394 |
+
return None
|
| 395 |
+
size_data = data[12:16]
|
| 396 |
+
if int.from_bytes(size_data, "little") != size & 0xFFFFFFFF:
|
| 397 |
+
trace(f"_read_pyc({source}): invalid pyc (incorrect size)")
|
| 398 |
+
return None
|
| 399 |
+
try:
|
| 400 |
+
co = marshal.load(fp)
|
| 401 |
+
except Exception as e:
|
| 402 |
+
trace(f"_read_pyc({source}): marshal.load error {e}")
|
| 403 |
+
return None
|
| 404 |
+
if not isinstance(co, types.CodeType):
|
| 405 |
+
trace(f"_read_pyc({source}): not a code object")
|
| 406 |
+
return None
|
| 407 |
+
return co
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def rewrite_asserts(
|
| 411 |
+
mod: ast.Module,
|
| 412 |
+
source: bytes,
|
| 413 |
+
module_path: str | None = None,
|
| 414 |
+
config: Config | None = None,
|
| 415 |
+
) -> None:
|
| 416 |
+
"""Rewrite the assert statements in mod."""
|
| 417 |
+
AssertionRewriter(module_path, config, source).run(mod)
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def _saferepr(obj: object) -> str:
|
| 421 |
+
r"""Get a safe repr of an object for assertion error messages.
|
| 422 |
+
|
| 423 |
+
The assertion formatting (util.format_explanation()) requires
|
| 424 |
+
newlines to be escaped since they are a special character for it.
|
| 425 |
+
Normally assertion.util.format_explanation() does this but for a
|
| 426 |
+
custom repr it is possible to contain one of the special escape
|
| 427 |
+
sequences, especially '\n{' and '\n}' are likely to be present in
|
| 428 |
+
JSON reprs.
|
| 429 |
+
"""
|
| 430 |
+
if isinstance(obj, types.MethodType):
|
| 431 |
+
# for bound methods, skip redundant <bound method ...> information
|
| 432 |
+
return obj.__name__
|
| 433 |
+
|
| 434 |
+
maxsize = _get_maxsize_for_saferepr(util._config)
|
| 435 |
+
return saferepr(obj, maxsize=maxsize).replace("\n", "\\n")
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def _get_maxsize_for_saferepr(config: Config | None) -> int | None:
|
| 439 |
+
"""Get `maxsize` configuration for saferepr based on the given config object."""
|
| 440 |
+
if config is None:
|
| 441 |
+
verbosity = 0
|
| 442 |
+
else:
|
| 443 |
+
verbosity = config.get_verbosity(Config.VERBOSITY_ASSERTIONS)
|
| 444 |
+
if verbosity >= 2:
|
| 445 |
+
return None
|
| 446 |
+
if verbosity >= 1:
|
| 447 |
+
return DEFAULT_REPR_MAX_SIZE * 10
|
| 448 |
+
return DEFAULT_REPR_MAX_SIZE
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def _format_assertmsg(obj: object) -> str:
|
| 452 |
+
r"""Format the custom assertion message given.
|
| 453 |
+
|
| 454 |
+
For strings this simply replaces newlines with '\n~' so that
|
| 455 |
+
util.format_explanation() will preserve them instead of escaping
|
| 456 |
+
newlines. For other objects saferepr() is used first.
|
| 457 |
+
"""
|
| 458 |
+
# reprlib appears to have a bug which means that if a string
|
| 459 |
+
# contains a newline it gets escaped, however if an object has a
|
| 460 |
+
# .__repr__() which contains newlines it does not get escaped.
|
| 461 |
+
# However in either case we want to preserve the newline.
|
| 462 |
+
replaces = [("\n", "\n~"), ("%", "%%")]
|
| 463 |
+
if not isinstance(obj, str):
|
| 464 |
+
obj = saferepr(obj, _get_maxsize_for_saferepr(util._config))
|
| 465 |
+
replaces.append(("\\n", "\n~"))
|
| 466 |
+
|
| 467 |
+
for r1, r2 in replaces:
|
| 468 |
+
obj = obj.replace(r1, r2)
|
| 469 |
+
|
| 470 |
+
return obj
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def _should_repr_global_name(obj: object) -> bool:
|
| 474 |
+
if callable(obj):
|
| 475 |
+
return False
|
| 476 |
+
|
| 477 |
+
try:
|
| 478 |
+
return not hasattr(obj, "__name__")
|
| 479 |
+
except Exception:
|
| 480 |
+
return True
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def _format_boolop(explanations: Iterable[str], is_or: bool) -> str:
|
| 484 |
+
explanation = "(" + (is_or and " or " or " and ").join(explanations) + ")"
|
| 485 |
+
return explanation.replace("%", "%%")
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def _call_reprcompare(
|
| 489 |
+
ops: Sequence[str],
|
| 490 |
+
results: Sequence[bool],
|
| 491 |
+
expls: Sequence[str],
|
| 492 |
+
each_obj: Sequence[object],
|
| 493 |
+
) -> str:
|
| 494 |
+
for i, res, expl in zip(range(len(ops)), results, expls):
|
| 495 |
+
try:
|
| 496 |
+
done = not res
|
| 497 |
+
except Exception:
|
| 498 |
+
done = True
|
| 499 |
+
if done:
|
| 500 |
+
break
|
| 501 |
+
if util._reprcompare is not None:
|
| 502 |
+
custom = util._reprcompare(ops[i], each_obj[i], each_obj[i + 1])
|
| 503 |
+
if custom is not None:
|
| 504 |
+
return custom
|
| 505 |
+
return expl
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def _call_assertion_pass(lineno: int, orig: str, expl: str) -> None:
|
| 509 |
+
if util._assertion_pass is not None:
|
| 510 |
+
util._assertion_pass(lineno, orig, expl)
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
def _check_if_assertion_pass_impl() -> bool:
|
| 514 |
+
"""Check if any plugins implement the pytest_assertion_pass hook
|
| 515 |
+
in order not to generate explanation unnecessarily (might be expensive)."""
|
| 516 |
+
return True if util._assertion_pass else False
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
UNARY_MAP = {ast.Not: "not %s", ast.Invert: "~%s", ast.USub: "-%s", ast.UAdd: "+%s"}
|
| 520 |
+
|
| 521 |
+
BINOP_MAP = {
|
| 522 |
+
ast.BitOr: "|",
|
| 523 |
+
ast.BitXor: "^",
|
| 524 |
+
ast.BitAnd: "&",
|
| 525 |
+
ast.LShift: "<<",
|
| 526 |
+
ast.RShift: ">>",
|
| 527 |
+
ast.Add: "+",
|
| 528 |
+
ast.Sub: "-",
|
| 529 |
+
ast.Mult: "*",
|
| 530 |
+
ast.Div: "/",
|
| 531 |
+
ast.FloorDiv: "//",
|
| 532 |
+
ast.Mod: "%%", # escaped for string formatting
|
| 533 |
+
ast.Eq: "==",
|
| 534 |
+
ast.NotEq: "!=",
|
| 535 |
+
ast.Lt: "<",
|
| 536 |
+
ast.LtE: "<=",
|
| 537 |
+
ast.Gt: ">",
|
| 538 |
+
ast.GtE: ">=",
|
| 539 |
+
ast.Pow: "**",
|
| 540 |
+
ast.Is: "is",
|
| 541 |
+
ast.IsNot: "is not",
|
| 542 |
+
ast.In: "in",
|
| 543 |
+
ast.NotIn: "not in",
|
| 544 |
+
ast.MatMult: "@",
|
| 545 |
+
}
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
def traverse_node(node: ast.AST) -> Iterator[ast.AST]:
|
| 549 |
+
"""Recursively yield node and all its children in depth-first order."""
|
| 550 |
+
yield node
|
| 551 |
+
for child in ast.iter_child_nodes(node):
|
| 552 |
+
yield from traverse_node(child)
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
@functools.lru_cache(maxsize=1)
|
| 556 |
+
def _get_assertion_exprs(src: bytes) -> dict[int, str]:
|
| 557 |
+
"""Return a mapping from {lineno: "assertion test expression"}."""
|
| 558 |
+
ret: dict[int, str] = {}
|
| 559 |
+
|
| 560 |
+
depth = 0
|
| 561 |
+
lines: list[str] = []
|
| 562 |
+
assert_lineno: int | None = None
|
| 563 |
+
seen_lines: set[int] = set()
|
| 564 |
+
|
| 565 |
+
def _write_and_reset() -> None:
|
| 566 |
+
nonlocal depth, lines, assert_lineno, seen_lines
|
| 567 |
+
assert assert_lineno is not None
|
| 568 |
+
ret[assert_lineno] = "".join(lines).rstrip().rstrip("\\")
|
| 569 |
+
depth = 0
|
| 570 |
+
lines = []
|
| 571 |
+
assert_lineno = None
|
| 572 |
+
seen_lines = set()
|
| 573 |
+
|
| 574 |
+
tokens = tokenize.tokenize(io.BytesIO(src).readline)
|
| 575 |
+
for tp, source, (lineno, offset), _, line in tokens:
|
| 576 |
+
if tp == tokenize.NAME and source == "assert":
|
| 577 |
+
assert_lineno = lineno
|
| 578 |
+
elif assert_lineno is not None:
|
| 579 |
+
# keep track of depth for the assert-message `,` lookup
|
| 580 |
+
if tp == tokenize.OP and source in "([{":
|
| 581 |
+
depth += 1
|
| 582 |
+
elif tp == tokenize.OP and source in ")]}":
|
| 583 |
+
depth -= 1
|
| 584 |
+
|
| 585 |
+
if not lines:
|
| 586 |
+
lines.append(line[offset:])
|
| 587 |
+
seen_lines.add(lineno)
|
| 588 |
+
# a non-nested comma separates the expression from the message
|
| 589 |
+
elif depth == 0 and tp == tokenize.OP and source == ",":
|
| 590 |
+
# one line assert with message
|
| 591 |
+
if lineno in seen_lines and len(lines) == 1:
|
| 592 |
+
offset_in_trimmed = offset + len(lines[-1]) - len(line)
|
| 593 |
+
lines[-1] = lines[-1][:offset_in_trimmed]
|
| 594 |
+
# multi-line assert with message
|
| 595 |
+
elif lineno in seen_lines:
|
| 596 |
+
lines[-1] = lines[-1][:offset]
|
| 597 |
+
# multi line assert with escaped newline before message
|
| 598 |
+
else:
|
| 599 |
+
lines.append(line[:offset])
|
| 600 |
+
_write_and_reset()
|
| 601 |
+
elif tp in {tokenize.NEWLINE, tokenize.ENDMARKER}:
|
| 602 |
+
_write_and_reset()
|
| 603 |
+
elif lines and lineno not in seen_lines:
|
| 604 |
+
lines.append(line)
|
| 605 |
+
seen_lines.add(lineno)
|
| 606 |
+
|
| 607 |
+
return ret
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
class AssertionRewriter(ast.NodeVisitor):
|
| 611 |
+
"""Assertion rewriting implementation.
|
| 612 |
+
|
| 613 |
+
The main entrypoint is to call .run() with an ast.Module instance,
|
| 614 |
+
this will then find all the assert statements and rewrite them to
|
| 615 |
+
provide intermediate values and a detailed assertion error. See
|
| 616 |
+
http://pybites.blogspot.be/2011/07/behind-scenes-of-pytests-new-assertion.html
|
| 617 |
+
for an overview of how this works.
|
| 618 |
+
|
| 619 |
+
The entry point here is .run() which will iterate over all the
|
| 620 |
+
statements in an ast.Module and for each ast.Assert statement it
|
| 621 |
+
finds call .visit() with it. Then .visit_Assert() takes over and
|
| 622 |
+
is responsible for creating new ast statements to replace the
|
| 623 |
+
original assert statement: it rewrites the test of an assertion
|
| 624 |
+
to provide intermediate values and replace it with an if statement
|
| 625 |
+
which raises an assertion error with a detailed explanation in
|
| 626 |
+
case the expression is false and calls pytest_assertion_pass hook
|
| 627 |
+
if expression is true.
|
| 628 |
+
|
| 629 |
+
For this .visit_Assert() uses the visitor pattern to visit all the
|
| 630 |
+
AST nodes of the ast.Assert.test field, each visit call returning
|
| 631 |
+
an AST node and the corresponding explanation string. During this
|
| 632 |
+
state is kept in several instance attributes:
|
| 633 |
+
|
| 634 |
+
:statements: All the AST statements which will replace the assert
|
| 635 |
+
statement.
|
| 636 |
+
|
| 637 |
+
:variables: This is populated by .variable() with each variable
|
| 638 |
+
used by the statements so that they can all be set to None at
|
| 639 |
+
the end of the statements.
|
| 640 |
+
|
| 641 |
+
:variable_counter: Counter to create new unique variables needed
|
| 642 |
+
by statements. Variables are created using .variable() and
|
| 643 |
+
have the form of "@py_assert0".
|
| 644 |
+
|
| 645 |
+
:expl_stmts: The AST statements which will be executed to get
|
| 646 |
+
data from the assertion. This is the code which will construct
|
| 647 |
+
the detailed assertion message that is used in the AssertionError
|
| 648 |
+
or for the pytest_assertion_pass hook.
|
| 649 |
+
|
| 650 |
+
:explanation_specifiers: A dict filled by .explanation_param()
|
| 651 |
+
with %-formatting placeholders and their corresponding
|
| 652 |
+
expressions to use in the building of an assertion message.
|
| 653 |
+
This is used by .pop_format_context() to build a message.
|
| 654 |
+
|
| 655 |
+
:stack: A stack of the explanation_specifiers dicts maintained by
|
| 656 |
+
.push_format_context() and .pop_format_context() which allows
|
| 657 |
+
to build another %-formatted string while already building one.
|
| 658 |
+
|
| 659 |
+
:scope: A tuple containing the current scope used for variables_overwrite.
|
| 660 |
+
|
| 661 |
+
:variables_overwrite: A dict filled with references to variables
|
| 662 |
+
that change value within an assert. This happens when a variable is
|
| 663 |
+
reassigned with the walrus operator
|
| 664 |
+
|
| 665 |
+
This state, except the variables_overwrite, is reset on every new assert
|
| 666 |
+
statement visited and used by the other visitors.
|
| 667 |
+
"""
|
| 668 |
+
|
| 669 |
+
def __init__(
|
| 670 |
+
self, module_path: str | None, config: Config | None, source: bytes
|
| 671 |
+
) -> None:
|
| 672 |
+
super().__init__()
|
| 673 |
+
self.module_path = module_path
|
| 674 |
+
self.config = config
|
| 675 |
+
if config is not None:
|
| 676 |
+
self.enable_assertion_pass_hook = config.getini(
|
| 677 |
+
"enable_assertion_pass_hook"
|
| 678 |
+
)
|
| 679 |
+
else:
|
| 680 |
+
self.enable_assertion_pass_hook = False
|
| 681 |
+
self.source = source
|
| 682 |
+
self.scope: tuple[ast.AST, ...] = ()
|
| 683 |
+
self.variables_overwrite: defaultdict[tuple[ast.AST, ...], dict[str, str]] = (
|
| 684 |
+
defaultdict(dict)
|
| 685 |
+
)
|
| 686 |
+
|
| 687 |
+
def run(self, mod: ast.Module) -> None:
|
| 688 |
+
"""Find all assert statements in *mod* and rewrite them."""
|
| 689 |
+
if not mod.body:
|
| 690 |
+
# Nothing to do.
|
| 691 |
+
return
|
| 692 |
+
|
| 693 |
+
# We'll insert some special imports at the top of the module, but after any
|
| 694 |
+
# docstrings and __future__ imports, so first figure out where that is.
|
| 695 |
+
doc = getattr(mod, "docstring", None)
|
| 696 |
+
expect_docstring = doc is None
|
| 697 |
+
if doc is not None and self.is_rewrite_disabled(doc):
|
| 698 |
+
return
|
| 699 |
+
pos = 0
|
| 700 |
+
item = None
|
| 701 |
+
for item in mod.body:
|
| 702 |
+
if (
|
| 703 |
+
expect_docstring
|
| 704 |
+
and isinstance(item, ast.Expr)
|
| 705 |
+
and isinstance(item.value, ast.Constant)
|
| 706 |
+
and isinstance(item.value.value, str)
|
| 707 |
+
):
|
| 708 |
+
doc = item.value.value
|
| 709 |
+
if self.is_rewrite_disabled(doc):
|
| 710 |
+
return
|
| 711 |
+
expect_docstring = False
|
| 712 |
+
elif (
|
| 713 |
+
isinstance(item, ast.ImportFrom)
|
| 714 |
+
and item.level == 0
|
| 715 |
+
and item.module == "__future__"
|
| 716 |
+
):
|
| 717 |
+
pass
|
| 718 |
+
else:
|
| 719 |
+
break
|
| 720 |
+
pos += 1
|
| 721 |
+
# Special case: for a decorated function, set the lineno to that of the
|
| 722 |
+
# first decorator, not the `def`. Issue #4984.
|
| 723 |
+
if isinstance(item, ast.FunctionDef) and item.decorator_list:
|
| 724 |
+
lineno = item.decorator_list[0].lineno
|
| 725 |
+
else:
|
| 726 |
+
lineno = item.lineno
|
| 727 |
+
# Now actually insert the special imports.
|
| 728 |
+
if sys.version_info >= (3, 10):
|
| 729 |
+
aliases = [
|
| 730 |
+
ast.alias("builtins", "@py_builtins", lineno=lineno, col_offset=0),
|
| 731 |
+
ast.alias(
|
| 732 |
+
"_pytest.assertion.rewrite",
|
| 733 |
+
"@pytest_ar",
|
| 734 |
+
lineno=lineno,
|
| 735 |
+
col_offset=0,
|
| 736 |
+
),
|
| 737 |
+
]
|
| 738 |
+
else:
|
| 739 |
+
aliases = [
|
| 740 |
+
ast.alias("builtins", "@py_builtins"),
|
| 741 |
+
ast.alias("_pytest.assertion.rewrite", "@pytest_ar"),
|
| 742 |
+
]
|
| 743 |
+
imports = [
|
| 744 |
+
ast.Import([alias], lineno=lineno, col_offset=0) for alias in aliases
|
| 745 |
+
]
|
| 746 |
+
mod.body[pos:pos] = imports
|
| 747 |
+
|
| 748 |
+
# Collect asserts.
|
| 749 |
+
self.scope = (mod,)
|
| 750 |
+
nodes: list[ast.AST | Sentinel] = [mod]
|
| 751 |
+
while nodes:
|
| 752 |
+
node = nodes.pop()
|
| 753 |
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
| 754 |
+
self.scope = tuple((*self.scope, node))
|
| 755 |
+
nodes.append(_SCOPE_END_MARKER)
|
| 756 |
+
if node == _SCOPE_END_MARKER:
|
| 757 |
+
self.scope = self.scope[:-1]
|
| 758 |
+
continue
|
| 759 |
+
assert isinstance(node, ast.AST)
|
| 760 |
+
for name, field in ast.iter_fields(node):
|
| 761 |
+
if isinstance(field, list):
|
| 762 |
+
new: list[ast.AST] = []
|
| 763 |
+
for i, child in enumerate(field):
|
| 764 |
+
if isinstance(child, ast.Assert):
|
| 765 |
+
# Transform assert.
|
| 766 |
+
new.extend(self.visit(child))
|
| 767 |
+
else:
|
| 768 |
+
new.append(child)
|
| 769 |
+
if isinstance(child, ast.AST):
|
| 770 |
+
nodes.append(child)
|
| 771 |
+
setattr(node, name, new)
|
| 772 |
+
elif (
|
| 773 |
+
isinstance(field, ast.AST)
|
| 774 |
+
# Don't recurse into expressions as they can't contain
|
| 775 |
+
# asserts.
|
| 776 |
+
and not isinstance(field, ast.expr)
|
| 777 |
+
):
|
| 778 |
+
nodes.append(field)
|
| 779 |
+
|
| 780 |
+
@staticmethod
|
| 781 |
+
def is_rewrite_disabled(docstring: str) -> bool:
|
| 782 |
+
return "PYTEST_DONT_REWRITE" in docstring
|
| 783 |
+
|
| 784 |
+
def variable(self) -> str:
|
| 785 |
+
"""Get a new variable."""
|
| 786 |
+
# Use a character invalid in python identifiers to avoid clashing.
|
| 787 |
+
name = "@py_assert" + str(next(self.variable_counter))
|
| 788 |
+
self.variables.append(name)
|
| 789 |
+
return name
|
| 790 |
+
|
| 791 |
+
def assign(self, expr: ast.expr) -> ast.Name:
|
| 792 |
+
"""Give *expr* a name."""
|
| 793 |
+
name = self.variable()
|
| 794 |
+
self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr))
|
| 795 |
+
return ast.copy_location(ast.Name(name, ast.Load()), expr)
|
| 796 |
+
|
| 797 |
+
def display(self, expr: ast.expr) -> ast.expr:
|
| 798 |
+
"""Call saferepr on the expression."""
|
| 799 |
+
return self.helper("_saferepr", expr)
|
| 800 |
+
|
| 801 |
+
def helper(self, name: str, *args: ast.expr) -> ast.expr:
|
| 802 |
+
"""Call a helper in this module."""
|
| 803 |
+
py_name = ast.Name("@pytest_ar", ast.Load())
|
| 804 |
+
attr = ast.Attribute(py_name, name, ast.Load())
|
| 805 |
+
return ast.Call(attr, list(args), [])
|
| 806 |
+
|
| 807 |
+
def builtin(self, name: str) -> ast.Attribute:
|
| 808 |
+
"""Return the builtin called *name*."""
|
| 809 |
+
builtin_name = ast.Name("@py_builtins", ast.Load())
|
| 810 |
+
return ast.Attribute(builtin_name, name, ast.Load())
|
| 811 |
+
|
| 812 |
+
def explanation_param(self, expr: ast.expr) -> str:
|
| 813 |
+
"""Return a new named %-formatting placeholder for expr.
|
| 814 |
+
|
| 815 |
+
This creates a %-formatting placeholder for expr in the
|
| 816 |
+
current formatting context, e.g. ``%(py0)s``. The placeholder
|
| 817 |
+
and expr are placed in the current format context so that it
|
| 818 |
+
can be used on the next call to .pop_format_context().
|
| 819 |
+
"""
|
| 820 |
+
specifier = "py" + str(next(self.variable_counter))
|
| 821 |
+
self.explanation_specifiers[specifier] = expr
|
| 822 |
+
return "%(" + specifier + ")s"
|
| 823 |
+
|
| 824 |
+
def push_format_context(self) -> None:
|
| 825 |
+
"""Create a new formatting context.
|
| 826 |
+
|
| 827 |
+
The format context is used for when an explanation wants to
|
| 828 |
+
have a variable value formatted in the assertion message. In
|
| 829 |
+
this case the value required can be added using
|
| 830 |
+
.explanation_param(). Finally .pop_format_context() is used
|
| 831 |
+
to format a string of %-formatted values as added by
|
| 832 |
+
.explanation_param().
|
| 833 |
+
"""
|
| 834 |
+
self.explanation_specifiers: dict[str, ast.expr] = {}
|
| 835 |
+
self.stack.append(self.explanation_specifiers)
|
| 836 |
+
|
| 837 |
+
def pop_format_context(self, expl_expr: ast.expr) -> ast.Name:
|
| 838 |
+
"""Format the %-formatted string with current format context.
|
| 839 |
+
|
| 840 |
+
The expl_expr should be an str ast.expr instance constructed from
|
| 841 |
+
the %-placeholders created by .explanation_param(). This will
|
| 842 |
+
add the required code to format said string to .expl_stmts and
|
| 843 |
+
return the ast.Name instance of the formatted string.
|
| 844 |
+
"""
|
| 845 |
+
current = self.stack.pop()
|
| 846 |
+
if self.stack:
|
| 847 |
+
self.explanation_specifiers = self.stack[-1]
|
| 848 |
+
keys: list[ast.expr | None] = [ast.Constant(key) for key in current.keys()]
|
| 849 |
+
format_dict = ast.Dict(keys, list(current.values()))
|
| 850 |
+
form = ast.BinOp(expl_expr, ast.Mod(), format_dict)
|
| 851 |
+
name = "@py_format" + str(next(self.variable_counter))
|
| 852 |
+
if self.enable_assertion_pass_hook:
|
| 853 |
+
self.format_variables.append(name)
|
| 854 |
+
self.expl_stmts.append(ast.Assign([ast.Name(name, ast.Store())], form))
|
| 855 |
+
return ast.Name(name, ast.Load())
|
| 856 |
+
|
| 857 |
+
def generic_visit(self, node: ast.AST) -> tuple[ast.Name, str]:
|
| 858 |
+
"""Handle expressions we don't have custom code for."""
|
| 859 |
+
assert isinstance(node, ast.expr)
|
| 860 |
+
res = self.assign(node)
|
| 861 |
+
return res, self.explanation_param(self.display(res))
|
| 862 |
+
|
| 863 |
+
def visit_Assert(self, assert_: ast.Assert) -> list[ast.stmt]:
|
| 864 |
+
"""Return the AST statements to replace the ast.Assert instance.
|
| 865 |
+
|
| 866 |
+
This rewrites the test of an assertion to provide
|
| 867 |
+
intermediate values and replace it with an if statement which
|
| 868 |
+
raises an assertion error with a detailed explanation in case
|
| 869 |
+
the expression is false.
|
| 870 |
+
"""
|
| 871 |
+
if isinstance(assert_.test, ast.Tuple) and len(assert_.test.elts) >= 1:
|
| 872 |
+
import warnings
|
| 873 |
+
|
| 874 |
+
from _pytest.warning_types import PytestAssertRewriteWarning
|
| 875 |
+
|
| 876 |
+
# TODO: This assert should not be needed.
|
| 877 |
+
assert self.module_path is not None
|
| 878 |
+
warnings.warn_explicit(
|
| 879 |
+
PytestAssertRewriteWarning(
|
| 880 |
+
"assertion is always true, perhaps remove parentheses?"
|
| 881 |
+
),
|
| 882 |
+
category=None,
|
| 883 |
+
filename=self.module_path,
|
| 884 |
+
lineno=assert_.lineno,
|
| 885 |
+
)
|
| 886 |
+
|
| 887 |
+
self.statements: list[ast.stmt] = []
|
| 888 |
+
self.variables: list[str] = []
|
| 889 |
+
self.variable_counter = itertools.count()
|
| 890 |
+
|
| 891 |
+
if self.enable_assertion_pass_hook:
|
| 892 |
+
self.format_variables: list[str] = []
|
| 893 |
+
|
| 894 |
+
self.stack: list[dict[str, ast.expr]] = []
|
| 895 |
+
self.expl_stmts: list[ast.stmt] = []
|
| 896 |
+
self.push_format_context()
|
| 897 |
+
# Rewrite assert into a bunch of statements.
|
| 898 |
+
top_condition, explanation = self.visit(assert_.test)
|
| 899 |
+
|
| 900 |
+
negation = ast.UnaryOp(ast.Not(), top_condition)
|
| 901 |
+
|
| 902 |
+
if self.enable_assertion_pass_hook: # Experimental pytest_assertion_pass hook
|
| 903 |
+
msg = self.pop_format_context(ast.Constant(explanation))
|
| 904 |
+
|
| 905 |
+
# Failed
|
| 906 |
+
if assert_.msg:
|
| 907 |
+
assertmsg = self.helper("_format_assertmsg", assert_.msg)
|
| 908 |
+
gluestr = "\n>assert "
|
| 909 |
+
else:
|
| 910 |
+
assertmsg = ast.Constant("")
|
| 911 |
+
gluestr = "assert "
|
| 912 |
+
err_explanation = ast.BinOp(ast.Constant(gluestr), ast.Add(), msg)
|
| 913 |
+
err_msg = ast.BinOp(assertmsg, ast.Add(), err_explanation)
|
| 914 |
+
err_name = ast.Name("AssertionError", ast.Load())
|
| 915 |
+
fmt = self.helper("_format_explanation", err_msg)
|
| 916 |
+
exc = ast.Call(err_name, [fmt], [])
|
| 917 |
+
raise_ = ast.Raise(exc, None)
|
| 918 |
+
statements_fail = []
|
| 919 |
+
statements_fail.extend(self.expl_stmts)
|
| 920 |
+
statements_fail.append(raise_)
|
| 921 |
+
|
| 922 |
+
# Passed
|
| 923 |
+
fmt_pass = self.helper("_format_explanation", msg)
|
| 924 |
+
orig = _get_assertion_exprs(self.source)[assert_.lineno]
|
| 925 |
+
hook_call_pass = ast.Expr(
|
| 926 |
+
self.helper(
|
| 927 |
+
"_call_assertion_pass",
|
| 928 |
+
ast.Constant(assert_.lineno),
|
| 929 |
+
ast.Constant(orig),
|
| 930 |
+
fmt_pass,
|
| 931 |
+
)
|
| 932 |
+
)
|
| 933 |
+
# If any hooks implement assert_pass hook
|
| 934 |
+
hook_impl_test = ast.If(
|
| 935 |
+
self.helper("_check_if_assertion_pass_impl"),
|
| 936 |
+
[*self.expl_stmts, hook_call_pass],
|
| 937 |
+
[],
|
| 938 |
+
)
|
| 939 |
+
statements_pass: list[ast.stmt] = [hook_impl_test]
|
| 940 |
+
|
| 941 |
+
# Test for assertion condition
|
| 942 |
+
main_test = ast.If(negation, statements_fail, statements_pass)
|
| 943 |
+
self.statements.append(main_test)
|
| 944 |
+
if self.format_variables:
|
| 945 |
+
variables: list[ast.expr] = [
|
| 946 |
+
ast.Name(name, ast.Store()) for name in self.format_variables
|
| 947 |
+
]
|
| 948 |
+
clear_format = ast.Assign(variables, ast.Constant(None))
|
| 949 |
+
self.statements.append(clear_format)
|
| 950 |
+
|
| 951 |
+
else: # Original assertion rewriting
|
| 952 |
+
# Create failure message.
|
| 953 |
+
body = self.expl_stmts
|
| 954 |
+
self.statements.append(ast.If(negation, body, []))
|
| 955 |
+
if assert_.msg:
|
| 956 |
+
assertmsg = self.helper("_format_assertmsg", assert_.msg)
|
| 957 |
+
explanation = "\n>assert " + explanation
|
| 958 |
+
else:
|
| 959 |
+
assertmsg = ast.Constant("")
|
| 960 |
+
explanation = "assert " + explanation
|
| 961 |
+
template = ast.BinOp(assertmsg, ast.Add(), ast.Constant(explanation))
|
| 962 |
+
msg = self.pop_format_context(template)
|
| 963 |
+
fmt = self.helper("_format_explanation", msg)
|
| 964 |
+
err_name = ast.Name("AssertionError", ast.Load())
|
| 965 |
+
exc = ast.Call(err_name, [fmt], [])
|
| 966 |
+
raise_ = ast.Raise(exc, None)
|
| 967 |
+
|
| 968 |
+
body.append(raise_)
|
| 969 |
+
|
| 970 |
+
# Clear temporary variables by setting them to None.
|
| 971 |
+
if self.variables:
|
| 972 |
+
variables = [ast.Name(name, ast.Store()) for name in self.variables]
|
| 973 |
+
clear = ast.Assign(variables, ast.Constant(None))
|
| 974 |
+
self.statements.append(clear)
|
| 975 |
+
# Fix locations (line numbers/column offsets).
|
| 976 |
+
for stmt in self.statements:
|
| 977 |
+
for node in traverse_node(stmt):
|
| 978 |
+
if getattr(node, "lineno", None) is None:
|
| 979 |
+
# apply the assertion location to all generated ast nodes without source location
|
| 980 |
+
# and preserve the location of existing nodes or generated nodes with an correct location.
|
| 981 |
+
ast.copy_location(node, assert_)
|
| 982 |
+
return self.statements
|
| 983 |
+
|
| 984 |
+
def visit_NamedExpr(self, name: ast.NamedExpr) -> tuple[ast.NamedExpr, str]:
|
| 985 |
+
# This method handles the 'walrus operator' repr of the target
|
| 986 |
+
# name if it's a local variable or _should_repr_global_name()
|
| 987 |
+
# thinks it's acceptable.
|
| 988 |
+
locs = ast.Call(self.builtin("locals"), [], [])
|
| 989 |
+
target_id = name.target.id
|
| 990 |
+
inlocs = ast.Compare(ast.Constant(target_id), [ast.In()], [locs])
|
| 991 |
+
dorepr = self.helper("_should_repr_global_name", name)
|
| 992 |
+
test = ast.BoolOp(ast.Or(), [inlocs, dorepr])
|
| 993 |
+
expr = ast.IfExp(test, self.display(name), ast.Constant(target_id))
|
| 994 |
+
return name, self.explanation_param(expr)
|
| 995 |
+
|
| 996 |
+
def visit_Name(self, name: ast.Name) -> tuple[ast.Name, str]:
|
| 997 |
+
# Display the repr of the name if it's a local variable or
|
| 998 |
+
# _should_repr_global_name() thinks it's acceptable.
|
| 999 |
+
locs = ast.Call(self.builtin("locals"), [], [])
|
| 1000 |
+
inlocs = ast.Compare(ast.Constant(name.id), [ast.In()], [locs])
|
| 1001 |
+
dorepr = self.helper("_should_repr_global_name", name)
|
| 1002 |
+
test = ast.BoolOp(ast.Or(), [inlocs, dorepr])
|
| 1003 |
+
expr = ast.IfExp(test, self.display(name), ast.Constant(name.id))
|
| 1004 |
+
return name, self.explanation_param(expr)
|
| 1005 |
+
|
| 1006 |
+
def visit_BoolOp(self, boolop: ast.BoolOp) -> tuple[ast.Name, str]:
|
| 1007 |
+
res_var = self.variable()
|
| 1008 |
+
expl_list = self.assign(ast.List([], ast.Load()))
|
| 1009 |
+
app = ast.Attribute(expl_list, "append", ast.Load())
|
| 1010 |
+
is_or = int(isinstance(boolop.op, ast.Or))
|
| 1011 |
+
body = save = self.statements
|
| 1012 |
+
fail_save = self.expl_stmts
|
| 1013 |
+
levels = len(boolop.values) - 1
|
| 1014 |
+
self.push_format_context()
|
| 1015 |
+
# Process each operand, short-circuiting if needed.
|
| 1016 |
+
for i, v in enumerate(boolop.values):
|
| 1017 |
+
if i:
|
| 1018 |
+
fail_inner: list[ast.stmt] = []
|
| 1019 |
+
# cond is set in a prior loop iteration below
|
| 1020 |
+
self.expl_stmts.append(ast.If(cond, fail_inner, [])) # noqa: F821
|
| 1021 |
+
self.expl_stmts = fail_inner
|
| 1022 |
+
# Check if the left operand is a ast.NamedExpr and the value has already been visited
|
| 1023 |
+
if (
|
| 1024 |
+
isinstance(v, ast.Compare)
|
| 1025 |
+
and isinstance(v.left, ast.NamedExpr)
|
| 1026 |
+
and v.left.target.id
|
| 1027 |
+
in [
|
| 1028 |
+
ast_expr.id
|
| 1029 |
+
for ast_expr in boolop.values[:i]
|
| 1030 |
+
if hasattr(ast_expr, "id")
|
| 1031 |
+
]
|
| 1032 |
+
):
|
| 1033 |
+
pytest_temp = self.variable()
|
| 1034 |
+
self.variables_overwrite[self.scope][v.left.target.id] = v.left # type:ignore[assignment]
|
| 1035 |
+
v.left.target.id = pytest_temp
|
| 1036 |
+
self.push_format_context()
|
| 1037 |
+
res, expl = self.visit(v)
|
| 1038 |
+
body.append(ast.Assign([ast.Name(res_var, ast.Store())], res))
|
| 1039 |
+
expl_format = self.pop_format_context(ast.Constant(expl))
|
| 1040 |
+
call = ast.Call(app, [expl_format], [])
|
| 1041 |
+
self.expl_stmts.append(ast.Expr(call))
|
| 1042 |
+
if i < levels:
|
| 1043 |
+
cond: ast.expr = res
|
| 1044 |
+
if is_or:
|
| 1045 |
+
cond = ast.UnaryOp(ast.Not(), cond)
|
| 1046 |
+
inner: list[ast.stmt] = []
|
| 1047 |
+
self.statements.append(ast.If(cond, inner, []))
|
| 1048 |
+
self.statements = body = inner
|
| 1049 |
+
self.statements = save
|
| 1050 |
+
self.expl_stmts = fail_save
|
| 1051 |
+
expl_template = self.helper("_format_boolop", expl_list, ast.Constant(is_or))
|
| 1052 |
+
expl = self.pop_format_context(expl_template)
|
| 1053 |
+
return ast.Name(res_var, ast.Load()), self.explanation_param(expl)
|
| 1054 |
+
|
| 1055 |
+
def visit_UnaryOp(self, unary: ast.UnaryOp) -> tuple[ast.Name, str]:
|
| 1056 |
+
pattern = UNARY_MAP[unary.op.__class__]
|
| 1057 |
+
operand_res, operand_expl = self.visit(unary.operand)
|
| 1058 |
+
res = self.assign(ast.copy_location(ast.UnaryOp(unary.op, operand_res), unary))
|
| 1059 |
+
return res, pattern % (operand_expl,)
|
| 1060 |
+
|
| 1061 |
+
def visit_BinOp(self, binop: ast.BinOp) -> tuple[ast.Name, str]:
|
| 1062 |
+
symbol = BINOP_MAP[binop.op.__class__]
|
| 1063 |
+
left_expr, left_expl = self.visit(binop.left)
|
| 1064 |
+
right_expr, right_expl = self.visit(binop.right)
|
| 1065 |
+
explanation = f"({left_expl} {symbol} {right_expl})"
|
| 1066 |
+
res = self.assign(
|
| 1067 |
+
ast.copy_location(ast.BinOp(left_expr, binop.op, right_expr), binop)
|
| 1068 |
+
)
|
| 1069 |
+
return res, explanation
|
| 1070 |
+
|
| 1071 |
+
def visit_Call(self, call: ast.Call) -> tuple[ast.Name, str]:
|
| 1072 |
+
new_func, func_expl = self.visit(call.func)
|
| 1073 |
+
arg_expls = []
|
| 1074 |
+
new_args = []
|
| 1075 |
+
new_kwargs = []
|
| 1076 |
+
for arg in call.args:
|
| 1077 |
+
if isinstance(arg, ast.Name) and arg.id in self.variables_overwrite.get(
|
| 1078 |
+
self.scope, {}
|
| 1079 |
+
):
|
| 1080 |
+
arg = self.variables_overwrite[self.scope][arg.id] # type:ignore[assignment]
|
| 1081 |
+
res, expl = self.visit(arg)
|
| 1082 |
+
arg_expls.append(expl)
|
| 1083 |
+
new_args.append(res)
|
| 1084 |
+
for keyword in call.keywords:
|
| 1085 |
+
if isinstance(
|
| 1086 |
+
keyword.value, ast.Name
|
| 1087 |
+
) and keyword.value.id in self.variables_overwrite.get(self.scope, {}):
|
| 1088 |
+
keyword.value = self.variables_overwrite[self.scope][keyword.value.id] # type:ignore[assignment]
|
| 1089 |
+
res, expl = self.visit(keyword.value)
|
| 1090 |
+
new_kwargs.append(ast.keyword(keyword.arg, res))
|
| 1091 |
+
if keyword.arg:
|
| 1092 |
+
arg_expls.append(keyword.arg + "=" + expl)
|
| 1093 |
+
else: # **args have `arg` keywords with an .arg of None
|
| 1094 |
+
arg_expls.append("**" + expl)
|
| 1095 |
+
|
| 1096 |
+
expl = "{}({})".format(func_expl, ", ".join(arg_expls))
|
| 1097 |
+
new_call = ast.copy_location(ast.Call(new_func, new_args, new_kwargs), call)
|
| 1098 |
+
res = self.assign(new_call)
|
| 1099 |
+
res_expl = self.explanation_param(self.display(res))
|
| 1100 |
+
outer_expl = f"{res_expl}\n{{{res_expl} = {expl}\n}}"
|
| 1101 |
+
return res, outer_expl
|
| 1102 |
+
|
| 1103 |
+
def visit_Starred(self, starred: ast.Starred) -> tuple[ast.Starred, str]:
|
| 1104 |
+
# A Starred node can appear in a function call.
|
| 1105 |
+
res, expl = self.visit(starred.value)
|
| 1106 |
+
new_starred = ast.Starred(res, starred.ctx)
|
| 1107 |
+
return new_starred, "*" + expl
|
| 1108 |
+
|
| 1109 |
+
def visit_Attribute(self, attr: ast.Attribute) -> tuple[ast.Name, str]:
|
| 1110 |
+
if not isinstance(attr.ctx, ast.Load):
|
| 1111 |
+
return self.generic_visit(attr)
|
| 1112 |
+
value, value_expl = self.visit(attr.value)
|
| 1113 |
+
res = self.assign(
|
| 1114 |
+
ast.copy_location(ast.Attribute(value, attr.attr, ast.Load()), attr)
|
| 1115 |
+
)
|
| 1116 |
+
res_expl = self.explanation_param(self.display(res))
|
| 1117 |
+
pat = "%s\n{%s = %s.%s\n}"
|
| 1118 |
+
expl = pat % (res_expl, res_expl, value_expl, attr.attr)
|
| 1119 |
+
return res, expl
|
| 1120 |
+
|
| 1121 |
+
def visit_Compare(self, comp: ast.Compare) -> tuple[ast.expr, str]:
|
| 1122 |
+
self.push_format_context()
|
| 1123 |
+
# We first check if we have overwritten a variable in the previous assert
|
| 1124 |
+
if isinstance(
|
| 1125 |
+
comp.left, ast.Name
|
| 1126 |
+
) and comp.left.id in self.variables_overwrite.get(self.scope, {}):
|
| 1127 |
+
comp.left = self.variables_overwrite[self.scope][comp.left.id] # type:ignore[assignment]
|
| 1128 |
+
if isinstance(comp.left, ast.NamedExpr):
|
| 1129 |
+
self.variables_overwrite[self.scope][comp.left.target.id] = comp.left # type:ignore[assignment]
|
| 1130 |
+
left_res, left_expl = self.visit(comp.left)
|
| 1131 |
+
if isinstance(comp.left, (ast.Compare, ast.BoolOp)):
|
| 1132 |
+
left_expl = f"({left_expl})"
|
| 1133 |
+
res_variables = [self.variable() for i in range(len(comp.ops))]
|
| 1134 |
+
load_names: list[ast.expr] = [ast.Name(v, ast.Load()) for v in res_variables]
|
| 1135 |
+
store_names = [ast.Name(v, ast.Store()) for v in res_variables]
|
| 1136 |
+
it = zip(range(len(comp.ops)), comp.ops, comp.comparators)
|
| 1137 |
+
expls: list[ast.expr] = []
|
| 1138 |
+
syms: list[ast.expr] = []
|
| 1139 |
+
results = [left_res]
|
| 1140 |
+
for i, op, next_operand in it:
|
| 1141 |
+
if (
|
| 1142 |
+
isinstance(next_operand, ast.NamedExpr)
|
| 1143 |
+
and isinstance(left_res, ast.Name)
|
| 1144 |
+
and next_operand.target.id == left_res.id
|
| 1145 |
+
):
|
| 1146 |
+
next_operand.target.id = self.variable()
|
| 1147 |
+
self.variables_overwrite[self.scope][left_res.id] = next_operand # type:ignore[assignment]
|
| 1148 |
+
next_res, next_expl = self.visit(next_operand)
|
| 1149 |
+
if isinstance(next_operand, (ast.Compare, ast.BoolOp)):
|
| 1150 |
+
next_expl = f"({next_expl})"
|
| 1151 |
+
results.append(next_res)
|
| 1152 |
+
sym = BINOP_MAP[op.__class__]
|
| 1153 |
+
syms.append(ast.Constant(sym))
|
| 1154 |
+
expl = f"{left_expl} {sym} {next_expl}"
|
| 1155 |
+
expls.append(ast.Constant(expl))
|
| 1156 |
+
res_expr = ast.copy_location(ast.Compare(left_res, [op], [next_res]), comp)
|
| 1157 |
+
self.statements.append(ast.Assign([store_names[i]], res_expr))
|
| 1158 |
+
left_res, left_expl = next_res, next_expl
|
| 1159 |
+
# Use pytest.assertion.util._reprcompare if that's available.
|
| 1160 |
+
expl_call = self.helper(
|
| 1161 |
+
"_call_reprcompare",
|
| 1162 |
+
ast.Tuple(syms, ast.Load()),
|
| 1163 |
+
ast.Tuple(load_names, ast.Load()),
|
| 1164 |
+
ast.Tuple(expls, ast.Load()),
|
| 1165 |
+
ast.Tuple(results, ast.Load()),
|
| 1166 |
+
)
|
| 1167 |
+
if len(comp.ops) > 1:
|
| 1168 |
+
res: ast.expr = ast.BoolOp(ast.And(), load_names)
|
| 1169 |
+
else:
|
| 1170 |
+
res = load_names[0]
|
| 1171 |
+
|
| 1172 |
+
return res, self.explanation_param(self.pop_format_context(expl_call))
|
| 1173 |
+
|
| 1174 |
+
|
| 1175 |
+
def try_makedirs(cache_dir: Path) -> bool:
|
| 1176 |
+
"""Attempt to create the given directory and sub-directories exist.
|
| 1177 |
+
|
| 1178 |
+
Returns True if successful or if it already exists.
|
| 1179 |
+
"""
|
| 1180 |
+
try:
|
| 1181 |
+
os.makedirs(cache_dir, exist_ok=True)
|
| 1182 |
+
except (FileNotFoundError, NotADirectoryError, FileExistsError):
|
| 1183 |
+
# One of the path components was not a directory:
|
| 1184 |
+
# - we're in a zip file
|
| 1185 |
+
# - it is a file
|
| 1186 |
+
return False
|
| 1187 |
+
except PermissionError:
|
| 1188 |
+
return False
|
| 1189 |
+
except OSError as e:
|
| 1190 |
+
# as of now, EROFS doesn't have an equivalent OSError-subclass
|
| 1191 |
+
#
|
| 1192 |
+
# squashfuse_ll returns ENOSYS "OSError: [Errno 38] Function not
|
| 1193 |
+
# implemented" for a read-only error
|
| 1194 |
+
if e.errno in {errno.EROFS, errno.ENOSYS}:
|
| 1195 |
+
return False
|
| 1196 |
+
raise
|
| 1197 |
+
return True
|
| 1198 |
+
|
| 1199 |
+
|
| 1200 |
+
def get_cache_dir(file_path: Path) -> Path:
|
| 1201 |
+
"""Return the cache directory to write .pyc files for the given .py file path."""
|
| 1202 |
+
if sys.pycache_prefix:
|
| 1203 |
+
# given:
|
| 1204 |
+
# prefix = '/tmp/pycs'
|
| 1205 |
+
# path = '/home/user/proj/test_app.py'
|
| 1206 |
+
# we want:
|
| 1207 |
+
# '/tmp/pycs/home/user/proj'
|
| 1208 |
+
return Path(sys.pycache_prefix) / Path(*file_path.parts[1:-1])
|
| 1209 |
+
else:
|
| 1210 |
+
# classic pycache directory
|
| 1211 |
+
return file_path.parent / "__pycache__"
|
vllm/lib/python3.10/site-packages/_pytest/assertion/truncate.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Utilities for truncating assertion output.
|
| 2 |
+
|
| 3 |
+
Current default behaviour is to truncate assertion explanations at
|
| 4 |
+
terminal lines, unless running with an assertions verbosity level of at least 2 or running on CI.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from _pytest.assertion import util
|
| 10 |
+
from _pytest.config import Config
|
| 11 |
+
from _pytest.nodes import Item
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
DEFAULT_MAX_LINES = 8
|
| 15 |
+
DEFAULT_MAX_CHARS = 8 * 80
|
| 16 |
+
USAGE_MSG = "use '-vv' to show"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def truncate_if_required(
|
| 20 |
+
explanation: list[str], item: Item, max_length: int | None = None
|
| 21 |
+
) -> list[str]:
|
| 22 |
+
"""Truncate this assertion explanation if the given test item is eligible."""
|
| 23 |
+
if _should_truncate_item(item):
|
| 24 |
+
return _truncate_explanation(explanation)
|
| 25 |
+
return explanation
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _should_truncate_item(item: Item) -> bool:
|
| 29 |
+
"""Whether or not this test item is eligible for truncation."""
|
| 30 |
+
verbose = item.config.get_verbosity(Config.VERBOSITY_ASSERTIONS)
|
| 31 |
+
return verbose < 2 and not util.running_on_ci()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _truncate_explanation(
|
| 35 |
+
input_lines: list[str],
|
| 36 |
+
max_lines: int | None = None,
|
| 37 |
+
max_chars: int | None = None,
|
| 38 |
+
) -> list[str]:
|
| 39 |
+
"""Truncate given list of strings that makes up the assertion explanation.
|
| 40 |
+
|
| 41 |
+
Truncates to either 8 lines, or 640 characters - whichever the input reaches
|
| 42 |
+
first, taking the truncation explanation into account. The remaining lines
|
| 43 |
+
will be replaced by a usage message.
|
| 44 |
+
"""
|
| 45 |
+
if max_lines is None:
|
| 46 |
+
max_lines = DEFAULT_MAX_LINES
|
| 47 |
+
if max_chars is None:
|
| 48 |
+
max_chars = DEFAULT_MAX_CHARS
|
| 49 |
+
|
| 50 |
+
# Check if truncation required
|
| 51 |
+
input_char_count = len("".join(input_lines))
|
| 52 |
+
# The length of the truncation explanation depends on the number of lines
|
| 53 |
+
# removed but is at least 68 characters:
|
| 54 |
+
# The real value is
|
| 55 |
+
# 64 (for the base message:
|
| 56 |
+
# '...\n...Full output truncated (1 line hidden), use '-vv' to show")'
|
| 57 |
+
# )
|
| 58 |
+
# + 1 (for plural)
|
| 59 |
+
# + int(math.log10(len(input_lines) - max_lines)) (number of hidden line, at least 1)
|
| 60 |
+
# + 3 for the '...' added to the truncated line
|
| 61 |
+
# But if there's more than 100 lines it's very likely that we're going to
|
| 62 |
+
# truncate, so we don't need the exact value using log10.
|
| 63 |
+
tolerable_max_chars = (
|
| 64 |
+
max_chars + 70 # 64 + 1 (for plural) + 2 (for '99') + 3 for '...'
|
| 65 |
+
)
|
| 66 |
+
# The truncation explanation add two lines to the output
|
| 67 |
+
tolerable_max_lines = max_lines + 2
|
| 68 |
+
if (
|
| 69 |
+
len(input_lines) <= tolerable_max_lines
|
| 70 |
+
and input_char_count <= tolerable_max_chars
|
| 71 |
+
):
|
| 72 |
+
return input_lines
|
| 73 |
+
# Truncate first to max_lines, and then truncate to max_chars if necessary
|
| 74 |
+
truncated_explanation = input_lines[:max_lines]
|
| 75 |
+
truncated_char = True
|
| 76 |
+
# We reevaluate the need to truncate chars following removal of some lines
|
| 77 |
+
if len("".join(truncated_explanation)) > tolerable_max_chars:
|
| 78 |
+
truncated_explanation = _truncate_by_char_count(
|
| 79 |
+
truncated_explanation, max_chars
|
| 80 |
+
)
|
| 81 |
+
else:
|
| 82 |
+
truncated_char = False
|
| 83 |
+
|
| 84 |
+
truncated_line_count = len(input_lines) - len(truncated_explanation)
|
| 85 |
+
if truncated_explanation[-1]:
|
| 86 |
+
# Add ellipsis and take into account part-truncated final line
|
| 87 |
+
truncated_explanation[-1] = truncated_explanation[-1] + "..."
|
| 88 |
+
if truncated_char:
|
| 89 |
+
# It's possible that we did not remove any char from this line
|
| 90 |
+
truncated_line_count += 1
|
| 91 |
+
else:
|
| 92 |
+
# Add proper ellipsis when we were able to fit a full line exactly
|
| 93 |
+
truncated_explanation[-1] = "..."
|
| 94 |
+
return [
|
| 95 |
+
*truncated_explanation,
|
| 96 |
+
"",
|
| 97 |
+
f"...Full output truncated ({truncated_line_count} line"
|
| 98 |
+
f"{'' if truncated_line_count == 1 else 's'} hidden), {USAGE_MSG}",
|
| 99 |
+
]
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _truncate_by_char_count(input_lines: list[str], max_chars: int) -> list[str]:
|
| 103 |
+
# Find point at which input length exceeds total allowed length
|
| 104 |
+
iterated_char_count = 0
|
| 105 |
+
for iterated_index, input_line in enumerate(input_lines):
|
| 106 |
+
if iterated_char_count + len(input_line) > max_chars:
|
| 107 |
+
break
|
| 108 |
+
iterated_char_count += len(input_line)
|
| 109 |
+
|
| 110 |
+
# Create truncated explanation with modified final line
|
| 111 |
+
truncated_result = input_lines[:iterated_index]
|
| 112 |
+
final_line = input_lines[iterated_index]
|
| 113 |
+
if final_line:
|
| 114 |
+
final_line_truncate_point = max_chars - iterated_char_count
|
| 115 |
+
final_line = final_line[:final_line_truncate_point]
|
| 116 |
+
truncated_result.append(final_line)
|
| 117 |
+
return truncated_result
|