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 +1 -0
- wemm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/LICENSE.txt +28 -0
- wemm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/RECORD +15 -0
- wemm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/REQUESTED +0 -0
- wemm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/top_level.txt +1 -0
- wemm/lib/python3.10/site-packages/_pytest/__pycache__/helpconfig.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/_pytest/_argcomplete.py +116 -0
- wemm/lib/python3.10/site-packages/_pytest/_code/__init__.py +22 -0
- wemm/lib/python3.10/site-packages/_pytest/_code/__pycache__/code.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/_pytest/_code/__pycache__/source.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/_pytest/_io/wcwidth.py +55 -0
- wemm/lib/python3.10/site-packages/_pytest/_py/__pycache__/path.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/_pytest/_version.py +4 -0
- wemm/lib/python3.10/site-packages/_pytest/assertion/__init__.py +181 -0
- wemm/lib/python3.10/site-packages/_pytest/assertion/__pycache__/rewrite.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/_pytest/assertion/rewrite.py +1185 -0
- wemm/lib/python3.10/site-packages/_pytest/cacheprovider.py +598 -0
- wemm/lib/python3.10/site-packages/_pytest/capture.py +1082 -0
- wemm/lib/python3.10/site-packages/_pytest/compat.py +426 -0
- wemm/lib/python3.10/site-packages/_pytest/config/__pycache__/__init__.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/_pytest/config/__pycache__/argparsing.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/_pytest/config/__pycache__/exceptions.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/_pytest/config/__pycache__/findpaths.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/_pytest/config/compat.py +70 -0
- wemm/lib/python3.10/site-packages/_pytest/config/exceptions.py +11 -0
- wemm/lib/python3.10/site-packages/_pytest/deprecated.py +146 -0
- wemm/lib/python3.10/site-packages/_pytest/faulthandler.py +95 -0
- wemm/lib/python3.10/site-packages/_pytest/freeze_support.py +44 -0
- wemm/lib/python3.10/site-packages/_pytest/helpconfig.py +266 -0
- wemm/lib/python3.10/site-packages/_pytest/hookspec.py +979 -0
- wemm/lib/python3.10/site-packages/_pytest/logging.py +918 -0
- wemm/lib/python3.10/site-packages/_pytest/mark/__pycache__/__init__.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/_pytest/monkeypatch.py +421 -0
- wemm/lib/python3.10/site-packages/_pytest/nose.py +50 -0
- wemm/lib/python3.10/site-packages/_pytest/outcomes.py +311 -0
- wemm/lib/python3.10/site-packages/_pytest/pathlib.py +775 -0
- wemm/lib/python3.10/site-packages/_pytest/pytester_assertions.py +75 -0
- wemm/lib/python3.10/site-packages/_pytest/recwarn.py +313 -0
- wemm/lib/python3.10/site-packages/_pytest/reports.py +622 -0
- wemm/lib/python3.10/site-packages/_pytest/setupplan.py +40 -0
- wemm/lib/python3.10/site-packages/_pytest/skipping.py +297 -0
- wemm/lib/python3.10/site-packages/_pytest/terminal.py +1481 -0
- wemm/lib/python3.10/site-packages/_pytest/timing.py +12 -0
- wemm/lib/python3.10/site-packages/_pytest/tmpdir.py +324 -0
- wemm/lib/python3.10/site-packages/_pytest/unraisableexception.py +93 -0
- wemm/lib/python3.10/site-packages/_pytest/warnings.py +148 -0
- wemm/lib/python3.10/site-packages/boto3-1.26.118.dist-info/NOTICE +2 -0
- wemm/lib/python3.10/site-packages/boto3-1.26.118.dist-info/RECORD +100 -0
- wemm/lib/python3.10/site-packages/cos_python_sdk_v5-1.9.33.dist-info/METADATA +57 -0
- wemm/lib/python3.10/site-packages/cos_python_sdk_v5-1.9.33.dist-info/RECORD +40 -0
.gitattributes
CHANGED
|
@@ -185,3 +185,4 @@ parrot/lib/libsqlite3.so filter=lfs diff=lfs merge=lfs -text
|
|
| 185 |
parrot/lib/libtcl8.6.so filter=lfs diff=lfs merge=lfs -text
|
| 186 |
wemm/lib/python3.10/site-packages/tokenizers/tokenizers.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 187 |
wemm/lib/python3.10/site-packages/charset_normalizer/md__mypyc.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 185 |
parrot/lib/libtcl8.6.so filter=lfs diff=lfs merge=lfs -text
|
| 186 |
wemm/lib/python3.10/site-packages/tokenizers/tokenizers.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 187 |
wemm/lib/python3.10/site-packages/charset_normalizer/md__mypyc.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 188 |
+
wemm/lib/python3.10/site-packages/triton/third_party/cuda/lib/libdevice.10.bc filter=lfs diff=lfs merge=lfs -text
|
wemm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/LICENSE.txt
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright 2010 Pallets
|
| 2 |
+
|
| 3 |
+
Redistribution and use in source and binary forms, with or without
|
| 4 |
+
modification, are permitted provided that the following conditions are
|
| 5 |
+
met:
|
| 6 |
+
|
| 7 |
+
1. Redistributions of source code must retain the above copyright
|
| 8 |
+
notice, this list of conditions and the following disclaimer.
|
| 9 |
+
|
| 10 |
+
2. Redistributions in binary form must reproduce the above copyright
|
| 11 |
+
notice, this list of conditions and the following disclaimer in the
|
| 12 |
+
documentation and/or other materials provided with the distribution.
|
| 13 |
+
|
| 14 |
+
3. Neither the name of the copyright holder nor the names of its
|
| 15 |
+
contributors may be used to endorse or promote products derived from
|
| 16 |
+
this software without specific prior written permission.
|
| 17 |
+
|
| 18 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 19 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 20 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
|
| 21 |
+
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
| 22 |
+
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
| 23 |
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
| 24 |
+
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
| 25 |
+
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
| 26 |
+
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
| 27 |
+
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
| 28 |
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
wemm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/RECORD
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MarkupSafe-3.0.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
MarkupSafe-3.0.2.dist-info/LICENSE.txt,sha256=SJqOEQhQntmKN7uYPhHg9-HTHwvY-Zp5yESOf_N9B-o,1475
|
| 3 |
+
MarkupSafe-3.0.2.dist-info/METADATA,sha256=aAwbZhSmXdfFuMM-rEHpeiHRkBOGESyVLJIuwzHP-nw,3975
|
| 4 |
+
MarkupSafe-3.0.2.dist-info/RECORD,,
|
| 5 |
+
MarkupSafe-3.0.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 6 |
+
MarkupSafe-3.0.2.dist-info/WHEEL,sha256=_kVlewavvOSnwZE_whBk3jlE_Ob-nL5GvlVcLkpXSD8,151
|
| 7 |
+
MarkupSafe-3.0.2.dist-info/top_level.txt,sha256=qy0Plje5IJuvsCBjejJyhDCjEAdcDLK_2agVcex8Z6U,11
|
| 8 |
+
markupsafe/__init__.py,sha256=sr-U6_27DfaSrj5jnHYxWN-pvhM27sjlDplMDPZKm7k,13214
|
| 9 |
+
markupsafe/__pycache__/__init__.cpython-310.pyc,,
|
| 10 |
+
markupsafe/__pycache__/_native.cpython-310.pyc,,
|
| 11 |
+
markupsafe/_native.py,sha256=hSLs8Jmz5aqayuengJJ3kdT5PwNpBWpKrmQSdipndC8,210
|
| 12 |
+
markupsafe/_speedups.c,sha256=O7XulmTo-epI6n2FtMVOrJXl8EAaIwD2iNYmBI5SEoQ,4149
|
| 13 |
+
markupsafe/_speedups.cpython-310-x86_64-linux-gnu.so,sha256=x4RoxWgyqAEokk-AZrWvrLDxLE-dm-zZSZYV_gOiLJA,34976
|
| 14 |
+
markupsafe/_speedups.pyi,sha256=ENd1bYe7gbBUf2ywyYWOGUpnXOHNJ-cgTNqetlW8h5k,41
|
| 15 |
+
markupsafe/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
wemm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/REQUESTED
ADDED
|
File without changes
|
wemm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
markupsafe
|
wemm/lib/python3.10/site-packages/_pytest/__pycache__/helpconfig.cpython-310.pyc
ADDED
|
Binary file (7.48 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/_pytest/_argcomplete.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Allow bash-completion for argparse with argcomplete if installed.
|
| 2 |
+
|
| 3 |
+
Needs argcomplete>=0.5.6 for python 3.2/3.3 (older versions fail
|
| 4 |
+
to find the magic string, so _ARGCOMPLETE env. var is never set, and
|
| 5 |
+
this does not need special code).
|
| 6 |
+
|
| 7 |
+
Function try_argcomplete(parser) should be called directly before
|
| 8 |
+
the call to ArgumentParser.parse_args().
|
| 9 |
+
|
| 10 |
+
The filescompleter is what you normally would use on the positional
|
| 11 |
+
arguments specification, in order to get "dirname/" after "dirn<TAB>"
|
| 12 |
+
instead of the default "dirname ":
|
| 13 |
+
|
| 14 |
+
optparser.add_argument(Config._file_or_dir, nargs='*').completer=filescompleter
|
| 15 |
+
|
| 16 |
+
Other, application specific, completers should go in the file
|
| 17 |
+
doing the add_argument calls as they need to be specified as .completer
|
| 18 |
+
attributes as well. (If argcomplete is not installed, the function the
|
| 19 |
+
attribute points to will not be used).
|
| 20 |
+
|
| 21 |
+
SPEEDUP
|
| 22 |
+
=======
|
| 23 |
+
|
| 24 |
+
The generic argcomplete script for bash-completion
|
| 25 |
+
(/etc/bash_completion.d/python-argcomplete.sh)
|
| 26 |
+
uses a python program to determine startup script generated by pip.
|
| 27 |
+
You can speed up completion somewhat by changing this script to include
|
| 28 |
+
# PYTHON_ARGCOMPLETE_OK
|
| 29 |
+
so the python-argcomplete-check-easy-install-script does not
|
| 30 |
+
need to be called to find the entry point of the code and see if that is
|
| 31 |
+
marked with PYTHON_ARGCOMPLETE_OK.
|
| 32 |
+
|
| 33 |
+
INSTALL/DEBUGGING
|
| 34 |
+
=================
|
| 35 |
+
|
| 36 |
+
To include this support in another application that has setup.py generated
|
| 37 |
+
scripts:
|
| 38 |
+
|
| 39 |
+
- Add the line:
|
| 40 |
+
# PYTHON_ARGCOMPLETE_OK
|
| 41 |
+
near the top of the main python entry point.
|
| 42 |
+
|
| 43 |
+
- Include in the file calling parse_args():
|
| 44 |
+
from _argcomplete import try_argcomplete, filescompleter
|
| 45 |
+
Call try_argcomplete just before parse_args(), and optionally add
|
| 46 |
+
filescompleter to the positional arguments' add_argument().
|
| 47 |
+
|
| 48 |
+
If things do not work right away:
|
| 49 |
+
|
| 50 |
+
- Switch on argcomplete debugging with (also helpful when doing custom
|
| 51 |
+
completers):
|
| 52 |
+
export _ARC_DEBUG=1
|
| 53 |
+
|
| 54 |
+
- Run:
|
| 55 |
+
python-argcomplete-check-easy-install-script $(which appname)
|
| 56 |
+
echo $?
|
| 57 |
+
will echo 0 if the magic line has been found, 1 if not.
|
| 58 |
+
|
| 59 |
+
- Sometimes it helps to find early on errors using:
|
| 60 |
+
_ARGCOMPLETE=1 _ARC_DEBUG=1 appname
|
| 61 |
+
which should throw a KeyError: 'COMPLINE' (which is properly set by the
|
| 62 |
+
global argcomplete script).
|
| 63 |
+
"""
|
| 64 |
+
import argparse
|
| 65 |
+
import os
|
| 66 |
+
import sys
|
| 67 |
+
from glob import glob
|
| 68 |
+
from typing import Any
|
| 69 |
+
from typing import List
|
| 70 |
+
from typing import Optional
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class FastFilesCompleter:
|
| 74 |
+
"""Fast file completer class."""
|
| 75 |
+
|
| 76 |
+
def __init__(self, directories: bool = True) -> None:
|
| 77 |
+
self.directories = directories
|
| 78 |
+
|
| 79 |
+
def __call__(self, prefix: str, **kwargs: Any) -> List[str]:
|
| 80 |
+
# Only called on non option completions.
|
| 81 |
+
if os.sep in prefix[1:]:
|
| 82 |
+
prefix_dir = len(os.path.dirname(prefix) + os.sep)
|
| 83 |
+
else:
|
| 84 |
+
prefix_dir = 0
|
| 85 |
+
completion = []
|
| 86 |
+
globbed = []
|
| 87 |
+
if "*" not in prefix and "?" not in prefix:
|
| 88 |
+
# We are on unix, otherwise no bash.
|
| 89 |
+
if not prefix or prefix[-1] == os.sep:
|
| 90 |
+
globbed.extend(glob(prefix + ".*"))
|
| 91 |
+
prefix += "*"
|
| 92 |
+
globbed.extend(glob(prefix))
|
| 93 |
+
for x in sorted(globbed):
|
| 94 |
+
if os.path.isdir(x):
|
| 95 |
+
x += "/"
|
| 96 |
+
# Append stripping the prefix (like bash, not like compgen).
|
| 97 |
+
completion.append(x[prefix_dir:])
|
| 98 |
+
return completion
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
if os.environ.get("_ARGCOMPLETE"):
|
| 102 |
+
try:
|
| 103 |
+
import argcomplete.completers
|
| 104 |
+
except ImportError:
|
| 105 |
+
sys.exit(-1)
|
| 106 |
+
filescompleter: Optional[FastFilesCompleter] = FastFilesCompleter()
|
| 107 |
+
|
| 108 |
+
def try_argcomplete(parser: argparse.ArgumentParser) -> None:
|
| 109 |
+
argcomplete.autocomplete(parser, always_complete_options=False)
|
| 110 |
+
|
| 111 |
+
else:
|
| 112 |
+
|
| 113 |
+
def try_argcomplete(parser: argparse.ArgumentParser) -> None:
|
| 114 |
+
pass
|
| 115 |
+
|
| 116 |
+
filescompleter = None
|
wemm/lib/python3.10/site-packages/_pytest/_code/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Python inspection/code generation API."""
|
| 2 |
+
from .code import Code
|
| 3 |
+
from .code import ExceptionInfo
|
| 4 |
+
from .code import filter_traceback
|
| 5 |
+
from .code import Frame
|
| 6 |
+
from .code import getfslineno
|
| 7 |
+
from .code import Traceback
|
| 8 |
+
from .code import TracebackEntry
|
| 9 |
+
from .source import getrawcode
|
| 10 |
+
from .source import Source
|
| 11 |
+
|
| 12 |
+
__all__ = [
|
| 13 |
+
"Code",
|
| 14 |
+
"ExceptionInfo",
|
| 15 |
+
"filter_traceback",
|
| 16 |
+
"Frame",
|
| 17 |
+
"getfslineno",
|
| 18 |
+
"getrawcode",
|
| 19 |
+
"Traceback",
|
| 20 |
+
"TracebackEntry",
|
| 21 |
+
"Source",
|
| 22 |
+
]
|
wemm/lib/python3.10/site-packages/_pytest/_code/__pycache__/code.cpython-310.pyc
ADDED
|
Binary file (39.5 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/_pytest/_code/__pycache__/source.cpython-310.pyc
ADDED
|
Binary file (7.14 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/_pytest/_io/wcwidth.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unicodedata
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
@lru_cache(100)
|
| 6 |
+
def wcwidth(c: str) -> int:
|
| 7 |
+
"""Determine how many columns are needed to display a character in a terminal.
|
| 8 |
+
|
| 9 |
+
Returns -1 if the character is not printable.
|
| 10 |
+
Returns 0, 1 or 2 for other characters.
|
| 11 |
+
"""
|
| 12 |
+
o = ord(c)
|
| 13 |
+
|
| 14 |
+
# ASCII fast path.
|
| 15 |
+
if 0x20 <= o < 0x07F:
|
| 16 |
+
return 1
|
| 17 |
+
|
| 18 |
+
# Some Cf/Zp/Zl characters which should be zero-width.
|
| 19 |
+
if (
|
| 20 |
+
o == 0x0000
|
| 21 |
+
or 0x200B <= o <= 0x200F
|
| 22 |
+
or 0x2028 <= o <= 0x202E
|
| 23 |
+
or 0x2060 <= o <= 0x2063
|
| 24 |
+
):
|
| 25 |
+
return 0
|
| 26 |
+
|
| 27 |
+
category = unicodedata.category(c)
|
| 28 |
+
|
| 29 |
+
# Control characters.
|
| 30 |
+
if category == "Cc":
|
| 31 |
+
return -1
|
| 32 |
+
|
| 33 |
+
# Combining characters with zero width.
|
| 34 |
+
if category in ("Me", "Mn"):
|
| 35 |
+
return 0
|
| 36 |
+
|
| 37 |
+
# Full/Wide east asian characters.
|
| 38 |
+
if unicodedata.east_asian_width(c) in ("F", "W"):
|
| 39 |
+
return 2
|
| 40 |
+
|
| 41 |
+
return 1
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def wcswidth(s: str) -> int:
|
| 45 |
+
"""Determine how many columns are needed to display a string in a terminal.
|
| 46 |
+
|
| 47 |
+
Returns -1 if the string contains non-printable characters.
|
| 48 |
+
"""
|
| 49 |
+
width = 0
|
| 50 |
+
for c in unicodedata.normalize("NFC", s):
|
| 51 |
+
wc = wcwidth(c)
|
| 52 |
+
if wc < 0:
|
| 53 |
+
return -1
|
| 54 |
+
width += wc
|
| 55 |
+
return width
|
wemm/lib/python3.10/site-packages/_pytest/_py/__pycache__/path.cpython-310.pyc
ADDED
|
Binary file (43.1 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/_pytest/_version.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# file generated by setuptools_scm
|
| 2 |
+
# don't change, don't track in version control
|
| 3 |
+
__version__ = version = '7.4.0'
|
| 4 |
+
__version_tuple__ = version_tuple = (7, 4, 0)
|
wemm/lib/python3.10/site-packages/_pytest/assertion/__init__.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Support for presenting detailed information in failing assertions."""
|
| 2 |
+
import sys
|
| 3 |
+
from typing import Any
|
| 4 |
+
from typing import Generator
|
| 5 |
+
from typing import List
|
| 6 |
+
from typing import Optional
|
| 7 |
+
from typing import TYPE_CHECKING
|
| 8 |
+
|
| 9 |
+
from _pytest.assertion import rewrite
|
| 10 |
+
from _pytest.assertion import truncate
|
| 11 |
+
from _pytest.assertion import util
|
| 12 |
+
from _pytest.assertion.rewrite import assertstate_key
|
| 13 |
+
from _pytest.config import Config
|
| 14 |
+
from _pytest.config import hookimpl
|
| 15 |
+
from _pytest.config.argparsing import Parser
|
| 16 |
+
from _pytest.nodes import Item
|
| 17 |
+
|
| 18 |
+
if TYPE_CHECKING:
|
| 19 |
+
from _pytest.main import Session
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def pytest_addoption(parser: Parser) -> None:
|
| 23 |
+
group = parser.getgroup("debugconfig")
|
| 24 |
+
group.addoption(
|
| 25 |
+
"--assert",
|
| 26 |
+
action="store",
|
| 27 |
+
dest="assertmode",
|
| 28 |
+
choices=("rewrite", "plain"),
|
| 29 |
+
default="rewrite",
|
| 30 |
+
metavar="MODE",
|
| 31 |
+
help=(
|
| 32 |
+
"Control assertion debugging tools.\n"
|
| 33 |
+
"'plain' performs no assertion debugging.\n"
|
| 34 |
+
"'rewrite' (the default) rewrites assert statements in test modules"
|
| 35 |
+
" on import to provide assert expression information."
|
| 36 |
+
),
|
| 37 |
+
)
|
| 38 |
+
parser.addini(
|
| 39 |
+
"enable_assertion_pass_hook",
|
| 40 |
+
type="bool",
|
| 41 |
+
default=False,
|
| 42 |
+
help="Enables the pytest_assertion_pass hook. "
|
| 43 |
+
"Make sure to delete any previously generated pyc cache files.",
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def register_assert_rewrite(*names: str) -> None:
|
| 48 |
+
"""Register one or more module names to be rewritten on import.
|
| 49 |
+
|
| 50 |
+
This function will make sure that this module or all modules inside
|
| 51 |
+
the package will get their assert statements rewritten.
|
| 52 |
+
Thus you should make sure to call this before the module is
|
| 53 |
+
actually imported, usually in your __init__.py if you are a plugin
|
| 54 |
+
using a package.
|
| 55 |
+
|
| 56 |
+
:param names: The module names to register.
|
| 57 |
+
"""
|
| 58 |
+
for name in names:
|
| 59 |
+
if not isinstance(name, str):
|
| 60 |
+
msg = "expected module names as *args, got {0} instead" # type: ignore[unreachable]
|
| 61 |
+
raise TypeError(msg.format(repr(names)))
|
| 62 |
+
for hook in sys.meta_path:
|
| 63 |
+
if isinstance(hook, rewrite.AssertionRewritingHook):
|
| 64 |
+
importhook = hook
|
| 65 |
+
break
|
| 66 |
+
else:
|
| 67 |
+
# TODO(typing): Add a protocol for mark_rewrite() and use it
|
| 68 |
+
# for importhook and for PytestPluginManager.rewrite_hook.
|
| 69 |
+
importhook = DummyRewriteHook() # type: ignore
|
| 70 |
+
importhook.mark_rewrite(*names)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class DummyRewriteHook:
|
| 74 |
+
"""A no-op import hook for when rewriting is disabled."""
|
| 75 |
+
|
| 76 |
+
def mark_rewrite(self, *names: str) -> None:
|
| 77 |
+
pass
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class AssertionState:
|
| 81 |
+
"""State for the assertion plugin."""
|
| 82 |
+
|
| 83 |
+
def __init__(self, config: Config, mode) -> None:
|
| 84 |
+
self.mode = mode
|
| 85 |
+
self.trace = config.trace.root.get("assertion")
|
| 86 |
+
self.hook: Optional[rewrite.AssertionRewritingHook] = None
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def install_importhook(config: Config) -> rewrite.AssertionRewritingHook:
|
| 90 |
+
"""Try to install the rewrite hook, raise SystemError if it fails."""
|
| 91 |
+
config.stash[assertstate_key] = AssertionState(config, "rewrite")
|
| 92 |
+
config.stash[assertstate_key].hook = hook = rewrite.AssertionRewritingHook(config)
|
| 93 |
+
sys.meta_path.insert(0, hook)
|
| 94 |
+
config.stash[assertstate_key].trace("installed rewrite import hook")
|
| 95 |
+
|
| 96 |
+
def undo() -> None:
|
| 97 |
+
hook = config.stash[assertstate_key].hook
|
| 98 |
+
if hook is not None and hook in sys.meta_path:
|
| 99 |
+
sys.meta_path.remove(hook)
|
| 100 |
+
|
| 101 |
+
config.add_cleanup(undo)
|
| 102 |
+
return hook
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def pytest_collection(session: "Session") -> None:
|
| 106 |
+
# This hook is only called when test modules are collected
|
| 107 |
+
# so for example not in the managing process of pytest-xdist
|
| 108 |
+
# (which does not collect test modules).
|
| 109 |
+
assertstate = session.config.stash.get(assertstate_key, None)
|
| 110 |
+
if assertstate:
|
| 111 |
+
if assertstate.hook is not None:
|
| 112 |
+
assertstate.hook.set_session(session)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@hookimpl(tryfirst=True, hookwrapper=True)
|
| 116 |
+
def pytest_runtest_protocol(item: Item) -> Generator[None, None, None]:
|
| 117 |
+
"""Setup the pytest_assertrepr_compare and pytest_assertion_pass hooks.
|
| 118 |
+
|
| 119 |
+
The rewrite module will use util._reprcompare if it exists to use custom
|
| 120 |
+
reporting via the pytest_assertrepr_compare hook. This sets up this custom
|
| 121 |
+
comparison for the test.
|
| 122 |
+
"""
|
| 123 |
+
|
| 124 |
+
ihook = item.ihook
|
| 125 |
+
|
| 126 |
+
def callbinrepr(op, left: object, right: object) -> Optional[str]:
|
| 127 |
+
"""Call the pytest_assertrepr_compare hook and prepare the result.
|
| 128 |
+
|
| 129 |
+
This uses the first result from the hook and then ensures the
|
| 130 |
+
following:
|
| 131 |
+
* Overly verbose explanations are truncated unless configured otherwise
|
| 132 |
+
(eg. if running in verbose mode).
|
| 133 |
+
* Embedded newlines are escaped to help util.format_explanation()
|
| 134 |
+
later.
|
| 135 |
+
* If the rewrite mode is used embedded %-characters are replaced
|
| 136 |
+
to protect later % formatting.
|
| 137 |
+
|
| 138 |
+
The result can be formatted by util.format_explanation() for
|
| 139 |
+
pretty printing.
|
| 140 |
+
"""
|
| 141 |
+
hook_result = ihook.pytest_assertrepr_compare(
|
| 142 |
+
config=item.config, op=op, left=left, right=right
|
| 143 |
+
)
|
| 144 |
+
for new_expl in hook_result:
|
| 145 |
+
if new_expl:
|
| 146 |
+
new_expl = truncate.truncate_if_required(new_expl, item)
|
| 147 |
+
new_expl = [line.replace("\n", "\\n") for line in new_expl]
|
| 148 |
+
res = "\n~".join(new_expl)
|
| 149 |
+
if item.config.getvalue("assertmode") == "rewrite":
|
| 150 |
+
res = res.replace("%", "%%")
|
| 151 |
+
return res
|
| 152 |
+
return None
|
| 153 |
+
|
| 154 |
+
saved_assert_hooks = util._reprcompare, util._assertion_pass
|
| 155 |
+
util._reprcompare = callbinrepr
|
| 156 |
+
util._config = item.config
|
| 157 |
+
|
| 158 |
+
if ihook.pytest_assertion_pass.get_hookimpls():
|
| 159 |
+
|
| 160 |
+
def call_assertion_pass_hook(lineno: int, orig: str, expl: str) -> None:
|
| 161 |
+
ihook.pytest_assertion_pass(item=item, lineno=lineno, orig=orig, expl=expl)
|
| 162 |
+
|
| 163 |
+
util._assertion_pass = call_assertion_pass_hook
|
| 164 |
+
|
| 165 |
+
yield
|
| 166 |
+
|
| 167 |
+
util._reprcompare, util._assertion_pass = saved_assert_hooks
|
| 168 |
+
util._config = None
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def pytest_sessionfinish(session: "Session") -> None:
|
| 172 |
+
assertstate = session.config.stash.get(assertstate_key, None)
|
| 173 |
+
if assertstate:
|
| 174 |
+
if assertstate.hook is not None:
|
| 175 |
+
assertstate.hook.set_session(None)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def pytest_assertrepr_compare(
|
| 179 |
+
config: Config, op: str, left: Any, right: Any
|
| 180 |
+
) -> Optional[List[str]]:
|
| 181 |
+
return util.assertrepr_compare(config=config, op=op, left=left, right=right)
|
wemm/lib/python3.10/site-packages/_pytest/assertion/__pycache__/rewrite.cpython-310.pyc
ADDED
|
Binary file (34.3 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/_pytest/assertion/rewrite.py
ADDED
|
@@ -0,0 +1,1185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 7 |
+
import importlib.util
|
| 8 |
+
import io
|
| 9 |
+
import itertools
|
| 10 |
+
import marshal
|
| 11 |
+
import os
|
| 12 |
+
import struct
|
| 13 |
+
import sys
|
| 14 |
+
import tokenize
|
| 15 |
+
import types
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from pathlib import PurePath
|
| 18 |
+
from typing import Callable
|
| 19 |
+
from typing import Dict
|
| 20 |
+
from typing import IO
|
| 21 |
+
from typing import Iterable
|
| 22 |
+
from typing import Iterator
|
| 23 |
+
from typing import List
|
| 24 |
+
from typing import Optional
|
| 25 |
+
from typing import Sequence
|
| 26 |
+
from typing import Set
|
| 27 |
+
from typing import Tuple
|
| 28 |
+
from typing import TYPE_CHECKING
|
| 29 |
+
from typing import Union
|
| 30 |
+
|
| 31 |
+
from _pytest._io.saferepr import DEFAULT_REPR_MAX_SIZE
|
| 32 |
+
from _pytest._io.saferepr import saferepr
|
| 33 |
+
from _pytest._version import version
|
| 34 |
+
from _pytest.assertion import util
|
| 35 |
+
from _pytest.assertion.util import ( # noqa: F401
|
| 36 |
+
format_explanation as _format_explanation,
|
| 37 |
+
)
|
| 38 |
+
from _pytest.config import Config
|
| 39 |
+
from _pytest.main import Session
|
| 40 |
+
from _pytest.pathlib import absolutepath
|
| 41 |
+
from _pytest.pathlib import fnmatch_ex
|
| 42 |
+
from _pytest.stash import StashKey
|
| 43 |
+
|
| 44 |
+
if TYPE_CHECKING:
|
| 45 |
+
from _pytest.assertion import AssertionState
|
| 46 |
+
|
| 47 |
+
if sys.version_info >= (3, 8):
|
| 48 |
+
namedExpr = ast.NamedExpr
|
| 49 |
+
astNameConstant = ast.Constant
|
| 50 |
+
astStr = ast.Constant
|
| 51 |
+
astNum = ast.Constant
|
| 52 |
+
else:
|
| 53 |
+
namedExpr = ast.Expr
|
| 54 |
+
astNameConstant = ast.NameConstant
|
| 55 |
+
astStr = ast.Str
|
| 56 |
+
astNum = ast.Num
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
assertstate_key = StashKey["AssertionState"]()
|
| 60 |
+
|
| 61 |
+
# pytest caches rewritten pycs in pycache dirs
|
| 62 |
+
PYTEST_TAG = f"{sys.implementation.cache_tag}-pytest-{version}"
|
| 63 |
+
PYC_EXT = ".py" + (__debug__ and "c" or "o")
|
| 64 |
+
PYC_TAIL = "." + PYTEST_TAG + PYC_EXT
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class AssertionRewritingHook(importlib.abc.MetaPathFinder, importlib.abc.Loader):
|
| 68 |
+
"""PEP302/PEP451 import hook which rewrites asserts."""
|
| 69 |
+
|
| 70 |
+
def __init__(self, config: Config) -> None:
|
| 71 |
+
self.config = config
|
| 72 |
+
try:
|
| 73 |
+
self.fnpats = config.getini("python_files")
|
| 74 |
+
except ValueError:
|
| 75 |
+
self.fnpats = ["test_*.py", "*_test.py"]
|
| 76 |
+
self.session: Optional[Session] = None
|
| 77 |
+
self._rewritten_names: Dict[str, Path] = {}
|
| 78 |
+
self._must_rewrite: Set[str] = set()
|
| 79 |
+
# flag to guard against trying to rewrite a pyc file while we are already writing another pyc file,
|
| 80 |
+
# which might result in infinite recursion (#3506)
|
| 81 |
+
self._writing_pyc = False
|
| 82 |
+
self._basenames_to_check_rewrite = {"conftest"}
|
| 83 |
+
self._marked_for_rewrite_cache: Dict[str, bool] = {}
|
| 84 |
+
self._session_paths_checked = False
|
| 85 |
+
|
| 86 |
+
def set_session(self, session: Optional[Session]) -> None:
|
| 87 |
+
self.session = session
|
| 88 |
+
self._session_paths_checked = False
|
| 89 |
+
|
| 90 |
+
# Indirection so we can mock calls to find_spec originated from the hook during testing
|
| 91 |
+
_find_spec = importlib.machinery.PathFinder.find_spec
|
| 92 |
+
|
| 93 |
+
def find_spec(
|
| 94 |
+
self,
|
| 95 |
+
name: str,
|
| 96 |
+
path: Optional[Sequence[Union[str, bytes]]] = None,
|
| 97 |
+
target: Optional[types.ModuleType] = None,
|
| 98 |
+
) -> Optional[importlib.machinery.ModuleSpec]:
|
| 99 |
+
if self._writing_pyc:
|
| 100 |
+
return None
|
| 101 |
+
state = self.config.stash[assertstate_key]
|
| 102 |
+
if self._early_rewrite_bailout(name, state):
|
| 103 |
+
return None
|
| 104 |
+
state.trace("find_module called for: %s" % name)
|
| 105 |
+
|
| 106 |
+
# Type ignored because mypy is confused about the `self` binding here.
|
| 107 |
+
spec = self._find_spec(name, path) # type: ignore
|
| 108 |
+
if (
|
| 109 |
+
# the import machinery could not find a file to import
|
| 110 |
+
spec is None
|
| 111 |
+
# this is a namespace package (without `__init__.py`)
|
| 112 |
+
# there's nothing to rewrite there
|
| 113 |
+
or spec.origin is None
|
| 114 |
+
# we can only rewrite source files
|
| 115 |
+
or not isinstance(spec.loader, importlib.machinery.SourceFileLoader)
|
| 116 |
+
# if the file doesn't exist, we can't rewrite it
|
| 117 |
+
or not os.path.exists(spec.origin)
|
| 118 |
+
):
|
| 119 |
+
return None
|
| 120 |
+
else:
|
| 121 |
+
fn = spec.origin
|
| 122 |
+
|
| 123 |
+
if not self._should_rewrite(name, fn, state):
|
| 124 |
+
return None
|
| 125 |
+
|
| 126 |
+
return importlib.util.spec_from_file_location(
|
| 127 |
+
name,
|
| 128 |
+
fn,
|
| 129 |
+
loader=self,
|
| 130 |
+
submodule_search_locations=spec.submodule_search_locations,
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
def create_module(
|
| 134 |
+
self, spec: importlib.machinery.ModuleSpec
|
| 135 |
+
) -> Optional[types.ModuleType]:
|
| 136 |
+
return None # default behaviour is fine
|
| 137 |
+
|
| 138 |
+
def exec_module(self, module: types.ModuleType) -> None:
|
| 139 |
+
assert module.__spec__ is not None
|
| 140 |
+
assert module.__spec__.origin is not None
|
| 141 |
+
fn = Path(module.__spec__.origin)
|
| 142 |
+
state = self.config.stash[assertstate_key]
|
| 143 |
+
|
| 144 |
+
self._rewritten_names[module.__name__] = fn
|
| 145 |
+
|
| 146 |
+
# The requested module looks like a test file, so rewrite it. This is
|
| 147 |
+
# the most magical part of the process: load the source, rewrite the
|
| 148 |
+
# asserts, and load the rewritten source. We also cache the rewritten
|
| 149 |
+
# module code in a special pyc. We must be aware of the possibility of
|
| 150 |
+
# concurrent pytest processes rewriting and loading pycs. To avoid
|
| 151 |
+
# tricky race conditions, we maintain the following invariant: The
|
| 152 |
+
# cached pyc is always a complete, valid pyc. Operations on it must be
|
| 153 |
+
# atomic. POSIX's atomic rename comes in handy.
|
| 154 |
+
write = not sys.dont_write_bytecode
|
| 155 |
+
cache_dir = get_cache_dir(fn)
|
| 156 |
+
if write:
|
| 157 |
+
ok = try_makedirs(cache_dir)
|
| 158 |
+
if not ok:
|
| 159 |
+
write = False
|
| 160 |
+
state.trace(f"read only directory: {cache_dir}")
|
| 161 |
+
|
| 162 |
+
cache_name = fn.name[:-3] + PYC_TAIL
|
| 163 |
+
pyc = cache_dir / cache_name
|
| 164 |
+
# Notice that even if we're in a read-only directory, I'm going
|
| 165 |
+
# to check for a cached pyc. This may not be optimal...
|
| 166 |
+
co = _read_pyc(fn, pyc, state.trace)
|
| 167 |
+
if co is None:
|
| 168 |
+
state.trace(f"rewriting {fn!r}")
|
| 169 |
+
source_stat, co = _rewrite_test(fn, self.config)
|
| 170 |
+
if write:
|
| 171 |
+
self._writing_pyc = True
|
| 172 |
+
try:
|
| 173 |
+
_write_pyc(state, co, source_stat, pyc)
|
| 174 |
+
finally:
|
| 175 |
+
self._writing_pyc = False
|
| 176 |
+
else:
|
| 177 |
+
state.trace(f"found cached rewritten pyc for {fn}")
|
| 178 |
+
exec(co, module.__dict__)
|
| 179 |
+
|
| 180 |
+
def _early_rewrite_bailout(self, name: str, state: "AssertionState") -> bool:
|
| 181 |
+
"""A fast way to get out of rewriting modules.
|
| 182 |
+
|
| 183 |
+
Profiling has shown that the call to PathFinder.find_spec (inside of
|
| 184 |
+
the find_spec from this class) is a major slowdown, so, this method
|
| 185 |
+
tries to filter what we're sure won't be rewritten before getting to
|
| 186 |
+
it.
|
| 187 |
+
"""
|
| 188 |
+
if self.session is not None and not self._session_paths_checked:
|
| 189 |
+
self._session_paths_checked = True
|
| 190 |
+
for initial_path in self.session._initialpaths:
|
| 191 |
+
# Make something as c:/projects/my_project/path.py ->
|
| 192 |
+
# ['c:', 'projects', 'my_project', 'path.py']
|
| 193 |
+
parts = str(initial_path).split(os.sep)
|
| 194 |
+
# add 'path' to basenames to be checked.
|
| 195 |
+
self._basenames_to_check_rewrite.add(os.path.splitext(parts[-1])[0])
|
| 196 |
+
|
| 197 |
+
# Note: conftest already by default in _basenames_to_check_rewrite.
|
| 198 |
+
parts = name.split(".")
|
| 199 |
+
if parts[-1] in self._basenames_to_check_rewrite:
|
| 200 |
+
return False
|
| 201 |
+
|
| 202 |
+
# For matching the name it must be as if it was a filename.
|
| 203 |
+
path = PurePath(*parts).with_suffix(".py")
|
| 204 |
+
|
| 205 |
+
for pat in self.fnpats:
|
| 206 |
+
# if the pattern contains subdirectories ("tests/**.py" for example) we can't bail out based
|
| 207 |
+
# on the name alone because we need to match against the full path
|
| 208 |
+
if os.path.dirname(pat):
|
| 209 |
+
return False
|
| 210 |
+
if fnmatch_ex(pat, path):
|
| 211 |
+
return False
|
| 212 |
+
|
| 213 |
+
if self._is_marked_for_rewrite(name, state):
|
| 214 |
+
return False
|
| 215 |
+
|
| 216 |
+
state.trace(f"early skip of rewriting module: {name}")
|
| 217 |
+
return True
|
| 218 |
+
|
| 219 |
+
def _should_rewrite(self, name: str, fn: str, state: "AssertionState") -> bool:
|
| 220 |
+
# always rewrite conftest files
|
| 221 |
+
if os.path.basename(fn) == "conftest.py":
|
| 222 |
+
state.trace(f"rewriting conftest file: {fn!r}")
|
| 223 |
+
return True
|
| 224 |
+
|
| 225 |
+
if self.session is not None:
|
| 226 |
+
if self.session.isinitpath(absolutepath(fn)):
|
| 227 |
+
state.trace(f"matched test file (was specified on cmdline): {fn!r}")
|
| 228 |
+
return True
|
| 229 |
+
|
| 230 |
+
# modules not passed explicitly on the command line are only
|
| 231 |
+
# rewritten if they match the naming convention for test files
|
| 232 |
+
fn_path = PurePath(fn)
|
| 233 |
+
for pat in self.fnpats:
|
| 234 |
+
if fnmatch_ex(pat, fn_path):
|
| 235 |
+
state.trace(f"matched test file {fn!r}")
|
| 236 |
+
return True
|
| 237 |
+
|
| 238 |
+
return self._is_marked_for_rewrite(name, state)
|
| 239 |
+
|
| 240 |
+
def _is_marked_for_rewrite(self, name: str, state: "AssertionState") -> bool:
|
| 241 |
+
try:
|
| 242 |
+
return self._marked_for_rewrite_cache[name]
|
| 243 |
+
except KeyError:
|
| 244 |
+
for marked in self._must_rewrite:
|
| 245 |
+
if name == marked or name.startswith(marked + "."):
|
| 246 |
+
state.trace(f"matched marked file {name!r} (from {marked!r})")
|
| 247 |
+
self._marked_for_rewrite_cache[name] = True
|
| 248 |
+
return True
|
| 249 |
+
|
| 250 |
+
self._marked_for_rewrite_cache[name] = False
|
| 251 |
+
return False
|
| 252 |
+
|
| 253 |
+
def mark_rewrite(self, *names: str) -> None:
|
| 254 |
+
"""Mark import names as needing to be rewritten.
|
| 255 |
+
|
| 256 |
+
The named module or package as well as any nested modules will
|
| 257 |
+
be rewritten on import.
|
| 258 |
+
"""
|
| 259 |
+
already_imported = (
|
| 260 |
+
set(names).intersection(sys.modules).difference(self._rewritten_names)
|
| 261 |
+
)
|
| 262 |
+
for name in already_imported:
|
| 263 |
+
mod = sys.modules[name]
|
| 264 |
+
if not AssertionRewriter.is_rewrite_disabled(
|
| 265 |
+
mod.__doc__ or ""
|
| 266 |
+
) and not isinstance(mod.__loader__, type(self)):
|
| 267 |
+
self._warn_already_imported(name)
|
| 268 |
+
self._must_rewrite.update(names)
|
| 269 |
+
self._marked_for_rewrite_cache.clear()
|
| 270 |
+
|
| 271 |
+
def _warn_already_imported(self, name: str) -> None:
|
| 272 |
+
from _pytest.warning_types import PytestAssertRewriteWarning
|
| 273 |
+
|
| 274 |
+
self.config.issue_config_time_warning(
|
| 275 |
+
PytestAssertRewriteWarning(
|
| 276 |
+
"Module already imported so cannot be rewritten: %s" % name
|
| 277 |
+
),
|
| 278 |
+
stacklevel=5,
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
def get_data(self, pathname: Union[str, bytes]) -> bytes:
|
| 282 |
+
"""Optional PEP302 get_data API."""
|
| 283 |
+
with open(pathname, "rb") as f:
|
| 284 |
+
return f.read()
|
| 285 |
+
|
| 286 |
+
if sys.version_info >= (3, 10):
|
| 287 |
+
if sys.version_info >= (3, 12):
|
| 288 |
+
from importlib.resources.abc import TraversableResources
|
| 289 |
+
else:
|
| 290 |
+
from importlib.abc import TraversableResources
|
| 291 |
+
|
| 292 |
+
def get_resource_reader(self, name: str) -> TraversableResources: # type: ignore
|
| 293 |
+
if sys.version_info < (3, 11):
|
| 294 |
+
from importlib.readers import FileReader
|
| 295 |
+
else:
|
| 296 |
+
from importlib.resources.readers import FileReader
|
| 297 |
+
|
| 298 |
+
return FileReader( # type:ignore[no-any-return]
|
| 299 |
+
types.SimpleNamespace(path=self._rewritten_names[name])
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def _write_pyc_fp(
|
| 304 |
+
fp: IO[bytes], source_stat: os.stat_result, co: types.CodeType
|
| 305 |
+
) -> None:
|
| 306 |
+
# Technically, we don't have to have the same pyc format as
|
| 307 |
+
# (C)Python, since these "pycs" should never be seen by builtin
|
| 308 |
+
# import. However, there's little reason to deviate.
|
| 309 |
+
fp.write(importlib.util.MAGIC_NUMBER)
|
| 310 |
+
# https://www.python.org/dev/peps/pep-0552/
|
| 311 |
+
flags = b"\x00\x00\x00\x00"
|
| 312 |
+
fp.write(flags)
|
| 313 |
+
# as of now, bytecode header expects 32-bit numbers for size and mtime (#4903)
|
| 314 |
+
mtime = int(source_stat.st_mtime) & 0xFFFFFFFF
|
| 315 |
+
size = source_stat.st_size & 0xFFFFFFFF
|
| 316 |
+
# "<LL" stands for 2 unsigned longs, little-endian.
|
| 317 |
+
fp.write(struct.pack("<LL", mtime, size))
|
| 318 |
+
fp.write(marshal.dumps(co))
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def _write_pyc(
|
| 322 |
+
state: "AssertionState",
|
| 323 |
+
co: types.CodeType,
|
| 324 |
+
source_stat: os.stat_result,
|
| 325 |
+
pyc: Path,
|
| 326 |
+
) -> bool:
|
| 327 |
+
proc_pyc = f"{pyc}.{os.getpid()}"
|
| 328 |
+
try:
|
| 329 |
+
with open(proc_pyc, "wb") as fp:
|
| 330 |
+
_write_pyc_fp(fp, source_stat, co)
|
| 331 |
+
except OSError as e:
|
| 332 |
+
state.trace(f"error writing pyc file at {proc_pyc}: errno={e.errno}")
|
| 333 |
+
return False
|
| 334 |
+
|
| 335 |
+
try:
|
| 336 |
+
os.replace(proc_pyc, pyc)
|
| 337 |
+
except OSError as e:
|
| 338 |
+
state.trace(f"error writing pyc file at {pyc}: {e}")
|
| 339 |
+
# we ignore any failure to write the cache file
|
| 340 |
+
# there are many reasons, permission-denied, pycache dir being a
|
| 341 |
+
# file etc.
|
| 342 |
+
return False
|
| 343 |
+
return True
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def _rewrite_test(fn: Path, config: Config) -> Tuple[os.stat_result, types.CodeType]:
|
| 347 |
+
"""Read and rewrite *fn* and return the code object."""
|
| 348 |
+
stat = os.stat(fn)
|
| 349 |
+
source = fn.read_bytes()
|
| 350 |
+
strfn = str(fn)
|
| 351 |
+
tree = ast.parse(source, filename=strfn)
|
| 352 |
+
rewrite_asserts(tree, source, strfn, config)
|
| 353 |
+
co = compile(tree, strfn, "exec", dont_inherit=True)
|
| 354 |
+
return stat, co
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def _read_pyc(
|
| 358 |
+
source: Path, pyc: Path, trace: Callable[[str], None] = lambda x: None
|
| 359 |
+
) -> Optional[types.CodeType]:
|
| 360 |
+
"""Possibly read a pytest pyc containing rewritten code.
|
| 361 |
+
|
| 362 |
+
Return rewritten code if successful or None if not.
|
| 363 |
+
"""
|
| 364 |
+
try:
|
| 365 |
+
fp = open(pyc, "rb")
|
| 366 |
+
except OSError:
|
| 367 |
+
return None
|
| 368 |
+
with fp:
|
| 369 |
+
try:
|
| 370 |
+
stat_result = os.stat(source)
|
| 371 |
+
mtime = int(stat_result.st_mtime)
|
| 372 |
+
size = stat_result.st_size
|
| 373 |
+
data = fp.read(16)
|
| 374 |
+
except OSError as e:
|
| 375 |
+
trace(f"_read_pyc({source}): OSError {e}")
|
| 376 |
+
return None
|
| 377 |
+
# Check for invalid or out of date pyc file.
|
| 378 |
+
if len(data) != (16):
|
| 379 |
+
trace("_read_pyc(%s): invalid pyc (too short)" % source)
|
| 380 |
+
return None
|
| 381 |
+
if data[:4] != importlib.util.MAGIC_NUMBER:
|
| 382 |
+
trace("_read_pyc(%s): invalid pyc (bad magic number)" % source)
|
| 383 |
+
return None
|
| 384 |
+
if data[4:8] != b"\x00\x00\x00\x00":
|
| 385 |
+
trace("_read_pyc(%s): invalid pyc (unsupported flags)" % source)
|
| 386 |
+
return None
|
| 387 |
+
mtime_data = data[8:12]
|
| 388 |
+
if int.from_bytes(mtime_data, "little") != mtime & 0xFFFFFFFF:
|
| 389 |
+
trace("_read_pyc(%s): out of date" % source)
|
| 390 |
+
return None
|
| 391 |
+
size_data = data[12:16]
|
| 392 |
+
if int.from_bytes(size_data, "little") != size & 0xFFFFFFFF:
|
| 393 |
+
trace("_read_pyc(%s): invalid pyc (incorrect size)" % source)
|
| 394 |
+
return None
|
| 395 |
+
try:
|
| 396 |
+
co = marshal.load(fp)
|
| 397 |
+
except Exception as e:
|
| 398 |
+
trace(f"_read_pyc({source}): marshal.load error {e}")
|
| 399 |
+
return None
|
| 400 |
+
if not isinstance(co, types.CodeType):
|
| 401 |
+
trace("_read_pyc(%s): not a code object" % source)
|
| 402 |
+
return None
|
| 403 |
+
return co
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def rewrite_asserts(
|
| 407 |
+
mod: ast.Module,
|
| 408 |
+
source: bytes,
|
| 409 |
+
module_path: Optional[str] = None,
|
| 410 |
+
config: Optional[Config] = None,
|
| 411 |
+
) -> None:
|
| 412 |
+
"""Rewrite the assert statements in mod."""
|
| 413 |
+
AssertionRewriter(module_path, config, source).run(mod)
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def _saferepr(obj: object) -> str:
|
| 417 |
+
r"""Get a safe repr of an object for assertion error messages.
|
| 418 |
+
|
| 419 |
+
The assertion formatting (util.format_explanation()) requires
|
| 420 |
+
newlines to be escaped since they are a special character for it.
|
| 421 |
+
Normally assertion.util.format_explanation() does this but for a
|
| 422 |
+
custom repr it is possible to contain one of the special escape
|
| 423 |
+
sequences, especially '\n{' and '\n}' are likely to be present in
|
| 424 |
+
JSON reprs.
|
| 425 |
+
"""
|
| 426 |
+
maxsize = _get_maxsize_for_saferepr(util._config)
|
| 427 |
+
return saferepr(obj, maxsize=maxsize).replace("\n", "\\n")
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def _get_maxsize_for_saferepr(config: Optional[Config]) -> Optional[int]:
|
| 431 |
+
"""Get `maxsize` configuration for saferepr based on the given config object."""
|
| 432 |
+
verbosity = config.getoption("verbose") if config is not None else 0
|
| 433 |
+
if verbosity >= 2:
|
| 434 |
+
return None
|
| 435 |
+
if verbosity >= 1:
|
| 436 |
+
return DEFAULT_REPR_MAX_SIZE * 10
|
| 437 |
+
return DEFAULT_REPR_MAX_SIZE
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def _format_assertmsg(obj: object) -> str:
|
| 441 |
+
r"""Format the custom assertion message given.
|
| 442 |
+
|
| 443 |
+
For strings this simply replaces newlines with '\n~' so that
|
| 444 |
+
util.format_explanation() will preserve them instead of escaping
|
| 445 |
+
newlines. For other objects saferepr() is used first.
|
| 446 |
+
"""
|
| 447 |
+
# reprlib appears to have a bug which means that if a string
|
| 448 |
+
# contains a newline it gets escaped, however if an object has a
|
| 449 |
+
# .__repr__() which contains newlines it does not get escaped.
|
| 450 |
+
# However in either case we want to preserve the newline.
|
| 451 |
+
replaces = [("\n", "\n~"), ("%", "%%")]
|
| 452 |
+
if not isinstance(obj, str):
|
| 453 |
+
obj = saferepr(obj)
|
| 454 |
+
replaces.append(("\\n", "\n~"))
|
| 455 |
+
|
| 456 |
+
for r1, r2 in replaces:
|
| 457 |
+
obj = obj.replace(r1, r2)
|
| 458 |
+
|
| 459 |
+
return obj
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def _should_repr_global_name(obj: object) -> bool:
|
| 463 |
+
if callable(obj):
|
| 464 |
+
return False
|
| 465 |
+
|
| 466 |
+
try:
|
| 467 |
+
return not hasattr(obj, "__name__")
|
| 468 |
+
except Exception:
|
| 469 |
+
return True
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def _format_boolop(explanations: Iterable[str], is_or: bool) -> str:
|
| 473 |
+
explanation = "(" + (is_or and " or " or " and ").join(explanations) + ")"
|
| 474 |
+
return explanation.replace("%", "%%")
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def _call_reprcompare(
|
| 478 |
+
ops: Sequence[str],
|
| 479 |
+
results: Sequence[bool],
|
| 480 |
+
expls: Sequence[str],
|
| 481 |
+
each_obj: Sequence[object],
|
| 482 |
+
) -> str:
|
| 483 |
+
for i, res, expl in zip(range(len(ops)), results, expls):
|
| 484 |
+
try:
|
| 485 |
+
done = not res
|
| 486 |
+
except Exception:
|
| 487 |
+
done = True
|
| 488 |
+
if done:
|
| 489 |
+
break
|
| 490 |
+
if util._reprcompare is not None:
|
| 491 |
+
custom = util._reprcompare(ops[i], each_obj[i], each_obj[i + 1])
|
| 492 |
+
if custom is not None:
|
| 493 |
+
return custom
|
| 494 |
+
return expl
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def _call_assertion_pass(lineno: int, orig: str, expl: str) -> None:
|
| 498 |
+
if util._assertion_pass is not None:
|
| 499 |
+
util._assertion_pass(lineno, orig, expl)
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def _check_if_assertion_pass_impl() -> bool:
|
| 503 |
+
"""Check if any plugins implement the pytest_assertion_pass hook
|
| 504 |
+
in order not to generate explanation unnecessarily (might be expensive)."""
|
| 505 |
+
return True if util._assertion_pass else False
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
UNARY_MAP = {ast.Not: "not %s", ast.Invert: "~%s", ast.USub: "-%s", ast.UAdd: "+%s"}
|
| 509 |
+
|
| 510 |
+
BINOP_MAP = {
|
| 511 |
+
ast.BitOr: "|",
|
| 512 |
+
ast.BitXor: "^",
|
| 513 |
+
ast.BitAnd: "&",
|
| 514 |
+
ast.LShift: "<<",
|
| 515 |
+
ast.RShift: ">>",
|
| 516 |
+
ast.Add: "+",
|
| 517 |
+
ast.Sub: "-",
|
| 518 |
+
ast.Mult: "*",
|
| 519 |
+
ast.Div: "/",
|
| 520 |
+
ast.FloorDiv: "//",
|
| 521 |
+
ast.Mod: "%%", # escaped for string formatting
|
| 522 |
+
ast.Eq: "==",
|
| 523 |
+
ast.NotEq: "!=",
|
| 524 |
+
ast.Lt: "<",
|
| 525 |
+
ast.LtE: "<=",
|
| 526 |
+
ast.Gt: ">",
|
| 527 |
+
ast.GtE: ">=",
|
| 528 |
+
ast.Pow: "**",
|
| 529 |
+
ast.Is: "is",
|
| 530 |
+
ast.IsNot: "is not",
|
| 531 |
+
ast.In: "in",
|
| 532 |
+
ast.NotIn: "not in",
|
| 533 |
+
ast.MatMult: "@",
|
| 534 |
+
}
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def traverse_node(node: ast.AST) -> Iterator[ast.AST]:
|
| 538 |
+
"""Recursively yield node and all its children in depth-first order."""
|
| 539 |
+
yield node
|
| 540 |
+
for child in ast.iter_child_nodes(node):
|
| 541 |
+
yield from traverse_node(child)
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
@functools.lru_cache(maxsize=1)
|
| 545 |
+
def _get_assertion_exprs(src: bytes) -> Dict[int, str]:
|
| 546 |
+
"""Return a mapping from {lineno: "assertion test expression"}."""
|
| 547 |
+
ret: Dict[int, str] = {}
|
| 548 |
+
|
| 549 |
+
depth = 0
|
| 550 |
+
lines: List[str] = []
|
| 551 |
+
assert_lineno: Optional[int] = None
|
| 552 |
+
seen_lines: Set[int] = set()
|
| 553 |
+
|
| 554 |
+
def _write_and_reset() -> None:
|
| 555 |
+
nonlocal depth, lines, assert_lineno, seen_lines
|
| 556 |
+
assert assert_lineno is not None
|
| 557 |
+
ret[assert_lineno] = "".join(lines).rstrip().rstrip("\\")
|
| 558 |
+
depth = 0
|
| 559 |
+
lines = []
|
| 560 |
+
assert_lineno = None
|
| 561 |
+
seen_lines = set()
|
| 562 |
+
|
| 563 |
+
tokens = tokenize.tokenize(io.BytesIO(src).readline)
|
| 564 |
+
for tp, source, (lineno, offset), _, line in tokens:
|
| 565 |
+
if tp == tokenize.NAME and source == "assert":
|
| 566 |
+
assert_lineno = lineno
|
| 567 |
+
elif assert_lineno is not None:
|
| 568 |
+
# keep track of depth for the assert-message `,` lookup
|
| 569 |
+
if tp == tokenize.OP and source in "([{":
|
| 570 |
+
depth += 1
|
| 571 |
+
elif tp == tokenize.OP and source in ")]}":
|
| 572 |
+
depth -= 1
|
| 573 |
+
|
| 574 |
+
if not lines:
|
| 575 |
+
lines.append(line[offset:])
|
| 576 |
+
seen_lines.add(lineno)
|
| 577 |
+
# a non-nested comma separates the expression from the message
|
| 578 |
+
elif depth == 0 and tp == tokenize.OP and source == ",":
|
| 579 |
+
# one line assert with message
|
| 580 |
+
if lineno in seen_lines and len(lines) == 1:
|
| 581 |
+
offset_in_trimmed = offset + len(lines[-1]) - len(line)
|
| 582 |
+
lines[-1] = lines[-1][:offset_in_trimmed]
|
| 583 |
+
# multi-line assert with message
|
| 584 |
+
elif lineno in seen_lines:
|
| 585 |
+
lines[-1] = lines[-1][:offset]
|
| 586 |
+
# multi line assert with escapd newline before message
|
| 587 |
+
else:
|
| 588 |
+
lines.append(line[:offset])
|
| 589 |
+
_write_and_reset()
|
| 590 |
+
elif tp in {tokenize.NEWLINE, tokenize.ENDMARKER}:
|
| 591 |
+
_write_and_reset()
|
| 592 |
+
elif lines and lineno not in seen_lines:
|
| 593 |
+
lines.append(line)
|
| 594 |
+
seen_lines.add(lineno)
|
| 595 |
+
|
| 596 |
+
return ret
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
class AssertionRewriter(ast.NodeVisitor):
|
| 600 |
+
"""Assertion rewriting implementation.
|
| 601 |
+
|
| 602 |
+
The main entrypoint is to call .run() with an ast.Module instance,
|
| 603 |
+
this will then find all the assert statements and rewrite them to
|
| 604 |
+
provide intermediate values and a detailed assertion error. See
|
| 605 |
+
http://pybites.blogspot.be/2011/07/behind-scenes-of-pytests-new-assertion.html
|
| 606 |
+
for an overview of how this works.
|
| 607 |
+
|
| 608 |
+
The entry point here is .run() which will iterate over all the
|
| 609 |
+
statements in an ast.Module and for each ast.Assert statement it
|
| 610 |
+
finds call .visit() with it. Then .visit_Assert() takes over and
|
| 611 |
+
is responsible for creating new ast statements to replace the
|
| 612 |
+
original assert statement: it rewrites the test of an assertion
|
| 613 |
+
to provide intermediate values and replace it with an if statement
|
| 614 |
+
which raises an assertion error with a detailed explanation in
|
| 615 |
+
case the expression is false and calls pytest_assertion_pass hook
|
| 616 |
+
if expression is true.
|
| 617 |
+
|
| 618 |
+
For this .visit_Assert() uses the visitor pattern to visit all the
|
| 619 |
+
AST nodes of the ast.Assert.test field, each visit call returning
|
| 620 |
+
an AST node and the corresponding explanation string. During this
|
| 621 |
+
state is kept in several instance attributes:
|
| 622 |
+
|
| 623 |
+
:statements: All the AST statements which will replace the assert
|
| 624 |
+
statement.
|
| 625 |
+
|
| 626 |
+
:variables: This is populated by .variable() with each variable
|
| 627 |
+
used by the statements so that they can all be set to None at
|
| 628 |
+
the end of the statements.
|
| 629 |
+
|
| 630 |
+
:variable_counter: Counter to create new unique variables needed
|
| 631 |
+
by statements. Variables are created using .variable() and
|
| 632 |
+
have the form of "@py_assert0".
|
| 633 |
+
|
| 634 |
+
:expl_stmts: The AST statements which will be executed to get
|
| 635 |
+
data from the assertion. This is the code which will construct
|
| 636 |
+
the detailed assertion message that is used in the AssertionError
|
| 637 |
+
or for the pytest_assertion_pass hook.
|
| 638 |
+
|
| 639 |
+
:explanation_specifiers: A dict filled by .explanation_param()
|
| 640 |
+
with %-formatting placeholders and their corresponding
|
| 641 |
+
expressions to use in the building of an assertion message.
|
| 642 |
+
This is used by .pop_format_context() to build a message.
|
| 643 |
+
|
| 644 |
+
:stack: A stack of the explanation_specifiers dicts maintained by
|
| 645 |
+
.push_format_context() and .pop_format_context() which allows
|
| 646 |
+
to build another %-formatted string while already building one.
|
| 647 |
+
|
| 648 |
+
:variables_overwrite: A dict filled with references to variables
|
| 649 |
+
that change value within an assert. This happens when a variable is
|
| 650 |
+
reassigned with the walrus operator
|
| 651 |
+
|
| 652 |
+
This state, except the variables_overwrite, is reset on every new assert
|
| 653 |
+
statement visited and used by the other visitors.
|
| 654 |
+
"""
|
| 655 |
+
|
| 656 |
+
def __init__(
|
| 657 |
+
self, module_path: Optional[str], config: Optional[Config], source: bytes
|
| 658 |
+
) -> None:
|
| 659 |
+
super().__init__()
|
| 660 |
+
self.module_path = module_path
|
| 661 |
+
self.config = config
|
| 662 |
+
if config is not None:
|
| 663 |
+
self.enable_assertion_pass_hook = config.getini(
|
| 664 |
+
"enable_assertion_pass_hook"
|
| 665 |
+
)
|
| 666 |
+
else:
|
| 667 |
+
self.enable_assertion_pass_hook = False
|
| 668 |
+
self.source = source
|
| 669 |
+
self.variables_overwrite: Dict[str, str] = {}
|
| 670 |
+
|
| 671 |
+
def run(self, mod: ast.Module) -> None:
|
| 672 |
+
"""Find all assert statements in *mod* and rewrite them."""
|
| 673 |
+
if not mod.body:
|
| 674 |
+
# Nothing to do.
|
| 675 |
+
return
|
| 676 |
+
|
| 677 |
+
# We'll insert some special imports at the top of the module, but after any
|
| 678 |
+
# docstrings and __future__ imports, so first figure out where that is.
|
| 679 |
+
doc = getattr(mod, "docstring", None)
|
| 680 |
+
expect_docstring = doc is None
|
| 681 |
+
if doc is not None and self.is_rewrite_disabled(doc):
|
| 682 |
+
return
|
| 683 |
+
pos = 0
|
| 684 |
+
item = None
|
| 685 |
+
for item in mod.body:
|
| 686 |
+
if (
|
| 687 |
+
expect_docstring
|
| 688 |
+
and isinstance(item, ast.Expr)
|
| 689 |
+
and isinstance(item.value, astStr)
|
| 690 |
+
):
|
| 691 |
+
if sys.version_info >= (3, 8):
|
| 692 |
+
doc = item.value.value
|
| 693 |
+
else:
|
| 694 |
+
doc = item.value.s
|
| 695 |
+
if self.is_rewrite_disabled(doc):
|
| 696 |
+
return
|
| 697 |
+
expect_docstring = False
|
| 698 |
+
elif (
|
| 699 |
+
isinstance(item, ast.ImportFrom)
|
| 700 |
+
and item.level == 0
|
| 701 |
+
and item.module == "__future__"
|
| 702 |
+
):
|
| 703 |
+
pass
|
| 704 |
+
else:
|
| 705 |
+
break
|
| 706 |
+
pos += 1
|
| 707 |
+
# Special case: for a decorated function, set the lineno to that of the
|
| 708 |
+
# first decorator, not the `def`. Issue #4984.
|
| 709 |
+
if isinstance(item, ast.FunctionDef) and item.decorator_list:
|
| 710 |
+
lineno = item.decorator_list[0].lineno
|
| 711 |
+
else:
|
| 712 |
+
lineno = item.lineno
|
| 713 |
+
# Now actually insert the special imports.
|
| 714 |
+
if sys.version_info >= (3, 10):
|
| 715 |
+
aliases = [
|
| 716 |
+
ast.alias("builtins", "@py_builtins", lineno=lineno, col_offset=0),
|
| 717 |
+
ast.alias(
|
| 718 |
+
"_pytest.assertion.rewrite",
|
| 719 |
+
"@pytest_ar",
|
| 720 |
+
lineno=lineno,
|
| 721 |
+
col_offset=0,
|
| 722 |
+
),
|
| 723 |
+
]
|
| 724 |
+
else:
|
| 725 |
+
aliases = [
|
| 726 |
+
ast.alias("builtins", "@py_builtins"),
|
| 727 |
+
ast.alias("_pytest.assertion.rewrite", "@pytest_ar"),
|
| 728 |
+
]
|
| 729 |
+
imports = [
|
| 730 |
+
ast.Import([alias], lineno=lineno, col_offset=0) for alias in aliases
|
| 731 |
+
]
|
| 732 |
+
mod.body[pos:pos] = imports
|
| 733 |
+
|
| 734 |
+
# Collect asserts.
|
| 735 |
+
nodes: List[ast.AST] = [mod]
|
| 736 |
+
while nodes:
|
| 737 |
+
node = nodes.pop()
|
| 738 |
+
for name, field in ast.iter_fields(node):
|
| 739 |
+
if isinstance(field, list):
|
| 740 |
+
new: List[ast.AST] = []
|
| 741 |
+
for i, child in enumerate(field):
|
| 742 |
+
if isinstance(child, ast.Assert):
|
| 743 |
+
# Transform assert.
|
| 744 |
+
new.extend(self.visit(child))
|
| 745 |
+
else:
|
| 746 |
+
new.append(child)
|
| 747 |
+
if isinstance(child, ast.AST):
|
| 748 |
+
nodes.append(child)
|
| 749 |
+
setattr(node, name, new)
|
| 750 |
+
elif (
|
| 751 |
+
isinstance(field, ast.AST)
|
| 752 |
+
# Don't recurse into expressions as they can't contain
|
| 753 |
+
# asserts.
|
| 754 |
+
and not isinstance(field, ast.expr)
|
| 755 |
+
):
|
| 756 |
+
nodes.append(field)
|
| 757 |
+
|
| 758 |
+
@staticmethod
|
| 759 |
+
def is_rewrite_disabled(docstring: str) -> bool:
|
| 760 |
+
return "PYTEST_DONT_REWRITE" in docstring
|
| 761 |
+
|
| 762 |
+
def variable(self) -> str:
|
| 763 |
+
"""Get a new variable."""
|
| 764 |
+
# Use a character invalid in python identifiers to avoid clashing.
|
| 765 |
+
name = "@py_assert" + str(next(self.variable_counter))
|
| 766 |
+
self.variables.append(name)
|
| 767 |
+
return name
|
| 768 |
+
|
| 769 |
+
def assign(self, expr: ast.expr) -> ast.Name:
|
| 770 |
+
"""Give *expr* a name."""
|
| 771 |
+
name = self.variable()
|
| 772 |
+
self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr))
|
| 773 |
+
return ast.Name(name, ast.Load())
|
| 774 |
+
|
| 775 |
+
def display(self, expr: ast.expr) -> ast.expr:
|
| 776 |
+
"""Call saferepr on the expression."""
|
| 777 |
+
return self.helper("_saferepr", expr)
|
| 778 |
+
|
| 779 |
+
def helper(self, name: str, *args: ast.expr) -> ast.expr:
|
| 780 |
+
"""Call a helper in this module."""
|
| 781 |
+
py_name = ast.Name("@pytest_ar", ast.Load())
|
| 782 |
+
attr = ast.Attribute(py_name, name, ast.Load())
|
| 783 |
+
return ast.Call(attr, list(args), [])
|
| 784 |
+
|
| 785 |
+
def builtin(self, name: str) -> ast.Attribute:
|
| 786 |
+
"""Return the builtin called *name*."""
|
| 787 |
+
builtin_name = ast.Name("@py_builtins", ast.Load())
|
| 788 |
+
return ast.Attribute(builtin_name, name, ast.Load())
|
| 789 |
+
|
| 790 |
+
def explanation_param(self, expr: ast.expr) -> str:
|
| 791 |
+
"""Return a new named %-formatting placeholder for expr.
|
| 792 |
+
|
| 793 |
+
This creates a %-formatting placeholder for expr in the
|
| 794 |
+
current formatting context, e.g. ``%(py0)s``. The placeholder
|
| 795 |
+
and expr are placed in the current format context so that it
|
| 796 |
+
can be used on the next call to .pop_format_context().
|
| 797 |
+
"""
|
| 798 |
+
specifier = "py" + str(next(self.variable_counter))
|
| 799 |
+
self.explanation_specifiers[specifier] = expr
|
| 800 |
+
return "%(" + specifier + ")s"
|
| 801 |
+
|
| 802 |
+
def push_format_context(self) -> None:
|
| 803 |
+
"""Create a new formatting context.
|
| 804 |
+
|
| 805 |
+
The format context is used for when an explanation wants to
|
| 806 |
+
have a variable value formatted in the assertion message. In
|
| 807 |
+
this case the value required can be added using
|
| 808 |
+
.explanation_param(). Finally .pop_format_context() is used
|
| 809 |
+
to format a string of %-formatted values as added by
|
| 810 |
+
.explanation_param().
|
| 811 |
+
"""
|
| 812 |
+
self.explanation_specifiers: Dict[str, ast.expr] = {}
|
| 813 |
+
self.stack.append(self.explanation_specifiers)
|
| 814 |
+
|
| 815 |
+
def pop_format_context(self, expl_expr: ast.expr) -> ast.Name:
|
| 816 |
+
"""Format the %-formatted string with current format context.
|
| 817 |
+
|
| 818 |
+
The expl_expr should be an str ast.expr instance constructed from
|
| 819 |
+
the %-placeholders created by .explanation_param(). This will
|
| 820 |
+
add the required code to format said string to .expl_stmts and
|
| 821 |
+
return the ast.Name instance of the formatted string.
|
| 822 |
+
"""
|
| 823 |
+
current = self.stack.pop()
|
| 824 |
+
if self.stack:
|
| 825 |
+
self.explanation_specifiers = self.stack[-1]
|
| 826 |
+
keys = [astStr(key) for key in current.keys()]
|
| 827 |
+
format_dict = ast.Dict(keys, list(current.values()))
|
| 828 |
+
form = ast.BinOp(expl_expr, ast.Mod(), format_dict)
|
| 829 |
+
name = "@py_format" + str(next(self.variable_counter))
|
| 830 |
+
if self.enable_assertion_pass_hook:
|
| 831 |
+
self.format_variables.append(name)
|
| 832 |
+
self.expl_stmts.append(ast.Assign([ast.Name(name, ast.Store())], form))
|
| 833 |
+
return ast.Name(name, ast.Load())
|
| 834 |
+
|
| 835 |
+
def generic_visit(self, node: ast.AST) -> Tuple[ast.Name, str]:
|
| 836 |
+
"""Handle expressions we don't have custom code for."""
|
| 837 |
+
assert isinstance(node, ast.expr)
|
| 838 |
+
res = self.assign(node)
|
| 839 |
+
return res, self.explanation_param(self.display(res))
|
| 840 |
+
|
| 841 |
+
def visit_Assert(self, assert_: ast.Assert) -> List[ast.stmt]:
|
| 842 |
+
"""Return the AST statements to replace the ast.Assert instance.
|
| 843 |
+
|
| 844 |
+
This rewrites the test of an assertion to provide
|
| 845 |
+
intermediate values and replace it with an if statement which
|
| 846 |
+
raises an assertion error with a detailed explanation in case
|
| 847 |
+
the expression is false.
|
| 848 |
+
"""
|
| 849 |
+
if isinstance(assert_.test, ast.Tuple) and len(assert_.test.elts) >= 1:
|
| 850 |
+
from _pytest.warning_types import PytestAssertRewriteWarning
|
| 851 |
+
import warnings
|
| 852 |
+
|
| 853 |
+
# TODO: This assert should not be needed.
|
| 854 |
+
assert self.module_path is not None
|
| 855 |
+
warnings.warn_explicit(
|
| 856 |
+
PytestAssertRewriteWarning(
|
| 857 |
+
"assertion is always true, perhaps remove parentheses?"
|
| 858 |
+
),
|
| 859 |
+
category=None,
|
| 860 |
+
filename=self.module_path,
|
| 861 |
+
lineno=assert_.lineno,
|
| 862 |
+
)
|
| 863 |
+
|
| 864 |
+
self.statements: List[ast.stmt] = []
|
| 865 |
+
self.variables: List[str] = []
|
| 866 |
+
self.variable_counter = itertools.count()
|
| 867 |
+
|
| 868 |
+
if self.enable_assertion_pass_hook:
|
| 869 |
+
self.format_variables: List[str] = []
|
| 870 |
+
|
| 871 |
+
self.stack: List[Dict[str, ast.expr]] = []
|
| 872 |
+
self.expl_stmts: List[ast.stmt] = []
|
| 873 |
+
self.push_format_context()
|
| 874 |
+
# Rewrite assert into a bunch of statements.
|
| 875 |
+
top_condition, explanation = self.visit(assert_.test)
|
| 876 |
+
|
| 877 |
+
negation = ast.UnaryOp(ast.Not(), top_condition)
|
| 878 |
+
|
| 879 |
+
if self.enable_assertion_pass_hook: # Experimental pytest_assertion_pass hook
|
| 880 |
+
msg = self.pop_format_context(astStr(explanation))
|
| 881 |
+
|
| 882 |
+
# Failed
|
| 883 |
+
if assert_.msg:
|
| 884 |
+
assertmsg = self.helper("_format_assertmsg", assert_.msg)
|
| 885 |
+
gluestr = "\n>assert "
|
| 886 |
+
else:
|
| 887 |
+
assertmsg = astStr("")
|
| 888 |
+
gluestr = "assert "
|
| 889 |
+
err_explanation = ast.BinOp(astStr(gluestr), ast.Add(), msg)
|
| 890 |
+
err_msg = ast.BinOp(assertmsg, ast.Add(), err_explanation)
|
| 891 |
+
err_name = ast.Name("AssertionError", ast.Load())
|
| 892 |
+
fmt = self.helper("_format_explanation", err_msg)
|
| 893 |
+
exc = ast.Call(err_name, [fmt], [])
|
| 894 |
+
raise_ = ast.Raise(exc, None)
|
| 895 |
+
statements_fail = []
|
| 896 |
+
statements_fail.extend(self.expl_stmts)
|
| 897 |
+
statements_fail.append(raise_)
|
| 898 |
+
|
| 899 |
+
# Passed
|
| 900 |
+
fmt_pass = self.helper("_format_explanation", msg)
|
| 901 |
+
orig = _get_assertion_exprs(self.source)[assert_.lineno]
|
| 902 |
+
hook_call_pass = ast.Expr(
|
| 903 |
+
self.helper(
|
| 904 |
+
"_call_assertion_pass",
|
| 905 |
+
astNum(assert_.lineno),
|
| 906 |
+
astStr(orig),
|
| 907 |
+
fmt_pass,
|
| 908 |
+
)
|
| 909 |
+
)
|
| 910 |
+
# If any hooks implement assert_pass hook
|
| 911 |
+
hook_impl_test = ast.If(
|
| 912 |
+
self.helper("_check_if_assertion_pass_impl"),
|
| 913 |
+
self.expl_stmts + [hook_call_pass],
|
| 914 |
+
[],
|
| 915 |
+
)
|
| 916 |
+
statements_pass = [hook_impl_test]
|
| 917 |
+
|
| 918 |
+
# Test for assertion condition
|
| 919 |
+
main_test = ast.If(negation, statements_fail, statements_pass)
|
| 920 |
+
self.statements.append(main_test)
|
| 921 |
+
if self.format_variables:
|
| 922 |
+
variables = [
|
| 923 |
+
ast.Name(name, ast.Store()) for name in self.format_variables
|
| 924 |
+
]
|
| 925 |
+
clear_format = ast.Assign(variables, astNameConstant(None))
|
| 926 |
+
self.statements.append(clear_format)
|
| 927 |
+
|
| 928 |
+
else: # Original assertion rewriting
|
| 929 |
+
# Create failure message.
|
| 930 |
+
body = self.expl_stmts
|
| 931 |
+
self.statements.append(ast.If(negation, body, []))
|
| 932 |
+
if assert_.msg:
|
| 933 |
+
assertmsg = self.helper("_format_assertmsg", assert_.msg)
|
| 934 |
+
explanation = "\n>assert " + explanation
|
| 935 |
+
else:
|
| 936 |
+
assertmsg = astStr("")
|
| 937 |
+
explanation = "assert " + explanation
|
| 938 |
+
template = ast.BinOp(assertmsg, ast.Add(), astStr(explanation))
|
| 939 |
+
msg = self.pop_format_context(template)
|
| 940 |
+
fmt = self.helper("_format_explanation", msg)
|
| 941 |
+
err_name = ast.Name("AssertionError", ast.Load())
|
| 942 |
+
exc = ast.Call(err_name, [fmt], [])
|
| 943 |
+
raise_ = ast.Raise(exc, None)
|
| 944 |
+
|
| 945 |
+
body.append(raise_)
|
| 946 |
+
|
| 947 |
+
# Clear temporary variables by setting them to None.
|
| 948 |
+
if self.variables:
|
| 949 |
+
variables = [ast.Name(name, ast.Store()) for name in self.variables]
|
| 950 |
+
clear = ast.Assign(variables, astNameConstant(None))
|
| 951 |
+
self.statements.append(clear)
|
| 952 |
+
# Fix locations (line numbers/column offsets).
|
| 953 |
+
for stmt in self.statements:
|
| 954 |
+
for node in traverse_node(stmt):
|
| 955 |
+
ast.copy_location(node, assert_)
|
| 956 |
+
return self.statements
|
| 957 |
+
|
| 958 |
+
def visit_NamedExpr(self, name: namedExpr) -> Tuple[namedExpr, str]:
|
| 959 |
+
# This method handles the 'walrus operator' repr of the target
|
| 960 |
+
# name if it's a local variable or _should_repr_global_name()
|
| 961 |
+
# thinks it's acceptable.
|
| 962 |
+
locs = ast.Call(self.builtin("locals"), [], [])
|
| 963 |
+
target_id = name.target.id # type: ignore[attr-defined]
|
| 964 |
+
inlocs = ast.Compare(astStr(target_id), [ast.In()], [locs])
|
| 965 |
+
dorepr = self.helper("_should_repr_global_name", name)
|
| 966 |
+
test = ast.BoolOp(ast.Or(), [inlocs, dorepr])
|
| 967 |
+
expr = ast.IfExp(test, self.display(name), astStr(target_id))
|
| 968 |
+
return name, self.explanation_param(expr)
|
| 969 |
+
|
| 970 |
+
def visit_Name(self, name: ast.Name) -> Tuple[ast.Name, str]:
|
| 971 |
+
# Display the repr of the name if it's a local variable or
|
| 972 |
+
# _should_repr_global_name() thinks it's acceptable.
|
| 973 |
+
locs = ast.Call(self.builtin("locals"), [], [])
|
| 974 |
+
inlocs = ast.Compare(astStr(name.id), [ast.In()], [locs])
|
| 975 |
+
dorepr = self.helper("_should_repr_global_name", name)
|
| 976 |
+
test = ast.BoolOp(ast.Or(), [inlocs, dorepr])
|
| 977 |
+
expr = ast.IfExp(test, self.display(name), astStr(name.id))
|
| 978 |
+
return name, self.explanation_param(expr)
|
| 979 |
+
|
| 980 |
+
def visit_BoolOp(self, boolop: ast.BoolOp) -> Tuple[ast.Name, str]:
|
| 981 |
+
res_var = self.variable()
|
| 982 |
+
expl_list = self.assign(ast.List([], ast.Load()))
|
| 983 |
+
app = ast.Attribute(expl_list, "append", ast.Load())
|
| 984 |
+
is_or = int(isinstance(boolop.op, ast.Or))
|
| 985 |
+
body = save = self.statements
|
| 986 |
+
fail_save = self.expl_stmts
|
| 987 |
+
levels = len(boolop.values) - 1
|
| 988 |
+
self.push_format_context()
|
| 989 |
+
# Process each operand, short-circuiting if needed.
|
| 990 |
+
for i, v in enumerate(boolop.values):
|
| 991 |
+
if i:
|
| 992 |
+
fail_inner: List[ast.stmt] = []
|
| 993 |
+
# cond is set in a prior loop iteration below
|
| 994 |
+
self.expl_stmts.append(ast.If(cond, fail_inner, [])) # noqa
|
| 995 |
+
self.expl_stmts = fail_inner
|
| 996 |
+
# Check if the left operand is a namedExpr and the value has already been visited
|
| 997 |
+
if (
|
| 998 |
+
isinstance(v, ast.Compare)
|
| 999 |
+
and isinstance(v.left, namedExpr)
|
| 1000 |
+
and v.left.target.id
|
| 1001 |
+
in [
|
| 1002 |
+
ast_expr.id
|
| 1003 |
+
for ast_expr in boolop.values[:i]
|
| 1004 |
+
if hasattr(ast_expr, "id")
|
| 1005 |
+
]
|
| 1006 |
+
):
|
| 1007 |
+
pytest_temp = self.variable()
|
| 1008 |
+
self.variables_overwrite[
|
| 1009 |
+
v.left.target.id
|
| 1010 |
+
] = v.left # type:ignore[assignment]
|
| 1011 |
+
v.left.target.id = pytest_temp
|
| 1012 |
+
self.push_format_context()
|
| 1013 |
+
res, expl = self.visit(v)
|
| 1014 |
+
body.append(ast.Assign([ast.Name(res_var, ast.Store())], res))
|
| 1015 |
+
expl_format = self.pop_format_context(astStr(expl))
|
| 1016 |
+
call = ast.Call(app, [expl_format], [])
|
| 1017 |
+
self.expl_stmts.append(ast.Expr(call))
|
| 1018 |
+
if i < levels:
|
| 1019 |
+
cond: ast.expr = res
|
| 1020 |
+
if is_or:
|
| 1021 |
+
cond = ast.UnaryOp(ast.Not(), cond)
|
| 1022 |
+
inner: List[ast.stmt] = []
|
| 1023 |
+
self.statements.append(ast.If(cond, inner, []))
|
| 1024 |
+
self.statements = body = inner
|
| 1025 |
+
self.statements = save
|
| 1026 |
+
self.expl_stmts = fail_save
|
| 1027 |
+
expl_template = self.helper("_format_boolop", expl_list, astNum(is_or))
|
| 1028 |
+
expl = self.pop_format_context(expl_template)
|
| 1029 |
+
return ast.Name(res_var, ast.Load()), self.explanation_param(expl)
|
| 1030 |
+
|
| 1031 |
+
def visit_UnaryOp(self, unary: ast.UnaryOp) -> Tuple[ast.Name, str]:
|
| 1032 |
+
pattern = UNARY_MAP[unary.op.__class__]
|
| 1033 |
+
operand_res, operand_expl = self.visit(unary.operand)
|
| 1034 |
+
res = self.assign(ast.UnaryOp(unary.op, operand_res))
|
| 1035 |
+
return res, pattern % (operand_expl,)
|
| 1036 |
+
|
| 1037 |
+
def visit_BinOp(self, binop: ast.BinOp) -> Tuple[ast.Name, str]:
|
| 1038 |
+
symbol = BINOP_MAP[binop.op.__class__]
|
| 1039 |
+
left_expr, left_expl = self.visit(binop.left)
|
| 1040 |
+
right_expr, right_expl = self.visit(binop.right)
|
| 1041 |
+
explanation = f"({left_expl} {symbol} {right_expl})"
|
| 1042 |
+
res = self.assign(ast.BinOp(left_expr, binop.op, right_expr))
|
| 1043 |
+
return res, explanation
|
| 1044 |
+
|
| 1045 |
+
def visit_Call(self, call: ast.Call) -> Tuple[ast.Name, str]:
|
| 1046 |
+
new_func, func_expl = self.visit(call.func)
|
| 1047 |
+
arg_expls = []
|
| 1048 |
+
new_args = []
|
| 1049 |
+
new_kwargs = []
|
| 1050 |
+
for arg in call.args:
|
| 1051 |
+
if isinstance(arg, ast.Name) and arg.id in self.variables_overwrite:
|
| 1052 |
+
arg = self.variables_overwrite[arg.id] # type:ignore[assignment]
|
| 1053 |
+
res, expl = self.visit(arg)
|
| 1054 |
+
arg_expls.append(expl)
|
| 1055 |
+
new_args.append(res)
|
| 1056 |
+
for keyword in call.keywords:
|
| 1057 |
+
if (
|
| 1058 |
+
isinstance(keyword.value, ast.Name)
|
| 1059 |
+
and keyword.value.id in self.variables_overwrite
|
| 1060 |
+
):
|
| 1061 |
+
keyword.value = self.variables_overwrite[
|
| 1062 |
+
keyword.value.id
|
| 1063 |
+
] # type:ignore[assignment]
|
| 1064 |
+
res, expl = self.visit(keyword.value)
|
| 1065 |
+
new_kwargs.append(ast.keyword(keyword.arg, res))
|
| 1066 |
+
if keyword.arg:
|
| 1067 |
+
arg_expls.append(keyword.arg + "=" + expl)
|
| 1068 |
+
else: # **args have `arg` keywords with an .arg of None
|
| 1069 |
+
arg_expls.append("**" + expl)
|
| 1070 |
+
|
| 1071 |
+
expl = "{}({})".format(func_expl, ", ".join(arg_expls))
|
| 1072 |
+
new_call = ast.Call(new_func, new_args, new_kwargs)
|
| 1073 |
+
res = self.assign(new_call)
|
| 1074 |
+
res_expl = self.explanation_param(self.display(res))
|
| 1075 |
+
outer_expl = f"{res_expl}\n{{{res_expl} = {expl}\n}}"
|
| 1076 |
+
return res, outer_expl
|
| 1077 |
+
|
| 1078 |
+
def visit_Starred(self, starred: ast.Starred) -> Tuple[ast.Starred, str]:
|
| 1079 |
+
# A Starred node can appear in a function call.
|
| 1080 |
+
res, expl = self.visit(starred.value)
|
| 1081 |
+
new_starred = ast.Starred(res, starred.ctx)
|
| 1082 |
+
return new_starred, "*" + expl
|
| 1083 |
+
|
| 1084 |
+
def visit_Attribute(self, attr: ast.Attribute) -> Tuple[ast.Name, str]:
|
| 1085 |
+
if not isinstance(attr.ctx, ast.Load):
|
| 1086 |
+
return self.generic_visit(attr)
|
| 1087 |
+
value, value_expl = self.visit(attr.value)
|
| 1088 |
+
res = self.assign(ast.Attribute(value, attr.attr, ast.Load()))
|
| 1089 |
+
res_expl = self.explanation_param(self.display(res))
|
| 1090 |
+
pat = "%s\n{%s = %s.%s\n}"
|
| 1091 |
+
expl = pat % (res_expl, res_expl, value_expl, attr.attr)
|
| 1092 |
+
return res, expl
|
| 1093 |
+
|
| 1094 |
+
def visit_Compare(self, comp: ast.Compare) -> Tuple[ast.expr, str]:
|
| 1095 |
+
self.push_format_context()
|
| 1096 |
+
# We first check if we have overwritten a variable in the previous assert
|
| 1097 |
+
if isinstance(comp.left, ast.Name) and comp.left.id in self.variables_overwrite:
|
| 1098 |
+
comp.left = self.variables_overwrite[
|
| 1099 |
+
comp.left.id
|
| 1100 |
+
] # type:ignore[assignment]
|
| 1101 |
+
if isinstance(comp.left, namedExpr):
|
| 1102 |
+
self.variables_overwrite[
|
| 1103 |
+
comp.left.target.id
|
| 1104 |
+
] = comp.left # type:ignore[assignment]
|
| 1105 |
+
left_res, left_expl = self.visit(comp.left)
|
| 1106 |
+
if isinstance(comp.left, (ast.Compare, ast.BoolOp)):
|
| 1107 |
+
left_expl = f"({left_expl})"
|
| 1108 |
+
res_variables = [self.variable() for i in range(len(comp.ops))]
|
| 1109 |
+
load_names = [ast.Name(v, ast.Load()) for v in res_variables]
|
| 1110 |
+
store_names = [ast.Name(v, ast.Store()) for v in res_variables]
|
| 1111 |
+
it = zip(range(len(comp.ops)), comp.ops, comp.comparators)
|
| 1112 |
+
expls = []
|
| 1113 |
+
syms = []
|
| 1114 |
+
results = [left_res]
|
| 1115 |
+
for i, op, next_operand in it:
|
| 1116 |
+
if (
|
| 1117 |
+
isinstance(next_operand, namedExpr)
|
| 1118 |
+
and isinstance(left_res, ast.Name)
|
| 1119 |
+
and next_operand.target.id == left_res.id
|
| 1120 |
+
):
|
| 1121 |
+
next_operand.target.id = self.variable()
|
| 1122 |
+
self.variables_overwrite[
|
| 1123 |
+
left_res.id
|
| 1124 |
+
] = next_operand # type:ignore[assignment]
|
| 1125 |
+
next_res, next_expl = self.visit(next_operand)
|
| 1126 |
+
if isinstance(next_operand, (ast.Compare, ast.BoolOp)):
|
| 1127 |
+
next_expl = f"({next_expl})"
|
| 1128 |
+
results.append(next_res)
|
| 1129 |
+
sym = BINOP_MAP[op.__class__]
|
| 1130 |
+
syms.append(astStr(sym))
|
| 1131 |
+
expl = f"{left_expl} {sym} {next_expl}"
|
| 1132 |
+
expls.append(astStr(expl))
|
| 1133 |
+
res_expr = ast.Compare(left_res, [op], [next_res])
|
| 1134 |
+
self.statements.append(ast.Assign([store_names[i]], res_expr))
|
| 1135 |
+
left_res, left_expl = next_res, next_expl
|
| 1136 |
+
# Use pytest.assertion.util._reprcompare if that's available.
|
| 1137 |
+
expl_call = self.helper(
|
| 1138 |
+
"_call_reprcompare",
|
| 1139 |
+
ast.Tuple(syms, ast.Load()),
|
| 1140 |
+
ast.Tuple(load_names, ast.Load()),
|
| 1141 |
+
ast.Tuple(expls, ast.Load()),
|
| 1142 |
+
ast.Tuple(results, ast.Load()),
|
| 1143 |
+
)
|
| 1144 |
+
if len(comp.ops) > 1:
|
| 1145 |
+
res: ast.expr = ast.BoolOp(ast.And(), load_names)
|
| 1146 |
+
else:
|
| 1147 |
+
res = load_names[0]
|
| 1148 |
+
|
| 1149 |
+
return res, self.explanation_param(self.pop_format_context(expl_call))
|
| 1150 |
+
|
| 1151 |
+
|
| 1152 |
+
def try_makedirs(cache_dir: Path) -> bool:
|
| 1153 |
+
"""Attempt to create the given directory and sub-directories exist.
|
| 1154 |
+
|
| 1155 |
+
Returns True if successful or if it already exists.
|
| 1156 |
+
"""
|
| 1157 |
+
try:
|
| 1158 |
+
os.makedirs(cache_dir, exist_ok=True)
|
| 1159 |
+
except (FileNotFoundError, NotADirectoryError, FileExistsError):
|
| 1160 |
+
# One of the path components was not a directory:
|
| 1161 |
+
# - we're in a zip file
|
| 1162 |
+
# - it is a file
|
| 1163 |
+
return False
|
| 1164 |
+
except PermissionError:
|
| 1165 |
+
return False
|
| 1166 |
+
except OSError as e:
|
| 1167 |
+
# as of now, EROFS doesn't have an equivalent OSError-subclass
|
| 1168 |
+
if e.errno == errno.EROFS:
|
| 1169 |
+
return False
|
| 1170 |
+
raise
|
| 1171 |
+
return True
|
| 1172 |
+
|
| 1173 |
+
|
| 1174 |
+
def get_cache_dir(file_path: Path) -> Path:
|
| 1175 |
+
"""Return the cache directory to write .pyc files for the given .py file path."""
|
| 1176 |
+
if sys.version_info >= (3, 8) and sys.pycache_prefix:
|
| 1177 |
+
# given:
|
| 1178 |
+
# prefix = '/tmp/pycs'
|
| 1179 |
+
# path = '/home/user/proj/test_app.py'
|
| 1180 |
+
# we want:
|
| 1181 |
+
# '/tmp/pycs/home/user/proj'
|
| 1182 |
+
return Path(sys.pycache_prefix) / Path(*file_path.parts[1:-1])
|
| 1183 |
+
else:
|
| 1184 |
+
# classic pycache directory
|
| 1185 |
+
return file_path.parent / "__pycache__"
|
wemm/lib/python3.10/site-packages/_pytest/cacheprovider.py
ADDED
|
@@ -0,0 +1,598 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Implementation of the cache provider."""
|
| 2 |
+
# This plugin was not named "cache" to avoid conflicts with the external
|
| 3 |
+
# pytest-cache version.
|
| 4 |
+
import dataclasses
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Dict
|
| 9 |
+
from typing import Generator
|
| 10 |
+
from typing import Iterable
|
| 11 |
+
from typing import List
|
| 12 |
+
from typing import Optional
|
| 13 |
+
from typing import Set
|
| 14 |
+
from typing import Union
|
| 15 |
+
|
| 16 |
+
from .pathlib import resolve_from_str
|
| 17 |
+
from .pathlib import rm_rf
|
| 18 |
+
from .reports import CollectReport
|
| 19 |
+
from _pytest import nodes
|
| 20 |
+
from _pytest._io import TerminalWriter
|
| 21 |
+
from _pytest.compat import final
|
| 22 |
+
from _pytest.config import Config
|
| 23 |
+
from _pytest.config import ExitCode
|
| 24 |
+
from _pytest.config import hookimpl
|
| 25 |
+
from _pytest.config.argparsing import Parser
|
| 26 |
+
from _pytest.deprecated import check_ispytest
|
| 27 |
+
from _pytest.fixtures import fixture
|
| 28 |
+
from _pytest.fixtures import FixtureRequest
|
| 29 |
+
from _pytest.main import Session
|
| 30 |
+
from _pytest.nodes import File
|
| 31 |
+
from _pytest.python import Package
|
| 32 |
+
from _pytest.reports import TestReport
|
| 33 |
+
|
| 34 |
+
README_CONTENT = """\
|
| 35 |
+
# pytest cache directory #
|
| 36 |
+
|
| 37 |
+
This directory contains data from the pytest's cache plugin,
|
| 38 |
+
which provides the `--lf` and `--ff` options, as well as the `cache` fixture.
|
| 39 |
+
|
| 40 |
+
**Do not** commit this to version control.
|
| 41 |
+
|
| 42 |
+
See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
CACHEDIR_TAG_CONTENT = b"""\
|
| 46 |
+
Signature: 8a477f597d28d172789f06886806bc55
|
| 47 |
+
# This file is a cache directory tag created by pytest.
|
| 48 |
+
# For information about cache directory tags, see:
|
| 49 |
+
# https://bford.info/cachedir/spec.html
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@final
|
| 54 |
+
@dataclasses.dataclass
|
| 55 |
+
class Cache:
|
| 56 |
+
"""Instance of the `cache` fixture."""
|
| 57 |
+
|
| 58 |
+
_cachedir: Path = dataclasses.field(repr=False)
|
| 59 |
+
_config: Config = dataclasses.field(repr=False)
|
| 60 |
+
|
| 61 |
+
# Sub-directory under cache-dir for directories created by `mkdir()`.
|
| 62 |
+
_CACHE_PREFIX_DIRS = "d"
|
| 63 |
+
|
| 64 |
+
# Sub-directory under cache-dir for values created by `set()`.
|
| 65 |
+
_CACHE_PREFIX_VALUES = "v"
|
| 66 |
+
|
| 67 |
+
def __init__(
|
| 68 |
+
self, cachedir: Path, config: Config, *, _ispytest: bool = False
|
| 69 |
+
) -> None:
|
| 70 |
+
check_ispytest(_ispytest)
|
| 71 |
+
self._cachedir = cachedir
|
| 72 |
+
self._config = config
|
| 73 |
+
|
| 74 |
+
@classmethod
|
| 75 |
+
def for_config(cls, config: Config, *, _ispytest: bool = False) -> "Cache":
|
| 76 |
+
"""Create the Cache instance for a Config.
|
| 77 |
+
|
| 78 |
+
:meta private:
|
| 79 |
+
"""
|
| 80 |
+
check_ispytest(_ispytest)
|
| 81 |
+
cachedir = cls.cache_dir_from_config(config, _ispytest=True)
|
| 82 |
+
if config.getoption("cacheclear") and cachedir.is_dir():
|
| 83 |
+
cls.clear_cache(cachedir, _ispytest=True)
|
| 84 |
+
return cls(cachedir, config, _ispytest=True)
|
| 85 |
+
|
| 86 |
+
@classmethod
|
| 87 |
+
def clear_cache(cls, cachedir: Path, _ispytest: bool = False) -> None:
|
| 88 |
+
"""Clear the sub-directories used to hold cached directories and values.
|
| 89 |
+
|
| 90 |
+
:meta private:
|
| 91 |
+
"""
|
| 92 |
+
check_ispytest(_ispytest)
|
| 93 |
+
for prefix in (cls._CACHE_PREFIX_DIRS, cls._CACHE_PREFIX_VALUES):
|
| 94 |
+
d = cachedir / prefix
|
| 95 |
+
if d.is_dir():
|
| 96 |
+
rm_rf(d)
|
| 97 |
+
|
| 98 |
+
@staticmethod
|
| 99 |
+
def cache_dir_from_config(config: Config, *, _ispytest: bool = False) -> Path:
|
| 100 |
+
"""Get the path to the cache directory for a Config.
|
| 101 |
+
|
| 102 |
+
:meta private:
|
| 103 |
+
"""
|
| 104 |
+
check_ispytest(_ispytest)
|
| 105 |
+
return resolve_from_str(config.getini("cache_dir"), config.rootpath)
|
| 106 |
+
|
| 107 |
+
def warn(self, fmt: str, *, _ispytest: bool = False, **args: object) -> None:
|
| 108 |
+
"""Issue a cache warning.
|
| 109 |
+
|
| 110 |
+
:meta private:
|
| 111 |
+
"""
|
| 112 |
+
check_ispytest(_ispytest)
|
| 113 |
+
import warnings
|
| 114 |
+
from _pytest.warning_types import PytestCacheWarning
|
| 115 |
+
|
| 116 |
+
warnings.warn(
|
| 117 |
+
PytestCacheWarning(fmt.format(**args) if args else fmt),
|
| 118 |
+
self._config.hook,
|
| 119 |
+
stacklevel=3,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
def mkdir(self, name: str) -> Path:
|
| 123 |
+
"""Return a directory path object with the given name.
|
| 124 |
+
|
| 125 |
+
If the directory does not yet exist, it will be created. You can use
|
| 126 |
+
it to manage files to e.g. store/retrieve database dumps across test
|
| 127 |
+
sessions.
|
| 128 |
+
|
| 129 |
+
.. versionadded:: 7.0
|
| 130 |
+
|
| 131 |
+
:param name:
|
| 132 |
+
Must be a string not containing a ``/`` separator.
|
| 133 |
+
Make sure the name contains your plugin or application
|
| 134 |
+
identifiers to prevent clashes with other cache users.
|
| 135 |
+
"""
|
| 136 |
+
path = Path(name)
|
| 137 |
+
if len(path.parts) > 1:
|
| 138 |
+
raise ValueError("name is not allowed to contain path separators")
|
| 139 |
+
res = self._cachedir.joinpath(self._CACHE_PREFIX_DIRS, path)
|
| 140 |
+
res.mkdir(exist_ok=True, parents=True)
|
| 141 |
+
return res
|
| 142 |
+
|
| 143 |
+
def _getvaluepath(self, key: str) -> Path:
|
| 144 |
+
return self._cachedir.joinpath(self._CACHE_PREFIX_VALUES, Path(key))
|
| 145 |
+
|
| 146 |
+
def get(self, key: str, default):
|
| 147 |
+
"""Return the cached value for the given key.
|
| 148 |
+
|
| 149 |
+
If no value was yet cached or the value cannot be read, the specified
|
| 150 |
+
default is returned.
|
| 151 |
+
|
| 152 |
+
:param key:
|
| 153 |
+
Must be a ``/`` separated value. Usually the first
|
| 154 |
+
name is the name of your plugin or your application.
|
| 155 |
+
:param default:
|
| 156 |
+
The value to return in case of a cache-miss or invalid cache value.
|
| 157 |
+
"""
|
| 158 |
+
path = self._getvaluepath(key)
|
| 159 |
+
try:
|
| 160 |
+
with path.open("r", encoding="UTF-8") as f:
|
| 161 |
+
return json.load(f)
|
| 162 |
+
except (ValueError, OSError):
|
| 163 |
+
return default
|
| 164 |
+
|
| 165 |
+
def set(self, key: str, value: object) -> None:
|
| 166 |
+
"""Save value for the given key.
|
| 167 |
+
|
| 168 |
+
:param key:
|
| 169 |
+
Must be a ``/`` separated value. Usually the first
|
| 170 |
+
name is the name of your plugin or your application.
|
| 171 |
+
:param value:
|
| 172 |
+
Must be of any combination of basic python types,
|
| 173 |
+
including nested types like lists of dictionaries.
|
| 174 |
+
"""
|
| 175 |
+
path = self._getvaluepath(key)
|
| 176 |
+
try:
|
| 177 |
+
if path.parent.is_dir():
|
| 178 |
+
cache_dir_exists_already = True
|
| 179 |
+
else:
|
| 180 |
+
cache_dir_exists_already = self._cachedir.exists()
|
| 181 |
+
path.parent.mkdir(exist_ok=True, parents=True)
|
| 182 |
+
except OSError as exc:
|
| 183 |
+
self.warn(
|
| 184 |
+
f"could not create cache path {path}: {exc}",
|
| 185 |
+
_ispytest=True,
|
| 186 |
+
)
|
| 187 |
+
return
|
| 188 |
+
if not cache_dir_exists_already:
|
| 189 |
+
self._ensure_supporting_files()
|
| 190 |
+
data = json.dumps(value, ensure_ascii=False, indent=2)
|
| 191 |
+
try:
|
| 192 |
+
f = path.open("w", encoding="UTF-8")
|
| 193 |
+
except OSError as exc:
|
| 194 |
+
self.warn(
|
| 195 |
+
f"cache could not write path {path}: {exc}",
|
| 196 |
+
_ispytest=True,
|
| 197 |
+
)
|
| 198 |
+
else:
|
| 199 |
+
with f:
|
| 200 |
+
f.write(data)
|
| 201 |
+
|
| 202 |
+
def _ensure_supporting_files(self) -> None:
|
| 203 |
+
"""Create supporting files in the cache dir that are not really part of the cache."""
|
| 204 |
+
readme_path = self._cachedir / "README.md"
|
| 205 |
+
readme_path.write_text(README_CONTENT, encoding="UTF-8")
|
| 206 |
+
|
| 207 |
+
gitignore_path = self._cachedir.joinpath(".gitignore")
|
| 208 |
+
msg = "# Created by pytest automatically.\n*\n"
|
| 209 |
+
gitignore_path.write_text(msg, encoding="UTF-8")
|
| 210 |
+
|
| 211 |
+
cachedir_tag_path = self._cachedir.joinpath("CACHEDIR.TAG")
|
| 212 |
+
cachedir_tag_path.write_bytes(CACHEDIR_TAG_CONTENT)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class LFPluginCollWrapper:
|
| 216 |
+
def __init__(self, lfplugin: "LFPlugin") -> None:
|
| 217 |
+
self.lfplugin = lfplugin
|
| 218 |
+
self._collected_at_least_one_failure = False
|
| 219 |
+
|
| 220 |
+
@hookimpl(hookwrapper=True)
|
| 221 |
+
def pytest_make_collect_report(self, collector: nodes.Collector):
|
| 222 |
+
if isinstance(collector, (Session, Package)):
|
| 223 |
+
out = yield
|
| 224 |
+
res: CollectReport = out.get_result()
|
| 225 |
+
|
| 226 |
+
# Sort any lf-paths to the beginning.
|
| 227 |
+
lf_paths = self.lfplugin._last_failed_paths
|
| 228 |
+
|
| 229 |
+
# Use stable sort to priorize last failed.
|
| 230 |
+
def sort_key(node: Union[nodes.Item, nodes.Collector]) -> bool:
|
| 231 |
+
# Package.path is the __init__.py file, we need the directory.
|
| 232 |
+
if isinstance(node, Package):
|
| 233 |
+
path = node.path.parent
|
| 234 |
+
else:
|
| 235 |
+
path = node.path
|
| 236 |
+
return path in lf_paths
|
| 237 |
+
|
| 238 |
+
res.result = sorted(
|
| 239 |
+
res.result,
|
| 240 |
+
key=sort_key,
|
| 241 |
+
reverse=True,
|
| 242 |
+
)
|
| 243 |
+
return
|
| 244 |
+
|
| 245 |
+
elif isinstance(collector, File):
|
| 246 |
+
if collector.path in self.lfplugin._last_failed_paths:
|
| 247 |
+
out = yield
|
| 248 |
+
res = out.get_result()
|
| 249 |
+
result = res.result
|
| 250 |
+
lastfailed = self.lfplugin.lastfailed
|
| 251 |
+
|
| 252 |
+
# Only filter with known failures.
|
| 253 |
+
if not self._collected_at_least_one_failure:
|
| 254 |
+
if not any(x.nodeid in lastfailed for x in result):
|
| 255 |
+
return
|
| 256 |
+
self.lfplugin.config.pluginmanager.register(
|
| 257 |
+
LFPluginCollSkipfiles(self.lfplugin), "lfplugin-collskip"
|
| 258 |
+
)
|
| 259 |
+
self._collected_at_least_one_failure = True
|
| 260 |
+
|
| 261 |
+
session = collector.session
|
| 262 |
+
result[:] = [
|
| 263 |
+
x
|
| 264 |
+
for x in result
|
| 265 |
+
if x.nodeid in lastfailed
|
| 266 |
+
# Include any passed arguments (not trivial to filter).
|
| 267 |
+
or session.isinitpath(x.path)
|
| 268 |
+
# Keep all sub-collectors.
|
| 269 |
+
or isinstance(x, nodes.Collector)
|
| 270 |
+
]
|
| 271 |
+
return
|
| 272 |
+
yield
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
class LFPluginCollSkipfiles:
|
| 276 |
+
def __init__(self, lfplugin: "LFPlugin") -> None:
|
| 277 |
+
self.lfplugin = lfplugin
|
| 278 |
+
|
| 279 |
+
@hookimpl
|
| 280 |
+
def pytest_make_collect_report(
|
| 281 |
+
self, collector: nodes.Collector
|
| 282 |
+
) -> Optional[CollectReport]:
|
| 283 |
+
# Packages are Files, but we only want to skip test-bearing Files,
|
| 284 |
+
# so don't filter Packages.
|
| 285 |
+
if isinstance(collector, File) and not isinstance(collector, Package):
|
| 286 |
+
if collector.path not in self.lfplugin._last_failed_paths:
|
| 287 |
+
self.lfplugin._skipped_files += 1
|
| 288 |
+
|
| 289 |
+
return CollectReport(
|
| 290 |
+
collector.nodeid, "passed", longrepr=None, result=[]
|
| 291 |
+
)
|
| 292 |
+
return None
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
class LFPlugin:
|
| 296 |
+
"""Plugin which implements the --lf (run last-failing) option."""
|
| 297 |
+
|
| 298 |
+
def __init__(self, config: Config) -> None:
|
| 299 |
+
self.config = config
|
| 300 |
+
active_keys = "lf", "failedfirst"
|
| 301 |
+
self.active = any(config.getoption(key) for key in active_keys)
|
| 302 |
+
assert config.cache
|
| 303 |
+
self.lastfailed: Dict[str, bool] = config.cache.get("cache/lastfailed", {})
|
| 304 |
+
self._previously_failed_count: Optional[int] = None
|
| 305 |
+
self._report_status: Optional[str] = None
|
| 306 |
+
self._skipped_files = 0 # count skipped files during collection due to --lf
|
| 307 |
+
|
| 308 |
+
if config.getoption("lf"):
|
| 309 |
+
self._last_failed_paths = self.get_last_failed_paths()
|
| 310 |
+
config.pluginmanager.register(
|
| 311 |
+
LFPluginCollWrapper(self), "lfplugin-collwrapper"
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
def get_last_failed_paths(self) -> Set[Path]:
|
| 315 |
+
"""Return a set with all Paths of the previously failed nodeids and
|
| 316 |
+
their parents."""
|
| 317 |
+
rootpath = self.config.rootpath
|
| 318 |
+
result = set()
|
| 319 |
+
for nodeid in self.lastfailed:
|
| 320 |
+
path = rootpath / nodeid.split("::")[0]
|
| 321 |
+
result.add(path)
|
| 322 |
+
result.update(path.parents)
|
| 323 |
+
return {x for x in result if x.exists()}
|
| 324 |
+
|
| 325 |
+
def pytest_report_collectionfinish(self) -> Optional[str]:
|
| 326 |
+
if self.active and self.config.getoption("verbose") >= 0:
|
| 327 |
+
return "run-last-failure: %s" % self._report_status
|
| 328 |
+
return None
|
| 329 |
+
|
| 330 |
+
def pytest_runtest_logreport(self, report: TestReport) -> None:
|
| 331 |
+
if (report.when == "call" and report.passed) or report.skipped:
|
| 332 |
+
self.lastfailed.pop(report.nodeid, None)
|
| 333 |
+
elif report.failed:
|
| 334 |
+
self.lastfailed[report.nodeid] = True
|
| 335 |
+
|
| 336 |
+
def pytest_collectreport(self, report: CollectReport) -> None:
|
| 337 |
+
passed = report.outcome in ("passed", "skipped")
|
| 338 |
+
if passed:
|
| 339 |
+
if report.nodeid in self.lastfailed:
|
| 340 |
+
self.lastfailed.pop(report.nodeid)
|
| 341 |
+
self.lastfailed.update((item.nodeid, True) for item in report.result)
|
| 342 |
+
else:
|
| 343 |
+
self.lastfailed[report.nodeid] = True
|
| 344 |
+
|
| 345 |
+
@hookimpl(hookwrapper=True, tryfirst=True)
|
| 346 |
+
def pytest_collection_modifyitems(
|
| 347 |
+
self, config: Config, items: List[nodes.Item]
|
| 348 |
+
) -> Generator[None, None, None]:
|
| 349 |
+
yield
|
| 350 |
+
|
| 351 |
+
if not self.active:
|
| 352 |
+
return
|
| 353 |
+
|
| 354 |
+
if self.lastfailed:
|
| 355 |
+
previously_failed = []
|
| 356 |
+
previously_passed = []
|
| 357 |
+
for item in items:
|
| 358 |
+
if item.nodeid in self.lastfailed:
|
| 359 |
+
previously_failed.append(item)
|
| 360 |
+
else:
|
| 361 |
+
previously_passed.append(item)
|
| 362 |
+
self._previously_failed_count = len(previously_failed)
|
| 363 |
+
|
| 364 |
+
if not previously_failed:
|
| 365 |
+
# Running a subset of all tests with recorded failures
|
| 366 |
+
# only outside of it.
|
| 367 |
+
self._report_status = "%d known failures not in selected tests" % (
|
| 368 |
+
len(self.lastfailed),
|
| 369 |
+
)
|
| 370 |
+
else:
|
| 371 |
+
if self.config.getoption("lf"):
|
| 372 |
+
items[:] = previously_failed
|
| 373 |
+
config.hook.pytest_deselected(items=previously_passed)
|
| 374 |
+
else: # --failedfirst
|
| 375 |
+
items[:] = previously_failed + previously_passed
|
| 376 |
+
|
| 377 |
+
noun = "failure" if self._previously_failed_count == 1 else "failures"
|
| 378 |
+
suffix = " first" if self.config.getoption("failedfirst") else ""
|
| 379 |
+
self._report_status = "rerun previous {count} {noun}{suffix}".format(
|
| 380 |
+
count=self._previously_failed_count, suffix=suffix, noun=noun
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
if self._skipped_files > 0:
|
| 384 |
+
files_noun = "file" if self._skipped_files == 1 else "files"
|
| 385 |
+
self._report_status += " (skipped {files} {files_noun})".format(
|
| 386 |
+
files=self._skipped_files, files_noun=files_noun
|
| 387 |
+
)
|
| 388 |
+
else:
|
| 389 |
+
self._report_status = "no previously failed tests, "
|
| 390 |
+
if self.config.getoption("last_failed_no_failures") == "none":
|
| 391 |
+
self._report_status += "deselecting all items."
|
| 392 |
+
config.hook.pytest_deselected(items=items[:])
|
| 393 |
+
items[:] = []
|
| 394 |
+
else:
|
| 395 |
+
self._report_status += "not deselecting items."
|
| 396 |
+
|
| 397 |
+
def pytest_sessionfinish(self, session: Session) -> None:
|
| 398 |
+
config = self.config
|
| 399 |
+
if config.getoption("cacheshow") or hasattr(config, "workerinput"):
|
| 400 |
+
return
|
| 401 |
+
|
| 402 |
+
assert config.cache is not None
|
| 403 |
+
saved_lastfailed = config.cache.get("cache/lastfailed", {})
|
| 404 |
+
if saved_lastfailed != self.lastfailed:
|
| 405 |
+
config.cache.set("cache/lastfailed", self.lastfailed)
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
class NFPlugin:
|
| 409 |
+
"""Plugin which implements the --nf (run new-first) option."""
|
| 410 |
+
|
| 411 |
+
def __init__(self, config: Config) -> None:
|
| 412 |
+
self.config = config
|
| 413 |
+
self.active = config.option.newfirst
|
| 414 |
+
assert config.cache is not None
|
| 415 |
+
self.cached_nodeids = set(config.cache.get("cache/nodeids", []))
|
| 416 |
+
|
| 417 |
+
@hookimpl(hookwrapper=True, tryfirst=True)
|
| 418 |
+
def pytest_collection_modifyitems(
|
| 419 |
+
self, items: List[nodes.Item]
|
| 420 |
+
) -> Generator[None, None, None]:
|
| 421 |
+
yield
|
| 422 |
+
|
| 423 |
+
if self.active:
|
| 424 |
+
new_items: Dict[str, nodes.Item] = {}
|
| 425 |
+
other_items: Dict[str, nodes.Item] = {}
|
| 426 |
+
for item in items:
|
| 427 |
+
if item.nodeid not in self.cached_nodeids:
|
| 428 |
+
new_items[item.nodeid] = item
|
| 429 |
+
else:
|
| 430 |
+
other_items[item.nodeid] = item
|
| 431 |
+
|
| 432 |
+
items[:] = self._get_increasing_order(
|
| 433 |
+
new_items.values()
|
| 434 |
+
) + self._get_increasing_order(other_items.values())
|
| 435 |
+
self.cached_nodeids.update(new_items)
|
| 436 |
+
else:
|
| 437 |
+
self.cached_nodeids.update(item.nodeid for item in items)
|
| 438 |
+
|
| 439 |
+
def _get_increasing_order(self, items: Iterable[nodes.Item]) -> List[nodes.Item]:
|
| 440 |
+
return sorted(items, key=lambda item: item.path.stat().st_mtime, reverse=True) # type: ignore[no-any-return]
|
| 441 |
+
|
| 442 |
+
def pytest_sessionfinish(self) -> None:
|
| 443 |
+
config = self.config
|
| 444 |
+
if config.getoption("cacheshow") or hasattr(config, "workerinput"):
|
| 445 |
+
return
|
| 446 |
+
|
| 447 |
+
if config.getoption("collectonly"):
|
| 448 |
+
return
|
| 449 |
+
|
| 450 |
+
assert config.cache is not None
|
| 451 |
+
config.cache.set("cache/nodeids", sorted(self.cached_nodeids))
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def pytest_addoption(parser: Parser) -> None:
|
| 455 |
+
group = parser.getgroup("general")
|
| 456 |
+
group.addoption(
|
| 457 |
+
"--lf",
|
| 458 |
+
"--last-failed",
|
| 459 |
+
action="store_true",
|
| 460 |
+
dest="lf",
|
| 461 |
+
help="Rerun only the tests that failed "
|
| 462 |
+
"at the last run (or all if none failed)",
|
| 463 |
+
)
|
| 464 |
+
group.addoption(
|
| 465 |
+
"--ff",
|
| 466 |
+
"--failed-first",
|
| 467 |
+
action="store_true",
|
| 468 |
+
dest="failedfirst",
|
| 469 |
+
help="Run all tests, but run the last failures first. "
|
| 470 |
+
"This may re-order tests and thus lead to "
|
| 471 |
+
"repeated fixture setup/teardown.",
|
| 472 |
+
)
|
| 473 |
+
group.addoption(
|
| 474 |
+
"--nf",
|
| 475 |
+
"--new-first",
|
| 476 |
+
action="store_true",
|
| 477 |
+
dest="newfirst",
|
| 478 |
+
help="Run tests from new files first, then the rest of the tests "
|
| 479 |
+
"sorted by file mtime",
|
| 480 |
+
)
|
| 481 |
+
group.addoption(
|
| 482 |
+
"--cache-show",
|
| 483 |
+
action="append",
|
| 484 |
+
nargs="?",
|
| 485 |
+
dest="cacheshow",
|
| 486 |
+
help=(
|
| 487 |
+
"Show cache contents, don't perform collection or tests. "
|
| 488 |
+
"Optional argument: glob (default: '*')."
|
| 489 |
+
),
|
| 490 |
+
)
|
| 491 |
+
group.addoption(
|
| 492 |
+
"--cache-clear",
|
| 493 |
+
action="store_true",
|
| 494 |
+
dest="cacheclear",
|
| 495 |
+
help="Remove all cache contents at start of test run",
|
| 496 |
+
)
|
| 497 |
+
cache_dir_default = ".pytest_cache"
|
| 498 |
+
if "TOX_ENV_DIR" in os.environ:
|
| 499 |
+
cache_dir_default = os.path.join(os.environ["TOX_ENV_DIR"], cache_dir_default)
|
| 500 |
+
parser.addini("cache_dir", default=cache_dir_default, help="Cache directory path")
|
| 501 |
+
group.addoption(
|
| 502 |
+
"--lfnf",
|
| 503 |
+
"--last-failed-no-failures",
|
| 504 |
+
action="store",
|
| 505 |
+
dest="last_failed_no_failures",
|
| 506 |
+
choices=("all", "none"),
|
| 507 |
+
default="all",
|
| 508 |
+
help="Which tests to run with no previously (known) failures",
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def pytest_cmdline_main(config: Config) -> Optional[Union[int, ExitCode]]:
|
| 513 |
+
if config.option.cacheshow and not config.option.help:
|
| 514 |
+
from _pytest.main import wrap_session
|
| 515 |
+
|
| 516 |
+
return wrap_session(config, cacheshow)
|
| 517 |
+
return None
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
@hookimpl(tryfirst=True)
|
| 521 |
+
def pytest_configure(config: Config) -> None:
|
| 522 |
+
config.cache = Cache.for_config(config, _ispytest=True)
|
| 523 |
+
config.pluginmanager.register(LFPlugin(config), "lfplugin")
|
| 524 |
+
config.pluginmanager.register(NFPlugin(config), "nfplugin")
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
@fixture
|
| 528 |
+
def cache(request: FixtureRequest) -> Cache:
|
| 529 |
+
"""Return a cache object that can persist state between testing sessions.
|
| 530 |
+
|
| 531 |
+
cache.get(key, default)
|
| 532 |
+
cache.set(key, value)
|
| 533 |
+
|
| 534 |
+
Keys must be ``/`` separated strings, where the first part is usually the
|
| 535 |
+
name of your plugin or application to avoid clashes with other cache users.
|
| 536 |
+
|
| 537 |
+
Values can be any object handled by the json stdlib module.
|
| 538 |
+
"""
|
| 539 |
+
assert request.config.cache is not None
|
| 540 |
+
return request.config.cache
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
def pytest_report_header(config: Config) -> Optional[str]:
|
| 544 |
+
"""Display cachedir with --cache-show and if non-default."""
|
| 545 |
+
if config.option.verbose > 0 or config.getini("cache_dir") != ".pytest_cache":
|
| 546 |
+
assert config.cache is not None
|
| 547 |
+
cachedir = config.cache._cachedir
|
| 548 |
+
# TODO: evaluate generating upward relative paths
|
| 549 |
+
# starting with .., ../.. if sensible
|
| 550 |
+
|
| 551 |
+
try:
|
| 552 |
+
displaypath = cachedir.relative_to(config.rootpath)
|
| 553 |
+
except ValueError:
|
| 554 |
+
displaypath = cachedir
|
| 555 |
+
return f"cachedir: {displaypath}"
|
| 556 |
+
return None
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
def cacheshow(config: Config, session: Session) -> int:
|
| 560 |
+
from pprint import pformat
|
| 561 |
+
|
| 562 |
+
assert config.cache is not None
|
| 563 |
+
|
| 564 |
+
tw = TerminalWriter()
|
| 565 |
+
tw.line("cachedir: " + str(config.cache._cachedir))
|
| 566 |
+
if not config.cache._cachedir.is_dir():
|
| 567 |
+
tw.line("cache is empty")
|
| 568 |
+
return 0
|
| 569 |
+
|
| 570 |
+
glob = config.option.cacheshow[0]
|
| 571 |
+
if glob is None:
|
| 572 |
+
glob = "*"
|
| 573 |
+
|
| 574 |
+
dummy = object()
|
| 575 |
+
basedir = config.cache._cachedir
|
| 576 |
+
vdir = basedir / Cache._CACHE_PREFIX_VALUES
|
| 577 |
+
tw.sep("-", "cache values for %r" % glob)
|
| 578 |
+
for valpath in sorted(x for x in vdir.rglob(glob) if x.is_file()):
|
| 579 |
+
key = str(valpath.relative_to(vdir))
|
| 580 |
+
val = config.cache.get(key, dummy)
|
| 581 |
+
if val is dummy:
|
| 582 |
+
tw.line("%s contains unreadable content, will be ignored" % key)
|
| 583 |
+
else:
|
| 584 |
+
tw.line("%s contains:" % key)
|
| 585 |
+
for line in pformat(val).splitlines():
|
| 586 |
+
tw.line(" " + line)
|
| 587 |
+
|
| 588 |
+
ddir = basedir / Cache._CACHE_PREFIX_DIRS
|
| 589 |
+
if ddir.is_dir():
|
| 590 |
+
contents = sorted(ddir.rglob(glob))
|
| 591 |
+
tw.sep("-", "cache directories for %r" % glob)
|
| 592 |
+
for p in contents:
|
| 593 |
+
# if p.is_dir():
|
| 594 |
+
# print("%s/" % p.relative_to(basedir))
|
| 595 |
+
if p.is_file():
|
| 596 |
+
key = str(p.relative_to(basedir))
|
| 597 |
+
tw.line(f"{key} is a file of length {p.stat().st_size:d}")
|
| 598 |
+
return 0
|
wemm/lib/python3.10/site-packages/_pytest/capture.py
ADDED
|
@@ -0,0 +1,1082 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-test stdout/stderr capturing mechanism."""
|
| 2 |
+
import abc
|
| 3 |
+
import collections
|
| 4 |
+
import contextlib
|
| 5 |
+
import io
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
from io import UnsupportedOperation
|
| 9 |
+
from tempfile import TemporaryFile
|
| 10 |
+
from types import TracebackType
|
| 11 |
+
from typing import Any
|
| 12 |
+
from typing import AnyStr
|
| 13 |
+
from typing import BinaryIO
|
| 14 |
+
from typing import Generator
|
| 15 |
+
from typing import Generic
|
| 16 |
+
from typing import Iterable
|
| 17 |
+
from typing import Iterator
|
| 18 |
+
from typing import List
|
| 19 |
+
from typing import NamedTuple
|
| 20 |
+
from typing import Optional
|
| 21 |
+
from typing import TextIO
|
| 22 |
+
from typing import Tuple
|
| 23 |
+
from typing import Type
|
| 24 |
+
from typing import TYPE_CHECKING
|
| 25 |
+
from typing import Union
|
| 26 |
+
|
| 27 |
+
from _pytest.compat import final
|
| 28 |
+
from _pytest.config import Config
|
| 29 |
+
from _pytest.config import hookimpl
|
| 30 |
+
from _pytest.config.argparsing import Parser
|
| 31 |
+
from _pytest.deprecated import check_ispytest
|
| 32 |
+
from _pytest.fixtures import fixture
|
| 33 |
+
from _pytest.fixtures import SubRequest
|
| 34 |
+
from _pytest.nodes import Collector
|
| 35 |
+
from _pytest.nodes import File
|
| 36 |
+
from _pytest.nodes import Item
|
| 37 |
+
|
| 38 |
+
if TYPE_CHECKING:
|
| 39 |
+
from typing_extensions import Final
|
| 40 |
+
from typing_extensions import Literal
|
| 41 |
+
|
| 42 |
+
_CaptureMethod = Literal["fd", "sys", "no", "tee-sys"]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def pytest_addoption(parser: Parser) -> None:
|
| 46 |
+
group = parser.getgroup("general")
|
| 47 |
+
group._addoption(
|
| 48 |
+
"--capture",
|
| 49 |
+
action="store",
|
| 50 |
+
default="fd",
|
| 51 |
+
metavar="method",
|
| 52 |
+
choices=["fd", "sys", "no", "tee-sys"],
|
| 53 |
+
help="Per-test capturing method: one of fd|sys|no|tee-sys",
|
| 54 |
+
)
|
| 55 |
+
group._addoption(
|
| 56 |
+
"-s",
|
| 57 |
+
action="store_const",
|
| 58 |
+
const="no",
|
| 59 |
+
dest="capture",
|
| 60 |
+
help="Shortcut for --capture=no",
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _colorama_workaround() -> None:
|
| 65 |
+
"""Ensure colorama is imported so that it attaches to the correct stdio
|
| 66 |
+
handles on Windows.
|
| 67 |
+
|
| 68 |
+
colorama uses the terminal on import time. So if something does the
|
| 69 |
+
first import of colorama while I/O capture is active, colorama will
|
| 70 |
+
fail in various ways.
|
| 71 |
+
"""
|
| 72 |
+
if sys.platform.startswith("win32"):
|
| 73 |
+
try:
|
| 74 |
+
import colorama # noqa: F401
|
| 75 |
+
except ImportError:
|
| 76 |
+
pass
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _windowsconsoleio_workaround(stream: TextIO) -> None:
|
| 80 |
+
"""Workaround for Windows Unicode console handling.
|
| 81 |
+
|
| 82 |
+
Python 3.6 implemented Unicode console handling for Windows. This works
|
| 83 |
+
by reading/writing to the raw console handle using
|
| 84 |
+
``{Read,Write}ConsoleW``.
|
| 85 |
+
|
| 86 |
+
The problem is that we are going to ``dup2`` over the stdio file
|
| 87 |
+
descriptors when doing ``FDCapture`` and this will ``CloseHandle`` the
|
| 88 |
+
handles used by Python to write to the console. Though there is still some
|
| 89 |
+
weirdness and the console handle seems to only be closed randomly and not
|
| 90 |
+
on the first call to ``CloseHandle``, or maybe it gets reopened with the
|
| 91 |
+
same handle value when we suspend capturing.
|
| 92 |
+
|
| 93 |
+
The workaround in this case will reopen stdio with a different fd which
|
| 94 |
+
also means a different handle by replicating the logic in
|
| 95 |
+
"Py_lifecycle.c:initstdio/create_stdio".
|
| 96 |
+
|
| 97 |
+
:param stream:
|
| 98 |
+
In practice ``sys.stdout`` or ``sys.stderr``, but given
|
| 99 |
+
here as parameter for unittesting purposes.
|
| 100 |
+
|
| 101 |
+
See https://github.com/pytest-dev/py/issues/103.
|
| 102 |
+
"""
|
| 103 |
+
if not sys.platform.startswith("win32") or hasattr(sys, "pypy_version_info"):
|
| 104 |
+
return
|
| 105 |
+
|
| 106 |
+
# Bail out if ``stream`` doesn't seem like a proper ``io`` stream (#2666).
|
| 107 |
+
if not hasattr(stream, "buffer"): # type: ignore[unreachable]
|
| 108 |
+
return
|
| 109 |
+
|
| 110 |
+
buffered = hasattr(stream.buffer, "raw")
|
| 111 |
+
raw_stdout = stream.buffer.raw if buffered else stream.buffer # type: ignore[attr-defined]
|
| 112 |
+
|
| 113 |
+
if not isinstance(raw_stdout, io._WindowsConsoleIO): # type: ignore[attr-defined]
|
| 114 |
+
return
|
| 115 |
+
|
| 116 |
+
def _reopen_stdio(f, mode):
|
| 117 |
+
if not buffered and mode[0] == "w":
|
| 118 |
+
buffering = 0
|
| 119 |
+
else:
|
| 120 |
+
buffering = -1
|
| 121 |
+
|
| 122 |
+
return io.TextIOWrapper(
|
| 123 |
+
open(os.dup(f.fileno()), mode, buffering),
|
| 124 |
+
f.encoding,
|
| 125 |
+
f.errors,
|
| 126 |
+
f.newlines,
|
| 127 |
+
f.line_buffering,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
sys.stdin = _reopen_stdio(sys.stdin, "rb")
|
| 131 |
+
sys.stdout = _reopen_stdio(sys.stdout, "wb")
|
| 132 |
+
sys.stderr = _reopen_stdio(sys.stderr, "wb")
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@hookimpl(hookwrapper=True)
|
| 136 |
+
def pytest_load_initial_conftests(early_config: Config):
|
| 137 |
+
ns = early_config.known_args_namespace
|
| 138 |
+
if ns.capture == "fd":
|
| 139 |
+
_windowsconsoleio_workaround(sys.stdout)
|
| 140 |
+
_colorama_workaround()
|
| 141 |
+
pluginmanager = early_config.pluginmanager
|
| 142 |
+
capman = CaptureManager(ns.capture)
|
| 143 |
+
pluginmanager.register(capman, "capturemanager")
|
| 144 |
+
|
| 145 |
+
# Make sure that capturemanager is properly reset at final shutdown.
|
| 146 |
+
early_config.add_cleanup(capman.stop_global_capturing)
|
| 147 |
+
|
| 148 |
+
# Finally trigger conftest loading but while capturing (issue #93).
|
| 149 |
+
capman.start_global_capturing()
|
| 150 |
+
outcome = yield
|
| 151 |
+
capman.suspend_global_capture()
|
| 152 |
+
if outcome.excinfo is not None:
|
| 153 |
+
out, err = capman.read_global_capture()
|
| 154 |
+
sys.stdout.write(out)
|
| 155 |
+
sys.stderr.write(err)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
# IO Helpers.
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class EncodedFile(io.TextIOWrapper):
|
| 162 |
+
__slots__ = ()
|
| 163 |
+
|
| 164 |
+
@property
|
| 165 |
+
def name(self) -> str:
|
| 166 |
+
# Ensure that file.name is a string. Workaround for a Python bug
|
| 167 |
+
# fixed in >=3.7.4: https://bugs.python.org/issue36015
|
| 168 |
+
return repr(self.buffer)
|
| 169 |
+
|
| 170 |
+
@property
|
| 171 |
+
def mode(self) -> str:
|
| 172 |
+
# TextIOWrapper doesn't expose a mode, but at least some of our
|
| 173 |
+
# tests check it.
|
| 174 |
+
return self.buffer.mode.replace("b", "")
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class CaptureIO(io.TextIOWrapper):
|
| 178 |
+
def __init__(self) -> None:
|
| 179 |
+
super().__init__(io.BytesIO(), encoding="UTF-8", newline="", write_through=True)
|
| 180 |
+
|
| 181 |
+
def getvalue(self) -> str:
|
| 182 |
+
assert isinstance(self.buffer, io.BytesIO)
|
| 183 |
+
return self.buffer.getvalue().decode("UTF-8")
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class TeeCaptureIO(CaptureIO):
|
| 187 |
+
def __init__(self, other: TextIO) -> None:
|
| 188 |
+
self._other = other
|
| 189 |
+
super().__init__()
|
| 190 |
+
|
| 191 |
+
def write(self, s: str) -> int:
|
| 192 |
+
super().write(s)
|
| 193 |
+
return self._other.write(s)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
class DontReadFromInput(TextIO):
|
| 197 |
+
@property
|
| 198 |
+
def encoding(self) -> str:
|
| 199 |
+
return sys.__stdin__.encoding
|
| 200 |
+
|
| 201 |
+
def read(self, size: int = -1) -> str:
|
| 202 |
+
raise OSError(
|
| 203 |
+
"pytest: reading from stdin while output is captured! Consider using `-s`."
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
readline = read
|
| 207 |
+
|
| 208 |
+
def __next__(self) -> str:
|
| 209 |
+
return self.readline()
|
| 210 |
+
|
| 211 |
+
def readlines(self, hint: Optional[int] = -1) -> List[str]:
|
| 212 |
+
raise OSError(
|
| 213 |
+
"pytest: reading from stdin while output is captured! Consider using `-s`."
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
def __iter__(self) -> Iterator[str]:
|
| 217 |
+
return self
|
| 218 |
+
|
| 219 |
+
def fileno(self) -> int:
|
| 220 |
+
raise UnsupportedOperation("redirected stdin is pseudofile, has no fileno()")
|
| 221 |
+
|
| 222 |
+
def flush(self) -> None:
|
| 223 |
+
raise UnsupportedOperation("redirected stdin is pseudofile, has no flush()")
|
| 224 |
+
|
| 225 |
+
def isatty(self) -> bool:
|
| 226 |
+
return False
|
| 227 |
+
|
| 228 |
+
def close(self) -> None:
|
| 229 |
+
pass
|
| 230 |
+
|
| 231 |
+
def readable(self) -> bool:
|
| 232 |
+
return False
|
| 233 |
+
|
| 234 |
+
def seek(self, offset: int, whence: int = 0) -> int:
|
| 235 |
+
raise UnsupportedOperation("redirected stdin is pseudofile, has no seek(int)")
|
| 236 |
+
|
| 237 |
+
def seekable(self) -> bool:
|
| 238 |
+
return False
|
| 239 |
+
|
| 240 |
+
def tell(self) -> int:
|
| 241 |
+
raise UnsupportedOperation("redirected stdin is pseudofile, has no tell()")
|
| 242 |
+
|
| 243 |
+
def truncate(self, size: Optional[int] = None) -> int:
|
| 244 |
+
raise UnsupportedOperation("cannot truncate stdin")
|
| 245 |
+
|
| 246 |
+
def write(self, data: str) -> int:
|
| 247 |
+
raise UnsupportedOperation("cannot write to stdin")
|
| 248 |
+
|
| 249 |
+
def writelines(self, lines: Iterable[str]) -> None:
|
| 250 |
+
raise UnsupportedOperation("Cannot write to stdin")
|
| 251 |
+
|
| 252 |
+
def writable(self) -> bool:
|
| 253 |
+
return False
|
| 254 |
+
|
| 255 |
+
def __enter__(self) -> "DontReadFromInput":
|
| 256 |
+
return self
|
| 257 |
+
|
| 258 |
+
def __exit__(
|
| 259 |
+
self,
|
| 260 |
+
type: Optional[Type[BaseException]],
|
| 261 |
+
value: Optional[BaseException],
|
| 262 |
+
traceback: Optional[TracebackType],
|
| 263 |
+
) -> None:
|
| 264 |
+
pass
|
| 265 |
+
|
| 266 |
+
@property
|
| 267 |
+
def buffer(self) -> BinaryIO:
|
| 268 |
+
# The str/bytes doesn't actually matter in this type, so OK to fake.
|
| 269 |
+
return self # type: ignore[return-value]
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
# Capture classes.
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
class CaptureBase(abc.ABC, Generic[AnyStr]):
|
| 276 |
+
EMPTY_BUFFER: AnyStr
|
| 277 |
+
|
| 278 |
+
@abc.abstractmethod
|
| 279 |
+
def __init__(self, fd: int) -> None:
|
| 280 |
+
raise NotImplementedError()
|
| 281 |
+
|
| 282 |
+
@abc.abstractmethod
|
| 283 |
+
def start(self) -> None:
|
| 284 |
+
raise NotImplementedError()
|
| 285 |
+
|
| 286 |
+
@abc.abstractmethod
|
| 287 |
+
def done(self) -> None:
|
| 288 |
+
raise NotImplementedError()
|
| 289 |
+
|
| 290 |
+
@abc.abstractmethod
|
| 291 |
+
def suspend(self) -> None:
|
| 292 |
+
raise NotImplementedError()
|
| 293 |
+
|
| 294 |
+
@abc.abstractmethod
|
| 295 |
+
def resume(self) -> None:
|
| 296 |
+
raise NotImplementedError()
|
| 297 |
+
|
| 298 |
+
@abc.abstractmethod
|
| 299 |
+
def writeorg(self, data: AnyStr) -> None:
|
| 300 |
+
raise NotImplementedError()
|
| 301 |
+
|
| 302 |
+
@abc.abstractmethod
|
| 303 |
+
def snap(self) -> AnyStr:
|
| 304 |
+
raise NotImplementedError()
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
patchsysdict = {0: "stdin", 1: "stdout", 2: "stderr"}
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
class NoCapture(CaptureBase[str]):
|
| 311 |
+
EMPTY_BUFFER = ""
|
| 312 |
+
|
| 313 |
+
def __init__(self, fd: int) -> None:
|
| 314 |
+
pass
|
| 315 |
+
|
| 316 |
+
def start(self) -> None:
|
| 317 |
+
pass
|
| 318 |
+
|
| 319 |
+
def done(self) -> None:
|
| 320 |
+
pass
|
| 321 |
+
|
| 322 |
+
def suspend(self) -> None:
|
| 323 |
+
pass
|
| 324 |
+
|
| 325 |
+
def resume(self) -> None:
|
| 326 |
+
pass
|
| 327 |
+
|
| 328 |
+
def snap(self) -> str:
|
| 329 |
+
return ""
|
| 330 |
+
|
| 331 |
+
def writeorg(self, data: str) -> None:
|
| 332 |
+
pass
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
class SysCaptureBase(CaptureBase[AnyStr]):
|
| 336 |
+
def __init__(
|
| 337 |
+
self, fd: int, tmpfile: Optional[TextIO] = None, *, tee: bool = False
|
| 338 |
+
) -> None:
|
| 339 |
+
name = patchsysdict[fd]
|
| 340 |
+
self._old: TextIO = getattr(sys, name)
|
| 341 |
+
self.name = name
|
| 342 |
+
if tmpfile is None:
|
| 343 |
+
if name == "stdin":
|
| 344 |
+
tmpfile = DontReadFromInput()
|
| 345 |
+
else:
|
| 346 |
+
tmpfile = CaptureIO() if not tee else TeeCaptureIO(self._old)
|
| 347 |
+
self.tmpfile = tmpfile
|
| 348 |
+
self._state = "initialized"
|
| 349 |
+
|
| 350 |
+
def repr(self, class_name: str) -> str:
|
| 351 |
+
return "<{} {} _old={} _state={!r} tmpfile={!r}>".format(
|
| 352 |
+
class_name,
|
| 353 |
+
self.name,
|
| 354 |
+
hasattr(self, "_old") and repr(self._old) or "<UNSET>",
|
| 355 |
+
self._state,
|
| 356 |
+
self.tmpfile,
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
def __repr__(self) -> str:
|
| 360 |
+
return "<{} {} _old={} _state={!r} tmpfile={!r}>".format(
|
| 361 |
+
self.__class__.__name__,
|
| 362 |
+
self.name,
|
| 363 |
+
hasattr(self, "_old") and repr(self._old) or "<UNSET>",
|
| 364 |
+
self._state,
|
| 365 |
+
self.tmpfile,
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
def _assert_state(self, op: str, states: Tuple[str, ...]) -> None:
|
| 369 |
+
assert (
|
| 370 |
+
self._state in states
|
| 371 |
+
), "cannot {} in state {!r}: expected one of {}".format(
|
| 372 |
+
op, self._state, ", ".join(states)
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
def start(self) -> None:
|
| 376 |
+
self._assert_state("start", ("initialized",))
|
| 377 |
+
setattr(sys, self.name, self.tmpfile)
|
| 378 |
+
self._state = "started"
|
| 379 |
+
|
| 380 |
+
def done(self) -> None:
|
| 381 |
+
self._assert_state("done", ("initialized", "started", "suspended", "done"))
|
| 382 |
+
if self._state == "done":
|
| 383 |
+
return
|
| 384 |
+
setattr(sys, self.name, self._old)
|
| 385 |
+
del self._old
|
| 386 |
+
self.tmpfile.close()
|
| 387 |
+
self._state = "done"
|
| 388 |
+
|
| 389 |
+
def suspend(self) -> None:
|
| 390 |
+
self._assert_state("suspend", ("started", "suspended"))
|
| 391 |
+
setattr(sys, self.name, self._old)
|
| 392 |
+
self._state = "suspended"
|
| 393 |
+
|
| 394 |
+
def resume(self) -> None:
|
| 395 |
+
self._assert_state("resume", ("started", "suspended"))
|
| 396 |
+
if self._state == "started":
|
| 397 |
+
return
|
| 398 |
+
setattr(sys, self.name, self.tmpfile)
|
| 399 |
+
self._state = "started"
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
class SysCaptureBinary(SysCaptureBase[bytes]):
|
| 403 |
+
EMPTY_BUFFER = b""
|
| 404 |
+
|
| 405 |
+
def snap(self) -> bytes:
|
| 406 |
+
self._assert_state("snap", ("started", "suspended"))
|
| 407 |
+
self.tmpfile.seek(0)
|
| 408 |
+
res = self.tmpfile.buffer.read()
|
| 409 |
+
self.tmpfile.seek(0)
|
| 410 |
+
self.tmpfile.truncate()
|
| 411 |
+
return res
|
| 412 |
+
|
| 413 |
+
def writeorg(self, data: bytes) -> None:
|
| 414 |
+
self._assert_state("writeorg", ("started", "suspended"))
|
| 415 |
+
self._old.flush()
|
| 416 |
+
self._old.buffer.write(data)
|
| 417 |
+
self._old.buffer.flush()
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
class SysCapture(SysCaptureBase[str]):
|
| 421 |
+
EMPTY_BUFFER = ""
|
| 422 |
+
|
| 423 |
+
def snap(self) -> str:
|
| 424 |
+
self._assert_state("snap", ("started", "suspended"))
|
| 425 |
+
assert isinstance(self.tmpfile, CaptureIO)
|
| 426 |
+
res = self.tmpfile.getvalue()
|
| 427 |
+
self.tmpfile.seek(0)
|
| 428 |
+
self.tmpfile.truncate()
|
| 429 |
+
return res
|
| 430 |
+
|
| 431 |
+
def writeorg(self, data: str) -> None:
|
| 432 |
+
self._assert_state("writeorg", ("started", "suspended"))
|
| 433 |
+
self._old.write(data)
|
| 434 |
+
self._old.flush()
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
class FDCaptureBase(CaptureBase[AnyStr]):
|
| 438 |
+
def __init__(self, targetfd: int) -> None:
|
| 439 |
+
self.targetfd = targetfd
|
| 440 |
+
|
| 441 |
+
try:
|
| 442 |
+
os.fstat(targetfd)
|
| 443 |
+
except OSError:
|
| 444 |
+
# FD capturing is conceptually simple -- create a temporary file,
|
| 445 |
+
# redirect the FD to it, redirect back when done. But when the
|
| 446 |
+
# target FD is invalid it throws a wrench into this lovely scheme.
|
| 447 |
+
#
|
| 448 |
+
# Tests themselves shouldn't care if the FD is valid, FD capturing
|
| 449 |
+
# should work regardless of external circumstances. So falling back
|
| 450 |
+
# to just sys capturing is not a good option.
|
| 451 |
+
#
|
| 452 |
+
# Further complications are the need to support suspend() and the
|
| 453 |
+
# possibility of FD reuse (e.g. the tmpfile getting the very same
|
| 454 |
+
# target FD). The following approach is robust, I believe.
|
| 455 |
+
self.targetfd_invalid: Optional[int] = os.open(os.devnull, os.O_RDWR)
|
| 456 |
+
os.dup2(self.targetfd_invalid, targetfd)
|
| 457 |
+
else:
|
| 458 |
+
self.targetfd_invalid = None
|
| 459 |
+
self.targetfd_save = os.dup(targetfd)
|
| 460 |
+
|
| 461 |
+
if targetfd == 0:
|
| 462 |
+
self.tmpfile = open(os.devnull, encoding="utf-8")
|
| 463 |
+
self.syscapture: CaptureBase[str] = SysCapture(targetfd)
|
| 464 |
+
else:
|
| 465 |
+
self.tmpfile = EncodedFile(
|
| 466 |
+
TemporaryFile(buffering=0),
|
| 467 |
+
encoding="utf-8",
|
| 468 |
+
errors="replace",
|
| 469 |
+
newline="",
|
| 470 |
+
write_through=True,
|
| 471 |
+
)
|
| 472 |
+
if targetfd in patchsysdict:
|
| 473 |
+
self.syscapture = SysCapture(targetfd, self.tmpfile)
|
| 474 |
+
else:
|
| 475 |
+
self.syscapture = NoCapture(targetfd)
|
| 476 |
+
|
| 477 |
+
self._state = "initialized"
|
| 478 |
+
|
| 479 |
+
def __repr__(self) -> str:
|
| 480 |
+
return "<{} {} oldfd={} _state={!r} tmpfile={!r}>".format(
|
| 481 |
+
self.__class__.__name__,
|
| 482 |
+
self.targetfd,
|
| 483 |
+
self.targetfd_save,
|
| 484 |
+
self._state,
|
| 485 |
+
self.tmpfile,
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
def _assert_state(self, op: str, states: Tuple[str, ...]) -> None:
|
| 489 |
+
assert (
|
| 490 |
+
self._state in states
|
| 491 |
+
), "cannot {} in state {!r}: expected one of {}".format(
|
| 492 |
+
op, self._state, ", ".join(states)
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
def start(self) -> None:
|
| 496 |
+
"""Start capturing on targetfd using memorized tmpfile."""
|
| 497 |
+
self._assert_state("start", ("initialized",))
|
| 498 |
+
os.dup2(self.tmpfile.fileno(), self.targetfd)
|
| 499 |
+
self.syscapture.start()
|
| 500 |
+
self._state = "started"
|
| 501 |
+
|
| 502 |
+
def done(self) -> None:
|
| 503 |
+
"""Stop capturing, restore streams, return original capture file,
|
| 504 |
+
seeked to position zero."""
|
| 505 |
+
self._assert_state("done", ("initialized", "started", "suspended", "done"))
|
| 506 |
+
if self._state == "done":
|
| 507 |
+
return
|
| 508 |
+
os.dup2(self.targetfd_save, self.targetfd)
|
| 509 |
+
os.close(self.targetfd_save)
|
| 510 |
+
if self.targetfd_invalid is not None:
|
| 511 |
+
if self.targetfd_invalid != self.targetfd:
|
| 512 |
+
os.close(self.targetfd)
|
| 513 |
+
os.close(self.targetfd_invalid)
|
| 514 |
+
self.syscapture.done()
|
| 515 |
+
self.tmpfile.close()
|
| 516 |
+
self._state = "done"
|
| 517 |
+
|
| 518 |
+
def suspend(self) -> None:
|
| 519 |
+
self._assert_state("suspend", ("started", "suspended"))
|
| 520 |
+
if self._state == "suspended":
|
| 521 |
+
return
|
| 522 |
+
self.syscapture.suspend()
|
| 523 |
+
os.dup2(self.targetfd_save, self.targetfd)
|
| 524 |
+
self._state = "suspended"
|
| 525 |
+
|
| 526 |
+
def resume(self) -> None:
|
| 527 |
+
self._assert_state("resume", ("started", "suspended"))
|
| 528 |
+
if self._state == "started":
|
| 529 |
+
return
|
| 530 |
+
self.syscapture.resume()
|
| 531 |
+
os.dup2(self.tmpfile.fileno(), self.targetfd)
|
| 532 |
+
self._state = "started"
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
class FDCaptureBinary(FDCaptureBase[bytes]):
|
| 536 |
+
"""Capture IO to/from a given OS-level file descriptor.
|
| 537 |
+
|
| 538 |
+
snap() produces `bytes`.
|
| 539 |
+
"""
|
| 540 |
+
|
| 541 |
+
EMPTY_BUFFER = b""
|
| 542 |
+
|
| 543 |
+
def snap(self) -> bytes:
|
| 544 |
+
self._assert_state("snap", ("started", "suspended"))
|
| 545 |
+
self.tmpfile.seek(0)
|
| 546 |
+
res = self.tmpfile.buffer.read()
|
| 547 |
+
self.tmpfile.seek(0)
|
| 548 |
+
self.tmpfile.truncate()
|
| 549 |
+
return res
|
| 550 |
+
|
| 551 |
+
def writeorg(self, data: bytes) -> None:
|
| 552 |
+
"""Write to original file descriptor."""
|
| 553 |
+
self._assert_state("writeorg", ("started", "suspended"))
|
| 554 |
+
os.write(self.targetfd_save, data)
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
class FDCapture(FDCaptureBase[str]):
|
| 558 |
+
"""Capture IO to/from a given OS-level file descriptor.
|
| 559 |
+
|
| 560 |
+
snap() produces text.
|
| 561 |
+
"""
|
| 562 |
+
|
| 563 |
+
EMPTY_BUFFER = ""
|
| 564 |
+
|
| 565 |
+
def snap(self) -> str:
|
| 566 |
+
self._assert_state("snap", ("started", "suspended"))
|
| 567 |
+
self.tmpfile.seek(0)
|
| 568 |
+
res = self.tmpfile.read()
|
| 569 |
+
self.tmpfile.seek(0)
|
| 570 |
+
self.tmpfile.truncate()
|
| 571 |
+
return res
|
| 572 |
+
|
| 573 |
+
def writeorg(self, data: str) -> None:
|
| 574 |
+
"""Write to original file descriptor."""
|
| 575 |
+
self._assert_state("writeorg", ("started", "suspended"))
|
| 576 |
+
# XXX use encoding of original stream
|
| 577 |
+
os.write(self.targetfd_save, data.encode("utf-8"))
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
# MultiCapture
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
# Generic NamedTuple only supported since Python 3.11.
|
| 584 |
+
if sys.version_info >= (3, 11) or TYPE_CHECKING:
|
| 585 |
+
|
| 586 |
+
@final
|
| 587 |
+
class CaptureResult(NamedTuple, Generic[AnyStr]):
|
| 588 |
+
"""The result of :method:`CaptureFixture.readouterr`."""
|
| 589 |
+
|
| 590 |
+
out: AnyStr
|
| 591 |
+
err: AnyStr
|
| 592 |
+
|
| 593 |
+
else:
|
| 594 |
+
|
| 595 |
+
class CaptureResult(
|
| 596 |
+
collections.namedtuple("CaptureResult", ["out", "err"]), Generic[AnyStr]
|
| 597 |
+
):
|
| 598 |
+
"""The result of :method:`CaptureFixture.readouterr`."""
|
| 599 |
+
|
| 600 |
+
__slots__ = ()
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
class MultiCapture(Generic[AnyStr]):
|
| 604 |
+
_state = None
|
| 605 |
+
_in_suspended = False
|
| 606 |
+
|
| 607 |
+
def __init__(
|
| 608 |
+
self,
|
| 609 |
+
in_: Optional[CaptureBase[AnyStr]],
|
| 610 |
+
out: Optional[CaptureBase[AnyStr]],
|
| 611 |
+
err: Optional[CaptureBase[AnyStr]],
|
| 612 |
+
) -> None:
|
| 613 |
+
self.in_: Optional[CaptureBase[AnyStr]] = in_
|
| 614 |
+
self.out: Optional[CaptureBase[AnyStr]] = out
|
| 615 |
+
self.err: Optional[CaptureBase[AnyStr]] = err
|
| 616 |
+
|
| 617 |
+
def __repr__(self) -> str:
|
| 618 |
+
return "<MultiCapture out={!r} err={!r} in_={!r} _state={!r} _in_suspended={!r}>".format(
|
| 619 |
+
self.out,
|
| 620 |
+
self.err,
|
| 621 |
+
self.in_,
|
| 622 |
+
self._state,
|
| 623 |
+
self._in_suspended,
|
| 624 |
+
)
|
| 625 |
+
|
| 626 |
+
def start_capturing(self) -> None:
|
| 627 |
+
self._state = "started"
|
| 628 |
+
if self.in_:
|
| 629 |
+
self.in_.start()
|
| 630 |
+
if self.out:
|
| 631 |
+
self.out.start()
|
| 632 |
+
if self.err:
|
| 633 |
+
self.err.start()
|
| 634 |
+
|
| 635 |
+
def pop_outerr_to_orig(self) -> Tuple[AnyStr, AnyStr]:
|
| 636 |
+
"""Pop current snapshot out/err capture and flush to orig streams."""
|
| 637 |
+
out, err = self.readouterr()
|
| 638 |
+
if out:
|
| 639 |
+
assert self.out is not None
|
| 640 |
+
self.out.writeorg(out)
|
| 641 |
+
if err:
|
| 642 |
+
assert self.err is not None
|
| 643 |
+
self.err.writeorg(err)
|
| 644 |
+
return out, err
|
| 645 |
+
|
| 646 |
+
def suspend_capturing(self, in_: bool = False) -> None:
|
| 647 |
+
self._state = "suspended"
|
| 648 |
+
if self.out:
|
| 649 |
+
self.out.suspend()
|
| 650 |
+
if self.err:
|
| 651 |
+
self.err.suspend()
|
| 652 |
+
if in_ and self.in_:
|
| 653 |
+
self.in_.suspend()
|
| 654 |
+
self._in_suspended = True
|
| 655 |
+
|
| 656 |
+
def resume_capturing(self) -> None:
|
| 657 |
+
self._state = "started"
|
| 658 |
+
if self.out:
|
| 659 |
+
self.out.resume()
|
| 660 |
+
if self.err:
|
| 661 |
+
self.err.resume()
|
| 662 |
+
if self._in_suspended:
|
| 663 |
+
assert self.in_ is not None
|
| 664 |
+
self.in_.resume()
|
| 665 |
+
self._in_suspended = False
|
| 666 |
+
|
| 667 |
+
def stop_capturing(self) -> None:
|
| 668 |
+
"""Stop capturing and reset capturing streams."""
|
| 669 |
+
if self._state == "stopped":
|
| 670 |
+
raise ValueError("was already stopped")
|
| 671 |
+
self._state = "stopped"
|
| 672 |
+
if self.out:
|
| 673 |
+
self.out.done()
|
| 674 |
+
if self.err:
|
| 675 |
+
self.err.done()
|
| 676 |
+
if self.in_:
|
| 677 |
+
self.in_.done()
|
| 678 |
+
|
| 679 |
+
def is_started(self) -> bool:
|
| 680 |
+
"""Whether actively capturing -- not suspended or stopped."""
|
| 681 |
+
return self._state == "started"
|
| 682 |
+
|
| 683 |
+
def readouterr(self) -> CaptureResult[AnyStr]:
|
| 684 |
+
out = self.out.snap() if self.out else ""
|
| 685 |
+
err = self.err.snap() if self.err else ""
|
| 686 |
+
# TODO: This type error is real, need to fix.
|
| 687 |
+
return CaptureResult(out, err) # type: ignore[arg-type]
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
def _get_multicapture(method: "_CaptureMethod") -> MultiCapture[str]:
|
| 691 |
+
if method == "fd":
|
| 692 |
+
return MultiCapture(in_=FDCapture(0), out=FDCapture(1), err=FDCapture(2))
|
| 693 |
+
elif method == "sys":
|
| 694 |
+
return MultiCapture(in_=SysCapture(0), out=SysCapture(1), err=SysCapture(2))
|
| 695 |
+
elif method == "no":
|
| 696 |
+
return MultiCapture(in_=None, out=None, err=None)
|
| 697 |
+
elif method == "tee-sys":
|
| 698 |
+
return MultiCapture(
|
| 699 |
+
in_=None, out=SysCapture(1, tee=True), err=SysCapture(2, tee=True)
|
| 700 |
+
)
|
| 701 |
+
raise ValueError(f"unknown capturing method: {method!r}")
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
# CaptureManager and CaptureFixture
|
| 705 |
+
|
| 706 |
+
|
| 707 |
+
class CaptureManager:
|
| 708 |
+
"""The capture plugin.
|
| 709 |
+
|
| 710 |
+
Manages that the appropriate capture method is enabled/disabled during
|
| 711 |
+
collection and each test phase (setup, call, teardown). After each of
|
| 712 |
+
those points, the captured output is obtained and attached to the
|
| 713 |
+
collection/runtest report.
|
| 714 |
+
|
| 715 |
+
There are two levels of capture:
|
| 716 |
+
|
| 717 |
+
* global: enabled by default and can be suppressed by the ``-s``
|
| 718 |
+
option. This is always enabled/disabled during collection and each test
|
| 719 |
+
phase.
|
| 720 |
+
|
| 721 |
+
* fixture: when a test function or one of its fixture depend on the
|
| 722 |
+
``capsys`` or ``capfd`` fixtures. In this case special handling is
|
| 723 |
+
needed to ensure the fixtures take precedence over the global capture.
|
| 724 |
+
"""
|
| 725 |
+
|
| 726 |
+
def __init__(self, method: "_CaptureMethod") -> None:
|
| 727 |
+
self._method: Final = method
|
| 728 |
+
self._global_capturing: Optional[MultiCapture[str]] = None
|
| 729 |
+
self._capture_fixture: Optional[CaptureFixture[Any]] = None
|
| 730 |
+
|
| 731 |
+
def __repr__(self) -> str:
|
| 732 |
+
return "<CaptureManager _method={!r} _global_capturing={!r} _capture_fixture={!r}>".format(
|
| 733 |
+
self._method, self._global_capturing, self._capture_fixture
|
| 734 |
+
)
|
| 735 |
+
|
| 736 |
+
def is_capturing(self) -> Union[str, bool]:
|
| 737 |
+
if self.is_globally_capturing():
|
| 738 |
+
return "global"
|
| 739 |
+
if self._capture_fixture:
|
| 740 |
+
return "fixture %s" % self._capture_fixture.request.fixturename
|
| 741 |
+
return False
|
| 742 |
+
|
| 743 |
+
# Global capturing control
|
| 744 |
+
|
| 745 |
+
def is_globally_capturing(self) -> bool:
|
| 746 |
+
return self._method != "no"
|
| 747 |
+
|
| 748 |
+
def start_global_capturing(self) -> None:
|
| 749 |
+
assert self._global_capturing is None
|
| 750 |
+
self._global_capturing = _get_multicapture(self._method)
|
| 751 |
+
self._global_capturing.start_capturing()
|
| 752 |
+
|
| 753 |
+
def stop_global_capturing(self) -> None:
|
| 754 |
+
if self._global_capturing is not None:
|
| 755 |
+
self._global_capturing.pop_outerr_to_orig()
|
| 756 |
+
self._global_capturing.stop_capturing()
|
| 757 |
+
self._global_capturing = None
|
| 758 |
+
|
| 759 |
+
def resume_global_capture(self) -> None:
|
| 760 |
+
# During teardown of the python process, and on rare occasions, capture
|
| 761 |
+
# attributes can be `None` while trying to resume global capture.
|
| 762 |
+
if self._global_capturing is not None:
|
| 763 |
+
self._global_capturing.resume_capturing()
|
| 764 |
+
|
| 765 |
+
def suspend_global_capture(self, in_: bool = False) -> None:
|
| 766 |
+
if self._global_capturing is not None:
|
| 767 |
+
self._global_capturing.suspend_capturing(in_=in_)
|
| 768 |
+
|
| 769 |
+
def suspend(self, in_: bool = False) -> None:
|
| 770 |
+
# Need to undo local capsys-et-al if it exists before disabling global capture.
|
| 771 |
+
self.suspend_fixture()
|
| 772 |
+
self.suspend_global_capture(in_)
|
| 773 |
+
|
| 774 |
+
def resume(self) -> None:
|
| 775 |
+
self.resume_global_capture()
|
| 776 |
+
self.resume_fixture()
|
| 777 |
+
|
| 778 |
+
def read_global_capture(self) -> CaptureResult[str]:
|
| 779 |
+
assert self._global_capturing is not None
|
| 780 |
+
return self._global_capturing.readouterr()
|
| 781 |
+
|
| 782 |
+
# Fixture Control
|
| 783 |
+
|
| 784 |
+
def set_fixture(self, capture_fixture: "CaptureFixture[Any]") -> None:
|
| 785 |
+
if self._capture_fixture:
|
| 786 |
+
current_fixture = self._capture_fixture.request.fixturename
|
| 787 |
+
requested_fixture = capture_fixture.request.fixturename
|
| 788 |
+
capture_fixture.request.raiseerror(
|
| 789 |
+
"cannot use {} and {} at the same time".format(
|
| 790 |
+
requested_fixture, current_fixture
|
| 791 |
+
)
|
| 792 |
+
)
|
| 793 |
+
self._capture_fixture = capture_fixture
|
| 794 |
+
|
| 795 |
+
def unset_fixture(self) -> None:
|
| 796 |
+
self._capture_fixture = None
|
| 797 |
+
|
| 798 |
+
def activate_fixture(self) -> None:
|
| 799 |
+
"""If the current item is using ``capsys`` or ``capfd``, activate
|
| 800 |
+
them so they take precedence over the global capture."""
|
| 801 |
+
if self._capture_fixture:
|
| 802 |
+
self._capture_fixture._start()
|
| 803 |
+
|
| 804 |
+
def deactivate_fixture(self) -> None:
|
| 805 |
+
"""Deactivate the ``capsys`` or ``capfd`` fixture of this item, if any."""
|
| 806 |
+
if self._capture_fixture:
|
| 807 |
+
self._capture_fixture.close()
|
| 808 |
+
|
| 809 |
+
def suspend_fixture(self) -> None:
|
| 810 |
+
if self._capture_fixture:
|
| 811 |
+
self._capture_fixture._suspend()
|
| 812 |
+
|
| 813 |
+
def resume_fixture(self) -> None:
|
| 814 |
+
if self._capture_fixture:
|
| 815 |
+
self._capture_fixture._resume()
|
| 816 |
+
|
| 817 |
+
# Helper context managers
|
| 818 |
+
|
| 819 |
+
@contextlib.contextmanager
|
| 820 |
+
def global_and_fixture_disabled(self) -> Generator[None, None, None]:
|
| 821 |
+
"""Context manager to temporarily disable global and current fixture capturing."""
|
| 822 |
+
do_fixture = self._capture_fixture and self._capture_fixture._is_started()
|
| 823 |
+
if do_fixture:
|
| 824 |
+
self.suspend_fixture()
|
| 825 |
+
do_global = self._global_capturing and self._global_capturing.is_started()
|
| 826 |
+
if do_global:
|
| 827 |
+
self.suspend_global_capture()
|
| 828 |
+
try:
|
| 829 |
+
yield
|
| 830 |
+
finally:
|
| 831 |
+
if do_global:
|
| 832 |
+
self.resume_global_capture()
|
| 833 |
+
if do_fixture:
|
| 834 |
+
self.resume_fixture()
|
| 835 |
+
|
| 836 |
+
@contextlib.contextmanager
|
| 837 |
+
def item_capture(self, when: str, item: Item) -> Generator[None, None, None]:
|
| 838 |
+
self.resume_global_capture()
|
| 839 |
+
self.activate_fixture()
|
| 840 |
+
try:
|
| 841 |
+
yield
|
| 842 |
+
finally:
|
| 843 |
+
self.deactivate_fixture()
|
| 844 |
+
self.suspend_global_capture(in_=False)
|
| 845 |
+
|
| 846 |
+
out, err = self.read_global_capture()
|
| 847 |
+
item.add_report_section(when, "stdout", out)
|
| 848 |
+
item.add_report_section(when, "stderr", err)
|
| 849 |
+
|
| 850 |
+
# Hooks
|
| 851 |
+
|
| 852 |
+
@hookimpl(hookwrapper=True)
|
| 853 |
+
def pytest_make_collect_report(self, collector: Collector):
|
| 854 |
+
if isinstance(collector, File):
|
| 855 |
+
self.resume_global_capture()
|
| 856 |
+
outcome = yield
|
| 857 |
+
self.suspend_global_capture()
|
| 858 |
+
out, err = self.read_global_capture()
|
| 859 |
+
rep = outcome.get_result()
|
| 860 |
+
if out:
|
| 861 |
+
rep.sections.append(("Captured stdout", out))
|
| 862 |
+
if err:
|
| 863 |
+
rep.sections.append(("Captured stderr", err))
|
| 864 |
+
else:
|
| 865 |
+
yield
|
| 866 |
+
|
| 867 |
+
@hookimpl(hookwrapper=True)
|
| 868 |
+
def pytest_runtest_setup(self, item: Item) -> Generator[None, None, None]:
|
| 869 |
+
with self.item_capture("setup", item):
|
| 870 |
+
yield
|
| 871 |
+
|
| 872 |
+
@hookimpl(hookwrapper=True)
|
| 873 |
+
def pytest_runtest_call(self, item: Item) -> Generator[None, None, None]:
|
| 874 |
+
with self.item_capture("call", item):
|
| 875 |
+
yield
|
| 876 |
+
|
| 877 |
+
@hookimpl(hookwrapper=True)
|
| 878 |
+
def pytest_runtest_teardown(self, item: Item) -> Generator[None, None, None]:
|
| 879 |
+
with self.item_capture("teardown", item):
|
| 880 |
+
yield
|
| 881 |
+
|
| 882 |
+
@hookimpl(tryfirst=True)
|
| 883 |
+
def pytest_keyboard_interrupt(self) -> None:
|
| 884 |
+
self.stop_global_capturing()
|
| 885 |
+
|
| 886 |
+
@hookimpl(tryfirst=True)
|
| 887 |
+
def pytest_internalerror(self) -> None:
|
| 888 |
+
self.stop_global_capturing()
|
| 889 |
+
|
| 890 |
+
|
| 891 |
+
class CaptureFixture(Generic[AnyStr]):
|
| 892 |
+
"""Object returned by the :fixture:`capsys`, :fixture:`capsysbinary`,
|
| 893 |
+
:fixture:`capfd` and :fixture:`capfdbinary` fixtures."""
|
| 894 |
+
|
| 895 |
+
def __init__(
|
| 896 |
+
self,
|
| 897 |
+
captureclass: Type[CaptureBase[AnyStr]],
|
| 898 |
+
request: SubRequest,
|
| 899 |
+
*,
|
| 900 |
+
_ispytest: bool = False,
|
| 901 |
+
) -> None:
|
| 902 |
+
check_ispytest(_ispytest)
|
| 903 |
+
self.captureclass: Type[CaptureBase[AnyStr]] = captureclass
|
| 904 |
+
self.request = request
|
| 905 |
+
self._capture: Optional[MultiCapture[AnyStr]] = None
|
| 906 |
+
self._captured_out: AnyStr = self.captureclass.EMPTY_BUFFER
|
| 907 |
+
self._captured_err: AnyStr = self.captureclass.EMPTY_BUFFER
|
| 908 |
+
|
| 909 |
+
def _start(self) -> None:
|
| 910 |
+
if self._capture is None:
|
| 911 |
+
self._capture = MultiCapture(
|
| 912 |
+
in_=None,
|
| 913 |
+
out=self.captureclass(1),
|
| 914 |
+
err=self.captureclass(2),
|
| 915 |
+
)
|
| 916 |
+
self._capture.start_capturing()
|
| 917 |
+
|
| 918 |
+
def close(self) -> None:
|
| 919 |
+
if self._capture is not None:
|
| 920 |
+
out, err = self._capture.pop_outerr_to_orig()
|
| 921 |
+
self._captured_out += out
|
| 922 |
+
self._captured_err += err
|
| 923 |
+
self._capture.stop_capturing()
|
| 924 |
+
self._capture = None
|
| 925 |
+
|
| 926 |
+
def readouterr(self) -> CaptureResult[AnyStr]:
|
| 927 |
+
"""Read and return the captured output so far, resetting the internal
|
| 928 |
+
buffer.
|
| 929 |
+
|
| 930 |
+
:returns:
|
| 931 |
+
The captured content as a namedtuple with ``out`` and ``err``
|
| 932 |
+
string attributes.
|
| 933 |
+
"""
|
| 934 |
+
captured_out, captured_err = self._captured_out, self._captured_err
|
| 935 |
+
if self._capture is not None:
|
| 936 |
+
out, err = self._capture.readouterr()
|
| 937 |
+
captured_out += out
|
| 938 |
+
captured_err += err
|
| 939 |
+
self._captured_out = self.captureclass.EMPTY_BUFFER
|
| 940 |
+
self._captured_err = self.captureclass.EMPTY_BUFFER
|
| 941 |
+
return CaptureResult(captured_out, captured_err)
|
| 942 |
+
|
| 943 |
+
def _suspend(self) -> None:
|
| 944 |
+
"""Suspend this fixture's own capturing temporarily."""
|
| 945 |
+
if self._capture is not None:
|
| 946 |
+
self._capture.suspend_capturing()
|
| 947 |
+
|
| 948 |
+
def _resume(self) -> None:
|
| 949 |
+
"""Resume this fixture's own capturing temporarily."""
|
| 950 |
+
if self._capture is not None:
|
| 951 |
+
self._capture.resume_capturing()
|
| 952 |
+
|
| 953 |
+
def _is_started(self) -> bool:
|
| 954 |
+
"""Whether actively capturing -- not disabled or closed."""
|
| 955 |
+
if self._capture is not None:
|
| 956 |
+
return self._capture.is_started()
|
| 957 |
+
return False
|
| 958 |
+
|
| 959 |
+
@contextlib.contextmanager
|
| 960 |
+
def disabled(self) -> Generator[None, None, None]:
|
| 961 |
+
"""Temporarily disable capturing while inside the ``with`` block."""
|
| 962 |
+
capmanager: CaptureManager = self.request.config.pluginmanager.getplugin(
|
| 963 |
+
"capturemanager"
|
| 964 |
+
)
|
| 965 |
+
with capmanager.global_and_fixture_disabled():
|
| 966 |
+
yield
|
| 967 |
+
|
| 968 |
+
|
| 969 |
+
# The fixtures.
|
| 970 |
+
|
| 971 |
+
|
| 972 |
+
@fixture
|
| 973 |
+
def capsys(request: SubRequest) -> Generator[CaptureFixture[str], None, None]:
|
| 974 |
+
r"""Enable text capturing of writes to ``sys.stdout`` and ``sys.stderr``.
|
| 975 |
+
|
| 976 |
+
The captured output is made available via ``capsys.readouterr()`` method
|
| 977 |
+
calls, which return a ``(out, err)`` namedtuple.
|
| 978 |
+
``out`` and ``err`` will be ``text`` objects.
|
| 979 |
+
|
| 980 |
+
Returns an instance of :class:`CaptureFixture[str] <pytest.CaptureFixture>`.
|
| 981 |
+
|
| 982 |
+
Example:
|
| 983 |
+
|
| 984 |
+
.. code-block:: python
|
| 985 |
+
|
| 986 |
+
def test_output(capsys):
|
| 987 |
+
print("hello")
|
| 988 |
+
captured = capsys.readouterr()
|
| 989 |
+
assert captured.out == "hello\n"
|
| 990 |
+
"""
|
| 991 |
+
capman: CaptureManager = request.config.pluginmanager.getplugin("capturemanager")
|
| 992 |
+
capture_fixture = CaptureFixture(SysCapture, request, _ispytest=True)
|
| 993 |
+
capman.set_fixture(capture_fixture)
|
| 994 |
+
capture_fixture._start()
|
| 995 |
+
yield capture_fixture
|
| 996 |
+
capture_fixture.close()
|
| 997 |
+
capman.unset_fixture()
|
| 998 |
+
|
| 999 |
+
|
| 1000 |
+
@fixture
|
| 1001 |
+
def capsysbinary(request: SubRequest) -> Generator[CaptureFixture[bytes], None, None]:
|
| 1002 |
+
r"""Enable bytes capturing of writes to ``sys.stdout`` and ``sys.stderr``.
|
| 1003 |
+
|
| 1004 |
+
The captured output is made available via ``capsysbinary.readouterr()``
|
| 1005 |
+
method calls, which return a ``(out, err)`` namedtuple.
|
| 1006 |
+
``out`` and ``err`` will be ``bytes`` objects.
|
| 1007 |
+
|
| 1008 |
+
Returns an instance of :class:`CaptureFixture[bytes] <pytest.CaptureFixture>`.
|
| 1009 |
+
|
| 1010 |
+
Example:
|
| 1011 |
+
|
| 1012 |
+
.. code-block:: python
|
| 1013 |
+
|
| 1014 |
+
def test_output(capsysbinary):
|
| 1015 |
+
print("hello")
|
| 1016 |
+
captured = capsysbinary.readouterr()
|
| 1017 |
+
assert captured.out == b"hello\n"
|
| 1018 |
+
"""
|
| 1019 |
+
capman: CaptureManager = request.config.pluginmanager.getplugin("capturemanager")
|
| 1020 |
+
capture_fixture = CaptureFixture(SysCaptureBinary, request, _ispytest=True)
|
| 1021 |
+
capman.set_fixture(capture_fixture)
|
| 1022 |
+
capture_fixture._start()
|
| 1023 |
+
yield capture_fixture
|
| 1024 |
+
capture_fixture.close()
|
| 1025 |
+
capman.unset_fixture()
|
| 1026 |
+
|
| 1027 |
+
|
| 1028 |
+
@fixture
|
| 1029 |
+
def capfd(request: SubRequest) -> Generator[CaptureFixture[str], None, None]:
|
| 1030 |
+
r"""Enable text capturing of writes to file descriptors ``1`` and ``2``.
|
| 1031 |
+
|
| 1032 |
+
The captured output is made available via ``capfd.readouterr()`` method
|
| 1033 |
+
calls, which return a ``(out, err)`` namedtuple.
|
| 1034 |
+
``out`` and ``err`` will be ``text`` objects.
|
| 1035 |
+
|
| 1036 |
+
Returns an instance of :class:`CaptureFixture[str] <pytest.CaptureFixture>`.
|
| 1037 |
+
|
| 1038 |
+
Example:
|
| 1039 |
+
|
| 1040 |
+
.. code-block:: python
|
| 1041 |
+
|
| 1042 |
+
def test_system_echo(capfd):
|
| 1043 |
+
os.system('echo "hello"')
|
| 1044 |
+
captured = capfd.readouterr()
|
| 1045 |
+
assert captured.out == "hello\n"
|
| 1046 |
+
"""
|
| 1047 |
+
capman: CaptureManager = request.config.pluginmanager.getplugin("capturemanager")
|
| 1048 |
+
capture_fixture = CaptureFixture(FDCapture, request, _ispytest=True)
|
| 1049 |
+
capman.set_fixture(capture_fixture)
|
| 1050 |
+
capture_fixture._start()
|
| 1051 |
+
yield capture_fixture
|
| 1052 |
+
capture_fixture.close()
|
| 1053 |
+
capman.unset_fixture()
|
| 1054 |
+
|
| 1055 |
+
|
| 1056 |
+
@fixture
|
| 1057 |
+
def capfdbinary(request: SubRequest) -> Generator[CaptureFixture[bytes], None, None]:
|
| 1058 |
+
r"""Enable bytes capturing of writes to file descriptors ``1`` and ``2``.
|
| 1059 |
+
|
| 1060 |
+
The captured output is made available via ``capfd.readouterr()`` method
|
| 1061 |
+
calls, which return a ``(out, err)`` namedtuple.
|
| 1062 |
+
``out`` and ``err`` will be ``byte`` objects.
|
| 1063 |
+
|
| 1064 |
+
Returns an instance of :class:`CaptureFixture[bytes] <pytest.CaptureFixture>`.
|
| 1065 |
+
|
| 1066 |
+
Example:
|
| 1067 |
+
|
| 1068 |
+
.. code-block:: python
|
| 1069 |
+
|
| 1070 |
+
def test_system_echo(capfdbinary):
|
| 1071 |
+
os.system('echo "hello"')
|
| 1072 |
+
captured = capfdbinary.readouterr()
|
| 1073 |
+
assert captured.out == b"hello\n"
|
| 1074 |
+
|
| 1075 |
+
"""
|
| 1076 |
+
capman: CaptureManager = request.config.pluginmanager.getplugin("capturemanager")
|
| 1077 |
+
capture_fixture = CaptureFixture(FDCaptureBinary, request, _ispytest=True)
|
| 1078 |
+
capman.set_fixture(capture_fixture)
|
| 1079 |
+
capture_fixture._start()
|
| 1080 |
+
yield capture_fixture
|
| 1081 |
+
capture_fixture.close()
|
| 1082 |
+
capman.unset_fixture()
|
wemm/lib/python3.10/site-packages/_pytest/compat.py
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Python version compatibility code."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import dataclasses
|
| 5 |
+
import enum
|
| 6 |
+
import functools
|
| 7 |
+
import inspect
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
from inspect import Parameter
|
| 11 |
+
from inspect import signature
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Any
|
| 14 |
+
from typing import Callable
|
| 15 |
+
from typing import Generic
|
| 16 |
+
from typing import NoReturn
|
| 17 |
+
from typing import TYPE_CHECKING
|
| 18 |
+
from typing import TypeVar
|
| 19 |
+
|
| 20 |
+
import py
|
| 21 |
+
|
| 22 |
+
# fmt: off
|
| 23 |
+
# Workaround for https://github.com/sphinx-doc/sphinx/issues/10351.
|
| 24 |
+
# If `overload` is imported from `compat` instead of from `typing`,
|
| 25 |
+
# Sphinx doesn't recognize it as `overload` and the API docs for
|
| 26 |
+
# overloaded functions look good again. But type checkers handle
|
| 27 |
+
# it fine.
|
| 28 |
+
# fmt: on
|
| 29 |
+
if True:
|
| 30 |
+
from typing import overload as overload
|
| 31 |
+
|
| 32 |
+
if TYPE_CHECKING:
|
| 33 |
+
from typing_extensions import Final
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
_T = TypeVar("_T")
|
| 37 |
+
_S = TypeVar("_S")
|
| 38 |
+
|
| 39 |
+
#: constant to prepare valuing pylib path replacements/lazy proxies later on
|
| 40 |
+
# intended for removal in pytest 8.0 or 9.0
|
| 41 |
+
|
| 42 |
+
# fmt: off
|
| 43 |
+
# intentional space to create a fake difference for the verification
|
| 44 |
+
LEGACY_PATH = py.path. local
|
| 45 |
+
# fmt: on
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def legacy_path(path: str | os.PathLike[str]) -> LEGACY_PATH:
|
| 49 |
+
"""Internal wrapper to prepare lazy proxies for legacy_path instances"""
|
| 50 |
+
return LEGACY_PATH(path)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# fmt: off
|
| 54 |
+
# Singleton type for NOTSET, as described in:
|
| 55 |
+
# https://www.python.org/dev/peps/pep-0484/#support-for-singleton-types-in-unions
|
| 56 |
+
class NotSetType(enum.Enum):
|
| 57 |
+
token = 0
|
| 58 |
+
NOTSET: Final = NotSetType.token # noqa: E305
|
| 59 |
+
# fmt: on
|
| 60 |
+
|
| 61 |
+
if sys.version_info >= (3, 8):
|
| 62 |
+
import importlib.metadata
|
| 63 |
+
|
| 64 |
+
importlib_metadata = importlib.metadata
|
| 65 |
+
else:
|
| 66 |
+
import importlib_metadata as importlib_metadata # noqa: F401
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _format_args(func: Callable[..., Any]) -> str:
|
| 70 |
+
return str(signature(func))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def is_generator(func: object) -> bool:
|
| 74 |
+
genfunc = inspect.isgeneratorfunction(func)
|
| 75 |
+
return genfunc and not iscoroutinefunction(func)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def iscoroutinefunction(func: object) -> bool:
|
| 79 |
+
"""Return True if func is a coroutine function (a function defined with async
|
| 80 |
+
def syntax, and doesn't contain yield), or a function decorated with
|
| 81 |
+
@asyncio.coroutine.
|
| 82 |
+
|
| 83 |
+
Note: copied and modified from Python 3.5's builtin couroutines.py to avoid
|
| 84 |
+
importing asyncio directly, which in turns also initializes the "logging"
|
| 85 |
+
module as a side-effect (see issue #8).
|
| 86 |
+
"""
|
| 87 |
+
return inspect.iscoroutinefunction(func) or getattr(func, "_is_coroutine", False)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def is_async_function(func: object) -> bool:
|
| 91 |
+
"""Return True if the given function seems to be an async function or
|
| 92 |
+
an async generator."""
|
| 93 |
+
return iscoroutinefunction(func) or inspect.isasyncgenfunction(func)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def getlocation(function, curdir: str | None = None) -> str:
|
| 97 |
+
function = get_real_func(function)
|
| 98 |
+
fn = Path(inspect.getfile(function))
|
| 99 |
+
lineno = function.__code__.co_firstlineno
|
| 100 |
+
if curdir is not None:
|
| 101 |
+
try:
|
| 102 |
+
relfn = fn.relative_to(curdir)
|
| 103 |
+
except ValueError:
|
| 104 |
+
pass
|
| 105 |
+
else:
|
| 106 |
+
return "%s:%d" % (relfn, lineno + 1)
|
| 107 |
+
return "%s:%d" % (fn, lineno + 1)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def num_mock_patch_args(function) -> int:
|
| 111 |
+
"""Return number of arguments used up by mock arguments (if any)."""
|
| 112 |
+
patchings = getattr(function, "patchings", None)
|
| 113 |
+
if not patchings:
|
| 114 |
+
return 0
|
| 115 |
+
|
| 116 |
+
mock_sentinel = getattr(sys.modules.get("mock"), "DEFAULT", object())
|
| 117 |
+
ut_mock_sentinel = getattr(sys.modules.get("unittest.mock"), "DEFAULT", object())
|
| 118 |
+
|
| 119 |
+
return len(
|
| 120 |
+
[
|
| 121 |
+
p
|
| 122 |
+
for p in patchings
|
| 123 |
+
if not p.attribute_name
|
| 124 |
+
and (p.new is mock_sentinel or p.new is ut_mock_sentinel)
|
| 125 |
+
]
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def getfuncargnames(
|
| 130 |
+
function: Callable[..., Any],
|
| 131 |
+
*,
|
| 132 |
+
name: str = "",
|
| 133 |
+
is_method: bool = False,
|
| 134 |
+
cls: type | None = None,
|
| 135 |
+
) -> tuple[str, ...]:
|
| 136 |
+
"""Return the names of a function's mandatory arguments.
|
| 137 |
+
|
| 138 |
+
Should return the names of all function arguments that:
|
| 139 |
+
* Aren't bound to an instance or type as in instance or class methods.
|
| 140 |
+
* Don't have default values.
|
| 141 |
+
* Aren't bound with functools.partial.
|
| 142 |
+
* Aren't replaced with mocks.
|
| 143 |
+
|
| 144 |
+
The is_method and cls arguments indicate that the function should
|
| 145 |
+
be treated as a bound method even though it's not unless, only in
|
| 146 |
+
the case of cls, the function is a static method.
|
| 147 |
+
|
| 148 |
+
The name parameter should be the original name in which the function was collected.
|
| 149 |
+
"""
|
| 150 |
+
# TODO(RonnyPfannschmidt): This function should be refactored when we
|
| 151 |
+
# revisit fixtures. The fixture mechanism should ask the node for
|
| 152 |
+
# the fixture names, and not try to obtain directly from the
|
| 153 |
+
# function object well after collection has occurred.
|
| 154 |
+
|
| 155 |
+
# The parameters attribute of a Signature object contains an
|
| 156 |
+
# ordered mapping of parameter names to Parameter instances. This
|
| 157 |
+
# creates a tuple of the names of the parameters that don't have
|
| 158 |
+
# defaults.
|
| 159 |
+
try:
|
| 160 |
+
parameters = signature(function).parameters
|
| 161 |
+
except (ValueError, TypeError) as e:
|
| 162 |
+
from _pytest.outcomes import fail
|
| 163 |
+
|
| 164 |
+
fail(
|
| 165 |
+
f"Could not determine arguments of {function!r}: {e}",
|
| 166 |
+
pytrace=False,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
arg_names = tuple(
|
| 170 |
+
p.name
|
| 171 |
+
for p in parameters.values()
|
| 172 |
+
if (
|
| 173 |
+
p.kind is Parameter.POSITIONAL_OR_KEYWORD
|
| 174 |
+
or p.kind is Parameter.KEYWORD_ONLY
|
| 175 |
+
)
|
| 176 |
+
and p.default is Parameter.empty
|
| 177 |
+
)
|
| 178 |
+
if not name:
|
| 179 |
+
name = function.__name__
|
| 180 |
+
|
| 181 |
+
# If this function should be treated as a bound method even though
|
| 182 |
+
# it's passed as an unbound method or function, remove the first
|
| 183 |
+
# parameter name.
|
| 184 |
+
if is_method or (
|
| 185 |
+
# Not using `getattr` because we don't want to resolve the staticmethod.
|
| 186 |
+
# Not using `cls.__dict__` because we want to check the entire MRO.
|
| 187 |
+
cls
|
| 188 |
+
and not isinstance(
|
| 189 |
+
inspect.getattr_static(cls, name, default=None), staticmethod
|
| 190 |
+
)
|
| 191 |
+
):
|
| 192 |
+
arg_names = arg_names[1:]
|
| 193 |
+
# Remove any names that will be replaced with mocks.
|
| 194 |
+
if hasattr(function, "__wrapped__"):
|
| 195 |
+
arg_names = arg_names[num_mock_patch_args(function) :]
|
| 196 |
+
return arg_names
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def get_default_arg_names(function: Callable[..., Any]) -> tuple[str, ...]:
|
| 200 |
+
# Note: this code intentionally mirrors the code at the beginning of
|
| 201 |
+
# getfuncargnames, to get the arguments which were excluded from its result
|
| 202 |
+
# because they had default values.
|
| 203 |
+
return tuple(
|
| 204 |
+
p.name
|
| 205 |
+
for p in signature(function).parameters.values()
|
| 206 |
+
if p.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY)
|
| 207 |
+
and p.default is not Parameter.empty
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
_non_printable_ascii_translate_table = {
|
| 212 |
+
i: f"\\x{i:02x}" for i in range(128) if i not in range(32, 127)
|
| 213 |
+
}
|
| 214 |
+
_non_printable_ascii_translate_table.update(
|
| 215 |
+
{ord("\t"): "\\t", ord("\r"): "\\r", ord("\n"): "\\n"}
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def _translate_non_printable(s: str) -> str:
|
| 220 |
+
return s.translate(_non_printable_ascii_translate_table)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
STRING_TYPES = bytes, str
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def _bytes_to_ascii(val: bytes) -> str:
|
| 227 |
+
return val.decode("ascii", "backslashreplace")
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def ascii_escaped(val: bytes | str) -> str:
|
| 231 |
+
r"""If val is pure ASCII, return it as an str, otherwise, escape
|
| 232 |
+
bytes objects into a sequence of escaped bytes:
|
| 233 |
+
|
| 234 |
+
b'\xc3\xb4\xc5\xd6' -> r'\xc3\xb4\xc5\xd6'
|
| 235 |
+
|
| 236 |
+
and escapes unicode objects into a sequence of escaped unicode
|
| 237 |
+
ids, e.g.:
|
| 238 |
+
|
| 239 |
+
r'4\nV\U00043efa\x0eMXWB\x1e\u3028\u15fd\xcd\U0007d944'
|
| 240 |
+
|
| 241 |
+
Note:
|
| 242 |
+
The obvious "v.decode('unicode-escape')" will return
|
| 243 |
+
valid UTF-8 unicode if it finds them in bytes, but we
|
| 244 |
+
want to return escaped bytes for any byte, even if they match
|
| 245 |
+
a UTF-8 string.
|
| 246 |
+
"""
|
| 247 |
+
if isinstance(val, bytes):
|
| 248 |
+
ret = _bytes_to_ascii(val)
|
| 249 |
+
else:
|
| 250 |
+
ret = val.encode("unicode_escape").decode("ascii")
|
| 251 |
+
return _translate_non_printable(ret)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
@dataclasses.dataclass
|
| 255 |
+
class _PytestWrapper:
|
| 256 |
+
"""Dummy wrapper around a function object for internal use only.
|
| 257 |
+
|
| 258 |
+
Used to correctly unwrap the underlying function object when we are
|
| 259 |
+
creating fixtures, because we wrap the function object ourselves with a
|
| 260 |
+
decorator to issue warnings when the fixture function is called directly.
|
| 261 |
+
"""
|
| 262 |
+
|
| 263 |
+
obj: Any
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def get_real_func(obj):
|
| 267 |
+
"""Get the real function object of the (possibly) wrapped object by
|
| 268 |
+
functools.wraps or functools.partial."""
|
| 269 |
+
start_obj = obj
|
| 270 |
+
for i in range(100):
|
| 271 |
+
# __pytest_wrapped__ is set by @pytest.fixture when wrapping the fixture function
|
| 272 |
+
# to trigger a warning if it gets called directly instead of by pytest: we don't
|
| 273 |
+
# want to unwrap further than this otherwise we lose useful wrappings like @mock.patch (#3774)
|
| 274 |
+
new_obj = getattr(obj, "__pytest_wrapped__", None)
|
| 275 |
+
if isinstance(new_obj, _PytestWrapper):
|
| 276 |
+
obj = new_obj.obj
|
| 277 |
+
break
|
| 278 |
+
new_obj = getattr(obj, "__wrapped__", None)
|
| 279 |
+
if new_obj is None:
|
| 280 |
+
break
|
| 281 |
+
obj = new_obj
|
| 282 |
+
else:
|
| 283 |
+
from _pytest._io.saferepr import saferepr
|
| 284 |
+
|
| 285 |
+
raise ValueError(
|
| 286 |
+
("could not find real function of {start}\nstopped at {current}").format(
|
| 287 |
+
start=saferepr(start_obj), current=saferepr(obj)
|
| 288 |
+
)
|
| 289 |
+
)
|
| 290 |
+
if isinstance(obj, functools.partial):
|
| 291 |
+
obj = obj.func
|
| 292 |
+
return obj
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def get_real_method(obj, holder):
|
| 296 |
+
"""Attempt to obtain the real function object that might be wrapping
|
| 297 |
+
``obj``, while at the same time returning a bound method to ``holder`` if
|
| 298 |
+
the original object was a bound method."""
|
| 299 |
+
try:
|
| 300 |
+
is_method = hasattr(obj, "__func__")
|
| 301 |
+
obj = get_real_func(obj)
|
| 302 |
+
except Exception: # pragma: no cover
|
| 303 |
+
return obj
|
| 304 |
+
if is_method and hasattr(obj, "__get__") and callable(obj.__get__):
|
| 305 |
+
obj = obj.__get__(holder)
|
| 306 |
+
return obj
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def getimfunc(func):
|
| 310 |
+
try:
|
| 311 |
+
return func.__func__
|
| 312 |
+
except AttributeError:
|
| 313 |
+
return func
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def safe_getattr(object: Any, name: str, default: Any) -> Any:
|
| 317 |
+
"""Like getattr but return default upon any Exception or any OutcomeException.
|
| 318 |
+
|
| 319 |
+
Attribute access can potentially fail for 'evil' Python objects.
|
| 320 |
+
See issue #214.
|
| 321 |
+
It catches OutcomeException because of #2490 (issue #580), new outcomes
|
| 322 |
+
are derived from BaseException instead of Exception (for more details
|
| 323 |
+
check #2707).
|
| 324 |
+
"""
|
| 325 |
+
from _pytest.outcomes import TEST_OUTCOME
|
| 326 |
+
|
| 327 |
+
try:
|
| 328 |
+
return getattr(object, name, default)
|
| 329 |
+
except TEST_OUTCOME:
|
| 330 |
+
return default
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def safe_isclass(obj: object) -> bool:
|
| 334 |
+
"""Ignore any exception via isinstance on Python 3."""
|
| 335 |
+
try:
|
| 336 |
+
return inspect.isclass(obj)
|
| 337 |
+
except Exception:
|
| 338 |
+
return False
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
if TYPE_CHECKING:
|
| 342 |
+
if sys.version_info >= (3, 8):
|
| 343 |
+
from typing import final as final
|
| 344 |
+
else:
|
| 345 |
+
from typing_extensions import final as final
|
| 346 |
+
elif sys.version_info >= (3, 8):
|
| 347 |
+
from typing import final as final
|
| 348 |
+
else:
|
| 349 |
+
|
| 350 |
+
def final(f):
|
| 351 |
+
return f
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
if sys.version_info >= (3, 8):
|
| 355 |
+
from functools import cached_property as cached_property
|
| 356 |
+
else:
|
| 357 |
+
|
| 358 |
+
class cached_property(Generic[_S, _T]):
|
| 359 |
+
__slots__ = ("func", "__doc__")
|
| 360 |
+
|
| 361 |
+
def __init__(self, func: Callable[[_S], _T]) -> None:
|
| 362 |
+
self.func = func
|
| 363 |
+
self.__doc__ = func.__doc__
|
| 364 |
+
|
| 365 |
+
@overload
|
| 366 |
+
def __get__(
|
| 367 |
+
self, instance: None, owner: type[_S] | None = ...
|
| 368 |
+
) -> cached_property[_S, _T]:
|
| 369 |
+
...
|
| 370 |
+
|
| 371 |
+
@overload
|
| 372 |
+
def __get__(self, instance: _S, owner: type[_S] | None = ...) -> _T:
|
| 373 |
+
...
|
| 374 |
+
|
| 375 |
+
def __get__(self, instance, owner=None):
|
| 376 |
+
if instance is None:
|
| 377 |
+
return self
|
| 378 |
+
value = instance.__dict__[self.func.__name__] = self.func(instance)
|
| 379 |
+
return value
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def get_user_id() -> int | None:
|
| 383 |
+
"""Return the current user id, or None if we cannot get it reliably on the current platform."""
|
| 384 |
+
# win32 does not have a getuid() function.
|
| 385 |
+
# On Emscripten, getuid() is a stub that always returns 0.
|
| 386 |
+
if sys.platform in ("win32", "emscripten"):
|
| 387 |
+
return None
|
| 388 |
+
# getuid shouldn't fail, but cpython defines such a case.
|
| 389 |
+
# Let's hope for the best.
|
| 390 |
+
uid = os.getuid()
|
| 391 |
+
return uid if uid != -1 else None
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
# Perform exhaustiveness checking.
|
| 395 |
+
#
|
| 396 |
+
# Consider this example:
|
| 397 |
+
#
|
| 398 |
+
# MyUnion = Union[int, str]
|
| 399 |
+
#
|
| 400 |
+
# def handle(x: MyUnion) -> int {
|
| 401 |
+
# if isinstance(x, int):
|
| 402 |
+
# return 1
|
| 403 |
+
# elif isinstance(x, str):
|
| 404 |
+
# return 2
|
| 405 |
+
# else:
|
| 406 |
+
# raise Exception('unreachable')
|
| 407 |
+
#
|
| 408 |
+
# Now suppose we add a new variant:
|
| 409 |
+
#
|
| 410 |
+
# MyUnion = Union[int, str, bytes]
|
| 411 |
+
#
|
| 412 |
+
# After doing this, we must remember ourselves to go and update the handle
|
| 413 |
+
# function to handle the new variant.
|
| 414 |
+
#
|
| 415 |
+
# With `assert_never` we can do better:
|
| 416 |
+
#
|
| 417 |
+
# // raise Exception('unreachable')
|
| 418 |
+
# return assert_never(x)
|
| 419 |
+
#
|
| 420 |
+
# Now, if we forget to handle the new variant, the type-checker will emit a
|
| 421 |
+
# compile-time error, instead of the runtime error we would have gotten
|
| 422 |
+
# previously.
|
| 423 |
+
#
|
| 424 |
+
# This also work for Enums (if you use `is` to compare) and Literals.
|
| 425 |
+
def assert_never(value: NoReturn) -> NoReturn:
|
| 426 |
+
assert False, f"Unhandled value: {value} ({type(value).__name__})"
|
wemm/lib/python3.10/site-packages/_pytest/config/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (48.2 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/_pytest/config/__pycache__/argparsing.cpython-310.pyc
ADDED
|
Binary file (18.2 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/_pytest/config/__pycache__/exceptions.cpython-310.pyc
ADDED
|
Binary file (657 Bytes). View file
|
|
|
wemm/lib/python3.10/site-packages/_pytest/config/__pycache__/findpaths.cpython-310.pyc
ADDED
|
Binary file (6.34 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/_pytest/config/compat.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
import warnings
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
from ..compat import LEGACY_PATH
|
| 7 |
+
from ..compat import legacy_path
|
| 8 |
+
from ..deprecated import HOOK_LEGACY_PATH_ARG
|
| 9 |
+
from _pytest.nodes import _check_path
|
| 10 |
+
|
| 11 |
+
# hookname: (Path, LEGACY_PATH)
|
| 12 |
+
imply_paths_hooks = {
|
| 13 |
+
"pytest_ignore_collect": ("collection_path", "path"),
|
| 14 |
+
"pytest_collect_file": ("file_path", "path"),
|
| 15 |
+
"pytest_pycollect_makemodule": ("module_path", "path"),
|
| 16 |
+
"pytest_report_header": ("start_path", "startdir"),
|
| 17 |
+
"pytest_report_collectionfinish": ("start_path", "startdir"),
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class PathAwareHookProxy:
|
| 22 |
+
"""
|
| 23 |
+
this helper wraps around hook callers
|
| 24 |
+
until pluggy supports fixingcalls, this one will do
|
| 25 |
+
|
| 26 |
+
it currently doesn't return full hook caller proxies for fixed hooks,
|
| 27 |
+
this may have to be changed later depending on bugs
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
def __init__(self, hook_caller):
|
| 31 |
+
self.__hook_caller = hook_caller
|
| 32 |
+
|
| 33 |
+
def __dir__(self):
|
| 34 |
+
return dir(self.__hook_caller)
|
| 35 |
+
|
| 36 |
+
def __getattr__(self, key, _wraps=functools.wraps):
|
| 37 |
+
hook = getattr(self.__hook_caller, key)
|
| 38 |
+
if key not in imply_paths_hooks:
|
| 39 |
+
self.__dict__[key] = hook
|
| 40 |
+
return hook
|
| 41 |
+
else:
|
| 42 |
+
path_var, fspath_var = imply_paths_hooks[key]
|
| 43 |
+
|
| 44 |
+
@_wraps(hook)
|
| 45 |
+
def fixed_hook(**kw):
|
| 46 |
+
path_value: Optional[Path] = kw.pop(path_var, None)
|
| 47 |
+
fspath_value: Optional[LEGACY_PATH] = kw.pop(fspath_var, None)
|
| 48 |
+
if fspath_value is not None:
|
| 49 |
+
warnings.warn(
|
| 50 |
+
HOOK_LEGACY_PATH_ARG.format(
|
| 51 |
+
pylib_path_arg=fspath_var, pathlib_path_arg=path_var
|
| 52 |
+
),
|
| 53 |
+
stacklevel=2,
|
| 54 |
+
)
|
| 55 |
+
if path_value is not None:
|
| 56 |
+
if fspath_value is not None:
|
| 57 |
+
_check_path(path_value, fspath_value)
|
| 58 |
+
else:
|
| 59 |
+
fspath_value = legacy_path(path_value)
|
| 60 |
+
else:
|
| 61 |
+
assert fspath_value is not None
|
| 62 |
+
path_value = Path(fspath_value)
|
| 63 |
+
|
| 64 |
+
kw[path_var] = path_value
|
| 65 |
+
kw[fspath_var] = fspath_value
|
| 66 |
+
return hook(**kw)
|
| 67 |
+
|
| 68 |
+
fixed_hook.__name__ = key
|
| 69 |
+
self.__dict__[key] = fixed_hook
|
| 70 |
+
return fixed_hook
|
wemm/lib/python3.10/site-packages/_pytest/config/exceptions.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from _pytest.compat import final
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
@final
|
| 5 |
+
class UsageError(Exception):
|
| 6 |
+
"""Error in pytest usage or invocation."""
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class PrintHelp(Exception):
|
| 10 |
+
"""Raised when pytest should print its help to skip the rest of the
|
| 11 |
+
argument parsing and validation."""
|
wemm/lib/python3.10/site-packages/_pytest/deprecated.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deprecation messages and bits of code used elsewhere in the codebase that
|
| 2 |
+
is planned to be removed in the next pytest release.
|
| 3 |
+
|
| 4 |
+
Keeping it in a central location makes it easy to track what is deprecated and should
|
| 5 |
+
be removed when the time comes.
|
| 6 |
+
|
| 7 |
+
All constants defined in this module should be either instances of
|
| 8 |
+
:class:`PytestWarning`, or :class:`UnformattedWarning`
|
| 9 |
+
in case of warnings which need to format their messages.
|
| 10 |
+
"""
|
| 11 |
+
from warnings import warn
|
| 12 |
+
|
| 13 |
+
from _pytest.warning_types import PytestDeprecationWarning
|
| 14 |
+
from _pytest.warning_types import PytestRemovedIn8Warning
|
| 15 |
+
from _pytest.warning_types import UnformattedWarning
|
| 16 |
+
|
| 17 |
+
# set of plugins which have been integrated into the core; we use this list to ignore
|
| 18 |
+
# them during registration to avoid conflicts
|
| 19 |
+
DEPRECATED_EXTERNAL_PLUGINS = {
|
| 20 |
+
"pytest_catchlog",
|
| 21 |
+
"pytest_capturelog",
|
| 22 |
+
"pytest_faulthandler",
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
NOSE_SUPPORT = UnformattedWarning(
|
| 26 |
+
PytestRemovedIn8Warning,
|
| 27 |
+
"Support for nose tests is deprecated and will be removed in a future release.\n"
|
| 28 |
+
"{nodeid} is using nose method: `{method}` ({stage})\n"
|
| 29 |
+
"See docs: https://docs.pytest.org/en/stable/deprecations.html#support-for-tests-written-for-nose",
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
NOSE_SUPPORT_METHOD = UnformattedWarning(
|
| 33 |
+
PytestRemovedIn8Warning,
|
| 34 |
+
"Support for nose tests is deprecated and will be removed in a future release.\n"
|
| 35 |
+
"{nodeid} is using nose-specific method: `{method}(self)`\n"
|
| 36 |
+
"To remove this warning, rename it to `{method}_method(self)`\n"
|
| 37 |
+
"See docs: https://docs.pytest.org/en/stable/deprecations.html#support-for-tests-written-for-nose",
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# This can be* removed pytest 8, but it's harmless and common, so no rush to remove.
|
| 42 |
+
# * If you're in the future: "could have been".
|
| 43 |
+
YIELD_FIXTURE = PytestDeprecationWarning(
|
| 44 |
+
"@pytest.yield_fixture is deprecated.\n"
|
| 45 |
+
"Use @pytest.fixture instead; they are the same."
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
WARNING_CMDLINE_PREPARSE_HOOK = PytestRemovedIn8Warning(
|
| 49 |
+
"The pytest_cmdline_preparse hook is deprecated and will be removed in a future release. \n"
|
| 50 |
+
"Please use pytest_load_initial_conftests hook instead."
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
FSCOLLECTOR_GETHOOKPROXY_ISINITPATH = PytestRemovedIn8Warning(
|
| 54 |
+
"The gethookproxy() and isinitpath() methods of FSCollector and Package are deprecated; "
|
| 55 |
+
"use self.session.gethookproxy() and self.session.isinitpath() instead. "
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
STRICT_OPTION = PytestRemovedIn8Warning(
|
| 59 |
+
"The --strict option is deprecated, use --strict-markers instead."
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
# This deprecation is never really meant to be removed.
|
| 63 |
+
PRIVATE = PytestDeprecationWarning("A private pytest class or function was used.")
|
| 64 |
+
|
| 65 |
+
ARGUMENT_PERCENT_DEFAULT = PytestRemovedIn8Warning(
|
| 66 |
+
'pytest now uses argparse. "%default" should be changed to "%(default)s"',
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
ARGUMENT_TYPE_STR_CHOICE = UnformattedWarning(
|
| 70 |
+
PytestRemovedIn8Warning,
|
| 71 |
+
"`type` argument to addoption() is the string {typ!r}."
|
| 72 |
+
" For choices this is optional and can be omitted, "
|
| 73 |
+
" but when supplied should be a type (for example `str` or `int`)."
|
| 74 |
+
" (options: {names})",
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
ARGUMENT_TYPE_STR = UnformattedWarning(
|
| 78 |
+
PytestRemovedIn8Warning,
|
| 79 |
+
"`type` argument to addoption() is the string {typ!r}, "
|
| 80 |
+
" but when supplied should be a type (for example `str` or `int`)."
|
| 81 |
+
" (options: {names})",
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
HOOK_LEGACY_PATH_ARG = UnformattedWarning(
|
| 86 |
+
PytestRemovedIn8Warning,
|
| 87 |
+
"The ({pylib_path_arg}: py.path.local) argument is deprecated, please use ({pathlib_path_arg}: pathlib.Path)\n"
|
| 88 |
+
"see https://docs.pytest.org/en/latest/deprecations.html"
|
| 89 |
+
"#py-path-local-arguments-for-hooks-replaced-with-pathlib-path",
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
NODE_CTOR_FSPATH_ARG = UnformattedWarning(
|
| 93 |
+
PytestRemovedIn8Warning,
|
| 94 |
+
"The (fspath: py.path.local) argument to {node_type_name} is deprecated. "
|
| 95 |
+
"Please use the (path: pathlib.Path) argument instead.\n"
|
| 96 |
+
"See https://docs.pytest.org/en/latest/deprecations.html"
|
| 97 |
+
"#fspath-argument-for-node-constructors-replaced-with-pathlib-path",
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
WARNS_NONE_ARG = PytestRemovedIn8Warning(
|
| 101 |
+
"Passing None has been deprecated.\n"
|
| 102 |
+
"See https://docs.pytest.org/en/latest/how-to/capture-warnings.html"
|
| 103 |
+
"#additional-use-cases-of-warnings-in-tests"
|
| 104 |
+
" for alternatives in common use cases."
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
KEYWORD_MSG_ARG = UnformattedWarning(
|
| 108 |
+
PytestRemovedIn8Warning,
|
| 109 |
+
"pytest.{func}(msg=...) is now deprecated, use pytest.{func}(reason=...) instead",
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
INSTANCE_COLLECTOR = PytestRemovedIn8Warning(
|
| 113 |
+
"The pytest.Instance collector type is deprecated and is no longer used. "
|
| 114 |
+
"See https://docs.pytest.org/en/latest/deprecations.html#the-pytest-instance-collector",
|
| 115 |
+
)
|
| 116 |
+
HOOK_LEGACY_MARKING = UnformattedWarning(
|
| 117 |
+
PytestDeprecationWarning,
|
| 118 |
+
"The hook{type} {fullname} uses old-style configuration options (marks or attributes).\n"
|
| 119 |
+
"Please use the pytest.hook{type}({hook_opts}) decorator instead\n"
|
| 120 |
+
" to configure the hooks.\n"
|
| 121 |
+
" See https://docs.pytest.org/en/latest/deprecations.html"
|
| 122 |
+
"#configuring-hook-specs-impls-using-markers",
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
# You want to make some `__init__` or function "private".
|
| 126 |
+
#
|
| 127 |
+
# def my_private_function(some, args):
|
| 128 |
+
# ...
|
| 129 |
+
#
|
| 130 |
+
# Do this:
|
| 131 |
+
#
|
| 132 |
+
# def my_private_function(some, args, *, _ispytest: bool = False):
|
| 133 |
+
# check_ispytest(_ispytest)
|
| 134 |
+
# ...
|
| 135 |
+
#
|
| 136 |
+
# Change all internal/allowed calls to
|
| 137 |
+
#
|
| 138 |
+
# my_private_function(some, args, _ispytest=True)
|
| 139 |
+
#
|
| 140 |
+
# All other calls will get the default _ispytest=False and trigger
|
| 141 |
+
# the warning (possibly error in the future).
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def check_ispytest(ispytest: bool) -> None:
|
| 145 |
+
if not ispytest:
|
| 146 |
+
warn(PRIVATE, stacklevel=3)
|
wemm/lib/python3.10/site-packages/_pytest/faulthandler.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
from typing import Generator
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
from _pytest.config import Config
|
| 8 |
+
from _pytest.config.argparsing import Parser
|
| 9 |
+
from _pytest.nodes import Item
|
| 10 |
+
from _pytest.stash import StashKey
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
fault_handler_stderr_fd_key = StashKey[int]()
|
| 14 |
+
fault_handler_originally_enabled_key = StashKey[bool]()
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def pytest_addoption(parser: Parser) -> None:
|
| 18 |
+
help = (
|
| 19 |
+
"Dump the traceback of all threads if a test takes "
|
| 20 |
+
"more than TIMEOUT seconds to finish"
|
| 21 |
+
)
|
| 22 |
+
parser.addini("faulthandler_timeout", help, default=0.0)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def pytest_configure(config: Config) -> None:
|
| 26 |
+
import faulthandler
|
| 27 |
+
|
| 28 |
+
config.stash[fault_handler_stderr_fd_key] = os.dup(get_stderr_fileno())
|
| 29 |
+
config.stash[fault_handler_originally_enabled_key] = faulthandler.is_enabled()
|
| 30 |
+
faulthandler.enable(file=config.stash[fault_handler_stderr_fd_key])
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def pytest_unconfigure(config: Config) -> None:
|
| 34 |
+
import faulthandler
|
| 35 |
+
|
| 36 |
+
faulthandler.disable()
|
| 37 |
+
# Close the dup file installed during pytest_configure.
|
| 38 |
+
if fault_handler_stderr_fd_key in config.stash:
|
| 39 |
+
os.close(config.stash[fault_handler_stderr_fd_key])
|
| 40 |
+
del config.stash[fault_handler_stderr_fd_key]
|
| 41 |
+
if config.stash.get(fault_handler_originally_enabled_key, False):
|
| 42 |
+
# Re-enable the faulthandler if it was originally enabled.
|
| 43 |
+
faulthandler.enable(file=get_stderr_fileno())
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def get_stderr_fileno() -> int:
|
| 47 |
+
try:
|
| 48 |
+
fileno = sys.stderr.fileno()
|
| 49 |
+
# The Twisted Logger will return an invalid file descriptor since it is not backed
|
| 50 |
+
# by an FD. So, let's also forward this to the same code path as with pytest-xdist.
|
| 51 |
+
if fileno == -1:
|
| 52 |
+
raise AttributeError()
|
| 53 |
+
return fileno
|
| 54 |
+
except (AttributeError, io.UnsupportedOperation):
|
| 55 |
+
# pytest-xdist monkeypatches sys.stderr with an object that is not an actual file.
|
| 56 |
+
# https://docs.python.org/3/library/faulthandler.html#issue-with-file-descriptors
|
| 57 |
+
# This is potentially dangerous, but the best we can do.
|
| 58 |
+
return sys.__stderr__.fileno()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def get_timeout_config_value(config: Config) -> float:
|
| 62 |
+
return float(config.getini("faulthandler_timeout") or 0.0)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@pytest.hookimpl(hookwrapper=True, trylast=True)
|
| 66 |
+
def pytest_runtest_protocol(item: Item) -> Generator[None, None, None]:
|
| 67 |
+
timeout = get_timeout_config_value(item.config)
|
| 68 |
+
if timeout > 0:
|
| 69 |
+
import faulthandler
|
| 70 |
+
|
| 71 |
+
stderr = item.config.stash[fault_handler_stderr_fd_key]
|
| 72 |
+
faulthandler.dump_traceback_later(timeout, file=stderr)
|
| 73 |
+
try:
|
| 74 |
+
yield
|
| 75 |
+
finally:
|
| 76 |
+
faulthandler.cancel_dump_traceback_later()
|
| 77 |
+
else:
|
| 78 |
+
yield
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@pytest.hookimpl(tryfirst=True)
|
| 82 |
+
def pytest_enter_pdb() -> None:
|
| 83 |
+
"""Cancel any traceback dumping due to timeout before entering pdb."""
|
| 84 |
+
import faulthandler
|
| 85 |
+
|
| 86 |
+
faulthandler.cancel_dump_traceback_later()
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@pytest.hookimpl(tryfirst=True)
|
| 90 |
+
def pytest_exception_interact() -> None:
|
| 91 |
+
"""Cancel any traceback dumping due to an interactive exception being
|
| 92 |
+
raised."""
|
| 93 |
+
import faulthandler
|
| 94 |
+
|
| 95 |
+
faulthandler.cancel_dump_traceback_later()
|
wemm/lib/python3.10/site-packages/_pytest/freeze_support.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Provides a function to report all internal modules for using freezing
|
| 2 |
+
tools."""
|
| 3 |
+
import types
|
| 4 |
+
from typing import Iterator
|
| 5 |
+
from typing import List
|
| 6 |
+
from typing import Union
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def freeze_includes() -> List[str]:
|
| 10 |
+
"""Return a list of module names used by pytest that should be
|
| 11 |
+
included by cx_freeze."""
|
| 12 |
+
import _pytest
|
| 13 |
+
|
| 14 |
+
result = list(_iter_all_modules(_pytest))
|
| 15 |
+
return result
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _iter_all_modules(
|
| 19 |
+
package: Union[str, types.ModuleType],
|
| 20 |
+
prefix: str = "",
|
| 21 |
+
) -> Iterator[str]:
|
| 22 |
+
"""Iterate over the names of all modules that can be found in the given
|
| 23 |
+
package, recursively.
|
| 24 |
+
|
| 25 |
+
>>> import _pytest
|
| 26 |
+
>>> list(_iter_all_modules(_pytest))
|
| 27 |
+
['_pytest._argcomplete', '_pytest._code.code', ...]
|
| 28 |
+
"""
|
| 29 |
+
import os
|
| 30 |
+
import pkgutil
|
| 31 |
+
|
| 32 |
+
if isinstance(package, str):
|
| 33 |
+
path = package
|
| 34 |
+
else:
|
| 35 |
+
# Type ignored because typeshed doesn't define ModuleType.__path__
|
| 36 |
+
# (only defined on packages).
|
| 37 |
+
package_path = package.__path__ # type: ignore[attr-defined]
|
| 38 |
+
path, prefix = package_path[0], package.__name__ + "."
|
| 39 |
+
for _, name, is_package in pkgutil.iter_modules([path]):
|
| 40 |
+
if is_package:
|
| 41 |
+
for m in _iter_all_modules(os.path.join(path, name), prefix=name + "."):
|
| 42 |
+
yield prefix + m
|
| 43 |
+
else:
|
| 44 |
+
yield prefix + name
|
wemm/lib/python3.10/site-packages/_pytest/helpconfig.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Version info, help messages, tracing configuration."""
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
from argparse import Action
|
| 5 |
+
from typing import List
|
| 6 |
+
from typing import Optional
|
| 7 |
+
from typing import Union
|
| 8 |
+
|
| 9 |
+
import pytest
|
| 10 |
+
from _pytest.config import Config
|
| 11 |
+
from _pytest.config import ExitCode
|
| 12 |
+
from _pytest.config import PrintHelp
|
| 13 |
+
from _pytest.config.argparsing import Parser
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class HelpAction(Action):
|
| 17 |
+
"""An argparse Action that will raise an exception in order to skip the
|
| 18 |
+
rest of the argument parsing when --help is passed.
|
| 19 |
+
|
| 20 |
+
This prevents argparse from quitting due to missing required arguments
|
| 21 |
+
when any are defined, for example by ``pytest_addoption``.
|
| 22 |
+
This is similar to the way that the builtin argparse --help option is
|
| 23 |
+
implemented by raising SystemExit.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(self, option_strings, dest=None, default=False, help=None):
|
| 27 |
+
super().__init__(
|
| 28 |
+
option_strings=option_strings,
|
| 29 |
+
dest=dest,
|
| 30 |
+
const=True,
|
| 31 |
+
default=default,
|
| 32 |
+
nargs=0,
|
| 33 |
+
help=help,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
def __call__(self, parser, namespace, values, option_string=None):
|
| 37 |
+
setattr(namespace, self.dest, self.const)
|
| 38 |
+
|
| 39 |
+
# We should only skip the rest of the parsing after preparse is done.
|
| 40 |
+
if getattr(parser._parser, "after_preparse", False):
|
| 41 |
+
raise PrintHelp
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def pytest_addoption(parser: Parser) -> None:
|
| 45 |
+
group = parser.getgroup("debugconfig")
|
| 46 |
+
group.addoption(
|
| 47 |
+
"--version",
|
| 48 |
+
"-V",
|
| 49 |
+
action="count",
|
| 50 |
+
default=0,
|
| 51 |
+
dest="version",
|
| 52 |
+
help="Display pytest version and information about plugins. "
|
| 53 |
+
"When given twice, also display information about plugins.",
|
| 54 |
+
)
|
| 55 |
+
group._addoption(
|
| 56 |
+
"-h",
|
| 57 |
+
"--help",
|
| 58 |
+
action=HelpAction,
|
| 59 |
+
dest="help",
|
| 60 |
+
help="Show help message and configuration info",
|
| 61 |
+
)
|
| 62 |
+
group._addoption(
|
| 63 |
+
"-p",
|
| 64 |
+
action="append",
|
| 65 |
+
dest="plugins",
|
| 66 |
+
default=[],
|
| 67 |
+
metavar="name",
|
| 68 |
+
help="Early-load given plugin module name or entry point (multi-allowed). "
|
| 69 |
+
"To avoid loading of plugins, use the `no:` prefix, e.g. "
|
| 70 |
+
"`no:doctest`.",
|
| 71 |
+
)
|
| 72 |
+
group.addoption(
|
| 73 |
+
"--traceconfig",
|
| 74 |
+
"--trace-config",
|
| 75 |
+
action="store_true",
|
| 76 |
+
default=False,
|
| 77 |
+
help="Trace considerations of conftest.py files",
|
| 78 |
+
)
|
| 79 |
+
group.addoption(
|
| 80 |
+
"--debug",
|
| 81 |
+
action="store",
|
| 82 |
+
nargs="?",
|
| 83 |
+
const="pytestdebug.log",
|
| 84 |
+
dest="debug",
|
| 85 |
+
metavar="DEBUG_FILE_NAME",
|
| 86 |
+
help="Store internal tracing debug information in this log file. "
|
| 87 |
+
"This file is opened with 'w' and truncated as a result, care advised. "
|
| 88 |
+
"Default: pytestdebug.log.",
|
| 89 |
+
)
|
| 90 |
+
group._addoption(
|
| 91 |
+
"-o",
|
| 92 |
+
"--override-ini",
|
| 93 |
+
dest="override_ini",
|
| 94 |
+
action="append",
|
| 95 |
+
help='Override ini option with "option=value" style, '
|
| 96 |
+
"e.g. `-o xfail_strict=True -o cache_dir=cache`.",
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@pytest.hookimpl(hookwrapper=True)
|
| 101 |
+
def pytest_cmdline_parse():
|
| 102 |
+
outcome = yield
|
| 103 |
+
config: Config = outcome.get_result()
|
| 104 |
+
|
| 105 |
+
if config.option.debug:
|
| 106 |
+
# --debug | --debug <file.log> was provided.
|
| 107 |
+
path = config.option.debug
|
| 108 |
+
debugfile = open(path, "w", encoding="utf-8")
|
| 109 |
+
debugfile.write(
|
| 110 |
+
"versions pytest-%s, "
|
| 111 |
+
"python-%s\ncwd=%s\nargs=%s\n\n"
|
| 112 |
+
% (
|
| 113 |
+
pytest.__version__,
|
| 114 |
+
".".join(map(str, sys.version_info)),
|
| 115 |
+
os.getcwd(),
|
| 116 |
+
config.invocation_params.args,
|
| 117 |
+
)
|
| 118 |
+
)
|
| 119 |
+
config.trace.root.setwriter(debugfile.write)
|
| 120 |
+
undo_tracing = config.pluginmanager.enable_tracing()
|
| 121 |
+
sys.stderr.write("writing pytest debug information to %s\n" % path)
|
| 122 |
+
|
| 123 |
+
def unset_tracing() -> None:
|
| 124 |
+
debugfile.close()
|
| 125 |
+
sys.stderr.write("wrote pytest debug information to %s\n" % debugfile.name)
|
| 126 |
+
config.trace.root.setwriter(None)
|
| 127 |
+
undo_tracing()
|
| 128 |
+
|
| 129 |
+
config.add_cleanup(unset_tracing)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def showversion(config: Config) -> None:
|
| 133 |
+
if config.option.version > 1:
|
| 134 |
+
sys.stdout.write(
|
| 135 |
+
"This is pytest version {}, imported from {}\n".format(
|
| 136 |
+
pytest.__version__, pytest.__file__
|
| 137 |
+
)
|
| 138 |
+
)
|
| 139 |
+
plugininfo = getpluginversioninfo(config)
|
| 140 |
+
if plugininfo:
|
| 141 |
+
for line in plugininfo:
|
| 142 |
+
sys.stdout.write(line + "\n")
|
| 143 |
+
else:
|
| 144 |
+
sys.stdout.write(f"pytest {pytest.__version__}\n")
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def pytest_cmdline_main(config: Config) -> Optional[Union[int, ExitCode]]:
|
| 148 |
+
if config.option.version > 0:
|
| 149 |
+
showversion(config)
|
| 150 |
+
return 0
|
| 151 |
+
elif config.option.help:
|
| 152 |
+
config._do_configure()
|
| 153 |
+
showhelp(config)
|
| 154 |
+
config._ensure_unconfigure()
|
| 155 |
+
return 0
|
| 156 |
+
return None
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def showhelp(config: Config) -> None:
|
| 160 |
+
import textwrap
|
| 161 |
+
|
| 162 |
+
reporter = config.pluginmanager.get_plugin("terminalreporter")
|
| 163 |
+
tw = reporter._tw
|
| 164 |
+
tw.write(config._parser.optparser.format_help())
|
| 165 |
+
tw.line()
|
| 166 |
+
tw.line(
|
| 167 |
+
"[pytest] ini-options in the first "
|
| 168 |
+
"pytest.ini|tox.ini|setup.cfg|pyproject.toml file found:"
|
| 169 |
+
)
|
| 170 |
+
tw.line()
|
| 171 |
+
|
| 172 |
+
columns = tw.fullwidth # costly call
|
| 173 |
+
indent_len = 24 # based on argparse's max_help_position=24
|
| 174 |
+
indent = " " * indent_len
|
| 175 |
+
for name in config._parser._ininames:
|
| 176 |
+
help, type, default = config._parser._inidict[name]
|
| 177 |
+
if type is None:
|
| 178 |
+
type = "string"
|
| 179 |
+
if help is None:
|
| 180 |
+
raise TypeError(f"help argument cannot be None for {name}")
|
| 181 |
+
spec = f"{name} ({type}):"
|
| 182 |
+
tw.write(" %s" % spec)
|
| 183 |
+
spec_len = len(spec)
|
| 184 |
+
if spec_len > (indent_len - 3):
|
| 185 |
+
# Display help starting at a new line.
|
| 186 |
+
tw.line()
|
| 187 |
+
helplines = textwrap.wrap(
|
| 188 |
+
help,
|
| 189 |
+
columns,
|
| 190 |
+
initial_indent=indent,
|
| 191 |
+
subsequent_indent=indent,
|
| 192 |
+
break_on_hyphens=False,
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
for line in helplines:
|
| 196 |
+
tw.line(line)
|
| 197 |
+
else:
|
| 198 |
+
# Display help starting after the spec, following lines indented.
|
| 199 |
+
tw.write(" " * (indent_len - spec_len - 2))
|
| 200 |
+
wrapped = textwrap.wrap(help, columns - indent_len, break_on_hyphens=False)
|
| 201 |
+
|
| 202 |
+
if wrapped:
|
| 203 |
+
tw.line(wrapped[0])
|
| 204 |
+
for line in wrapped[1:]:
|
| 205 |
+
tw.line(indent + line)
|
| 206 |
+
|
| 207 |
+
tw.line()
|
| 208 |
+
tw.line("Environment variables:")
|
| 209 |
+
vars = [
|
| 210 |
+
("PYTEST_ADDOPTS", "Extra command line options"),
|
| 211 |
+
("PYTEST_PLUGINS", "Comma-separated plugins to load during startup"),
|
| 212 |
+
("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "Set to disable plugin auto-loading"),
|
| 213 |
+
("PYTEST_DEBUG", "Set to enable debug tracing of pytest's internals"),
|
| 214 |
+
]
|
| 215 |
+
for name, help in vars:
|
| 216 |
+
tw.line(f" {name:<24} {help}")
|
| 217 |
+
tw.line()
|
| 218 |
+
tw.line()
|
| 219 |
+
|
| 220 |
+
tw.line("to see available markers type: pytest --markers")
|
| 221 |
+
tw.line("to see available fixtures type: pytest --fixtures")
|
| 222 |
+
tw.line(
|
| 223 |
+
"(shown according to specified file_or_dir or current dir "
|
| 224 |
+
"if not specified; fixtures with leading '_' are only shown "
|
| 225 |
+
"with the '-v' option"
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
for warningreport in reporter.stats.get("warnings", []):
|
| 229 |
+
tw.line("warning : " + warningreport.message, red=True)
|
| 230 |
+
return
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
conftest_options = [("pytest_plugins", "list of plugin names to load")]
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def getpluginversioninfo(config: Config) -> List[str]:
|
| 237 |
+
lines = []
|
| 238 |
+
plugininfo = config.pluginmanager.list_plugin_distinfo()
|
| 239 |
+
if plugininfo:
|
| 240 |
+
lines.append("setuptools registered plugins:")
|
| 241 |
+
for plugin, dist in plugininfo:
|
| 242 |
+
loc = getattr(plugin, "__file__", repr(plugin))
|
| 243 |
+
content = f"{dist.project_name}-{dist.version} at {loc}"
|
| 244 |
+
lines.append(" " + content)
|
| 245 |
+
return lines
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def pytest_report_header(config: Config) -> List[str]:
|
| 249 |
+
lines = []
|
| 250 |
+
if config.option.debug or config.option.traceconfig:
|
| 251 |
+
lines.append(f"using: pytest-{pytest.__version__}")
|
| 252 |
+
|
| 253 |
+
verinfo = getpluginversioninfo(config)
|
| 254 |
+
if verinfo:
|
| 255 |
+
lines.extend(verinfo)
|
| 256 |
+
|
| 257 |
+
if config.option.traceconfig:
|
| 258 |
+
lines.append("active plugins:")
|
| 259 |
+
items = config.pluginmanager.list_name_plugin()
|
| 260 |
+
for name, plugin in items:
|
| 261 |
+
if hasattr(plugin, "__file__"):
|
| 262 |
+
r = plugin.__file__
|
| 263 |
+
else:
|
| 264 |
+
r = repr(plugin)
|
| 265 |
+
lines.append(f" {name:<20}: {r}")
|
| 266 |
+
return lines
|
wemm/lib/python3.10/site-packages/_pytest/hookspec.py
ADDED
|
@@ -0,0 +1,979 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ications for pytest plugins which are invoked by pytest itself
|
| 2 |
+
and by builtin plugins."""
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Any
|
| 5 |
+
from typing import Dict
|
| 6 |
+
from typing import List
|
| 7 |
+
from typing import Mapping
|
| 8 |
+
from typing import Optional
|
| 9 |
+
from typing import Sequence
|
| 10 |
+
from typing import Tuple
|
| 11 |
+
from typing import TYPE_CHECKING
|
| 12 |
+
from typing import Union
|
| 13 |
+
|
| 14 |
+
from pluggy import HookspecMarker
|
| 15 |
+
|
| 16 |
+
from _pytest.deprecated import WARNING_CMDLINE_PREPARSE_HOOK
|
| 17 |
+
|
| 18 |
+
if TYPE_CHECKING:
|
| 19 |
+
import pdb
|
| 20 |
+
import warnings
|
| 21 |
+
from typing_extensions import Literal
|
| 22 |
+
|
| 23 |
+
from _pytest._code.code import ExceptionRepr
|
| 24 |
+
from _pytest._code.code import ExceptionInfo
|
| 25 |
+
from _pytest.config import Config
|
| 26 |
+
from _pytest.config import ExitCode
|
| 27 |
+
from _pytest.config import PytestPluginManager
|
| 28 |
+
from _pytest.config import _PluggyPlugin
|
| 29 |
+
from _pytest.config.argparsing import Parser
|
| 30 |
+
from _pytest.fixtures import FixtureDef
|
| 31 |
+
from _pytest.fixtures import SubRequest
|
| 32 |
+
from _pytest.main import Session
|
| 33 |
+
from _pytest.nodes import Collector
|
| 34 |
+
from _pytest.nodes import Item
|
| 35 |
+
from _pytest.outcomes import Exit
|
| 36 |
+
from _pytest.python import Class
|
| 37 |
+
from _pytest.python import Function
|
| 38 |
+
from _pytest.python import Metafunc
|
| 39 |
+
from _pytest.python import Module
|
| 40 |
+
from _pytest.reports import CollectReport
|
| 41 |
+
from _pytest.reports import TestReport
|
| 42 |
+
from _pytest.runner import CallInfo
|
| 43 |
+
from _pytest.terminal import TerminalReporter
|
| 44 |
+
from _pytest.terminal import TestShortLogReport
|
| 45 |
+
from _pytest.compat import LEGACY_PATH
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
hookspec = HookspecMarker("pytest")
|
| 49 |
+
|
| 50 |
+
# -------------------------------------------------------------------------
|
| 51 |
+
# Initialization hooks called for every plugin
|
| 52 |
+
# -------------------------------------------------------------------------
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@hookspec(historic=True)
|
| 56 |
+
def pytest_addhooks(pluginmanager: "PytestPluginManager") -> None:
|
| 57 |
+
"""Called at plugin registration time to allow adding new hooks via a call to
|
| 58 |
+
``pluginmanager.add_hookspecs(module_or_class, prefix)``.
|
| 59 |
+
|
| 60 |
+
:param pytest.PytestPluginManager pluginmanager: The pytest plugin manager.
|
| 61 |
+
|
| 62 |
+
.. note::
|
| 63 |
+
This hook is incompatible with ``hookwrapper=True``.
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@hookspec(historic=True)
|
| 68 |
+
def pytest_plugin_registered(
|
| 69 |
+
plugin: "_PluggyPlugin", manager: "PytestPluginManager"
|
| 70 |
+
) -> None:
|
| 71 |
+
"""A new pytest plugin got registered.
|
| 72 |
+
|
| 73 |
+
:param plugin: The plugin module or instance.
|
| 74 |
+
:param pytest.PytestPluginManager manager: pytest plugin manager.
|
| 75 |
+
|
| 76 |
+
.. note::
|
| 77 |
+
This hook is incompatible with ``hookwrapper=True``.
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@hookspec(historic=True)
|
| 82 |
+
def pytest_addoption(parser: "Parser", pluginmanager: "PytestPluginManager") -> None:
|
| 83 |
+
"""Register argparse-style options and ini-style config values,
|
| 84 |
+
called once at the beginning of a test run.
|
| 85 |
+
|
| 86 |
+
.. note::
|
| 87 |
+
|
| 88 |
+
This function should be implemented only in plugins or ``conftest.py``
|
| 89 |
+
files situated at the tests root directory due to how pytest
|
| 90 |
+
:ref:`discovers plugins during startup <pluginorder>`.
|
| 91 |
+
|
| 92 |
+
:param pytest.Parser parser:
|
| 93 |
+
To add command line options, call
|
| 94 |
+
:py:func:`parser.addoption(...) <pytest.Parser.addoption>`.
|
| 95 |
+
To add ini-file values call :py:func:`parser.addini(...)
|
| 96 |
+
<pytest.Parser.addini>`.
|
| 97 |
+
|
| 98 |
+
:param pytest.PytestPluginManager pluginmanager:
|
| 99 |
+
The pytest plugin manager, which can be used to install :py:func:`hookspec`'s
|
| 100 |
+
or :py:func:`hookimpl`'s and allow one plugin to call another plugin's hooks
|
| 101 |
+
to change how command line options are added.
|
| 102 |
+
|
| 103 |
+
Options can later be accessed through the
|
| 104 |
+
:py:class:`config <pytest.Config>` object, respectively:
|
| 105 |
+
|
| 106 |
+
- :py:func:`config.getoption(name) <pytest.Config.getoption>` to
|
| 107 |
+
retrieve the value of a command line option.
|
| 108 |
+
|
| 109 |
+
- :py:func:`config.getini(name) <pytest.Config.getini>` to retrieve
|
| 110 |
+
a value read from an ini-style file.
|
| 111 |
+
|
| 112 |
+
The config object is passed around on many internal objects via the ``.config``
|
| 113 |
+
attribute or can be retrieved as the ``pytestconfig`` fixture.
|
| 114 |
+
|
| 115 |
+
.. note::
|
| 116 |
+
This hook is incompatible with ``hookwrapper=True``.
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
@hookspec(historic=True)
|
| 121 |
+
def pytest_configure(config: "Config") -> None:
|
| 122 |
+
"""Allow plugins and conftest files to perform initial configuration.
|
| 123 |
+
|
| 124 |
+
This hook is called for every plugin and initial conftest file
|
| 125 |
+
after command line options have been parsed.
|
| 126 |
+
|
| 127 |
+
After that, the hook is called for other conftest files as they are
|
| 128 |
+
imported.
|
| 129 |
+
|
| 130 |
+
.. note::
|
| 131 |
+
This hook is incompatible with ``hookwrapper=True``.
|
| 132 |
+
|
| 133 |
+
:param pytest.Config config: The pytest config object.
|
| 134 |
+
"""
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
# -------------------------------------------------------------------------
|
| 138 |
+
# Bootstrapping hooks called for plugins registered early enough:
|
| 139 |
+
# internal and 3rd party plugins.
|
| 140 |
+
# -------------------------------------------------------------------------
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@hookspec(firstresult=True)
|
| 144 |
+
def pytest_cmdline_parse(
|
| 145 |
+
pluginmanager: "PytestPluginManager", args: List[str]
|
| 146 |
+
) -> Optional["Config"]:
|
| 147 |
+
"""Return an initialized :class:`~pytest.Config`, parsing the specified args.
|
| 148 |
+
|
| 149 |
+
Stops at first non-None result, see :ref:`firstresult`.
|
| 150 |
+
|
| 151 |
+
.. note::
|
| 152 |
+
This hook will only be called for plugin classes passed to the
|
| 153 |
+
``plugins`` arg when using `pytest.main`_ to perform an in-process
|
| 154 |
+
test run.
|
| 155 |
+
|
| 156 |
+
:param pluginmanager: The pytest plugin manager.
|
| 157 |
+
:param args: List of arguments passed on the command line.
|
| 158 |
+
:returns: A pytest config object.
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
@hookspec(warn_on_impl=WARNING_CMDLINE_PREPARSE_HOOK)
|
| 163 |
+
def pytest_cmdline_preparse(config: "Config", args: List[str]) -> None:
|
| 164 |
+
"""(**Deprecated**) modify command line arguments before option parsing.
|
| 165 |
+
|
| 166 |
+
This hook is considered deprecated and will be removed in a future pytest version. Consider
|
| 167 |
+
using :hook:`pytest_load_initial_conftests` instead.
|
| 168 |
+
|
| 169 |
+
.. note::
|
| 170 |
+
This hook will not be called for ``conftest.py`` files, only for setuptools plugins.
|
| 171 |
+
|
| 172 |
+
:param config: The pytest config object.
|
| 173 |
+
:param args: Arguments passed on the command line.
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
@hookspec(firstresult=True)
|
| 178 |
+
def pytest_cmdline_main(config: "Config") -> Optional[Union["ExitCode", int]]:
|
| 179 |
+
"""Called for performing the main command line action. The default
|
| 180 |
+
implementation will invoke the configure hooks and runtest_mainloop.
|
| 181 |
+
|
| 182 |
+
Stops at first non-None result, see :ref:`firstresult`.
|
| 183 |
+
|
| 184 |
+
:param config: The pytest config object.
|
| 185 |
+
:returns: The exit code.
|
| 186 |
+
"""
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def pytest_load_initial_conftests(
|
| 190 |
+
early_config: "Config", parser: "Parser", args: List[str]
|
| 191 |
+
) -> None:
|
| 192 |
+
"""Called to implement the loading of initial conftest files ahead
|
| 193 |
+
of command line option parsing.
|
| 194 |
+
|
| 195 |
+
.. note::
|
| 196 |
+
This hook will not be called for ``conftest.py`` files, only for setuptools plugins.
|
| 197 |
+
|
| 198 |
+
:param early_config: The pytest config object.
|
| 199 |
+
:param args: Arguments passed on the command line.
|
| 200 |
+
:param parser: To add command line options.
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
# -------------------------------------------------------------------------
|
| 205 |
+
# collection hooks
|
| 206 |
+
# -------------------------------------------------------------------------
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
@hookspec(firstresult=True)
|
| 210 |
+
def pytest_collection(session: "Session") -> Optional[object]:
|
| 211 |
+
"""Perform the collection phase for the given session.
|
| 212 |
+
|
| 213 |
+
Stops at first non-None result, see :ref:`firstresult`.
|
| 214 |
+
The return value is not used, but only stops further processing.
|
| 215 |
+
|
| 216 |
+
The default collection phase is this (see individual hooks for full details):
|
| 217 |
+
|
| 218 |
+
1. Starting from ``session`` as the initial collector:
|
| 219 |
+
|
| 220 |
+
1. ``pytest_collectstart(collector)``
|
| 221 |
+
2. ``report = pytest_make_collect_report(collector)``
|
| 222 |
+
3. ``pytest_exception_interact(collector, call, report)`` if an interactive exception occurred
|
| 223 |
+
4. For each collected node:
|
| 224 |
+
|
| 225 |
+
1. If an item, ``pytest_itemcollected(item)``
|
| 226 |
+
2. If a collector, recurse into it.
|
| 227 |
+
|
| 228 |
+
5. ``pytest_collectreport(report)``
|
| 229 |
+
|
| 230 |
+
2. ``pytest_collection_modifyitems(session, config, items)``
|
| 231 |
+
|
| 232 |
+
1. ``pytest_deselected(items)`` for any deselected items (may be called multiple times)
|
| 233 |
+
|
| 234 |
+
3. ``pytest_collection_finish(session)``
|
| 235 |
+
4. Set ``session.items`` to the list of collected items
|
| 236 |
+
5. Set ``session.testscollected`` to the number of collected items
|
| 237 |
+
|
| 238 |
+
You can implement this hook to only perform some action before collection,
|
| 239 |
+
for example the terminal plugin uses it to start displaying the collection
|
| 240 |
+
counter (and returns `None`).
|
| 241 |
+
|
| 242 |
+
:param session: The pytest session object.
|
| 243 |
+
"""
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def pytest_collection_modifyitems(
|
| 247 |
+
session: "Session", config: "Config", items: List["Item"]
|
| 248 |
+
) -> None:
|
| 249 |
+
"""Called after collection has been performed. May filter or re-order
|
| 250 |
+
the items in-place.
|
| 251 |
+
|
| 252 |
+
:param session: The pytest session object.
|
| 253 |
+
:param config: The pytest config object.
|
| 254 |
+
:param items: List of item objects.
|
| 255 |
+
"""
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def pytest_collection_finish(session: "Session") -> None:
|
| 259 |
+
"""Called after collection has been performed and modified.
|
| 260 |
+
|
| 261 |
+
:param session: The pytest session object.
|
| 262 |
+
"""
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@hookspec(firstresult=True)
|
| 266 |
+
def pytest_ignore_collect(
|
| 267 |
+
collection_path: Path, path: "LEGACY_PATH", config: "Config"
|
| 268 |
+
) -> Optional[bool]:
|
| 269 |
+
"""Return True to prevent considering this path for collection.
|
| 270 |
+
|
| 271 |
+
This hook is consulted for all files and directories prior to calling
|
| 272 |
+
more specific hooks.
|
| 273 |
+
|
| 274 |
+
Stops at first non-None result, see :ref:`firstresult`.
|
| 275 |
+
|
| 276 |
+
:param collection_path: The path to analyze.
|
| 277 |
+
:param path: The path to analyze (deprecated).
|
| 278 |
+
:param config: The pytest config object.
|
| 279 |
+
|
| 280 |
+
.. versionchanged:: 7.0.0
|
| 281 |
+
The ``collection_path`` parameter was added as a :class:`pathlib.Path`
|
| 282 |
+
equivalent of the ``path`` parameter. The ``path`` parameter
|
| 283 |
+
has been deprecated.
|
| 284 |
+
"""
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def pytest_collect_file(
|
| 288 |
+
file_path: Path, path: "LEGACY_PATH", parent: "Collector"
|
| 289 |
+
) -> "Optional[Collector]":
|
| 290 |
+
"""Create a :class:`~pytest.Collector` for the given path, or None if not relevant.
|
| 291 |
+
|
| 292 |
+
The new node needs to have the specified ``parent`` as a parent.
|
| 293 |
+
|
| 294 |
+
:param file_path: The path to analyze.
|
| 295 |
+
:param path: The path to collect (deprecated).
|
| 296 |
+
|
| 297 |
+
.. versionchanged:: 7.0.0
|
| 298 |
+
The ``file_path`` parameter was added as a :class:`pathlib.Path`
|
| 299 |
+
equivalent of the ``path`` parameter. The ``path`` parameter
|
| 300 |
+
has been deprecated.
|
| 301 |
+
"""
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
# logging hooks for collection
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def pytest_collectstart(collector: "Collector") -> None:
|
| 308 |
+
"""Collector starts collecting.
|
| 309 |
+
|
| 310 |
+
:param collector:
|
| 311 |
+
The collector.
|
| 312 |
+
"""
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def pytest_itemcollected(item: "Item") -> None:
|
| 316 |
+
"""We just collected a test item.
|
| 317 |
+
|
| 318 |
+
:param item:
|
| 319 |
+
The item.
|
| 320 |
+
"""
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def pytest_collectreport(report: "CollectReport") -> None:
|
| 324 |
+
"""Collector finished collecting.
|
| 325 |
+
|
| 326 |
+
:param report:
|
| 327 |
+
The collect report.
|
| 328 |
+
"""
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def pytest_deselected(items: Sequence["Item"]) -> None:
|
| 332 |
+
"""Called for deselected test items, e.g. by keyword.
|
| 333 |
+
|
| 334 |
+
May be called multiple times.
|
| 335 |
+
|
| 336 |
+
:param items:
|
| 337 |
+
The items.
|
| 338 |
+
"""
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
@hookspec(firstresult=True)
|
| 342 |
+
def pytest_make_collect_report(collector: "Collector") -> "Optional[CollectReport]":
|
| 343 |
+
"""Perform :func:`collector.collect() <pytest.Collector.collect>` and return
|
| 344 |
+
a :class:`~pytest.CollectReport`.
|
| 345 |
+
|
| 346 |
+
Stops at first non-None result, see :ref:`firstresult`.
|
| 347 |
+
|
| 348 |
+
:param collector:
|
| 349 |
+
The collector.
|
| 350 |
+
"""
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
# -------------------------------------------------------------------------
|
| 354 |
+
# Python test function related hooks
|
| 355 |
+
# -------------------------------------------------------------------------
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
@hookspec(firstresult=True)
|
| 359 |
+
def pytest_pycollect_makemodule(
|
| 360 |
+
module_path: Path, path: "LEGACY_PATH", parent
|
| 361 |
+
) -> Optional["Module"]:
|
| 362 |
+
"""Return a :class:`pytest.Module` collector or None for the given path.
|
| 363 |
+
|
| 364 |
+
This hook will be called for each matching test module path.
|
| 365 |
+
The :hook:`pytest_collect_file` hook needs to be used if you want to
|
| 366 |
+
create test modules for files that do not match as a test module.
|
| 367 |
+
|
| 368 |
+
Stops at first non-None result, see :ref:`firstresult`.
|
| 369 |
+
|
| 370 |
+
:param module_path: The path of the module to collect.
|
| 371 |
+
:param path: The path of the module to collect (deprecated).
|
| 372 |
+
|
| 373 |
+
.. versionchanged:: 7.0.0
|
| 374 |
+
The ``module_path`` parameter was added as a :class:`pathlib.Path`
|
| 375 |
+
equivalent of the ``path`` parameter.
|
| 376 |
+
|
| 377 |
+
The ``path`` parameter has been deprecated in favor of ``fspath``.
|
| 378 |
+
"""
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
@hookspec(firstresult=True)
|
| 382 |
+
def pytest_pycollect_makeitem(
|
| 383 |
+
collector: Union["Module", "Class"], name: str, obj: object
|
| 384 |
+
) -> Union[None, "Item", "Collector", List[Union["Item", "Collector"]]]:
|
| 385 |
+
"""Return a custom item/collector for a Python object in a module, or None.
|
| 386 |
+
|
| 387 |
+
Stops at first non-None result, see :ref:`firstresult`.
|
| 388 |
+
|
| 389 |
+
:param collector:
|
| 390 |
+
The module/class collector.
|
| 391 |
+
:param name:
|
| 392 |
+
The name of the object in the module/class.
|
| 393 |
+
:param obj:
|
| 394 |
+
The object.
|
| 395 |
+
:returns:
|
| 396 |
+
The created items/collectors.
|
| 397 |
+
"""
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
@hookspec(firstresult=True)
|
| 401 |
+
def pytest_pyfunc_call(pyfuncitem: "Function") -> Optional[object]:
|
| 402 |
+
"""Call underlying test function.
|
| 403 |
+
|
| 404 |
+
Stops at first non-None result, see :ref:`firstresult`.
|
| 405 |
+
|
| 406 |
+
:param pyfuncitem:
|
| 407 |
+
The function item.
|
| 408 |
+
"""
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def pytest_generate_tests(metafunc: "Metafunc") -> None:
|
| 412 |
+
"""Generate (multiple) parametrized calls to a test function.
|
| 413 |
+
|
| 414 |
+
:param metafunc:
|
| 415 |
+
The :class:`~pytest.Metafunc` helper for the test function.
|
| 416 |
+
"""
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
@hookspec(firstresult=True)
|
| 420 |
+
def pytest_make_parametrize_id(
|
| 421 |
+
config: "Config", val: object, argname: str
|
| 422 |
+
) -> Optional[str]:
|
| 423 |
+
"""Return a user-friendly string representation of the given ``val``
|
| 424 |
+
that will be used by @pytest.mark.parametrize calls, or None if the hook
|
| 425 |
+
doesn't know about ``val``.
|
| 426 |
+
|
| 427 |
+
The parameter name is available as ``argname``, if required.
|
| 428 |
+
|
| 429 |
+
Stops at first non-None result, see :ref:`firstresult`.
|
| 430 |
+
|
| 431 |
+
:param config: The pytest config object.
|
| 432 |
+
:param val: The parametrized value.
|
| 433 |
+
:param str argname: The automatic parameter name produced by pytest.
|
| 434 |
+
"""
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
# -------------------------------------------------------------------------
|
| 438 |
+
# runtest related hooks
|
| 439 |
+
# -------------------------------------------------------------------------
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
@hookspec(firstresult=True)
|
| 443 |
+
def pytest_runtestloop(session: "Session") -> Optional[object]:
|
| 444 |
+
"""Perform the main runtest loop (after collection finished).
|
| 445 |
+
|
| 446 |
+
The default hook implementation performs the runtest protocol for all items
|
| 447 |
+
collected in the session (``session.items``), unless the collection failed
|
| 448 |
+
or the ``collectonly`` pytest option is set.
|
| 449 |
+
|
| 450 |
+
If at any point :py:func:`pytest.exit` is called, the loop is
|
| 451 |
+
terminated immediately.
|
| 452 |
+
|
| 453 |
+
If at any point ``session.shouldfail`` or ``session.shouldstop`` are set, the
|
| 454 |
+
loop is terminated after the runtest protocol for the current item is finished.
|
| 455 |
+
|
| 456 |
+
:param session: The pytest session object.
|
| 457 |
+
|
| 458 |
+
Stops at first non-None result, see :ref:`firstresult`.
|
| 459 |
+
The return value is not used, but only stops further processing.
|
| 460 |
+
"""
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
@hookspec(firstresult=True)
|
| 464 |
+
def pytest_runtest_protocol(
|
| 465 |
+
item: "Item", nextitem: "Optional[Item]"
|
| 466 |
+
) -> Optional[object]:
|
| 467 |
+
"""Perform the runtest protocol for a single test item.
|
| 468 |
+
|
| 469 |
+
The default runtest protocol is this (see individual hooks for full details):
|
| 470 |
+
|
| 471 |
+
- ``pytest_runtest_logstart(nodeid, location)``
|
| 472 |
+
|
| 473 |
+
- Setup phase:
|
| 474 |
+
- ``call = pytest_runtest_setup(item)`` (wrapped in ``CallInfo(when="setup")``)
|
| 475 |
+
- ``report = pytest_runtest_makereport(item, call)``
|
| 476 |
+
- ``pytest_runtest_logreport(report)``
|
| 477 |
+
- ``pytest_exception_interact(call, report)`` if an interactive exception occurred
|
| 478 |
+
|
| 479 |
+
- Call phase, if the the setup passed and the ``setuponly`` pytest option is not set:
|
| 480 |
+
- ``call = pytest_runtest_call(item)`` (wrapped in ``CallInfo(when="call")``)
|
| 481 |
+
- ``report = pytest_runtest_makereport(item, call)``
|
| 482 |
+
- ``pytest_runtest_logreport(report)``
|
| 483 |
+
- ``pytest_exception_interact(call, report)`` if an interactive exception occurred
|
| 484 |
+
|
| 485 |
+
- Teardown phase:
|
| 486 |
+
- ``call = pytest_runtest_teardown(item, nextitem)`` (wrapped in ``CallInfo(when="teardown")``)
|
| 487 |
+
- ``report = pytest_runtest_makereport(item, call)``
|
| 488 |
+
- ``pytest_runtest_logreport(report)``
|
| 489 |
+
- ``pytest_exception_interact(call, report)`` if an interactive exception occurred
|
| 490 |
+
|
| 491 |
+
- ``pytest_runtest_logfinish(nodeid, location)``
|
| 492 |
+
|
| 493 |
+
:param item: Test item for which the runtest protocol is performed.
|
| 494 |
+
:param nextitem: The scheduled-to-be-next test item (or None if this is the end my friend).
|
| 495 |
+
|
| 496 |
+
Stops at first non-None result, see :ref:`firstresult`.
|
| 497 |
+
The return value is not used, but only stops further processing.
|
| 498 |
+
"""
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
def pytest_runtest_logstart(
|
| 502 |
+
nodeid: str, location: Tuple[str, Optional[int], str]
|
| 503 |
+
) -> None:
|
| 504 |
+
"""Called at the start of running the runtest protocol for a single item.
|
| 505 |
+
|
| 506 |
+
See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.
|
| 507 |
+
|
| 508 |
+
:param nodeid: Full node ID of the item.
|
| 509 |
+
:param location: A tuple of ``(filename, lineno, testname)``
|
| 510 |
+
where ``filename`` is a file path relative to ``config.rootpath``
|
| 511 |
+
and ``lineno`` is 0-based.
|
| 512 |
+
"""
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def pytest_runtest_logfinish(
|
| 516 |
+
nodeid: str, location: Tuple[str, Optional[int], str]
|
| 517 |
+
) -> None:
|
| 518 |
+
"""Called at the end of running the runtest protocol for a single item.
|
| 519 |
+
|
| 520 |
+
See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.
|
| 521 |
+
|
| 522 |
+
:param nodeid: Full node ID of the item.
|
| 523 |
+
:param location: A tuple of ``(filename, lineno, testname)``
|
| 524 |
+
where ``filename`` is a file path relative to ``config.rootpath``
|
| 525 |
+
and ``lineno`` is 0-based.
|
| 526 |
+
"""
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
def pytest_runtest_setup(item: "Item") -> None:
|
| 530 |
+
"""Called to perform the setup phase for a test item.
|
| 531 |
+
|
| 532 |
+
The default implementation runs ``setup()`` on ``item`` and all of its
|
| 533 |
+
parents (which haven't been setup yet). This includes obtaining the
|
| 534 |
+
values of fixtures required by the item (which haven't been obtained
|
| 535 |
+
yet).
|
| 536 |
+
|
| 537 |
+
:param item:
|
| 538 |
+
The item.
|
| 539 |
+
"""
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def pytest_runtest_call(item: "Item") -> None:
|
| 543 |
+
"""Called to run the test for test item (the call phase).
|
| 544 |
+
|
| 545 |
+
The default implementation calls ``item.runtest()``.
|
| 546 |
+
|
| 547 |
+
:param item:
|
| 548 |
+
The item.
|
| 549 |
+
"""
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
def pytest_runtest_teardown(item: "Item", nextitem: Optional["Item"]) -> None:
|
| 553 |
+
"""Called to perform the teardown phase for a test item.
|
| 554 |
+
|
| 555 |
+
The default implementation runs the finalizers and calls ``teardown()``
|
| 556 |
+
on ``item`` and all of its parents (which need to be torn down). This
|
| 557 |
+
includes running the teardown phase of fixtures required by the item (if
|
| 558 |
+
they go out of scope).
|
| 559 |
+
|
| 560 |
+
:param item:
|
| 561 |
+
The item.
|
| 562 |
+
:param nextitem:
|
| 563 |
+
The scheduled-to-be-next test item (None if no further test item is
|
| 564 |
+
scheduled). This argument is used to perform exact teardowns, i.e.
|
| 565 |
+
calling just enough finalizers so that nextitem only needs to call
|
| 566 |
+
setup functions.
|
| 567 |
+
"""
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
@hookspec(firstresult=True)
|
| 571 |
+
def pytest_runtest_makereport(
|
| 572 |
+
item: "Item", call: "CallInfo[None]"
|
| 573 |
+
) -> Optional["TestReport"]:
|
| 574 |
+
"""Called to create a :class:`~pytest.TestReport` for each of
|
| 575 |
+
the setup, call and teardown runtest phases of a test item.
|
| 576 |
+
|
| 577 |
+
See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.
|
| 578 |
+
|
| 579 |
+
:param item: The item.
|
| 580 |
+
:param call: The :class:`~pytest.CallInfo` for the phase.
|
| 581 |
+
|
| 582 |
+
Stops at first non-None result, see :ref:`firstresult`.
|
| 583 |
+
"""
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
def pytest_runtest_logreport(report: "TestReport") -> None:
|
| 587 |
+
"""Process the :class:`~pytest.TestReport` produced for each
|
| 588 |
+
of the setup, call and teardown runtest phases of an item.
|
| 589 |
+
|
| 590 |
+
See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.
|
| 591 |
+
"""
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
@hookspec(firstresult=True)
|
| 595 |
+
def pytest_report_to_serializable(
|
| 596 |
+
config: "Config",
|
| 597 |
+
report: Union["CollectReport", "TestReport"],
|
| 598 |
+
) -> Optional[Dict[str, Any]]:
|
| 599 |
+
"""Serialize the given report object into a data structure suitable for
|
| 600 |
+
sending over the wire, e.g. converted to JSON.
|
| 601 |
+
|
| 602 |
+
:param config: The pytest config object.
|
| 603 |
+
:param report: The report.
|
| 604 |
+
"""
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
@hookspec(firstresult=True)
|
| 608 |
+
def pytest_report_from_serializable(
|
| 609 |
+
config: "Config",
|
| 610 |
+
data: Dict[str, Any],
|
| 611 |
+
) -> Optional[Union["CollectReport", "TestReport"]]:
|
| 612 |
+
"""Restore a report object previously serialized with
|
| 613 |
+
:hook:`pytest_report_to_serializable`.
|
| 614 |
+
|
| 615 |
+
:param config: The pytest config object.
|
| 616 |
+
"""
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
# -------------------------------------------------------------------------
|
| 620 |
+
# Fixture related hooks
|
| 621 |
+
# -------------------------------------------------------------------------
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
@hookspec(firstresult=True)
|
| 625 |
+
def pytest_fixture_setup(
|
| 626 |
+
fixturedef: "FixtureDef[Any]", request: "SubRequest"
|
| 627 |
+
) -> Optional[object]:
|
| 628 |
+
"""Perform fixture setup execution.
|
| 629 |
+
|
| 630 |
+
:param fixturdef:
|
| 631 |
+
The fixture definition object.
|
| 632 |
+
:param request:
|
| 633 |
+
The fixture request object.
|
| 634 |
+
:returns:
|
| 635 |
+
The return value of the call to the fixture function.
|
| 636 |
+
|
| 637 |
+
Stops at first non-None result, see :ref:`firstresult`.
|
| 638 |
+
|
| 639 |
+
.. note::
|
| 640 |
+
If the fixture function returns None, other implementations of
|
| 641 |
+
this hook function will continue to be called, according to the
|
| 642 |
+
behavior of the :ref:`firstresult` option.
|
| 643 |
+
"""
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
def pytest_fixture_post_finalizer(
|
| 647 |
+
fixturedef: "FixtureDef[Any]", request: "SubRequest"
|
| 648 |
+
) -> None:
|
| 649 |
+
"""Called after fixture teardown, but before the cache is cleared, so
|
| 650 |
+
the fixture result ``fixturedef.cached_result`` is still available (not
|
| 651 |
+
``None``).
|
| 652 |
+
|
| 653 |
+
:param fixturdef:
|
| 654 |
+
The fixture definition object.
|
| 655 |
+
:param request:
|
| 656 |
+
The fixture request object.
|
| 657 |
+
"""
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
# -------------------------------------------------------------------------
|
| 661 |
+
# test session related hooks
|
| 662 |
+
# -------------------------------------------------------------------------
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
def pytest_sessionstart(session: "Session") -> None:
|
| 666 |
+
"""Called after the ``Session`` object has been created and before performing collection
|
| 667 |
+
and entering the run test loop.
|
| 668 |
+
|
| 669 |
+
:param session: The pytest session object.
|
| 670 |
+
"""
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
def pytest_sessionfinish(
|
| 674 |
+
session: "Session",
|
| 675 |
+
exitstatus: Union[int, "ExitCode"],
|
| 676 |
+
) -> None:
|
| 677 |
+
"""Called after whole test run finished, right before returning the exit status to the system.
|
| 678 |
+
|
| 679 |
+
:param session: The pytest session object.
|
| 680 |
+
:param exitstatus: The status which pytest will return to the system.
|
| 681 |
+
"""
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def pytest_unconfigure(config: "Config") -> None:
|
| 685 |
+
"""Called before test process is exited.
|
| 686 |
+
|
| 687 |
+
:param config: The pytest config object.
|
| 688 |
+
"""
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
# -------------------------------------------------------------------------
|
| 692 |
+
# hooks for customizing the assert methods
|
| 693 |
+
# -------------------------------------------------------------------------
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
def pytest_assertrepr_compare(
|
| 697 |
+
config: "Config", op: str, left: object, right: object
|
| 698 |
+
) -> Optional[List[str]]:
|
| 699 |
+
"""Return explanation for comparisons in failing assert expressions.
|
| 700 |
+
|
| 701 |
+
Return None for no custom explanation, otherwise return a list
|
| 702 |
+
of strings. The strings will be joined by newlines but any newlines
|
| 703 |
+
*in* a string will be escaped. Note that all but the first line will
|
| 704 |
+
be indented slightly, the intention is for the first line to be a summary.
|
| 705 |
+
|
| 706 |
+
:param config: The pytest config object.
|
| 707 |
+
:param op: The operator, e.g. `"=="`, `"!="`, `"not in"`.
|
| 708 |
+
:param left: The left operand.
|
| 709 |
+
:param right: The right operand.
|
| 710 |
+
"""
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
def pytest_assertion_pass(item: "Item", lineno: int, orig: str, expl: str) -> None:
|
| 714 |
+
"""Called whenever an assertion passes.
|
| 715 |
+
|
| 716 |
+
.. versionadded:: 5.0
|
| 717 |
+
|
| 718 |
+
Use this hook to do some processing after a passing assertion.
|
| 719 |
+
The original assertion information is available in the `orig` string
|
| 720 |
+
and the pytest introspected assertion information is available in the
|
| 721 |
+
`expl` string.
|
| 722 |
+
|
| 723 |
+
This hook must be explicitly enabled by the ``enable_assertion_pass_hook``
|
| 724 |
+
ini-file option:
|
| 725 |
+
|
| 726 |
+
.. code-block:: ini
|
| 727 |
+
|
| 728 |
+
[pytest]
|
| 729 |
+
enable_assertion_pass_hook=true
|
| 730 |
+
|
| 731 |
+
You need to **clean the .pyc** files in your project directory and interpreter libraries
|
| 732 |
+
when enabling this option, as assertions will require to be re-written.
|
| 733 |
+
|
| 734 |
+
:param item: pytest item object of current test.
|
| 735 |
+
:param lineno: Line number of the assert statement.
|
| 736 |
+
:param orig: String with the original assertion.
|
| 737 |
+
:param expl: String with the assert explanation.
|
| 738 |
+
"""
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
# -------------------------------------------------------------------------
|
| 742 |
+
# Hooks for influencing reporting (invoked from _pytest_terminal).
|
| 743 |
+
# -------------------------------------------------------------------------
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
def pytest_report_header( # type:ignore[empty-body]
|
| 747 |
+
config: "Config", start_path: Path, startdir: "LEGACY_PATH"
|
| 748 |
+
) -> Union[str, List[str]]:
|
| 749 |
+
"""Return a string or list of strings to be displayed as header info for terminal reporting.
|
| 750 |
+
|
| 751 |
+
:param config: The pytest config object.
|
| 752 |
+
:param start_path: The starting dir.
|
| 753 |
+
:param startdir: The starting dir (deprecated).
|
| 754 |
+
|
| 755 |
+
.. note::
|
| 756 |
+
|
| 757 |
+
Lines returned by a plugin are displayed before those of plugins which
|
| 758 |
+
ran before it.
|
| 759 |
+
If you want to have your line(s) displayed first, use
|
| 760 |
+
:ref:`trylast=True <plugin-hookorder>`.
|
| 761 |
+
|
| 762 |
+
.. note::
|
| 763 |
+
|
| 764 |
+
This function should be implemented only in plugins or ``conftest.py``
|
| 765 |
+
files situated at the tests root directory due to how pytest
|
| 766 |
+
:ref:`discovers plugins during startup <pluginorder>`.
|
| 767 |
+
|
| 768 |
+
.. versionchanged:: 7.0.0
|
| 769 |
+
The ``start_path`` parameter was added as a :class:`pathlib.Path`
|
| 770 |
+
equivalent of the ``startdir`` parameter. The ``startdir`` parameter
|
| 771 |
+
has been deprecated.
|
| 772 |
+
"""
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
def pytest_report_collectionfinish( # type:ignore[empty-body]
|
| 776 |
+
config: "Config",
|
| 777 |
+
start_path: Path,
|
| 778 |
+
startdir: "LEGACY_PATH",
|
| 779 |
+
items: Sequence["Item"],
|
| 780 |
+
) -> Union[str, List[str]]:
|
| 781 |
+
"""Return a string or list of strings to be displayed after collection
|
| 782 |
+
has finished successfully.
|
| 783 |
+
|
| 784 |
+
These strings will be displayed after the standard "collected X items" message.
|
| 785 |
+
|
| 786 |
+
.. versionadded:: 3.2
|
| 787 |
+
|
| 788 |
+
:param config: The pytest config object.
|
| 789 |
+
:param start_path: The starting dir.
|
| 790 |
+
:param startdir: The starting dir (deprecated).
|
| 791 |
+
:param items: List of pytest items that are going to be executed; this list should not be modified.
|
| 792 |
+
|
| 793 |
+
.. note::
|
| 794 |
+
|
| 795 |
+
Lines returned by a plugin are displayed before those of plugins which
|
| 796 |
+
ran before it.
|
| 797 |
+
If you want to have your line(s) displayed first, use
|
| 798 |
+
:ref:`trylast=True <plugin-hookorder>`.
|
| 799 |
+
|
| 800 |
+
.. versionchanged:: 7.0.0
|
| 801 |
+
The ``start_path`` parameter was added as a :class:`pathlib.Path`
|
| 802 |
+
equivalent of the ``startdir`` parameter. The ``startdir`` parameter
|
| 803 |
+
has been deprecated.
|
| 804 |
+
"""
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
@hookspec(firstresult=True)
|
| 808 |
+
def pytest_report_teststatus( # type:ignore[empty-body]
|
| 809 |
+
report: Union["CollectReport", "TestReport"], config: "Config"
|
| 810 |
+
) -> "TestShortLogReport | Tuple[str, str, Union[str, Tuple[str, Mapping[str, bool]]]]":
|
| 811 |
+
"""Return result-category, shortletter and verbose word for status
|
| 812 |
+
reporting.
|
| 813 |
+
|
| 814 |
+
The result-category is a category in which to count the result, for
|
| 815 |
+
example "passed", "skipped", "error" or the empty string.
|
| 816 |
+
|
| 817 |
+
The shortletter is shown as testing progresses, for example ".", "s",
|
| 818 |
+
"E" or the empty string.
|
| 819 |
+
|
| 820 |
+
The verbose word is shown as testing progresses in verbose mode, for
|
| 821 |
+
example "PASSED", "SKIPPED", "ERROR" or the empty string.
|
| 822 |
+
|
| 823 |
+
pytest may style these implicitly according to the report outcome.
|
| 824 |
+
To provide explicit styling, return a tuple for the verbose word,
|
| 825 |
+
for example ``"rerun", "R", ("RERUN", {"yellow": True})``.
|
| 826 |
+
|
| 827 |
+
:param report: The report object whose status is to be returned.
|
| 828 |
+
:param config: The pytest config object.
|
| 829 |
+
:returns: The test status.
|
| 830 |
+
|
| 831 |
+
Stops at first non-None result, see :ref:`firstresult`.
|
| 832 |
+
"""
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
def pytest_terminal_summary(
|
| 836 |
+
terminalreporter: "TerminalReporter",
|
| 837 |
+
exitstatus: "ExitCode",
|
| 838 |
+
config: "Config",
|
| 839 |
+
) -> None:
|
| 840 |
+
"""Add a section to terminal summary reporting.
|
| 841 |
+
|
| 842 |
+
:param terminalreporter: The internal terminal reporter object.
|
| 843 |
+
:param exitstatus: The exit status that will be reported back to the OS.
|
| 844 |
+
:param config: The pytest config object.
|
| 845 |
+
|
| 846 |
+
.. versionadded:: 4.2
|
| 847 |
+
The ``config`` parameter.
|
| 848 |
+
"""
|
| 849 |
+
|
| 850 |
+
|
| 851 |
+
@hookspec(historic=True)
|
| 852 |
+
def pytest_warning_recorded(
|
| 853 |
+
warning_message: "warnings.WarningMessage",
|
| 854 |
+
when: "Literal['config', 'collect', 'runtest']",
|
| 855 |
+
nodeid: str,
|
| 856 |
+
location: Optional[Tuple[str, int, str]],
|
| 857 |
+
) -> None:
|
| 858 |
+
"""Process a warning captured by the internal pytest warnings plugin.
|
| 859 |
+
|
| 860 |
+
:param warning_message:
|
| 861 |
+
The captured warning. This is the same object produced by :py:func:`warnings.catch_warnings`, and contains
|
| 862 |
+
the same attributes as the parameters of :py:func:`warnings.showwarning`.
|
| 863 |
+
|
| 864 |
+
:param when:
|
| 865 |
+
Indicates when the warning was captured. Possible values:
|
| 866 |
+
|
| 867 |
+
* ``"config"``: during pytest configuration/initialization stage.
|
| 868 |
+
* ``"collect"``: during test collection.
|
| 869 |
+
* ``"runtest"``: during test execution.
|
| 870 |
+
|
| 871 |
+
:param nodeid:
|
| 872 |
+
Full id of the item.
|
| 873 |
+
|
| 874 |
+
:param location:
|
| 875 |
+
When available, holds information about the execution context of the captured
|
| 876 |
+
warning (filename, linenumber, function). ``function`` evaluates to <module>
|
| 877 |
+
when the execution context is at the module level.
|
| 878 |
+
|
| 879 |
+
.. versionadded:: 6.0
|
| 880 |
+
"""
|
| 881 |
+
|
| 882 |
+
|
| 883 |
+
# -------------------------------------------------------------------------
|
| 884 |
+
# Hooks for influencing skipping
|
| 885 |
+
# -------------------------------------------------------------------------
|
| 886 |
+
|
| 887 |
+
|
| 888 |
+
def pytest_markeval_namespace( # type:ignore[empty-body]
|
| 889 |
+
config: "Config",
|
| 890 |
+
) -> Dict[str, Any]:
|
| 891 |
+
"""Called when constructing the globals dictionary used for
|
| 892 |
+
evaluating string conditions in xfail/skipif markers.
|
| 893 |
+
|
| 894 |
+
This is useful when the condition for a marker requires
|
| 895 |
+
objects that are expensive or impossible to obtain during
|
| 896 |
+
collection time, which is required by normal boolean
|
| 897 |
+
conditions.
|
| 898 |
+
|
| 899 |
+
.. versionadded:: 6.2
|
| 900 |
+
|
| 901 |
+
:param config: The pytest config object.
|
| 902 |
+
:returns: A dictionary of additional globals to add.
|
| 903 |
+
"""
|
| 904 |
+
|
| 905 |
+
|
| 906 |
+
# -------------------------------------------------------------------------
|
| 907 |
+
# error handling and internal debugging hooks
|
| 908 |
+
# -------------------------------------------------------------------------
|
| 909 |
+
|
| 910 |
+
|
| 911 |
+
def pytest_internalerror(
|
| 912 |
+
excrepr: "ExceptionRepr",
|
| 913 |
+
excinfo: "ExceptionInfo[BaseException]",
|
| 914 |
+
) -> Optional[bool]:
|
| 915 |
+
"""Called for internal errors.
|
| 916 |
+
|
| 917 |
+
Return True to suppress the fallback handling of printing an
|
| 918 |
+
INTERNALERROR message directly to sys.stderr.
|
| 919 |
+
|
| 920 |
+
:param excrepr: The exception repr object.
|
| 921 |
+
:param excinfo: The exception info.
|
| 922 |
+
"""
|
| 923 |
+
|
| 924 |
+
|
| 925 |
+
def pytest_keyboard_interrupt(
|
| 926 |
+
excinfo: "ExceptionInfo[Union[KeyboardInterrupt, Exit]]",
|
| 927 |
+
) -> None:
|
| 928 |
+
"""Called for keyboard interrupt.
|
| 929 |
+
|
| 930 |
+
:param excinfo: The exception info.
|
| 931 |
+
"""
|
| 932 |
+
|
| 933 |
+
|
| 934 |
+
def pytest_exception_interact(
|
| 935 |
+
node: Union["Item", "Collector"],
|
| 936 |
+
call: "CallInfo[Any]",
|
| 937 |
+
report: Union["CollectReport", "TestReport"],
|
| 938 |
+
) -> None:
|
| 939 |
+
"""Called when an exception was raised which can potentially be
|
| 940 |
+
interactively handled.
|
| 941 |
+
|
| 942 |
+
May be called during collection (see :hook:`pytest_make_collect_report`),
|
| 943 |
+
in which case ``report`` is a :class:`CollectReport`.
|
| 944 |
+
|
| 945 |
+
May be called during runtest of an item (see :hook:`pytest_runtest_protocol`),
|
| 946 |
+
in which case ``report`` is a :class:`TestReport`.
|
| 947 |
+
|
| 948 |
+
This hook is not called if the exception that was raised is an internal
|
| 949 |
+
exception like ``skip.Exception``.
|
| 950 |
+
|
| 951 |
+
:param node:
|
| 952 |
+
The item or collector.
|
| 953 |
+
:param call:
|
| 954 |
+
The call information. Contains the exception.
|
| 955 |
+
:param report:
|
| 956 |
+
The collection or test report.
|
| 957 |
+
"""
|
| 958 |
+
|
| 959 |
+
|
| 960 |
+
def pytest_enter_pdb(config: "Config", pdb: "pdb.Pdb") -> None:
|
| 961 |
+
"""Called upon pdb.set_trace().
|
| 962 |
+
|
| 963 |
+
Can be used by plugins to take special action just before the python
|
| 964 |
+
debugger enters interactive mode.
|
| 965 |
+
|
| 966 |
+
:param config: The pytest config object.
|
| 967 |
+
:param pdb: The Pdb instance.
|
| 968 |
+
"""
|
| 969 |
+
|
| 970 |
+
|
| 971 |
+
def pytest_leave_pdb(config: "Config", pdb: "pdb.Pdb") -> None:
|
| 972 |
+
"""Called when leaving pdb (e.g. with continue after pdb.set_trace()).
|
| 973 |
+
|
| 974 |
+
Can be used by plugins to take special action just after the python
|
| 975 |
+
debugger leaves interactive mode.
|
| 976 |
+
|
| 977 |
+
:param config: The pytest config object.
|
| 978 |
+
:param pdb: The Pdb instance.
|
| 979 |
+
"""
|
wemm/lib/python3.10/site-packages/_pytest/logging.py
ADDED
|
@@ -0,0 +1,918 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Access and control log capturing."""
|
| 2 |
+
import io
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
from contextlib import contextmanager
|
| 7 |
+
from contextlib import nullcontext
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from datetime import timedelta
|
| 10 |
+
from datetime import timezone
|
| 11 |
+
from io import StringIO
|
| 12 |
+
from logging import LogRecord
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from typing import AbstractSet
|
| 15 |
+
from typing import Dict
|
| 16 |
+
from typing import Generator
|
| 17 |
+
from typing import List
|
| 18 |
+
from typing import Mapping
|
| 19 |
+
from typing import Optional
|
| 20 |
+
from typing import Tuple
|
| 21 |
+
from typing import TYPE_CHECKING
|
| 22 |
+
from typing import TypeVar
|
| 23 |
+
from typing import Union
|
| 24 |
+
|
| 25 |
+
from _pytest import nodes
|
| 26 |
+
from _pytest._io import TerminalWriter
|
| 27 |
+
from _pytest.capture import CaptureManager
|
| 28 |
+
from _pytest.compat import final
|
| 29 |
+
from _pytest.config import _strtobool
|
| 30 |
+
from _pytest.config import Config
|
| 31 |
+
from _pytest.config import create_terminal_writer
|
| 32 |
+
from _pytest.config import hookimpl
|
| 33 |
+
from _pytest.config import UsageError
|
| 34 |
+
from _pytest.config.argparsing import Parser
|
| 35 |
+
from _pytest.deprecated import check_ispytest
|
| 36 |
+
from _pytest.fixtures import fixture
|
| 37 |
+
from _pytest.fixtures import FixtureRequest
|
| 38 |
+
from _pytest.main import Session
|
| 39 |
+
from _pytest.stash import StashKey
|
| 40 |
+
from _pytest.terminal import TerminalReporter
|
| 41 |
+
|
| 42 |
+
if TYPE_CHECKING:
|
| 43 |
+
logging_StreamHandler = logging.StreamHandler[StringIO]
|
| 44 |
+
|
| 45 |
+
from typing_extensions import Literal
|
| 46 |
+
else:
|
| 47 |
+
logging_StreamHandler = logging.StreamHandler
|
| 48 |
+
|
| 49 |
+
DEFAULT_LOG_FORMAT = "%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s"
|
| 50 |
+
DEFAULT_LOG_DATE_FORMAT = "%H:%M:%S"
|
| 51 |
+
_ANSI_ESCAPE_SEQ = re.compile(r"\x1b\[[\d;]+m")
|
| 52 |
+
caplog_handler_key = StashKey["LogCaptureHandler"]()
|
| 53 |
+
caplog_records_key = StashKey[Dict[str, List[logging.LogRecord]]]()
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _remove_ansi_escape_sequences(text: str) -> str:
|
| 57 |
+
return _ANSI_ESCAPE_SEQ.sub("", text)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class DatetimeFormatter(logging.Formatter):
|
| 61 |
+
"""A logging formatter which formats record with
|
| 62 |
+
:func:`datetime.datetime.strftime` formatter instead of
|
| 63 |
+
:func:`time.strftime` in case of microseconds in format string.
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
def formatTime(self, record: LogRecord, datefmt=None) -> str:
|
| 67 |
+
if datefmt and "%f" in datefmt:
|
| 68 |
+
ct = self.converter(record.created)
|
| 69 |
+
tz = timezone(timedelta(seconds=ct.tm_gmtoff), ct.tm_zone)
|
| 70 |
+
# Construct `datetime.datetime` object from `struct_time`
|
| 71 |
+
# and msecs information from `record`
|
| 72 |
+
dt = datetime(*ct[0:6], microsecond=round(record.msecs * 1000), tzinfo=tz)
|
| 73 |
+
return dt.strftime(datefmt)
|
| 74 |
+
# Use `logging.Formatter` for non-microsecond formats
|
| 75 |
+
return super().formatTime(record, datefmt)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class ColoredLevelFormatter(DatetimeFormatter):
|
| 79 |
+
"""A logging formatter which colorizes the %(levelname)..s part of the
|
| 80 |
+
log format passed to __init__."""
|
| 81 |
+
|
| 82 |
+
LOGLEVEL_COLOROPTS: Mapping[int, AbstractSet[str]] = {
|
| 83 |
+
logging.CRITICAL: {"red"},
|
| 84 |
+
logging.ERROR: {"red", "bold"},
|
| 85 |
+
logging.WARNING: {"yellow"},
|
| 86 |
+
logging.WARN: {"yellow"},
|
| 87 |
+
logging.INFO: {"green"},
|
| 88 |
+
logging.DEBUG: {"purple"},
|
| 89 |
+
logging.NOTSET: set(),
|
| 90 |
+
}
|
| 91 |
+
LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-.]?\d*(?:\.\d+)?s)")
|
| 92 |
+
|
| 93 |
+
def __init__(self, terminalwriter: TerminalWriter, *args, **kwargs) -> None:
|
| 94 |
+
super().__init__(*args, **kwargs)
|
| 95 |
+
self._terminalwriter = terminalwriter
|
| 96 |
+
self._original_fmt = self._style._fmt
|
| 97 |
+
self._level_to_fmt_mapping: Dict[int, str] = {}
|
| 98 |
+
|
| 99 |
+
for level, color_opts in self.LOGLEVEL_COLOROPTS.items():
|
| 100 |
+
self.add_color_level(level, *color_opts)
|
| 101 |
+
|
| 102 |
+
def add_color_level(self, level: int, *color_opts: str) -> None:
|
| 103 |
+
"""Add or update color opts for a log level.
|
| 104 |
+
|
| 105 |
+
:param level:
|
| 106 |
+
Log level to apply a style to, e.g. ``logging.INFO``.
|
| 107 |
+
:param color_opts:
|
| 108 |
+
ANSI escape sequence color options. Capitalized colors indicates
|
| 109 |
+
background color, i.e. ``'green', 'Yellow', 'bold'`` will give bold
|
| 110 |
+
green text on yellow background.
|
| 111 |
+
|
| 112 |
+
.. warning::
|
| 113 |
+
This is an experimental API.
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
assert self._fmt is not None
|
| 117 |
+
levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt)
|
| 118 |
+
if not levelname_fmt_match:
|
| 119 |
+
return
|
| 120 |
+
levelname_fmt = levelname_fmt_match.group()
|
| 121 |
+
|
| 122 |
+
formatted_levelname = levelname_fmt % {"levelname": logging.getLevelName(level)}
|
| 123 |
+
|
| 124 |
+
# add ANSI escape sequences around the formatted levelname
|
| 125 |
+
color_kwargs = {name: True for name in color_opts}
|
| 126 |
+
colorized_formatted_levelname = self._terminalwriter.markup(
|
| 127 |
+
formatted_levelname, **color_kwargs
|
| 128 |
+
)
|
| 129 |
+
self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub(
|
| 130 |
+
colorized_formatted_levelname, self._fmt
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
def format(self, record: logging.LogRecord) -> str:
|
| 134 |
+
fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt)
|
| 135 |
+
self._style._fmt = fmt
|
| 136 |
+
return super().format(record)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class PercentStyleMultiline(logging.PercentStyle):
|
| 140 |
+
"""A logging style with special support for multiline messages.
|
| 141 |
+
|
| 142 |
+
If the message of a record consists of multiple lines, this style
|
| 143 |
+
formats the message as if each line were logged separately.
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
def __init__(self, fmt: str, auto_indent: Union[int, str, bool, None]) -> None:
|
| 147 |
+
super().__init__(fmt)
|
| 148 |
+
self._auto_indent = self._get_auto_indent(auto_indent)
|
| 149 |
+
|
| 150 |
+
@staticmethod
|
| 151 |
+
def _get_auto_indent(auto_indent_option: Union[int, str, bool, None]) -> int:
|
| 152 |
+
"""Determine the current auto indentation setting.
|
| 153 |
+
|
| 154 |
+
Specify auto indent behavior (on/off/fixed) by passing in
|
| 155 |
+
extra={"auto_indent": [value]} to the call to logging.log() or
|
| 156 |
+
using a --log-auto-indent [value] command line or the
|
| 157 |
+
log_auto_indent [value] config option.
|
| 158 |
+
|
| 159 |
+
Default behavior is auto-indent off.
|
| 160 |
+
|
| 161 |
+
Using the string "True" or "on" or the boolean True as the value
|
| 162 |
+
turns auto indent on, using the string "False" or "off" or the
|
| 163 |
+
boolean False or the int 0 turns it off, and specifying a
|
| 164 |
+
positive integer fixes the indentation position to the value
|
| 165 |
+
specified.
|
| 166 |
+
|
| 167 |
+
Any other values for the option are invalid, and will silently be
|
| 168 |
+
converted to the default.
|
| 169 |
+
|
| 170 |
+
:param None|bool|int|str auto_indent_option:
|
| 171 |
+
User specified option for indentation from command line, config
|
| 172 |
+
or extra kwarg. Accepts int, bool or str. str option accepts the
|
| 173 |
+
same range of values as boolean config options, as well as
|
| 174 |
+
positive integers represented in str form.
|
| 175 |
+
|
| 176 |
+
:returns:
|
| 177 |
+
Indentation value, which can be
|
| 178 |
+
-1 (automatically determine indentation) or
|
| 179 |
+
0 (auto-indent turned off) or
|
| 180 |
+
>0 (explicitly set indentation position).
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
if auto_indent_option is None:
|
| 184 |
+
return 0
|
| 185 |
+
elif isinstance(auto_indent_option, bool):
|
| 186 |
+
if auto_indent_option:
|
| 187 |
+
return -1
|
| 188 |
+
else:
|
| 189 |
+
return 0
|
| 190 |
+
elif isinstance(auto_indent_option, int):
|
| 191 |
+
return int(auto_indent_option)
|
| 192 |
+
elif isinstance(auto_indent_option, str):
|
| 193 |
+
try:
|
| 194 |
+
return int(auto_indent_option)
|
| 195 |
+
except ValueError:
|
| 196 |
+
pass
|
| 197 |
+
try:
|
| 198 |
+
if _strtobool(auto_indent_option):
|
| 199 |
+
return -1
|
| 200 |
+
except ValueError:
|
| 201 |
+
return 0
|
| 202 |
+
|
| 203 |
+
return 0
|
| 204 |
+
|
| 205 |
+
def format(self, record: logging.LogRecord) -> str:
|
| 206 |
+
if "\n" in record.message:
|
| 207 |
+
if hasattr(record, "auto_indent"):
|
| 208 |
+
# Passed in from the "extra={}" kwarg on the call to logging.log().
|
| 209 |
+
auto_indent = self._get_auto_indent(record.auto_indent) # type: ignore[attr-defined]
|
| 210 |
+
else:
|
| 211 |
+
auto_indent = self._auto_indent
|
| 212 |
+
|
| 213 |
+
if auto_indent:
|
| 214 |
+
lines = record.message.splitlines()
|
| 215 |
+
formatted = self._fmt % {**record.__dict__, "message": lines[0]}
|
| 216 |
+
|
| 217 |
+
if auto_indent < 0:
|
| 218 |
+
indentation = _remove_ansi_escape_sequences(formatted).find(
|
| 219 |
+
lines[0]
|
| 220 |
+
)
|
| 221 |
+
else:
|
| 222 |
+
# Optimizes logging by allowing a fixed indentation.
|
| 223 |
+
indentation = auto_indent
|
| 224 |
+
lines[0] = formatted
|
| 225 |
+
return ("\n" + " " * indentation).join(lines)
|
| 226 |
+
return self._fmt % record.__dict__
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def get_option_ini(config: Config, *names: str):
|
| 230 |
+
for name in names:
|
| 231 |
+
ret = config.getoption(name) # 'default' arg won't work as expected
|
| 232 |
+
if ret is None:
|
| 233 |
+
ret = config.getini(name)
|
| 234 |
+
if ret:
|
| 235 |
+
return ret
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def pytest_addoption(parser: Parser) -> None:
|
| 239 |
+
"""Add options to control log capturing."""
|
| 240 |
+
group = parser.getgroup("logging")
|
| 241 |
+
|
| 242 |
+
def add_option_ini(option, dest, default=None, type=None, **kwargs):
|
| 243 |
+
parser.addini(
|
| 244 |
+
dest, default=default, type=type, help="Default value for " + option
|
| 245 |
+
)
|
| 246 |
+
group.addoption(option, dest=dest, **kwargs)
|
| 247 |
+
|
| 248 |
+
add_option_ini(
|
| 249 |
+
"--log-level",
|
| 250 |
+
dest="log_level",
|
| 251 |
+
default=None,
|
| 252 |
+
metavar="LEVEL",
|
| 253 |
+
help=(
|
| 254 |
+
"Level of messages to catch/display."
|
| 255 |
+
" Not set by default, so it depends on the root/parent log handler's"
|
| 256 |
+
' effective level, where it is "WARNING" by default.'
|
| 257 |
+
),
|
| 258 |
+
)
|
| 259 |
+
add_option_ini(
|
| 260 |
+
"--log-format",
|
| 261 |
+
dest="log_format",
|
| 262 |
+
default=DEFAULT_LOG_FORMAT,
|
| 263 |
+
help="Log format used by the logging module",
|
| 264 |
+
)
|
| 265 |
+
add_option_ini(
|
| 266 |
+
"--log-date-format",
|
| 267 |
+
dest="log_date_format",
|
| 268 |
+
default=DEFAULT_LOG_DATE_FORMAT,
|
| 269 |
+
help="Log date format used by the logging module",
|
| 270 |
+
)
|
| 271 |
+
parser.addini(
|
| 272 |
+
"log_cli",
|
| 273 |
+
default=False,
|
| 274 |
+
type="bool",
|
| 275 |
+
help='Enable log display during test run (also known as "live logging")',
|
| 276 |
+
)
|
| 277 |
+
add_option_ini(
|
| 278 |
+
"--log-cli-level", dest="log_cli_level", default=None, help="CLI logging level"
|
| 279 |
+
)
|
| 280 |
+
add_option_ini(
|
| 281 |
+
"--log-cli-format",
|
| 282 |
+
dest="log_cli_format",
|
| 283 |
+
default=None,
|
| 284 |
+
help="Log format used by the logging module",
|
| 285 |
+
)
|
| 286 |
+
add_option_ini(
|
| 287 |
+
"--log-cli-date-format",
|
| 288 |
+
dest="log_cli_date_format",
|
| 289 |
+
default=None,
|
| 290 |
+
help="Log date format used by the logging module",
|
| 291 |
+
)
|
| 292 |
+
add_option_ini(
|
| 293 |
+
"--log-file",
|
| 294 |
+
dest="log_file",
|
| 295 |
+
default=None,
|
| 296 |
+
help="Path to a file when logging will be written to",
|
| 297 |
+
)
|
| 298 |
+
add_option_ini(
|
| 299 |
+
"--log-file-level",
|
| 300 |
+
dest="log_file_level",
|
| 301 |
+
default=None,
|
| 302 |
+
help="Log file logging level",
|
| 303 |
+
)
|
| 304 |
+
add_option_ini(
|
| 305 |
+
"--log-file-format",
|
| 306 |
+
dest="log_file_format",
|
| 307 |
+
default=DEFAULT_LOG_FORMAT,
|
| 308 |
+
help="Log format used by the logging module",
|
| 309 |
+
)
|
| 310 |
+
add_option_ini(
|
| 311 |
+
"--log-file-date-format",
|
| 312 |
+
dest="log_file_date_format",
|
| 313 |
+
default=DEFAULT_LOG_DATE_FORMAT,
|
| 314 |
+
help="Log date format used by the logging module",
|
| 315 |
+
)
|
| 316 |
+
add_option_ini(
|
| 317 |
+
"--log-auto-indent",
|
| 318 |
+
dest="log_auto_indent",
|
| 319 |
+
default=None,
|
| 320 |
+
help="Auto-indent multiline messages passed to the logging module. Accepts true|on, false|off or an integer.",
|
| 321 |
+
)
|
| 322 |
+
group.addoption(
|
| 323 |
+
"--log-disable",
|
| 324 |
+
action="append",
|
| 325 |
+
default=[],
|
| 326 |
+
dest="logger_disable",
|
| 327 |
+
help="Disable a logger by name. Can be passed multiple times.",
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
_HandlerType = TypeVar("_HandlerType", bound=logging.Handler)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
# Not using @contextmanager for performance reasons.
|
| 335 |
+
class catching_logs:
|
| 336 |
+
"""Context manager that prepares the whole logging machinery properly."""
|
| 337 |
+
|
| 338 |
+
__slots__ = ("handler", "level", "orig_level")
|
| 339 |
+
|
| 340 |
+
def __init__(self, handler: _HandlerType, level: Optional[int] = None) -> None:
|
| 341 |
+
self.handler = handler
|
| 342 |
+
self.level = level
|
| 343 |
+
|
| 344 |
+
def __enter__(self):
|
| 345 |
+
root_logger = logging.getLogger()
|
| 346 |
+
if self.level is not None:
|
| 347 |
+
self.handler.setLevel(self.level)
|
| 348 |
+
root_logger.addHandler(self.handler)
|
| 349 |
+
if self.level is not None:
|
| 350 |
+
self.orig_level = root_logger.level
|
| 351 |
+
root_logger.setLevel(min(self.orig_level, self.level))
|
| 352 |
+
return self.handler
|
| 353 |
+
|
| 354 |
+
def __exit__(self, type, value, traceback):
|
| 355 |
+
root_logger = logging.getLogger()
|
| 356 |
+
if self.level is not None:
|
| 357 |
+
root_logger.setLevel(self.orig_level)
|
| 358 |
+
root_logger.removeHandler(self.handler)
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
class LogCaptureHandler(logging_StreamHandler):
|
| 362 |
+
"""A logging handler that stores log records and the log text."""
|
| 363 |
+
|
| 364 |
+
def __init__(self) -> None:
|
| 365 |
+
"""Create a new log handler."""
|
| 366 |
+
super().__init__(StringIO())
|
| 367 |
+
self.records: List[logging.LogRecord] = []
|
| 368 |
+
|
| 369 |
+
def emit(self, record: logging.LogRecord) -> None:
|
| 370 |
+
"""Keep the log records in a list in addition to the log text."""
|
| 371 |
+
self.records.append(record)
|
| 372 |
+
super().emit(record)
|
| 373 |
+
|
| 374 |
+
def reset(self) -> None:
|
| 375 |
+
self.records = []
|
| 376 |
+
self.stream = StringIO()
|
| 377 |
+
|
| 378 |
+
def clear(self) -> None:
|
| 379 |
+
self.records.clear()
|
| 380 |
+
self.stream = StringIO()
|
| 381 |
+
|
| 382 |
+
def handleError(self, record: logging.LogRecord) -> None:
|
| 383 |
+
if logging.raiseExceptions:
|
| 384 |
+
# Fail the test if the log message is bad (emit failed).
|
| 385 |
+
# The default behavior of logging is to print "Logging error"
|
| 386 |
+
# to stderr with the call stack and some extra details.
|
| 387 |
+
# pytest wants to make such mistakes visible during testing.
|
| 388 |
+
raise
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
@final
|
| 392 |
+
class LogCaptureFixture:
|
| 393 |
+
"""Provides access and control of log capturing."""
|
| 394 |
+
|
| 395 |
+
def __init__(self, item: nodes.Node, *, _ispytest: bool = False) -> None:
|
| 396 |
+
check_ispytest(_ispytest)
|
| 397 |
+
self._item = item
|
| 398 |
+
self._initial_handler_level: Optional[int] = None
|
| 399 |
+
# Dict of log name -> log level.
|
| 400 |
+
self._initial_logger_levels: Dict[Optional[str], int] = {}
|
| 401 |
+
self._initial_disabled_logging_level: Optional[int] = None
|
| 402 |
+
|
| 403 |
+
def _finalize(self) -> None:
|
| 404 |
+
"""Finalize the fixture.
|
| 405 |
+
|
| 406 |
+
This restores the log levels and the disabled logging levels changed by :meth:`set_level`.
|
| 407 |
+
"""
|
| 408 |
+
# Restore log levels.
|
| 409 |
+
if self._initial_handler_level is not None:
|
| 410 |
+
self.handler.setLevel(self._initial_handler_level)
|
| 411 |
+
for logger_name, level in self._initial_logger_levels.items():
|
| 412 |
+
logger = logging.getLogger(logger_name)
|
| 413 |
+
logger.setLevel(level)
|
| 414 |
+
# Disable logging at the original disabled logging level.
|
| 415 |
+
if self._initial_disabled_logging_level is not None:
|
| 416 |
+
logging.disable(self._initial_disabled_logging_level)
|
| 417 |
+
self._initial_disabled_logging_level = None
|
| 418 |
+
|
| 419 |
+
@property
|
| 420 |
+
def handler(self) -> LogCaptureHandler:
|
| 421 |
+
"""Get the logging handler used by the fixture."""
|
| 422 |
+
return self._item.stash[caplog_handler_key]
|
| 423 |
+
|
| 424 |
+
def get_records(
|
| 425 |
+
self, when: "Literal['setup', 'call', 'teardown']"
|
| 426 |
+
) -> List[logging.LogRecord]:
|
| 427 |
+
"""Get the logging records for one of the possible test phases.
|
| 428 |
+
|
| 429 |
+
:param when:
|
| 430 |
+
Which test phase to obtain the records from.
|
| 431 |
+
Valid values are: "setup", "call" and "teardown".
|
| 432 |
+
|
| 433 |
+
:returns: The list of captured records at the given stage.
|
| 434 |
+
|
| 435 |
+
.. versionadded:: 3.4
|
| 436 |
+
"""
|
| 437 |
+
return self._item.stash[caplog_records_key].get(when, [])
|
| 438 |
+
|
| 439 |
+
@property
|
| 440 |
+
def text(self) -> str:
|
| 441 |
+
"""The formatted log text."""
|
| 442 |
+
return _remove_ansi_escape_sequences(self.handler.stream.getvalue())
|
| 443 |
+
|
| 444 |
+
@property
|
| 445 |
+
def records(self) -> List[logging.LogRecord]:
|
| 446 |
+
"""The list of log records."""
|
| 447 |
+
return self.handler.records
|
| 448 |
+
|
| 449 |
+
@property
|
| 450 |
+
def record_tuples(self) -> List[Tuple[str, int, str]]:
|
| 451 |
+
"""A list of a stripped down version of log records intended
|
| 452 |
+
for use in assertion comparison.
|
| 453 |
+
|
| 454 |
+
The format of the tuple is:
|
| 455 |
+
|
| 456 |
+
(logger_name, log_level, message)
|
| 457 |
+
"""
|
| 458 |
+
return [(r.name, r.levelno, r.getMessage()) for r in self.records]
|
| 459 |
+
|
| 460 |
+
@property
|
| 461 |
+
def messages(self) -> List[str]:
|
| 462 |
+
"""A list of format-interpolated log messages.
|
| 463 |
+
|
| 464 |
+
Unlike 'records', which contains the format string and parameters for
|
| 465 |
+
interpolation, log messages in this list are all interpolated.
|
| 466 |
+
|
| 467 |
+
Unlike 'text', which contains the output from the handler, log
|
| 468 |
+
messages in this list are unadorned with levels, timestamps, etc,
|
| 469 |
+
making exact comparisons more reliable.
|
| 470 |
+
|
| 471 |
+
Note that traceback or stack info (from :func:`logging.exception` or
|
| 472 |
+
the `exc_info` or `stack_info` arguments to the logging functions) is
|
| 473 |
+
not included, as this is added by the formatter in the handler.
|
| 474 |
+
|
| 475 |
+
.. versionadded:: 3.7
|
| 476 |
+
"""
|
| 477 |
+
return [r.getMessage() for r in self.records]
|
| 478 |
+
|
| 479 |
+
def clear(self) -> None:
|
| 480 |
+
"""Reset the list of log records and the captured log text."""
|
| 481 |
+
self.handler.clear()
|
| 482 |
+
|
| 483 |
+
def _force_enable_logging(
|
| 484 |
+
self, level: Union[int, str], logger_obj: logging.Logger
|
| 485 |
+
) -> int:
|
| 486 |
+
"""Enable the desired logging level if the global level was disabled via ``logging.disabled``.
|
| 487 |
+
|
| 488 |
+
Only enables logging levels greater than or equal to the requested ``level``.
|
| 489 |
+
|
| 490 |
+
Does nothing if the desired ``level`` wasn't disabled.
|
| 491 |
+
|
| 492 |
+
:param level:
|
| 493 |
+
The logger level caplog should capture.
|
| 494 |
+
All logging is enabled if a non-standard logging level string is supplied.
|
| 495 |
+
Valid level strings are in :data:`logging._nameToLevel`.
|
| 496 |
+
:param logger_obj: The logger object to check.
|
| 497 |
+
|
| 498 |
+
:return: The original disabled logging level.
|
| 499 |
+
"""
|
| 500 |
+
original_disable_level: int = logger_obj.manager.disable # type: ignore[attr-defined]
|
| 501 |
+
|
| 502 |
+
if isinstance(level, str):
|
| 503 |
+
# Try to translate the level string to an int for `logging.disable()`
|
| 504 |
+
level = logging.getLevelName(level)
|
| 505 |
+
|
| 506 |
+
if not isinstance(level, int):
|
| 507 |
+
# The level provided was not valid, so just un-disable all logging.
|
| 508 |
+
logging.disable(logging.NOTSET)
|
| 509 |
+
elif not logger_obj.isEnabledFor(level):
|
| 510 |
+
# Each level is `10` away from other levels.
|
| 511 |
+
# https://docs.python.org/3/library/logging.html#logging-levels
|
| 512 |
+
disable_level = max(level - 10, logging.NOTSET)
|
| 513 |
+
logging.disable(disable_level)
|
| 514 |
+
|
| 515 |
+
return original_disable_level
|
| 516 |
+
|
| 517 |
+
def set_level(self, level: Union[int, str], logger: Optional[str] = None) -> None:
|
| 518 |
+
"""Set the threshold level of a logger for the duration of a test.
|
| 519 |
+
|
| 520 |
+
Logging messages which are less severe than this level will not be captured.
|
| 521 |
+
|
| 522 |
+
.. versionchanged:: 3.4
|
| 523 |
+
The levels of the loggers changed by this function will be
|
| 524 |
+
restored to their initial values at the end of the test.
|
| 525 |
+
|
| 526 |
+
Will enable the requested logging level if it was disabled via :meth:`logging.disable`.
|
| 527 |
+
|
| 528 |
+
:param level: The level.
|
| 529 |
+
:param logger: The logger to update. If not given, the root logger.
|
| 530 |
+
"""
|
| 531 |
+
logger_obj = logging.getLogger(logger)
|
| 532 |
+
# Save the original log-level to restore it during teardown.
|
| 533 |
+
self._initial_logger_levels.setdefault(logger, logger_obj.level)
|
| 534 |
+
logger_obj.setLevel(level)
|
| 535 |
+
if self._initial_handler_level is None:
|
| 536 |
+
self._initial_handler_level = self.handler.level
|
| 537 |
+
self.handler.setLevel(level)
|
| 538 |
+
initial_disabled_logging_level = self._force_enable_logging(level, logger_obj)
|
| 539 |
+
if self._initial_disabled_logging_level is None:
|
| 540 |
+
self._initial_disabled_logging_level = initial_disabled_logging_level
|
| 541 |
+
|
| 542 |
+
@contextmanager
|
| 543 |
+
def at_level(
|
| 544 |
+
self, level: Union[int, str], logger: Optional[str] = None
|
| 545 |
+
) -> Generator[None, None, None]:
|
| 546 |
+
"""Context manager that sets the level for capturing of logs. After
|
| 547 |
+
the end of the 'with' statement the level is restored to its original
|
| 548 |
+
value.
|
| 549 |
+
|
| 550 |
+
Will enable the requested logging level if it was disabled via :meth:`logging.disable`.
|
| 551 |
+
|
| 552 |
+
:param level: The level.
|
| 553 |
+
:param logger: The logger to update. If not given, the root logger.
|
| 554 |
+
"""
|
| 555 |
+
logger_obj = logging.getLogger(logger)
|
| 556 |
+
orig_level = logger_obj.level
|
| 557 |
+
logger_obj.setLevel(level)
|
| 558 |
+
handler_orig_level = self.handler.level
|
| 559 |
+
self.handler.setLevel(level)
|
| 560 |
+
original_disable_level = self._force_enable_logging(level, logger_obj)
|
| 561 |
+
try:
|
| 562 |
+
yield
|
| 563 |
+
finally:
|
| 564 |
+
logger_obj.setLevel(orig_level)
|
| 565 |
+
self.handler.setLevel(handler_orig_level)
|
| 566 |
+
logging.disable(original_disable_level)
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
@fixture
|
| 570 |
+
def caplog(request: FixtureRequest) -> Generator[LogCaptureFixture, None, None]:
|
| 571 |
+
"""Access and control log capturing.
|
| 572 |
+
|
| 573 |
+
Captured logs are available through the following properties/methods::
|
| 574 |
+
|
| 575 |
+
* caplog.messages -> list of format-interpolated log messages
|
| 576 |
+
* caplog.text -> string containing formatted log output
|
| 577 |
+
* caplog.records -> list of logging.LogRecord instances
|
| 578 |
+
* caplog.record_tuples -> list of (logger_name, level, message) tuples
|
| 579 |
+
* caplog.clear() -> clear captured records and formatted log output string
|
| 580 |
+
"""
|
| 581 |
+
result = LogCaptureFixture(request.node, _ispytest=True)
|
| 582 |
+
yield result
|
| 583 |
+
result._finalize()
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
def get_log_level_for_setting(config: Config, *setting_names: str) -> Optional[int]:
|
| 587 |
+
for setting_name in setting_names:
|
| 588 |
+
log_level = config.getoption(setting_name)
|
| 589 |
+
if log_level is None:
|
| 590 |
+
log_level = config.getini(setting_name)
|
| 591 |
+
if log_level:
|
| 592 |
+
break
|
| 593 |
+
else:
|
| 594 |
+
return None
|
| 595 |
+
|
| 596 |
+
if isinstance(log_level, str):
|
| 597 |
+
log_level = log_level.upper()
|
| 598 |
+
try:
|
| 599 |
+
return int(getattr(logging, log_level, log_level))
|
| 600 |
+
except ValueError as e:
|
| 601 |
+
# Python logging does not recognise this as a logging level
|
| 602 |
+
raise UsageError(
|
| 603 |
+
"'{}' is not recognized as a logging level name for "
|
| 604 |
+
"'{}'. Please consider passing the "
|
| 605 |
+
"logging level num instead.".format(log_level, setting_name)
|
| 606 |
+
) from e
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
# run after terminalreporter/capturemanager are configured
|
| 610 |
+
@hookimpl(trylast=True)
|
| 611 |
+
def pytest_configure(config: Config) -> None:
|
| 612 |
+
config.pluginmanager.register(LoggingPlugin(config), "logging-plugin")
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
class LoggingPlugin:
|
| 616 |
+
"""Attaches to the logging module and captures log messages for each test."""
|
| 617 |
+
|
| 618 |
+
def __init__(self, config: Config) -> None:
|
| 619 |
+
"""Create a new plugin to capture log messages.
|
| 620 |
+
|
| 621 |
+
The formatter can be safely shared across all handlers so
|
| 622 |
+
create a single one for the entire test session here.
|
| 623 |
+
"""
|
| 624 |
+
self._config = config
|
| 625 |
+
|
| 626 |
+
# Report logging.
|
| 627 |
+
self.formatter = self._create_formatter(
|
| 628 |
+
get_option_ini(config, "log_format"),
|
| 629 |
+
get_option_ini(config, "log_date_format"),
|
| 630 |
+
get_option_ini(config, "log_auto_indent"),
|
| 631 |
+
)
|
| 632 |
+
self.log_level = get_log_level_for_setting(config, "log_level")
|
| 633 |
+
self.caplog_handler = LogCaptureHandler()
|
| 634 |
+
self.caplog_handler.setFormatter(self.formatter)
|
| 635 |
+
self.report_handler = LogCaptureHandler()
|
| 636 |
+
self.report_handler.setFormatter(self.formatter)
|
| 637 |
+
|
| 638 |
+
# File logging.
|
| 639 |
+
self.log_file_level = get_log_level_for_setting(config, "log_file_level")
|
| 640 |
+
log_file = get_option_ini(config, "log_file") or os.devnull
|
| 641 |
+
if log_file != os.devnull:
|
| 642 |
+
directory = os.path.dirname(os.path.abspath(log_file))
|
| 643 |
+
if not os.path.isdir(directory):
|
| 644 |
+
os.makedirs(directory)
|
| 645 |
+
|
| 646 |
+
self.log_file_handler = _FileHandler(log_file, mode="w", encoding="UTF-8")
|
| 647 |
+
log_file_format = get_option_ini(config, "log_file_format", "log_format")
|
| 648 |
+
log_file_date_format = get_option_ini(
|
| 649 |
+
config, "log_file_date_format", "log_date_format"
|
| 650 |
+
)
|
| 651 |
+
|
| 652 |
+
log_file_formatter = DatetimeFormatter(
|
| 653 |
+
log_file_format, datefmt=log_file_date_format
|
| 654 |
+
)
|
| 655 |
+
self.log_file_handler.setFormatter(log_file_formatter)
|
| 656 |
+
|
| 657 |
+
# CLI/live logging.
|
| 658 |
+
self.log_cli_level = get_log_level_for_setting(
|
| 659 |
+
config, "log_cli_level", "log_level"
|
| 660 |
+
)
|
| 661 |
+
if self._log_cli_enabled():
|
| 662 |
+
terminal_reporter = config.pluginmanager.get_plugin("terminalreporter")
|
| 663 |
+
capture_manager = config.pluginmanager.get_plugin("capturemanager")
|
| 664 |
+
# if capturemanager plugin is disabled, live logging still works.
|
| 665 |
+
self.log_cli_handler: Union[
|
| 666 |
+
_LiveLoggingStreamHandler, _LiveLoggingNullHandler
|
| 667 |
+
] = _LiveLoggingStreamHandler(terminal_reporter, capture_manager)
|
| 668 |
+
else:
|
| 669 |
+
self.log_cli_handler = _LiveLoggingNullHandler()
|
| 670 |
+
log_cli_formatter = self._create_formatter(
|
| 671 |
+
get_option_ini(config, "log_cli_format", "log_format"),
|
| 672 |
+
get_option_ini(config, "log_cli_date_format", "log_date_format"),
|
| 673 |
+
get_option_ini(config, "log_auto_indent"),
|
| 674 |
+
)
|
| 675 |
+
self.log_cli_handler.setFormatter(log_cli_formatter)
|
| 676 |
+
self._disable_loggers(loggers_to_disable=config.option.logger_disable)
|
| 677 |
+
|
| 678 |
+
def _disable_loggers(self, loggers_to_disable: List[str]) -> None:
|
| 679 |
+
if not loggers_to_disable:
|
| 680 |
+
return
|
| 681 |
+
|
| 682 |
+
for name in loggers_to_disable:
|
| 683 |
+
logger = logging.getLogger(name)
|
| 684 |
+
logger.disabled = True
|
| 685 |
+
|
| 686 |
+
def _create_formatter(self, log_format, log_date_format, auto_indent):
|
| 687 |
+
# Color option doesn't exist if terminal plugin is disabled.
|
| 688 |
+
color = getattr(self._config.option, "color", "no")
|
| 689 |
+
if color != "no" and ColoredLevelFormatter.LEVELNAME_FMT_REGEX.search(
|
| 690 |
+
log_format
|
| 691 |
+
):
|
| 692 |
+
formatter: logging.Formatter = ColoredLevelFormatter(
|
| 693 |
+
create_terminal_writer(self._config), log_format, log_date_format
|
| 694 |
+
)
|
| 695 |
+
else:
|
| 696 |
+
formatter = DatetimeFormatter(log_format, log_date_format)
|
| 697 |
+
|
| 698 |
+
formatter._style = PercentStyleMultiline(
|
| 699 |
+
formatter._style._fmt, auto_indent=auto_indent
|
| 700 |
+
)
|
| 701 |
+
|
| 702 |
+
return formatter
|
| 703 |
+
|
| 704 |
+
def set_log_path(self, fname: str) -> None:
|
| 705 |
+
"""Set the filename parameter for Logging.FileHandler().
|
| 706 |
+
|
| 707 |
+
Creates parent directory if it does not exist.
|
| 708 |
+
|
| 709 |
+
.. warning::
|
| 710 |
+
This is an experimental API.
|
| 711 |
+
"""
|
| 712 |
+
fpath = Path(fname)
|
| 713 |
+
|
| 714 |
+
if not fpath.is_absolute():
|
| 715 |
+
fpath = self._config.rootpath / fpath
|
| 716 |
+
|
| 717 |
+
if not fpath.parent.exists():
|
| 718 |
+
fpath.parent.mkdir(exist_ok=True, parents=True)
|
| 719 |
+
|
| 720 |
+
# https://github.com/python/mypy/issues/11193
|
| 721 |
+
stream: io.TextIOWrapper = fpath.open(mode="w", encoding="UTF-8") # type: ignore[assignment]
|
| 722 |
+
old_stream = self.log_file_handler.setStream(stream)
|
| 723 |
+
if old_stream:
|
| 724 |
+
old_stream.close()
|
| 725 |
+
|
| 726 |
+
def _log_cli_enabled(self):
|
| 727 |
+
"""Return whether live logging is enabled."""
|
| 728 |
+
enabled = self._config.getoption(
|
| 729 |
+
"--log-cli-level"
|
| 730 |
+
) is not None or self._config.getini("log_cli")
|
| 731 |
+
if not enabled:
|
| 732 |
+
return False
|
| 733 |
+
|
| 734 |
+
terminal_reporter = self._config.pluginmanager.get_plugin("terminalreporter")
|
| 735 |
+
if terminal_reporter is None:
|
| 736 |
+
# terminal reporter is disabled e.g. by pytest-xdist.
|
| 737 |
+
return False
|
| 738 |
+
|
| 739 |
+
return True
|
| 740 |
+
|
| 741 |
+
@hookimpl(hookwrapper=True, tryfirst=True)
|
| 742 |
+
def pytest_sessionstart(self) -> Generator[None, None, None]:
|
| 743 |
+
self.log_cli_handler.set_when("sessionstart")
|
| 744 |
+
|
| 745 |
+
with catching_logs(self.log_cli_handler, level=self.log_cli_level):
|
| 746 |
+
with catching_logs(self.log_file_handler, level=self.log_file_level):
|
| 747 |
+
yield
|
| 748 |
+
|
| 749 |
+
@hookimpl(hookwrapper=True, tryfirst=True)
|
| 750 |
+
def pytest_collection(self) -> Generator[None, None, None]:
|
| 751 |
+
self.log_cli_handler.set_when("collection")
|
| 752 |
+
|
| 753 |
+
with catching_logs(self.log_cli_handler, level=self.log_cli_level):
|
| 754 |
+
with catching_logs(self.log_file_handler, level=self.log_file_level):
|
| 755 |
+
yield
|
| 756 |
+
|
| 757 |
+
@hookimpl(hookwrapper=True)
|
| 758 |
+
def pytest_runtestloop(self, session: Session) -> Generator[None, None, None]:
|
| 759 |
+
if session.config.option.collectonly:
|
| 760 |
+
yield
|
| 761 |
+
return
|
| 762 |
+
|
| 763 |
+
if self._log_cli_enabled() and self._config.getoption("verbose") < 1:
|
| 764 |
+
# The verbose flag is needed to avoid messy test progress output.
|
| 765 |
+
self._config.option.verbose = 1
|
| 766 |
+
|
| 767 |
+
with catching_logs(self.log_cli_handler, level=self.log_cli_level):
|
| 768 |
+
with catching_logs(self.log_file_handler, level=self.log_file_level):
|
| 769 |
+
yield # Run all the tests.
|
| 770 |
+
|
| 771 |
+
@hookimpl
|
| 772 |
+
def pytest_runtest_logstart(self) -> None:
|
| 773 |
+
self.log_cli_handler.reset()
|
| 774 |
+
self.log_cli_handler.set_when("start")
|
| 775 |
+
|
| 776 |
+
@hookimpl
|
| 777 |
+
def pytest_runtest_logreport(self) -> None:
|
| 778 |
+
self.log_cli_handler.set_when("logreport")
|
| 779 |
+
|
| 780 |
+
def _runtest_for(self, item: nodes.Item, when: str) -> Generator[None, None, None]:
|
| 781 |
+
"""Implement the internals of the pytest_runtest_xxx() hooks."""
|
| 782 |
+
with catching_logs(
|
| 783 |
+
self.caplog_handler,
|
| 784 |
+
level=self.log_level,
|
| 785 |
+
) as caplog_handler, catching_logs(
|
| 786 |
+
self.report_handler,
|
| 787 |
+
level=self.log_level,
|
| 788 |
+
) as report_handler:
|
| 789 |
+
caplog_handler.reset()
|
| 790 |
+
report_handler.reset()
|
| 791 |
+
item.stash[caplog_records_key][when] = caplog_handler.records
|
| 792 |
+
item.stash[caplog_handler_key] = caplog_handler
|
| 793 |
+
|
| 794 |
+
yield
|
| 795 |
+
|
| 796 |
+
log = report_handler.stream.getvalue().strip()
|
| 797 |
+
item.add_report_section(when, "log", log)
|
| 798 |
+
|
| 799 |
+
@hookimpl(hookwrapper=True)
|
| 800 |
+
def pytest_runtest_setup(self, item: nodes.Item) -> Generator[None, None, None]:
|
| 801 |
+
self.log_cli_handler.set_when("setup")
|
| 802 |
+
|
| 803 |
+
empty: Dict[str, List[logging.LogRecord]] = {}
|
| 804 |
+
item.stash[caplog_records_key] = empty
|
| 805 |
+
yield from self._runtest_for(item, "setup")
|
| 806 |
+
|
| 807 |
+
@hookimpl(hookwrapper=True)
|
| 808 |
+
def pytest_runtest_call(self, item: nodes.Item) -> Generator[None, None, None]:
|
| 809 |
+
self.log_cli_handler.set_when("call")
|
| 810 |
+
|
| 811 |
+
yield from self._runtest_for(item, "call")
|
| 812 |
+
|
| 813 |
+
@hookimpl(hookwrapper=True)
|
| 814 |
+
def pytest_runtest_teardown(self, item: nodes.Item) -> Generator[None, None, None]:
|
| 815 |
+
self.log_cli_handler.set_when("teardown")
|
| 816 |
+
|
| 817 |
+
yield from self._runtest_for(item, "teardown")
|
| 818 |
+
del item.stash[caplog_records_key]
|
| 819 |
+
del item.stash[caplog_handler_key]
|
| 820 |
+
|
| 821 |
+
@hookimpl
|
| 822 |
+
def pytest_runtest_logfinish(self) -> None:
|
| 823 |
+
self.log_cli_handler.set_when("finish")
|
| 824 |
+
|
| 825 |
+
@hookimpl(hookwrapper=True, tryfirst=True)
|
| 826 |
+
def pytest_sessionfinish(self) -> Generator[None, None, None]:
|
| 827 |
+
self.log_cli_handler.set_when("sessionfinish")
|
| 828 |
+
|
| 829 |
+
with catching_logs(self.log_cli_handler, level=self.log_cli_level):
|
| 830 |
+
with catching_logs(self.log_file_handler, level=self.log_file_level):
|
| 831 |
+
yield
|
| 832 |
+
|
| 833 |
+
@hookimpl
|
| 834 |
+
def pytest_unconfigure(self) -> None:
|
| 835 |
+
# Close the FileHandler explicitly.
|
| 836 |
+
# (logging.shutdown might have lost the weakref?!)
|
| 837 |
+
self.log_file_handler.close()
|
| 838 |
+
|
| 839 |
+
|
| 840 |
+
class _FileHandler(logging.FileHandler):
|
| 841 |
+
"""A logging FileHandler with pytest tweaks."""
|
| 842 |
+
|
| 843 |
+
def handleError(self, record: logging.LogRecord) -> None:
|
| 844 |
+
# Handled by LogCaptureHandler.
|
| 845 |
+
pass
|
| 846 |
+
|
| 847 |
+
|
| 848 |
+
class _LiveLoggingStreamHandler(logging_StreamHandler):
|
| 849 |
+
"""A logging StreamHandler used by the live logging feature: it will
|
| 850 |
+
write a newline before the first log message in each test.
|
| 851 |
+
|
| 852 |
+
During live logging we must also explicitly disable stdout/stderr
|
| 853 |
+
capturing otherwise it will get captured and won't appear in the
|
| 854 |
+
terminal.
|
| 855 |
+
"""
|
| 856 |
+
|
| 857 |
+
# Officially stream needs to be a IO[str], but TerminalReporter
|
| 858 |
+
# isn't. So force it.
|
| 859 |
+
stream: TerminalReporter = None # type: ignore
|
| 860 |
+
|
| 861 |
+
def __init__(
|
| 862 |
+
self,
|
| 863 |
+
terminal_reporter: TerminalReporter,
|
| 864 |
+
capture_manager: Optional[CaptureManager],
|
| 865 |
+
) -> None:
|
| 866 |
+
super().__init__(stream=terminal_reporter) # type: ignore[arg-type]
|
| 867 |
+
self.capture_manager = capture_manager
|
| 868 |
+
self.reset()
|
| 869 |
+
self.set_when(None)
|
| 870 |
+
self._test_outcome_written = False
|
| 871 |
+
|
| 872 |
+
def reset(self) -> None:
|
| 873 |
+
"""Reset the handler; should be called before the start of each test."""
|
| 874 |
+
self._first_record_emitted = False
|
| 875 |
+
|
| 876 |
+
def set_when(self, when: Optional[str]) -> None:
|
| 877 |
+
"""Prepare for the given test phase (setup/call/teardown)."""
|
| 878 |
+
self._when = when
|
| 879 |
+
self._section_name_shown = False
|
| 880 |
+
if when == "start":
|
| 881 |
+
self._test_outcome_written = False
|
| 882 |
+
|
| 883 |
+
def emit(self, record: logging.LogRecord) -> None:
|
| 884 |
+
ctx_manager = (
|
| 885 |
+
self.capture_manager.global_and_fixture_disabled()
|
| 886 |
+
if self.capture_manager
|
| 887 |
+
else nullcontext()
|
| 888 |
+
)
|
| 889 |
+
with ctx_manager:
|
| 890 |
+
if not self._first_record_emitted:
|
| 891 |
+
self.stream.write("\n")
|
| 892 |
+
self._first_record_emitted = True
|
| 893 |
+
elif self._when in ("teardown", "finish"):
|
| 894 |
+
if not self._test_outcome_written:
|
| 895 |
+
self._test_outcome_written = True
|
| 896 |
+
self.stream.write("\n")
|
| 897 |
+
if not self._section_name_shown and self._when:
|
| 898 |
+
self.stream.section("live log " + self._when, sep="-", bold=True)
|
| 899 |
+
self._section_name_shown = True
|
| 900 |
+
super().emit(record)
|
| 901 |
+
|
| 902 |
+
def handleError(self, record: logging.LogRecord) -> None:
|
| 903 |
+
# Handled by LogCaptureHandler.
|
| 904 |
+
pass
|
| 905 |
+
|
| 906 |
+
|
| 907 |
+
class _LiveLoggingNullHandler(logging.NullHandler):
|
| 908 |
+
"""A logging handler used when live logging is disabled."""
|
| 909 |
+
|
| 910 |
+
def reset(self) -> None:
|
| 911 |
+
pass
|
| 912 |
+
|
| 913 |
+
def set_when(self, when: str) -> None:
|
| 914 |
+
pass
|
| 915 |
+
|
| 916 |
+
def handleError(self, record: logging.LogRecord) -> None:
|
| 917 |
+
# Handled by LogCaptureHandler.
|
| 918 |
+
pass
|
wemm/lib/python3.10/site-packages/_pytest/mark/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (8.4 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/_pytest/monkeypatch.py
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Monkeypatching and mocking functionality."""
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
import sys
|
| 5 |
+
import warnings
|
| 6 |
+
from contextlib import contextmanager
|
| 7 |
+
from typing import Any
|
| 8 |
+
from typing import Generator
|
| 9 |
+
from typing import List
|
| 10 |
+
from typing import Mapping
|
| 11 |
+
from typing import MutableMapping
|
| 12 |
+
from typing import Optional
|
| 13 |
+
from typing import overload
|
| 14 |
+
from typing import Tuple
|
| 15 |
+
from typing import TypeVar
|
| 16 |
+
from typing import Union
|
| 17 |
+
|
| 18 |
+
from _pytest.compat import final
|
| 19 |
+
from _pytest.fixtures import fixture
|
| 20 |
+
from _pytest.warning_types import PytestWarning
|
| 21 |
+
|
| 22 |
+
RE_IMPORT_ERROR_NAME = re.compile(r"^No module named (.*)$")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
K = TypeVar("K")
|
| 26 |
+
V = TypeVar("V")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@fixture
|
| 30 |
+
def monkeypatch() -> Generator["MonkeyPatch", None, None]:
|
| 31 |
+
"""A convenient fixture for monkey-patching.
|
| 32 |
+
|
| 33 |
+
The fixture provides these methods to modify objects, dictionaries, or
|
| 34 |
+
:data:`os.environ`:
|
| 35 |
+
|
| 36 |
+
* :meth:`monkeypatch.setattr(obj, name, value, raising=True) <pytest.MonkeyPatch.setattr>`
|
| 37 |
+
* :meth:`monkeypatch.delattr(obj, name, raising=True) <pytest.MonkeyPatch.delattr>`
|
| 38 |
+
* :meth:`monkeypatch.setitem(mapping, name, value) <pytest.MonkeyPatch.setitem>`
|
| 39 |
+
* :meth:`monkeypatch.delitem(obj, name, raising=True) <pytest.MonkeyPatch.delitem>`
|
| 40 |
+
* :meth:`monkeypatch.setenv(name, value, prepend=None) <pytest.MonkeyPatch.setenv>`
|
| 41 |
+
* :meth:`monkeypatch.delenv(name, raising=True) <pytest.MonkeyPatch.delenv>`
|
| 42 |
+
* :meth:`monkeypatch.syspath_prepend(path) <pytest.MonkeyPatch.syspath_prepend>`
|
| 43 |
+
* :meth:`monkeypatch.chdir(path) <pytest.MonkeyPatch.chdir>`
|
| 44 |
+
* :meth:`monkeypatch.context() <pytest.MonkeyPatch.context>`
|
| 45 |
+
|
| 46 |
+
All modifications will be undone after the requesting test function or
|
| 47 |
+
fixture has finished. The ``raising`` parameter determines if a :class:`KeyError`
|
| 48 |
+
or :class:`AttributeError` will be raised if the set/deletion operation does not have the
|
| 49 |
+
specified target.
|
| 50 |
+
|
| 51 |
+
To undo modifications done by the fixture in a contained scope,
|
| 52 |
+
use :meth:`context() <pytest.MonkeyPatch.context>`.
|
| 53 |
+
"""
|
| 54 |
+
mpatch = MonkeyPatch()
|
| 55 |
+
yield mpatch
|
| 56 |
+
mpatch.undo()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def resolve(name: str) -> object:
|
| 60 |
+
# Simplified from zope.dottedname.
|
| 61 |
+
parts = name.split(".")
|
| 62 |
+
|
| 63 |
+
used = parts.pop(0)
|
| 64 |
+
found: object = __import__(used)
|
| 65 |
+
for part in parts:
|
| 66 |
+
used += "." + part
|
| 67 |
+
try:
|
| 68 |
+
found = getattr(found, part)
|
| 69 |
+
except AttributeError:
|
| 70 |
+
pass
|
| 71 |
+
else:
|
| 72 |
+
continue
|
| 73 |
+
# We use explicit un-nesting of the handling block in order
|
| 74 |
+
# to avoid nested exceptions.
|
| 75 |
+
try:
|
| 76 |
+
__import__(used)
|
| 77 |
+
except ImportError as ex:
|
| 78 |
+
expected = str(ex).split()[-1]
|
| 79 |
+
if expected == used:
|
| 80 |
+
raise
|
| 81 |
+
else:
|
| 82 |
+
raise ImportError(f"import error in {used}: {ex}") from ex
|
| 83 |
+
found = annotated_getattr(found, part, used)
|
| 84 |
+
return found
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def annotated_getattr(obj: object, name: str, ann: str) -> object:
|
| 88 |
+
try:
|
| 89 |
+
obj = getattr(obj, name)
|
| 90 |
+
except AttributeError as e:
|
| 91 |
+
raise AttributeError(
|
| 92 |
+
"{!r} object at {} has no attribute {!r}".format(
|
| 93 |
+
type(obj).__name__, ann, name
|
| 94 |
+
)
|
| 95 |
+
) from e
|
| 96 |
+
return obj
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def derive_importpath(import_path: str, raising: bool) -> Tuple[str, object]:
|
| 100 |
+
if not isinstance(import_path, str) or "." not in import_path:
|
| 101 |
+
raise TypeError(f"must be absolute import path string, not {import_path!r}")
|
| 102 |
+
module, attr = import_path.rsplit(".", 1)
|
| 103 |
+
target = resolve(module)
|
| 104 |
+
if raising:
|
| 105 |
+
annotated_getattr(target, attr, ann=module)
|
| 106 |
+
return attr, target
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class Notset:
|
| 110 |
+
def __repr__(self) -> str:
|
| 111 |
+
return "<notset>"
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
notset = Notset()
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
@final
|
| 118 |
+
class MonkeyPatch:
|
| 119 |
+
"""Helper to conveniently monkeypatch attributes/items/environment
|
| 120 |
+
variables/syspath.
|
| 121 |
+
|
| 122 |
+
Returned by the :fixture:`monkeypatch` fixture.
|
| 123 |
+
|
| 124 |
+
.. versionchanged:: 6.2
|
| 125 |
+
Can now also be used directly as `pytest.MonkeyPatch()`, for when
|
| 126 |
+
the fixture is not available. In this case, use
|
| 127 |
+
:meth:`with MonkeyPatch.context() as mp: <context>` or remember to call
|
| 128 |
+
:meth:`undo` explicitly.
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
def __init__(self) -> None:
|
| 132 |
+
self._setattr: List[Tuple[object, str, object]] = []
|
| 133 |
+
self._setitem: List[Tuple[Mapping[Any, Any], object, object]] = []
|
| 134 |
+
self._cwd: Optional[str] = None
|
| 135 |
+
self._savesyspath: Optional[List[str]] = None
|
| 136 |
+
|
| 137 |
+
@classmethod
|
| 138 |
+
@contextmanager
|
| 139 |
+
def context(cls) -> Generator["MonkeyPatch", None, None]:
|
| 140 |
+
"""Context manager that returns a new :class:`MonkeyPatch` object
|
| 141 |
+
which undoes any patching done inside the ``with`` block upon exit.
|
| 142 |
+
|
| 143 |
+
Example:
|
| 144 |
+
|
| 145 |
+
.. code-block:: python
|
| 146 |
+
|
| 147 |
+
import functools
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def test_partial(monkeypatch):
|
| 151 |
+
with monkeypatch.context() as m:
|
| 152 |
+
m.setattr(functools, "partial", 3)
|
| 153 |
+
|
| 154 |
+
Useful in situations where it is desired to undo some patches before the test ends,
|
| 155 |
+
such as mocking ``stdlib`` functions that might break pytest itself if mocked (for examples
|
| 156 |
+
of this see :issue:`3290`).
|
| 157 |
+
"""
|
| 158 |
+
m = cls()
|
| 159 |
+
try:
|
| 160 |
+
yield m
|
| 161 |
+
finally:
|
| 162 |
+
m.undo()
|
| 163 |
+
|
| 164 |
+
@overload
|
| 165 |
+
def setattr(
|
| 166 |
+
self,
|
| 167 |
+
target: str,
|
| 168 |
+
name: object,
|
| 169 |
+
value: Notset = ...,
|
| 170 |
+
raising: bool = ...,
|
| 171 |
+
) -> None:
|
| 172 |
+
...
|
| 173 |
+
|
| 174 |
+
@overload
|
| 175 |
+
def setattr(
|
| 176 |
+
self,
|
| 177 |
+
target: object,
|
| 178 |
+
name: str,
|
| 179 |
+
value: object,
|
| 180 |
+
raising: bool = ...,
|
| 181 |
+
) -> None:
|
| 182 |
+
...
|
| 183 |
+
|
| 184 |
+
def setattr(
|
| 185 |
+
self,
|
| 186 |
+
target: Union[str, object],
|
| 187 |
+
name: Union[object, str],
|
| 188 |
+
value: object = notset,
|
| 189 |
+
raising: bool = True,
|
| 190 |
+
) -> None:
|
| 191 |
+
"""
|
| 192 |
+
Set attribute value on target, memorizing the old value.
|
| 193 |
+
|
| 194 |
+
For example:
|
| 195 |
+
|
| 196 |
+
.. code-block:: python
|
| 197 |
+
|
| 198 |
+
import os
|
| 199 |
+
|
| 200 |
+
monkeypatch.setattr(os, "getcwd", lambda: "/")
|
| 201 |
+
|
| 202 |
+
The code above replaces the :func:`os.getcwd` function by a ``lambda`` which
|
| 203 |
+
always returns ``"/"``.
|
| 204 |
+
|
| 205 |
+
For convenience, you can specify a string as ``target`` which
|
| 206 |
+
will be interpreted as a dotted import path, with the last part
|
| 207 |
+
being the attribute name:
|
| 208 |
+
|
| 209 |
+
.. code-block:: python
|
| 210 |
+
|
| 211 |
+
monkeypatch.setattr("os.getcwd", lambda: "/")
|
| 212 |
+
|
| 213 |
+
Raises :class:`AttributeError` if the attribute does not exist, unless
|
| 214 |
+
``raising`` is set to False.
|
| 215 |
+
|
| 216 |
+
**Where to patch**
|
| 217 |
+
|
| 218 |
+
``monkeypatch.setattr`` works by (temporarily) changing the object that a name points to with another one.
|
| 219 |
+
There can be many names pointing to any individual object, so for patching to work you must ensure
|
| 220 |
+
that you patch the name used by the system under test.
|
| 221 |
+
|
| 222 |
+
See the section :ref:`Where to patch <python:where-to-patch>` in the :mod:`unittest.mock`
|
| 223 |
+
docs for a complete explanation, which is meant for :func:`unittest.mock.patch` but
|
| 224 |
+
applies to ``monkeypatch.setattr`` as well.
|
| 225 |
+
"""
|
| 226 |
+
__tracebackhide__ = True
|
| 227 |
+
import inspect
|
| 228 |
+
|
| 229 |
+
if isinstance(value, Notset):
|
| 230 |
+
if not isinstance(target, str):
|
| 231 |
+
raise TypeError(
|
| 232 |
+
"use setattr(target, name, value) or "
|
| 233 |
+
"setattr(target, value) with target being a dotted "
|
| 234 |
+
"import string"
|
| 235 |
+
)
|
| 236 |
+
value = name
|
| 237 |
+
name, target = derive_importpath(target, raising)
|
| 238 |
+
else:
|
| 239 |
+
if not isinstance(name, str):
|
| 240 |
+
raise TypeError(
|
| 241 |
+
"use setattr(target, name, value) with name being a string or "
|
| 242 |
+
"setattr(target, value) with target being a dotted "
|
| 243 |
+
"import string"
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
oldval = getattr(target, name, notset)
|
| 247 |
+
if raising and oldval is notset:
|
| 248 |
+
raise AttributeError(f"{target!r} has no attribute {name!r}")
|
| 249 |
+
|
| 250 |
+
# avoid class descriptors like staticmethod/classmethod
|
| 251 |
+
if inspect.isclass(target):
|
| 252 |
+
oldval = target.__dict__.get(name, notset)
|
| 253 |
+
self._setattr.append((target, name, oldval))
|
| 254 |
+
setattr(target, name, value)
|
| 255 |
+
|
| 256 |
+
def delattr(
|
| 257 |
+
self,
|
| 258 |
+
target: Union[object, str],
|
| 259 |
+
name: Union[str, Notset] = notset,
|
| 260 |
+
raising: bool = True,
|
| 261 |
+
) -> None:
|
| 262 |
+
"""Delete attribute ``name`` from ``target``.
|
| 263 |
+
|
| 264 |
+
If no ``name`` is specified and ``target`` is a string
|
| 265 |
+
it will be interpreted as a dotted import path with the
|
| 266 |
+
last part being the attribute name.
|
| 267 |
+
|
| 268 |
+
Raises AttributeError it the attribute does not exist, unless
|
| 269 |
+
``raising`` is set to False.
|
| 270 |
+
"""
|
| 271 |
+
__tracebackhide__ = True
|
| 272 |
+
import inspect
|
| 273 |
+
|
| 274 |
+
if isinstance(name, Notset):
|
| 275 |
+
if not isinstance(target, str):
|
| 276 |
+
raise TypeError(
|
| 277 |
+
"use delattr(target, name) or "
|
| 278 |
+
"delattr(target) with target being a dotted "
|
| 279 |
+
"import string"
|
| 280 |
+
)
|
| 281 |
+
name, target = derive_importpath(target, raising)
|
| 282 |
+
|
| 283 |
+
if not hasattr(target, name):
|
| 284 |
+
if raising:
|
| 285 |
+
raise AttributeError(name)
|
| 286 |
+
else:
|
| 287 |
+
oldval = getattr(target, name, notset)
|
| 288 |
+
# Avoid class descriptors like staticmethod/classmethod.
|
| 289 |
+
if inspect.isclass(target):
|
| 290 |
+
oldval = target.__dict__.get(name, notset)
|
| 291 |
+
self._setattr.append((target, name, oldval))
|
| 292 |
+
delattr(target, name)
|
| 293 |
+
|
| 294 |
+
def setitem(self, dic: Mapping[K, V], name: K, value: V) -> None:
|
| 295 |
+
"""Set dictionary entry ``name`` to value."""
|
| 296 |
+
self._setitem.append((dic, name, dic.get(name, notset)))
|
| 297 |
+
# Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict
|
| 298 |
+
dic[name] = value # type: ignore[index]
|
| 299 |
+
|
| 300 |
+
def delitem(self, dic: Mapping[K, V], name: K, raising: bool = True) -> None:
|
| 301 |
+
"""Delete ``name`` from dict.
|
| 302 |
+
|
| 303 |
+
Raises ``KeyError`` if it doesn't exist, unless ``raising`` is set to
|
| 304 |
+
False.
|
| 305 |
+
"""
|
| 306 |
+
if name not in dic:
|
| 307 |
+
if raising:
|
| 308 |
+
raise KeyError(name)
|
| 309 |
+
else:
|
| 310 |
+
self._setitem.append((dic, name, dic.get(name, notset)))
|
| 311 |
+
# Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict
|
| 312 |
+
del dic[name] # type: ignore[attr-defined]
|
| 313 |
+
|
| 314 |
+
def setenv(self, name: str, value: str, prepend: Optional[str] = None) -> None:
|
| 315 |
+
"""Set environment variable ``name`` to ``value``.
|
| 316 |
+
|
| 317 |
+
If ``prepend`` is a character, read the current environment variable
|
| 318 |
+
value and prepend the ``value`` adjoined with the ``prepend``
|
| 319 |
+
character.
|
| 320 |
+
"""
|
| 321 |
+
if not isinstance(value, str):
|
| 322 |
+
warnings.warn( # type: ignore[unreachable]
|
| 323 |
+
PytestWarning(
|
| 324 |
+
"Value of environment variable {name} type should be str, but got "
|
| 325 |
+
"{value!r} (type: {type}); converted to str implicitly".format(
|
| 326 |
+
name=name, value=value, type=type(value).__name__
|
| 327 |
+
)
|
| 328 |
+
),
|
| 329 |
+
stacklevel=2,
|
| 330 |
+
)
|
| 331 |
+
value = str(value)
|
| 332 |
+
if prepend and name in os.environ:
|
| 333 |
+
value = value + prepend + os.environ[name]
|
| 334 |
+
self.setitem(os.environ, name, value)
|
| 335 |
+
|
| 336 |
+
def delenv(self, name: str, raising: bool = True) -> None:
|
| 337 |
+
"""Delete ``name`` from the environment.
|
| 338 |
+
|
| 339 |
+
Raises ``KeyError`` if it does not exist, unless ``raising`` is set to
|
| 340 |
+
False.
|
| 341 |
+
"""
|
| 342 |
+
environ: MutableMapping[str, str] = os.environ
|
| 343 |
+
self.delitem(environ, name, raising=raising)
|
| 344 |
+
|
| 345 |
+
def syspath_prepend(self, path) -> None:
|
| 346 |
+
"""Prepend ``path`` to ``sys.path`` list of import locations."""
|
| 347 |
+
|
| 348 |
+
if self._savesyspath is None:
|
| 349 |
+
self._savesyspath = sys.path[:]
|
| 350 |
+
sys.path.insert(0, str(path))
|
| 351 |
+
|
| 352 |
+
# https://github.com/pypa/setuptools/blob/d8b901bc/docs/pkg_resources.txt#L162-L171
|
| 353 |
+
# this is only needed when pkg_resources was already loaded by the namespace package
|
| 354 |
+
if "pkg_resources" in sys.modules:
|
| 355 |
+
from pkg_resources import fixup_namespace_packages
|
| 356 |
+
|
| 357 |
+
fixup_namespace_packages(str(path))
|
| 358 |
+
|
| 359 |
+
# A call to syspathinsert() usually means that the caller wants to
|
| 360 |
+
# import some dynamically created files, thus with python3 we
|
| 361 |
+
# invalidate its import caches.
|
| 362 |
+
# This is especially important when any namespace package is in use,
|
| 363 |
+
# since then the mtime based FileFinder cache (that gets created in
|
| 364 |
+
# this case already) gets not invalidated when writing the new files
|
| 365 |
+
# quickly afterwards.
|
| 366 |
+
from importlib import invalidate_caches
|
| 367 |
+
|
| 368 |
+
invalidate_caches()
|
| 369 |
+
|
| 370 |
+
def chdir(self, path: Union[str, "os.PathLike[str]"]) -> None:
|
| 371 |
+
"""Change the current working directory to the specified path.
|
| 372 |
+
|
| 373 |
+
:param path:
|
| 374 |
+
The path to change into.
|
| 375 |
+
"""
|
| 376 |
+
if self._cwd is None:
|
| 377 |
+
self._cwd = os.getcwd()
|
| 378 |
+
os.chdir(path)
|
| 379 |
+
|
| 380 |
+
def undo(self) -> None:
|
| 381 |
+
"""Undo previous changes.
|
| 382 |
+
|
| 383 |
+
This call consumes the undo stack. Calling it a second time has no
|
| 384 |
+
effect unless you do more monkeypatching after the undo call.
|
| 385 |
+
|
| 386 |
+
There is generally no need to call `undo()`, since it is
|
| 387 |
+
called automatically during tear-down.
|
| 388 |
+
|
| 389 |
+
.. note::
|
| 390 |
+
The same `monkeypatch` fixture is used across a
|
| 391 |
+
single test function invocation. If `monkeypatch` is used both by
|
| 392 |
+
the test function itself and one of the test fixtures,
|
| 393 |
+
calling `undo()` will undo all of the changes made in
|
| 394 |
+
both functions.
|
| 395 |
+
|
| 396 |
+
Prefer to use :meth:`context() <pytest.MonkeyPatch.context>` instead.
|
| 397 |
+
"""
|
| 398 |
+
for obj, name, value in reversed(self._setattr):
|
| 399 |
+
if value is not notset:
|
| 400 |
+
setattr(obj, name, value)
|
| 401 |
+
else:
|
| 402 |
+
delattr(obj, name)
|
| 403 |
+
self._setattr[:] = []
|
| 404 |
+
for dictionary, key, value in reversed(self._setitem):
|
| 405 |
+
if value is notset:
|
| 406 |
+
try:
|
| 407 |
+
# Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict
|
| 408 |
+
del dictionary[key] # type: ignore[attr-defined]
|
| 409 |
+
except KeyError:
|
| 410 |
+
pass # Was already deleted, so we have the desired state.
|
| 411 |
+
else:
|
| 412 |
+
# Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict
|
| 413 |
+
dictionary[key] = value # type: ignore[index]
|
| 414 |
+
self._setitem[:] = []
|
| 415 |
+
if self._savesyspath is not None:
|
| 416 |
+
sys.path[:] = self._savesyspath
|
| 417 |
+
self._savesyspath = None
|
| 418 |
+
|
| 419 |
+
if self._cwd is not None:
|
| 420 |
+
os.chdir(self._cwd)
|
| 421 |
+
self._cwd = None
|
wemm/lib/python3.10/site-packages/_pytest/nose.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run testsuites written for nose."""
|
| 2 |
+
import warnings
|
| 3 |
+
|
| 4 |
+
from _pytest.config import hookimpl
|
| 5 |
+
from _pytest.deprecated import NOSE_SUPPORT
|
| 6 |
+
from _pytest.fixtures import getfixturemarker
|
| 7 |
+
from _pytest.nodes import Item
|
| 8 |
+
from _pytest.python import Function
|
| 9 |
+
from _pytest.unittest import TestCaseFunction
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@hookimpl(trylast=True)
|
| 13 |
+
def pytest_runtest_setup(item: Item) -> None:
|
| 14 |
+
if not isinstance(item, Function):
|
| 15 |
+
return
|
| 16 |
+
# Don't do nose style setup/teardown on direct unittest style classes.
|
| 17 |
+
if isinstance(item, TestCaseFunction):
|
| 18 |
+
return
|
| 19 |
+
|
| 20 |
+
# Capture the narrowed type of item for the teardown closure,
|
| 21 |
+
# see https://github.com/python/mypy/issues/2608
|
| 22 |
+
func = item
|
| 23 |
+
|
| 24 |
+
call_optional(func.obj, "setup", func.nodeid)
|
| 25 |
+
func.addfinalizer(lambda: call_optional(func.obj, "teardown", func.nodeid))
|
| 26 |
+
|
| 27 |
+
# NOTE: Module- and class-level fixtures are handled in python.py
|
| 28 |
+
# with `pluginmanager.has_plugin("nose")` checks.
|
| 29 |
+
# It would have been nicer to implement them outside of core, but
|
| 30 |
+
# it's not straightforward.
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def call_optional(obj: object, name: str, nodeid: str) -> bool:
|
| 34 |
+
method = getattr(obj, name, None)
|
| 35 |
+
if method is None:
|
| 36 |
+
return False
|
| 37 |
+
is_fixture = getfixturemarker(method) is not None
|
| 38 |
+
if is_fixture:
|
| 39 |
+
return False
|
| 40 |
+
if not callable(method):
|
| 41 |
+
return False
|
| 42 |
+
# Warn about deprecation of this plugin.
|
| 43 |
+
method_name = getattr(method, "__name__", str(method))
|
| 44 |
+
warnings.warn(
|
| 45 |
+
NOSE_SUPPORT.format(nodeid=nodeid, method=method_name, stage=name), stacklevel=2
|
| 46 |
+
)
|
| 47 |
+
# If there are any problems allow the exception to raise rather than
|
| 48 |
+
# silently ignoring it.
|
| 49 |
+
method()
|
| 50 |
+
return True
|
wemm/lib/python3.10/site-packages/_pytest/outcomes.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exception classes and constants handling test outcomes as well as
|
| 2 |
+
functions creating them."""
|
| 3 |
+
import sys
|
| 4 |
+
import warnings
|
| 5 |
+
from typing import Any
|
| 6 |
+
from typing import Callable
|
| 7 |
+
from typing import cast
|
| 8 |
+
from typing import NoReturn
|
| 9 |
+
from typing import Optional
|
| 10 |
+
from typing import Type
|
| 11 |
+
from typing import TypeVar
|
| 12 |
+
|
| 13 |
+
from _pytest.deprecated import KEYWORD_MSG_ARG
|
| 14 |
+
|
| 15 |
+
TYPE_CHECKING = False # Avoid circular import through compat.
|
| 16 |
+
|
| 17 |
+
if TYPE_CHECKING:
|
| 18 |
+
from typing_extensions import Protocol
|
| 19 |
+
else:
|
| 20 |
+
# typing.Protocol is only available starting from Python 3.8. It is also
|
| 21 |
+
# available from typing_extensions, but we don't want a runtime dependency
|
| 22 |
+
# on that. So use a dummy runtime implementation.
|
| 23 |
+
from typing import Generic
|
| 24 |
+
|
| 25 |
+
Protocol = Generic
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class OutcomeException(BaseException):
|
| 29 |
+
"""OutcomeException and its subclass instances indicate and contain info
|
| 30 |
+
about test and collection outcomes."""
|
| 31 |
+
|
| 32 |
+
def __init__(self, msg: Optional[str] = None, pytrace: bool = True) -> None:
|
| 33 |
+
if msg is not None and not isinstance(msg, str):
|
| 34 |
+
error_msg = ( # type: ignore[unreachable]
|
| 35 |
+
"{} expected string as 'msg' parameter, got '{}' instead.\n"
|
| 36 |
+
"Perhaps you meant to use a mark?"
|
| 37 |
+
)
|
| 38 |
+
raise TypeError(error_msg.format(type(self).__name__, type(msg).__name__))
|
| 39 |
+
super().__init__(msg)
|
| 40 |
+
self.msg = msg
|
| 41 |
+
self.pytrace = pytrace
|
| 42 |
+
|
| 43 |
+
def __repr__(self) -> str:
|
| 44 |
+
if self.msg is not None:
|
| 45 |
+
return self.msg
|
| 46 |
+
return f"<{self.__class__.__name__} instance>"
|
| 47 |
+
|
| 48 |
+
__str__ = __repr__
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
TEST_OUTCOME = (OutcomeException, Exception)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class Skipped(OutcomeException):
|
| 55 |
+
# XXX hackish: on 3k we fake to live in the builtins
|
| 56 |
+
# in order to have Skipped exception printing shorter/nicer
|
| 57 |
+
__module__ = "builtins"
|
| 58 |
+
|
| 59 |
+
def __init__(
|
| 60 |
+
self,
|
| 61 |
+
msg: Optional[str] = None,
|
| 62 |
+
pytrace: bool = True,
|
| 63 |
+
allow_module_level: bool = False,
|
| 64 |
+
*,
|
| 65 |
+
_use_item_location: bool = False,
|
| 66 |
+
) -> None:
|
| 67 |
+
super().__init__(msg=msg, pytrace=pytrace)
|
| 68 |
+
self.allow_module_level = allow_module_level
|
| 69 |
+
# If true, the skip location is reported as the item's location,
|
| 70 |
+
# instead of the place that raises the exception/calls skip().
|
| 71 |
+
self._use_item_location = _use_item_location
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class Failed(OutcomeException):
|
| 75 |
+
"""Raised from an explicit call to pytest.fail()."""
|
| 76 |
+
|
| 77 |
+
__module__ = "builtins"
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class Exit(Exception):
|
| 81 |
+
"""Raised for immediate program exits (no tracebacks/summaries)."""
|
| 82 |
+
|
| 83 |
+
def __init__(
|
| 84 |
+
self, msg: str = "unknown reason", returncode: Optional[int] = None
|
| 85 |
+
) -> None:
|
| 86 |
+
self.msg = msg
|
| 87 |
+
self.returncode = returncode
|
| 88 |
+
super().__init__(msg)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# Elaborate hack to work around https://github.com/python/mypy/issues/2087.
|
| 92 |
+
# Ideally would just be `exit.Exception = Exit` etc.
|
| 93 |
+
|
| 94 |
+
_F = TypeVar("_F", bound=Callable[..., object])
|
| 95 |
+
_ET = TypeVar("_ET", bound=Type[BaseException])
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class _WithException(Protocol[_F, _ET]):
|
| 99 |
+
Exception: _ET
|
| 100 |
+
__call__: _F
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _with_exception(exception_type: _ET) -> Callable[[_F], _WithException[_F, _ET]]:
|
| 104 |
+
def decorate(func: _F) -> _WithException[_F, _ET]:
|
| 105 |
+
func_with_exception = cast(_WithException[_F, _ET], func)
|
| 106 |
+
func_with_exception.Exception = exception_type
|
| 107 |
+
return func_with_exception
|
| 108 |
+
|
| 109 |
+
return decorate
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# Exposed helper methods.
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@_with_exception(Exit)
|
| 116 |
+
def exit(
|
| 117 |
+
reason: str = "", returncode: Optional[int] = None, *, msg: Optional[str] = None
|
| 118 |
+
) -> NoReturn:
|
| 119 |
+
"""Exit testing process.
|
| 120 |
+
|
| 121 |
+
:param reason:
|
| 122 |
+
The message to show as the reason for exiting pytest. reason has a default value
|
| 123 |
+
only because `msg` is deprecated.
|
| 124 |
+
|
| 125 |
+
:param returncode:
|
| 126 |
+
Return code to be used when exiting pytest.
|
| 127 |
+
|
| 128 |
+
:param msg:
|
| 129 |
+
Same as ``reason``, but deprecated. Will be removed in a future version, use ``reason`` instead.
|
| 130 |
+
"""
|
| 131 |
+
__tracebackhide__ = True
|
| 132 |
+
from _pytest.config import UsageError
|
| 133 |
+
|
| 134 |
+
if reason and msg:
|
| 135 |
+
raise UsageError(
|
| 136 |
+
"cannot pass reason and msg to exit(), `msg` is deprecated, use `reason`."
|
| 137 |
+
)
|
| 138 |
+
if not reason:
|
| 139 |
+
if msg is None:
|
| 140 |
+
raise UsageError("exit() requires a reason argument")
|
| 141 |
+
warnings.warn(KEYWORD_MSG_ARG.format(func="exit"), stacklevel=2)
|
| 142 |
+
reason = msg
|
| 143 |
+
raise Exit(reason, returncode)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
@_with_exception(Skipped)
|
| 147 |
+
def skip(
|
| 148 |
+
reason: str = "", *, allow_module_level: bool = False, msg: Optional[str] = None
|
| 149 |
+
) -> NoReturn:
|
| 150 |
+
"""Skip an executing test with the given message.
|
| 151 |
+
|
| 152 |
+
This function should be called only during testing (setup, call or teardown) or
|
| 153 |
+
during collection by using the ``allow_module_level`` flag. This function can
|
| 154 |
+
be called in doctests as well.
|
| 155 |
+
|
| 156 |
+
:param reason:
|
| 157 |
+
The message to show the user as reason for the skip.
|
| 158 |
+
|
| 159 |
+
:param allow_module_level:
|
| 160 |
+
Allows this function to be called at module level.
|
| 161 |
+
Raising the skip exception at module level will stop
|
| 162 |
+
the execution of the module and prevent the collection of all tests in the module,
|
| 163 |
+
even those defined before the `skip` call.
|
| 164 |
+
|
| 165 |
+
Defaults to False.
|
| 166 |
+
|
| 167 |
+
:param msg:
|
| 168 |
+
Same as ``reason``, but deprecated. Will be removed in a future version, use ``reason`` instead.
|
| 169 |
+
|
| 170 |
+
.. note::
|
| 171 |
+
It is better to use the :ref:`pytest.mark.skipif ref` marker when
|
| 172 |
+
possible to declare a test to be skipped under certain conditions
|
| 173 |
+
like mismatching platforms or dependencies.
|
| 174 |
+
Similarly, use the ``# doctest: +SKIP`` directive (see :py:data:`doctest.SKIP`)
|
| 175 |
+
to skip a doctest statically.
|
| 176 |
+
"""
|
| 177 |
+
__tracebackhide__ = True
|
| 178 |
+
reason = _resolve_msg_to_reason("skip", reason, msg)
|
| 179 |
+
raise Skipped(msg=reason, allow_module_level=allow_module_level)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
@_with_exception(Failed)
|
| 183 |
+
def fail(reason: str = "", pytrace: bool = True, msg: Optional[str] = None) -> NoReturn:
|
| 184 |
+
"""Explicitly fail an executing test with the given message.
|
| 185 |
+
|
| 186 |
+
:param reason:
|
| 187 |
+
The message to show the user as reason for the failure.
|
| 188 |
+
|
| 189 |
+
:param pytrace:
|
| 190 |
+
If False, msg represents the full failure information and no
|
| 191 |
+
python traceback will be reported.
|
| 192 |
+
|
| 193 |
+
:param msg:
|
| 194 |
+
Same as ``reason``, but deprecated. Will be removed in a future version, use ``reason`` instead.
|
| 195 |
+
"""
|
| 196 |
+
__tracebackhide__ = True
|
| 197 |
+
reason = _resolve_msg_to_reason("fail", reason, msg)
|
| 198 |
+
raise Failed(msg=reason, pytrace=pytrace)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def _resolve_msg_to_reason(
|
| 202 |
+
func_name: str, reason: str, msg: Optional[str] = None
|
| 203 |
+
) -> str:
|
| 204 |
+
"""
|
| 205 |
+
Handles converting the deprecated msg parameter if provided into
|
| 206 |
+
reason, raising a deprecation warning. This function will be removed
|
| 207 |
+
when the optional msg argument is removed from here in future.
|
| 208 |
+
|
| 209 |
+
:param str func_name:
|
| 210 |
+
The name of the offending function, this is formatted into the deprecation message.
|
| 211 |
+
|
| 212 |
+
:param str reason:
|
| 213 |
+
The reason= passed into either pytest.fail() or pytest.skip()
|
| 214 |
+
|
| 215 |
+
:param str msg:
|
| 216 |
+
The msg= passed into either pytest.fail() or pytest.skip(). This will
|
| 217 |
+
be converted into reason if it is provided to allow pytest.skip(msg=) or
|
| 218 |
+
pytest.fail(msg=) to continue working in the interim period.
|
| 219 |
+
|
| 220 |
+
:returns:
|
| 221 |
+
The value to use as reason.
|
| 222 |
+
|
| 223 |
+
"""
|
| 224 |
+
__tracebackhide__ = True
|
| 225 |
+
if msg is not None:
|
| 226 |
+
if reason:
|
| 227 |
+
from pytest import UsageError
|
| 228 |
+
|
| 229 |
+
raise UsageError(
|
| 230 |
+
f"Passing both ``reason`` and ``msg`` to pytest.{func_name}(...) is not permitted."
|
| 231 |
+
)
|
| 232 |
+
warnings.warn(KEYWORD_MSG_ARG.format(func=func_name), stacklevel=3)
|
| 233 |
+
reason = msg
|
| 234 |
+
return reason
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
class XFailed(Failed):
|
| 238 |
+
"""Raised from an explicit call to pytest.xfail()."""
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
@_with_exception(XFailed)
|
| 242 |
+
def xfail(reason: str = "") -> NoReturn:
|
| 243 |
+
"""Imperatively xfail an executing test or setup function with the given reason.
|
| 244 |
+
|
| 245 |
+
This function should be called only during testing (setup, call or teardown).
|
| 246 |
+
|
| 247 |
+
:param reason:
|
| 248 |
+
The message to show the user as reason for the xfail.
|
| 249 |
+
|
| 250 |
+
.. note::
|
| 251 |
+
It is better to use the :ref:`pytest.mark.xfail ref` marker when
|
| 252 |
+
possible to declare a test to be xfailed under certain conditions
|
| 253 |
+
like known bugs or missing features.
|
| 254 |
+
"""
|
| 255 |
+
__tracebackhide__ = True
|
| 256 |
+
raise XFailed(reason)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def importorskip(
|
| 260 |
+
modname: str, minversion: Optional[str] = None, reason: Optional[str] = None
|
| 261 |
+
) -> Any:
|
| 262 |
+
"""Import and return the requested module ``modname``, or skip the
|
| 263 |
+
current test if the module cannot be imported.
|
| 264 |
+
|
| 265 |
+
:param modname:
|
| 266 |
+
The name of the module to import.
|
| 267 |
+
:param minversion:
|
| 268 |
+
If given, the imported module's ``__version__`` attribute must be at
|
| 269 |
+
least this minimal version, otherwise the test is still skipped.
|
| 270 |
+
:param reason:
|
| 271 |
+
If given, this reason is shown as the message when the module cannot
|
| 272 |
+
be imported.
|
| 273 |
+
|
| 274 |
+
:returns:
|
| 275 |
+
The imported module. This should be assigned to its canonical name.
|
| 276 |
+
|
| 277 |
+
Example::
|
| 278 |
+
|
| 279 |
+
docutils = pytest.importorskip("docutils")
|
| 280 |
+
"""
|
| 281 |
+
import warnings
|
| 282 |
+
|
| 283 |
+
__tracebackhide__ = True
|
| 284 |
+
compile(modname, "", "eval") # to catch syntaxerrors
|
| 285 |
+
|
| 286 |
+
with warnings.catch_warnings():
|
| 287 |
+
# Make sure to ignore ImportWarnings that might happen because
|
| 288 |
+
# of existing directories with the same name we're trying to
|
| 289 |
+
# import but without a __init__.py file.
|
| 290 |
+
warnings.simplefilter("ignore")
|
| 291 |
+
try:
|
| 292 |
+
__import__(modname)
|
| 293 |
+
except ImportError as exc:
|
| 294 |
+
if reason is None:
|
| 295 |
+
reason = f"could not import {modname!r}: {exc}"
|
| 296 |
+
raise Skipped(reason, allow_module_level=True) from None
|
| 297 |
+
mod = sys.modules[modname]
|
| 298 |
+
if minversion is None:
|
| 299 |
+
return mod
|
| 300 |
+
verattr = getattr(mod, "__version__", None)
|
| 301 |
+
if minversion is not None:
|
| 302 |
+
# Imported lazily to improve start-up time.
|
| 303 |
+
from packaging.version import Version
|
| 304 |
+
|
| 305 |
+
if verattr is None or Version(verattr) < Version(minversion):
|
| 306 |
+
raise Skipped(
|
| 307 |
+
"module %r has __version__ %r, required is: %r"
|
| 308 |
+
% (modname, verattr, minversion),
|
| 309 |
+
allow_module_level=True,
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import atexit
|
| 2 |
+
import contextlib
|
| 3 |
+
import fnmatch
|
| 4 |
+
import importlib.util
|
| 5 |
+
import itertools
|
| 6 |
+
import os
|
| 7 |
+
import shutil
|
| 8 |
+
import sys
|
| 9 |
+
import types
|
| 10 |
+
import uuid
|
| 11 |
+
import warnings
|
| 12 |
+
from enum import Enum
|
| 13 |
+
from errno import EBADF
|
| 14 |
+
from errno import ELOOP
|
| 15 |
+
from errno import ENOENT
|
| 16 |
+
from errno import ENOTDIR
|
| 17 |
+
from functools import partial
|
| 18 |
+
from os.path import expanduser
|
| 19 |
+
from os.path import expandvars
|
| 20 |
+
from os.path import isabs
|
| 21 |
+
from os.path import sep
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from pathlib import PurePath
|
| 24 |
+
from posixpath import sep as posix_sep
|
| 25 |
+
from types import ModuleType
|
| 26 |
+
from typing import Callable
|
| 27 |
+
from typing import Dict
|
| 28 |
+
from typing import Iterable
|
| 29 |
+
from typing import Iterator
|
| 30 |
+
from typing import List
|
| 31 |
+
from typing import Optional
|
| 32 |
+
from typing import Set
|
| 33 |
+
from typing import Tuple
|
| 34 |
+
from typing import Type
|
| 35 |
+
from typing import TypeVar
|
| 36 |
+
from typing import Union
|
| 37 |
+
|
| 38 |
+
from _pytest.compat import assert_never
|
| 39 |
+
from _pytest.outcomes import skip
|
| 40 |
+
from _pytest.warning_types import PytestWarning
|
| 41 |
+
|
| 42 |
+
LOCK_TIMEOUT = 60 * 60 * 24 * 3
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
_AnyPurePath = TypeVar("_AnyPurePath", bound=PurePath)
|
| 46 |
+
|
| 47 |
+
# The following function, variables and comments were
|
| 48 |
+
# copied from cpython 3.9 Lib/pathlib.py file.
|
| 49 |
+
|
| 50 |
+
# EBADF - guard against macOS `stat` throwing EBADF
|
| 51 |
+
_IGNORED_ERRORS = (ENOENT, ENOTDIR, EBADF, ELOOP)
|
| 52 |
+
|
| 53 |
+
_IGNORED_WINERRORS = (
|
| 54 |
+
21, # ERROR_NOT_READY - drive exists but is not accessible
|
| 55 |
+
1921, # ERROR_CANT_RESOLVE_FILENAME - fix for broken symlink pointing to itself
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _ignore_error(exception):
|
| 60 |
+
return (
|
| 61 |
+
getattr(exception, "errno", None) in _IGNORED_ERRORS
|
| 62 |
+
or getattr(exception, "winerror", None) in _IGNORED_WINERRORS
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def get_lock_path(path: _AnyPurePath) -> _AnyPurePath:
|
| 67 |
+
return path.joinpath(".lock")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def on_rm_rf_error(
|
| 71 |
+
func,
|
| 72 |
+
path: str,
|
| 73 |
+
excinfo: Union[
|
| 74 |
+
BaseException,
|
| 75 |
+
Tuple[Type[BaseException], BaseException, Optional[types.TracebackType]],
|
| 76 |
+
],
|
| 77 |
+
*,
|
| 78 |
+
start_path: Path,
|
| 79 |
+
) -> bool:
|
| 80 |
+
"""Handle known read-only errors during rmtree.
|
| 81 |
+
|
| 82 |
+
The returned value is used only by our own tests.
|
| 83 |
+
"""
|
| 84 |
+
if isinstance(excinfo, BaseException):
|
| 85 |
+
exc = excinfo
|
| 86 |
+
else:
|
| 87 |
+
exc = excinfo[1]
|
| 88 |
+
|
| 89 |
+
# Another process removed the file in the middle of the "rm_rf" (xdist for example).
|
| 90 |
+
# More context: https://github.com/pytest-dev/pytest/issues/5974#issuecomment-543799018
|
| 91 |
+
if isinstance(exc, FileNotFoundError):
|
| 92 |
+
return False
|
| 93 |
+
|
| 94 |
+
if not isinstance(exc, PermissionError):
|
| 95 |
+
warnings.warn(
|
| 96 |
+
PytestWarning(f"(rm_rf) error removing {path}\n{type(exc)}: {exc}")
|
| 97 |
+
)
|
| 98 |
+
return False
|
| 99 |
+
|
| 100 |
+
if func not in (os.rmdir, os.remove, os.unlink):
|
| 101 |
+
if func not in (os.open,):
|
| 102 |
+
warnings.warn(
|
| 103 |
+
PytestWarning(
|
| 104 |
+
"(rm_rf) unknown function {} when removing {}:\n{}: {}".format(
|
| 105 |
+
func, path, type(exc), exc
|
| 106 |
+
)
|
| 107 |
+
)
|
| 108 |
+
)
|
| 109 |
+
return False
|
| 110 |
+
|
| 111 |
+
# Chmod + retry.
|
| 112 |
+
import stat
|
| 113 |
+
|
| 114 |
+
def chmod_rw(p: str) -> None:
|
| 115 |
+
mode = os.stat(p).st_mode
|
| 116 |
+
os.chmod(p, mode | stat.S_IRUSR | stat.S_IWUSR)
|
| 117 |
+
|
| 118 |
+
# For files, we need to recursively go upwards in the directories to
|
| 119 |
+
# ensure they all are also writable.
|
| 120 |
+
p = Path(path)
|
| 121 |
+
if p.is_file():
|
| 122 |
+
for parent in p.parents:
|
| 123 |
+
chmod_rw(str(parent))
|
| 124 |
+
# Stop when we reach the original path passed to rm_rf.
|
| 125 |
+
if parent == start_path:
|
| 126 |
+
break
|
| 127 |
+
chmod_rw(str(path))
|
| 128 |
+
|
| 129 |
+
func(path)
|
| 130 |
+
return True
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def ensure_extended_length_path(path: Path) -> Path:
|
| 134 |
+
"""Get the extended-length version of a path (Windows).
|
| 135 |
+
|
| 136 |
+
On Windows, by default, the maximum length of a path (MAX_PATH) is 260
|
| 137 |
+
characters, and operations on paths longer than that fail. But it is possible
|
| 138 |
+
to overcome this by converting the path to "extended-length" form before
|
| 139 |
+
performing the operation:
|
| 140 |
+
https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#maximum-path-length-limitation
|
| 141 |
+
|
| 142 |
+
On Windows, this function returns the extended-length absolute version of path.
|
| 143 |
+
On other platforms it returns path unchanged.
|
| 144 |
+
"""
|
| 145 |
+
if sys.platform.startswith("win32"):
|
| 146 |
+
path = path.resolve()
|
| 147 |
+
path = Path(get_extended_length_path_str(str(path)))
|
| 148 |
+
return path
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def get_extended_length_path_str(path: str) -> str:
|
| 152 |
+
"""Convert a path to a Windows extended length path."""
|
| 153 |
+
long_path_prefix = "\\\\?\\"
|
| 154 |
+
unc_long_path_prefix = "\\\\?\\UNC\\"
|
| 155 |
+
if path.startswith((long_path_prefix, unc_long_path_prefix)):
|
| 156 |
+
return path
|
| 157 |
+
# UNC
|
| 158 |
+
if path.startswith("\\\\"):
|
| 159 |
+
return unc_long_path_prefix + path[2:]
|
| 160 |
+
return long_path_prefix + path
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def rm_rf(path: Path) -> None:
|
| 164 |
+
"""Remove the path contents recursively, even if some elements
|
| 165 |
+
are read-only."""
|
| 166 |
+
path = ensure_extended_length_path(path)
|
| 167 |
+
onerror = partial(on_rm_rf_error, start_path=path)
|
| 168 |
+
if sys.version_info >= (3, 12):
|
| 169 |
+
shutil.rmtree(str(path), onexc=onerror)
|
| 170 |
+
else:
|
| 171 |
+
shutil.rmtree(str(path), onerror=onerror)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def find_prefixed(root: Path, prefix: str) -> Iterator[Path]:
|
| 175 |
+
"""Find all elements in root that begin with the prefix, case insensitive."""
|
| 176 |
+
l_prefix = prefix.lower()
|
| 177 |
+
for x in root.iterdir():
|
| 178 |
+
if x.name.lower().startswith(l_prefix):
|
| 179 |
+
yield x
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def extract_suffixes(iter: Iterable[PurePath], prefix: str) -> Iterator[str]:
|
| 183 |
+
"""Return the parts of the paths following the prefix.
|
| 184 |
+
|
| 185 |
+
:param iter: Iterator over path names.
|
| 186 |
+
:param prefix: Expected prefix of the path names.
|
| 187 |
+
"""
|
| 188 |
+
p_len = len(prefix)
|
| 189 |
+
for p in iter:
|
| 190 |
+
yield p.name[p_len:]
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def find_suffixes(root: Path, prefix: str) -> Iterator[str]:
|
| 194 |
+
"""Combine find_prefixes and extract_suffixes."""
|
| 195 |
+
return extract_suffixes(find_prefixed(root, prefix), prefix)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def parse_num(maybe_num) -> int:
|
| 199 |
+
"""Parse number path suffixes, returns -1 on error."""
|
| 200 |
+
try:
|
| 201 |
+
return int(maybe_num)
|
| 202 |
+
except ValueError:
|
| 203 |
+
return -1
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _force_symlink(
|
| 207 |
+
root: Path, target: Union[str, PurePath], link_to: Union[str, Path]
|
| 208 |
+
) -> None:
|
| 209 |
+
"""Helper to create the current symlink.
|
| 210 |
+
|
| 211 |
+
It's full of race conditions that are reasonably OK to ignore
|
| 212 |
+
for the context of best effort linking to the latest test run.
|
| 213 |
+
|
| 214 |
+
The presumption being that in case of much parallelism
|
| 215 |
+
the inaccuracy is going to be acceptable.
|
| 216 |
+
"""
|
| 217 |
+
current_symlink = root.joinpath(target)
|
| 218 |
+
try:
|
| 219 |
+
current_symlink.unlink()
|
| 220 |
+
except OSError:
|
| 221 |
+
pass
|
| 222 |
+
try:
|
| 223 |
+
current_symlink.symlink_to(link_to)
|
| 224 |
+
except Exception:
|
| 225 |
+
pass
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def make_numbered_dir(root: Path, prefix: str, mode: int = 0o700) -> Path:
|
| 229 |
+
"""Create a directory with an increased number as suffix for the given prefix."""
|
| 230 |
+
for i in range(10):
|
| 231 |
+
# try up to 10 times to create the folder
|
| 232 |
+
max_existing = max(map(parse_num, find_suffixes(root, prefix)), default=-1)
|
| 233 |
+
new_number = max_existing + 1
|
| 234 |
+
new_path = root.joinpath(f"{prefix}{new_number}")
|
| 235 |
+
try:
|
| 236 |
+
new_path.mkdir(mode=mode)
|
| 237 |
+
except Exception:
|
| 238 |
+
pass
|
| 239 |
+
else:
|
| 240 |
+
_force_symlink(root, prefix + "current", new_path)
|
| 241 |
+
return new_path
|
| 242 |
+
else:
|
| 243 |
+
raise OSError(
|
| 244 |
+
"could not create numbered dir with prefix "
|
| 245 |
+
"{prefix} in {root} after 10 tries".format(prefix=prefix, root=root)
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def create_cleanup_lock(p: Path) -> Path:
|
| 250 |
+
"""Create a lock to prevent premature folder cleanup."""
|
| 251 |
+
lock_path = get_lock_path(p)
|
| 252 |
+
try:
|
| 253 |
+
fd = os.open(str(lock_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
|
| 254 |
+
except FileExistsError as e:
|
| 255 |
+
raise OSError(f"cannot create lockfile in {p}") from e
|
| 256 |
+
else:
|
| 257 |
+
pid = os.getpid()
|
| 258 |
+
spid = str(pid).encode()
|
| 259 |
+
os.write(fd, spid)
|
| 260 |
+
os.close(fd)
|
| 261 |
+
if not lock_path.is_file():
|
| 262 |
+
raise OSError("lock path got renamed after successful creation")
|
| 263 |
+
return lock_path
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def register_cleanup_lock_removal(lock_path: Path, register=atexit.register):
|
| 267 |
+
"""Register a cleanup function for removing a lock, by default on atexit."""
|
| 268 |
+
pid = os.getpid()
|
| 269 |
+
|
| 270 |
+
def cleanup_on_exit(lock_path: Path = lock_path, original_pid: int = pid) -> None:
|
| 271 |
+
current_pid = os.getpid()
|
| 272 |
+
if current_pid != original_pid:
|
| 273 |
+
# fork
|
| 274 |
+
return
|
| 275 |
+
try:
|
| 276 |
+
lock_path.unlink()
|
| 277 |
+
except OSError:
|
| 278 |
+
pass
|
| 279 |
+
|
| 280 |
+
return register(cleanup_on_exit)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def maybe_delete_a_numbered_dir(path: Path) -> None:
|
| 284 |
+
"""Remove a numbered directory if its lock can be obtained and it does
|
| 285 |
+
not seem to be in use."""
|
| 286 |
+
path = ensure_extended_length_path(path)
|
| 287 |
+
lock_path = None
|
| 288 |
+
try:
|
| 289 |
+
lock_path = create_cleanup_lock(path)
|
| 290 |
+
parent = path.parent
|
| 291 |
+
|
| 292 |
+
garbage = parent.joinpath(f"garbage-{uuid.uuid4()}")
|
| 293 |
+
path.rename(garbage)
|
| 294 |
+
rm_rf(garbage)
|
| 295 |
+
except OSError:
|
| 296 |
+
# known races:
|
| 297 |
+
# * other process did a cleanup at the same time
|
| 298 |
+
# * deletable folder was found
|
| 299 |
+
# * process cwd (Windows)
|
| 300 |
+
return
|
| 301 |
+
finally:
|
| 302 |
+
# If we created the lock, ensure we remove it even if we failed
|
| 303 |
+
# to properly remove the numbered dir.
|
| 304 |
+
if lock_path is not None:
|
| 305 |
+
try:
|
| 306 |
+
lock_path.unlink()
|
| 307 |
+
except OSError:
|
| 308 |
+
pass
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def ensure_deletable(path: Path, consider_lock_dead_if_created_before: float) -> bool:
|
| 312 |
+
"""Check if `path` is deletable based on whether the lock file is expired."""
|
| 313 |
+
if path.is_symlink():
|
| 314 |
+
return False
|
| 315 |
+
lock = get_lock_path(path)
|
| 316 |
+
try:
|
| 317 |
+
if not lock.is_file():
|
| 318 |
+
return True
|
| 319 |
+
except OSError:
|
| 320 |
+
# we might not have access to the lock file at all, in this case assume
|
| 321 |
+
# we don't have access to the entire directory (#7491).
|
| 322 |
+
return False
|
| 323 |
+
try:
|
| 324 |
+
lock_time = lock.stat().st_mtime
|
| 325 |
+
except Exception:
|
| 326 |
+
return False
|
| 327 |
+
else:
|
| 328 |
+
if lock_time < consider_lock_dead_if_created_before:
|
| 329 |
+
# We want to ignore any errors while trying to remove the lock such as:
|
| 330 |
+
# - PermissionDenied, like the file permissions have changed since the lock creation;
|
| 331 |
+
# - FileNotFoundError, in case another pytest process got here first;
|
| 332 |
+
# and any other cause of failure.
|
| 333 |
+
with contextlib.suppress(OSError):
|
| 334 |
+
lock.unlink()
|
| 335 |
+
return True
|
| 336 |
+
return False
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def try_cleanup(path: Path, consider_lock_dead_if_created_before: float) -> None:
|
| 340 |
+
"""Try to cleanup a folder if we can ensure it's deletable."""
|
| 341 |
+
if ensure_deletable(path, consider_lock_dead_if_created_before):
|
| 342 |
+
maybe_delete_a_numbered_dir(path)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def cleanup_candidates(root: Path, prefix: str, keep: int) -> Iterator[Path]:
|
| 346 |
+
"""List candidates for numbered directories to be removed - follows py.path."""
|
| 347 |
+
max_existing = max(map(parse_num, find_suffixes(root, prefix)), default=-1)
|
| 348 |
+
max_delete = max_existing - keep
|
| 349 |
+
paths = find_prefixed(root, prefix)
|
| 350 |
+
paths, paths2 = itertools.tee(paths)
|
| 351 |
+
numbers = map(parse_num, extract_suffixes(paths2, prefix))
|
| 352 |
+
for path, number in zip(paths, numbers):
|
| 353 |
+
if number <= max_delete:
|
| 354 |
+
yield path
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def cleanup_dead_symlinks(root: Path):
|
| 358 |
+
for left_dir in root.iterdir():
|
| 359 |
+
if left_dir.is_symlink():
|
| 360 |
+
if not left_dir.resolve().exists():
|
| 361 |
+
left_dir.unlink()
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def cleanup_numbered_dir(
|
| 365 |
+
root: Path, prefix: str, keep: int, consider_lock_dead_if_created_before: float
|
| 366 |
+
) -> None:
|
| 367 |
+
"""Cleanup for lock driven numbered directories."""
|
| 368 |
+
if not root.exists():
|
| 369 |
+
return
|
| 370 |
+
for path in cleanup_candidates(root, prefix, keep):
|
| 371 |
+
try_cleanup(path, consider_lock_dead_if_created_before)
|
| 372 |
+
for path in root.glob("garbage-*"):
|
| 373 |
+
try_cleanup(path, consider_lock_dead_if_created_before)
|
| 374 |
+
|
| 375 |
+
cleanup_dead_symlinks(root)
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def make_numbered_dir_with_cleanup(
|
| 379 |
+
root: Path,
|
| 380 |
+
prefix: str,
|
| 381 |
+
keep: int,
|
| 382 |
+
lock_timeout: float,
|
| 383 |
+
mode: int,
|
| 384 |
+
) -> Path:
|
| 385 |
+
"""Create a numbered dir with a cleanup lock and remove old ones."""
|
| 386 |
+
e = None
|
| 387 |
+
for i in range(10):
|
| 388 |
+
try:
|
| 389 |
+
p = make_numbered_dir(root, prefix, mode)
|
| 390 |
+
# Only lock the current dir when keep is not 0
|
| 391 |
+
if keep != 0:
|
| 392 |
+
lock_path = create_cleanup_lock(p)
|
| 393 |
+
register_cleanup_lock_removal(lock_path)
|
| 394 |
+
except Exception as exc:
|
| 395 |
+
e = exc
|
| 396 |
+
else:
|
| 397 |
+
consider_lock_dead_if_created_before = p.stat().st_mtime - lock_timeout
|
| 398 |
+
# Register a cleanup for program exit
|
| 399 |
+
atexit.register(
|
| 400 |
+
cleanup_numbered_dir,
|
| 401 |
+
root,
|
| 402 |
+
prefix,
|
| 403 |
+
keep,
|
| 404 |
+
consider_lock_dead_if_created_before,
|
| 405 |
+
)
|
| 406 |
+
return p
|
| 407 |
+
assert e is not None
|
| 408 |
+
raise e
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def resolve_from_str(input: str, rootpath: Path) -> Path:
|
| 412 |
+
input = expanduser(input)
|
| 413 |
+
input = expandvars(input)
|
| 414 |
+
if isabs(input):
|
| 415 |
+
return Path(input)
|
| 416 |
+
else:
|
| 417 |
+
return rootpath.joinpath(input)
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def fnmatch_ex(pattern: str, path: Union[str, "os.PathLike[str]"]) -> bool:
|
| 421 |
+
"""A port of FNMatcher from py.path.common which works with PurePath() instances.
|
| 422 |
+
|
| 423 |
+
The difference between this algorithm and PurePath.match() is that the
|
| 424 |
+
latter matches "**" glob expressions for each part of the path, while
|
| 425 |
+
this algorithm uses the whole path instead.
|
| 426 |
+
|
| 427 |
+
For example:
|
| 428 |
+
"tests/foo/bar/doc/test_foo.py" matches pattern "tests/**/doc/test*.py"
|
| 429 |
+
with this algorithm, but not with PurePath.match().
|
| 430 |
+
|
| 431 |
+
This algorithm was ported to keep backward-compatibility with existing
|
| 432 |
+
settings which assume paths match according this logic.
|
| 433 |
+
|
| 434 |
+
References:
|
| 435 |
+
* https://bugs.python.org/issue29249
|
| 436 |
+
* https://bugs.python.org/issue34731
|
| 437 |
+
"""
|
| 438 |
+
path = PurePath(path)
|
| 439 |
+
iswin32 = sys.platform.startswith("win")
|
| 440 |
+
|
| 441 |
+
if iswin32 and sep not in pattern and posix_sep in pattern:
|
| 442 |
+
# Running on Windows, the pattern has no Windows path separators,
|
| 443 |
+
# and the pattern has one or more Posix path separators. Replace
|
| 444 |
+
# the Posix path separators with the Windows path separator.
|
| 445 |
+
pattern = pattern.replace(posix_sep, sep)
|
| 446 |
+
|
| 447 |
+
if sep not in pattern:
|
| 448 |
+
name = path.name
|
| 449 |
+
else:
|
| 450 |
+
name = str(path)
|
| 451 |
+
if path.is_absolute() and not os.path.isabs(pattern):
|
| 452 |
+
pattern = f"*{os.sep}{pattern}"
|
| 453 |
+
return fnmatch.fnmatch(name, pattern)
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def parts(s: str) -> Set[str]:
|
| 457 |
+
parts = s.split(sep)
|
| 458 |
+
return {sep.join(parts[: i + 1]) or sep for i in range(len(parts))}
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
def symlink_or_skip(src, dst, **kwargs):
|
| 462 |
+
"""Make a symlink, or skip the test in case symlinks are not supported."""
|
| 463 |
+
try:
|
| 464 |
+
os.symlink(str(src), str(dst), **kwargs)
|
| 465 |
+
except OSError as e:
|
| 466 |
+
skip(f"symlinks not supported: {e}")
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
class ImportMode(Enum):
|
| 470 |
+
"""Possible values for `mode` parameter of `import_path`."""
|
| 471 |
+
|
| 472 |
+
prepend = "prepend"
|
| 473 |
+
append = "append"
|
| 474 |
+
importlib = "importlib"
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
class ImportPathMismatchError(ImportError):
|
| 478 |
+
"""Raised on import_path() if there is a mismatch of __file__'s.
|
| 479 |
+
|
| 480 |
+
This can happen when `import_path` is called multiple times with different filenames that has
|
| 481 |
+
the same basename but reside in packages
|
| 482 |
+
(for example "/tests1/test_foo.py" and "/tests2/test_foo.py").
|
| 483 |
+
"""
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
def import_path(
|
| 487 |
+
p: Union[str, "os.PathLike[str]"],
|
| 488 |
+
*,
|
| 489 |
+
mode: Union[str, ImportMode] = ImportMode.prepend,
|
| 490 |
+
root: Path,
|
| 491 |
+
) -> ModuleType:
|
| 492 |
+
"""Import and return a module from the given path, which can be a file (a module) or
|
| 493 |
+
a directory (a package).
|
| 494 |
+
|
| 495 |
+
The import mechanism used is controlled by the `mode` parameter:
|
| 496 |
+
|
| 497 |
+
* `mode == ImportMode.prepend`: the directory containing the module (or package, taking
|
| 498 |
+
`__init__.py` files into account) will be put at the *start* of `sys.path` before
|
| 499 |
+
being imported with `importlib.import_module`.
|
| 500 |
+
|
| 501 |
+
* `mode == ImportMode.append`: same as `prepend`, but the directory will be appended
|
| 502 |
+
to the end of `sys.path`, if not already in `sys.path`.
|
| 503 |
+
|
| 504 |
+
* `mode == ImportMode.importlib`: uses more fine control mechanisms provided by `importlib`
|
| 505 |
+
to import the module, which avoids having to muck with `sys.path` at all. It effectively
|
| 506 |
+
allows having same-named test modules in different places.
|
| 507 |
+
|
| 508 |
+
:param root:
|
| 509 |
+
Used as an anchor when mode == ImportMode.importlib to obtain
|
| 510 |
+
a unique name for the module being imported so it can safely be stored
|
| 511 |
+
into ``sys.modules``.
|
| 512 |
+
|
| 513 |
+
:raises ImportPathMismatchError:
|
| 514 |
+
If after importing the given `path` and the module `__file__`
|
| 515 |
+
are different. Only raised in `prepend` and `append` modes.
|
| 516 |
+
"""
|
| 517 |
+
mode = ImportMode(mode)
|
| 518 |
+
|
| 519 |
+
path = Path(p)
|
| 520 |
+
|
| 521 |
+
if not path.exists():
|
| 522 |
+
raise ImportError(path)
|
| 523 |
+
|
| 524 |
+
if mode is ImportMode.importlib:
|
| 525 |
+
module_name = module_name_from_path(path, root)
|
| 526 |
+
|
| 527 |
+
for meta_importer in sys.meta_path:
|
| 528 |
+
spec = meta_importer.find_spec(module_name, [str(path.parent)])
|
| 529 |
+
if spec is not None:
|
| 530 |
+
break
|
| 531 |
+
else:
|
| 532 |
+
spec = importlib.util.spec_from_file_location(module_name, str(path))
|
| 533 |
+
|
| 534 |
+
if spec is None:
|
| 535 |
+
raise ImportError(f"Can't find module {module_name} at location {path}")
|
| 536 |
+
mod = importlib.util.module_from_spec(spec)
|
| 537 |
+
sys.modules[module_name] = mod
|
| 538 |
+
spec.loader.exec_module(mod) # type: ignore[union-attr]
|
| 539 |
+
insert_missing_modules(sys.modules, module_name)
|
| 540 |
+
return mod
|
| 541 |
+
|
| 542 |
+
pkg_path = resolve_package_path(path)
|
| 543 |
+
if pkg_path is not None:
|
| 544 |
+
pkg_root = pkg_path.parent
|
| 545 |
+
names = list(path.with_suffix("").relative_to(pkg_root).parts)
|
| 546 |
+
if names[-1] == "__init__":
|
| 547 |
+
names.pop()
|
| 548 |
+
module_name = ".".join(names)
|
| 549 |
+
else:
|
| 550 |
+
pkg_root = path.parent
|
| 551 |
+
module_name = path.stem
|
| 552 |
+
|
| 553 |
+
# Change sys.path permanently: restoring it at the end of this function would cause surprising
|
| 554 |
+
# problems because of delayed imports: for example, a conftest.py file imported by this function
|
| 555 |
+
# might have local imports, which would fail at runtime if we restored sys.path.
|
| 556 |
+
if mode is ImportMode.append:
|
| 557 |
+
if str(pkg_root) not in sys.path:
|
| 558 |
+
sys.path.append(str(pkg_root))
|
| 559 |
+
elif mode is ImportMode.prepend:
|
| 560 |
+
if str(pkg_root) != sys.path[0]:
|
| 561 |
+
sys.path.insert(0, str(pkg_root))
|
| 562 |
+
else:
|
| 563 |
+
assert_never(mode)
|
| 564 |
+
|
| 565 |
+
importlib.import_module(module_name)
|
| 566 |
+
|
| 567 |
+
mod = sys.modules[module_name]
|
| 568 |
+
if path.name == "__init__.py":
|
| 569 |
+
return mod
|
| 570 |
+
|
| 571 |
+
ignore = os.environ.get("PY_IGNORE_IMPORTMISMATCH", "")
|
| 572 |
+
if ignore != "1":
|
| 573 |
+
module_file = mod.__file__
|
| 574 |
+
if module_file is None:
|
| 575 |
+
raise ImportPathMismatchError(module_name, module_file, path)
|
| 576 |
+
|
| 577 |
+
if module_file.endswith((".pyc", ".pyo")):
|
| 578 |
+
module_file = module_file[:-1]
|
| 579 |
+
if module_file.endswith(os.sep + "__init__.py"):
|
| 580 |
+
module_file = module_file[: -(len(os.sep + "__init__.py"))]
|
| 581 |
+
|
| 582 |
+
try:
|
| 583 |
+
is_same = _is_same(str(path), module_file)
|
| 584 |
+
except FileNotFoundError:
|
| 585 |
+
is_same = False
|
| 586 |
+
|
| 587 |
+
if not is_same:
|
| 588 |
+
raise ImportPathMismatchError(module_name, module_file, path)
|
| 589 |
+
|
| 590 |
+
return mod
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
# Implement a special _is_same function on Windows which returns True if the two filenames
|
| 594 |
+
# compare equal, to circumvent os.path.samefile returning False for mounts in UNC (#7678).
|
| 595 |
+
if sys.platform.startswith("win"):
|
| 596 |
+
|
| 597 |
+
def _is_same(f1: str, f2: str) -> bool:
|
| 598 |
+
return Path(f1) == Path(f2) or os.path.samefile(f1, f2)
|
| 599 |
+
|
| 600 |
+
else:
|
| 601 |
+
|
| 602 |
+
def _is_same(f1: str, f2: str) -> bool:
|
| 603 |
+
return os.path.samefile(f1, f2)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def module_name_from_path(path: Path, root: Path) -> str:
|
| 607 |
+
"""
|
| 608 |
+
Return a dotted module name based on the given path, anchored on root.
|
| 609 |
+
|
| 610 |
+
For example: path="projects/src/tests/test_foo.py" and root="/projects", the
|
| 611 |
+
resulting module name will be "src.tests.test_foo".
|
| 612 |
+
"""
|
| 613 |
+
path = path.with_suffix("")
|
| 614 |
+
try:
|
| 615 |
+
relative_path = path.relative_to(root)
|
| 616 |
+
except ValueError:
|
| 617 |
+
# If we can't get a relative path to root, use the full path, except
|
| 618 |
+
# for the first part ("d:\\" or "/" depending on the platform, for example).
|
| 619 |
+
path_parts = path.parts[1:]
|
| 620 |
+
else:
|
| 621 |
+
# Use the parts for the relative path to the root path.
|
| 622 |
+
path_parts = relative_path.parts
|
| 623 |
+
|
| 624 |
+
return ".".join(path_parts)
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
def insert_missing_modules(modules: Dict[str, ModuleType], module_name: str) -> None:
|
| 628 |
+
"""
|
| 629 |
+
Used by ``import_path`` to create intermediate modules when using mode=importlib.
|
| 630 |
+
|
| 631 |
+
When we want to import a module as "src.tests.test_foo" for example, we need
|
| 632 |
+
to create empty modules "src" and "src.tests" after inserting "src.tests.test_foo",
|
| 633 |
+
otherwise "src.tests.test_foo" is not importable by ``__import__``.
|
| 634 |
+
"""
|
| 635 |
+
module_parts = module_name.split(".")
|
| 636 |
+
while module_name:
|
| 637 |
+
if module_name not in modules:
|
| 638 |
+
try:
|
| 639 |
+
# If sys.meta_path is empty, calling import_module will issue
|
| 640 |
+
# a warning and raise ModuleNotFoundError. To avoid the
|
| 641 |
+
# warning, we check sys.meta_path explicitly and raise the error
|
| 642 |
+
# ourselves to fall back to creating a dummy module.
|
| 643 |
+
if not sys.meta_path:
|
| 644 |
+
raise ModuleNotFoundError
|
| 645 |
+
importlib.import_module(module_name)
|
| 646 |
+
except ModuleNotFoundError:
|
| 647 |
+
module = ModuleType(
|
| 648 |
+
module_name,
|
| 649 |
+
doc="Empty module created by pytest's importmode=importlib.",
|
| 650 |
+
)
|
| 651 |
+
modules[module_name] = module
|
| 652 |
+
module_parts.pop(-1)
|
| 653 |
+
module_name = ".".join(module_parts)
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
def resolve_package_path(path: Path) -> Optional[Path]:
|
| 657 |
+
"""Return the Python package path by looking for the last
|
| 658 |
+
directory upwards which still contains an __init__.py.
|
| 659 |
+
|
| 660 |
+
Returns None if it can not be determined.
|
| 661 |
+
"""
|
| 662 |
+
result = None
|
| 663 |
+
for parent in itertools.chain((path,), path.parents):
|
| 664 |
+
if parent.is_dir():
|
| 665 |
+
if not parent.joinpath("__init__.py").is_file():
|
| 666 |
+
break
|
| 667 |
+
if not parent.name.isidentifier():
|
| 668 |
+
break
|
| 669 |
+
result = parent
|
| 670 |
+
return result
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
def scandir(path: Union[str, "os.PathLike[str]"]) -> List["os.DirEntry[str]"]:
|
| 674 |
+
"""Scan a directory recursively, in breadth-first order.
|
| 675 |
+
|
| 676 |
+
The returned entries are sorted.
|
| 677 |
+
"""
|
| 678 |
+
entries = []
|
| 679 |
+
with os.scandir(path) as s:
|
| 680 |
+
# Skip entries with symlink loops and other brokenness, so the caller
|
| 681 |
+
# doesn't have to deal with it.
|
| 682 |
+
for entry in s:
|
| 683 |
+
try:
|
| 684 |
+
entry.is_file()
|
| 685 |
+
except OSError as err:
|
| 686 |
+
if _ignore_error(err):
|
| 687 |
+
continue
|
| 688 |
+
raise
|
| 689 |
+
entries.append(entry)
|
| 690 |
+
entries.sort(key=lambda entry: entry.name)
|
| 691 |
+
return entries
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
def visit(
|
| 695 |
+
path: Union[str, "os.PathLike[str]"], recurse: Callable[["os.DirEntry[str]"], bool]
|
| 696 |
+
) -> Iterator["os.DirEntry[str]"]:
|
| 697 |
+
"""Walk a directory recursively, in breadth-first order.
|
| 698 |
+
|
| 699 |
+
The `recurse` predicate determines whether a directory is recursed.
|
| 700 |
+
|
| 701 |
+
Entries at each directory level are sorted.
|
| 702 |
+
"""
|
| 703 |
+
entries = scandir(path)
|
| 704 |
+
yield from entries
|
| 705 |
+
for entry in entries:
|
| 706 |
+
if entry.is_dir() and recurse(entry):
|
| 707 |
+
yield from visit(entry.path, recurse)
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def absolutepath(path: Union[Path, str]) -> Path:
|
| 711 |
+
"""Convert a path to an absolute path using os.path.abspath.
|
| 712 |
+
|
| 713 |
+
Prefer this over Path.resolve() (see #6523).
|
| 714 |
+
Prefer this over Path.absolute() (not public, doesn't normalize).
|
| 715 |
+
"""
|
| 716 |
+
return Path(os.path.abspath(str(path)))
|
| 717 |
+
|
| 718 |
+
|
| 719 |
+
def commonpath(path1: Path, path2: Path) -> Optional[Path]:
|
| 720 |
+
"""Return the common part shared with the other path, or None if there is
|
| 721 |
+
no common part.
|
| 722 |
+
|
| 723 |
+
If one path is relative and one is absolute, returns None.
|
| 724 |
+
"""
|
| 725 |
+
try:
|
| 726 |
+
return Path(os.path.commonpath((str(path1), str(path2))))
|
| 727 |
+
except ValueError:
|
| 728 |
+
return None
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
def bestrelpath(directory: Path, dest: Path) -> str:
|
| 732 |
+
"""Return a string which is a relative path from directory to dest such
|
| 733 |
+
that directory/bestrelpath == dest.
|
| 734 |
+
|
| 735 |
+
The paths must be either both absolute or both relative.
|
| 736 |
+
|
| 737 |
+
If no such path can be determined, returns dest.
|
| 738 |
+
"""
|
| 739 |
+
assert isinstance(directory, Path)
|
| 740 |
+
assert isinstance(dest, Path)
|
| 741 |
+
if dest == directory:
|
| 742 |
+
return os.curdir
|
| 743 |
+
# Find the longest common directory.
|
| 744 |
+
base = commonpath(directory, dest)
|
| 745 |
+
# Can be the case on Windows for two absolute paths on different drives.
|
| 746 |
+
# Can be the case for two relative paths without common prefix.
|
| 747 |
+
# Can be the case for a relative path and an absolute path.
|
| 748 |
+
if not base:
|
| 749 |
+
return str(dest)
|
| 750 |
+
reldirectory = directory.relative_to(base)
|
| 751 |
+
reldest = dest.relative_to(base)
|
| 752 |
+
return os.path.join(
|
| 753 |
+
# Back from directory to base.
|
| 754 |
+
*([os.pardir] * len(reldirectory.parts)),
|
| 755 |
+
# Forward from base to dest.
|
| 756 |
+
*reldest.parts,
|
| 757 |
+
)
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
# Originates from py. path.local.copy(), with siginficant trims and adjustments.
|
| 761 |
+
# TODO(py38): Replace with shutil.copytree(..., symlinks=True, dirs_exist_ok=True)
|
| 762 |
+
def copytree(source: Path, target: Path) -> None:
|
| 763 |
+
"""Recursively copy a source directory to target."""
|
| 764 |
+
assert source.is_dir()
|
| 765 |
+
for entry in visit(source, recurse=lambda entry: not entry.is_symlink()):
|
| 766 |
+
x = Path(entry)
|
| 767 |
+
relpath = x.relative_to(source)
|
| 768 |
+
newx = target / relpath
|
| 769 |
+
newx.parent.mkdir(exist_ok=True)
|
| 770 |
+
if x.is_symlink():
|
| 771 |
+
newx.symlink_to(os.readlink(x))
|
| 772 |
+
elif x.is_file():
|
| 773 |
+
shutil.copyfile(x, newx)
|
| 774 |
+
elif x.is_dir():
|
| 775 |
+
newx.mkdir(exist_ok=True)
|
wemm/lib/python3.10/site-packages/_pytest/pytester_assertions.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Helper plugin for pytester; should not be loaded on its own."""
|
| 2 |
+
# This plugin contains assertions used by pytester. pytester cannot
|
| 3 |
+
# contain them itself, since it is imported by the `pytest` module,
|
| 4 |
+
# hence cannot be subject to assertion rewriting, which requires a
|
| 5 |
+
# module to not be already imported.
|
| 6 |
+
from typing import Dict
|
| 7 |
+
from typing import Optional
|
| 8 |
+
from typing import Sequence
|
| 9 |
+
from typing import Tuple
|
| 10 |
+
from typing import Union
|
| 11 |
+
|
| 12 |
+
from _pytest.reports import CollectReport
|
| 13 |
+
from _pytest.reports import TestReport
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def assertoutcome(
|
| 17 |
+
outcomes: Tuple[
|
| 18 |
+
Sequence[TestReport],
|
| 19 |
+
Sequence[Union[CollectReport, TestReport]],
|
| 20 |
+
Sequence[Union[CollectReport, TestReport]],
|
| 21 |
+
],
|
| 22 |
+
passed: int = 0,
|
| 23 |
+
skipped: int = 0,
|
| 24 |
+
failed: int = 0,
|
| 25 |
+
) -> None:
|
| 26 |
+
__tracebackhide__ = True
|
| 27 |
+
|
| 28 |
+
realpassed, realskipped, realfailed = outcomes
|
| 29 |
+
obtained = {
|
| 30 |
+
"passed": len(realpassed),
|
| 31 |
+
"skipped": len(realskipped),
|
| 32 |
+
"failed": len(realfailed),
|
| 33 |
+
}
|
| 34 |
+
expected = {"passed": passed, "skipped": skipped, "failed": failed}
|
| 35 |
+
assert obtained == expected, outcomes
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def assert_outcomes(
|
| 39 |
+
outcomes: Dict[str, int],
|
| 40 |
+
passed: int = 0,
|
| 41 |
+
skipped: int = 0,
|
| 42 |
+
failed: int = 0,
|
| 43 |
+
errors: int = 0,
|
| 44 |
+
xpassed: int = 0,
|
| 45 |
+
xfailed: int = 0,
|
| 46 |
+
warnings: Optional[int] = None,
|
| 47 |
+
deselected: Optional[int] = None,
|
| 48 |
+
) -> None:
|
| 49 |
+
"""Assert that the specified outcomes appear with the respective
|
| 50 |
+
numbers (0 means it didn't occur) in the text output from a test run."""
|
| 51 |
+
__tracebackhide__ = True
|
| 52 |
+
|
| 53 |
+
obtained = {
|
| 54 |
+
"passed": outcomes.get("passed", 0),
|
| 55 |
+
"skipped": outcomes.get("skipped", 0),
|
| 56 |
+
"failed": outcomes.get("failed", 0),
|
| 57 |
+
"errors": outcomes.get("errors", 0),
|
| 58 |
+
"xpassed": outcomes.get("xpassed", 0),
|
| 59 |
+
"xfailed": outcomes.get("xfailed", 0),
|
| 60 |
+
}
|
| 61 |
+
expected = {
|
| 62 |
+
"passed": passed,
|
| 63 |
+
"skipped": skipped,
|
| 64 |
+
"failed": failed,
|
| 65 |
+
"errors": errors,
|
| 66 |
+
"xpassed": xpassed,
|
| 67 |
+
"xfailed": xfailed,
|
| 68 |
+
}
|
| 69 |
+
if warnings is not None:
|
| 70 |
+
obtained["warnings"] = outcomes.get("warnings", 0)
|
| 71 |
+
expected["warnings"] = warnings
|
| 72 |
+
if deselected is not None:
|
| 73 |
+
obtained["deselected"] = outcomes.get("deselected", 0)
|
| 74 |
+
expected["deselected"] = deselected
|
| 75 |
+
assert obtained == expected
|
wemm/lib/python3.10/site-packages/_pytest/recwarn.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
"""Record warnings during test function execution."""
|
| 2 |
+
import re
|
| 3 |
+
import warnings
|
| 4 |
+
from pprint import pformat
|
| 5 |
+
from types import TracebackType
|
| 6 |
+
from typing import Any
|
| 7 |
+
from typing import Callable
|
| 8 |
+
from typing import Generator
|
| 9 |
+
from typing import Iterator
|
| 10 |
+
from typing import List
|
| 11 |
+
from typing import Optional
|
| 12 |
+
from typing import Pattern
|
| 13 |
+
from typing import Tuple
|
| 14 |
+
from typing import Type
|
| 15 |
+
from typing import TypeVar
|
| 16 |
+
from typing import Union
|
| 17 |
+
|
| 18 |
+
from _pytest.compat import final
|
| 19 |
+
from _pytest.compat import overload
|
| 20 |
+
from _pytest.deprecated import check_ispytest
|
| 21 |
+
from _pytest.deprecated import WARNS_NONE_ARG
|
| 22 |
+
from _pytest.fixtures import fixture
|
| 23 |
+
from _pytest.outcomes import fail
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
T = TypeVar("T")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@fixture
|
| 30 |
+
def recwarn() -> Generator["WarningsRecorder", None, None]:
|
| 31 |
+
"""Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions.
|
| 32 |
+
|
| 33 |
+
See https://docs.pytest.org/en/latest/how-to/capture-warnings.html for information
|
| 34 |
+
on warning categories.
|
| 35 |
+
"""
|
| 36 |
+
wrec = WarningsRecorder(_ispytest=True)
|
| 37 |
+
with wrec:
|
| 38 |
+
warnings.simplefilter("default")
|
| 39 |
+
yield wrec
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@overload
|
| 43 |
+
def deprecated_call(
|
| 44 |
+
*, match: Optional[Union[str, Pattern[str]]] = ...
|
| 45 |
+
) -> "WarningsRecorder":
|
| 46 |
+
...
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@overload
|
| 50 |
+
def deprecated_call( # noqa: F811
|
| 51 |
+
func: Callable[..., T], *args: Any, **kwargs: Any
|
| 52 |
+
) -> T:
|
| 53 |
+
...
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def deprecated_call( # noqa: F811
|
| 57 |
+
func: Optional[Callable[..., Any]] = None, *args: Any, **kwargs: Any
|
| 58 |
+
) -> Union["WarningsRecorder", Any]:
|
| 59 |
+
"""Assert that code produces a ``DeprecationWarning`` or ``PendingDeprecationWarning``.
|
| 60 |
+
|
| 61 |
+
This function can be used as a context manager::
|
| 62 |
+
|
| 63 |
+
>>> import warnings
|
| 64 |
+
>>> def api_call_v2():
|
| 65 |
+
... warnings.warn('use v3 of this api', DeprecationWarning)
|
| 66 |
+
... return 200
|
| 67 |
+
|
| 68 |
+
>>> import pytest
|
| 69 |
+
>>> with pytest.deprecated_call():
|
| 70 |
+
... assert api_call_v2() == 200
|
| 71 |
+
|
| 72 |
+
It can also be used by passing a function and ``*args`` and ``**kwargs``,
|
| 73 |
+
in which case it will ensure calling ``func(*args, **kwargs)`` produces one of
|
| 74 |
+
the warnings types above. The return value is the return value of the function.
|
| 75 |
+
|
| 76 |
+
In the context manager form you may use the keyword argument ``match`` to assert
|
| 77 |
+
that the warning matches a text or regex.
|
| 78 |
+
|
| 79 |
+
The context manager produces a list of :class:`warnings.WarningMessage` objects,
|
| 80 |
+
one for each warning raised.
|
| 81 |
+
"""
|
| 82 |
+
__tracebackhide__ = True
|
| 83 |
+
if func is not None:
|
| 84 |
+
args = (func,) + args
|
| 85 |
+
return warns((DeprecationWarning, PendingDeprecationWarning), *args, **kwargs)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@overload
|
| 89 |
+
def warns(
|
| 90 |
+
expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]] = ...,
|
| 91 |
+
*,
|
| 92 |
+
match: Optional[Union[str, Pattern[str]]] = ...,
|
| 93 |
+
) -> "WarningsChecker":
|
| 94 |
+
...
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
@overload
|
| 98 |
+
def warns( # noqa: F811
|
| 99 |
+
expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]],
|
| 100 |
+
func: Callable[..., T],
|
| 101 |
+
*args: Any,
|
| 102 |
+
**kwargs: Any,
|
| 103 |
+
) -> T:
|
| 104 |
+
...
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def warns( # noqa: F811
|
| 108 |
+
expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]] = Warning,
|
| 109 |
+
*args: Any,
|
| 110 |
+
match: Optional[Union[str, Pattern[str]]] = None,
|
| 111 |
+
**kwargs: Any,
|
| 112 |
+
) -> Union["WarningsChecker", Any]:
|
| 113 |
+
r"""Assert that code raises a particular class of warning.
|
| 114 |
+
|
| 115 |
+
Specifically, the parameter ``expected_warning`` can be a warning class or sequence
|
| 116 |
+
of warning classes, and the code inside the ``with`` block must issue at least one
|
| 117 |
+
warning of that class or classes.
|
| 118 |
+
|
| 119 |
+
This helper produces a list of :class:`warnings.WarningMessage` objects, one for
|
| 120 |
+
each warning raised (regardless of whether it is an ``expected_warning`` or not).
|
| 121 |
+
|
| 122 |
+
This function can be used as a context manager, which will capture all the raised
|
| 123 |
+
warnings inside it::
|
| 124 |
+
|
| 125 |
+
>>> import pytest
|
| 126 |
+
>>> with pytest.warns(RuntimeWarning):
|
| 127 |
+
... warnings.warn("my warning", RuntimeWarning)
|
| 128 |
+
|
| 129 |
+
In the context manager form you may use the keyword argument ``match`` to assert
|
| 130 |
+
that the warning matches a text or regex::
|
| 131 |
+
|
| 132 |
+
>>> with pytest.warns(UserWarning, match='must be 0 or None'):
|
| 133 |
+
... warnings.warn("value must be 0 or None", UserWarning)
|
| 134 |
+
|
| 135 |
+
>>> with pytest.warns(UserWarning, match=r'must be \d+$'):
|
| 136 |
+
... warnings.warn("value must be 42", UserWarning)
|
| 137 |
+
|
| 138 |
+
>>> with pytest.warns(UserWarning, match=r'must be \d+$'):
|
| 139 |
+
... warnings.warn("this is not here", UserWarning)
|
| 140 |
+
Traceback (most recent call last):
|
| 141 |
+
...
|
| 142 |
+
Failed: DID NOT WARN. No warnings of type ...UserWarning... were emitted...
|
| 143 |
+
|
| 144 |
+
**Using with** ``pytest.mark.parametrize``
|
| 145 |
+
|
| 146 |
+
When using :ref:`pytest.mark.parametrize ref` it is possible to parametrize tests
|
| 147 |
+
such that some runs raise a warning and others do not.
|
| 148 |
+
|
| 149 |
+
This could be achieved in the same way as with exceptions, see
|
| 150 |
+
:ref:`parametrizing_conditional_raising` for an example.
|
| 151 |
+
|
| 152 |
+
"""
|
| 153 |
+
__tracebackhide__ = True
|
| 154 |
+
if not args:
|
| 155 |
+
if kwargs:
|
| 156 |
+
argnames = ", ".join(sorted(kwargs))
|
| 157 |
+
raise TypeError(
|
| 158 |
+
f"Unexpected keyword arguments passed to pytest.warns: {argnames}"
|
| 159 |
+
"\nUse context-manager form instead?"
|
| 160 |
+
)
|
| 161 |
+
return WarningsChecker(expected_warning, match_expr=match, _ispytest=True)
|
| 162 |
+
else:
|
| 163 |
+
func = args[0]
|
| 164 |
+
if not callable(func):
|
| 165 |
+
raise TypeError(f"{func!r} object (type: {type(func)}) must be callable")
|
| 166 |
+
with WarningsChecker(expected_warning, _ispytest=True):
|
| 167 |
+
return func(*args[1:], **kwargs)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
class WarningsRecorder(warnings.catch_warnings): # type:ignore[type-arg]
|
| 171 |
+
"""A context manager to record raised warnings.
|
| 172 |
+
|
| 173 |
+
Each recorded warning is an instance of :class:`warnings.WarningMessage`.
|
| 174 |
+
|
| 175 |
+
Adapted from `warnings.catch_warnings`.
|
| 176 |
+
|
| 177 |
+
.. note::
|
| 178 |
+
``DeprecationWarning`` and ``PendingDeprecationWarning`` are treated
|
| 179 |
+
differently; see :ref:`ensuring_function_triggers`.
|
| 180 |
+
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
def __init__(self, *, _ispytest: bool = False) -> None:
|
| 184 |
+
check_ispytest(_ispytest)
|
| 185 |
+
# Type ignored due to the way typeshed handles warnings.catch_warnings.
|
| 186 |
+
super().__init__(record=True) # type: ignore[call-arg]
|
| 187 |
+
self._entered = False
|
| 188 |
+
self._list: List[warnings.WarningMessage] = []
|
| 189 |
+
|
| 190 |
+
@property
|
| 191 |
+
def list(self) -> List["warnings.WarningMessage"]:
|
| 192 |
+
"""The list of recorded warnings."""
|
| 193 |
+
return self._list
|
| 194 |
+
|
| 195 |
+
def __getitem__(self, i: int) -> "warnings.WarningMessage":
|
| 196 |
+
"""Get a recorded warning by index."""
|
| 197 |
+
return self._list[i]
|
| 198 |
+
|
| 199 |
+
def __iter__(self) -> Iterator["warnings.WarningMessage"]:
|
| 200 |
+
"""Iterate through the recorded warnings."""
|
| 201 |
+
return iter(self._list)
|
| 202 |
+
|
| 203 |
+
def __len__(self) -> int:
|
| 204 |
+
"""The number of recorded warnings."""
|
| 205 |
+
return len(self._list)
|
| 206 |
+
|
| 207 |
+
def pop(self, cls: Type[Warning] = Warning) -> "warnings.WarningMessage":
|
| 208 |
+
"""Pop the first recorded warning, raise exception if not exists."""
|
| 209 |
+
for i, w in enumerate(self._list):
|
| 210 |
+
if issubclass(w.category, cls):
|
| 211 |
+
return self._list.pop(i)
|
| 212 |
+
__tracebackhide__ = True
|
| 213 |
+
raise AssertionError(f"{cls!r} not found in warning list")
|
| 214 |
+
|
| 215 |
+
def clear(self) -> None:
|
| 216 |
+
"""Clear the list of recorded warnings."""
|
| 217 |
+
self._list[:] = []
|
| 218 |
+
|
| 219 |
+
# Type ignored because it doesn't exactly warnings.catch_warnings.__enter__
|
| 220 |
+
# -- it returns a List but we only emulate one.
|
| 221 |
+
def __enter__(self) -> "WarningsRecorder": # type: ignore
|
| 222 |
+
if self._entered:
|
| 223 |
+
__tracebackhide__ = True
|
| 224 |
+
raise RuntimeError(f"Cannot enter {self!r} twice")
|
| 225 |
+
_list = super().__enter__()
|
| 226 |
+
# record=True means it's None.
|
| 227 |
+
assert _list is not None
|
| 228 |
+
self._list = _list
|
| 229 |
+
warnings.simplefilter("always")
|
| 230 |
+
return self
|
| 231 |
+
|
| 232 |
+
def __exit__(
|
| 233 |
+
self,
|
| 234 |
+
exc_type: Optional[Type[BaseException]],
|
| 235 |
+
exc_val: Optional[BaseException],
|
| 236 |
+
exc_tb: Optional[TracebackType],
|
| 237 |
+
) -> None:
|
| 238 |
+
if not self._entered:
|
| 239 |
+
__tracebackhide__ = True
|
| 240 |
+
raise RuntimeError(f"Cannot exit {self!r} without entering first")
|
| 241 |
+
|
| 242 |
+
super().__exit__(exc_type, exc_val, exc_tb)
|
| 243 |
+
|
| 244 |
+
# Built-in catch_warnings does not reset entered state so we do it
|
| 245 |
+
# manually here for this context manager to become reusable.
|
| 246 |
+
self._entered = False
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
@final
|
| 250 |
+
class WarningsChecker(WarningsRecorder):
|
| 251 |
+
def __init__(
|
| 252 |
+
self,
|
| 253 |
+
expected_warning: Optional[
|
| 254 |
+
Union[Type[Warning], Tuple[Type[Warning], ...]]
|
| 255 |
+
] = Warning,
|
| 256 |
+
match_expr: Optional[Union[str, Pattern[str]]] = None,
|
| 257 |
+
*,
|
| 258 |
+
_ispytest: bool = False,
|
| 259 |
+
) -> None:
|
| 260 |
+
check_ispytest(_ispytest)
|
| 261 |
+
super().__init__(_ispytest=True)
|
| 262 |
+
|
| 263 |
+
msg = "exceptions must be derived from Warning, not %s"
|
| 264 |
+
if expected_warning is None:
|
| 265 |
+
warnings.warn(WARNS_NONE_ARG, stacklevel=4)
|
| 266 |
+
expected_warning_tup = None
|
| 267 |
+
elif isinstance(expected_warning, tuple):
|
| 268 |
+
for exc in expected_warning:
|
| 269 |
+
if not issubclass(exc, Warning):
|
| 270 |
+
raise TypeError(msg % type(exc))
|
| 271 |
+
expected_warning_tup = expected_warning
|
| 272 |
+
elif issubclass(expected_warning, Warning):
|
| 273 |
+
expected_warning_tup = (expected_warning,)
|
| 274 |
+
else:
|
| 275 |
+
raise TypeError(msg % type(expected_warning))
|
| 276 |
+
|
| 277 |
+
self.expected_warning = expected_warning_tup
|
| 278 |
+
self.match_expr = match_expr
|
| 279 |
+
|
| 280 |
+
def __exit__(
|
| 281 |
+
self,
|
| 282 |
+
exc_type: Optional[Type[BaseException]],
|
| 283 |
+
exc_val: Optional[BaseException],
|
| 284 |
+
exc_tb: Optional[TracebackType],
|
| 285 |
+
) -> None:
|
| 286 |
+
super().__exit__(exc_type, exc_val, exc_tb)
|
| 287 |
+
|
| 288 |
+
__tracebackhide__ = True
|
| 289 |
+
|
| 290 |
+
def found_str():
|
| 291 |
+
return pformat([record.message for record in self], indent=2)
|
| 292 |
+
|
| 293 |
+
# only check if we're not currently handling an exception
|
| 294 |
+
if exc_type is None and exc_val is None and exc_tb is None:
|
| 295 |
+
if self.expected_warning is not None:
|
| 296 |
+
if not any(issubclass(r.category, self.expected_warning) for r in self):
|
| 297 |
+
__tracebackhide__ = True
|
| 298 |
+
fail(
|
| 299 |
+
f"DID NOT WARN. No warnings of type {self.expected_warning} were emitted.\n"
|
| 300 |
+
f"The list of emitted warnings is: {found_str()}."
|
| 301 |
+
)
|
| 302 |
+
elif self.match_expr is not None:
|
| 303 |
+
for r in self:
|
| 304 |
+
if issubclass(r.category, self.expected_warning):
|
| 305 |
+
if re.compile(self.match_expr).search(str(r.message)):
|
| 306 |
+
break
|
| 307 |
+
else:
|
| 308 |
+
fail(
|
| 309 |
+
f"""\
|
| 310 |
+
DID NOT WARN. No warnings of type {self.expected_warning} matching the regex were emitted.
|
| 311 |
+
Regex: {self.match_expr}
|
| 312 |
+
Emitted warnings: {found_str()}"""
|
| 313 |
+
)
|
wemm/lib/python3.10/site-packages/_pytest/reports.py
ADDED
|
@@ -0,0 +1,622 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dataclasses
|
| 2 |
+
import os
|
| 3 |
+
from io import StringIO
|
| 4 |
+
from pprint import pprint
|
| 5 |
+
from typing import Any
|
| 6 |
+
from typing import cast
|
| 7 |
+
from typing import Dict
|
| 8 |
+
from typing import Iterable
|
| 9 |
+
from typing import Iterator
|
| 10 |
+
from typing import List
|
| 11 |
+
from typing import Mapping
|
| 12 |
+
from typing import NoReturn
|
| 13 |
+
from typing import Optional
|
| 14 |
+
from typing import Tuple
|
| 15 |
+
from typing import Type
|
| 16 |
+
from typing import TYPE_CHECKING
|
| 17 |
+
from typing import TypeVar
|
| 18 |
+
from typing import Union
|
| 19 |
+
|
| 20 |
+
from _pytest._code.code import ExceptionChainRepr
|
| 21 |
+
from _pytest._code.code import ExceptionInfo
|
| 22 |
+
from _pytest._code.code import ExceptionRepr
|
| 23 |
+
from _pytest._code.code import ReprEntry
|
| 24 |
+
from _pytest._code.code import ReprEntryNative
|
| 25 |
+
from _pytest._code.code import ReprExceptionInfo
|
| 26 |
+
from _pytest._code.code import ReprFileLocation
|
| 27 |
+
from _pytest._code.code import ReprFuncArgs
|
| 28 |
+
from _pytest._code.code import ReprLocals
|
| 29 |
+
from _pytest._code.code import ReprTraceback
|
| 30 |
+
from _pytest._code.code import TerminalRepr
|
| 31 |
+
from _pytest._io import TerminalWriter
|
| 32 |
+
from _pytest.compat import final
|
| 33 |
+
from _pytest.config import Config
|
| 34 |
+
from _pytest.nodes import Collector
|
| 35 |
+
from _pytest.nodes import Item
|
| 36 |
+
from _pytest.outcomes import skip
|
| 37 |
+
|
| 38 |
+
if TYPE_CHECKING:
|
| 39 |
+
from typing_extensions import Literal
|
| 40 |
+
|
| 41 |
+
from _pytest.runner import CallInfo
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def getworkerinfoline(node):
|
| 45 |
+
try:
|
| 46 |
+
return node._workerinfocache
|
| 47 |
+
except AttributeError:
|
| 48 |
+
d = node.workerinfo
|
| 49 |
+
ver = "%s.%s.%s" % d["version_info"][:3]
|
| 50 |
+
node._workerinfocache = s = "[{}] {} -- Python {} {}".format(
|
| 51 |
+
d["id"], d["sysplatform"], ver, d["executable"]
|
| 52 |
+
)
|
| 53 |
+
return s
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
_R = TypeVar("_R", bound="BaseReport")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class BaseReport:
|
| 60 |
+
when: Optional[str]
|
| 61 |
+
location: Optional[Tuple[str, Optional[int], str]]
|
| 62 |
+
longrepr: Union[
|
| 63 |
+
None, ExceptionInfo[BaseException], Tuple[str, int, str], str, TerminalRepr
|
| 64 |
+
]
|
| 65 |
+
sections: List[Tuple[str, str]]
|
| 66 |
+
nodeid: str
|
| 67 |
+
outcome: "Literal['passed', 'failed', 'skipped']"
|
| 68 |
+
|
| 69 |
+
def __init__(self, **kw: Any) -> None:
|
| 70 |
+
self.__dict__.update(kw)
|
| 71 |
+
|
| 72 |
+
if TYPE_CHECKING:
|
| 73 |
+
# Can have arbitrary fields given to __init__().
|
| 74 |
+
def __getattr__(self, key: str) -> Any:
|
| 75 |
+
...
|
| 76 |
+
|
| 77 |
+
def toterminal(self, out: TerminalWriter) -> None:
|
| 78 |
+
if hasattr(self, "node"):
|
| 79 |
+
worker_info = getworkerinfoline(self.node)
|
| 80 |
+
if worker_info:
|
| 81 |
+
out.line(worker_info)
|
| 82 |
+
|
| 83 |
+
longrepr = self.longrepr
|
| 84 |
+
if longrepr is None:
|
| 85 |
+
return
|
| 86 |
+
|
| 87 |
+
if hasattr(longrepr, "toterminal"):
|
| 88 |
+
longrepr_terminal = cast(TerminalRepr, longrepr)
|
| 89 |
+
longrepr_terminal.toterminal(out)
|
| 90 |
+
else:
|
| 91 |
+
try:
|
| 92 |
+
s = str(longrepr)
|
| 93 |
+
except UnicodeEncodeError:
|
| 94 |
+
s = "<unprintable longrepr>"
|
| 95 |
+
out.line(s)
|
| 96 |
+
|
| 97 |
+
def get_sections(self, prefix: str) -> Iterator[Tuple[str, str]]:
|
| 98 |
+
for name, content in self.sections:
|
| 99 |
+
if name.startswith(prefix):
|
| 100 |
+
yield prefix, content
|
| 101 |
+
|
| 102 |
+
@property
|
| 103 |
+
def longreprtext(self) -> str:
|
| 104 |
+
"""Read-only property that returns the full string representation of
|
| 105 |
+
``longrepr``.
|
| 106 |
+
|
| 107 |
+
.. versionadded:: 3.0
|
| 108 |
+
"""
|
| 109 |
+
file = StringIO()
|
| 110 |
+
tw = TerminalWriter(file)
|
| 111 |
+
tw.hasmarkup = False
|
| 112 |
+
self.toterminal(tw)
|
| 113 |
+
exc = file.getvalue()
|
| 114 |
+
return exc.strip()
|
| 115 |
+
|
| 116 |
+
@property
|
| 117 |
+
def caplog(self) -> str:
|
| 118 |
+
"""Return captured log lines, if log capturing is enabled.
|
| 119 |
+
|
| 120 |
+
.. versionadded:: 3.5
|
| 121 |
+
"""
|
| 122 |
+
return "\n".join(
|
| 123 |
+
content for (prefix, content) in self.get_sections("Captured log")
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
@property
|
| 127 |
+
def capstdout(self) -> str:
|
| 128 |
+
"""Return captured text from stdout, if capturing is enabled.
|
| 129 |
+
|
| 130 |
+
.. versionadded:: 3.0
|
| 131 |
+
"""
|
| 132 |
+
return "".join(
|
| 133 |
+
content for (prefix, content) in self.get_sections("Captured stdout")
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
@property
|
| 137 |
+
def capstderr(self) -> str:
|
| 138 |
+
"""Return captured text from stderr, if capturing is enabled.
|
| 139 |
+
|
| 140 |
+
.. versionadded:: 3.0
|
| 141 |
+
"""
|
| 142 |
+
return "".join(
|
| 143 |
+
content for (prefix, content) in self.get_sections("Captured stderr")
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
@property
|
| 147 |
+
def passed(self) -> bool:
|
| 148 |
+
"""Whether the outcome is passed."""
|
| 149 |
+
return self.outcome == "passed"
|
| 150 |
+
|
| 151 |
+
@property
|
| 152 |
+
def failed(self) -> bool:
|
| 153 |
+
"""Whether the outcome is failed."""
|
| 154 |
+
return self.outcome == "failed"
|
| 155 |
+
|
| 156 |
+
@property
|
| 157 |
+
def skipped(self) -> bool:
|
| 158 |
+
"""Whether the outcome is skipped."""
|
| 159 |
+
return self.outcome == "skipped"
|
| 160 |
+
|
| 161 |
+
@property
|
| 162 |
+
def fspath(self) -> str:
|
| 163 |
+
"""The path portion of the reported node, as a string."""
|
| 164 |
+
return self.nodeid.split("::")[0]
|
| 165 |
+
|
| 166 |
+
@property
|
| 167 |
+
def count_towards_summary(self) -> bool:
|
| 168 |
+
"""**Experimental** Whether this report should be counted towards the
|
| 169 |
+
totals shown at the end of the test session: "1 passed, 1 failure, etc".
|
| 170 |
+
|
| 171 |
+
.. note::
|
| 172 |
+
|
| 173 |
+
This function is considered **experimental**, so beware that it is subject to changes
|
| 174 |
+
even in patch releases.
|
| 175 |
+
"""
|
| 176 |
+
return True
|
| 177 |
+
|
| 178 |
+
@property
|
| 179 |
+
def head_line(self) -> Optional[str]:
|
| 180 |
+
"""**Experimental** The head line shown with longrepr output for this
|
| 181 |
+
report, more commonly during traceback representation during
|
| 182 |
+
failures::
|
| 183 |
+
|
| 184 |
+
________ Test.foo ________
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
In the example above, the head_line is "Test.foo".
|
| 188 |
+
|
| 189 |
+
.. note::
|
| 190 |
+
|
| 191 |
+
This function is considered **experimental**, so beware that it is subject to changes
|
| 192 |
+
even in patch releases.
|
| 193 |
+
"""
|
| 194 |
+
if self.location is not None:
|
| 195 |
+
fspath, lineno, domain = self.location
|
| 196 |
+
return domain
|
| 197 |
+
return None
|
| 198 |
+
|
| 199 |
+
def _get_verbose_word(self, config: Config):
|
| 200 |
+
_category, _short, verbose = config.hook.pytest_report_teststatus(
|
| 201 |
+
report=self, config=config
|
| 202 |
+
)
|
| 203 |
+
return verbose
|
| 204 |
+
|
| 205 |
+
def _to_json(self) -> Dict[str, Any]:
|
| 206 |
+
"""Return the contents of this report as a dict of builtin entries,
|
| 207 |
+
suitable for serialization.
|
| 208 |
+
|
| 209 |
+
This was originally the serialize_report() function from xdist (ca03269).
|
| 210 |
+
|
| 211 |
+
Experimental method.
|
| 212 |
+
"""
|
| 213 |
+
return _report_to_json(self)
|
| 214 |
+
|
| 215 |
+
@classmethod
|
| 216 |
+
def _from_json(cls: Type[_R], reportdict: Dict[str, object]) -> _R:
|
| 217 |
+
"""Create either a TestReport or CollectReport, depending on the calling class.
|
| 218 |
+
|
| 219 |
+
It is the callers responsibility to know which class to pass here.
|
| 220 |
+
|
| 221 |
+
This was originally the serialize_report() function from xdist (ca03269).
|
| 222 |
+
|
| 223 |
+
Experimental method.
|
| 224 |
+
"""
|
| 225 |
+
kwargs = _report_kwargs_from_json(reportdict)
|
| 226 |
+
return cls(**kwargs)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def _report_unserialization_failure(
|
| 230 |
+
type_name: str, report_class: Type[BaseReport], reportdict
|
| 231 |
+
) -> NoReturn:
|
| 232 |
+
url = "https://github.com/pytest-dev/pytest/issues"
|
| 233 |
+
stream = StringIO()
|
| 234 |
+
pprint("-" * 100, stream=stream)
|
| 235 |
+
pprint("INTERNALERROR: Unknown entry type returned: %s" % type_name, stream=stream)
|
| 236 |
+
pprint("report_name: %s" % report_class, stream=stream)
|
| 237 |
+
pprint(reportdict, stream=stream)
|
| 238 |
+
pprint("Please report this bug at %s" % url, stream=stream)
|
| 239 |
+
pprint("-" * 100, stream=stream)
|
| 240 |
+
raise RuntimeError(stream.getvalue())
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
@final
|
| 244 |
+
class TestReport(BaseReport):
|
| 245 |
+
"""Basic test report object (also used for setup and teardown calls if
|
| 246 |
+
they fail).
|
| 247 |
+
|
| 248 |
+
Reports can contain arbitrary extra attributes.
|
| 249 |
+
"""
|
| 250 |
+
|
| 251 |
+
__test__ = False
|
| 252 |
+
|
| 253 |
+
def __init__(
|
| 254 |
+
self,
|
| 255 |
+
nodeid: str,
|
| 256 |
+
location: Tuple[str, Optional[int], str],
|
| 257 |
+
keywords: Mapping[str, Any],
|
| 258 |
+
outcome: "Literal['passed', 'failed', 'skipped']",
|
| 259 |
+
longrepr: Union[
|
| 260 |
+
None, ExceptionInfo[BaseException], Tuple[str, int, str], str, TerminalRepr
|
| 261 |
+
],
|
| 262 |
+
when: "Literal['setup', 'call', 'teardown']",
|
| 263 |
+
sections: Iterable[Tuple[str, str]] = (),
|
| 264 |
+
duration: float = 0,
|
| 265 |
+
start: float = 0,
|
| 266 |
+
stop: float = 0,
|
| 267 |
+
user_properties: Optional[Iterable[Tuple[str, object]]] = None,
|
| 268 |
+
**extra,
|
| 269 |
+
) -> None:
|
| 270 |
+
#: Normalized collection nodeid.
|
| 271 |
+
self.nodeid = nodeid
|
| 272 |
+
|
| 273 |
+
#: A (filesystempath, lineno, domaininfo) tuple indicating the
|
| 274 |
+
#: actual location of a test item - it might be different from the
|
| 275 |
+
#: collected one e.g. if a method is inherited from a different module.
|
| 276 |
+
#: The filesystempath may be relative to ``config.rootdir``.
|
| 277 |
+
#: The line number is 0-based.
|
| 278 |
+
self.location: Tuple[str, Optional[int], str] = location
|
| 279 |
+
|
| 280 |
+
#: A name -> value dictionary containing all keywords and
|
| 281 |
+
#: markers associated with a test invocation.
|
| 282 |
+
self.keywords: Mapping[str, Any] = keywords
|
| 283 |
+
|
| 284 |
+
#: Test outcome, always one of "passed", "failed", "skipped".
|
| 285 |
+
self.outcome = outcome
|
| 286 |
+
|
| 287 |
+
#: None or a failure representation.
|
| 288 |
+
self.longrepr = longrepr
|
| 289 |
+
|
| 290 |
+
#: One of 'setup', 'call', 'teardown' to indicate runtest phase.
|
| 291 |
+
self.when = when
|
| 292 |
+
|
| 293 |
+
#: User properties is a list of tuples (name, value) that holds user
|
| 294 |
+
#: defined properties of the test.
|
| 295 |
+
self.user_properties = list(user_properties or [])
|
| 296 |
+
|
| 297 |
+
#: Tuples of str ``(heading, content)`` with extra information
|
| 298 |
+
#: for the test report. Used by pytest to add text captured
|
| 299 |
+
#: from ``stdout``, ``stderr``, and intercepted logging events. May
|
| 300 |
+
#: be used by other plugins to add arbitrary information to reports.
|
| 301 |
+
self.sections = list(sections)
|
| 302 |
+
|
| 303 |
+
#: Time it took to run just the test.
|
| 304 |
+
self.duration: float = duration
|
| 305 |
+
|
| 306 |
+
#: The system time when the call started, in seconds since the epoch.
|
| 307 |
+
self.start: float = start
|
| 308 |
+
#: The system time when the call ended, in seconds since the epoch.
|
| 309 |
+
self.stop: float = stop
|
| 310 |
+
|
| 311 |
+
self.__dict__.update(extra)
|
| 312 |
+
|
| 313 |
+
def __repr__(self) -> str:
|
| 314 |
+
return "<{} {!r} when={!r} outcome={!r}>".format(
|
| 315 |
+
self.__class__.__name__, self.nodeid, self.when, self.outcome
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
@classmethod
|
| 319 |
+
def from_item_and_call(cls, item: Item, call: "CallInfo[None]") -> "TestReport":
|
| 320 |
+
"""Create and fill a TestReport with standard item and call info.
|
| 321 |
+
|
| 322 |
+
:param item: The item.
|
| 323 |
+
:param call: The call info.
|
| 324 |
+
"""
|
| 325 |
+
when = call.when
|
| 326 |
+
# Remove "collect" from the Literal type -- only for collection calls.
|
| 327 |
+
assert when != "collect"
|
| 328 |
+
duration = call.duration
|
| 329 |
+
start = call.start
|
| 330 |
+
stop = call.stop
|
| 331 |
+
keywords = {x: 1 for x in item.keywords}
|
| 332 |
+
excinfo = call.excinfo
|
| 333 |
+
sections = []
|
| 334 |
+
if not call.excinfo:
|
| 335 |
+
outcome: Literal["passed", "failed", "skipped"] = "passed"
|
| 336 |
+
longrepr: Union[
|
| 337 |
+
None,
|
| 338 |
+
ExceptionInfo[BaseException],
|
| 339 |
+
Tuple[str, int, str],
|
| 340 |
+
str,
|
| 341 |
+
TerminalRepr,
|
| 342 |
+
] = None
|
| 343 |
+
else:
|
| 344 |
+
if not isinstance(excinfo, ExceptionInfo):
|
| 345 |
+
outcome = "failed"
|
| 346 |
+
longrepr = excinfo
|
| 347 |
+
elif isinstance(excinfo.value, skip.Exception):
|
| 348 |
+
outcome = "skipped"
|
| 349 |
+
r = excinfo._getreprcrash()
|
| 350 |
+
assert (
|
| 351 |
+
r is not None
|
| 352 |
+
), "There should always be a traceback entry for skipping a test."
|
| 353 |
+
if excinfo.value._use_item_location:
|
| 354 |
+
path, line = item.reportinfo()[:2]
|
| 355 |
+
assert line is not None
|
| 356 |
+
longrepr = os.fspath(path), line + 1, r.message
|
| 357 |
+
else:
|
| 358 |
+
longrepr = (str(r.path), r.lineno, r.message)
|
| 359 |
+
else:
|
| 360 |
+
outcome = "failed"
|
| 361 |
+
if call.when == "call":
|
| 362 |
+
longrepr = item.repr_failure(excinfo)
|
| 363 |
+
else: # exception in setup or teardown
|
| 364 |
+
longrepr = item._repr_failure_py(
|
| 365 |
+
excinfo, style=item.config.getoption("tbstyle", "auto")
|
| 366 |
+
)
|
| 367 |
+
for rwhen, key, content in item._report_sections:
|
| 368 |
+
sections.append((f"Captured {key} {rwhen}", content))
|
| 369 |
+
return cls(
|
| 370 |
+
item.nodeid,
|
| 371 |
+
item.location,
|
| 372 |
+
keywords,
|
| 373 |
+
outcome,
|
| 374 |
+
longrepr,
|
| 375 |
+
when,
|
| 376 |
+
sections,
|
| 377 |
+
duration,
|
| 378 |
+
start,
|
| 379 |
+
stop,
|
| 380 |
+
user_properties=item.user_properties,
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
@final
|
| 385 |
+
class CollectReport(BaseReport):
|
| 386 |
+
"""Collection report object.
|
| 387 |
+
|
| 388 |
+
Reports can contain arbitrary extra attributes.
|
| 389 |
+
"""
|
| 390 |
+
|
| 391 |
+
when = "collect"
|
| 392 |
+
|
| 393 |
+
def __init__(
|
| 394 |
+
self,
|
| 395 |
+
nodeid: str,
|
| 396 |
+
outcome: "Literal['passed', 'failed', 'skipped']",
|
| 397 |
+
longrepr: Union[
|
| 398 |
+
None, ExceptionInfo[BaseException], Tuple[str, int, str], str, TerminalRepr
|
| 399 |
+
],
|
| 400 |
+
result: Optional[List[Union[Item, Collector]]],
|
| 401 |
+
sections: Iterable[Tuple[str, str]] = (),
|
| 402 |
+
**extra,
|
| 403 |
+
) -> None:
|
| 404 |
+
#: Normalized collection nodeid.
|
| 405 |
+
self.nodeid = nodeid
|
| 406 |
+
|
| 407 |
+
#: Test outcome, always one of "passed", "failed", "skipped".
|
| 408 |
+
self.outcome = outcome
|
| 409 |
+
|
| 410 |
+
#: None or a failure representation.
|
| 411 |
+
self.longrepr = longrepr
|
| 412 |
+
|
| 413 |
+
#: The collected items and collection nodes.
|
| 414 |
+
self.result = result or []
|
| 415 |
+
|
| 416 |
+
#: Tuples of str ``(heading, content)`` with extra information
|
| 417 |
+
#: for the test report. Used by pytest to add text captured
|
| 418 |
+
#: from ``stdout``, ``stderr``, and intercepted logging events. May
|
| 419 |
+
#: be used by other plugins to add arbitrary information to reports.
|
| 420 |
+
self.sections = list(sections)
|
| 421 |
+
|
| 422 |
+
self.__dict__.update(extra)
|
| 423 |
+
|
| 424 |
+
@property
|
| 425 |
+
def location( # type:ignore[override]
|
| 426 |
+
self,
|
| 427 |
+
) -> Optional[Tuple[str, Optional[int], str]]:
|
| 428 |
+
return (self.fspath, None, self.fspath)
|
| 429 |
+
|
| 430 |
+
def __repr__(self) -> str:
|
| 431 |
+
return "<CollectReport {!r} lenresult={} outcome={!r}>".format(
|
| 432 |
+
self.nodeid, len(self.result), self.outcome
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
class CollectErrorRepr(TerminalRepr):
|
| 437 |
+
def __init__(self, msg: str) -> None:
|
| 438 |
+
self.longrepr = msg
|
| 439 |
+
|
| 440 |
+
def toterminal(self, out: TerminalWriter) -> None:
|
| 441 |
+
out.line(self.longrepr, red=True)
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def pytest_report_to_serializable(
|
| 445 |
+
report: Union[CollectReport, TestReport]
|
| 446 |
+
) -> Optional[Dict[str, Any]]:
|
| 447 |
+
if isinstance(report, (TestReport, CollectReport)):
|
| 448 |
+
data = report._to_json()
|
| 449 |
+
data["$report_type"] = report.__class__.__name__
|
| 450 |
+
return data
|
| 451 |
+
# TODO: Check if this is actually reachable.
|
| 452 |
+
return None # type: ignore[unreachable]
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def pytest_report_from_serializable(
|
| 456 |
+
data: Dict[str, Any],
|
| 457 |
+
) -> Optional[Union[CollectReport, TestReport]]:
|
| 458 |
+
if "$report_type" in data:
|
| 459 |
+
if data["$report_type"] == "TestReport":
|
| 460 |
+
return TestReport._from_json(data)
|
| 461 |
+
elif data["$report_type"] == "CollectReport":
|
| 462 |
+
return CollectReport._from_json(data)
|
| 463 |
+
assert False, "Unknown report_type unserialize data: {}".format(
|
| 464 |
+
data["$report_type"]
|
| 465 |
+
)
|
| 466 |
+
return None
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def _report_to_json(report: BaseReport) -> Dict[str, Any]:
|
| 470 |
+
"""Return the contents of this report as a dict of builtin entries,
|
| 471 |
+
suitable for serialization.
|
| 472 |
+
|
| 473 |
+
This was originally the serialize_report() function from xdist (ca03269).
|
| 474 |
+
"""
|
| 475 |
+
|
| 476 |
+
def serialize_repr_entry(
|
| 477 |
+
entry: Union[ReprEntry, ReprEntryNative]
|
| 478 |
+
) -> Dict[str, Any]:
|
| 479 |
+
data = dataclasses.asdict(entry)
|
| 480 |
+
for key, value in data.items():
|
| 481 |
+
if hasattr(value, "__dict__"):
|
| 482 |
+
data[key] = dataclasses.asdict(value)
|
| 483 |
+
entry_data = {"type": type(entry).__name__, "data": data}
|
| 484 |
+
return entry_data
|
| 485 |
+
|
| 486 |
+
def serialize_repr_traceback(reprtraceback: ReprTraceback) -> Dict[str, Any]:
|
| 487 |
+
result = dataclasses.asdict(reprtraceback)
|
| 488 |
+
result["reprentries"] = [
|
| 489 |
+
serialize_repr_entry(x) for x in reprtraceback.reprentries
|
| 490 |
+
]
|
| 491 |
+
return result
|
| 492 |
+
|
| 493 |
+
def serialize_repr_crash(
|
| 494 |
+
reprcrash: Optional[ReprFileLocation],
|
| 495 |
+
) -> Optional[Dict[str, Any]]:
|
| 496 |
+
if reprcrash is not None:
|
| 497 |
+
return dataclasses.asdict(reprcrash)
|
| 498 |
+
else:
|
| 499 |
+
return None
|
| 500 |
+
|
| 501 |
+
def serialize_exception_longrepr(rep: BaseReport) -> Dict[str, Any]:
|
| 502 |
+
assert rep.longrepr is not None
|
| 503 |
+
# TODO: Investigate whether the duck typing is really necessary here.
|
| 504 |
+
longrepr = cast(ExceptionRepr, rep.longrepr)
|
| 505 |
+
result: Dict[str, Any] = {
|
| 506 |
+
"reprcrash": serialize_repr_crash(longrepr.reprcrash),
|
| 507 |
+
"reprtraceback": serialize_repr_traceback(longrepr.reprtraceback),
|
| 508 |
+
"sections": longrepr.sections,
|
| 509 |
+
}
|
| 510 |
+
if isinstance(longrepr, ExceptionChainRepr):
|
| 511 |
+
result["chain"] = []
|
| 512 |
+
for repr_traceback, repr_crash, description in longrepr.chain:
|
| 513 |
+
result["chain"].append(
|
| 514 |
+
(
|
| 515 |
+
serialize_repr_traceback(repr_traceback),
|
| 516 |
+
serialize_repr_crash(repr_crash),
|
| 517 |
+
description,
|
| 518 |
+
)
|
| 519 |
+
)
|
| 520 |
+
else:
|
| 521 |
+
result["chain"] = None
|
| 522 |
+
return result
|
| 523 |
+
|
| 524 |
+
d = report.__dict__.copy()
|
| 525 |
+
if hasattr(report.longrepr, "toterminal"):
|
| 526 |
+
if hasattr(report.longrepr, "reprtraceback") and hasattr(
|
| 527 |
+
report.longrepr, "reprcrash"
|
| 528 |
+
):
|
| 529 |
+
d["longrepr"] = serialize_exception_longrepr(report)
|
| 530 |
+
else:
|
| 531 |
+
d["longrepr"] = str(report.longrepr)
|
| 532 |
+
else:
|
| 533 |
+
d["longrepr"] = report.longrepr
|
| 534 |
+
for name in d:
|
| 535 |
+
if isinstance(d[name], os.PathLike):
|
| 536 |
+
d[name] = os.fspath(d[name])
|
| 537 |
+
elif name == "result":
|
| 538 |
+
d[name] = None # for now
|
| 539 |
+
return d
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def _report_kwargs_from_json(reportdict: Dict[str, Any]) -> Dict[str, Any]:
|
| 543 |
+
"""Return **kwargs that can be used to construct a TestReport or
|
| 544 |
+
CollectReport instance.
|
| 545 |
+
|
| 546 |
+
This was originally the serialize_report() function from xdist (ca03269).
|
| 547 |
+
"""
|
| 548 |
+
|
| 549 |
+
def deserialize_repr_entry(entry_data):
|
| 550 |
+
data = entry_data["data"]
|
| 551 |
+
entry_type = entry_data["type"]
|
| 552 |
+
if entry_type == "ReprEntry":
|
| 553 |
+
reprfuncargs = None
|
| 554 |
+
reprfileloc = None
|
| 555 |
+
reprlocals = None
|
| 556 |
+
if data["reprfuncargs"]:
|
| 557 |
+
reprfuncargs = ReprFuncArgs(**data["reprfuncargs"])
|
| 558 |
+
if data["reprfileloc"]:
|
| 559 |
+
reprfileloc = ReprFileLocation(**data["reprfileloc"])
|
| 560 |
+
if data["reprlocals"]:
|
| 561 |
+
reprlocals = ReprLocals(data["reprlocals"]["lines"])
|
| 562 |
+
|
| 563 |
+
reprentry: Union[ReprEntry, ReprEntryNative] = ReprEntry(
|
| 564 |
+
lines=data["lines"],
|
| 565 |
+
reprfuncargs=reprfuncargs,
|
| 566 |
+
reprlocals=reprlocals,
|
| 567 |
+
reprfileloc=reprfileloc,
|
| 568 |
+
style=data["style"],
|
| 569 |
+
)
|
| 570 |
+
elif entry_type == "ReprEntryNative":
|
| 571 |
+
reprentry = ReprEntryNative(data["lines"])
|
| 572 |
+
else:
|
| 573 |
+
_report_unserialization_failure(entry_type, TestReport, reportdict)
|
| 574 |
+
return reprentry
|
| 575 |
+
|
| 576 |
+
def deserialize_repr_traceback(repr_traceback_dict):
|
| 577 |
+
repr_traceback_dict["reprentries"] = [
|
| 578 |
+
deserialize_repr_entry(x) for x in repr_traceback_dict["reprentries"]
|
| 579 |
+
]
|
| 580 |
+
return ReprTraceback(**repr_traceback_dict)
|
| 581 |
+
|
| 582 |
+
def deserialize_repr_crash(repr_crash_dict: Optional[Dict[str, Any]]):
|
| 583 |
+
if repr_crash_dict is not None:
|
| 584 |
+
return ReprFileLocation(**repr_crash_dict)
|
| 585 |
+
else:
|
| 586 |
+
return None
|
| 587 |
+
|
| 588 |
+
if (
|
| 589 |
+
reportdict["longrepr"]
|
| 590 |
+
and "reprcrash" in reportdict["longrepr"]
|
| 591 |
+
and "reprtraceback" in reportdict["longrepr"]
|
| 592 |
+
):
|
| 593 |
+
reprtraceback = deserialize_repr_traceback(
|
| 594 |
+
reportdict["longrepr"]["reprtraceback"]
|
| 595 |
+
)
|
| 596 |
+
reprcrash = deserialize_repr_crash(reportdict["longrepr"]["reprcrash"])
|
| 597 |
+
if reportdict["longrepr"]["chain"]:
|
| 598 |
+
chain = []
|
| 599 |
+
for repr_traceback_data, repr_crash_data, description in reportdict[
|
| 600 |
+
"longrepr"
|
| 601 |
+
]["chain"]:
|
| 602 |
+
chain.append(
|
| 603 |
+
(
|
| 604 |
+
deserialize_repr_traceback(repr_traceback_data),
|
| 605 |
+
deserialize_repr_crash(repr_crash_data),
|
| 606 |
+
description,
|
| 607 |
+
)
|
| 608 |
+
)
|
| 609 |
+
exception_info: Union[
|
| 610 |
+
ExceptionChainRepr, ReprExceptionInfo
|
| 611 |
+
] = ExceptionChainRepr(chain)
|
| 612 |
+
else:
|
| 613 |
+
exception_info = ReprExceptionInfo(
|
| 614 |
+
reprtraceback=reprtraceback,
|
| 615 |
+
reprcrash=reprcrash,
|
| 616 |
+
)
|
| 617 |
+
|
| 618 |
+
for section in reportdict["longrepr"]["sections"]:
|
| 619 |
+
exception_info.addsection(*section)
|
| 620 |
+
reportdict["longrepr"] = exception_info
|
| 621 |
+
|
| 622 |
+
return reportdict
|
wemm/lib/python3.10/site-packages/_pytest/setupplan.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
from typing import Union
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
from _pytest.config import Config
|
| 6 |
+
from _pytest.config import ExitCode
|
| 7 |
+
from _pytest.config.argparsing import Parser
|
| 8 |
+
from _pytest.fixtures import FixtureDef
|
| 9 |
+
from _pytest.fixtures import SubRequest
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def pytest_addoption(parser: Parser) -> None:
|
| 13 |
+
group = parser.getgroup("debugconfig")
|
| 14 |
+
group.addoption(
|
| 15 |
+
"--setupplan",
|
| 16 |
+
"--setup-plan",
|
| 17 |
+
action="store_true",
|
| 18 |
+
help="Show what fixtures and tests would be executed but "
|
| 19 |
+
"don't execute anything",
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@pytest.hookimpl(tryfirst=True)
|
| 24 |
+
def pytest_fixture_setup(
|
| 25 |
+
fixturedef: FixtureDef[object], request: SubRequest
|
| 26 |
+
) -> Optional[object]:
|
| 27 |
+
# Will return a dummy fixture if the setuponly option is provided.
|
| 28 |
+
if request.config.option.setupplan:
|
| 29 |
+
my_cache_key = fixturedef.cache_key(request)
|
| 30 |
+
fixturedef.cached_result = (None, my_cache_key, None)
|
| 31 |
+
return fixturedef.cached_result
|
| 32 |
+
return None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@pytest.hookimpl(tryfirst=True)
|
| 36 |
+
def pytest_cmdline_main(config: Config) -> Optional[Union[int, ExitCode]]:
|
| 37 |
+
if config.option.setupplan:
|
| 38 |
+
config.option.setuponly = True
|
| 39 |
+
config.option.setupshow = True
|
| 40 |
+
return None
|
wemm/lib/python3.10/site-packages/_pytest/skipping.py
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Support for skip/xfail functions and markers."""
|
| 2 |
+
import dataclasses
|
| 3 |
+
import os
|
| 4 |
+
import platform
|
| 5 |
+
import sys
|
| 6 |
+
import traceback
|
| 7 |
+
from collections.abc import Mapping
|
| 8 |
+
from typing import Generator
|
| 9 |
+
from typing import Optional
|
| 10 |
+
from typing import Tuple
|
| 11 |
+
from typing import Type
|
| 12 |
+
|
| 13 |
+
from _pytest.config import Config
|
| 14 |
+
from _pytest.config import hookimpl
|
| 15 |
+
from _pytest.config.argparsing import Parser
|
| 16 |
+
from _pytest.mark.structures import Mark
|
| 17 |
+
from _pytest.nodes import Item
|
| 18 |
+
from _pytest.outcomes import fail
|
| 19 |
+
from _pytest.outcomes import skip
|
| 20 |
+
from _pytest.outcomes import xfail
|
| 21 |
+
from _pytest.reports import BaseReport
|
| 22 |
+
from _pytest.runner import CallInfo
|
| 23 |
+
from _pytest.stash import StashKey
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def pytest_addoption(parser: Parser) -> None:
|
| 27 |
+
group = parser.getgroup("general")
|
| 28 |
+
group.addoption(
|
| 29 |
+
"--runxfail",
|
| 30 |
+
action="store_true",
|
| 31 |
+
dest="runxfail",
|
| 32 |
+
default=False,
|
| 33 |
+
help="Report the results of xfail tests as if they were not marked",
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
parser.addini(
|
| 37 |
+
"xfail_strict",
|
| 38 |
+
"Default for the strict parameter of xfail "
|
| 39 |
+
"markers when not given explicitly (default: False)",
|
| 40 |
+
default=False,
|
| 41 |
+
type="bool",
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def pytest_configure(config: Config) -> None:
|
| 46 |
+
if config.option.runxfail:
|
| 47 |
+
# yay a hack
|
| 48 |
+
import pytest
|
| 49 |
+
|
| 50 |
+
old = pytest.xfail
|
| 51 |
+
config.add_cleanup(lambda: setattr(pytest, "xfail", old))
|
| 52 |
+
|
| 53 |
+
def nop(*args, **kwargs):
|
| 54 |
+
pass
|
| 55 |
+
|
| 56 |
+
nop.Exception = xfail.Exception # type: ignore[attr-defined]
|
| 57 |
+
setattr(pytest, "xfail", nop)
|
| 58 |
+
|
| 59 |
+
config.addinivalue_line(
|
| 60 |
+
"markers",
|
| 61 |
+
"skip(reason=None): skip the given test function with an optional reason. "
|
| 62 |
+
'Example: skip(reason="no way of currently testing this") skips the '
|
| 63 |
+
"test.",
|
| 64 |
+
)
|
| 65 |
+
config.addinivalue_line(
|
| 66 |
+
"markers",
|
| 67 |
+
"skipif(condition, ..., *, reason=...): "
|
| 68 |
+
"skip the given test function if any of the conditions evaluate to True. "
|
| 69 |
+
"Example: skipif(sys.platform == 'win32') skips the test if we are on the win32 platform. "
|
| 70 |
+
"See https://docs.pytest.org/en/stable/reference/reference.html#pytest-mark-skipif",
|
| 71 |
+
)
|
| 72 |
+
config.addinivalue_line(
|
| 73 |
+
"markers",
|
| 74 |
+
"xfail(condition, ..., *, reason=..., run=True, raises=None, strict=xfail_strict): "
|
| 75 |
+
"mark the test function as an expected failure if any of the conditions "
|
| 76 |
+
"evaluate to True. Optionally specify a reason for better reporting "
|
| 77 |
+
"and run=False if you don't even want to execute the test function. "
|
| 78 |
+
"If only specific exception(s) are expected, you can list them in "
|
| 79 |
+
"raises, and if the test fails in other ways, it will be reported as "
|
| 80 |
+
"a true failure. See https://docs.pytest.org/en/stable/reference/reference.html#pytest-mark-xfail",
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def evaluate_condition(item: Item, mark: Mark, condition: object) -> Tuple[bool, str]:
|
| 85 |
+
"""Evaluate a single skipif/xfail condition.
|
| 86 |
+
|
| 87 |
+
If an old-style string condition is given, it is eval()'d, otherwise the
|
| 88 |
+
condition is bool()'d. If this fails, an appropriately formatted pytest.fail
|
| 89 |
+
is raised.
|
| 90 |
+
|
| 91 |
+
Returns (result, reason). The reason is only relevant if the result is True.
|
| 92 |
+
"""
|
| 93 |
+
# String condition.
|
| 94 |
+
if isinstance(condition, str):
|
| 95 |
+
globals_ = {
|
| 96 |
+
"os": os,
|
| 97 |
+
"sys": sys,
|
| 98 |
+
"platform": platform,
|
| 99 |
+
"config": item.config,
|
| 100 |
+
}
|
| 101 |
+
for dictionary in reversed(
|
| 102 |
+
item.ihook.pytest_markeval_namespace(config=item.config)
|
| 103 |
+
):
|
| 104 |
+
if not isinstance(dictionary, Mapping):
|
| 105 |
+
raise ValueError(
|
| 106 |
+
"pytest_markeval_namespace() needs to return a dict, got {!r}".format(
|
| 107 |
+
dictionary
|
| 108 |
+
)
|
| 109 |
+
)
|
| 110 |
+
globals_.update(dictionary)
|
| 111 |
+
if hasattr(item, "obj"):
|
| 112 |
+
globals_.update(item.obj.__globals__) # type: ignore[attr-defined]
|
| 113 |
+
try:
|
| 114 |
+
filename = f"<{mark.name} condition>"
|
| 115 |
+
condition_code = compile(condition, filename, "eval")
|
| 116 |
+
result = eval(condition_code, globals_)
|
| 117 |
+
except SyntaxError as exc:
|
| 118 |
+
msglines = [
|
| 119 |
+
"Error evaluating %r condition" % mark.name,
|
| 120 |
+
" " + condition,
|
| 121 |
+
" " + " " * (exc.offset or 0) + "^",
|
| 122 |
+
"SyntaxError: invalid syntax",
|
| 123 |
+
]
|
| 124 |
+
fail("\n".join(msglines), pytrace=False)
|
| 125 |
+
except Exception as exc:
|
| 126 |
+
msglines = [
|
| 127 |
+
"Error evaluating %r condition" % mark.name,
|
| 128 |
+
" " + condition,
|
| 129 |
+
*traceback.format_exception_only(type(exc), exc),
|
| 130 |
+
]
|
| 131 |
+
fail("\n".join(msglines), pytrace=False)
|
| 132 |
+
|
| 133 |
+
# Boolean condition.
|
| 134 |
+
else:
|
| 135 |
+
try:
|
| 136 |
+
result = bool(condition)
|
| 137 |
+
except Exception as exc:
|
| 138 |
+
msglines = [
|
| 139 |
+
"Error evaluating %r condition as a boolean" % mark.name,
|
| 140 |
+
*traceback.format_exception_only(type(exc), exc),
|
| 141 |
+
]
|
| 142 |
+
fail("\n".join(msglines), pytrace=False)
|
| 143 |
+
|
| 144 |
+
reason = mark.kwargs.get("reason", None)
|
| 145 |
+
if reason is None:
|
| 146 |
+
if isinstance(condition, str):
|
| 147 |
+
reason = "condition: " + condition
|
| 148 |
+
else:
|
| 149 |
+
# XXX better be checked at collection time
|
| 150 |
+
msg = (
|
| 151 |
+
"Error evaluating %r: " % mark.name
|
| 152 |
+
+ "you need to specify reason=STRING when using booleans as conditions."
|
| 153 |
+
)
|
| 154 |
+
fail(msg, pytrace=False)
|
| 155 |
+
|
| 156 |
+
return result, reason
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@dataclasses.dataclass(frozen=True)
|
| 160 |
+
class Skip:
|
| 161 |
+
"""The result of evaluate_skip_marks()."""
|
| 162 |
+
|
| 163 |
+
reason: str = "unconditional skip"
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def evaluate_skip_marks(item: Item) -> Optional[Skip]:
|
| 167 |
+
"""Evaluate skip and skipif marks on item, returning Skip if triggered."""
|
| 168 |
+
for mark in item.iter_markers(name="skipif"):
|
| 169 |
+
if "condition" not in mark.kwargs:
|
| 170 |
+
conditions = mark.args
|
| 171 |
+
else:
|
| 172 |
+
conditions = (mark.kwargs["condition"],)
|
| 173 |
+
|
| 174 |
+
# Unconditional.
|
| 175 |
+
if not conditions:
|
| 176 |
+
reason = mark.kwargs.get("reason", "")
|
| 177 |
+
return Skip(reason)
|
| 178 |
+
|
| 179 |
+
# If any of the conditions are true.
|
| 180 |
+
for condition in conditions:
|
| 181 |
+
result, reason = evaluate_condition(item, mark, condition)
|
| 182 |
+
if result:
|
| 183 |
+
return Skip(reason)
|
| 184 |
+
|
| 185 |
+
for mark in item.iter_markers(name="skip"):
|
| 186 |
+
try:
|
| 187 |
+
return Skip(*mark.args, **mark.kwargs)
|
| 188 |
+
except TypeError as e:
|
| 189 |
+
raise TypeError(str(e) + " - maybe you meant pytest.mark.skipif?") from None
|
| 190 |
+
|
| 191 |
+
return None
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
@dataclasses.dataclass(frozen=True)
|
| 195 |
+
class Xfail:
|
| 196 |
+
"""The result of evaluate_xfail_marks()."""
|
| 197 |
+
|
| 198 |
+
__slots__ = ("reason", "run", "strict", "raises")
|
| 199 |
+
|
| 200 |
+
reason: str
|
| 201 |
+
run: bool
|
| 202 |
+
strict: bool
|
| 203 |
+
raises: Optional[Tuple[Type[BaseException], ...]]
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def evaluate_xfail_marks(item: Item) -> Optional[Xfail]:
|
| 207 |
+
"""Evaluate xfail marks on item, returning Xfail if triggered."""
|
| 208 |
+
for mark in item.iter_markers(name="xfail"):
|
| 209 |
+
run = mark.kwargs.get("run", True)
|
| 210 |
+
strict = mark.kwargs.get("strict", item.config.getini("xfail_strict"))
|
| 211 |
+
raises = mark.kwargs.get("raises", None)
|
| 212 |
+
if "condition" not in mark.kwargs:
|
| 213 |
+
conditions = mark.args
|
| 214 |
+
else:
|
| 215 |
+
conditions = (mark.kwargs["condition"],)
|
| 216 |
+
|
| 217 |
+
# Unconditional.
|
| 218 |
+
if not conditions:
|
| 219 |
+
reason = mark.kwargs.get("reason", "")
|
| 220 |
+
return Xfail(reason, run, strict, raises)
|
| 221 |
+
|
| 222 |
+
# If any of the conditions are true.
|
| 223 |
+
for condition in conditions:
|
| 224 |
+
result, reason = evaluate_condition(item, mark, condition)
|
| 225 |
+
if result:
|
| 226 |
+
return Xfail(reason, run, strict, raises)
|
| 227 |
+
|
| 228 |
+
return None
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
# Saves the xfail mark evaluation. Can be refreshed during call if None.
|
| 232 |
+
xfailed_key = StashKey[Optional[Xfail]]()
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
@hookimpl(tryfirst=True)
|
| 236 |
+
def pytest_runtest_setup(item: Item) -> None:
|
| 237 |
+
skipped = evaluate_skip_marks(item)
|
| 238 |
+
if skipped:
|
| 239 |
+
raise skip.Exception(skipped.reason, _use_item_location=True)
|
| 240 |
+
|
| 241 |
+
item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item)
|
| 242 |
+
if xfailed and not item.config.option.runxfail and not xfailed.run:
|
| 243 |
+
xfail("[NOTRUN] " + xfailed.reason)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
@hookimpl(hookwrapper=True)
|
| 247 |
+
def pytest_runtest_call(item: Item) -> Generator[None, None, None]:
|
| 248 |
+
xfailed = item.stash.get(xfailed_key, None)
|
| 249 |
+
if xfailed is None:
|
| 250 |
+
item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item)
|
| 251 |
+
|
| 252 |
+
if xfailed and not item.config.option.runxfail and not xfailed.run:
|
| 253 |
+
xfail("[NOTRUN] " + xfailed.reason)
|
| 254 |
+
|
| 255 |
+
yield
|
| 256 |
+
|
| 257 |
+
# The test run may have added an xfail mark dynamically.
|
| 258 |
+
xfailed = item.stash.get(xfailed_key, None)
|
| 259 |
+
if xfailed is None:
|
| 260 |
+
item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
@hookimpl(hookwrapper=True)
|
| 264 |
+
def pytest_runtest_makereport(item: Item, call: CallInfo[None]):
|
| 265 |
+
outcome = yield
|
| 266 |
+
rep = outcome.get_result()
|
| 267 |
+
xfailed = item.stash.get(xfailed_key, None)
|
| 268 |
+
if item.config.option.runxfail:
|
| 269 |
+
pass # don't interfere
|
| 270 |
+
elif call.excinfo and isinstance(call.excinfo.value, xfail.Exception):
|
| 271 |
+
assert call.excinfo.value.msg is not None
|
| 272 |
+
rep.wasxfail = "reason: " + call.excinfo.value.msg
|
| 273 |
+
rep.outcome = "skipped"
|
| 274 |
+
elif not rep.skipped and xfailed:
|
| 275 |
+
if call.excinfo:
|
| 276 |
+
raises = xfailed.raises
|
| 277 |
+
if raises is not None and not isinstance(call.excinfo.value, raises):
|
| 278 |
+
rep.outcome = "failed"
|
| 279 |
+
else:
|
| 280 |
+
rep.outcome = "skipped"
|
| 281 |
+
rep.wasxfail = xfailed.reason
|
| 282 |
+
elif call.when == "call":
|
| 283 |
+
if xfailed.strict:
|
| 284 |
+
rep.outcome = "failed"
|
| 285 |
+
rep.longrepr = "[XPASS(strict)] " + xfailed.reason
|
| 286 |
+
else:
|
| 287 |
+
rep.outcome = "passed"
|
| 288 |
+
rep.wasxfail = xfailed.reason
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def pytest_report_teststatus(report: BaseReport) -> Optional[Tuple[str, str, str]]:
|
| 292 |
+
if hasattr(report, "wasxfail"):
|
| 293 |
+
if report.skipped:
|
| 294 |
+
return "xfailed", "x", "XFAIL"
|
| 295 |
+
elif report.passed:
|
| 296 |
+
return "xpassed", "X", "XPASS"
|
| 297 |
+
return None
|
wemm/lib/python3.10/site-packages/_pytest/terminal.py
ADDED
|
@@ -0,0 +1,1481 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Terminal reporting of the full testing process.
|
| 2 |
+
|
| 3 |
+
This is a good source for looking at the various reporting hooks.
|
| 4 |
+
"""
|
| 5 |
+
import argparse
|
| 6 |
+
import dataclasses
|
| 7 |
+
import datetime
|
| 8 |
+
import inspect
|
| 9 |
+
import platform
|
| 10 |
+
import sys
|
| 11 |
+
import textwrap
|
| 12 |
+
import warnings
|
| 13 |
+
from collections import Counter
|
| 14 |
+
from functools import partial
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Any
|
| 17 |
+
from typing import Callable
|
| 18 |
+
from typing import cast
|
| 19 |
+
from typing import ClassVar
|
| 20 |
+
from typing import Dict
|
| 21 |
+
from typing import Generator
|
| 22 |
+
from typing import List
|
| 23 |
+
from typing import Mapping
|
| 24 |
+
from typing import NamedTuple
|
| 25 |
+
from typing import Optional
|
| 26 |
+
from typing import Sequence
|
| 27 |
+
from typing import Set
|
| 28 |
+
from typing import TextIO
|
| 29 |
+
from typing import Tuple
|
| 30 |
+
from typing import TYPE_CHECKING
|
| 31 |
+
from typing import Union
|
| 32 |
+
|
| 33 |
+
import pluggy
|
| 34 |
+
|
| 35 |
+
import _pytest._version
|
| 36 |
+
from _pytest import nodes
|
| 37 |
+
from _pytest import timing
|
| 38 |
+
from _pytest._code import ExceptionInfo
|
| 39 |
+
from _pytest._code.code import ExceptionRepr
|
| 40 |
+
from _pytest._io import TerminalWriter
|
| 41 |
+
from _pytest._io.wcwidth import wcswidth
|
| 42 |
+
from _pytest.assertion.util import running_on_ci
|
| 43 |
+
from _pytest.compat import final
|
| 44 |
+
from _pytest.config import _PluggyPlugin
|
| 45 |
+
from _pytest.config import Config
|
| 46 |
+
from _pytest.config import ExitCode
|
| 47 |
+
from _pytest.config import hookimpl
|
| 48 |
+
from _pytest.config.argparsing import Parser
|
| 49 |
+
from _pytest.nodes import Item
|
| 50 |
+
from _pytest.nodes import Node
|
| 51 |
+
from _pytest.pathlib import absolutepath
|
| 52 |
+
from _pytest.pathlib import bestrelpath
|
| 53 |
+
from _pytest.reports import BaseReport
|
| 54 |
+
from _pytest.reports import CollectReport
|
| 55 |
+
from _pytest.reports import TestReport
|
| 56 |
+
|
| 57 |
+
if TYPE_CHECKING:
|
| 58 |
+
from typing_extensions import Literal
|
| 59 |
+
|
| 60 |
+
from _pytest.main import Session
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
REPORT_COLLECTING_RESOLUTION = 0.5
|
| 64 |
+
|
| 65 |
+
KNOWN_TYPES = (
|
| 66 |
+
"failed",
|
| 67 |
+
"passed",
|
| 68 |
+
"skipped",
|
| 69 |
+
"deselected",
|
| 70 |
+
"xfailed",
|
| 71 |
+
"xpassed",
|
| 72 |
+
"warnings",
|
| 73 |
+
"error",
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
_REPORTCHARS_DEFAULT = "fE"
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class MoreQuietAction(argparse.Action):
|
| 80 |
+
"""A modified copy of the argparse count action which counts down and updates
|
| 81 |
+
the legacy quiet attribute at the same time.
|
| 82 |
+
|
| 83 |
+
Used to unify verbosity handling.
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
def __init__(
|
| 87 |
+
self,
|
| 88 |
+
option_strings: Sequence[str],
|
| 89 |
+
dest: str,
|
| 90 |
+
default: object = None,
|
| 91 |
+
required: bool = False,
|
| 92 |
+
help: Optional[str] = None,
|
| 93 |
+
) -> None:
|
| 94 |
+
super().__init__(
|
| 95 |
+
option_strings=option_strings,
|
| 96 |
+
dest=dest,
|
| 97 |
+
nargs=0,
|
| 98 |
+
default=default,
|
| 99 |
+
required=required,
|
| 100 |
+
help=help,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
def __call__(
|
| 104 |
+
self,
|
| 105 |
+
parser: argparse.ArgumentParser,
|
| 106 |
+
namespace: argparse.Namespace,
|
| 107 |
+
values: Union[str, Sequence[object], None],
|
| 108 |
+
option_string: Optional[str] = None,
|
| 109 |
+
) -> None:
|
| 110 |
+
new_count = getattr(namespace, self.dest, 0) - 1
|
| 111 |
+
setattr(namespace, self.dest, new_count)
|
| 112 |
+
# todo Deprecate config.quiet
|
| 113 |
+
namespace.quiet = getattr(namespace, "quiet", 0) + 1
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class TestShortLogReport(NamedTuple):
|
| 117 |
+
"""Used to store the test status result category, shortletter and verbose word.
|
| 118 |
+
For example ``"rerun", "R", ("RERUN", {"yellow": True})``.
|
| 119 |
+
|
| 120 |
+
:ivar category:
|
| 121 |
+
The class of result, for example ``“passed”``, ``“skipped”``, ``“error”``, or the empty string.
|
| 122 |
+
|
| 123 |
+
:ivar letter:
|
| 124 |
+
The short letter shown as testing progresses, for example ``"."``, ``"s"``, ``"E"``, or the empty string.
|
| 125 |
+
|
| 126 |
+
:ivar word:
|
| 127 |
+
Verbose word is shown as testing progresses in verbose mode, for example ``"PASSED"``, ``"SKIPPED"``,
|
| 128 |
+
``"ERROR"``, or the empty string.
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
category: str
|
| 132 |
+
letter: str
|
| 133 |
+
word: Union[str, Tuple[str, Mapping[str, bool]]]
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def pytest_addoption(parser: Parser) -> None:
|
| 137 |
+
group = parser.getgroup("terminal reporting", "Reporting", after="general")
|
| 138 |
+
group._addoption(
|
| 139 |
+
"-v",
|
| 140 |
+
"--verbose",
|
| 141 |
+
action="count",
|
| 142 |
+
default=0,
|
| 143 |
+
dest="verbose",
|
| 144 |
+
help="Increase verbosity",
|
| 145 |
+
)
|
| 146 |
+
group._addoption(
|
| 147 |
+
"--no-header",
|
| 148 |
+
action="store_true",
|
| 149 |
+
default=False,
|
| 150 |
+
dest="no_header",
|
| 151 |
+
help="Disable header",
|
| 152 |
+
)
|
| 153 |
+
group._addoption(
|
| 154 |
+
"--no-summary",
|
| 155 |
+
action="store_true",
|
| 156 |
+
default=False,
|
| 157 |
+
dest="no_summary",
|
| 158 |
+
help="Disable summary",
|
| 159 |
+
)
|
| 160 |
+
group._addoption(
|
| 161 |
+
"-q",
|
| 162 |
+
"--quiet",
|
| 163 |
+
action=MoreQuietAction,
|
| 164 |
+
default=0,
|
| 165 |
+
dest="verbose",
|
| 166 |
+
help="Decrease verbosity",
|
| 167 |
+
)
|
| 168 |
+
group._addoption(
|
| 169 |
+
"--verbosity",
|
| 170 |
+
dest="verbose",
|
| 171 |
+
type=int,
|
| 172 |
+
default=0,
|
| 173 |
+
help="Set verbosity. Default: 0.",
|
| 174 |
+
)
|
| 175 |
+
group._addoption(
|
| 176 |
+
"-r",
|
| 177 |
+
action="store",
|
| 178 |
+
dest="reportchars",
|
| 179 |
+
default=_REPORTCHARS_DEFAULT,
|
| 180 |
+
metavar="chars",
|
| 181 |
+
help="Show extra test summary info as specified by chars: (f)ailed, "
|
| 182 |
+
"(E)rror, (s)kipped, (x)failed, (X)passed, "
|
| 183 |
+
"(p)assed, (P)assed with output, (a)ll except passed (p/P), or (A)ll. "
|
| 184 |
+
"(w)arnings are enabled by default (see --disable-warnings), "
|
| 185 |
+
"'N' can be used to reset the list. (default: 'fE').",
|
| 186 |
+
)
|
| 187 |
+
group._addoption(
|
| 188 |
+
"--disable-warnings",
|
| 189 |
+
"--disable-pytest-warnings",
|
| 190 |
+
default=False,
|
| 191 |
+
dest="disable_warnings",
|
| 192 |
+
action="store_true",
|
| 193 |
+
help="Disable warnings summary",
|
| 194 |
+
)
|
| 195 |
+
group._addoption(
|
| 196 |
+
"-l",
|
| 197 |
+
"--showlocals",
|
| 198 |
+
action="store_true",
|
| 199 |
+
dest="showlocals",
|
| 200 |
+
default=False,
|
| 201 |
+
help="Show locals in tracebacks (disabled by default)",
|
| 202 |
+
)
|
| 203 |
+
group._addoption(
|
| 204 |
+
"--no-showlocals",
|
| 205 |
+
action="store_false",
|
| 206 |
+
dest="showlocals",
|
| 207 |
+
help="Hide locals in tracebacks (negate --showlocals passed through addopts)",
|
| 208 |
+
)
|
| 209 |
+
group._addoption(
|
| 210 |
+
"--tb",
|
| 211 |
+
metavar="style",
|
| 212 |
+
action="store",
|
| 213 |
+
dest="tbstyle",
|
| 214 |
+
default="auto",
|
| 215 |
+
choices=["auto", "long", "short", "no", "line", "native"],
|
| 216 |
+
help="Traceback print mode (auto/long/short/line/native/no)",
|
| 217 |
+
)
|
| 218 |
+
group._addoption(
|
| 219 |
+
"--show-capture",
|
| 220 |
+
action="store",
|
| 221 |
+
dest="showcapture",
|
| 222 |
+
choices=["no", "stdout", "stderr", "log", "all"],
|
| 223 |
+
default="all",
|
| 224 |
+
help="Controls how captured stdout/stderr/log is shown on failed tests. "
|
| 225 |
+
"Default: all.",
|
| 226 |
+
)
|
| 227 |
+
group._addoption(
|
| 228 |
+
"--fulltrace",
|
| 229 |
+
"--full-trace",
|
| 230 |
+
action="store_true",
|
| 231 |
+
default=False,
|
| 232 |
+
help="Don't cut any tracebacks (default is to cut)",
|
| 233 |
+
)
|
| 234 |
+
group._addoption(
|
| 235 |
+
"--color",
|
| 236 |
+
metavar="color",
|
| 237 |
+
action="store",
|
| 238 |
+
dest="color",
|
| 239 |
+
default="auto",
|
| 240 |
+
choices=["yes", "no", "auto"],
|
| 241 |
+
help="Color terminal output (yes/no/auto)",
|
| 242 |
+
)
|
| 243 |
+
group._addoption(
|
| 244 |
+
"--code-highlight",
|
| 245 |
+
default="yes",
|
| 246 |
+
choices=["yes", "no"],
|
| 247 |
+
help="Whether code should be highlighted (only if --color is also enabled). "
|
| 248 |
+
"Default: yes.",
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
parser.addini(
|
| 252 |
+
"console_output_style",
|
| 253 |
+
help='Console output: "classic", or with additional progress information '
|
| 254 |
+
'("progress" (percentage) | "count" | "progress-even-when-capture-no" (forces '
|
| 255 |
+
"progress even when capture=no)",
|
| 256 |
+
default="progress",
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def pytest_configure(config: Config) -> None:
|
| 261 |
+
reporter = TerminalReporter(config, sys.stdout)
|
| 262 |
+
config.pluginmanager.register(reporter, "terminalreporter")
|
| 263 |
+
if config.option.debug or config.option.traceconfig:
|
| 264 |
+
|
| 265 |
+
def mywriter(tags, args):
|
| 266 |
+
msg = " ".join(map(str, args))
|
| 267 |
+
reporter.write_line("[traceconfig] " + msg)
|
| 268 |
+
|
| 269 |
+
config.trace.root.setprocessor("pytest:config", mywriter)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def getreportopt(config: Config) -> str:
|
| 273 |
+
reportchars: str = config.option.reportchars
|
| 274 |
+
|
| 275 |
+
old_aliases = {"F", "S"}
|
| 276 |
+
reportopts = ""
|
| 277 |
+
for char in reportchars:
|
| 278 |
+
if char in old_aliases:
|
| 279 |
+
char = char.lower()
|
| 280 |
+
if char == "a":
|
| 281 |
+
reportopts = "sxXEf"
|
| 282 |
+
elif char == "A":
|
| 283 |
+
reportopts = "PpsxXEf"
|
| 284 |
+
elif char == "N":
|
| 285 |
+
reportopts = ""
|
| 286 |
+
elif char not in reportopts:
|
| 287 |
+
reportopts += char
|
| 288 |
+
|
| 289 |
+
if not config.option.disable_warnings and "w" not in reportopts:
|
| 290 |
+
reportopts = "w" + reportopts
|
| 291 |
+
elif config.option.disable_warnings and "w" in reportopts:
|
| 292 |
+
reportopts = reportopts.replace("w", "")
|
| 293 |
+
|
| 294 |
+
return reportopts
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
@hookimpl(trylast=True) # after _pytest.runner
|
| 298 |
+
def pytest_report_teststatus(report: BaseReport) -> Tuple[str, str, str]:
|
| 299 |
+
letter = "F"
|
| 300 |
+
if report.passed:
|
| 301 |
+
letter = "."
|
| 302 |
+
elif report.skipped:
|
| 303 |
+
letter = "s"
|
| 304 |
+
|
| 305 |
+
outcome: str = report.outcome
|
| 306 |
+
if report.when in ("collect", "setup", "teardown") and outcome == "failed":
|
| 307 |
+
outcome = "error"
|
| 308 |
+
letter = "E"
|
| 309 |
+
|
| 310 |
+
return outcome, letter, outcome.upper()
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
@dataclasses.dataclass
|
| 314 |
+
class WarningReport:
|
| 315 |
+
"""Simple structure to hold warnings information captured by ``pytest_warning_recorded``.
|
| 316 |
+
|
| 317 |
+
:ivar str message:
|
| 318 |
+
User friendly message about the warning.
|
| 319 |
+
:ivar str|None nodeid:
|
| 320 |
+
nodeid that generated the warning (see ``get_location``).
|
| 321 |
+
:ivar tuple fslocation:
|
| 322 |
+
File system location of the source of the warning (see ``get_location``).
|
| 323 |
+
"""
|
| 324 |
+
|
| 325 |
+
message: str
|
| 326 |
+
nodeid: Optional[str] = None
|
| 327 |
+
fslocation: Optional[Tuple[str, int]] = None
|
| 328 |
+
|
| 329 |
+
count_towards_summary: ClassVar = True
|
| 330 |
+
|
| 331 |
+
def get_location(self, config: Config) -> Optional[str]:
|
| 332 |
+
"""Return the more user-friendly information about the location of a warning, or None."""
|
| 333 |
+
if self.nodeid:
|
| 334 |
+
return self.nodeid
|
| 335 |
+
if self.fslocation:
|
| 336 |
+
filename, linenum = self.fslocation
|
| 337 |
+
relpath = bestrelpath(config.invocation_params.dir, absolutepath(filename))
|
| 338 |
+
return f"{relpath}:{linenum}"
|
| 339 |
+
return None
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
@final
|
| 343 |
+
class TerminalReporter:
|
| 344 |
+
def __init__(self, config: Config, file: Optional[TextIO] = None) -> None:
|
| 345 |
+
import _pytest.config
|
| 346 |
+
|
| 347 |
+
self.config = config
|
| 348 |
+
self._numcollected = 0
|
| 349 |
+
self._session: Optional[Session] = None
|
| 350 |
+
self._showfspath: Optional[bool] = None
|
| 351 |
+
|
| 352 |
+
self.stats: Dict[str, List[Any]] = {}
|
| 353 |
+
self._main_color: Optional[str] = None
|
| 354 |
+
self._known_types: Optional[List[str]] = None
|
| 355 |
+
self.startpath = config.invocation_params.dir
|
| 356 |
+
if file is None:
|
| 357 |
+
file = sys.stdout
|
| 358 |
+
self._tw = _pytest.config.create_terminal_writer(config, file)
|
| 359 |
+
self._screen_width = self._tw.fullwidth
|
| 360 |
+
self.currentfspath: Union[None, Path, str, int] = None
|
| 361 |
+
self.reportchars = getreportopt(config)
|
| 362 |
+
self.hasmarkup = self._tw.hasmarkup
|
| 363 |
+
self.isatty = file.isatty()
|
| 364 |
+
self._progress_nodeids_reported: Set[str] = set()
|
| 365 |
+
self._show_progress_info = self._determine_show_progress_info()
|
| 366 |
+
self._collect_report_last_write: Optional[float] = None
|
| 367 |
+
self._already_displayed_warnings: Optional[int] = None
|
| 368 |
+
self._keyboardinterrupt_memo: Optional[ExceptionRepr] = None
|
| 369 |
+
|
| 370 |
+
def _determine_show_progress_info(self) -> "Literal['progress', 'count', False]":
|
| 371 |
+
"""Return whether we should display progress information based on the current config."""
|
| 372 |
+
# do not show progress if we are not capturing output (#3038) unless explicitly
|
| 373 |
+
# overridden by progress-even-when-capture-no
|
| 374 |
+
if (
|
| 375 |
+
self.config.getoption("capture", "no") == "no"
|
| 376 |
+
and self.config.getini("console_output_style")
|
| 377 |
+
!= "progress-even-when-capture-no"
|
| 378 |
+
):
|
| 379 |
+
return False
|
| 380 |
+
# do not show progress if we are showing fixture setup/teardown
|
| 381 |
+
if self.config.getoption("setupshow", False):
|
| 382 |
+
return False
|
| 383 |
+
cfg: str = self.config.getini("console_output_style")
|
| 384 |
+
if cfg == "progress" or cfg == "progress-even-when-capture-no":
|
| 385 |
+
return "progress"
|
| 386 |
+
elif cfg == "count":
|
| 387 |
+
return "count"
|
| 388 |
+
else:
|
| 389 |
+
return False
|
| 390 |
+
|
| 391 |
+
@property
|
| 392 |
+
def verbosity(self) -> int:
|
| 393 |
+
verbosity: int = self.config.option.verbose
|
| 394 |
+
return verbosity
|
| 395 |
+
|
| 396 |
+
@property
|
| 397 |
+
def showheader(self) -> bool:
|
| 398 |
+
return self.verbosity >= 0
|
| 399 |
+
|
| 400 |
+
@property
|
| 401 |
+
def no_header(self) -> bool:
|
| 402 |
+
return bool(self.config.option.no_header)
|
| 403 |
+
|
| 404 |
+
@property
|
| 405 |
+
def no_summary(self) -> bool:
|
| 406 |
+
return bool(self.config.option.no_summary)
|
| 407 |
+
|
| 408 |
+
@property
|
| 409 |
+
def showfspath(self) -> bool:
|
| 410 |
+
if self._showfspath is None:
|
| 411 |
+
return self.verbosity >= 0
|
| 412 |
+
return self._showfspath
|
| 413 |
+
|
| 414 |
+
@showfspath.setter
|
| 415 |
+
def showfspath(self, value: Optional[bool]) -> None:
|
| 416 |
+
self._showfspath = value
|
| 417 |
+
|
| 418 |
+
@property
|
| 419 |
+
def showlongtestinfo(self) -> bool:
|
| 420 |
+
return self.verbosity > 0
|
| 421 |
+
|
| 422 |
+
def hasopt(self, char: str) -> bool:
|
| 423 |
+
char = {"xfailed": "x", "skipped": "s"}.get(char, char)
|
| 424 |
+
return char in self.reportchars
|
| 425 |
+
|
| 426 |
+
def write_fspath_result(self, nodeid: str, res, **markup: bool) -> None:
|
| 427 |
+
fspath = self.config.rootpath / nodeid.split("::")[0]
|
| 428 |
+
if self.currentfspath is None or fspath != self.currentfspath:
|
| 429 |
+
if self.currentfspath is not None and self._show_progress_info:
|
| 430 |
+
self._write_progress_information_filling_space()
|
| 431 |
+
self.currentfspath = fspath
|
| 432 |
+
relfspath = bestrelpath(self.startpath, fspath)
|
| 433 |
+
self._tw.line()
|
| 434 |
+
self._tw.write(relfspath + " ")
|
| 435 |
+
self._tw.write(res, flush=True, **markup)
|
| 436 |
+
|
| 437 |
+
def write_ensure_prefix(self, prefix: str, extra: str = "", **kwargs) -> None:
|
| 438 |
+
if self.currentfspath != prefix:
|
| 439 |
+
self._tw.line()
|
| 440 |
+
self.currentfspath = prefix
|
| 441 |
+
self._tw.write(prefix)
|
| 442 |
+
if extra:
|
| 443 |
+
self._tw.write(extra, **kwargs)
|
| 444 |
+
self.currentfspath = -2
|
| 445 |
+
|
| 446 |
+
def ensure_newline(self) -> None:
|
| 447 |
+
if self.currentfspath:
|
| 448 |
+
self._tw.line()
|
| 449 |
+
self.currentfspath = None
|
| 450 |
+
|
| 451 |
+
def wrap_write(
|
| 452 |
+
self,
|
| 453 |
+
content: str,
|
| 454 |
+
*,
|
| 455 |
+
flush: bool = False,
|
| 456 |
+
margin: int = 8,
|
| 457 |
+
line_sep: str = "\n",
|
| 458 |
+
**markup: bool,
|
| 459 |
+
) -> None:
|
| 460 |
+
"""Wrap message with margin for progress info."""
|
| 461 |
+
width_of_current_line = self._tw.width_of_current_line
|
| 462 |
+
wrapped = line_sep.join(
|
| 463 |
+
textwrap.wrap(
|
| 464 |
+
" " * width_of_current_line + content,
|
| 465 |
+
width=self._screen_width - margin,
|
| 466 |
+
drop_whitespace=True,
|
| 467 |
+
replace_whitespace=False,
|
| 468 |
+
),
|
| 469 |
+
)
|
| 470 |
+
wrapped = wrapped[width_of_current_line:]
|
| 471 |
+
self._tw.write(wrapped, flush=flush, **markup)
|
| 472 |
+
|
| 473 |
+
def write(self, content: str, *, flush: bool = False, **markup: bool) -> None:
|
| 474 |
+
self._tw.write(content, flush=flush, **markup)
|
| 475 |
+
|
| 476 |
+
def flush(self) -> None:
|
| 477 |
+
self._tw.flush()
|
| 478 |
+
|
| 479 |
+
def write_line(self, line: Union[str, bytes], **markup: bool) -> None:
|
| 480 |
+
if not isinstance(line, str):
|
| 481 |
+
line = str(line, errors="replace")
|
| 482 |
+
self.ensure_newline()
|
| 483 |
+
self._tw.line(line, **markup)
|
| 484 |
+
|
| 485 |
+
def rewrite(self, line: str, **markup: bool) -> None:
|
| 486 |
+
"""Rewinds the terminal cursor to the beginning and writes the given line.
|
| 487 |
+
|
| 488 |
+
:param erase:
|
| 489 |
+
If True, will also add spaces until the full terminal width to ensure
|
| 490 |
+
previous lines are properly erased.
|
| 491 |
+
|
| 492 |
+
The rest of the keyword arguments are markup instructions.
|
| 493 |
+
"""
|
| 494 |
+
erase = markup.pop("erase", False)
|
| 495 |
+
if erase:
|
| 496 |
+
fill_count = self._tw.fullwidth - len(line) - 1
|
| 497 |
+
fill = " " * fill_count
|
| 498 |
+
else:
|
| 499 |
+
fill = ""
|
| 500 |
+
line = str(line)
|
| 501 |
+
self._tw.write("\r" + line + fill, **markup)
|
| 502 |
+
|
| 503 |
+
def write_sep(
|
| 504 |
+
self,
|
| 505 |
+
sep: str,
|
| 506 |
+
title: Optional[str] = None,
|
| 507 |
+
fullwidth: Optional[int] = None,
|
| 508 |
+
**markup: bool,
|
| 509 |
+
) -> None:
|
| 510 |
+
self.ensure_newline()
|
| 511 |
+
self._tw.sep(sep, title, fullwidth, **markup)
|
| 512 |
+
|
| 513 |
+
def section(self, title: str, sep: str = "=", **kw: bool) -> None:
|
| 514 |
+
self._tw.sep(sep, title, **kw)
|
| 515 |
+
|
| 516 |
+
def line(self, msg: str, **kw: bool) -> None:
|
| 517 |
+
self._tw.line(msg, **kw)
|
| 518 |
+
|
| 519 |
+
def _add_stats(self, category: str, items: Sequence[Any]) -> None:
|
| 520 |
+
set_main_color = category not in self.stats
|
| 521 |
+
self.stats.setdefault(category, []).extend(items)
|
| 522 |
+
if set_main_color:
|
| 523 |
+
self._set_main_color()
|
| 524 |
+
|
| 525 |
+
def pytest_internalerror(self, excrepr: ExceptionRepr) -> bool:
|
| 526 |
+
for line in str(excrepr).split("\n"):
|
| 527 |
+
self.write_line("INTERNALERROR> " + line)
|
| 528 |
+
return True
|
| 529 |
+
|
| 530 |
+
def pytest_warning_recorded(
|
| 531 |
+
self,
|
| 532 |
+
warning_message: warnings.WarningMessage,
|
| 533 |
+
nodeid: str,
|
| 534 |
+
) -> None:
|
| 535 |
+
from _pytest.warnings import warning_record_to_str
|
| 536 |
+
|
| 537 |
+
fslocation = warning_message.filename, warning_message.lineno
|
| 538 |
+
message = warning_record_to_str(warning_message)
|
| 539 |
+
|
| 540 |
+
warning_report = WarningReport(
|
| 541 |
+
fslocation=fslocation, message=message, nodeid=nodeid
|
| 542 |
+
)
|
| 543 |
+
self._add_stats("warnings", [warning_report])
|
| 544 |
+
|
| 545 |
+
def pytest_plugin_registered(self, plugin: _PluggyPlugin) -> None:
|
| 546 |
+
if self.config.option.traceconfig:
|
| 547 |
+
msg = f"PLUGIN registered: {plugin}"
|
| 548 |
+
# XXX This event may happen during setup/teardown time
|
| 549 |
+
# which unfortunately captures our output here
|
| 550 |
+
# which garbles our output if we use self.write_line.
|
| 551 |
+
self.write_line(msg)
|
| 552 |
+
|
| 553 |
+
def pytest_deselected(self, items: Sequence[Item]) -> None:
|
| 554 |
+
self._add_stats("deselected", items)
|
| 555 |
+
|
| 556 |
+
def pytest_runtest_logstart(
|
| 557 |
+
self, nodeid: str, location: Tuple[str, Optional[int], str]
|
| 558 |
+
) -> None:
|
| 559 |
+
# Ensure that the path is printed before the
|
| 560 |
+
# 1st test of a module starts running.
|
| 561 |
+
if self.showlongtestinfo:
|
| 562 |
+
line = self._locationline(nodeid, *location)
|
| 563 |
+
self.write_ensure_prefix(line, "")
|
| 564 |
+
self.flush()
|
| 565 |
+
elif self.showfspath:
|
| 566 |
+
self.write_fspath_result(nodeid, "")
|
| 567 |
+
self.flush()
|
| 568 |
+
|
| 569 |
+
def pytest_runtest_logreport(self, report: TestReport) -> None:
|
| 570 |
+
self._tests_ran = True
|
| 571 |
+
rep = report
|
| 572 |
+
|
| 573 |
+
res = TestShortLogReport(
|
| 574 |
+
*self.config.hook.pytest_report_teststatus(report=rep, config=self.config)
|
| 575 |
+
)
|
| 576 |
+
category, letter, word = res.category, res.letter, res.word
|
| 577 |
+
if not isinstance(word, tuple):
|
| 578 |
+
markup = None
|
| 579 |
+
else:
|
| 580 |
+
word, markup = word
|
| 581 |
+
self._add_stats(category, [rep])
|
| 582 |
+
if not letter and not word:
|
| 583 |
+
# Probably passed setup/teardown.
|
| 584 |
+
return
|
| 585 |
+
running_xdist = hasattr(rep, "node")
|
| 586 |
+
if markup is None:
|
| 587 |
+
was_xfail = hasattr(report, "wasxfail")
|
| 588 |
+
if rep.passed and not was_xfail:
|
| 589 |
+
markup = {"green": True}
|
| 590 |
+
elif rep.passed and was_xfail:
|
| 591 |
+
markup = {"yellow": True}
|
| 592 |
+
elif rep.failed:
|
| 593 |
+
markup = {"red": True}
|
| 594 |
+
elif rep.skipped:
|
| 595 |
+
markup = {"yellow": True}
|
| 596 |
+
else:
|
| 597 |
+
markup = {}
|
| 598 |
+
if self.verbosity <= 0:
|
| 599 |
+
self._tw.write(letter, **markup)
|
| 600 |
+
else:
|
| 601 |
+
self._progress_nodeids_reported.add(rep.nodeid)
|
| 602 |
+
line = self._locationline(rep.nodeid, *rep.location)
|
| 603 |
+
if not running_xdist:
|
| 604 |
+
self.write_ensure_prefix(line, word, **markup)
|
| 605 |
+
if rep.skipped or hasattr(report, "wasxfail"):
|
| 606 |
+
reason = _get_raw_skip_reason(rep)
|
| 607 |
+
if self.config.option.verbose < 2:
|
| 608 |
+
available_width = (
|
| 609 |
+
(self._tw.fullwidth - self._tw.width_of_current_line)
|
| 610 |
+
- len(" [100%]")
|
| 611 |
+
- 1
|
| 612 |
+
)
|
| 613 |
+
formatted_reason = _format_trimmed(
|
| 614 |
+
" ({})", reason, available_width
|
| 615 |
+
)
|
| 616 |
+
else:
|
| 617 |
+
formatted_reason = f" ({reason})"
|
| 618 |
+
|
| 619 |
+
if reason and formatted_reason is not None:
|
| 620 |
+
self.wrap_write(formatted_reason)
|
| 621 |
+
if self._show_progress_info:
|
| 622 |
+
self._write_progress_information_filling_space()
|
| 623 |
+
else:
|
| 624 |
+
self.ensure_newline()
|
| 625 |
+
self._tw.write("[%s]" % rep.node.gateway.id)
|
| 626 |
+
if self._show_progress_info:
|
| 627 |
+
self._tw.write(
|
| 628 |
+
self._get_progress_information_message() + " ", cyan=True
|
| 629 |
+
)
|
| 630 |
+
else:
|
| 631 |
+
self._tw.write(" ")
|
| 632 |
+
self._tw.write(word, **markup)
|
| 633 |
+
self._tw.write(" " + line)
|
| 634 |
+
self.currentfspath = -2
|
| 635 |
+
self.flush()
|
| 636 |
+
|
| 637 |
+
@property
|
| 638 |
+
def _is_last_item(self) -> bool:
|
| 639 |
+
assert self._session is not None
|
| 640 |
+
return len(self._progress_nodeids_reported) == self._session.testscollected
|
| 641 |
+
|
| 642 |
+
def pytest_runtest_logfinish(self, nodeid: str) -> None:
|
| 643 |
+
assert self._session
|
| 644 |
+
if self.verbosity <= 0 and self._show_progress_info:
|
| 645 |
+
if self._show_progress_info == "count":
|
| 646 |
+
num_tests = self._session.testscollected
|
| 647 |
+
progress_length = len(f" [{num_tests}/{num_tests}]")
|
| 648 |
+
else:
|
| 649 |
+
progress_length = len(" [100%]")
|
| 650 |
+
|
| 651 |
+
self._progress_nodeids_reported.add(nodeid)
|
| 652 |
+
|
| 653 |
+
if self._is_last_item:
|
| 654 |
+
self._write_progress_information_filling_space()
|
| 655 |
+
else:
|
| 656 |
+
main_color, _ = self._get_main_color()
|
| 657 |
+
w = self._width_of_current_line
|
| 658 |
+
past_edge = w + progress_length + 1 >= self._screen_width
|
| 659 |
+
if past_edge:
|
| 660 |
+
msg = self._get_progress_information_message()
|
| 661 |
+
self._tw.write(msg + "\n", **{main_color: True})
|
| 662 |
+
|
| 663 |
+
def _get_progress_information_message(self) -> str:
|
| 664 |
+
assert self._session
|
| 665 |
+
collected = self._session.testscollected
|
| 666 |
+
if self._show_progress_info == "count":
|
| 667 |
+
if collected:
|
| 668 |
+
progress = self._progress_nodeids_reported
|
| 669 |
+
counter_format = f"{{:{len(str(collected))}d}}"
|
| 670 |
+
format_string = f" [{counter_format}/{{}}]"
|
| 671 |
+
return format_string.format(len(progress), collected)
|
| 672 |
+
return f" [ {collected} / {collected} ]"
|
| 673 |
+
else:
|
| 674 |
+
if collected:
|
| 675 |
+
return " [{:3d}%]".format(
|
| 676 |
+
len(self._progress_nodeids_reported) * 100 // collected
|
| 677 |
+
)
|
| 678 |
+
return " [100%]"
|
| 679 |
+
|
| 680 |
+
def _write_progress_information_filling_space(self) -> None:
|
| 681 |
+
color, _ = self._get_main_color()
|
| 682 |
+
msg = self._get_progress_information_message()
|
| 683 |
+
w = self._width_of_current_line
|
| 684 |
+
fill = self._tw.fullwidth - w - 1
|
| 685 |
+
self.write(msg.rjust(fill), flush=True, **{color: True})
|
| 686 |
+
|
| 687 |
+
@property
|
| 688 |
+
def _width_of_current_line(self) -> int:
|
| 689 |
+
"""Return the width of the current line."""
|
| 690 |
+
return self._tw.width_of_current_line
|
| 691 |
+
|
| 692 |
+
def pytest_collection(self) -> None:
|
| 693 |
+
if self.isatty:
|
| 694 |
+
if self.config.option.verbose >= 0:
|
| 695 |
+
self.write("collecting ... ", flush=True, bold=True)
|
| 696 |
+
self._collect_report_last_write = timing.time()
|
| 697 |
+
elif self.config.option.verbose >= 1:
|
| 698 |
+
self.write("collecting ... ", flush=True, bold=True)
|
| 699 |
+
|
| 700 |
+
def pytest_collectreport(self, report: CollectReport) -> None:
|
| 701 |
+
if report.failed:
|
| 702 |
+
self._add_stats("error", [report])
|
| 703 |
+
elif report.skipped:
|
| 704 |
+
self._add_stats("skipped", [report])
|
| 705 |
+
items = [x for x in report.result if isinstance(x, Item)]
|
| 706 |
+
self._numcollected += len(items)
|
| 707 |
+
if self.isatty:
|
| 708 |
+
self.report_collect()
|
| 709 |
+
|
| 710 |
+
def report_collect(self, final: bool = False) -> None:
|
| 711 |
+
if self.config.option.verbose < 0:
|
| 712 |
+
return
|
| 713 |
+
|
| 714 |
+
if not final:
|
| 715 |
+
# Only write "collecting" report every 0.5s.
|
| 716 |
+
t = timing.time()
|
| 717 |
+
if (
|
| 718 |
+
self._collect_report_last_write is not None
|
| 719 |
+
and self._collect_report_last_write > t - REPORT_COLLECTING_RESOLUTION
|
| 720 |
+
):
|
| 721 |
+
return
|
| 722 |
+
self._collect_report_last_write = t
|
| 723 |
+
|
| 724 |
+
errors = len(self.stats.get("error", []))
|
| 725 |
+
skipped = len(self.stats.get("skipped", []))
|
| 726 |
+
deselected = len(self.stats.get("deselected", []))
|
| 727 |
+
selected = self._numcollected - deselected
|
| 728 |
+
line = "collected " if final else "collecting "
|
| 729 |
+
line += (
|
| 730 |
+
str(self._numcollected) + " item" + ("" if self._numcollected == 1 else "s")
|
| 731 |
+
)
|
| 732 |
+
if errors:
|
| 733 |
+
line += " / %d error%s" % (errors, "s" if errors != 1 else "")
|
| 734 |
+
if deselected:
|
| 735 |
+
line += " / %d deselected" % deselected
|
| 736 |
+
if skipped:
|
| 737 |
+
line += " / %d skipped" % skipped
|
| 738 |
+
if self._numcollected > selected:
|
| 739 |
+
line += " / %d selected" % selected
|
| 740 |
+
if self.isatty:
|
| 741 |
+
self.rewrite(line, bold=True, erase=True)
|
| 742 |
+
if final:
|
| 743 |
+
self.write("\n")
|
| 744 |
+
else:
|
| 745 |
+
self.write_line(line)
|
| 746 |
+
|
| 747 |
+
@hookimpl(trylast=True)
|
| 748 |
+
def pytest_sessionstart(self, session: "Session") -> None:
|
| 749 |
+
self._session = session
|
| 750 |
+
self._sessionstarttime = timing.time()
|
| 751 |
+
if not self.showheader:
|
| 752 |
+
return
|
| 753 |
+
self.write_sep("=", "test session starts", bold=True)
|
| 754 |
+
verinfo = platform.python_version()
|
| 755 |
+
if not self.no_header:
|
| 756 |
+
msg = f"platform {sys.platform} -- Python {verinfo}"
|
| 757 |
+
pypy_version_info = getattr(sys, "pypy_version_info", None)
|
| 758 |
+
if pypy_version_info:
|
| 759 |
+
verinfo = ".".join(map(str, pypy_version_info[:3]))
|
| 760 |
+
msg += f"[pypy-{verinfo}-{pypy_version_info[3]}]"
|
| 761 |
+
msg += ", pytest-{}, pluggy-{}".format(
|
| 762 |
+
_pytest._version.version, pluggy.__version__
|
| 763 |
+
)
|
| 764 |
+
if (
|
| 765 |
+
self.verbosity > 0
|
| 766 |
+
or self.config.option.debug
|
| 767 |
+
or getattr(self.config.option, "pastebin", None)
|
| 768 |
+
):
|
| 769 |
+
msg += " -- " + str(sys.executable)
|
| 770 |
+
self.write_line(msg)
|
| 771 |
+
lines = self.config.hook.pytest_report_header(
|
| 772 |
+
config=self.config, start_path=self.startpath
|
| 773 |
+
)
|
| 774 |
+
self._write_report_lines_from_hooks(lines)
|
| 775 |
+
|
| 776 |
+
def _write_report_lines_from_hooks(
|
| 777 |
+
self, lines: Sequence[Union[str, Sequence[str]]]
|
| 778 |
+
) -> None:
|
| 779 |
+
for line_or_lines in reversed(lines):
|
| 780 |
+
if isinstance(line_or_lines, str):
|
| 781 |
+
self.write_line(line_or_lines)
|
| 782 |
+
else:
|
| 783 |
+
for line in line_or_lines:
|
| 784 |
+
self.write_line(line)
|
| 785 |
+
|
| 786 |
+
def pytest_report_header(self, config: Config) -> List[str]:
|
| 787 |
+
result = [f"rootdir: {config.rootpath}"]
|
| 788 |
+
|
| 789 |
+
if config.inipath:
|
| 790 |
+
result.append("configfile: " + bestrelpath(config.rootpath, config.inipath))
|
| 791 |
+
|
| 792 |
+
if config.args_source == Config.ArgsSource.TESTPATHS:
|
| 793 |
+
testpaths: List[str] = config.getini("testpaths")
|
| 794 |
+
result.append("testpaths: {}".format(", ".join(testpaths)))
|
| 795 |
+
|
| 796 |
+
plugininfo = config.pluginmanager.list_plugin_distinfo()
|
| 797 |
+
if plugininfo:
|
| 798 |
+
result.append("plugins: %s" % ", ".join(_plugin_nameversions(plugininfo)))
|
| 799 |
+
return result
|
| 800 |
+
|
| 801 |
+
def pytest_collection_finish(self, session: "Session") -> None:
|
| 802 |
+
self.report_collect(True)
|
| 803 |
+
|
| 804 |
+
lines = self.config.hook.pytest_report_collectionfinish(
|
| 805 |
+
config=self.config,
|
| 806 |
+
start_path=self.startpath,
|
| 807 |
+
items=session.items,
|
| 808 |
+
)
|
| 809 |
+
self._write_report_lines_from_hooks(lines)
|
| 810 |
+
|
| 811 |
+
if self.config.getoption("collectonly"):
|
| 812 |
+
if session.items:
|
| 813 |
+
if self.config.option.verbose > -1:
|
| 814 |
+
self._tw.line("")
|
| 815 |
+
self._printcollecteditems(session.items)
|
| 816 |
+
|
| 817 |
+
failed = self.stats.get("failed")
|
| 818 |
+
if failed:
|
| 819 |
+
self._tw.sep("!", "collection failures")
|
| 820 |
+
for rep in failed:
|
| 821 |
+
rep.toterminal(self._tw)
|
| 822 |
+
|
| 823 |
+
def _printcollecteditems(self, items: Sequence[Item]) -> None:
|
| 824 |
+
if self.config.option.verbose < 0:
|
| 825 |
+
if self.config.option.verbose < -1:
|
| 826 |
+
counts = Counter(item.nodeid.split("::", 1)[0] for item in items)
|
| 827 |
+
for name, count in sorted(counts.items()):
|
| 828 |
+
self._tw.line("%s: %d" % (name, count))
|
| 829 |
+
else:
|
| 830 |
+
for item in items:
|
| 831 |
+
self._tw.line(item.nodeid)
|
| 832 |
+
return
|
| 833 |
+
stack: List[Node] = []
|
| 834 |
+
indent = ""
|
| 835 |
+
for item in items:
|
| 836 |
+
needed_collectors = item.listchain()[1:] # strip root node
|
| 837 |
+
while stack:
|
| 838 |
+
if stack == needed_collectors[: len(stack)]:
|
| 839 |
+
break
|
| 840 |
+
stack.pop()
|
| 841 |
+
for col in needed_collectors[len(stack) :]:
|
| 842 |
+
stack.append(col)
|
| 843 |
+
indent = (len(stack) - 1) * " "
|
| 844 |
+
self._tw.line(f"{indent}{col}")
|
| 845 |
+
if self.config.option.verbose >= 1:
|
| 846 |
+
obj = getattr(col, "obj", None)
|
| 847 |
+
doc = inspect.getdoc(obj) if obj else None
|
| 848 |
+
if doc:
|
| 849 |
+
for line in doc.splitlines():
|
| 850 |
+
self._tw.line("{}{}".format(indent + " ", line))
|
| 851 |
+
|
| 852 |
+
@hookimpl(hookwrapper=True)
|
| 853 |
+
def pytest_sessionfinish(
|
| 854 |
+
self, session: "Session", exitstatus: Union[int, ExitCode]
|
| 855 |
+
):
|
| 856 |
+
outcome = yield
|
| 857 |
+
outcome.get_result()
|
| 858 |
+
self._tw.line("")
|
| 859 |
+
summary_exit_codes = (
|
| 860 |
+
ExitCode.OK,
|
| 861 |
+
ExitCode.TESTS_FAILED,
|
| 862 |
+
ExitCode.INTERRUPTED,
|
| 863 |
+
ExitCode.USAGE_ERROR,
|
| 864 |
+
ExitCode.NO_TESTS_COLLECTED,
|
| 865 |
+
)
|
| 866 |
+
if exitstatus in summary_exit_codes and not self.no_summary:
|
| 867 |
+
self.config.hook.pytest_terminal_summary(
|
| 868 |
+
terminalreporter=self, exitstatus=exitstatus, config=self.config
|
| 869 |
+
)
|
| 870 |
+
if session.shouldfail:
|
| 871 |
+
self.write_sep("!", str(session.shouldfail), red=True)
|
| 872 |
+
if exitstatus == ExitCode.INTERRUPTED:
|
| 873 |
+
self._report_keyboardinterrupt()
|
| 874 |
+
self._keyboardinterrupt_memo = None
|
| 875 |
+
elif session.shouldstop:
|
| 876 |
+
self.write_sep("!", str(session.shouldstop), red=True)
|
| 877 |
+
self.summary_stats()
|
| 878 |
+
|
| 879 |
+
@hookimpl(hookwrapper=True)
|
| 880 |
+
def pytest_terminal_summary(self) -> Generator[None, None, None]:
|
| 881 |
+
self.summary_errors()
|
| 882 |
+
self.summary_failures()
|
| 883 |
+
self.summary_warnings()
|
| 884 |
+
self.summary_passes()
|
| 885 |
+
yield
|
| 886 |
+
self.short_test_summary()
|
| 887 |
+
# Display any extra warnings from teardown here (if any).
|
| 888 |
+
self.summary_warnings()
|
| 889 |
+
|
| 890 |
+
def pytest_keyboard_interrupt(self, excinfo: ExceptionInfo[BaseException]) -> None:
|
| 891 |
+
self._keyboardinterrupt_memo = excinfo.getrepr(funcargs=True)
|
| 892 |
+
|
| 893 |
+
def pytest_unconfigure(self) -> None:
|
| 894 |
+
if self._keyboardinterrupt_memo is not None:
|
| 895 |
+
self._report_keyboardinterrupt()
|
| 896 |
+
|
| 897 |
+
def _report_keyboardinterrupt(self) -> None:
|
| 898 |
+
excrepr = self._keyboardinterrupt_memo
|
| 899 |
+
assert excrepr is not None
|
| 900 |
+
assert excrepr.reprcrash is not None
|
| 901 |
+
msg = excrepr.reprcrash.message
|
| 902 |
+
self.write_sep("!", msg)
|
| 903 |
+
if "KeyboardInterrupt" in msg:
|
| 904 |
+
if self.config.option.fulltrace:
|
| 905 |
+
excrepr.toterminal(self._tw)
|
| 906 |
+
else:
|
| 907 |
+
excrepr.reprcrash.toterminal(self._tw)
|
| 908 |
+
self._tw.line(
|
| 909 |
+
"(to show a full traceback on KeyboardInterrupt use --full-trace)",
|
| 910 |
+
yellow=True,
|
| 911 |
+
)
|
| 912 |
+
|
| 913 |
+
def _locationline(
|
| 914 |
+
self, nodeid: str, fspath: str, lineno: Optional[int], domain: str
|
| 915 |
+
) -> str:
|
| 916 |
+
def mkrel(nodeid: str) -> str:
|
| 917 |
+
line = self.config.cwd_relative_nodeid(nodeid)
|
| 918 |
+
if domain and line.endswith(domain):
|
| 919 |
+
line = line[: -len(domain)]
|
| 920 |
+
values = domain.split("[")
|
| 921 |
+
values[0] = values[0].replace(".", "::") # don't replace '.' in params
|
| 922 |
+
line += "[".join(values)
|
| 923 |
+
return line
|
| 924 |
+
|
| 925 |
+
# collect_fspath comes from testid which has a "/"-normalized path.
|
| 926 |
+
if fspath:
|
| 927 |
+
res = mkrel(nodeid)
|
| 928 |
+
if self.verbosity >= 2 and nodeid.split("::")[0] != fspath.replace(
|
| 929 |
+
"\\", nodes.SEP
|
| 930 |
+
):
|
| 931 |
+
res += " <- " + bestrelpath(self.startpath, Path(fspath))
|
| 932 |
+
else:
|
| 933 |
+
res = "[location]"
|
| 934 |
+
return res + " "
|
| 935 |
+
|
| 936 |
+
def _getfailureheadline(self, rep):
|
| 937 |
+
head_line = rep.head_line
|
| 938 |
+
if head_line:
|
| 939 |
+
return head_line
|
| 940 |
+
return "test session" # XXX?
|
| 941 |
+
|
| 942 |
+
def _getcrashline(self, rep):
|
| 943 |
+
try:
|
| 944 |
+
return str(rep.longrepr.reprcrash)
|
| 945 |
+
except AttributeError:
|
| 946 |
+
try:
|
| 947 |
+
return str(rep.longrepr)[:50]
|
| 948 |
+
except AttributeError:
|
| 949 |
+
return ""
|
| 950 |
+
|
| 951 |
+
#
|
| 952 |
+
# Summaries for sessionfinish.
|
| 953 |
+
#
|
| 954 |
+
def getreports(self, name: str):
|
| 955 |
+
return [x for x in self.stats.get(name, ()) if not hasattr(x, "_pdbshown")]
|
| 956 |
+
|
| 957 |
+
def summary_warnings(self) -> None:
|
| 958 |
+
if self.hasopt("w"):
|
| 959 |
+
all_warnings: Optional[List[WarningReport]] = self.stats.get("warnings")
|
| 960 |
+
if not all_warnings:
|
| 961 |
+
return
|
| 962 |
+
|
| 963 |
+
final = self._already_displayed_warnings is not None
|
| 964 |
+
if final:
|
| 965 |
+
warning_reports = all_warnings[self._already_displayed_warnings :]
|
| 966 |
+
else:
|
| 967 |
+
warning_reports = all_warnings
|
| 968 |
+
self._already_displayed_warnings = len(warning_reports)
|
| 969 |
+
if not warning_reports:
|
| 970 |
+
return
|
| 971 |
+
|
| 972 |
+
reports_grouped_by_message: Dict[str, List[WarningReport]] = {}
|
| 973 |
+
for wr in warning_reports:
|
| 974 |
+
reports_grouped_by_message.setdefault(wr.message, []).append(wr)
|
| 975 |
+
|
| 976 |
+
def collapsed_location_report(reports: List[WarningReport]) -> str:
|
| 977 |
+
locations = []
|
| 978 |
+
for w in reports:
|
| 979 |
+
location = w.get_location(self.config)
|
| 980 |
+
if location:
|
| 981 |
+
locations.append(location)
|
| 982 |
+
|
| 983 |
+
if len(locations) < 10:
|
| 984 |
+
return "\n".join(map(str, locations))
|
| 985 |
+
|
| 986 |
+
counts_by_filename = Counter(
|
| 987 |
+
str(loc).split("::", 1)[0] for loc in locations
|
| 988 |
+
)
|
| 989 |
+
return "\n".join(
|
| 990 |
+
"{}: {} warning{}".format(k, v, "s" if v > 1 else "")
|
| 991 |
+
for k, v in counts_by_filename.items()
|
| 992 |
+
)
|
| 993 |
+
|
| 994 |
+
title = "warnings summary (final)" if final else "warnings summary"
|
| 995 |
+
self.write_sep("=", title, yellow=True, bold=False)
|
| 996 |
+
for message, message_reports in reports_grouped_by_message.items():
|
| 997 |
+
maybe_location = collapsed_location_report(message_reports)
|
| 998 |
+
if maybe_location:
|
| 999 |
+
self._tw.line(maybe_location)
|
| 1000 |
+
lines = message.splitlines()
|
| 1001 |
+
indented = "\n".join(" " + x for x in lines)
|
| 1002 |
+
message = indented.rstrip()
|
| 1003 |
+
else:
|
| 1004 |
+
message = message.rstrip()
|
| 1005 |
+
self._tw.line(message)
|
| 1006 |
+
self._tw.line()
|
| 1007 |
+
self._tw.line(
|
| 1008 |
+
"-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html"
|
| 1009 |
+
)
|
| 1010 |
+
|
| 1011 |
+
def summary_passes(self) -> None:
|
| 1012 |
+
if self.config.option.tbstyle != "no":
|
| 1013 |
+
if self.hasopt("P"):
|
| 1014 |
+
reports: List[TestReport] = self.getreports("passed")
|
| 1015 |
+
if not reports:
|
| 1016 |
+
return
|
| 1017 |
+
self.write_sep("=", "PASSES")
|
| 1018 |
+
for rep in reports:
|
| 1019 |
+
if rep.sections:
|
| 1020 |
+
msg = self._getfailureheadline(rep)
|
| 1021 |
+
self.write_sep("_", msg, green=True, bold=True)
|
| 1022 |
+
self._outrep_summary(rep)
|
| 1023 |
+
self._handle_teardown_sections(rep.nodeid)
|
| 1024 |
+
|
| 1025 |
+
def _get_teardown_reports(self, nodeid: str) -> List[TestReport]:
|
| 1026 |
+
reports = self.getreports("")
|
| 1027 |
+
return [
|
| 1028 |
+
report
|
| 1029 |
+
for report in reports
|
| 1030 |
+
if report.when == "teardown" and report.nodeid == nodeid
|
| 1031 |
+
]
|
| 1032 |
+
|
| 1033 |
+
def _handle_teardown_sections(self, nodeid: str) -> None:
|
| 1034 |
+
for report in self._get_teardown_reports(nodeid):
|
| 1035 |
+
self.print_teardown_sections(report)
|
| 1036 |
+
|
| 1037 |
+
def print_teardown_sections(self, rep: TestReport) -> None:
|
| 1038 |
+
showcapture = self.config.option.showcapture
|
| 1039 |
+
if showcapture == "no":
|
| 1040 |
+
return
|
| 1041 |
+
for secname, content in rep.sections:
|
| 1042 |
+
if showcapture != "all" and showcapture not in secname:
|
| 1043 |
+
continue
|
| 1044 |
+
if "teardown" in secname:
|
| 1045 |
+
self._tw.sep("-", secname)
|
| 1046 |
+
if content[-1:] == "\n":
|
| 1047 |
+
content = content[:-1]
|
| 1048 |
+
self._tw.line(content)
|
| 1049 |
+
|
| 1050 |
+
def summary_failures(self) -> None:
|
| 1051 |
+
if self.config.option.tbstyle != "no":
|
| 1052 |
+
reports: List[BaseReport] = self.getreports("failed")
|
| 1053 |
+
if not reports:
|
| 1054 |
+
return
|
| 1055 |
+
self.write_sep("=", "FAILURES")
|
| 1056 |
+
if self.config.option.tbstyle == "line":
|
| 1057 |
+
for rep in reports:
|
| 1058 |
+
line = self._getcrashline(rep)
|
| 1059 |
+
self.write_line(line)
|
| 1060 |
+
else:
|
| 1061 |
+
for rep in reports:
|
| 1062 |
+
msg = self._getfailureheadline(rep)
|
| 1063 |
+
self.write_sep("_", msg, red=True, bold=True)
|
| 1064 |
+
self._outrep_summary(rep)
|
| 1065 |
+
self._handle_teardown_sections(rep.nodeid)
|
| 1066 |
+
|
| 1067 |
+
def summary_errors(self) -> None:
|
| 1068 |
+
if self.config.option.tbstyle != "no":
|
| 1069 |
+
reports: List[BaseReport] = self.getreports("error")
|
| 1070 |
+
if not reports:
|
| 1071 |
+
return
|
| 1072 |
+
self.write_sep("=", "ERRORS")
|
| 1073 |
+
for rep in self.stats["error"]:
|
| 1074 |
+
msg = self._getfailureheadline(rep)
|
| 1075 |
+
if rep.when == "collect":
|
| 1076 |
+
msg = "ERROR collecting " + msg
|
| 1077 |
+
else:
|
| 1078 |
+
msg = f"ERROR at {rep.when} of {msg}"
|
| 1079 |
+
self.write_sep("_", msg, red=True, bold=True)
|
| 1080 |
+
self._outrep_summary(rep)
|
| 1081 |
+
|
| 1082 |
+
def _outrep_summary(self, rep: BaseReport) -> None:
|
| 1083 |
+
rep.toterminal(self._tw)
|
| 1084 |
+
showcapture = self.config.option.showcapture
|
| 1085 |
+
if showcapture == "no":
|
| 1086 |
+
return
|
| 1087 |
+
for secname, content in rep.sections:
|
| 1088 |
+
if showcapture != "all" and showcapture not in secname:
|
| 1089 |
+
continue
|
| 1090 |
+
self._tw.sep("-", secname)
|
| 1091 |
+
if content[-1:] == "\n":
|
| 1092 |
+
content = content[:-1]
|
| 1093 |
+
self._tw.line(content)
|
| 1094 |
+
|
| 1095 |
+
def summary_stats(self) -> None:
|
| 1096 |
+
if self.verbosity < -1:
|
| 1097 |
+
return
|
| 1098 |
+
|
| 1099 |
+
session_duration = timing.time() - self._sessionstarttime
|
| 1100 |
+
(parts, main_color) = self.build_summary_stats_line()
|
| 1101 |
+
line_parts = []
|
| 1102 |
+
|
| 1103 |
+
display_sep = self.verbosity >= 0
|
| 1104 |
+
if display_sep:
|
| 1105 |
+
fullwidth = self._tw.fullwidth
|
| 1106 |
+
for text, markup in parts:
|
| 1107 |
+
with_markup = self._tw.markup(text, **markup)
|
| 1108 |
+
if display_sep:
|
| 1109 |
+
fullwidth += len(with_markup) - len(text)
|
| 1110 |
+
line_parts.append(with_markup)
|
| 1111 |
+
msg = ", ".join(line_parts)
|
| 1112 |
+
|
| 1113 |
+
main_markup = {main_color: True}
|
| 1114 |
+
duration = f" in {format_session_duration(session_duration)}"
|
| 1115 |
+
duration_with_markup = self._tw.markup(duration, **main_markup)
|
| 1116 |
+
if display_sep:
|
| 1117 |
+
fullwidth += len(duration_with_markup) - len(duration)
|
| 1118 |
+
msg += duration_with_markup
|
| 1119 |
+
|
| 1120 |
+
if display_sep:
|
| 1121 |
+
markup_for_end_sep = self._tw.markup("", **main_markup)
|
| 1122 |
+
if markup_for_end_sep.endswith("\x1b[0m"):
|
| 1123 |
+
markup_for_end_sep = markup_for_end_sep[:-4]
|
| 1124 |
+
fullwidth += len(markup_for_end_sep)
|
| 1125 |
+
msg += markup_for_end_sep
|
| 1126 |
+
|
| 1127 |
+
if display_sep:
|
| 1128 |
+
self.write_sep("=", msg, fullwidth=fullwidth, **main_markup)
|
| 1129 |
+
else:
|
| 1130 |
+
self.write_line(msg, **main_markup)
|
| 1131 |
+
|
| 1132 |
+
def short_test_summary(self) -> None:
|
| 1133 |
+
if not self.reportchars:
|
| 1134 |
+
return
|
| 1135 |
+
|
| 1136 |
+
def show_simple(lines: List[str], *, stat: str) -> None:
|
| 1137 |
+
failed = self.stats.get(stat, [])
|
| 1138 |
+
if not failed:
|
| 1139 |
+
return
|
| 1140 |
+
config = self.config
|
| 1141 |
+
for rep in failed:
|
| 1142 |
+
color = _color_for_type.get(stat, _color_for_type_default)
|
| 1143 |
+
line = _get_line_with_reprcrash_message(
|
| 1144 |
+
config, rep, self._tw, {color: True}
|
| 1145 |
+
)
|
| 1146 |
+
lines.append(line)
|
| 1147 |
+
|
| 1148 |
+
def show_xfailed(lines: List[str]) -> None:
|
| 1149 |
+
xfailed = self.stats.get("xfailed", [])
|
| 1150 |
+
for rep in xfailed:
|
| 1151 |
+
verbose_word = rep._get_verbose_word(self.config)
|
| 1152 |
+
markup_word = self._tw.markup(
|
| 1153 |
+
verbose_word, **{_color_for_type["warnings"]: True}
|
| 1154 |
+
)
|
| 1155 |
+
nodeid = _get_node_id_with_markup(self._tw, self.config, rep)
|
| 1156 |
+
line = f"{markup_word} {nodeid}"
|
| 1157 |
+
reason = rep.wasxfail
|
| 1158 |
+
if reason:
|
| 1159 |
+
line += " - " + str(reason)
|
| 1160 |
+
|
| 1161 |
+
lines.append(line)
|
| 1162 |
+
|
| 1163 |
+
def show_xpassed(lines: List[str]) -> None:
|
| 1164 |
+
xpassed = self.stats.get("xpassed", [])
|
| 1165 |
+
for rep in xpassed:
|
| 1166 |
+
verbose_word = rep._get_verbose_word(self.config)
|
| 1167 |
+
markup_word = self._tw.markup(
|
| 1168 |
+
verbose_word, **{_color_for_type["warnings"]: True}
|
| 1169 |
+
)
|
| 1170 |
+
nodeid = _get_node_id_with_markup(self._tw, self.config, rep)
|
| 1171 |
+
reason = rep.wasxfail
|
| 1172 |
+
lines.append(f"{markup_word} {nodeid} {reason}")
|
| 1173 |
+
|
| 1174 |
+
def show_skipped(lines: List[str]) -> None:
|
| 1175 |
+
skipped: List[CollectReport] = self.stats.get("skipped", [])
|
| 1176 |
+
fskips = _folded_skips(self.startpath, skipped) if skipped else []
|
| 1177 |
+
if not fskips:
|
| 1178 |
+
return
|
| 1179 |
+
verbose_word = skipped[0]._get_verbose_word(self.config)
|
| 1180 |
+
markup_word = self._tw.markup(
|
| 1181 |
+
verbose_word, **{_color_for_type["warnings"]: True}
|
| 1182 |
+
)
|
| 1183 |
+
prefix = "Skipped: "
|
| 1184 |
+
for num, fspath, lineno, reason in fskips:
|
| 1185 |
+
if reason.startswith(prefix):
|
| 1186 |
+
reason = reason[len(prefix) :]
|
| 1187 |
+
if lineno is not None:
|
| 1188 |
+
lines.append(
|
| 1189 |
+
"%s [%d] %s:%d: %s" % (markup_word, num, fspath, lineno, reason)
|
| 1190 |
+
)
|
| 1191 |
+
else:
|
| 1192 |
+
lines.append("%s [%d] %s: %s" % (markup_word, num, fspath, reason))
|
| 1193 |
+
|
| 1194 |
+
REPORTCHAR_ACTIONS: Mapping[str, Callable[[List[str]], None]] = {
|
| 1195 |
+
"x": show_xfailed,
|
| 1196 |
+
"X": show_xpassed,
|
| 1197 |
+
"f": partial(show_simple, stat="failed"),
|
| 1198 |
+
"s": show_skipped,
|
| 1199 |
+
"p": partial(show_simple, stat="passed"),
|
| 1200 |
+
"E": partial(show_simple, stat="error"),
|
| 1201 |
+
}
|
| 1202 |
+
|
| 1203 |
+
lines: List[str] = []
|
| 1204 |
+
for char in self.reportchars:
|
| 1205 |
+
action = REPORTCHAR_ACTIONS.get(char)
|
| 1206 |
+
if action: # skipping e.g. "P" (passed with output) here.
|
| 1207 |
+
action(lines)
|
| 1208 |
+
|
| 1209 |
+
if lines:
|
| 1210 |
+
self.write_sep("=", "short test summary info", cyan=True, bold=True)
|
| 1211 |
+
for line in lines:
|
| 1212 |
+
self.write_line(line)
|
| 1213 |
+
|
| 1214 |
+
def _get_main_color(self) -> Tuple[str, List[str]]:
|
| 1215 |
+
if self._main_color is None or self._known_types is None or self._is_last_item:
|
| 1216 |
+
self._set_main_color()
|
| 1217 |
+
assert self._main_color
|
| 1218 |
+
assert self._known_types
|
| 1219 |
+
return self._main_color, self._known_types
|
| 1220 |
+
|
| 1221 |
+
def _determine_main_color(self, unknown_type_seen: bool) -> str:
|
| 1222 |
+
stats = self.stats
|
| 1223 |
+
if "failed" in stats or "error" in stats:
|
| 1224 |
+
main_color = "red"
|
| 1225 |
+
elif "warnings" in stats or "xpassed" in stats or unknown_type_seen:
|
| 1226 |
+
main_color = "yellow"
|
| 1227 |
+
elif "passed" in stats or not self._is_last_item:
|
| 1228 |
+
main_color = "green"
|
| 1229 |
+
else:
|
| 1230 |
+
main_color = "yellow"
|
| 1231 |
+
return main_color
|
| 1232 |
+
|
| 1233 |
+
def _set_main_color(self) -> None:
|
| 1234 |
+
unknown_types: List[str] = []
|
| 1235 |
+
for found_type in self.stats.keys():
|
| 1236 |
+
if found_type: # setup/teardown reports have an empty key, ignore them
|
| 1237 |
+
if found_type not in KNOWN_TYPES and found_type not in unknown_types:
|
| 1238 |
+
unknown_types.append(found_type)
|
| 1239 |
+
self._known_types = list(KNOWN_TYPES) + unknown_types
|
| 1240 |
+
self._main_color = self._determine_main_color(bool(unknown_types))
|
| 1241 |
+
|
| 1242 |
+
def build_summary_stats_line(self) -> Tuple[List[Tuple[str, Dict[str, bool]]], str]:
|
| 1243 |
+
"""
|
| 1244 |
+
Build the parts used in the last summary stats line.
|
| 1245 |
+
|
| 1246 |
+
The summary stats line is the line shown at the end, "=== 12 passed, 2 errors in Xs===".
|
| 1247 |
+
|
| 1248 |
+
This function builds a list of the "parts" that make up for the text in that line, in
|
| 1249 |
+
the example above it would be:
|
| 1250 |
+
|
| 1251 |
+
[
|
| 1252 |
+
("12 passed", {"green": True}),
|
| 1253 |
+
("2 errors", {"red": True}
|
| 1254 |
+
]
|
| 1255 |
+
|
| 1256 |
+
That last dict for each line is a "markup dictionary", used by TerminalWriter to
|
| 1257 |
+
color output.
|
| 1258 |
+
|
| 1259 |
+
The final color of the line is also determined by this function, and is the second
|
| 1260 |
+
element of the returned tuple.
|
| 1261 |
+
"""
|
| 1262 |
+
if self.config.getoption("collectonly"):
|
| 1263 |
+
return self._build_collect_only_summary_stats_line()
|
| 1264 |
+
else:
|
| 1265 |
+
return self._build_normal_summary_stats_line()
|
| 1266 |
+
|
| 1267 |
+
def _get_reports_to_display(self, key: str) -> List[Any]:
|
| 1268 |
+
"""Get test/collection reports for the given status key, such as `passed` or `error`."""
|
| 1269 |
+
reports = self.stats.get(key, [])
|
| 1270 |
+
return [x for x in reports if getattr(x, "count_towards_summary", True)]
|
| 1271 |
+
|
| 1272 |
+
def _build_normal_summary_stats_line(
|
| 1273 |
+
self,
|
| 1274 |
+
) -> Tuple[List[Tuple[str, Dict[str, bool]]], str]:
|
| 1275 |
+
main_color, known_types = self._get_main_color()
|
| 1276 |
+
parts = []
|
| 1277 |
+
|
| 1278 |
+
for key in known_types:
|
| 1279 |
+
reports = self._get_reports_to_display(key)
|
| 1280 |
+
if reports:
|
| 1281 |
+
count = len(reports)
|
| 1282 |
+
color = _color_for_type.get(key, _color_for_type_default)
|
| 1283 |
+
markup = {color: True, "bold": color == main_color}
|
| 1284 |
+
parts.append(("%d %s" % pluralize(count, key), markup))
|
| 1285 |
+
|
| 1286 |
+
if not parts:
|
| 1287 |
+
parts = [("no tests ran", {_color_for_type_default: True})]
|
| 1288 |
+
|
| 1289 |
+
return parts, main_color
|
| 1290 |
+
|
| 1291 |
+
def _build_collect_only_summary_stats_line(
|
| 1292 |
+
self,
|
| 1293 |
+
) -> Tuple[List[Tuple[str, Dict[str, bool]]], str]:
|
| 1294 |
+
deselected = len(self._get_reports_to_display("deselected"))
|
| 1295 |
+
errors = len(self._get_reports_to_display("error"))
|
| 1296 |
+
|
| 1297 |
+
if self._numcollected == 0:
|
| 1298 |
+
parts = [("no tests collected", {"yellow": True})]
|
| 1299 |
+
main_color = "yellow"
|
| 1300 |
+
|
| 1301 |
+
elif deselected == 0:
|
| 1302 |
+
main_color = "green"
|
| 1303 |
+
collected_output = "%d %s collected" % pluralize(self._numcollected, "test")
|
| 1304 |
+
parts = [(collected_output, {main_color: True})]
|
| 1305 |
+
else:
|
| 1306 |
+
all_tests_were_deselected = self._numcollected == deselected
|
| 1307 |
+
if all_tests_were_deselected:
|
| 1308 |
+
main_color = "yellow"
|
| 1309 |
+
collected_output = f"no tests collected ({deselected} deselected)"
|
| 1310 |
+
else:
|
| 1311 |
+
main_color = "green"
|
| 1312 |
+
selected = self._numcollected - deselected
|
| 1313 |
+
collected_output = f"{selected}/{self._numcollected} tests collected ({deselected} deselected)"
|
| 1314 |
+
|
| 1315 |
+
parts = [(collected_output, {main_color: True})]
|
| 1316 |
+
|
| 1317 |
+
if errors:
|
| 1318 |
+
main_color = _color_for_type["error"]
|
| 1319 |
+
parts += [("%d %s" % pluralize(errors, "error"), {main_color: True})]
|
| 1320 |
+
|
| 1321 |
+
return parts, main_color
|
| 1322 |
+
|
| 1323 |
+
|
| 1324 |
+
def _get_node_id_with_markup(tw: TerminalWriter, config: Config, rep: BaseReport):
|
| 1325 |
+
nodeid = config.cwd_relative_nodeid(rep.nodeid)
|
| 1326 |
+
path, *parts = nodeid.split("::")
|
| 1327 |
+
if parts:
|
| 1328 |
+
parts_markup = tw.markup("::".join(parts), bold=True)
|
| 1329 |
+
return path + "::" + parts_markup
|
| 1330 |
+
else:
|
| 1331 |
+
return path
|
| 1332 |
+
|
| 1333 |
+
|
| 1334 |
+
def _format_trimmed(format: str, msg: str, available_width: int) -> Optional[str]:
|
| 1335 |
+
"""Format msg into format, ellipsizing it if doesn't fit in available_width.
|
| 1336 |
+
|
| 1337 |
+
Returns None if even the ellipsis can't fit.
|
| 1338 |
+
"""
|
| 1339 |
+
# Only use the first line.
|
| 1340 |
+
i = msg.find("\n")
|
| 1341 |
+
if i != -1:
|
| 1342 |
+
msg = msg[:i]
|
| 1343 |
+
|
| 1344 |
+
ellipsis = "..."
|
| 1345 |
+
format_width = wcswidth(format.format(""))
|
| 1346 |
+
if format_width + len(ellipsis) > available_width:
|
| 1347 |
+
return None
|
| 1348 |
+
|
| 1349 |
+
if format_width + wcswidth(msg) > available_width:
|
| 1350 |
+
available_width -= len(ellipsis)
|
| 1351 |
+
msg = msg[:available_width]
|
| 1352 |
+
while format_width + wcswidth(msg) > available_width:
|
| 1353 |
+
msg = msg[:-1]
|
| 1354 |
+
msg += ellipsis
|
| 1355 |
+
|
| 1356 |
+
return format.format(msg)
|
| 1357 |
+
|
| 1358 |
+
|
| 1359 |
+
def _get_line_with_reprcrash_message(
|
| 1360 |
+
config: Config, rep: BaseReport, tw: TerminalWriter, word_markup: Dict[str, bool]
|
| 1361 |
+
) -> str:
|
| 1362 |
+
"""Get summary line for a report, trying to add reprcrash message."""
|
| 1363 |
+
verbose_word = rep._get_verbose_word(config)
|
| 1364 |
+
word = tw.markup(verbose_word, **word_markup)
|
| 1365 |
+
node = _get_node_id_with_markup(tw, config, rep)
|
| 1366 |
+
|
| 1367 |
+
line = f"{word} {node}"
|
| 1368 |
+
line_width = wcswidth(line)
|
| 1369 |
+
|
| 1370 |
+
try:
|
| 1371 |
+
# Type ignored intentionally -- possible AttributeError expected.
|
| 1372 |
+
msg = rep.longrepr.reprcrash.message # type: ignore[union-attr]
|
| 1373 |
+
except AttributeError:
|
| 1374 |
+
pass
|
| 1375 |
+
else:
|
| 1376 |
+
if not running_on_ci():
|
| 1377 |
+
available_width = tw.fullwidth - line_width
|
| 1378 |
+
msg = _format_trimmed(" - {}", msg, available_width)
|
| 1379 |
+
else:
|
| 1380 |
+
msg = f" - {msg}"
|
| 1381 |
+
if msg is not None:
|
| 1382 |
+
line += msg
|
| 1383 |
+
|
| 1384 |
+
return line
|
| 1385 |
+
|
| 1386 |
+
|
| 1387 |
+
def _folded_skips(
|
| 1388 |
+
startpath: Path,
|
| 1389 |
+
skipped: Sequence[CollectReport],
|
| 1390 |
+
) -> List[Tuple[int, str, Optional[int], str]]:
|
| 1391 |
+
d: Dict[Tuple[str, Optional[int], str], List[CollectReport]] = {}
|
| 1392 |
+
for event in skipped:
|
| 1393 |
+
assert event.longrepr is not None
|
| 1394 |
+
assert isinstance(event.longrepr, tuple), (event, event.longrepr)
|
| 1395 |
+
assert len(event.longrepr) == 3, (event, event.longrepr)
|
| 1396 |
+
fspath, lineno, reason = event.longrepr
|
| 1397 |
+
# For consistency, report all fspaths in relative form.
|
| 1398 |
+
fspath = bestrelpath(startpath, Path(fspath))
|
| 1399 |
+
keywords = getattr(event, "keywords", {})
|
| 1400 |
+
# Folding reports with global pytestmark variable.
|
| 1401 |
+
# This is a workaround, because for now we cannot identify the scope of a skip marker
|
| 1402 |
+
# TODO: Revisit after marks scope would be fixed.
|
| 1403 |
+
if (
|
| 1404 |
+
event.when == "setup"
|
| 1405 |
+
and "skip" in keywords
|
| 1406 |
+
and "pytestmark" not in keywords
|
| 1407 |
+
):
|
| 1408 |
+
key: Tuple[str, Optional[int], str] = (fspath, None, reason)
|
| 1409 |
+
else:
|
| 1410 |
+
key = (fspath, lineno, reason)
|
| 1411 |
+
d.setdefault(key, []).append(event)
|
| 1412 |
+
values: List[Tuple[int, str, Optional[int], str]] = []
|
| 1413 |
+
for key, events in d.items():
|
| 1414 |
+
values.append((len(events), *key))
|
| 1415 |
+
return values
|
| 1416 |
+
|
| 1417 |
+
|
| 1418 |
+
_color_for_type = {
|
| 1419 |
+
"failed": "red",
|
| 1420 |
+
"error": "red",
|
| 1421 |
+
"warnings": "yellow",
|
| 1422 |
+
"passed": "green",
|
| 1423 |
+
}
|
| 1424 |
+
_color_for_type_default = "yellow"
|
| 1425 |
+
|
| 1426 |
+
|
| 1427 |
+
def pluralize(count: int, noun: str) -> Tuple[int, str]:
|
| 1428 |
+
# No need to pluralize words such as `failed` or `passed`.
|
| 1429 |
+
if noun not in ["error", "warnings", "test"]:
|
| 1430 |
+
return count, noun
|
| 1431 |
+
|
| 1432 |
+
# The `warnings` key is plural. To avoid API breakage, we keep it that way but
|
| 1433 |
+
# set it to singular here so we can determine plurality in the same way as we do
|
| 1434 |
+
# for `error`.
|
| 1435 |
+
noun = noun.replace("warnings", "warning")
|
| 1436 |
+
|
| 1437 |
+
return count, noun + "s" if count != 1 else noun
|
| 1438 |
+
|
| 1439 |
+
|
| 1440 |
+
def _plugin_nameversions(plugininfo) -> List[str]:
|
| 1441 |
+
values: List[str] = []
|
| 1442 |
+
for plugin, dist in plugininfo:
|
| 1443 |
+
# Gets us name and version!
|
| 1444 |
+
name = "{dist.project_name}-{dist.version}".format(dist=dist)
|
| 1445 |
+
# Questionable convenience, but it keeps things short.
|
| 1446 |
+
if name.startswith("pytest-"):
|
| 1447 |
+
name = name[7:]
|
| 1448 |
+
# We decided to print python package names they can have more than one plugin.
|
| 1449 |
+
if name not in values:
|
| 1450 |
+
values.append(name)
|
| 1451 |
+
return values
|
| 1452 |
+
|
| 1453 |
+
|
| 1454 |
+
def format_session_duration(seconds: float) -> str:
|
| 1455 |
+
"""Format the given seconds in a human readable manner to show in the final summary."""
|
| 1456 |
+
if seconds < 60:
|
| 1457 |
+
return f"{seconds:.2f}s"
|
| 1458 |
+
else:
|
| 1459 |
+
dt = datetime.timedelta(seconds=int(seconds))
|
| 1460 |
+
return f"{seconds:.2f}s ({dt})"
|
| 1461 |
+
|
| 1462 |
+
|
| 1463 |
+
def _get_raw_skip_reason(report: TestReport) -> str:
|
| 1464 |
+
"""Get the reason string of a skip/xfail/xpass test report.
|
| 1465 |
+
|
| 1466 |
+
The string is just the part given by the user.
|
| 1467 |
+
"""
|
| 1468 |
+
if hasattr(report, "wasxfail"):
|
| 1469 |
+
reason = cast(str, report.wasxfail)
|
| 1470 |
+
if reason.startswith("reason: "):
|
| 1471 |
+
reason = reason[len("reason: ") :]
|
| 1472 |
+
return reason
|
| 1473 |
+
else:
|
| 1474 |
+
assert report.skipped
|
| 1475 |
+
assert isinstance(report.longrepr, tuple)
|
| 1476 |
+
_, _, reason = report.longrepr
|
| 1477 |
+
if reason.startswith("Skipped: "):
|
| 1478 |
+
reason = reason[len("Skipped: ") :]
|
| 1479 |
+
elif reason == "Skipped":
|
| 1480 |
+
reason = ""
|
| 1481 |
+
return reason
|
wemm/lib/python3.10/site-packages/_pytest/timing.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Indirection for time functions.
|
| 2 |
+
|
| 3 |
+
We intentionally grab some "time" functions internally to avoid tests mocking "time" to affect
|
| 4 |
+
pytest runtime information (issue #185).
|
| 5 |
+
|
| 6 |
+
Fixture "mock_timing" also interacts with this module for pytest's own tests.
|
| 7 |
+
"""
|
| 8 |
+
from time import perf_counter
|
| 9 |
+
from time import sleep
|
| 10 |
+
from time import time
|
| 11 |
+
|
| 12 |
+
__all__ = ["perf_counter", "sleep", "time"]
|
wemm/lib/python3.10/site-packages/_pytest/tmpdir.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Support for providing temporary directories to test functions."""
|
| 2 |
+
import dataclasses
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
import tempfile
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from shutil import rmtree
|
| 8 |
+
from typing import Any
|
| 9 |
+
from typing import Dict
|
| 10 |
+
from typing import Generator
|
| 11 |
+
from typing import Optional
|
| 12 |
+
from typing import TYPE_CHECKING
|
| 13 |
+
from typing import Union
|
| 14 |
+
|
| 15 |
+
from _pytest.nodes import Item
|
| 16 |
+
from _pytest.reports import CollectReport
|
| 17 |
+
from _pytest.stash import StashKey
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from typing_extensions import Literal
|
| 21 |
+
|
| 22 |
+
RetentionType = Literal["all", "failed", "none"]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
from _pytest.config.argparsing import Parser
|
| 26 |
+
|
| 27 |
+
from .pathlib import LOCK_TIMEOUT
|
| 28 |
+
from .pathlib import make_numbered_dir
|
| 29 |
+
from .pathlib import make_numbered_dir_with_cleanup
|
| 30 |
+
from .pathlib import rm_rf
|
| 31 |
+
from .pathlib import cleanup_dead_symlinks
|
| 32 |
+
from _pytest.compat import final, get_user_id
|
| 33 |
+
from _pytest.config import Config
|
| 34 |
+
from _pytest.config import ExitCode
|
| 35 |
+
from _pytest.config import hookimpl
|
| 36 |
+
from _pytest.deprecated import check_ispytest
|
| 37 |
+
from _pytest.fixtures import fixture
|
| 38 |
+
from _pytest.fixtures import FixtureRequest
|
| 39 |
+
from _pytest.monkeypatch import MonkeyPatch
|
| 40 |
+
|
| 41 |
+
tmppath_result_key = StashKey[Dict[str, bool]]()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@final
|
| 45 |
+
@dataclasses.dataclass
|
| 46 |
+
class TempPathFactory:
|
| 47 |
+
"""Factory for temporary directories under the common base temp directory.
|
| 48 |
+
|
| 49 |
+
The base directory can be configured using the ``--basetemp`` option.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
_given_basetemp: Optional[Path]
|
| 53 |
+
# pluggy TagTracerSub, not currently exposed, so Any.
|
| 54 |
+
_trace: Any
|
| 55 |
+
_basetemp: Optional[Path]
|
| 56 |
+
_retention_count: int
|
| 57 |
+
_retention_policy: "RetentionType"
|
| 58 |
+
|
| 59 |
+
def __init__(
|
| 60 |
+
self,
|
| 61 |
+
given_basetemp: Optional[Path],
|
| 62 |
+
retention_count: int,
|
| 63 |
+
retention_policy: "RetentionType",
|
| 64 |
+
trace,
|
| 65 |
+
basetemp: Optional[Path] = None,
|
| 66 |
+
*,
|
| 67 |
+
_ispytest: bool = False,
|
| 68 |
+
) -> None:
|
| 69 |
+
check_ispytest(_ispytest)
|
| 70 |
+
if given_basetemp is None:
|
| 71 |
+
self._given_basetemp = None
|
| 72 |
+
else:
|
| 73 |
+
# Use os.path.abspath() to get absolute path instead of resolve() as it
|
| 74 |
+
# does not work the same in all platforms (see #4427).
|
| 75 |
+
# Path.absolute() exists, but it is not public (see https://bugs.python.org/issue25012).
|
| 76 |
+
self._given_basetemp = Path(os.path.abspath(str(given_basetemp)))
|
| 77 |
+
self._trace = trace
|
| 78 |
+
self._retention_count = retention_count
|
| 79 |
+
self._retention_policy = retention_policy
|
| 80 |
+
self._basetemp = basetemp
|
| 81 |
+
|
| 82 |
+
@classmethod
|
| 83 |
+
def from_config(
|
| 84 |
+
cls,
|
| 85 |
+
config: Config,
|
| 86 |
+
*,
|
| 87 |
+
_ispytest: bool = False,
|
| 88 |
+
) -> "TempPathFactory":
|
| 89 |
+
"""Create a factory according to pytest configuration.
|
| 90 |
+
|
| 91 |
+
:meta private:
|
| 92 |
+
"""
|
| 93 |
+
check_ispytest(_ispytest)
|
| 94 |
+
count = int(config.getini("tmp_path_retention_count"))
|
| 95 |
+
if count < 0:
|
| 96 |
+
raise ValueError(
|
| 97 |
+
f"tmp_path_retention_count must be >= 0. Current input: {count}."
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
policy = config.getini("tmp_path_retention_policy")
|
| 101 |
+
if policy not in ("all", "failed", "none"):
|
| 102 |
+
raise ValueError(
|
| 103 |
+
f"tmp_path_retention_policy must be either all, failed, none. Current input: {policy}."
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
return cls(
|
| 107 |
+
given_basetemp=config.option.basetemp,
|
| 108 |
+
trace=config.trace.get("tmpdir"),
|
| 109 |
+
retention_count=count,
|
| 110 |
+
retention_policy=policy,
|
| 111 |
+
_ispytest=True,
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
def _ensure_relative_to_basetemp(self, basename: str) -> str:
|
| 115 |
+
basename = os.path.normpath(basename)
|
| 116 |
+
if (self.getbasetemp() / basename).resolve().parent != self.getbasetemp():
|
| 117 |
+
raise ValueError(f"{basename} is not a normalized and relative path")
|
| 118 |
+
return basename
|
| 119 |
+
|
| 120 |
+
def mktemp(self, basename: str, numbered: bool = True) -> Path:
|
| 121 |
+
"""Create a new temporary directory managed by the factory.
|
| 122 |
+
|
| 123 |
+
:param basename:
|
| 124 |
+
Directory base name, must be a relative path.
|
| 125 |
+
|
| 126 |
+
:param numbered:
|
| 127 |
+
If ``True``, ensure the directory is unique by adding a numbered
|
| 128 |
+
suffix greater than any existing one: ``basename="foo-"`` and ``numbered=True``
|
| 129 |
+
means that this function will create directories named ``"foo-0"``,
|
| 130 |
+
``"foo-1"``, ``"foo-2"`` and so on.
|
| 131 |
+
|
| 132 |
+
:returns:
|
| 133 |
+
The path to the new directory.
|
| 134 |
+
"""
|
| 135 |
+
basename = self._ensure_relative_to_basetemp(basename)
|
| 136 |
+
if not numbered:
|
| 137 |
+
p = self.getbasetemp().joinpath(basename)
|
| 138 |
+
p.mkdir(mode=0o700)
|
| 139 |
+
else:
|
| 140 |
+
p = make_numbered_dir(root=self.getbasetemp(), prefix=basename, mode=0o700)
|
| 141 |
+
self._trace("mktemp", p)
|
| 142 |
+
return p
|
| 143 |
+
|
| 144 |
+
def getbasetemp(self) -> Path:
|
| 145 |
+
"""Return the base temporary directory, creating it if needed.
|
| 146 |
+
|
| 147 |
+
:returns:
|
| 148 |
+
The base temporary directory.
|
| 149 |
+
"""
|
| 150 |
+
if self._basetemp is not None:
|
| 151 |
+
return self._basetemp
|
| 152 |
+
|
| 153 |
+
if self._given_basetemp is not None:
|
| 154 |
+
basetemp = self._given_basetemp
|
| 155 |
+
if basetemp.exists():
|
| 156 |
+
rm_rf(basetemp)
|
| 157 |
+
basetemp.mkdir(mode=0o700)
|
| 158 |
+
basetemp = basetemp.resolve()
|
| 159 |
+
else:
|
| 160 |
+
from_env = os.environ.get("PYTEST_DEBUG_TEMPROOT")
|
| 161 |
+
temproot = Path(from_env or tempfile.gettempdir()).resolve()
|
| 162 |
+
user = get_user() or "unknown"
|
| 163 |
+
# use a sub-directory in the temproot to speed-up
|
| 164 |
+
# make_numbered_dir() call
|
| 165 |
+
rootdir = temproot.joinpath(f"pytest-of-{user}")
|
| 166 |
+
try:
|
| 167 |
+
rootdir.mkdir(mode=0o700, exist_ok=True)
|
| 168 |
+
except OSError:
|
| 169 |
+
# getuser() likely returned illegal characters for the platform, use unknown back off mechanism
|
| 170 |
+
rootdir = temproot.joinpath("pytest-of-unknown")
|
| 171 |
+
rootdir.mkdir(mode=0o700, exist_ok=True)
|
| 172 |
+
# Because we use exist_ok=True with a predictable name, make sure
|
| 173 |
+
# we are the owners, to prevent any funny business (on unix, where
|
| 174 |
+
# temproot is usually shared).
|
| 175 |
+
# Also, to keep things private, fixup any world-readable temp
|
| 176 |
+
# rootdir's permissions. Historically 0o755 was used, so we can't
|
| 177 |
+
# just error out on this, at least for a while.
|
| 178 |
+
uid = get_user_id()
|
| 179 |
+
if uid is not None:
|
| 180 |
+
rootdir_stat = rootdir.stat()
|
| 181 |
+
if rootdir_stat.st_uid != uid:
|
| 182 |
+
raise OSError(
|
| 183 |
+
f"The temporary directory {rootdir} is not owned by the current user. "
|
| 184 |
+
"Fix this and try again."
|
| 185 |
+
)
|
| 186 |
+
if (rootdir_stat.st_mode & 0o077) != 0:
|
| 187 |
+
os.chmod(rootdir, rootdir_stat.st_mode & ~0o077)
|
| 188 |
+
keep = self._retention_count
|
| 189 |
+
if self._retention_policy == "none":
|
| 190 |
+
keep = 0
|
| 191 |
+
basetemp = make_numbered_dir_with_cleanup(
|
| 192 |
+
prefix="pytest-",
|
| 193 |
+
root=rootdir,
|
| 194 |
+
keep=keep,
|
| 195 |
+
lock_timeout=LOCK_TIMEOUT,
|
| 196 |
+
mode=0o700,
|
| 197 |
+
)
|
| 198 |
+
assert basetemp is not None, basetemp
|
| 199 |
+
self._basetemp = basetemp
|
| 200 |
+
self._trace("new basetemp", basetemp)
|
| 201 |
+
return basetemp
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def get_user() -> Optional[str]:
|
| 205 |
+
"""Return the current user name, or None if getuser() does not work
|
| 206 |
+
in the current environment (see #1010)."""
|
| 207 |
+
try:
|
| 208 |
+
# In some exotic environments, getpass may not be importable.
|
| 209 |
+
import getpass
|
| 210 |
+
|
| 211 |
+
return getpass.getuser()
|
| 212 |
+
except (ImportError, KeyError):
|
| 213 |
+
return None
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def pytest_configure(config: Config) -> None:
|
| 217 |
+
"""Create a TempPathFactory and attach it to the config object.
|
| 218 |
+
|
| 219 |
+
This is to comply with existing plugins which expect the handler to be
|
| 220 |
+
available at pytest_configure time, but ideally should be moved entirely
|
| 221 |
+
to the tmp_path_factory session fixture.
|
| 222 |
+
"""
|
| 223 |
+
mp = MonkeyPatch()
|
| 224 |
+
config.add_cleanup(mp.undo)
|
| 225 |
+
_tmp_path_factory = TempPathFactory.from_config(config, _ispytest=True)
|
| 226 |
+
mp.setattr(config, "_tmp_path_factory", _tmp_path_factory, raising=False)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def pytest_addoption(parser: Parser) -> None:
|
| 230 |
+
parser.addini(
|
| 231 |
+
"tmp_path_retention_count",
|
| 232 |
+
help="How many sessions should we keep the `tmp_path` directories, according to `tmp_path_retention_policy`.",
|
| 233 |
+
default=3,
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
parser.addini(
|
| 237 |
+
"tmp_path_retention_policy",
|
| 238 |
+
help="Controls which directories created by the `tmp_path` fixture are kept around, based on test outcome. "
|
| 239 |
+
"(all/failed/none)",
|
| 240 |
+
default="all",
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
@fixture(scope="session")
|
| 245 |
+
def tmp_path_factory(request: FixtureRequest) -> TempPathFactory:
|
| 246 |
+
"""Return a :class:`pytest.TempPathFactory` instance for the test session."""
|
| 247 |
+
# Set dynamically by pytest_configure() above.
|
| 248 |
+
return request.config._tmp_path_factory # type: ignore
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def _mk_tmp(request: FixtureRequest, factory: TempPathFactory) -> Path:
|
| 252 |
+
name = request.node.name
|
| 253 |
+
name = re.sub(r"[\W]", "_", name)
|
| 254 |
+
MAXVAL = 30
|
| 255 |
+
name = name[:MAXVAL]
|
| 256 |
+
return factory.mktemp(name, numbered=True)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
@fixture
|
| 260 |
+
def tmp_path(
|
| 261 |
+
request: FixtureRequest, tmp_path_factory: TempPathFactory
|
| 262 |
+
) -> Generator[Path, None, None]:
|
| 263 |
+
"""Return a temporary directory path object which is unique to each test
|
| 264 |
+
function invocation, created as a sub directory of the base temporary
|
| 265 |
+
directory.
|
| 266 |
+
|
| 267 |
+
By default, a new base temporary directory is created each test session,
|
| 268 |
+
and old bases are removed after 3 sessions, to aid in debugging.
|
| 269 |
+
This behavior can be configured with :confval:`tmp_path_retention_count` and
|
| 270 |
+
:confval:`tmp_path_retention_policy`.
|
| 271 |
+
If ``--basetemp`` is used then it is cleared each session. See :ref:`base
|
| 272 |
+
temporary directory`.
|
| 273 |
+
|
| 274 |
+
The returned object is a :class:`pathlib.Path` object.
|
| 275 |
+
"""
|
| 276 |
+
|
| 277 |
+
path = _mk_tmp(request, tmp_path_factory)
|
| 278 |
+
yield path
|
| 279 |
+
|
| 280 |
+
# Remove the tmpdir if the policy is "failed" and the test passed.
|
| 281 |
+
tmp_path_factory: TempPathFactory = request.session.config._tmp_path_factory # type: ignore
|
| 282 |
+
policy = tmp_path_factory._retention_policy
|
| 283 |
+
result_dict = request.node.stash[tmppath_result_key]
|
| 284 |
+
|
| 285 |
+
if policy == "failed" and result_dict.get("call", True):
|
| 286 |
+
# We do a "best effort" to remove files, but it might not be possible due to some leaked resource,
|
| 287 |
+
# permissions, etc, in which case we ignore it.
|
| 288 |
+
rmtree(path, ignore_errors=True)
|
| 289 |
+
|
| 290 |
+
del request.node.stash[tmppath_result_key]
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def pytest_sessionfinish(session, exitstatus: Union[int, ExitCode]):
|
| 294 |
+
"""After each session, remove base directory if all the tests passed,
|
| 295 |
+
the policy is "failed", and the basetemp is not specified by a user.
|
| 296 |
+
"""
|
| 297 |
+
tmp_path_factory: TempPathFactory = session.config._tmp_path_factory
|
| 298 |
+
basetemp = tmp_path_factory._basetemp
|
| 299 |
+
if basetemp is None:
|
| 300 |
+
return
|
| 301 |
+
|
| 302 |
+
policy = tmp_path_factory._retention_policy
|
| 303 |
+
if (
|
| 304 |
+
exitstatus == 0
|
| 305 |
+
and policy == "failed"
|
| 306 |
+
and tmp_path_factory._given_basetemp is None
|
| 307 |
+
):
|
| 308 |
+
if basetemp.is_dir():
|
| 309 |
+
# We do a "best effort" to remove files, but it might not be possible due to some leaked resource,
|
| 310 |
+
# permissions, etc, in which case we ignore it.
|
| 311 |
+
rmtree(basetemp, ignore_errors=True)
|
| 312 |
+
|
| 313 |
+
# Remove dead symlinks.
|
| 314 |
+
if basetemp.is_dir():
|
| 315 |
+
cleanup_dead_symlinks(basetemp)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
@hookimpl(tryfirst=True, hookwrapper=True)
|
| 319 |
+
def pytest_runtest_makereport(item: Item, call):
|
| 320 |
+
outcome = yield
|
| 321 |
+
result: CollectReport = outcome.get_result()
|
| 322 |
+
|
| 323 |
+
empty: Dict[str, bool] = {}
|
| 324 |
+
item.stash.setdefault(tmppath_result_key, empty)[result.when] = result.passed
|
wemm/lib/python3.10/site-packages/_pytest/unraisableexception.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import traceback
|
| 3 |
+
import warnings
|
| 4 |
+
from types import TracebackType
|
| 5 |
+
from typing import Any
|
| 6 |
+
from typing import Callable
|
| 7 |
+
from typing import Generator
|
| 8 |
+
from typing import Optional
|
| 9 |
+
from typing import Type
|
| 10 |
+
|
| 11 |
+
import pytest
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# Copied from cpython/Lib/test/support/__init__.py, with modifications.
|
| 15 |
+
class catch_unraisable_exception:
|
| 16 |
+
"""Context manager catching unraisable exception using sys.unraisablehook.
|
| 17 |
+
|
| 18 |
+
Storing the exception value (cm.unraisable.exc_value) creates a reference
|
| 19 |
+
cycle. The reference cycle is broken explicitly when the context manager
|
| 20 |
+
exits.
|
| 21 |
+
|
| 22 |
+
Storing the object (cm.unraisable.object) can resurrect it if it is set to
|
| 23 |
+
an object which is being finalized. Exiting the context manager clears the
|
| 24 |
+
stored object.
|
| 25 |
+
|
| 26 |
+
Usage:
|
| 27 |
+
with catch_unraisable_exception() as cm:
|
| 28 |
+
# code creating an "unraisable exception"
|
| 29 |
+
...
|
| 30 |
+
# check the unraisable exception: use cm.unraisable
|
| 31 |
+
...
|
| 32 |
+
# cm.unraisable attribute no longer exists at this point
|
| 33 |
+
# (to break a reference cycle)
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(self) -> None:
|
| 37 |
+
self.unraisable: Optional["sys.UnraisableHookArgs"] = None
|
| 38 |
+
self._old_hook: Optional[Callable[["sys.UnraisableHookArgs"], Any]] = None
|
| 39 |
+
|
| 40 |
+
def _hook(self, unraisable: "sys.UnraisableHookArgs") -> None:
|
| 41 |
+
# Storing unraisable.object can resurrect an object which is being
|
| 42 |
+
# finalized. Storing unraisable.exc_value creates a reference cycle.
|
| 43 |
+
self.unraisable = unraisable
|
| 44 |
+
|
| 45 |
+
def __enter__(self) -> "catch_unraisable_exception":
|
| 46 |
+
self._old_hook = sys.unraisablehook
|
| 47 |
+
sys.unraisablehook = self._hook
|
| 48 |
+
return self
|
| 49 |
+
|
| 50 |
+
def __exit__(
|
| 51 |
+
self,
|
| 52 |
+
exc_type: Optional[Type[BaseException]],
|
| 53 |
+
exc_val: Optional[BaseException],
|
| 54 |
+
exc_tb: Optional[TracebackType],
|
| 55 |
+
) -> None:
|
| 56 |
+
assert self._old_hook is not None
|
| 57 |
+
sys.unraisablehook = self._old_hook
|
| 58 |
+
self._old_hook = None
|
| 59 |
+
del self.unraisable
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def unraisable_exception_runtest_hook() -> Generator[None, None, None]:
|
| 63 |
+
with catch_unraisable_exception() as cm:
|
| 64 |
+
yield
|
| 65 |
+
if cm.unraisable:
|
| 66 |
+
if cm.unraisable.err_msg is not None:
|
| 67 |
+
err_msg = cm.unraisable.err_msg
|
| 68 |
+
else:
|
| 69 |
+
err_msg = "Exception ignored in"
|
| 70 |
+
msg = f"{err_msg}: {cm.unraisable.object!r}\n\n"
|
| 71 |
+
msg += "".join(
|
| 72 |
+
traceback.format_exception(
|
| 73 |
+
cm.unraisable.exc_type,
|
| 74 |
+
cm.unraisable.exc_value,
|
| 75 |
+
cm.unraisable.exc_traceback,
|
| 76 |
+
)
|
| 77 |
+
)
|
| 78 |
+
warnings.warn(pytest.PytestUnraisableExceptionWarning(msg))
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
|
| 82 |
+
def pytest_runtest_setup() -> Generator[None, None, None]:
|
| 83 |
+
yield from unraisable_exception_runtest_hook()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
|
| 87 |
+
def pytest_runtest_call() -> Generator[None, None, None]:
|
| 88 |
+
yield from unraisable_exception_runtest_hook()
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
|
| 92 |
+
def pytest_runtest_teardown() -> Generator[None, None, None]:
|
| 93 |
+
yield from unraisable_exception_runtest_hook()
|
wemm/lib/python3.10/site-packages/_pytest/warnings.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import warnings
|
| 3 |
+
from contextlib import contextmanager
|
| 4 |
+
from typing import Generator
|
| 5 |
+
from typing import Optional
|
| 6 |
+
from typing import TYPE_CHECKING
|
| 7 |
+
|
| 8 |
+
import pytest
|
| 9 |
+
from _pytest.config import apply_warning_filters
|
| 10 |
+
from _pytest.config import Config
|
| 11 |
+
from _pytest.config import parse_warning_filter
|
| 12 |
+
from _pytest.main import Session
|
| 13 |
+
from _pytest.nodes import Item
|
| 14 |
+
from _pytest.terminal import TerminalReporter
|
| 15 |
+
|
| 16 |
+
if TYPE_CHECKING:
|
| 17 |
+
from typing_extensions import Literal
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def pytest_configure(config: Config) -> None:
|
| 21 |
+
config.addinivalue_line(
|
| 22 |
+
"markers",
|
| 23 |
+
"filterwarnings(warning): add a warning filter to the given test. "
|
| 24 |
+
"see https://docs.pytest.org/en/stable/how-to/capture-warnings.html#pytest-mark-filterwarnings ",
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@contextmanager
|
| 29 |
+
def catch_warnings_for_item(
|
| 30 |
+
config: Config,
|
| 31 |
+
ihook,
|
| 32 |
+
when: "Literal['config', 'collect', 'runtest']",
|
| 33 |
+
item: Optional[Item],
|
| 34 |
+
) -> Generator[None, None, None]:
|
| 35 |
+
"""Context manager that catches warnings generated in the contained execution block.
|
| 36 |
+
|
| 37 |
+
``item`` can be None if we are not in the context of an item execution.
|
| 38 |
+
|
| 39 |
+
Each warning captured triggers the ``pytest_warning_recorded`` hook.
|
| 40 |
+
"""
|
| 41 |
+
config_filters = config.getini("filterwarnings")
|
| 42 |
+
cmdline_filters = config.known_args_namespace.pythonwarnings or []
|
| 43 |
+
with warnings.catch_warnings(record=True) as log:
|
| 44 |
+
# mypy can't infer that record=True means log is not None; help it.
|
| 45 |
+
assert log is not None
|
| 46 |
+
|
| 47 |
+
if not sys.warnoptions:
|
| 48 |
+
# If user is not explicitly configuring warning filters, show deprecation warnings by default (#2908).
|
| 49 |
+
warnings.filterwarnings("always", category=DeprecationWarning)
|
| 50 |
+
warnings.filterwarnings("always", category=PendingDeprecationWarning)
|
| 51 |
+
|
| 52 |
+
apply_warning_filters(config_filters, cmdline_filters)
|
| 53 |
+
|
| 54 |
+
# apply filters from "filterwarnings" marks
|
| 55 |
+
nodeid = "" if item is None else item.nodeid
|
| 56 |
+
if item is not None:
|
| 57 |
+
for mark in item.iter_markers(name="filterwarnings"):
|
| 58 |
+
for arg in mark.args:
|
| 59 |
+
warnings.filterwarnings(*parse_warning_filter(arg, escape=False))
|
| 60 |
+
|
| 61 |
+
yield
|
| 62 |
+
|
| 63 |
+
for warning_message in log:
|
| 64 |
+
ihook.pytest_warning_recorded.call_historic(
|
| 65 |
+
kwargs=dict(
|
| 66 |
+
warning_message=warning_message,
|
| 67 |
+
nodeid=nodeid,
|
| 68 |
+
when=when,
|
| 69 |
+
location=None,
|
| 70 |
+
)
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def warning_record_to_str(warning_message: warnings.WarningMessage) -> str:
|
| 75 |
+
"""Convert a warnings.WarningMessage to a string."""
|
| 76 |
+
warn_msg = warning_message.message
|
| 77 |
+
msg = warnings.formatwarning(
|
| 78 |
+
str(warn_msg),
|
| 79 |
+
warning_message.category,
|
| 80 |
+
warning_message.filename,
|
| 81 |
+
warning_message.lineno,
|
| 82 |
+
warning_message.line,
|
| 83 |
+
)
|
| 84 |
+
if warning_message.source is not None:
|
| 85 |
+
try:
|
| 86 |
+
import tracemalloc
|
| 87 |
+
except ImportError:
|
| 88 |
+
pass
|
| 89 |
+
else:
|
| 90 |
+
tb = tracemalloc.get_object_traceback(warning_message.source)
|
| 91 |
+
if tb is not None:
|
| 92 |
+
formatted_tb = "\n".join(tb.format())
|
| 93 |
+
# Use a leading new line to better separate the (large) output
|
| 94 |
+
# from the traceback to the previous warning text.
|
| 95 |
+
msg += f"\nObject allocated at:\n{formatted_tb}"
|
| 96 |
+
else:
|
| 97 |
+
# No need for a leading new line.
|
| 98 |
+
url = "https://docs.pytest.org/en/stable/how-to/capture-warnings.html#resource-warnings"
|
| 99 |
+
msg += "Enable tracemalloc to get traceback where the object was allocated.\n"
|
| 100 |
+
msg += f"See {url} for more info."
|
| 101 |
+
return msg
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
|
| 105 |
+
def pytest_runtest_protocol(item: Item) -> Generator[None, None, None]:
|
| 106 |
+
with catch_warnings_for_item(
|
| 107 |
+
config=item.config, ihook=item.ihook, when="runtest", item=item
|
| 108 |
+
):
|
| 109 |
+
yield
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
|
| 113 |
+
def pytest_collection(session: Session) -> Generator[None, None, None]:
|
| 114 |
+
config = session.config
|
| 115 |
+
with catch_warnings_for_item(
|
| 116 |
+
config=config, ihook=config.hook, when="collect", item=None
|
| 117 |
+
):
|
| 118 |
+
yield
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@pytest.hookimpl(hookwrapper=True)
|
| 122 |
+
def pytest_terminal_summary(
|
| 123 |
+
terminalreporter: TerminalReporter,
|
| 124 |
+
) -> Generator[None, None, None]:
|
| 125 |
+
config = terminalreporter.config
|
| 126 |
+
with catch_warnings_for_item(
|
| 127 |
+
config=config, ihook=config.hook, when="config", item=None
|
| 128 |
+
):
|
| 129 |
+
yield
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@pytest.hookimpl(hookwrapper=True)
|
| 133 |
+
def pytest_sessionfinish(session: Session) -> Generator[None, None, None]:
|
| 134 |
+
config = session.config
|
| 135 |
+
with catch_warnings_for_item(
|
| 136 |
+
config=config, ihook=config.hook, when="config", item=None
|
| 137 |
+
):
|
| 138 |
+
yield
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
@pytest.hookimpl(hookwrapper=True)
|
| 142 |
+
def pytest_load_initial_conftests(
|
| 143 |
+
early_config: "Config",
|
| 144 |
+
) -> Generator[None, None, None]:
|
| 145 |
+
with catch_warnings_for_item(
|
| 146 |
+
config=early_config, ihook=early_config.hook, when="config", item=None
|
| 147 |
+
):
|
| 148 |
+
yield
|
wemm/lib/python3.10/site-packages/boto3-1.26.118.dist-info/NOTICE
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
boto3
|
| 2 |
+
Copyright 2013-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
wemm/lib/python3.10/site-packages/boto3-1.26.118.dist-info/RECORD
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
boto3-1.26.118.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
boto3-1.26.118.dist-info/LICENSE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174
|
| 3 |
+
boto3-1.26.118.dist-info/METADATA,sha256=ozJ3CA1nsch9DvjVwQl5D75VBYjCQQTb1H2ZFUrFCHg,6957
|
| 4 |
+
boto3-1.26.118.dist-info/NOTICE,sha256=BPseYUhKeBDxugm7QrwByljJrzOSfXxaIVVuTE0cf6Q,83
|
| 5 |
+
boto3-1.26.118.dist-info/RECORD,,
|
| 6 |
+
boto3-1.26.118.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 7 |
+
boto3-1.26.118.dist-info/WHEEL,sha256=ewwEueio1C2XeHTvT17n8dZUJgOvyCWCt0WVNLClP9o,92
|
| 8 |
+
boto3-1.26.118.dist-info/top_level.txt,sha256=MP6_SI1GcPseXodd3Ykt5F_mCBsrUksiziLxjEZKGUU,6
|
| 9 |
+
boto3/__init__.py,sha256=FNYW6qCf2uu550pIBZ9YDqgpWcTsD7t0JmNjtacBv2Y,3421
|
| 10 |
+
boto3/__pycache__/__init__.cpython-310.pyc,,
|
| 11 |
+
boto3/__pycache__/compat.cpython-310.pyc,,
|
| 12 |
+
boto3/__pycache__/exceptions.cpython-310.pyc,,
|
| 13 |
+
boto3/__pycache__/session.cpython-310.pyc,,
|
| 14 |
+
boto3/__pycache__/utils.cpython-310.pyc,,
|
| 15 |
+
boto3/compat.py,sha256=JXI_O9tsMYL90cmiT7ssicHRu6am5hdgkV_olIPEMLU,2884
|
| 16 |
+
boto3/data/cloudformation/2010-05-15/resources-1.json,sha256=5mFVKJVtbVoHyPdHSyNfZ5mpkgCAws5PhnveSu4qzdI,5110
|
| 17 |
+
boto3/data/cloudwatch/2010-08-01/resources-1.json,sha256=q4AgE8F4pbscd-2U3NYSGAzK55zpMyOQGr83JUxbZXI,11690
|
| 18 |
+
boto3/data/dynamodb/2012-08-10/resources-1.json,sha256=hBLa1Jt7bdT557U9A7UcSi8SCpONKzdbtDRTzjM1-Y0,3849
|
| 19 |
+
boto3/data/ec2/2014-10-01/resources-1.json,sha256=tMG1AMYP2ksnPWY6-3l8DB-EhKsSNtAO9YHhvHqBKu0,68469
|
| 20 |
+
boto3/data/ec2/2015-03-01/resources-1.json,sha256=tMG1AMYP2ksnPWY6-3l8DB-EhKsSNtAO9YHhvHqBKu0,68469
|
| 21 |
+
boto3/data/ec2/2015-04-15/resources-1.json,sha256=tMG1AMYP2ksnPWY6-3l8DB-EhKsSNtAO9YHhvHqBKu0,68469
|
| 22 |
+
boto3/data/ec2/2015-10-01/resources-1.json,sha256=SOfYX2c1KgvnxMO2FCdJpV42rJWNMwVhlFAXhvUPTzA,76564
|
| 23 |
+
boto3/data/ec2/2016-04-01/resources-1.json,sha256=SOfYX2c1KgvnxMO2FCdJpV42rJWNMwVhlFAXhvUPTzA,76564
|
| 24 |
+
boto3/data/ec2/2016-09-15/resources-1.json,sha256=SOfYX2c1KgvnxMO2FCdJpV42rJWNMwVhlFAXhvUPTzA,76564
|
| 25 |
+
boto3/data/ec2/2016-11-15/resources-1.json,sha256=vx7YiL-sUvBFeo4SZ81G7Qa2Hy-y6xY4z2YlSx7_wEw,76922
|
| 26 |
+
boto3/data/glacier/2012-06-01/resources-1.json,sha256=GT5qWQLGeXtrHgTDNG23Mrpyweg6O0Udgd139BuNTVs,19940
|
| 27 |
+
boto3/data/iam/2010-05-08/resources-1.json,sha256=PsOT9yBqSJtluBFHCVRsg6k6Ly2VkSYODnYxSl0DVOc,50357
|
| 28 |
+
boto3/data/opsworks/2013-02-18/resources-1.json,sha256=Y6ygEyegsbYA1gGZn-Ad2yuDd3jUCOt2UKrW_b2YBeM,4136
|
| 29 |
+
boto3/data/s3/2006-03-01/resources-1.json,sha256=VeKALhMRqv7fyDHMLOM5_RzXUEuDdg_n6OIRi3sdB-o,37204
|
| 30 |
+
boto3/data/sns/2010-03-31/resources-1.json,sha256=7zmKQhafgsRDu4U1yiw3NXHz-zJhHKrOmtuoYlxQP-s,9091
|
| 31 |
+
boto3/data/sqs/2012-11-05/resources-1.json,sha256=LRIIr5BId3UDeuBfLn-vRiWsSZCM9_ynqdxF8uzHgy8,6545
|
| 32 |
+
boto3/docs/__init__.py,sha256=ncXQfWgitU2kFSghqy2lezeeW1RneKZ-3wcsvEddsr0,1845
|
| 33 |
+
boto3/docs/__pycache__/__init__.cpython-310.pyc,,
|
| 34 |
+
boto3/docs/__pycache__/action.cpython-310.pyc,,
|
| 35 |
+
boto3/docs/__pycache__/attr.cpython-310.pyc,,
|
| 36 |
+
boto3/docs/__pycache__/base.cpython-310.pyc,,
|
| 37 |
+
boto3/docs/__pycache__/client.cpython-310.pyc,,
|
| 38 |
+
boto3/docs/__pycache__/collection.cpython-310.pyc,,
|
| 39 |
+
boto3/docs/__pycache__/docstring.cpython-310.pyc,,
|
| 40 |
+
boto3/docs/__pycache__/method.cpython-310.pyc,,
|
| 41 |
+
boto3/docs/__pycache__/resource.cpython-310.pyc,,
|
| 42 |
+
boto3/docs/__pycache__/service.cpython-310.pyc,,
|
| 43 |
+
boto3/docs/__pycache__/subresource.cpython-310.pyc,,
|
| 44 |
+
boto3/docs/__pycache__/utils.cpython-310.pyc,,
|
| 45 |
+
boto3/docs/__pycache__/waiter.cpython-310.pyc,,
|
| 46 |
+
boto3/docs/action.py,sha256=J9zesr4iCwb2FSEQmQ6KWqFk4z6NoNpgpBfTYZ_cb90,7347
|
| 47 |
+
boto3/docs/attr.py,sha256=BnG3tR1KKQvvY58aeJiWQ5W5DiMnJ_9jUjmG6tDbFiU,2500
|
| 48 |
+
boto3/docs/base.py,sha256=nOrQSCeUSIZPkn-I59o7CfjEthgdkpCt_rXtE9zQnXc,2103
|
| 49 |
+
boto3/docs/client.py,sha256=RpCngTolE4OtGIPvvJvkw8FJCqh5-7b-Q0QN5mVE7to,1078
|
| 50 |
+
boto3/docs/collection.py,sha256=pWO9I9LTMyhyYyCT_alrO4hZpqNI1228IwABotYTqBU,11679
|
| 51 |
+
boto3/docs/docstring.py,sha256=oPugaubdAXY6aNa-kXGI51lP1xE2s4AnfTsLhibf7-E,2511
|
| 52 |
+
boto3/docs/method.py,sha256=ueltQZjgd6558XBa1XxyZ88wgBrLi85ezOJ0M647ajw,2734
|
| 53 |
+
boto3/docs/resource.py,sha256=HBFq7c-tio19Da2Wb60j99EcW-I9M5-_C-9IjTuWrok,15376
|
| 54 |
+
boto3/docs/service.py,sha256=-Diwwdh2ZmJ7DGiMQN_Zq_gG9xW2oRW2ckPMZMm2k50,8378
|
| 55 |
+
boto3/docs/subresource.py,sha256=W19brjJjeW55ssyYhCnFaZICfp2LjOoC4BP_jW2ViC8,5864
|
| 56 |
+
boto3/docs/utils.py,sha256=H0UeVvmVbYBZ6F-CVEUxVggLMBOIoA5q8y8hxBFnRKE,5436
|
| 57 |
+
boto3/docs/waiter.py,sha256=6wSsxog2I8o5hqgpjI_P1HNWRdYMqnZtTM5kdBaGnSg,5176
|
| 58 |
+
boto3/dynamodb/__init__.py,sha256=GkSq-WxXWfVHu1SEcMrlJbzkfw9ACgF3UdCL6fPpTmY,562
|
| 59 |
+
boto3/dynamodb/__pycache__/__init__.cpython-310.pyc,,
|
| 60 |
+
boto3/dynamodb/__pycache__/conditions.cpython-310.pyc,,
|
| 61 |
+
boto3/dynamodb/__pycache__/table.cpython-310.pyc,,
|
| 62 |
+
boto3/dynamodb/__pycache__/transform.cpython-310.pyc,,
|
| 63 |
+
boto3/dynamodb/__pycache__/types.cpython-310.pyc,,
|
| 64 |
+
boto3/dynamodb/conditions.py,sha256=1CroEyYWRyLa8QDIlUrlqq4a4DGerUg97Az2qGVhXvo,15046
|
| 65 |
+
boto3/dynamodb/table.py,sha256=us79dxZSQSno8gsUoAdQyzc2oBJL2riUpN6RGc8vQk8,6343
|
| 66 |
+
boto3/dynamodb/transform.py,sha256=JnW5ZzPIfxEcDszSvXKUZmp_1rw445tsddS3FG--JwA,12909
|
| 67 |
+
boto3/dynamodb/types.py,sha256=ch0vIKaAYexjL42S_OJWyvjWMcb0UbNrmkKGcz76O3c,9541
|
| 68 |
+
boto3/ec2/__init__.py,sha256=GkSq-WxXWfVHu1SEcMrlJbzkfw9ACgF3UdCL6fPpTmY,562
|
| 69 |
+
boto3/ec2/__pycache__/__init__.cpython-310.pyc,,
|
| 70 |
+
boto3/ec2/__pycache__/createtags.cpython-310.pyc,,
|
| 71 |
+
boto3/ec2/__pycache__/deletetags.cpython-310.pyc,,
|
| 72 |
+
boto3/ec2/createtags.py,sha256=pUPJOYn7m0Jcch9UL-DEVGgbQHoyAemECPBhzyBx28c,1577
|
| 73 |
+
boto3/ec2/deletetags.py,sha256=KaYcqSt8FFM_TW0g0pZ14qDjVnmRCPV0sMe6DprEtvo,1217
|
| 74 |
+
boto3/examples/cloudfront.rst,sha256=K-sBWZxoLjABCZHrqAZs57cYefwPmDir03pm6PE_mh4,1390
|
| 75 |
+
boto3/examples/s3.rst,sha256=jCfgEDfpw08nFtCizCN2OGg15zQRkx3DiJXZUfqhE2s,5486
|
| 76 |
+
boto3/exceptions.py,sha256=rQkmjFkG-AuNrNAm5G5cOw_BGBdIQ_FJklWm-rqCODg,4119
|
| 77 |
+
boto3/resources/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 78 |
+
boto3/resources/__pycache__/__init__.cpython-310.pyc,,
|
| 79 |
+
boto3/resources/__pycache__/action.cpython-310.pyc,,
|
| 80 |
+
boto3/resources/__pycache__/base.cpython-310.pyc,,
|
| 81 |
+
boto3/resources/__pycache__/collection.cpython-310.pyc,,
|
| 82 |
+
boto3/resources/__pycache__/factory.cpython-310.pyc,,
|
| 83 |
+
boto3/resources/__pycache__/model.cpython-310.pyc,,
|
| 84 |
+
boto3/resources/__pycache__/params.cpython-310.pyc,,
|
| 85 |
+
boto3/resources/__pycache__/response.cpython-310.pyc,,
|
| 86 |
+
boto3/resources/action.py,sha256=vPfVHVgXiGqhwpgRSCC7lSsY3vGjgsSiYhXa14CMAqw,9600
|
| 87 |
+
boto3/resources/base.py,sha256=Nf5Anssquo3urPDyWLAN8di379z5oafjwzl3gD9WbsI,5044
|
| 88 |
+
boto3/resources/collection.py,sha256=bSV0353zcTRLEPws2qqMFd2Xure8I8LgU-IDR-TM3sI,19242
|
| 89 |
+
boto3/resources/factory.py,sha256=gFPmhKh99zztkpBMZ8ToUbOVrJnyXqymcN-d_Ig3vRU,22707
|
| 90 |
+
boto3/resources/model.py,sha256=3mCNSvnmCKPzjK-hW4yEv0PjKYb0hxBsAE9nopY-3bU,20394
|
| 91 |
+
boto3/resources/params.py,sha256=i6KAjOzjzou7ouViYbRZCz0CwqB6fA_6gOJFDIruTV8,6112
|
| 92 |
+
boto3/resources/response.py,sha256=aC1AZuO08qtb1psJtbrc5Na32AQ9WI-Il4DpVxsUtXs,11694
|
| 93 |
+
boto3/s3/__init__.py,sha256=GkSq-WxXWfVHu1SEcMrlJbzkfw9ACgF3UdCL6fPpTmY,562
|
| 94 |
+
boto3/s3/__pycache__/__init__.cpython-310.pyc,,
|
| 95 |
+
boto3/s3/__pycache__/inject.cpython-310.pyc,,
|
| 96 |
+
boto3/s3/__pycache__/transfer.cpython-310.pyc,,
|
| 97 |
+
boto3/s3/inject.py,sha256=Ixa2AHHkwyrsAOGAE_7B5QoJq6v-yxj2O_z2T80Orfs,28038
|
| 98 |
+
boto3/s3/transfer.py,sha256=PwxaTRX1R5hYU77QTqdUBUmb_aeZxXMbzf-7h0g_hvA,13189
|
| 99 |
+
boto3/session.py,sha256=ihfVht4XQWHYxv5C6WvtjUYUrYblYpIYfsffrDDAXU8,20759
|
| 100 |
+
boto3/utils.py,sha256=dBw0Eu23TOhDsP1Lkrp4uOVMn5DS8s0kRGwVRiCD_KM,3141
|
wemm/lib/python3.10/site-packages/cos_python_sdk_v5-1.9.33.dist-info/METADATA
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.2
|
| 2 |
+
Name: cos-python-sdk-v5
|
| 3 |
+
Version: 1.9.33
|
| 4 |
+
Summary: cos-python-sdk-v5
|
| 5 |
+
Home-page: https://www.qcloud.com/
|
| 6 |
+
Author: tiedu, lewzylu, channingliu
|
| 7 |
+
Author-email: dutie123@qq.com
|
| 8 |
+
License: MIT
|
| 9 |
+
Requires-Dist: requests>=2.8
|
| 10 |
+
Requires-Dist: xmltodict
|
| 11 |
+
Requires-Dist: six
|
| 12 |
+
Requires-Dist: crcmod
|
| 13 |
+
Requires-Dist: pycryptodome
|
| 14 |
+
Dynamic: author
|
| 15 |
+
Dynamic: author-email
|
| 16 |
+
Dynamic: description
|
| 17 |
+
Dynamic: home-page
|
| 18 |
+
Dynamic: license
|
| 19 |
+
Dynamic: requires-dist
|
| 20 |
+
Dynamic: summary
|
| 21 |
+
|
| 22 |
+
Qcloud COSv5 SDK
|
| 23 |
+
#######################
|
| 24 |
+
|
| 25 |
+
.. image:: https://img.shields.io/pypi/v/cos-python-sdk-v5.svg
|
| 26 |
+
:target: https://pypi.org/search/?q=cos-python-sdk-v5
|
| 27 |
+
:alt: Pypi
|
| 28 |
+
.. image:: https://api.travis-ci.com/tencentyun/cos-python-sdk-v5.svg?branch=master
|
| 29 |
+
:target: https://app.travis-ci.com/github/tencentyun/cos-python-sdk-v5
|
| 30 |
+
:alt: Travis CI
|
| 31 |
+
|
| 32 |
+
介绍
|
| 33 |
+
_______
|
| 34 |
+
|
| 35 |
+
腾讯云COSV5Python SDK, 目前可以支持Python2.6与Python2.7以及Python3.x。
|
| 36 |
+
|
| 37 |
+
安装指南
|
| 38 |
+
__________
|
| 39 |
+
|
| 40 |
+
使用pip安装 ::
|
| 41 |
+
|
| 42 |
+
pip install -U cos-python-sdk-v5
|
| 43 |
+
|
| 44 |
+
手动安装::
|
| 45 |
+
|
| 46 |
+
python setup.py install
|
| 47 |
+
|
| 48 |
+
使用方法
|
| 49 |
+
__________
|
| 50 |
+
|
| 51 |
+
使用python sdk,参照 https://github.com/tencentyun/cos-python-sdk-v5/blob/master/demo/demo.py
|
| 52 |
+
|
| 53 |
+
cos最新可用地域,参照 https://cloud.tencent.com/document/product/436/6224
|
| 54 |
+
|
| 55 |
+
python sdk 快速入门,参照 https://cloud.tencent.com/document/product/436/12269
|
| 56 |
+
|
| 57 |
+
python sdk 接口文档,参照 https://cloud.tencent.com/document/product/436/12270
|
wemm/lib/python3.10/site-packages/cos_python_sdk_v5-1.9.33.dist-info/RECORD
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cos_python_sdk_v5-1.9.33.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
cos_python_sdk_v5-1.9.33.dist-info/METADATA,sha256=zA5NqAlh5n472bOnQKP205fDUL9u-wcg30ulyYf3PvU,1428
|
| 3 |
+
cos_python_sdk_v5-1.9.33.dist-info/RECORD,,
|
| 4 |
+
cos_python_sdk_v5-1.9.33.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 5 |
+
cos_python_sdk_v5-1.9.33.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
|
| 6 |
+
cos_python_sdk_v5-1.9.33.dist-info/top_level.txt,sha256=rKIVGdJRciC4LUT3wyVCXhalOYYP1PpWHxlmeFfRLBE,14
|
| 7 |
+
qcloud_cos/__init__.py,sha256=LyxiB-laLe-p5shiNv69QPePAPWaulv3v7kyY8iFl3c,532
|
| 8 |
+
qcloud_cos/__pycache__/__init__.cpython-310.pyc,,
|
| 9 |
+
qcloud_cos/__pycache__/ai_recognition.cpython-310.pyc,,
|
| 10 |
+
qcloud_cos/__pycache__/cos_auth.cpython-310.pyc,,
|
| 11 |
+
qcloud_cos/__pycache__/cos_client.cpython-310.pyc,,
|
| 12 |
+
qcloud_cos/__pycache__/cos_comm.cpython-310.pyc,,
|
| 13 |
+
qcloud_cos/__pycache__/cos_encryption_client.cpython-310.pyc,,
|
| 14 |
+
qcloud_cos/__pycache__/cos_exception.cpython-310.pyc,,
|
| 15 |
+
qcloud_cos/__pycache__/cos_threadpool.cpython-310.pyc,,
|
| 16 |
+
qcloud_cos/__pycache__/crypto.cpython-310.pyc,,
|
| 17 |
+
qcloud_cos/__pycache__/meta_insight.cpython-310.pyc,,
|
| 18 |
+
qcloud_cos/__pycache__/resumable_downloader.cpython-310.pyc,,
|
| 19 |
+
qcloud_cos/__pycache__/select_event_stream.cpython-310.pyc,,
|
| 20 |
+
qcloud_cos/__pycache__/streambody.cpython-310.pyc,,
|
| 21 |
+
qcloud_cos/__pycache__/version.cpython-310.pyc,,
|
| 22 |
+
qcloud_cos/__pycache__/xml2dict.cpython-310.pyc,,
|
| 23 |
+
qcloud_cos/ai_recognition.py,sha256=F8FIwrCg3YjpCR6uOLfuzRVLvgh40XO-mYvPGGDvJsc,48954
|
| 24 |
+
qcloud_cos/cos_auth.py,sha256=_4_uFWl2FO_WhpUpqvfjAT7JZ083QZWqvXdUHrkM2BE,7526
|
| 25 |
+
qcloud_cos/cos_client.py,sha256=6rsG2hkmnZhmnvpSj2UVrDdz1sARhJxZB5_SqbPjido,467267
|
| 26 |
+
qcloud_cos/cos_comm.py,sha256=011dJHTARMJUgTxCsFKdSG6uGvdSkApvtRscK-z99L0,21296
|
| 27 |
+
qcloud_cos/cos_encryption_client.py,sha256=eUCazQhJoQQ8a1LAFJ6ecxZcj-QGpQmgS1DylofY6yI,7627
|
| 28 |
+
qcloud_cos/cos_exception.py,sha256=2c3X2PVSJpkT1Ua8-eq9dAy-8-aFKxjKBm06NlhsjIg,2947
|
| 29 |
+
qcloud_cos/cos_threadpool.py,sha256=E0poXI0pjWDS2HbTVdpV6gZv1Z3cllyQAyqE5zoV6Yk,3321
|
| 30 |
+
qcloud_cos/crypto.py,sha256=kEHyhKMCIX-pcS31fNlKjxtpReKc9h3nV46KDLmVt_4,16057
|
| 31 |
+
qcloud_cos/meta_insight.py,sha256=VI2XtV6So11ZzVRg6j6jAYvaNLH8ArgUbQfg7bBHXYY,32968
|
| 32 |
+
qcloud_cos/resumable_downloader.py,sha256=zSeOArgdurs-WmjIVQrS8ABOJ5gpDmSkys6WXn7Rr1Y,9767
|
| 33 |
+
qcloud_cos/select_event_stream.py,sha256=e2tkM6K5NJlfwDYmpHJFNNeb_FoLesfWSpxzzpyiJm0,4284
|
| 34 |
+
qcloud_cos/streambody.py,sha256=KyRu0uhFN9ezaXXlpgT7gUHyCFrUZqko8dScRwEeBb8,3011
|
| 35 |
+
qcloud_cos/version.py,sha256=lmagyyfyz2O4z3rVCf8ex6Zt0aw8XDCsEo8OX1rgz44,25
|
| 36 |
+
qcloud_cos/xml2dict.py,sha256=euH6lDATcGbyiqsmMkV78iwwT9Dclk4FnegdjBkWoj8,1732
|
| 37 |
+
ut/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 38 |
+
ut/__pycache__/__init__.cpython-310.pyc,,
|
| 39 |
+
ut/__pycache__/test.cpython-310.pyc,,
|
| 40 |
+
ut/test.py,sha256=BhtmNJdR-fhEuF9Fk295u-wLvfrarItW2Ier-SQsaxk,183546
|