ZTWHHH commited on
Commit
b94d268
·
verified ·
1 Parent(s): 7a75a36

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. vllm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/INSTALLER +1 -0
  2. vllm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/LICENSE.txt +28 -0
  3. vllm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/METADATA +92 -0
  4. vllm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/RECORD +15 -0
  5. vllm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/REQUESTED +0 -0
  6. vllm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/WHEEL +6 -0
  7. vllm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/top_level.txt +1 -0
  8. vllm/lib/python3.10/site-packages/_pytest/__init__.py +13 -0
  9. vllm/lib/python3.10/site-packages/_pytest/_argcomplete.py +117 -0
  10. vllm/lib/python3.10/site-packages/_pytest/_io/pprint.py +673 -0
  11. vllm/lib/python3.10/site-packages/_pytest/_io/saferepr.py +130 -0
  12. vllm/lib/python3.10/site-packages/_pytest/_io/terminalwriter.py +274 -0
  13. vllm/lib/python3.10/site-packages/_pytest/_version.py +16 -0
  14. vllm/lib/python3.10/site-packages/_pytest/cacheprovider.py +626 -0
  15. vllm/lib/python3.10/site-packages/_pytest/compat.py +351 -0
  16. vllm/lib/python3.10/site-packages/_pytest/config/__init__.py +1973 -0
  17. vllm/lib/python3.10/site-packages/_pytest/config/__pycache__/__init__.cpython-310.pyc +0 -0
  18. vllm/lib/python3.10/site-packages/_pytest/config/__pycache__/argparsing.cpython-310.pyc +0 -0
  19. vllm/lib/python3.10/site-packages/_pytest/config/__pycache__/compat.cpython-310.pyc +0 -0
  20. vllm/lib/python3.10/site-packages/_pytest/config/__pycache__/exceptions.cpython-310.pyc +0 -0
  21. vllm/lib/python3.10/site-packages/_pytest/config/__pycache__/findpaths.cpython-310.pyc +0 -0
  22. vllm/lib/python3.10/site-packages/_pytest/config/argparsing.py +551 -0
  23. vllm/lib/python3.10/site-packages/_pytest/config/compat.py +85 -0
  24. vllm/lib/python3.10/site-packages/_pytest/config/findpaths.py +228 -0
  25. vllm/lib/python3.10/site-packages/_pytest/debugging.py +385 -0
  26. vllm/lib/python3.10/site-packages/_pytest/doctest.py +755 -0
  27. vllm/lib/python3.10/site-packages/_pytest/fixtures.py +1932 -0
  28. vllm/lib/python3.10/site-packages/_pytest/freeze_support.py +45 -0
  29. vllm/lib/python3.10/site-packages/_pytest/helpconfig.py +276 -0
  30. vllm/lib/python3.10/site-packages/_pytest/hookspec.py +1333 -0
  31. vllm/lib/python3.10/site-packages/_pytest/junitxml.py +697 -0
  32. vllm/lib/python3.10/site-packages/_pytest/legacypath.py +468 -0
  33. vllm/lib/python3.10/site-packages/_pytest/logging.py +955 -0
  34. vllm/lib/python3.10/site-packages/_pytest/main.py +1072 -0
  35. vllm/lib/python3.10/site-packages/_pytest/mark/__init__.py +292 -0
  36. vllm/lib/python3.10/site-packages/_pytest/mark/__pycache__/__init__.cpython-310.pyc +0 -0
  37. vllm/lib/python3.10/site-packages/_pytest/mark/__pycache__/expression.cpython-310.pyc +0 -0
  38. vllm/lib/python3.10/site-packages/_pytest/mark/__pycache__/structures.cpython-310.pyc +0 -0
  39. vllm/lib/python3.10/site-packages/_pytest/mark/expression.py +333 -0
  40. vllm/lib/python3.10/site-packages/_pytest/mark/structures.py +615 -0
  41. vllm/lib/python3.10/site-packages/_pytest/monkeypatch.py +415 -0
  42. vllm/lib/python3.10/site-packages/_pytest/outcomes.py +318 -0
  43. vllm/lib/python3.10/site-packages/_pytest/pastebin.py +113 -0
  44. vllm/lib/python3.10/site-packages/_pytest/pathlib.py +1038 -0
  45. vllm/lib/python3.10/site-packages/_pytest/py.typed +0 -0
  46. vllm/lib/python3.10/site-packages/_pytest/pytester.py +1766 -0
  47. vllm/lib/python3.10/site-packages/_pytest/pytester_assertions.py +74 -0
  48. vllm/lib/python3.10/site-packages/_pytest/python.py +1679 -0
  49. vllm/lib/python3.10/site-packages/_pytest/python_api.py +1028 -0
  50. vllm/lib/python3.10/site-packages/_pytest/python_path.py +26 -0
vllm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
vllm/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.
vllm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/METADATA ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: MarkupSafe
3
+ Version: 3.0.2
4
+ Summary: Safely add untrusted strings to HTML/XML markup.
5
+ Maintainer-email: Pallets <contact@palletsprojects.com>
6
+ License: Copyright 2010 Pallets
7
+
8
+ Redistribution and use in source and binary forms, with or without
9
+ modification, are permitted provided that the following conditions are
10
+ met:
11
+
12
+ 1. Redistributions of source code must retain the above copyright
13
+ notice, this list of conditions and the following disclaimer.
14
+
15
+ 2. Redistributions in binary form must reproduce the above copyright
16
+ notice, this list of conditions and the following disclaimer in the
17
+ documentation and/or other materials provided with the distribution.
18
+
19
+ 3. Neither the name of the copyright holder nor the names of its
20
+ contributors may be used to endorse or promote products derived from
21
+ this software without specific prior written permission.
22
+
23
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
26
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29
+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34
+
35
+ Project-URL: Donate, https://palletsprojects.com/donate
36
+ Project-URL: Documentation, https://markupsafe.palletsprojects.com/
37
+ Project-URL: Changes, https://markupsafe.palletsprojects.com/changes/
38
+ Project-URL: Source, https://github.com/pallets/markupsafe/
39
+ Project-URL: Chat, https://discord.gg/pallets
40
+ Classifier: Development Status :: 5 - Production/Stable
41
+ Classifier: Environment :: Web Environment
42
+ Classifier: Intended Audience :: Developers
43
+ Classifier: License :: OSI Approved :: BSD License
44
+ Classifier: Operating System :: OS Independent
45
+ Classifier: Programming Language :: Python
46
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
47
+ Classifier: Topic :: Text Processing :: Markup :: HTML
48
+ Classifier: Typing :: Typed
49
+ Requires-Python: >=3.9
50
+ Description-Content-Type: text/markdown
51
+ License-File: LICENSE.txt
52
+
53
+ # MarkupSafe
54
+
55
+ MarkupSafe implements a text object that escapes characters so it is
56
+ safe to use in HTML and XML. Characters that have special meanings are
57
+ replaced so that they display as the actual characters. This mitigates
58
+ injection attacks, meaning untrusted user input can safely be displayed
59
+ on a page.
60
+
61
+
62
+ ## Examples
63
+
64
+ ```pycon
65
+ >>> from markupsafe import Markup, escape
66
+
67
+ >>> # escape replaces special characters and wraps in Markup
68
+ >>> escape("<script>alert(document.cookie);</script>")
69
+ Markup('&lt;script&gt;alert(document.cookie);&lt;/script&gt;')
70
+
71
+ >>> # wrap in Markup to mark text "safe" and prevent escaping
72
+ >>> Markup("<strong>Hello</strong>")
73
+ Markup('<strong>hello</strong>')
74
+
75
+ >>> escape(Markup("<strong>Hello</strong>"))
76
+ Markup('<strong>hello</strong>')
77
+
78
+ >>> # Markup is a str subclass
79
+ >>> # methods and operators escape their arguments
80
+ >>> template = Markup("Hello <em>{name}</em>")
81
+ >>> template.format(name='"World"')
82
+ Markup('Hello <em>&#34;World&#34;</em>')
83
+ ```
84
+
85
+ ## Donate
86
+
87
+ The Pallets organization develops and supports MarkupSafe and other
88
+ popular packages. In order to grow the community of contributors and
89
+ users, and allow the maintainers to devote more time to the projects,
90
+ [please donate today][].
91
+
92
+ [please donate today]: https://palletsprojects.com/donate
vllm/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
vllm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/REQUESTED ADDED
File without changes
vllm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.2.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp310-cp310-manylinux_2_17_x86_64
5
+ Tag: cp310-cp310-manylinux2014_x86_64
6
+
vllm/lib/python3.10/site-packages/MarkupSafe-3.0.2.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ markupsafe
vllm/lib/python3.10/site-packages/_pytest/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+
4
+ __all__ = ["__version__", "version_tuple"]
5
+
6
+ try:
7
+ from ._version import version as __version__
8
+ from ._version import version_tuple
9
+ except ImportError: # pragma: no cover
10
+ # broken installation, we don't even try
11
+ # unknown only works because we do poor mans version compare
12
+ __version__ = "unknown"
13
+ version_tuple = (0, 0, "unknown")
vllm/lib/python3.10/site-packages/_pytest/_argcomplete.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
65
+ from __future__ import annotations
66
+
67
+ import argparse
68
+ from glob import glob
69
+ import os
70
+ import sys
71
+ from typing import Any
72
+
73
+
74
+ class FastFilesCompleter:
75
+ """Fast file completer class."""
76
+
77
+ def __init__(self, directories: bool = True) -> None:
78
+ self.directories = directories
79
+
80
+ def __call__(self, prefix: str, **kwargs: Any) -> list[str]:
81
+ # Only called on non option completions.
82
+ if os.sep in prefix[1:]:
83
+ prefix_dir = len(os.path.dirname(prefix) + os.sep)
84
+ else:
85
+ prefix_dir = 0
86
+ completion = []
87
+ globbed = []
88
+ if "*" not in prefix and "?" not in prefix:
89
+ # We are on unix, otherwise no bash.
90
+ if not prefix or prefix[-1] == os.sep:
91
+ globbed.extend(glob(prefix + ".*"))
92
+ prefix += "*"
93
+ globbed.extend(glob(prefix))
94
+ for x in sorted(globbed):
95
+ if os.path.isdir(x):
96
+ x += "/"
97
+ # Append stripping the prefix (like bash, not like compgen).
98
+ completion.append(x[prefix_dir:])
99
+ return completion
100
+
101
+
102
+ if os.environ.get("_ARGCOMPLETE"):
103
+ try:
104
+ import argcomplete.completers
105
+ except ImportError:
106
+ sys.exit(-1)
107
+ filescompleter: FastFilesCompleter | None = FastFilesCompleter()
108
+
109
+ def try_argcomplete(parser: argparse.ArgumentParser) -> None:
110
+ argcomplete.autocomplete(parser, always_complete_options=False)
111
+
112
+ else:
113
+
114
+ def try_argcomplete(parser: argparse.ArgumentParser) -> None:
115
+ pass
116
+
117
+ filescompleter = None
vllm/lib/python3.10/site-packages/_pytest/_io/pprint.py ADDED
@@ -0,0 +1,673 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # This module was imported from the cpython standard library
3
+ # (https://github.com/python/cpython/) at commit
4
+ # c5140945c723ae6c4b7ee81ff720ac8ea4b52cfd (python3.12).
5
+ #
6
+ #
7
+ # Original Author: Fred L. Drake, Jr.
8
+ # fdrake@acm.org
9
+ #
10
+ # This is a simple little module I wrote to make life easier. I didn't
11
+ # see anything quite like it in the library, though I may have overlooked
12
+ # something. I wrote this when I was trying to read some heavily nested
13
+ # tuples with fairly non-descriptive content. This is modeled very much
14
+ # after Lisp/Scheme - style pretty-printing of lists. If you find it
15
+ # useful, thank small children who sleep at night.
16
+ from __future__ import annotations
17
+
18
+ import collections as _collections
19
+ import dataclasses as _dataclasses
20
+ from io import StringIO as _StringIO
21
+ import re
22
+ import types as _types
23
+ from typing import Any
24
+ from typing import Callable
25
+ from typing import IO
26
+ from typing import Iterator
27
+
28
+
29
+ class _safe_key:
30
+ """Helper function for key functions when sorting unorderable objects.
31
+
32
+ The wrapped-object will fallback to a Py2.x style comparison for
33
+ unorderable types (sorting first comparing the type name and then by
34
+ the obj ids). Does not work recursively, so dict.items() must have
35
+ _safe_key applied to both the key and the value.
36
+
37
+ """
38
+
39
+ __slots__ = ["obj"]
40
+
41
+ def __init__(self, obj):
42
+ self.obj = obj
43
+
44
+ def __lt__(self, other):
45
+ try:
46
+ return self.obj < other.obj
47
+ except TypeError:
48
+ return (str(type(self.obj)), id(self.obj)) < (
49
+ str(type(other.obj)),
50
+ id(other.obj),
51
+ )
52
+
53
+
54
+ def _safe_tuple(t):
55
+ """Helper function for comparing 2-tuples"""
56
+ return _safe_key(t[0]), _safe_key(t[1])
57
+
58
+
59
+ class PrettyPrinter:
60
+ def __init__(
61
+ self,
62
+ indent: int = 4,
63
+ width: int = 80,
64
+ depth: int | None = None,
65
+ ) -> None:
66
+ """Handle pretty printing operations onto a stream using a set of
67
+ configured parameters.
68
+
69
+ indent
70
+ Number of spaces to indent for each level of nesting.
71
+
72
+ width
73
+ Attempted maximum number of columns in the output.
74
+
75
+ depth
76
+ The maximum depth to print out nested structures.
77
+
78
+ """
79
+ if indent < 0:
80
+ raise ValueError("indent must be >= 0")
81
+ if depth is not None and depth <= 0:
82
+ raise ValueError("depth must be > 0")
83
+ if not width:
84
+ raise ValueError("width must be != 0")
85
+ self._depth = depth
86
+ self._indent_per_level = indent
87
+ self._width = width
88
+
89
+ def pformat(self, object: Any) -> str:
90
+ sio = _StringIO()
91
+ self._format(object, sio, 0, 0, set(), 0)
92
+ return sio.getvalue()
93
+
94
+ def _format(
95
+ self,
96
+ object: Any,
97
+ stream: IO[str],
98
+ indent: int,
99
+ allowance: int,
100
+ context: set[int],
101
+ level: int,
102
+ ) -> None:
103
+ objid = id(object)
104
+ if objid in context:
105
+ stream.write(_recursion(object))
106
+ return
107
+
108
+ p = self._dispatch.get(type(object).__repr__, None)
109
+ if p is not None:
110
+ context.add(objid)
111
+ p(self, object, stream, indent, allowance, context, level + 1)
112
+ context.remove(objid)
113
+ elif (
114
+ _dataclasses.is_dataclass(object) # type:ignore[unreachable]
115
+ and not isinstance(object, type)
116
+ and object.__dataclass_params__.repr
117
+ and
118
+ # Check dataclass has generated repr method.
119
+ hasattr(object.__repr__, "__wrapped__")
120
+ and "__create_fn__" in object.__repr__.__wrapped__.__qualname__
121
+ ):
122
+ context.add(objid) # type:ignore[unreachable]
123
+ self._pprint_dataclass(
124
+ object, stream, indent, allowance, context, level + 1
125
+ )
126
+ context.remove(objid)
127
+ else:
128
+ stream.write(self._repr(object, context, level))
129
+
130
+ def _pprint_dataclass(
131
+ self,
132
+ object: Any,
133
+ stream: IO[str],
134
+ indent: int,
135
+ allowance: int,
136
+ context: set[int],
137
+ level: int,
138
+ ) -> None:
139
+ cls_name = object.__class__.__name__
140
+ items = [
141
+ (f.name, getattr(object, f.name))
142
+ for f in _dataclasses.fields(object)
143
+ if f.repr
144
+ ]
145
+ stream.write(cls_name + "(")
146
+ self._format_namespace_items(items, stream, indent, allowance, context, level)
147
+ stream.write(")")
148
+
149
+ _dispatch: dict[
150
+ Callable[..., str],
151
+ Callable[[PrettyPrinter, Any, IO[str], int, int, set[int], int], None],
152
+ ] = {}
153
+
154
+ def _pprint_dict(
155
+ self,
156
+ object: Any,
157
+ stream: IO[str],
158
+ indent: int,
159
+ allowance: int,
160
+ context: set[int],
161
+ level: int,
162
+ ) -> None:
163
+ write = stream.write
164
+ write("{")
165
+ items = sorted(object.items(), key=_safe_tuple)
166
+ self._format_dict_items(items, stream, indent, allowance, context, level)
167
+ write("}")
168
+
169
+ _dispatch[dict.__repr__] = _pprint_dict
170
+
171
+ def _pprint_ordered_dict(
172
+ self,
173
+ object: Any,
174
+ stream: IO[str],
175
+ indent: int,
176
+ allowance: int,
177
+ context: set[int],
178
+ level: int,
179
+ ) -> None:
180
+ if not len(object):
181
+ stream.write(repr(object))
182
+ return
183
+ cls = object.__class__
184
+ stream.write(cls.__name__ + "(")
185
+ self._pprint_dict(object, stream, indent, allowance, context, level)
186
+ stream.write(")")
187
+
188
+ _dispatch[_collections.OrderedDict.__repr__] = _pprint_ordered_dict
189
+
190
+ def _pprint_list(
191
+ self,
192
+ object: Any,
193
+ stream: IO[str],
194
+ indent: int,
195
+ allowance: int,
196
+ context: set[int],
197
+ level: int,
198
+ ) -> None:
199
+ stream.write("[")
200
+ self._format_items(object, stream, indent, allowance, context, level)
201
+ stream.write("]")
202
+
203
+ _dispatch[list.__repr__] = _pprint_list
204
+
205
+ def _pprint_tuple(
206
+ self,
207
+ object: Any,
208
+ stream: IO[str],
209
+ indent: int,
210
+ allowance: int,
211
+ context: set[int],
212
+ level: int,
213
+ ) -> None:
214
+ stream.write("(")
215
+ self._format_items(object, stream, indent, allowance, context, level)
216
+ stream.write(")")
217
+
218
+ _dispatch[tuple.__repr__] = _pprint_tuple
219
+
220
+ def _pprint_set(
221
+ self,
222
+ object: Any,
223
+ stream: IO[str],
224
+ indent: int,
225
+ allowance: int,
226
+ context: set[int],
227
+ level: int,
228
+ ) -> None:
229
+ if not len(object):
230
+ stream.write(repr(object))
231
+ return
232
+ typ = object.__class__
233
+ if typ is set:
234
+ stream.write("{")
235
+ endchar = "}"
236
+ else:
237
+ stream.write(typ.__name__ + "({")
238
+ endchar = "})"
239
+ object = sorted(object, key=_safe_key)
240
+ self._format_items(object, stream, indent, allowance, context, level)
241
+ stream.write(endchar)
242
+
243
+ _dispatch[set.__repr__] = _pprint_set
244
+ _dispatch[frozenset.__repr__] = _pprint_set
245
+
246
+ def _pprint_str(
247
+ self,
248
+ object: Any,
249
+ stream: IO[str],
250
+ indent: int,
251
+ allowance: int,
252
+ context: set[int],
253
+ level: int,
254
+ ) -> None:
255
+ write = stream.write
256
+ if not len(object):
257
+ write(repr(object))
258
+ return
259
+ chunks = []
260
+ lines = object.splitlines(True)
261
+ if level == 1:
262
+ indent += 1
263
+ allowance += 1
264
+ max_width1 = max_width = self._width - indent
265
+ for i, line in enumerate(lines):
266
+ rep = repr(line)
267
+ if i == len(lines) - 1:
268
+ max_width1 -= allowance
269
+ if len(rep) <= max_width1:
270
+ chunks.append(rep)
271
+ else:
272
+ # A list of alternating (non-space, space) strings
273
+ parts = re.findall(r"\S*\s*", line)
274
+ assert parts
275
+ assert not parts[-1]
276
+ parts.pop() # drop empty last part
277
+ max_width2 = max_width
278
+ current = ""
279
+ for j, part in enumerate(parts):
280
+ candidate = current + part
281
+ if j == len(parts) - 1 and i == len(lines) - 1:
282
+ max_width2 -= allowance
283
+ if len(repr(candidate)) > max_width2:
284
+ if current:
285
+ chunks.append(repr(current))
286
+ current = part
287
+ else:
288
+ current = candidate
289
+ if current:
290
+ chunks.append(repr(current))
291
+ if len(chunks) == 1:
292
+ write(rep)
293
+ return
294
+ if level == 1:
295
+ write("(")
296
+ for i, rep in enumerate(chunks):
297
+ if i > 0:
298
+ write("\n" + " " * indent)
299
+ write(rep)
300
+ if level == 1:
301
+ write(")")
302
+
303
+ _dispatch[str.__repr__] = _pprint_str
304
+
305
+ def _pprint_bytes(
306
+ self,
307
+ object: Any,
308
+ stream: IO[str],
309
+ indent: int,
310
+ allowance: int,
311
+ context: set[int],
312
+ level: int,
313
+ ) -> None:
314
+ write = stream.write
315
+ if len(object) <= 4:
316
+ write(repr(object))
317
+ return
318
+ parens = level == 1
319
+ if parens:
320
+ indent += 1
321
+ allowance += 1
322
+ write("(")
323
+ delim = ""
324
+ for rep in _wrap_bytes_repr(object, self._width - indent, allowance):
325
+ write(delim)
326
+ write(rep)
327
+ if not delim:
328
+ delim = "\n" + " " * indent
329
+ if parens:
330
+ write(")")
331
+
332
+ _dispatch[bytes.__repr__] = _pprint_bytes
333
+
334
+ def _pprint_bytearray(
335
+ self,
336
+ object: Any,
337
+ stream: IO[str],
338
+ indent: int,
339
+ allowance: int,
340
+ context: set[int],
341
+ level: int,
342
+ ) -> None:
343
+ write = stream.write
344
+ write("bytearray(")
345
+ self._pprint_bytes(
346
+ bytes(object), stream, indent + 10, allowance + 1, context, level + 1
347
+ )
348
+ write(")")
349
+
350
+ _dispatch[bytearray.__repr__] = _pprint_bytearray
351
+
352
+ def _pprint_mappingproxy(
353
+ self,
354
+ object: Any,
355
+ stream: IO[str],
356
+ indent: int,
357
+ allowance: int,
358
+ context: set[int],
359
+ level: int,
360
+ ) -> None:
361
+ stream.write("mappingproxy(")
362
+ self._format(object.copy(), stream, indent, allowance, context, level)
363
+ stream.write(")")
364
+
365
+ _dispatch[_types.MappingProxyType.__repr__] = _pprint_mappingproxy
366
+
367
+ def _pprint_simplenamespace(
368
+ self,
369
+ object: Any,
370
+ stream: IO[str],
371
+ indent: int,
372
+ allowance: int,
373
+ context: set[int],
374
+ level: int,
375
+ ) -> None:
376
+ if type(object) is _types.SimpleNamespace:
377
+ # The SimpleNamespace repr is "namespace" instead of the class
378
+ # name, so we do the same here. For subclasses; use the class name.
379
+ cls_name = "namespace"
380
+ else:
381
+ cls_name = object.__class__.__name__
382
+ items = object.__dict__.items()
383
+ stream.write(cls_name + "(")
384
+ self._format_namespace_items(items, stream, indent, allowance, context, level)
385
+ stream.write(")")
386
+
387
+ _dispatch[_types.SimpleNamespace.__repr__] = _pprint_simplenamespace
388
+
389
+ def _format_dict_items(
390
+ self,
391
+ items: list[tuple[Any, Any]],
392
+ stream: IO[str],
393
+ indent: int,
394
+ allowance: int,
395
+ context: set[int],
396
+ level: int,
397
+ ) -> None:
398
+ if not items:
399
+ return
400
+
401
+ write = stream.write
402
+ item_indent = indent + self._indent_per_level
403
+ delimnl = "\n" + " " * item_indent
404
+ for key, ent in items:
405
+ write(delimnl)
406
+ write(self._repr(key, context, level))
407
+ write(": ")
408
+ self._format(ent, stream, item_indent, 1, context, level)
409
+ write(",")
410
+
411
+ write("\n" + " " * indent)
412
+
413
+ def _format_namespace_items(
414
+ self,
415
+ items: list[tuple[Any, Any]],
416
+ stream: IO[str],
417
+ indent: int,
418
+ allowance: int,
419
+ context: set[int],
420
+ level: int,
421
+ ) -> None:
422
+ if not items:
423
+ return
424
+
425
+ write = stream.write
426
+ item_indent = indent + self._indent_per_level
427
+ delimnl = "\n" + " " * item_indent
428
+ for key, ent in items:
429
+ write(delimnl)
430
+ write(key)
431
+ write("=")
432
+ if id(ent) in context:
433
+ # Special-case representation of recursion to match standard
434
+ # recursive dataclass repr.
435
+ write("...")
436
+ else:
437
+ self._format(
438
+ ent,
439
+ stream,
440
+ item_indent + len(key) + 1,
441
+ 1,
442
+ context,
443
+ level,
444
+ )
445
+
446
+ write(",")
447
+
448
+ write("\n" + " " * indent)
449
+
450
+ def _format_items(
451
+ self,
452
+ items: list[Any],
453
+ stream: IO[str],
454
+ indent: int,
455
+ allowance: int,
456
+ context: set[int],
457
+ level: int,
458
+ ) -> None:
459
+ if not items:
460
+ return
461
+
462
+ write = stream.write
463
+ item_indent = indent + self._indent_per_level
464
+ delimnl = "\n" + " " * item_indent
465
+
466
+ for item in items:
467
+ write(delimnl)
468
+ self._format(item, stream, item_indent, 1, context, level)
469
+ write(",")
470
+
471
+ write("\n" + " " * indent)
472
+
473
+ def _repr(self, object: Any, context: set[int], level: int) -> str:
474
+ return self._safe_repr(object, context.copy(), self._depth, level)
475
+
476
+ def _pprint_default_dict(
477
+ self,
478
+ object: Any,
479
+ stream: IO[str],
480
+ indent: int,
481
+ allowance: int,
482
+ context: set[int],
483
+ level: int,
484
+ ) -> None:
485
+ rdf = self._repr(object.default_factory, context, level)
486
+ stream.write(f"{object.__class__.__name__}({rdf}, ")
487
+ self._pprint_dict(object, stream, indent, allowance, context, level)
488
+ stream.write(")")
489
+
490
+ _dispatch[_collections.defaultdict.__repr__] = _pprint_default_dict
491
+
492
+ def _pprint_counter(
493
+ self,
494
+ object: Any,
495
+ stream: IO[str],
496
+ indent: int,
497
+ allowance: int,
498
+ context: set[int],
499
+ level: int,
500
+ ) -> None:
501
+ stream.write(object.__class__.__name__ + "(")
502
+
503
+ if object:
504
+ stream.write("{")
505
+ items = object.most_common()
506
+ self._format_dict_items(items, stream, indent, allowance, context, level)
507
+ stream.write("}")
508
+
509
+ stream.write(")")
510
+
511
+ _dispatch[_collections.Counter.__repr__] = _pprint_counter
512
+
513
+ def _pprint_chain_map(
514
+ self,
515
+ object: Any,
516
+ stream: IO[str],
517
+ indent: int,
518
+ allowance: int,
519
+ context: set[int],
520
+ level: int,
521
+ ) -> None:
522
+ if not len(object.maps) or (len(object.maps) == 1 and not len(object.maps[0])):
523
+ stream.write(repr(object))
524
+ return
525
+
526
+ stream.write(object.__class__.__name__ + "(")
527
+ self._format_items(object.maps, stream, indent, allowance, context, level)
528
+ stream.write(")")
529
+
530
+ _dispatch[_collections.ChainMap.__repr__] = _pprint_chain_map
531
+
532
+ def _pprint_deque(
533
+ self,
534
+ object: Any,
535
+ stream: IO[str],
536
+ indent: int,
537
+ allowance: int,
538
+ context: set[int],
539
+ level: int,
540
+ ) -> None:
541
+ stream.write(object.__class__.__name__ + "(")
542
+ if object.maxlen is not None:
543
+ stream.write("maxlen=%d, " % object.maxlen)
544
+ stream.write("[")
545
+
546
+ self._format_items(object, stream, indent, allowance + 1, context, level)
547
+ stream.write("])")
548
+
549
+ _dispatch[_collections.deque.__repr__] = _pprint_deque
550
+
551
+ def _pprint_user_dict(
552
+ self,
553
+ object: Any,
554
+ stream: IO[str],
555
+ indent: int,
556
+ allowance: int,
557
+ context: set[int],
558
+ level: int,
559
+ ) -> None:
560
+ self._format(object.data, stream, indent, allowance, context, level - 1)
561
+
562
+ _dispatch[_collections.UserDict.__repr__] = _pprint_user_dict
563
+
564
+ def _pprint_user_list(
565
+ self,
566
+ object: Any,
567
+ stream: IO[str],
568
+ indent: int,
569
+ allowance: int,
570
+ context: set[int],
571
+ level: int,
572
+ ) -> None:
573
+ self._format(object.data, stream, indent, allowance, context, level - 1)
574
+
575
+ _dispatch[_collections.UserList.__repr__] = _pprint_user_list
576
+
577
+ def _pprint_user_string(
578
+ self,
579
+ object: Any,
580
+ stream: IO[str],
581
+ indent: int,
582
+ allowance: int,
583
+ context: set[int],
584
+ level: int,
585
+ ) -> None:
586
+ self._format(object.data, stream, indent, allowance, context, level - 1)
587
+
588
+ _dispatch[_collections.UserString.__repr__] = _pprint_user_string
589
+
590
+ def _safe_repr(
591
+ self, object: Any, context: set[int], maxlevels: int | None, level: int
592
+ ) -> str:
593
+ typ = type(object)
594
+ if typ in _builtin_scalars:
595
+ return repr(object)
596
+
597
+ r = getattr(typ, "__repr__", None)
598
+
599
+ if issubclass(typ, dict) and r is dict.__repr__:
600
+ if not object:
601
+ return "{}"
602
+ objid = id(object)
603
+ if maxlevels and level >= maxlevels:
604
+ return "{...}"
605
+ if objid in context:
606
+ return _recursion(object)
607
+ context.add(objid)
608
+ components: list[str] = []
609
+ append = components.append
610
+ level += 1
611
+ for k, v in sorted(object.items(), key=_safe_tuple):
612
+ krepr = self._safe_repr(k, context, maxlevels, level)
613
+ vrepr = self._safe_repr(v, context, maxlevels, level)
614
+ append(f"{krepr}: {vrepr}")
615
+ context.remove(objid)
616
+ return "{{{}}}".format(", ".join(components))
617
+
618
+ if (issubclass(typ, list) and r is list.__repr__) or (
619
+ issubclass(typ, tuple) and r is tuple.__repr__
620
+ ):
621
+ if issubclass(typ, list):
622
+ if not object:
623
+ return "[]"
624
+ format = "[%s]"
625
+ elif len(object) == 1:
626
+ format = "(%s,)"
627
+ else:
628
+ if not object:
629
+ return "()"
630
+ format = "(%s)"
631
+ objid = id(object)
632
+ if maxlevels and level >= maxlevels:
633
+ return format % "..."
634
+ if objid in context:
635
+ return _recursion(object)
636
+ context.add(objid)
637
+ components = []
638
+ append = components.append
639
+ level += 1
640
+ for o in object:
641
+ orepr = self._safe_repr(o, context, maxlevels, level)
642
+ append(orepr)
643
+ context.remove(objid)
644
+ return format % ", ".join(components)
645
+
646
+ return repr(object)
647
+
648
+
649
+ _builtin_scalars = frozenset(
650
+ {str, bytes, bytearray, float, complex, bool, type(None), int}
651
+ )
652
+
653
+
654
+ def _recursion(object: Any) -> str:
655
+ return f"<Recursion on {type(object).__name__} with id={id(object)}>"
656
+
657
+
658
+ def _wrap_bytes_repr(object: Any, width: int, allowance: int) -> Iterator[str]:
659
+ current = b""
660
+ last = len(object) // 4 * 4
661
+ for i in range(0, len(object), 4):
662
+ part = object[i : i + 4]
663
+ candidate = current + part
664
+ if i == last:
665
+ width -= allowance
666
+ if len(repr(candidate)) > width:
667
+ if current:
668
+ yield repr(current)
669
+ current = part
670
+ else:
671
+ current = candidate
672
+ if current:
673
+ yield repr(current)
vllm/lib/python3.10/site-packages/_pytest/_io/saferepr.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import pprint
4
+ import reprlib
5
+
6
+
7
+ def _try_repr_or_str(obj: object) -> str:
8
+ try:
9
+ return repr(obj)
10
+ except (KeyboardInterrupt, SystemExit):
11
+ raise
12
+ except BaseException:
13
+ return f'{type(obj).__name__}("{obj}")'
14
+
15
+
16
+ def _format_repr_exception(exc: BaseException, obj: object) -> str:
17
+ try:
18
+ exc_info = _try_repr_or_str(exc)
19
+ except (KeyboardInterrupt, SystemExit):
20
+ raise
21
+ except BaseException as inner_exc:
22
+ exc_info = f"unpresentable exception ({_try_repr_or_str(inner_exc)})"
23
+ return (
24
+ f"<[{exc_info} raised in repr()] {type(obj).__name__} object at 0x{id(obj):x}>"
25
+ )
26
+
27
+
28
+ def _ellipsize(s: str, maxsize: int) -> str:
29
+ if len(s) > maxsize:
30
+ i = max(0, (maxsize - 3) // 2)
31
+ j = max(0, maxsize - 3 - i)
32
+ return s[:i] + "..." + s[len(s) - j :]
33
+ return s
34
+
35
+
36
+ class SafeRepr(reprlib.Repr):
37
+ """
38
+ repr.Repr that limits the resulting size of repr() and includes
39
+ information on exceptions raised during the call.
40
+ """
41
+
42
+ def __init__(self, maxsize: int | None, use_ascii: bool = False) -> None:
43
+ """
44
+ :param maxsize:
45
+ If not None, will truncate the resulting repr to that specific size, using ellipsis
46
+ somewhere in the middle to hide the extra text.
47
+ If None, will not impose any size limits on the returning repr.
48
+ """
49
+ super().__init__()
50
+ # ``maxstring`` is used by the superclass, and needs to be an int; using a
51
+ # very large number in case maxsize is None, meaning we want to disable
52
+ # truncation.
53
+ self.maxstring = maxsize if maxsize is not None else 1_000_000_000
54
+ self.maxsize = maxsize
55
+ self.use_ascii = use_ascii
56
+
57
+ def repr(self, x: object) -> str:
58
+ try:
59
+ if self.use_ascii:
60
+ s = ascii(x)
61
+ else:
62
+ s = super().repr(x)
63
+ except (KeyboardInterrupt, SystemExit):
64
+ raise
65
+ except BaseException as exc:
66
+ s = _format_repr_exception(exc, x)
67
+ if self.maxsize is not None:
68
+ s = _ellipsize(s, self.maxsize)
69
+ return s
70
+
71
+ def repr_instance(self, x: object, level: int) -> str:
72
+ try:
73
+ s = repr(x)
74
+ except (KeyboardInterrupt, SystemExit):
75
+ raise
76
+ except BaseException as exc:
77
+ s = _format_repr_exception(exc, x)
78
+ if self.maxsize is not None:
79
+ s = _ellipsize(s, self.maxsize)
80
+ return s
81
+
82
+
83
+ def safeformat(obj: object) -> str:
84
+ """Return a pretty printed string for the given object.
85
+
86
+ Failing __repr__ functions of user instances will be represented
87
+ with a short exception info.
88
+ """
89
+ try:
90
+ return pprint.pformat(obj)
91
+ except Exception as exc:
92
+ return _format_repr_exception(exc, obj)
93
+
94
+
95
+ # Maximum size of overall repr of objects to display during assertion errors.
96
+ DEFAULT_REPR_MAX_SIZE = 240
97
+
98
+
99
+ def saferepr(
100
+ obj: object, maxsize: int | None = DEFAULT_REPR_MAX_SIZE, use_ascii: bool = False
101
+ ) -> str:
102
+ """Return a size-limited safe repr-string for the given object.
103
+
104
+ Failing __repr__ functions of user instances will be represented
105
+ with a short exception info and 'saferepr' generally takes
106
+ care to never raise exceptions itself.
107
+
108
+ This function is a wrapper around the Repr/reprlib functionality of the
109
+ stdlib.
110
+ """
111
+ return SafeRepr(maxsize, use_ascii).repr(obj)
112
+
113
+
114
+ def saferepr_unlimited(obj: object, use_ascii: bool = True) -> str:
115
+ """Return an unlimited-size safe repr-string for the given object.
116
+
117
+ As with saferepr, failing __repr__ functions of user instances
118
+ will be represented with a short exception info.
119
+
120
+ This function is a wrapper around simple repr.
121
+
122
+ Note: a cleaner solution would be to alter ``saferepr``this way
123
+ when maxsize=None, but that might affect some other code.
124
+ """
125
+ try:
126
+ if use_ascii:
127
+ return ascii(obj)
128
+ return repr(obj)
129
+ except Exception as exc:
130
+ return _format_repr_exception(exc, obj)
vllm/lib/python3.10/site-packages/_pytest/_io/terminalwriter.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helper functions for writing to terminals and files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import sys
8
+ from typing import final
9
+ from typing import Literal
10
+ from typing import Sequence
11
+ from typing import TextIO
12
+ from typing import TYPE_CHECKING
13
+
14
+ from ..compat import assert_never
15
+ from .wcwidth import wcswidth
16
+
17
+
18
+ if TYPE_CHECKING:
19
+ from pygments.formatter import Formatter
20
+ from pygments.lexer import Lexer
21
+
22
+
23
+ # This code was initially copied from py 1.8.1, file _io/terminalwriter.py.
24
+
25
+
26
+ def get_terminal_width() -> int:
27
+ width, _ = shutil.get_terminal_size(fallback=(80, 24))
28
+
29
+ # The Windows get_terminal_size may be bogus, let's sanify a bit.
30
+ if width < 40:
31
+ width = 80
32
+
33
+ return width
34
+
35
+
36
+ def should_do_markup(file: TextIO) -> bool:
37
+ if os.environ.get("PY_COLORS") == "1":
38
+ return True
39
+ if os.environ.get("PY_COLORS") == "0":
40
+ return False
41
+ if os.environ.get("NO_COLOR"):
42
+ return False
43
+ if os.environ.get("FORCE_COLOR"):
44
+ return True
45
+ return (
46
+ hasattr(file, "isatty") and file.isatty() and os.environ.get("TERM") != "dumb"
47
+ )
48
+
49
+
50
+ @final
51
+ class TerminalWriter:
52
+ _esctable = dict(
53
+ black=30,
54
+ red=31,
55
+ green=32,
56
+ yellow=33,
57
+ blue=34,
58
+ purple=35,
59
+ cyan=36,
60
+ white=37,
61
+ Black=40,
62
+ Red=41,
63
+ Green=42,
64
+ Yellow=43,
65
+ Blue=44,
66
+ Purple=45,
67
+ Cyan=46,
68
+ White=47,
69
+ bold=1,
70
+ light=2,
71
+ blink=5,
72
+ invert=7,
73
+ )
74
+
75
+ def __init__(self, file: TextIO | None = None) -> None:
76
+ if file is None:
77
+ file = sys.stdout
78
+ if hasattr(file, "isatty") and file.isatty() and sys.platform == "win32":
79
+ try:
80
+ import colorama
81
+ except ImportError:
82
+ pass
83
+ else:
84
+ file = colorama.AnsiToWin32(file).stream
85
+ assert file is not None
86
+ self._file = file
87
+ self.hasmarkup = should_do_markup(file)
88
+ self._current_line = ""
89
+ self._terminal_width: int | None = None
90
+ self.code_highlight = True
91
+
92
+ @property
93
+ def fullwidth(self) -> int:
94
+ if self._terminal_width is not None:
95
+ return self._terminal_width
96
+ return get_terminal_width()
97
+
98
+ @fullwidth.setter
99
+ def fullwidth(self, value: int) -> None:
100
+ self._terminal_width = value
101
+
102
+ @property
103
+ def width_of_current_line(self) -> int:
104
+ """Return an estimate of the width so far in the current line."""
105
+ return wcswidth(self._current_line)
106
+
107
+ def markup(self, text: str, **markup: bool) -> str:
108
+ for name in markup:
109
+ if name not in self._esctable:
110
+ raise ValueError(f"unknown markup: {name!r}")
111
+ if self.hasmarkup:
112
+ esc = [self._esctable[name] for name, on in markup.items() if on]
113
+ if esc:
114
+ text = "".join(f"\x1b[{cod}m" for cod in esc) + text + "\x1b[0m"
115
+ return text
116
+
117
+ def sep(
118
+ self,
119
+ sepchar: str,
120
+ title: str | None = None,
121
+ fullwidth: int | None = None,
122
+ **markup: bool,
123
+ ) -> None:
124
+ if fullwidth is None:
125
+ fullwidth = self.fullwidth
126
+ # The goal is to have the line be as long as possible
127
+ # under the condition that len(line) <= fullwidth.
128
+ if sys.platform == "win32":
129
+ # If we print in the last column on windows we are on a
130
+ # new line but there is no way to verify/neutralize this
131
+ # (we may not know the exact line width).
132
+ # So let's be defensive to avoid empty lines in the output.
133
+ fullwidth -= 1
134
+ if title is not None:
135
+ # we want 2 + 2*len(fill) + len(title) <= fullwidth
136
+ # i.e. 2 + 2*len(sepchar)*N + len(title) <= fullwidth
137
+ # 2*len(sepchar)*N <= fullwidth - len(title) - 2
138
+ # N <= (fullwidth - len(title) - 2) // (2*len(sepchar))
139
+ N = max((fullwidth - len(title) - 2) // (2 * len(sepchar)), 1)
140
+ fill = sepchar * N
141
+ line = f"{fill} {title} {fill}"
142
+ else:
143
+ # we want len(sepchar)*N <= fullwidth
144
+ # i.e. N <= fullwidth // len(sepchar)
145
+ line = sepchar * (fullwidth // len(sepchar))
146
+ # In some situations there is room for an extra sepchar at the right,
147
+ # in particular if we consider that with a sepchar like "_ " the
148
+ # trailing space is not important at the end of the line.
149
+ if len(line) + len(sepchar.rstrip()) <= fullwidth:
150
+ line += sepchar.rstrip()
151
+
152
+ self.line(line, **markup)
153
+
154
+ def write(self, msg: str, *, flush: bool = False, **markup: bool) -> None:
155
+ if msg:
156
+ current_line = msg.rsplit("\n", 1)[-1]
157
+ if "\n" in msg:
158
+ self._current_line = current_line
159
+ else:
160
+ self._current_line += current_line
161
+
162
+ msg = self.markup(msg, **markup)
163
+
164
+ try:
165
+ self._file.write(msg)
166
+ except UnicodeEncodeError:
167
+ # Some environments don't support printing general Unicode
168
+ # strings, due to misconfiguration or otherwise; in that case,
169
+ # print the string escaped to ASCII.
170
+ # When the Unicode situation improves we should consider
171
+ # letting the error propagate instead of masking it (see #7475
172
+ # for one brief attempt).
173
+ msg = msg.encode("unicode-escape").decode("ascii")
174
+ self._file.write(msg)
175
+
176
+ if flush:
177
+ self.flush()
178
+
179
+ def line(self, s: str = "", **markup: bool) -> None:
180
+ self.write(s, **markup)
181
+ self.write("\n")
182
+
183
+ def flush(self) -> None:
184
+ self._file.flush()
185
+
186
+ def _write_source(self, lines: Sequence[str], indents: Sequence[str] = ()) -> None:
187
+ """Write lines of source code possibly highlighted.
188
+
189
+ Keeping this private for now because the API is clunky. We should discuss how
190
+ to evolve the terminal writer so we can have more precise color support, for example
191
+ being able to write part of a line in one color and the rest in another, and so on.
192
+ """
193
+ if indents and len(indents) != len(lines):
194
+ raise ValueError(
195
+ f"indents size ({len(indents)}) should have same size as lines ({len(lines)})"
196
+ )
197
+ if not indents:
198
+ indents = [""] * len(lines)
199
+ source = "\n".join(lines)
200
+ new_lines = self._highlight(source).splitlines()
201
+ for indent, new_line in zip(indents, new_lines):
202
+ self.line(indent + new_line)
203
+
204
+ def _get_pygments_lexer(self, lexer: Literal["python", "diff"]) -> Lexer | None:
205
+ try:
206
+ if lexer == "python":
207
+ from pygments.lexers.python import PythonLexer
208
+
209
+ return PythonLexer()
210
+ elif lexer == "diff":
211
+ from pygments.lexers.diff import DiffLexer
212
+
213
+ return DiffLexer()
214
+ else:
215
+ assert_never(lexer)
216
+ except ModuleNotFoundError:
217
+ return None
218
+
219
+ def _get_pygments_formatter(self) -> Formatter | None:
220
+ try:
221
+ import pygments.util
222
+ except ModuleNotFoundError:
223
+ return None
224
+
225
+ from _pytest.config.exceptions import UsageError
226
+
227
+ theme = os.getenv("PYTEST_THEME")
228
+ theme_mode = os.getenv("PYTEST_THEME_MODE", "dark")
229
+
230
+ try:
231
+ from pygments.formatters.terminal import TerminalFormatter
232
+
233
+ return TerminalFormatter(bg=theme_mode, style=theme)
234
+
235
+ except pygments.util.ClassNotFound as e:
236
+ raise UsageError(
237
+ f"PYTEST_THEME environment variable has an invalid value: '{theme}'. "
238
+ "Hint: See available pygments styles with `pygmentize -L styles`."
239
+ ) from e
240
+ except pygments.util.OptionError as e:
241
+ raise UsageError(
242
+ f"PYTEST_THEME_MODE environment variable has an invalid value: '{theme_mode}'. "
243
+ "The allowed values are 'dark' (default) and 'light'."
244
+ ) from e
245
+
246
+ def _highlight(
247
+ self, source: str, lexer: Literal["diff", "python"] = "python"
248
+ ) -> str:
249
+ """Highlight the given source if we have markup support."""
250
+ if not source or not self.hasmarkup or not self.code_highlight:
251
+ return source
252
+
253
+ pygments_lexer = self._get_pygments_lexer(lexer)
254
+ if pygments_lexer is None:
255
+ return source
256
+
257
+ pygments_formatter = self._get_pygments_formatter()
258
+ if pygments_formatter is None:
259
+ return source
260
+
261
+ from pygments import highlight
262
+
263
+ highlighted: str = highlight(source, pygments_lexer, pygments_formatter)
264
+ # pygments terminal formatter may add a newline when there wasn't one.
265
+ # We don't want this, remove.
266
+ if highlighted[-1] == "\n" and source[-1] != "\n":
267
+ highlighted = highlighted[:-1]
268
+
269
+ # Some lexers will not set the initial color explicitly
270
+ # which may lead to the previous color being propagated to the
271
+ # start of the expression, so reset first.
272
+ highlighted = "\x1b[0m" + highlighted
273
+
274
+ return highlighted
vllm/lib/python3.10/site-packages/_pytest/_version.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # file generated by setuptools_scm
2
+ # don't change, don't track in version control
3
+ TYPE_CHECKING = False
4
+ if TYPE_CHECKING:
5
+ from typing import Tuple, Union
6
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
7
+ else:
8
+ VERSION_TUPLE = object
9
+
10
+ version: str
11
+ __version__: str
12
+ __version_tuple__: VERSION_TUPLE
13
+ version_tuple: VERSION_TUPLE
14
+
15
+ __version__ = version = '8.3.4'
16
+ __version_tuple__ = version_tuple = (8, 3, 4)
vllm/lib/python3.10/site-packages/_pytest/cacheprovider.py ADDED
@@ -0,0 +1,626 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """Implementation of the cache provider."""
3
+
4
+ # This plugin was not named "cache" to avoid conflicts with the external
5
+ # pytest-cache version.
6
+ from __future__ import annotations
7
+
8
+ import dataclasses
9
+ import errno
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+ import tempfile
14
+ from typing import final
15
+ from typing import Generator
16
+ from typing import Iterable
17
+
18
+ from .pathlib import resolve_from_str
19
+ from .pathlib import rm_rf
20
+ from .reports import CollectReport
21
+ from _pytest import nodes
22
+ from _pytest._io import TerminalWriter
23
+ from _pytest.config import Config
24
+ from _pytest.config import ExitCode
25
+ from _pytest.config import hookimpl
26
+ from _pytest.config.argparsing import Parser
27
+ from _pytest.deprecated import check_ispytest
28
+ from _pytest.fixtures import fixture
29
+ from _pytest.fixtures import FixtureRequest
30
+ from _pytest.main import Session
31
+ from _pytest.nodes import Directory
32
+ from _pytest.nodes import File
33
+ from _pytest.reports import TestReport
34
+
35
+
36
+ README_CONTENT = """\
37
+ # pytest cache directory #
38
+
39
+ This directory contains data from the pytest's cache plugin,
40
+ which provides the `--lf` and `--ff` options, as well as the `cache` fixture.
41
+
42
+ **Do not** commit this to version control.
43
+
44
+ See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information.
45
+ """
46
+
47
+ CACHEDIR_TAG_CONTENT = b"""\
48
+ Signature: 8a477f597d28d172789f06886806bc55
49
+ # This file is a cache directory tag created by pytest.
50
+ # For information about cache directory tags, see:
51
+ # https://bford.info/cachedir/spec.html
52
+ """
53
+
54
+
55
+ @final
56
+ @dataclasses.dataclass
57
+ class Cache:
58
+ """Instance of the `cache` fixture."""
59
+
60
+ _cachedir: Path = dataclasses.field(repr=False)
61
+ _config: Config = dataclasses.field(repr=False)
62
+
63
+ # Sub-directory under cache-dir for directories created by `mkdir()`.
64
+ _CACHE_PREFIX_DIRS = "d"
65
+
66
+ # Sub-directory under cache-dir for values created by `set()`.
67
+ _CACHE_PREFIX_VALUES = "v"
68
+
69
+ def __init__(
70
+ self, cachedir: Path, config: Config, *, _ispytest: bool = False
71
+ ) -> None:
72
+ check_ispytest(_ispytest)
73
+ self._cachedir = cachedir
74
+ self._config = config
75
+
76
+ @classmethod
77
+ def for_config(cls, config: Config, *, _ispytest: bool = False) -> Cache:
78
+ """Create the Cache instance for a Config.
79
+
80
+ :meta private:
81
+ """
82
+ check_ispytest(_ispytest)
83
+ cachedir = cls.cache_dir_from_config(config, _ispytest=True)
84
+ if config.getoption("cacheclear") and cachedir.is_dir():
85
+ cls.clear_cache(cachedir, _ispytest=True)
86
+ return cls(cachedir, config, _ispytest=True)
87
+
88
+ @classmethod
89
+ def clear_cache(cls, cachedir: Path, _ispytest: bool = False) -> None:
90
+ """Clear the sub-directories used to hold cached directories and values.
91
+
92
+ :meta private:
93
+ """
94
+ check_ispytest(_ispytest)
95
+ for prefix in (cls._CACHE_PREFIX_DIRS, cls._CACHE_PREFIX_VALUES):
96
+ d = cachedir / prefix
97
+ if d.is_dir():
98
+ rm_rf(d)
99
+
100
+ @staticmethod
101
+ def cache_dir_from_config(config: Config, *, _ispytest: bool = False) -> Path:
102
+ """Get the path to the cache directory for a Config.
103
+
104
+ :meta private:
105
+ """
106
+ check_ispytest(_ispytest)
107
+ return resolve_from_str(config.getini("cache_dir"), config.rootpath)
108
+
109
+ def warn(self, fmt: str, *, _ispytest: bool = False, **args: object) -> None:
110
+ """Issue a cache warning.
111
+
112
+ :meta private:
113
+ """
114
+ check_ispytest(_ispytest)
115
+ import warnings
116
+
117
+ from _pytest.warning_types import PytestCacheWarning
118
+
119
+ warnings.warn(
120
+ PytestCacheWarning(fmt.format(**args) if args else fmt),
121
+ self._config.hook,
122
+ stacklevel=3,
123
+ )
124
+
125
+ def _mkdir(self, path: Path) -> None:
126
+ self._ensure_cache_dir_and_supporting_files()
127
+ path.mkdir(exist_ok=True, parents=True)
128
+
129
+ def mkdir(self, name: str) -> Path:
130
+ """Return a directory path object with the given name.
131
+
132
+ If the directory does not yet exist, it will be created. You can use
133
+ it to manage files to e.g. store/retrieve database dumps across test
134
+ sessions.
135
+
136
+ .. versionadded:: 7.0
137
+
138
+ :param name:
139
+ Must be a string not containing a ``/`` separator.
140
+ Make sure the name contains your plugin or application
141
+ identifiers to prevent clashes with other cache users.
142
+ """
143
+ path = Path(name)
144
+ if len(path.parts) > 1:
145
+ raise ValueError("name is not allowed to contain path separators")
146
+ res = self._cachedir.joinpath(self._CACHE_PREFIX_DIRS, path)
147
+ self._mkdir(res)
148
+ return res
149
+
150
+ def _getvaluepath(self, key: str) -> Path:
151
+ return self._cachedir.joinpath(self._CACHE_PREFIX_VALUES, Path(key))
152
+
153
+ def get(self, key: str, default):
154
+ """Return the cached value for the given key.
155
+
156
+ If no value was yet cached or the value cannot be read, the specified
157
+ default is returned.
158
+
159
+ :param key:
160
+ Must be a ``/`` separated value. Usually the first
161
+ name is the name of your plugin or your application.
162
+ :param default:
163
+ The value to return in case of a cache-miss or invalid cache value.
164
+ """
165
+ path = self._getvaluepath(key)
166
+ try:
167
+ with path.open("r", encoding="UTF-8") as f:
168
+ return json.load(f)
169
+ except (ValueError, OSError):
170
+ return default
171
+
172
+ def set(self, key: str, value: object) -> None:
173
+ """Save value for the given key.
174
+
175
+ :param key:
176
+ Must be a ``/`` separated value. Usually the first
177
+ name is the name of your plugin or your application.
178
+ :param value:
179
+ Must be of any combination of basic python types,
180
+ including nested types like lists of dictionaries.
181
+ """
182
+ path = self._getvaluepath(key)
183
+ try:
184
+ self._mkdir(path.parent)
185
+ except OSError as exc:
186
+ self.warn(
187
+ f"could not create cache path {path}: {exc}",
188
+ _ispytest=True,
189
+ )
190
+ return
191
+ data = json.dumps(value, ensure_ascii=False, indent=2)
192
+ try:
193
+ f = path.open("w", encoding="UTF-8")
194
+ except OSError as exc:
195
+ self.warn(
196
+ f"cache could not write path {path}: {exc}",
197
+ _ispytest=True,
198
+ )
199
+ else:
200
+ with f:
201
+ f.write(data)
202
+
203
+ def _ensure_cache_dir_and_supporting_files(self) -> None:
204
+ """Create the cache dir and its supporting files."""
205
+ if self._cachedir.is_dir():
206
+ return
207
+
208
+ self._cachedir.parent.mkdir(parents=True, exist_ok=True)
209
+ with tempfile.TemporaryDirectory(
210
+ prefix="pytest-cache-files-",
211
+ dir=self._cachedir.parent,
212
+ ) as newpath:
213
+ path = Path(newpath)
214
+
215
+ # Reset permissions to the default, see #12308.
216
+ # Note: there's no way to get the current umask atomically, eek.
217
+ umask = os.umask(0o022)
218
+ os.umask(umask)
219
+ path.chmod(0o777 - umask)
220
+
221
+ with open(path.joinpath("README.md"), "x", encoding="UTF-8") as f:
222
+ f.write(README_CONTENT)
223
+ with open(path.joinpath(".gitignore"), "x", encoding="UTF-8") as f:
224
+ f.write("# Created by pytest automatically.\n*\n")
225
+ with open(path.joinpath("CACHEDIR.TAG"), "xb") as f:
226
+ f.write(CACHEDIR_TAG_CONTENT)
227
+
228
+ try:
229
+ path.rename(self._cachedir)
230
+ except OSError as e:
231
+ # If 2 concurrent pytests both race to the rename, the loser
232
+ # gets "Directory not empty" from the rename. In this case,
233
+ # everything is handled so just continue (while letting the
234
+ # temporary directory be cleaned up).
235
+ # On Windows, the error is a FileExistsError which translates to EEXIST.
236
+ if e.errno not in (errno.ENOTEMPTY, errno.EEXIST):
237
+ raise
238
+ else:
239
+ # Create a directory in place of the one we just moved so that
240
+ # `TemporaryDirectory`'s cleanup doesn't complain.
241
+ #
242
+ # TODO: pass ignore_cleanup_errors=True when we no longer support python < 3.10.
243
+ # See https://github.com/python/cpython/issues/74168. Note that passing
244
+ # delete=False would do the wrong thing in case of errors and isn't supported
245
+ # until python 3.12.
246
+ path.mkdir()
247
+
248
+
249
+ class LFPluginCollWrapper:
250
+ def __init__(self, lfplugin: LFPlugin) -> None:
251
+ self.lfplugin = lfplugin
252
+ self._collected_at_least_one_failure = False
253
+
254
+ @hookimpl(wrapper=True)
255
+ def pytest_make_collect_report(
256
+ self, collector: nodes.Collector
257
+ ) -> Generator[None, CollectReport, CollectReport]:
258
+ res = yield
259
+ if isinstance(collector, (Session, Directory)):
260
+ # Sort any lf-paths to the beginning.
261
+ lf_paths = self.lfplugin._last_failed_paths
262
+
263
+ # Use stable sort to prioritize last failed.
264
+ def sort_key(node: nodes.Item | nodes.Collector) -> bool:
265
+ return node.path in lf_paths
266
+
267
+ res.result = sorted(
268
+ res.result,
269
+ key=sort_key,
270
+ reverse=True,
271
+ )
272
+
273
+ elif isinstance(collector, File):
274
+ if collector.path in self.lfplugin._last_failed_paths:
275
+ result = res.result
276
+ lastfailed = self.lfplugin.lastfailed
277
+
278
+ # Only filter with known failures.
279
+ if not self._collected_at_least_one_failure:
280
+ if not any(x.nodeid in lastfailed for x in result):
281
+ return res
282
+ self.lfplugin.config.pluginmanager.register(
283
+ LFPluginCollSkipfiles(self.lfplugin), "lfplugin-collskip"
284
+ )
285
+ self._collected_at_least_one_failure = True
286
+
287
+ session = collector.session
288
+ result[:] = [
289
+ x
290
+ for x in result
291
+ if x.nodeid in lastfailed
292
+ # Include any passed arguments (not trivial to filter).
293
+ or session.isinitpath(x.path)
294
+ # Keep all sub-collectors.
295
+ or isinstance(x, nodes.Collector)
296
+ ]
297
+
298
+ return res
299
+
300
+
301
+ class LFPluginCollSkipfiles:
302
+ def __init__(self, lfplugin: LFPlugin) -> None:
303
+ self.lfplugin = lfplugin
304
+
305
+ @hookimpl
306
+ def pytest_make_collect_report(
307
+ self, collector: nodes.Collector
308
+ ) -> CollectReport | None:
309
+ if isinstance(collector, File):
310
+ if collector.path not in self.lfplugin._last_failed_paths:
311
+ self.lfplugin._skipped_files += 1
312
+
313
+ return CollectReport(
314
+ collector.nodeid, "passed", longrepr=None, result=[]
315
+ )
316
+ return None
317
+
318
+
319
+ class LFPlugin:
320
+ """Plugin which implements the --lf (run last-failing) option."""
321
+
322
+ def __init__(self, config: Config) -> None:
323
+ self.config = config
324
+ active_keys = "lf", "failedfirst"
325
+ self.active = any(config.getoption(key) for key in active_keys)
326
+ assert config.cache
327
+ self.lastfailed: dict[str, bool] = config.cache.get("cache/lastfailed", {})
328
+ self._previously_failed_count: int | None = None
329
+ self._report_status: str | None = None
330
+ self._skipped_files = 0 # count skipped files during collection due to --lf
331
+
332
+ if config.getoption("lf"):
333
+ self._last_failed_paths = self.get_last_failed_paths()
334
+ config.pluginmanager.register(
335
+ LFPluginCollWrapper(self), "lfplugin-collwrapper"
336
+ )
337
+
338
+ def get_last_failed_paths(self) -> set[Path]:
339
+ """Return a set with all Paths of the previously failed nodeids and
340
+ their parents."""
341
+ rootpath = self.config.rootpath
342
+ result = set()
343
+ for nodeid in self.lastfailed:
344
+ path = rootpath / nodeid.split("::")[0]
345
+ result.add(path)
346
+ result.update(path.parents)
347
+ return {x for x in result if x.exists()}
348
+
349
+ def pytest_report_collectionfinish(self) -> str | None:
350
+ if self.active and self.config.get_verbosity() >= 0:
351
+ return f"run-last-failure: {self._report_status}"
352
+ return None
353
+
354
+ def pytest_runtest_logreport(self, report: TestReport) -> None:
355
+ if (report.when == "call" and report.passed) or report.skipped:
356
+ self.lastfailed.pop(report.nodeid, None)
357
+ elif report.failed:
358
+ self.lastfailed[report.nodeid] = True
359
+
360
+ def pytest_collectreport(self, report: CollectReport) -> None:
361
+ passed = report.outcome in ("passed", "skipped")
362
+ if passed:
363
+ if report.nodeid in self.lastfailed:
364
+ self.lastfailed.pop(report.nodeid)
365
+ self.lastfailed.update((item.nodeid, True) for item in report.result)
366
+ else:
367
+ self.lastfailed[report.nodeid] = True
368
+
369
+ @hookimpl(wrapper=True, tryfirst=True)
370
+ def pytest_collection_modifyitems(
371
+ self, config: Config, items: list[nodes.Item]
372
+ ) -> Generator[None]:
373
+ res = yield
374
+
375
+ if not self.active:
376
+ return res
377
+
378
+ if self.lastfailed:
379
+ previously_failed = []
380
+ previously_passed = []
381
+ for item in items:
382
+ if item.nodeid in self.lastfailed:
383
+ previously_failed.append(item)
384
+ else:
385
+ previously_passed.append(item)
386
+ self._previously_failed_count = len(previously_failed)
387
+
388
+ if not previously_failed:
389
+ # Running a subset of all tests with recorded failures
390
+ # only outside of it.
391
+ self._report_status = "%d known failures not in selected tests" % (
392
+ len(self.lastfailed),
393
+ )
394
+ else:
395
+ if self.config.getoption("lf"):
396
+ items[:] = previously_failed
397
+ config.hook.pytest_deselected(items=previously_passed)
398
+ else: # --failedfirst
399
+ items[:] = previously_failed + previously_passed
400
+
401
+ noun = "failure" if self._previously_failed_count == 1 else "failures"
402
+ suffix = " first" if self.config.getoption("failedfirst") else ""
403
+ self._report_status = (
404
+ f"rerun previous {self._previously_failed_count} {noun}{suffix}"
405
+ )
406
+
407
+ if self._skipped_files > 0:
408
+ files_noun = "file" if self._skipped_files == 1 else "files"
409
+ self._report_status += f" (skipped {self._skipped_files} {files_noun})"
410
+ else:
411
+ self._report_status = "no previously failed tests, "
412
+ if self.config.getoption("last_failed_no_failures") == "none":
413
+ self._report_status += "deselecting all items."
414
+ config.hook.pytest_deselected(items=items[:])
415
+ items[:] = []
416
+ else:
417
+ self._report_status += "not deselecting items."
418
+
419
+ return res
420
+
421
+ def pytest_sessionfinish(self, session: Session) -> None:
422
+ config = self.config
423
+ if config.getoption("cacheshow") or hasattr(config, "workerinput"):
424
+ return
425
+
426
+ assert config.cache is not None
427
+ saved_lastfailed = config.cache.get("cache/lastfailed", {})
428
+ if saved_lastfailed != self.lastfailed:
429
+ config.cache.set("cache/lastfailed", self.lastfailed)
430
+
431
+
432
+ class NFPlugin:
433
+ """Plugin which implements the --nf (run new-first) option."""
434
+
435
+ def __init__(self, config: Config) -> None:
436
+ self.config = config
437
+ self.active = config.option.newfirst
438
+ assert config.cache is not None
439
+ self.cached_nodeids = set(config.cache.get("cache/nodeids", []))
440
+
441
+ @hookimpl(wrapper=True, tryfirst=True)
442
+ def pytest_collection_modifyitems(self, items: list[nodes.Item]) -> Generator[None]:
443
+ res = yield
444
+
445
+ if self.active:
446
+ new_items: dict[str, nodes.Item] = {}
447
+ other_items: dict[str, nodes.Item] = {}
448
+ for item in items:
449
+ if item.nodeid not in self.cached_nodeids:
450
+ new_items[item.nodeid] = item
451
+ else:
452
+ other_items[item.nodeid] = item
453
+
454
+ items[:] = self._get_increasing_order(
455
+ new_items.values()
456
+ ) + self._get_increasing_order(other_items.values())
457
+ self.cached_nodeids.update(new_items)
458
+ else:
459
+ self.cached_nodeids.update(item.nodeid for item in items)
460
+
461
+ return res
462
+
463
+ def _get_increasing_order(self, items: Iterable[nodes.Item]) -> list[nodes.Item]:
464
+ return sorted(items, key=lambda item: item.path.stat().st_mtime, reverse=True)
465
+
466
+ def pytest_sessionfinish(self) -> None:
467
+ config = self.config
468
+ if config.getoption("cacheshow") or hasattr(config, "workerinput"):
469
+ return
470
+
471
+ if config.getoption("collectonly"):
472
+ return
473
+
474
+ assert config.cache is not None
475
+ config.cache.set("cache/nodeids", sorted(self.cached_nodeids))
476
+
477
+
478
+ def pytest_addoption(parser: Parser) -> None:
479
+ group = parser.getgroup("general")
480
+ group.addoption(
481
+ "--lf",
482
+ "--last-failed",
483
+ action="store_true",
484
+ dest="lf",
485
+ help="Rerun only the tests that failed "
486
+ "at the last run (or all if none failed)",
487
+ )
488
+ group.addoption(
489
+ "--ff",
490
+ "--failed-first",
491
+ action="store_true",
492
+ dest="failedfirst",
493
+ help="Run all tests, but run the last failures first. "
494
+ "This may re-order tests and thus lead to "
495
+ "repeated fixture setup/teardown.",
496
+ )
497
+ group.addoption(
498
+ "--nf",
499
+ "--new-first",
500
+ action="store_true",
501
+ dest="newfirst",
502
+ help="Run tests from new files first, then the rest of the tests "
503
+ "sorted by file mtime",
504
+ )
505
+ group.addoption(
506
+ "--cache-show",
507
+ action="append",
508
+ nargs="?",
509
+ dest="cacheshow",
510
+ help=(
511
+ "Show cache contents, don't perform collection or tests. "
512
+ "Optional argument: glob (default: '*')."
513
+ ),
514
+ )
515
+ group.addoption(
516
+ "--cache-clear",
517
+ action="store_true",
518
+ dest="cacheclear",
519
+ help="Remove all cache contents at start of test run",
520
+ )
521
+ cache_dir_default = ".pytest_cache"
522
+ if "TOX_ENV_DIR" in os.environ:
523
+ cache_dir_default = os.path.join(os.environ["TOX_ENV_DIR"], cache_dir_default)
524
+ parser.addini("cache_dir", default=cache_dir_default, help="Cache directory path")
525
+ group.addoption(
526
+ "--lfnf",
527
+ "--last-failed-no-failures",
528
+ action="store",
529
+ dest="last_failed_no_failures",
530
+ choices=("all", "none"),
531
+ default="all",
532
+ help="With ``--lf``, determines whether to execute tests when there "
533
+ "are no previously (known) failures or when no "
534
+ "cached ``lastfailed`` data was found. "
535
+ "``all`` (the default) runs the full test suite again. "
536
+ "``none`` just emits a message about no known failures and exits successfully.",
537
+ )
538
+
539
+
540
+ def pytest_cmdline_main(config: Config) -> int | ExitCode | None:
541
+ if config.option.cacheshow and not config.option.help:
542
+ from _pytest.main import wrap_session
543
+
544
+ return wrap_session(config, cacheshow)
545
+ return None
546
+
547
+
548
+ @hookimpl(tryfirst=True)
549
+ def pytest_configure(config: Config) -> None:
550
+ config.cache = Cache.for_config(config, _ispytest=True)
551
+ config.pluginmanager.register(LFPlugin(config), "lfplugin")
552
+ config.pluginmanager.register(NFPlugin(config), "nfplugin")
553
+
554
+
555
+ @fixture
556
+ def cache(request: FixtureRequest) -> Cache:
557
+ """Return a cache object that can persist state between testing sessions.
558
+
559
+ cache.get(key, default)
560
+ cache.set(key, value)
561
+
562
+ Keys must be ``/`` separated strings, where the first part is usually the
563
+ name of your plugin or application to avoid clashes with other cache users.
564
+
565
+ Values can be any object handled by the json stdlib module.
566
+ """
567
+ assert request.config.cache is not None
568
+ return request.config.cache
569
+
570
+
571
+ def pytest_report_header(config: Config) -> str | None:
572
+ """Display cachedir with --cache-show and if non-default."""
573
+ if config.option.verbose > 0 or config.getini("cache_dir") != ".pytest_cache":
574
+ assert config.cache is not None
575
+ cachedir = config.cache._cachedir
576
+ # TODO: evaluate generating upward relative paths
577
+ # starting with .., ../.. if sensible
578
+
579
+ try:
580
+ displaypath = cachedir.relative_to(config.rootpath)
581
+ except ValueError:
582
+ displaypath = cachedir
583
+ return f"cachedir: {displaypath}"
584
+ return None
585
+
586
+
587
+ def cacheshow(config: Config, session: Session) -> int:
588
+ from pprint import pformat
589
+
590
+ assert config.cache is not None
591
+
592
+ tw = TerminalWriter()
593
+ tw.line("cachedir: " + str(config.cache._cachedir))
594
+ if not config.cache._cachedir.is_dir():
595
+ tw.line("cache is empty")
596
+ return 0
597
+
598
+ glob = config.option.cacheshow[0]
599
+ if glob is None:
600
+ glob = "*"
601
+
602
+ dummy = object()
603
+ basedir = config.cache._cachedir
604
+ vdir = basedir / Cache._CACHE_PREFIX_VALUES
605
+ tw.sep("-", f"cache values for {glob!r}")
606
+ for valpath in sorted(x for x in vdir.rglob(glob) if x.is_file()):
607
+ key = str(valpath.relative_to(vdir))
608
+ val = config.cache.get(key, dummy)
609
+ if val is dummy:
610
+ tw.line(f"{key} contains unreadable content, will be ignored")
611
+ else:
612
+ tw.line(f"{key} contains:")
613
+ for line in pformat(val).splitlines():
614
+ tw.line(" " + line)
615
+
616
+ ddir = basedir / Cache._CACHE_PREFIX_DIRS
617
+ if ddir.is_dir():
618
+ contents = sorted(ddir.rglob(glob))
619
+ tw.sep("-", f"cache directories for {glob!r}")
620
+ for p in contents:
621
+ # if p.is_dir():
622
+ # print("%s/" % p.relative_to(basedir))
623
+ if p.is_file():
624
+ key = str(p.relative_to(basedir))
625
+ tw.line(f"{key} is a file of length {p.stat().st_size:d}")
626
+ return 0
vllm/lib/python3.10/site-packages/_pytest/compat.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """Python version compatibility code."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import dataclasses
7
+ import enum
8
+ import functools
9
+ import inspect
10
+ from inspect import Parameter
11
+ from inspect import signature
12
+ import os
13
+ from pathlib import Path
14
+ import sys
15
+ from typing import Any
16
+ from typing import Callable
17
+ from typing import Final
18
+ from typing import NoReturn
19
+
20
+ import py
21
+
22
+
23
+ #: constant to prepare valuing pylib path replacements/lazy proxies later on
24
+ # intended for removal in pytest 8.0 or 9.0
25
+
26
+ # fmt: off
27
+ # intentional space to create a fake difference for the verification
28
+ LEGACY_PATH = py.path. local
29
+ # fmt: on
30
+
31
+
32
+ def legacy_path(path: str | os.PathLike[str]) -> LEGACY_PATH:
33
+ """Internal wrapper to prepare lazy proxies for legacy_path instances"""
34
+ return LEGACY_PATH(path)
35
+
36
+
37
+ # fmt: off
38
+ # Singleton type for NOTSET, as described in:
39
+ # https://www.python.org/dev/peps/pep-0484/#support-for-singleton-types-in-unions
40
+ class NotSetType(enum.Enum):
41
+ token = 0
42
+ NOTSET: Final = NotSetType.token
43
+ # fmt: on
44
+
45
+
46
+ def is_generator(func: object) -> bool:
47
+ genfunc = inspect.isgeneratorfunction(func)
48
+ return genfunc and not iscoroutinefunction(func)
49
+
50
+
51
+ def iscoroutinefunction(func: object) -> bool:
52
+ """Return True if func is a coroutine function (a function defined with async
53
+ def syntax, and doesn't contain yield), or a function decorated with
54
+ @asyncio.coroutine.
55
+
56
+ Note: copied and modified from Python 3.5's builtin coroutines.py to avoid
57
+ importing asyncio directly, which in turns also initializes the "logging"
58
+ module as a side-effect (see issue #8).
59
+ """
60
+ return inspect.iscoroutinefunction(func) or getattr(func, "_is_coroutine", False)
61
+
62
+
63
+ def is_async_function(func: object) -> bool:
64
+ """Return True if the given function seems to be an async function or
65
+ an async generator."""
66
+ return iscoroutinefunction(func) or inspect.isasyncgenfunction(func)
67
+
68
+
69
+ def getlocation(function, curdir: str | os.PathLike[str] | None = None) -> str:
70
+ function = get_real_func(function)
71
+ fn = Path(inspect.getfile(function))
72
+ lineno = function.__code__.co_firstlineno
73
+ if curdir is not None:
74
+ try:
75
+ relfn = fn.relative_to(curdir)
76
+ except ValueError:
77
+ pass
78
+ else:
79
+ return "%s:%d" % (relfn, lineno + 1)
80
+ return "%s:%d" % (fn, lineno + 1)
81
+
82
+
83
+ def num_mock_patch_args(function) -> int:
84
+ """Return number of arguments used up by mock arguments (if any)."""
85
+ patchings = getattr(function, "patchings", None)
86
+ if not patchings:
87
+ return 0
88
+
89
+ mock_sentinel = getattr(sys.modules.get("mock"), "DEFAULT", object())
90
+ ut_mock_sentinel = getattr(sys.modules.get("unittest.mock"), "DEFAULT", object())
91
+
92
+ return len(
93
+ [
94
+ p
95
+ for p in patchings
96
+ if not p.attribute_name
97
+ and (p.new is mock_sentinel or p.new is ut_mock_sentinel)
98
+ ]
99
+ )
100
+
101
+
102
+ def getfuncargnames(
103
+ function: Callable[..., object],
104
+ *,
105
+ name: str = "",
106
+ cls: type | None = None,
107
+ ) -> tuple[str, ...]:
108
+ """Return the names of a function's mandatory arguments.
109
+
110
+ Should return the names of all function arguments that:
111
+ * Aren't bound to an instance or type as in instance or class methods.
112
+ * Don't have default values.
113
+ * Aren't bound with functools.partial.
114
+ * Aren't replaced with mocks.
115
+
116
+ The cls arguments indicate that the function should be treated as a bound
117
+ method even though it's not unless the function is a static method.
118
+
119
+ The name parameter should be the original name in which the function was collected.
120
+ """
121
+ # TODO(RonnyPfannschmidt): This function should be refactored when we
122
+ # revisit fixtures. The fixture mechanism should ask the node for
123
+ # the fixture names, and not try to obtain directly from the
124
+ # function object well after collection has occurred.
125
+
126
+ # The parameters attribute of a Signature object contains an
127
+ # ordered mapping of parameter names to Parameter instances. This
128
+ # creates a tuple of the names of the parameters that don't have
129
+ # defaults.
130
+ try:
131
+ parameters = signature(function).parameters
132
+ except (ValueError, TypeError) as e:
133
+ from _pytest.outcomes import fail
134
+
135
+ fail(
136
+ f"Could not determine arguments of {function!r}: {e}",
137
+ pytrace=False,
138
+ )
139
+
140
+ arg_names = tuple(
141
+ p.name
142
+ for p in parameters.values()
143
+ if (
144
+ p.kind is Parameter.POSITIONAL_OR_KEYWORD
145
+ or p.kind is Parameter.KEYWORD_ONLY
146
+ )
147
+ and p.default is Parameter.empty
148
+ )
149
+ if not name:
150
+ name = function.__name__
151
+
152
+ # If this function should be treated as a bound method even though
153
+ # it's passed as an unbound method or function, remove the first
154
+ # parameter name.
155
+ if (
156
+ # Not using `getattr` because we don't want to resolve the staticmethod.
157
+ # Not using `cls.__dict__` because we want to check the entire MRO.
158
+ cls
159
+ and not isinstance(
160
+ inspect.getattr_static(cls, name, default=None), staticmethod
161
+ )
162
+ ):
163
+ arg_names = arg_names[1:]
164
+ # Remove any names that will be replaced with mocks.
165
+ if hasattr(function, "__wrapped__"):
166
+ arg_names = arg_names[num_mock_patch_args(function) :]
167
+ return arg_names
168
+
169
+
170
+ def get_default_arg_names(function: Callable[..., Any]) -> tuple[str, ...]:
171
+ # Note: this code intentionally mirrors the code at the beginning of
172
+ # getfuncargnames, to get the arguments which were excluded from its result
173
+ # because they had default values.
174
+ return tuple(
175
+ p.name
176
+ for p in signature(function).parameters.values()
177
+ if p.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY)
178
+ and p.default is not Parameter.empty
179
+ )
180
+
181
+
182
+ _non_printable_ascii_translate_table = {
183
+ i: f"\\x{i:02x}" for i in range(128) if i not in range(32, 127)
184
+ }
185
+ _non_printable_ascii_translate_table.update(
186
+ {ord("\t"): "\\t", ord("\r"): "\\r", ord("\n"): "\\n"}
187
+ )
188
+
189
+
190
+ def ascii_escaped(val: bytes | str) -> str:
191
+ r"""If val is pure ASCII, return it as an str, otherwise, escape
192
+ bytes objects into a sequence of escaped bytes:
193
+
194
+ b'\xc3\xb4\xc5\xd6' -> r'\xc3\xb4\xc5\xd6'
195
+
196
+ and escapes strings into a sequence of escaped unicode ids, e.g.:
197
+
198
+ r'4\nV\U00043efa\x0eMXWB\x1e\u3028\u15fd\xcd\U0007d944'
199
+
200
+ Note:
201
+ The obvious "v.decode('unicode-escape')" will return
202
+ valid UTF-8 unicode if it finds them in bytes, but we
203
+ want to return escaped bytes for any byte, even if they match
204
+ a UTF-8 string.
205
+ """
206
+ if isinstance(val, bytes):
207
+ ret = val.decode("ascii", "backslashreplace")
208
+ else:
209
+ ret = val.encode("unicode_escape").decode("ascii")
210
+ return ret.translate(_non_printable_ascii_translate_table)
211
+
212
+
213
+ @dataclasses.dataclass
214
+ class _PytestWrapper:
215
+ """Dummy wrapper around a function object for internal use only.
216
+
217
+ Used to correctly unwrap the underlying function object when we are
218
+ creating fixtures, because we wrap the function object ourselves with a
219
+ decorator to issue warnings when the fixture function is called directly.
220
+ """
221
+
222
+ obj: Any
223
+
224
+
225
+ def get_real_func(obj):
226
+ """Get the real function object of the (possibly) wrapped object by
227
+ functools.wraps or functools.partial."""
228
+ start_obj = obj
229
+ for i in range(100):
230
+ # __pytest_wrapped__ is set by @pytest.fixture when wrapping the fixture function
231
+ # to trigger a warning if it gets called directly instead of by pytest: we don't
232
+ # want to unwrap further than this otherwise we lose useful wrappings like @mock.patch (#3774)
233
+ new_obj = getattr(obj, "__pytest_wrapped__", None)
234
+ if isinstance(new_obj, _PytestWrapper):
235
+ obj = new_obj.obj
236
+ break
237
+ new_obj = getattr(obj, "__wrapped__", None)
238
+ if new_obj is None:
239
+ break
240
+ obj = new_obj
241
+ else:
242
+ from _pytest._io.saferepr import saferepr
243
+
244
+ raise ValueError(
245
+ f"could not find real function of {saferepr(start_obj)}\nstopped at {saferepr(obj)}"
246
+ )
247
+ if isinstance(obj, functools.partial):
248
+ obj = obj.func
249
+ return obj
250
+
251
+
252
+ def get_real_method(obj, holder):
253
+ """Attempt to obtain the real function object that might be wrapping
254
+ ``obj``, while at the same time returning a bound method to ``holder`` if
255
+ the original object was a bound method."""
256
+ try:
257
+ is_method = hasattr(obj, "__func__")
258
+ obj = get_real_func(obj)
259
+ except Exception: # pragma: no cover
260
+ return obj
261
+ if is_method and hasattr(obj, "__get__") and callable(obj.__get__):
262
+ obj = obj.__get__(holder)
263
+ return obj
264
+
265
+
266
+ def getimfunc(func):
267
+ try:
268
+ return func.__func__
269
+ except AttributeError:
270
+ return func
271
+
272
+
273
+ def safe_getattr(object: Any, name: str, default: Any) -> Any:
274
+ """Like getattr but return default upon any Exception or any OutcomeException.
275
+
276
+ Attribute access can potentially fail for 'evil' Python objects.
277
+ See issue #214.
278
+ It catches OutcomeException because of #2490 (issue #580), new outcomes
279
+ are derived from BaseException instead of Exception (for more details
280
+ check #2707).
281
+ """
282
+ from _pytest.outcomes import TEST_OUTCOME
283
+
284
+ try:
285
+ return getattr(object, name, default)
286
+ except TEST_OUTCOME:
287
+ return default
288
+
289
+
290
+ def safe_isclass(obj: object) -> bool:
291
+ """Ignore any exception via isinstance on Python 3."""
292
+ try:
293
+ return inspect.isclass(obj)
294
+ except Exception:
295
+ return False
296
+
297
+
298
+ def get_user_id() -> int | None:
299
+ """Return the current process's real user id or None if it could not be
300
+ determined.
301
+
302
+ :return: The user id or None if it could not be determined.
303
+ """
304
+ # mypy follows the version and platform checking expectation of PEP 484:
305
+ # https://mypy.readthedocs.io/en/stable/common_issues.html?highlight=platform#python-version-and-system-platform-checks
306
+ # Containment checks are too complex for mypy v1.5.0 and cause failure.
307
+ if sys.platform == "win32" or sys.platform == "emscripten":
308
+ # win32 does not have a getuid() function.
309
+ # Emscripten has a return 0 stub.
310
+ return None
311
+ else:
312
+ # On other platforms, a return value of -1 is assumed to indicate that
313
+ # the current process's real user id could not be determined.
314
+ ERROR = -1
315
+ uid = os.getuid()
316
+ return uid if uid != ERROR else None
317
+
318
+
319
+ # Perform exhaustiveness checking.
320
+ #
321
+ # Consider this example:
322
+ #
323
+ # MyUnion = Union[int, str]
324
+ #
325
+ # def handle(x: MyUnion) -> int {
326
+ # if isinstance(x, int):
327
+ # return 1
328
+ # elif isinstance(x, str):
329
+ # return 2
330
+ # else:
331
+ # raise Exception('unreachable')
332
+ #
333
+ # Now suppose we add a new variant:
334
+ #
335
+ # MyUnion = Union[int, str, bytes]
336
+ #
337
+ # After doing this, we must remember ourselves to go and update the handle
338
+ # function to handle the new variant.
339
+ #
340
+ # With `assert_never` we can do better:
341
+ #
342
+ # // raise Exception('unreachable')
343
+ # return assert_never(x)
344
+ #
345
+ # Now, if we forget to handle the new variant, the type-checker will emit a
346
+ # compile-time error, instead of the runtime error we would have gotten
347
+ # previously.
348
+ #
349
+ # This also work for Enums (if you use `is` to compare) and Literals.
350
+ def assert_never(value: NoReturn) -> NoReturn:
351
+ assert False, f"Unhandled value: {value} ({type(value).__name__})"
vllm/lib/python3.10/site-packages/_pytest/config/__init__.py ADDED
@@ -0,0 +1,1973 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """Command line options, ini-file and conftest.py processing."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import collections.abc
8
+ import copy
9
+ import dataclasses
10
+ import enum
11
+ from functools import lru_cache
12
+ import glob
13
+ import importlib.metadata
14
+ import inspect
15
+ import os
16
+ import pathlib
17
+ import re
18
+ import shlex
19
+ import sys
20
+ from textwrap import dedent
21
+ import types
22
+ from types import FunctionType
23
+ from typing import Any
24
+ from typing import Callable
25
+ from typing import cast
26
+ from typing import Final
27
+ from typing import final
28
+ from typing import Generator
29
+ from typing import IO
30
+ from typing import Iterable
31
+ from typing import Iterator
32
+ from typing import Sequence
33
+ from typing import TextIO
34
+ from typing import Type
35
+ from typing import TYPE_CHECKING
36
+ import warnings
37
+
38
+ import pluggy
39
+ from pluggy import HookimplMarker
40
+ from pluggy import HookimplOpts
41
+ from pluggy import HookspecMarker
42
+ from pluggy import HookspecOpts
43
+ from pluggy import PluginManager
44
+
45
+ from .compat import PathAwareHookProxy
46
+ from .exceptions import PrintHelp as PrintHelp
47
+ from .exceptions import UsageError as UsageError
48
+ from .findpaths import determine_setup
49
+ from _pytest import __version__
50
+ import _pytest._code
51
+ from _pytest._code import ExceptionInfo
52
+ from _pytest._code import filter_traceback
53
+ from _pytest._code.code import TracebackStyle
54
+ from _pytest._io import TerminalWriter
55
+ from _pytest.config.argparsing import Argument
56
+ from _pytest.config.argparsing import Parser
57
+ import _pytest.deprecated
58
+ import _pytest.hookspec
59
+ from _pytest.outcomes import fail
60
+ from _pytest.outcomes import Skipped
61
+ from _pytest.pathlib import absolutepath
62
+ from _pytest.pathlib import bestrelpath
63
+ from _pytest.pathlib import import_path
64
+ from _pytest.pathlib import ImportMode
65
+ from _pytest.pathlib import resolve_package_path
66
+ from _pytest.pathlib import safe_exists
67
+ from _pytest.stash import Stash
68
+ from _pytest.warning_types import PytestConfigWarning
69
+ from _pytest.warning_types import warn_explicit_for
70
+
71
+
72
+ if TYPE_CHECKING:
73
+ from _pytest.cacheprovider import Cache
74
+ from _pytest.terminal import TerminalReporter
75
+
76
+
77
+ _PluggyPlugin = object
78
+ """A type to represent plugin objects.
79
+
80
+ Plugins can be any namespace, so we can't narrow it down much, but we use an
81
+ alias to make the intent clear.
82
+
83
+ Ideally this type would be provided by pluggy itself.
84
+ """
85
+
86
+
87
+ hookimpl = HookimplMarker("pytest")
88
+ hookspec = HookspecMarker("pytest")
89
+
90
+
91
+ @final
92
+ class ExitCode(enum.IntEnum):
93
+ """Encodes the valid exit codes by pytest.
94
+
95
+ Currently users and plugins may supply other exit codes as well.
96
+
97
+ .. versionadded:: 5.0
98
+ """
99
+
100
+ #: Tests passed.
101
+ OK = 0
102
+ #: Tests failed.
103
+ TESTS_FAILED = 1
104
+ #: pytest was interrupted.
105
+ INTERRUPTED = 2
106
+ #: An internal error got in the way.
107
+ INTERNAL_ERROR = 3
108
+ #: pytest was misused.
109
+ USAGE_ERROR = 4
110
+ #: pytest couldn't find tests.
111
+ NO_TESTS_COLLECTED = 5
112
+
113
+
114
+ class ConftestImportFailure(Exception):
115
+ def __init__(
116
+ self,
117
+ path: pathlib.Path,
118
+ *,
119
+ cause: Exception,
120
+ ) -> None:
121
+ self.path = path
122
+ self.cause = cause
123
+
124
+ def __str__(self) -> str:
125
+ return f"{type(self.cause).__name__}: {self.cause} (from {self.path})"
126
+
127
+
128
+ def filter_traceback_for_conftest_import_failure(
129
+ entry: _pytest._code.TracebackEntry,
130
+ ) -> bool:
131
+ """Filter tracebacks entries which point to pytest internals or importlib.
132
+
133
+ Make a special case for importlib because we use it to import test modules and conftest files
134
+ in _pytest.pathlib.import_path.
135
+ """
136
+ return filter_traceback(entry) and "importlib" not in str(entry.path).split(os.sep)
137
+
138
+
139
+ def main(
140
+ args: list[str] | os.PathLike[str] | None = None,
141
+ plugins: Sequence[str | _PluggyPlugin] | None = None,
142
+ ) -> int | ExitCode:
143
+ """Perform an in-process test run.
144
+
145
+ :param args:
146
+ List of command line arguments. If `None` or not given, defaults to reading
147
+ arguments directly from the process command line (:data:`sys.argv`).
148
+ :param plugins: List of plugin objects to be auto-registered during initialization.
149
+
150
+ :returns: An exit code.
151
+ """
152
+ old_pytest_version = os.environ.get("PYTEST_VERSION")
153
+ try:
154
+ os.environ["PYTEST_VERSION"] = __version__
155
+ try:
156
+ config = _prepareconfig(args, plugins)
157
+ except ConftestImportFailure as e:
158
+ exc_info = ExceptionInfo.from_exception(e.cause)
159
+ tw = TerminalWriter(sys.stderr)
160
+ tw.line(f"ImportError while loading conftest '{e.path}'.", red=True)
161
+ exc_info.traceback = exc_info.traceback.filter(
162
+ filter_traceback_for_conftest_import_failure
163
+ )
164
+ exc_repr = (
165
+ exc_info.getrepr(style="short", chain=False)
166
+ if exc_info.traceback
167
+ else exc_info.exconly()
168
+ )
169
+ formatted_tb = str(exc_repr)
170
+ for line in formatted_tb.splitlines():
171
+ tw.line(line.rstrip(), red=True)
172
+ return ExitCode.USAGE_ERROR
173
+ else:
174
+ try:
175
+ ret: ExitCode | int = config.hook.pytest_cmdline_main(config=config)
176
+ try:
177
+ return ExitCode(ret)
178
+ except ValueError:
179
+ return ret
180
+ finally:
181
+ config._ensure_unconfigure()
182
+ except UsageError as e:
183
+ tw = TerminalWriter(sys.stderr)
184
+ for msg in e.args:
185
+ tw.line(f"ERROR: {msg}\n", red=True)
186
+ return ExitCode.USAGE_ERROR
187
+ finally:
188
+ if old_pytest_version is None:
189
+ os.environ.pop("PYTEST_VERSION", None)
190
+ else:
191
+ os.environ["PYTEST_VERSION"] = old_pytest_version
192
+
193
+
194
+ def console_main() -> int:
195
+ """The CLI entry point of pytest.
196
+
197
+ This function is not meant for programmable use; use `main()` instead.
198
+ """
199
+ # https://docs.python.org/3/library/signal.html#note-on-sigpipe
200
+ try:
201
+ code = main()
202
+ sys.stdout.flush()
203
+ return code
204
+ except BrokenPipeError:
205
+ # Python flushes standard streams on exit; redirect remaining output
206
+ # to devnull to avoid another BrokenPipeError at shutdown
207
+ devnull = os.open(os.devnull, os.O_WRONLY)
208
+ os.dup2(devnull, sys.stdout.fileno())
209
+ return 1 # Python exits with error code 1 on EPIPE
210
+
211
+
212
+ class cmdline: # compatibility namespace
213
+ main = staticmethod(main)
214
+
215
+
216
+ def filename_arg(path: str, optname: str) -> str:
217
+ """Argparse type validator for filename arguments.
218
+
219
+ :path: Path of filename.
220
+ :optname: Name of the option.
221
+ """
222
+ if os.path.isdir(path):
223
+ raise UsageError(f"{optname} must be a filename, given: {path}")
224
+ return path
225
+
226
+
227
+ def directory_arg(path: str, optname: str) -> str:
228
+ """Argparse type validator for directory arguments.
229
+
230
+ :path: Path of directory.
231
+ :optname: Name of the option.
232
+ """
233
+ if not os.path.isdir(path):
234
+ raise UsageError(f"{optname} must be a directory, given: {path}")
235
+ return path
236
+
237
+
238
+ # Plugins that cannot be disabled via "-p no:X" currently.
239
+ essential_plugins = (
240
+ "mark",
241
+ "main",
242
+ "runner",
243
+ "fixtures",
244
+ "helpconfig", # Provides -p.
245
+ )
246
+
247
+ default_plugins = (
248
+ *essential_plugins,
249
+ "python",
250
+ "terminal",
251
+ "debugging",
252
+ "unittest",
253
+ "capture",
254
+ "skipping",
255
+ "legacypath",
256
+ "tmpdir",
257
+ "monkeypatch",
258
+ "recwarn",
259
+ "pastebin",
260
+ "assertion",
261
+ "junitxml",
262
+ "doctest",
263
+ "cacheprovider",
264
+ "freeze_support",
265
+ "setuponly",
266
+ "setupplan",
267
+ "stepwise",
268
+ "warnings",
269
+ "logging",
270
+ "reports",
271
+ "python_path",
272
+ "unraisableexception",
273
+ "threadexception",
274
+ "faulthandler",
275
+ )
276
+
277
+ builtin_plugins = set(default_plugins)
278
+ builtin_plugins.add("pytester")
279
+ builtin_plugins.add("pytester_assertions")
280
+
281
+
282
+ def get_config(
283
+ args: list[str] | None = None,
284
+ plugins: Sequence[str | _PluggyPlugin] | None = None,
285
+ ) -> Config:
286
+ # subsequent calls to main will create a fresh instance
287
+ pluginmanager = PytestPluginManager()
288
+ config = Config(
289
+ pluginmanager,
290
+ invocation_params=Config.InvocationParams(
291
+ args=args or (),
292
+ plugins=plugins,
293
+ dir=pathlib.Path.cwd(),
294
+ ),
295
+ )
296
+
297
+ if args is not None:
298
+ # Handle any "-p no:plugin" args.
299
+ pluginmanager.consider_preparse(args, exclude_only=True)
300
+
301
+ for spec in default_plugins:
302
+ pluginmanager.import_plugin(spec)
303
+
304
+ return config
305
+
306
+
307
+ def get_plugin_manager() -> PytestPluginManager:
308
+ """Obtain a new instance of the
309
+ :py:class:`pytest.PytestPluginManager`, with default plugins
310
+ already loaded.
311
+
312
+ This function can be used by integration with other tools, like hooking
313
+ into pytest to run tests into an IDE.
314
+ """
315
+ return get_config().pluginmanager
316
+
317
+
318
+ def _prepareconfig(
319
+ args: list[str] | os.PathLike[str] | None = None,
320
+ plugins: Sequence[str | _PluggyPlugin] | None = None,
321
+ ) -> Config:
322
+ if args is None:
323
+ args = sys.argv[1:]
324
+ elif isinstance(args, os.PathLike):
325
+ args = [os.fspath(args)]
326
+ elif not isinstance(args, list):
327
+ msg = ( # type:ignore[unreachable]
328
+ "`args` parameter expected to be a list of strings, got: {!r} (type: {})"
329
+ )
330
+ raise TypeError(msg.format(args, type(args)))
331
+
332
+ config = get_config(args, plugins)
333
+ pluginmanager = config.pluginmanager
334
+ try:
335
+ if plugins:
336
+ for plugin in plugins:
337
+ if isinstance(plugin, str):
338
+ pluginmanager.consider_pluginarg(plugin)
339
+ else:
340
+ pluginmanager.register(plugin)
341
+ config = pluginmanager.hook.pytest_cmdline_parse(
342
+ pluginmanager=pluginmanager, args=args
343
+ )
344
+ return config
345
+ except BaseException:
346
+ config._ensure_unconfigure()
347
+ raise
348
+
349
+
350
+ def _get_directory(path: pathlib.Path) -> pathlib.Path:
351
+ """Get the directory of a path - itself if already a directory."""
352
+ if path.is_file():
353
+ return path.parent
354
+ else:
355
+ return path
356
+
357
+
358
+ def _get_legacy_hook_marks(
359
+ method: Any,
360
+ hook_type: str,
361
+ opt_names: tuple[str, ...],
362
+ ) -> dict[str, bool]:
363
+ if TYPE_CHECKING:
364
+ # abuse typeguard from importlib to avoid massive method type union that's lacking an alias
365
+ assert inspect.isroutine(method)
366
+ known_marks: set[str] = {m.name for m in getattr(method, "pytestmark", [])}
367
+ must_warn: list[str] = []
368
+ opts: dict[str, bool] = {}
369
+ for opt_name in opt_names:
370
+ opt_attr = getattr(method, opt_name, AttributeError)
371
+ if opt_attr is not AttributeError:
372
+ must_warn.append(f"{opt_name}={opt_attr}")
373
+ opts[opt_name] = True
374
+ elif opt_name in known_marks:
375
+ must_warn.append(f"{opt_name}=True")
376
+ opts[opt_name] = True
377
+ else:
378
+ opts[opt_name] = False
379
+ if must_warn:
380
+ hook_opts = ", ".join(must_warn)
381
+ message = _pytest.deprecated.HOOK_LEGACY_MARKING.format(
382
+ type=hook_type,
383
+ fullname=method.__qualname__,
384
+ hook_opts=hook_opts,
385
+ )
386
+ warn_explicit_for(cast(FunctionType, method), message)
387
+ return opts
388
+
389
+
390
+ @final
391
+ class PytestPluginManager(PluginManager):
392
+ """A :py:class:`pluggy.PluginManager <pluggy.PluginManager>` with
393
+ additional pytest-specific functionality:
394
+
395
+ * Loading plugins from the command line, ``PYTEST_PLUGINS`` env variable and
396
+ ``pytest_plugins`` global variables found in plugins being loaded.
397
+ * ``conftest.py`` loading during start-up.
398
+ """
399
+
400
+ def __init__(self) -> None:
401
+ import _pytest.assertion
402
+
403
+ super().__init__("pytest")
404
+
405
+ # -- State related to local conftest plugins.
406
+ # All loaded conftest modules.
407
+ self._conftest_plugins: set[types.ModuleType] = set()
408
+ # All conftest modules applicable for a directory.
409
+ # This includes the directory's own conftest modules as well
410
+ # as those of its parent directories.
411
+ self._dirpath2confmods: dict[pathlib.Path, list[types.ModuleType]] = {}
412
+ # Cutoff directory above which conftests are no longer discovered.
413
+ self._confcutdir: pathlib.Path | None = None
414
+ # If set, conftest loading is skipped.
415
+ self._noconftest = False
416
+
417
+ # _getconftestmodules()'s call to _get_directory() causes a stat
418
+ # storm when it's called potentially thousands of times in a test
419
+ # session (#9478), often with the same path, so cache it.
420
+ self._get_directory = lru_cache(256)(_get_directory)
421
+
422
+ # plugins that were explicitly skipped with pytest.skip
423
+ # list of (module name, skip reason)
424
+ # previously we would issue a warning when a plugin was skipped, but
425
+ # since we refactored warnings as first citizens of Config, they are
426
+ # just stored here to be used later.
427
+ self.skipped_plugins: list[tuple[str, str]] = []
428
+
429
+ self.add_hookspecs(_pytest.hookspec)
430
+ self.register(self)
431
+ if os.environ.get("PYTEST_DEBUG"):
432
+ err: IO[str] = sys.stderr
433
+ encoding: str = getattr(err, "encoding", "utf8")
434
+ try:
435
+ err = open(
436
+ os.dup(err.fileno()),
437
+ mode=err.mode,
438
+ buffering=1,
439
+ encoding=encoding,
440
+ )
441
+ except Exception:
442
+ pass
443
+ self.trace.root.setwriter(err.write)
444
+ self.enable_tracing()
445
+
446
+ # Config._consider_importhook will set a real object if required.
447
+ self.rewrite_hook = _pytest.assertion.DummyRewriteHook()
448
+ # Used to know when we are importing conftests after the pytest_configure stage.
449
+ self._configured = False
450
+
451
+ def parse_hookimpl_opts(
452
+ self, plugin: _PluggyPlugin, name: str
453
+ ) -> HookimplOpts | None:
454
+ """:meta private:"""
455
+ # pytest hooks are always prefixed with "pytest_",
456
+ # so we avoid accessing possibly non-readable attributes
457
+ # (see issue #1073).
458
+ if not name.startswith("pytest_"):
459
+ return None
460
+ # Ignore names which cannot be hooks.
461
+ if name == "pytest_plugins":
462
+ return None
463
+
464
+ opts = super().parse_hookimpl_opts(plugin, name)
465
+ if opts is not None:
466
+ return opts
467
+
468
+ method = getattr(plugin, name)
469
+ # Consider only actual functions for hooks (#3775).
470
+ if not inspect.isroutine(method):
471
+ return None
472
+ # Collect unmarked hooks as long as they have the `pytest_' prefix.
473
+ return _get_legacy_hook_marks( # type: ignore[return-value]
474
+ method, "impl", ("tryfirst", "trylast", "optionalhook", "hookwrapper")
475
+ )
476
+
477
+ def parse_hookspec_opts(self, module_or_class, name: str) -> HookspecOpts | None:
478
+ """:meta private:"""
479
+ opts = super().parse_hookspec_opts(module_or_class, name)
480
+ if opts is None:
481
+ method = getattr(module_or_class, name)
482
+ if name.startswith("pytest_"):
483
+ opts = _get_legacy_hook_marks( # type: ignore[assignment]
484
+ method,
485
+ "spec",
486
+ ("firstresult", "historic"),
487
+ )
488
+ return opts
489
+
490
+ def register(self, plugin: _PluggyPlugin, name: str | None = None) -> str | None:
491
+ if name in _pytest.deprecated.DEPRECATED_EXTERNAL_PLUGINS:
492
+ warnings.warn(
493
+ PytestConfigWarning(
494
+ "{} plugin has been merged into the core, "
495
+ "please remove it from your requirements.".format(
496
+ name.replace("_", "-")
497
+ )
498
+ )
499
+ )
500
+ return None
501
+ plugin_name = super().register(plugin, name)
502
+ if plugin_name is not None:
503
+ self.hook.pytest_plugin_registered.call_historic(
504
+ kwargs=dict(
505
+ plugin=plugin,
506
+ plugin_name=plugin_name,
507
+ manager=self,
508
+ )
509
+ )
510
+
511
+ if isinstance(plugin, types.ModuleType):
512
+ self.consider_module(plugin)
513
+ return plugin_name
514
+
515
+ def getplugin(self, name: str):
516
+ # Support deprecated naming because plugins (xdist e.g.) use it.
517
+ plugin: _PluggyPlugin | None = self.get_plugin(name)
518
+ return plugin
519
+
520
+ def hasplugin(self, name: str) -> bool:
521
+ """Return whether a plugin with the given name is registered."""
522
+ return bool(self.get_plugin(name))
523
+
524
+ def pytest_configure(self, config: Config) -> None:
525
+ """:meta private:"""
526
+ # XXX now that the pluginmanager exposes hookimpl(tryfirst...)
527
+ # we should remove tryfirst/trylast as markers.
528
+ config.addinivalue_line(
529
+ "markers",
530
+ "tryfirst: mark a hook implementation function such that the "
531
+ "plugin machinery will try to call it first/as early as possible. "
532
+ "DEPRECATED, use @pytest.hookimpl(tryfirst=True) instead.",
533
+ )
534
+ config.addinivalue_line(
535
+ "markers",
536
+ "trylast: mark a hook implementation function such that the "
537
+ "plugin machinery will try to call it last/as late as possible. "
538
+ "DEPRECATED, use @pytest.hookimpl(trylast=True) instead.",
539
+ )
540
+ self._configured = True
541
+
542
+ #
543
+ # Internal API for local conftest plugin handling.
544
+ #
545
+ def _set_initial_conftests(
546
+ self,
547
+ args: Sequence[str | pathlib.Path],
548
+ pyargs: bool,
549
+ noconftest: bool,
550
+ rootpath: pathlib.Path,
551
+ confcutdir: pathlib.Path | None,
552
+ invocation_dir: pathlib.Path,
553
+ importmode: ImportMode | str,
554
+ *,
555
+ consider_namespace_packages: bool,
556
+ ) -> None:
557
+ """Load initial conftest files given a preparsed "namespace".
558
+
559
+ As conftest files may add their own command line options which have
560
+ arguments ('--my-opt somepath') we might get some false positives.
561
+ All builtin and 3rd party plugins will have been loaded, however, so
562
+ common options will not confuse our logic here.
563
+ """
564
+ self._confcutdir = (
565
+ absolutepath(invocation_dir / confcutdir) if confcutdir else None
566
+ )
567
+ self._noconftest = noconftest
568
+ self._using_pyargs = pyargs
569
+ foundanchor = False
570
+ for initial_path in args:
571
+ path = str(initial_path)
572
+ # remove node-id syntax
573
+ i = path.find("::")
574
+ if i != -1:
575
+ path = path[:i]
576
+ anchor = absolutepath(invocation_dir / path)
577
+
578
+ # Ensure we do not break if what appears to be an anchor
579
+ # is in fact a very long option (#10169, #11394).
580
+ if safe_exists(anchor):
581
+ self._try_load_conftest(
582
+ anchor,
583
+ importmode,
584
+ rootpath,
585
+ consider_namespace_packages=consider_namespace_packages,
586
+ )
587
+ foundanchor = True
588
+ if not foundanchor:
589
+ self._try_load_conftest(
590
+ invocation_dir,
591
+ importmode,
592
+ rootpath,
593
+ consider_namespace_packages=consider_namespace_packages,
594
+ )
595
+
596
+ def _is_in_confcutdir(self, path: pathlib.Path) -> bool:
597
+ """Whether to consider the given path to load conftests from."""
598
+ if self._confcutdir is None:
599
+ return True
600
+ # The semantics here are literally:
601
+ # Do not load a conftest if it is found upwards from confcut dir.
602
+ # But this is *not* the same as:
603
+ # Load only conftests from confcutdir or below.
604
+ # At first glance they might seem the same thing, however we do support use cases where
605
+ # we want to load conftests that are not found in confcutdir or below, but are found
606
+ # in completely different directory hierarchies like packages installed
607
+ # in out-of-source trees.
608
+ # (see #9767 for a regression where the logic was inverted).
609
+ return path not in self._confcutdir.parents
610
+
611
+ def _try_load_conftest(
612
+ self,
613
+ anchor: pathlib.Path,
614
+ importmode: str | ImportMode,
615
+ rootpath: pathlib.Path,
616
+ *,
617
+ consider_namespace_packages: bool,
618
+ ) -> None:
619
+ self._loadconftestmodules(
620
+ anchor,
621
+ importmode,
622
+ rootpath,
623
+ consider_namespace_packages=consider_namespace_packages,
624
+ )
625
+ # let's also consider test* subdirs
626
+ if anchor.is_dir():
627
+ for x in anchor.glob("test*"):
628
+ if x.is_dir():
629
+ self._loadconftestmodules(
630
+ x,
631
+ importmode,
632
+ rootpath,
633
+ consider_namespace_packages=consider_namespace_packages,
634
+ )
635
+
636
+ def _loadconftestmodules(
637
+ self,
638
+ path: pathlib.Path,
639
+ importmode: str | ImportMode,
640
+ rootpath: pathlib.Path,
641
+ *,
642
+ consider_namespace_packages: bool,
643
+ ) -> None:
644
+ if self._noconftest:
645
+ return
646
+
647
+ directory = self._get_directory(path)
648
+
649
+ # Optimization: avoid repeated searches in the same directory.
650
+ # Assumes always called with same importmode and rootpath.
651
+ if directory in self._dirpath2confmods:
652
+ return
653
+
654
+ clist = []
655
+ for parent in reversed((directory, *directory.parents)):
656
+ if self._is_in_confcutdir(parent):
657
+ conftestpath = parent / "conftest.py"
658
+ if conftestpath.is_file():
659
+ mod = self._importconftest(
660
+ conftestpath,
661
+ importmode,
662
+ rootpath,
663
+ consider_namespace_packages=consider_namespace_packages,
664
+ )
665
+ clist.append(mod)
666
+ self._dirpath2confmods[directory] = clist
667
+
668
+ def _getconftestmodules(self, path: pathlib.Path) -> Sequence[types.ModuleType]:
669
+ directory = self._get_directory(path)
670
+ return self._dirpath2confmods.get(directory, ())
671
+
672
+ def _rget_with_confmod(
673
+ self,
674
+ name: str,
675
+ path: pathlib.Path,
676
+ ) -> tuple[types.ModuleType, Any]:
677
+ modules = self._getconftestmodules(path)
678
+ for mod in reversed(modules):
679
+ try:
680
+ return mod, getattr(mod, name)
681
+ except AttributeError:
682
+ continue
683
+ raise KeyError(name)
684
+
685
+ def _importconftest(
686
+ self,
687
+ conftestpath: pathlib.Path,
688
+ importmode: str | ImportMode,
689
+ rootpath: pathlib.Path,
690
+ *,
691
+ consider_namespace_packages: bool,
692
+ ) -> types.ModuleType:
693
+ conftestpath_plugin_name = str(conftestpath)
694
+ existing = self.get_plugin(conftestpath_plugin_name)
695
+ if existing is not None:
696
+ return cast(types.ModuleType, existing)
697
+
698
+ # conftest.py files there are not in a Python package all have module
699
+ # name "conftest", and thus conflict with each other. Clear the existing
700
+ # before loading the new one, otherwise the existing one will be
701
+ # returned from the module cache.
702
+ pkgpath = resolve_package_path(conftestpath)
703
+ if pkgpath is None:
704
+ try:
705
+ del sys.modules[conftestpath.stem]
706
+ except KeyError:
707
+ pass
708
+
709
+ try:
710
+ mod = import_path(
711
+ conftestpath,
712
+ mode=importmode,
713
+ root=rootpath,
714
+ consider_namespace_packages=consider_namespace_packages,
715
+ )
716
+ except Exception as e:
717
+ assert e.__traceback__ is not None
718
+ raise ConftestImportFailure(conftestpath, cause=e) from e
719
+
720
+ self._check_non_top_pytest_plugins(mod, conftestpath)
721
+
722
+ self._conftest_plugins.add(mod)
723
+ dirpath = conftestpath.parent
724
+ if dirpath in self._dirpath2confmods:
725
+ for path, mods in self._dirpath2confmods.items():
726
+ if dirpath in path.parents or path == dirpath:
727
+ if mod in mods:
728
+ raise AssertionError(
729
+ f"While trying to load conftest path {conftestpath!s}, "
730
+ f"found that the module {mod} is already loaded with path {mod.__file__}. "
731
+ "This is not supposed to happen. Please report this issue to pytest."
732
+ )
733
+ mods.append(mod)
734
+ self.trace(f"loading conftestmodule {mod!r}")
735
+ self.consider_conftest(mod, registration_name=conftestpath_plugin_name)
736
+ return mod
737
+
738
+ def _check_non_top_pytest_plugins(
739
+ self,
740
+ mod: types.ModuleType,
741
+ conftestpath: pathlib.Path,
742
+ ) -> None:
743
+ if (
744
+ hasattr(mod, "pytest_plugins")
745
+ and self._configured
746
+ and not self._using_pyargs
747
+ ):
748
+ msg = (
749
+ "Defining 'pytest_plugins' in a non-top-level conftest is no longer supported:\n"
750
+ "It affects the entire test suite instead of just below the conftest as expected.\n"
751
+ " {}\n"
752
+ "Please move it to a top level conftest file at the rootdir:\n"
753
+ " {}\n"
754
+ "For more information, visit:\n"
755
+ " https://docs.pytest.org/en/stable/deprecations.html#pytest-plugins-in-non-top-level-conftest-files"
756
+ )
757
+ fail(msg.format(conftestpath, self._confcutdir), pytrace=False)
758
+
759
+ #
760
+ # API for bootstrapping plugin loading
761
+ #
762
+ #
763
+
764
+ def consider_preparse(
765
+ self, args: Sequence[str], *, exclude_only: bool = False
766
+ ) -> None:
767
+ """:meta private:"""
768
+ i = 0
769
+ n = len(args)
770
+ while i < n:
771
+ opt = args[i]
772
+ i += 1
773
+ if isinstance(opt, str):
774
+ if opt == "-p":
775
+ try:
776
+ parg = args[i]
777
+ except IndexError:
778
+ return
779
+ i += 1
780
+ elif opt.startswith("-p"):
781
+ parg = opt[2:]
782
+ else:
783
+ continue
784
+ parg = parg.strip()
785
+ if exclude_only and not parg.startswith("no:"):
786
+ continue
787
+ self.consider_pluginarg(parg)
788
+
789
+ def consider_pluginarg(self, arg: str) -> None:
790
+ """:meta private:"""
791
+ if arg.startswith("no:"):
792
+ name = arg[3:]
793
+ if name in essential_plugins:
794
+ raise UsageError(f"plugin {name} cannot be disabled")
795
+
796
+ # PR #4304: remove stepwise if cacheprovider is blocked.
797
+ if name == "cacheprovider":
798
+ self.set_blocked("stepwise")
799
+ self.set_blocked("pytest_stepwise")
800
+
801
+ self.set_blocked(name)
802
+ if not name.startswith("pytest_"):
803
+ self.set_blocked("pytest_" + name)
804
+ else:
805
+ name = arg
806
+ # Unblock the plugin.
807
+ self.unblock(name)
808
+ if not name.startswith("pytest_"):
809
+ self.unblock("pytest_" + name)
810
+ self.import_plugin(arg, consider_entry_points=True)
811
+
812
+ def consider_conftest(
813
+ self, conftestmodule: types.ModuleType, registration_name: str
814
+ ) -> None:
815
+ """:meta private:"""
816
+ self.register(conftestmodule, name=registration_name)
817
+
818
+ def consider_env(self) -> None:
819
+ """:meta private:"""
820
+ self._import_plugin_specs(os.environ.get("PYTEST_PLUGINS"))
821
+
822
+ def consider_module(self, mod: types.ModuleType) -> None:
823
+ """:meta private:"""
824
+ self._import_plugin_specs(getattr(mod, "pytest_plugins", []))
825
+
826
+ def _import_plugin_specs(
827
+ self, spec: None | types.ModuleType | str | Sequence[str]
828
+ ) -> None:
829
+ plugins = _get_plugin_specs_as_list(spec)
830
+ for import_spec in plugins:
831
+ self.import_plugin(import_spec)
832
+
833
+ def import_plugin(self, modname: str, consider_entry_points: bool = False) -> None:
834
+ """Import a plugin with ``modname``.
835
+
836
+ If ``consider_entry_points`` is True, entry point names are also
837
+ considered to find a plugin.
838
+ """
839
+ # Most often modname refers to builtin modules, e.g. "pytester",
840
+ # "terminal" or "capture". Those plugins are registered under their
841
+ # basename for historic purposes but must be imported with the
842
+ # _pytest prefix.
843
+ assert isinstance(
844
+ modname, str
845
+ ), f"module name as text required, got {modname!r}"
846
+ if self.is_blocked(modname) or self.get_plugin(modname) is not None:
847
+ return
848
+
849
+ importspec = "_pytest." + modname if modname in builtin_plugins else modname
850
+ self.rewrite_hook.mark_rewrite(importspec)
851
+
852
+ if consider_entry_points:
853
+ loaded = self.load_setuptools_entrypoints("pytest11", name=modname)
854
+ if loaded:
855
+ return
856
+
857
+ try:
858
+ __import__(importspec)
859
+ except ImportError as e:
860
+ raise ImportError(
861
+ f'Error importing plugin "{modname}": {e.args[0]}'
862
+ ).with_traceback(e.__traceback__) from e
863
+
864
+ except Skipped as e:
865
+ self.skipped_plugins.append((modname, e.msg or ""))
866
+ else:
867
+ mod = sys.modules[importspec]
868
+ self.register(mod, modname)
869
+
870
+
871
+ def _get_plugin_specs_as_list(
872
+ specs: None | types.ModuleType | str | Sequence[str],
873
+ ) -> list[str]:
874
+ """Parse a plugins specification into a list of plugin names."""
875
+ # None means empty.
876
+ if specs is None:
877
+ return []
878
+ # Workaround for #3899 - a submodule which happens to be called "pytest_plugins".
879
+ if isinstance(specs, types.ModuleType):
880
+ return []
881
+ # Comma-separated list.
882
+ if isinstance(specs, str):
883
+ return specs.split(",") if specs else []
884
+ # Direct specification.
885
+ if isinstance(specs, collections.abc.Sequence):
886
+ return list(specs)
887
+ raise UsageError(
888
+ f"Plugins may be specified as a sequence or a ','-separated string of plugin names. Got: {specs!r}"
889
+ )
890
+
891
+
892
+ class Notset:
893
+ def __repr__(self):
894
+ return "<NOTSET>"
895
+
896
+
897
+ notset = Notset()
898
+
899
+
900
+ def _iter_rewritable_modules(package_files: Iterable[str]) -> Iterator[str]:
901
+ """Given an iterable of file names in a source distribution, return the "names" that should
902
+ be marked for assertion rewrite.
903
+
904
+ For example the package "pytest_mock/__init__.py" should be added as "pytest_mock" in
905
+ the assertion rewrite mechanism.
906
+
907
+ This function has to deal with dist-info based distributions and egg based distributions
908
+ (which are still very much in use for "editable" installs).
909
+
910
+ Here are the file names as seen in a dist-info based distribution:
911
+
912
+ pytest_mock/__init__.py
913
+ pytest_mock/_version.py
914
+ pytest_mock/plugin.py
915
+ pytest_mock.egg-info/PKG-INFO
916
+
917
+ Here are the file names as seen in an egg based distribution:
918
+
919
+ src/pytest_mock/__init__.py
920
+ src/pytest_mock/_version.py
921
+ src/pytest_mock/plugin.py
922
+ src/pytest_mock.egg-info/PKG-INFO
923
+ LICENSE
924
+ setup.py
925
+
926
+ We have to take in account those two distribution flavors in order to determine which
927
+ names should be considered for assertion rewriting.
928
+
929
+ More information:
930
+ https://github.com/pytest-dev/pytest-mock/issues/167
931
+ """
932
+ package_files = list(package_files)
933
+ seen_some = False
934
+ for fn in package_files:
935
+ is_simple_module = "/" not in fn and fn.endswith(".py")
936
+ is_package = fn.count("/") == 1 and fn.endswith("__init__.py")
937
+ if is_simple_module:
938
+ module_name, _ = os.path.splitext(fn)
939
+ # we ignore "setup.py" at the root of the distribution
940
+ # as well as editable installation finder modules made by setuptools
941
+ if module_name != "setup" and not module_name.startswith("__editable__"):
942
+ seen_some = True
943
+ yield module_name
944
+ elif is_package:
945
+ package_name = os.path.dirname(fn)
946
+ seen_some = True
947
+ yield package_name
948
+
949
+ if not seen_some:
950
+ # At this point we did not find any packages or modules suitable for assertion
951
+ # rewriting, so we try again by stripping the first path component (to account for
952
+ # "src" based source trees for example).
953
+ # This approach lets us have the common case continue to be fast, as egg-distributions
954
+ # are rarer.
955
+ new_package_files = []
956
+ for fn in package_files:
957
+ parts = fn.split("/")
958
+ new_fn = "/".join(parts[1:])
959
+ if new_fn:
960
+ new_package_files.append(new_fn)
961
+ if new_package_files:
962
+ yield from _iter_rewritable_modules(new_package_files)
963
+
964
+
965
+ @final
966
+ class Config:
967
+ """Access to configuration values, pluginmanager and plugin hooks.
968
+
969
+ :param PytestPluginManager pluginmanager:
970
+ A pytest PluginManager.
971
+
972
+ :param InvocationParams invocation_params:
973
+ Object containing parameters regarding the :func:`pytest.main`
974
+ invocation.
975
+ """
976
+
977
+ @final
978
+ @dataclasses.dataclass(frozen=True)
979
+ class InvocationParams:
980
+ """Holds parameters passed during :func:`pytest.main`.
981
+
982
+ The object attributes are read-only.
983
+
984
+ .. versionadded:: 5.1
985
+
986
+ .. note::
987
+
988
+ Note that the environment variable ``PYTEST_ADDOPTS`` and the ``addopts``
989
+ ini option are handled by pytest, not being included in the ``args`` attribute.
990
+
991
+ Plugins accessing ``InvocationParams`` must be aware of that.
992
+ """
993
+
994
+ args: tuple[str, ...]
995
+ """The command-line arguments as passed to :func:`pytest.main`."""
996
+ plugins: Sequence[str | _PluggyPlugin] | None
997
+ """Extra plugins, might be `None`."""
998
+ dir: pathlib.Path
999
+ """The directory from which :func:`pytest.main` was invoked. :type: pathlib.Path"""
1000
+
1001
+ def __init__(
1002
+ self,
1003
+ *,
1004
+ args: Iterable[str],
1005
+ plugins: Sequence[str | _PluggyPlugin] | None,
1006
+ dir: pathlib.Path,
1007
+ ) -> None:
1008
+ object.__setattr__(self, "args", tuple(args))
1009
+ object.__setattr__(self, "plugins", plugins)
1010
+ object.__setattr__(self, "dir", dir)
1011
+
1012
+ class ArgsSource(enum.Enum):
1013
+ """Indicates the source of the test arguments.
1014
+
1015
+ .. versionadded:: 7.2
1016
+ """
1017
+
1018
+ #: Command line arguments.
1019
+ ARGS = enum.auto()
1020
+ #: Invocation directory.
1021
+ INVOCATION_DIR = enum.auto()
1022
+ INCOVATION_DIR = INVOCATION_DIR # backwards compatibility alias
1023
+ #: 'testpaths' configuration value.
1024
+ TESTPATHS = enum.auto()
1025
+
1026
+ # Set by cacheprovider plugin.
1027
+ cache: Cache
1028
+
1029
+ def __init__(
1030
+ self,
1031
+ pluginmanager: PytestPluginManager,
1032
+ *,
1033
+ invocation_params: InvocationParams | None = None,
1034
+ ) -> None:
1035
+ from .argparsing import FILE_OR_DIR
1036
+ from .argparsing import Parser
1037
+
1038
+ if invocation_params is None:
1039
+ invocation_params = self.InvocationParams(
1040
+ args=(), plugins=None, dir=pathlib.Path.cwd()
1041
+ )
1042
+
1043
+ self.option = argparse.Namespace()
1044
+ """Access to command line option as attributes.
1045
+
1046
+ :type: argparse.Namespace
1047
+ """
1048
+
1049
+ self.invocation_params = invocation_params
1050
+ """The parameters with which pytest was invoked.
1051
+
1052
+ :type: InvocationParams
1053
+ """
1054
+
1055
+ _a = FILE_OR_DIR
1056
+ self._parser = Parser(
1057
+ usage=f"%(prog)s [options] [{_a}] [{_a}] [...]",
1058
+ processopt=self._processopt,
1059
+ _ispytest=True,
1060
+ )
1061
+ self.pluginmanager = pluginmanager
1062
+ """The plugin manager handles plugin registration and hook invocation.
1063
+
1064
+ :type: PytestPluginManager
1065
+ """
1066
+
1067
+ self.stash = Stash()
1068
+ """A place where plugins can store information on the config for their
1069
+ own use.
1070
+
1071
+ :type: Stash
1072
+ """
1073
+ # Deprecated alias. Was never public. Can be removed in a few releases.
1074
+ self._store = self.stash
1075
+
1076
+ self.trace = self.pluginmanager.trace.root.get("config")
1077
+ self.hook: pluggy.HookRelay = PathAwareHookProxy(self.pluginmanager.hook) # type: ignore[assignment]
1078
+ self._inicache: dict[str, Any] = {}
1079
+ self._override_ini: Sequence[str] = ()
1080
+ self._opt2dest: dict[str, str] = {}
1081
+ self._cleanup: list[Callable[[], None]] = []
1082
+ self.pluginmanager.register(self, "pytestconfig")
1083
+ self._configured = False
1084
+ self.hook.pytest_addoption.call_historic(
1085
+ kwargs=dict(parser=self._parser, pluginmanager=self.pluginmanager)
1086
+ )
1087
+ self.args_source = Config.ArgsSource.ARGS
1088
+ self.args: list[str] = []
1089
+
1090
+ @property
1091
+ def rootpath(self) -> pathlib.Path:
1092
+ """The path to the :ref:`rootdir <rootdir>`.
1093
+
1094
+ :type: pathlib.Path
1095
+
1096
+ .. versionadded:: 6.1
1097
+ """
1098
+ return self._rootpath
1099
+
1100
+ @property
1101
+ def inipath(self) -> pathlib.Path | None:
1102
+ """The path to the :ref:`configfile <configfiles>`.
1103
+
1104
+ .. versionadded:: 6.1
1105
+ """
1106
+ return self._inipath
1107
+
1108
+ def add_cleanup(self, func: Callable[[], None]) -> None:
1109
+ """Add a function to be called when the config object gets out of
1110
+ use (usually coinciding with pytest_unconfigure)."""
1111
+ self._cleanup.append(func)
1112
+
1113
+ def _do_configure(self) -> None:
1114
+ assert not self._configured
1115
+ self._configured = True
1116
+ with warnings.catch_warnings():
1117
+ warnings.simplefilter("default")
1118
+ self.hook.pytest_configure.call_historic(kwargs=dict(config=self))
1119
+
1120
+ def _ensure_unconfigure(self) -> None:
1121
+ if self._configured:
1122
+ self._configured = False
1123
+ self.hook.pytest_unconfigure(config=self)
1124
+ self.hook.pytest_configure._call_history = []
1125
+ while self._cleanup:
1126
+ fin = self._cleanup.pop()
1127
+ fin()
1128
+
1129
+ def get_terminal_writer(self) -> TerminalWriter:
1130
+ terminalreporter: TerminalReporter | None = self.pluginmanager.get_plugin(
1131
+ "terminalreporter"
1132
+ )
1133
+ assert terminalreporter is not None
1134
+ return terminalreporter._tw
1135
+
1136
+ def pytest_cmdline_parse(
1137
+ self, pluginmanager: PytestPluginManager, args: list[str]
1138
+ ) -> Config:
1139
+ try:
1140
+ self.parse(args)
1141
+ except UsageError:
1142
+ # Handle --version and --help here in a minimal fashion.
1143
+ # This gets done via helpconfig normally, but its
1144
+ # pytest_cmdline_main is not called in case of errors.
1145
+ if getattr(self.option, "version", False) or "--version" in args:
1146
+ from _pytest.helpconfig import showversion
1147
+
1148
+ showversion(self)
1149
+ elif (
1150
+ getattr(self.option, "help", False) or "--help" in args or "-h" in args
1151
+ ):
1152
+ self._parser._getparser().print_help()
1153
+ sys.stdout.write(
1154
+ "\nNOTE: displaying only minimal help due to UsageError.\n\n"
1155
+ )
1156
+
1157
+ raise
1158
+
1159
+ return self
1160
+
1161
+ def notify_exception(
1162
+ self,
1163
+ excinfo: ExceptionInfo[BaseException],
1164
+ option: argparse.Namespace | None = None,
1165
+ ) -> None:
1166
+ if option and getattr(option, "fulltrace", False):
1167
+ style: TracebackStyle = "long"
1168
+ else:
1169
+ style = "native"
1170
+ excrepr = excinfo.getrepr(
1171
+ funcargs=True, showlocals=getattr(option, "showlocals", False), style=style
1172
+ )
1173
+ res = self.hook.pytest_internalerror(excrepr=excrepr, excinfo=excinfo)
1174
+ if not any(res):
1175
+ for line in str(excrepr).split("\n"):
1176
+ sys.stderr.write(f"INTERNALERROR> {line}\n")
1177
+ sys.stderr.flush()
1178
+
1179
+ def cwd_relative_nodeid(self, nodeid: str) -> str:
1180
+ # nodeid's are relative to the rootpath, compute relative to cwd.
1181
+ if self.invocation_params.dir != self.rootpath:
1182
+ base_path_part, *nodeid_part = nodeid.split("::")
1183
+ # Only process path part
1184
+ fullpath = self.rootpath / base_path_part
1185
+ relative_path = bestrelpath(self.invocation_params.dir, fullpath)
1186
+
1187
+ nodeid = "::".join([relative_path, *nodeid_part])
1188
+ return nodeid
1189
+
1190
+ @classmethod
1191
+ def fromdictargs(cls, option_dict, args) -> Config:
1192
+ """Constructor usable for subprocesses."""
1193
+ config = get_config(args)
1194
+ config.option.__dict__.update(option_dict)
1195
+ config.parse(args, addopts=False)
1196
+ for x in config.option.plugins:
1197
+ config.pluginmanager.consider_pluginarg(x)
1198
+ return config
1199
+
1200
+ def _processopt(self, opt: Argument) -> None:
1201
+ for name in opt._short_opts + opt._long_opts:
1202
+ self._opt2dest[name] = opt.dest
1203
+
1204
+ if hasattr(opt, "default"):
1205
+ if not hasattr(self.option, opt.dest):
1206
+ setattr(self.option, opt.dest, opt.default)
1207
+
1208
+ @hookimpl(trylast=True)
1209
+ def pytest_load_initial_conftests(self, early_config: Config) -> None:
1210
+ # We haven't fully parsed the command line arguments yet, so
1211
+ # early_config.args it not set yet. But we need it for
1212
+ # discovering the initial conftests. So "pre-run" the logic here.
1213
+ # It will be done for real in `parse()`.
1214
+ args, args_source = early_config._decide_args(
1215
+ args=early_config.known_args_namespace.file_or_dir,
1216
+ pyargs=early_config.known_args_namespace.pyargs,
1217
+ testpaths=early_config.getini("testpaths"),
1218
+ invocation_dir=early_config.invocation_params.dir,
1219
+ rootpath=early_config.rootpath,
1220
+ warn=False,
1221
+ )
1222
+ self.pluginmanager._set_initial_conftests(
1223
+ args=args,
1224
+ pyargs=early_config.known_args_namespace.pyargs,
1225
+ noconftest=early_config.known_args_namespace.noconftest,
1226
+ rootpath=early_config.rootpath,
1227
+ confcutdir=early_config.known_args_namespace.confcutdir,
1228
+ invocation_dir=early_config.invocation_params.dir,
1229
+ importmode=early_config.known_args_namespace.importmode,
1230
+ consider_namespace_packages=early_config.getini(
1231
+ "consider_namespace_packages"
1232
+ ),
1233
+ )
1234
+
1235
+ def _initini(self, args: Sequence[str]) -> None:
1236
+ ns, unknown_args = self._parser.parse_known_and_unknown_args(
1237
+ args, namespace=copy.copy(self.option)
1238
+ )
1239
+ rootpath, inipath, inicfg = determine_setup(
1240
+ inifile=ns.inifilename,
1241
+ args=ns.file_or_dir + unknown_args,
1242
+ rootdir_cmd_arg=ns.rootdir or None,
1243
+ invocation_dir=self.invocation_params.dir,
1244
+ )
1245
+ self._rootpath = rootpath
1246
+ self._inipath = inipath
1247
+ self.inicfg = inicfg
1248
+ self._parser.extra_info["rootdir"] = str(self.rootpath)
1249
+ self._parser.extra_info["inifile"] = str(self.inipath)
1250
+ self._parser.addini("addopts", "Extra command line options", "args")
1251
+ self._parser.addini("minversion", "Minimally required pytest version")
1252
+ self._parser.addini(
1253
+ "required_plugins",
1254
+ "Plugins that must be present for pytest to run",
1255
+ type="args",
1256
+ default=[],
1257
+ )
1258
+ self._override_ini = ns.override_ini or ()
1259
+
1260
+ def _consider_importhook(self, args: Sequence[str]) -> None:
1261
+ """Install the PEP 302 import hook if using assertion rewriting.
1262
+
1263
+ Needs to parse the --assert=<mode> option from the commandline
1264
+ and find all the installed plugins to mark them for rewriting
1265
+ by the importhook.
1266
+ """
1267
+ ns, unknown_args = self._parser.parse_known_and_unknown_args(args)
1268
+ mode = getattr(ns, "assertmode", "plain")
1269
+ if mode == "rewrite":
1270
+ import _pytest.assertion
1271
+
1272
+ try:
1273
+ hook = _pytest.assertion.install_importhook(self)
1274
+ except SystemError:
1275
+ mode = "plain"
1276
+ else:
1277
+ self._mark_plugins_for_rewrite(hook)
1278
+ self._warn_about_missing_assertion(mode)
1279
+
1280
+ def _mark_plugins_for_rewrite(self, hook) -> None:
1281
+ """Given an importhook, mark for rewrite any top-level
1282
+ modules or packages in the distribution package for
1283
+ all pytest plugins."""
1284
+ self.pluginmanager.rewrite_hook = hook
1285
+
1286
+ if os.environ.get("PYTEST_DISABLE_PLUGIN_AUTOLOAD"):
1287
+ # We don't autoload from distribution package entry points,
1288
+ # no need to continue.
1289
+ return
1290
+
1291
+ package_files = (
1292
+ str(file)
1293
+ for dist in importlib.metadata.distributions()
1294
+ if any(ep.group == "pytest11" for ep in dist.entry_points)
1295
+ for file in dist.files or []
1296
+ )
1297
+
1298
+ for name in _iter_rewritable_modules(package_files):
1299
+ hook.mark_rewrite(name)
1300
+
1301
+ def _validate_args(self, args: list[str], via: str) -> list[str]:
1302
+ """Validate known args."""
1303
+ self._parser._config_source_hint = via # type: ignore
1304
+ try:
1305
+ self._parser.parse_known_and_unknown_args(
1306
+ args, namespace=copy.copy(self.option)
1307
+ )
1308
+ finally:
1309
+ del self._parser._config_source_hint # type: ignore
1310
+
1311
+ return args
1312
+
1313
+ def _decide_args(
1314
+ self,
1315
+ *,
1316
+ args: list[str],
1317
+ pyargs: bool,
1318
+ testpaths: list[str],
1319
+ invocation_dir: pathlib.Path,
1320
+ rootpath: pathlib.Path,
1321
+ warn: bool,
1322
+ ) -> tuple[list[str], ArgsSource]:
1323
+ """Decide the args (initial paths/nodeids) to use given the relevant inputs.
1324
+
1325
+ :param warn: Whether can issue warnings.
1326
+
1327
+ :returns: The args and the args source. Guaranteed to be non-empty.
1328
+ """
1329
+ if args:
1330
+ source = Config.ArgsSource.ARGS
1331
+ result = args
1332
+ else:
1333
+ if invocation_dir == rootpath:
1334
+ source = Config.ArgsSource.TESTPATHS
1335
+ if pyargs:
1336
+ result = testpaths
1337
+ else:
1338
+ result = []
1339
+ for path in testpaths:
1340
+ result.extend(sorted(glob.iglob(path, recursive=True)))
1341
+ if testpaths and not result:
1342
+ if warn:
1343
+ warning_text = (
1344
+ "No files were found in testpaths; "
1345
+ "consider removing or adjusting your testpaths configuration. "
1346
+ "Searching recursively from the current directory instead."
1347
+ )
1348
+ self.issue_config_time_warning(
1349
+ PytestConfigWarning(warning_text), stacklevel=3
1350
+ )
1351
+ else:
1352
+ result = []
1353
+ if not result:
1354
+ source = Config.ArgsSource.INVOCATION_DIR
1355
+ result = [str(invocation_dir)]
1356
+ return result, source
1357
+
1358
+ def _preparse(self, args: list[str], addopts: bool = True) -> None:
1359
+ if addopts:
1360
+ env_addopts = os.environ.get("PYTEST_ADDOPTS", "")
1361
+ if len(env_addopts):
1362
+ args[:] = (
1363
+ self._validate_args(shlex.split(env_addopts), "via PYTEST_ADDOPTS")
1364
+ + args
1365
+ )
1366
+ self._initini(args)
1367
+ if addopts:
1368
+ args[:] = (
1369
+ self._validate_args(self.getini("addopts"), "via addopts config") + args
1370
+ )
1371
+
1372
+ self.known_args_namespace = self._parser.parse_known_args(
1373
+ args, namespace=copy.copy(self.option)
1374
+ )
1375
+ self._checkversion()
1376
+ self._consider_importhook(args)
1377
+ self.pluginmanager.consider_preparse(args, exclude_only=False)
1378
+ if not os.environ.get("PYTEST_DISABLE_PLUGIN_AUTOLOAD"):
1379
+ # Don't autoload from distribution package entry point. Only
1380
+ # explicitly specified plugins are going to be loaded.
1381
+ self.pluginmanager.load_setuptools_entrypoints("pytest11")
1382
+ self.pluginmanager.consider_env()
1383
+
1384
+ self.known_args_namespace = self._parser.parse_known_args(
1385
+ args, namespace=copy.copy(self.known_args_namespace)
1386
+ )
1387
+
1388
+ self._validate_plugins()
1389
+ self._warn_about_skipped_plugins()
1390
+
1391
+ if self.known_args_namespace.confcutdir is None:
1392
+ if self.inipath is not None:
1393
+ confcutdir = str(self.inipath.parent)
1394
+ else:
1395
+ confcutdir = str(self.rootpath)
1396
+ self.known_args_namespace.confcutdir = confcutdir
1397
+ try:
1398
+ self.hook.pytest_load_initial_conftests(
1399
+ early_config=self, args=args, parser=self._parser
1400
+ )
1401
+ except ConftestImportFailure as e:
1402
+ if self.known_args_namespace.help or self.known_args_namespace.version:
1403
+ # we don't want to prevent --help/--version to work
1404
+ # so just let is pass and print a warning at the end
1405
+ self.issue_config_time_warning(
1406
+ PytestConfigWarning(f"could not load initial conftests: {e.path}"),
1407
+ stacklevel=2,
1408
+ )
1409
+ else:
1410
+ raise
1411
+
1412
+ @hookimpl(wrapper=True)
1413
+ def pytest_collection(self) -> Generator[None, object, object]:
1414
+ # Validate invalid ini keys after collection is done so we take in account
1415
+ # options added by late-loading conftest files.
1416
+ try:
1417
+ return (yield)
1418
+ finally:
1419
+ self._validate_config_options()
1420
+
1421
+ def _checkversion(self) -> None:
1422
+ import pytest
1423
+
1424
+ minver = self.inicfg.get("minversion", None)
1425
+ if minver:
1426
+ # Imported lazily to improve start-up time.
1427
+ from packaging.version import Version
1428
+
1429
+ if not isinstance(minver, str):
1430
+ raise pytest.UsageError(
1431
+ f"{self.inipath}: 'minversion' must be a single value"
1432
+ )
1433
+
1434
+ if Version(minver) > Version(pytest.__version__):
1435
+ raise pytest.UsageError(
1436
+ f"{self.inipath}: 'minversion' requires pytest-{minver}, actual pytest-{pytest.__version__}'"
1437
+ )
1438
+
1439
+ def _validate_config_options(self) -> None:
1440
+ for key in sorted(self._get_unknown_ini_keys()):
1441
+ self._warn_or_fail_if_strict(f"Unknown config option: {key}\n")
1442
+
1443
+ def _validate_plugins(self) -> None:
1444
+ required_plugins = sorted(self.getini("required_plugins"))
1445
+ if not required_plugins:
1446
+ return
1447
+
1448
+ # Imported lazily to improve start-up time.
1449
+ from packaging.requirements import InvalidRequirement
1450
+ from packaging.requirements import Requirement
1451
+ from packaging.version import Version
1452
+
1453
+ plugin_info = self.pluginmanager.list_plugin_distinfo()
1454
+ plugin_dist_info = {dist.project_name: dist.version for _, dist in plugin_info}
1455
+
1456
+ missing_plugins = []
1457
+ for required_plugin in required_plugins:
1458
+ try:
1459
+ req = Requirement(required_plugin)
1460
+ except InvalidRequirement:
1461
+ missing_plugins.append(required_plugin)
1462
+ continue
1463
+
1464
+ if req.name not in plugin_dist_info:
1465
+ missing_plugins.append(required_plugin)
1466
+ elif not req.specifier.contains(
1467
+ Version(plugin_dist_info[req.name]), prereleases=True
1468
+ ):
1469
+ missing_plugins.append(required_plugin)
1470
+
1471
+ if missing_plugins:
1472
+ raise UsageError(
1473
+ "Missing required plugins: {}".format(", ".join(missing_plugins)),
1474
+ )
1475
+
1476
+ def _warn_or_fail_if_strict(self, message: str) -> None:
1477
+ if self.known_args_namespace.strict_config:
1478
+ raise UsageError(message)
1479
+
1480
+ self.issue_config_time_warning(PytestConfigWarning(message), stacklevel=3)
1481
+
1482
+ def _get_unknown_ini_keys(self) -> list[str]:
1483
+ parser_inicfg = self._parser._inidict
1484
+ return [name for name in self.inicfg if name not in parser_inicfg]
1485
+
1486
+ def parse(self, args: list[str], addopts: bool = True) -> None:
1487
+ # Parse given cmdline arguments into this config object.
1488
+ assert (
1489
+ self.args == []
1490
+ ), "can only parse cmdline args at most once per Config object"
1491
+ self.hook.pytest_addhooks.call_historic(
1492
+ kwargs=dict(pluginmanager=self.pluginmanager)
1493
+ )
1494
+ self._preparse(args, addopts=addopts)
1495
+ self._parser.after_preparse = True # type: ignore
1496
+ try:
1497
+ args = self._parser.parse_setoption(
1498
+ args, self.option, namespace=self.option
1499
+ )
1500
+ self.args, self.args_source = self._decide_args(
1501
+ args=args,
1502
+ pyargs=self.known_args_namespace.pyargs,
1503
+ testpaths=self.getini("testpaths"),
1504
+ invocation_dir=self.invocation_params.dir,
1505
+ rootpath=self.rootpath,
1506
+ warn=True,
1507
+ )
1508
+ except PrintHelp:
1509
+ pass
1510
+
1511
+ def issue_config_time_warning(self, warning: Warning, stacklevel: int) -> None:
1512
+ """Issue and handle a warning during the "configure" stage.
1513
+
1514
+ During ``pytest_configure`` we can't capture warnings using the ``catch_warnings_for_item``
1515
+ function because it is not possible to have hook wrappers around ``pytest_configure``.
1516
+
1517
+ This function is mainly intended for plugins that need to issue warnings during
1518
+ ``pytest_configure`` (or similar stages).
1519
+
1520
+ :param warning: The warning instance.
1521
+ :param stacklevel: stacklevel forwarded to warnings.warn.
1522
+ """
1523
+ if self.pluginmanager.is_blocked("warnings"):
1524
+ return
1525
+
1526
+ cmdline_filters = self.known_args_namespace.pythonwarnings or []
1527
+ config_filters = self.getini("filterwarnings")
1528
+
1529
+ with warnings.catch_warnings(record=True) as records:
1530
+ warnings.simplefilter("always", type(warning))
1531
+ apply_warning_filters(config_filters, cmdline_filters)
1532
+ warnings.warn(warning, stacklevel=stacklevel)
1533
+
1534
+ if records:
1535
+ frame = sys._getframe(stacklevel - 1)
1536
+ location = frame.f_code.co_filename, frame.f_lineno, frame.f_code.co_name
1537
+ self.hook.pytest_warning_recorded.call_historic(
1538
+ kwargs=dict(
1539
+ warning_message=records[0],
1540
+ when="config",
1541
+ nodeid="",
1542
+ location=location,
1543
+ )
1544
+ )
1545
+
1546
+ def addinivalue_line(self, name: str, line: str) -> None:
1547
+ """Add a line to an ini-file option. The option must have been
1548
+ declared but might not yet be set in which case the line becomes
1549
+ the first line in its value."""
1550
+ x = self.getini(name)
1551
+ assert isinstance(x, list)
1552
+ x.append(line) # modifies the cached list inline
1553
+
1554
+ def getini(self, name: str):
1555
+ """Return configuration value from an :ref:`ini file <configfiles>`.
1556
+
1557
+ If a configuration value is not defined in an
1558
+ :ref:`ini file <configfiles>`, then the ``default`` value provided while
1559
+ registering the configuration through
1560
+ :func:`parser.addini <pytest.Parser.addini>` will be returned.
1561
+ Please note that you can even provide ``None`` as a valid
1562
+ default value.
1563
+
1564
+ If ``default`` is not provided while registering using
1565
+ :func:`parser.addini <pytest.Parser.addini>`, then a default value
1566
+ based on the ``type`` parameter passed to
1567
+ :func:`parser.addini <pytest.Parser.addini>` will be returned.
1568
+ The default values based on ``type`` are:
1569
+ ``paths``, ``pathlist``, ``args`` and ``linelist`` : empty list ``[]``
1570
+ ``bool`` : ``False``
1571
+ ``string`` : empty string ``""``
1572
+
1573
+ If neither the ``default`` nor the ``type`` parameter is passed
1574
+ while registering the configuration through
1575
+ :func:`parser.addini <pytest.Parser.addini>`, then the configuration
1576
+ is treated as a string and a default empty string '' is returned.
1577
+
1578
+ If the specified name hasn't been registered through a prior
1579
+ :func:`parser.addini <pytest.Parser.addini>` call (usually from a
1580
+ plugin), a ValueError is raised.
1581
+ """
1582
+ try:
1583
+ return self._inicache[name]
1584
+ except KeyError:
1585
+ self._inicache[name] = val = self._getini(name)
1586
+ return val
1587
+
1588
+ # Meant for easy monkeypatching by legacypath plugin.
1589
+ # Can be inlined back (with no cover removed) once legacypath is gone.
1590
+ def _getini_unknown_type(self, name: str, type: str, value: str | list[str]):
1591
+ msg = f"unknown configuration type: {type}"
1592
+ raise ValueError(msg, value) # pragma: no cover
1593
+
1594
+ def _getini(self, name: str):
1595
+ try:
1596
+ description, type, default = self._parser._inidict[name]
1597
+ except KeyError as e:
1598
+ raise ValueError(f"unknown configuration value: {name!r}") from e
1599
+ override_value = self._get_override_ini_value(name)
1600
+ if override_value is None:
1601
+ try:
1602
+ value = self.inicfg[name]
1603
+ except KeyError:
1604
+ return default
1605
+ else:
1606
+ value = override_value
1607
+ # Coerce the values based on types.
1608
+ #
1609
+ # Note: some coercions are only required if we are reading from .ini files, because
1610
+ # the file format doesn't contain type information, but when reading from toml we will
1611
+ # get either str or list of str values (see _parse_ini_config_from_pyproject_toml).
1612
+ # For example:
1613
+ #
1614
+ # ini:
1615
+ # a_line_list = "tests acceptance"
1616
+ # in this case, we need to split the string to obtain a list of strings.
1617
+ #
1618
+ # toml:
1619
+ # a_line_list = ["tests", "acceptance"]
1620
+ # in this case, we already have a list ready to use.
1621
+ #
1622
+ if type == "paths":
1623
+ dp = (
1624
+ self.inipath.parent
1625
+ if self.inipath is not None
1626
+ else self.invocation_params.dir
1627
+ )
1628
+ input_values = shlex.split(value) if isinstance(value, str) else value
1629
+ return [dp / x for x in input_values]
1630
+ elif type == "args":
1631
+ return shlex.split(value) if isinstance(value, str) else value
1632
+ elif type == "linelist":
1633
+ if isinstance(value, str):
1634
+ return [t for t in map(lambda x: x.strip(), value.split("\n")) if t]
1635
+ else:
1636
+ return value
1637
+ elif type == "bool":
1638
+ return _strtobool(str(value).strip())
1639
+ elif type == "string":
1640
+ return value
1641
+ elif type is None:
1642
+ return value
1643
+ else:
1644
+ return self._getini_unknown_type(name, type, value)
1645
+
1646
+ def _getconftest_pathlist(
1647
+ self, name: str, path: pathlib.Path
1648
+ ) -> list[pathlib.Path] | None:
1649
+ try:
1650
+ mod, relroots = self.pluginmanager._rget_with_confmod(name, path)
1651
+ except KeyError:
1652
+ return None
1653
+ assert mod.__file__ is not None
1654
+ modpath = pathlib.Path(mod.__file__).parent
1655
+ values: list[pathlib.Path] = []
1656
+ for relroot in relroots:
1657
+ if isinstance(relroot, os.PathLike):
1658
+ relroot = pathlib.Path(relroot)
1659
+ else:
1660
+ relroot = relroot.replace("/", os.sep)
1661
+ relroot = absolutepath(modpath / relroot)
1662
+ values.append(relroot)
1663
+ return values
1664
+
1665
+ def _get_override_ini_value(self, name: str) -> str | None:
1666
+ value = None
1667
+ # override_ini is a list of "ini=value" options.
1668
+ # Always use the last item if multiple values are set for same ini-name,
1669
+ # e.g. -o foo=bar1 -o foo=bar2 will set foo to bar2.
1670
+ for ini_config in self._override_ini:
1671
+ try:
1672
+ key, user_ini_value = ini_config.split("=", 1)
1673
+ except ValueError as e:
1674
+ raise UsageError(
1675
+ f"-o/--override-ini expects option=value style (got: {ini_config!r})."
1676
+ ) from e
1677
+ else:
1678
+ if key == name:
1679
+ value = user_ini_value
1680
+ return value
1681
+
1682
+ def getoption(self, name: str, default=notset, skip: bool = False):
1683
+ """Return command line option value.
1684
+
1685
+ :param name: Name of the option. You may also specify
1686
+ the literal ``--OPT`` option instead of the "dest" option name.
1687
+ :param default: Fallback value if no option of that name is **declared** via :hook:`pytest_addoption`.
1688
+ Note this parameter will be ignored when the option is **declared** even if the option's value is ``None``.
1689
+ :param skip: If ``True``, raise :func:`pytest.skip` if option is undeclared or has a ``None`` value.
1690
+ Note that even if ``True``, if a default was specified it will be returned instead of a skip.
1691
+ """
1692
+ name = self._opt2dest.get(name, name)
1693
+ try:
1694
+ val = getattr(self.option, name)
1695
+ if val is None and skip:
1696
+ raise AttributeError(name)
1697
+ return val
1698
+ except AttributeError as e:
1699
+ if default is not notset:
1700
+ return default
1701
+ if skip:
1702
+ import pytest
1703
+
1704
+ pytest.skip(f"no {name!r} option found")
1705
+ raise ValueError(f"no option named {name!r}") from e
1706
+
1707
+ def getvalue(self, name: str, path=None):
1708
+ """Deprecated, use getoption() instead."""
1709
+ return self.getoption(name)
1710
+
1711
+ def getvalueorskip(self, name: str, path=None):
1712
+ """Deprecated, use getoption(skip=True) instead."""
1713
+ return self.getoption(name, skip=True)
1714
+
1715
+ #: Verbosity type for failed assertions (see :confval:`verbosity_assertions`).
1716
+ VERBOSITY_ASSERTIONS: Final = "assertions"
1717
+ #: Verbosity type for test case execution (see :confval:`verbosity_test_cases`).
1718
+ VERBOSITY_TEST_CASES: Final = "test_cases"
1719
+ _VERBOSITY_INI_DEFAULT: Final = "auto"
1720
+
1721
+ def get_verbosity(self, verbosity_type: str | None = None) -> int:
1722
+ r"""Retrieve the verbosity level for a fine-grained verbosity type.
1723
+
1724
+ :param verbosity_type: Verbosity type to get level for. If a level is
1725
+ configured for the given type, that value will be returned. If the
1726
+ given type is not a known verbosity type, the global verbosity
1727
+ level will be returned. If the given type is None (default), the
1728
+ global verbosity level will be returned.
1729
+
1730
+ To configure a level for a fine-grained verbosity type, the
1731
+ configuration file should have a setting for the configuration name
1732
+ and a numeric value for the verbosity level. A special value of "auto"
1733
+ can be used to explicitly use the global verbosity level.
1734
+
1735
+ Example:
1736
+
1737
+ .. code-block:: ini
1738
+
1739
+ # content of pytest.ini
1740
+ [pytest]
1741
+ verbosity_assertions = 2
1742
+
1743
+ .. code-block:: console
1744
+
1745
+ pytest -v
1746
+
1747
+ .. code-block:: python
1748
+
1749
+ print(config.get_verbosity()) # 1
1750
+ print(config.get_verbosity(Config.VERBOSITY_ASSERTIONS)) # 2
1751
+ """
1752
+ global_level = self.getoption("verbose", default=0)
1753
+ assert isinstance(global_level, int)
1754
+ if verbosity_type is None:
1755
+ return global_level
1756
+
1757
+ ini_name = Config._verbosity_ini_name(verbosity_type)
1758
+ if ini_name not in self._parser._inidict:
1759
+ return global_level
1760
+
1761
+ level = self.getini(ini_name)
1762
+ if level == Config._VERBOSITY_INI_DEFAULT:
1763
+ return global_level
1764
+
1765
+ return int(level)
1766
+
1767
+ @staticmethod
1768
+ def _verbosity_ini_name(verbosity_type: str) -> str:
1769
+ return f"verbosity_{verbosity_type}"
1770
+
1771
+ @staticmethod
1772
+ def _add_verbosity_ini(parser: Parser, verbosity_type: str, help: str) -> None:
1773
+ """Add a output verbosity configuration option for the given output type.
1774
+
1775
+ :param parser: Parser for command line arguments and ini-file values.
1776
+ :param verbosity_type: Fine-grained verbosity category.
1777
+ :param help: Description of the output this type controls.
1778
+
1779
+ The value should be retrieved via a call to
1780
+ :py:func:`config.get_verbosity(type) <pytest.Config.get_verbosity>`.
1781
+ """
1782
+ parser.addini(
1783
+ Config._verbosity_ini_name(verbosity_type),
1784
+ help=help,
1785
+ type="string",
1786
+ default=Config._VERBOSITY_INI_DEFAULT,
1787
+ )
1788
+
1789
+ def _warn_about_missing_assertion(self, mode: str) -> None:
1790
+ if not _assertion_supported():
1791
+ if mode == "plain":
1792
+ warning_text = (
1793
+ "ASSERTIONS ARE NOT EXECUTED"
1794
+ " and FAILING TESTS WILL PASS. Are you"
1795
+ " using python -O?"
1796
+ )
1797
+ else:
1798
+ warning_text = (
1799
+ "assertions not in test modules or"
1800
+ " plugins will be ignored"
1801
+ " because assert statements are not executed "
1802
+ "by the underlying Python interpreter "
1803
+ "(are you using python -O?)\n"
1804
+ )
1805
+ self.issue_config_time_warning(
1806
+ PytestConfigWarning(warning_text),
1807
+ stacklevel=3,
1808
+ )
1809
+
1810
+ def _warn_about_skipped_plugins(self) -> None:
1811
+ for module_name, msg in self.pluginmanager.skipped_plugins:
1812
+ self.issue_config_time_warning(
1813
+ PytestConfigWarning(f"skipped plugin {module_name!r}: {msg}"),
1814
+ stacklevel=2,
1815
+ )
1816
+
1817
+
1818
+ def _assertion_supported() -> bool:
1819
+ try:
1820
+ assert False
1821
+ except AssertionError:
1822
+ return True
1823
+ else:
1824
+ return False # type: ignore[unreachable]
1825
+
1826
+
1827
+ def create_terminal_writer(
1828
+ config: Config, file: TextIO | None = None
1829
+ ) -> TerminalWriter:
1830
+ """Create a TerminalWriter instance configured according to the options
1831
+ in the config object.
1832
+
1833
+ Every code which requires a TerminalWriter object and has access to a
1834
+ config object should use this function.
1835
+ """
1836
+ tw = TerminalWriter(file=file)
1837
+
1838
+ if config.option.color == "yes":
1839
+ tw.hasmarkup = True
1840
+ elif config.option.color == "no":
1841
+ tw.hasmarkup = False
1842
+
1843
+ if config.option.code_highlight == "yes":
1844
+ tw.code_highlight = True
1845
+ elif config.option.code_highlight == "no":
1846
+ tw.code_highlight = False
1847
+
1848
+ return tw
1849
+
1850
+
1851
+ def _strtobool(val: str) -> bool:
1852
+ """Convert a string representation of truth to True or False.
1853
+
1854
+ True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
1855
+ are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
1856
+ 'val' is anything else.
1857
+
1858
+ .. note:: Copied from distutils.util.
1859
+ """
1860
+ val = val.lower()
1861
+ if val in ("y", "yes", "t", "true", "on", "1"):
1862
+ return True
1863
+ elif val in ("n", "no", "f", "false", "off", "0"):
1864
+ return False
1865
+ else:
1866
+ raise ValueError(f"invalid truth value {val!r}")
1867
+
1868
+
1869
+ @lru_cache(maxsize=50)
1870
+ def parse_warning_filter(
1871
+ arg: str, *, escape: bool
1872
+ ) -> tuple[warnings._ActionKind, str, type[Warning], str, int]:
1873
+ """Parse a warnings filter string.
1874
+
1875
+ This is copied from warnings._setoption with the following changes:
1876
+
1877
+ * Does not apply the filter.
1878
+ * Escaping is optional.
1879
+ * Raises UsageError so we get nice error messages on failure.
1880
+ """
1881
+ __tracebackhide__ = True
1882
+ error_template = dedent(
1883
+ f"""\
1884
+ while parsing the following warning configuration:
1885
+
1886
+ {arg}
1887
+
1888
+ This error occurred:
1889
+
1890
+ {{error}}
1891
+ """
1892
+ )
1893
+
1894
+ parts = arg.split(":")
1895
+ if len(parts) > 5:
1896
+ doc_url = (
1897
+ "https://docs.python.org/3/library/warnings.html#describing-warning-filters"
1898
+ )
1899
+ error = dedent(
1900
+ f"""\
1901
+ Too many fields ({len(parts)}), expected at most 5 separated by colons:
1902
+
1903
+ action:message:category:module:line
1904
+
1905
+ For more information please consult: {doc_url}
1906
+ """
1907
+ )
1908
+ raise UsageError(error_template.format(error=error))
1909
+
1910
+ while len(parts) < 5:
1911
+ parts.append("")
1912
+ action_, message, category_, module, lineno_ = (s.strip() for s in parts)
1913
+ try:
1914
+ action: warnings._ActionKind = warnings._getaction(action_) # type: ignore[attr-defined]
1915
+ except warnings._OptionError as e:
1916
+ raise UsageError(error_template.format(error=str(e))) from None
1917
+ try:
1918
+ category: type[Warning] = _resolve_warning_category(category_)
1919
+ except Exception:
1920
+ exc_info = ExceptionInfo.from_current()
1921
+ exception_text = exc_info.getrepr(style="native")
1922
+ raise UsageError(error_template.format(error=exception_text)) from None
1923
+ if message and escape:
1924
+ message = re.escape(message)
1925
+ if module and escape:
1926
+ module = re.escape(module) + r"\Z"
1927
+ if lineno_:
1928
+ try:
1929
+ lineno = int(lineno_)
1930
+ if lineno < 0:
1931
+ raise ValueError("number is negative")
1932
+ except ValueError as e:
1933
+ raise UsageError(
1934
+ error_template.format(error=f"invalid lineno {lineno_!r}: {e}")
1935
+ ) from None
1936
+ else:
1937
+ lineno = 0
1938
+ return action, message, category, module, lineno
1939
+
1940
+
1941
+ def _resolve_warning_category(category: str) -> type[Warning]:
1942
+ """
1943
+ Copied from warnings._getcategory, but changed so it lets exceptions (specially ImportErrors)
1944
+ propagate so we can get access to their tracebacks (#9218).
1945
+ """
1946
+ __tracebackhide__ = True
1947
+ if not category:
1948
+ return Warning
1949
+
1950
+ if "." not in category:
1951
+ import builtins as m
1952
+
1953
+ klass = category
1954
+ else:
1955
+ module, _, klass = category.rpartition(".")
1956
+ m = __import__(module, None, None, [klass])
1957
+ cat = getattr(m, klass)
1958
+ if not issubclass(cat, Warning):
1959
+ raise UsageError(f"{cat} is not a Warning subclass")
1960
+ return cast(Type[Warning], cat)
1961
+
1962
+
1963
+ def apply_warning_filters(
1964
+ config_filters: Iterable[str], cmdline_filters: Iterable[str]
1965
+ ) -> None:
1966
+ """Applies pytest-configured filters to the warnings module"""
1967
+ # Filters should have this precedence: cmdline options, config.
1968
+ # Filters should be applied in the inverse order of precedence.
1969
+ for arg in config_filters:
1970
+ warnings.filterwarnings(*parse_warning_filter(arg, escape=False))
1971
+
1972
+ for arg in cmdline_filters:
1973
+ warnings.filterwarnings(*parse_warning_filter(arg, escape=True))
vllm/lib/python3.10/site-packages/_pytest/config/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (53.8 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/config/__pycache__/argparsing.cpython-310.pyc ADDED
Binary file (18.9 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/config/__pycache__/compat.cpython-310.pyc ADDED
Binary file (2.82 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/config/__pycache__/exceptions.cpython-310.pyc ADDED
Binary file (695 Bytes). View file
 
vllm/lib/python3.10/site-packages/_pytest/config/__pycache__/findpaths.cpython-310.pyc ADDED
Binary file (6.67 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/config/argparsing.py ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ from gettext import gettext
6
+ import os
7
+ import sys
8
+ from typing import Any
9
+ from typing import Callable
10
+ from typing import cast
11
+ from typing import final
12
+ from typing import List
13
+ from typing import Literal
14
+ from typing import Mapping
15
+ from typing import NoReturn
16
+ from typing import Sequence
17
+
18
+ import _pytest._io
19
+ from _pytest.config.exceptions import UsageError
20
+ from _pytest.deprecated import check_ispytest
21
+
22
+
23
+ FILE_OR_DIR = "file_or_dir"
24
+
25
+
26
+ class NotSet:
27
+ def __repr__(self) -> str:
28
+ return "<notset>"
29
+
30
+
31
+ NOT_SET = NotSet()
32
+
33
+
34
+ @final
35
+ class Parser:
36
+ """Parser for command line arguments and ini-file values.
37
+
38
+ :ivar extra_info: Dict of generic param -> value to display in case
39
+ there's an error processing the command line arguments.
40
+ """
41
+
42
+ prog: str | None = None
43
+
44
+ def __init__(
45
+ self,
46
+ usage: str | None = None,
47
+ processopt: Callable[[Argument], None] | None = None,
48
+ *,
49
+ _ispytest: bool = False,
50
+ ) -> None:
51
+ check_ispytest(_ispytest)
52
+ self._anonymous = OptionGroup("Custom options", parser=self, _ispytest=True)
53
+ self._groups: list[OptionGroup] = []
54
+ self._processopt = processopt
55
+ self._usage = usage
56
+ self._inidict: dict[str, tuple[str, str | None, Any]] = {}
57
+ self._ininames: list[str] = []
58
+ self.extra_info: dict[str, Any] = {}
59
+
60
+ def processoption(self, option: Argument) -> None:
61
+ if self._processopt:
62
+ if option.dest:
63
+ self._processopt(option)
64
+
65
+ def getgroup(
66
+ self, name: str, description: str = "", after: str | None = None
67
+ ) -> OptionGroup:
68
+ """Get (or create) a named option Group.
69
+
70
+ :param name: Name of the option group.
71
+ :param description: Long description for --help output.
72
+ :param after: Name of another group, used for ordering --help output.
73
+ :returns: The option group.
74
+
75
+ The returned group object has an ``addoption`` method with the same
76
+ signature as :func:`parser.addoption <pytest.Parser.addoption>` but
77
+ will be shown in the respective group in the output of
78
+ ``pytest --help``.
79
+ """
80
+ for group in self._groups:
81
+ if group.name == name:
82
+ return group
83
+ group = OptionGroup(name, description, parser=self, _ispytest=True)
84
+ i = 0
85
+ for i, grp in enumerate(self._groups):
86
+ if grp.name == after:
87
+ break
88
+ self._groups.insert(i + 1, group)
89
+ return group
90
+
91
+ def addoption(self, *opts: str, **attrs: Any) -> None:
92
+ """Register a command line option.
93
+
94
+ :param opts:
95
+ Option names, can be short or long options.
96
+ :param attrs:
97
+ Same attributes as the argparse library's :meth:`add_argument()
98
+ <argparse.ArgumentParser.add_argument>` function accepts.
99
+
100
+ After command line parsing, options are available on the pytest config
101
+ object via ``config.option.NAME`` where ``NAME`` is usually set
102
+ by passing a ``dest`` attribute, for example
103
+ ``addoption("--long", dest="NAME", ...)``.
104
+ """
105
+ self._anonymous.addoption(*opts, **attrs)
106
+
107
+ def parse(
108
+ self,
109
+ args: Sequence[str | os.PathLike[str]],
110
+ namespace: argparse.Namespace | None = None,
111
+ ) -> argparse.Namespace:
112
+ from _pytest._argcomplete import try_argcomplete
113
+
114
+ self.optparser = self._getparser()
115
+ try_argcomplete(self.optparser)
116
+ strargs = [os.fspath(x) for x in args]
117
+ return self.optparser.parse_args(strargs, namespace=namespace)
118
+
119
+ def _getparser(self) -> MyOptionParser:
120
+ from _pytest._argcomplete import filescompleter
121
+
122
+ optparser = MyOptionParser(self, self.extra_info, prog=self.prog)
123
+ groups = [*self._groups, self._anonymous]
124
+ for group in groups:
125
+ if group.options:
126
+ desc = group.description or group.name
127
+ arggroup = optparser.add_argument_group(desc)
128
+ for option in group.options:
129
+ n = option.names()
130
+ a = option.attrs()
131
+ arggroup.add_argument(*n, **a)
132
+ file_or_dir_arg = optparser.add_argument(FILE_OR_DIR, nargs="*")
133
+ # bash like autocompletion for dirs (appending '/')
134
+ # Type ignored because typeshed doesn't know about argcomplete.
135
+ file_or_dir_arg.completer = filescompleter # type: ignore
136
+ return optparser
137
+
138
+ def parse_setoption(
139
+ self,
140
+ args: Sequence[str | os.PathLike[str]],
141
+ option: argparse.Namespace,
142
+ namespace: argparse.Namespace | None = None,
143
+ ) -> list[str]:
144
+ parsedoption = self.parse(args, namespace=namespace)
145
+ for name, value in parsedoption.__dict__.items():
146
+ setattr(option, name, value)
147
+ return cast(List[str], getattr(parsedoption, FILE_OR_DIR))
148
+
149
+ def parse_known_args(
150
+ self,
151
+ args: Sequence[str | os.PathLike[str]],
152
+ namespace: argparse.Namespace | None = None,
153
+ ) -> argparse.Namespace:
154
+ """Parse the known arguments at this point.
155
+
156
+ :returns: An argparse namespace object.
157
+ """
158
+ return self.parse_known_and_unknown_args(args, namespace=namespace)[0]
159
+
160
+ def parse_known_and_unknown_args(
161
+ self,
162
+ args: Sequence[str | os.PathLike[str]],
163
+ namespace: argparse.Namespace | None = None,
164
+ ) -> tuple[argparse.Namespace, list[str]]:
165
+ """Parse the known arguments at this point, and also return the
166
+ remaining unknown arguments.
167
+
168
+ :returns:
169
+ A tuple containing an argparse namespace object for the known
170
+ arguments, and a list of the unknown arguments.
171
+ """
172
+ optparser = self._getparser()
173
+ strargs = [os.fspath(x) for x in args]
174
+ return optparser.parse_known_args(strargs, namespace=namespace)
175
+
176
+ def addini(
177
+ self,
178
+ name: str,
179
+ help: str,
180
+ type: Literal["string", "paths", "pathlist", "args", "linelist", "bool"]
181
+ | None = None,
182
+ default: Any = NOT_SET,
183
+ ) -> None:
184
+ """Register an ini-file option.
185
+
186
+ :param name:
187
+ Name of the ini-variable.
188
+ :param type:
189
+ Type of the variable. Can be:
190
+
191
+ * ``string``: a string
192
+ * ``bool``: a boolean
193
+ * ``args``: a list of strings, separated as in a shell
194
+ * ``linelist``: a list of strings, separated by line breaks
195
+ * ``paths``: a list of :class:`pathlib.Path`, separated as in a shell
196
+ * ``pathlist``: a list of ``py.path``, separated as in a shell
197
+
198
+ For ``paths`` and ``pathlist`` types, they are considered relative to the ini-file.
199
+ In case the execution is happening without an ini-file defined,
200
+ they will be considered relative to the current working directory (for example with ``--override-ini``).
201
+
202
+ .. versionadded:: 7.0
203
+ The ``paths`` variable type.
204
+
205
+ .. versionadded:: 8.1
206
+ Use the current working directory to resolve ``paths`` and ``pathlist`` in the absence of an ini-file.
207
+
208
+ Defaults to ``string`` if ``None`` or not passed.
209
+ :param default:
210
+ Default value if no ini-file option exists but is queried.
211
+
212
+ The value of ini-variables can be retrieved via a call to
213
+ :py:func:`config.getini(name) <pytest.Config.getini>`.
214
+ """
215
+ assert type in (None, "string", "paths", "pathlist", "args", "linelist", "bool")
216
+ if default is NOT_SET:
217
+ default = get_ini_default_for_type(type)
218
+
219
+ self._inidict[name] = (help, type, default)
220
+ self._ininames.append(name)
221
+
222
+
223
+ def get_ini_default_for_type(
224
+ type: Literal["string", "paths", "pathlist", "args", "linelist", "bool"] | None,
225
+ ) -> Any:
226
+ """
227
+ Used by addini to get the default value for a given ini-option type, when
228
+ default is not supplied.
229
+ """
230
+ if type is None:
231
+ return ""
232
+ elif type in ("paths", "pathlist", "args", "linelist"):
233
+ return []
234
+ elif type == "bool":
235
+ return False
236
+ else:
237
+ return ""
238
+
239
+
240
+ class ArgumentError(Exception):
241
+ """Raised if an Argument instance is created with invalid or
242
+ inconsistent arguments."""
243
+
244
+ def __init__(self, msg: str, option: Argument | str) -> None:
245
+ self.msg = msg
246
+ self.option_id = str(option)
247
+
248
+ def __str__(self) -> str:
249
+ if self.option_id:
250
+ return f"option {self.option_id}: {self.msg}"
251
+ else:
252
+ return self.msg
253
+
254
+
255
+ class Argument:
256
+ """Class that mimics the necessary behaviour of optparse.Option.
257
+
258
+ It's currently a least effort implementation and ignoring choices
259
+ and integer prefixes.
260
+
261
+ https://docs.python.org/3/library/optparse.html#optparse-standard-option-types
262
+ """
263
+
264
+ def __init__(self, *names: str, **attrs: Any) -> None:
265
+ """Store params in private vars for use in add_argument."""
266
+ self._attrs = attrs
267
+ self._short_opts: list[str] = []
268
+ self._long_opts: list[str] = []
269
+ try:
270
+ self.type = attrs["type"]
271
+ except KeyError:
272
+ pass
273
+ try:
274
+ # Attribute existence is tested in Config._processopt.
275
+ self.default = attrs["default"]
276
+ except KeyError:
277
+ pass
278
+ self._set_opt_strings(names)
279
+ dest: str | None = attrs.get("dest")
280
+ if dest:
281
+ self.dest = dest
282
+ elif self._long_opts:
283
+ self.dest = self._long_opts[0][2:].replace("-", "_")
284
+ else:
285
+ try:
286
+ self.dest = self._short_opts[0][1:]
287
+ except IndexError as e:
288
+ self.dest = "???" # Needed for the error repr.
289
+ raise ArgumentError("need a long or short option", self) from e
290
+
291
+ def names(self) -> list[str]:
292
+ return self._short_opts + self._long_opts
293
+
294
+ def attrs(self) -> Mapping[str, Any]:
295
+ # Update any attributes set by processopt.
296
+ attrs = "default dest help".split()
297
+ attrs.append(self.dest)
298
+ for attr in attrs:
299
+ try:
300
+ self._attrs[attr] = getattr(self, attr)
301
+ except AttributeError:
302
+ pass
303
+ return self._attrs
304
+
305
+ def _set_opt_strings(self, opts: Sequence[str]) -> None:
306
+ """Directly from optparse.
307
+
308
+ Might not be necessary as this is passed to argparse later on.
309
+ """
310
+ for opt in opts:
311
+ if len(opt) < 2:
312
+ raise ArgumentError(
313
+ f"invalid option string {opt!r}: "
314
+ "must be at least two characters long",
315
+ self,
316
+ )
317
+ elif len(opt) == 2:
318
+ if not (opt[0] == "-" and opt[1] != "-"):
319
+ raise ArgumentError(
320
+ f"invalid short option string {opt!r}: "
321
+ "must be of the form -x, (x any non-dash char)",
322
+ self,
323
+ )
324
+ self._short_opts.append(opt)
325
+ else:
326
+ if not (opt[0:2] == "--" and opt[2] != "-"):
327
+ raise ArgumentError(
328
+ f"invalid long option string {opt!r}: "
329
+ "must start with --, followed by non-dash",
330
+ self,
331
+ )
332
+ self._long_opts.append(opt)
333
+
334
+ def __repr__(self) -> str:
335
+ args: list[str] = []
336
+ if self._short_opts:
337
+ args += ["_short_opts: " + repr(self._short_opts)]
338
+ if self._long_opts:
339
+ args += ["_long_opts: " + repr(self._long_opts)]
340
+ args += ["dest: " + repr(self.dest)]
341
+ if hasattr(self, "type"):
342
+ args += ["type: " + repr(self.type)]
343
+ if hasattr(self, "default"):
344
+ args += ["default: " + repr(self.default)]
345
+ return "Argument({})".format(", ".join(args))
346
+
347
+
348
+ class OptionGroup:
349
+ """A group of options shown in its own section."""
350
+
351
+ def __init__(
352
+ self,
353
+ name: str,
354
+ description: str = "",
355
+ parser: Parser | None = None,
356
+ *,
357
+ _ispytest: bool = False,
358
+ ) -> None:
359
+ check_ispytest(_ispytest)
360
+ self.name = name
361
+ self.description = description
362
+ self.options: list[Argument] = []
363
+ self.parser = parser
364
+
365
+ def addoption(self, *opts: str, **attrs: Any) -> None:
366
+ """Add an option to this group.
367
+
368
+ If a shortened version of a long option is specified, it will
369
+ be suppressed in the help. ``addoption('--twowords', '--two-words')``
370
+ results in help showing ``--two-words`` only, but ``--twowords`` gets
371
+ accepted **and** the automatic destination is in ``args.twowords``.
372
+
373
+ :param opts:
374
+ Option names, can be short or long options.
375
+ :param attrs:
376
+ Same attributes as the argparse library's :meth:`add_argument()
377
+ <argparse.ArgumentParser.add_argument>` function accepts.
378
+ """
379
+ conflict = set(opts).intersection(
380
+ name for opt in self.options for name in opt.names()
381
+ )
382
+ if conflict:
383
+ raise ValueError(f"option names {conflict} already added")
384
+ option = Argument(*opts, **attrs)
385
+ self._addoption_instance(option, shortupper=False)
386
+
387
+ def _addoption(self, *opts: str, **attrs: Any) -> None:
388
+ option = Argument(*opts, **attrs)
389
+ self._addoption_instance(option, shortupper=True)
390
+
391
+ def _addoption_instance(self, option: Argument, shortupper: bool = False) -> None:
392
+ if not shortupper:
393
+ for opt in option._short_opts:
394
+ if opt[0] == "-" and opt[1].islower():
395
+ raise ValueError("lowercase shortoptions reserved")
396
+ if self.parser:
397
+ self.parser.processoption(option)
398
+ self.options.append(option)
399
+
400
+
401
+ class MyOptionParser(argparse.ArgumentParser):
402
+ def __init__(
403
+ self,
404
+ parser: Parser,
405
+ extra_info: dict[str, Any] | None = None,
406
+ prog: str | None = None,
407
+ ) -> None:
408
+ self._parser = parser
409
+ super().__init__(
410
+ prog=prog,
411
+ usage=parser._usage,
412
+ add_help=False,
413
+ formatter_class=DropShorterLongHelpFormatter,
414
+ allow_abbrev=False,
415
+ fromfile_prefix_chars="@",
416
+ )
417
+ # extra_info is a dict of (param -> value) to display if there's
418
+ # an usage error to provide more contextual information to the user.
419
+ self.extra_info = extra_info if extra_info else {}
420
+
421
+ def error(self, message: str) -> NoReturn:
422
+ """Transform argparse error message into UsageError."""
423
+ msg = f"{self.prog}: error: {message}"
424
+
425
+ if hasattr(self._parser, "_config_source_hint"):
426
+ msg = f"{msg} ({self._parser._config_source_hint})"
427
+
428
+ raise UsageError(self.format_usage() + msg)
429
+
430
+ # Type ignored because typeshed has a very complex type in the superclass.
431
+ def parse_args( # type: ignore
432
+ self,
433
+ args: Sequence[str] | None = None,
434
+ namespace: argparse.Namespace | None = None,
435
+ ) -> argparse.Namespace:
436
+ """Allow splitting of positional arguments."""
437
+ parsed, unrecognized = self.parse_known_args(args, namespace)
438
+ if unrecognized:
439
+ for arg in unrecognized:
440
+ if arg and arg[0] == "-":
441
+ lines = [
442
+ "unrecognized arguments: {}".format(" ".join(unrecognized))
443
+ ]
444
+ for k, v in sorted(self.extra_info.items()):
445
+ lines.append(f" {k}: {v}")
446
+ self.error("\n".join(lines))
447
+ getattr(parsed, FILE_OR_DIR).extend(unrecognized)
448
+ return parsed
449
+
450
+ if sys.version_info < (3, 9): # pragma: no cover
451
+ # Backport of https://github.com/python/cpython/pull/14316 so we can
452
+ # disable long --argument abbreviations without breaking short flags.
453
+ def _parse_optional(
454
+ self, arg_string: str
455
+ ) -> tuple[argparse.Action | None, str, str | None] | None:
456
+ if not arg_string:
457
+ return None
458
+ if arg_string[0] not in self.prefix_chars:
459
+ return None
460
+ if arg_string in self._option_string_actions:
461
+ action = self._option_string_actions[arg_string]
462
+ return action, arg_string, None
463
+ if len(arg_string) == 1:
464
+ return None
465
+ if "=" in arg_string:
466
+ option_string, explicit_arg = arg_string.split("=", 1)
467
+ if option_string in self._option_string_actions:
468
+ action = self._option_string_actions[option_string]
469
+ return action, option_string, explicit_arg
470
+ if self.allow_abbrev or not arg_string.startswith("--"):
471
+ option_tuples = self._get_option_tuples(arg_string)
472
+ if len(option_tuples) > 1:
473
+ msg = gettext(
474
+ "ambiguous option: %(option)s could match %(matches)s"
475
+ )
476
+ options = ", ".join(option for _, option, _ in option_tuples)
477
+ self.error(msg % {"option": arg_string, "matches": options})
478
+ elif len(option_tuples) == 1:
479
+ (option_tuple,) = option_tuples
480
+ return option_tuple
481
+ if self._negative_number_matcher.match(arg_string):
482
+ if not self._has_negative_number_optionals:
483
+ return None
484
+ if " " in arg_string:
485
+ return None
486
+ return None, arg_string, None
487
+
488
+
489
+ class DropShorterLongHelpFormatter(argparse.HelpFormatter):
490
+ """Shorten help for long options that differ only in extra hyphens.
491
+
492
+ - Collapse **long** options that are the same except for extra hyphens.
493
+ - Shortcut if there are only two options and one of them is a short one.
494
+ - Cache result on the action object as this is called at least 2 times.
495
+ """
496
+
497
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
498
+ # Use more accurate terminal width.
499
+ if "width" not in kwargs:
500
+ kwargs["width"] = _pytest._io.get_terminal_width()
501
+ super().__init__(*args, **kwargs)
502
+
503
+ def _format_action_invocation(self, action: argparse.Action) -> str:
504
+ orgstr = super()._format_action_invocation(action)
505
+ if orgstr and orgstr[0] != "-": # only optional arguments
506
+ return orgstr
507
+ res: str | None = getattr(action, "_formatted_action_invocation", None)
508
+ if res:
509
+ return res
510
+ options = orgstr.split(", ")
511
+ if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2):
512
+ # a shortcut for '-h, --help' or '--abc', '-a'
513
+ action._formatted_action_invocation = orgstr # type: ignore
514
+ return orgstr
515
+ return_list = []
516
+ short_long: dict[str, str] = {}
517
+ for option in options:
518
+ if len(option) == 2 or option[2] == " ":
519
+ continue
520
+ if not option.startswith("--"):
521
+ raise ArgumentError(
522
+ f'long optional argument without "--": [{option}]', option
523
+ )
524
+ xxoption = option[2:]
525
+ shortened = xxoption.replace("-", "")
526
+ if shortened not in short_long or len(short_long[shortened]) < len(
527
+ xxoption
528
+ ):
529
+ short_long[shortened] = xxoption
530
+ # now short_long has been filled out to the longest with dashes
531
+ # **and** we keep the right option ordering from add_argument
532
+ for option in options:
533
+ if len(option) == 2 or option[2] == " ":
534
+ return_list.append(option)
535
+ if option[2:] == short_long.get(option.replace("-", "")):
536
+ return_list.append(option.replace(" ", "=", 1))
537
+ formatted_action_invocation = ", ".join(return_list)
538
+ action._formatted_action_invocation = formatted_action_invocation # type: ignore
539
+ return formatted_action_invocation
540
+
541
+ def _split_lines(self, text, width):
542
+ """Wrap lines after splitting on original newlines.
543
+
544
+ This allows to have explicit line breaks in the help text.
545
+ """
546
+ import textwrap
547
+
548
+ lines = []
549
+ for line in text.splitlines():
550
+ lines.extend(textwrap.wrap(line.strip(), width))
551
+ return lines
vllm/lib/python3.10/site-packages/_pytest/config/compat.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import functools
4
+ from pathlib import Path
5
+ from typing import Any
6
+ from typing import Mapping
7
+ import warnings
8
+
9
+ import pluggy
10
+
11
+ from ..compat import LEGACY_PATH
12
+ from ..compat import legacy_path
13
+ from ..deprecated import HOOK_LEGACY_PATH_ARG
14
+
15
+
16
+ # hookname: (Path, LEGACY_PATH)
17
+ imply_paths_hooks: Mapping[str, tuple[str, str]] = {
18
+ "pytest_ignore_collect": ("collection_path", "path"),
19
+ "pytest_collect_file": ("file_path", "path"),
20
+ "pytest_pycollect_makemodule": ("module_path", "path"),
21
+ "pytest_report_header": ("start_path", "startdir"),
22
+ "pytest_report_collectionfinish": ("start_path", "startdir"),
23
+ }
24
+
25
+
26
+ def _check_path(path: Path, fspath: LEGACY_PATH) -> None:
27
+ if Path(fspath) != path:
28
+ raise ValueError(
29
+ f"Path({fspath!r}) != {path!r}\n"
30
+ "if both path and fspath are given they need to be equal"
31
+ )
32
+
33
+
34
+ class PathAwareHookProxy:
35
+ """
36
+ this helper wraps around hook callers
37
+ until pluggy supports fixingcalls, this one will do
38
+
39
+ it currently doesn't return full hook caller proxies for fixed hooks,
40
+ this may have to be changed later depending on bugs
41
+ """
42
+
43
+ def __init__(self, hook_relay: pluggy.HookRelay) -> None:
44
+ self._hook_relay = hook_relay
45
+
46
+ def __dir__(self) -> list[str]:
47
+ return dir(self._hook_relay)
48
+
49
+ def __getattr__(self, key: str) -> pluggy.HookCaller:
50
+ hook: pluggy.HookCaller = getattr(self._hook_relay, key)
51
+ if key not in imply_paths_hooks:
52
+ self.__dict__[key] = hook
53
+ return hook
54
+ else:
55
+ path_var, fspath_var = imply_paths_hooks[key]
56
+
57
+ @functools.wraps(hook)
58
+ def fixed_hook(**kw: Any) -> Any:
59
+ path_value: Path | None = kw.pop(path_var, None)
60
+ fspath_value: LEGACY_PATH | None = kw.pop(fspath_var, None)
61
+ if fspath_value is not None:
62
+ warnings.warn(
63
+ HOOK_LEGACY_PATH_ARG.format(
64
+ pylib_path_arg=fspath_var, pathlib_path_arg=path_var
65
+ ),
66
+ stacklevel=2,
67
+ )
68
+ if path_value is not None:
69
+ if fspath_value is not None:
70
+ _check_path(path_value, fspath_value)
71
+ else:
72
+ fspath_value = legacy_path(path_value)
73
+ else:
74
+ assert fspath_value is not None
75
+ path_value = Path(fspath_value)
76
+
77
+ kw[path_var] = path_value
78
+ kw[fspath_var] = fspath_value
79
+ return hook(**kw)
80
+
81
+ fixed_hook.name = hook.name # type: ignore[attr-defined]
82
+ fixed_hook.spec = hook.spec # type: ignore[attr-defined]
83
+ fixed_hook.__name__ = key
84
+ self.__dict__[key] = fixed_hook
85
+ return fixed_hook # type: ignore[return-value]
vllm/lib/python3.10/site-packages/_pytest/config/findpaths.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from pathlib import Path
5
+ import sys
6
+ from typing import Iterable
7
+ from typing import Sequence
8
+
9
+ import iniconfig
10
+
11
+ from .exceptions import UsageError
12
+ from _pytest.outcomes import fail
13
+ from _pytest.pathlib import absolutepath
14
+ from _pytest.pathlib import commonpath
15
+ from _pytest.pathlib import safe_exists
16
+
17
+
18
+ def _parse_ini_config(path: Path) -> iniconfig.IniConfig:
19
+ """Parse the given generic '.ini' file using legacy IniConfig parser, returning
20
+ the parsed object.
21
+
22
+ Raise UsageError if the file cannot be parsed.
23
+ """
24
+ try:
25
+ return iniconfig.IniConfig(str(path))
26
+ except iniconfig.ParseError as exc:
27
+ raise UsageError(str(exc)) from exc
28
+
29
+
30
+ def load_config_dict_from_file(
31
+ filepath: Path,
32
+ ) -> dict[str, str | list[str]] | None:
33
+ """Load pytest configuration from the given file path, if supported.
34
+
35
+ Return None if the file does not contain valid pytest configuration.
36
+ """
37
+ # Configuration from ini files are obtained from the [pytest] section, if present.
38
+ if filepath.suffix == ".ini":
39
+ iniconfig = _parse_ini_config(filepath)
40
+
41
+ if "pytest" in iniconfig:
42
+ return dict(iniconfig["pytest"].items())
43
+ else:
44
+ # "pytest.ini" files are always the source of configuration, even if empty.
45
+ if filepath.name == "pytest.ini":
46
+ return {}
47
+
48
+ # '.cfg' files are considered if they contain a "[tool:pytest]" section.
49
+ elif filepath.suffix == ".cfg":
50
+ iniconfig = _parse_ini_config(filepath)
51
+
52
+ if "tool:pytest" in iniconfig.sections:
53
+ return dict(iniconfig["tool:pytest"].items())
54
+ elif "pytest" in iniconfig.sections:
55
+ # If a setup.cfg contains a "[pytest]" section, we raise a failure to indicate users that
56
+ # plain "[pytest]" sections in setup.cfg files is no longer supported (#3086).
57
+ fail(CFG_PYTEST_SECTION.format(filename="setup.cfg"), pytrace=False)
58
+
59
+ # '.toml' files are considered if they contain a [tool.pytest.ini_options] table.
60
+ elif filepath.suffix == ".toml":
61
+ if sys.version_info >= (3, 11):
62
+ import tomllib
63
+ else:
64
+ import tomli as tomllib
65
+
66
+ toml_text = filepath.read_text(encoding="utf-8")
67
+ try:
68
+ config = tomllib.loads(toml_text)
69
+ except tomllib.TOMLDecodeError as exc:
70
+ raise UsageError(f"{filepath}: {exc}") from exc
71
+
72
+ result = config.get("tool", {}).get("pytest", {}).get("ini_options", None)
73
+ if result is not None:
74
+ # TOML supports richer data types than ini files (strings, arrays, floats, ints, etc),
75
+ # however we need to convert all scalar values to str for compatibility with the rest
76
+ # of the configuration system, which expects strings only.
77
+ def make_scalar(v: object) -> str | list[str]:
78
+ return v if isinstance(v, list) else str(v)
79
+
80
+ return {k: make_scalar(v) for k, v in result.items()}
81
+
82
+ return None
83
+
84
+
85
+ def locate_config(
86
+ invocation_dir: Path,
87
+ args: Iterable[Path],
88
+ ) -> tuple[Path | None, Path | None, dict[str, str | list[str]]]:
89
+ """Search in the list of arguments for a valid ini-file for pytest,
90
+ and return a tuple of (rootdir, inifile, cfg-dict)."""
91
+ config_names = [
92
+ "pytest.ini",
93
+ ".pytest.ini",
94
+ "pyproject.toml",
95
+ "tox.ini",
96
+ "setup.cfg",
97
+ ]
98
+ args = [x for x in args if not str(x).startswith("-")]
99
+ if not args:
100
+ args = [invocation_dir]
101
+ found_pyproject_toml: Path | None = None
102
+ for arg in args:
103
+ argpath = absolutepath(arg)
104
+ for base in (argpath, *argpath.parents):
105
+ for config_name in config_names:
106
+ p = base / config_name
107
+ if p.is_file():
108
+ if p.name == "pyproject.toml" and found_pyproject_toml is None:
109
+ found_pyproject_toml = p
110
+ ini_config = load_config_dict_from_file(p)
111
+ if ini_config is not None:
112
+ return base, p, ini_config
113
+ if found_pyproject_toml is not None:
114
+ return found_pyproject_toml.parent, found_pyproject_toml, {}
115
+ return None, None, {}
116
+
117
+
118
+ def get_common_ancestor(
119
+ invocation_dir: Path,
120
+ paths: Iterable[Path],
121
+ ) -> Path:
122
+ common_ancestor: Path | None = None
123
+ for path in paths:
124
+ if not path.exists():
125
+ continue
126
+ if common_ancestor is None:
127
+ common_ancestor = path
128
+ else:
129
+ if common_ancestor in path.parents or path == common_ancestor:
130
+ continue
131
+ elif path in common_ancestor.parents:
132
+ common_ancestor = path
133
+ else:
134
+ shared = commonpath(path, common_ancestor)
135
+ if shared is not None:
136
+ common_ancestor = shared
137
+ if common_ancestor is None:
138
+ common_ancestor = invocation_dir
139
+ elif common_ancestor.is_file():
140
+ common_ancestor = common_ancestor.parent
141
+ return common_ancestor
142
+
143
+
144
+ def get_dirs_from_args(args: Iterable[str]) -> list[Path]:
145
+ def is_option(x: str) -> bool:
146
+ return x.startswith("-")
147
+
148
+ def get_file_part_from_node_id(x: str) -> str:
149
+ return x.split("::")[0]
150
+
151
+ def get_dir_from_path(path: Path) -> Path:
152
+ if path.is_dir():
153
+ return path
154
+ return path.parent
155
+
156
+ # These look like paths but may not exist
157
+ possible_paths = (
158
+ absolutepath(get_file_part_from_node_id(arg))
159
+ for arg in args
160
+ if not is_option(arg)
161
+ )
162
+
163
+ return [get_dir_from_path(path) for path in possible_paths if safe_exists(path)]
164
+
165
+
166
+ CFG_PYTEST_SECTION = "[pytest] section in {filename} files is no longer supported, change to [tool:pytest] instead."
167
+
168
+
169
+ def determine_setup(
170
+ *,
171
+ inifile: str | None,
172
+ args: Sequence[str],
173
+ rootdir_cmd_arg: str | None,
174
+ invocation_dir: Path,
175
+ ) -> tuple[Path, Path | None, dict[str, str | list[str]]]:
176
+ """Determine the rootdir, inifile and ini configuration values from the
177
+ command line arguments.
178
+
179
+ :param inifile:
180
+ The `--inifile` command line argument, if given.
181
+ :param args:
182
+ The free command line arguments.
183
+ :param rootdir_cmd_arg:
184
+ The `--rootdir` command line argument, if given.
185
+ :param invocation_dir:
186
+ The working directory when pytest was invoked.
187
+ """
188
+ rootdir = None
189
+ dirs = get_dirs_from_args(args)
190
+ if inifile:
191
+ inipath_ = absolutepath(inifile)
192
+ inipath: Path | None = inipath_
193
+ inicfg = load_config_dict_from_file(inipath_) or {}
194
+ if rootdir_cmd_arg is None:
195
+ rootdir = inipath_.parent
196
+ else:
197
+ ancestor = get_common_ancestor(invocation_dir, dirs)
198
+ rootdir, inipath, inicfg = locate_config(invocation_dir, [ancestor])
199
+ if rootdir is None and rootdir_cmd_arg is None:
200
+ for possible_rootdir in (ancestor, *ancestor.parents):
201
+ if (possible_rootdir / "setup.py").is_file():
202
+ rootdir = possible_rootdir
203
+ break
204
+ else:
205
+ if dirs != [ancestor]:
206
+ rootdir, inipath, inicfg = locate_config(invocation_dir, dirs)
207
+ if rootdir is None:
208
+ rootdir = get_common_ancestor(
209
+ invocation_dir, [invocation_dir, ancestor]
210
+ )
211
+ if is_fs_root(rootdir):
212
+ rootdir = ancestor
213
+ if rootdir_cmd_arg:
214
+ rootdir = absolutepath(os.path.expandvars(rootdir_cmd_arg))
215
+ if not rootdir.is_dir():
216
+ raise UsageError(
217
+ f"Directory '{rootdir}' not found. Check your '--rootdir' option."
218
+ )
219
+ assert rootdir is not None
220
+ return rootdir, inipath, inicfg or {}
221
+
222
+
223
+ def is_fs_root(p: Path) -> bool:
224
+ r"""
225
+ Return True if the given path is pointing to the root of the
226
+ file system ("/" on Unix and "C:\\" on Windows for example).
227
+ """
228
+ return os.path.splitdrive(str(p))[1] == os.sep
vllm/lib/python3.10/site-packages/_pytest/debugging.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # ruff: noqa: T100
3
+ """Interactive debugging with PDB, the Python Debugger."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import argparse
8
+ import functools
9
+ import sys
10
+ import types
11
+ from typing import Any
12
+ from typing import Callable
13
+ from typing import Generator
14
+ import unittest
15
+
16
+ from _pytest import outcomes
17
+ from _pytest._code import ExceptionInfo
18
+ from _pytest.capture import CaptureManager
19
+ from _pytest.config import Config
20
+ from _pytest.config import ConftestImportFailure
21
+ from _pytest.config import hookimpl
22
+ from _pytest.config import PytestPluginManager
23
+ from _pytest.config.argparsing import Parser
24
+ from _pytest.config.exceptions import UsageError
25
+ from _pytest.nodes import Node
26
+ from _pytest.reports import BaseReport
27
+ from _pytest.runner import CallInfo
28
+
29
+
30
+ def _validate_usepdb_cls(value: str) -> tuple[str, str]:
31
+ """Validate syntax of --pdbcls option."""
32
+ try:
33
+ modname, classname = value.split(":")
34
+ except ValueError as e:
35
+ raise argparse.ArgumentTypeError(
36
+ f"{value!r} is not in the format 'modname:classname'"
37
+ ) from e
38
+ return (modname, classname)
39
+
40
+
41
+ def pytest_addoption(parser: Parser) -> None:
42
+ group = parser.getgroup("general")
43
+ group._addoption(
44
+ "--pdb",
45
+ dest="usepdb",
46
+ action="store_true",
47
+ help="Start the interactive Python debugger on errors or KeyboardInterrupt",
48
+ )
49
+ group._addoption(
50
+ "--pdbcls",
51
+ dest="usepdb_cls",
52
+ metavar="modulename:classname",
53
+ type=_validate_usepdb_cls,
54
+ help="Specify a custom interactive Python debugger for use with --pdb."
55
+ "For example: --pdbcls=IPython.terminal.debugger:TerminalPdb",
56
+ )
57
+ group._addoption(
58
+ "--trace",
59
+ dest="trace",
60
+ action="store_true",
61
+ help="Immediately break when running each test",
62
+ )
63
+
64
+
65
+ def pytest_configure(config: Config) -> None:
66
+ import pdb
67
+
68
+ if config.getvalue("trace"):
69
+ config.pluginmanager.register(PdbTrace(), "pdbtrace")
70
+ if config.getvalue("usepdb"):
71
+ config.pluginmanager.register(PdbInvoke(), "pdbinvoke")
72
+
73
+ pytestPDB._saved.append(
74
+ (pdb.set_trace, pytestPDB._pluginmanager, pytestPDB._config)
75
+ )
76
+ pdb.set_trace = pytestPDB.set_trace
77
+ pytestPDB._pluginmanager = config.pluginmanager
78
+ pytestPDB._config = config
79
+
80
+ # NOTE: not using pytest_unconfigure, since it might get called although
81
+ # pytest_configure was not (if another plugin raises UsageError).
82
+ def fin() -> None:
83
+ (
84
+ pdb.set_trace,
85
+ pytestPDB._pluginmanager,
86
+ pytestPDB._config,
87
+ ) = pytestPDB._saved.pop()
88
+
89
+ config.add_cleanup(fin)
90
+
91
+
92
+ class pytestPDB:
93
+ """Pseudo PDB that defers to the real pdb."""
94
+
95
+ _pluginmanager: PytestPluginManager | None = None
96
+ _config: Config | None = None
97
+ _saved: list[
98
+ tuple[Callable[..., None], PytestPluginManager | None, Config | None]
99
+ ] = []
100
+ _recursive_debug = 0
101
+ _wrapped_pdb_cls: tuple[type[Any], type[Any]] | None = None
102
+
103
+ @classmethod
104
+ def _is_capturing(cls, capman: CaptureManager | None) -> str | bool:
105
+ if capman:
106
+ return capman.is_capturing()
107
+ return False
108
+
109
+ @classmethod
110
+ def _import_pdb_cls(cls, capman: CaptureManager | None):
111
+ if not cls._config:
112
+ import pdb
113
+
114
+ # Happens when using pytest.set_trace outside of a test.
115
+ return pdb.Pdb
116
+
117
+ usepdb_cls = cls._config.getvalue("usepdb_cls")
118
+
119
+ if cls._wrapped_pdb_cls and cls._wrapped_pdb_cls[0] == usepdb_cls:
120
+ return cls._wrapped_pdb_cls[1]
121
+
122
+ if usepdb_cls:
123
+ modname, classname = usepdb_cls
124
+
125
+ try:
126
+ __import__(modname)
127
+ mod = sys.modules[modname]
128
+
129
+ # Handle --pdbcls=pdb:pdb.Pdb (useful e.g. with pdbpp).
130
+ parts = classname.split(".")
131
+ pdb_cls = getattr(mod, parts[0])
132
+ for part in parts[1:]:
133
+ pdb_cls = getattr(pdb_cls, part)
134
+ except Exception as exc:
135
+ value = ":".join((modname, classname))
136
+ raise UsageError(
137
+ f"--pdbcls: could not import {value!r}: {exc}"
138
+ ) from exc
139
+ else:
140
+ import pdb
141
+
142
+ pdb_cls = pdb.Pdb
143
+
144
+ wrapped_cls = cls._get_pdb_wrapper_class(pdb_cls, capman)
145
+ cls._wrapped_pdb_cls = (usepdb_cls, wrapped_cls)
146
+ return wrapped_cls
147
+
148
+ @classmethod
149
+ def _get_pdb_wrapper_class(cls, pdb_cls, capman: CaptureManager | None):
150
+ import _pytest.config
151
+
152
+ class PytestPdbWrapper(pdb_cls):
153
+ _pytest_capman = capman
154
+ _continued = False
155
+
156
+ def do_debug(self, arg):
157
+ cls._recursive_debug += 1
158
+ ret = super().do_debug(arg)
159
+ cls._recursive_debug -= 1
160
+ return ret
161
+
162
+ def do_continue(self, arg):
163
+ ret = super().do_continue(arg)
164
+ if cls._recursive_debug == 0:
165
+ assert cls._config is not None
166
+ tw = _pytest.config.create_terminal_writer(cls._config)
167
+ tw.line()
168
+
169
+ capman = self._pytest_capman
170
+ capturing = pytestPDB._is_capturing(capman)
171
+ if capturing:
172
+ if capturing == "global":
173
+ tw.sep(">", "PDB continue (IO-capturing resumed)")
174
+ else:
175
+ tw.sep(
176
+ ">",
177
+ f"PDB continue (IO-capturing resumed for {capturing})",
178
+ )
179
+ assert capman is not None
180
+ capman.resume()
181
+ else:
182
+ tw.sep(">", "PDB continue")
183
+ assert cls._pluginmanager is not None
184
+ cls._pluginmanager.hook.pytest_leave_pdb(config=cls._config, pdb=self)
185
+ self._continued = True
186
+ return ret
187
+
188
+ do_c = do_cont = do_continue
189
+
190
+ def do_quit(self, arg):
191
+ """Raise Exit outcome when quit command is used in pdb.
192
+
193
+ This is a bit of a hack - it would be better if BdbQuit
194
+ could be handled, but this would require to wrap the
195
+ whole pytest run, and adjust the report etc.
196
+ """
197
+ ret = super().do_quit(arg)
198
+
199
+ if cls._recursive_debug == 0:
200
+ outcomes.exit("Quitting debugger")
201
+
202
+ return ret
203
+
204
+ do_q = do_quit
205
+ do_exit = do_quit
206
+
207
+ def setup(self, f, tb):
208
+ """Suspend on setup().
209
+
210
+ Needed after do_continue resumed, and entering another
211
+ breakpoint again.
212
+ """
213
+ ret = super().setup(f, tb)
214
+ if not ret and self._continued:
215
+ # pdb.setup() returns True if the command wants to exit
216
+ # from the interaction: do not suspend capturing then.
217
+ if self._pytest_capman:
218
+ self._pytest_capman.suspend_global_capture(in_=True)
219
+ return ret
220
+
221
+ def get_stack(self, f, t):
222
+ stack, i = super().get_stack(f, t)
223
+ if f is None:
224
+ # Find last non-hidden frame.
225
+ i = max(0, len(stack) - 1)
226
+ while i and stack[i][0].f_locals.get("__tracebackhide__", False):
227
+ i -= 1
228
+ return stack, i
229
+
230
+ return PytestPdbWrapper
231
+
232
+ @classmethod
233
+ def _init_pdb(cls, method, *args, **kwargs):
234
+ """Initialize PDB debugging, dropping any IO capturing."""
235
+ import _pytest.config
236
+
237
+ if cls._pluginmanager is None:
238
+ capman: CaptureManager | None = None
239
+ else:
240
+ capman = cls._pluginmanager.getplugin("capturemanager")
241
+ if capman:
242
+ capman.suspend(in_=True)
243
+
244
+ if cls._config:
245
+ tw = _pytest.config.create_terminal_writer(cls._config)
246
+ tw.line()
247
+
248
+ if cls._recursive_debug == 0:
249
+ # Handle header similar to pdb.set_trace in py37+.
250
+ header = kwargs.pop("header", None)
251
+ if header is not None:
252
+ tw.sep(">", header)
253
+ else:
254
+ capturing = cls._is_capturing(capman)
255
+ if capturing == "global":
256
+ tw.sep(">", f"PDB {method} (IO-capturing turned off)")
257
+ elif capturing:
258
+ tw.sep(
259
+ ">",
260
+ f"PDB {method} (IO-capturing turned off for {capturing})",
261
+ )
262
+ else:
263
+ tw.sep(">", f"PDB {method}")
264
+
265
+ _pdb = cls._import_pdb_cls(capman)(**kwargs)
266
+
267
+ if cls._pluginmanager:
268
+ cls._pluginmanager.hook.pytest_enter_pdb(config=cls._config, pdb=_pdb)
269
+ return _pdb
270
+
271
+ @classmethod
272
+ def set_trace(cls, *args, **kwargs) -> None:
273
+ """Invoke debugging via ``Pdb.set_trace``, dropping any IO capturing."""
274
+ frame = sys._getframe().f_back
275
+ _pdb = cls._init_pdb("set_trace", *args, **kwargs)
276
+ _pdb.set_trace(frame)
277
+
278
+
279
+ class PdbInvoke:
280
+ def pytest_exception_interact(
281
+ self, node: Node, call: CallInfo[Any], report: BaseReport
282
+ ) -> None:
283
+ capman = node.config.pluginmanager.getplugin("capturemanager")
284
+ if capman:
285
+ capman.suspend_global_capture(in_=True)
286
+ out, err = capman.read_global_capture()
287
+ sys.stdout.write(out)
288
+ sys.stdout.write(err)
289
+ assert call.excinfo is not None
290
+
291
+ if not isinstance(call.excinfo.value, unittest.SkipTest):
292
+ _enter_pdb(node, call.excinfo, report)
293
+
294
+ def pytest_internalerror(self, excinfo: ExceptionInfo[BaseException]) -> None:
295
+ tb = _postmortem_traceback(excinfo)
296
+ post_mortem(tb)
297
+
298
+
299
+ class PdbTrace:
300
+ @hookimpl(wrapper=True)
301
+ def pytest_pyfunc_call(self, pyfuncitem) -> Generator[None, object, object]:
302
+ wrap_pytest_function_for_tracing(pyfuncitem)
303
+ return (yield)
304
+
305
+
306
+ def wrap_pytest_function_for_tracing(pyfuncitem) -> None:
307
+ """Change the Python function object of the given Function item by a
308
+ wrapper which actually enters pdb before calling the python function
309
+ itself, effectively leaving the user in the pdb prompt in the first
310
+ statement of the function."""
311
+ _pdb = pytestPDB._init_pdb("runcall")
312
+ testfunction = pyfuncitem.obj
313
+
314
+ # we can't just return `partial(pdb.runcall, testfunction)` because (on
315
+ # python < 3.7.4) runcall's first param is `func`, which means we'd get
316
+ # an exception if one of the kwargs to testfunction was called `func`.
317
+ @functools.wraps(testfunction)
318
+ def wrapper(*args, **kwargs) -> None:
319
+ func = functools.partial(testfunction, *args, **kwargs)
320
+ _pdb.runcall(func)
321
+
322
+ pyfuncitem.obj = wrapper
323
+
324
+
325
+ def maybe_wrap_pytest_function_for_tracing(pyfuncitem) -> None:
326
+ """Wrap the given pytestfunct item for tracing support if --trace was given in
327
+ the command line."""
328
+ if pyfuncitem.config.getvalue("trace"):
329
+ wrap_pytest_function_for_tracing(pyfuncitem)
330
+
331
+
332
+ def _enter_pdb(
333
+ node: Node, excinfo: ExceptionInfo[BaseException], rep: BaseReport
334
+ ) -> BaseReport:
335
+ # XXX we reuse the TerminalReporter's terminalwriter
336
+ # because this seems to avoid some encoding related troubles
337
+ # for not completely clear reasons.
338
+ tw = node.config.pluginmanager.getplugin("terminalreporter")._tw
339
+ tw.line()
340
+
341
+ showcapture = node.config.option.showcapture
342
+
343
+ for sectionname, content in (
344
+ ("stdout", rep.capstdout),
345
+ ("stderr", rep.capstderr),
346
+ ("log", rep.caplog),
347
+ ):
348
+ if showcapture in (sectionname, "all") and content:
349
+ tw.sep(">", "captured " + sectionname)
350
+ if content[-1:] == "\n":
351
+ content = content[:-1]
352
+ tw.line(content)
353
+
354
+ tw.sep(">", "traceback")
355
+ rep.toterminal(tw)
356
+ tw.sep(">", "entering PDB")
357
+ tb = _postmortem_traceback(excinfo)
358
+ rep._pdbshown = True # type: ignore[attr-defined]
359
+ post_mortem(tb)
360
+ return rep
361
+
362
+
363
+ def _postmortem_traceback(excinfo: ExceptionInfo[BaseException]) -> types.TracebackType:
364
+ from doctest import UnexpectedException
365
+
366
+ if isinstance(excinfo.value, UnexpectedException):
367
+ # A doctest.UnexpectedException is not useful for post_mortem.
368
+ # Use the underlying exception instead:
369
+ return excinfo.value.exc_info[2]
370
+ elif isinstance(excinfo.value, ConftestImportFailure):
371
+ # A config.ConftestImportFailure is not useful for post_mortem.
372
+ # Use the underlying exception instead:
373
+ assert excinfo.value.cause.__traceback__ is not None
374
+ return excinfo.value.cause.__traceback__
375
+ else:
376
+ assert excinfo._excinfo is not None
377
+ return excinfo._excinfo[2]
378
+
379
+
380
+ def post_mortem(t: types.TracebackType) -> None:
381
+ p = pytestPDB._init_pdb("post_mortem")
382
+ p.reset()
383
+ p.interaction(None, t)
384
+ if p.quitting:
385
+ outcomes.exit("Quitting debugger")
vllm/lib/python3.10/site-packages/_pytest/doctest.py ADDED
@@ -0,0 +1,755 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """Discover and run doctests in modules and test files."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import bdb
7
+ from contextlib import contextmanager
8
+ import functools
9
+ import inspect
10
+ import os
11
+ from pathlib import Path
12
+ import platform
13
+ import sys
14
+ import traceback
15
+ import types
16
+ from typing import Any
17
+ from typing import Callable
18
+ from typing import Generator
19
+ from typing import Iterable
20
+ from typing import Pattern
21
+ from typing import Sequence
22
+ from typing import TYPE_CHECKING
23
+ import warnings
24
+
25
+ from _pytest import outcomes
26
+ from _pytest._code.code import ExceptionInfo
27
+ from _pytest._code.code import ReprFileLocation
28
+ from _pytest._code.code import TerminalRepr
29
+ from _pytest._io import TerminalWriter
30
+ from _pytest.compat import safe_getattr
31
+ from _pytest.config import Config
32
+ from _pytest.config.argparsing import Parser
33
+ from _pytest.fixtures import fixture
34
+ from _pytest.fixtures import TopRequest
35
+ from _pytest.nodes import Collector
36
+ from _pytest.nodes import Item
37
+ from _pytest.outcomes import OutcomeException
38
+ from _pytest.outcomes import skip
39
+ from _pytest.pathlib import fnmatch_ex
40
+ from _pytest.python import Module
41
+ from _pytest.python_api import approx
42
+ from _pytest.warning_types import PytestWarning
43
+
44
+
45
+ if TYPE_CHECKING:
46
+ import doctest
47
+
48
+ from typing_extensions import Self
49
+
50
+ DOCTEST_REPORT_CHOICE_NONE = "none"
51
+ DOCTEST_REPORT_CHOICE_CDIFF = "cdiff"
52
+ DOCTEST_REPORT_CHOICE_NDIFF = "ndiff"
53
+ DOCTEST_REPORT_CHOICE_UDIFF = "udiff"
54
+ DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE = "only_first_failure"
55
+
56
+ DOCTEST_REPORT_CHOICES = (
57
+ DOCTEST_REPORT_CHOICE_NONE,
58
+ DOCTEST_REPORT_CHOICE_CDIFF,
59
+ DOCTEST_REPORT_CHOICE_NDIFF,
60
+ DOCTEST_REPORT_CHOICE_UDIFF,
61
+ DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE,
62
+ )
63
+
64
+ # Lazy definition of runner class
65
+ RUNNER_CLASS = None
66
+ # Lazy definition of output checker class
67
+ CHECKER_CLASS: type[doctest.OutputChecker] | None = None
68
+
69
+
70
+ def pytest_addoption(parser: Parser) -> None:
71
+ parser.addini(
72
+ "doctest_optionflags",
73
+ "Option flags for doctests",
74
+ type="args",
75
+ default=["ELLIPSIS"],
76
+ )
77
+ parser.addini(
78
+ "doctest_encoding", "Encoding used for doctest files", default="utf-8"
79
+ )
80
+ group = parser.getgroup("collect")
81
+ group.addoption(
82
+ "--doctest-modules",
83
+ action="store_true",
84
+ default=False,
85
+ help="Run doctests in all .py modules",
86
+ dest="doctestmodules",
87
+ )
88
+ group.addoption(
89
+ "--doctest-report",
90
+ type=str.lower,
91
+ default="udiff",
92
+ help="Choose another output format for diffs on doctest failure",
93
+ choices=DOCTEST_REPORT_CHOICES,
94
+ dest="doctestreport",
95
+ )
96
+ group.addoption(
97
+ "--doctest-glob",
98
+ action="append",
99
+ default=[],
100
+ metavar="pat",
101
+ help="Doctests file matching pattern, default: test*.txt",
102
+ dest="doctestglob",
103
+ )
104
+ group.addoption(
105
+ "--doctest-ignore-import-errors",
106
+ action="store_true",
107
+ default=False,
108
+ help="Ignore doctest collection errors",
109
+ dest="doctest_ignore_import_errors",
110
+ )
111
+ group.addoption(
112
+ "--doctest-continue-on-failure",
113
+ action="store_true",
114
+ default=False,
115
+ help="For a given doctest, continue to run after the first failure",
116
+ dest="doctest_continue_on_failure",
117
+ )
118
+
119
+
120
+ def pytest_unconfigure() -> None:
121
+ global RUNNER_CLASS
122
+
123
+ RUNNER_CLASS = None
124
+
125
+
126
+ def pytest_collect_file(
127
+ file_path: Path,
128
+ parent: Collector,
129
+ ) -> DoctestModule | DoctestTextfile | None:
130
+ config = parent.config
131
+ if file_path.suffix == ".py":
132
+ if config.option.doctestmodules and not any(
133
+ (_is_setup_py(file_path), _is_main_py(file_path))
134
+ ):
135
+ return DoctestModule.from_parent(parent, path=file_path)
136
+ elif _is_doctest(config, file_path, parent):
137
+ return DoctestTextfile.from_parent(parent, path=file_path)
138
+ return None
139
+
140
+
141
+ def _is_setup_py(path: Path) -> bool:
142
+ if path.name != "setup.py":
143
+ return False
144
+ contents = path.read_bytes()
145
+ return b"setuptools" in contents or b"distutils" in contents
146
+
147
+
148
+ def _is_doctest(config: Config, path: Path, parent: Collector) -> bool:
149
+ if path.suffix in (".txt", ".rst") and parent.session.isinitpath(path):
150
+ return True
151
+ globs = config.getoption("doctestglob") or ["test*.txt"]
152
+ return any(fnmatch_ex(glob, path) for glob in globs)
153
+
154
+
155
+ def _is_main_py(path: Path) -> bool:
156
+ return path.name == "__main__.py"
157
+
158
+
159
+ class ReprFailDoctest(TerminalRepr):
160
+ def __init__(
161
+ self, reprlocation_lines: Sequence[tuple[ReprFileLocation, Sequence[str]]]
162
+ ) -> None:
163
+ self.reprlocation_lines = reprlocation_lines
164
+
165
+ def toterminal(self, tw: TerminalWriter) -> None:
166
+ for reprlocation, lines in self.reprlocation_lines:
167
+ for line in lines:
168
+ tw.line(line)
169
+ reprlocation.toterminal(tw)
170
+
171
+
172
+ class MultipleDoctestFailures(Exception):
173
+ def __init__(self, failures: Sequence[doctest.DocTestFailure]) -> None:
174
+ super().__init__()
175
+ self.failures = failures
176
+
177
+
178
+ def _init_runner_class() -> type[doctest.DocTestRunner]:
179
+ import doctest
180
+
181
+ class PytestDoctestRunner(doctest.DebugRunner):
182
+ """Runner to collect failures.
183
+
184
+ Note that the out variable in this case is a list instead of a
185
+ stdout-like object.
186
+ """
187
+
188
+ def __init__(
189
+ self,
190
+ checker: doctest.OutputChecker | None = None,
191
+ verbose: bool | None = None,
192
+ optionflags: int = 0,
193
+ continue_on_failure: bool = True,
194
+ ) -> None:
195
+ super().__init__(checker=checker, verbose=verbose, optionflags=optionflags)
196
+ self.continue_on_failure = continue_on_failure
197
+
198
+ def report_failure(
199
+ self,
200
+ out,
201
+ test: doctest.DocTest,
202
+ example: doctest.Example,
203
+ got: str,
204
+ ) -> None:
205
+ failure = doctest.DocTestFailure(test, example, got)
206
+ if self.continue_on_failure:
207
+ out.append(failure)
208
+ else:
209
+ raise failure
210
+
211
+ def report_unexpected_exception(
212
+ self,
213
+ out,
214
+ test: doctest.DocTest,
215
+ example: doctest.Example,
216
+ exc_info: tuple[type[BaseException], BaseException, types.TracebackType],
217
+ ) -> None:
218
+ if isinstance(exc_info[1], OutcomeException):
219
+ raise exc_info[1]
220
+ if isinstance(exc_info[1], bdb.BdbQuit):
221
+ outcomes.exit("Quitting debugger")
222
+ failure = doctest.UnexpectedException(test, example, exc_info)
223
+ if self.continue_on_failure:
224
+ out.append(failure)
225
+ else:
226
+ raise failure
227
+
228
+ return PytestDoctestRunner
229
+
230
+
231
+ def _get_runner(
232
+ checker: doctest.OutputChecker | None = None,
233
+ verbose: bool | None = None,
234
+ optionflags: int = 0,
235
+ continue_on_failure: bool = True,
236
+ ) -> doctest.DocTestRunner:
237
+ # We need this in order to do a lazy import on doctest
238
+ global RUNNER_CLASS
239
+ if RUNNER_CLASS is None:
240
+ RUNNER_CLASS = _init_runner_class()
241
+ # Type ignored because the continue_on_failure argument is only defined on
242
+ # PytestDoctestRunner, which is lazily defined so can't be used as a type.
243
+ return RUNNER_CLASS( # type: ignore
244
+ checker=checker,
245
+ verbose=verbose,
246
+ optionflags=optionflags,
247
+ continue_on_failure=continue_on_failure,
248
+ )
249
+
250
+
251
+ class DoctestItem(Item):
252
+ def __init__(
253
+ self,
254
+ name: str,
255
+ parent: DoctestTextfile | DoctestModule,
256
+ runner: doctest.DocTestRunner,
257
+ dtest: doctest.DocTest,
258
+ ) -> None:
259
+ super().__init__(name, parent)
260
+ self.runner = runner
261
+ self.dtest = dtest
262
+
263
+ # Stuff needed for fixture support.
264
+ self.obj = None
265
+ fm = self.session._fixturemanager
266
+ fixtureinfo = fm.getfixtureinfo(node=self, func=None, cls=None)
267
+ self._fixtureinfo = fixtureinfo
268
+ self.fixturenames = fixtureinfo.names_closure
269
+ self._initrequest()
270
+
271
+ @classmethod
272
+ def from_parent( # type: ignore[override]
273
+ cls,
274
+ parent: DoctestTextfile | DoctestModule,
275
+ *,
276
+ name: str,
277
+ runner: doctest.DocTestRunner,
278
+ dtest: doctest.DocTest,
279
+ ) -> Self:
280
+ # incompatible signature due to imposed limits on subclass
281
+ """The public named constructor."""
282
+ return super().from_parent(name=name, parent=parent, runner=runner, dtest=dtest)
283
+
284
+ def _initrequest(self) -> None:
285
+ self.funcargs: dict[str, object] = {}
286
+ self._request = TopRequest(self, _ispytest=True) # type: ignore[arg-type]
287
+
288
+ def setup(self) -> None:
289
+ self._request._fillfixtures()
290
+ globs = dict(getfixture=self._request.getfixturevalue)
291
+ for name, value in self._request.getfixturevalue("doctest_namespace").items():
292
+ globs[name] = value
293
+ self.dtest.globs.update(globs)
294
+
295
+ def runtest(self) -> None:
296
+ _check_all_skipped(self.dtest)
297
+ self._disable_output_capturing_for_darwin()
298
+ failures: list[doctest.DocTestFailure] = []
299
+ # Type ignored because we change the type of `out` from what
300
+ # doctest expects.
301
+ self.runner.run(self.dtest, out=failures) # type: ignore[arg-type]
302
+ if failures:
303
+ raise MultipleDoctestFailures(failures)
304
+
305
+ def _disable_output_capturing_for_darwin(self) -> None:
306
+ """Disable output capturing. Otherwise, stdout is lost to doctest (#985)."""
307
+ if platform.system() != "Darwin":
308
+ return
309
+ capman = self.config.pluginmanager.getplugin("capturemanager")
310
+ if capman:
311
+ capman.suspend_global_capture(in_=True)
312
+ out, err = capman.read_global_capture()
313
+ sys.stdout.write(out)
314
+ sys.stderr.write(err)
315
+
316
+ # TODO: Type ignored -- breaks Liskov Substitution.
317
+ def repr_failure( # type: ignore[override]
318
+ self,
319
+ excinfo: ExceptionInfo[BaseException],
320
+ ) -> str | TerminalRepr:
321
+ import doctest
322
+
323
+ failures: (
324
+ Sequence[doctest.DocTestFailure | doctest.UnexpectedException] | None
325
+ ) = None
326
+ if isinstance(
327
+ excinfo.value, (doctest.DocTestFailure, doctest.UnexpectedException)
328
+ ):
329
+ failures = [excinfo.value]
330
+ elif isinstance(excinfo.value, MultipleDoctestFailures):
331
+ failures = excinfo.value.failures
332
+
333
+ if failures is None:
334
+ return super().repr_failure(excinfo)
335
+
336
+ reprlocation_lines = []
337
+ for failure in failures:
338
+ example = failure.example
339
+ test = failure.test
340
+ filename = test.filename
341
+ if test.lineno is None:
342
+ lineno = None
343
+ else:
344
+ lineno = test.lineno + example.lineno + 1
345
+ message = type(failure).__name__
346
+ # TODO: ReprFileLocation doesn't expect a None lineno.
347
+ reprlocation = ReprFileLocation(filename, lineno, message) # type: ignore[arg-type]
348
+ checker = _get_checker()
349
+ report_choice = _get_report_choice(self.config.getoption("doctestreport"))
350
+ if lineno is not None:
351
+ assert failure.test.docstring is not None
352
+ lines = failure.test.docstring.splitlines(False)
353
+ # add line numbers to the left of the error message
354
+ assert test.lineno is not None
355
+ lines = [
356
+ "%03d %s" % (i + test.lineno + 1, x) for (i, x) in enumerate(lines)
357
+ ]
358
+ # trim docstring error lines to 10
359
+ lines = lines[max(example.lineno - 9, 0) : example.lineno + 1]
360
+ else:
361
+ lines = [
362
+ "EXAMPLE LOCATION UNKNOWN, not showing all tests of that example"
363
+ ]
364
+ indent = ">>>"
365
+ for line in example.source.splitlines():
366
+ lines.append(f"??? {indent} {line}")
367
+ indent = "..."
368
+ if isinstance(failure, doctest.DocTestFailure):
369
+ lines += checker.output_difference(
370
+ example, failure.got, report_choice
371
+ ).split("\n")
372
+ else:
373
+ inner_excinfo = ExceptionInfo.from_exc_info(failure.exc_info)
374
+ lines += [f"UNEXPECTED EXCEPTION: {inner_excinfo.value!r}"]
375
+ lines += [
376
+ x.strip("\n") for x in traceback.format_exception(*failure.exc_info)
377
+ ]
378
+ reprlocation_lines.append((reprlocation, lines))
379
+ return ReprFailDoctest(reprlocation_lines)
380
+
381
+ def reportinfo(self) -> tuple[os.PathLike[str] | str, int | None, str]:
382
+ return self.path, self.dtest.lineno, f"[doctest] {self.name}"
383
+
384
+
385
+ def _get_flag_lookup() -> dict[str, int]:
386
+ import doctest
387
+
388
+ return dict(
389
+ DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1,
390
+ DONT_ACCEPT_BLANKLINE=doctest.DONT_ACCEPT_BLANKLINE,
391
+ NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE,
392
+ ELLIPSIS=doctest.ELLIPSIS,
393
+ IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL,
394
+ COMPARISON_FLAGS=doctest.COMPARISON_FLAGS,
395
+ ALLOW_UNICODE=_get_allow_unicode_flag(),
396
+ ALLOW_BYTES=_get_allow_bytes_flag(),
397
+ NUMBER=_get_number_flag(),
398
+ )
399
+
400
+
401
+ def get_optionflags(config: Config) -> int:
402
+ optionflags_str = config.getini("doctest_optionflags")
403
+ flag_lookup_table = _get_flag_lookup()
404
+ flag_acc = 0
405
+ for flag in optionflags_str:
406
+ flag_acc |= flag_lookup_table[flag]
407
+ return flag_acc
408
+
409
+
410
+ def _get_continue_on_failure(config: Config) -> bool:
411
+ continue_on_failure: bool = config.getvalue("doctest_continue_on_failure")
412
+ if continue_on_failure:
413
+ # We need to turn off this if we use pdb since we should stop at
414
+ # the first failure.
415
+ if config.getvalue("usepdb"):
416
+ continue_on_failure = False
417
+ return continue_on_failure
418
+
419
+
420
+ class DoctestTextfile(Module):
421
+ obj = None
422
+
423
+ def collect(self) -> Iterable[DoctestItem]:
424
+ import doctest
425
+
426
+ # Inspired by doctest.testfile; ideally we would use it directly,
427
+ # but it doesn't support passing a custom checker.
428
+ encoding = self.config.getini("doctest_encoding")
429
+ text = self.path.read_text(encoding)
430
+ filename = str(self.path)
431
+ name = self.path.name
432
+ globs = {"__name__": "__main__"}
433
+
434
+ optionflags = get_optionflags(self.config)
435
+
436
+ runner = _get_runner(
437
+ verbose=False,
438
+ optionflags=optionflags,
439
+ checker=_get_checker(),
440
+ continue_on_failure=_get_continue_on_failure(self.config),
441
+ )
442
+
443
+ parser = doctest.DocTestParser()
444
+ test = parser.get_doctest(text, globs, name, filename, 0)
445
+ if test.examples:
446
+ yield DoctestItem.from_parent(
447
+ self, name=test.name, runner=runner, dtest=test
448
+ )
449
+
450
+
451
+ def _check_all_skipped(test: doctest.DocTest) -> None:
452
+ """Raise pytest.skip() if all examples in the given DocTest have the SKIP
453
+ option set."""
454
+ import doctest
455
+
456
+ all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples)
457
+ if all_skipped:
458
+ skip("all tests skipped by +SKIP option")
459
+
460
+
461
+ def _is_mocked(obj: object) -> bool:
462
+ """Return if an object is possibly a mock object by checking the
463
+ existence of a highly improbable attribute."""
464
+ return (
465
+ safe_getattr(obj, "pytest_mock_example_attribute_that_shouldnt_exist", None)
466
+ is not None
467
+ )
468
+
469
+
470
+ @contextmanager
471
+ def _patch_unwrap_mock_aware() -> Generator[None]:
472
+ """Context manager which replaces ``inspect.unwrap`` with a version
473
+ that's aware of mock objects and doesn't recurse into them."""
474
+ real_unwrap = inspect.unwrap
475
+
476
+ def _mock_aware_unwrap(
477
+ func: Callable[..., Any], *, stop: Callable[[Any], Any] | None = None
478
+ ) -> Any:
479
+ try:
480
+ if stop is None or stop is _is_mocked:
481
+ return real_unwrap(func, stop=_is_mocked)
482
+ _stop = stop
483
+ return real_unwrap(func, stop=lambda obj: _is_mocked(obj) or _stop(func))
484
+ except Exception as e:
485
+ warnings.warn(
486
+ f"Got {e!r} when unwrapping {func!r}. This is usually caused "
487
+ "by a violation of Python's object protocol; see e.g. "
488
+ "https://github.com/pytest-dev/pytest/issues/5080",
489
+ PytestWarning,
490
+ )
491
+ raise
492
+
493
+ inspect.unwrap = _mock_aware_unwrap
494
+ try:
495
+ yield
496
+ finally:
497
+ inspect.unwrap = real_unwrap
498
+
499
+
500
+ class DoctestModule(Module):
501
+ def collect(self) -> Iterable[DoctestItem]:
502
+ import doctest
503
+
504
+ class MockAwareDocTestFinder(doctest.DocTestFinder):
505
+ py_ver_info_minor = sys.version_info[:2]
506
+ is_find_lineno_broken = (
507
+ py_ver_info_minor < (3, 11)
508
+ or (py_ver_info_minor == (3, 11) and sys.version_info.micro < 9)
509
+ or (py_ver_info_minor == (3, 12) and sys.version_info.micro < 3)
510
+ )
511
+ if is_find_lineno_broken:
512
+
513
+ def _find_lineno(self, obj, source_lines):
514
+ """On older Pythons, doctest code does not take into account
515
+ `@property`. https://github.com/python/cpython/issues/61648
516
+
517
+ Moreover, wrapped Doctests need to be unwrapped so the correct
518
+ line number is returned. #8796
519
+ """
520
+ if isinstance(obj, property):
521
+ obj = getattr(obj, "fget", obj)
522
+
523
+ if hasattr(obj, "__wrapped__"):
524
+ # Get the main obj in case of it being wrapped
525
+ obj = inspect.unwrap(obj)
526
+
527
+ # Type ignored because this is a private function.
528
+ return super()._find_lineno( # type:ignore[misc]
529
+ obj,
530
+ source_lines,
531
+ )
532
+
533
+ if sys.version_info < (3, 10):
534
+
535
+ def _find(
536
+ self, tests, obj, name, module, source_lines, globs, seen
537
+ ) -> None:
538
+ """Override _find to work around issue in stdlib.
539
+
540
+ https://github.com/pytest-dev/pytest/issues/3456
541
+ https://github.com/python/cpython/issues/69718
542
+ """
543
+ if _is_mocked(obj):
544
+ return # pragma: no cover
545
+ with _patch_unwrap_mock_aware():
546
+ # Type ignored because this is a private function.
547
+ super()._find( # type:ignore[misc]
548
+ tests, obj, name, module, source_lines, globs, seen
549
+ )
550
+
551
+ if sys.version_info < (3, 13):
552
+
553
+ def _from_module(self, module, object):
554
+ """`cached_property` objects are never considered a part
555
+ of the 'current module'. As such they are skipped by doctest.
556
+ Here we override `_from_module` to check the underlying
557
+ function instead. https://github.com/python/cpython/issues/107995
558
+ """
559
+ if isinstance(object, functools.cached_property):
560
+ object = object.func
561
+
562
+ # Type ignored because this is a private function.
563
+ return super()._from_module(module, object) # type: ignore[misc]
564
+
565
+ try:
566
+ module = self.obj
567
+ except Collector.CollectError:
568
+ if self.config.getvalue("doctest_ignore_import_errors"):
569
+ skip(f"unable to import module {self.path!r}")
570
+ else:
571
+ raise
572
+
573
+ # While doctests currently don't support fixtures directly, we still
574
+ # need to pick up autouse fixtures.
575
+ self.session._fixturemanager.parsefactories(self)
576
+
577
+ # Uses internal doctest module parsing mechanism.
578
+ finder = MockAwareDocTestFinder()
579
+ optionflags = get_optionflags(self.config)
580
+ runner = _get_runner(
581
+ verbose=False,
582
+ optionflags=optionflags,
583
+ checker=_get_checker(),
584
+ continue_on_failure=_get_continue_on_failure(self.config),
585
+ )
586
+
587
+ for test in finder.find(module, module.__name__):
588
+ if test.examples: # skip empty doctests
589
+ yield DoctestItem.from_parent(
590
+ self, name=test.name, runner=runner, dtest=test
591
+ )
592
+
593
+
594
+ def _init_checker_class() -> type[doctest.OutputChecker]:
595
+ import doctest
596
+ import re
597
+
598
+ class LiteralsOutputChecker(doctest.OutputChecker):
599
+ # Based on doctest_nose_plugin.py from the nltk project
600
+ # (https://github.com/nltk/nltk) and on the "numtest" doctest extension
601
+ # by Sebastien Boisgerault (https://github.com/boisgera/numtest).
602
+
603
+ _unicode_literal_re = re.compile(r"(\W|^)[uU]([rR]?[\'\"])", re.UNICODE)
604
+ _bytes_literal_re = re.compile(r"(\W|^)[bB]([rR]?[\'\"])", re.UNICODE)
605
+ _number_re = re.compile(
606
+ r"""
607
+ (?P<number>
608
+ (?P<mantissa>
609
+ (?P<integer1> [+-]?\d*)\.(?P<fraction>\d+)
610
+ |
611
+ (?P<integer2> [+-]?\d+)\.
612
+ )
613
+ (?:
614
+ [Ee]
615
+ (?P<exponent1> [+-]?\d+)
616
+ )?
617
+ |
618
+ (?P<integer3> [+-]?\d+)
619
+ (?:
620
+ [Ee]
621
+ (?P<exponent2> [+-]?\d+)
622
+ )
623
+ )
624
+ """,
625
+ re.VERBOSE,
626
+ )
627
+
628
+ def check_output(self, want: str, got: str, optionflags: int) -> bool:
629
+ if super().check_output(want, got, optionflags):
630
+ return True
631
+
632
+ allow_unicode = optionflags & _get_allow_unicode_flag()
633
+ allow_bytes = optionflags & _get_allow_bytes_flag()
634
+ allow_number = optionflags & _get_number_flag()
635
+
636
+ if not allow_unicode and not allow_bytes and not allow_number:
637
+ return False
638
+
639
+ def remove_prefixes(regex: Pattern[str], txt: str) -> str:
640
+ return re.sub(regex, r"\1\2", txt)
641
+
642
+ if allow_unicode:
643
+ want = remove_prefixes(self._unicode_literal_re, want)
644
+ got = remove_prefixes(self._unicode_literal_re, got)
645
+
646
+ if allow_bytes:
647
+ want = remove_prefixes(self._bytes_literal_re, want)
648
+ got = remove_prefixes(self._bytes_literal_re, got)
649
+
650
+ if allow_number:
651
+ got = self._remove_unwanted_precision(want, got)
652
+
653
+ return super().check_output(want, got, optionflags)
654
+
655
+ def _remove_unwanted_precision(self, want: str, got: str) -> str:
656
+ wants = list(self._number_re.finditer(want))
657
+ gots = list(self._number_re.finditer(got))
658
+ if len(wants) != len(gots):
659
+ return got
660
+ offset = 0
661
+ for w, g in zip(wants, gots):
662
+ fraction: str | None = w.group("fraction")
663
+ exponent: str | None = w.group("exponent1")
664
+ if exponent is None:
665
+ exponent = w.group("exponent2")
666
+ precision = 0 if fraction is None else len(fraction)
667
+ if exponent is not None:
668
+ precision -= int(exponent)
669
+ if float(w.group()) == approx(float(g.group()), abs=10**-precision):
670
+ # They're close enough. Replace the text we actually
671
+ # got with the text we want, so that it will match when we
672
+ # check the string literally.
673
+ got = (
674
+ got[: g.start() + offset] + w.group() + got[g.end() + offset :]
675
+ )
676
+ offset += w.end() - w.start() - (g.end() - g.start())
677
+ return got
678
+
679
+ return LiteralsOutputChecker
680
+
681
+
682
+ def _get_checker() -> doctest.OutputChecker:
683
+ """Return a doctest.OutputChecker subclass that supports some
684
+ additional options:
685
+
686
+ * ALLOW_UNICODE and ALLOW_BYTES options to ignore u'' and b''
687
+ prefixes (respectively) in string literals. Useful when the same
688
+ doctest should run in Python 2 and Python 3.
689
+
690
+ * NUMBER to ignore floating-point differences smaller than the
691
+ precision of the literal number in the doctest.
692
+
693
+ An inner class is used to avoid importing "doctest" at the module
694
+ level.
695
+ """
696
+ global CHECKER_CLASS
697
+ if CHECKER_CLASS is None:
698
+ CHECKER_CLASS = _init_checker_class()
699
+ return CHECKER_CLASS()
700
+
701
+
702
+ def _get_allow_unicode_flag() -> int:
703
+ """Register and return the ALLOW_UNICODE flag."""
704
+ import doctest
705
+
706
+ return doctest.register_optionflag("ALLOW_UNICODE")
707
+
708
+
709
+ def _get_allow_bytes_flag() -> int:
710
+ """Register and return the ALLOW_BYTES flag."""
711
+ import doctest
712
+
713
+ return doctest.register_optionflag("ALLOW_BYTES")
714
+
715
+
716
+ def _get_number_flag() -> int:
717
+ """Register and return the NUMBER flag."""
718
+ import doctest
719
+
720
+ return doctest.register_optionflag("NUMBER")
721
+
722
+
723
+ def _get_report_choice(key: str) -> int:
724
+ """Return the actual `doctest` module flag value.
725
+
726
+ We want to do it as late as possible to avoid importing `doctest` and all
727
+ its dependencies when parsing options, as it adds overhead and breaks tests.
728
+ """
729
+ import doctest
730
+
731
+ return {
732
+ DOCTEST_REPORT_CHOICE_UDIFF: doctest.REPORT_UDIFF,
733
+ DOCTEST_REPORT_CHOICE_CDIFF: doctest.REPORT_CDIFF,
734
+ DOCTEST_REPORT_CHOICE_NDIFF: doctest.REPORT_NDIFF,
735
+ DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE: doctest.REPORT_ONLY_FIRST_FAILURE,
736
+ DOCTEST_REPORT_CHOICE_NONE: 0,
737
+ }[key]
738
+
739
+
740
+ @fixture(scope="session")
741
+ def doctest_namespace() -> dict[str, Any]:
742
+ """Fixture that returns a :py:class:`dict` that will be injected into the
743
+ namespace of doctests.
744
+
745
+ Usually this fixture is used in conjunction with another ``autouse`` fixture:
746
+
747
+ .. code-block:: python
748
+
749
+ @pytest.fixture(autouse=True)
750
+ def add_np(doctest_namespace):
751
+ doctest_namespace["np"] = numpy
752
+
753
+ For more details: :ref:`doctest_namespace`.
754
+ """
755
+ return dict()
vllm/lib/python3.10/site-packages/_pytest/fixtures.py ADDED
@@ -0,0 +1,1932 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ import abc
5
+ from collections import defaultdict
6
+ from collections import deque
7
+ import dataclasses
8
+ import functools
9
+ import inspect
10
+ import os
11
+ from pathlib import Path
12
+ import sys
13
+ import types
14
+ from typing import AbstractSet
15
+ from typing import Any
16
+ from typing import Callable
17
+ from typing import cast
18
+ from typing import Dict
19
+ from typing import Final
20
+ from typing import final
21
+ from typing import Generator
22
+ from typing import Generic
23
+ from typing import Iterable
24
+ from typing import Iterator
25
+ from typing import Mapping
26
+ from typing import MutableMapping
27
+ from typing import NoReturn
28
+ from typing import Optional
29
+ from typing import OrderedDict
30
+ from typing import overload
31
+ from typing import Sequence
32
+ from typing import Tuple
33
+ from typing import TYPE_CHECKING
34
+ from typing import TypeVar
35
+ from typing import Union
36
+ import warnings
37
+
38
+ import _pytest
39
+ from _pytest import nodes
40
+ from _pytest._code import getfslineno
41
+ from _pytest._code import Source
42
+ from _pytest._code.code import FormattedExcinfo
43
+ from _pytest._code.code import TerminalRepr
44
+ from _pytest._io import TerminalWriter
45
+ from _pytest.compat import _PytestWrapper
46
+ from _pytest.compat import assert_never
47
+ from _pytest.compat import get_real_func
48
+ from _pytest.compat import get_real_method
49
+ from _pytest.compat import getfuncargnames
50
+ from _pytest.compat import getimfunc
51
+ from _pytest.compat import getlocation
52
+ from _pytest.compat import is_generator
53
+ from _pytest.compat import NOTSET
54
+ from _pytest.compat import NotSetType
55
+ from _pytest.compat import safe_getattr
56
+ from _pytest.compat import safe_isclass
57
+ from _pytest.config import _PluggyPlugin
58
+ from _pytest.config import Config
59
+ from _pytest.config import ExitCode
60
+ from _pytest.config.argparsing import Parser
61
+ from _pytest.deprecated import check_ispytest
62
+ from _pytest.deprecated import MARKED_FIXTURE
63
+ from _pytest.deprecated import YIELD_FIXTURE
64
+ from _pytest.main import Session
65
+ from _pytest.mark import Mark
66
+ from _pytest.mark import ParameterSet
67
+ from _pytest.mark.structures import MarkDecorator
68
+ from _pytest.outcomes import fail
69
+ from _pytest.outcomes import skip
70
+ from _pytest.outcomes import TEST_OUTCOME
71
+ from _pytest.pathlib import absolutepath
72
+ from _pytest.pathlib import bestrelpath
73
+ from _pytest.scope import _ScopeName
74
+ from _pytest.scope import HIGH_SCOPES
75
+ from _pytest.scope import Scope
76
+
77
+
78
+ if sys.version_info < (3, 11):
79
+ from exceptiongroup import BaseExceptionGroup
80
+
81
+
82
+ if TYPE_CHECKING:
83
+ from _pytest.python import CallSpec2
84
+ from _pytest.python import Function
85
+ from _pytest.python import Metafunc
86
+
87
+
88
+ # The value of the fixture -- return/yield of the fixture function (type variable).
89
+ FixtureValue = TypeVar("FixtureValue")
90
+ # The type of the fixture function (type variable).
91
+ FixtureFunction = TypeVar("FixtureFunction", bound=Callable[..., object])
92
+ # The type of a fixture function (type alias generic in fixture value).
93
+ _FixtureFunc = Union[
94
+ Callable[..., FixtureValue], Callable[..., Generator[FixtureValue, None, None]]
95
+ ]
96
+ # The type of FixtureDef.cached_result (type alias generic in fixture value).
97
+ _FixtureCachedResult = Union[
98
+ Tuple[
99
+ # The result.
100
+ FixtureValue,
101
+ # Cache key.
102
+ object,
103
+ None,
104
+ ],
105
+ Tuple[
106
+ None,
107
+ # Cache key.
108
+ object,
109
+ # The exception and the original traceback.
110
+ Tuple[BaseException, Optional[types.TracebackType]],
111
+ ],
112
+ ]
113
+
114
+
115
+ @dataclasses.dataclass(frozen=True)
116
+ class PseudoFixtureDef(Generic[FixtureValue]):
117
+ cached_result: _FixtureCachedResult[FixtureValue]
118
+ _scope: Scope
119
+
120
+
121
+ def pytest_sessionstart(session: Session) -> None:
122
+ session._fixturemanager = FixtureManager(session)
123
+
124
+
125
+ def get_scope_package(
126
+ node: nodes.Item,
127
+ fixturedef: FixtureDef[object],
128
+ ) -> nodes.Node | None:
129
+ from _pytest.python import Package
130
+
131
+ for parent in node.iter_parents():
132
+ if isinstance(parent, Package) and parent.nodeid == fixturedef.baseid:
133
+ return parent
134
+ return node.session
135
+
136
+
137
+ def get_scope_node(node: nodes.Node, scope: Scope) -> nodes.Node | None:
138
+ import _pytest.python
139
+
140
+ if scope is Scope.Function:
141
+ # Type ignored because this is actually safe, see:
142
+ # https://github.com/python/mypy/issues/4717
143
+ return node.getparent(nodes.Item) # type: ignore[type-abstract]
144
+ elif scope is Scope.Class:
145
+ return node.getparent(_pytest.python.Class)
146
+ elif scope is Scope.Module:
147
+ return node.getparent(_pytest.python.Module)
148
+ elif scope is Scope.Package:
149
+ return node.getparent(_pytest.python.Package)
150
+ elif scope is Scope.Session:
151
+ return node.getparent(_pytest.main.Session)
152
+ else:
153
+ assert_never(scope)
154
+
155
+
156
+ def getfixturemarker(obj: object) -> FixtureFunctionMarker | None:
157
+ """Return fixturemarker or None if it doesn't exist or raised
158
+ exceptions."""
159
+ return cast(
160
+ Optional[FixtureFunctionMarker],
161
+ safe_getattr(obj, "_pytestfixturefunction", None),
162
+ )
163
+
164
+
165
+ # Algorithm for sorting on a per-parametrized resource setup basis.
166
+ # It is called for Session scope first and performs sorting
167
+ # down to the lower scopes such as to minimize number of "high scope"
168
+ # setups and teardowns.
169
+
170
+
171
+ @dataclasses.dataclass(frozen=True)
172
+ class FixtureArgKey:
173
+ argname: str
174
+ param_index: int
175
+ scoped_item_path: Path | None
176
+ item_cls: type | None
177
+
178
+
179
+ _V = TypeVar("_V")
180
+ OrderedSet = Dict[_V, None]
181
+
182
+
183
+ def get_parametrized_fixture_argkeys(
184
+ item: nodes.Item, scope: Scope
185
+ ) -> Iterator[FixtureArgKey]:
186
+ """Return list of keys for all parametrized arguments which match
187
+ the specified scope."""
188
+ assert scope is not Scope.Function
189
+
190
+ try:
191
+ callspec: CallSpec2 = item.callspec # type: ignore[attr-defined]
192
+ except AttributeError:
193
+ return
194
+
195
+ item_cls = None
196
+ if scope is Scope.Session:
197
+ scoped_item_path = None
198
+ elif scope is Scope.Package:
199
+ # Package key = module's directory.
200
+ scoped_item_path = item.path.parent
201
+ elif scope is Scope.Module:
202
+ scoped_item_path = item.path
203
+ elif scope is Scope.Class:
204
+ scoped_item_path = item.path
205
+ item_cls = item.cls # type: ignore[attr-defined]
206
+ else:
207
+ assert_never(scope)
208
+
209
+ for argname in callspec.indices:
210
+ if callspec._arg2scope[argname] != scope:
211
+ continue
212
+ param_index = callspec.indices[argname]
213
+ yield FixtureArgKey(argname, param_index, scoped_item_path, item_cls)
214
+
215
+
216
+ def reorder_items(items: Sequence[nodes.Item]) -> list[nodes.Item]:
217
+ argkeys_by_item: dict[Scope, dict[nodes.Item, OrderedSet[FixtureArgKey]]] = {}
218
+ items_by_argkey: dict[
219
+ Scope, dict[FixtureArgKey, OrderedDict[nodes.Item, None]]
220
+ ] = {}
221
+ for scope in HIGH_SCOPES:
222
+ scoped_argkeys_by_item = argkeys_by_item[scope] = {}
223
+ scoped_items_by_argkey = items_by_argkey[scope] = defaultdict(OrderedDict)
224
+ for item in items:
225
+ argkeys = dict.fromkeys(get_parametrized_fixture_argkeys(item, scope))
226
+ if argkeys:
227
+ scoped_argkeys_by_item[item] = argkeys
228
+ for argkey in argkeys:
229
+ scoped_items_by_argkey[argkey][item] = None
230
+
231
+ items_set = dict.fromkeys(items)
232
+ return list(
233
+ reorder_items_atscope(
234
+ items_set, argkeys_by_item, items_by_argkey, Scope.Session
235
+ )
236
+ )
237
+
238
+
239
+ def reorder_items_atscope(
240
+ items: OrderedSet[nodes.Item],
241
+ argkeys_by_item: Mapping[Scope, Mapping[nodes.Item, OrderedSet[FixtureArgKey]]],
242
+ items_by_argkey: Mapping[
243
+ Scope, Mapping[FixtureArgKey, OrderedDict[nodes.Item, None]]
244
+ ],
245
+ scope: Scope,
246
+ ) -> OrderedSet[nodes.Item]:
247
+ if scope is Scope.Function or len(items) < 3:
248
+ return items
249
+
250
+ scoped_items_by_argkey = items_by_argkey[scope]
251
+ scoped_argkeys_by_item = argkeys_by_item[scope]
252
+
253
+ ignore: set[FixtureArgKey] = set()
254
+ items_deque = deque(items)
255
+ items_done: OrderedSet[nodes.Item] = {}
256
+ while items_deque:
257
+ no_argkey_items: OrderedSet[nodes.Item] = {}
258
+ slicing_argkey = None
259
+ while items_deque:
260
+ item = items_deque.popleft()
261
+ if item in items_done or item in no_argkey_items:
262
+ continue
263
+ argkeys = dict.fromkeys(
264
+ k for k in scoped_argkeys_by_item.get(item, ()) if k not in ignore
265
+ )
266
+ if not argkeys:
267
+ no_argkey_items[item] = None
268
+ else:
269
+ slicing_argkey, _ = argkeys.popitem()
270
+ # We don't have to remove relevant items from later in the
271
+ # deque because they'll just be ignored.
272
+ matching_items = [
273
+ i for i in scoped_items_by_argkey[slicing_argkey] if i in items
274
+ ]
275
+ for i in reversed(matching_items):
276
+ items_deque.appendleft(i)
277
+ # Fix items_by_argkey order.
278
+ for other_scope in HIGH_SCOPES:
279
+ other_scoped_items_by_argkey = items_by_argkey[other_scope]
280
+ for argkey in argkeys_by_item[other_scope].get(i, ()):
281
+ other_scoped_items_by_argkey[argkey][i] = None
282
+ other_scoped_items_by_argkey[argkey].move_to_end(
283
+ i, last=False
284
+ )
285
+ break
286
+ if no_argkey_items:
287
+ reordered_no_argkey_items = reorder_items_atscope(
288
+ no_argkey_items, argkeys_by_item, items_by_argkey, scope.next_lower()
289
+ )
290
+ items_done.update(reordered_no_argkey_items)
291
+ if slicing_argkey is not None:
292
+ ignore.add(slicing_argkey)
293
+ return items_done
294
+
295
+
296
+ @dataclasses.dataclass(frozen=True)
297
+ class FuncFixtureInfo:
298
+ """Fixture-related information for a fixture-requesting item (e.g. test
299
+ function).
300
+
301
+ This is used to examine the fixtures which an item requests statically
302
+ (known during collection). This includes autouse fixtures, fixtures
303
+ requested by the `usefixtures` marker, fixtures requested in the function
304
+ parameters, and the transitive closure of these.
305
+
306
+ An item may also request fixtures dynamically (using `request.getfixturevalue`);
307
+ these are not reflected here.
308
+ """
309
+
310
+ __slots__ = ("argnames", "initialnames", "names_closure", "name2fixturedefs")
311
+
312
+ # Fixture names that the item requests directly by function parameters.
313
+ argnames: tuple[str, ...]
314
+ # Fixture names that the item immediately requires. These include
315
+ # argnames + fixture names specified via usefixtures and via autouse=True in
316
+ # fixture definitions.
317
+ initialnames: tuple[str, ...]
318
+ # The transitive closure of the fixture names that the item requires.
319
+ # Note: can't include dynamic dependencies (`request.getfixturevalue` calls).
320
+ names_closure: list[str]
321
+ # A map from a fixture name in the transitive closure to the FixtureDefs
322
+ # matching the name which are applicable to this function.
323
+ # There may be multiple overriding fixtures with the same name. The
324
+ # sequence is ordered from furthest to closes to the function.
325
+ name2fixturedefs: dict[str, Sequence[FixtureDef[Any]]]
326
+
327
+ def prune_dependency_tree(self) -> None:
328
+ """Recompute names_closure from initialnames and name2fixturedefs.
329
+
330
+ Can only reduce names_closure, which means that the new closure will
331
+ always be a subset of the old one. The order is preserved.
332
+
333
+ This method is needed because direct parametrization may shadow some
334
+ of the fixtures that were included in the originally built dependency
335
+ tree. In this way the dependency tree can get pruned, and the closure
336
+ of argnames may get reduced.
337
+ """
338
+ closure: set[str] = set()
339
+ working_set = set(self.initialnames)
340
+ while working_set:
341
+ argname = working_set.pop()
342
+ # Argname may be something not included in the original names_closure,
343
+ # in which case we ignore it. This currently happens with pseudo
344
+ # FixtureDefs which wrap 'get_direct_param_fixture_func(request)'.
345
+ # So they introduce the new dependency 'request' which might have
346
+ # been missing in the original tree (closure).
347
+ if argname not in closure and argname in self.names_closure:
348
+ closure.add(argname)
349
+ if argname in self.name2fixturedefs:
350
+ working_set.update(self.name2fixturedefs[argname][-1].argnames)
351
+
352
+ self.names_closure[:] = sorted(closure, key=self.names_closure.index)
353
+
354
+
355
+ class FixtureRequest(abc.ABC):
356
+ """The type of the ``request`` fixture.
357
+
358
+ A request object gives access to the requesting test context and has a
359
+ ``param`` attribute in case the fixture is parametrized.
360
+ """
361
+
362
+ def __init__(
363
+ self,
364
+ pyfuncitem: Function,
365
+ fixturename: str | None,
366
+ arg2fixturedefs: dict[str, Sequence[FixtureDef[Any]]],
367
+ fixture_defs: dict[str, FixtureDef[Any]],
368
+ *,
369
+ _ispytest: bool = False,
370
+ ) -> None:
371
+ check_ispytest(_ispytest)
372
+ #: Fixture for which this request is being performed.
373
+ self.fixturename: Final = fixturename
374
+ self._pyfuncitem: Final = pyfuncitem
375
+ # The FixtureDefs for each fixture name requested by this item.
376
+ # Starts from the statically-known fixturedefs resolved during
377
+ # collection. Dynamically requested fixtures (using
378
+ # `request.getfixturevalue("foo")`) are added dynamically.
379
+ self._arg2fixturedefs: Final = arg2fixturedefs
380
+ # The evaluated argnames so far, mapping to the FixtureDef they resolved
381
+ # to.
382
+ self._fixture_defs: Final = fixture_defs
383
+ # Notes on the type of `param`:
384
+ # -`request.param` is only defined in parametrized fixtures, and will raise
385
+ # AttributeError otherwise. Python typing has no notion of "undefined", so
386
+ # this cannot be reflected in the type.
387
+ # - Technically `param` is only (possibly) defined on SubRequest, not
388
+ # FixtureRequest, but the typing of that is still in flux so this cheats.
389
+ # - In the future we might consider using a generic for the param type, but
390
+ # for now just using Any.
391
+ self.param: Any
392
+
393
+ @property
394
+ def _fixturemanager(self) -> FixtureManager:
395
+ return self._pyfuncitem.session._fixturemanager
396
+
397
+ @property
398
+ @abc.abstractmethod
399
+ def _scope(self) -> Scope:
400
+ raise NotImplementedError()
401
+
402
+ @property
403
+ def scope(self) -> _ScopeName:
404
+ """Scope string, one of "function", "class", "module", "package", "session"."""
405
+ return self._scope.value
406
+
407
+ @abc.abstractmethod
408
+ def _check_scope(
409
+ self,
410
+ requested_fixturedef: FixtureDef[object] | PseudoFixtureDef[object],
411
+ requested_scope: Scope,
412
+ ) -> None:
413
+ raise NotImplementedError()
414
+
415
+ @property
416
+ def fixturenames(self) -> list[str]:
417
+ """Names of all active fixtures in this request."""
418
+ result = list(self._pyfuncitem.fixturenames)
419
+ result.extend(set(self._fixture_defs).difference(result))
420
+ return result
421
+
422
+ @property
423
+ @abc.abstractmethod
424
+ def node(self):
425
+ """Underlying collection node (depends on current request scope)."""
426
+ raise NotImplementedError()
427
+
428
+ @property
429
+ def config(self) -> Config:
430
+ """The pytest config object associated with this request."""
431
+ return self._pyfuncitem.config
432
+
433
+ @property
434
+ def function(self):
435
+ """Test function object if the request has a per-function scope."""
436
+ if self.scope != "function":
437
+ raise AttributeError(
438
+ f"function not available in {self.scope}-scoped context"
439
+ )
440
+ return self._pyfuncitem.obj
441
+
442
+ @property
443
+ def cls(self):
444
+ """Class (can be None) where the test function was collected."""
445
+ if self.scope not in ("class", "function"):
446
+ raise AttributeError(f"cls not available in {self.scope}-scoped context")
447
+ clscol = self._pyfuncitem.getparent(_pytest.python.Class)
448
+ if clscol:
449
+ return clscol.obj
450
+
451
+ @property
452
+ def instance(self):
453
+ """Instance (can be None) on which test function was collected."""
454
+ if self.scope != "function":
455
+ return None
456
+ return getattr(self._pyfuncitem, "instance", None)
457
+
458
+ @property
459
+ def module(self):
460
+ """Python module object where the test function was collected."""
461
+ if self.scope not in ("function", "class", "module"):
462
+ raise AttributeError(f"module not available in {self.scope}-scoped context")
463
+ mod = self._pyfuncitem.getparent(_pytest.python.Module)
464
+ assert mod is not None
465
+ return mod.obj
466
+
467
+ @property
468
+ def path(self) -> Path:
469
+ """Path where the test function was collected."""
470
+ if self.scope not in ("function", "class", "module", "package"):
471
+ raise AttributeError(f"path not available in {self.scope}-scoped context")
472
+ return self._pyfuncitem.path
473
+
474
+ @property
475
+ def keywords(self) -> MutableMapping[str, Any]:
476
+ """Keywords/markers dictionary for the underlying node."""
477
+ node: nodes.Node = self.node
478
+ return node.keywords
479
+
480
+ @property
481
+ def session(self) -> Session:
482
+ """Pytest session object."""
483
+ return self._pyfuncitem.session
484
+
485
+ @abc.abstractmethod
486
+ def addfinalizer(self, finalizer: Callable[[], object]) -> None:
487
+ """Add finalizer/teardown function to be called without arguments after
488
+ the last test within the requesting test context finished execution."""
489
+ raise NotImplementedError()
490
+
491
+ def applymarker(self, marker: str | MarkDecorator) -> None:
492
+ """Apply a marker to a single test function invocation.
493
+
494
+ This method is useful if you don't want to have a keyword/marker
495
+ on all function invocations.
496
+
497
+ :param marker:
498
+ An object created by a call to ``pytest.mark.NAME(...)``.
499
+ """
500
+ self.node.add_marker(marker)
501
+
502
+ def raiseerror(self, msg: str | None) -> NoReturn:
503
+ """Raise a FixtureLookupError exception.
504
+
505
+ :param msg:
506
+ An optional custom error message.
507
+ """
508
+ raise FixtureLookupError(None, self, msg)
509
+
510
+ def getfixturevalue(self, argname: str) -> Any:
511
+ """Dynamically run a named fixture function.
512
+
513
+ Declaring fixtures via function argument is recommended where possible.
514
+ But if you can only decide whether to use another fixture at test
515
+ setup time, you may use this function to retrieve it inside a fixture
516
+ or test function body.
517
+
518
+ This method can be used during the test setup phase or the test run
519
+ phase, but during the test teardown phase a fixture's value may not
520
+ be available.
521
+
522
+ :param argname:
523
+ The fixture name.
524
+ :raises pytest.FixtureLookupError:
525
+ If the given fixture could not be found.
526
+ """
527
+ # Note that in addition to the use case described in the docstring,
528
+ # getfixturevalue() is also called by pytest itself during item and fixture
529
+ # setup to evaluate the fixtures that are requested statically
530
+ # (using function parameters, autouse, etc).
531
+
532
+ fixturedef = self._get_active_fixturedef(argname)
533
+ assert fixturedef.cached_result is not None, (
534
+ f'The fixture value for "{argname}" is not available. '
535
+ "This can happen when the fixture has already been torn down."
536
+ )
537
+ return fixturedef.cached_result[0]
538
+
539
+ def _iter_chain(self) -> Iterator[SubRequest]:
540
+ """Yield all SubRequests in the chain, from self up.
541
+
542
+ Note: does *not* yield the TopRequest.
543
+ """
544
+ current = self
545
+ while isinstance(current, SubRequest):
546
+ yield current
547
+ current = current._parent_request
548
+
549
+ def _get_active_fixturedef(
550
+ self, argname: str
551
+ ) -> FixtureDef[object] | PseudoFixtureDef[object]:
552
+ if argname == "request":
553
+ cached_result = (self, [0], None)
554
+ return PseudoFixtureDef(cached_result, Scope.Function)
555
+
556
+ # If we already finished computing a fixture by this name in this item,
557
+ # return it.
558
+ fixturedef = self._fixture_defs.get(argname)
559
+ if fixturedef is not None:
560
+ self._check_scope(fixturedef, fixturedef._scope)
561
+ return fixturedef
562
+
563
+ # Find the appropriate fixturedef.
564
+ fixturedefs = self._arg2fixturedefs.get(argname, None)
565
+ if fixturedefs is None:
566
+ # We arrive here because of a dynamic call to
567
+ # getfixturevalue(argname) which was naturally
568
+ # not known at parsing/collection time.
569
+ fixturedefs = self._fixturemanager.getfixturedefs(argname, self._pyfuncitem)
570
+ if fixturedefs is not None:
571
+ self._arg2fixturedefs[argname] = fixturedefs
572
+ # No fixtures defined with this name.
573
+ if fixturedefs is None:
574
+ raise FixtureLookupError(argname, self)
575
+ # The are no fixtures with this name applicable for the function.
576
+ if not fixturedefs:
577
+ raise FixtureLookupError(argname, self)
578
+ # A fixture may override another fixture with the same name, e.g. a
579
+ # fixture in a module can override a fixture in a conftest, a fixture in
580
+ # a class can override a fixture in the module, and so on.
581
+ # An overriding fixture can request its own name (possibly indirectly);
582
+ # in this case it gets the value of the fixture it overrides, one level
583
+ # up.
584
+ # Check how many `argname`s deep we are, and take the next one.
585
+ # `fixturedefs` is sorted from furthest to closest, so use negative
586
+ # indexing to go in reverse.
587
+ index = -1
588
+ for request in self._iter_chain():
589
+ if request.fixturename == argname:
590
+ index -= 1
591
+ # If already consumed all of the available levels, fail.
592
+ if -index > len(fixturedefs):
593
+ raise FixtureLookupError(argname, self)
594
+ fixturedef = fixturedefs[index]
595
+
596
+ # Prepare a SubRequest object for calling the fixture.
597
+ try:
598
+ callspec = self._pyfuncitem.callspec
599
+ except AttributeError:
600
+ callspec = None
601
+ if callspec is not None and argname in callspec.params:
602
+ param = callspec.params[argname]
603
+ param_index = callspec.indices[argname]
604
+ # The parametrize invocation scope overrides the fixture's scope.
605
+ scope = callspec._arg2scope[argname]
606
+ else:
607
+ param = NOTSET
608
+ param_index = 0
609
+ scope = fixturedef._scope
610
+ self._check_fixturedef_without_param(fixturedef)
611
+ self._check_scope(fixturedef, scope)
612
+ subrequest = SubRequest(
613
+ self, scope, param, param_index, fixturedef, _ispytest=True
614
+ )
615
+
616
+ # Make sure the fixture value is cached, running it if it isn't
617
+ fixturedef.execute(request=subrequest)
618
+
619
+ self._fixture_defs[argname] = fixturedef
620
+ return fixturedef
621
+
622
+ def _check_fixturedef_without_param(self, fixturedef: FixtureDef[object]) -> None:
623
+ """Check that this request is allowed to execute this fixturedef without
624
+ a param."""
625
+ funcitem = self._pyfuncitem
626
+ has_params = fixturedef.params is not None
627
+ fixtures_not_supported = getattr(funcitem, "nofuncargs", False)
628
+ if has_params and fixtures_not_supported:
629
+ msg = (
630
+ f"{funcitem.name} does not support fixtures, maybe unittest.TestCase subclass?\n"
631
+ f"Node id: {funcitem.nodeid}\n"
632
+ f"Function type: {type(funcitem).__name__}"
633
+ )
634
+ fail(msg, pytrace=False)
635
+ if has_params:
636
+ frame = inspect.stack()[3]
637
+ frameinfo = inspect.getframeinfo(frame[0])
638
+ source_path = absolutepath(frameinfo.filename)
639
+ source_lineno = frameinfo.lineno
640
+ try:
641
+ source_path_str = str(source_path.relative_to(funcitem.config.rootpath))
642
+ except ValueError:
643
+ source_path_str = str(source_path)
644
+ location = getlocation(fixturedef.func, funcitem.config.rootpath)
645
+ msg = (
646
+ "The requested fixture has no parameter defined for test:\n"
647
+ f" {funcitem.nodeid}\n\n"
648
+ f"Requested fixture '{fixturedef.argname}' defined in:\n"
649
+ f"{location}\n\n"
650
+ f"Requested here:\n"
651
+ f"{source_path_str}:{source_lineno}"
652
+ )
653
+ fail(msg, pytrace=False)
654
+
655
+ def _get_fixturestack(self) -> list[FixtureDef[Any]]:
656
+ values = [request._fixturedef for request in self._iter_chain()]
657
+ values.reverse()
658
+ return values
659
+
660
+
661
+ @final
662
+ class TopRequest(FixtureRequest):
663
+ """The type of the ``request`` fixture in a test function."""
664
+
665
+ def __init__(self, pyfuncitem: Function, *, _ispytest: bool = False) -> None:
666
+ super().__init__(
667
+ fixturename=None,
668
+ pyfuncitem=pyfuncitem,
669
+ arg2fixturedefs=pyfuncitem._fixtureinfo.name2fixturedefs.copy(),
670
+ fixture_defs={},
671
+ _ispytest=_ispytest,
672
+ )
673
+
674
+ @property
675
+ def _scope(self) -> Scope:
676
+ return Scope.Function
677
+
678
+ def _check_scope(
679
+ self,
680
+ requested_fixturedef: FixtureDef[object] | PseudoFixtureDef[object],
681
+ requested_scope: Scope,
682
+ ) -> None:
683
+ # TopRequest always has function scope so always valid.
684
+ pass
685
+
686
+ @property
687
+ def node(self):
688
+ return self._pyfuncitem
689
+
690
+ def __repr__(self) -> str:
691
+ return f"<FixtureRequest for {self.node!r}>"
692
+
693
+ def _fillfixtures(self) -> None:
694
+ item = self._pyfuncitem
695
+ for argname in item.fixturenames:
696
+ if argname not in item.funcargs:
697
+ item.funcargs[argname] = self.getfixturevalue(argname)
698
+
699
+ def addfinalizer(self, finalizer: Callable[[], object]) -> None:
700
+ self.node.addfinalizer(finalizer)
701
+
702
+
703
+ @final
704
+ class SubRequest(FixtureRequest):
705
+ """The type of the ``request`` fixture in a fixture function requested
706
+ (transitively) by a test function."""
707
+
708
+ def __init__(
709
+ self,
710
+ request: FixtureRequest,
711
+ scope: Scope,
712
+ param: Any,
713
+ param_index: int,
714
+ fixturedef: FixtureDef[object],
715
+ *,
716
+ _ispytest: bool = False,
717
+ ) -> None:
718
+ super().__init__(
719
+ pyfuncitem=request._pyfuncitem,
720
+ fixturename=fixturedef.argname,
721
+ fixture_defs=request._fixture_defs,
722
+ arg2fixturedefs=request._arg2fixturedefs,
723
+ _ispytest=_ispytest,
724
+ )
725
+ self._parent_request: Final[FixtureRequest] = request
726
+ self._scope_field: Final = scope
727
+ self._fixturedef: Final[FixtureDef[object]] = fixturedef
728
+ if param is not NOTSET:
729
+ self.param = param
730
+ self.param_index: Final = param_index
731
+
732
+ def __repr__(self) -> str:
733
+ return f"<SubRequest {self.fixturename!r} for {self._pyfuncitem!r}>"
734
+
735
+ @property
736
+ def _scope(self) -> Scope:
737
+ return self._scope_field
738
+
739
+ @property
740
+ def node(self):
741
+ scope = self._scope
742
+ if scope is Scope.Function:
743
+ # This might also be a non-function Item despite its attribute name.
744
+ node: nodes.Node | None = self._pyfuncitem
745
+ elif scope is Scope.Package:
746
+ node = get_scope_package(self._pyfuncitem, self._fixturedef)
747
+ else:
748
+ node = get_scope_node(self._pyfuncitem, scope)
749
+ if node is None and scope is Scope.Class:
750
+ # Fallback to function item itself.
751
+ node = self._pyfuncitem
752
+ assert node, f'Could not obtain a node for scope "{scope}" for function {self._pyfuncitem!r}'
753
+ return node
754
+
755
+ def _check_scope(
756
+ self,
757
+ requested_fixturedef: FixtureDef[object] | PseudoFixtureDef[object],
758
+ requested_scope: Scope,
759
+ ) -> None:
760
+ if isinstance(requested_fixturedef, PseudoFixtureDef):
761
+ return
762
+ if self._scope > requested_scope:
763
+ # Try to report something helpful.
764
+ argname = requested_fixturedef.argname
765
+ fixture_stack = "\n".join(
766
+ self._format_fixturedef_line(fixturedef)
767
+ for fixturedef in self._get_fixturestack()
768
+ )
769
+ requested_fixture = self._format_fixturedef_line(requested_fixturedef)
770
+ fail(
771
+ f"ScopeMismatch: You tried to access the {requested_scope.value} scoped "
772
+ f"fixture {argname} with a {self._scope.value} scoped request object. "
773
+ f"Requesting fixture stack:\n{fixture_stack}\n"
774
+ f"Requested fixture:\n{requested_fixture}",
775
+ pytrace=False,
776
+ )
777
+
778
+ def _format_fixturedef_line(self, fixturedef: FixtureDef[object]) -> str:
779
+ factory = fixturedef.func
780
+ path, lineno = getfslineno(factory)
781
+ if isinstance(path, Path):
782
+ path = bestrelpath(self._pyfuncitem.session.path, path)
783
+ signature = inspect.signature(factory)
784
+ return f"{path}:{lineno + 1}: def {factory.__name__}{signature}"
785
+
786
+ def addfinalizer(self, finalizer: Callable[[], object]) -> None:
787
+ self._fixturedef.addfinalizer(finalizer)
788
+
789
+
790
+ @final
791
+ class FixtureLookupError(LookupError):
792
+ """Could not return a requested fixture (missing or invalid)."""
793
+
794
+ def __init__(
795
+ self, argname: str | None, request: FixtureRequest, msg: str | None = None
796
+ ) -> None:
797
+ self.argname = argname
798
+ self.request = request
799
+ self.fixturestack = request._get_fixturestack()
800
+ self.msg = msg
801
+
802
+ def formatrepr(self) -> FixtureLookupErrorRepr:
803
+ tblines: list[str] = []
804
+ addline = tblines.append
805
+ stack = [self.request._pyfuncitem.obj]
806
+ stack.extend(map(lambda x: x.func, self.fixturestack))
807
+ msg = self.msg
808
+ if msg is not None:
809
+ # The last fixture raise an error, let's present
810
+ # it at the requesting side.
811
+ stack = stack[:-1]
812
+ for function in stack:
813
+ fspath, lineno = getfslineno(function)
814
+ try:
815
+ lines, _ = inspect.getsourcelines(get_real_func(function))
816
+ except (OSError, IndexError, TypeError):
817
+ error_msg = "file %s, line %s: source code not available"
818
+ addline(error_msg % (fspath, lineno + 1))
819
+ else:
820
+ addline(f"file {fspath}, line {lineno + 1}")
821
+ for i, line in enumerate(lines):
822
+ line = line.rstrip()
823
+ addline(" " + line)
824
+ if line.lstrip().startswith("def"):
825
+ break
826
+
827
+ if msg is None:
828
+ fm = self.request._fixturemanager
829
+ available = set()
830
+ parent = self.request._pyfuncitem.parent
831
+ assert parent is not None
832
+ for name, fixturedefs in fm._arg2fixturedefs.items():
833
+ faclist = list(fm._matchfactories(fixturedefs, parent))
834
+ if faclist:
835
+ available.add(name)
836
+ if self.argname in available:
837
+ msg = (
838
+ f" recursive dependency involving fixture '{self.argname}' detected"
839
+ )
840
+ else:
841
+ msg = f"fixture '{self.argname}' not found"
842
+ msg += "\n available fixtures: {}".format(", ".join(sorted(available)))
843
+ msg += "\n use 'pytest --fixtures [testpath]' for help on them."
844
+
845
+ return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname)
846
+
847
+
848
+ class FixtureLookupErrorRepr(TerminalRepr):
849
+ def __init__(
850
+ self,
851
+ filename: str | os.PathLike[str],
852
+ firstlineno: int,
853
+ tblines: Sequence[str],
854
+ errorstring: str,
855
+ argname: str | None,
856
+ ) -> None:
857
+ self.tblines = tblines
858
+ self.errorstring = errorstring
859
+ self.filename = filename
860
+ self.firstlineno = firstlineno
861
+ self.argname = argname
862
+
863
+ def toterminal(self, tw: TerminalWriter) -> None:
864
+ # tw.line("FixtureLookupError: %s" %(self.argname), red=True)
865
+ for tbline in self.tblines:
866
+ tw.line(tbline.rstrip())
867
+ lines = self.errorstring.split("\n")
868
+ if lines:
869
+ tw.line(
870
+ f"{FormattedExcinfo.fail_marker} {lines[0].strip()}",
871
+ red=True,
872
+ )
873
+ for line in lines[1:]:
874
+ tw.line(
875
+ f"{FormattedExcinfo.flow_marker} {line.strip()}",
876
+ red=True,
877
+ )
878
+ tw.line()
879
+ tw.line("%s:%d" % (os.fspath(self.filename), self.firstlineno + 1))
880
+
881
+
882
+ def call_fixture_func(
883
+ fixturefunc: _FixtureFunc[FixtureValue], request: FixtureRequest, kwargs
884
+ ) -> FixtureValue:
885
+ if is_generator(fixturefunc):
886
+ fixturefunc = cast(
887
+ Callable[..., Generator[FixtureValue, None, None]], fixturefunc
888
+ )
889
+ generator = fixturefunc(**kwargs)
890
+ try:
891
+ fixture_result = next(generator)
892
+ except StopIteration:
893
+ raise ValueError(f"{request.fixturename} did not yield a value") from None
894
+ finalizer = functools.partial(_teardown_yield_fixture, fixturefunc, generator)
895
+ request.addfinalizer(finalizer)
896
+ else:
897
+ fixturefunc = cast(Callable[..., FixtureValue], fixturefunc)
898
+ fixture_result = fixturefunc(**kwargs)
899
+ return fixture_result
900
+
901
+
902
+ def _teardown_yield_fixture(fixturefunc, it) -> None:
903
+ """Execute the teardown of a fixture function by advancing the iterator
904
+ after the yield and ensure the iteration ends (if not it means there is
905
+ more than one yield in the function)."""
906
+ try:
907
+ next(it)
908
+ except StopIteration:
909
+ pass
910
+ else:
911
+ fs, lineno = getfslineno(fixturefunc)
912
+ fail(
913
+ f"fixture function has more than one 'yield':\n\n"
914
+ f"{Source(fixturefunc).indent()}\n"
915
+ f"{fs}:{lineno + 1}",
916
+ pytrace=False,
917
+ )
918
+
919
+
920
+ def _eval_scope_callable(
921
+ scope_callable: Callable[[str, Config], _ScopeName],
922
+ fixture_name: str,
923
+ config: Config,
924
+ ) -> _ScopeName:
925
+ try:
926
+ # Type ignored because there is no typing mechanism to specify
927
+ # keyword arguments, currently.
928
+ result = scope_callable(fixture_name=fixture_name, config=config) # type: ignore[call-arg]
929
+ except Exception as e:
930
+ raise TypeError(
931
+ f"Error evaluating {scope_callable} while defining fixture '{fixture_name}'.\n"
932
+ "Expected a function with the signature (*, fixture_name, config)"
933
+ ) from e
934
+ if not isinstance(result, str):
935
+ fail(
936
+ f"Expected {scope_callable} to return a 'str' while defining fixture '{fixture_name}', but it returned:\n"
937
+ f"{result!r}",
938
+ pytrace=False,
939
+ )
940
+ return result
941
+
942
+
943
+ @final
944
+ class FixtureDef(Generic[FixtureValue]):
945
+ """A container for a fixture definition.
946
+
947
+ Note: At this time, only explicitly documented fields and methods are
948
+ considered public stable API.
949
+ """
950
+
951
+ def __init__(
952
+ self,
953
+ config: Config,
954
+ baseid: str | None,
955
+ argname: str,
956
+ func: _FixtureFunc[FixtureValue],
957
+ scope: Scope | _ScopeName | Callable[[str, Config], _ScopeName] | None,
958
+ params: Sequence[object] | None,
959
+ ids: tuple[object | None, ...] | Callable[[Any], object | None] | None = None,
960
+ *,
961
+ _ispytest: bool = False,
962
+ ) -> None:
963
+ check_ispytest(_ispytest)
964
+ # The "base" node ID for the fixture.
965
+ #
966
+ # This is a node ID prefix. A fixture is only available to a node (e.g.
967
+ # a `Function` item) if the fixture's baseid is a nodeid of a parent of
968
+ # node.
969
+ #
970
+ # For a fixture found in a Collector's object (e.g. a `Module`s module,
971
+ # a `Class`'s class), the baseid is the Collector's nodeid.
972
+ #
973
+ # For a fixture found in a conftest plugin, the baseid is the conftest's
974
+ # directory path relative to the rootdir.
975
+ #
976
+ # For other plugins, the baseid is the empty string (always matches).
977
+ self.baseid: Final = baseid or ""
978
+ # Whether the fixture was found from a node or a conftest in the
979
+ # collection tree. Will be false for fixtures defined in non-conftest
980
+ # plugins.
981
+ self.has_location: Final = baseid is not None
982
+ # The fixture factory function.
983
+ self.func: Final = func
984
+ # The name by which the fixture may be requested.
985
+ self.argname: Final = argname
986
+ if scope is None:
987
+ scope = Scope.Function
988
+ elif callable(scope):
989
+ scope = _eval_scope_callable(scope, argname, config)
990
+ if isinstance(scope, str):
991
+ scope = Scope.from_user(
992
+ scope, descr=f"Fixture '{func.__name__}'", where=baseid
993
+ )
994
+ self._scope: Final = scope
995
+ # If the fixture is directly parametrized, the parameter values.
996
+ self.params: Final = params
997
+ # If the fixture is directly parametrized, a tuple of explicit IDs to
998
+ # assign to the parameter values, or a callable to generate an ID given
999
+ # a parameter value.
1000
+ self.ids: Final = ids
1001
+ # The names requested by the fixtures.
1002
+ self.argnames: Final = getfuncargnames(func, name=argname)
1003
+ # If the fixture was executed, the current value of the fixture.
1004
+ # Can change if the fixture is executed with different parameters.
1005
+ self.cached_result: _FixtureCachedResult[FixtureValue] | None = None
1006
+ self._finalizers: Final[list[Callable[[], object]]] = []
1007
+
1008
+ @property
1009
+ def scope(self) -> _ScopeName:
1010
+ """Scope string, one of "function", "class", "module", "package", "session"."""
1011
+ return self._scope.value
1012
+
1013
+ def addfinalizer(self, finalizer: Callable[[], object]) -> None:
1014
+ self._finalizers.append(finalizer)
1015
+
1016
+ def finish(self, request: SubRequest) -> None:
1017
+ exceptions: list[BaseException] = []
1018
+ while self._finalizers:
1019
+ fin = self._finalizers.pop()
1020
+ try:
1021
+ fin()
1022
+ except BaseException as e:
1023
+ exceptions.append(e)
1024
+ node = request.node
1025
+ node.ihook.pytest_fixture_post_finalizer(fixturedef=self, request=request)
1026
+ # Even if finalization fails, we invalidate the cached fixture
1027
+ # value and remove all finalizers because they may be bound methods
1028
+ # which will keep instances alive.
1029
+ self.cached_result = None
1030
+ self._finalizers.clear()
1031
+ if len(exceptions) == 1:
1032
+ raise exceptions[0]
1033
+ elif len(exceptions) > 1:
1034
+ msg = f'errors while tearing down fixture "{self.argname}" of {node}'
1035
+ raise BaseExceptionGroup(msg, exceptions[::-1])
1036
+
1037
+ def execute(self, request: SubRequest) -> FixtureValue:
1038
+ """Return the value of this fixture, executing it if not cached."""
1039
+ # Ensure that the dependent fixtures requested by this fixture are loaded.
1040
+ # This needs to be done before checking if we have a cached value, since
1041
+ # if a dependent fixture has their cache invalidated, e.g. due to
1042
+ # parametrization, they finalize themselves and fixtures depending on it
1043
+ # (which will likely include this fixture) setting `self.cached_result = None`.
1044
+ # See #4871
1045
+ requested_fixtures_that_should_finalize_us = []
1046
+ for argname in self.argnames:
1047
+ fixturedef = request._get_active_fixturedef(argname)
1048
+ # Saves requested fixtures in a list so we later can add our finalizer
1049
+ # to them, ensuring that if a requested fixture gets torn down we get torn
1050
+ # down first. This is generally handled by SetupState, but still currently
1051
+ # needed when this fixture is not parametrized but depends on a parametrized
1052
+ # fixture.
1053
+ if not isinstance(fixturedef, PseudoFixtureDef):
1054
+ requested_fixtures_that_should_finalize_us.append(fixturedef)
1055
+
1056
+ # Check for (and return) cached value/exception.
1057
+ if self.cached_result is not None:
1058
+ request_cache_key = self.cache_key(request)
1059
+ cache_key = self.cached_result[1]
1060
+ try:
1061
+ # Attempt to make a normal == check: this might fail for objects
1062
+ # which do not implement the standard comparison (like numpy arrays -- #6497).
1063
+ cache_hit = bool(request_cache_key == cache_key)
1064
+ except (ValueError, RuntimeError):
1065
+ # If the comparison raises, use 'is' as fallback.
1066
+ cache_hit = request_cache_key is cache_key
1067
+
1068
+ if cache_hit:
1069
+ if self.cached_result[2] is not None:
1070
+ exc, exc_tb = self.cached_result[2]
1071
+ raise exc.with_traceback(exc_tb)
1072
+ else:
1073
+ result = self.cached_result[0]
1074
+ return result
1075
+ # We have a previous but differently parametrized fixture instance
1076
+ # so we need to tear it down before creating a new one.
1077
+ self.finish(request)
1078
+ assert self.cached_result is None
1079
+
1080
+ # Add finalizer to requested fixtures we saved previously.
1081
+ # We make sure to do this after checking for cached value to avoid
1082
+ # adding our finalizer multiple times. (#12135)
1083
+ finalizer = functools.partial(self.finish, request=request)
1084
+ for parent_fixture in requested_fixtures_that_should_finalize_us:
1085
+ parent_fixture.addfinalizer(finalizer)
1086
+
1087
+ ihook = request.node.ihook
1088
+ try:
1089
+ # Setup the fixture, run the code in it, and cache the value
1090
+ # in self.cached_result
1091
+ result = ihook.pytest_fixture_setup(fixturedef=self, request=request)
1092
+ finally:
1093
+ # schedule our finalizer, even if the setup failed
1094
+ request.node.addfinalizer(finalizer)
1095
+
1096
+ return result
1097
+
1098
+ def cache_key(self, request: SubRequest) -> object:
1099
+ return getattr(request, "param", None)
1100
+
1101
+ def __repr__(self) -> str:
1102
+ return f"<FixtureDef argname={self.argname!r} scope={self.scope!r} baseid={self.baseid!r}>"
1103
+
1104
+
1105
+ def resolve_fixture_function(
1106
+ fixturedef: FixtureDef[FixtureValue], request: FixtureRequest
1107
+ ) -> _FixtureFunc[FixtureValue]:
1108
+ """Get the actual callable that can be called to obtain the fixture
1109
+ value."""
1110
+ fixturefunc = fixturedef.func
1111
+ # The fixture function needs to be bound to the actual
1112
+ # request.instance so that code working with "fixturedef" behaves
1113
+ # as expected.
1114
+ instance = request.instance
1115
+ if instance is not None:
1116
+ # Handle the case where fixture is defined not in a test class, but some other class
1117
+ # (for example a plugin class with a fixture), see #2270.
1118
+ if hasattr(fixturefunc, "__self__") and not isinstance(
1119
+ instance,
1120
+ fixturefunc.__self__.__class__,
1121
+ ):
1122
+ return fixturefunc
1123
+ fixturefunc = getimfunc(fixturedef.func)
1124
+ if fixturefunc != fixturedef.func:
1125
+ fixturefunc = fixturefunc.__get__(instance)
1126
+ return fixturefunc
1127
+
1128
+
1129
+ def pytest_fixture_setup(
1130
+ fixturedef: FixtureDef[FixtureValue], request: SubRequest
1131
+ ) -> FixtureValue:
1132
+ """Execution of fixture setup."""
1133
+ kwargs = {}
1134
+ for argname in fixturedef.argnames:
1135
+ kwargs[argname] = request.getfixturevalue(argname)
1136
+
1137
+ fixturefunc = resolve_fixture_function(fixturedef, request)
1138
+ my_cache_key = fixturedef.cache_key(request)
1139
+ try:
1140
+ result = call_fixture_func(fixturefunc, request, kwargs)
1141
+ except TEST_OUTCOME as e:
1142
+ if isinstance(e, skip.Exception):
1143
+ # The test requested a fixture which caused a skip.
1144
+ # Don't show the fixture as the skip location, as then the user
1145
+ # wouldn't know which test skipped.
1146
+ e._use_item_location = True
1147
+ fixturedef.cached_result = (None, my_cache_key, (e, e.__traceback__))
1148
+ raise
1149
+ fixturedef.cached_result = (result, my_cache_key, None)
1150
+ return result
1151
+
1152
+
1153
+ def wrap_function_to_error_out_if_called_directly(
1154
+ function: FixtureFunction,
1155
+ fixture_marker: FixtureFunctionMarker,
1156
+ ) -> FixtureFunction:
1157
+ """Wrap the given fixture function so we can raise an error about it being called directly,
1158
+ instead of used as an argument in a test function."""
1159
+ name = fixture_marker.name or function.__name__
1160
+ message = (
1161
+ f'Fixture "{name}" called directly. Fixtures are not meant to be called directly,\n'
1162
+ "but are created automatically when test functions request them as parameters.\n"
1163
+ "See https://docs.pytest.org/en/stable/explanation/fixtures.html for more information about fixtures, and\n"
1164
+ "https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly about how to update your code."
1165
+ )
1166
+
1167
+ @functools.wraps(function)
1168
+ def result(*args, **kwargs):
1169
+ fail(message, pytrace=False)
1170
+
1171
+ # Keep reference to the original function in our own custom attribute so we don't unwrap
1172
+ # further than this point and lose useful wrappings like @mock.patch (#3774).
1173
+ result.__pytest_wrapped__ = _PytestWrapper(function) # type: ignore[attr-defined]
1174
+
1175
+ return cast(FixtureFunction, result)
1176
+
1177
+
1178
+ @final
1179
+ @dataclasses.dataclass(frozen=True)
1180
+ class FixtureFunctionMarker:
1181
+ scope: _ScopeName | Callable[[str, Config], _ScopeName]
1182
+ params: tuple[object, ...] | None
1183
+ autouse: bool = False
1184
+ ids: tuple[object | None, ...] | Callable[[Any], object | None] | None = None
1185
+ name: str | None = None
1186
+
1187
+ _ispytest: dataclasses.InitVar[bool] = False
1188
+
1189
+ def __post_init__(self, _ispytest: bool) -> None:
1190
+ check_ispytest(_ispytest)
1191
+
1192
+ def __call__(self, function: FixtureFunction) -> FixtureFunction:
1193
+ if inspect.isclass(function):
1194
+ raise ValueError("class fixtures not supported (maybe in the future)")
1195
+
1196
+ if getattr(function, "_pytestfixturefunction", False):
1197
+ raise ValueError(
1198
+ f"@pytest.fixture is being applied more than once to the same function {function.__name__!r}"
1199
+ )
1200
+
1201
+ if hasattr(function, "pytestmark"):
1202
+ warnings.warn(MARKED_FIXTURE, stacklevel=2)
1203
+
1204
+ function = wrap_function_to_error_out_if_called_directly(function, self)
1205
+
1206
+ name = self.name or function.__name__
1207
+ if name == "request":
1208
+ location = getlocation(function)
1209
+ fail(
1210
+ f"'request' is a reserved word for fixtures, use another name:\n {location}",
1211
+ pytrace=False,
1212
+ )
1213
+
1214
+ # Type ignored because https://github.com/python/mypy/issues/2087.
1215
+ function._pytestfixturefunction = self # type: ignore[attr-defined]
1216
+ return function
1217
+
1218
+
1219
+ @overload
1220
+ def fixture(
1221
+ fixture_function: FixtureFunction,
1222
+ *,
1223
+ scope: _ScopeName | Callable[[str, Config], _ScopeName] = ...,
1224
+ params: Iterable[object] | None = ...,
1225
+ autouse: bool = ...,
1226
+ ids: Sequence[object | None] | Callable[[Any], object | None] | None = ...,
1227
+ name: str | None = ...,
1228
+ ) -> FixtureFunction: ...
1229
+
1230
+
1231
+ @overload
1232
+ def fixture(
1233
+ fixture_function: None = ...,
1234
+ *,
1235
+ scope: _ScopeName | Callable[[str, Config], _ScopeName] = ...,
1236
+ params: Iterable[object] | None = ...,
1237
+ autouse: bool = ...,
1238
+ ids: Sequence[object | None] | Callable[[Any], object | None] | None = ...,
1239
+ name: str | None = None,
1240
+ ) -> FixtureFunctionMarker: ...
1241
+
1242
+
1243
+ def fixture(
1244
+ fixture_function: FixtureFunction | None = None,
1245
+ *,
1246
+ scope: _ScopeName | Callable[[str, Config], _ScopeName] = "function",
1247
+ params: Iterable[object] | None = None,
1248
+ autouse: bool = False,
1249
+ ids: Sequence[object | None] | Callable[[Any], object | None] | None = None,
1250
+ name: str | None = None,
1251
+ ) -> FixtureFunctionMarker | FixtureFunction:
1252
+ """Decorator to mark a fixture factory function.
1253
+
1254
+ This decorator can be used, with or without parameters, to define a
1255
+ fixture function.
1256
+
1257
+ The name of the fixture function can later be referenced to cause its
1258
+ invocation ahead of running tests: test modules or classes can use the
1259
+ ``pytest.mark.usefixtures(fixturename)`` marker.
1260
+
1261
+ Test functions can directly use fixture names as input arguments in which
1262
+ case the fixture instance returned from the fixture function will be
1263
+ injected.
1264
+
1265
+ Fixtures can provide their values to test functions using ``return`` or
1266
+ ``yield`` statements. When using ``yield`` the code block after the
1267
+ ``yield`` statement is executed as teardown code regardless of the test
1268
+ outcome, and must yield exactly once.
1269
+
1270
+ :param scope:
1271
+ The scope for which this fixture is shared; one of ``"function"``
1272
+ (default), ``"class"``, ``"module"``, ``"package"`` or ``"session"``.
1273
+
1274
+ This parameter may also be a callable which receives ``(fixture_name, config)``
1275
+ as parameters, and must return a ``str`` with one of the values mentioned above.
1276
+
1277
+ See :ref:`dynamic scope` in the docs for more information.
1278
+
1279
+ :param params:
1280
+ An optional list of parameters which will cause multiple invocations
1281
+ of the fixture function and all of the tests using it. The current
1282
+ parameter is available in ``request.param``.
1283
+
1284
+ :param autouse:
1285
+ If True, the fixture func is activated for all tests that can see it.
1286
+ If False (the default), an explicit reference is needed to activate
1287
+ the fixture.
1288
+
1289
+ :param ids:
1290
+ Sequence of ids each corresponding to the params so that they are
1291
+ part of the test id. If no ids are provided they will be generated
1292
+ automatically from the params.
1293
+
1294
+ :param name:
1295
+ The name of the fixture. This defaults to the name of the decorated
1296
+ function. If a fixture is used in the same module in which it is
1297
+ defined, the function name of the fixture will be shadowed by the
1298
+ function arg that requests the fixture; one way to resolve this is to
1299
+ name the decorated function ``fixture_<fixturename>`` and then use
1300
+ ``@pytest.fixture(name='<fixturename>')``.
1301
+ """
1302
+ fixture_marker = FixtureFunctionMarker(
1303
+ scope=scope,
1304
+ params=tuple(params) if params is not None else None,
1305
+ autouse=autouse,
1306
+ ids=None if ids is None else ids if callable(ids) else tuple(ids),
1307
+ name=name,
1308
+ _ispytest=True,
1309
+ )
1310
+
1311
+ # Direct decoration.
1312
+ if fixture_function:
1313
+ return fixture_marker(fixture_function)
1314
+
1315
+ return fixture_marker
1316
+
1317
+
1318
+ def yield_fixture(
1319
+ fixture_function=None,
1320
+ *args,
1321
+ scope="function",
1322
+ params=None,
1323
+ autouse=False,
1324
+ ids=None,
1325
+ name=None,
1326
+ ):
1327
+ """(Return a) decorator to mark a yield-fixture factory function.
1328
+
1329
+ .. deprecated:: 3.0
1330
+ Use :py:func:`pytest.fixture` directly instead.
1331
+ """
1332
+ warnings.warn(YIELD_FIXTURE, stacklevel=2)
1333
+ return fixture(
1334
+ fixture_function,
1335
+ *args,
1336
+ scope=scope,
1337
+ params=params,
1338
+ autouse=autouse,
1339
+ ids=ids,
1340
+ name=name,
1341
+ )
1342
+
1343
+
1344
+ @fixture(scope="session")
1345
+ def pytestconfig(request: FixtureRequest) -> Config:
1346
+ """Session-scoped fixture that returns the session's :class:`pytest.Config`
1347
+ object.
1348
+
1349
+ Example::
1350
+
1351
+ def test_foo(pytestconfig):
1352
+ if pytestconfig.get_verbosity() > 0:
1353
+ ...
1354
+
1355
+ """
1356
+ return request.config
1357
+
1358
+
1359
+ def pytest_addoption(parser: Parser) -> None:
1360
+ parser.addini(
1361
+ "usefixtures",
1362
+ type="args",
1363
+ default=[],
1364
+ help="List of default fixtures to be used with this project",
1365
+ )
1366
+ group = parser.getgroup("general")
1367
+ group.addoption(
1368
+ "--fixtures",
1369
+ "--funcargs",
1370
+ action="store_true",
1371
+ dest="showfixtures",
1372
+ default=False,
1373
+ help="Show available fixtures, sorted by plugin appearance "
1374
+ "(fixtures with leading '_' are only shown with '-v')",
1375
+ )
1376
+ group.addoption(
1377
+ "--fixtures-per-test",
1378
+ action="store_true",
1379
+ dest="show_fixtures_per_test",
1380
+ default=False,
1381
+ help="Show fixtures per test",
1382
+ )
1383
+
1384
+
1385
+ def pytest_cmdline_main(config: Config) -> int | ExitCode | None:
1386
+ if config.option.showfixtures:
1387
+ showfixtures(config)
1388
+ return 0
1389
+ if config.option.show_fixtures_per_test:
1390
+ show_fixtures_per_test(config)
1391
+ return 0
1392
+ return None
1393
+
1394
+
1395
+ def _get_direct_parametrize_args(node: nodes.Node) -> set[str]:
1396
+ """Return all direct parametrization arguments of a node, so we don't
1397
+ mistake them for fixtures.
1398
+
1399
+ Check https://github.com/pytest-dev/pytest/issues/5036.
1400
+
1401
+ These things are done later as well when dealing with parametrization
1402
+ so this could be improved.
1403
+ """
1404
+ parametrize_argnames: set[str] = set()
1405
+ for marker in node.iter_markers(name="parametrize"):
1406
+ if not marker.kwargs.get("indirect", False):
1407
+ p_argnames, _ = ParameterSet._parse_parametrize_args(
1408
+ *marker.args, **marker.kwargs
1409
+ )
1410
+ parametrize_argnames.update(p_argnames)
1411
+ return parametrize_argnames
1412
+
1413
+
1414
+ def deduplicate_names(*seqs: Iterable[str]) -> tuple[str, ...]:
1415
+ """De-duplicate the sequence of names while keeping the original order."""
1416
+ # Ideally we would use a set, but it does not preserve insertion order.
1417
+ return tuple(dict.fromkeys(name for seq in seqs for name in seq))
1418
+
1419
+
1420
+ class FixtureManager:
1421
+ """pytest fixture definitions and information is stored and managed
1422
+ from this class.
1423
+
1424
+ During collection fm.parsefactories() is called multiple times to parse
1425
+ fixture function definitions into FixtureDef objects and internal
1426
+ data structures.
1427
+
1428
+ During collection of test functions, metafunc-mechanics instantiate
1429
+ a FuncFixtureInfo object which is cached per node/func-name.
1430
+ This FuncFixtureInfo object is later retrieved by Function nodes
1431
+ which themselves offer a fixturenames attribute.
1432
+
1433
+ The FuncFixtureInfo object holds information about fixtures and FixtureDefs
1434
+ relevant for a particular function. An initial list of fixtures is
1435
+ assembled like this:
1436
+
1437
+ - ini-defined usefixtures
1438
+ - autouse-marked fixtures along the collection chain up from the function
1439
+ - usefixtures markers at module/class/function level
1440
+ - test function funcargs
1441
+
1442
+ Subsequently the funcfixtureinfo.fixturenames attribute is computed
1443
+ as the closure of the fixtures needed to setup the initial fixtures,
1444
+ i.e. fixtures needed by fixture functions themselves are appended
1445
+ to the fixturenames list.
1446
+
1447
+ Upon the test-setup phases all fixturenames are instantiated, retrieved
1448
+ by a lookup of their FuncFixtureInfo.
1449
+ """
1450
+
1451
+ def __init__(self, session: Session) -> None:
1452
+ self.session = session
1453
+ self.config: Config = session.config
1454
+ # Maps a fixture name (argname) to all of the FixtureDefs in the test
1455
+ # suite/plugins defined with this name. Populated by parsefactories().
1456
+ # TODO: The order of the FixtureDefs list of each arg is significant,
1457
+ # explain.
1458
+ self._arg2fixturedefs: Final[dict[str, list[FixtureDef[Any]]]] = {}
1459
+ self._holderobjseen: Final[set[object]] = set()
1460
+ # A mapping from a nodeid to a list of autouse fixtures it defines.
1461
+ self._nodeid_autousenames: Final[dict[str, list[str]]] = {
1462
+ "": self.config.getini("usefixtures"),
1463
+ }
1464
+ session.config.pluginmanager.register(self, "funcmanage")
1465
+
1466
+ def getfixtureinfo(
1467
+ self,
1468
+ node: nodes.Item,
1469
+ func: Callable[..., object] | None,
1470
+ cls: type | None,
1471
+ ) -> FuncFixtureInfo:
1472
+ """Calculate the :class:`FuncFixtureInfo` for an item.
1473
+
1474
+ If ``func`` is None, or if the item sets an attribute
1475
+ ``nofuncargs = True``, then ``func`` is not examined at all.
1476
+
1477
+ :param node:
1478
+ The item requesting the fixtures.
1479
+ :param func:
1480
+ The item's function.
1481
+ :param cls:
1482
+ If the function is a method, the method's class.
1483
+ """
1484
+ if func is not None and not getattr(node, "nofuncargs", False):
1485
+ argnames = getfuncargnames(func, name=node.name, cls=cls)
1486
+ else:
1487
+ argnames = ()
1488
+ usefixturesnames = self._getusefixturesnames(node)
1489
+ autousenames = self._getautousenames(node)
1490
+ initialnames = deduplicate_names(autousenames, usefixturesnames, argnames)
1491
+
1492
+ direct_parametrize_args = _get_direct_parametrize_args(node)
1493
+
1494
+ names_closure, arg2fixturedefs = self.getfixtureclosure(
1495
+ parentnode=node,
1496
+ initialnames=initialnames,
1497
+ ignore_args=direct_parametrize_args,
1498
+ )
1499
+
1500
+ return FuncFixtureInfo(argnames, initialnames, names_closure, arg2fixturedefs)
1501
+
1502
+ def pytest_plugin_registered(self, plugin: _PluggyPlugin, plugin_name: str) -> None:
1503
+ # Fixtures defined in conftest plugins are only visible to within the
1504
+ # conftest's directory. This is unlike fixtures in non-conftest plugins
1505
+ # which have global visibility. So for conftests, construct the base
1506
+ # nodeid from the plugin name (which is the conftest path).
1507
+ if plugin_name and plugin_name.endswith("conftest.py"):
1508
+ # Note: we explicitly do *not* use `plugin.__file__` here -- The
1509
+ # difference is that plugin_name has the correct capitalization on
1510
+ # case-insensitive systems (Windows) and other normalization issues
1511
+ # (issue #11816).
1512
+ conftestpath = absolutepath(plugin_name)
1513
+ try:
1514
+ nodeid = str(conftestpath.parent.relative_to(self.config.rootpath))
1515
+ except ValueError:
1516
+ nodeid = ""
1517
+ if nodeid == ".":
1518
+ nodeid = ""
1519
+ if os.sep != nodes.SEP:
1520
+ nodeid = nodeid.replace(os.sep, nodes.SEP)
1521
+ else:
1522
+ nodeid = None
1523
+
1524
+ self.parsefactories(plugin, nodeid)
1525
+
1526
+ def _getautousenames(self, node: nodes.Node) -> Iterator[str]:
1527
+ """Return the names of autouse fixtures applicable to node."""
1528
+ for parentnode in node.listchain():
1529
+ basenames = self._nodeid_autousenames.get(parentnode.nodeid)
1530
+ if basenames:
1531
+ yield from basenames
1532
+
1533
+ def _getusefixturesnames(self, node: nodes.Item) -> Iterator[str]:
1534
+ """Return the names of usefixtures fixtures applicable to node."""
1535
+ for mark in node.iter_markers(name="usefixtures"):
1536
+ yield from mark.args
1537
+
1538
+ def getfixtureclosure(
1539
+ self,
1540
+ parentnode: nodes.Node,
1541
+ initialnames: tuple[str, ...],
1542
+ ignore_args: AbstractSet[str],
1543
+ ) -> tuple[list[str], dict[str, Sequence[FixtureDef[Any]]]]:
1544
+ # Collect the closure of all fixtures, starting with the given
1545
+ # fixturenames as the initial set. As we have to visit all
1546
+ # factory definitions anyway, we also return an arg2fixturedefs
1547
+ # mapping so that the caller can reuse it and does not have
1548
+ # to re-discover fixturedefs again for each fixturename
1549
+ # (discovering matching fixtures for a given name/node is expensive).
1550
+
1551
+ fixturenames_closure = list(initialnames)
1552
+
1553
+ arg2fixturedefs: dict[str, Sequence[FixtureDef[Any]]] = {}
1554
+ lastlen = -1
1555
+ while lastlen != len(fixturenames_closure):
1556
+ lastlen = len(fixturenames_closure)
1557
+ for argname in fixturenames_closure:
1558
+ if argname in ignore_args:
1559
+ continue
1560
+ if argname in arg2fixturedefs:
1561
+ continue
1562
+ fixturedefs = self.getfixturedefs(argname, parentnode)
1563
+ if fixturedefs:
1564
+ arg2fixturedefs[argname] = fixturedefs
1565
+ for arg in fixturedefs[-1].argnames:
1566
+ if arg not in fixturenames_closure:
1567
+ fixturenames_closure.append(arg)
1568
+
1569
+ def sort_by_scope(arg_name: str) -> Scope:
1570
+ try:
1571
+ fixturedefs = arg2fixturedefs[arg_name]
1572
+ except KeyError:
1573
+ return Scope.Function
1574
+ else:
1575
+ return fixturedefs[-1]._scope
1576
+
1577
+ fixturenames_closure.sort(key=sort_by_scope, reverse=True)
1578
+ return fixturenames_closure, arg2fixturedefs
1579
+
1580
+ def pytest_generate_tests(self, metafunc: Metafunc) -> None:
1581
+ """Generate new tests based on parametrized fixtures used by the given metafunc"""
1582
+
1583
+ def get_parametrize_mark_argnames(mark: Mark) -> Sequence[str]:
1584
+ args, _ = ParameterSet._parse_parametrize_args(*mark.args, **mark.kwargs)
1585
+ return args
1586
+
1587
+ for argname in metafunc.fixturenames:
1588
+ # Get the FixtureDefs for the argname.
1589
+ fixture_defs = metafunc._arg2fixturedefs.get(argname)
1590
+ if not fixture_defs:
1591
+ # Will raise FixtureLookupError at setup time if not parametrized somewhere
1592
+ # else (e.g @pytest.mark.parametrize)
1593
+ continue
1594
+
1595
+ # If the test itself parametrizes using this argname, give it
1596
+ # precedence.
1597
+ if any(
1598
+ argname in get_parametrize_mark_argnames(mark)
1599
+ for mark in metafunc.definition.iter_markers("parametrize")
1600
+ ):
1601
+ continue
1602
+
1603
+ # In the common case we only look at the fixture def with the
1604
+ # closest scope (last in the list). But if the fixture overrides
1605
+ # another fixture, while requesting the super fixture, keep going
1606
+ # in case the super fixture is parametrized (#1953).
1607
+ for fixturedef in reversed(fixture_defs):
1608
+ # Fixture is parametrized, apply it and stop.
1609
+ if fixturedef.params is not None:
1610
+ metafunc.parametrize(
1611
+ argname,
1612
+ fixturedef.params,
1613
+ indirect=True,
1614
+ scope=fixturedef.scope,
1615
+ ids=fixturedef.ids,
1616
+ )
1617
+ break
1618
+
1619
+ # Not requesting the overridden super fixture, stop.
1620
+ if argname not in fixturedef.argnames:
1621
+ break
1622
+
1623
+ # Try next super fixture, if any.
1624
+
1625
+ def pytest_collection_modifyitems(self, items: list[nodes.Item]) -> None:
1626
+ # Separate parametrized setups.
1627
+ items[:] = reorder_items(items)
1628
+
1629
+ def _register_fixture(
1630
+ self,
1631
+ *,
1632
+ name: str,
1633
+ func: _FixtureFunc[object],
1634
+ nodeid: str | None,
1635
+ scope: Scope | _ScopeName | Callable[[str, Config], _ScopeName] = "function",
1636
+ params: Sequence[object] | None = None,
1637
+ ids: tuple[object | None, ...] | Callable[[Any], object | None] | None = None,
1638
+ autouse: bool = False,
1639
+ ) -> None:
1640
+ """Register a fixture
1641
+
1642
+ :param name:
1643
+ The fixture's name.
1644
+ :param func:
1645
+ The fixture's implementation function.
1646
+ :param nodeid:
1647
+ The visibility of the fixture. The fixture will be available to the
1648
+ node with this nodeid and its children in the collection tree.
1649
+ None means that the fixture is visible to the entire collection tree,
1650
+ e.g. a fixture defined for general use in a plugin.
1651
+ :param scope:
1652
+ The fixture's scope.
1653
+ :param params:
1654
+ The fixture's parametrization params.
1655
+ :param ids:
1656
+ The fixture's IDs.
1657
+ :param autouse:
1658
+ Whether this is an autouse fixture.
1659
+ """
1660
+ fixture_def = FixtureDef(
1661
+ config=self.config,
1662
+ baseid=nodeid,
1663
+ argname=name,
1664
+ func=func,
1665
+ scope=scope,
1666
+ params=params,
1667
+ ids=ids,
1668
+ _ispytest=True,
1669
+ )
1670
+
1671
+ faclist = self._arg2fixturedefs.setdefault(name, [])
1672
+ if fixture_def.has_location:
1673
+ faclist.append(fixture_def)
1674
+ else:
1675
+ # fixturedefs with no location are at the front
1676
+ # so this inserts the current fixturedef after the
1677
+ # existing fixturedefs from external plugins but
1678
+ # before the fixturedefs provided in conftests.
1679
+ i = len([f for f in faclist if not f.has_location])
1680
+ faclist.insert(i, fixture_def)
1681
+ if autouse:
1682
+ self._nodeid_autousenames.setdefault(nodeid or "", []).append(name)
1683
+
1684
+ @overload
1685
+ def parsefactories(
1686
+ self,
1687
+ node_or_obj: nodes.Node,
1688
+ ) -> None:
1689
+ raise NotImplementedError()
1690
+
1691
+ @overload
1692
+ def parsefactories(
1693
+ self,
1694
+ node_or_obj: object,
1695
+ nodeid: str | None,
1696
+ ) -> None:
1697
+ raise NotImplementedError()
1698
+
1699
+ def parsefactories(
1700
+ self,
1701
+ node_or_obj: nodes.Node | object,
1702
+ nodeid: str | NotSetType | None = NOTSET,
1703
+ ) -> None:
1704
+ """Collect fixtures from a collection node or object.
1705
+
1706
+ Found fixtures are parsed into `FixtureDef`s and saved.
1707
+
1708
+ If `node_or_object` is a collection node (with an underlying Python
1709
+ object), the node's object is traversed and the node's nodeid is used to
1710
+ determine the fixtures' visibility. `nodeid` must not be specified in
1711
+ this case.
1712
+
1713
+ If `node_or_object` is an object (e.g. a plugin), the object is
1714
+ traversed and the given `nodeid` is used to determine the fixtures'
1715
+ visibility. `nodeid` must be specified in this case; None and "" mean
1716
+ total visibility.
1717
+ """
1718
+ if nodeid is not NOTSET:
1719
+ holderobj = node_or_obj
1720
+ else:
1721
+ assert isinstance(node_or_obj, nodes.Node)
1722
+ holderobj = cast(object, node_or_obj.obj) # type: ignore[attr-defined]
1723
+ assert isinstance(node_or_obj.nodeid, str)
1724
+ nodeid = node_or_obj.nodeid
1725
+ if holderobj in self._holderobjseen:
1726
+ return
1727
+
1728
+ # Avoid accessing `@property` (and other descriptors) when iterating fixtures.
1729
+ if not safe_isclass(holderobj) and not isinstance(holderobj, types.ModuleType):
1730
+ holderobj_tp: object = type(holderobj)
1731
+ else:
1732
+ holderobj_tp = holderobj
1733
+
1734
+ self._holderobjseen.add(holderobj)
1735
+ for name in dir(holderobj):
1736
+ # The attribute can be an arbitrary descriptor, so the attribute
1737
+ # access below can raise. safe_getattr() ignores such exceptions.
1738
+ obj_ub = safe_getattr(holderobj_tp, name, None)
1739
+ marker = getfixturemarker(obj_ub)
1740
+ if not isinstance(marker, FixtureFunctionMarker):
1741
+ # Magic globals with __getattr__ might have got us a wrong
1742
+ # fixture attribute.
1743
+ continue
1744
+
1745
+ # OK we know it is a fixture -- now safe to look up on the _instance_.
1746
+ obj = getattr(holderobj, name)
1747
+
1748
+ if marker.name:
1749
+ name = marker.name
1750
+
1751
+ # During fixture definition we wrap the original fixture function
1752
+ # to issue a warning if called directly, so here we unwrap it in
1753
+ # order to not emit the warning when pytest itself calls the
1754
+ # fixture function.
1755
+ func = get_real_method(obj, holderobj)
1756
+
1757
+ self._register_fixture(
1758
+ name=name,
1759
+ nodeid=nodeid,
1760
+ func=func,
1761
+ scope=marker.scope,
1762
+ params=marker.params,
1763
+ ids=marker.ids,
1764
+ autouse=marker.autouse,
1765
+ )
1766
+
1767
+ def getfixturedefs(
1768
+ self, argname: str, node: nodes.Node
1769
+ ) -> Sequence[FixtureDef[Any]] | None:
1770
+ """Get FixtureDefs for a fixture name which are applicable
1771
+ to a given node.
1772
+
1773
+ Returns None if there are no fixtures at all defined with the given
1774
+ name. (This is different from the case in which there are fixtures
1775
+ with the given name, but none applicable to the node. In this case,
1776
+ an empty result is returned).
1777
+
1778
+ :param argname: Name of the fixture to search for.
1779
+ :param node: The requesting Node.
1780
+ """
1781
+ try:
1782
+ fixturedefs = self._arg2fixturedefs[argname]
1783
+ except KeyError:
1784
+ return None
1785
+ return tuple(self._matchfactories(fixturedefs, node))
1786
+
1787
+ def _matchfactories(
1788
+ self, fixturedefs: Iterable[FixtureDef[Any]], node: nodes.Node
1789
+ ) -> Iterator[FixtureDef[Any]]:
1790
+ parentnodeids = {n.nodeid for n in node.iter_parents()}
1791
+ for fixturedef in fixturedefs:
1792
+ if fixturedef.baseid in parentnodeids:
1793
+ yield fixturedef
1794
+
1795
+
1796
+ def show_fixtures_per_test(config: Config) -> int | ExitCode:
1797
+ from _pytest.main import wrap_session
1798
+
1799
+ return wrap_session(config, _show_fixtures_per_test)
1800
+
1801
+
1802
+ _PYTEST_DIR = Path(_pytest.__file__).parent
1803
+
1804
+
1805
+ def _pretty_fixture_path(invocation_dir: Path, func) -> str:
1806
+ loc = Path(getlocation(func, invocation_dir))
1807
+ prefix = Path("...", "_pytest")
1808
+ try:
1809
+ return str(prefix / loc.relative_to(_PYTEST_DIR))
1810
+ except ValueError:
1811
+ return bestrelpath(invocation_dir, loc)
1812
+
1813
+
1814
+ def _show_fixtures_per_test(config: Config, session: Session) -> None:
1815
+ import _pytest.config
1816
+
1817
+ session.perform_collect()
1818
+ invocation_dir = config.invocation_params.dir
1819
+ tw = _pytest.config.create_terminal_writer(config)
1820
+ verbose = config.get_verbosity()
1821
+
1822
+ def get_best_relpath(func) -> str:
1823
+ loc = getlocation(func, invocation_dir)
1824
+ return bestrelpath(invocation_dir, Path(loc))
1825
+
1826
+ def write_fixture(fixture_def: FixtureDef[object]) -> None:
1827
+ argname = fixture_def.argname
1828
+ if verbose <= 0 and argname.startswith("_"):
1829
+ return
1830
+ prettypath = _pretty_fixture_path(invocation_dir, fixture_def.func)
1831
+ tw.write(f"{argname}", green=True)
1832
+ tw.write(f" -- {prettypath}", yellow=True)
1833
+ tw.write("\n")
1834
+ fixture_doc = inspect.getdoc(fixture_def.func)
1835
+ if fixture_doc:
1836
+ write_docstring(
1837
+ tw,
1838
+ fixture_doc.split("\n\n", maxsplit=1)[0]
1839
+ if verbose <= 0
1840
+ else fixture_doc,
1841
+ )
1842
+ else:
1843
+ tw.line(" no docstring available", red=True)
1844
+
1845
+ def write_item(item: nodes.Item) -> None:
1846
+ # Not all items have _fixtureinfo attribute.
1847
+ info: FuncFixtureInfo | None = getattr(item, "_fixtureinfo", None)
1848
+ if info is None or not info.name2fixturedefs:
1849
+ # This test item does not use any fixtures.
1850
+ return
1851
+ tw.line()
1852
+ tw.sep("-", f"fixtures used by {item.name}")
1853
+ # TODO: Fix this type ignore.
1854
+ tw.sep("-", f"({get_best_relpath(item.function)})") # type: ignore[attr-defined]
1855
+ # dict key not used in loop but needed for sorting.
1856
+ for _, fixturedefs in sorted(info.name2fixturedefs.items()):
1857
+ assert fixturedefs is not None
1858
+ if not fixturedefs:
1859
+ continue
1860
+ # Last item is expected to be the one used by the test item.
1861
+ write_fixture(fixturedefs[-1])
1862
+
1863
+ for session_item in session.items:
1864
+ write_item(session_item)
1865
+
1866
+
1867
+ def showfixtures(config: Config) -> int | ExitCode:
1868
+ from _pytest.main import wrap_session
1869
+
1870
+ return wrap_session(config, _showfixtures_main)
1871
+
1872
+
1873
+ def _showfixtures_main(config: Config, session: Session) -> None:
1874
+ import _pytest.config
1875
+
1876
+ session.perform_collect()
1877
+ invocation_dir = config.invocation_params.dir
1878
+ tw = _pytest.config.create_terminal_writer(config)
1879
+ verbose = config.get_verbosity()
1880
+
1881
+ fm = session._fixturemanager
1882
+
1883
+ available = []
1884
+ seen: set[tuple[str, str]] = set()
1885
+
1886
+ for argname, fixturedefs in fm._arg2fixturedefs.items():
1887
+ assert fixturedefs is not None
1888
+ if not fixturedefs:
1889
+ continue
1890
+ for fixturedef in fixturedefs:
1891
+ loc = getlocation(fixturedef.func, invocation_dir)
1892
+ if (fixturedef.argname, loc) in seen:
1893
+ continue
1894
+ seen.add((fixturedef.argname, loc))
1895
+ available.append(
1896
+ (
1897
+ len(fixturedef.baseid),
1898
+ fixturedef.func.__module__,
1899
+ _pretty_fixture_path(invocation_dir, fixturedef.func),
1900
+ fixturedef.argname,
1901
+ fixturedef,
1902
+ )
1903
+ )
1904
+
1905
+ available.sort()
1906
+ currentmodule = None
1907
+ for baseid, module, prettypath, argname, fixturedef in available:
1908
+ if currentmodule != module:
1909
+ if not module.startswith("_pytest."):
1910
+ tw.line()
1911
+ tw.sep("-", f"fixtures defined from {module}")
1912
+ currentmodule = module
1913
+ if verbose <= 0 and argname.startswith("_"):
1914
+ continue
1915
+ tw.write(f"{argname}", green=True)
1916
+ if fixturedef.scope != "function":
1917
+ tw.write(f" [{fixturedef.scope} scope]", cyan=True)
1918
+ tw.write(f" -- {prettypath}", yellow=True)
1919
+ tw.write("\n")
1920
+ doc = inspect.getdoc(fixturedef.func)
1921
+ if doc:
1922
+ write_docstring(
1923
+ tw, doc.split("\n\n", maxsplit=1)[0] if verbose <= 0 else doc
1924
+ )
1925
+ else:
1926
+ tw.line(" no docstring available", red=True)
1927
+ tw.line()
1928
+
1929
+
1930
+ def write_docstring(tw: TerminalWriter, doc: str, indent: str = " ") -> None:
1931
+ for line in doc.split("\n"):
1932
+ tw.line(indent + line)
vllm/lib/python3.10/site-packages/_pytest/freeze_support.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Provides a function to report all internal modules for using freezing
2
+ tools."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import types
7
+ from typing import Iterator
8
+
9
+
10
+ def freeze_includes() -> list[str]:
11
+ """Return a list of module names used by pytest that should be
12
+ included by cx_freeze."""
13
+ import _pytest
14
+
15
+ result = list(_iter_all_modules(_pytest))
16
+ return result
17
+
18
+
19
+ def _iter_all_modules(
20
+ package: str | types.ModuleType,
21
+ prefix: str = "",
22
+ ) -> Iterator[str]:
23
+ """Iterate over the names of all modules that can be found in the given
24
+ package, recursively.
25
+
26
+ >>> import _pytest
27
+ >>> list(_iter_all_modules(_pytest))
28
+ ['_pytest._argcomplete', '_pytest._code.code', ...]
29
+ """
30
+ import os
31
+ import pkgutil
32
+
33
+ if isinstance(package, str):
34
+ path = package
35
+ else:
36
+ # Type ignored because typeshed doesn't define ModuleType.__path__
37
+ # (only defined on packages).
38
+ package_path = package.__path__
39
+ path, prefix = package_path[0], package.__name__ + "."
40
+ for _, name, is_package in pkgutil.iter_modules([path]):
41
+ if is_package:
42
+ for m in _iter_all_modules(os.path.join(path, name), prefix=name + "."):
43
+ yield prefix + m
44
+ else:
45
+ yield prefix + name
vllm/lib/python3.10/site-packages/_pytest/helpconfig.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """Version info, help messages, tracing configuration."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from argparse import Action
7
+ import os
8
+ import sys
9
+ from typing import Generator
10
+
11
+ from _pytest.config import Config
12
+ from _pytest.config import ExitCode
13
+ from _pytest.config import PrintHelp
14
+ from _pytest.config.argparsing import Parser
15
+ from _pytest.terminal import TerminalReporter
16
+ import pytest
17
+
18
+
19
+ class HelpAction(Action):
20
+ """An argparse Action that will raise an exception in order to skip the
21
+ rest of the argument parsing when --help is passed.
22
+
23
+ This prevents argparse from quitting due to missing required arguments
24
+ when any are defined, for example by ``pytest_addoption``.
25
+ This is similar to the way that the builtin argparse --help option is
26
+ implemented by raising SystemExit.
27
+ """
28
+
29
+ def __init__(self, option_strings, dest=None, default=False, help=None):
30
+ super().__init__(
31
+ option_strings=option_strings,
32
+ dest=dest,
33
+ const=True,
34
+ default=default,
35
+ nargs=0,
36
+ help=help,
37
+ )
38
+
39
+ def __call__(self, parser, namespace, values, option_string=None):
40
+ setattr(namespace, self.dest, self.const)
41
+
42
+ # We should only skip the rest of the parsing after preparse is done.
43
+ if getattr(parser._parser, "after_preparse", False):
44
+ raise PrintHelp
45
+
46
+
47
+ def pytest_addoption(parser: Parser) -> None:
48
+ group = parser.getgroup("debugconfig")
49
+ group.addoption(
50
+ "--version",
51
+ "-V",
52
+ action="count",
53
+ default=0,
54
+ dest="version",
55
+ help="Display pytest version and information about plugins. "
56
+ "When given twice, also display information about plugins.",
57
+ )
58
+ group._addoption(
59
+ "-h",
60
+ "--help",
61
+ action=HelpAction,
62
+ dest="help",
63
+ help="Show help message and configuration info",
64
+ )
65
+ group._addoption(
66
+ "-p",
67
+ action="append",
68
+ dest="plugins",
69
+ default=[],
70
+ metavar="name",
71
+ help="Early-load given plugin module name or entry point (multi-allowed). "
72
+ "To avoid loading of plugins, use the `no:` prefix, e.g. "
73
+ "`no:doctest`.",
74
+ )
75
+ group.addoption(
76
+ "--traceconfig",
77
+ "--trace-config",
78
+ action="store_true",
79
+ default=False,
80
+ help="Trace considerations of conftest.py files",
81
+ )
82
+ group.addoption(
83
+ "--debug",
84
+ action="store",
85
+ nargs="?",
86
+ const="pytestdebug.log",
87
+ dest="debug",
88
+ metavar="DEBUG_FILE_NAME",
89
+ help="Store internal tracing debug information in this log file. "
90
+ "This file is opened with 'w' and truncated as a result, care advised. "
91
+ "Default: pytestdebug.log.",
92
+ )
93
+ group._addoption(
94
+ "-o",
95
+ "--override-ini",
96
+ dest="override_ini",
97
+ action="append",
98
+ help='Override ini option with "option=value" style, '
99
+ "e.g. `-o xfail_strict=True -o cache_dir=cache`.",
100
+ )
101
+
102
+
103
+ @pytest.hookimpl(wrapper=True)
104
+ def pytest_cmdline_parse() -> Generator[None, Config, Config]:
105
+ config = yield
106
+
107
+ if config.option.debug:
108
+ # --debug | --debug <file.log> was provided.
109
+ path = config.option.debug
110
+ debugfile = open(path, "w", encoding="utf-8")
111
+ debugfile.write(
112
+ "versions pytest-{}, "
113
+ "python-{}\ninvocation_dir={}\ncwd={}\nargs={}\n\n".format(
114
+ pytest.__version__,
115
+ ".".join(map(str, sys.version_info)),
116
+ config.invocation_params.dir,
117
+ os.getcwd(),
118
+ config.invocation_params.args,
119
+ )
120
+ )
121
+ config.trace.root.setwriter(debugfile.write)
122
+ undo_tracing = config.pluginmanager.enable_tracing()
123
+ sys.stderr.write(f"writing pytest debug information to {path}\n")
124
+
125
+ def unset_tracing() -> None:
126
+ debugfile.close()
127
+ sys.stderr.write(f"wrote pytest debug information to {debugfile.name}\n")
128
+ config.trace.root.setwriter(None)
129
+ undo_tracing()
130
+
131
+ config.add_cleanup(unset_tracing)
132
+
133
+ return config
134
+
135
+
136
+ def showversion(config: Config) -> None:
137
+ if config.option.version > 1:
138
+ sys.stdout.write(
139
+ f"This is pytest version {pytest.__version__}, imported from {pytest.__file__}\n"
140
+ )
141
+ plugininfo = getpluginversioninfo(config)
142
+ if plugininfo:
143
+ for line in plugininfo:
144
+ sys.stdout.write(line + "\n")
145
+ else:
146
+ sys.stdout.write(f"pytest {pytest.__version__}\n")
147
+
148
+
149
+ def pytest_cmdline_main(config: Config) -> int | ExitCode | None:
150
+ if config.option.version > 0:
151
+ showversion(config)
152
+ return 0
153
+ elif config.option.help:
154
+ config._do_configure()
155
+ showhelp(config)
156
+ config._ensure_unconfigure()
157
+ return 0
158
+ return None
159
+
160
+
161
+ def showhelp(config: Config) -> None:
162
+ import textwrap
163
+
164
+ reporter: TerminalReporter | None = config.pluginmanager.get_plugin(
165
+ "terminalreporter"
166
+ )
167
+ assert reporter is not None
168
+ tw = reporter._tw
169
+ tw.write(config._parser.optparser.format_help())
170
+ tw.line()
171
+ tw.line(
172
+ "[pytest] ini-options in the first "
173
+ "pytest.ini|tox.ini|setup.cfg|pyproject.toml file found:"
174
+ )
175
+ tw.line()
176
+
177
+ columns = tw.fullwidth # costly call
178
+ indent_len = 24 # based on argparse's max_help_position=24
179
+ indent = " " * indent_len
180
+ for name in config._parser._ininames:
181
+ help, type, default = config._parser._inidict[name]
182
+ if type is None:
183
+ type = "string"
184
+ if help is None:
185
+ raise TypeError(f"help argument cannot be None for {name}")
186
+ spec = f"{name} ({type}):"
187
+ tw.write(f" {spec}")
188
+ spec_len = len(spec)
189
+ if spec_len > (indent_len - 3):
190
+ # Display help starting at a new line.
191
+ tw.line()
192
+ helplines = textwrap.wrap(
193
+ help,
194
+ columns,
195
+ initial_indent=indent,
196
+ subsequent_indent=indent,
197
+ break_on_hyphens=False,
198
+ )
199
+
200
+ for line in helplines:
201
+ tw.line(line)
202
+ else:
203
+ # Display help starting after the spec, following lines indented.
204
+ tw.write(" " * (indent_len - spec_len - 2))
205
+ wrapped = textwrap.wrap(help, columns - indent_len, break_on_hyphens=False)
206
+
207
+ if wrapped:
208
+ tw.line(wrapped[0])
209
+ for line in wrapped[1:]:
210
+ tw.line(indent + line)
211
+
212
+ tw.line()
213
+ tw.line("Environment variables:")
214
+ vars = [
215
+ (
216
+ "CI",
217
+ "When set (regardless of value), pytest knows it is running in a "
218
+ "CI process and does not truncate summary info",
219
+ ),
220
+ ("BUILD_NUMBER", "Equivalent to CI"),
221
+ ("PYTEST_ADDOPTS", "Extra command line options"),
222
+ ("PYTEST_PLUGINS", "Comma-separated plugins to load during startup"),
223
+ ("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "Set to disable plugin auto-loading"),
224
+ ("PYTEST_DEBUG", "Set to enable debug tracing of pytest's internals"),
225
+ ]
226
+ for name, help in vars:
227
+ tw.line(f" {name:<24} {help}")
228
+ tw.line()
229
+ tw.line()
230
+
231
+ tw.line("to see available markers type: pytest --markers")
232
+ tw.line("to see available fixtures type: pytest --fixtures")
233
+ tw.line(
234
+ "(shown according to specified file_or_dir or current dir "
235
+ "if not specified; fixtures with leading '_' are only shown "
236
+ "with the '-v' option"
237
+ )
238
+
239
+ for warningreport in reporter.stats.get("warnings", []):
240
+ tw.line("warning : " + warningreport.message, red=True)
241
+
242
+
243
+ conftest_options = [("pytest_plugins", "list of plugin names to load")]
244
+
245
+
246
+ def getpluginversioninfo(config: Config) -> list[str]:
247
+ lines = []
248
+ plugininfo = config.pluginmanager.list_plugin_distinfo()
249
+ if plugininfo:
250
+ lines.append("registered third-party plugins:")
251
+ for plugin, dist in plugininfo:
252
+ loc = getattr(plugin, "__file__", repr(plugin))
253
+ content = f"{dist.project_name}-{dist.version} at {loc}"
254
+ lines.append(" " + content)
255
+ return lines
256
+
257
+
258
+ def pytest_report_header(config: Config) -> list[str]:
259
+ lines = []
260
+ if config.option.debug or config.option.traceconfig:
261
+ lines.append(f"using: pytest-{pytest.__version__}")
262
+
263
+ verinfo = getpluginversioninfo(config)
264
+ if verinfo:
265
+ lines.extend(verinfo)
266
+
267
+ if config.option.traceconfig:
268
+ lines.append("active plugins:")
269
+ items = config.pluginmanager.list_name_plugin()
270
+ for name, plugin in items:
271
+ if hasattr(plugin, "__file__"):
272
+ r = plugin.__file__
273
+ else:
274
+ r = repr(plugin)
275
+ lines.append(f" {name:<20}: {r}")
276
+ return lines
vllm/lib/python3.10/site-packages/_pytest/hookspec.py ADDED
@@ -0,0 +1,1333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # ruff: noqa: T100
3
+ """Hook specifications for pytest plugins which are invoked by pytest itself
4
+ and by builtin plugins."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from pathlib import Path
9
+ from typing import Any
10
+ from typing import Mapping
11
+ from typing import Sequence
12
+ from typing import TYPE_CHECKING
13
+
14
+ from pluggy import HookspecMarker
15
+
16
+ from .deprecated import HOOK_LEGACY_PATH_ARG
17
+
18
+
19
+ if TYPE_CHECKING:
20
+ import pdb
21
+ from typing import Literal
22
+ import warnings
23
+
24
+ from _pytest._code.code import ExceptionInfo
25
+ from _pytest._code.code import ExceptionRepr
26
+ from _pytest.compat import LEGACY_PATH
27
+ from _pytest.config import _PluggyPlugin
28
+ from _pytest.config import Config
29
+ from _pytest.config import ExitCode
30
+ from _pytest.config import PytestPluginManager
31
+ from _pytest.config.argparsing import Parser
32
+ from _pytest.fixtures import FixtureDef
33
+ from _pytest.fixtures import SubRequest
34
+ from _pytest.main import Session
35
+ from _pytest.nodes import Collector
36
+ from _pytest.nodes import Item
37
+ from _pytest.outcomes import Exit
38
+ from _pytest.python import Class
39
+ from _pytest.python import Function
40
+ from _pytest.python import Metafunc
41
+ from _pytest.python import Module
42
+ from _pytest.reports import CollectReport
43
+ from _pytest.reports import TestReport
44
+ from _pytest.runner import CallInfo
45
+ from _pytest.terminal import TerminalReporter
46
+ from _pytest.terminal import TestShortLogReport
47
+
48
+
49
+ hookspec = HookspecMarker("pytest")
50
+
51
+ # -------------------------------------------------------------------------
52
+ # Initialization hooks called for every plugin
53
+ # -------------------------------------------------------------------------
54
+
55
+
56
+ @hookspec(historic=True)
57
+ def pytest_addhooks(pluginmanager: PytestPluginManager) -> None:
58
+ """Called at plugin registration time to allow adding new hooks via a call to
59
+ :func:`pluginmanager.add_hookspecs(module_or_class, prefix) <pytest.PytestPluginManager.add_hookspecs>`.
60
+
61
+ :param pluginmanager: The pytest plugin manager.
62
+
63
+ .. note::
64
+ This hook is incompatible with hook wrappers.
65
+
66
+ Use in conftest plugins
67
+ =======================
68
+
69
+ If a conftest plugin implements this hook, it will be called immediately
70
+ when the conftest is registered.
71
+ """
72
+
73
+
74
+ @hookspec(historic=True)
75
+ def pytest_plugin_registered(
76
+ plugin: _PluggyPlugin,
77
+ plugin_name: str,
78
+ manager: PytestPluginManager,
79
+ ) -> None:
80
+ """A new pytest plugin got registered.
81
+
82
+ :param plugin: The plugin module or instance.
83
+ :param plugin_name: The name by which the plugin is registered.
84
+ :param manager: The pytest plugin manager.
85
+
86
+ .. note::
87
+ This hook is incompatible with hook wrappers.
88
+
89
+ Use in conftest plugins
90
+ =======================
91
+
92
+ If a conftest plugin implements this hook, it will be called immediately
93
+ when the conftest is registered, once for each plugin registered thus far
94
+ (including itself!), and for all plugins thereafter when they are
95
+ registered.
96
+ """
97
+
98
+
99
+ @hookspec(historic=True)
100
+ def pytest_addoption(parser: Parser, pluginmanager: PytestPluginManager) -> None:
101
+ """Register argparse-style options and ini-style config values,
102
+ called once at the beginning of a test run.
103
+
104
+ :param parser:
105
+ To add command line options, call
106
+ :py:func:`parser.addoption(...) <pytest.Parser.addoption>`.
107
+ To add ini-file values call :py:func:`parser.addini(...)
108
+ <pytest.Parser.addini>`.
109
+
110
+ :param pluginmanager:
111
+ The pytest plugin manager, which can be used to install :py:func:`~pytest.hookspec`'s
112
+ or :py:func:`~pytest.hookimpl`'s and allow one plugin to call another plugin's hooks
113
+ to change how command line options are added.
114
+
115
+ Options can later be accessed through the
116
+ :py:class:`config <pytest.Config>` object, respectively:
117
+
118
+ - :py:func:`config.getoption(name) <pytest.Config.getoption>` to
119
+ retrieve the value of a command line option.
120
+
121
+ - :py:func:`config.getini(name) <pytest.Config.getini>` to retrieve
122
+ a value read from an ini-style file.
123
+
124
+ The config object is passed around on many internal objects via the ``.config``
125
+ attribute or can be retrieved as the ``pytestconfig`` fixture.
126
+
127
+ .. note::
128
+ This hook is incompatible with hook wrappers.
129
+
130
+ Use in conftest plugins
131
+ =======================
132
+
133
+ If a conftest plugin implements this hook, it will be called immediately
134
+ when the conftest is registered.
135
+
136
+ This hook is only called for :ref:`initial conftests <pluginorder>`.
137
+ """
138
+
139
+
140
+ @hookspec(historic=True)
141
+ def pytest_configure(config: Config) -> None:
142
+ """Allow plugins and conftest files to perform initial configuration.
143
+
144
+ .. note::
145
+ This hook is incompatible with hook wrappers.
146
+
147
+ :param config: The pytest config object.
148
+
149
+ Use in conftest plugins
150
+ =======================
151
+
152
+ This hook is called for every :ref:`initial conftest <pluginorder>` file
153
+ after command line options have been parsed. After that, the hook is called
154
+ for other conftest files as they are registered.
155
+ """
156
+
157
+
158
+ # -------------------------------------------------------------------------
159
+ # Bootstrapping hooks called for plugins registered early enough:
160
+ # internal and 3rd party plugins.
161
+ # -------------------------------------------------------------------------
162
+
163
+
164
+ @hookspec(firstresult=True)
165
+ def pytest_cmdline_parse(
166
+ pluginmanager: PytestPluginManager, args: list[str]
167
+ ) -> Config | None:
168
+ """Return an initialized :class:`~pytest.Config`, parsing the specified args.
169
+
170
+ Stops at first non-None result, see :ref:`firstresult`.
171
+
172
+ .. note::
173
+ This hook is only called for plugin classes passed to the
174
+ ``plugins`` arg when using `pytest.main`_ to perform an in-process
175
+ test run.
176
+
177
+ :param pluginmanager: The pytest plugin manager.
178
+ :param args: List of arguments passed on the command line.
179
+ :returns: A pytest config object.
180
+
181
+ Use in conftest plugins
182
+ =======================
183
+
184
+ This hook is not called for conftest files.
185
+ """
186
+
187
+
188
+ def pytest_load_initial_conftests(
189
+ early_config: Config, parser: Parser, args: list[str]
190
+ ) -> None:
191
+ """Called to implement the loading of :ref:`initial conftest files
192
+ <pluginorder>` ahead of command line option parsing.
193
+
194
+ :param early_config: The pytest config object.
195
+ :param args: Arguments passed on the command line.
196
+ :param parser: To add command line options.
197
+
198
+ Use in conftest plugins
199
+ =======================
200
+
201
+ This hook is not called for conftest files.
202
+ """
203
+
204
+
205
+ @hookspec(firstresult=True)
206
+ def pytest_cmdline_main(config: Config) -> ExitCode | int | None:
207
+ """Called for performing the main command line action.
208
+
209
+ The default implementation will invoke the configure hooks and
210
+ :hook:`pytest_runtestloop`.
211
+
212
+ Stops at first non-None result, see :ref:`firstresult`.
213
+
214
+ :param config: The pytest config object.
215
+ :returns: The exit code.
216
+
217
+ Use in conftest plugins
218
+ =======================
219
+
220
+ This hook is only called for :ref:`initial conftests <pluginorder>`.
221
+ """
222
+
223
+
224
+ # -------------------------------------------------------------------------
225
+ # collection hooks
226
+ # -------------------------------------------------------------------------
227
+
228
+
229
+ @hookspec(firstresult=True)
230
+ def pytest_collection(session: Session) -> object | None:
231
+ """Perform the collection phase for the given session.
232
+
233
+ Stops at first non-None result, see :ref:`firstresult`.
234
+ The return value is not used, but only stops further processing.
235
+
236
+ The default collection phase is this (see individual hooks for full details):
237
+
238
+ 1. Starting from ``session`` as the initial collector:
239
+
240
+ 1. ``pytest_collectstart(collector)``
241
+ 2. ``report = pytest_make_collect_report(collector)``
242
+ 3. ``pytest_exception_interact(collector, call, report)`` if an interactive exception occurred
243
+ 4. For each collected node:
244
+
245
+ 1. If an item, ``pytest_itemcollected(item)``
246
+ 2. If a collector, recurse into it.
247
+
248
+ 5. ``pytest_collectreport(report)``
249
+
250
+ 2. ``pytest_collection_modifyitems(session, config, items)``
251
+
252
+ 1. ``pytest_deselected(items)`` for any deselected items (may be called multiple times)
253
+
254
+ 3. ``pytest_collection_finish(session)``
255
+ 4. Set ``session.items`` to the list of collected items
256
+ 5. Set ``session.testscollected`` to the number of collected items
257
+
258
+ You can implement this hook to only perform some action before collection,
259
+ for example the terminal plugin uses it to start displaying the collection
260
+ counter (and returns `None`).
261
+
262
+ :param session: The pytest session object.
263
+
264
+ Use in conftest plugins
265
+ =======================
266
+
267
+ This hook is only called for :ref:`initial conftests <pluginorder>`.
268
+ """
269
+
270
+
271
+ def pytest_collection_modifyitems(
272
+ session: Session, config: Config, items: list[Item]
273
+ ) -> None:
274
+ """Called after collection has been performed. May filter or re-order
275
+ the items in-place.
276
+
277
+ When items are deselected (filtered out from ``items``),
278
+ the hook :hook:`pytest_deselected` must be called explicitly
279
+ with the deselected items to properly notify other plugins,
280
+ e.g. with ``config.hook.pytest_deselected(deselected_items)``.
281
+
282
+ :param session: The pytest session object.
283
+ :param config: The pytest config object.
284
+ :param items: List of item objects.
285
+
286
+ Use in conftest plugins
287
+ =======================
288
+
289
+ Any conftest plugin can implement this hook.
290
+ """
291
+
292
+
293
+ def pytest_collection_finish(session: Session) -> None:
294
+ """Called after collection has been performed and modified.
295
+
296
+ :param session: The pytest session object.
297
+
298
+ Use in conftest plugins
299
+ =======================
300
+
301
+ Any conftest plugin can implement this hook.
302
+ """
303
+
304
+
305
+ @hookspec(
306
+ firstresult=True,
307
+ warn_on_impl_args={
308
+ "path": HOOK_LEGACY_PATH_ARG.format(
309
+ pylib_path_arg="path", pathlib_path_arg="collection_path"
310
+ ),
311
+ },
312
+ )
313
+ def pytest_ignore_collect(
314
+ collection_path: Path, path: LEGACY_PATH, config: Config
315
+ ) -> bool | None:
316
+ """Return ``True`` to ignore this path for collection.
317
+
318
+ Return ``None`` to let other plugins ignore the path for collection.
319
+
320
+ Returning ``False`` will forcefully *not* ignore this path for collection,
321
+ without giving a chance for other plugins to ignore this path.
322
+
323
+ This hook is consulted for all files and directories prior to calling
324
+ more specific hooks.
325
+
326
+ Stops at first non-None result, see :ref:`firstresult`.
327
+
328
+ :param collection_path: The path to analyze.
329
+ :type collection_path: pathlib.Path
330
+ :param path: The path to analyze (deprecated).
331
+ :param config: The pytest config object.
332
+
333
+ .. versionchanged:: 7.0.0
334
+ The ``collection_path`` parameter was added as a :class:`pathlib.Path`
335
+ equivalent of the ``path`` parameter. The ``path`` parameter
336
+ has been deprecated.
337
+
338
+ Use in conftest plugins
339
+ =======================
340
+
341
+ Any conftest file can implement this hook. For a given collection path, only
342
+ conftest files in parent directories of the collection path are consulted
343
+ (if the path is a directory, its own conftest file is *not* consulted - a
344
+ directory cannot ignore itself!).
345
+ """
346
+
347
+
348
+ @hookspec(firstresult=True)
349
+ def pytest_collect_directory(path: Path, parent: Collector) -> Collector | None:
350
+ """Create a :class:`~pytest.Collector` for the given directory, or None if
351
+ not relevant.
352
+
353
+ .. versionadded:: 8.0
354
+
355
+ For best results, the returned collector should be a subclass of
356
+ :class:`~pytest.Directory`, but this is not required.
357
+
358
+ The new node needs to have the specified ``parent`` as a parent.
359
+
360
+ Stops at first non-None result, see :ref:`firstresult`.
361
+
362
+ :param path: The path to analyze.
363
+ :type path: pathlib.Path
364
+
365
+ See :ref:`custom directory collectors` for a simple example of use of this
366
+ hook.
367
+
368
+ Use in conftest plugins
369
+ =======================
370
+
371
+ Any conftest file can implement this hook. For a given collection path, only
372
+ conftest files in parent directories of the collection path are consulted
373
+ (if the path is a directory, its own conftest file is *not* consulted - a
374
+ directory cannot collect itself!).
375
+ """
376
+
377
+
378
+ @hookspec(
379
+ warn_on_impl_args={
380
+ "path": HOOK_LEGACY_PATH_ARG.format(
381
+ pylib_path_arg="path", pathlib_path_arg="file_path"
382
+ ),
383
+ },
384
+ )
385
+ def pytest_collect_file(
386
+ file_path: Path, path: LEGACY_PATH, parent: Collector
387
+ ) -> Collector | None:
388
+ """Create a :class:`~pytest.Collector` for the given path, or None if not relevant.
389
+
390
+ For best results, the returned collector should be a subclass of
391
+ :class:`~pytest.File`, but this is not required.
392
+
393
+ The new node needs to have the specified ``parent`` as a parent.
394
+
395
+ :param file_path: The path to analyze.
396
+ :type file_path: pathlib.Path
397
+ :param path: The path to collect (deprecated).
398
+
399
+ .. versionchanged:: 7.0.0
400
+ The ``file_path`` parameter was added as a :class:`pathlib.Path`
401
+ equivalent of the ``path`` parameter. The ``path`` parameter
402
+ has been deprecated.
403
+
404
+ Use in conftest plugins
405
+ =======================
406
+
407
+ Any conftest file can implement this hook. For a given file path, only
408
+ conftest files in parent directories of the file path are consulted.
409
+ """
410
+
411
+
412
+ # logging hooks for collection
413
+
414
+
415
+ def pytest_collectstart(collector: Collector) -> None:
416
+ """Collector starts collecting.
417
+
418
+ :param collector:
419
+ The collector.
420
+
421
+ Use in conftest plugins
422
+ =======================
423
+
424
+ Any conftest file can implement this hook. For a given collector, only
425
+ conftest files in the collector's directory and its parent directories are
426
+ consulted.
427
+ """
428
+
429
+
430
+ def pytest_itemcollected(item: Item) -> None:
431
+ """We just collected a test item.
432
+
433
+ :param item:
434
+ The item.
435
+
436
+ Use in conftest plugins
437
+ =======================
438
+
439
+ Any conftest file can implement this hook. For a given item, only conftest
440
+ files in the item's directory and its parent directories are consulted.
441
+ """
442
+
443
+
444
+ def pytest_collectreport(report: CollectReport) -> None:
445
+ """Collector finished collecting.
446
+
447
+ :param report:
448
+ The collect report.
449
+
450
+ Use in conftest plugins
451
+ =======================
452
+
453
+ Any conftest file can implement this hook. For a given collector, only
454
+ conftest files in the collector's directory and its parent directories are
455
+ consulted.
456
+ """
457
+
458
+
459
+ def pytest_deselected(items: Sequence[Item]) -> None:
460
+ """Called for deselected test items, e.g. by keyword.
461
+
462
+ Note that this hook has two integration aspects for plugins:
463
+
464
+ - it can be *implemented* to be notified of deselected items
465
+ - it must be *called* from :hook:`pytest_collection_modifyitems`
466
+ implementations when items are deselected (to properly notify other plugins).
467
+
468
+ May be called multiple times.
469
+
470
+ :param items:
471
+ The items.
472
+
473
+ Use in conftest plugins
474
+ =======================
475
+
476
+ Any conftest file can implement this hook.
477
+ """
478
+
479
+
480
+ @hookspec(firstresult=True)
481
+ def pytest_make_collect_report(collector: Collector) -> CollectReport | None:
482
+ """Perform :func:`collector.collect() <pytest.Collector.collect>` and return
483
+ a :class:`~pytest.CollectReport`.
484
+
485
+ Stops at first non-None result, see :ref:`firstresult`.
486
+
487
+ :param collector:
488
+ The collector.
489
+
490
+ Use in conftest plugins
491
+ =======================
492
+
493
+ Any conftest file can implement this hook. For a given collector, only
494
+ conftest files in the collector's directory and its parent directories are
495
+ consulted.
496
+ """
497
+
498
+
499
+ # -------------------------------------------------------------------------
500
+ # Python test function related hooks
501
+ # -------------------------------------------------------------------------
502
+
503
+
504
+ @hookspec(
505
+ firstresult=True,
506
+ warn_on_impl_args={
507
+ "path": HOOK_LEGACY_PATH_ARG.format(
508
+ pylib_path_arg="path", pathlib_path_arg="module_path"
509
+ ),
510
+ },
511
+ )
512
+ def pytest_pycollect_makemodule(
513
+ module_path: Path, path: LEGACY_PATH, parent
514
+ ) -> Module | None:
515
+ """Return a :class:`pytest.Module` collector or None for the given path.
516
+
517
+ This hook will be called for each matching test module path.
518
+ The :hook:`pytest_collect_file` hook needs to be used if you want to
519
+ create test modules for files that do not match as a test module.
520
+
521
+ Stops at first non-None result, see :ref:`firstresult`.
522
+
523
+ :param module_path: The path of the module to collect.
524
+ :type module_path: pathlib.Path
525
+ :param path: The path of the module to collect (deprecated).
526
+
527
+ .. versionchanged:: 7.0.0
528
+ The ``module_path`` parameter was added as a :class:`pathlib.Path`
529
+ equivalent of the ``path`` parameter.
530
+
531
+ The ``path`` parameter has been deprecated in favor of ``fspath``.
532
+
533
+ Use in conftest plugins
534
+ =======================
535
+
536
+ Any conftest file can implement this hook. For a given parent collector,
537
+ only conftest files in the collector's directory and its parent directories
538
+ are consulted.
539
+ """
540
+
541
+
542
+ @hookspec(firstresult=True)
543
+ def pytest_pycollect_makeitem(
544
+ collector: Module | Class, name: str, obj: object
545
+ ) -> None | Item | Collector | list[Item | Collector]:
546
+ """Return a custom item/collector for a Python object in a module, or None.
547
+
548
+ Stops at first non-None result, see :ref:`firstresult`.
549
+
550
+ :param collector:
551
+ The module/class collector.
552
+ :param name:
553
+ The name of the object in the module/class.
554
+ :param obj:
555
+ The object.
556
+ :returns:
557
+ The created items/collectors.
558
+
559
+ Use in conftest plugins
560
+ =======================
561
+
562
+ Any conftest file can implement this hook. For a given collector, only
563
+ conftest files in the collector's directory and its parent directories
564
+ are consulted.
565
+ """
566
+
567
+
568
+ @hookspec(firstresult=True)
569
+ def pytest_pyfunc_call(pyfuncitem: Function) -> object | None:
570
+ """Call underlying test function.
571
+
572
+ Stops at first non-None result, see :ref:`firstresult`.
573
+
574
+ :param pyfuncitem:
575
+ The function item.
576
+
577
+ Use in conftest plugins
578
+ =======================
579
+
580
+ Any conftest file can implement this hook. For a given item, only
581
+ conftest files in the item's directory and its parent directories
582
+ are consulted.
583
+ """
584
+
585
+
586
+ def pytest_generate_tests(metafunc: Metafunc) -> None:
587
+ """Generate (multiple) parametrized calls to a test function.
588
+
589
+ :param metafunc:
590
+ The :class:`~pytest.Metafunc` helper for the test function.
591
+
592
+ Use in conftest plugins
593
+ =======================
594
+
595
+ Any conftest file can implement this hook. For a given function definition,
596
+ only conftest files in the functions's directory and its parent directories
597
+ are consulted.
598
+ """
599
+
600
+
601
+ @hookspec(firstresult=True)
602
+ def pytest_make_parametrize_id(config: Config, val: object, argname: str) -> str | None:
603
+ """Return a user-friendly string representation of the given ``val``
604
+ that will be used by @pytest.mark.parametrize calls, or None if the hook
605
+ doesn't know about ``val``.
606
+
607
+ The parameter name is available as ``argname``, if required.
608
+
609
+ Stops at first non-None result, see :ref:`firstresult`.
610
+
611
+ :param config: The pytest config object.
612
+ :param val: The parametrized value.
613
+ :param argname: The automatic parameter name produced by pytest.
614
+
615
+ Use in conftest plugins
616
+ =======================
617
+
618
+ Any conftest file can implement this hook.
619
+ """
620
+
621
+
622
+ # -------------------------------------------------------------------------
623
+ # runtest related hooks
624
+ # -------------------------------------------------------------------------
625
+
626
+
627
+ @hookspec(firstresult=True)
628
+ def pytest_runtestloop(session: Session) -> object | None:
629
+ """Perform the main runtest loop (after collection finished).
630
+
631
+ The default hook implementation performs the runtest protocol for all items
632
+ collected in the session (``session.items``), unless the collection failed
633
+ or the ``collectonly`` pytest option is set.
634
+
635
+ If at any point :py:func:`pytest.exit` is called, the loop is
636
+ terminated immediately.
637
+
638
+ If at any point ``session.shouldfail`` or ``session.shouldstop`` are set, the
639
+ loop is terminated after the runtest protocol for the current item is finished.
640
+
641
+ :param session: The pytest session object.
642
+
643
+ Stops at first non-None result, see :ref:`firstresult`.
644
+ The return value is not used, but only stops further processing.
645
+
646
+ Use in conftest plugins
647
+ =======================
648
+
649
+ Any conftest file can implement this hook.
650
+ """
651
+
652
+
653
+ @hookspec(firstresult=True)
654
+ def pytest_runtest_protocol(item: Item, nextitem: Item | None) -> object | None:
655
+ """Perform the runtest protocol for a single test item.
656
+
657
+ The default runtest protocol is this (see individual hooks for full details):
658
+
659
+ - ``pytest_runtest_logstart(nodeid, location)``
660
+
661
+ - Setup phase:
662
+ - ``call = pytest_runtest_setup(item)`` (wrapped in ``CallInfo(when="setup")``)
663
+ - ``report = pytest_runtest_makereport(item, call)``
664
+ - ``pytest_runtest_logreport(report)``
665
+ - ``pytest_exception_interact(call, report)`` if an interactive exception occurred
666
+
667
+ - Call phase, if the setup passed and the ``setuponly`` pytest option is not set:
668
+ - ``call = pytest_runtest_call(item)`` (wrapped in ``CallInfo(when="call")``)
669
+ - ``report = pytest_runtest_makereport(item, call)``
670
+ - ``pytest_runtest_logreport(report)``
671
+ - ``pytest_exception_interact(call, report)`` if an interactive exception occurred
672
+
673
+ - Teardown phase:
674
+ - ``call = pytest_runtest_teardown(item, nextitem)`` (wrapped in ``CallInfo(when="teardown")``)
675
+ - ``report = pytest_runtest_makereport(item, call)``
676
+ - ``pytest_runtest_logreport(report)``
677
+ - ``pytest_exception_interact(call, report)`` if an interactive exception occurred
678
+
679
+ - ``pytest_runtest_logfinish(nodeid, location)``
680
+
681
+ :param item: Test item for which the runtest protocol is performed.
682
+ :param nextitem: The scheduled-to-be-next test item (or None if this is the end my friend).
683
+
684
+ Stops at first non-None result, see :ref:`firstresult`.
685
+ The return value is not used, but only stops further processing.
686
+
687
+ Use in conftest plugins
688
+ =======================
689
+
690
+ Any conftest file can implement this hook.
691
+ """
692
+
693
+
694
+ def pytest_runtest_logstart(nodeid: str, location: tuple[str, int | None, str]) -> None:
695
+ """Called at the start of running the runtest protocol for a single item.
696
+
697
+ See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.
698
+
699
+ :param nodeid: Full node ID of the item.
700
+ :param location: A tuple of ``(filename, lineno, testname)``
701
+ where ``filename`` is a file path relative to ``config.rootpath``
702
+ and ``lineno`` is 0-based.
703
+
704
+ Use in conftest plugins
705
+ =======================
706
+
707
+ Any conftest file can implement this hook. For a given item, only conftest
708
+ files in the item's directory and its parent directories are consulted.
709
+ """
710
+
711
+
712
+ def pytest_runtest_logfinish(
713
+ nodeid: str, location: tuple[str, int | None, str]
714
+ ) -> None:
715
+ """Called at the end of running the runtest protocol for a single item.
716
+
717
+ See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.
718
+
719
+ :param nodeid: Full node ID of the item.
720
+ :param location: A tuple of ``(filename, lineno, testname)``
721
+ where ``filename`` is a file path relative to ``config.rootpath``
722
+ and ``lineno`` is 0-based.
723
+
724
+ Use in conftest plugins
725
+ =======================
726
+
727
+ Any conftest file can implement this hook. For a given item, only conftest
728
+ files in the item's directory and its parent directories are consulted.
729
+ """
730
+
731
+
732
+ def pytest_runtest_setup(item: Item) -> None:
733
+ """Called to perform the setup phase for a test item.
734
+
735
+ The default implementation runs ``setup()`` on ``item`` and all of its
736
+ parents (which haven't been setup yet). This includes obtaining the
737
+ values of fixtures required by the item (which haven't been obtained
738
+ yet).
739
+
740
+ :param item:
741
+ The item.
742
+
743
+ Use in conftest plugins
744
+ =======================
745
+
746
+ Any conftest file can implement this hook. For a given item, only conftest
747
+ files in the item's directory and its parent directories are consulted.
748
+ """
749
+
750
+
751
+ def pytest_runtest_call(item: Item) -> None:
752
+ """Called to run the test for test item (the call phase).
753
+
754
+ The default implementation calls ``item.runtest()``.
755
+
756
+ :param item:
757
+ The item.
758
+
759
+ Use in conftest plugins
760
+ =======================
761
+
762
+ Any conftest file can implement this hook. For a given item, only conftest
763
+ files in the item's directory and its parent directories are consulted.
764
+ """
765
+
766
+
767
+ def pytest_runtest_teardown(item: Item, nextitem: Item | None) -> None:
768
+ """Called to perform the teardown phase for a test item.
769
+
770
+ The default implementation runs the finalizers and calls ``teardown()``
771
+ on ``item`` and all of its parents (which need to be torn down). This
772
+ includes running the teardown phase of fixtures required by the item (if
773
+ they go out of scope).
774
+
775
+ :param item:
776
+ The item.
777
+ :param nextitem:
778
+ The scheduled-to-be-next test item (None if no further test item is
779
+ scheduled). This argument is used to perform exact teardowns, i.e.
780
+ calling just enough finalizers so that nextitem only needs to call
781
+ setup functions.
782
+
783
+ Use in conftest plugins
784
+ =======================
785
+
786
+ Any conftest file can implement this hook. For a given item, only conftest
787
+ files in the item's directory and its parent directories are consulted.
788
+ """
789
+
790
+
791
+ @hookspec(firstresult=True)
792
+ def pytest_runtest_makereport(item: Item, call: CallInfo[None]) -> TestReport | None:
793
+ """Called to create a :class:`~pytest.TestReport` for each of
794
+ the setup, call and teardown runtest phases of a test item.
795
+
796
+ See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.
797
+
798
+ :param item: The item.
799
+ :param call: The :class:`~pytest.CallInfo` for the phase.
800
+
801
+ Stops at first non-None result, see :ref:`firstresult`.
802
+
803
+ Use in conftest plugins
804
+ =======================
805
+
806
+ Any conftest file can implement this hook. For a given item, only conftest
807
+ files in the item's directory and its parent directories are consulted.
808
+ """
809
+
810
+
811
+ def pytest_runtest_logreport(report: TestReport) -> None:
812
+ """Process the :class:`~pytest.TestReport` produced for each
813
+ of the setup, call and teardown runtest phases of an item.
814
+
815
+ See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.
816
+
817
+ Use in conftest plugins
818
+ =======================
819
+
820
+ Any conftest file can implement this hook. For a given item, only conftest
821
+ files in the item's directory and its parent directories are consulted.
822
+ """
823
+
824
+
825
+ @hookspec(firstresult=True)
826
+ def pytest_report_to_serializable(
827
+ config: Config,
828
+ report: CollectReport | TestReport,
829
+ ) -> dict[str, Any] | None:
830
+ """Serialize the given report object into a data structure suitable for
831
+ sending over the wire, e.g. converted to JSON.
832
+
833
+ :param config: The pytest config object.
834
+ :param report: The report.
835
+
836
+ Use in conftest plugins
837
+ =======================
838
+
839
+ Any conftest file can implement this hook. The exact details may depend
840
+ on the plugin which calls the hook.
841
+ """
842
+
843
+
844
+ @hookspec(firstresult=True)
845
+ def pytest_report_from_serializable(
846
+ config: Config,
847
+ data: dict[str, Any],
848
+ ) -> CollectReport | TestReport | None:
849
+ """Restore a report object previously serialized with
850
+ :hook:`pytest_report_to_serializable`.
851
+
852
+ :param config: The pytest config object.
853
+
854
+ Use in conftest plugins
855
+ =======================
856
+
857
+ Any conftest file can implement this hook. The exact details may depend
858
+ on the plugin which calls the hook.
859
+ """
860
+
861
+
862
+ # -------------------------------------------------------------------------
863
+ # Fixture related hooks
864
+ # -------------------------------------------------------------------------
865
+
866
+
867
+ @hookspec(firstresult=True)
868
+ def pytest_fixture_setup(
869
+ fixturedef: FixtureDef[Any], request: SubRequest
870
+ ) -> object | None:
871
+ """Perform fixture setup execution.
872
+
873
+ :param fixturedef:
874
+ The fixture definition object.
875
+ :param request:
876
+ The fixture request object.
877
+ :returns:
878
+ The return value of the call to the fixture function.
879
+
880
+ Stops at first non-None result, see :ref:`firstresult`.
881
+
882
+ .. note::
883
+ If the fixture function returns None, other implementations of
884
+ this hook function will continue to be called, according to the
885
+ behavior of the :ref:`firstresult` option.
886
+
887
+ Use in conftest plugins
888
+ =======================
889
+
890
+ Any conftest file can implement this hook. For a given fixture, only
891
+ conftest files in the fixture scope's directory and its parent directories
892
+ are consulted.
893
+ """
894
+
895
+
896
+ def pytest_fixture_post_finalizer(
897
+ fixturedef: FixtureDef[Any], request: SubRequest
898
+ ) -> None:
899
+ """Called after fixture teardown, but before the cache is cleared, so
900
+ the fixture result ``fixturedef.cached_result`` is still available (not
901
+ ``None``).
902
+
903
+ :param fixturedef:
904
+ The fixture definition object.
905
+ :param request:
906
+ The fixture request object.
907
+
908
+ Use in conftest plugins
909
+ =======================
910
+
911
+ Any conftest file can implement this hook. For a given fixture, only
912
+ conftest files in the fixture scope's directory and its parent directories
913
+ are consulted.
914
+ """
915
+
916
+
917
+ # -------------------------------------------------------------------------
918
+ # test session related hooks
919
+ # -------------------------------------------------------------------------
920
+
921
+
922
+ def pytest_sessionstart(session: Session) -> None:
923
+ """Called after the ``Session`` object has been created and before performing collection
924
+ and entering the run test loop.
925
+
926
+ :param session: The pytest session object.
927
+
928
+ Use in conftest plugins
929
+ =======================
930
+
931
+ This hook is only called for :ref:`initial conftests <pluginorder>`.
932
+ """
933
+
934
+
935
+ def pytest_sessionfinish(
936
+ session: Session,
937
+ exitstatus: int | ExitCode,
938
+ ) -> None:
939
+ """Called after whole test run finished, right before returning the exit status to the system.
940
+
941
+ :param session: The pytest session object.
942
+ :param exitstatus: The status which pytest will return to the system.
943
+
944
+ Use in conftest plugins
945
+ =======================
946
+
947
+ Any conftest file can implement this hook.
948
+ """
949
+
950
+
951
+ def pytest_unconfigure(config: Config) -> None:
952
+ """Called before test process is exited.
953
+
954
+ :param config: The pytest config object.
955
+
956
+ Use in conftest plugins
957
+ =======================
958
+
959
+ Any conftest file can implement this hook.
960
+ """
961
+
962
+
963
+ # -------------------------------------------------------------------------
964
+ # hooks for customizing the assert methods
965
+ # -------------------------------------------------------------------------
966
+
967
+
968
+ def pytest_assertrepr_compare(
969
+ config: Config, op: str, left: object, right: object
970
+ ) -> list[str] | None:
971
+ """Return explanation for comparisons in failing assert expressions.
972
+
973
+ Return None for no custom explanation, otherwise return a list
974
+ of strings. The strings will be joined by newlines but any newlines
975
+ *in* a string will be escaped. Note that all but the first line will
976
+ be indented slightly, the intention is for the first line to be a summary.
977
+
978
+ :param config: The pytest config object.
979
+ :param op: The operator, e.g. `"=="`, `"!="`, `"not in"`.
980
+ :param left: The left operand.
981
+ :param right: The right operand.
982
+
983
+ Use in conftest plugins
984
+ =======================
985
+
986
+ Any conftest file can implement this hook. For a given item, only conftest
987
+ files in the item's directory and its parent directories are consulted.
988
+ """
989
+
990
+
991
+ def pytest_assertion_pass(item: Item, lineno: int, orig: str, expl: str) -> None:
992
+ """Called whenever an assertion passes.
993
+
994
+ .. versionadded:: 5.0
995
+
996
+ Use this hook to do some processing after a passing assertion.
997
+ The original assertion information is available in the `orig` string
998
+ and the pytest introspected assertion information is available in the
999
+ `expl` string.
1000
+
1001
+ This hook must be explicitly enabled by the ``enable_assertion_pass_hook``
1002
+ ini-file option:
1003
+
1004
+ .. code-block:: ini
1005
+
1006
+ [pytest]
1007
+ enable_assertion_pass_hook=true
1008
+
1009
+ You need to **clean the .pyc** files in your project directory and interpreter libraries
1010
+ when enabling this option, as assertions will require to be re-written.
1011
+
1012
+ :param item: pytest item object of current test.
1013
+ :param lineno: Line number of the assert statement.
1014
+ :param orig: String with the original assertion.
1015
+ :param expl: String with the assert explanation.
1016
+
1017
+ Use in conftest plugins
1018
+ =======================
1019
+
1020
+ Any conftest file can implement this hook. For a given item, only conftest
1021
+ files in the item's directory and its parent directories are consulted.
1022
+ """
1023
+
1024
+
1025
+ # -------------------------------------------------------------------------
1026
+ # Hooks for influencing reporting (invoked from _pytest_terminal).
1027
+ # -------------------------------------------------------------------------
1028
+
1029
+
1030
+ @hookspec(
1031
+ warn_on_impl_args={
1032
+ "startdir": HOOK_LEGACY_PATH_ARG.format(
1033
+ pylib_path_arg="startdir", pathlib_path_arg="start_path"
1034
+ ),
1035
+ },
1036
+ )
1037
+ def pytest_report_header( # type:ignore[empty-body]
1038
+ config: Config, start_path: Path, startdir: LEGACY_PATH
1039
+ ) -> str | list[str]:
1040
+ """Return a string or list of strings to be displayed as header info for terminal reporting.
1041
+
1042
+ :param config: The pytest config object.
1043
+ :param start_path: The starting dir.
1044
+ :type start_path: pathlib.Path
1045
+ :param startdir: The starting dir (deprecated).
1046
+
1047
+ .. note::
1048
+
1049
+ Lines returned by a plugin are displayed before those of plugins which
1050
+ ran before it.
1051
+ If you want to have your line(s) displayed first, use
1052
+ :ref:`trylast=True <plugin-hookorder>`.
1053
+
1054
+ .. versionchanged:: 7.0.0
1055
+ The ``start_path`` parameter was added as a :class:`pathlib.Path`
1056
+ equivalent of the ``startdir`` parameter. The ``startdir`` parameter
1057
+ has been deprecated.
1058
+
1059
+ Use in conftest plugins
1060
+ =======================
1061
+
1062
+ This hook is only called for :ref:`initial conftests <pluginorder>`.
1063
+ """
1064
+
1065
+
1066
+ @hookspec(
1067
+ warn_on_impl_args={
1068
+ "startdir": HOOK_LEGACY_PATH_ARG.format(
1069
+ pylib_path_arg="startdir", pathlib_path_arg="start_path"
1070
+ ),
1071
+ },
1072
+ )
1073
+ def pytest_report_collectionfinish( # type:ignore[empty-body]
1074
+ config: Config,
1075
+ start_path: Path,
1076
+ startdir: LEGACY_PATH,
1077
+ items: Sequence[Item],
1078
+ ) -> str | list[str]:
1079
+ """Return a string or list of strings to be displayed after collection
1080
+ has finished successfully.
1081
+
1082
+ These strings will be displayed after the standard "collected X items" message.
1083
+
1084
+ .. versionadded:: 3.2
1085
+
1086
+ :param config: The pytest config object.
1087
+ :param start_path: The starting dir.
1088
+ :type start_path: pathlib.Path
1089
+ :param startdir: The starting dir (deprecated).
1090
+ :param items: List of pytest items that are going to be executed; this list should not be modified.
1091
+
1092
+ .. note::
1093
+
1094
+ Lines returned by a plugin are displayed before those of plugins which
1095
+ ran before it.
1096
+ If you want to have your line(s) displayed first, use
1097
+ :ref:`trylast=True <plugin-hookorder>`.
1098
+
1099
+ .. versionchanged:: 7.0.0
1100
+ The ``start_path`` parameter was added as a :class:`pathlib.Path`
1101
+ equivalent of the ``startdir`` parameter. The ``startdir`` parameter
1102
+ has been deprecated.
1103
+
1104
+ Use in conftest plugins
1105
+ =======================
1106
+
1107
+ Any conftest plugin can implement this hook.
1108
+ """
1109
+
1110
+
1111
+ @hookspec(firstresult=True)
1112
+ def pytest_report_teststatus( # type:ignore[empty-body]
1113
+ report: CollectReport | TestReport, config: Config
1114
+ ) -> TestShortLogReport | tuple[str, str, str | tuple[str, Mapping[str, bool]]]:
1115
+ """Return result-category, shortletter and verbose word for status
1116
+ reporting.
1117
+
1118
+ The result-category is a category in which to count the result, for
1119
+ example "passed", "skipped", "error" or the empty string.
1120
+
1121
+ The shortletter is shown as testing progresses, for example ".", "s",
1122
+ "E" or the empty string.
1123
+
1124
+ The verbose word is shown as testing progresses in verbose mode, for
1125
+ example "PASSED", "SKIPPED", "ERROR" or the empty string.
1126
+
1127
+ pytest may style these implicitly according to the report outcome.
1128
+ To provide explicit styling, return a tuple for the verbose word,
1129
+ for example ``"rerun", "R", ("RERUN", {"yellow": True})``.
1130
+
1131
+ :param report: The report object whose status is to be returned.
1132
+ :param config: The pytest config object.
1133
+ :returns: The test status.
1134
+
1135
+ Stops at first non-None result, see :ref:`firstresult`.
1136
+
1137
+ Use in conftest plugins
1138
+ =======================
1139
+
1140
+ Any conftest plugin can implement this hook.
1141
+ """
1142
+
1143
+
1144
+ def pytest_terminal_summary(
1145
+ terminalreporter: TerminalReporter,
1146
+ exitstatus: ExitCode,
1147
+ config: Config,
1148
+ ) -> None:
1149
+ """Add a section to terminal summary reporting.
1150
+
1151
+ :param terminalreporter: The internal terminal reporter object.
1152
+ :param exitstatus: The exit status that will be reported back to the OS.
1153
+ :param config: The pytest config object.
1154
+
1155
+ .. versionadded:: 4.2
1156
+ The ``config`` parameter.
1157
+
1158
+ Use in conftest plugins
1159
+ =======================
1160
+
1161
+ Any conftest plugin can implement this hook.
1162
+ """
1163
+
1164
+
1165
+ @hookspec(historic=True)
1166
+ def pytest_warning_recorded(
1167
+ warning_message: warnings.WarningMessage,
1168
+ when: Literal["config", "collect", "runtest"],
1169
+ nodeid: str,
1170
+ location: tuple[str, int, str] | None,
1171
+ ) -> None:
1172
+ """Process a warning captured by the internal pytest warnings plugin.
1173
+
1174
+ :param warning_message:
1175
+ The captured warning. This is the same object produced by :class:`warnings.catch_warnings`,
1176
+ and contains the same attributes as the parameters of :py:func:`warnings.showwarning`.
1177
+
1178
+ :param when:
1179
+ Indicates when the warning was captured. Possible values:
1180
+
1181
+ * ``"config"``: during pytest configuration/initialization stage.
1182
+ * ``"collect"``: during test collection.
1183
+ * ``"runtest"``: during test execution.
1184
+
1185
+ :param nodeid:
1186
+ Full id of the item. Empty string for warnings that are not specific to
1187
+ a particular node.
1188
+
1189
+ :param location:
1190
+ When available, holds information about the execution context of the captured
1191
+ warning (filename, linenumber, function). ``function`` evaluates to <module>
1192
+ when the execution context is at the module level.
1193
+
1194
+ .. versionadded:: 6.0
1195
+
1196
+ Use in conftest plugins
1197
+ =======================
1198
+
1199
+ Any conftest file can implement this hook. If the warning is specific to a
1200
+ particular node, only conftest files in parent directories of the node are
1201
+ consulted.
1202
+ """
1203
+
1204
+
1205
+ # -------------------------------------------------------------------------
1206
+ # Hooks for influencing skipping
1207
+ # -------------------------------------------------------------------------
1208
+
1209
+
1210
+ def pytest_markeval_namespace( # type:ignore[empty-body]
1211
+ config: Config,
1212
+ ) -> dict[str, Any]:
1213
+ """Called when constructing the globals dictionary used for
1214
+ evaluating string conditions in xfail/skipif markers.
1215
+
1216
+ This is useful when the condition for a marker requires
1217
+ objects that are expensive or impossible to obtain during
1218
+ collection time, which is required by normal boolean
1219
+ conditions.
1220
+
1221
+ .. versionadded:: 6.2
1222
+
1223
+ :param config: The pytest config object.
1224
+ :returns: A dictionary of additional globals to add.
1225
+
1226
+ Use in conftest plugins
1227
+ =======================
1228
+
1229
+ Any conftest file can implement this hook. For a given item, only conftest
1230
+ files in parent directories of the item are consulted.
1231
+ """
1232
+
1233
+
1234
+ # -------------------------------------------------------------------------
1235
+ # error handling and internal debugging hooks
1236
+ # -------------------------------------------------------------------------
1237
+
1238
+
1239
+ def pytest_internalerror(
1240
+ excrepr: ExceptionRepr,
1241
+ excinfo: ExceptionInfo[BaseException],
1242
+ ) -> bool | None:
1243
+ """Called for internal errors.
1244
+
1245
+ Return True to suppress the fallback handling of printing an
1246
+ INTERNALERROR message directly to sys.stderr.
1247
+
1248
+ :param excrepr: The exception repr object.
1249
+ :param excinfo: The exception info.
1250
+
1251
+ Use in conftest plugins
1252
+ =======================
1253
+
1254
+ Any conftest plugin can implement this hook.
1255
+ """
1256
+
1257
+
1258
+ def pytest_keyboard_interrupt(
1259
+ excinfo: ExceptionInfo[KeyboardInterrupt | Exit],
1260
+ ) -> None:
1261
+ """Called for keyboard interrupt.
1262
+
1263
+ :param excinfo: The exception info.
1264
+
1265
+ Use in conftest plugins
1266
+ =======================
1267
+
1268
+ Any conftest plugin can implement this hook.
1269
+ """
1270
+
1271
+
1272
+ def pytest_exception_interact(
1273
+ node: Item | Collector,
1274
+ call: CallInfo[Any],
1275
+ report: CollectReport | TestReport,
1276
+ ) -> None:
1277
+ """Called when an exception was raised which can potentially be
1278
+ interactively handled.
1279
+
1280
+ May be called during collection (see :hook:`pytest_make_collect_report`),
1281
+ in which case ``report`` is a :class:`~pytest.CollectReport`.
1282
+
1283
+ May be called during runtest of an item (see :hook:`pytest_runtest_protocol`),
1284
+ in which case ``report`` is a :class:`~pytest.TestReport`.
1285
+
1286
+ This hook is not called if the exception that was raised is an internal
1287
+ exception like ``skip.Exception``.
1288
+
1289
+ :param node:
1290
+ The item or collector.
1291
+ :param call:
1292
+ The call information. Contains the exception.
1293
+ :param report:
1294
+ The collection or test report.
1295
+
1296
+ Use in conftest plugins
1297
+ =======================
1298
+
1299
+ Any conftest file can implement this hook. For a given node, only conftest
1300
+ files in parent directories of the node are consulted.
1301
+ """
1302
+
1303
+
1304
+ def pytest_enter_pdb(config: Config, pdb: pdb.Pdb) -> None:
1305
+ """Called upon pdb.set_trace().
1306
+
1307
+ Can be used by plugins to take special action just before the python
1308
+ debugger enters interactive mode.
1309
+
1310
+ :param config: The pytest config object.
1311
+ :param pdb: The Pdb instance.
1312
+
1313
+ Use in conftest plugins
1314
+ =======================
1315
+
1316
+ Any conftest plugin can implement this hook.
1317
+ """
1318
+
1319
+
1320
+ def pytest_leave_pdb(config: Config, pdb: pdb.Pdb) -> None:
1321
+ """Called when leaving pdb (e.g. with continue after pdb.set_trace()).
1322
+
1323
+ Can be used by plugins to take special action just after the python
1324
+ debugger leaves interactive mode.
1325
+
1326
+ :param config: The pytest config object.
1327
+ :param pdb: The Pdb instance.
1328
+
1329
+ Use in conftest plugins
1330
+ =======================
1331
+
1332
+ Any conftest plugin can implement this hook.
1333
+ """
vllm/lib/python3.10/site-packages/_pytest/junitxml.py ADDED
@@ -0,0 +1,697 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """Report test results in JUnit-XML format, for use with Jenkins and build
3
+ integration servers.
4
+
5
+ Based on initial code from Ross Lawley.
6
+
7
+ Output conforms to
8
+ https://github.com/jenkinsci/xunit-plugin/blob/master/src/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from datetime import datetime
14
+ from datetime import timezone
15
+ import functools
16
+ import os
17
+ import platform
18
+ import re
19
+ from typing import Callable
20
+ from typing import Match
21
+ import xml.etree.ElementTree as ET
22
+
23
+ from _pytest import nodes
24
+ from _pytest import timing
25
+ from _pytest._code.code import ExceptionRepr
26
+ from _pytest._code.code import ReprFileLocation
27
+ from _pytest.config import Config
28
+ from _pytest.config import filename_arg
29
+ from _pytest.config.argparsing import Parser
30
+ from _pytest.fixtures import FixtureRequest
31
+ from _pytest.reports import TestReport
32
+ from _pytest.stash import StashKey
33
+ from _pytest.terminal import TerminalReporter
34
+ import pytest
35
+
36
+
37
+ xml_key = StashKey["LogXML"]()
38
+
39
+
40
+ def bin_xml_escape(arg: object) -> str:
41
+ r"""Visually escape invalid XML characters.
42
+
43
+ For example, transforms
44
+ 'hello\aworld\b'
45
+ into
46
+ 'hello#x07world#x08'
47
+ Note that the #xABs are *not* XML escapes - missing the ampersand &#xAB.
48
+ The idea is to escape visually for the user rather than for XML itself.
49
+ """
50
+
51
+ def repl(matchobj: Match[str]) -> str:
52
+ i = ord(matchobj.group())
53
+ if i <= 0xFF:
54
+ return f"#x{i:02X}"
55
+ else:
56
+ return f"#x{i:04X}"
57
+
58
+ # The spec range of valid chars is:
59
+ # Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
60
+ # For an unknown(?) reason, we disallow #x7F (DEL) as well.
61
+ illegal_xml_re = (
62
+ "[^\u0009\u000a\u000d\u0020-\u007e\u0080-\ud7ff\ue000-\ufffd\u10000-\u10ffff]"
63
+ )
64
+ return re.sub(illegal_xml_re, repl, str(arg))
65
+
66
+
67
+ def merge_family(left, right) -> None:
68
+ result = {}
69
+ for kl, vl in left.items():
70
+ for kr, vr in right.items():
71
+ if not isinstance(vl, list):
72
+ raise TypeError(type(vl))
73
+ result[kl] = vl + vr
74
+ left.update(result)
75
+
76
+
77
+ families = {}
78
+ families["_base"] = {"testcase": ["classname", "name"]}
79
+ families["_base_legacy"] = {"testcase": ["file", "line", "url"]}
80
+
81
+ # xUnit 1.x inherits legacy attributes.
82
+ families["xunit1"] = families["_base"].copy()
83
+ merge_family(families["xunit1"], families["_base_legacy"])
84
+
85
+ # xUnit 2.x uses strict base attributes.
86
+ families["xunit2"] = families["_base"]
87
+
88
+
89
+ class _NodeReporter:
90
+ def __init__(self, nodeid: str | TestReport, xml: LogXML) -> None:
91
+ self.id = nodeid
92
+ self.xml = xml
93
+ self.add_stats = self.xml.add_stats
94
+ self.family = self.xml.family
95
+ self.duration = 0.0
96
+ self.properties: list[tuple[str, str]] = []
97
+ self.nodes: list[ET.Element] = []
98
+ self.attrs: dict[str, str] = {}
99
+
100
+ def append(self, node: ET.Element) -> None:
101
+ self.xml.add_stats(node.tag)
102
+ self.nodes.append(node)
103
+
104
+ def add_property(self, name: str, value: object) -> None:
105
+ self.properties.append((str(name), bin_xml_escape(value)))
106
+
107
+ def add_attribute(self, name: str, value: object) -> None:
108
+ self.attrs[str(name)] = bin_xml_escape(value)
109
+
110
+ def make_properties_node(self) -> ET.Element | None:
111
+ """Return a Junit node containing custom properties, if any."""
112
+ if self.properties:
113
+ properties = ET.Element("properties")
114
+ for name, value in self.properties:
115
+ properties.append(ET.Element("property", name=name, value=value))
116
+ return properties
117
+ return None
118
+
119
+ def record_testreport(self, testreport: TestReport) -> None:
120
+ names = mangle_test_address(testreport.nodeid)
121
+ existing_attrs = self.attrs
122
+ classnames = names[:-1]
123
+ if self.xml.prefix:
124
+ classnames.insert(0, self.xml.prefix)
125
+ attrs: dict[str, str] = {
126
+ "classname": ".".join(classnames),
127
+ "name": bin_xml_escape(names[-1]),
128
+ "file": testreport.location[0],
129
+ }
130
+ if testreport.location[1] is not None:
131
+ attrs["line"] = str(testreport.location[1])
132
+ if hasattr(testreport, "url"):
133
+ attrs["url"] = testreport.url
134
+ self.attrs = attrs
135
+ self.attrs.update(existing_attrs) # Restore any user-defined attributes.
136
+
137
+ # Preserve legacy testcase behavior.
138
+ if self.family == "xunit1":
139
+ return
140
+
141
+ # Filter out attributes not permitted by this test family.
142
+ # Including custom attributes because they are not valid here.
143
+ temp_attrs = {}
144
+ for key in self.attrs:
145
+ if key in families[self.family]["testcase"]:
146
+ temp_attrs[key] = self.attrs[key]
147
+ self.attrs = temp_attrs
148
+
149
+ def to_xml(self) -> ET.Element:
150
+ testcase = ET.Element("testcase", self.attrs, time=f"{self.duration:.3f}")
151
+ properties = self.make_properties_node()
152
+ if properties is not None:
153
+ testcase.append(properties)
154
+ testcase.extend(self.nodes)
155
+ return testcase
156
+
157
+ def _add_simple(self, tag: str, message: str, data: str | None = None) -> None:
158
+ node = ET.Element(tag, message=message)
159
+ node.text = bin_xml_escape(data)
160
+ self.append(node)
161
+
162
+ def write_captured_output(self, report: TestReport) -> None:
163
+ if not self.xml.log_passing_tests and report.passed:
164
+ return
165
+
166
+ content_out = report.capstdout
167
+ content_log = report.caplog
168
+ content_err = report.capstderr
169
+ if self.xml.logging == "no":
170
+ return
171
+ content_all = ""
172
+ if self.xml.logging in ["log", "all"]:
173
+ content_all = self._prepare_content(content_log, " Captured Log ")
174
+ if self.xml.logging in ["system-out", "out-err", "all"]:
175
+ content_all += self._prepare_content(content_out, " Captured Out ")
176
+ self._write_content(report, content_all, "system-out")
177
+ content_all = ""
178
+ if self.xml.logging in ["system-err", "out-err", "all"]:
179
+ content_all += self._prepare_content(content_err, " Captured Err ")
180
+ self._write_content(report, content_all, "system-err")
181
+ content_all = ""
182
+ if content_all:
183
+ self._write_content(report, content_all, "system-out")
184
+
185
+ def _prepare_content(self, content: str, header: str) -> str:
186
+ return "\n".join([header.center(80, "-"), content, ""])
187
+
188
+ def _write_content(self, report: TestReport, content: str, jheader: str) -> None:
189
+ tag = ET.Element(jheader)
190
+ tag.text = bin_xml_escape(content)
191
+ self.append(tag)
192
+
193
+ def append_pass(self, report: TestReport) -> None:
194
+ self.add_stats("passed")
195
+
196
+ def append_failure(self, report: TestReport) -> None:
197
+ # msg = str(report.longrepr.reprtraceback.extraline)
198
+ if hasattr(report, "wasxfail"):
199
+ self._add_simple("skipped", "xfail-marked test passes unexpectedly")
200
+ else:
201
+ assert report.longrepr is not None
202
+ reprcrash: ReprFileLocation | None = getattr(
203
+ report.longrepr, "reprcrash", None
204
+ )
205
+ if reprcrash is not None:
206
+ message = reprcrash.message
207
+ else:
208
+ message = str(report.longrepr)
209
+ message = bin_xml_escape(message)
210
+ self._add_simple("failure", message, str(report.longrepr))
211
+
212
+ def append_collect_error(self, report: TestReport) -> None:
213
+ # msg = str(report.longrepr.reprtraceback.extraline)
214
+ assert report.longrepr is not None
215
+ self._add_simple("error", "collection failure", str(report.longrepr))
216
+
217
+ def append_collect_skipped(self, report: TestReport) -> None:
218
+ self._add_simple("skipped", "collection skipped", str(report.longrepr))
219
+
220
+ def append_error(self, report: TestReport) -> None:
221
+ assert report.longrepr is not None
222
+ reprcrash: ReprFileLocation | None = getattr(report.longrepr, "reprcrash", None)
223
+ if reprcrash is not None:
224
+ reason = reprcrash.message
225
+ else:
226
+ reason = str(report.longrepr)
227
+
228
+ if report.when == "teardown":
229
+ msg = f'failed on teardown with "{reason}"'
230
+ else:
231
+ msg = f'failed on setup with "{reason}"'
232
+ self._add_simple("error", bin_xml_escape(msg), str(report.longrepr))
233
+
234
+ def append_skipped(self, report: TestReport) -> None:
235
+ if hasattr(report, "wasxfail"):
236
+ xfailreason = report.wasxfail
237
+ if xfailreason.startswith("reason: "):
238
+ xfailreason = xfailreason[8:]
239
+ xfailreason = bin_xml_escape(xfailreason)
240
+ skipped = ET.Element("skipped", type="pytest.xfail", message=xfailreason)
241
+ self.append(skipped)
242
+ else:
243
+ assert isinstance(report.longrepr, tuple)
244
+ filename, lineno, skipreason = report.longrepr
245
+ if skipreason.startswith("Skipped: "):
246
+ skipreason = skipreason[9:]
247
+ details = f"{filename}:{lineno}: {skipreason}"
248
+
249
+ skipped = ET.Element(
250
+ "skipped", type="pytest.skip", message=bin_xml_escape(skipreason)
251
+ )
252
+ skipped.text = bin_xml_escape(details)
253
+ self.append(skipped)
254
+ self.write_captured_output(report)
255
+
256
+ def finalize(self) -> None:
257
+ data = self.to_xml()
258
+ self.__dict__.clear()
259
+ # Type ignored because mypy doesn't like overriding a method.
260
+ # Also the return value doesn't match...
261
+ self.to_xml = lambda: data # type: ignore[method-assign]
262
+
263
+
264
+ def _warn_incompatibility_with_xunit2(
265
+ request: FixtureRequest, fixture_name: str
266
+ ) -> None:
267
+ """Emit a PytestWarning about the given fixture being incompatible with newer xunit revisions."""
268
+ from _pytest.warning_types import PytestWarning
269
+
270
+ xml = request.config.stash.get(xml_key, None)
271
+ if xml is not None and xml.family not in ("xunit1", "legacy"):
272
+ request.node.warn(
273
+ PytestWarning(
274
+ f"{fixture_name} is incompatible with junit_family '{xml.family}' (use 'legacy' or 'xunit1')"
275
+ )
276
+ )
277
+
278
+
279
+ @pytest.fixture
280
+ def record_property(request: FixtureRequest) -> Callable[[str, object], None]:
281
+ """Add extra properties to the calling test.
282
+
283
+ User properties become part of the test report and are available to the
284
+ configured reporters, like JUnit XML.
285
+
286
+ The fixture is callable with ``name, value``. The value is automatically
287
+ XML-encoded.
288
+
289
+ Example::
290
+
291
+ def test_function(record_property):
292
+ record_property("example_key", 1)
293
+ """
294
+ _warn_incompatibility_with_xunit2(request, "record_property")
295
+
296
+ def append_property(name: str, value: object) -> None:
297
+ request.node.user_properties.append((name, value))
298
+
299
+ return append_property
300
+
301
+
302
+ @pytest.fixture
303
+ def record_xml_attribute(request: FixtureRequest) -> Callable[[str, object], None]:
304
+ """Add extra xml attributes to the tag for the calling test.
305
+
306
+ The fixture is callable with ``name, value``. The value is
307
+ automatically XML-encoded.
308
+ """
309
+ from _pytest.warning_types import PytestExperimentalApiWarning
310
+
311
+ request.node.warn(
312
+ PytestExperimentalApiWarning("record_xml_attribute is an experimental feature")
313
+ )
314
+
315
+ _warn_incompatibility_with_xunit2(request, "record_xml_attribute")
316
+
317
+ # Declare noop
318
+ def add_attr_noop(name: str, value: object) -> None:
319
+ pass
320
+
321
+ attr_func = add_attr_noop
322
+
323
+ xml = request.config.stash.get(xml_key, None)
324
+ if xml is not None:
325
+ node_reporter = xml.node_reporter(request.node.nodeid)
326
+ attr_func = node_reporter.add_attribute
327
+
328
+ return attr_func
329
+
330
+
331
+ def _check_record_param_type(param: str, v: str) -> None:
332
+ """Used by record_testsuite_property to check that the given parameter name is of the proper
333
+ type."""
334
+ __tracebackhide__ = True
335
+ if not isinstance(v, str):
336
+ msg = "{param} parameter needs to be a string, but {g} given" # type: ignore[unreachable]
337
+ raise TypeError(msg.format(param=param, g=type(v).__name__))
338
+
339
+
340
+ @pytest.fixture(scope="session")
341
+ def record_testsuite_property(request: FixtureRequest) -> Callable[[str, object], None]:
342
+ """Record a new ``<property>`` tag as child of the root ``<testsuite>``.
343
+
344
+ This is suitable to writing global information regarding the entire test
345
+ suite, and is compatible with ``xunit2`` JUnit family.
346
+
347
+ This is a ``session``-scoped fixture which is called with ``(name, value)``. Example:
348
+
349
+ .. code-block:: python
350
+
351
+ def test_foo(record_testsuite_property):
352
+ record_testsuite_property("ARCH", "PPC")
353
+ record_testsuite_property("STORAGE_TYPE", "CEPH")
354
+
355
+ :param name:
356
+ The property name.
357
+ :param value:
358
+ The property value. Will be converted to a string.
359
+
360
+ .. warning::
361
+
362
+ Currently this fixture **does not work** with the
363
+ `pytest-xdist <https://github.com/pytest-dev/pytest-xdist>`__ plugin. See
364
+ :issue:`7767` for details.
365
+ """
366
+ __tracebackhide__ = True
367
+
368
+ def record_func(name: str, value: object) -> None:
369
+ """No-op function in case --junit-xml was not passed in the command-line."""
370
+ __tracebackhide__ = True
371
+ _check_record_param_type("name", name)
372
+
373
+ xml = request.config.stash.get(xml_key, None)
374
+ if xml is not None:
375
+ record_func = xml.add_global_property
376
+ return record_func
377
+
378
+
379
+ def pytest_addoption(parser: Parser) -> None:
380
+ group = parser.getgroup("terminal reporting")
381
+ group.addoption(
382
+ "--junitxml",
383
+ "--junit-xml",
384
+ action="store",
385
+ dest="xmlpath",
386
+ metavar="path",
387
+ type=functools.partial(filename_arg, optname="--junitxml"),
388
+ default=None,
389
+ help="Create junit-xml style report file at given path",
390
+ )
391
+ group.addoption(
392
+ "--junitprefix",
393
+ "--junit-prefix",
394
+ action="store",
395
+ metavar="str",
396
+ default=None,
397
+ help="Prepend prefix to classnames in junit-xml output",
398
+ )
399
+ parser.addini(
400
+ "junit_suite_name", "Test suite name for JUnit report", default="pytest"
401
+ )
402
+ parser.addini(
403
+ "junit_logging",
404
+ "Write captured log messages to JUnit report: "
405
+ "one of no|log|system-out|system-err|out-err|all",
406
+ default="no",
407
+ )
408
+ parser.addini(
409
+ "junit_log_passing_tests",
410
+ "Capture log information for passing tests to JUnit report: ",
411
+ type="bool",
412
+ default=True,
413
+ )
414
+ parser.addini(
415
+ "junit_duration_report",
416
+ "Duration time to report: one of total|call",
417
+ default="total",
418
+ ) # choices=['total', 'call'])
419
+ parser.addini(
420
+ "junit_family",
421
+ "Emit XML for schema: one of legacy|xunit1|xunit2",
422
+ default="xunit2",
423
+ )
424
+
425
+
426
+ def pytest_configure(config: Config) -> None:
427
+ xmlpath = config.option.xmlpath
428
+ # Prevent opening xmllog on worker nodes (xdist).
429
+ if xmlpath and not hasattr(config, "workerinput"):
430
+ junit_family = config.getini("junit_family")
431
+ config.stash[xml_key] = LogXML(
432
+ xmlpath,
433
+ config.option.junitprefix,
434
+ config.getini("junit_suite_name"),
435
+ config.getini("junit_logging"),
436
+ config.getini("junit_duration_report"),
437
+ junit_family,
438
+ config.getini("junit_log_passing_tests"),
439
+ )
440
+ config.pluginmanager.register(config.stash[xml_key])
441
+
442
+
443
+ def pytest_unconfigure(config: Config) -> None:
444
+ xml = config.stash.get(xml_key, None)
445
+ if xml:
446
+ del config.stash[xml_key]
447
+ config.pluginmanager.unregister(xml)
448
+
449
+
450
+ def mangle_test_address(address: str) -> list[str]:
451
+ path, possible_open_bracket, params = address.partition("[")
452
+ names = path.split("::")
453
+ # Convert file path to dotted path.
454
+ names[0] = names[0].replace(nodes.SEP, ".")
455
+ names[0] = re.sub(r"\.py$", "", names[0])
456
+ # Put any params back.
457
+ names[-1] += possible_open_bracket + params
458
+ return names
459
+
460
+
461
+ class LogXML:
462
+ def __init__(
463
+ self,
464
+ logfile,
465
+ prefix: str | None,
466
+ suite_name: str = "pytest",
467
+ logging: str = "no",
468
+ report_duration: str = "total",
469
+ family="xunit1",
470
+ log_passing_tests: bool = True,
471
+ ) -> None:
472
+ logfile = os.path.expanduser(os.path.expandvars(logfile))
473
+ self.logfile = os.path.normpath(os.path.abspath(logfile))
474
+ self.prefix = prefix
475
+ self.suite_name = suite_name
476
+ self.logging = logging
477
+ self.log_passing_tests = log_passing_tests
478
+ self.report_duration = report_duration
479
+ self.family = family
480
+ self.stats: dict[str, int] = dict.fromkeys(
481
+ ["error", "passed", "failure", "skipped"], 0
482
+ )
483
+ self.node_reporters: dict[tuple[str | TestReport, object], _NodeReporter] = {}
484
+ self.node_reporters_ordered: list[_NodeReporter] = []
485
+ self.global_properties: list[tuple[str, str]] = []
486
+
487
+ # List of reports that failed on call but teardown is pending.
488
+ self.open_reports: list[TestReport] = []
489
+ self.cnt_double_fail_tests = 0
490
+
491
+ # Replaces convenience family with real family.
492
+ if self.family == "legacy":
493
+ self.family = "xunit1"
494
+
495
+ def finalize(self, report: TestReport) -> None:
496
+ nodeid = getattr(report, "nodeid", report)
497
+ # Local hack to handle xdist report order.
498
+ workernode = getattr(report, "node", None)
499
+ reporter = self.node_reporters.pop((nodeid, workernode))
500
+
501
+ for propname, propvalue in report.user_properties:
502
+ reporter.add_property(propname, str(propvalue))
503
+
504
+ if reporter is not None:
505
+ reporter.finalize()
506
+
507
+ def node_reporter(self, report: TestReport | str) -> _NodeReporter:
508
+ nodeid: str | TestReport = getattr(report, "nodeid", report)
509
+ # Local hack to handle xdist report order.
510
+ workernode = getattr(report, "node", None)
511
+
512
+ key = nodeid, workernode
513
+
514
+ if key in self.node_reporters:
515
+ # TODO: breaks for --dist=each
516
+ return self.node_reporters[key]
517
+
518
+ reporter = _NodeReporter(nodeid, self)
519
+
520
+ self.node_reporters[key] = reporter
521
+ self.node_reporters_ordered.append(reporter)
522
+
523
+ return reporter
524
+
525
+ def add_stats(self, key: str) -> None:
526
+ if key in self.stats:
527
+ self.stats[key] += 1
528
+
529
+ def _opentestcase(self, report: TestReport) -> _NodeReporter:
530
+ reporter = self.node_reporter(report)
531
+ reporter.record_testreport(report)
532
+ return reporter
533
+
534
+ def pytest_runtest_logreport(self, report: TestReport) -> None:
535
+ """Handle a setup/call/teardown report, generating the appropriate
536
+ XML tags as necessary.
537
+
538
+ Note: due to plugins like xdist, this hook may be called in interlaced
539
+ order with reports from other nodes. For example:
540
+
541
+ Usual call order:
542
+ -> setup node1
543
+ -> call node1
544
+ -> teardown node1
545
+ -> setup node2
546
+ -> call node2
547
+ -> teardown node2
548
+
549
+ Possible call order in xdist:
550
+ -> setup node1
551
+ -> call node1
552
+ -> setup node2
553
+ -> call node2
554
+ -> teardown node2
555
+ -> teardown node1
556
+ """
557
+ close_report = None
558
+ if report.passed:
559
+ if report.when == "call": # ignore setup/teardown
560
+ reporter = self._opentestcase(report)
561
+ reporter.append_pass(report)
562
+ elif report.failed:
563
+ if report.when == "teardown":
564
+ # The following vars are needed when xdist plugin is used.
565
+ report_wid = getattr(report, "worker_id", None)
566
+ report_ii = getattr(report, "item_index", None)
567
+ close_report = next(
568
+ (
569
+ rep
570
+ for rep in self.open_reports
571
+ if (
572
+ rep.nodeid == report.nodeid
573
+ and getattr(rep, "item_index", None) == report_ii
574
+ and getattr(rep, "worker_id", None) == report_wid
575
+ )
576
+ ),
577
+ None,
578
+ )
579
+ if close_report:
580
+ # We need to open new testcase in case we have failure in
581
+ # call and error in teardown in order to follow junit
582
+ # schema.
583
+ self.finalize(close_report)
584
+ self.cnt_double_fail_tests += 1
585
+ reporter = self._opentestcase(report)
586
+ if report.when == "call":
587
+ reporter.append_failure(report)
588
+ self.open_reports.append(report)
589
+ if not self.log_passing_tests:
590
+ reporter.write_captured_output(report)
591
+ else:
592
+ reporter.append_error(report)
593
+ elif report.skipped:
594
+ reporter = self._opentestcase(report)
595
+ reporter.append_skipped(report)
596
+ self.update_testcase_duration(report)
597
+ if report.when == "teardown":
598
+ reporter = self._opentestcase(report)
599
+ reporter.write_captured_output(report)
600
+
601
+ self.finalize(report)
602
+ report_wid = getattr(report, "worker_id", None)
603
+ report_ii = getattr(report, "item_index", None)
604
+ close_report = next(
605
+ (
606
+ rep
607
+ for rep in self.open_reports
608
+ if (
609
+ rep.nodeid == report.nodeid
610
+ and getattr(rep, "item_index", None) == report_ii
611
+ and getattr(rep, "worker_id", None) == report_wid
612
+ )
613
+ ),
614
+ None,
615
+ )
616
+ if close_report:
617
+ self.open_reports.remove(close_report)
618
+
619
+ def update_testcase_duration(self, report: TestReport) -> None:
620
+ """Accumulate total duration for nodeid from given report and update
621
+ the Junit.testcase with the new total if already created."""
622
+ if self.report_duration in {"total", report.when}:
623
+ reporter = self.node_reporter(report)
624
+ reporter.duration += getattr(report, "duration", 0.0)
625
+
626
+ def pytest_collectreport(self, report: TestReport) -> None:
627
+ if not report.passed:
628
+ reporter = self._opentestcase(report)
629
+ if report.failed:
630
+ reporter.append_collect_error(report)
631
+ else:
632
+ reporter.append_collect_skipped(report)
633
+
634
+ def pytest_internalerror(self, excrepr: ExceptionRepr) -> None:
635
+ reporter = self.node_reporter("internal")
636
+ reporter.attrs.update(classname="pytest", name="internal")
637
+ reporter._add_simple("error", "internal error", str(excrepr))
638
+
639
+ def pytest_sessionstart(self) -> None:
640
+ self.suite_start_time = timing.time()
641
+
642
+ def pytest_sessionfinish(self) -> None:
643
+ dirname = os.path.dirname(os.path.abspath(self.logfile))
644
+ # exist_ok avoids filesystem race conditions between checking path existence and requesting creation
645
+ os.makedirs(dirname, exist_ok=True)
646
+
647
+ with open(self.logfile, "w", encoding="utf-8") as logfile:
648
+ suite_stop_time = timing.time()
649
+ suite_time_delta = suite_stop_time - self.suite_start_time
650
+
651
+ numtests = (
652
+ self.stats["passed"]
653
+ + self.stats["failure"]
654
+ + self.stats["skipped"]
655
+ + self.stats["error"]
656
+ - self.cnt_double_fail_tests
657
+ )
658
+ logfile.write('<?xml version="1.0" encoding="utf-8"?>')
659
+
660
+ suite_node = ET.Element(
661
+ "testsuite",
662
+ name=self.suite_name,
663
+ errors=str(self.stats["error"]),
664
+ failures=str(self.stats["failure"]),
665
+ skipped=str(self.stats["skipped"]),
666
+ tests=str(numtests),
667
+ time=f"{suite_time_delta:.3f}",
668
+ timestamp=datetime.fromtimestamp(self.suite_start_time, timezone.utc)
669
+ .astimezone()
670
+ .isoformat(),
671
+ hostname=platform.node(),
672
+ )
673
+ global_properties = self._get_global_properties_node()
674
+ if global_properties is not None:
675
+ suite_node.append(global_properties)
676
+ for node_reporter in self.node_reporters_ordered:
677
+ suite_node.append(node_reporter.to_xml())
678
+ testsuites = ET.Element("testsuites")
679
+ testsuites.append(suite_node)
680
+ logfile.write(ET.tostring(testsuites, encoding="unicode"))
681
+
682
+ def pytest_terminal_summary(self, terminalreporter: TerminalReporter) -> None:
683
+ terminalreporter.write_sep("-", f"generated xml file: {self.logfile}")
684
+
685
+ def add_global_property(self, name: str, value: object) -> None:
686
+ __tracebackhide__ = True
687
+ _check_record_param_type("name", name)
688
+ self.global_properties.append((name, bin_xml_escape(value)))
689
+
690
+ def _get_global_properties_node(self) -> ET.Element | None:
691
+ """Return a Junit node containing custom properties, if any."""
692
+ if self.global_properties:
693
+ properties = ET.Element("properties")
694
+ for name, value in self.global_properties:
695
+ properties.append(ET.Element("property", name=name, value=value))
696
+ return properties
697
+ return None
vllm/lib/python3.10/site-packages/_pytest/legacypath.py ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """Add backward compatibility support for the legacy py path type."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import dataclasses
7
+ from pathlib import Path
8
+ import shlex
9
+ import subprocess
10
+ from typing import Final
11
+ from typing import final
12
+ from typing import TYPE_CHECKING
13
+
14
+ from iniconfig import SectionWrapper
15
+
16
+ from _pytest.cacheprovider import Cache
17
+ from _pytest.compat import LEGACY_PATH
18
+ from _pytest.compat import legacy_path
19
+ from _pytest.config import Config
20
+ from _pytest.config import hookimpl
21
+ from _pytest.config import PytestPluginManager
22
+ from _pytest.deprecated import check_ispytest
23
+ from _pytest.fixtures import fixture
24
+ from _pytest.fixtures import FixtureRequest
25
+ from _pytest.main import Session
26
+ from _pytest.monkeypatch import MonkeyPatch
27
+ from _pytest.nodes import Collector
28
+ from _pytest.nodes import Item
29
+ from _pytest.nodes import Node
30
+ from _pytest.pytester import HookRecorder
31
+ from _pytest.pytester import Pytester
32
+ from _pytest.pytester import RunResult
33
+ from _pytest.terminal import TerminalReporter
34
+ from _pytest.tmpdir import TempPathFactory
35
+
36
+
37
+ if TYPE_CHECKING:
38
+ import pexpect
39
+
40
+
41
+ @final
42
+ class Testdir:
43
+ """
44
+ Similar to :class:`Pytester`, but this class works with legacy legacy_path objects instead.
45
+
46
+ All methods just forward to an internal :class:`Pytester` instance, converting results
47
+ to `legacy_path` objects as necessary.
48
+ """
49
+
50
+ __test__ = False
51
+
52
+ CLOSE_STDIN: Final = Pytester.CLOSE_STDIN
53
+ TimeoutExpired: Final = Pytester.TimeoutExpired
54
+
55
+ def __init__(self, pytester: Pytester, *, _ispytest: bool = False) -> None:
56
+ check_ispytest(_ispytest)
57
+ self._pytester = pytester
58
+
59
+ @property
60
+ def tmpdir(self) -> LEGACY_PATH:
61
+ """Temporary directory where tests are executed."""
62
+ return legacy_path(self._pytester.path)
63
+
64
+ @property
65
+ def test_tmproot(self) -> LEGACY_PATH:
66
+ return legacy_path(self._pytester._test_tmproot)
67
+
68
+ @property
69
+ def request(self):
70
+ return self._pytester._request
71
+
72
+ @property
73
+ def plugins(self):
74
+ return self._pytester.plugins
75
+
76
+ @plugins.setter
77
+ def plugins(self, plugins):
78
+ self._pytester.plugins = plugins
79
+
80
+ @property
81
+ def monkeypatch(self) -> MonkeyPatch:
82
+ return self._pytester._monkeypatch
83
+
84
+ def make_hook_recorder(self, pluginmanager) -> HookRecorder:
85
+ """See :meth:`Pytester.make_hook_recorder`."""
86
+ return self._pytester.make_hook_recorder(pluginmanager)
87
+
88
+ def chdir(self) -> None:
89
+ """See :meth:`Pytester.chdir`."""
90
+ return self._pytester.chdir()
91
+
92
+ def finalize(self) -> None:
93
+ return self._pytester._finalize()
94
+
95
+ def makefile(self, ext, *args, **kwargs) -> LEGACY_PATH:
96
+ """See :meth:`Pytester.makefile`."""
97
+ if ext and not ext.startswith("."):
98
+ # pytester.makefile is going to throw a ValueError in a way that
99
+ # testdir.makefile did not, because
100
+ # pathlib.Path is stricter suffixes than py.path
101
+ # This ext arguments is likely user error, but since testdir has
102
+ # allowed this, we will prepend "." as a workaround to avoid breaking
103
+ # testdir usage that worked before
104
+ ext = "." + ext
105
+ return legacy_path(self._pytester.makefile(ext, *args, **kwargs))
106
+
107
+ def makeconftest(self, source) -> LEGACY_PATH:
108
+ """See :meth:`Pytester.makeconftest`."""
109
+ return legacy_path(self._pytester.makeconftest(source))
110
+
111
+ def makeini(self, source) -> LEGACY_PATH:
112
+ """See :meth:`Pytester.makeini`."""
113
+ return legacy_path(self._pytester.makeini(source))
114
+
115
+ def getinicfg(self, source: str) -> SectionWrapper:
116
+ """See :meth:`Pytester.getinicfg`."""
117
+ return self._pytester.getinicfg(source)
118
+
119
+ def makepyprojecttoml(self, source) -> LEGACY_PATH:
120
+ """See :meth:`Pytester.makepyprojecttoml`."""
121
+ return legacy_path(self._pytester.makepyprojecttoml(source))
122
+
123
+ def makepyfile(self, *args, **kwargs) -> LEGACY_PATH:
124
+ """See :meth:`Pytester.makepyfile`."""
125
+ return legacy_path(self._pytester.makepyfile(*args, **kwargs))
126
+
127
+ def maketxtfile(self, *args, **kwargs) -> LEGACY_PATH:
128
+ """See :meth:`Pytester.maketxtfile`."""
129
+ return legacy_path(self._pytester.maketxtfile(*args, **kwargs))
130
+
131
+ def syspathinsert(self, path=None) -> None:
132
+ """See :meth:`Pytester.syspathinsert`."""
133
+ return self._pytester.syspathinsert(path)
134
+
135
+ def mkdir(self, name) -> LEGACY_PATH:
136
+ """See :meth:`Pytester.mkdir`."""
137
+ return legacy_path(self._pytester.mkdir(name))
138
+
139
+ def mkpydir(self, name) -> LEGACY_PATH:
140
+ """See :meth:`Pytester.mkpydir`."""
141
+ return legacy_path(self._pytester.mkpydir(name))
142
+
143
+ def copy_example(self, name=None) -> LEGACY_PATH:
144
+ """See :meth:`Pytester.copy_example`."""
145
+ return legacy_path(self._pytester.copy_example(name))
146
+
147
+ def getnode(self, config: Config, arg) -> Item | Collector | None:
148
+ """See :meth:`Pytester.getnode`."""
149
+ return self._pytester.getnode(config, arg)
150
+
151
+ def getpathnode(self, path):
152
+ """See :meth:`Pytester.getpathnode`."""
153
+ return self._pytester.getpathnode(path)
154
+
155
+ def genitems(self, colitems: list[Item | Collector]) -> list[Item]:
156
+ """See :meth:`Pytester.genitems`."""
157
+ return self._pytester.genitems(colitems)
158
+
159
+ def runitem(self, source):
160
+ """See :meth:`Pytester.runitem`."""
161
+ return self._pytester.runitem(source)
162
+
163
+ def inline_runsource(self, source, *cmdlineargs):
164
+ """See :meth:`Pytester.inline_runsource`."""
165
+ return self._pytester.inline_runsource(source, *cmdlineargs)
166
+
167
+ def inline_genitems(self, *args):
168
+ """See :meth:`Pytester.inline_genitems`."""
169
+ return self._pytester.inline_genitems(*args)
170
+
171
+ def inline_run(self, *args, plugins=(), no_reraise_ctrlc: bool = False):
172
+ """See :meth:`Pytester.inline_run`."""
173
+ return self._pytester.inline_run(
174
+ *args, plugins=plugins, no_reraise_ctrlc=no_reraise_ctrlc
175
+ )
176
+
177
+ def runpytest_inprocess(self, *args, **kwargs) -> RunResult:
178
+ """See :meth:`Pytester.runpytest_inprocess`."""
179
+ return self._pytester.runpytest_inprocess(*args, **kwargs)
180
+
181
+ def runpytest(self, *args, **kwargs) -> RunResult:
182
+ """See :meth:`Pytester.runpytest`."""
183
+ return self._pytester.runpytest(*args, **kwargs)
184
+
185
+ def parseconfig(self, *args) -> Config:
186
+ """See :meth:`Pytester.parseconfig`."""
187
+ return self._pytester.parseconfig(*args)
188
+
189
+ def parseconfigure(self, *args) -> Config:
190
+ """See :meth:`Pytester.parseconfigure`."""
191
+ return self._pytester.parseconfigure(*args)
192
+
193
+ def getitem(self, source, funcname="test_func"):
194
+ """See :meth:`Pytester.getitem`."""
195
+ return self._pytester.getitem(source, funcname)
196
+
197
+ def getitems(self, source):
198
+ """See :meth:`Pytester.getitems`."""
199
+ return self._pytester.getitems(source)
200
+
201
+ def getmodulecol(self, source, configargs=(), withinit=False):
202
+ """See :meth:`Pytester.getmodulecol`."""
203
+ return self._pytester.getmodulecol(
204
+ source, configargs=configargs, withinit=withinit
205
+ )
206
+
207
+ def collect_by_name(self, modcol: Collector, name: str) -> Item | Collector | None:
208
+ """See :meth:`Pytester.collect_by_name`."""
209
+ return self._pytester.collect_by_name(modcol, name)
210
+
211
+ def popen(
212
+ self,
213
+ cmdargs,
214
+ stdout=subprocess.PIPE,
215
+ stderr=subprocess.PIPE,
216
+ stdin=CLOSE_STDIN,
217
+ **kw,
218
+ ):
219
+ """See :meth:`Pytester.popen`."""
220
+ return self._pytester.popen(cmdargs, stdout, stderr, stdin, **kw)
221
+
222
+ def run(self, *cmdargs, timeout=None, stdin=CLOSE_STDIN) -> RunResult:
223
+ """See :meth:`Pytester.run`."""
224
+ return self._pytester.run(*cmdargs, timeout=timeout, stdin=stdin)
225
+
226
+ def runpython(self, script) -> RunResult:
227
+ """See :meth:`Pytester.runpython`."""
228
+ return self._pytester.runpython(script)
229
+
230
+ def runpython_c(self, command):
231
+ """See :meth:`Pytester.runpython_c`."""
232
+ return self._pytester.runpython_c(command)
233
+
234
+ def runpytest_subprocess(self, *args, timeout=None) -> RunResult:
235
+ """See :meth:`Pytester.runpytest_subprocess`."""
236
+ return self._pytester.runpytest_subprocess(*args, timeout=timeout)
237
+
238
+ def spawn_pytest(self, string: str, expect_timeout: float = 10.0) -> pexpect.spawn:
239
+ """See :meth:`Pytester.spawn_pytest`."""
240
+ return self._pytester.spawn_pytest(string, expect_timeout=expect_timeout)
241
+
242
+ def spawn(self, cmd: str, expect_timeout: float = 10.0) -> pexpect.spawn:
243
+ """See :meth:`Pytester.spawn`."""
244
+ return self._pytester.spawn(cmd, expect_timeout=expect_timeout)
245
+
246
+ def __repr__(self) -> str:
247
+ return f"<Testdir {self.tmpdir!r}>"
248
+
249
+ def __str__(self) -> str:
250
+ return str(self.tmpdir)
251
+
252
+
253
+ class LegacyTestdirPlugin:
254
+ @staticmethod
255
+ @fixture
256
+ def testdir(pytester: Pytester) -> Testdir:
257
+ """
258
+ Identical to :fixture:`pytester`, and provides an instance whose methods return
259
+ legacy ``LEGACY_PATH`` objects instead when applicable.
260
+
261
+ New code should avoid using :fixture:`testdir` in favor of :fixture:`pytester`.
262
+ """
263
+ return Testdir(pytester, _ispytest=True)
264
+
265
+
266
+ @final
267
+ @dataclasses.dataclass
268
+ class TempdirFactory:
269
+ """Backward compatibility wrapper that implements ``py.path.local``
270
+ for :class:`TempPathFactory`.
271
+
272
+ .. note::
273
+ These days, it is preferred to use ``tmp_path_factory``.
274
+
275
+ :ref:`About the tmpdir and tmpdir_factory fixtures<tmpdir and tmpdir_factory>`.
276
+
277
+ """
278
+
279
+ _tmppath_factory: TempPathFactory
280
+
281
+ def __init__(
282
+ self, tmppath_factory: TempPathFactory, *, _ispytest: bool = False
283
+ ) -> None:
284
+ check_ispytest(_ispytest)
285
+ self._tmppath_factory = tmppath_factory
286
+
287
+ def mktemp(self, basename: str, numbered: bool = True) -> LEGACY_PATH:
288
+ """Same as :meth:`TempPathFactory.mktemp`, but returns a ``py.path.local`` object."""
289
+ return legacy_path(self._tmppath_factory.mktemp(basename, numbered).resolve())
290
+
291
+ def getbasetemp(self) -> LEGACY_PATH:
292
+ """Same as :meth:`TempPathFactory.getbasetemp`, but returns a ``py.path.local`` object."""
293
+ return legacy_path(self._tmppath_factory.getbasetemp().resolve())
294
+
295
+
296
+ class LegacyTmpdirPlugin:
297
+ @staticmethod
298
+ @fixture(scope="session")
299
+ def tmpdir_factory(request: FixtureRequest) -> TempdirFactory:
300
+ """Return a :class:`pytest.TempdirFactory` instance for the test session."""
301
+ # Set dynamically by pytest_configure().
302
+ return request.config._tmpdirhandler # type: ignore
303
+
304
+ @staticmethod
305
+ @fixture
306
+ def tmpdir(tmp_path: Path) -> LEGACY_PATH:
307
+ """Return a temporary directory (as `legacy_path`_ object)
308
+ which is unique to each test function invocation.
309
+ The temporary directory is created as a subdirectory
310
+ of the base temporary directory, with configurable retention,
311
+ as discussed in :ref:`temporary directory location and retention`.
312
+
313
+ .. note::
314
+ These days, it is preferred to use ``tmp_path``.
315
+
316
+ :ref:`About the tmpdir and tmpdir_factory fixtures<tmpdir and tmpdir_factory>`.
317
+
318
+ .. _legacy_path: https://py.readthedocs.io/en/latest/path.html
319
+ """
320
+ return legacy_path(tmp_path)
321
+
322
+
323
+ def Cache_makedir(self: Cache, name: str) -> LEGACY_PATH:
324
+ """Return a directory path object with the given name.
325
+
326
+ Same as :func:`mkdir`, but returns a legacy py path instance.
327
+ """
328
+ return legacy_path(self.mkdir(name))
329
+
330
+
331
+ def FixtureRequest_fspath(self: FixtureRequest) -> LEGACY_PATH:
332
+ """(deprecated) The file system path of the test module which collected this test."""
333
+ return legacy_path(self.path)
334
+
335
+
336
+ def TerminalReporter_startdir(self: TerminalReporter) -> LEGACY_PATH:
337
+ """The directory from which pytest was invoked.
338
+
339
+ Prefer to use ``startpath`` which is a :class:`pathlib.Path`.
340
+
341
+ :type: LEGACY_PATH
342
+ """
343
+ return legacy_path(self.startpath)
344
+
345
+
346
+ def Config_invocation_dir(self: Config) -> LEGACY_PATH:
347
+ """The directory from which pytest was invoked.
348
+
349
+ Prefer to use :attr:`invocation_params.dir <InvocationParams.dir>`,
350
+ which is a :class:`pathlib.Path`.
351
+
352
+ :type: LEGACY_PATH
353
+ """
354
+ return legacy_path(str(self.invocation_params.dir))
355
+
356
+
357
+ def Config_rootdir(self: Config) -> LEGACY_PATH:
358
+ """The path to the :ref:`rootdir <rootdir>`.
359
+
360
+ Prefer to use :attr:`rootpath`, which is a :class:`pathlib.Path`.
361
+
362
+ :type: LEGACY_PATH
363
+ """
364
+ return legacy_path(str(self.rootpath))
365
+
366
+
367
+ def Config_inifile(self: Config) -> LEGACY_PATH | None:
368
+ """The path to the :ref:`configfile <configfiles>`.
369
+
370
+ Prefer to use :attr:`inipath`, which is a :class:`pathlib.Path`.
371
+
372
+ :type: Optional[LEGACY_PATH]
373
+ """
374
+ return legacy_path(str(self.inipath)) if self.inipath else None
375
+
376
+
377
+ def Session_startdir(self: Session) -> LEGACY_PATH:
378
+ """The path from which pytest was invoked.
379
+
380
+ Prefer to use ``startpath`` which is a :class:`pathlib.Path`.
381
+
382
+ :type: LEGACY_PATH
383
+ """
384
+ return legacy_path(self.startpath)
385
+
386
+
387
+ def Config__getini_unknown_type(self, name: str, type: str, value: str | list[str]):
388
+ if type == "pathlist":
389
+ # TODO: This assert is probably not valid in all cases.
390
+ assert self.inipath is not None
391
+ dp = self.inipath.parent
392
+ input_values = shlex.split(value) if isinstance(value, str) else value
393
+ return [legacy_path(str(dp / x)) for x in input_values]
394
+ else:
395
+ raise ValueError(f"unknown configuration type: {type}", value)
396
+
397
+
398
+ def Node_fspath(self: Node) -> LEGACY_PATH:
399
+ """(deprecated) returns a legacy_path copy of self.path"""
400
+ return legacy_path(self.path)
401
+
402
+
403
+ def Node_fspath_set(self: Node, value: LEGACY_PATH) -> None:
404
+ self.path = Path(value)
405
+
406
+
407
+ @hookimpl(tryfirst=True)
408
+ def pytest_load_initial_conftests(early_config: Config) -> None:
409
+ """Monkeypatch legacy path attributes in several classes, as early as possible."""
410
+ mp = MonkeyPatch()
411
+ early_config.add_cleanup(mp.undo)
412
+
413
+ # Add Cache.makedir().
414
+ mp.setattr(Cache, "makedir", Cache_makedir, raising=False)
415
+
416
+ # Add FixtureRequest.fspath property.
417
+ mp.setattr(FixtureRequest, "fspath", property(FixtureRequest_fspath), raising=False)
418
+
419
+ # Add TerminalReporter.startdir property.
420
+ mp.setattr(
421
+ TerminalReporter, "startdir", property(TerminalReporter_startdir), raising=False
422
+ )
423
+
424
+ # Add Config.{invocation_dir,rootdir,inifile} properties.
425
+ mp.setattr(Config, "invocation_dir", property(Config_invocation_dir), raising=False)
426
+ mp.setattr(Config, "rootdir", property(Config_rootdir), raising=False)
427
+ mp.setattr(Config, "inifile", property(Config_inifile), raising=False)
428
+
429
+ # Add Session.startdir property.
430
+ mp.setattr(Session, "startdir", property(Session_startdir), raising=False)
431
+
432
+ # Add pathlist configuration type.
433
+ mp.setattr(Config, "_getini_unknown_type", Config__getini_unknown_type)
434
+
435
+ # Add Node.fspath property.
436
+ mp.setattr(Node, "fspath", property(Node_fspath, Node_fspath_set), raising=False)
437
+
438
+
439
+ @hookimpl
440
+ def pytest_configure(config: Config) -> None:
441
+ """Installs the LegacyTmpdirPlugin if the ``tmpdir`` plugin is also installed."""
442
+ if config.pluginmanager.has_plugin("tmpdir"):
443
+ mp = MonkeyPatch()
444
+ config.add_cleanup(mp.undo)
445
+ # Create TmpdirFactory and attach it to the config object.
446
+ #
447
+ # This is to comply with existing plugins which expect the handler to be
448
+ # available at pytest_configure time, but ideally should be moved entirely
449
+ # to the tmpdir_factory session fixture.
450
+ try:
451
+ tmp_path_factory = config._tmp_path_factory # type: ignore[attr-defined]
452
+ except AttributeError:
453
+ # tmpdir plugin is blocked.
454
+ pass
455
+ else:
456
+ _tmpdirhandler = TempdirFactory(tmp_path_factory, _ispytest=True)
457
+ mp.setattr(config, "_tmpdirhandler", _tmpdirhandler, raising=False)
458
+
459
+ config.pluginmanager.register(LegacyTmpdirPlugin, "legacypath-tmpdir")
460
+
461
+
462
+ @hookimpl
463
+ def pytest_plugin_registered(plugin: object, manager: PytestPluginManager) -> None:
464
+ # pytester is not loaded by default and is commonly loaded from a conftest,
465
+ # so checking for it in `pytest_configure` is not enough.
466
+ is_pytester = plugin is manager.get_plugin("pytester")
467
+ if is_pytester and not manager.is_registered(LegacyTestdirPlugin):
468
+ manager.register(LegacyTestdirPlugin, "legacypath-pytester")
vllm/lib/python3.10/site-packages/_pytest/logging.py ADDED
@@ -0,0 +1,955 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """Access and control log capturing."""
3
+
4
+ from __future__ import annotations
5
+
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
+ import io
12
+ from io import StringIO
13
+ import logging
14
+ from logging import LogRecord
15
+ import os
16
+ from pathlib import Path
17
+ import re
18
+ from types import TracebackType
19
+ from typing import AbstractSet
20
+ from typing import Dict
21
+ from typing import final
22
+ from typing import Generator
23
+ from typing import Generic
24
+ from typing import List
25
+ from typing import Literal
26
+ from typing import Mapping
27
+ from typing import TYPE_CHECKING
28
+ from typing import TypeVar
29
+
30
+ from _pytest import nodes
31
+ from _pytest._io import TerminalWriter
32
+ from _pytest.capture import CaptureManager
33
+ from _pytest.config import _strtobool
34
+ from _pytest.config import Config
35
+ from _pytest.config import create_terminal_writer
36
+ from _pytest.config import hookimpl
37
+ from _pytest.config import UsageError
38
+ from _pytest.config.argparsing import Parser
39
+ from _pytest.deprecated import check_ispytest
40
+ from _pytest.fixtures import fixture
41
+ from _pytest.fixtures import FixtureRequest
42
+ from _pytest.main import Session
43
+ from _pytest.stash import StashKey
44
+ from _pytest.terminal import TerminalReporter
45
+
46
+
47
+ if TYPE_CHECKING:
48
+ logging_StreamHandler = logging.StreamHandler[StringIO]
49
+ else:
50
+ logging_StreamHandler = logging.StreamHandler
51
+
52
+ DEFAULT_LOG_FORMAT = "%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s"
53
+ DEFAULT_LOG_DATE_FORMAT = "%H:%M:%S"
54
+ _ANSI_ESCAPE_SEQ = re.compile(r"\x1b\[[\d;]+m")
55
+ caplog_handler_key = StashKey["LogCaptureHandler"]()
56
+ caplog_records_key = StashKey[Dict[str, List[logging.LogRecord]]]()
57
+
58
+
59
+ def _remove_ansi_escape_sequences(text: str) -> str:
60
+ return _ANSI_ESCAPE_SEQ.sub("", text)
61
+
62
+
63
+ class DatetimeFormatter(logging.Formatter):
64
+ """A logging formatter which formats record with
65
+ :func:`datetime.datetime.strftime` formatter instead of
66
+ :func:`time.strftime` in case of microseconds in format string.
67
+ """
68
+
69
+ def formatTime(self, record: LogRecord, datefmt: str | None = None) -> str:
70
+ if datefmt and "%f" in datefmt:
71
+ ct = self.converter(record.created)
72
+ tz = timezone(timedelta(seconds=ct.tm_gmtoff), ct.tm_zone)
73
+ # Construct `datetime.datetime` object from `struct_time`
74
+ # and msecs information from `record`
75
+ # Using int() instead of round() to avoid it exceeding 1_000_000 and causing a ValueError (#11861).
76
+ dt = datetime(*ct[0:6], microsecond=int(record.msecs * 1000), tzinfo=tz)
77
+ return dt.strftime(datefmt)
78
+ # Use `logging.Formatter` for non-microsecond formats
79
+ return super().formatTime(record, datefmt)
80
+
81
+
82
+ class ColoredLevelFormatter(DatetimeFormatter):
83
+ """A logging formatter which colorizes the %(levelname)..s part of the
84
+ log format passed to __init__."""
85
+
86
+ LOGLEVEL_COLOROPTS: Mapping[int, AbstractSet[str]] = {
87
+ logging.CRITICAL: {"red"},
88
+ logging.ERROR: {"red", "bold"},
89
+ logging.WARNING: {"yellow"},
90
+ logging.WARN: {"yellow"},
91
+ logging.INFO: {"green"},
92
+ logging.DEBUG: {"purple"},
93
+ logging.NOTSET: set(),
94
+ }
95
+ LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-.]?\d*(?:\.\d+)?s)")
96
+
97
+ def __init__(self, terminalwriter: TerminalWriter, *args, **kwargs) -> None:
98
+ super().__init__(*args, **kwargs)
99
+ self._terminalwriter = terminalwriter
100
+ self._original_fmt = self._style._fmt
101
+ self._level_to_fmt_mapping: dict[int, str] = {}
102
+
103
+ for level, color_opts in self.LOGLEVEL_COLOROPTS.items():
104
+ self.add_color_level(level, *color_opts)
105
+
106
+ def add_color_level(self, level: int, *color_opts: str) -> None:
107
+ """Add or update color opts for a log level.
108
+
109
+ :param level:
110
+ Log level to apply a style to, e.g. ``logging.INFO``.
111
+ :param color_opts:
112
+ ANSI escape sequence color options. Capitalized colors indicates
113
+ background color, i.e. ``'green', 'Yellow', 'bold'`` will give bold
114
+ green text on yellow background.
115
+
116
+ .. warning::
117
+ This is an experimental API.
118
+ """
119
+ assert self._fmt is not None
120
+ levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt)
121
+ if not levelname_fmt_match:
122
+ return
123
+ levelname_fmt = levelname_fmt_match.group()
124
+
125
+ formatted_levelname = levelname_fmt % {"levelname": logging.getLevelName(level)}
126
+
127
+ # add ANSI escape sequences around the formatted levelname
128
+ color_kwargs = {name: True for name in color_opts}
129
+ colorized_formatted_levelname = self._terminalwriter.markup(
130
+ formatted_levelname, **color_kwargs
131
+ )
132
+ self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub(
133
+ colorized_formatted_levelname, self._fmt
134
+ )
135
+
136
+ def format(self, record: logging.LogRecord) -> str:
137
+ fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt)
138
+ self._style._fmt = fmt
139
+ return super().format(record)
140
+
141
+
142
+ class PercentStyleMultiline(logging.PercentStyle):
143
+ """A logging style with special support for multiline messages.
144
+
145
+ If the message of a record consists of multiple lines, this style
146
+ formats the message as if each line were logged separately.
147
+ """
148
+
149
+ def __init__(self, fmt: str, auto_indent: int | str | bool | None) -> None:
150
+ super().__init__(fmt)
151
+ self._auto_indent = self._get_auto_indent(auto_indent)
152
+
153
+ @staticmethod
154
+ def _get_auto_indent(auto_indent_option: int | str | bool | None) -> int:
155
+ """Determine the current auto indentation setting.
156
+
157
+ Specify auto indent behavior (on/off/fixed) by passing in
158
+ extra={"auto_indent": [value]} to the call to logging.log() or
159
+ using a --log-auto-indent [value] command line or the
160
+ log_auto_indent [value] config option.
161
+
162
+ Default behavior is auto-indent off.
163
+
164
+ Using the string "True" or "on" or the boolean True as the value
165
+ turns auto indent on, using the string "False" or "off" or the
166
+ boolean False or the int 0 turns it off, and specifying a
167
+ positive integer fixes the indentation position to the value
168
+ specified.
169
+
170
+ Any other values for the option are invalid, and will silently be
171
+ converted to the default.
172
+
173
+ :param None|bool|int|str auto_indent_option:
174
+ User specified option for indentation from command line, config
175
+ or extra kwarg. Accepts int, bool or str. str option accepts the
176
+ same range of values as boolean config options, as well as
177
+ positive integers represented in str form.
178
+
179
+ :returns:
180
+ Indentation value, which can be
181
+ -1 (automatically determine indentation) or
182
+ 0 (auto-indent turned off) or
183
+ >0 (explicitly set indentation position).
184
+ """
185
+ if auto_indent_option is None:
186
+ return 0
187
+ elif isinstance(auto_indent_option, bool):
188
+ if auto_indent_option:
189
+ return -1
190
+ else:
191
+ return 0
192
+ elif isinstance(auto_indent_option, int):
193
+ return int(auto_indent_option)
194
+ elif isinstance(auto_indent_option, str):
195
+ try:
196
+ return int(auto_indent_option)
197
+ except ValueError:
198
+ pass
199
+ try:
200
+ if _strtobool(auto_indent_option):
201
+ return -1
202
+ except ValueError:
203
+ return 0
204
+
205
+ return 0
206
+
207
+ def format(self, record: logging.LogRecord) -> str:
208
+ if "\n" in record.message:
209
+ if hasattr(record, "auto_indent"):
210
+ # Passed in from the "extra={}" kwarg on the call to logging.log().
211
+ auto_indent = self._get_auto_indent(record.auto_indent)
212
+ else:
213
+ auto_indent = self._auto_indent
214
+
215
+ if auto_indent:
216
+ lines = record.message.splitlines()
217
+ formatted = self._fmt % {**record.__dict__, "message": lines[0]}
218
+
219
+ if auto_indent < 0:
220
+ indentation = _remove_ansi_escape_sequences(formatted).find(
221
+ lines[0]
222
+ )
223
+ else:
224
+ # Optimizes logging by allowing a fixed indentation.
225
+ indentation = auto_indent
226
+ lines[0] = formatted
227
+ return ("\n" + " " * indentation).join(lines)
228
+ return self._fmt % record.__dict__
229
+
230
+
231
+ def get_option_ini(config: Config, *names: str):
232
+ for name in names:
233
+ ret = config.getoption(name) # 'default' arg won't work as expected
234
+ if ret is None:
235
+ ret = config.getini(name)
236
+ if ret:
237
+ return ret
238
+
239
+
240
+ def pytest_addoption(parser: Parser) -> None:
241
+ """Add options to control log capturing."""
242
+ group = parser.getgroup("logging")
243
+
244
+ def add_option_ini(option, dest, default=None, type=None, **kwargs):
245
+ parser.addini(
246
+ dest, default=default, type=type, help="Default value for " + option
247
+ )
248
+ group.addoption(option, dest=dest, **kwargs)
249
+
250
+ add_option_ini(
251
+ "--log-level",
252
+ dest="log_level",
253
+ default=None,
254
+ metavar="LEVEL",
255
+ help=(
256
+ "Level of messages to catch/display."
257
+ " Not set by default, so it depends on the root/parent log handler's"
258
+ ' effective level, where it is "WARNING" by default.'
259
+ ),
260
+ )
261
+ add_option_ini(
262
+ "--log-format",
263
+ dest="log_format",
264
+ default=DEFAULT_LOG_FORMAT,
265
+ help="Log format used by the logging module",
266
+ )
267
+ add_option_ini(
268
+ "--log-date-format",
269
+ dest="log_date_format",
270
+ default=DEFAULT_LOG_DATE_FORMAT,
271
+ help="Log date format used by the logging module",
272
+ )
273
+ parser.addini(
274
+ "log_cli",
275
+ default=False,
276
+ type="bool",
277
+ help='Enable log display during test run (also known as "live logging")',
278
+ )
279
+ add_option_ini(
280
+ "--log-cli-level", dest="log_cli_level", default=None, help="CLI logging level"
281
+ )
282
+ add_option_ini(
283
+ "--log-cli-format",
284
+ dest="log_cli_format",
285
+ default=None,
286
+ help="Log format used by the logging module",
287
+ )
288
+ add_option_ini(
289
+ "--log-cli-date-format",
290
+ dest="log_cli_date_format",
291
+ default=None,
292
+ help="Log date format used by the logging module",
293
+ )
294
+ add_option_ini(
295
+ "--log-file",
296
+ dest="log_file",
297
+ default=None,
298
+ help="Path to a file when logging will be written to",
299
+ )
300
+ add_option_ini(
301
+ "--log-file-mode",
302
+ dest="log_file_mode",
303
+ default="w",
304
+ choices=["w", "a"],
305
+ help="Log file open mode",
306
+ )
307
+ add_option_ini(
308
+ "--log-file-level",
309
+ dest="log_file_level",
310
+ default=None,
311
+ help="Log file logging level",
312
+ )
313
+ add_option_ini(
314
+ "--log-file-format",
315
+ dest="log_file_format",
316
+ default=None,
317
+ help="Log format used by the logging module",
318
+ )
319
+ add_option_ini(
320
+ "--log-file-date-format",
321
+ dest="log_file_date_format",
322
+ default=None,
323
+ help="Log date format used by the logging module",
324
+ )
325
+ add_option_ini(
326
+ "--log-auto-indent",
327
+ dest="log_auto_indent",
328
+ default=None,
329
+ help="Auto-indent multiline messages passed to the logging module. Accepts true|on, false|off or an integer.",
330
+ )
331
+ group.addoption(
332
+ "--log-disable",
333
+ action="append",
334
+ default=[],
335
+ dest="logger_disable",
336
+ help="Disable a logger by name. Can be passed multiple times.",
337
+ )
338
+
339
+
340
+ _HandlerType = TypeVar("_HandlerType", bound=logging.Handler)
341
+
342
+
343
+ # Not using @contextmanager for performance reasons.
344
+ class catching_logs(Generic[_HandlerType]):
345
+ """Context manager that prepares the whole logging machinery properly."""
346
+
347
+ __slots__ = ("handler", "level", "orig_level")
348
+
349
+ def __init__(self, handler: _HandlerType, level: int | None = None) -> None:
350
+ self.handler = handler
351
+ self.level = level
352
+
353
+ def __enter__(self) -> _HandlerType:
354
+ root_logger = logging.getLogger()
355
+ if self.level is not None:
356
+ self.handler.setLevel(self.level)
357
+ root_logger.addHandler(self.handler)
358
+ if self.level is not None:
359
+ self.orig_level = root_logger.level
360
+ root_logger.setLevel(min(self.orig_level, self.level))
361
+ return self.handler
362
+
363
+ def __exit__(
364
+ self,
365
+ exc_type: type[BaseException] | None,
366
+ exc_val: BaseException | None,
367
+ exc_tb: TracebackType | None,
368
+ ) -> None:
369
+ root_logger = logging.getLogger()
370
+ if self.level is not None:
371
+ root_logger.setLevel(self.orig_level)
372
+ root_logger.removeHandler(self.handler)
373
+
374
+
375
+ class LogCaptureHandler(logging_StreamHandler):
376
+ """A logging handler that stores log records and the log text."""
377
+
378
+ def __init__(self) -> None:
379
+ """Create a new log handler."""
380
+ super().__init__(StringIO())
381
+ self.records: list[logging.LogRecord] = []
382
+
383
+ def emit(self, record: logging.LogRecord) -> None:
384
+ """Keep the log records in a list in addition to the log text."""
385
+ self.records.append(record)
386
+ super().emit(record)
387
+
388
+ def reset(self) -> None:
389
+ self.records = []
390
+ self.stream = StringIO()
391
+
392
+ def clear(self) -> None:
393
+ self.records.clear()
394
+ self.stream = StringIO()
395
+
396
+ def handleError(self, record: logging.LogRecord) -> None:
397
+ if logging.raiseExceptions:
398
+ # Fail the test if the log message is bad (emit failed).
399
+ # The default behavior of logging is to print "Logging error"
400
+ # to stderr with the call stack and some extra details.
401
+ # pytest wants to make such mistakes visible during testing.
402
+ raise # noqa: PLE0704
403
+
404
+
405
+ @final
406
+ class LogCaptureFixture:
407
+ """Provides access and control of log capturing."""
408
+
409
+ def __init__(self, item: nodes.Node, *, _ispytest: bool = False) -> None:
410
+ check_ispytest(_ispytest)
411
+ self._item = item
412
+ self._initial_handler_level: int | None = None
413
+ # Dict of log name -> log level.
414
+ self._initial_logger_levels: dict[str | None, int] = {}
415
+ self._initial_disabled_logging_level: int | None = None
416
+
417
+ def _finalize(self) -> None:
418
+ """Finalize the fixture.
419
+
420
+ This restores the log levels and the disabled logging levels changed by :meth:`set_level`.
421
+ """
422
+ # Restore log levels.
423
+ if self._initial_handler_level is not None:
424
+ self.handler.setLevel(self._initial_handler_level)
425
+ for logger_name, level in self._initial_logger_levels.items():
426
+ logger = logging.getLogger(logger_name)
427
+ logger.setLevel(level)
428
+ # Disable logging at the original disabled logging level.
429
+ if self._initial_disabled_logging_level is not None:
430
+ logging.disable(self._initial_disabled_logging_level)
431
+ self._initial_disabled_logging_level = None
432
+
433
+ @property
434
+ def handler(self) -> LogCaptureHandler:
435
+ """Get the logging handler used by the fixture."""
436
+ return self._item.stash[caplog_handler_key]
437
+
438
+ def get_records(
439
+ self, when: Literal["setup", "call", "teardown"]
440
+ ) -> list[logging.LogRecord]:
441
+ """Get the logging records for one of the possible test phases.
442
+
443
+ :param when:
444
+ Which test phase to obtain the records from.
445
+ Valid values are: "setup", "call" and "teardown".
446
+
447
+ :returns: The list of captured records at the given stage.
448
+
449
+ .. versionadded:: 3.4
450
+ """
451
+ return self._item.stash[caplog_records_key].get(when, [])
452
+
453
+ @property
454
+ def text(self) -> str:
455
+ """The formatted log text."""
456
+ return _remove_ansi_escape_sequences(self.handler.stream.getvalue())
457
+
458
+ @property
459
+ def records(self) -> list[logging.LogRecord]:
460
+ """The list of log records."""
461
+ return self.handler.records
462
+
463
+ @property
464
+ def record_tuples(self) -> list[tuple[str, int, str]]:
465
+ """A list of a stripped down version of log records intended
466
+ for use in assertion comparison.
467
+
468
+ The format of the tuple is:
469
+
470
+ (logger_name, log_level, message)
471
+ """
472
+ return [(r.name, r.levelno, r.getMessage()) for r in self.records]
473
+
474
+ @property
475
+ def messages(self) -> list[str]:
476
+ """A list of format-interpolated log messages.
477
+
478
+ Unlike 'records', which contains the format string and parameters for
479
+ interpolation, log messages in this list are all interpolated.
480
+
481
+ Unlike 'text', which contains the output from the handler, log
482
+ messages in this list are unadorned with levels, timestamps, etc,
483
+ making exact comparisons more reliable.
484
+
485
+ Note that traceback or stack info (from :func:`logging.exception` or
486
+ the `exc_info` or `stack_info` arguments to the logging functions) is
487
+ not included, as this is added by the formatter in the handler.
488
+
489
+ .. versionadded:: 3.7
490
+ """
491
+ return [r.getMessage() for r in self.records]
492
+
493
+ def clear(self) -> None:
494
+ """Reset the list of log records and the captured log text."""
495
+ self.handler.clear()
496
+
497
+ def _force_enable_logging(
498
+ self, level: int | str, logger_obj: logging.Logger
499
+ ) -> int:
500
+ """Enable the desired logging level if the global level was disabled via ``logging.disabled``.
501
+
502
+ Only enables logging levels greater than or equal to the requested ``level``.
503
+
504
+ Does nothing if the desired ``level`` wasn't disabled.
505
+
506
+ :param level:
507
+ The logger level caplog should capture.
508
+ All logging is enabled if a non-standard logging level string is supplied.
509
+ Valid level strings are in :data:`logging._nameToLevel`.
510
+ :param logger_obj: The logger object to check.
511
+
512
+ :return: The original disabled logging level.
513
+ """
514
+ original_disable_level: int = logger_obj.manager.disable
515
+
516
+ if isinstance(level, str):
517
+ # Try to translate the level string to an int for `logging.disable()`
518
+ level = logging.getLevelName(level)
519
+
520
+ if not isinstance(level, int):
521
+ # The level provided was not valid, so just un-disable all logging.
522
+ logging.disable(logging.NOTSET)
523
+ elif not logger_obj.isEnabledFor(level):
524
+ # Each level is `10` away from other levels.
525
+ # https://docs.python.org/3/library/logging.html#logging-levels
526
+ disable_level = max(level - 10, logging.NOTSET)
527
+ logging.disable(disable_level)
528
+
529
+ return original_disable_level
530
+
531
+ def set_level(self, level: int | str, logger: str | None = None) -> None:
532
+ """Set the threshold level of a logger for the duration of a test.
533
+
534
+ Logging messages which are less severe than this level will not be captured.
535
+
536
+ .. versionchanged:: 3.4
537
+ The levels of the loggers changed by this function will be
538
+ restored to their initial values at the end of the test.
539
+
540
+ Will enable the requested logging level if it was disabled via :func:`logging.disable`.
541
+
542
+ :param level: The level.
543
+ :param logger: The logger to update. If not given, the root logger.
544
+ """
545
+ logger_obj = logging.getLogger(logger)
546
+ # Save the original log-level to restore it during teardown.
547
+ self._initial_logger_levels.setdefault(logger, logger_obj.level)
548
+ logger_obj.setLevel(level)
549
+ if self._initial_handler_level is None:
550
+ self._initial_handler_level = self.handler.level
551
+ self.handler.setLevel(level)
552
+ initial_disabled_logging_level = self._force_enable_logging(level, logger_obj)
553
+ if self._initial_disabled_logging_level is None:
554
+ self._initial_disabled_logging_level = initial_disabled_logging_level
555
+
556
+ @contextmanager
557
+ def at_level(self, level: int | str, logger: str | None = None) -> Generator[None]:
558
+ """Context manager that sets the level for capturing of logs. After
559
+ the end of the 'with' statement the level is restored to its original
560
+ value.
561
+
562
+ Will enable the requested logging level if it was disabled via :func:`logging.disable`.
563
+
564
+ :param level: The level.
565
+ :param logger: The logger to update. If not given, the root logger.
566
+ """
567
+ logger_obj = logging.getLogger(logger)
568
+ orig_level = logger_obj.level
569
+ logger_obj.setLevel(level)
570
+ handler_orig_level = self.handler.level
571
+ self.handler.setLevel(level)
572
+ original_disable_level = self._force_enable_logging(level, logger_obj)
573
+ try:
574
+ yield
575
+ finally:
576
+ logger_obj.setLevel(orig_level)
577
+ self.handler.setLevel(handler_orig_level)
578
+ logging.disable(original_disable_level)
579
+
580
+ @contextmanager
581
+ def filtering(self, filter_: logging.Filter) -> Generator[None]:
582
+ """Context manager that temporarily adds the given filter to the caplog's
583
+ :meth:`handler` for the 'with' statement block, and removes that filter at the
584
+ end of the block.
585
+
586
+ :param filter_: A custom :class:`logging.Filter` object.
587
+
588
+ .. versionadded:: 7.5
589
+ """
590
+ self.handler.addFilter(filter_)
591
+ try:
592
+ yield
593
+ finally:
594
+ self.handler.removeFilter(filter_)
595
+
596
+
597
+ @fixture
598
+ def caplog(request: FixtureRequest) -> Generator[LogCaptureFixture]:
599
+ """Access and control log capturing.
600
+
601
+ Captured logs are available through the following properties/methods::
602
+
603
+ * caplog.messages -> list of format-interpolated log messages
604
+ * caplog.text -> string containing formatted log output
605
+ * caplog.records -> list of logging.LogRecord instances
606
+ * caplog.record_tuples -> list of (logger_name, level, message) tuples
607
+ * caplog.clear() -> clear captured records and formatted log output string
608
+ """
609
+ result = LogCaptureFixture(request.node, _ispytest=True)
610
+ yield result
611
+ result._finalize()
612
+
613
+
614
+ def get_log_level_for_setting(config: Config, *setting_names: str) -> int | None:
615
+ for setting_name in setting_names:
616
+ log_level = config.getoption(setting_name)
617
+ if log_level is None:
618
+ log_level = config.getini(setting_name)
619
+ if log_level:
620
+ break
621
+ else:
622
+ return None
623
+
624
+ if isinstance(log_level, str):
625
+ log_level = log_level.upper()
626
+ try:
627
+ return int(getattr(logging, log_level, log_level))
628
+ except ValueError as e:
629
+ # Python logging does not recognise this as a logging level
630
+ raise UsageError(
631
+ f"'{log_level}' is not recognized as a logging level name for "
632
+ f"'{setting_name}'. Please consider passing the "
633
+ "logging level num instead."
634
+ ) from e
635
+
636
+
637
+ # run after terminalreporter/capturemanager are configured
638
+ @hookimpl(trylast=True)
639
+ def pytest_configure(config: Config) -> None:
640
+ config.pluginmanager.register(LoggingPlugin(config), "logging-plugin")
641
+
642
+
643
+ class LoggingPlugin:
644
+ """Attaches to the logging module and captures log messages for each test."""
645
+
646
+ def __init__(self, config: Config) -> None:
647
+ """Create a new plugin to capture log messages.
648
+
649
+ The formatter can be safely shared across all handlers so
650
+ create a single one for the entire test session here.
651
+ """
652
+ self._config = config
653
+
654
+ # Report logging.
655
+ self.formatter = self._create_formatter(
656
+ get_option_ini(config, "log_format"),
657
+ get_option_ini(config, "log_date_format"),
658
+ get_option_ini(config, "log_auto_indent"),
659
+ )
660
+ self.log_level = get_log_level_for_setting(config, "log_level")
661
+ self.caplog_handler = LogCaptureHandler()
662
+ self.caplog_handler.setFormatter(self.formatter)
663
+ self.report_handler = LogCaptureHandler()
664
+ self.report_handler.setFormatter(self.formatter)
665
+
666
+ # File logging.
667
+ self.log_file_level = get_log_level_for_setting(
668
+ config, "log_file_level", "log_level"
669
+ )
670
+ log_file = get_option_ini(config, "log_file") or os.devnull
671
+ if log_file != os.devnull:
672
+ directory = os.path.dirname(os.path.abspath(log_file))
673
+ if not os.path.isdir(directory):
674
+ os.makedirs(directory)
675
+
676
+ self.log_file_mode = get_option_ini(config, "log_file_mode") or "w"
677
+ self.log_file_handler = _FileHandler(
678
+ log_file, mode=self.log_file_mode, encoding="UTF-8"
679
+ )
680
+ log_file_format = get_option_ini(config, "log_file_format", "log_format")
681
+ log_file_date_format = get_option_ini(
682
+ config, "log_file_date_format", "log_date_format"
683
+ )
684
+
685
+ log_file_formatter = DatetimeFormatter(
686
+ log_file_format, datefmt=log_file_date_format
687
+ )
688
+ self.log_file_handler.setFormatter(log_file_formatter)
689
+
690
+ # CLI/live logging.
691
+ self.log_cli_level = get_log_level_for_setting(
692
+ config, "log_cli_level", "log_level"
693
+ )
694
+ if self._log_cli_enabled():
695
+ terminal_reporter = config.pluginmanager.get_plugin("terminalreporter")
696
+ # Guaranteed by `_log_cli_enabled()`.
697
+ assert terminal_reporter is not None
698
+ capture_manager = config.pluginmanager.get_plugin("capturemanager")
699
+ # if capturemanager plugin is disabled, live logging still works.
700
+ self.log_cli_handler: (
701
+ _LiveLoggingStreamHandler | _LiveLoggingNullHandler
702
+ ) = _LiveLoggingStreamHandler(terminal_reporter, capture_manager)
703
+ else:
704
+ self.log_cli_handler = _LiveLoggingNullHandler()
705
+ log_cli_formatter = self._create_formatter(
706
+ get_option_ini(config, "log_cli_format", "log_format"),
707
+ get_option_ini(config, "log_cli_date_format", "log_date_format"),
708
+ get_option_ini(config, "log_auto_indent"),
709
+ )
710
+ self.log_cli_handler.setFormatter(log_cli_formatter)
711
+ self._disable_loggers(loggers_to_disable=config.option.logger_disable)
712
+
713
+ def _disable_loggers(self, loggers_to_disable: list[str]) -> None:
714
+ if not loggers_to_disable:
715
+ return
716
+
717
+ for name in loggers_to_disable:
718
+ logger = logging.getLogger(name)
719
+ logger.disabled = True
720
+
721
+ def _create_formatter(self, log_format, log_date_format, auto_indent):
722
+ # Color option doesn't exist if terminal plugin is disabled.
723
+ color = getattr(self._config.option, "color", "no")
724
+ if color != "no" and ColoredLevelFormatter.LEVELNAME_FMT_REGEX.search(
725
+ log_format
726
+ ):
727
+ formatter: logging.Formatter = ColoredLevelFormatter(
728
+ create_terminal_writer(self._config), log_format, log_date_format
729
+ )
730
+ else:
731
+ formatter = DatetimeFormatter(log_format, log_date_format)
732
+
733
+ formatter._style = PercentStyleMultiline(
734
+ formatter._style._fmt, auto_indent=auto_indent
735
+ )
736
+
737
+ return formatter
738
+
739
+ def set_log_path(self, fname: str) -> None:
740
+ """Set the filename parameter for Logging.FileHandler().
741
+
742
+ Creates parent directory if it does not exist.
743
+
744
+ .. warning::
745
+ This is an experimental API.
746
+ """
747
+ fpath = Path(fname)
748
+
749
+ if not fpath.is_absolute():
750
+ fpath = self._config.rootpath / fpath
751
+
752
+ if not fpath.parent.exists():
753
+ fpath.parent.mkdir(exist_ok=True, parents=True)
754
+
755
+ # https://github.com/python/mypy/issues/11193
756
+ stream: io.TextIOWrapper = fpath.open(mode=self.log_file_mode, encoding="UTF-8") # type: ignore[assignment]
757
+ old_stream = self.log_file_handler.setStream(stream)
758
+ if old_stream:
759
+ old_stream.close()
760
+
761
+ def _log_cli_enabled(self) -> bool:
762
+ """Return whether live logging is enabled."""
763
+ enabled = self._config.getoption(
764
+ "--log-cli-level"
765
+ ) is not None or self._config.getini("log_cli")
766
+ if not enabled:
767
+ return False
768
+
769
+ terminal_reporter = self._config.pluginmanager.get_plugin("terminalreporter")
770
+ if terminal_reporter is None:
771
+ # terminal reporter is disabled e.g. by pytest-xdist.
772
+ return False
773
+
774
+ return True
775
+
776
+ @hookimpl(wrapper=True, tryfirst=True)
777
+ def pytest_sessionstart(self) -> Generator[None]:
778
+ self.log_cli_handler.set_when("sessionstart")
779
+
780
+ with catching_logs(self.log_cli_handler, level=self.log_cli_level):
781
+ with catching_logs(self.log_file_handler, level=self.log_file_level):
782
+ return (yield)
783
+
784
+ @hookimpl(wrapper=True, tryfirst=True)
785
+ def pytest_collection(self) -> Generator[None]:
786
+ self.log_cli_handler.set_when("collection")
787
+
788
+ with catching_logs(self.log_cli_handler, level=self.log_cli_level):
789
+ with catching_logs(self.log_file_handler, level=self.log_file_level):
790
+ return (yield)
791
+
792
+ @hookimpl(wrapper=True)
793
+ def pytest_runtestloop(self, session: Session) -> Generator[None, object, object]:
794
+ if session.config.option.collectonly:
795
+ return (yield)
796
+
797
+ if self._log_cli_enabled() and self._config.get_verbosity() < 1:
798
+ # The verbose flag is needed to avoid messy test progress output.
799
+ self._config.option.verbose = 1
800
+
801
+ with catching_logs(self.log_cli_handler, level=self.log_cli_level):
802
+ with catching_logs(self.log_file_handler, level=self.log_file_level):
803
+ return (yield) # Run all the tests.
804
+
805
+ @hookimpl
806
+ def pytest_runtest_logstart(self) -> None:
807
+ self.log_cli_handler.reset()
808
+ self.log_cli_handler.set_when("start")
809
+
810
+ @hookimpl
811
+ def pytest_runtest_logreport(self) -> None:
812
+ self.log_cli_handler.set_when("logreport")
813
+
814
+ def _runtest_for(self, item: nodes.Item, when: str) -> Generator[None]:
815
+ """Implement the internals of the pytest_runtest_xxx() hooks."""
816
+ with catching_logs(
817
+ self.caplog_handler,
818
+ level=self.log_level,
819
+ ) as caplog_handler, catching_logs(
820
+ self.report_handler,
821
+ level=self.log_level,
822
+ ) as report_handler:
823
+ caplog_handler.reset()
824
+ report_handler.reset()
825
+ item.stash[caplog_records_key][when] = caplog_handler.records
826
+ item.stash[caplog_handler_key] = caplog_handler
827
+
828
+ try:
829
+ yield
830
+ finally:
831
+ log = report_handler.stream.getvalue().strip()
832
+ item.add_report_section(when, "log", log)
833
+
834
+ @hookimpl(wrapper=True)
835
+ def pytest_runtest_setup(self, item: nodes.Item) -> Generator[None]:
836
+ self.log_cli_handler.set_when("setup")
837
+
838
+ empty: dict[str, list[logging.LogRecord]] = {}
839
+ item.stash[caplog_records_key] = empty
840
+ yield from self._runtest_for(item, "setup")
841
+
842
+ @hookimpl(wrapper=True)
843
+ def pytest_runtest_call(self, item: nodes.Item) -> Generator[None]:
844
+ self.log_cli_handler.set_when("call")
845
+
846
+ yield from self._runtest_for(item, "call")
847
+
848
+ @hookimpl(wrapper=True)
849
+ def pytest_runtest_teardown(self, item: nodes.Item) -> Generator[None]:
850
+ self.log_cli_handler.set_when("teardown")
851
+
852
+ try:
853
+ yield from self._runtest_for(item, "teardown")
854
+ finally:
855
+ del item.stash[caplog_records_key]
856
+ del item.stash[caplog_handler_key]
857
+
858
+ @hookimpl
859
+ def pytest_runtest_logfinish(self) -> None:
860
+ self.log_cli_handler.set_when("finish")
861
+
862
+ @hookimpl(wrapper=True, tryfirst=True)
863
+ def pytest_sessionfinish(self) -> Generator[None]:
864
+ self.log_cli_handler.set_when("sessionfinish")
865
+
866
+ with catching_logs(self.log_cli_handler, level=self.log_cli_level):
867
+ with catching_logs(self.log_file_handler, level=self.log_file_level):
868
+ return (yield)
869
+
870
+ @hookimpl
871
+ def pytest_unconfigure(self) -> None:
872
+ # Close the FileHandler explicitly.
873
+ # (logging.shutdown might have lost the weakref?!)
874
+ self.log_file_handler.close()
875
+
876
+
877
+ class _FileHandler(logging.FileHandler):
878
+ """A logging FileHandler with pytest tweaks."""
879
+
880
+ def handleError(self, record: logging.LogRecord) -> None:
881
+ # Handled by LogCaptureHandler.
882
+ pass
883
+
884
+
885
+ class _LiveLoggingStreamHandler(logging_StreamHandler):
886
+ """A logging StreamHandler used by the live logging feature: it will
887
+ write a newline before the first log message in each test.
888
+
889
+ During live logging we must also explicitly disable stdout/stderr
890
+ capturing otherwise it will get captured and won't appear in the
891
+ terminal.
892
+ """
893
+
894
+ # Officially stream needs to be a IO[str], but TerminalReporter
895
+ # isn't. So force it.
896
+ stream: TerminalReporter = None # type: ignore
897
+
898
+ def __init__(
899
+ self,
900
+ terminal_reporter: TerminalReporter,
901
+ capture_manager: CaptureManager | None,
902
+ ) -> None:
903
+ super().__init__(stream=terminal_reporter) # type: ignore[arg-type]
904
+ self.capture_manager = capture_manager
905
+ self.reset()
906
+ self.set_when(None)
907
+ self._test_outcome_written = False
908
+
909
+ def reset(self) -> None:
910
+ """Reset the handler; should be called before the start of each test."""
911
+ self._first_record_emitted = False
912
+
913
+ def set_when(self, when: str | None) -> None:
914
+ """Prepare for the given test phase (setup/call/teardown)."""
915
+ self._when = when
916
+ self._section_name_shown = False
917
+ if when == "start":
918
+ self._test_outcome_written = False
919
+
920
+ def emit(self, record: logging.LogRecord) -> None:
921
+ ctx_manager = (
922
+ self.capture_manager.global_and_fixture_disabled()
923
+ if self.capture_manager
924
+ else nullcontext()
925
+ )
926
+ with ctx_manager:
927
+ if not self._first_record_emitted:
928
+ self.stream.write("\n")
929
+ self._first_record_emitted = True
930
+ elif self._when in ("teardown", "finish"):
931
+ if not self._test_outcome_written:
932
+ self._test_outcome_written = True
933
+ self.stream.write("\n")
934
+ if not self._section_name_shown and self._when:
935
+ self.stream.section("live log " + self._when, sep="-", bold=True)
936
+ self._section_name_shown = True
937
+ super().emit(record)
938
+
939
+ def handleError(self, record: logging.LogRecord) -> None:
940
+ # Handled by LogCaptureHandler.
941
+ pass
942
+
943
+
944
+ class _LiveLoggingNullHandler(logging.NullHandler):
945
+ """A logging handler used when live logging is disabled."""
946
+
947
+ def reset(self) -> None:
948
+ pass
949
+
950
+ def set_when(self, when: str) -> None:
951
+ pass
952
+
953
+ def handleError(self, record: logging.LogRecord) -> None:
954
+ # Handled by LogCaptureHandler.
955
+ pass
vllm/lib/python3.10/site-packages/_pytest/main.py ADDED
@@ -0,0 +1,1072 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Core implementation of the testing process: init, session, runtest loop."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import dataclasses
7
+ import fnmatch
8
+ import functools
9
+ import importlib
10
+ import importlib.util
11
+ import os
12
+ from pathlib import Path
13
+ import sys
14
+ from typing import AbstractSet
15
+ from typing import Callable
16
+ from typing import Dict
17
+ from typing import final
18
+ from typing import Iterable
19
+ from typing import Iterator
20
+ from typing import Literal
21
+ from typing import overload
22
+ from typing import Sequence
23
+ from typing import TYPE_CHECKING
24
+ import warnings
25
+
26
+ import pluggy
27
+
28
+ from _pytest import nodes
29
+ import _pytest._code
30
+ from _pytest.config import Config
31
+ from _pytest.config import directory_arg
32
+ from _pytest.config import ExitCode
33
+ from _pytest.config import hookimpl
34
+ from _pytest.config import PytestPluginManager
35
+ from _pytest.config import UsageError
36
+ from _pytest.config.argparsing import Parser
37
+ from _pytest.config.compat import PathAwareHookProxy
38
+ from _pytest.outcomes import exit
39
+ from _pytest.pathlib import absolutepath
40
+ from _pytest.pathlib import bestrelpath
41
+ from _pytest.pathlib import fnmatch_ex
42
+ from _pytest.pathlib import safe_exists
43
+ from _pytest.pathlib import scandir
44
+ from _pytest.reports import CollectReport
45
+ from _pytest.reports import TestReport
46
+ from _pytest.runner import collect_one_node
47
+ from _pytest.runner import SetupState
48
+ from _pytest.warning_types import PytestWarning
49
+
50
+
51
+ if TYPE_CHECKING:
52
+ from typing_extensions import Self
53
+
54
+ from _pytest.fixtures import FixtureManager
55
+
56
+
57
+ def pytest_addoption(parser: Parser) -> None:
58
+ parser.addini(
59
+ "norecursedirs",
60
+ "Directory patterns to avoid for recursion",
61
+ type="args",
62
+ default=[
63
+ "*.egg",
64
+ ".*",
65
+ "_darcs",
66
+ "build",
67
+ "CVS",
68
+ "dist",
69
+ "node_modules",
70
+ "venv",
71
+ "{arch}",
72
+ ],
73
+ )
74
+ parser.addini(
75
+ "testpaths",
76
+ "Directories to search for tests when no files or directories are given on the "
77
+ "command line",
78
+ type="args",
79
+ default=[],
80
+ )
81
+ group = parser.getgroup("general", "Running and selection options")
82
+ group._addoption(
83
+ "-x",
84
+ "--exitfirst",
85
+ action="store_const",
86
+ dest="maxfail",
87
+ const=1,
88
+ help="Exit instantly on first error or failed test",
89
+ )
90
+ group = parser.getgroup("pytest-warnings")
91
+ group.addoption(
92
+ "-W",
93
+ "--pythonwarnings",
94
+ action="append",
95
+ help="Set which warnings to report, see -W option of Python itself",
96
+ )
97
+ parser.addini(
98
+ "filterwarnings",
99
+ type="linelist",
100
+ help="Each line specifies a pattern for "
101
+ "warnings.filterwarnings. "
102
+ "Processed after -W/--pythonwarnings.",
103
+ )
104
+ group._addoption(
105
+ "--maxfail",
106
+ metavar="num",
107
+ action="store",
108
+ type=int,
109
+ dest="maxfail",
110
+ default=0,
111
+ help="Exit after first num failures or errors",
112
+ )
113
+ group._addoption(
114
+ "--strict-config",
115
+ action="store_true",
116
+ help="Any warnings encountered while parsing the `pytest` section of the "
117
+ "configuration file raise errors",
118
+ )
119
+ group._addoption(
120
+ "--strict-markers",
121
+ action="store_true",
122
+ help="Markers not registered in the `markers` section of the configuration "
123
+ "file raise errors",
124
+ )
125
+ group._addoption(
126
+ "--strict",
127
+ action="store_true",
128
+ help="(Deprecated) alias to --strict-markers",
129
+ )
130
+ group._addoption(
131
+ "-c",
132
+ "--config-file",
133
+ metavar="FILE",
134
+ type=str,
135
+ dest="inifilename",
136
+ help="Load configuration from `FILE` instead of trying to locate one of the "
137
+ "implicit configuration files.",
138
+ )
139
+ group._addoption(
140
+ "--continue-on-collection-errors",
141
+ action="store_true",
142
+ default=False,
143
+ dest="continue_on_collection_errors",
144
+ help="Force test execution even if collection errors occur",
145
+ )
146
+ group._addoption(
147
+ "--rootdir",
148
+ action="store",
149
+ dest="rootdir",
150
+ help="Define root directory for tests. Can be relative path: 'root_dir', './root_dir', "
151
+ "'root_dir/another_dir/'; absolute path: '/home/user/root_dir'; path with variables: "
152
+ "'$HOME/root_dir'.",
153
+ )
154
+
155
+ group = parser.getgroup("collect", "collection")
156
+ group.addoption(
157
+ "--collectonly",
158
+ "--collect-only",
159
+ "--co",
160
+ action="store_true",
161
+ help="Only collect tests, don't execute them",
162
+ )
163
+ group.addoption(
164
+ "--pyargs",
165
+ action="store_true",
166
+ help="Try to interpret all arguments as Python packages",
167
+ )
168
+ group.addoption(
169
+ "--ignore",
170
+ action="append",
171
+ metavar="path",
172
+ help="Ignore path during collection (multi-allowed)",
173
+ )
174
+ group.addoption(
175
+ "--ignore-glob",
176
+ action="append",
177
+ metavar="path",
178
+ help="Ignore path pattern during collection (multi-allowed)",
179
+ )
180
+ group.addoption(
181
+ "--deselect",
182
+ action="append",
183
+ metavar="nodeid_prefix",
184
+ help="Deselect item (via node id prefix) during collection (multi-allowed)",
185
+ )
186
+ group.addoption(
187
+ "--confcutdir",
188
+ dest="confcutdir",
189
+ default=None,
190
+ metavar="dir",
191
+ type=functools.partial(directory_arg, optname="--confcutdir"),
192
+ help="Only load conftest.py's relative to specified dir",
193
+ )
194
+ group.addoption(
195
+ "--noconftest",
196
+ action="store_true",
197
+ dest="noconftest",
198
+ default=False,
199
+ help="Don't load any conftest.py files",
200
+ )
201
+ group.addoption(
202
+ "--keepduplicates",
203
+ "--keep-duplicates",
204
+ action="store_true",
205
+ dest="keepduplicates",
206
+ default=False,
207
+ help="Keep duplicate tests",
208
+ )
209
+ group.addoption(
210
+ "--collect-in-virtualenv",
211
+ action="store_true",
212
+ dest="collect_in_virtualenv",
213
+ default=False,
214
+ help="Don't ignore tests in a local virtualenv directory",
215
+ )
216
+ group.addoption(
217
+ "--import-mode",
218
+ default="prepend",
219
+ choices=["prepend", "append", "importlib"],
220
+ dest="importmode",
221
+ help="Prepend/append to sys.path when importing test modules and conftest "
222
+ "files. Default: prepend.",
223
+ )
224
+ parser.addini(
225
+ "consider_namespace_packages",
226
+ type="bool",
227
+ default=False,
228
+ help="Consider namespace packages when resolving module names during import",
229
+ )
230
+
231
+ group = parser.getgroup("debugconfig", "test session debugging and configuration")
232
+ group.addoption(
233
+ "--basetemp",
234
+ dest="basetemp",
235
+ default=None,
236
+ type=validate_basetemp,
237
+ metavar="dir",
238
+ help=(
239
+ "Base temporary directory for this test run. "
240
+ "(Warning: this directory is removed if it exists.)"
241
+ ),
242
+ )
243
+
244
+
245
+ def validate_basetemp(path: str) -> str:
246
+ # GH 7119
247
+ msg = "basetemp must not be empty, the current working directory or any parent directory of it"
248
+
249
+ # empty path
250
+ if not path:
251
+ raise argparse.ArgumentTypeError(msg)
252
+
253
+ def is_ancestor(base: Path, query: Path) -> bool:
254
+ """Return whether query is an ancestor of base."""
255
+ if base == query:
256
+ return True
257
+ return query in base.parents
258
+
259
+ # check if path is an ancestor of cwd
260
+ if is_ancestor(Path.cwd(), Path(path).absolute()):
261
+ raise argparse.ArgumentTypeError(msg)
262
+
263
+ # check symlinks for ancestors
264
+ if is_ancestor(Path.cwd().resolve(), Path(path).resolve()):
265
+ raise argparse.ArgumentTypeError(msg)
266
+
267
+ return path
268
+
269
+
270
+ def wrap_session(
271
+ config: Config, doit: Callable[[Config, Session], int | ExitCode | None]
272
+ ) -> int | ExitCode:
273
+ """Skeleton command line program."""
274
+ session = Session.from_config(config)
275
+ session.exitstatus = ExitCode.OK
276
+ initstate = 0
277
+ try:
278
+ try:
279
+ config._do_configure()
280
+ initstate = 1
281
+ config.hook.pytest_sessionstart(session=session)
282
+ initstate = 2
283
+ session.exitstatus = doit(config, session) or 0
284
+ except UsageError:
285
+ session.exitstatus = ExitCode.USAGE_ERROR
286
+ raise
287
+ except Failed:
288
+ session.exitstatus = ExitCode.TESTS_FAILED
289
+ except (KeyboardInterrupt, exit.Exception):
290
+ excinfo = _pytest._code.ExceptionInfo.from_current()
291
+ exitstatus: int | ExitCode = ExitCode.INTERRUPTED
292
+ if isinstance(excinfo.value, exit.Exception):
293
+ if excinfo.value.returncode is not None:
294
+ exitstatus = excinfo.value.returncode
295
+ if initstate < 2:
296
+ sys.stderr.write(f"{excinfo.typename}: {excinfo.value.msg}\n")
297
+ config.hook.pytest_keyboard_interrupt(excinfo=excinfo)
298
+ session.exitstatus = exitstatus
299
+ except BaseException:
300
+ session.exitstatus = ExitCode.INTERNAL_ERROR
301
+ excinfo = _pytest._code.ExceptionInfo.from_current()
302
+ try:
303
+ config.notify_exception(excinfo, config.option)
304
+ except exit.Exception as exc:
305
+ if exc.returncode is not None:
306
+ session.exitstatus = exc.returncode
307
+ sys.stderr.write(f"{type(exc).__name__}: {exc}\n")
308
+ else:
309
+ if isinstance(excinfo.value, SystemExit):
310
+ sys.stderr.write("mainloop: caught unexpected SystemExit!\n")
311
+
312
+ finally:
313
+ # Explicitly break reference cycle.
314
+ excinfo = None # type: ignore
315
+ os.chdir(session.startpath)
316
+ if initstate >= 2:
317
+ try:
318
+ config.hook.pytest_sessionfinish(
319
+ session=session, exitstatus=session.exitstatus
320
+ )
321
+ except exit.Exception as exc:
322
+ if exc.returncode is not None:
323
+ session.exitstatus = exc.returncode
324
+ sys.stderr.write(f"{type(exc).__name__}: {exc}\n")
325
+ config._ensure_unconfigure()
326
+ return session.exitstatus
327
+
328
+
329
+ def pytest_cmdline_main(config: Config) -> int | ExitCode:
330
+ return wrap_session(config, _main)
331
+
332
+
333
+ def _main(config: Config, session: Session) -> int | ExitCode | None:
334
+ """Default command line protocol for initialization, session,
335
+ running tests and reporting."""
336
+ config.hook.pytest_collection(session=session)
337
+ config.hook.pytest_runtestloop(session=session)
338
+
339
+ if session.testsfailed:
340
+ return ExitCode.TESTS_FAILED
341
+ elif session.testscollected == 0:
342
+ return ExitCode.NO_TESTS_COLLECTED
343
+ return None
344
+
345
+
346
+ def pytest_collection(session: Session) -> None:
347
+ session.perform_collect()
348
+
349
+
350
+ def pytest_runtestloop(session: Session) -> bool:
351
+ if session.testsfailed and not session.config.option.continue_on_collection_errors:
352
+ raise session.Interrupted(
353
+ "%d error%s during collection"
354
+ % (session.testsfailed, "s" if session.testsfailed != 1 else "")
355
+ )
356
+
357
+ if session.config.option.collectonly:
358
+ return True
359
+
360
+ for i, item in enumerate(session.items):
361
+ nextitem = session.items[i + 1] if i + 1 < len(session.items) else None
362
+ item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem)
363
+ if session.shouldfail:
364
+ raise session.Failed(session.shouldfail)
365
+ if session.shouldstop:
366
+ raise session.Interrupted(session.shouldstop)
367
+ return True
368
+
369
+
370
+ def _in_venv(path: Path) -> bool:
371
+ """Attempt to detect if ``path`` is the root of a Virtual Environment by
372
+ checking for the existence of the pyvenv.cfg file.
373
+
374
+ [https://peps.python.org/pep-0405/]
375
+
376
+ For regression protection we also check for conda environments that do not include pyenv.cfg yet --
377
+ https://github.com/conda/conda/issues/13337 is the conda issue tracking adding pyenv.cfg.
378
+
379
+ Checking for the `conda-meta/history` file per https://github.com/pytest-dev/pytest/issues/12652#issuecomment-2246336902.
380
+
381
+ """
382
+ try:
383
+ return (
384
+ path.joinpath("pyvenv.cfg").is_file()
385
+ or path.joinpath("conda-meta", "history").is_file()
386
+ )
387
+ except OSError:
388
+ return False
389
+
390
+
391
+ def pytest_ignore_collect(collection_path: Path, config: Config) -> bool | None:
392
+ if collection_path.name == "__pycache__":
393
+ return True
394
+
395
+ ignore_paths = config._getconftest_pathlist(
396
+ "collect_ignore", path=collection_path.parent
397
+ )
398
+ ignore_paths = ignore_paths or []
399
+ excludeopt = config.getoption("ignore")
400
+ if excludeopt:
401
+ ignore_paths.extend(absolutepath(x) for x in excludeopt)
402
+
403
+ if collection_path in ignore_paths:
404
+ return True
405
+
406
+ ignore_globs = config._getconftest_pathlist(
407
+ "collect_ignore_glob", path=collection_path.parent
408
+ )
409
+ ignore_globs = ignore_globs or []
410
+ excludeglobopt = config.getoption("ignore_glob")
411
+ if excludeglobopt:
412
+ ignore_globs.extend(absolutepath(x) for x in excludeglobopt)
413
+
414
+ if any(fnmatch.fnmatch(str(collection_path), str(glob)) for glob in ignore_globs):
415
+ return True
416
+
417
+ allow_in_venv = config.getoption("collect_in_virtualenv")
418
+ if not allow_in_venv and _in_venv(collection_path):
419
+ return True
420
+
421
+ if collection_path.is_dir():
422
+ norecursepatterns = config.getini("norecursedirs")
423
+ if any(fnmatch_ex(pat, collection_path) for pat in norecursepatterns):
424
+ return True
425
+
426
+ return None
427
+
428
+
429
+ def pytest_collect_directory(
430
+ path: Path, parent: nodes.Collector
431
+ ) -> nodes.Collector | None:
432
+ return Dir.from_parent(parent, path=path)
433
+
434
+
435
+ def pytest_collection_modifyitems(items: list[nodes.Item], config: Config) -> None:
436
+ deselect_prefixes = tuple(config.getoption("deselect") or [])
437
+ if not deselect_prefixes:
438
+ return
439
+
440
+ remaining = []
441
+ deselected = []
442
+ for colitem in items:
443
+ if colitem.nodeid.startswith(deselect_prefixes):
444
+ deselected.append(colitem)
445
+ else:
446
+ remaining.append(colitem)
447
+
448
+ if deselected:
449
+ config.hook.pytest_deselected(items=deselected)
450
+ items[:] = remaining
451
+
452
+
453
+ class FSHookProxy:
454
+ def __init__(
455
+ self,
456
+ pm: PytestPluginManager,
457
+ remove_mods: AbstractSet[object],
458
+ ) -> None:
459
+ self.pm = pm
460
+ self.remove_mods = remove_mods
461
+
462
+ def __getattr__(self, name: str) -> pluggy.HookCaller:
463
+ x = self.pm.subset_hook_caller(name, remove_plugins=self.remove_mods)
464
+ self.__dict__[name] = x
465
+ return x
466
+
467
+
468
+ class Interrupted(KeyboardInterrupt):
469
+ """Signals that the test run was interrupted."""
470
+
471
+ __module__ = "builtins" # For py3.
472
+
473
+
474
+ class Failed(Exception):
475
+ """Signals a stop as failed test run."""
476
+
477
+
478
+ @dataclasses.dataclass
479
+ class _bestrelpath_cache(Dict[Path, str]):
480
+ __slots__ = ("path",)
481
+
482
+ path: Path
483
+
484
+ def __missing__(self, path: Path) -> str:
485
+ r = bestrelpath(self.path, path)
486
+ self[path] = r
487
+ return r
488
+
489
+
490
+ @final
491
+ class Dir(nodes.Directory):
492
+ """Collector of files in a file system directory.
493
+
494
+ .. versionadded:: 8.0
495
+
496
+ .. note::
497
+
498
+ Python directories with an `__init__.py` file are instead collected by
499
+ :class:`~pytest.Package` by default. Both are :class:`~pytest.Directory`
500
+ collectors.
501
+ """
502
+
503
+ @classmethod
504
+ def from_parent( # type: ignore[override]
505
+ cls,
506
+ parent: nodes.Collector,
507
+ *,
508
+ path: Path,
509
+ ) -> Self:
510
+ """The public constructor.
511
+
512
+ :param parent: The parent collector of this Dir.
513
+ :param path: The directory's path.
514
+ :type path: pathlib.Path
515
+ """
516
+ return super().from_parent(parent=parent, path=path)
517
+
518
+ def collect(self) -> Iterable[nodes.Item | nodes.Collector]:
519
+ config = self.config
520
+ col: nodes.Collector | None
521
+ cols: Sequence[nodes.Collector]
522
+ ihook = self.ihook
523
+ for direntry in scandir(self.path):
524
+ if direntry.is_dir():
525
+ path = Path(direntry.path)
526
+ if not self.session.isinitpath(path, with_parents=True):
527
+ if ihook.pytest_ignore_collect(collection_path=path, config=config):
528
+ continue
529
+ col = ihook.pytest_collect_directory(path=path, parent=self)
530
+ if col is not None:
531
+ yield col
532
+
533
+ elif direntry.is_file():
534
+ path = Path(direntry.path)
535
+ if not self.session.isinitpath(path):
536
+ if ihook.pytest_ignore_collect(collection_path=path, config=config):
537
+ continue
538
+ cols = ihook.pytest_collect_file(file_path=path, parent=self)
539
+ yield from cols
540
+
541
+
542
+ @final
543
+ class Session(nodes.Collector):
544
+ """The root of the collection tree.
545
+
546
+ ``Session`` collects the initial paths given as arguments to pytest.
547
+ """
548
+
549
+ Interrupted = Interrupted
550
+ Failed = Failed
551
+ # Set on the session by runner.pytest_sessionstart.
552
+ _setupstate: SetupState
553
+ # Set on the session by fixtures.pytest_sessionstart.
554
+ _fixturemanager: FixtureManager
555
+ exitstatus: int | ExitCode
556
+
557
+ def __init__(self, config: Config) -> None:
558
+ super().__init__(
559
+ name="",
560
+ path=config.rootpath,
561
+ fspath=None,
562
+ parent=None,
563
+ config=config,
564
+ session=self,
565
+ nodeid="",
566
+ )
567
+ self.testsfailed = 0
568
+ self.testscollected = 0
569
+ self._shouldstop: bool | str = False
570
+ self._shouldfail: bool | str = False
571
+ self.trace = config.trace.root.get("collection")
572
+ self._initialpaths: frozenset[Path] = frozenset()
573
+ self._initialpaths_with_parents: frozenset[Path] = frozenset()
574
+ self._notfound: list[tuple[str, Sequence[nodes.Collector]]] = []
575
+ self._initial_parts: list[CollectionArgument] = []
576
+ self._collection_cache: dict[nodes.Collector, CollectReport] = {}
577
+ self.items: list[nodes.Item] = []
578
+
579
+ self._bestrelpathcache: dict[Path, str] = _bestrelpath_cache(config.rootpath)
580
+
581
+ self.config.pluginmanager.register(self, name="session")
582
+
583
+ @classmethod
584
+ def from_config(cls, config: Config) -> Session:
585
+ session: Session = cls._create(config=config)
586
+ return session
587
+
588
+ def __repr__(self) -> str:
589
+ return "<%s %s exitstatus=%r testsfailed=%d testscollected=%d>" % (
590
+ self.__class__.__name__,
591
+ self.name,
592
+ getattr(self, "exitstatus", "<UNSET>"),
593
+ self.testsfailed,
594
+ self.testscollected,
595
+ )
596
+
597
+ @property
598
+ def shouldstop(self) -> bool | str:
599
+ return self._shouldstop
600
+
601
+ @shouldstop.setter
602
+ def shouldstop(self, value: bool | str) -> None:
603
+ # The runner checks shouldfail and assumes that if it is set we are
604
+ # definitely stopping, so prevent unsetting it.
605
+ if value is False and self._shouldstop:
606
+ warnings.warn(
607
+ PytestWarning(
608
+ "session.shouldstop cannot be unset after it has been set; ignoring."
609
+ ),
610
+ stacklevel=2,
611
+ )
612
+ return
613
+ self._shouldstop = value
614
+
615
+ @property
616
+ def shouldfail(self) -> bool | str:
617
+ return self._shouldfail
618
+
619
+ @shouldfail.setter
620
+ def shouldfail(self, value: bool | str) -> None:
621
+ # The runner checks shouldfail and assumes that if it is set we are
622
+ # definitely stopping, so prevent unsetting it.
623
+ if value is False and self._shouldfail:
624
+ warnings.warn(
625
+ PytestWarning(
626
+ "session.shouldfail cannot be unset after it has been set; ignoring."
627
+ ),
628
+ stacklevel=2,
629
+ )
630
+ return
631
+ self._shouldfail = value
632
+
633
+ @property
634
+ def startpath(self) -> Path:
635
+ """The path from which pytest was invoked.
636
+
637
+ .. versionadded:: 7.0.0
638
+ """
639
+ return self.config.invocation_params.dir
640
+
641
+ def _node_location_to_relpath(self, node_path: Path) -> str:
642
+ # bestrelpath is a quite slow function.
643
+ return self._bestrelpathcache[node_path]
644
+
645
+ @hookimpl(tryfirst=True)
646
+ def pytest_collectstart(self) -> None:
647
+ if self.shouldfail:
648
+ raise self.Failed(self.shouldfail)
649
+ if self.shouldstop:
650
+ raise self.Interrupted(self.shouldstop)
651
+
652
+ @hookimpl(tryfirst=True)
653
+ def pytest_runtest_logreport(self, report: TestReport | CollectReport) -> None:
654
+ if report.failed and not hasattr(report, "wasxfail"):
655
+ self.testsfailed += 1
656
+ maxfail = self.config.getvalue("maxfail")
657
+ if maxfail and self.testsfailed >= maxfail:
658
+ self.shouldfail = "stopping after %d failures" % (self.testsfailed)
659
+
660
+ pytest_collectreport = pytest_runtest_logreport
661
+
662
+ def isinitpath(
663
+ self,
664
+ path: str | os.PathLike[str],
665
+ *,
666
+ with_parents: bool = False,
667
+ ) -> bool:
668
+ """Is path an initial path?
669
+
670
+ An initial path is a path explicitly given to pytest on the command
671
+ line.
672
+
673
+ :param with_parents:
674
+ If set, also return True if the path is a parent of an initial path.
675
+
676
+ .. versionchanged:: 8.0
677
+ Added the ``with_parents`` parameter.
678
+ """
679
+ # Optimization: Path(Path(...)) is much slower than isinstance.
680
+ path_ = path if isinstance(path, Path) else Path(path)
681
+ if with_parents:
682
+ return path_ in self._initialpaths_with_parents
683
+ else:
684
+ return path_ in self._initialpaths
685
+
686
+ def gethookproxy(self, fspath: os.PathLike[str]) -> pluggy.HookRelay:
687
+ # Optimization: Path(Path(...)) is much slower than isinstance.
688
+ path = fspath if isinstance(fspath, Path) else Path(fspath)
689
+ pm = self.config.pluginmanager
690
+ # Check if we have the common case of running
691
+ # hooks with all conftest.py files.
692
+ my_conftestmodules = pm._getconftestmodules(path)
693
+ remove_mods = pm._conftest_plugins.difference(my_conftestmodules)
694
+ proxy: pluggy.HookRelay
695
+ if remove_mods:
696
+ # One or more conftests are not in use at this path.
697
+ proxy = PathAwareHookProxy(FSHookProxy(pm, remove_mods)) # type: ignore[arg-type,assignment]
698
+ else:
699
+ # All plugins are active for this fspath.
700
+ proxy = self.config.hook
701
+ return proxy
702
+
703
+ def _collect_path(
704
+ self,
705
+ path: Path,
706
+ path_cache: dict[Path, Sequence[nodes.Collector]],
707
+ ) -> Sequence[nodes.Collector]:
708
+ """Create a Collector for the given path.
709
+
710
+ `path_cache` makes it so the same Collectors are returned for the same
711
+ path.
712
+ """
713
+ if path in path_cache:
714
+ return path_cache[path]
715
+
716
+ if path.is_dir():
717
+ ihook = self.gethookproxy(path.parent)
718
+ col: nodes.Collector | None = ihook.pytest_collect_directory(
719
+ path=path, parent=self
720
+ )
721
+ cols: Sequence[nodes.Collector] = (col,) if col is not None else ()
722
+
723
+ elif path.is_file():
724
+ ihook = self.gethookproxy(path)
725
+ cols = ihook.pytest_collect_file(file_path=path, parent=self)
726
+
727
+ else:
728
+ # Broken symlink or invalid/missing file.
729
+ cols = ()
730
+
731
+ path_cache[path] = cols
732
+ return cols
733
+
734
+ @overload
735
+ def perform_collect(
736
+ self, args: Sequence[str] | None = ..., genitems: Literal[True] = ...
737
+ ) -> Sequence[nodes.Item]: ...
738
+
739
+ @overload
740
+ def perform_collect(
741
+ self, args: Sequence[str] | None = ..., genitems: bool = ...
742
+ ) -> Sequence[nodes.Item | nodes.Collector]: ...
743
+
744
+ def perform_collect(
745
+ self, args: Sequence[str] | None = None, genitems: bool = True
746
+ ) -> Sequence[nodes.Item | nodes.Collector]:
747
+ """Perform the collection phase for this session.
748
+
749
+ This is called by the default :hook:`pytest_collection` hook
750
+ implementation; see the documentation of this hook for more details.
751
+ For testing purposes, it may also be called directly on a fresh
752
+ ``Session``.
753
+
754
+ This function normally recursively expands any collectors collected
755
+ from the session to their items, and only items are returned. For
756
+ testing purposes, this may be suppressed by passing ``genitems=False``,
757
+ in which case the return value contains these collectors unexpanded,
758
+ and ``session.items`` is empty.
759
+ """
760
+ if args is None:
761
+ args = self.config.args
762
+
763
+ self.trace("perform_collect", self, args)
764
+ self.trace.root.indent += 1
765
+
766
+ hook = self.config.hook
767
+
768
+ self._notfound = []
769
+ self._initial_parts = []
770
+ self._collection_cache = {}
771
+ self.items = []
772
+ items: Sequence[nodes.Item | nodes.Collector] = self.items
773
+ try:
774
+ initialpaths: list[Path] = []
775
+ initialpaths_with_parents: list[Path] = []
776
+ for arg in args:
777
+ collection_argument = resolve_collection_argument(
778
+ self.config.invocation_params.dir,
779
+ arg,
780
+ as_pypath=self.config.option.pyargs,
781
+ )
782
+ self._initial_parts.append(collection_argument)
783
+ initialpaths.append(collection_argument.path)
784
+ initialpaths_with_parents.append(collection_argument.path)
785
+ initialpaths_with_parents.extend(collection_argument.path.parents)
786
+ self._initialpaths = frozenset(initialpaths)
787
+ self._initialpaths_with_parents = frozenset(initialpaths_with_parents)
788
+
789
+ rep = collect_one_node(self)
790
+ self.ihook.pytest_collectreport(report=rep)
791
+ self.trace.root.indent -= 1
792
+ if self._notfound:
793
+ errors = []
794
+ for arg, collectors in self._notfound:
795
+ if collectors:
796
+ errors.append(
797
+ f"not found: {arg}\n(no match in any of {collectors!r})"
798
+ )
799
+ else:
800
+ errors.append(f"found no collectors for {arg}")
801
+
802
+ raise UsageError(*errors)
803
+
804
+ if not genitems:
805
+ items = rep.result
806
+ else:
807
+ if rep.passed:
808
+ for node in rep.result:
809
+ self.items.extend(self.genitems(node))
810
+
811
+ self.config.pluginmanager.check_pending()
812
+ hook.pytest_collection_modifyitems(
813
+ session=self, config=self.config, items=items
814
+ )
815
+ finally:
816
+ self._notfound = []
817
+ self._initial_parts = []
818
+ self._collection_cache = {}
819
+ hook.pytest_collection_finish(session=self)
820
+
821
+ if genitems:
822
+ self.testscollected = len(items)
823
+
824
+ return items
825
+
826
+ def _collect_one_node(
827
+ self,
828
+ node: nodes.Collector,
829
+ handle_dupes: bool = True,
830
+ ) -> tuple[CollectReport, bool]:
831
+ if node in self._collection_cache and handle_dupes:
832
+ rep = self._collection_cache[node]
833
+ return rep, True
834
+ else:
835
+ rep = collect_one_node(node)
836
+ self._collection_cache[node] = rep
837
+ return rep, False
838
+
839
+ def collect(self) -> Iterator[nodes.Item | nodes.Collector]:
840
+ # This is a cache for the root directories of the initial paths.
841
+ # We can't use collection_cache for Session because of its special
842
+ # role as the bootstrapping collector.
843
+ path_cache: dict[Path, Sequence[nodes.Collector]] = {}
844
+
845
+ pm = self.config.pluginmanager
846
+
847
+ for collection_argument in self._initial_parts:
848
+ self.trace("processing argument", collection_argument)
849
+ self.trace.root.indent += 1
850
+
851
+ argpath = collection_argument.path
852
+ names = collection_argument.parts
853
+ module_name = collection_argument.module_name
854
+
855
+ # resolve_collection_argument() ensures this.
856
+ if argpath.is_dir():
857
+ assert not names, f"invalid arg {(argpath, names)!r}"
858
+
859
+ paths = [argpath]
860
+ # Add relevant parents of the path, from the root, e.g.
861
+ # /a/b/c.py -> [/, /a, /a/b, /a/b/c.py]
862
+ if module_name is None:
863
+ # Paths outside of the confcutdir should not be considered.
864
+ for path in argpath.parents:
865
+ if not pm._is_in_confcutdir(path):
866
+ break
867
+ paths.insert(0, path)
868
+ else:
869
+ # For --pyargs arguments, only consider paths matching the module
870
+ # name. Paths beyond the package hierarchy are not included.
871
+ module_name_parts = module_name.split(".")
872
+ for i, path in enumerate(argpath.parents, 2):
873
+ if i > len(module_name_parts) or path.stem != module_name_parts[-i]:
874
+ break
875
+ paths.insert(0, path)
876
+
877
+ # Start going over the parts from the root, collecting each level
878
+ # and discarding all nodes which don't match the level's part.
879
+ any_matched_in_initial_part = False
880
+ notfound_collectors = []
881
+ work: list[tuple[nodes.Collector | nodes.Item, list[Path | str]]] = [
882
+ (self, [*paths, *names])
883
+ ]
884
+ while work:
885
+ matchnode, matchparts = work.pop()
886
+
887
+ # Pop'd all of the parts, this is a match.
888
+ if not matchparts:
889
+ yield matchnode
890
+ any_matched_in_initial_part = True
891
+ continue
892
+
893
+ # Should have been matched by now, discard.
894
+ if not isinstance(matchnode, nodes.Collector):
895
+ continue
896
+
897
+ # Collect this level of matching.
898
+ # Collecting Session (self) is done directly to avoid endless
899
+ # recursion to this function.
900
+ subnodes: Sequence[nodes.Collector | nodes.Item]
901
+ if isinstance(matchnode, Session):
902
+ assert isinstance(matchparts[0], Path)
903
+ subnodes = matchnode._collect_path(matchparts[0], path_cache)
904
+ else:
905
+ # For backward compat, files given directly multiple
906
+ # times on the command line should not be deduplicated.
907
+ handle_dupes = not (
908
+ len(matchparts) == 1
909
+ and isinstance(matchparts[0], Path)
910
+ and matchparts[0].is_file()
911
+ )
912
+ rep, duplicate = self._collect_one_node(matchnode, handle_dupes)
913
+ if not duplicate and not rep.passed:
914
+ # Report collection failures here to avoid failing to
915
+ # run some test specified in the command line because
916
+ # the module could not be imported (#134).
917
+ matchnode.ihook.pytest_collectreport(report=rep)
918
+ if not rep.passed:
919
+ continue
920
+ subnodes = rep.result
921
+
922
+ # Prune this level.
923
+ any_matched_in_collector = False
924
+ for node in reversed(subnodes):
925
+ # Path part e.g. `/a/b/` in `/a/b/test_file.py::TestIt::test_it`.
926
+ if isinstance(matchparts[0], Path):
927
+ is_match = node.path == matchparts[0]
928
+ if sys.platform == "win32" and not is_match:
929
+ # In case the file paths do not match, fallback to samefile() to
930
+ # account for short-paths on Windows (#11895).
931
+ same_file = os.path.samefile(node.path, matchparts[0])
932
+ # We don't want to match links to the current node,
933
+ # otherwise we would match the same file more than once (#12039).
934
+ is_match = same_file and (
935
+ os.path.islink(node.path)
936
+ == os.path.islink(matchparts[0])
937
+ )
938
+
939
+ # Name part e.g. `TestIt` in `/a/b/test_file.py::TestIt::test_it`.
940
+ else:
941
+ # TODO: Remove parametrized workaround once collection structure contains
942
+ # parametrization.
943
+ is_match = (
944
+ node.name == matchparts[0]
945
+ or node.name.split("[")[0] == matchparts[0]
946
+ )
947
+ if is_match:
948
+ work.append((node, matchparts[1:]))
949
+ any_matched_in_collector = True
950
+
951
+ if not any_matched_in_collector:
952
+ notfound_collectors.append(matchnode)
953
+
954
+ if not any_matched_in_initial_part:
955
+ report_arg = "::".join((str(argpath), *names))
956
+ self._notfound.append((report_arg, notfound_collectors))
957
+
958
+ self.trace.root.indent -= 1
959
+
960
+ def genitems(self, node: nodes.Item | nodes.Collector) -> Iterator[nodes.Item]:
961
+ self.trace("genitems", node)
962
+ if isinstance(node, nodes.Item):
963
+ node.ihook.pytest_itemcollected(item=node)
964
+ yield node
965
+ else:
966
+ assert isinstance(node, nodes.Collector)
967
+ keepduplicates = self.config.getoption("keepduplicates")
968
+ # For backward compat, dedup only applies to files.
969
+ handle_dupes = not (keepduplicates and isinstance(node, nodes.File))
970
+ rep, duplicate = self._collect_one_node(node, handle_dupes)
971
+ if duplicate and not keepduplicates:
972
+ return
973
+ if rep.passed:
974
+ for subnode in rep.result:
975
+ yield from self.genitems(subnode)
976
+ if not duplicate:
977
+ node.ihook.pytest_collectreport(report=rep)
978
+
979
+
980
+ def search_pypath(module_name: str) -> str | None:
981
+ """Search sys.path for the given a dotted module name, and return its file
982
+ system path if found."""
983
+ try:
984
+ spec = importlib.util.find_spec(module_name)
985
+ # AttributeError: looks like package module, but actually filename
986
+ # ImportError: module does not exist
987
+ # ValueError: not a module name
988
+ except (AttributeError, ImportError, ValueError):
989
+ return None
990
+ if spec is None or spec.origin is None or spec.origin == "namespace":
991
+ return None
992
+ elif spec.submodule_search_locations:
993
+ return os.path.dirname(spec.origin)
994
+ else:
995
+ return spec.origin
996
+
997
+
998
+ @dataclasses.dataclass(frozen=True)
999
+ class CollectionArgument:
1000
+ """A resolved collection argument."""
1001
+
1002
+ path: Path
1003
+ parts: Sequence[str]
1004
+ module_name: str | None
1005
+
1006
+
1007
+ def resolve_collection_argument(
1008
+ invocation_path: Path, arg: str, *, as_pypath: bool = False
1009
+ ) -> CollectionArgument:
1010
+ """Parse path arguments optionally containing selection parts and return (fspath, names).
1011
+
1012
+ Command-line arguments can point to files and/or directories, and optionally contain
1013
+ parts for specific tests selection, for example:
1014
+
1015
+ "pkg/tests/test_foo.py::TestClass::test_foo"
1016
+
1017
+ This function ensures the path exists, and returns a resolved `CollectionArgument`:
1018
+
1019
+ CollectionArgument(
1020
+ path=Path("/full/path/to/pkg/tests/test_foo.py"),
1021
+ parts=["TestClass", "test_foo"],
1022
+ module_name=None,
1023
+ )
1024
+
1025
+ When as_pypath is True, expects that the command-line argument actually contains
1026
+ module paths instead of file-system paths:
1027
+
1028
+ "pkg.tests.test_foo::TestClass::test_foo"
1029
+
1030
+ In which case we search sys.path for a matching module, and then return the *path* to the
1031
+ found module, which may look like this:
1032
+
1033
+ CollectionArgument(
1034
+ path=Path("/home/u/myvenv/lib/site-packages/pkg/tests/test_foo.py"),
1035
+ parts=["TestClass", "test_foo"],
1036
+ module_name="pkg.tests.test_foo",
1037
+ )
1038
+
1039
+ If the path doesn't exist, raise UsageError.
1040
+ If the path is a directory and selection parts are present, raise UsageError.
1041
+ """
1042
+ base, squacket, rest = str(arg).partition("[")
1043
+ strpath, *parts = base.split("::")
1044
+ if parts:
1045
+ parts[-1] = f"{parts[-1]}{squacket}{rest}"
1046
+ module_name = None
1047
+ if as_pypath:
1048
+ pyarg_strpath = search_pypath(strpath)
1049
+ if pyarg_strpath is not None:
1050
+ module_name = strpath
1051
+ strpath = pyarg_strpath
1052
+ fspath = invocation_path / strpath
1053
+ fspath = absolutepath(fspath)
1054
+ if not safe_exists(fspath):
1055
+ msg = (
1056
+ "module or package not found: {arg} (missing __init__.py?)"
1057
+ if as_pypath
1058
+ else "file or directory not found: {arg}"
1059
+ )
1060
+ raise UsageError(msg.format(arg=arg))
1061
+ if parts and fspath.is_dir():
1062
+ msg = (
1063
+ "package argument cannot contain :: selection parts: {arg}"
1064
+ if as_pypath
1065
+ else "directory argument cannot contain :: selection parts: {arg}"
1066
+ )
1067
+ raise UsageError(msg.format(arg=arg))
1068
+ return CollectionArgument(
1069
+ path=fspath,
1070
+ parts=parts,
1071
+ module_name=module_name,
1072
+ )
vllm/lib/python3.10/site-packages/_pytest/mark/__init__.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generic mechanism for marking and selecting python functions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import collections
6
+ import dataclasses
7
+ from typing import AbstractSet
8
+ from typing import Collection
9
+ from typing import Iterable
10
+ from typing import Optional
11
+ from typing import TYPE_CHECKING
12
+
13
+ from .expression import Expression
14
+ from .expression import ParseError
15
+ from .structures import EMPTY_PARAMETERSET_OPTION
16
+ from .structures import get_empty_parameterset_mark
17
+ from .structures import Mark
18
+ from .structures import MARK_GEN
19
+ from .structures import MarkDecorator
20
+ from .structures import MarkGenerator
21
+ from .structures import ParameterSet
22
+ from _pytest.config import Config
23
+ from _pytest.config import ExitCode
24
+ from _pytest.config import hookimpl
25
+ from _pytest.config import UsageError
26
+ from _pytest.config.argparsing import NOT_SET
27
+ from _pytest.config.argparsing import Parser
28
+ from _pytest.stash import StashKey
29
+
30
+
31
+ if TYPE_CHECKING:
32
+ from _pytest.nodes import Item
33
+
34
+
35
+ __all__ = [
36
+ "MARK_GEN",
37
+ "Mark",
38
+ "MarkDecorator",
39
+ "MarkGenerator",
40
+ "ParameterSet",
41
+ "get_empty_parameterset_mark",
42
+ ]
43
+
44
+
45
+ old_mark_config_key = StashKey[Optional[Config]]()
46
+
47
+
48
+ def param(
49
+ *values: object,
50
+ marks: MarkDecorator | Collection[MarkDecorator | Mark] = (),
51
+ id: str | None = None,
52
+ ) -> ParameterSet:
53
+ """Specify a parameter in `pytest.mark.parametrize`_ calls or
54
+ :ref:`parametrized fixtures <fixture-parametrize-marks>`.
55
+
56
+ .. code-block:: python
57
+
58
+ @pytest.mark.parametrize(
59
+ "test_input,expected",
60
+ [
61
+ ("3+5", 8),
62
+ pytest.param("6*9", 42, marks=pytest.mark.xfail),
63
+ ],
64
+ )
65
+ def test_eval(test_input, expected):
66
+ assert eval(test_input) == expected
67
+
68
+ :param values: Variable args of the values of the parameter set, in order.
69
+ :param marks: A single mark or a list of marks to be applied to this parameter set.
70
+ :param id: The id to attribute to this parameter set.
71
+ """
72
+ return ParameterSet.param(*values, marks=marks, id=id)
73
+
74
+
75
+ def pytest_addoption(parser: Parser) -> None:
76
+ group = parser.getgroup("general")
77
+ group._addoption(
78
+ "-k",
79
+ action="store",
80
+ dest="keyword",
81
+ default="",
82
+ metavar="EXPRESSION",
83
+ help="Only run tests which match the given substring expression. "
84
+ "An expression is a Python evaluable expression "
85
+ "where all names are substring-matched against test names "
86
+ "and their parent classes. Example: -k 'test_method or test_"
87
+ "other' matches all test functions and classes whose name "
88
+ "contains 'test_method' or 'test_other', while -k 'not test_method' "
89
+ "matches those that don't contain 'test_method' in their names. "
90
+ "-k 'not test_method and not test_other' will eliminate the matches. "
91
+ "Additionally keywords are matched to classes and functions "
92
+ "containing extra names in their 'extra_keyword_matches' set, "
93
+ "as well as functions which have names assigned directly to them. "
94
+ "The matching is case-insensitive.",
95
+ )
96
+
97
+ group._addoption(
98
+ "-m",
99
+ action="store",
100
+ dest="markexpr",
101
+ default="",
102
+ metavar="MARKEXPR",
103
+ help="Only run tests matching given mark expression. "
104
+ "For example: -m 'mark1 and not mark2'.",
105
+ )
106
+
107
+ group.addoption(
108
+ "--markers",
109
+ action="store_true",
110
+ help="show markers (builtin, plugin and per-project ones).",
111
+ )
112
+
113
+ parser.addini("markers", "Register new markers for test functions", "linelist")
114
+ parser.addini(EMPTY_PARAMETERSET_OPTION, "Default marker for empty parametersets")
115
+
116
+
117
+ @hookimpl(tryfirst=True)
118
+ def pytest_cmdline_main(config: Config) -> int | ExitCode | None:
119
+ import _pytest.config
120
+
121
+ if config.option.markers:
122
+ config._do_configure()
123
+ tw = _pytest.config.create_terminal_writer(config)
124
+ for line in config.getini("markers"):
125
+ parts = line.split(":", 1)
126
+ name = parts[0]
127
+ rest = parts[1] if len(parts) == 2 else ""
128
+ tw.write(f"@pytest.mark.{name}:", bold=True)
129
+ tw.line(rest)
130
+ tw.line()
131
+ config._ensure_unconfigure()
132
+ return 0
133
+
134
+ return None
135
+
136
+
137
+ @dataclasses.dataclass
138
+ class KeywordMatcher:
139
+ """A matcher for keywords.
140
+
141
+ Given a list of names, matches any substring of one of these names. The
142
+ string inclusion check is case-insensitive.
143
+
144
+ Will match on the name of colitem, including the names of its parents.
145
+ Only matches names of items which are either a :class:`Class` or a
146
+ :class:`Function`.
147
+
148
+ Additionally, matches on names in the 'extra_keyword_matches' set of
149
+ any item, as well as names directly assigned to test functions.
150
+ """
151
+
152
+ __slots__ = ("_names",)
153
+
154
+ _names: AbstractSet[str]
155
+
156
+ @classmethod
157
+ def from_item(cls, item: Item) -> KeywordMatcher:
158
+ mapped_names = set()
159
+
160
+ # Add the names of the current item and any parent items,
161
+ # except the Session and root Directory's which are not
162
+ # interesting for matching.
163
+ import pytest
164
+
165
+ for node in item.listchain():
166
+ if isinstance(node, pytest.Session):
167
+ continue
168
+ if isinstance(node, pytest.Directory) and isinstance(
169
+ node.parent, pytest.Session
170
+ ):
171
+ continue
172
+ mapped_names.add(node.name)
173
+
174
+ # Add the names added as extra keywords to current or parent items.
175
+ mapped_names.update(item.listextrakeywords())
176
+
177
+ # Add the names attached to the current function through direct assignment.
178
+ function_obj = getattr(item, "function", None)
179
+ if function_obj:
180
+ mapped_names.update(function_obj.__dict__)
181
+
182
+ # Add the markers to the keywords as we no longer handle them correctly.
183
+ mapped_names.update(mark.name for mark in item.iter_markers())
184
+
185
+ return cls(mapped_names)
186
+
187
+ def __call__(self, subname: str, /, **kwargs: str | int | bool | None) -> bool:
188
+ if kwargs:
189
+ raise UsageError("Keyword expressions do not support call parameters.")
190
+ subname = subname.lower()
191
+ names = (name.lower() for name in self._names)
192
+
193
+ for name in names:
194
+ if subname in name:
195
+ return True
196
+ return False
197
+
198
+
199
+ def deselect_by_keyword(items: list[Item], config: Config) -> None:
200
+ keywordexpr = config.option.keyword.lstrip()
201
+ if not keywordexpr:
202
+ return
203
+
204
+ expr = _parse_expression(keywordexpr, "Wrong expression passed to '-k'")
205
+
206
+ remaining = []
207
+ deselected = []
208
+ for colitem in items:
209
+ if not expr.evaluate(KeywordMatcher.from_item(colitem)):
210
+ deselected.append(colitem)
211
+ else:
212
+ remaining.append(colitem)
213
+
214
+ if deselected:
215
+ config.hook.pytest_deselected(items=deselected)
216
+ items[:] = remaining
217
+
218
+
219
+ @dataclasses.dataclass
220
+ class MarkMatcher:
221
+ """A matcher for markers which are present.
222
+
223
+ Tries to match on any marker names, attached to the given colitem.
224
+ """
225
+
226
+ __slots__ = ("own_mark_name_mapping",)
227
+
228
+ own_mark_name_mapping: dict[str, list[Mark]]
229
+
230
+ @classmethod
231
+ def from_markers(cls, markers: Iterable[Mark]) -> MarkMatcher:
232
+ mark_name_mapping = collections.defaultdict(list)
233
+ for mark in markers:
234
+ mark_name_mapping[mark.name].append(mark)
235
+ return cls(mark_name_mapping)
236
+
237
+ def __call__(self, name: str, /, **kwargs: str | int | bool | None) -> bool:
238
+ if not (matches := self.own_mark_name_mapping.get(name, [])):
239
+ return False
240
+
241
+ for mark in matches:
242
+ if all(mark.kwargs.get(k, NOT_SET) == v for k, v in kwargs.items()):
243
+ return True
244
+
245
+ return False
246
+
247
+
248
+ def deselect_by_mark(items: list[Item], config: Config) -> None:
249
+ matchexpr = config.option.markexpr
250
+ if not matchexpr:
251
+ return
252
+
253
+ expr = _parse_expression(matchexpr, "Wrong expression passed to '-m'")
254
+ remaining: list[Item] = []
255
+ deselected: list[Item] = []
256
+ for item in items:
257
+ if expr.evaluate(MarkMatcher.from_markers(item.iter_markers())):
258
+ remaining.append(item)
259
+ else:
260
+ deselected.append(item)
261
+ if deselected:
262
+ config.hook.pytest_deselected(items=deselected)
263
+ items[:] = remaining
264
+
265
+
266
+ def _parse_expression(expr: str, exc_message: str) -> Expression:
267
+ try:
268
+ return Expression.compile(expr)
269
+ except ParseError as e:
270
+ raise UsageError(f"{exc_message}: {expr}: {e}") from None
271
+
272
+
273
+ def pytest_collection_modifyitems(items: list[Item], config: Config) -> None:
274
+ deselect_by_keyword(items, config)
275
+ deselect_by_mark(items, config)
276
+
277
+
278
+ def pytest_configure(config: Config) -> None:
279
+ config.stash[old_mark_config_key] = MARK_GEN._config
280
+ MARK_GEN._config = config
281
+
282
+ empty_parameterset = config.getini(EMPTY_PARAMETERSET_OPTION)
283
+
284
+ if empty_parameterset not in ("skip", "xfail", "fail_at_collect", None, ""):
285
+ raise UsageError(
286
+ f"{EMPTY_PARAMETERSET_OPTION!s} must be one of skip, xfail or fail_at_collect"
287
+ f" but it is {empty_parameterset!r}"
288
+ )
289
+
290
+
291
+ def pytest_unconfigure(config: Config) -> None:
292
+ MARK_GEN._config = config.stash.get(old_mark_config_key, None)
vllm/lib/python3.10/site-packages/_pytest/mark/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (9.16 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/mark/__pycache__/expression.cpython-310.pyc ADDED
Binary file (10.8 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/mark/__pycache__/structures.cpython-310.pyc ADDED
Binary file (19.5 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/mark/expression.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""Evaluate match expressions, as used by `-k` and `-m`.
2
+
3
+ The grammar is:
4
+
5
+ expression: expr? EOF
6
+ expr: and_expr ('or' and_expr)*
7
+ and_expr: not_expr ('and' not_expr)*
8
+ not_expr: 'not' not_expr | '(' expr ')' | ident kwargs?
9
+
10
+ ident: (\w|:|\+|-|\.|\[|\]|\\|/)+
11
+ kwargs: ('(' name '=' value ( ', ' name '=' value )* ')')
12
+ name: a valid ident, but not a reserved keyword
13
+ value: (unescaped) string literal | (-)?[0-9]+ | 'False' | 'True' | 'None'
14
+
15
+ The semantics are:
16
+
17
+ - Empty expression evaluates to False.
18
+ - ident evaluates to True or False according to a provided matcher function.
19
+ - or/and/not evaluate according to the usual boolean semantics.
20
+ - ident with parentheses and keyword arguments evaluates to True or False according to a provided matcher function.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import ast
26
+ import dataclasses
27
+ import enum
28
+ import keyword
29
+ import re
30
+ import types
31
+ from typing import Iterator
32
+ from typing import Literal
33
+ from typing import Mapping
34
+ from typing import NoReturn
35
+ from typing import overload
36
+ from typing import Protocol
37
+ from typing import Sequence
38
+
39
+
40
+ __all__ = [
41
+ "Expression",
42
+ "ParseError",
43
+ ]
44
+
45
+
46
+ class TokenType(enum.Enum):
47
+ LPAREN = "left parenthesis"
48
+ RPAREN = "right parenthesis"
49
+ OR = "or"
50
+ AND = "and"
51
+ NOT = "not"
52
+ IDENT = "identifier"
53
+ EOF = "end of input"
54
+ EQUAL = "="
55
+ STRING = "string literal"
56
+ COMMA = ","
57
+
58
+
59
+ @dataclasses.dataclass(frozen=True)
60
+ class Token:
61
+ __slots__ = ("type", "value", "pos")
62
+ type: TokenType
63
+ value: str
64
+ pos: int
65
+
66
+
67
+ class ParseError(Exception):
68
+ """The expression contains invalid syntax.
69
+
70
+ :param column: The column in the line where the error occurred (1-based).
71
+ :param message: A description of the error.
72
+ """
73
+
74
+ def __init__(self, column: int, message: str) -> None:
75
+ self.column = column
76
+ self.message = message
77
+
78
+ def __str__(self) -> str:
79
+ return f"at column {self.column}: {self.message}"
80
+
81
+
82
+ class Scanner:
83
+ __slots__ = ("tokens", "current")
84
+
85
+ def __init__(self, input: str) -> None:
86
+ self.tokens = self.lex(input)
87
+ self.current = next(self.tokens)
88
+
89
+ def lex(self, input: str) -> Iterator[Token]:
90
+ pos = 0
91
+ while pos < len(input):
92
+ if input[pos] in (" ", "\t"):
93
+ pos += 1
94
+ elif input[pos] == "(":
95
+ yield Token(TokenType.LPAREN, "(", pos)
96
+ pos += 1
97
+ elif input[pos] == ")":
98
+ yield Token(TokenType.RPAREN, ")", pos)
99
+ pos += 1
100
+ elif input[pos] == "=":
101
+ yield Token(TokenType.EQUAL, "=", pos)
102
+ pos += 1
103
+ elif input[pos] == ",":
104
+ yield Token(TokenType.COMMA, ",", pos)
105
+ pos += 1
106
+ elif (quote_char := input[pos]) in ("'", '"'):
107
+ end_quote_pos = input.find(quote_char, pos + 1)
108
+ if end_quote_pos == -1:
109
+ raise ParseError(
110
+ pos + 1,
111
+ f'closing quote "{quote_char}" is missing',
112
+ )
113
+ value = input[pos : end_quote_pos + 1]
114
+ if (backslash_pos := input.find("\\")) != -1:
115
+ raise ParseError(
116
+ backslash_pos + 1,
117
+ r'escaping with "\" not supported in marker expression',
118
+ )
119
+ yield Token(TokenType.STRING, value, pos)
120
+ pos += len(value)
121
+ else:
122
+ match = re.match(r"(:?\w|:|\+|-|\.|\[|\]|\\|/)+", input[pos:])
123
+ if match:
124
+ value = match.group(0)
125
+ if value == "or":
126
+ yield Token(TokenType.OR, value, pos)
127
+ elif value == "and":
128
+ yield Token(TokenType.AND, value, pos)
129
+ elif value == "not":
130
+ yield Token(TokenType.NOT, value, pos)
131
+ else:
132
+ yield Token(TokenType.IDENT, value, pos)
133
+ pos += len(value)
134
+ else:
135
+ raise ParseError(
136
+ pos + 1,
137
+ f'unexpected character "{input[pos]}"',
138
+ )
139
+ yield Token(TokenType.EOF, "", pos)
140
+
141
+ @overload
142
+ def accept(self, type: TokenType, *, reject: Literal[True]) -> Token: ...
143
+
144
+ @overload
145
+ def accept(
146
+ self, type: TokenType, *, reject: Literal[False] = False
147
+ ) -> Token | None: ...
148
+
149
+ def accept(self, type: TokenType, *, reject: bool = False) -> Token | None:
150
+ if self.current.type is type:
151
+ token = self.current
152
+ if token.type is not TokenType.EOF:
153
+ self.current = next(self.tokens)
154
+ return token
155
+ if reject:
156
+ self.reject((type,))
157
+ return None
158
+
159
+ def reject(self, expected: Sequence[TokenType]) -> NoReturn:
160
+ raise ParseError(
161
+ self.current.pos + 1,
162
+ "expected {}; got {}".format(
163
+ " OR ".join(type.value for type in expected),
164
+ self.current.type.value,
165
+ ),
166
+ )
167
+
168
+
169
+ # True, False and None are legal match expression identifiers,
170
+ # but illegal as Python identifiers. To fix this, this prefix
171
+ # is added to identifiers in the conversion to Python AST.
172
+ IDENT_PREFIX = "$"
173
+
174
+
175
+ def expression(s: Scanner) -> ast.Expression:
176
+ if s.accept(TokenType.EOF):
177
+ ret: ast.expr = ast.Constant(False)
178
+ else:
179
+ ret = expr(s)
180
+ s.accept(TokenType.EOF, reject=True)
181
+ return ast.fix_missing_locations(ast.Expression(ret))
182
+
183
+
184
+ def expr(s: Scanner) -> ast.expr:
185
+ ret = and_expr(s)
186
+ while s.accept(TokenType.OR):
187
+ rhs = and_expr(s)
188
+ ret = ast.BoolOp(ast.Or(), [ret, rhs])
189
+ return ret
190
+
191
+
192
+ def and_expr(s: Scanner) -> ast.expr:
193
+ ret = not_expr(s)
194
+ while s.accept(TokenType.AND):
195
+ rhs = not_expr(s)
196
+ ret = ast.BoolOp(ast.And(), [ret, rhs])
197
+ return ret
198
+
199
+
200
+ def not_expr(s: Scanner) -> ast.expr:
201
+ if s.accept(TokenType.NOT):
202
+ return ast.UnaryOp(ast.Not(), not_expr(s))
203
+ if s.accept(TokenType.LPAREN):
204
+ ret = expr(s)
205
+ s.accept(TokenType.RPAREN, reject=True)
206
+ return ret
207
+ ident = s.accept(TokenType.IDENT)
208
+ if ident:
209
+ name = ast.Name(IDENT_PREFIX + ident.value, ast.Load())
210
+ if s.accept(TokenType.LPAREN):
211
+ ret = ast.Call(func=name, args=[], keywords=all_kwargs(s))
212
+ s.accept(TokenType.RPAREN, reject=True)
213
+ else:
214
+ ret = name
215
+ return ret
216
+
217
+ s.reject((TokenType.NOT, TokenType.LPAREN, TokenType.IDENT))
218
+
219
+
220
+ BUILTIN_MATCHERS = {"True": True, "False": False, "None": None}
221
+
222
+
223
+ def single_kwarg(s: Scanner) -> ast.keyword:
224
+ keyword_name = s.accept(TokenType.IDENT, reject=True)
225
+ if not keyword_name.value.isidentifier():
226
+ raise ParseError(
227
+ keyword_name.pos + 1,
228
+ f"not a valid python identifier {keyword_name.value}",
229
+ )
230
+ if keyword.iskeyword(keyword_name.value):
231
+ raise ParseError(
232
+ keyword_name.pos + 1,
233
+ f"unexpected reserved python keyword `{keyword_name.value}`",
234
+ )
235
+ s.accept(TokenType.EQUAL, reject=True)
236
+
237
+ if value_token := s.accept(TokenType.STRING):
238
+ value: str | int | bool | None = value_token.value[1:-1] # strip quotes
239
+ else:
240
+ value_token = s.accept(TokenType.IDENT, reject=True)
241
+ if (
242
+ (number := value_token.value).isdigit()
243
+ or number.startswith("-")
244
+ and number[1:].isdigit()
245
+ ):
246
+ value = int(number)
247
+ elif value_token.value in BUILTIN_MATCHERS:
248
+ value = BUILTIN_MATCHERS[value_token.value]
249
+ else:
250
+ raise ParseError(
251
+ value_token.pos + 1,
252
+ f'unexpected character/s "{value_token.value}"',
253
+ )
254
+
255
+ ret = ast.keyword(keyword_name.value, ast.Constant(value))
256
+ return ret
257
+
258
+
259
+ def all_kwargs(s: Scanner) -> list[ast.keyword]:
260
+ ret = [single_kwarg(s)]
261
+ while s.accept(TokenType.COMMA):
262
+ ret.append(single_kwarg(s))
263
+ return ret
264
+
265
+
266
+ class MatcherCall(Protocol):
267
+ def __call__(self, name: str, /, **kwargs: str | int | bool | None) -> bool: ...
268
+
269
+
270
+ @dataclasses.dataclass
271
+ class MatcherNameAdapter:
272
+ matcher: MatcherCall
273
+ name: str
274
+
275
+ def __bool__(self) -> bool:
276
+ return self.matcher(self.name)
277
+
278
+ def __call__(self, **kwargs: str | int | bool | None) -> bool:
279
+ return self.matcher(self.name, **kwargs)
280
+
281
+
282
+ class MatcherAdapter(Mapping[str, MatcherNameAdapter]):
283
+ """Adapts a matcher function to a locals mapping as required by eval()."""
284
+
285
+ def __init__(self, matcher: MatcherCall) -> None:
286
+ self.matcher = matcher
287
+
288
+ def __getitem__(self, key: str) -> MatcherNameAdapter:
289
+ return MatcherNameAdapter(matcher=self.matcher, name=key[len(IDENT_PREFIX) :])
290
+
291
+ def __iter__(self) -> Iterator[str]:
292
+ raise NotImplementedError()
293
+
294
+ def __len__(self) -> int:
295
+ raise NotImplementedError()
296
+
297
+
298
+ class Expression:
299
+ """A compiled match expression as used by -k and -m.
300
+
301
+ The expression can be evaluated against different matchers.
302
+ """
303
+
304
+ __slots__ = ("code",)
305
+
306
+ def __init__(self, code: types.CodeType) -> None:
307
+ self.code = code
308
+
309
+ @classmethod
310
+ def compile(self, input: str) -> Expression:
311
+ """Compile a match expression.
312
+
313
+ :param input: The input expression - one line.
314
+ """
315
+ astexpr = expression(Scanner(input))
316
+ code: types.CodeType = compile(
317
+ astexpr,
318
+ filename="<pytest match expression>",
319
+ mode="eval",
320
+ )
321
+ return Expression(code)
322
+
323
+ def evaluate(self, matcher: MatcherCall) -> bool:
324
+ """Evaluate the match expression.
325
+
326
+ :param matcher:
327
+ Given an identifier, should return whether it matches or not.
328
+ Should be prepared to handle arbitrary strings as input.
329
+
330
+ :returns: Whether the expression matches or not.
331
+ """
332
+ ret: bool = bool(eval(self.code, {"__builtins__": {}}, MatcherAdapter(matcher)))
333
+ return ret
vllm/lib/python3.10/site-packages/_pytest/mark/structures.py ADDED
@@ -0,0 +1,615 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ import collections.abc
5
+ import dataclasses
6
+ import inspect
7
+ from typing import Any
8
+ from typing import Callable
9
+ from typing import Collection
10
+ from typing import final
11
+ from typing import Iterable
12
+ from typing import Iterator
13
+ from typing import Mapping
14
+ from typing import MutableMapping
15
+ from typing import NamedTuple
16
+ from typing import overload
17
+ from typing import Sequence
18
+ from typing import TYPE_CHECKING
19
+ from typing import TypeVar
20
+ from typing import Union
21
+ import warnings
22
+
23
+ from .._code import getfslineno
24
+ from ..compat import ascii_escaped
25
+ from ..compat import NOTSET
26
+ from ..compat import NotSetType
27
+ from _pytest.config import Config
28
+ from _pytest.deprecated import check_ispytest
29
+ from _pytest.deprecated import MARKED_FIXTURE
30
+ from _pytest.outcomes import fail
31
+ from _pytest.scope import _ScopeName
32
+ from _pytest.warning_types import PytestUnknownMarkWarning
33
+
34
+
35
+ if TYPE_CHECKING:
36
+ from ..nodes import Node
37
+
38
+
39
+ EMPTY_PARAMETERSET_OPTION = "empty_parameter_set_mark"
40
+
41
+
42
+ def istestfunc(func) -> bool:
43
+ return callable(func) and getattr(func, "__name__", "<lambda>") != "<lambda>"
44
+
45
+
46
+ def get_empty_parameterset_mark(
47
+ config: Config, argnames: Sequence[str], func
48
+ ) -> MarkDecorator:
49
+ from ..nodes import Collector
50
+
51
+ fs, lineno = getfslineno(func)
52
+ reason = "got empty parameter set %r, function %s at %s:%d" % (
53
+ argnames,
54
+ func.__name__,
55
+ fs,
56
+ lineno,
57
+ )
58
+
59
+ requested_mark = config.getini(EMPTY_PARAMETERSET_OPTION)
60
+ if requested_mark in ("", None, "skip"):
61
+ mark = MARK_GEN.skip(reason=reason)
62
+ elif requested_mark == "xfail":
63
+ mark = MARK_GEN.xfail(reason=reason, run=False)
64
+ elif requested_mark == "fail_at_collect":
65
+ f_name = func.__name__
66
+ _, lineno = getfslineno(func)
67
+ raise Collector.CollectError(
68
+ "Empty parameter set in '%s' at line %d" % (f_name, lineno + 1)
69
+ )
70
+ else:
71
+ raise LookupError(requested_mark)
72
+ return mark
73
+
74
+
75
+ class ParameterSet(NamedTuple):
76
+ values: Sequence[object | NotSetType]
77
+ marks: Collection[MarkDecorator | Mark]
78
+ id: str | None
79
+
80
+ @classmethod
81
+ def param(
82
+ cls,
83
+ *values: object,
84
+ marks: MarkDecorator | Collection[MarkDecorator | Mark] = (),
85
+ id: str | None = None,
86
+ ) -> ParameterSet:
87
+ if isinstance(marks, MarkDecorator):
88
+ marks = (marks,)
89
+ else:
90
+ assert isinstance(marks, collections.abc.Collection)
91
+
92
+ if id is not None:
93
+ if not isinstance(id, str):
94
+ raise TypeError(f"Expected id to be a string, got {type(id)}: {id!r}")
95
+ id = ascii_escaped(id)
96
+ return cls(values, marks, id)
97
+
98
+ @classmethod
99
+ def extract_from(
100
+ cls,
101
+ parameterset: ParameterSet | Sequence[object] | object,
102
+ force_tuple: bool = False,
103
+ ) -> ParameterSet:
104
+ """Extract from an object or objects.
105
+
106
+ :param parameterset:
107
+ A legacy style parameterset that may or may not be a tuple,
108
+ and may or may not be wrapped into a mess of mark objects.
109
+
110
+ :param force_tuple:
111
+ Enforce tuple wrapping so single argument tuple values
112
+ don't get decomposed and break tests.
113
+ """
114
+ if isinstance(parameterset, cls):
115
+ return parameterset
116
+ if force_tuple:
117
+ return cls.param(parameterset)
118
+ else:
119
+ # TODO: Refactor to fix this type-ignore. Currently the following
120
+ # passes type-checking but crashes:
121
+ #
122
+ # @pytest.mark.parametrize(('x', 'y'), [1, 2])
123
+ # def test_foo(x, y): pass
124
+ return cls(parameterset, marks=[], id=None) # type: ignore[arg-type]
125
+
126
+ @staticmethod
127
+ def _parse_parametrize_args(
128
+ argnames: str | Sequence[str],
129
+ argvalues: Iterable[ParameterSet | Sequence[object] | object],
130
+ *args,
131
+ **kwargs,
132
+ ) -> tuple[Sequence[str], bool]:
133
+ if isinstance(argnames, str):
134
+ argnames = [x.strip() for x in argnames.split(",") if x.strip()]
135
+ force_tuple = len(argnames) == 1
136
+ else:
137
+ force_tuple = False
138
+ return argnames, force_tuple
139
+
140
+ @staticmethod
141
+ def _parse_parametrize_parameters(
142
+ argvalues: Iterable[ParameterSet | Sequence[object] | object],
143
+ force_tuple: bool,
144
+ ) -> list[ParameterSet]:
145
+ return [
146
+ ParameterSet.extract_from(x, force_tuple=force_tuple) for x in argvalues
147
+ ]
148
+
149
+ @classmethod
150
+ def _for_parametrize(
151
+ cls,
152
+ argnames: str | Sequence[str],
153
+ argvalues: Iterable[ParameterSet | Sequence[object] | object],
154
+ func,
155
+ config: Config,
156
+ nodeid: str,
157
+ ) -> tuple[Sequence[str], list[ParameterSet]]:
158
+ argnames, force_tuple = cls._parse_parametrize_args(argnames, argvalues)
159
+ parameters = cls._parse_parametrize_parameters(argvalues, force_tuple)
160
+ del argvalues
161
+
162
+ if parameters:
163
+ # Check all parameter sets have the correct number of values.
164
+ for param in parameters:
165
+ if len(param.values) != len(argnames):
166
+ msg = (
167
+ '{nodeid}: in "parametrize" the number of names ({names_len}):\n'
168
+ " {names}\n"
169
+ "must be equal to the number of values ({values_len}):\n"
170
+ " {values}"
171
+ )
172
+ fail(
173
+ msg.format(
174
+ nodeid=nodeid,
175
+ values=param.values,
176
+ names=argnames,
177
+ names_len=len(argnames),
178
+ values_len=len(param.values),
179
+ ),
180
+ pytrace=False,
181
+ )
182
+ else:
183
+ # Empty parameter set (likely computed at runtime): create a single
184
+ # parameter set with NOTSET values, with the "empty parameter set" mark applied to it.
185
+ mark = get_empty_parameterset_mark(config, argnames, func)
186
+ parameters.append(
187
+ ParameterSet(values=(NOTSET,) * len(argnames), marks=[mark], id=None)
188
+ )
189
+ return argnames, parameters
190
+
191
+
192
+ @final
193
+ @dataclasses.dataclass(frozen=True)
194
+ class Mark:
195
+ """A pytest mark."""
196
+
197
+ #: Name of the mark.
198
+ name: str
199
+ #: Positional arguments of the mark decorator.
200
+ args: tuple[Any, ...]
201
+ #: Keyword arguments of the mark decorator.
202
+ kwargs: Mapping[str, Any]
203
+
204
+ #: Source Mark for ids with parametrize Marks.
205
+ _param_ids_from: Mark | None = dataclasses.field(default=None, repr=False)
206
+ #: Resolved/generated ids with parametrize Marks.
207
+ _param_ids_generated: Sequence[str] | None = dataclasses.field(
208
+ default=None, repr=False
209
+ )
210
+
211
+ def __init__(
212
+ self,
213
+ name: str,
214
+ args: tuple[Any, ...],
215
+ kwargs: Mapping[str, Any],
216
+ param_ids_from: Mark | None = None,
217
+ param_ids_generated: Sequence[str] | None = None,
218
+ *,
219
+ _ispytest: bool = False,
220
+ ) -> None:
221
+ """:meta private:"""
222
+ check_ispytest(_ispytest)
223
+ # Weirdness to bypass frozen=True.
224
+ object.__setattr__(self, "name", name)
225
+ object.__setattr__(self, "args", args)
226
+ object.__setattr__(self, "kwargs", kwargs)
227
+ object.__setattr__(self, "_param_ids_from", param_ids_from)
228
+ object.__setattr__(self, "_param_ids_generated", param_ids_generated)
229
+
230
+ def _has_param_ids(self) -> bool:
231
+ return "ids" in self.kwargs or len(self.args) >= 4
232
+
233
+ def combined_with(self, other: Mark) -> Mark:
234
+ """Return a new Mark which is a combination of this
235
+ Mark and another Mark.
236
+
237
+ Combines by appending args and merging kwargs.
238
+
239
+ :param Mark other: The mark to combine with.
240
+ :rtype: Mark
241
+ """
242
+ assert self.name == other.name
243
+
244
+ # Remember source of ids with parametrize Marks.
245
+ param_ids_from: Mark | None = None
246
+ if self.name == "parametrize":
247
+ if other._has_param_ids():
248
+ param_ids_from = other
249
+ elif self._has_param_ids():
250
+ param_ids_from = self
251
+
252
+ return Mark(
253
+ self.name,
254
+ self.args + other.args,
255
+ dict(self.kwargs, **other.kwargs),
256
+ param_ids_from=param_ids_from,
257
+ _ispytest=True,
258
+ )
259
+
260
+
261
+ # A generic parameter designating an object to which a Mark may
262
+ # be applied -- a test function (callable) or class.
263
+ # Note: a lambda is not allowed, but this can't be represented.
264
+ Markable = TypeVar("Markable", bound=Union[Callable[..., object], type])
265
+
266
+
267
+ @dataclasses.dataclass
268
+ class MarkDecorator:
269
+ """A decorator for applying a mark on test functions and classes.
270
+
271
+ ``MarkDecorators`` are created with ``pytest.mark``::
272
+
273
+ mark1 = pytest.mark.NAME # Simple MarkDecorator
274
+ mark2 = pytest.mark.NAME(name1=value) # Parametrized MarkDecorator
275
+
276
+ and can then be applied as decorators to test functions::
277
+
278
+ @mark2
279
+ def test_function():
280
+ pass
281
+
282
+ When a ``MarkDecorator`` is called, it does the following:
283
+
284
+ 1. If called with a single class as its only positional argument and no
285
+ additional keyword arguments, it attaches the mark to the class so it
286
+ gets applied automatically to all test cases found in that class.
287
+
288
+ 2. If called with a single function as its only positional argument and
289
+ no additional keyword arguments, it attaches the mark to the function,
290
+ containing all the arguments already stored internally in the
291
+ ``MarkDecorator``.
292
+
293
+ 3. When called in any other case, it returns a new ``MarkDecorator``
294
+ instance with the original ``MarkDecorator``'s content updated with
295
+ the arguments passed to this call.
296
+
297
+ Note: The rules above prevent a ``MarkDecorator`` from storing only a
298
+ single function or class reference as its positional argument with no
299
+ additional keyword or positional arguments. You can work around this by
300
+ using `with_args()`.
301
+ """
302
+
303
+ mark: Mark
304
+
305
+ def __init__(self, mark: Mark, *, _ispytest: bool = False) -> None:
306
+ """:meta private:"""
307
+ check_ispytest(_ispytest)
308
+ self.mark = mark
309
+
310
+ @property
311
+ def name(self) -> str:
312
+ """Alias for mark.name."""
313
+ return self.mark.name
314
+
315
+ @property
316
+ def args(self) -> tuple[Any, ...]:
317
+ """Alias for mark.args."""
318
+ return self.mark.args
319
+
320
+ @property
321
+ def kwargs(self) -> Mapping[str, Any]:
322
+ """Alias for mark.kwargs."""
323
+ return self.mark.kwargs
324
+
325
+ @property
326
+ def markname(self) -> str:
327
+ """:meta private:"""
328
+ return self.name # for backward-compat (2.4.1 had this attr)
329
+
330
+ def with_args(self, *args: object, **kwargs: object) -> MarkDecorator:
331
+ """Return a MarkDecorator with extra arguments added.
332
+
333
+ Unlike calling the MarkDecorator, with_args() can be used even
334
+ if the sole argument is a callable/class.
335
+ """
336
+ mark = Mark(self.name, args, kwargs, _ispytest=True)
337
+ return MarkDecorator(self.mark.combined_with(mark), _ispytest=True)
338
+
339
+ # Type ignored because the overloads overlap with an incompatible
340
+ # return type. Not much we can do about that. Thankfully mypy picks
341
+ # the first match so it works out even if we break the rules.
342
+ @overload
343
+ def __call__(self, arg: Markable) -> Markable: # type: ignore[overload-overlap]
344
+ pass
345
+
346
+ @overload
347
+ def __call__(self, *args: object, **kwargs: object) -> MarkDecorator:
348
+ pass
349
+
350
+ def __call__(self, *args: object, **kwargs: object):
351
+ """Call the MarkDecorator."""
352
+ if args and not kwargs:
353
+ func = args[0]
354
+ is_class = inspect.isclass(func)
355
+ if len(args) == 1 and (istestfunc(func) or is_class):
356
+ store_mark(func, self.mark, stacklevel=3)
357
+ return func
358
+ return self.with_args(*args, **kwargs)
359
+
360
+
361
+ def get_unpacked_marks(
362
+ obj: object | type,
363
+ *,
364
+ consider_mro: bool = True,
365
+ ) -> list[Mark]:
366
+ """Obtain the unpacked marks that are stored on an object.
367
+
368
+ If obj is a class and consider_mro is true, return marks applied to
369
+ this class and all of its super-classes in MRO order. If consider_mro
370
+ is false, only return marks applied directly to this class.
371
+ """
372
+ if isinstance(obj, type):
373
+ if not consider_mro:
374
+ mark_lists = [obj.__dict__.get("pytestmark", [])]
375
+ else:
376
+ mark_lists = [
377
+ x.__dict__.get("pytestmark", []) for x in reversed(obj.__mro__)
378
+ ]
379
+ mark_list = []
380
+ for item in mark_lists:
381
+ if isinstance(item, list):
382
+ mark_list.extend(item)
383
+ else:
384
+ mark_list.append(item)
385
+ else:
386
+ mark_attribute = getattr(obj, "pytestmark", [])
387
+ if isinstance(mark_attribute, list):
388
+ mark_list = mark_attribute
389
+ else:
390
+ mark_list = [mark_attribute]
391
+ return list(normalize_mark_list(mark_list))
392
+
393
+
394
+ def normalize_mark_list(
395
+ mark_list: Iterable[Mark | MarkDecorator],
396
+ ) -> Iterable[Mark]:
397
+ """
398
+ Normalize an iterable of Mark or MarkDecorator objects into a list of marks
399
+ by retrieving the `mark` attribute on MarkDecorator instances.
400
+
401
+ :param mark_list: marks to normalize
402
+ :returns: A new list of the extracted Mark objects
403
+ """
404
+ for mark in mark_list:
405
+ mark_obj = getattr(mark, "mark", mark)
406
+ if not isinstance(mark_obj, Mark):
407
+ raise TypeError(f"got {mark_obj!r} instead of Mark")
408
+ yield mark_obj
409
+
410
+
411
+ def store_mark(obj, mark: Mark, *, stacklevel: int = 2) -> None:
412
+ """Store a Mark on an object.
413
+
414
+ This is used to implement the Mark declarations/decorators correctly.
415
+ """
416
+ assert isinstance(mark, Mark), mark
417
+
418
+ from ..fixtures import getfixturemarker
419
+
420
+ if getfixturemarker(obj) is not None:
421
+ warnings.warn(MARKED_FIXTURE, stacklevel=stacklevel)
422
+
423
+ # Always reassign name to avoid updating pytestmark in a reference that
424
+ # was only borrowed.
425
+ obj.pytestmark = [*get_unpacked_marks(obj, consider_mro=False), mark]
426
+
427
+
428
+ # Typing for builtin pytest marks. This is cheating; it gives builtin marks
429
+ # special privilege, and breaks modularity. But practicality beats purity...
430
+ if TYPE_CHECKING:
431
+
432
+ class _SkipMarkDecorator(MarkDecorator):
433
+ @overload # type: ignore[override,no-overload-impl]
434
+ def __call__(self, arg: Markable) -> Markable: ...
435
+
436
+ @overload
437
+ def __call__(self, reason: str = ...) -> MarkDecorator: ...
438
+
439
+ class _SkipifMarkDecorator(MarkDecorator):
440
+ def __call__( # type: ignore[override]
441
+ self,
442
+ condition: str | bool = ...,
443
+ *conditions: str | bool,
444
+ reason: str = ...,
445
+ ) -> MarkDecorator: ...
446
+
447
+ class _XfailMarkDecorator(MarkDecorator):
448
+ @overload # type: ignore[override,no-overload-impl]
449
+ def __call__(self, arg: Markable) -> Markable: ...
450
+
451
+ @overload
452
+ def __call__(
453
+ self,
454
+ condition: str | bool = False,
455
+ *conditions: str | bool,
456
+ reason: str = ...,
457
+ run: bool = ...,
458
+ raises: None | type[BaseException] | tuple[type[BaseException], ...] = ...,
459
+ strict: bool = ...,
460
+ ) -> MarkDecorator: ...
461
+
462
+ class _ParametrizeMarkDecorator(MarkDecorator):
463
+ def __call__( # type: ignore[override]
464
+ self,
465
+ argnames: str | Sequence[str],
466
+ argvalues: Iterable[ParameterSet | Sequence[object] | object],
467
+ *,
468
+ indirect: bool | Sequence[str] = ...,
469
+ ids: Iterable[None | str | float | int | bool]
470
+ | Callable[[Any], object | None]
471
+ | None = ...,
472
+ scope: _ScopeName | None = ...,
473
+ ) -> MarkDecorator: ...
474
+
475
+ class _UsefixturesMarkDecorator(MarkDecorator):
476
+ def __call__(self, *fixtures: str) -> MarkDecorator: # type: ignore[override]
477
+ ...
478
+
479
+ class _FilterwarningsMarkDecorator(MarkDecorator):
480
+ def __call__(self, *filters: str) -> MarkDecorator: # type: ignore[override]
481
+ ...
482
+
483
+
484
+ @final
485
+ class MarkGenerator:
486
+ """Factory for :class:`MarkDecorator` objects - exposed as
487
+ a ``pytest.mark`` singleton instance.
488
+
489
+ Example::
490
+
491
+ import pytest
492
+
493
+
494
+ @pytest.mark.slowtest
495
+ def test_function():
496
+ pass
497
+
498
+ applies a 'slowtest' :class:`Mark` on ``test_function``.
499
+ """
500
+
501
+ # See TYPE_CHECKING above.
502
+ if TYPE_CHECKING:
503
+ skip: _SkipMarkDecorator
504
+ skipif: _SkipifMarkDecorator
505
+ xfail: _XfailMarkDecorator
506
+ parametrize: _ParametrizeMarkDecorator
507
+ usefixtures: _UsefixturesMarkDecorator
508
+ filterwarnings: _FilterwarningsMarkDecorator
509
+
510
+ def __init__(self, *, _ispytest: bool = False) -> None:
511
+ check_ispytest(_ispytest)
512
+ self._config: Config | None = None
513
+ self._markers: set[str] = set()
514
+
515
+ def __getattr__(self, name: str) -> MarkDecorator:
516
+ """Generate a new :class:`MarkDecorator` with the given name."""
517
+ if name[0] == "_":
518
+ raise AttributeError("Marker name must NOT start with underscore")
519
+
520
+ if self._config is not None:
521
+ # We store a set of markers as a performance optimisation - if a mark
522
+ # name is in the set we definitely know it, but a mark may be known and
523
+ # not in the set. We therefore start by updating the set!
524
+ if name not in self._markers:
525
+ for line in self._config.getini("markers"):
526
+ # example lines: "skipif(condition): skip the given test if..."
527
+ # or "hypothesis: tests which use Hypothesis", so to get the
528
+ # marker name we split on both `:` and `(`.
529
+ marker = line.split(":")[0].split("(")[0].strip()
530
+ self._markers.add(marker)
531
+
532
+ # If the name is not in the set of known marks after updating,
533
+ # then it really is time to issue a warning or an error.
534
+ if name not in self._markers:
535
+ if self._config.option.strict_markers or self._config.option.strict:
536
+ fail(
537
+ f"{name!r} not found in `markers` configuration option",
538
+ pytrace=False,
539
+ )
540
+
541
+ # Raise a specific error for common misspellings of "parametrize".
542
+ if name in ["parameterize", "parametrise", "parameterise"]:
543
+ __tracebackhide__ = True
544
+ fail(f"Unknown '{name}' mark, did you mean 'parametrize'?")
545
+
546
+ warnings.warn(
547
+ f"Unknown pytest.mark.{name} - is this a typo? You can register "
548
+ "custom marks to avoid this warning - for details, see "
549
+ "https://docs.pytest.org/en/stable/how-to/mark.html",
550
+ PytestUnknownMarkWarning,
551
+ 2,
552
+ )
553
+
554
+ return MarkDecorator(Mark(name, (), {}, _ispytest=True), _ispytest=True)
555
+
556
+
557
+ MARK_GEN = MarkGenerator(_ispytest=True)
558
+
559
+
560
+ @final
561
+ class NodeKeywords(MutableMapping[str, Any]):
562
+ __slots__ = ("node", "parent", "_markers")
563
+
564
+ def __init__(self, node: Node) -> None:
565
+ self.node = node
566
+ self.parent = node.parent
567
+ self._markers = {node.name: True}
568
+
569
+ def __getitem__(self, key: str) -> Any:
570
+ try:
571
+ return self._markers[key]
572
+ except KeyError:
573
+ if self.parent is None:
574
+ raise
575
+ return self.parent.keywords[key]
576
+
577
+ def __setitem__(self, key: str, value: Any) -> None:
578
+ self._markers[key] = value
579
+
580
+ # Note: we could've avoided explicitly implementing some of the methods
581
+ # below and use the collections.abc fallback, but that would be slow.
582
+
583
+ def __contains__(self, key: object) -> bool:
584
+ return (
585
+ key in self._markers
586
+ or self.parent is not None
587
+ and key in self.parent.keywords
588
+ )
589
+
590
+ def update( # type: ignore[override]
591
+ self,
592
+ other: Mapping[str, Any] | Iterable[tuple[str, Any]] = (),
593
+ **kwds: Any,
594
+ ) -> None:
595
+ self._markers.update(other)
596
+ self._markers.update(kwds)
597
+
598
+ def __delitem__(self, key: str) -> None:
599
+ raise ValueError("cannot delete key in keywords dict")
600
+
601
+ def __iter__(self) -> Iterator[str]:
602
+ # Doesn't need to be fast.
603
+ yield from self._markers
604
+ if self.parent is not None:
605
+ for keyword in self.parent.keywords:
606
+ # self._marks and self.parent.keywords can have duplicates.
607
+ if keyword not in self._markers:
608
+ yield keyword
609
+
610
+ def __len__(self) -> int:
611
+ # Doesn't need to be fast.
612
+ return sum(1 for keyword in self)
613
+
614
+ def __repr__(self) -> str:
615
+ return f"<NodeKeywords for node {self.node}>"
vllm/lib/python3.10/site-packages/_pytest/monkeypatch.py ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """Monkeypatching and mocking functionality."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from contextlib import contextmanager
7
+ import os
8
+ import re
9
+ import sys
10
+ from typing import Any
11
+ from typing import final
12
+ from typing import Generator
13
+ from typing import Mapping
14
+ from typing import MutableMapping
15
+ from typing import overload
16
+ from typing import TypeVar
17
+ import warnings
18
+
19
+ from _pytest.fixtures import fixture
20
+ from _pytest.warning_types import PytestWarning
21
+
22
+
23
+ RE_IMPORT_ERROR_NAME = re.compile(r"^No module named (.*)$")
24
+
25
+
26
+ K = TypeVar("K")
27
+ V = TypeVar("V")
28
+
29
+
30
+ @fixture
31
+ def monkeypatch() -> Generator[MonkeyPatch]:
32
+ """A convenient fixture for monkey-patching.
33
+
34
+ The fixture provides these methods to modify objects, dictionaries, or
35
+ :data:`os.environ`:
36
+
37
+ * :meth:`monkeypatch.setattr(obj, name, value, raising=True) <pytest.MonkeyPatch.setattr>`
38
+ * :meth:`monkeypatch.delattr(obj, name, raising=True) <pytest.MonkeyPatch.delattr>`
39
+ * :meth:`monkeypatch.setitem(mapping, name, value) <pytest.MonkeyPatch.setitem>`
40
+ * :meth:`monkeypatch.delitem(obj, name, raising=True) <pytest.MonkeyPatch.delitem>`
41
+ * :meth:`monkeypatch.setenv(name, value, prepend=None) <pytest.MonkeyPatch.setenv>`
42
+ * :meth:`monkeypatch.delenv(name, raising=True) <pytest.MonkeyPatch.delenv>`
43
+ * :meth:`monkeypatch.syspath_prepend(path) <pytest.MonkeyPatch.syspath_prepend>`
44
+ * :meth:`monkeypatch.chdir(path) <pytest.MonkeyPatch.chdir>`
45
+ * :meth:`monkeypatch.context() <pytest.MonkeyPatch.context>`
46
+
47
+ All modifications will be undone after the requesting test function or
48
+ fixture has finished. The ``raising`` parameter determines if a :class:`KeyError`
49
+ or :class:`AttributeError` will be raised if the set/deletion operation does not have the
50
+ specified target.
51
+
52
+ To undo modifications done by the fixture in a contained scope,
53
+ use :meth:`context() <pytest.MonkeyPatch.context>`.
54
+ """
55
+ mpatch = MonkeyPatch()
56
+ yield mpatch
57
+ mpatch.undo()
58
+
59
+
60
+ def resolve(name: str) -> object:
61
+ # Simplified from zope.dottedname.
62
+ parts = name.split(".")
63
+
64
+ used = parts.pop(0)
65
+ found: object = __import__(used)
66
+ for part in parts:
67
+ used += "." + part
68
+ try:
69
+ found = getattr(found, part)
70
+ except AttributeError:
71
+ pass
72
+ else:
73
+ continue
74
+ # We use explicit un-nesting of the handling block in order
75
+ # to avoid nested exceptions.
76
+ try:
77
+ __import__(used)
78
+ except ImportError as ex:
79
+ expected = str(ex).split()[-1]
80
+ if expected == used:
81
+ raise
82
+ else:
83
+ raise ImportError(f"import error in {used}: {ex}") from ex
84
+ found = annotated_getattr(found, part, used)
85
+ return found
86
+
87
+
88
+ def annotated_getattr(obj: object, name: str, ann: str) -> object:
89
+ try:
90
+ obj = getattr(obj, name)
91
+ except AttributeError as e:
92
+ raise AttributeError(
93
+ f"{type(obj).__name__!r} object at {ann} has no attribute {name!r}"
94
+ ) from e
95
+ return obj
96
+
97
+
98
+ def derive_importpath(import_path: str, raising: bool) -> tuple[str, object]:
99
+ if not isinstance(import_path, str) or "." not in import_path:
100
+ raise TypeError(f"must be absolute import path string, not {import_path!r}")
101
+ module, attr = import_path.rsplit(".", 1)
102
+ target = resolve(module)
103
+ if raising:
104
+ annotated_getattr(target, attr, ann=module)
105
+ return attr, target
106
+
107
+
108
+ class Notset:
109
+ def __repr__(self) -> str:
110
+ return "<notset>"
111
+
112
+
113
+ notset = Notset()
114
+
115
+
116
+ @final
117
+ class MonkeyPatch:
118
+ """Helper to conveniently monkeypatch attributes/items/environment
119
+ variables/syspath.
120
+
121
+ Returned by the :fixture:`monkeypatch` fixture.
122
+
123
+ .. versionchanged:: 6.2
124
+ Can now also be used directly as `pytest.MonkeyPatch()`, for when
125
+ the fixture is not available. In this case, use
126
+ :meth:`with MonkeyPatch.context() as mp: <context>` or remember to call
127
+ :meth:`undo` explicitly.
128
+ """
129
+
130
+ def __init__(self) -> None:
131
+ self._setattr: list[tuple[object, str, object]] = []
132
+ self._setitem: list[tuple[Mapping[Any, Any], object, object]] = []
133
+ self._cwd: str | None = None
134
+ self._savesyspath: list[str] | None = None
135
+
136
+ @classmethod
137
+ @contextmanager
138
+ def context(cls) -> Generator[MonkeyPatch]:
139
+ """Context manager that returns a new :class:`MonkeyPatch` object
140
+ which undoes any patching done inside the ``with`` block upon exit.
141
+
142
+ Example:
143
+
144
+ .. code-block:: python
145
+
146
+ import functools
147
+
148
+
149
+ def test_partial(monkeypatch):
150
+ with monkeypatch.context() as m:
151
+ m.setattr(functools, "partial", 3)
152
+
153
+ Useful in situations where it is desired to undo some patches before the test ends,
154
+ such as mocking ``stdlib`` functions that might break pytest itself if mocked (for examples
155
+ of this see :issue:`3290`).
156
+ """
157
+ m = cls()
158
+ try:
159
+ yield m
160
+ finally:
161
+ m.undo()
162
+
163
+ @overload
164
+ def setattr(
165
+ self,
166
+ target: str,
167
+ name: object,
168
+ value: Notset = ...,
169
+ raising: bool = ...,
170
+ ) -> None: ...
171
+
172
+ @overload
173
+ def setattr(
174
+ self,
175
+ target: object,
176
+ name: str,
177
+ value: object,
178
+ raising: bool = ...,
179
+ ) -> None: ...
180
+
181
+ def setattr(
182
+ self,
183
+ target: str | object,
184
+ name: object | str,
185
+ value: object = notset,
186
+ raising: bool = True,
187
+ ) -> None:
188
+ """
189
+ Set attribute value on target, memorizing the old value.
190
+
191
+ For example:
192
+
193
+ .. code-block:: python
194
+
195
+ import os
196
+
197
+ monkeypatch.setattr(os, "getcwd", lambda: "/")
198
+
199
+ The code above replaces the :func:`os.getcwd` function by a ``lambda`` which
200
+ always returns ``"/"``.
201
+
202
+ For convenience, you can specify a string as ``target`` which
203
+ will be interpreted as a dotted import path, with the last part
204
+ being the attribute name:
205
+
206
+ .. code-block:: python
207
+
208
+ monkeypatch.setattr("os.getcwd", lambda: "/")
209
+
210
+ Raises :class:`AttributeError` if the attribute does not exist, unless
211
+ ``raising`` is set to False.
212
+
213
+ **Where to patch**
214
+
215
+ ``monkeypatch.setattr`` works by (temporarily) changing the object that a name points to with another one.
216
+ There can be many names pointing to any individual object, so for patching to work you must ensure
217
+ that you patch the name used by the system under test.
218
+
219
+ See the section :ref:`Where to patch <python:where-to-patch>` in the :mod:`unittest.mock`
220
+ docs for a complete explanation, which is meant for :func:`unittest.mock.patch` but
221
+ applies to ``monkeypatch.setattr`` as well.
222
+ """
223
+ __tracebackhide__ = True
224
+ import inspect
225
+
226
+ if isinstance(value, Notset):
227
+ if not isinstance(target, str):
228
+ raise TypeError(
229
+ "use setattr(target, name, value) or "
230
+ "setattr(target, value) with target being a dotted "
231
+ "import string"
232
+ )
233
+ value = name
234
+ name, target = derive_importpath(target, raising)
235
+ else:
236
+ if not isinstance(name, str):
237
+ raise TypeError(
238
+ "use setattr(target, name, value) with name being a string or "
239
+ "setattr(target, value) with target being a dotted "
240
+ "import string"
241
+ )
242
+
243
+ oldval = getattr(target, name, notset)
244
+ if raising and oldval is notset:
245
+ raise AttributeError(f"{target!r} has no attribute {name!r}")
246
+
247
+ # avoid class descriptors like staticmethod/classmethod
248
+ if inspect.isclass(target):
249
+ oldval = target.__dict__.get(name, notset)
250
+ self._setattr.append((target, name, oldval))
251
+ setattr(target, name, value)
252
+
253
+ def delattr(
254
+ self,
255
+ target: object | str,
256
+ name: str | Notset = notset,
257
+ raising: bool = True,
258
+ ) -> None:
259
+ """Delete attribute ``name`` from ``target``.
260
+
261
+ If no ``name`` is specified and ``target`` is a string
262
+ it will be interpreted as a dotted import path with the
263
+ last part being the attribute name.
264
+
265
+ Raises AttributeError it the attribute does not exist, unless
266
+ ``raising`` is set to False.
267
+ """
268
+ __tracebackhide__ = True
269
+ import inspect
270
+
271
+ if isinstance(name, Notset):
272
+ if not isinstance(target, str):
273
+ raise TypeError(
274
+ "use delattr(target, name) or "
275
+ "delattr(target) with target being a dotted "
276
+ "import string"
277
+ )
278
+ name, target = derive_importpath(target, raising)
279
+
280
+ if not hasattr(target, name):
281
+ if raising:
282
+ raise AttributeError(name)
283
+ else:
284
+ oldval = getattr(target, name, notset)
285
+ # Avoid class descriptors like staticmethod/classmethod.
286
+ if inspect.isclass(target):
287
+ oldval = target.__dict__.get(name, notset)
288
+ self._setattr.append((target, name, oldval))
289
+ delattr(target, name)
290
+
291
+ def setitem(self, dic: Mapping[K, V], name: K, value: V) -> None:
292
+ """Set dictionary entry ``name`` to value."""
293
+ self._setitem.append((dic, name, dic.get(name, notset)))
294
+ # Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict
295
+ dic[name] = value # type: ignore[index]
296
+
297
+ def delitem(self, dic: Mapping[K, V], name: K, raising: bool = True) -> None:
298
+ """Delete ``name`` from dict.
299
+
300
+ Raises ``KeyError`` if it doesn't exist, unless ``raising`` is set to
301
+ False.
302
+ """
303
+ if name not in dic:
304
+ if raising:
305
+ raise KeyError(name)
306
+ else:
307
+ self._setitem.append((dic, name, dic.get(name, notset)))
308
+ # Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict
309
+ del dic[name] # type: ignore[attr-defined]
310
+
311
+ def setenv(self, name: str, value: str, prepend: str | None = None) -> None:
312
+ """Set environment variable ``name`` to ``value``.
313
+
314
+ If ``prepend`` is a character, read the current environment variable
315
+ value and prepend the ``value`` adjoined with the ``prepend``
316
+ character.
317
+ """
318
+ if not isinstance(value, str):
319
+ warnings.warn( # type: ignore[unreachable]
320
+ PytestWarning(
321
+ f"Value of environment variable {name} type should be str, but got "
322
+ f"{value!r} (type: {type(value).__name__}); converted to str implicitly"
323
+ ),
324
+ stacklevel=2,
325
+ )
326
+ value = str(value)
327
+ if prepend and name in os.environ:
328
+ value = value + prepend + os.environ[name]
329
+ self.setitem(os.environ, name, value)
330
+
331
+ def delenv(self, name: str, raising: bool = True) -> None:
332
+ """Delete ``name`` from the environment.
333
+
334
+ Raises ``KeyError`` if it does not exist, unless ``raising`` is set to
335
+ False.
336
+ """
337
+ environ: MutableMapping[str, str] = os.environ
338
+ self.delitem(environ, name, raising=raising)
339
+
340
+ def syspath_prepend(self, path) -> None:
341
+ """Prepend ``path`` to ``sys.path`` list of import locations."""
342
+ if self._savesyspath is None:
343
+ self._savesyspath = sys.path[:]
344
+ sys.path.insert(0, str(path))
345
+
346
+ # https://github.com/pypa/setuptools/blob/d8b901bc/docs/pkg_resources.txt#L162-L171
347
+ # this is only needed when pkg_resources was already loaded by the namespace package
348
+ if "pkg_resources" in sys.modules:
349
+ from pkg_resources import fixup_namespace_packages
350
+
351
+ fixup_namespace_packages(str(path))
352
+
353
+ # A call to syspathinsert() usually means that the caller wants to
354
+ # import some dynamically created files, thus with python3 we
355
+ # invalidate its import caches.
356
+ # This is especially important when any namespace package is in use,
357
+ # since then the mtime based FileFinder cache (that gets created in
358
+ # this case already) gets not invalidated when writing the new files
359
+ # quickly afterwards.
360
+ from importlib import invalidate_caches
361
+
362
+ invalidate_caches()
363
+
364
+ def chdir(self, path: str | os.PathLike[str]) -> None:
365
+ """Change the current working directory to the specified path.
366
+
367
+ :param path:
368
+ The path to change into.
369
+ """
370
+ if self._cwd is None:
371
+ self._cwd = os.getcwd()
372
+ os.chdir(path)
373
+
374
+ def undo(self) -> None:
375
+ """Undo previous changes.
376
+
377
+ This call consumes the undo stack. Calling it a second time has no
378
+ effect unless you do more monkeypatching after the undo call.
379
+
380
+ There is generally no need to call `undo()`, since it is
381
+ called automatically during tear-down.
382
+
383
+ .. note::
384
+ The same `monkeypatch` fixture is used across a
385
+ single test function invocation. If `monkeypatch` is used both by
386
+ the test function itself and one of the test fixtures,
387
+ calling `undo()` will undo all of the changes made in
388
+ both functions.
389
+
390
+ Prefer to use :meth:`context() <pytest.MonkeyPatch.context>` instead.
391
+ """
392
+ for obj, name, value in reversed(self._setattr):
393
+ if value is not notset:
394
+ setattr(obj, name, value)
395
+ else:
396
+ delattr(obj, name)
397
+ self._setattr[:] = []
398
+ for dictionary, key, value in reversed(self._setitem):
399
+ if value is notset:
400
+ try:
401
+ # Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict
402
+ del dictionary[key] # type: ignore[attr-defined]
403
+ except KeyError:
404
+ pass # Was already deleted, so we have the desired state.
405
+ else:
406
+ # Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict
407
+ dictionary[key] = value # type: ignore[index]
408
+ self._setitem[:] = []
409
+ if self._savesyspath is not None:
410
+ sys.path[:] = self._savesyspath
411
+ self._savesyspath = None
412
+
413
+ if self._cwd is not None:
414
+ os.chdir(self._cwd)
415
+ self._cwd = None
vllm/lib/python3.10/site-packages/_pytest/outcomes.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exception classes and constants handling test outcomes as well as
2
+ functions creating them."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import sys
7
+ from typing import Any
8
+ from typing import Callable
9
+ from typing import cast
10
+ from typing import NoReturn
11
+ from typing import Protocol
12
+ from typing import Type
13
+ from typing import TypeVar
14
+
15
+ from .warning_types import PytestDeprecationWarning
16
+
17
+
18
+ class OutcomeException(BaseException):
19
+ """OutcomeException and its subclass instances indicate and contain info
20
+ about test and collection outcomes."""
21
+
22
+ def __init__(self, msg: str | None = None, pytrace: bool = True) -> None:
23
+ if msg is not None and not isinstance(msg, str):
24
+ error_msg = ( # type: ignore[unreachable]
25
+ "{} expected string as 'msg' parameter, got '{}' instead.\n"
26
+ "Perhaps you meant to use a mark?"
27
+ )
28
+ raise TypeError(error_msg.format(type(self).__name__, type(msg).__name__))
29
+ super().__init__(msg)
30
+ self.msg = msg
31
+ self.pytrace = pytrace
32
+
33
+ def __repr__(self) -> str:
34
+ if self.msg is not None:
35
+ return self.msg
36
+ return f"<{self.__class__.__name__} instance>"
37
+
38
+ __str__ = __repr__
39
+
40
+
41
+ TEST_OUTCOME = (OutcomeException, Exception)
42
+
43
+
44
+ class Skipped(OutcomeException):
45
+ # XXX hackish: on 3k we fake to live in the builtins
46
+ # in order to have Skipped exception printing shorter/nicer
47
+ __module__ = "builtins"
48
+
49
+ def __init__(
50
+ self,
51
+ msg: str | None = None,
52
+ pytrace: bool = True,
53
+ allow_module_level: bool = False,
54
+ *,
55
+ _use_item_location: bool = False,
56
+ ) -> None:
57
+ super().__init__(msg=msg, pytrace=pytrace)
58
+ self.allow_module_level = allow_module_level
59
+ # If true, the skip location is reported as the item's location,
60
+ # instead of the place that raises the exception/calls skip().
61
+ self._use_item_location = _use_item_location
62
+
63
+
64
+ class Failed(OutcomeException):
65
+ """Raised from an explicit call to pytest.fail()."""
66
+
67
+ __module__ = "builtins"
68
+
69
+
70
+ class Exit(Exception):
71
+ """Raised for immediate program exits (no tracebacks/summaries)."""
72
+
73
+ def __init__(
74
+ self, msg: str = "unknown reason", returncode: int | None = None
75
+ ) -> None:
76
+ self.msg = msg
77
+ self.returncode = returncode
78
+ super().__init__(msg)
79
+
80
+
81
+ # Elaborate hack to work around https://github.com/python/mypy/issues/2087.
82
+ # Ideally would just be `exit.Exception = Exit` etc.
83
+
84
+ _F = TypeVar("_F", bound=Callable[..., object])
85
+ _ET = TypeVar("_ET", bound=Type[BaseException])
86
+
87
+
88
+ class _WithException(Protocol[_F, _ET]):
89
+ Exception: _ET
90
+ __call__: _F
91
+
92
+
93
+ def _with_exception(exception_type: _ET) -> Callable[[_F], _WithException[_F, _ET]]:
94
+ def decorate(func: _F) -> _WithException[_F, _ET]:
95
+ func_with_exception = cast(_WithException[_F, _ET], func)
96
+ func_with_exception.Exception = exception_type
97
+ return func_with_exception
98
+
99
+ return decorate
100
+
101
+
102
+ # Exposed helper methods.
103
+
104
+
105
+ @_with_exception(Exit)
106
+ def exit(
107
+ reason: str = "",
108
+ returncode: int | None = None,
109
+ ) -> NoReturn:
110
+ """Exit testing process.
111
+
112
+ :param reason:
113
+ The message to show as the reason for exiting pytest. reason has a default value
114
+ only because `msg` is deprecated.
115
+
116
+ :param returncode:
117
+ Return code to be used when exiting pytest. None means the same as ``0`` (no error), same as :func:`sys.exit`.
118
+
119
+ :raises pytest.exit.Exception:
120
+ The exception that is raised.
121
+ """
122
+ __tracebackhide__ = True
123
+ raise Exit(reason, returncode)
124
+
125
+
126
+ @_with_exception(Skipped)
127
+ def skip(
128
+ reason: str = "",
129
+ *,
130
+ allow_module_level: bool = False,
131
+ ) -> NoReturn:
132
+ """Skip an executing test with the given message.
133
+
134
+ This function should be called only during testing (setup, call or teardown) or
135
+ during collection by using the ``allow_module_level`` flag. This function can
136
+ be called in doctests as well.
137
+
138
+ :param reason:
139
+ The message to show the user as reason for the skip.
140
+
141
+ :param allow_module_level:
142
+ Allows this function to be called at module level.
143
+ Raising the skip exception at module level will stop
144
+ the execution of the module and prevent the collection of all tests in the module,
145
+ even those defined before the `skip` call.
146
+
147
+ Defaults to False.
148
+
149
+ :raises pytest.skip.Exception:
150
+ The exception that is raised.
151
+
152
+ .. note::
153
+ It is better to use the :ref:`pytest.mark.skipif ref` marker when
154
+ possible to declare a test to be skipped under certain conditions
155
+ like mismatching platforms or dependencies.
156
+ Similarly, use the ``# doctest: +SKIP`` directive (see :py:data:`doctest.SKIP`)
157
+ to skip a doctest statically.
158
+ """
159
+ __tracebackhide__ = True
160
+ raise Skipped(msg=reason, allow_module_level=allow_module_level)
161
+
162
+
163
+ @_with_exception(Failed)
164
+ def fail(reason: str = "", pytrace: bool = True) -> NoReturn:
165
+ """Explicitly fail an executing test with the given message.
166
+
167
+ :param reason:
168
+ The message to show the user as reason for the failure.
169
+
170
+ :param pytrace:
171
+ If False, msg represents the full failure information and no
172
+ python traceback will be reported.
173
+
174
+ :raises pytest.fail.Exception:
175
+ The exception that is raised.
176
+ """
177
+ __tracebackhide__ = True
178
+ raise Failed(msg=reason, pytrace=pytrace)
179
+
180
+
181
+ class XFailed(Failed):
182
+ """Raised from an explicit call to pytest.xfail()."""
183
+
184
+
185
+ @_with_exception(XFailed)
186
+ def xfail(reason: str = "") -> NoReturn:
187
+ """Imperatively xfail an executing test or setup function with the given reason.
188
+
189
+ This function should be called only during testing (setup, call or teardown).
190
+
191
+ No other code is executed after using ``xfail()`` (it is implemented
192
+ internally by raising an exception).
193
+
194
+ :param reason:
195
+ The message to show the user as reason for the xfail.
196
+
197
+ .. note::
198
+ It is better to use the :ref:`pytest.mark.xfail ref` marker when
199
+ possible to declare a test to be xfailed under certain conditions
200
+ like known bugs or missing features.
201
+
202
+ :raises pytest.xfail.Exception:
203
+ The exception that is raised.
204
+ """
205
+ __tracebackhide__ = True
206
+ raise XFailed(reason)
207
+
208
+
209
+ def importorskip(
210
+ modname: str,
211
+ minversion: str | None = None,
212
+ reason: str | None = None,
213
+ *,
214
+ exc_type: type[ImportError] | None = None,
215
+ ) -> Any:
216
+ """Import and return the requested module ``modname``, or skip the
217
+ current test if the module cannot be imported.
218
+
219
+ :param modname:
220
+ The name of the module to import.
221
+ :param minversion:
222
+ If given, the imported module's ``__version__`` attribute must be at
223
+ least this minimal version, otherwise the test is still skipped.
224
+ :param reason:
225
+ If given, this reason is shown as the message when the module cannot
226
+ be imported.
227
+ :param exc_type:
228
+ The exception that should be captured in order to skip modules.
229
+ Must be :py:class:`ImportError` or a subclass.
230
+
231
+ If the module can be imported but raises :class:`ImportError`, pytest will
232
+ issue a warning to the user, as often users expect the module not to be
233
+ found (which would raise :class:`ModuleNotFoundError` instead).
234
+
235
+ This warning can be suppressed by passing ``exc_type=ImportError`` explicitly.
236
+
237
+ See :ref:`import-or-skip-import-error` for details.
238
+
239
+
240
+ :returns:
241
+ The imported module. This should be assigned to its canonical name.
242
+
243
+ :raises pytest.skip.Exception:
244
+ If the module cannot be imported.
245
+
246
+ Example::
247
+
248
+ docutils = pytest.importorskip("docutils")
249
+
250
+ .. versionadded:: 8.2
251
+
252
+ The ``exc_type`` parameter.
253
+ """
254
+ import warnings
255
+
256
+ __tracebackhide__ = True
257
+ compile(modname, "", "eval") # to catch syntaxerrors
258
+
259
+ # Until pytest 9.1, we will warn the user if we catch ImportError (instead of ModuleNotFoundError),
260
+ # as this might be hiding an installation/environment problem, which is not usually what is intended
261
+ # when using importorskip() (#11523).
262
+ # In 9.1, to keep the function signature compatible, we just change the code below to:
263
+ # 1. Use `exc_type = ModuleNotFoundError` if `exc_type` is not given.
264
+ # 2. Remove `warn_on_import` and the warning handling.
265
+ if exc_type is None:
266
+ exc_type = ImportError
267
+ warn_on_import_error = True
268
+ else:
269
+ warn_on_import_error = False
270
+
271
+ skipped: Skipped | None = None
272
+ warning: Warning | None = None
273
+
274
+ with warnings.catch_warnings():
275
+ # Make sure to ignore ImportWarnings that might happen because
276
+ # of existing directories with the same name we're trying to
277
+ # import but without a __init__.py file.
278
+ warnings.simplefilter("ignore")
279
+
280
+ try:
281
+ __import__(modname)
282
+ except exc_type as exc:
283
+ # Do not raise or issue warnings inside the catch_warnings() block.
284
+ if reason is None:
285
+ reason = f"could not import {modname!r}: {exc}"
286
+ skipped = Skipped(reason, allow_module_level=True)
287
+
288
+ if warn_on_import_error and not isinstance(exc, ModuleNotFoundError):
289
+ lines = [
290
+ "",
291
+ f"Module '{modname}' was found, but when imported by pytest it raised:",
292
+ f" {exc!r}",
293
+ "In pytest 9.1 this warning will become an error by default.",
294
+ "You can fix the underlying problem, or alternatively overwrite this behavior and silence this "
295
+ "warning by passing exc_type=ImportError explicitly.",
296
+ "See https://docs.pytest.org/en/stable/deprecations.html#pytest-importorskip-default-behavior-regarding-importerror",
297
+ ]
298
+ warning = PytestDeprecationWarning("\n".join(lines))
299
+
300
+ if warning:
301
+ warnings.warn(warning, stacklevel=2)
302
+ if skipped:
303
+ raise skipped
304
+
305
+ mod = sys.modules[modname]
306
+ if minversion is None:
307
+ return mod
308
+ verattr = getattr(mod, "__version__", None)
309
+ if minversion is not None:
310
+ # Imported lazily to improve start-up time.
311
+ from packaging.version import Version
312
+
313
+ if verattr is None or Version(verattr) < Version(minversion):
314
+ raise Skipped(
315
+ f"module {modname!r} has __version__ {verattr!r}, required is: {minversion!r}",
316
+ allow_module_level=True,
317
+ )
318
+ return mod
vllm/lib/python3.10/site-packages/_pytest/pastebin.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """Submit failure or test session information to a pastebin service."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from io import StringIO
7
+ import tempfile
8
+ from typing import IO
9
+
10
+ from _pytest.config import Config
11
+ from _pytest.config import create_terminal_writer
12
+ from _pytest.config.argparsing import Parser
13
+ from _pytest.stash import StashKey
14
+ from _pytest.terminal import TerminalReporter
15
+ import pytest
16
+
17
+
18
+ pastebinfile_key = StashKey[IO[bytes]]()
19
+
20
+
21
+ def pytest_addoption(parser: Parser) -> None:
22
+ group = parser.getgroup("terminal reporting")
23
+ group._addoption(
24
+ "--pastebin",
25
+ metavar="mode",
26
+ action="store",
27
+ dest="pastebin",
28
+ default=None,
29
+ choices=["failed", "all"],
30
+ help="Send failed|all info to bpaste.net pastebin service",
31
+ )
32
+
33
+
34
+ @pytest.hookimpl(trylast=True)
35
+ def pytest_configure(config: Config) -> None:
36
+ if config.option.pastebin == "all":
37
+ tr = config.pluginmanager.getplugin("terminalreporter")
38
+ # If no terminal reporter plugin is present, nothing we can do here;
39
+ # this can happen when this function executes in a worker node
40
+ # when using pytest-xdist, for example.
41
+ if tr is not None:
42
+ # pastebin file will be UTF-8 encoded binary file.
43
+ config.stash[pastebinfile_key] = tempfile.TemporaryFile("w+b")
44
+ oldwrite = tr._tw.write
45
+
46
+ def tee_write(s, **kwargs):
47
+ oldwrite(s, **kwargs)
48
+ if isinstance(s, str):
49
+ s = s.encode("utf-8")
50
+ config.stash[pastebinfile_key].write(s)
51
+
52
+ tr._tw.write = tee_write
53
+
54
+
55
+ def pytest_unconfigure(config: Config) -> None:
56
+ if pastebinfile_key in config.stash:
57
+ pastebinfile = config.stash[pastebinfile_key]
58
+ # Get terminal contents and delete file.
59
+ pastebinfile.seek(0)
60
+ sessionlog = pastebinfile.read()
61
+ pastebinfile.close()
62
+ del config.stash[pastebinfile_key]
63
+ # Undo our patching in the terminal reporter.
64
+ tr = config.pluginmanager.getplugin("terminalreporter")
65
+ del tr._tw.__dict__["write"]
66
+ # Write summary.
67
+ tr.write_sep("=", "Sending information to Paste Service")
68
+ pastebinurl = create_new_paste(sessionlog)
69
+ tr.write_line(f"pastebin session-log: {pastebinurl}\n")
70
+
71
+
72
+ def create_new_paste(contents: str | bytes) -> str:
73
+ """Create a new paste using the bpaste.net service.
74
+
75
+ :contents: Paste contents string.
76
+ :returns: URL to the pasted contents, or an error message.
77
+ """
78
+ import re
79
+ from urllib.parse import urlencode
80
+ from urllib.request import urlopen
81
+
82
+ params = {"code": contents, "lexer": "text", "expiry": "1week"}
83
+ url = "https://bpa.st"
84
+ try:
85
+ response: str = (
86
+ urlopen(url, data=urlencode(params).encode("ascii")).read().decode("utf-8")
87
+ )
88
+ except OSError as exc_info: # urllib errors
89
+ return f"bad response: {exc_info}"
90
+ m = re.search(r'href="/raw/(\w+)"', response)
91
+ if m:
92
+ return f"{url}/show/{m.group(1)}"
93
+ else:
94
+ return "bad response: invalid format ('" + response + "')"
95
+
96
+
97
+ def pytest_terminal_summary(terminalreporter: TerminalReporter) -> None:
98
+ if terminalreporter.config.option.pastebin != "failed":
99
+ return
100
+ if "failed" in terminalreporter.stats:
101
+ terminalreporter.write_sep("=", "Sending information to Paste Service")
102
+ for rep in terminalreporter.stats["failed"]:
103
+ try:
104
+ msg = rep.longrepr.reprtraceback.reprentries[-1].reprfileloc
105
+ except AttributeError:
106
+ msg = terminalreporter._getfailureheadline(rep)
107
+ file = StringIO()
108
+ tw = create_terminal_writer(terminalreporter.config, file)
109
+ rep.toterminal(tw)
110
+ s = file.getvalue()
111
+ assert len(s)
112
+ pastebinurl = create_new_paste(s)
113
+ terminalreporter.write_line(f"{msg} --> {pastebinurl}")
vllm/lib/python3.10/site-packages/_pytest/pathlib.py ADDED
@@ -0,0 +1,1038 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import atexit
4
+ import contextlib
5
+ from enum import Enum
6
+ from errno import EBADF
7
+ from errno import ELOOP
8
+ from errno import ENOENT
9
+ from errno import ENOTDIR
10
+ import fnmatch
11
+ from functools import partial
12
+ from importlib.machinery import ModuleSpec
13
+ from importlib.machinery import PathFinder
14
+ import importlib.util
15
+ import itertools
16
+ import os
17
+ from os.path import expanduser
18
+ from os.path import expandvars
19
+ from os.path import isabs
20
+ from os.path import sep
21
+ from pathlib import Path
22
+ from pathlib import PurePath
23
+ from posixpath import sep as posix_sep
24
+ import shutil
25
+ import sys
26
+ import types
27
+ from types import ModuleType
28
+ from typing import Any
29
+ from typing import Callable
30
+ from typing import Iterable
31
+ from typing import Iterator
32
+ from typing import TypeVar
33
+ import uuid
34
+ import warnings
35
+
36
+ from _pytest.compat import assert_never
37
+ from _pytest.outcomes import skip
38
+ from _pytest.warning_types import PytestWarning
39
+
40
+
41
+ if sys.version_info < (3, 11):
42
+ from importlib._bootstrap_external import _NamespaceLoader as NamespaceLoader
43
+ else:
44
+ from importlib.machinery import NamespaceLoader
45
+
46
+ LOCK_TIMEOUT = 60 * 60 * 24 * 3
47
+
48
+ _AnyPurePath = TypeVar("_AnyPurePath", bound=PurePath)
49
+
50
+ # The following function, variables and comments were
51
+ # copied from cpython 3.9 Lib/pathlib.py file.
52
+
53
+ # EBADF - guard against macOS `stat` throwing EBADF
54
+ _IGNORED_ERRORS = (ENOENT, ENOTDIR, EBADF, ELOOP)
55
+
56
+ _IGNORED_WINERRORS = (
57
+ 21, # ERROR_NOT_READY - drive exists but is not accessible
58
+ 1921, # ERROR_CANT_RESOLVE_FILENAME - fix for broken symlink pointing to itself
59
+ )
60
+
61
+
62
+ def _ignore_error(exception: Exception) -> bool:
63
+ return (
64
+ getattr(exception, "errno", None) in _IGNORED_ERRORS
65
+ or getattr(exception, "winerror", None) in _IGNORED_WINERRORS
66
+ )
67
+
68
+
69
+ def get_lock_path(path: _AnyPurePath) -> _AnyPurePath:
70
+ return path.joinpath(".lock")
71
+
72
+
73
+ def on_rm_rf_error(
74
+ func: Callable[..., Any] | None,
75
+ path: str,
76
+ excinfo: BaseException
77
+ | tuple[type[BaseException], BaseException, types.TracebackType | None],
78
+ *,
79
+ start_path: Path,
80
+ ) -> bool:
81
+ """Handle known read-only errors during rmtree.
82
+
83
+ The returned value is used only by our own tests.
84
+ """
85
+ if isinstance(excinfo, BaseException):
86
+ exc = excinfo
87
+ else:
88
+ exc = excinfo[1]
89
+
90
+ # Another process removed the file in the middle of the "rm_rf" (xdist for example).
91
+ # More context: https://github.com/pytest-dev/pytest/issues/5974#issuecomment-543799018
92
+ if isinstance(exc, FileNotFoundError):
93
+ return False
94
+
95
+ if not isinstance(exc, PermissionError):
96
+ warnings.warn(
97
+ PytestWarning(f"(rm_rf) error removing {path}\n{type(exc)}: {exc}")
98
+ )
99
+ return False
100
+
101
+ if func not in (os.rmdir, os.remove, os.unlink):
102
+ if func not in (os.open,):
103
+ warnings.warn(
104
+ PytestWarning(
105
+ f"(rm_rf) unknown function {func} when removing {path}:\n{type(exc)}: {exc}"
106
+ )
107
+ )
108
+ return False
109
+
110
+ # Chmod + retry.
111
+ import stat
112
+
113
+ def chmod_rw(p: str) -> None:
114
+ mode = os.stat(p).st_mode
115
+ os.chmod(p, mode | stat.S_IRUSR | stat.S_IWUSR)
116
+
117
+ # For files, we need to recursively go upwards in the directories to
118
+ # ensure they all are also writable.
119
+ p = Path(path)
120
+ if p.is_file():
121
+ for parent in p.parents:
122
+ chmod_rw(str(parent))
123
+ # Stop when we reach the original path passed to rm_rf.
124
+ if parent == start_path:
125
+ break
126
+ chmod_rw(str(path))
127
+
128
+ func(path)
129
+ return True
130
+
131
+
132
+ def ensure_extended_length_path(path: Path) -> Path:
133
+ """Get the extended-length version of a path (Windows).
134
+
135
+ On Windows, by default, the maximum length of a path (MAX_PATH) is 260
136
+ characters, and operations on paths longer than that fail. But it is possible
137
+ to overcome this by converting the path to "extended-length" form before
138
+ performing the operation:
139
+ https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#maximum-path-length-limitation
140
+
141
+ On Windows, this function returns the extended-length absolute version of path.
142
+ On other platforms it returns path unchanged.
143
+ """
144
+ if sys.platform.startswith("win32"):
145
+ path = path.resolve()
146
+ path = Path(get_extended_length_path_str(str(path)))
147
+ return path
148
+
149
+
150
+ def get_extended_length_path_str(path: str) -> str:
151
+ """Convert a path to a Windows extended length path."""
152
+ long_path_prefix = "\\\\?\\"
153
+ unc_long_path_prefix = "\\\\?\\UNC\\"
154
+ if path.startswith((long_path_prefix, unc_long_path_prefix)):
155
+ return path
156
+ # UNC
157
+ if path.startswith("\\\\"):
158
+ return unc_long_path_prefix + path[2:]
159
+ return long_path_prefix + path
160
+
161
+
162
+ def rm_rf(path: Path) -> None:
163
+ """Remove the path contents recursively, even if some elements
164
+ are read-only."""
165
+ path = ensure_extended_length_path(path)
166
+ onerror = partial(on_rm_rf_error, start_path=path)
167
+ if sys.version_info >= (3, 12):
168
+ shutil.rmtree(str(path), onexc=onerror)
169
+ else:
170
+ shutil.rmtree(str(path), onerror=onerror)
171
+
172
+
173
+ def find_prefixed(root: Path, prefix: str) -> Iterator[os.DirEntry[str]]:
174
+ """Find all elements in root that begin with the prefix, case-insensitive."""
175
+ l_prefix = prefix.lower()
176
+ for x in os.scandir(root):
177
+ if x.name.lower().startswith(l_prefix):
178
+ yield x
179
+
180
+
181
+ def extract_suffixes(iter: Iterable[os.DirEntry[str]], prefix: str) -> Iterator[str]:
182
+ """Return the parts of the paths following the prefix.
183
+
184
+ :param iter: Iterator over path names.
185
+ :param prefix: Expected prefix of the path names.
186
+ """
187
+ p_len = len(prefix)
188
+ for entry in iter:
189
+ yield entry.name[p_len:]
190
+
191
+
192
+ def find_suffixes(root: Path, prefix: str) -> Iterator[str]:
193
+ """Combine find_prefixes and extract_suffixes."""
194
+ return extract_suffixes(find_prefixed(root, prefix), prefix)
195
+
196
+
197
+ def parse_num(maybe_num: str) -> int:
198
+ """Parse number path suffixes, returns -1 on error."""
199
+ try:
200
+ return int(maybe_num)
201
+ except ValueError:
202
+ return -1
203
+
204
+
205
+ def _force_symlink(root: Path, target: str | PurePath, link_to: str | Path) -> None:
206
+ """Helper to create the current symlink.
207
+
208
+ It's full of race conditions that are reasonably OK to ignore
209
+ for the context of best effort linking to the latest test run.
210
+
211
+ The presumption being that in case of much parallelism
212
+ the inaccuracy is going to be acceptable.
213
+ """
214
+ current_symlink = root.joinpath(target)
215
+ try:
216
+ current_symlink.unlink()
217
+ except OSError:
218
+ pass
219
+ try:
220
+ current_symlink.symlink_to(link_to)
221
+ except Exception:
222
+ pass
223
+
224
+
225
+ def make_numbered_dir(root: Path, prefix: str, mode: int = 0o700) -> Path:
226
+ """Create a directory with an increased number as suffix for the given prefix."""
227
+ for i in range(10):
228
+ # try up to 10 times to create the folder
229
+ max_existing = max(map(parse_num, find_suffixes(root, prefix)), default=-1)
230
+ new_number = max_existing + 1
231
+ new_path = root.joinpath(f"{prefix}{new_number}")
232
+ try:
233
+ new_path.mkdir(mode=mode)
234
+ except Exception:
235
+ pass
236
+ else:
237
+ _force_symlink(root, prefix + "current", new_path)
238
+ return new_path
239
+ else:
240
+ raise OSError(
241
+ "could not create numbered dir with prefix "
242
+ f"{prefix} in {root} after 10 tries"
243
+ )
244
+
245
+
246
+ def create_cleanup_lock(p: Path) -> Path:
247
+ """Create a lock to prevent premature folder cleanup."""
248
+ lock_path = get_lock_path(p)
249
+ try:
250
+ fd = os.open(str(lock_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
251
+ except FileExistsError as e:
252
+ raise OSError(f"cannot create lockfile in {p}") from e
253
+ else:
254
+ pid = os.getpid()
255
+ spid = str(pid).encode()
256
+ os.write(fd, spid)
257
+ os.close(fd)
258
+ if not lock_path.is_file():
259
+ raise OSError("lock path got renamed after successful creation")
260
+ return lock_path
261
+
262
+
263
+ def register_cleanup_lock_removal(
264
+ lock_path: Path, register: Any = atexit.register
265
+ ) -> Any:
266
+ """Register a cleanup function for removing a lock, by default on atexit."""
267
+ pid = os.getpid()
268
+
269
+ def cleanup_on_exit(lock_path: Path = lock_path, original_pid: int = pid) -> None:
270
+ current_pid = os.getpid()
271
+ if current_pid != original_pid:
272
+ # fork
273
+ return
274
+ try:
275
+ lock_path.unlink()
276
+ except OSError:
277
+ pass
278
+
279
+ return register(cleanup_on_exit)
280
+
281
+
282
+ def maybe_delete_a_numbered_dir(path: Path) -> None:
283
+ """Remove a numbered directory if its lock can be obtained and it does
284
+ not seem to be in use."""
285
+ path = ensure_extended_length_path(path)
286
+ lock_path = None
287
+ try:
288
+ lock_path = create_cleanup_lock(path)
289
+ parent = path.parent
290
+
291
+ garbage = parent.joinpath(f"garbage-{uuid.uuid4()}")
292
+ path.rename(garbage)
293
+ rm_rf(garbage)
294
+ except OSError:
295
+ # known races:
296
+ # * other process did a cleanup at the same time
297
+ # * deletable folder was found
298
+ # * process cwd (Windows)
299
+ return
300
+ finally:
301
+ # If we created the lock, ensure we remove it even if we failed
302
+ # to properly remove the numbered dir.
303
+ if lock_path is not None:
304
+ try:
305
+ lock_path.unlink()
306
+ except OSError:
307
+ pass
308
+
309
+
310
+ def ensure_deletable(path: Path, consider_lock_dead_if_created_before: float) -> bool:
311
+ """Check if `path` is deletable based on whether the lock file is expired."""
312
+ if path.is_symlink():
313
+ return False
314
+ lock = get_lock_path(path)
315
+ try:
316
+ if not lock.is_file():
317
+ return True
318
+ except OSError:
319
+ # we might not have access to the lock file at all, in this case assume
320
+ # we don't have access to the entire directory (#7491).
321
+ return False
322
+ try:
323
+ lock_time = lock.stat().st_mtime
324
+ except Exception:
325
+ return False
326
+ else:
327
+ if lock_time < consider_lock_dead_if_created_before:
328
+ # We want to ignore any errors while trying to remove the lock such as:
329
+ # - PermissionDenied, like the file permissions have changed since the lock creation;
330
+ # - FileNotFoundError, in case another pytest process got here first;
331
+ # and any other cause of failure.
332
+ with contextlib.suppress(OSError):
333
+ lock.unlink()
334
+ return True
335
+ return False
336
+
337
+
338
+ def try_cleanup(path: Path, consider_lock_dead_if_created_before: float) -> None:
339
+ """Try to cleanup a folder if we can ensure it's deletable."""
340
+ if ensure_deletable(path, consider_lock_dead_if_created_before):
341
+ maybe_delete_a_numbered_dir(path)
342
+
343
+
344
+ def cleanup_candidates(root: Path, prefix: str, keep: int) -> Iterator[Path]:
345
+ """List candidates for numbered directories to be removed - follows py.path."""
346
+ max_existing = max(map(parse_num, find_suffixes(root, prefix)), default=-1)
347
+ max_delete = max_existing - keep
348
+ entries = find_prefixed(root, prefix)
349
+ entries, entries2 = itertools.tee(entries)
350
+ numbers = map(parse_num, extract_suffixes(entries2, prefix))
351
+ for entry, number in zip(entries, numbers):
352
+ if number <= max_delete:
353
+ yield Path(entry)
354
+
355
+
356
+ def cleanup_dead_symlinks(root: Path) -> None:
357
+ for left_dir in root.iterdir():
358
+ if left_dir.is_symlink():
359
+ if not left_dir.resolve().exists():
360
+ left_dir.unlink()
361
+
362
+
363
+ def cleanup_numbered_dir(
364
+ root: Path, prefix: str, keep: int, consider_lock_dead_if_created_before: float
365
+ ) -> None:
366
+ """Cleanup for lock driven numbered directories."""
367
+ if not root.exists():
368
+ return
369
+ for path in cleanup_candidates(root, prefix, keep):
370
+ try_cleanup(path, consider_lock_dead_if_created_before)
371
+ for path in root.glob("garbage-*"):
372
+ try_cleanup(path, consider_lock_dead_if_created_before)
373
+
374
+ cleanup_dead_symlinks(root)
375
+
376
+
377
+ def make_numbered_dir_with_cleanup(
378
+ root: Path,
379
+ prefix: str,
380
+ keep: int,
381
+ lock_timeout: float,
382
+ mode: int,
383
+ ) -> Path:
384
+ """Create a numbered dir with a cleanup lock and remove old ones."""
385
+ e = None
386
+ for i in range(10):
387
+ try:
388
+ p = make_numbered_dir(root, prefix, mode)
389
+ # Only lock the current dir when keep is not 0
390
+ if keep != 0:
391
+ lock_path = create_cleanup_lock(p)
392
+ register_cleanup_lock_removal(lock_path)
393
+ except Exception as exc:
394
+ e = exc
395
+ else:
396
+ consider_lock_dead_if_created_before = p.stat().st_mtime - lock_timeout
397
+ # Register a cleanup for program exit
398
+ atexit.register(
399
+ cleanup_numbered_dir,
400
+ root,
401
+ prefix,
402
+ keep,
403
+ consider_lock_dead_if_created_before,
404
+ )
405
+ return p
406
+ assert e is not None
407
+ raise e
408
+
409
+
410
+ def resolve_from_str(input: str, rootpath: Path) -> Path:
411
+ input = expanduser(input)
412
+ input = expandvars(input)
413
+ if isabs(input):
414
+ return Path(input)
415
+ else:
416
+ return rootpath.joinpath(input)
417
+
418
+
419
+ def fnmatch_ex(pattern: str, path: str | os.PathLike[str]) -> bool:
420
+ """A port of FNMatcher from py.path.common which works with PurePath() instances.
421
+
422
+ The difference between this algorithm and PurePath.match() is that the
423
+ latter matches "**" glob expressions for each part of the path, while
424
+ this algorithm uses the whole path instead.
425
+
426
+ For example:
427
+ "tests/foo/bar/doc/test_foo.py" matches pattern "tests/**/doc/test*.py"
428
+ with this algorithm, but not with PurePath.match().
429
+
430
+ This algorithm was ported to keep backward-compatibility with existing
431
+ settings which assume paths match according this logic.
432
+
433
+ References:
434
+ * https://bugs.python.org/issue29249
435
+ * https://bugs.python.org/issue34731
436
+ """
437
+ path = PurePath(path)
438
+ iswin32 = sys.platform.startswith("win")
439
+
440
+ if iswin32 and sep not in pattern and posix_sep in pattern:
441
+ # Running on Windows, the pattern has no Windows path separators,
442
+ # and the pattern has one or more Posix path separators. Replace
443
+ # the Posix path separators with the Windows path separator.
444
+ pattern = pattern.replace(posix_sep, sep)
445
+
446
+ if sep not in pattern:
447
+ name = path.name
448
+ else:
449
+ name = str(path)
450
+ if path.is_absolute() and not os.path.isabs(pattern):
451
+ pattern = f"*{os.sep}{pattern}"
452
+ return fnmatch.fnmatch(name, pattern)
453
+
454
+
455
+ def parts(s: str) -> set[str]:
456
+ parts = s.split(sep)
457
+ return {sep.join(parts[: i + 1]) or sep for i in range(len(parts))}
458
+
459
+
460
+ def symlink_or_skip(
461
+ src: os.PathLike[str] | str,
462
+ dst: os.PathLike[str] | str,
463
+ **kwargs: Any,
464
+ ) -> None:
465
+ """Make a symlink, or skip the test in case symlinks are not supported."""
466
+ try:
467
+ os.symlink(src, dst, **kwargs)
468
+ except OSError as e:
469
+ skip(f"symlinks not supported: {e}")
470
+
471
+
472
+ class ImportMode(Enum):
473
+ """Possible values for `mode` parameter of `import_path`."""
474
+
475
+ prepend = "prepend"
476
+ append = "append"
477
+ importlib = "importlib"
478
+
479
+
480
+ class ImportPathMismatchError(ImportError):
481
+ """Raised on import_path() if there is a mismatch of __file__'s.
482
+
483
+ This can happen when `import_path` is called multiple times with different filenames that has
484
+ the same basename but reside in packages
485
+ (for example "/tests1/test_foo.py" and "/tests2/test_foo.py").
486
+ """
487
+
488
+
489
+ def import_path(
490
+ path: str | os.PathLike[str],
491
+ *,
492
+ mode: str | ImportMode = ImportMode.prepend,
493
+ root: Path,
494
+ consider_namespace_packages: bool,
495
+ ) -> ModuleType:
496
+ """
497
+ Import and return a module from the given path, which can be a file (a module) or
498
+ a directory (a package).
499
+
500
+ :param path:
501
+ Path to the file to import.
502
+
503
+ :param mode:
504
+ Controls the underlying import mechanism that will be used:
505
+
506
+ * ImportMode.prepend: the directory containing the module (or package, taking
507
+ `__init__.py` files into account) will be put at the *start* of `sys.path` before
508
+ being imported with `importlib.import_module`.
509
+
510
+ * ImportMode.append: same as `prepend`, but the directory will be appended
511
+ to the end of `sys.path`, if not already in `sys.path`.
512
+
513
+ * ImportMode.importlib: uses more fine control mechanisms provided by `importlib`
514
+ to import the module, which avoids having to muck with `sys.path` at all. It effectively
515
+ allows having same-named test modules in different places.
516
+
517
+ :param root:
518
+ Used as an anchor when mode == ImportMode.importlib to obtain
519
+ a unique name for the module being imported so it can safely be stored
520
+ into ``sys.modules``.
521
+
522
+ :param consider_namespace_packages:
523
+ If True, consider namespace packages when resolving module names.
524
+
525
+ :raises ImportPathMismatchError:
526
+ If after importing the given `path` and the module `__file__`
527
+ are different. Only raised in `prepend` and `append` modes.
528
+ """
529
+ path = Path(path)
530
+ mode = ImportMode(mode)
531
+
532
+ if not path.exists():
533
+ raise ImportError(path)
534
+
535
+ if mode is ImportMode.importlib:
536
+ # Try to import this module using the standard import mechanisms, but
537
+ # without touching sys.path.
538
+ try:
539
+ pkg_root, module_name = resolve_pkg_root_and_module_name(
540
+ path, consider_namespace_packages=consider_namespace_packages
541
+ )
542
+ except CouldNotResolvePathError:
543
+ pass
544
+ else:
545
+ # If the given module name is already in sys.modules, do not import it again.
546
+ with contextlib.suppress(KeyError):
547
+ return sys.modules[module_name]
548
+
549
+ mod = _import_module_using_spec(
550
+ module_name, path, pkg_root, insert_modules=False
551
+ )
552
+ if mod is not None:
553
+ return mod
554
+
555
+ # Could not import the module with the current sys.path, so we fall back
556
+ # to importing the file as a single module, not being a part of a package.
557
+ module_name = module_name_from_path(path, root)
558
+ with contextlib.suppress(KeyError):
559
+ return sys.modules[module_name]
560
+
561
+ mod = _import_module_using_spec(
562
+ module_name, path, path.parent, insert_modules=True
563
+ )
564
+ if mod is None:
565
+ raise ImportError(f"Can't find module {module_name} at location {path}")
566
+ return mod
567
+
568
+ try:
569
+ pkg_root, module_name = resolve_pkg_root_and_module_name(
570
+ path, consider_namespace_packages=consider_namespace_packages
571
+ )
572
+ except CouldNotResolvePathError:
573
+ pkg_root, module_name = path.parent, path.stem
574
+
575
+ # Change sys.path permanently: restoring it at the end of this function would cause surprising
576
+ # problems because of delayed imports: for example, a conftest.py file imported by this function
577
+ # might have local imports, which would fail at runtime if we restored sys.path.
578
+ if mode is ImportMode.append:
579
+ if str(pkg_root) not in sys.path:
580
+ sys.path.append(str(pkg_root))
581
+ elif mode is ImportMode.prepend:
582
+ if str(pkg_root) != sys.path[0]:
583
+ sys.path.insert(0, str(pkg_root))
584
+ else:
585
+ assert_never(mode)
586
+
587
+ importlib.import_module(module_name)
588
+
589
+ mod = sys.modules[module_name]
590
+ if path.name == "__init__.py":
591
+ return mod
592
+
593
+ ignore = os.environ.get("PY_IGNORE_IMPORTMISMATCH", "")
594
+ if ignore != "1":
595
+ module_file = mod.__file__
596
+ if module_file is None:
597
+ raise ImportPathMismatchError(module_name, module_file, path)
598
+
599
+ if module_file.endswith((".pyc", ".pyo")):
600
+ module_file = module_file[:-1]
601
+ if module_file.endswith(os.sep + "__init__.py"):
602
+ module_file = module_file[: -(len(os.sep + "__init__.py"))]
603
+
604
+ try:
605
+ is_same = _is_same(str(path), module_file)
606
+ except FileNotFoundError:
607
+ is_same = False
608
+
609
+ if not is_same:
610
+ raise ImportPathMismatchError(module_name, module_file, path)
611
+
612
+ return mod
613
+
614
+
615
+ def _import_module_using_spec(
616
+ module_name: str, module_path: Path, module_location: Path, *, insert_modules: bool
617
+ ) -> ModuleType | None:
618
+ """
619
+ Tries to import a module by its canonical name, path, and its parent location.
620
+
621
+ :param module_name:
622
+ The expected module name, will become the key of `sys.modules`.
623
+
624
+ :param module_path:
625
+ The file path of the module, for example `/foo/bar/test_demo.py`.
626
+ If module is a package, pass the path to the `__init__.py` of the package.
627
+ If module is a namespace package, pass directory path.
628
+
629
+ :param module_location:
630
+ The parent location of the module.
631
+ If module is a package, pass the directory containing the `__init__.py` file.
632
+
633
+ :param insert_modules:
634
+ If True, will call `insert_missing_modules` to create empty intermediate modules
635
+ with made-up module names (when importing test files not reachable from `sys.path`).
636
+
637
+ Example 1 of parent_module_*:
638
+
639
+ module_name: "a.b.c.demo"
640
+ module_path: Path("a/b/c/demo.py")
641
+ module_location: Path("a/b/c/")
642
+ if "a.b.c" is package ("a/b/c/__init__.py" exists), then
643
+ parent_module_name: "a.b.c"
644
+ parent_module_path: Path("a/b/c/__init__.py")
645
+ parent_module_location: Path("a/b/c/")
646
+ else:
647
+ parent_module_name: "a.b.c"
648
+ parent_module_path: Path("a/b/c")
649
+ parent_module_location: Path("a/b/")
650
+
651
+ Example 2 of parent_module_*:
652
+
653
+ module_name: "a.b.c"
654
+ module_path: Path("a/b/c/__init__.py")
655
+ module_location: Path("a/b/c/")
656
+ if "a.b" is package ("a/b/__init__.py" exists), then
657
+ parent_module_name: "a.b"
658
+ parent_module_path: Path("a/b/__init__.py")
659
+ parent_module_location: Path("a/b/")
660
+ else:
661
+ parent_module_name: "a.b"
662
+ parent_module_path: Path("a/b/")
663
+ parent_module_location: Path("a/")
664
+ """
665
+ # Attempt to import the parent module, seems is our responsibility:
666
+ # https://github.com/python/cpython/blob/73906d5c908c1e0b73c5436faeff7d93698fc074/Lib/importlib/_bootstrap.py#L1308-L1311
667
+ parent_module_name, _, name = module_name.rpartition(".")
668
+ parent_module: ModuleType | None = None
669
+ if parent_module_name:
670
+ parent_module = sys.modules.get(parent_module_name)
671
+ if parent_module is None:
672
+ # Get parent_location based on location, get parent_path based on path.
673
+ if module_path.name == "__init__.py":
674
+ # If the current module is in a package,
675
+ # need to leave the package first and then enter the parent module.
676
+ parent_module_path = module_path.parent.parent
677
+ else:
678
+ parent_module_path = module_path.parent
679
+
680
+ if (parent_module_path / "__init__.py").is_file():
681
+ # If the parent module is a package, loading by __init__.py file.
682
+ parent_module_path = parent_module_path / "__init__.py"
683
+
684
+ parent_module = _import_module_using_spec(
685
+ parent_module_name,
686
+ parent_module_path,
687
+ parent_module_path.parent,
688
+ insert_modules=insert_modules,
689
+ )
690
+
691
+ # Checking with sys.meta_path first in case one of its hooks can import this module,
692
+ # such as our own assertion-rewrite hook.
693
+ for meta_importer in sys.meta_path:
694
+ spec = meta_importer.find_spec(
695
+ module_name, [str(module_location), str(module_path)]
696
+ )
697
+ if spec_matches_module_path(spec, module_path):
698
+ break
699
+ else:
700
+ loader = None
701
+ if module_path.is_dir():
702
+ # The `spec_from_file_location` matches a loader based on the file extension by default.
703
+ # For a namespace package, need to manually specify a loader.
704
+ loader = NamespaceLoader(name, module_path, PathFinder())
705
+
706
+ spec = importlib.util.spec_from_file_location(
707
+ module_name, str(module_path), loader=loader
708
+ )
709
+
710
+ if spec_matches_module_path(spec, module_path):
711
+ assert spec is not None
712
+ # Find spec and import this module.
713
+ mod = importlib.util.module_from_spec(spec)
714
+ sys.modules[module_name] = mod
715
+ spec.loader.exec_module(mod) # type: ignore[union-attr]
716
+
717
+ # Set this module as an attribute of the parent module (#12194).
718
+ if parent_module is not None:
719
+ setattr(parent_module, name, mod)
720
+
721
+ if insert_modules:
722
+ insert_missing_modules(sys.modules, module_name)
723
+ return mod
724
+
725
+ return None
726
+
727
+
728
+ def spec_matches_module_path(module_spec: ModuleSpec | None, module_path: Path) -> bool:
729
+ """Return true if the given ModuleSpec can be used to import the given module path."""
730
+ if module_spec is None:
731
+ return False
732
+
733
+ if module_spec.origin:
734
+ return Path(module_spec.origin) == module_path
735
+
736
+ # Compare the path with the `module_spec.submodule_Search_Locations` in case
737
+ # the module is part of a namespace package.
738
+ # https://docs.python.org/3/library/importlib.html#importlib.machinery.ModuleSpec.submodule_search_locations
739
+ if module_spec.submodule_search_locations: # can be None.
740
+ for path in module_spec.submodule_search_locations:
741
+ if Path(path) == module_path:
742
+ return True
743
+
744
+ return False
745
+
746
+
747
+ # Implement a special _is_same function on Windows which returns True if the two filenames
748
+ # compare equal, to circumvent os.path.samefile returning False for mounts in UNC (#7678).
749
+ if sys.platform.startswith("win"):
750
+
751
+ def _is_same(f1: str, f2: str) -> bool:
752
+ return Path(f1) == Path(f2) or os.path.samefile(f1, f2)
753
+
754
+ else:
755
+
756
+ def _is_same(f1: str, f2: str) -> bool:
757
+ return os.path.samefile(f1, f2)
758
+
759
+
760
+ def module_name_from_path(path: Path, root: Path) -> str:
761
+ """
762
+ Return a dotted module name based on the given path, anchored on root.
763
+
764
+ For example: path="projects/src/tests/test_foo.py" and root="/projects", the
765
+ resulting module name will be "src.tests.test_foo".
766
+ """
767
+ path = path.with_suffix("")
768
+ try:
769
+ relative_path = path.relative_to(root)
770
+ except ValueError:
771
+ # If we can't get a relative path to root, use the full path, except
772
+ # for the first part ("d:\\" or "/" depending on the platform, for example).
773
+ path_parts = path.parts[1:]
774
+ else:
775
+ # Use the parts for the relative path to the root path.
776
+ path_parts = relative_path.parts
777
+
778
+ # Module name for packages do not contain the __init__ file, unless
779
+ # the `__init__.py` file is at the root.
780
+ if len(path_parts) >= 2 and path_parts[-1] == "__init__":
781
+ path_parts = path_parts[:-1]
782
+
783
+ # Module names cannot contain ".", normalize them to "_". This prevents
784
+ # a directory having a "." in the name (".env.310" for example) causing extra intermediate modules.
785
+ # Also, important to replace "." at the start of paths, as those are considered relative imports.
786
+ path_parts = tuple(x.replace(".", "_") for x in path_parts)
787
+
788
+ return ".".join(path_parts)
789
+
790
+
791
+ def insert_missing_modules(modules: dict[str, ModuleType], module_name: str) -> None:
792
+ """
793
+ Used by ``import_path`` to create intermediate modules when using mode=importlib.
794
+
795
+ When we want to import a module as "src.tests.test_foo" for example, we need
796
+ to create empty modules "src" and "src.tests" after inserting "src.tests.test_foo",
797
+ otherwise "src.tests.test_foo" is not importable by ``__import__``.
798
+ """
799
+ module_parts = module_name.split(".")
800
+ while module_name:
801
+ parent_module_name, _, child_name = module_name.rpartition(".")
802
+ if parent_module_name:
803
+ parent_module = modules.get(parent_module_name)
804
+ if parent_module is None:
805
+ try:
806
+ # If sys.meta_path is empty, calling import_module will issue
807
+ # a warning and raise ModuleNotFoundError. To avoid the
808
+ # warning, we check sys.meta_path explicitly and raise the error
809
+ # ourselves to fall back to creating a dummy module.
810
+ if not sys.meta_path:
811
+ raise ModuleNotFoundError
812
+ parent_module = importlib.import_module(parent_module_name)
813
+ except ModuleNotFoundError:
814
+ parent_module = ModuleType(
815
+ module_name,
816
+ doc="Empty module created by pytest's importmode=importlib.",
817
+ )
818
+ modules[parent_module_name] = parent_module
819
+
820
+ # Add child attribute to the parent that can reference the child
821
+ # modules.
822
+ if not hasattr(parent_module, child_name):
823
+ setattr(parent_module, child_name, modules[module_name])
824
+
825
+ module_parts.pop(-1)
826
+ module_name = ".".join(module_parts)
827
+
828
+
829
+ def resolve_package_path(path: Path) -> Path | None:
830
+ """Return the Python package path by looking for the last
831
+ directory upwards which still contains an __init__.py.
832
+
833
+ Returns None if it cannot be determined.
834
+ """
835
+ result = None
836
+ for parent in itertools.chain((path,), path.parents):
837
+ if parent.is_dir():
838
+ if not (parent / "__init__.py").is_file():
839
+ break
840
+ if not parent.name.isidentifier():
841
+ break
842
+ result = parent
843
+ return result
844
+
845
+
846
+ def resolve_pkg_root_and_module_name(
847
+ path: Path, *, consider_namespace_packages: bool = False
848
+ ) -> tuple[Path, str]:
849
+ """
850
+ Return the path to the directory of the root package that contains the
851
+ given Python file, and its module name:
852
+
853
+ src/
854
+ app/
855
+ __init__.py
856
+ core/
857
+ __init__.py
858
+ models.py
859
+
860
+ Passing the full path to `models.py` will yield Path("src") and "app.core.models".
861
+
862
+ If consider_namespace_packages is True, then we additionally check upwards in the hierarchy
863
+ for namespace packages:
864
+
865
+ https://packaging.python.org/en/latest/guides/packaging-namespace-packages
866
+
867
+ Raises CouldNotResolvePathError if the given path does not belong to a package (missing any __init__.py files).
868
+ """
869
+ pkg_root: Path | None = None
870
+ pkg_path = resolve_package_path(path)
871
+ if pkg_path is not None:
872
+ pkg_root = pkg_path.parent
873
+ if consider_namespace_packages:
874
+ start = pkg_root if pkg_root is not None else path.parent
875
+ for candidate in (start, *start.parents):
876
+ module_name = compute_module_name(candidate, path)
877
+ if module_name and is_importable(module_name, path):
878
+ # Point the pkg_root to the root of the namespace package.
879
+ pkg_root = candidate
880
+ break
881
+
882
+ if pkg_root is not None:
883
+ module_name = compute_module_name(pkg_root, path)
884
+ if module_name:
885
+ return pkg_root, module_name
886
+
887
+ raise CouldNotResolvePathError(f"Could not resolve for {path}")
888
+
889
+
890
+ def is_importable(module_name: str, module_path: Path) -> bool:
891
+ """
892
+ Return if the given module path could be imported normally by Python, akin to the user
893
+ entering the REPL and importing the corresponding module name directly, and corresponds
894
+ to the module_path specified.
895
+
896
+ :param module_name:
897
+ Full module name that we want to check if is importable.
898
+ For example, "app.models".
899
+
900
+ :param module_path:
901
+ Full path to the python module/package we want to check if is importable.
902
+ For example, "/projects/src/app/models.py".
903
+ """
904
+ try:
905
+ # Note this is different from what we do in ``_import_module_using_spec``, where we explicitly search through
906
+ # sys.meta_path to be able to pass the path of the module that we want to import (``meta_importer.find_spec``).
907
+ # Using importlib.util.find_spec() is different, it gives the same results as trying to import
908
+ # the module normally in the REPL.
909
+ spec = importlib.util.find_spec(module_name)
910
+ except (ImportError, ValueError, ImportWarning):
911
+ return False
912
+ else:
913
+ return spec_matches_module_path(spec, module_path)
914
+
915
+
916
+ def compute_module_name(root: Path, module_path: Path) -> str | None:
917
+ """Compute a module name based on a path and a root anchor."""
918
+ try:
919
+ path_without_suffix = module_path.with_suffix("")
920
+ except ValueError:
921
+ # Empty paths (such as Path.cwd()) might break meta_path hooks (like our own assertion rewriter).
922
+ return None
923
+
924
+ try:
925
+ relative = path_without_suffix.relative_to(root)
926
+ except ValueError: # pragma: no cover
927
+ return None
928
+ names = list(relative.parts)
929
+ if not names:
930
+ return None
931
+ if names[-1] == "__init__":
932
+ names.pop()
933
+ return ".".join(names)
934
+
935
+
936
+ class CouldNotResolvePathError(Exception):
937
+ """Custom exception raised by resolve_pkg_root_and_module_name."""
938
+
939
+
940
+ def scandir(
941
+ path: str | os.PathLike[str],
942
+ sort_key: Callable[[os.DirEntry[str]], object] = lambda entry: entry.name,
943
+ ) -> list[os.DirEntry[str]]:
944
+ """Scan a directory recursively, in breadth-first order.
945
+
946
+ The returned entries are sorted according to the given key.
947
+ The default is to sort by name.
948
+ """
949
+ entries = []
950
+ with os.scandir(path) as s:
951
+ # Skip entries with symlink loops and other brokenness, so the caller
952
+ # doesn't have to deal with it.
953
+ for entry in s:
954
+ try:
955
+ entry.is_file()
956
+ except OSError as err:
957
+ if _ignore_error(err):
958
+ continue
959
+ raise
960
+ entries.append(entry)
961
+ entries.sort(key=sort_key) # type: ignore[arg-type]
962
+ return entries
963
+
964
+
965
+ def visit(
966
+ path: str | os.PathLike[str], recurse: Callable[[os.DirEntry[str]], bool]
967
+ ) -> Iterator[os.DirEntry[str]]:
968
+ """Walk a directory recursively, in breadth-first order.
969
+
970
+ The `recurse` predicate determines whether a directory is recursed.
971
+
972
+ Entries at each directory level are sorted.
973
+ """
974
+ entries = scandir(path)
975
+ yield from entries
976
+ for entry in entries:
977
+ if entry.is_dir() and recurse(entry):
978
+ yield from visit(entry.path, recurse)
979
+
980
+
981
+ def absolutepath(path: str | os.PathLike[str]) -> Path:
982
+ """Convert a path to an absolute path using os.path.abspath.
983
+
984
+ Prefer this over Path.resolve() (see #6523).
985
+ Prefer this over Path.absolute() (not public, doesn't normalize).
986
+ """
987
+ return Path(os.path.abspath(path))
988
+
989
+
990
+ def commonpath(path1: Path, path2: Path) -> Path | None:
991
+ """Return the common part shared with the other path, or None if there is
992
+ no common part.
993
+
994
+ If one path is relative and one is absolute, returns None.
995
+ """
996
+ try:
997
+ return Path(os.path.commonpath((str(path1), str(path2))))
998
+ except ValueError:
999
+ return None
1000
+
1001
+
1002
+ def bestrelpath(directory: Path, dest: Path) -> str:
1003
+ """Return a string which is a relative path from directory to dest such
1004
+ that directory/bestrelpath == dest.
1005
+
1006
+ The paths must be either both absolute or both relative.
1007
+
1008
+ If no such path can be determined, returns dest.
1009
+ """
1010
+ assert isinstance(directory, Path)
1011
+ assert isinstance(dest, Path)
1012
+ if dest == directory:
1013
+ return os.curdir
1014
+ # Find the longest common directory.
1015
+ base = commonpath(directory, dest)
1016
+ # Can be the case on Windows for two absolute paths on different drives.
1017
+ # Can be the case for two relative paths without common prefix.
1018
+ # Can be the case for a relative path and an absolute path.
1019
+ if not base:
1020
+ return str(dest)
1021
+ reldirectory = directory.relative_to(base)
1022
+ reldest = dest.relative_to(base)
1023
+ return os.path.join(
1024
+ # Back from directory to base.
1025
+ *([os.pardir] * len(reldirectory.parts)),
1026
+ # Forward from base to dest.
1027
+ *reldest.parts,
1028
+ )
1029
+
1030
+
1031
+ def safe_exists(p: Path) -> bool:
1032
+ """Like Path.exists(), but account for input arguments that might be too long (#11394)."""
1033
+ try:
1034
+ return p.exists()
1035
+ except (ValueError, OSError):
1036
+ # ValueError: stat: path too long for Windows
1037
+ # OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect
1038
+ return False
vllm/lib/python3.10/site-packages/_pytest/py.typed ADDED
File without changes
vllm/lib/python3.10/site-packages/_pytest/pytester.py ADDED
@@ -0,0 +1,1766 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """(Disabled by default) support for testing pytest and pytest plugins.
3
+
4
+ PYTEST_DONT_REWRITE
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import collections.abc
10
+ import contextlib
11
+ from fnmatch import fnmatch
12
+ import gc
13
+ import importlib
14
+ from io import StringIO
15
+ import locale
16
+ import os
17
+ from pathlib import Path
18
+ import platform
19
+ import re
20
+ import shutil
21
+ import subprocess
22
+ import sys
23
+ import traceback
24
+ from typing import Any
25
+ from typing import Callable
26
+ from typing import Final
27
+ from typing import final
28
+ from typing import Generator
29
+ from typing import IO
30
+ from typing import Iterable
31
+ from typing import Literal
32
+ from typing import overload
33
+ from typing import Sequence
34
+ from typing import TextIO
35
+ from typing import TYPE_CHECKING
36
+ from weakref import WeakKeyDictionary
37
+
38
+ from iniconfig import IniConfig
39
+ from iniconfig import SectionWrapper
40
+
41
+ from _pytest import timing
42
+ from _pytest._code import Source
43
+ from _pytest.capture import _get_multicapture
44
+ from _pytest.compat import NOTSET
45
+ from _pytest.compat import NotSetType
46
+ from _pytest.config import _PluggyPlugin
47
+ from _pytest.config import Config
48
+ from _pytest.config import ExitCode
49
+ from _pytest.config import hookimpl
50
+ from _pytest.config import main
51
+ from _pytest.config import PytestPluginManager
52
+ from _pytest.config.argparsing import Parser
53
+ from _pytest.deprecated import check_ispytest
54
+ from _pytest.fixtures import fixture
55
+ from _pytest.fixtures import FixtureRequest
56
+ from _pytest.main import Session
57
+ from _pytest.monkeypatch import MonkeyPatch
58
+ from _pytest.nodes import Collector
59
+ from _pytest.nodes import Item
60
+ from _pytest.outcomes import fail
61
+ from _pytest.outcomes import importorskip
62
+ from _pytest.outcomes import skip
63
+ from _pytest.pathlib import bestrelpath
64
+ from _pytest.pathlib import make_numbered_dir
65
+ from _pytest.reports import CollectReport
66
+ from _pytest.reports import TestReport
67
+ from _pytest.tmpdir import TempPathFactory
68
+ from _pytest.warning_types import PytestWarning
69
+
70
+
71
+ if TYPE_CHECKING:
72
+ import pexpect
73
+
74
+
75
+ pytest_plugins = ["pytester_assertions"]
76
+
77
+
78
+ IGNORE_PAM = [ # filenames added when obtaining details about the current user
79
+ "/var/lib/sss/mc/passwd"
80
+ ]
81
+
82
+
83
+ def pytest_addoption(parser: Parser) -> None:
84
+ parser.addoption(
85
+ "--lsof",
86
+ action="store_true",
87
+ dest="lsof",
88
+ default=False,
89
+ help="Run FD checks if lsof is available",
90
+ )
91
+
92
+ parser.addoption(
93
+ "--runpytest",
94
+ default="inprocess",
95
+ dest="runpytest",
96
+ choices=("inprocess", "subprocess"),
97
+ help=(
98
+ "Run pytest sub runs in tests using an 'inprocess' "
99
+ "or 'subprocess' (python -m main) method"
100
+ ),
101
+ )
102
+
103
+ parser.addini(
104
+ "pytester_example_dir", help="Directory to take the pytester example files from"
105
+ )
106
+
107
+
108
+ def pytest_configure(config: Config) -> None:
109
+ if config.getvalue("lsof"):
110
+ checker = LsofFdLeakChecker()
111
+ if checker.matching_platform():
112
+ config.pluginmanager.register(checker)
113
+
114
+ config.addinivalue_line(
115
+ "markers",
116
+ "pytester_example_path(*path_segments): join the given path "
117
+ "segments to `pytester_example_dir` for this test.",
118
+ )
119
+
120
+
121
+ class LsofFdLeakChecker:
122
+ def get_open_files(self) -> list[tuple[str, str]]:
123
+ if sys.version_info >= (3, 11):
124
+ # New in Python 3.11, ignores utf-8 mode
125
+ encoding = locale.getencoding()
126
+ else:
127
+ encoding = locale.getpreferredencoding(False)
128
+ out = subprocess.run(
129
+ ("lsof", "-Ffn0", "-p", str(os.getpid())),
130
+ stdout=subprocess.PIPE,
131
+ stderr=subprocess.DEVNULL,
132
+ check=True,
133
+ text=True,
134
+ encoding=encoding,
135
+ ).stdout
136
+
137
+ def isopen(line: str) -> bool:
138
+ return line.startswith("f") and (
139
+ "deleted" not in line
140
+ and "mem" not in line
141
+ and "txt" not in line
142
+ and "cwd" not in line
143
+ )
144
+
145
+ open_files = []
146
+
147
+ for line in out.split("\n"):
148
+ if isopen(line):
149
+ fields = line.split("\0")
150
+ fd = fields[0][1:]
151
+ filename = fields[1][1:]
152
+ if filename in IGNORE_PAM:
153
+ continue
154
+ if filename.startswith("/"):
155
+ open_files.append((fd, filename))
156
+
157
+ return open_files
158
+
159
+ def matching_platform(self) -> bool:
160
+ try:
161
+ subprocess.run(("lsof", "-v"), check=True)
162
+ except (OSError, subprocess.CalledProcessError):
163
+ return False
164
+ else:
165
+ return True
166
+
167
+ @hookimpl(wrapper=True, tryfirst=True)
168
+ def pytest_runtest_protocol(self, item: Item) -> Generator[None, object, object]:
169
+ lines1 = self.get_open_files()
170
+ try:
171
+ return (yield)
172
+ finally:
173
+ if hasattr(sys, "pypy_version_info"):
174
+ gc.collect()
175
+ lines2 = self.get_open_files()
176
+
177
+ new_fds = {t[0] for t in lines2} - {t[0] for t in lines1}
178
+ leaked_files = [t for t in lines2 if t[0] in new_fds]
179
+ if leaked_files:
180
+ error = [
181
+ f"***** {len(leaked_files)} FD leakage detected",
182
+ *(str(f) for f in leaked_files),
183
+ "*** Before:",
184
+ *(str(f) for f in lines1),
185
+ "*** After:",
186
+ *(str(f) for f in lines2),
187
+ f"***** {len(leaked_files)} FD leakage detected",
188
+ "*** function {}:{}: {} ".format(*item.location),
189
+ "See issue #2366",
190
+ ]
191
+ item.warn(PytestWarning("\n".join(error)))
192
+
193
+
194
+ # used at least by pytest-xdist plugin
195
+
196
+
197
+ @fixture
198
+ def _pytest(request: FixtureRequest) -> PytestArg:
199
+ """Return a helper which offers a gethookrecorder(hook) method which
200
+ returns a HookRecorder instance which helps to make assertions about called
201
+ hooks."""
202
+ return PytestArg(request)
203
+
204
+
205
+ class PytestArg:
206
+ def __init__(self, request: FixtureRequest) -> None:
207
+ self._request = request
208
+
209
+ def gethookrecorder(self, hook) -> HookRecorder:
210
+ hookrecorder = HookRecorder(hook._pm)
211
+ self._request.addfinalizer(hookrecorder.finish_recording)
212
+ return hookrecorder
213
+
214
+
215
+ def get_public_names(values: Iterable[str]) -> list[str]:
216
+ """Only return names from iterator values without a leading underscore."""
217
+ return [x for x in values if x[0] != "_"]
218
+
219
+
220
+ @final
221
+ class RecordedHookCall:
222
+ """A recorded call to a hook.
223
+
224
+ The arguments to the hook call are set as attributes.
225
+ For example:
226
+
227
+ .. code-block:: python
228
+
229
+ calls = hook_recorder.getcalls("pytest_runtest_setup")
230
+ # Suppose pytest_runtest_setup was called once with `item=an_item`.
231
+ assert calls[0].item is an_item
232
+ """
233
+
234
+ def __init__(self, name: str, kwargs) -> None:
235
+ self.__dict__.update(kwargs)
236
+ self._name = name
237
+
238
+ def __repr__(self) -> str:
239
+ d = self.__dict__.copy()
240
+ del d["_name"]
241
+ return f"<RecordedHookCall {self._name!r}(**{d!r})>"
242
+
243
+ if TYPE_CHECKING:
244
+ # The class has undetermined attributes, this tells mypy about it.
245
+ def __getattr__(self, key: str): ...
246
+
247
+
248
+ @final
249
+ class HookRecorder:
250
+ """Record all hooks called in a plugin manager.
251
+
252
+ Hook recorders are created by :class:`Pytester`.
253
+
254
+ This wraps all the hook calls in the plugin manager, recording each call
255
+ before propagating the normal calls.
256
+ """
257
+
258
+ def __init__(
259
+ self, pluginmanager: PytestPluginManager, *, _ispytest: bool = False
260
+ ) -> None:
261
+ check_ispytest(_ispytest)
262
+
263
+ self._pluginmanager = pluginmanager
264
+ self.calls: list[RecordedHookCall] = []
265
+ self.ret: int | ExitCode | None = None
266
+
267
+ def before(hook_name: str, hook_impls, kwargs) -> None:
268
+ self.calls.append(RecordedHookCall(hook_name, kwargs))
269
+
270
+ def after(outcome, hook_name: str, hook_impls, kwargs) -> None:
271
+ pass
272
+
273
+ self._undo_wrapping = pluginmanager.add_hookcall_monitoring(before, after)
274
+
275
+ def finish_recording(self) -> None:
276
+ self._undo_wrapping()
277
+
278
+ def getcalls(self, names: str | Iterable[str]) -> list[RecordedHookCall]:
279
+ """Get all recorded calls to hooks with the given names (or name)."""
280
+ if isinstance(names, str):
281
+ names = names.split()
282
+ return [call for call in self.calls if call._name in names]
283
+
284
+ def assert_contains(self, entries: Sequence[tuple[str, str]]) -> None:
285
+ __tracebackhide__ = True
286
+ i = 0
287
+ entries = list(entries)
288
+ # Since Python 3.13, f_locals is not a dict, but eval requires a dict.
289
+ backlocals = dict(sys._getframe(1).f_locals)
290
+ while entries:
291
+ name, check = entries.pop(0)
292
+ for ind, call in enumerate(self.calls[i:]):
293
+ if call._name == name:
294
+ print("NAMEMATCH", name, call)
295
+ if eval(check, backlocals, call.__dict__):
296
+ print("CHECKERMATCH", repr(check), "->", call)
297
+ else:
298
+ print("NOCHECKERMATCH", repr(check), "-", call)
299
+ continue
300
+ i += ind + 1
301
+ break
302
+ print("NONAMEMATCH", name, "with", call)
303
+ else:
304
+ fail(f"could not find {name!r} check {check!r}")
305
+
306
+ def popcall(self, name: str) -> RecordedHookCall:
307
+ __tracebackhide__ = True
308
+ for i, call in enumerate(self.calls):
309
+ if call._name == name:
310
+ del self.calls[i]
311
+ return call
312
+ lines = [f"could not find call {name!r}, in:"]
313
+ lines.extend([f" {x}" for x in self.calls])
314
+ fail("\n".join(lines))
315
+
316
+ def getcall(self, name: str) -> RecordedHookCall:
317
+ values = self.getcalls(name)
318
+ assert len(values) == 1, (name, values)
319
+ return values[0]
320
+
321
+ # functionality for test reports
322
+
323
+ @overload
324
+ def getreports(
325
+ self,
326
+ names: Literal["pytest_collectreport"],
327
+ ) -> Sequence[CollectReport]: ...
328
+
329
+ @overload
330
+ def getreports(
331
+ self,
332
+ names: Literal["pytest_runtest_logreport"],
333
+ ) -> Sequence[TestReport]: ...
334
+
335
+ @overload
336
+ def getreports(
337
+ self,
338
+ names: str | Iterable[str] = (
339
+ "pytest_collectreport",
340
+ "pytest_runtest_logreport",
341
+ ),
342
+ ) -> Sequence[CollectReport | TestReport]: ...
343
+
344
+ def getreports(
345
+ self,
346
+ names: str | Iterable[str] = (
347
+ "pytest_collectreport",
348
+ "pytest_runtest_logreport",
349
+ ),
350
+ ) -> Sequence[CollectReport | TestReport]:
351
+ return [x.report for x in self.getcalls(names)]
352
+
353
+ def matchreport(
354
+ self,
355
+ inamepart: str = "",
356
+ names: str | Iterable[str] = (
357
+ "pytest_runtest_logreport",
358
+ "pytest_collectreport",
359
+ ),
360
+ when: str | None = None,
361
+ ) -> CollectReport | TestReport:
362
+ """Return a testreport whose dotted import path matches."""
363
+ values = []
364
+ for rep in self.getreports(names=names):
365
+ if not when and rep.when != "call" and rep.passed:
366
+ # setup/teardown passing reports - let's ignore those
367
+ continue
368
+ if when and rep.when != when:
369
+ continue
370
+ if not inamepart or inamepart in rep.nodeid.split("::"):
371
+ values.append(rep)
372
+ if not values:
373
+ raise ValueError(
374
+ f"could not find test report matching {inamepart!r}: "
375
+ "no test reports at all!"
376
+ )
377
+ if len(values) > 1:
378
+ raise ValueError(
379
+ f"found 2 or more testreports matching {inamepart!r}: {values}"
380
+ )
381
+ return values[0]
382
+
383
+ @overload
384
+ def getfailures(
385
+ self,
386
+ names: Literal["pytest_collectreport"],
387
+ ) -> Sequence[CollectReport]: ...
388
+
389
+ @overload
390
+ def getfailures(
391
+ self,
392
+ names: Literal["pytest_runtest_logreport"],
393
+ ) -> Sequence[TestReport]: ...
394
+
395
+ @overload
396
+ def getfailures(
397
+ self,
398
+ names: str | Iterable[str] = (
399
+ "pytest_collectreport",
400
+ "pytest_runtest_logreport",
401
+ ),
402
+ ) -> Sequence[CollectReport | TestReport]: ...
403
+
404
+ def getfailures(
405
+ self,
406
+ names: str | Iterable[str] = (
407
+ "pytest_collectreport",
408
+ "pytest_runtest_logreport",
409
+ ),
410
+ ) -> Sequence[CollectReport | TestReport]:
411
+ return [rep for rep in self.getreports(names) if rep.failed]
412
+
413
+ def getfailedcollections(self) -> Sequence[CollectReport]:
414
+ return self.getfailures("pytest_collectreport")
415
+
416
+ def listoutcomes(
417
+ self,
418
+ ) -> tuple[
419
+ Sequence[TestReport],
420
+ Sequence[CollectReport | TestReport],
421
+ Sequence[CollectReport | TestReport],
422
+ ]:
423
+ passed = []
424
+ skipped = []
425
+ failed = []
426
+ for rep in self.getreports(
427
+ ("pytest_collectreport", "pytest_runtest_logreport")
428
+ ):
429
+ if rep.passed:
430
+ if rep.when == "call":
431
+ assert isinstance(rep, TestReport)
432
+ passed.append(rep)
433
+ elif rep.skipped:
434
+ skipped.append(rep)
435
+ else:
436
+ assert rep.failed, f"Unexpected outcome: {rep!r}"
437
+ failed.append(rep)
438
+ return passed, skipped, failed
439
+
440
+ def countoutcomes(self) -> list[int]:
441
+ return [len(x) for x in self.listoutcomes()]
442
+
443
+ def assertoutcome(self, passed: int = 0, skipped: int = 0, failed: int = 0) -> None:
444
+ __tracebackhide__ = True
445
+ from _pytest.pytester_assertions import assertoutcome
446
+
447
+ outcomes = self.listoutcomes()
448
+ assertoutcome(
449
+ outcomes,
450
+ passed=passed,
451
+ skipped=skipped,
452
+ failed=failed,
453
+ )
454
+
455
+ def clear(self) -> None:
456
+ self.calls[:] = []
457
+
458
+
459
+ @fixture
460
+ def linecomp() -> LineComp:
461
+ """A :class: `LineComp` instance for checking that an input linearly
462
+ contains a sequence of strings."""
463
+ return LineComp()
464
+
465
+
466
+ @fixture(name="LineMatcher")
467
+ def LineMatcher_fixture(request: FixtureRequest) -> type[LineMatcher]:
468
+ """A reference to the :class: `LineMatcher`.
469
+
470
+ This is instantiable with a list of lines (without their trailing newlines).
471
+ This is useful for testing large texts, such as the output of commands.
472
+ """
473
+ return LineMatcher
474
+
475
+
476
+ @fixture
477
+ def pytester(
478
+ request: FixtureRequest, tmp_path_factory: TempPathFactory, monkeypatch: MonkeyPatch
479
+ ) -> Pytester:
480
+ """
481
+ Facilities to write tests/configuration files, execute pytest in isolation, and match
482
+ against expected output, perfect for black-box testing of pytest plugins.
483
+
484
+ It attempts to isolate the test run from external factors as much as possible, modifying
485
+ the current working directory to ``path`` and environment variables during initialization.
486
+
487
+ It is particularly useful for testing plugins. It is similar to the :fixture:`tmp_path`
488
+ fixture but provides methods which aid in testing pytest itself.
489
+ """
490
+ return Pytester(request, tmp_path_factory, monkeypatch, _ispytest=True)
491
+
492
+
493
+ @fixture
494
+ def _sys_snapshot() -> Generator[None]:
495
+ snappaths = SysPathsSnapshot()
496
+ snapmods = SysModulesSnapshot()
497
+ yield
498
+ snapmods.restore()
499
+ snappaths.restore()
500
+
501
+
502
+ @fixture
503
+ def _config_for_test() -> Generator[Config]:
504
+ from _pytest.config import get_config
505
+
506
+ config = get_config()
507
+ yield config
508
+ config._ensure_unconfigure() # cleanup, e.g. capman closing tmpfiles.
509
+
510
+
511
+ # Regex to match the session duration string in the summary: "74.34s".
512
+ rex_session_duration = re.compile(r"\d+\.\d\ds")
513
+ # Regex to match all the counts and phrases in the summary line: "34 passed, 111 skipped".
514
+ rex_outcome = re.compile(r"(\d+) (\w+)")
515
+
516
+
517
+ @final
518
+ class RunResult:
519
+ """The result of running a command from :class:`~pytest.Pytester`."""
520
+
521
+ def __init__(
522
+ self,
523
+ ret: int | ExitCode,
524
+ outlines: list[str],
525
+ errlines: list[str],
526
+ duration: float,
527
+ ) -> None:
528
+ try:
529
+ self.ret: int | ExitCode = ExitCode(ret)
530
+ """The return value."""
531
+ except ValueError:
532
+ self.ret = ret
533
+ self.outlines = outlines
534
+ """List of lines captured from stdout."""
535
+ self.errlines = errlines
536
+ """List of lines captured from stderr."""
537
+ self.stdout = LineMatcher(outlines)
538
+ """:class:`~pytest.LineMatcher` of stdout.
539
+
540
+ Use e.g. :func:`str(stdout) <pytest.LineMatcher.__str__()>` to reconstruct stdout, or the commonly used
541
+ :func:`stdout.fnmatch_lines() <pytest.LineMatcher.fnmatch_lines()>` method.
542
+ """
543
+ self.stderr = LineMatcher(errlines)
544
+ """:class:`~pytest.LineMatcher` of stderr."""
545
+ self.duration = duration
546
+ """Duration in seconds."""
547
+
548
+ def __repr__(self) -> str:
549
+ return (
550
+ "<RunResult ret=%s len(stdout.lines)=%d len(stderr.lines)=%d duration=%.2fs>"
551
+ % (self.ret, len(self.stdout.lines), len(self.stderr.lines), self.duration)
552
+ )
553
+
554
+ def parseoutcomes(self) -> dict[str, int]:
555
+ """Return a dictionary of outcome noun -> count from parsing the terminal
556
+ output that the test process produced.
557
+
558
+ The returned nouns will always be in plural form::
559
+
560
+ ======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s ====
561
+
562
+ Will return ``{"failed": 1, "passed": 1, "warnings": 1, "errors": 1}``.
563
+ """
564
+ return self.parse_summary_nouns(self.outlines)
565
+
566
+ @classmethod
567
+ def parse_summary_nouns(cls, lines) -> dict[str, int]:
568
+ """Extract the nouns from a pytest terminal summary line.
569
+
570
+ It always returns the plural noun for consistency::
571
+
572
+ ======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s ====
573
+
574
+ Will return ``{"failed": 1, "passed": 1, "warnings": 1, "errors": 1}``.
575
+ """
576
+ for line in reversed(lines):
577
+ if rex_session_duration.search(line):
578
+ outcomes = rex_outcome.findall(line)
579
+ ret = {noun: int(count) for (count, noun) in outcomes}
580
+ break
581
+ else:
582
+ raise ValueError("Pytest terminal summary report not found")
583
+
584
+ to_plural = {
585
+ "warning": "warnings",
586
+ "error": "errors",
587
+ }
588
+ return {to_plural.get(k, k): v for k, v in ret.items()}
589
+
590
+ def assert_outcomes(
591
+ self,
592
+ passed: int = 0,
593
+ skipped: int = 0,
594
+ failed: int = 0,
595
+ errors: int = 0,
596
+ xpassed: int = 0,
597
+ xfailed: int = 0,
598
+ warnings: int | None = None,
599
+ deselected: int | None = None,
600
+ ) -> None:
601
+ """
602
+ Assert that the specified outcomes appear with the respective
603
+ numbers (0 means it didn't occur) in the text output from a test run.
604
+
605
+ ``warnings`` and ``deselected`` are only checked if not None.
606
+ """
607
+ __tracebackhide__ = True
608
+ from _pytest.pytester_assertions import assert_outcomes
609
+
610
+ outcomes = self.parseoutcomes()
611
+ assert_outcomes(
612
+ outcomes,
613
+ passed=passed,
614
+ skipped=skipped,
615
+ failed=failed,
616
+ errors=errors,
617
+ xpassed=xpassed,
618
+ xfailed=xfailed,
619
+ warnings=warnings,
620
+ deselected=deselected,
621
+ )
622
+
623
+
624
+ class SysModulesSnapshot:
625
+ def __init__(self, preserve: Callable[[str], bool] | None = None) -> None:
626
+ self.__preserve = preserve
627
+ self.__saved = dict(sys.modules)
628
+
629
+ def restore(self) -> None:
630
+ if self.__preserve:
631
+ self.__saved.update(
632
+ (k, m) for k, m in sys.modules.items() if self.__preserve(k)
633
+ )
634
+ sys.modules.clear()
635
+ sys.modules.update(self.__saved)
636
+
637
+
638
+ class SysPathsSnapshot:
639
+ def __init__(self) -> None:
640
+ self.__saved = list(sys.path), list(sys.meta_path)
641
+
642
+ def restore(self) -> None:
643
+ sys.path[:], sys.meta_path[:] = self.__saved
644
+
645
+
646
+ @final
647
+ class Pytester:
648
+ """
649
+ Facilities to write tests/configuration files, execute pytest in isolation, and match
650
+ against expected output, perfect for black-box testing of pytest plugins.
651
+
652
+ It attempts to isolate the test run from external factors as much as possible, modifying
653
+ the current working directory to :attr:`path` and environment variables during initialization.
654
+ """
655
+
656
+ __test__ = False
657
+
658
+ CLOSE_STDIN: Final = NOTSET
659
+
660
+ class TimeoutExpired(Exception):
661
+ pass
662
+
663
+ def __init__(
664
+ self,
665
+ request: FixtureRequest,
666
+ tmp_path_factory: TempPathFactory,
667
+ monkeypatch: MonkeyPatch,
668
+ *,
669
+ _ispytest: bool = False,
670
+ ) -> None:
671
+ check_ispytest(_ispytest)
672
+ self._request = request
673
+ self._mod_collections: WeakKeyDictionary[Collector, list[Item | Collector]] = (
674
+ WeakKeyDictionary()
675
+ )
676
+ if request.function:
677
+ name: str = request.function.__name__
678
+ else:
679
+ name = request.node.name
680
+ self._name = name
681
+ self._path: Path = tmp_path_factory.mktemp(name, numbered=True)
682
+ #: A list of plugins to use with :py:meth:`parseconfig` and
683
+ #: :py:meth:`runpytest`. Initially this is an empty list but plugins can
684
+ #: be added to the list. The type of items to add to the list depends on
685
+ #: the method using them so refer to them for details.
686
+ self.plugins: list[str | _PluggyPlugin] = []
687
+ self._sys_path_snapshot = SysPathsSnapshot()
688
+ self._sys_modules_snapshot = self.__take_sys_modules_snapshot()
689
+ self._request.addfinalizer(self._finalize)
690
+ self._method = self._request.config.getoption("--runpytest")
691
+ self._test_tmproot = tmp_path_factory.mktemp(f"tmp-{name}", numbered=True)
692
+
693
+ self._monkeypatch = mp = monkeypatch
694
+ self.chdir()
695
+ mp.setenv("PYTEST_DEBUG_TEMPROOT", str(self._test_tmproot))
696
+ # Ensure no unexpected caching via tox.
697
+ mp.delenv("TOX_ENV_DIR", raising=False)
698
+ # Discard outer pytest options.
699
+ mp.delenv("PYTEST_ADDOPTS", raising=False)
700
+ # Ensure no user config is used.
701
+ tmphome = str(self.path)
702
+ mp.setenv("HOME", tmphome)
703
+ mp.setenv("USERPROFILE", tmphome)
704
+ # Do not use colors for inner runs by default.
705
+ mp.setenv("PY_COLORS", "0")
706
+
707
+ @property
708
+ def path(self) -> Path:
709
+ """Temporary directory path used to create files/run tests from, etc."""
710
+ return self._path
711
+
712
+ def __repr__(self) -> str:
713
+ return f"<Pytester {self.path!r}>"
714
+
715
+ def _finalize(self) -> None:
716
+ """
717
+ Clean up global state artifacts.
718
+
719
+ Some methods modify the global interpreter state and this tries to
720
+ clean this up. It does not remove the temporary directory however so
721
+ it can be looked at after the test run has finished.
722
+ """
723
+ self._sys_modules_snapshot.restore()
724
+ self._sys_path_snapshot.restore()
725
+
726
+ def __take_sys_modules_snapshot(self) -> SysModulesSnapshot:
727
+ # Some zope modules used by twisted-related tests keep internal state
728
+ # and can't be deleted; we had some trouble in the past with
729
+ # `zope.interface` for example.
730
+ #
731
+ # Preserve readline due to https://bugs.python.org/issue41033.
732
+ # pexpect issues a SIGWINCH.
733
+ def preserve_module(name):
734
+ return name.startswith(("zope", "readline"))
735
+
736
+ return SysModulesSnapshot(preserve=preserve_module)
737
+
738
+ def make_hook_recorder(self, pluginmanager: PytestPluginManager) -> HookRecorder:
739
+ """Create a new :class:`HookRecorder` for a :class:`PytestPluginManager`."""
740
+ pluginmanager.reprec = reprec = HookRecorder(pluginmanager, _ispytest=True) # type: ignore[attr-defined]
741
+ self._request.addfinalizer(reprec.finish_recording)
742
+ return reprec
743
+
744
+ def chdir(self) -> None:
745
+ """Cd into the temporary directory.
746
+
747
+ This is done automatically upon instantiation.
748
+ """
749
+ self._monkeypatch.chdir(self.path)
750
+
751
+ def _makefile(
752
+ self,
753
+ ext: str,
754
+ lines: Sequence[Any | bytes],
755
+ files: dict[str, str],
756
+ encoding: str = "utf-8",
757
+ ) -> Path:
758
+ items = list(files.items())
759
+
760
+ if ext is None:
761
+ raise TypeError("ext must not be None")
762
+
763
+ if ext and not ext.startswith("."):
764
+ raise ValueError(
765
+ f"pytester.makefile expects a file extension, try .{ext} instead of {ext}"
766
+ )
767
+
768
+ def to_text(s: Any | bytes) -> str:
769
+ return s.decode(encoding) if isinstance(s, bytes) else str(s)
770
+
771
+ if lines:
772
+ source = "\n".join(to_text(x) for x in lines)
773
+ basename = self._name
774
+ items.insert(0, (basename, source))
775
+
776
+ ret = None
777
+ for basename, value in items:
778
+ p = self.path.joinpath(basename).with_suffix(ext)
779
+ p.parent.mkdir(parents=True, exist_ok=True)
780
+ source_ = Source(value)
781
+ source = "\n".join(to_text(line) for line in source_.lines)
782
+ p.write_text(source.strip(), encoding=encoding)
783
+ if ret is None:
784
+ ret = p
785
+ assert ret is not None
786
+ return ret
787
+
788
+ def makefile(self, ext: str, *args: str, **kwargs: str) -> Path:
789
+ r"""Create new text file(s) in the test directory.
790
+
791
+ :param ext:
792
+ The extension the file(s) should use, including the dot, e.g. `.py`.
793
+ :param args:
794
+ All args are treated as strings and joined using newlines.
795
+ The result is written as contents to the file. The name of the
796
+ file is based on the test function requesting this fixture.
797
+ :param kwargs:
798
+ Each keyword is the name of a file, while the value of it will
799
+ be written as contents of the file.
800
+ :returns:
801
+ The first created file.
802
+
803
+ Examples:
804
+
805
+ .. code-block:: python
806
+
807
+ pytester.makefile(".txt", "line1", "line2")
808
+
809
+ pytester.makefile(".ini", pytest="[pytest]\naddopts=-rs\n")
810
+
811
+ To create binary files, use :meth:`pathlib.Path.write_bytes` directly:
812
+
813
+ .. code-block:: python
814
+
815
+ filename = pytester.path.joinpath("foo.bin")
816
+ filename.write_bytes(b"...")
817
+ """
818
+ return self._makefile(ext, args, kwargs)
819
+
820
+ def makeconftest(self, source: str) -> Path:
821
+ """Write a conftest.py file.
822
+
823
+ :param source: The contents.
824
+ :returns: The conftest.py file.
825
+ """
826
+ return self.makepyfile(conftest=source)
827
+
828
+ def makeini(self, source: str) -> Path:
829
+ """Write a tox.ini file.
830
+
831
+ :param source: The contents.
832
+ :returns: The tox.ini file.
833
+ """
834
+ return self.makefile(".ini", tox=source)
835
+
836
+ def getinicfg(self, source: str) -> SectionWrapper:
837
+ """Return the pytest section from the tox.ini config file."""
838
+ p = self.makeini(source)
839
+ return IniConfig(str(p))["pytest"]
840
+
841
+ def makepyprojecttoml(self, source: str) -> Path:
842
+ """Write a pyproject.toml file.
843
+
844
+ :param source: The contents.
845
+ :returns: The pyproject.ini file.
846
+
847
+ .. versionadded:: 6.0
848
+ """
849
+ return self.makefile(".toml", pyproject=source)
850
+
851
+ def makepyfile(self, *args, **kwargs) -> Path:
852
+ r"""Shortcut for .makefile() with a .py extension.
853
+
854
+ Defaults to the test name with a '.py' extension, e.g test_foobar.py, overwriting
855
+ existing files.
856
+
857
+ Examples:
858
+
859
+ .. code-block:: python
860
+
861
+ def test_something(pytester):
862
+ # Initial file is created test_something.py.
863
+ pytester.makepyfile("foobar")
864
+ # To create multiple files, pass kwargs accordingly.
865
+ pytester.makepyfile(custom="foobar")
866
+ # At this point, both 'test_something.py' & 'custom.py' exist in the test directory.
867
+
868
+ """
869
+ return self._makefile(".py", args, kwargs)
870
+
871
+ def maketxtfile(self, *args, **kwargs) -> Path:
872
+ r"""Shortcut for .makefile() with a .txt extension.
873
+
874
+ Defaults to the test name with a '.txt' extension, e.g test_foobar.txt, overwriting
875
+ existing files.
876
+
877
+ Examples:
878
+
879
+ .. code-block:: python
880
+
881
+ def test_something(pytester):
882
+ # Initial file is created test_something.txt.
883
+ pytester.maketxtfile("foobar")
884
+ # To create multiple files, pass kwargs accordingly.
885
+ pytester.maketxtfile(custom="foobar")
886
+ # At this point, both 'test_something.txt' & 'custom.txt' exist in the test directory.
887
+
888
+ """
889
+ return self._makefile(".txt", args, kwargs)
890
+
891
+ def syspathinsert(self, path: str | os.PathLike[str] | None = None) -> None:
892
+ """Prepend a directory to sys.path, defaults to :attr:`path`.
893
+
894
+ This is undone automatically when this object dies at the end of each
895
+ test.
896
+
897
+ :param path:
898
+ The path.
899
+ """
900
+ if path is None:
901
+ path = self.path
902
+
903
+ self._monkeypatch.syspath_prepend(str(path))
904
+
905
+ def mkdir(self, name: str | os.PathLike[str]) -> Path:
906
+ """Create a new (sub)directory.
907
+
908
+ :param name:
909
+ The name of the directory, relative to the pytester path.
910
+ :returns:
911
+ The created directory.
912
+ :rtype: pathlib.Path
913
+ """
914
+ p = self.path / name
915
+ p.mkdir()
916
+ return p
917
+
918
+ def mkpydir(self, name: str | os.PathLike[str]) -> Path:
919
+ """Create a new python package.
920
+
921
+ This creates a (sub)directory with an empty ``__init__.py`` file so it
922
+ gets recognised as a Python package.
923
+ """
924
+ p = self.path / name
925
+ p.mkdir()
926
+ p.joinpath("__init__.py").touch()
927
+ return p
928
+
929
+ def copy_example(self, name: str | None = None) -> Path:
930
+ """Copy file from project's directory into the testdir.
931
+
932
+ :param name:
933
+ The name of the file to copy.
934
+ :return:
935
+ Path to the copied directory (inside ``self.path``).
936
+ :rtype: pathlib.Path
937
+ """
938
+ example_dir_ = self._request.config.getini("pytester_example_dir")
939
+ if example_dir_ is None:
940
+ raise ValueError("pytester_example_dir is unset, can't copy examples")
941
+ example_dir: Path = self._request.config.rootpath / example_dir_
942
+
943
+ for extra_element in self._request.node.iter_markers("pytester_example_path"):
944
+ assert extra_element.args
945
+ example_dir = example_dir.joinpath(*extra_element.args)
946
+
947
+ if name is None:
948
+ func_name = self._name
949
+ maybe_dir = example_dir / func_name
950
+ maybe_file = example_dir / (func_name + ".py")
951
+
952
+ if maybe_dir.is_dir():
953
+ example_path = maybe_dir
954
+ elif maybe_file.is_file():
955
+ example_path = maybe_file
956
+ else:
957
+ raise LookupError(
958
+ f"{func_name} can't be found as module or package in {example_dir}"
959
+ )
960
+ else:
961
+ example_path = example_dir.joinpath(name)
962
+
963
+ if example_path.is_dir() and not example_path.joinpath("__init__.py").is_file():
964
+ shutil.copytree(example_path, self.path, symlinks=True, dirs_exist_ok=True)
965
+ return self.path
966
+ elif example_path.is_file():
967
+ result = self.path.joinpath(example_path.name)
968
+ shutil.copy(example_path, result)
969
+ return result
970
+ else:
971
+ raise LookupError(
972
+ f'example "{example_path}" is not found as a file or directory'
973
+ )
974
+
975
+ def getnode(self, config: Config, arg: str | os.PathLike[str]) -> Collector | Item:
976
+ """Get the collection node of a file.
977
+
978
+ :param config:
979
+ A pytest config.
980
+ See :py:meth:`parseconfig` and :py:meth:`parseconfigure` for creating it.
981
+ :param arg:
982
+ Path to the file.
983
+ :returns:
984
+ The node.
985
+ """
986
+ session = Session.from_config(config)
987
+ assert "::" not in str(arg)
988
+ p = Path(os.path.abspath(arg))
989
+ config.hook.pytest_sessionstart(session=session)
990
+ res = session.perform_collect([str(p)], genitems=False)[0]
991
+ config.hook.pytest_sessionfinish(session=session, exitstatus=ExitCode.OK)
992
+ return res
993
+
994
+ def getpathnode(self, path: str | os.PathLike[str]) -> Collector | Item:
995
+ """Return the collection node of a file.
996
+
997
+ This is like :py:meth:`getnode` but uses :py:meth:`parseconfigure` to
998
+ create the (configured) pytest Config instance.
999
+
1000
+ :param path:
1001
+ Path to the file.
1002
+ :returns:
1003
+ The node.
1004
+ """
1005
+ path = Path(path)
1006
+ config = self.parseconfigure(path)
1007
+ session = Session.from_config(config)
1008
+ x = bestrelpath(session.path, path)
1009
+ config.hook.pytest_sessionstart(session=session)
1010
+ res = session.perform_collect([x], genitems=False)[0]
1011
+ config.hook.pytest_sessionfinish(session=session, exitstatus=ExitCode.OK)
1012
+ return res
1013
+
1014
+ def genitems(self, colitems: Sequence[Item | Collector]) -> list[Item]:
1015
+ """Generate all test items from a collection node.
1016
+
1017
+ This recurses into the collection node and returns a list of all the
1018
+ test items contained within.
1019
+
1020
+ :param colitems:
1021
+ The collection nodes.
1022
+ :returns:
1023
+ The collected items.
1024
+ """
1025
+ session = colitems[0].session
1026
+ result: list[Item] = []
1027
+ for colitem in colitems:
1028
+ result.extend(session.genitems(colitem))
1029
+ return result
1030
+
1031
+ def runitem(self, source: str) -> Any:
1032
+ """Run the "test_func" Item.
1033
+
1034
+ The calling test instance (class containing the test method) must
1035
+ provide a ``.getrunner()`` method which should return a runner which
1036
+ can run the test protocol for a single item, e.g.
1037
+ ``_pytest.runner.runtestprotocol``.
1038
+ """
1039
+ # used from runner functional tests
1040
+ item = self.getitem(source)
1041
+ # the test class where we are called from wants to provide the runner
1042
+ testclassinstance = self._request.instance
1043
+ runner = testclassinstance.getrunner()
1044
+ return runner(item)
1045
+
1046
+ def inline_runsource(self, source: str, *cmdlineargs) -> HookRecorder:
1047
+ """Run a test module in process using ``pytest.main()``.
1048
+
1049
+ This run writes "source" into a temporary file and runs
1050
+ ``pytest.main()`` on it, returning a :py:class:`HookRecorder` instance
1051
+ for the result.
1052
+
1053
+ :param source: The source code of the test module.
1054
+ :param cmdlineargs: Any extra command line arguments to use.
1055
+ """
1056
+ p = self.makepyfile(source)
1057
+ values = [*list(cmdlineargs), p]
1058
+ return self.inline_run(*values)
1059
+
1060
+ def inline_genitems(self, *args) -> tuple[list[Item], HookRecorder]:
1061
+ """Run ``pytest.main(['--collect-only'])`` in-process.
1062
+
1063
+ Runs the :py:func:`pytest.main` function to run all of pytest inside
1064
+ the test process itself like :py:meth:`inline_run`, but returns a
1065
+ tuple of the collected items and a :py:class:`HookRecorder` instance.
1066
+ """
1067
+ rec = self.inline_run("--collect-only", *args)
1068
+ items = [x.item for x in rec.getcalls("pytest_itemcollected")]
1069
+ return items, rec
1070
+
1071
+ def inline_run(
1072
+ self,
1073
+ *args: str | os.PathLike[str],
1074
+ plugins=(),
1075
+ no_reraise_ctrlc: bool = False,
1076
+ ) -> HookRecorder:
1077
+ """Run ``pytest.main()`` in-process, returning a HookRecorder.
1078
+
1079
+ Runs the :py:func:`pytest.main` function to run all of pytest inside
1080
+ the test process itself. This means it can return a
1081
+ :py:class:`HookRecorder` instance which gives more detailed results
1082
+ from that run than can be done by matching stdout/stderr from
1083
+ :py:meth:`runpytest`.
1084
+
1085
+ :param args:
1086
+ Command line arguments to pass to :py:func:`pytest.main`.
1087
+ :param plugins:
1088
+ Extra plugin instances the ``pytest.main()`` instance should use.
1089
+ :param no_reraise_ctrlc:
1090
+ Typically we reraise keyboard interrupts from the child run. If
1091
+ True, the KeyboardInterrupt exception is captured.
1092
+ """
1093
+ # (maybe a cpython bug?) the importlib cache sometimes isn't updated
1094
+ # properly between file creation and inline_run (especially if imports
1095
+ # are interspersed with file creation)
1096
+ importlib.invalidate_caches()
1097
+
1098
+ plugins = list(plugins)
1099
+ finalizers = []
1100
+ try:
1101
+ # Any sys.module or sys.path changes done while running pytest
1102
+ # inline should be reverted after the test run completes to avoid
1103
+ # clashing with later inline tests run within the same pytest test,
1104
+ # e.g. just because they use matching test module names.
1105
+ finalizers.append(self.__take_sys_modules_snapshot().restore)
1106
+ finalizers.append(SysPathsSnapshot().restore)
1107
+
1108
+ # Important note:
1109
+ # - our tests should not leave any other references/registrations
1110
+ # laying around other than possibly loaded test modules
1111
+ # referenced from sys.modules, as nothing will clean those up
1112
+ # automatically
1113
+
1114
+ rec = []
1115
+
1116
+ class Collect:
1117
+ def pytest_configure(x, config: Config) -> None:
1118
+ rec.append(self.make_hook_recorder(config.pluginmanager))
1119
+
1120
+ plugins.append(Collect())
1121
+ ret = main([str(x) for x in args], plugins=plugins)
1122
+ if len(rec) == 1:
1123
+ reprec = rec.pop()
1124
+ else:
1125
+
1126
+ class reprec: # type: ignore
1127
+ pass
1128
+
1129
+ reprec.ret = ret
1130
+
1131
+ # Typically we reraise keyboard interrupts from the child run
1132
+ # because it's our user requesting interruption of the testing.
1133
+ if ret == ExitCode.INTERRUPTED and not no_reraise_ctrlc:
1134
+ calls = reprec.getcalls("pytest_keyboard_interrupt")
1135
+ if calls and calls[-1].excinfo.type == KeyboardInterrupt:
1136
+ raise KeyboardInterrupt()
1137
+ return reprec
1138
+ finally:
1139
+ for finalizer in finalizers:
1140
+ finalizer()
1141
+
1142
+ def runpytest_inprocess(
1143
+ self, *args: str | os.PathLike[str], **kwargs: Any
1144
+ ) -> RunResult:
1145
+ """Return result of running pytest in-process, providing a similar
1146
+ interface to what self.runpytest() provides."""
1147
+ syspathinsert = kwargs.pop("syspathinsert", False)
1148
+
1149
+ if syspathinsert:
1150
+ self.syspathinsert()
1151
+ now = timing.time()
1152
+ capture = _get_multicapture("sys")
1153
+ capture.start_capturing()
1154
+ try:
1155
+ try:
1156
+ reprec = self.inline_run(*args, **kwargs)
1157
+ except SystemExit as e:
1158
+ ret = e.args[0]
1159
+ try:
1160
+ ret = ExitCode(e.args[0])
1161
+ except ValueError:
1162
+ pass
1163
+
1164
+ class reprec: # type: ignore
1165
+ ret = ret
1166
+
1167
+ except Exception:
1168
+ traceback.print_exc()
1169
+
1170
+ class reprec: # type: ignore
1171
+ ret = ExitCode(3)
1172
+
1173
+ finally:
1174
+ out, err = capture.readouterr()
1175
+ capture.stop_capturing()
1176
+ sys.stdout.write(out)
1177
+ sys.stderr.write(err)
1178
+
1179
+ assert reprec.ret is not None
1180
+ res = RunResult(
1181
+ reprec.ret, out.splitlines(), err.splitlines(), timing.time() - now
1182
+ )
1183
+ res.reprec = reprec # type: ignore
1184
+ return res
1185
+
1186
+ def runpytest(self, *args: str | os.PathLike[str], **kwargs: Any) -> RunResult:
1187
+ """Run pytest inline or in a subprocess, depending on the command line
1188
+ option "--runpytest" and return a :py:class:`~pytest.RunResult`."""
1189
+ new_args = self._ensure_basetemp(args)
1190
+ if self._method == "inprocess":
1191
+ return self.runpytest_inprocess(*new_args, **kwargs)
1192
+ elif self._method == "subprocess":
1193
+ return self.runpytest_subprocess(*new_args, **kwargs)
1194
+ raise RuntimeError(f"Unrecognized runpytest option: {self._method}")
1195
+
1196
+ def _ensure_basetemp(
1197
+ self, args: Sequence[str | os.PathLike[str]]
1198
+ ) -> list[str | os.PathLike[str]]:
1199
+ new_args = list(args)
1200
+ for x in new_args:
1201
+ if str(x).startswith("--basetemp"):
1202
+ break
1203
+ else:
1204
+ new_args.append(
1205
+ "--basetemp={}".format(self.path.parent.joinpath("basetemp"))
1206
+ )
1207
+ return new_args
1208
+
1209
+ def parseconfig(self, *args: str | os.PathLike[str]) -> Config:
1210
+ """Return a new pytest :class:`pytest.Config` instance from given
1211
+ commandline args.
1212
+
1213
+ This invokes the pytest bootstrapping code in _pytest.config to create a
1214
+ new :py:class:`pytest.PytestPluginManager` and call the
1215
+ :hook:`pytest_cmdline_parse` hook to create a new :class:`pytest.Config`
1216
+ instance.
1217
+
1218
+ If :attr:`plugins` has been populated they should be plugin modules
1219
+ to be registered with the plugin manager.
1220
+ """
1221
+ import _pytest.config
1222
+
1223
+ new_args = self._ensure_basetemp(args)
1224
+ new_args = [str(x) for x in new_args]
1225
+
1226
+ config = _pytest.config._prepareconfig(new_args, self.plugins) # type: ignore[arg-type]
1227
+ # we don't know what the test will do with this half-setup config
1228
+ # object and thus we make sure it gets unconfigured properly in any
1229
+ # case (otherwise capturing could still be active, for example)
1230
+ self._request.addfinalizer(config._ensure_unconfigure)
1231
+ return config
1232
+
1233
+ def parseconfigure(self, *args: str | os.PathLike[str]) -> Config:
1234
+ """Return a new pytest configured Config instance.
1235
+
1236
+ Returns a new :py:class:`pytest.Config` instance like
1237
+ :py:meth:`parseconfig`, but also calls the :hook:`pytest_configure`
1238
+ hook.
1239
+ """
1240
+ config = self.parseconfig(*args)
1241
+ config._do_configure()
1242
+ return config
1243
+
1244
+ def getitem(
1245
+ self, source: str | os.PathLike[str], funcname: str = "test_func"
1246
+ ) -> Item:
1247
+ """Return the test item for a test function.
1248
+
1249
+ Writes the source to a python file and runs pytest's collection on
1250
+ the resulting module, returning the test item for the requested
1251
+ function name.
1252
+
1253
+ :param source:
1254
+ The module source.
1255
+ :param funcname:
1256
+ The name of the test function for which to return a test item.
1257
+ :returns:
1258
+ The test item.
1259
+ """
1260
+ items = self.getitems(source)
1261
+ for item in items:
1262
+ if item.name == funcname:
1263
+ return item
1264
+ assert 0, f"{funcname!r} item not found in module:\n{source}\nitems: {items}"
1265
+
1266
+ def getitems(self, source: str | os.PathLike[str]) -> list[Item]:
1267
+ """Return all test items collected from the module.
1268
+
1269
+ Writes the source to a Python file and runs pytest's collection on
1270
+ the resulting module, returning all test items contained within.
1271
+ """
1272
+ modcol = self.getmodulecol(source)
1273
+ return self.genitems([modcol])
1274
+
1275
+ def getmodulecol(
1276
+ self,
1277
+ source: str | os.PathLike[str],
1278
+ configargs=(),
1279
+ *,
1280
+ withinit: bool = False,
1281
+ ):
1282
+ """Return the module collection node for ``source``.
1283
+
1284
+ Writes ``source`` to a file using :py:meth:`makepyfile` and then
1285
+ runs the pytest collection on it, returning the collection node for the
1286
+ test module.
1287
+
1288
+ :param source:
1289
+ The source code of the module to collect.
1290
+
1291
+ :param configargs:
1292
+ Any extra arguments to pass to :py:meth:`parseconfigure`.
1293
+
1294
+ :param withinit:
1295
+ Whether to also write an ``__init__.py`` file to the same
1296
+ directory to ensure it is a package.
1297
+ """
1298
+ if isinstance(source, os.PathLike):
1299
+ path = self.path.joinpath(source)
1300
+ assert not withinit, "not supported for paths"
1301
+ else:
1302
+ kw = {self._name: str(source)}
1303
+ path = self.makepyfile(**kw)
1304
+ if withinit:
1305
+ self.makepyfile(__init__="#")
1306
+ self.config = config = self.parseconfigure(path, *configargs)
1307
+ return self.getnode(config, path)
1308
+
1309
+ def collect_by_name(self, modcol: Collector, name: str) -> Item | Collector | None:
1310
+ """Return the collection node for name from the module collection.
1311
+
1312
+ Searches a module collection node for a collection node matching the
1313
+ given name.
1314
+
1315
+ :param modcol: A module collection node; see :py:meth:`getmodulecol`.
1316
+ :param name: The name of the node to return.
1317
+ """
1318
+ if modcol not in self._mod_collections:
1319
+ self._mod_collections[modcol] = list(modcol.collect())
1320
+ for colitem in self._mod_collections[modcol]:
1321
+ if colitem.name == name:
1322
+ return colitem
1323
+ return None
1324
+
1325
+ def popen(
1326
+ self,
1327
+ cmdargs: Sequence[str | os.PathLike[str]],
1328
+ stdout: int | TextIO = subprocess.PIPE,
1329
+ stderr: int | TextIO = subprocess.PIPE,
1330
+ stdin: NotSetType | bytes | IO[Any] | int = CLOSE_STDIN,
1331
+ **kw,
1332
+ ):
1333
+ """Invoke :py:class:`subprocess.Popen`.
1334
+
1335
+ Calls :py:class:`subprocess.Popen` making sure the current working
1336
+ directory is in ``PYTHONPATH``.
1337
+
1338
+ You probably want to use :py:meth:`run` instead.
1339
+ """
1340
+ env = os.environ.copy()
1341
+ env["PYTHONPATH"] = os.pathsep.join(
1342
+ filter(None, [os.getcwd(), env.get("PYTHONPATH", "")])
1343
+ )
1344
+ kw["env"] = env
1345
+
1346
+ if stdin is self.CLOSE_STDIN:
1347
+ kw["stdin"] = subprocess.PIPE
1348
+ elif isinstance(stdin, bytes):
1349
+ kw["stdin"] = subprocess.PIPE
1350
+ else:
1351
+ kw["stdin"] = stdin
1352
+
1353
+ popen = subprocess.Popen(cmdargs, stdout=stdout, stderr=stderr, **kw)
1354
+ if stdin is self.CLOSE_STDIN:
1355
+ assert popen.stdin is not None
1356
+ popen.stdin.close()
1357
+ elif isinstance(stdin, bytes):
1358
+ assert popen.stdin is not None
1359
+ popen.stdin.write(stdin)
1360
+
1361
+ return popen
1362
+
1363
+ def run(
1364
+ self,
1365
+ *cmdargs: str | os.PathLike[str],
1366
+ timeout: float | None = None,
1367
+ stdin: NotSetType | bytes | IO[Any] | int = CLOSE_STDIN,
1368
+ ) -> RunResult:
1369
+ """Run a command with arguments.
1370
+
1371
+ Run a process using :py:class:`subprocess.Popen` saving the stdout and
1372
+ stderr.
1373
+
1374
+ :param cmdargs:
1375
+ The sequence of arguments to pass to :py:class:`subprocess.Popen`,
1376
+ with path-like objects being converted to :py:class:`str`
1377
+ automatically.
1378
+ :param timeout:
1379
+ The period in seconds after which to timeout and raise
1380
+ :py:class:`Pytester.TimeoutExpired`.
1381
+ :param stdin:
1382
+ Optional standard input.
1383
+
1384
+ - If it is ``CLOSE_STDIN`` (Default), then this method calls
1385
+ :py:class:`subprocess.Popen` with ``stdin=subprocess.PIPE``, and
1386
+ the standard input is closed immediately after the new command is
1387
+ started.
1388
+
1389
+ - If it is of type :py:class:`bytes`, these bytes are sent to the
1390
+ standard input of the command.
1391
+
1392
+ - Otherwise, it is passed through to :py:class:`subprocess.Popen`.
1393
+ For further information in this case, consult the document of the
1394
+ ``stdin`` parameter in :py:class:`subprocess.Popen`.
1395
+ :type stdin: _pytest.compat.NotSetType | bytes | IO[Any] | int
1396
+ :returns:
1397
+ The result.
1398
+
1399
+ """
1400
+ __tracebackhide__ = True
1401
+
1402
+ cmdargs = tuple(os.fspath(arg) for arg in cmdargs)
1403
+ p1 = self.path.joinpath("stdout")
1404
+ p2 = self.path.joinpath("stderr")
1405
+ print("running:", *cmdargs)
1406
+ print(" in:", Path.cwd())
1407
+
1408
+ with p1.open("w", encoding="utf8") as f1, p2.open("w", encoding="utf8") as f2:
1409
+ now = timing.time()
1410
+ popen = self.popen(
1411
+ cmdargs,
1412
+ stdin=stdin,
1413
+ stdout=f1,
1414
+ stderr=f2,
1415
+ close_fds=(sys.platform != "win32"),
1416
+ )
1417
+ if popen.stdin is not None:
1418
+ popen.stdin.close()
1419
+
1420
+ def handle_timeout() -> None:
1421
+ __tracebackhide__ = True
1422
+
1423
+ timeout_message = f"{timeout} second timeout expired running: {cmdargs}"
1424
+
1425
+ popen.kill()
1426
+ popen.wait()
1427
+ raise self.TimeoutExpired(timeout_message)
1428
+
1429
+ if timeout is None:
1430
+ ret = popen.wait()
1431
+ else:
1432
+ try:
1433
+ ret = popen.wait(timeout)
1434
+ except subprocess.TimeoutExpired:
1435
+ handle_timeout()
1436
+
1437
+ with p1.open(encoding="utf8") as f1, p2.open(encoding="utf8") as f2:
1438
+ out = f1.read().splitlines()
1439
+ err = f2.read().splitlines()
1440
+
1441
+ self._dump_lines(out, sys.stdout)
1442
+ self._dump_lines(err, sys.stderr)
1443
+
1444
+ with contextlib.suppress(ValueError):
1445
+ ret = ExitCode(ret)
1446
+ return RunResult(ret, out, err, timing.time() - now)
1447
+
1448
+ def _dump_lines(self, lines, fp):
1449
+ try:
1450
+ for line in lines:
1451
+ print(line, file=fp)
1452
+ except UnicodeEncodeError:
1453
+ print(f"couldn't print to {fp} because of encoding")
1454
+
1455
+ def _getpytestargs(self) -> tuple[str, ...]:
1456
+ return sys.executable, "-mpytest"
1457
+
1458
+ def runpython(self, script: os.PathLike[str]) -> RunResult:
1459
+ """Run a python script using sys.executable as interpreter."""
1460
+ return self.run(sys.executable, script)
1461
+
1462
+ def runpython_c(self, command: str) -> RunResult:
1463
+ """Run ``python -c "command"``."""
1464
+ return self.run(sys.executable, "-c", command)
1465
+
1466
+ def runpytest_subprocess(
1467
+ self, *args: str | os.PathLike[str], timeout: float | None = None
1468
+ ) -> RunResult:
1469
+ """Run pytest as a subprocess with given arguments.
1470
+
1471
+ Any plugins added to the :py:attr:`plugins` list will be added using the
1472
+ ``-p`` command line option. Additionally ``--basetemp`` is used to put
1473
+ any temporary files and directories in a numbered directory prefixed
1474
+ with "runpytest-" to not conflict with the normal numbered pytest
1475
+ location for temporary files and directories.
1476
+
1477
+ :param args:
1478
+ The sequence of arguments to pass to the pytest subprocess.
1479
+ :param timeout:
1480
+ The period in seconds after which to timeout and raise
1481
+ :py:class:`Pytester.TimeoutExpired`.
1482
+ :returns:
1483
+ The result.
1484
+ """
1485
+ __tracebackhide__ = True
1486
+ p = make_numbered_dir(root=self.path, prefix="runpytest-", mode=0o700)
1487
+ args = (f"--basetemp={p}", *args)
1488
+ plugins = [x for x in self.plugins if isinstance(x, str)]
1489
+ if plugins:
1490
+ args = ("-p", plugins[0], *args)
1491
+ args = self._getpytestargs() + args
1492
+ return self.run(*args, timeout=timeout)
1493
+
1494
+ def spawn_pytest(self, string: str, expect_timeout: float = 10.0) -> pexpect.spawn:
1495
+ """Run pytest using pexpect.
1496
+
1497
+ This makes sure to use the right pytest and sets up the temporary
1498
+ directory locations.
1499
+
1500
+ The pexpect child is returned.
1501
+ """
1502
+ basetemp = self.path / "temp-pexpect"
1503
+ basetemp.mkdir(mode=0o700)
1504
+ invoke = " ".join(map(str, self._getpytestargs()))
1505
+ cmd = f"{invoke} --basetemp={basetemp} {string}"
1506
+ return self.spawn(cmd, expect_timeout=expect_timeout)
1507
+
1508
+ def spawn(self, cmd: str, expect_timeout: float = 10.0) -> pexpect.spawn:
1509
+ """Run a command using pexpect.
1510
+
1511
+ The pexpect child is returned.
1512
+ """
1513
+ pexpect = importorskip("pexpect", "3.0")
1514
+ if hasattr(sys, "pypy_version_info") and "64" in platform.machine():
1515
+ skip("pypy-64 bit not supported")
1516
+ if not hasattr(pexpect, "spawn"):
1517
+ skip("pexpect.spawn not available")
1518
+ logfile = self.path.joinpath("spawn.out").open("wb")
1519
+
1520
+ child = pexpect.spawn(cmd, logfile=logfile, timeout=expect_timeout)
1521
+ self._request.addfinalizer(logfile.close)
1522
+ return child
1523
+
1524
+
1525
+ class LineComp:
1526
+ def __init__(self) -> None:
1527
+ self.stringio = StringIO()
1528
+ """:class:`python:io.StringIO()` instance used for input."""
1529
+
1530
+ def assert_contains_lines(self, lines2: Sequence[str]) -> None:
1531
+ """Assert that ``lines2`` are contained (linearly) in :attr:`stringio`'s value.
1532
+
1533
+ Lines are matched using :func:`LineMatcher.fnmatch_lines <pytest.LineMatcher.fnmatch_lines>`.
1534
+ """
1535
+ __tracebackhide__ = True
1536
+ val = self.stringio.getvalue()
1537
+ self.stringio.truncate(0)
1538
+ self.stringio.seek(0)
1539
+ lines1 = val.split("\n")
1540
+ LineMatcher(lines1).fnmatch_lines(lines2)
1541
+
1542
+
1543
+ class LineMatcher:
1544
+ """Flexible matching of text.
1545
+
1546
+ This is a convenience class to test large texts like the output of
1547
+ commands.
1548
+
1549
+ The constructor takes a list of lines without their trailing newlines, i.e.
1550
+ ``text.splitlines()``.
1551
+ """
1552
+
1553
+ def __init__(self, lines: list[str]) -> None:
1554
+ self.lines = lines
1555
+ self._log_output: list[str] = []
1556
+
1557
+ def __str__(self) -> str:
1558
+ """Return the entire original text.
1559
+
1560
+ .. versionadded:: 6.2
1561
+ You can use :meth:`str` in older versions.
1562
+ """
1563
+ return "\n".join(self.lines)
1564
+
1565
+ def _getlines(self, lines2: str | Sequence[str] | Source) -> Sequence[str]:
1566
+ if isinstance(lines2, str):
1567
+ lines2 = Source(lines2)
1568
+ if isinstance(lines2, Source):
1569
+ lines2 = lines2.strip().lines
1570
+ return lines2
1571
+
1572
+ def fnmatch_lines_random(self, lines2: Sequence[str]) -> None:
1573
+ """Check lines exist in the output in any order (using :func:`python:fnmatch.fnmatch`)."""
1574
+ __tracebackhide__ = True
1575
+ self._match_lines_random(lines2, fnmatch)
1576
+
1577
+ def re_match_lines_random(self, lines2: Sequence[str]) -> None:
1578
+ """Check lines exist in the output in any order (using :func:`python:re.match`)."""
1579
+ __tracebackhide__ = True
1580
+ self._match_lines_random(lines2, lambda name, pat: bool(re.match(pat, name)))
1581
+
1582
+ def _match_lines_random(
1583
+ self, lines2: Sequence[str], match_func: Callable[[str, str], bool]
1584
+ ) -> None:
1585
+ __tracebackhide__ = True
1586
+ lines2 = self._getlines(lines2)
1587
+ for line in lines2:
1588
+ for x in self.lines:
1589
+ if line == x or match_func(x, line):
1590
+ self._log("matched: ", repr(line))
1591
+ break
1592
+ else:
1593
+ msg = f"line {line!r} not found in output"
1594
+ self._log(msg)
1595
+ self._fail(msg)
1596
+
1597
+ def get_lines_after(self, fnline: str) -> Sequence[str]:
1598
+ """Return all lines following the given line in the text.
1599
+
1600
+ The given line can contain glob wildcards.
1601
+ """
1602
+ for i, line in enumerate(self.lines):
1603
+ if fnline == line or fnmatch(line, fnline):
1604
+ return self.lines[i + 1 :]
1605
+ raise ValueError(f"line {fnline!r} not found in output")
1606
+
1607
+ def _log(self, *args) -> None:
1608
+ self._log_output.append(" ".join(str(x) for x in args))
1609
+
1610
+ @property
1611
+ def _log_text(self) -> str:
1612
+ return "\n".join(self._log_output)
1613
+
1614
+ def fnmatch_lines(
1615
+ self, lines2: Sequence[str], *, consecutive: bool = False
1616
+ ) -> None:
1617
+ """Check lines exist in the output (using :func:`python:fnmatch.fnmatch`).
1618
+
1619
+ The argument is a list of lines which have to match and can use glob
1620
+ wildcards. If they do not match a pytest.fail() is called. The
1621
+ matches and non-matches are also shown as part of the error message.
1622
+
1623
+ :param lines2: String patterns to match.
1624
+ :param consecutive: Match lines consecutively?
1625
+ """
1626
+ __tracebackhide__ = True
1627
+ self._match_lines(lines2, fnmatch, "fnmatch", consecutive=consecutive)
1628
+
1629
+ def re_match_lines(
1630
+ self, lines2: Sequence[str], *, consecutive: bool = False
1631
+ ) -> None:
1632
+ """Check lines exist in the output (using :func:`python:re.match`).
1633
+
1634
+ The argument is a list of lines which have to match using ``re.match``.
1635
+ If they do not match a pytest.fail() is called.
1636
+
1637
+ The matches and non-matches are also shown as part of the error message.
1638
+
1639
+ :param lines2: string patterns to match.
1640
+ :param consecutive: match lines consecutively?
1641
+ """
1642
+ __tracebackhide__ = True
1643
+ self._match_lines(
1644
+ lines2,
1645
+ lambda name, pat: bool(re.match(pat, name)),
1646
+ "re.match",
1647
+ consecutive=consecutive,
1648
+ )
1649
+
1650
+ def _match_lines(
1651
+ self,
1652
+ lines2: Sequence[str],
1653
+ match_func: Callable[[str, str], bool],
1654
+ match_nickname: str,
1655
+ *,
1656
+ consecutive: bool = False,
1657
+ ) -> None:
1658
+ """Underlying implementation of ``fnmatch_lines`` and ``re_match_lines``.
1659
+
1660
+ :param Sequence[str] lines2:
1661
+ List of string patterns to match. The actual format depends on
1662
+ ``match_func``.
1663
+ :param match_func:
1664
+ A callable ``match_func(line, pattern)`` where line is the
1665
+ captured line from stdout/stderr and pattern is the matching
1666
+ pattern.
1667
+ :param str match_nickname:
1668
+ The nickname for the match function that will be logged to stdout
1669
+ when a match occurs.
1670
+ :param consecutive:
1671
+ Match lines consecutively?
1672
+ """
1673
+ if not isinstance(lines2, collections.abc.Sequence):
1674
+ raise TypeError(f"invalid type for lines2: {type(lines2).__name__}")
1675
+ lines2 = self._getlines(lines2)
1676
+ lines1 = self.lines[:]
1677
+ extralines = []
1678
+ __tracebackhide__ = True
1679
+ wnick = len(match_nickname) + 1
1680
+ started = False
1681
+ for line in lines2:
1682
+ nomatchprinted = False
1683
+ while lines1:
1684
+ nextline = lines1.pop(0)
1685
+ if line == nextline:
1686
+ self._log("exact match:", repr(line))
1687
+ started = True
1688
+ break
1689
+ elif match_func(nextline, line):
1690
+ self._log(f"{match_nickname}:", repr(line))
1691
+ self._log(
1692
+ "{:>{width}}".format("with:", width=wnick), repr(nextline)
1693
+ )
1694
+ started = True
1695
+ break
1696
+ else:
1697
+ if consecutive and started:
1698
+ msg = f"no consecutive match: {line!r}"
1699
+ self._log(msg)
1700
+ self._log(
1701
+ "{:>{width}}".format("with:", width=wnick), repr(nextline)
1702
+ )
1703
+ self._fail(msg)
1704
+ if not nomatchprinted:
1705
+ self._log(
1706
+ "{:>{width}}".format("nomatch:", width=wnick), repr(line)
1707
+ )
1708
+ nomatchprinted = True
1709
+ self._log("{:>{width}}".format("and:", width=wnick), repr(nextline))
1710
+ extralines.append(nextline)
1711
+ else:
1712
+ msg = f"remains unmatched: {line!r}"
1713
+ self._log(msg)
1714
+ self._fail(msg)
1715
+ self._log_output = []
1716
+
1717
+ def no_fnmatch_line(self, pat: str) -> None:
1718
+ """Ensure captured lines do not match the given pattern, using ``fnmatch.fnmatch``.
1719
+
1720
+ :param str pat: The pattern to match lines.
1721
+ """
1722
+ __tracebackhide__ = True
1723
+ self._no_match_line(pat, fnmatch, "fnmatch")
1724
+
1725
+ def no_re_match_line(self, pat: str) -> None:
1726
+ """Ensure captured lines do not match the given pattern, using ``re.match``.
1727
+
1728
+ :param str pat: The regular expression to match lines.
1729
+ """
1730
+ __tracebackhide__ = True
1731
+ self._no_match_line(
1732
+ pat, lambda name, pat: bool(re.match(pat, name)), "re.match"
1733
+ )
1734
+
1735
+ def _no_match_line(
1736
+ self, pat: str, match_func: Callable[[str, str], bool], match_nickname: str
1737
+ ) -> None:
1738
+ """Ensure captured lines does not have a the given pattern, using ``fnmatch.fnmatch``.
1739
+
1740
+ :param str pat: The pattern to match lines.
1741
+ """
1742
+ __tracebackhide__ = True
1743
+ nomatch_printed = False
1744
+ wnick = len(match_nickname) + 1
1745
+ for line in self.lines:
1746
+ if match_func(line, pat):
1747
+ msg = f"{match_nickname}: {pat!r}"
1748
+ self._log(msg)
1749
+ self._log("{:>{width}}".format("with:", width=wnick), repr(line))
1750
+ self._fail(msg)
1751
+ else:
1752
+ if not nomatch_printed:
1753
+ self._log("{:>{width}}".format("nomatch:", width=wnick), repr(pat))
1754
+ nomatch_printed = True
1755
+ self._log("{:>{width}}".format("and:", width=wnick), repr(line))
1756
+ self._log_output = []
1757
+
1758
+ def _fail(self, msg: str) -> None:
1759
+ __tracebackhide__ = True
1760
+ log_text = self._log_text
1761
+ self._log_output = []
1762
+ fail(log_text)
1763
+
1764
+ def str(self) -> str:
1765
+ """Return the entire original text."""
1766
+ return str(self)
vllm/lib/python3.10/site-packages/_pytest/pytester_assertions.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helper plugin for pytester; should not be loaded on its own."""
2
+
3
+ # This plugin contains assertions used by pytester. pytester cannot
4
+ # contain them itself, since it is imported by the `pytest` module,
5
+ # hence cannot be subject to assertion rewriting, which requires a
6
+ # module to not be already imported.
7
+ from __future__ import annotations
8
+
9
+ from typing import Sequence
10
+
11
+ from _pytest.reports import CollectReport
12
+ from _pytest.reports import TestReport
13
+
14
+
15
+ def assertoutcome(
16
+ outcomes: tuple[
17
+ Sequence[TestReport],
18
+ Sequence[CollectReport | TestReport],
19
+ Sequence[CollectReport | TestReport],
20
+ ],
21
+ passed: int = 0,
22
+ skipped: int = 0,
23
+ failed: int = 0,
24
+ ) -> None:
25
+ __tracebackhide__ = True
26
+
27
+ realpassed, realskipped, realfailed = outcomes
28
+ obtained = {
29
+ "passed": len(realpassed),
30
+ "skipped": len(realskipped),
31
+ "failed": len(realfailed),
32
+ }
33
+ expected = {"passed": passed, "skipped": skipped, "failed": failed}
34
+ assert obtained == expected, outcomes
35
+
36
+
37
+ def assert_outcomes(
38
+ outcomes: dict[str, int],
39
+ passed: int = 0,
40
+ skipped: int = 0,
41
+ failed: int = 0,
42
+ errors: int = 0,
43
+ xpassed: int = 0,
44
+ xfailed: int = 0,
45
+ warnings: int | None = None,
46
+ deselected: int | None = None,
47
+ ) -> None:
48
+ """Assert that the specified outcomes appear with the respective
49
+ numbers (0 means it didn't occur) in the text output from a test run."""
50
+ __tracebackhide__ = True
51
+
52
+ obtained = {
53
+ "passed": outcomes.get("passed", 0),
54
+ "skipped": outcomes.get("skipped", 0),
55
+ "failed": outcomes.get("failed", 0),
56
+ "errors": outcomes.get("errors", 0),
57
+ "xpassed": outcomes.get("xpassed", 0),
58
+ "xfailed": outcomes.get("xfailed", 0),
59
+ }
60
+ expected = {
61
+ "passed": passed,
62
+ "skipped": skipped,
63
+ "failed": failed,
64
+ "errors": errors,
65
+ "xpassed": xpassed,
66
+ "xfailed": xfailed,
67
+ }
68
+ if warnings is not None:
69
+ obtained["warnings"] = outcomes.get("warnings", 0)
70
+ expected["warnings"] = warnings
71
+ if deselected is not None:
72
+ obtained["deselected"] = outcomes.get("deselected", 0)
73
+ expected["deselected"] = deselected
74
+ assert obtained == expected
vllm/lib/python3.10/site-packages/_pytest/python.py ADDED
@@ -0,0 +1,1679 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """Python test discovery, setup and run of test functions."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import abc
7
+ from collections import Counter
8
+ from collections import defaultdict
9
+ import dataclasses
10
+ import enum
11
+ import fnmatch
12
+ from functools import partial
13
+ import inspect
14
+ import itertools
15
+ import os
16
+ from pathlib import Path
17
+ import types
18
+ from typing import Any
19
+ from typing import Callable
20
+ from typing import Dict
21
+ from typing import final
22
+ from typing import Generator
23
+ from typing import Iterable
24
+ from typing import Iterator
25
+ from typing import Literal
26
+ from typing import Mapping
27
+ from typing import Pattern
28
+ from typing import Sequence
29
+ from typing import TYPE_CHECKING
30
+ import warnings
31
+
32
+ import _pytest
33
+ from _pytest import fixtures
34
+ from _pytest import nodes
35
+ from _pytest._code import filter_traceback
36
+ from _pytest._code import getfslineno
37
+ from _pytest._code.code import ExceptionInfo
38
+ from _pytest._code.code import TerminalRepr
39
+ from _pytest._code.code import Traceback
40
+ from _pytest._io.saferepr import saferepr
41
+ from _pytest.compat import ascii_escaped
42
+ from _pytest.compat import get_default_arg_names
43
+ from _pytest.compat import get_real_func
44
+ from _pytest.compat import getimfunc
45
+ from _pytest.compat import is_async_function
46
+ from _pytest.compat import is_generator
47
+ from _pytest.compat import LEGACY_PATH
48
+ from _pytest.compat import NOTSET
49
+ from _pytest.compat import safe_getattr
50
+ from _pytest.compat import safe_isclass
51
+ from _pytest.config import Config
52
+ from _pytest.config import hookimpl
53
+ from _pytest.config.argparsing import Parser
54
+ from _pytest.deprecated import check_ispytest
55
+ from _pytest.fixtures import FixtureDef
56
+ from _pytest.fixtures import FixtureRequest
57
+ from _pytest.fixtures import FuncFixtureInfo
58
+ from _pytest.fixtures import get_scope_node
59
+ from _pytest.main import Session
60
+ from _pytest.mark import MARK_GEN
61
+ from _pytest.mark import ParameterSet
62
+ from _pytest.mark.structures import get_unpacked_marks
63
+ from _pytest.mark.structures import Mark
64
+ from _pytest.mark.structures import MarkDecorator
65
+ from _pytest.mark.structures import normalize_mark_list
66
+ from _pytest.outcomes import fail
67
+ from _pytest.outcomes import skip
68
+ from _pytest.pathlib import fnmatch_ex
69
+ from _pytest.pathlib import import_path
70
+ from _pytest.pathlib import ImportPathMismatchError
71
+ from _pytest.pathlib import scandir
72
+ from _pytest.scope import _ScopeName
73
+ from _pytest.scope import Scope
74
+ from _pytest.stash import StashKey
75
+ from _pytest.warning_types import PytestCollectionWarning
76
+ from _pytest.warning_types import PytestReturnNotNoneWarning
77
+ from _pytest.warning_types import PytestUnhandledCoroutineWarning
78
+
79
+
80
+ if TYPE_CHECKING:
81
+ from typing_extensions import Self
82
+
83
+
84
+ def pytest_addoption(parser: Parser) -> None:
85
+ parser.addini(
86
+ "python_files",
87
+ type="args",
88
+ # NOTE: default is also used in AssertionRewritingHook.
89
+ default=["test_*.py", "*_test.py"],
90
+ help="Glob-style file patterns for Python test module discovery",
91
+ )
92
+ parser.addini(
93
+ "python_classes",
94
+ type="args",
95
+ default=["Test"],
96
+ help="Prefixes or glob names for Python test class discovery",
97
+ )
98
+ parser.addini(
99
+ "python_functions",
100
+ type="args",
101
+ default=["test"],
102
+ help="Prefixes or glob names for Python test function and method discovery",
103
+ )
104
+ parser.addini(
105
+ "disable_test_id_escaping_and_forfeit_all_rights_to_community_support",
106
+ type="bool",
107
+ default=False,
108
+ help="Disable string escape non-ASCII characters, might cause unwanted "
109
+ "side effects(use at your own risk)",
110
+ )
111
+
112
+
113
+ def pytest_generate_tests(metafunc: Metafunc) -> None:
114
+ for marker in metafunc.definition.iter_markers(name="parametrize"):
115
+ metafunc.parametrize(*marker.args, **marker.kwargs, _param_mark=marker)
116
+
117
+
118
+ def pytest_configure(config: Config) -> None:
119
+ config.addinivalue_line(
120
+ "markers",
121
+ "parametrize(argnames, argvalues): call a test function multiple "
122
+ "times passing in different arguments in turn. argvalues generally "
123
+ "needs to be a list of values if argnames specifies only one name "
124
+ "or a list of tuples of values if argnames specifies multiple names. "
125
+ "Example: @parametrize('arg1', [1,2]) would lead to two calls of the "
126
+ "decorated test function, one with arg1=1 and another with arg1=2."
127
+ "see https://docs.pytest.org/en/stable/how-to/parametrize.html for more info "
128
+ "and examples.",
129
+ )
130
+ config.addinivalue_line(
131
+ "markers",
132
+ "usefixtures(fixturename1, fixturename2, ...): mark tests as needing "
133
+ "all of the specified fixtures. see "
134
+ "https://docs.pytest.org/en/stable/explanation/fixtures.html#usefixtures ",
135
+ )
136
+
137
+
138
+ def async_warn_and_skip(nodeid: str) -> None:
139
+ msg = "async def functions are not natively supported and have been skipped.\n"
140
+ msg += (
141
+ "You need to install a suitable plugin for your async framework, for example:\n"
142
+ )
143
+ msg += " - anyio\n"
144
+ msg += " - pytest-asyncio\n"
145
+ msg += " - pytest-tornasync\n"
146
+ msg += " - pytest-trio\n"
147
+ msg += " - pytest-twisted"
148
+ warnings.warn(PytestUnhandledCoroutineWarning(msg.format(nodeid)))
149
+ skip(reason="async def function and no async plugin installed (see warnings)")
150
+
151
+
152
+ @hookimpl(trylast=True)
153
+ def pytest_pyfunc_call(pyfuncitem: Function) -> object | None:
154
+ testfunction = pyfuncitem.obj
155
+ if is_async_function(testfunction):
156
+ async_warn_and_skip(pyfuncitem.nodeid)
157
+ funcargs = pyfuncitem.funcargs
158
+ testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames}
159
+ result = testfunction(**testargs)
160
+ if hasattr(result, "__await__") or hasattr(result, "__aiter__"):
161
+ async_warn_and_skip(pyfuncitem.nodeid)
162
+ elif result is not None:
163
+ warnings.warn(
164
+ PytestReturnNotNoneWarning(
165
+ f"Expected None, but {pyfuncitem.nodeid} returned {result!r}, which will be an error in a "
166
+ "future version of pytest. Did you mean to use `assert` instead of `return`?"
167
+ )
168
+ )
169
+ return True
170
+
171
+
172
+ def pytest_collect_directory(
173
+ path: Path, parent: nodes.Collector
174
+ ) -> nodes.Collector | None:
175
+ pkginit = path / "__init__.py"
176
+ try:
177
+ has_pkginit = pkginit.is_file()
178
+ except PermissionError:
179
+ # See https://github.com/pytest-dev/pytest/issues/12120#issuecomment-2106349096.
180
+ return None
181
+ if has_pkginit:
182
+ return Package.from_parent(parent, path=path)
183
+ return None
184
+
185
+
186
+ def pytest_collect_file(file_path: Path, parent: nodes.Collector) -> Module | None:
187
+ if file_path.suffix == ".py":
188
+ if not parent.session.isinitpath(file_path):
189
+ if not path_matches_patterns(
190
+ file_path, parent.config.getini("python_files")
191
+ ):
192
+ return None
193
+ ihook = parent.session.gethookproxy(file_path)
194
+ module: Module = ihook.pytest_pycollect_makemodule(
195
+ module_path=file_path, parent=parent
196
+ )
197
+ return module
198
+ return None
199
+
200
+
201
+ def path_matches_patterns(path: Path, patterns: Iterable[str]) -> bool:
202
+ """Return whether path matches any of the patterns in the list of globs given."""
203
+ return any(fnmatch_ex(pattern, path) for pattern in patterns)
204
+
205
+
206
+ def pytest_pycollect_makemodule(module_path: Path, parent) -> Module:
207
+ return Module.from_parent(parent, path=module_path)
208
+
209
+
210
+ @hookimpl(trylast=True)
211
+ def pytest_pycollect_makeitem(
212
+ collector: Module | Class, name: str, obj: object
213
+ ) -> None | nodes.Item | nodes.Collector | list[nodes.Item | nodes.Collector]:
214
+ assert isinstance(collector, (Class, Module)), type(collector)
215
+ # Nothing was collected elsewhere, let's do it here.
216
+ if safe_isclass(obj):
217
+ if collector.istestclass(obj, name):
218
+ return Class.from_parent(collector, name=name, obj=obj)
219
+ elif collector.istestfunction(obj, name):
220
+ # mock seems to store unbound methods (issue473), normalize it.
221
+ obj = getattr(obj, "__func__", obj)
222
+ # We need to try and unwrap the function if it's a functools.partial
223
+ # or a functools.wrapped.
224
+ # We mustn't if it's been wrapped with mock.patch (python 2 only).
225
+ if not (inspect.isfunction(obj) or inspect.isfunction(get_real_func(obj))):
226
+ filename, lineno = getfslineno(obj)
227
+ warnings.warn_explicit(
228
+ message=PytestCollectionWarning(
229
+ f"cannot collect {name!r} because it is not a function."
230
+ ),
231
+ category=None,
232
+ filename=str(filename),
233
+ lineno=lineno + 1,
234
+ )
235
+ elif getattr(obj, "__test__", True):
236
+ if is_generator(obj):
237
+ res = Function.from_parent(collector, name=name)
238
+ reason = (
239
+ f"yield tests were removed in pytest 4.0 - {name} will be ignored"
240
+ )
241
+ res.add_marker(MARK_GEN.xfail(run=False, reason=reason))
242
+ res.warn(PytestCollectionWarning(reason))
243
+ return res
244
+ else:
245
+ return list(collector._genfunctions(name, obj))
246
+ return None
247
+
248
+
249
+ class PyobjMixin(nodes.Node):
250
+ """this mix-in inherits from Node to carry over the typing information
251
+
252
+ as its intended to always mix in before a node
253
+ its position in the mro is unaffected"""
254
+
255
+ _ALLOW_MARKERS = True
256
+
257
+ @property
258
+ def module(self):
259
+ """Python module object this node was collected from (can be None)."""
260
+ node = self.getparent(Module)
261
+ return node.obj if node is not None else None
262
+
263
+ @property
264
+ def cls(self):
265
+ """Python class object this node was collected from (can be None)."""
266
+ node = self.getparent(Class)
267
+ return node.obj if node is not None else None
268
+
269
+ @property
270
+ def instance(self):
271
+ """Python instance object the function is bound to.
272
+
273
+ Returns None if not a test method, e.g. for a standalone test function,
274
+ a class or a module.
275
+ """
276
+ # Overridden by Function.
277
+ return None
278
+
279
+ @property
280
+ def obj(self):
281
+ """Underlying Python object."""
282
+ obj = getattr(self, "_obj", None)
283
+ if obj is None:
284
+ self._obj = obj = self._getobj()
285
+ # XXX evil hack
286
+ # used to avoid Function marker duplication
287
+ if self._ALLOW_MARKERS:
288
+ self.own_markers.extend(get_unpacked_marks(self.obj))
289
+ # This assumes that `obj` is called before there is a chance
290
+ # to add custom keys to `self.keywords`, so no fear of overriding.
291
+ self.keywords.update((mark.name, mark) for mark in self.own_markers)
292
+ return obj
293
+
294
+ @obj.setter
295
+ def obj(self, value):
296
+ self._obj = value
297
+
298
+ def _getobj(self):
299
+ """Get the underlying Python object. May be overwritten by subclasses."""
300
+ # TODO: Improve the type of `parent` such that assert/ignore aren't needed.
301
+ assert self.parent is not None
302
+ obj = self.parent.obj # type: ignore[attr-defined]
303
+ return getattr(obj, self.name)
304
+
305
+ def getmodpath(self, stopatmodule: bool = True, includemodule: bool = False) -> str:
306
+ """Return Python path relative to the containing module."""
307
+ parts = []
308
+ for node in self.iter_parents():
309
+ name = node.name
310
+ if isinstance(node, Module):
311
+ name = os.path.splitext(name)[0]
312
+ if stopatmodule:
313
+ if includemodule:
314
+ parts.append(name)
315
+ break
316
+ parts.append(name)
317
+ parts.reverse()
318
+ return ".".join(parts)
319
+
320
+ def reportinfo(self) -> tuple[os.PathLike[str] | str, int | None, str]:
321
+ # XXX caching?
322
+ path, lineno = getfslineno(self.obj)
323
+ modpath = self.getmodpath()
324
+ return path, lineno, modpath
325
+
326
+
327
+ # As an optimization, these builtin attribute names are pre-ignored when
328
+ # iterating over an object during collection -- the pytest_pycollect_makeitem
329
+ # hook is not called for them.
330
+ # fmt: off
331
+ class _EmptyClass: pass # noqa: E701
332
+ IGNORED_ATTRIBUTES = frozenset.union(
333
+ frozenset(),
334
+ # Module.
335
+ dir(types.ModuleType("empty_module")),
336
+ # Some extra module attributes the above doesn't catch.
337
+ {"__builtins__", "__file__", "__cached__"},
338
+ # Class.
339
+ dir(_EmptyClass),
340
+ # Instance.
341
+ dir(_EmptyClass()),
342
+ )
343
+ del _EmptyClass
344
+ # fmt: on
345
+
346
+
347
+ class PyCollector(PyobjMixin, nodes.Collector, abc.ABC):
348
+ def funcnamefilter(self, name: str) -> bool:
349
+ return self._matches_prefix_or_glob_option("python_functions", name)
350
+
351
+ def isnosetest(self, obj: object) -> bool:
352
+ """Look for the __test__ attribute, which is applied by the
353
+ @nose.tools.istest decorator.
354
+ """
355
+ # We explicitly check for "is True" here to not mistakenly treat
356
+ # classes with a custom __getattr__ returning something truthy (like a
357
+ # function) as test classes.
358
+ return safe_getattr(obj, "__test__", False) is True
359
+
360
+ def classnamefilter(self, name: str) -> bool:
361
+ return self._matches_prefix_or_glob_option("python_classes", name)
362
+
363
+ def istestfunction(self, obj: object, name: str) -> bool:
364
+ if self.funcnamefilter(name) or self.isnosetest(obj):
365
+ if isinstance(obj, (staticmethod, classmethod)):
366
+ # staticmethods and classmethods need to be unwrapped.
367
+ obj = safe_getattr(obj, "__func__", False)
368
+ return callable(obj) and fixtures.getfixturemarker(obj) is None
369
+ else:
370
+ return False
371
+
372
+ def istestclass(self, obj: object, name: str) -> bool:
373
+ if not (self.classnamefilter(name) or self.isnosetest(obj)):
374
+ return False
375
+ if inspect.isabstract(obj):
376
+ return False
377
+ return True
378
+
379
+ def _matches_prefix_or_glob_option(self, option_name: str, name: str) -> bool:
380
+ """Check if the given name matches the prefix or glob-pattern defined
381
+ in ini configuration."""
382
+ for option in self.config.getini(option_name):
383
+ if name.startswith(option):
384
+ return True
385
+ # Check that name looks like a glob-string before calling fnmatch
386
+ # because this is called for every name in each collected module,
387
+ # and fnmatch is somewhat expensive to call.
388
+ elif ("*" in option or "?" in option or "[" in option) and fnmatch.fnmatch(
389
+ name, option
390
+ ):
391
+ return True
392
+ return False
393
+
394
+ def collect(self) -> Iterable[nodes.Item | nodes.Collector]:
395
+ if not getattr(self.obj, "__test__", True):
396
+ return []
397
+
398
+ # Avoid random getattrs and peek in the __dict__ instead.
399
+ dicts = [getattr(self.obj, "__dict__", {})]
400
+ if isinstance(self.obj, type):
401
+ for basecls in self.obj.__mro__:
402
+ dicts.append(basecls.__dict__)
403
+
404
+ # In each class, nodes should be definition ordered.
405
+ # __dict__ is definition ordered.
406
+ seen: set[str] = set()
407
+ dict_values: list[list[nodes.Item | nodes.Collector]] = []
408
+ ihook = self.ihook
409
+ for dic in dicts:
410
+ values: list[nodes.Item | nodes.Collector] = []
411
+ # Note: seems like the dict can change during iteration -
412
+ # be careful not to remove the list() without consideration.
413
+ for name, obj in list(dic.items()):
414
+ if name in IGNORED_ATTRIBUTES:
415
+ continue
416
+ if name in seen:
417
+ continue
418
+ seen.add(name)
419
+ res = ihook.pytest_pycollect_makeitem(
420
+ collector=self, name=name, obj=obj
421
+ )
422
+ if res is None:
423
+ continue
424
+ elif isinstance(res, list):
425
+ values.extend(res)
426
+ else:
427
+ values.append(res)
428
+ dict_values.append(values)
429
+
430
+ # Between classes in the class hierarchy, reverse-MRO order -- nodes
431
+ # inherited from base classes should come before subclasses.
432
+ result = []
433
+ for values in reversed(dict_values):
434
+ result.extend(values)
435
+ return result
436
+
437
+ def _genfunctions(self, name: str, funcobj) -> Iterator[Function]:
438
+ modulecol = self.getparent(Module)
439
+ assert modulecol is not None
440
+ module = modulecol.obj
441
+ clscol = self.getparent(Class)
442
+ cls = clscol and clscol.obj or None
443
+
444
+ definition = FunctionDefinition.from_parent(self, name=name, callobj=funcobj)
445
+ fixtureinfo = definition._fixtureinfo
446
+
447
+ # pytest_generate_tests impls call metafunc.parametrize() which fills
448
+ # metafunc._calls, the outcome of the hook.
449
+ metafunc = Metafunc(
450
+ definition=definition,
451
+ fixtureinfo=fixtureinfo,
452
+ config=self.config,
453
+ cls=cls,
454
+ module=module,
455
+ _ispytest=True,
456
+ )
457
+ methods = []
458
+ if hasattr(module, "pytest_generate_tests"):
459
+ methods.append(module.pytest_generate_tests)
460
+ if cls is not None and hasattr(cls, "pytest_generate_tests"):
461
+ methods.append(cls().pytest_generate_tests)
462
+ self.ihook.pytest_generate_tests.call_extra(methods, dict(metafunc=metafunc))
463
+
464
+ if not metafunc._calls:
465
+ yield Function.from_parent(self, name=name, fixtureinfo=fixtureinfo)
466
+ else:
467
+ # Direct parametrizations taking place in module/class-specific
468
+ # `metafunc.parametrize` calls may have shadowed some fixtures, so make sure
469
+ # we update what the function really needs a.k.a its fixture closure. Note that
470
+ # direct parametrizations using `@pytest.mark.parametrize` have already been considered
471
+ # into making the closure using `ignore_args` arg to `getfixtureclosure`.
472
+ fixtureinfo.prune_dependency_tree()
473
+
474
+ for callspec in metafunc._calls:
475
+ subname = f"{name}[{callspec.id}]"
476
+ yield Function.from_parent(
477
+ self,
478
+ name=subname,
479
+ callspec=callspec,
480
+ fixtureinfo=fixtureinfo,
481
+ keywords={callspec.id: True},
482
+ originalname=name,
483
+ )
484
+
485
+
486
+ def importtestmodule(
487
+ path: Path,
488
+ config: Config,
489
+ ):
490
+ # We assume we are only called once per module.
491
+ importmode = config.getoption("--import-mode")
492
+ try:
493
+ mod = import_path(
494
+ path,
495
+ mode=importmode,
496
+ root=config.rootpath,
497
+ consider_namespace_packages=config.getini("consider_namespace_packages"),
498
+ )
499
+ except SyntaxError as e:
500
+ raise nodes.Collector.CollectError(
501
+ ExceptionInfo.from_current().getrepr(style="short")
502
+ ) from e
503
+ except ImportPathMismatchError as e:
504
+ raise nodes.Collector.CollectError(
505
+ "import file mismatch:\n"
506
+ "imported module {!r} has this __file__ attribute:\n"
507
+ " {}\n"
508
+ "which is not the same as the test file we want to collect:\n"
509
+ " {}\n"
510
+ "HINT: remove __pycache__ / .pyc files and/or use a "
511
+ "unique basename for your test file modules".format(*e.args)
512
+ ) from e
513
+ except ImportError as e:
514
+ exc_info = ExceptionInfo.from_current()
515
+ if config.get_verbosity() < 2:
516
+ exc_info.traceback = exc_info.traceback.filter(filter_traceback)
517
+ exc_repr = (
518
+ exc_info.getrepr(style="short")
519
+ if exc_info.traceback
520
+ else exc_info.exconly()
521
+ )
522
+ formatted_tb = str(exc_repr)
523
+ raise nodes.Collector.CollectError(
524
+ f"ImportError while importing test module '{path}'.\n"
525
+ "Hint: make sure your test modules/packages have valid Python names.\n"
526
+ "Traceback:\n"
527
+ f"{formatted_tb}"
528
+ ) from e
529
+ except skip.Exception as e:
530
+ if e.allow_module_level:
531
+ raise
532
+ raise nodes.Collector.CollectError(
533
+ "Using pytest.skip outside of a test will skip the entire module. "
534
+ "If that's your intention, pass `allow_module_level=True`. "
535
+ "If you want to skip a specific test or an entire class, "
536
+ "use the @pytest.mark.skip or @pytest.mark.skipif decorators."
537
+ ) from e
538
+ config.pluginmanager.consider_module(mod)
539
+ return mod
540
+
541
+
542
+ class Module(nodes.File, PyCollector):
543
+ """Collector for test classes and functions in a Python module."""
544
+
545
+ def _getobj(self):
546
+ return importtestmodule(self.path, self.config)
547
+
548
+ def collect(self) -> Iterable[nodes.Item | nodes.Collector]:
549
+ self._register_setup_module_fixture()
550
+ self._register_setup_function_fixture()
551
+ self.session._fixturemanager.parsefactories(self)
552
+ return super().collect()
553
+
554
+ def _register_setup_module_fixture(self) -> None:
555
+ """Register an autouse, module-scoped fixture for the collected module object
556
+ that invokes setUpModule/tearDownModule if either or both are available.
557
+
558
+ Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with
559
+ other fixtures (#517).
560
+ """
561
+ setup_module = _get_first_non_fixture_func(
562
+ self.obj, ("setUpModule", "setup_module")
563
+ )
564
+ teardown_module = _get_first_non_fixture_func(
565
+ self.obj, ("tearDownModule", "teardown_module")
566
+ )
567
+
568
+ if setup_module is None and teardown_module is None:
569
+ return
570
+
571
+ def xunit_setup_module_fixture(request) -> Generator[None]:
572
+ module = request.module
573
+ if setup_module is not None:
574
+ _call_with_optional_argument(setup_module, module)
575
+ yield
576
+ if teardown_module is not None:
577
+ _call_with_optional_argument(teardown_module, module)
578
+
579
+ self.session._fixturemanager._register_fixture(
580
+ # Use a unique name to speed up lookup.
581
+ name=f"_xunit_setup_module_fixture_{self.obj.__name__}",
582
+ func=xunit_setup_module_fixture,
583
+ nodeid=self.nodeid,
584
+ scope="module",
585
+ autouse=True,
586
+ )
587
+
588
+ def _register_setup_function_fixture(self) -> None:
589
+ """Register an autouse, function-scoped fixture for the collected module object
590
+ that invokes setup_function/teardown_function if either or both are available.
591
+
592
+ Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with
593
+ other fixtures (#517).
594
+ """
595
+ setup_function = _get_first_non_fixture_func(self.obj, ("setup_function",))
596
+ teardown_function = _get_first_non_fixture_func(
597
+ self.obj, ("teardown_function",)
598
+ )
599
+ if setup_function is None and teardown_function is None:
600
+ return
601
+
602
+ def xunit_setup_function_fixture(request) -> Generator[None]:
603
+ if request.instance is not None:
604
+ # in this case we are bound to an instance, so we need to let
605
+ # setup_method handle this
606
+ yield
607
+ return
608
+ function = request.function
609
+ if setup_function is not None:
610
+ _call_with_optional_argument(setup_function, function)
611
+ yield
612
+ if teardown_function is not None:
613
+ _call_with_optional_argument(teardown_function, function)
614
+
615
+ self.session._fixturemanager._register_fixture(
616
+ # Use a unique name to speed up lookup.
617
+ name=f"_xunit_setup_function_fixture_{self.obj.__name__}",
618
+ func=xunit_setup_function_fixture,
619
+ nodeid=self.nodeid,
620
+ scope="function",
621
+ autouse=True,
622
+ )
623
+
624
+
625
+ class Package(nodes.Directory):
626
+ """Collector for files and directories in a Python packages -- directories
627
+ with an `__init__.py` file.
628
+
629
+ .. note::
630
+
631
+ Directories without an `__init__.py` file are instead collected by
632
+ :class:`~pytest.Dir` by default. Both are :class:`~pytest.Directory`
633
+ collectors.
634
+
635
+ .. versionchanged:: 8.0
636
+
637
+ Now inherits from :class:`~pytest.Directory`.
638
+ """
639
+
640
+ def __init__(
641
+ self,
642
+ fspath: LEGACY_PATH | None,
643
+ parent: nodes.Collector,
644
+ # NOTE: following args are unused:
645
+ config=None,
646
+ session=None,
647
+ nodeid=None,
648
+ path: Path | None = None,
649
+ ) -> None:
650
+ # NOTE: Could be just the following, but kept as-is for compat.
651
+ # super().__init__(self, fspath, parent=parent)
652
+ session = parent.session
653
+ super().__init__(
654
+ fspath=fspath,
655
+ path=path,
656
+ parent=parent,
657
+ config=config,
658
+ session=session,
659
+ nodeid=nodeid,
660
+ )
661
+
662
+ def setup(self) -> None:
663
+ init_mod = importtestmodule(self.path / "__init__.py", self.config)
664
+
665
+ # Not using fixtures to call setup_module here because autouse fixtures
666
+ # from packages are not called automatically (#4085).
667
+ setup_module = _get_first_non_fixture_func(
668
+ init_mod, ("setUpModule", "setup_module")
669
+ )
670
+ if setup_module is not None:
671
+ _call_with_optional_argument(setup_module, init_mod)
672
+
673
+ teardown_module = _get_first_non_fixture_func(
674
+ init_mod, ("tearDownModule", "teardown_module")
675
+ )
676
+ if teardown_module is not None:
677
+ func = partial(_call_with_optional_argument, teardown_module, init_mod)
678
+ self.addfinalizer(func)
679
+
680
+ def collect(self) -> Iterable[nodes.Item | nodes.Collector]:
681
+ # Always collect __init__.py first.
682
+ def sort_key(entry: os.DirEntry[str]) -> object:
683
+ return (entry.name != "__init__.py", entry.name)
684
+
685
+ config = self.config
686
+ col: nodes.Collector | None
687
+ cols: Sequence[nodes.Collector]
688
+ ihook = self.ihook
689
+ for direntry in scandir(self.path, sort_key):
690
+ if direntry.is_dir():
691
+ path = Path(direntry.path)
692
+ if not self.session.isinitpath(path, with_parents=True):
693
+ if ihook.pytest_ignore_collect(collection_path=path, config=config):
694
+ continue
695
+ col = ihook.pytest_collect_directory(path=path, parent=self)
696
+ if col is not None:
697
+ yield col
698
+
699
+ elif direntry.is_file():
700
+ path = Path(direntry.path)
701
+ if not self.session.isinitpath(path):
702
+ if ihook.pytest_ignore_collect(collection_path=path, config=config):
703
+ continue
704
+ cols = ihook.pytest_collect_file(file_path=path, parent=self)
705
+ yield from cols
706
+
707
+
708
+ def _call_with_optional_argument(func, arg) -> None:
709
+ """Call the given function with the given argument if func accepts one argument, otherwise
710
+ calls func without arguments."""
711
+ arg_count = func.__code__.co_argcount
712
+ if inspect.ismethod(func):
713
+ arg_count -= 1
714
+ if arg_count:
715
+ func(arg)
716
+ else:
717
+ func()
718
+
719
+
720
+ def _get_first_non_fixture_func(obj: object, names: Iterable[str]) -> object | None:
721
+ """Return the attribute from the given object to be used as a setup/teardown
722
+ xunit-style function, but only if not marked as a fixture to avoid calling it twice.
723
+ """
724
+ for name in names:
725
+ meth: object | None = getattr(obj, name, None)
726
+ if meth is not None and fixtures.getfixturemarker(meth) is None:
727
+ return meth
728
+ return None
729
+
730
+
731
+ class Class(PyCollector):
732
+ """Collector for test methods (and nested classes) in a Python class."""
733
+
734
+ @classmethod
735
+ def from_parent(cls, parent, *, name, obj=None, **kw) -> Self: # type: ignore[override]
736
+ """The public constructor."""
737
+ return super().from_parent(name=name, parent=parent, **kw)
738
+
739
+ def newinstance(self):
740
+ return self.obj()
741
+
742
+ def collect(self) -> Iterable[nodes.Item | nodes.Collector]:
743
+ if not safe_getattr(self.obj, "__test__", True):
744
+ return []
745
+ if hasinit(self.obj):
746
+ assert self.parent is not None
747
+ self.warn(
748
+ PytestCollectionWarning(
749
+ f"cannot collect test class {self.obj.__name__!r} because it has a "
750
+ f"__init__ constructor (from: {self.parent.nodeid})"
751
+ )
752
+ )
753
+ return []
754
+ elif hasnew(self.obj):
755
+ assert self.parent is not None
756
+ self.warn(
757
+ PytestCollectionWarning(
758
+ f"cannot collect test class {self.obj.__name__!r} because it has a "
759
+ f"__new__ constructor (from: {self.parent.nodeid})"
760
+ )
761
+ )
762
+ return []
763
+
764
+ self._register_setup_class_fixture()
765
+ self._register_setup_method_fixture()
766
+
767
+ self.session._fixturemanager.parsefactories(self.newinstance(), self.nodeid)
768
+
769
+ return super().collect()
770
+
771
+ def _register_setup_class_fixture(self) -> None:
772
+ """Register an autouse, class scoped fixture into the collected class object
773
+ that invokes setup_class/teardown_class if either or both are available.
774
+
775
+ Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with
776
+ other fixtures (#517).
777
+ """
778
+ setup_class = _get_first_non_fixture_func(self.obj, ("setup_class",))
779
+ teardown_class = _get_first_non_fixture_func(self.obj, ("teardown_class",))
780
+ if setup_class is None and teardown_class is None:
781
+ return
782
+
783
+ def xunit_setup_class_fixture(request) -> Generator[None]:
784
+ cls = request.cls
785
+ if setup_class is not None:
786
+ func = getimfunc(setup_class)
787
+ _call_with_optional_argument(func, cls)
788
+ yield
789
+ if teardown_class is not None:
790
+ func = getimfunc(teardown_class)
791
+ _call_with_optional_argument(func, cls)
792
+
793
+ self.session._fixturemanager._register_fixture(
794
+ # Use a unique name to speed up lookup.
795
+ name=f"_xunit_setup_class_fixture_{self.obj.__qualname__}",
796
+ func=xunit_setup_class_fixture,
797
+ nodeid=self.nodeid,
798
+ scope="class",
799
+ autouse=True,
800
+ )
801
+
802
+ def _register_setup_method_fixture(self) -> None:
803
+ """Register an autouse, function scoped fixture into the collected class object
804
+ that invokes setup_method/teardown_method if either or both are available.
805
+
806
+ Using a fixture to invoke these methods ensures we play nicely and unsurprisingly with
807
+ other fixtures (#517).
808
+ """
809
+ setup_name = "setup_method"
810
+ setup_method = _get_first_non_fixture_func(self.obj, (setup_name,))
811
+ teardown_name = "teardown_method"
812
+ teardown_method = _get_first_non_fixture_func(self.obj, (teardown_name,))
813
+ if setup_method is None and teardown_method is None:
814
+ return
815
+
816
+ def xunit_setup_method_fixture(request) -> Generator[None]:
817
+ instance = request.instance
818
+ method = request.function
819
+ if setup_method is not None:
820
+ func = getattr(instance, setup_name)
821
+ _call_with_optional_argument(func, method)
822
+ yield
823
+ if teardown_method is not None:
824
+ func = getattr(instance, teardown_name)
825
+ _call_with_optional_argument(func, method)
826
+
827
+ self.session._fixturemanager._register_fixture(
828
+ # Use a unique name to speed up lookup.
829
+ name=f"_xunit_setup_method_fixture_{self.obj.__qualname__}",
830
+ func=xunit_setup_method_fixture,
831
+ nodeid=self.nodeid,
832
+ scope="function",
833
+ autouse=True,
834
+ )
835
+
836
+
837
+ def hasinit(obj: object) -> bool:
838
+ init: object = getattr(obj, "__init__", None)
839
+ if init:
840
+ return init != object.__init__
841
+ return False
842
+
843
+
844
+ def hasnew(obj: object) -> bool:
845
+ new: object = getattr(obj, "__new__", None)
846
+ if new:
847
+ return new != object.__new__
848
+ return False
849
+
850
+
851
+ @final
852
+ @dataclasses.dataclass(frozen=True)
853
+ class IdMaker:
854
+ """Make IDs for a parametrization."""
855
+
856
+ __slots__ = (
857
+ "argnames",
858
+ "parametersets",
859
+ "idfn",
860
+ "ids",
861
+ "config",
862
+ "nodeid",
863
+ "func_name",
864
+ )
865
+
866
+ # The argnames of the parametrization.
867
+ argnames: Sequence[str]
868
+ # The ParameterSets of the parametrization.
869
+ parametersets: Sequence[ParameterSet]
870
+ # Optionally, a user-provided callable to make IDs for parameters in a
871
+ # ParameterSet.
872
+ idfn: Callable[[Any], object | None] | None
873
+ # Optionally, explicit IDs for ParameterSets by index.
874
+ ids: Sequence[object | None] | None
875
+ # Optionally, the pytest config.
876
+ # Used for controlling ASCII escaping, and for calling the
877
+ # :hook:`pytest_make_parametrize_id` hook.
878
+ config: Config | None
879
+ # Optionally, the ID of the node being parametrized.
880
+ # Used only for clearer error messages.
881
+ nodeid: str | None
882
+ # Optionally, the ID of the function being parametrized.
883
+ # Used only for clearer error messages.
884
+ func_name: str | None
885
+
886
+ def make_unique_parameterset_ids(self) -> list[str]:
887
+ """Make a unique identifier for each ParameterSet, that may be used to
888
+ identify the parametrization in a node ID.
889
+
890
+ Format is <prm_1_token>-...-<prm_n_token>[counter], where prm_x_token is
891
+ - user-provided id, if given
892
+ - else an id derived from the value, applicable for certain types
893
+ - else <argname><parameterset index>
894
+ The counter suffix is appended only in case a string wouldn't be unique
895
+ otherwise.
896
+ """
897
+ resolved_ids = list(self._resolve_ids())
898
+ # All IDs must be unique!
899
+ if len(resolved_ids) != len(set(resolved_ids)):
900
+ # Record the number of occurrences of each ID.
901
+ id_counts = Counter(resolved_ids)
902
+ # Map the ID to its next suffix.
903
+ id_suffixes: dict[str, int] = defaultdict(int)
904
+ # Suffix non-unique IDs to make them unique.
905
+ for index, id in enumerate(resolved_ids):
906
+ if id_counts[id] > 1:
907
+ suffix = ""
908
+ if id and id[-1].isdigit():
909
+ suffix = "_"
910
+ new_id = f"{id}{suffix}{id_suffixes[id]}"
911
+ while new_id in set(resolved_ids):
912
+ id_suffixes[id] += 1
913
+ new_id = f"{id}{suffix}{id_suffixes[id]}"
914
+ resolved_ids[index] = new_id
915
+ id_suffixes[id] += 1
916
+ assert len(resolved_ids) == len(
917
+ set(resolved_ids)
918
+ ), f"Internal error: {resolved_ids=}"
919
+ return resolved_ids
920
+
921
+ def _resolve_ids(self) -> Iterable[str]:
922
+ """Resolve IDs for all ParameterSets (may contain duplicates)."""
923
+ for idx, parameterset in enumerate(self.parametersets):
924
+ if parameterset.id is not None:
925
+ # ID provided directly - pytest.param(..., id="...")
926
+ yield parameterset.id
927
+ elif self.ids and idx < len(self.ids) and self.ids[idx] is not None:
928
+ # ID provided in the IDs list - parametrize(..., ids=[...]).
929
+ yield self._idval_from_value_required(self.ids[idx], idx)
930
+ else:
931
+ # ID not provided - generate it.
932
+ yield "-".join(
933
+ self._idval(val, argname, idx)
934
+ for val, argname in zip(parameterset.values, self.argnames)
935
+ )
936
+
937
+ def _idval(self, val: object, argname: str, idx: int) -> str:
938
+ """Make an ID for a parameter in a ParameterSet."""
939
+ idval = self._idval_from_function(val, argname, idx)
940
+ if idval is not None:
941
+ return idval
942
+ idval = self._idval_from_hook(val, argname)
943
+ if idval is not None:
944
+ return idval
945
+ idval = self._idval_from_value(val)
946
+ if idval is not None:
947
+ return idval
948
+ return self._idval_from_argname(argname, idx)
949
+
950
+ def _idval_from_function(self, val: object, argname: str, idx: int) -> str | None:
951
+ """Try to make an ID for a parameter in a ParameterSet using the
952
+ user-provided id callable, if given."""
953
+ if self.idfn is None:
954
+ return None
955
+ try:
956
+ id = self.idfn(val)
957
+ except Exception as e:
958
+ prefix = f"{self.nodeid}: " if self.nodeid is not None else ""
959
+ msg = "error raised while trying to determine id of parameter '{}' at position {}"
960
+ msg = prefix + msg.format(argname, idx)
961
+ raise ValueError(msg) from e
962
+ if id is None:
963
+ return None
964
+ return self._idval_from_value(id)
965
+
966
+ def _idval_from_hook(self, val: object, argname: str) -> str | None:
967
+ """Try to make an ID for a parameter in a ParameterSet by calling the
968
+ :hook:`pytest_make_parametrize_id` hook."""
969
+ if self.config:
970
+ id: str | None = self.config.hook.pytest_make_parametrize_id(
971
+ config=self.config, val=val, argname=argname
972
+ )
973
+ return id
974
+ return None
975
+
976
+ def _idval_from_value(self, val: object) -> str | None:
977
+ """Try to make an ID for a parameter in a ParameterSet from its value,
978
+ if the value type is supported."""
979
+ if isinstance(val, (str, bytes)):
980
+ return _ascii_escaped_by_config(val, self.config)
981
+ elif val is None or isinstance(val, (float, int, bool, complex)):
982
+ return str(val)
983
+ elif isinstance(val, Pattern):
984
+ return ascii_escaped(val.pattern)
985
+ elif val is NOTSET:
986
+ # Fallback to default. Note that NOTSET is an enum.Enum.
987
+ pass
988
+ elif isinstance(val, enum.Enum):
989
+ return str(val)
990
+ elif isinstance(getattr(val, "__name__", None), str):
991
+ # Name of a class, function, module, etc.
992
+ name: str = getattr(val, "__name__")
993
+ return name
994
+ return None
995
+
996
+ def _idval_from_value_required(self, val: object, idx: int) -> str:
997
+ """Like _idval_from_value(), but fails if the type is not supported."""
998
+ id = self._idval_from_value(val)
999
+ if id is not None:
1000
+ return id
1001
+
1002
+ # Fail.
1003
+ if self.func_name is not None:
1004
+ prefix = f"In {self.func_name}: "
1005
+ elif self.nodeid is not None:
1006
+ prefix = f"In {self.nodeid}: "
1007
+ else:
1008
+ prefix = ""
1009
+ msg = (
1010
+ f"{prefix}ids contains unsupported value {saferepr(val)} (type: {type(val)!r}) at index {idx}. "
1011
+ "Supported types are: str, bytes, int, float, complex, bool, enum, regex or anything with a __name__."
1012
+ )
1013
+ fail(msg, pytrace=False)
1014
+
1015
+ @staticmethod
1016
+ def _idval_from_argname(argname: str, idx: int) -> str:
1017
+ """Make an ID for a parameter in a ParameterSet from the argument name
1018
+ and the index of the ParameterSet."""
1019
+ return str(argname) + str(idx)
1020
+
1021
+
1022
+ @final
1023
+ @dataclasses.dataclass(frozen=True)
1024
+ class CallSpec2:
1025
+ """A planned parameterized invocation of a test function.
1026
+
1027
+ Calculated during collection for a given test function's Metafunc.
1028
+ Once collection is over, each callspec is turned into a single Item
1029
+ and stored in item.callspec.
1030
+ """
1031
+
1032
+ # arg name -> arg value which will be passed to a fixture or pseudo-fixture
1033
+ # of the same name. (indirect or direct parametrization respectively)
1034
+ params: dict[str, object] = dataclasses.field(default_factory=dict)
1035
+ # arg name -> arg index.
1036
+ indices: dict[str, int] = dataclasses.field(default_factory=dict)
1037
+ # Used for sorting parametrized resources.
1038
+ _arg2scope: Mapping[str, Scope] = dataclasses.field(default_factory=dict)
1039
+ # Parts which will be added to the item's name in `[..]` separated by "-".
1040
+ _idlist: Sequence[str] = dataclasses.field(default_factory=tuple)
1041
+ # Marks which will be applied to the item.
1042
+ marks: list[Mark] = dataclasses.field(default_factory=list)
1043
+
1044
+ def setmulti(
1045
+ self,
1046
+ *,
1047
+ argnames: Iterable[str],
1048
+ valset: Iterable[object],
1049
+ id: str,
1050
+ marks: Iterable[Mark | MarkDecorator],
1051
+ scope: Scope,
1052
+ param_index: int,
1053
+ ) -> CallSpec2:
1054
+ params = self.params.copy()
1055
+ indices = self.indices.copy()
1056
+ arg2scope = dict(self._arg2scope)
1057
+ for arg, val in zip(argnames, valset):
1058
+ if arg in params:
1059
+ raise ValueError(f"duplicate parametrization of {arg!r}")
1060
+ params[arg] = val
1061
+ indices[arg] = param_index
1062
+ arg2scope[arg] = scope
1063
+ return CallSpec2(
1064
+ params=params,
1065
+ indices=indices,
1066
+ _arg2scope=arg2scope,
1067
+ _idlist=[*self._idlist, id],
1068
+ marks=[*self.marks, *normalize_mark_list(marks)],
1069
+ )
1070
+
1071
+ def getparam(self, name: str) -> object:
1072
+ try:
1073
+ return self.params[name]
1074
+ except KeyError as e:
1075
+ raise ValueError(name) from e
1076
+
1077
+ @property
1078
+ def id(self) -> str:
1079
+ return "-".join(self._idlist)
1080
+
1081
+
1082
+ def get_direct_param_fixture_func(request: FixtureRequest) -> Any:
1083
+ return request.param
1084
+
1085
+
1086
+ # Used for storing pseudo fixturedefs for direct parametrization.
1087
+ name2pseudofixturedef_key = StashKey[Dict[str, FixtureDef[Any]]]()
1088
+
1089
+
1090
+ @final
1091
+ class Metafunc:
1092
+ """Objects passed to the :hook:`pytest_generate_tests` hook.
1093
+
1094
+ They help to inspect a test function and to generate tests according to
1095
+ test configuration or values specified in the class or module where a
1096
+ test function is defined.
1097
+ """
1098
+
1099
+ def __init__(
1100
+ self,
1101
+ definition: FunctionDefinition,
1102
+ fixtureinfo: fixtures.FuncFixtureInfo,
1103
+ config: Config,
1104
+ cls=None,
1105
+ module=None,
1106
+ *,
1107
+ _ispytest: bool = False,
1108
+ ) -> None:
1109
+ check_ispytest(_ispytest)
1110
+
1111
+ #: Access to the underlying :class:`_pytest.python.FunctionDefinition`.
1112
+ self.definition = definition
1113
+
1114
+ #: Access to the :class:`pytest.Config` object for the test session.
1115
+ self.config = config
1116
+
1117
+ #: The module object where the test function is defined in.
1118
+ self.module = module
1119
+
1120
+ #: Underlying Python test function.
1121
+ self.function = definition.obj
1122
+
1123
+ #: Set of fixture names required by the test function.
1124
+ self.fixturenames = fixtureinfo.names_closure
1125
+
1126
+ #: Class object where the test function is defined in or ``None``.
1127
+ self.cls = cls
1128
+
1129
+ self._arg2fixturedefs = fixtureinfo.name2fixturedefs
1130
+
1131
+ # Result of parametrize().
1132
+ self._calls: list[CallSpec2] = []
1133
+
1134
+ def parametrize(
1135
+ self,
1136
+ argnames: str | Sequence[str],
1137
+ argvalues: Iterable[ParameterSet | Sequence[object] | object],
1138
+ indirect: bool | Sequence[str] = False,
1139
+ ids: Iterable[object | None] | Callable[[Any], object | None] | None = None,
1140
+ scope: _ScopeName | None = None,
1141
+ *,
1142
+ _param_mark: Mark | None = None,
1143
+ ) -> None:
1144
+ """Add new invocations to the underlying test function using the list
1145
+ of argvalues for the given argnames. Parametrization is performed
1146
+ during the collection phase. If you need to setup expensive resources
1147
+ see about setting indirect to do it rather than at test setup time.
1148
+
1149
+ Can be called multiple times per test function (but only on different
1150
+ argument names), in which case each call parametrizes all previous
1151
+ parametrizations, e.g.
1152
+
1153
+ ::
1154
+
1155
+ unparametrized: t
1156
+ parametrize ["x", "y"]: t[x], t[y]
1157
+ parametrize [1, 2]: t[x-1], t[x-2], t[y-1], t[y-2]
1158
+
1159
+ :param argnames:
1160
+ A comma-separated string denoting one or more argument names, or
1161
+ a list/tuple of argument strings.
1162
+
1163
+ :param argvalues:
1164
+ The list of argvalues determines how often a test is invoked with
1165
+ different argument values.
1166
+
1167
+ If only one argname was specified argvalues is a list of values.
1168
+ If N argnames were specified, argvalues must be a list of
1169
+ N-tuples, where each tuple-element specifies a value for its
1170
+ respective argname.
1171
+ :type argvalues: Iterable[_pytest.mark.structures.ParameterSet | Sequence[object] | object]
1172
+ :param indirect:
1173
+ A list of arguments' names (subset of argnames) or a boolean.
1174
+ If True the list contains all names from the argnames. Each
1175
+ argvalue corresponding to an argname in this list will
1176
+ be passed as request.param to its respective argname fixture
1177
+ function so that it can perform more expensive setups during the
1178
+ setup phase of a test rather than at collection time.
1179
+
1180
+ :param ids:
1181
+ Sequence of (or generator for) ids for ``argvalues``,
1182
+ or a callable to return part of the id for each argvalue.
1183
+
1184
+ With sequences (and generators like ``itertools.count()``) the
1185
+ returned ids should be of type ``string``, ``int``, ``float``,
1186
+ ``bool``, or ``None``.
1187
+ They are mapped to the corresponding index in ``argvalues``.
1188
+ ``None`` means to use the auto-generated id.
1189
+
1190
+ If it is a callable it will be called for each entry in
1191
+ ``argvalues``, and the return value is used as part of the
1192
+ auto-generated id for the whole set (where parts are joined with
1193
+ dashes ("-")).
1194
+ This is useful to provide more specific ids for certain items, e.g.
1195
+ dates. Returning ``None`` will use an auto-generated id.
1196
+
1197
+ If no ids are provided they will be generated automatically from
1198
+ the argvalues.
1199
+
1200
+ :param scope:
1201
+ If specified it denotes the scope of the parameters.
1202
+ The scope is used for grouping tests by parameter instances.
1203
+ It will also override any fixture-function defined scope, allowing
1204
+ to set a dynamic scope using test context or configuration.
1205
+ """
1206
+ argnames, parametersets = ParameterSet._for_parametrize(
1207
+ argnames,
1208
+ argvalues,
1209
+ self.function,
1210
+ self.config,
1211
+ nodeid=self.definition.nodeid,
1212
+ )
1213
+ del argvalues
1214
+
1215
+ if "request" in argnames:
1216
+ fail(
1217
+ "'request' is a reserved name and cannot be used in @pytest.mark.parametrize",
1218
+ pytrace=False,
1219
+ )
1220
+
1221
+ if scope is not None:
1222
+ scope_ = Scope.from_user(
1223
+ scope, descr=f"parametrize() call in {self.function.__name__}"
1224
+ )
1225
+ else:
1226
+ scope_ = _find_parametrized_scope(argnames, self._arg2fixturedefs, indirect)
1227
+
1228
+ self._validate_if_using_arg_names(argnames, indirect)
1229
+
1230
+ # Use any already (possibly) generated ids with parametrize Marks.
1231
+ if _param_mark and _param_mark._param_ids_from:
1232
+ generated_ids = _param_mark._param_ids_from._param_ids_generated
1233
+ if generated_ids is not None:
1234
+ ids = generated_ids
1235
+
1236
+ ids = self._resolve_parameter_set_ids(
1237
+ argnames, ids, parametersets, nodeid=self.definition.nodeid
1238
+ )
1239
+
1240
+ # Store used (possibly generated) ids with parametrize Marks.
1241
+ if _param_mark and _param_mark._param_ids_from and generated_ids is None:
1242
+ object.__setattr__(_param_mark._param_ids_from, "_param_ids_generated", ids)
1243
+
1244
+ # Add funcargs as fixturedefs to fixtureinfo.arg2fixturedefs by registering
1245
+ # artificial "pseudo" FixtureDef's so that later at test execution time we can
1246
+ # rely on a proper FixtureDef to exist for fixture setup.
1247
+ node = None
1248
+ # If we have a scope that is higher than function, we need
1249
+ # to make sure we only ever create an according fixturedef on
1250
+ # a per-scope basis. We thus store and cache the fixturedef on the
1251
+ # node related to the scope.
1252
+ if scope_ is not Scope.Function:
1253
+ collector = self.definition.parent
1254
+ assert collector is not None
1255
+ node = get_scope_node(collector, scope_)
1256
+ if node is None:
1257
+ # If used class scope and there is no class, use module-level
1258
+ # collector (for now).
1259
+ if scope_ is Scope.Class:
1260
+ assert isinstance(collector, Module)
1261
+ node = collector
1262
+ # If used package scope and there is no package, use session
1263
+ # (for now).
1264
+ elif scope_ is Scope.Package:
1265
+ node = collector.session
1266
+ else:
1267
+ assert False, f"Unhandled missing scope: {scope}"
1268
+ if node is None:
1269
+ name2pseudofixturedef = None
1270
+ else:
1271
+ default: dict[str, FixtureDef[Any]] = {}
1272
+ name2pseudofixturedef = node.stash.setdefault(
1273
+ name2pseudofixturedef_key, default
1274
+ )
1275
+ arg_directness = self._resolve_args_directness(argnames, indirect)
1276
+ for argname in argnames:
1277
+ if arg_directness[argname] == "indirect":
1278
+ continue
1279
+ if name2pseudofixturedef is not None and argname in name2pseudofixturedef:
1280
+ fixturedef = name2pseudofixturedef[argname]
1281
+ else:
1282
+ fixturedef = FixtureDef(
1283
+ config=self.config,
1284
+ baseid="",
1285
+ argname=argname,
1286
+ func=get_direct_param_fixture_func,
1287
+ scope=scope_,
1288
+ params=None,
1289
+ ids=None,
1290
+ _ispytest=True,
1291
+ )
1292
+ if name2pseudofixturedef is not None:
1293
+ name2pseudofixturedef[argname] = fixturedef
1294
+ self._arg2fixturedefs[argname] = [fixturedef]
1295
+
1296
+ # Create the new calls: if we are parametrize() multiple times (by applying the decorator
1297
+ # more than once) then we accumulate those calls generating the cartesian product
1298
+ # of all calls.
1299
+ newcalls = []
1300
+ for callspec in self._calls or [CallSpec2()]:
1301
+ for param_index, (param_id, param_set) in enumerate(
1302
+ zip(ids, parametersets)
1303
+ ):
1304
+ newcallspec = callspec.setmulti(
1305
+ argnames=argnames,
1306
+ valset=param_set.values,
1307
+ id=param_id,
1308
+ marks=param_set.marks,
1309
+ scope=scope_,
1310
+ param_index=param_index,
1311
+ )
1312
+ newcalls.append(newcallspec)
1313
+ self._calls = newcalls
1314
+
1315
+ def _resolve_parameter_set_ids(
1316
+ self,
1317
+ argnames: Sequence[str],
1318
+ ids: Iterable[object | None] | Callable[[Any], object | None] | None,
1319
+ parametersets: Sequence[ParameterSet],
1320
+ nodeid: str,
1321
+ ) -> list[str]:
1322
+ """Resolve the actual ids for the given parameter sets.
1323
+
1324
+ :param argnames:
1325
+ Argument names passed to ``parametrize()``.
1326
+ :param ids:
1327
+ The `ids` parameter of the ``parametrize()`` call (see docs).
1328
+ :param parametersets:
1329
+ The parameter sets, each containing a set of values corresponding
1330
+ to ``argnames``.
1331
+ :param nodeid str:
1332
+ The nodeid of the definition item that generated this
1333
+ parametrization.
1334
+ :returns:
1335
+ List with ids for each parameter set given.
1336
+ """
1337
+ if ids is None:
1338
+ idfn = None
1339
+ ids_ = None
1340
+ elif callable(ids):
1341
+ idfn = ids
1342
+ ids_ = None
1343
+ else:
1344
+ idfn = None
1345
+ ids_ = self._validate_ids(ids, parametersets, self.function.__name__)
1346
+ id_maker = IdMaker(
1347
+ argnames,
1348
+ parametersets,
1349
+ idfn,
1350
+ ids_,
1351
+ self.config,
1352
+ nodeid=nodeid,
1353
+ func_name=self.function.__name__,
1354
+ )
1355
+ return id_maker.make_unique_parameterset_ids()
1356
+
1357
+ def _validate_ids(
1358
+ self,
1359
+ ids: Iterable[object | None],
1360
+ parametersets: Sequence[ParameterSet],
1361
+ func_name: str,
1362
+ ) -> list[object | None]:
1363
+ try:
1364
+ num_ids = len(ids) # type: ignore[arg-type]
1365
+ except TypeError:
1366
+ try:
1367
+ iter(ids)
1368
+ except TypeError as e:
1369
+ raise TypeError("ids must be a callable or an iterable") from e
1370
+ num_ids = len(parametersets)
1371
+
1372
+ # num_ids == 0 is a special case: https://github.com/pytest-dev/pytest/issues/1849
1373
+ if num_ids != len(parametersets) and num_ids != 0:
1374
+ msg = "In {}: {} parameter sets specified, with different number of ids: {}"
1375
+ fail(msg.format(func_name, len(parametersets), num_ids), pytrace=False)
1376
+
1377
+ return list(itertools.islice(ids, num_ids))
1378
+
1379
+ def _resolve_args_directness(
1380
+ self,
1381
+ argnames: Sequence[str],
1382
+ indirect: bool | Sequence[str],
1383
+ ) -> dict[str, Literal["indirect", "direct"]]:
1384
+ """Resolve if each parametrized argument must be considered an indirect
1385
+ parameter to a fixture of the same name, or a direct parameter to the
1386
+ parametrized function, based on the ``indirect`` parameter of the
1387
+ parametrized() call.
1388
+
1389
+ :param argnames:
1390
+ List of argument names passed to ``parametrize()``.
1391
+ :param indirect:
1392
+ Same as the ``indirect`` parameter of ``parametrize()``.
1393
+ :returns
1394
+ A dict mapping each arg name to either "indirect" or "direct".
1395
+ """
1396
+ arg_directness: dict[str, Literal["indirect", "direct"]]
1397
+ if isinstance(indirect, bool):
1398
+ arg_directness = dict.fromkeys(
1399
+ argnames, "indirect" if indirect else "direct"
1400
+ )
1401
+ elif isinstance(indirect, Sequence):
1402
+ arg_directness = dict.fromkeys(argnames, "direct")
1403
+ for arg in indirect:
1404
+ if arg not in argnames:
1405
+ fail(
1406
+ f"In {self.function.__name__}: indirect fixture '{arg}' doesn't exist",
1407
+ pytrace=False,
1408
+ )
1409
+ arg_directness[arg] = "indirect"
1410
+ else:
1411
+ fail(
1412
+ f"In {self.function.__name__}: expected Sequence or boolean"
1413
+ f" for indirect, got {type(indirect).__name__}",
1414
+ pytrace=False,
1415
+ )
1416
+ return arg_directness
1417
+
1418
+ def _validate_if_using_arg_names(
1419
+ self,
1420
+ argnames: Sequence[str],
1421
+ indirect: bool | Sequence[str],
1422
+ ) -> None:
1423
+ """Check if all argnames are being used, by default values, or directly/indirectly.
1424
+
1425
+ :param List[str] argnames: List of argument names passed to ``parametrize()``.
1426
+ :param indirect: Same as the ``indirect`` parameter of ``parametrize()``.
1427
+ :raises ValueError: If validation fails.
1428
+ """
1429
+ default_arg_names = set(get_default_arg_names(self.function))
1430
+ func_name = self.function.__name__
1431
+ for arg in argnames:
1432
+ if arg not in self.fixturenames:
1433
+ if arg in default_arg_names:
1434
+ fail(
1435
+ f"In {func_name}: function already takes an argument '{arg}' with a default value",
1436
+ pytrace=False,
1437
+ )
1438
+ else:
1439
+ if isinstance(indirect, Sequence):
1440
+ name = "fixture" if arg in indirect else "argument"
1441
+ else:
1442
+ name = "fixture" if indirect else "argument"
1443
+ fail(
1444
+ f"In {func_name}: function uses no {name} '{arg}'",
1445
+ pytrace=False,
1446
+ )
1447
+
1448
+
1449
+ def _find_parametrized_scope(
1450
+ argnames: Sequence[str],
1451
+ arg2fixturedefs: Mapping[str, Sequence[fixtures.FixtureDef[object]]],
1452
+ indirect: bool | Sequence[str],
1453
+ ) -> Scope:
1454
+ """Find the most appropriate scope for a parametrized call based on its arguments.
1455
+
1456
+ When there's at least one direct argument, always use "function" scope.
1457
+
1458
+ When a test function is parametrized and all its arguments are indirect
1459
+ (e.g. fixtures), return the most narrow scope based on the fixtures used.
1460
+
1461
+ Related to issue #1832, based on code posted by @Kingdread.
1462
+ """
1463
+ if isinstance(indirect, Sequence):
1464
+ all_arguments_are_fixtures = len(indirect) == len(argnames)
1465
+ else:
1466
+ all_arguments_are_fixtures = bool(indirect)
1467
+
1468
+ if all_arguments_are_fixtures:
1469
+ fixturedefs = arg2fixturedefs or {}
1470
+ used_scopes = [
1471
+ fixturedef[-1]._scope
1472
+ for name, fixturedef in fixturedefs.items()
1473
+ if name in argnames
1474
+ ]
1475
+ # Takes the most narrow scope from used fixtures.
1476
+ return min(used_scopes, default=Scope.Function)
1477
+
1478
+ return Scope.Function
1479
+
1480
+
1481
+ def _ascii_escaped_by_config(val: str | bytes, config: Config | None) -> str:
1482
+ if config is None:
1483
+ escape_option = False
1484
+ else:
1485
+ escape_option = config.getini(
1486
+ "disable_test_id_escaping_and_forfeit_all_rights_to_community_support"
1487
+ )
1488
+ # TODO: If escaping is turned off and the user passes bytes,
1489
+ # will return a bytes. For now we ignore this but the
1490
+ # code *probably* doesn't handle this case.
1491
+ return val if escape_option else ascii_escaped(val) # type: ignore
1492
+
1493
+
1494
+ class Function(PyobjMixin, nodes.Item):
1495
+ """Item responsible for setting up and executing a Python test function.
1496
+
1497
+ :param name:
1498
+ The full function name, including any decorations like those
1499
+ added by parametrization (``my_func[my_param]``).
1500
+ :param parent:
1501
+ The parent Node.
1502
+ :param config:
1503
+ The pytest Config object.
1504
+ :param callspec:
1505
+ If given, this function has been parametrized and the callspec contains
1506
+ meta information about the parametrization.
1507
+ :param callobj:
1508
+ If given, the object which will be called when the Function is invoked,
1509
+ otherwise the callobj will be obtained from ``parent`` using ``originalname``.
1510
+ :param keywords:
1511
+ Keywords bound to the function object for "-k" matching.
1512
+ :param session:
1513
+ The pytest Session object.
1514
+ :param fixtureinfo:
1515
+ Fixture information already resolved at this fixture node..
1516
+ :param originalname:
1517
+ The attribute name to use for accessing the underlying function object.
1518
+ Defaults to ``name``. Set this if name is different from the original name,
1519
+ for example when it contains decorations like those added by parametrization
1520
+ (``my_func[my_param]``).
1521
+ """
1522
+
1523
+ # Disable since functions handle it themselves.
1524
+ _ALLOW_MARKERS = False
1525
+
1526
+ def __init__(
1527
+ self,
1528
+ name: str,
1529
+ parent,
1530
+ config: Config | None = None,
1531
+ callspec: CallSpec2 | None = None,
1532
+ callobj=NOTSET,
1533
+ keywords: Mapping[str, Any] | None = None,
1534
+ session: Session | None = None,
1535
+ fixtureinfo: FuncFixtureInfo | None = None,
1536
+ originalname: str | None = None,
1537
+ ) -> None:
1538
+ super().__init__(name, parent, config=config, session=session)
1539
+
1540
+ if callobj is not NOTSET:
1541
+ self._obj = callobj
1542
+ self._instance = getattr(callobj, "__self__", None)
1543
+
1544
+ #: Original function name, without any decorations (for example
1545
+ #: parametrization adds a ``"[...]"`` suffix to function names), used to access
1546
+ #: the underlying function object from ``parent`` (in case ``callobj`` is not given
1547
+ #: explicitly).
1548
+ #:
1549
+ #: .. versionadded:: 3.0
1550
+ self.originalname = originalname or name
1551
+
1552
+ # Note: when FunctionDefinition is introduced, we should change ``originalname``
1553
+ # to a readonly property that returns FunctionDefinition.name.
1554
+
1555
+ self.own_markers.extend(get_unpacked_marks(self.obj))
1556
+ if callspec:
1557
+ self.callspec = callspec
1558
+ self.own_markers.extend(callspec.marks)
1559
+
1560
+ # todo: this is a hell of a hack
1561
+ # https://github.com/pytest-dev/pytest/issues/4569
1562
+ # Note: the order of the updates is important here; indicates what
1563
+ # takes priority (ctor argument over function attributes over markers).
1564
+ # Take own_markers only; NodeKeywords handles parent traversal on its own.
1565
+ self.keywords.update((mark.name, mark) for mark in self.own_markers)
1566
+ self.keywords.update(self.obj.__dict__)
1567
+ if keywords:
1568
+ self.keywords.update(keywords)
1569
+
1570
+ if fixtureinfo is None:
1571
+ fm = self.session._fixturemanager
1572
+ fixtureinfo = fm.getfixtureinfo(self, self.obj, self.cls)
1573
+ self._fixtureinfo: FuncFixtureInfo = fixtureinfo
1574
+ self.fixturenames = fixtureinfo.names_closure
1575
+ self._initrequest()
1576
+
1577
+ # todo: determine sound type limitations
1578
+ @classmethod
1579
+ def from_parent(cls, parent, **kw) -> Self:
1580
+ """The public constructor."""
1581
+ return super().from_parent(parent=parent, **kw)
1582
+
1583
+ def _initrequest(self) -> None:
1584
+ self.funcargs: dict[str, object] = {}
1585
+ self._request = fixtures.TopRequest(self, _ispytest=True)
1586
+
1587
+ @property
1588
+ def function(self):
1589
+ """Underlying python 'function' object."""
1590
+ return getimfunc(self.obj)
1591
+
1592
+ @property
1593
+ def instance(self):
1594
+ try:
1595
+ return self._instance
1596
+ except AttributeError:
1597
+ if isinstance(self.parent, Class):
1598
+ # Each Function gets a fresh class instance.
1599
+ self._instance = self._getinstance()
1600
+ else:
1601
+ self._instance = None
1602
+ return self._instance
1603
+
1604
+ def _getinstance(self):
1605
+ if isinstance(self.parent, Class):
1606
+ # Each Function gets a fresh class instance.
1607
+ return self.parent.newinstance()
1608
+ else:
1609
+ return None
1610
+
1611
+ def _getobj(self):
1612
+ instance = self.instance
1613
+ if instance is not None:
1614
+ parent_obj = instance
1615
+ else:
1616
+ assert self.parent is not None
1617
+ parent_obj = self.parent.obj # type: ignore[attr-defined]
1618
+ return getattr(parent_obj, self.originalname)
1619
+
1620
+ @property
1621
+ def _pyfuncitem(self):
1622
+ """(compatonly) for code expecting pytest-2.2 style request objects."""
1623
+ return self
1624
+
1625
+ def runtest(self) -> None:
1626
+ """Execute the underlying test function."""
1627
+ self.ihook.pytest_pyfunc_call(pyfuncitem=self)
1628
+
1629
+ def setup(self) -> None:
1630
+ self._request._fillfixtures()
1631
+
1632
+ def _traceback_filter(self, excinfo: ExceptionInfo[BaseException]) -> Traceback:
1633
+ if hasattr(self, "_obj") and not self.config.getoption("fulltrace", False):
1634
+ code = _pytest._code.Code.from_function(get_real_func(self.obj))
1635
+ path, firstlineno = code.path, code.firstlineno
1636
+ traceback = excinfo.traceback
1637
+ ntraceback = traceback.cut(path=path, firstlineno=firstlineno)
1638
+ if ntraceback == traceback:
1639
+ ntraceback = ntraceback.cut(path=path)
1640
+ if ntraceback == traceback:
1641
+ ntraceback = ntraceback.filter(filter_traceback)
1642
+ if not ntraceback:
1643
+ ntraceback = traceback
1644
+ ntraceback = ntraceback.filter(excinfo)
1645
+
1646
+ # issue364: mark all but first and last frames to
1647
+ # only show a single-line message for each frame.
1648
+ if self.config.getoption("tbstyle", "auto") == "auto":
1649
+ if len(ntraceback) > 2:
1650
+ ntraceback = Traceback(
1651
+ (
1652
+ ntraceback[0],
1653
+ *(t.with_repr_style("short") for t in ntraceback[1:-1]),
1654
+ ntraceback[-1],
1655
+ )
1656
+ )
1657
+
1658
+ return ntraceback
1659
+ return excinfo.traceback
1660
+
1661
+ # TODO: Type ignored -- breaks Liskov Substitution.
1662
+ def repr_failure( # type: ignore[override]
1663
+ self,
1664
+ excinfo: ExceptionInfo[BaseException],
1665
+ ) -> str | TerminalRepr:
1666
+ style = self.config.getoption("tbstyle", "auto")
1667
+ if style == "auto":
1668
+ style = "long"
1669
+ return self._repr_failure_py(excinfo, style=style)
1670
+
1671
+
1672
+ class FunctionDefinition(Function):
1673
+ """This class is a stop gap solution until we evolve to have actual function
1674
+ definition nodes and manage to get rid of ``metafunc``."""
1675
+
1676
+ def runtest(self) -> None:
1677
+ raise RuntimeError("function definitions are not supposed to be run as tests")
1678
+
1679
+ setup = runtest
vllm/lib/python3.10/site-packages/_pytest/python_api.py ADDED
@@ -0,0 +1,1028 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ from collections.abc import Collection
5
+ from collections.abc import Sized
6
+ from decimal import Decimal
7
+ import math
8
+ from numbers import Complex
9
+ import pprint
10
+ import re
11
+ from types import TracebackType
12
+ from typing import Any
13
+ from typing import Callable
14
+ from typing import cast
15
+ from typing import ContextManager
16
+ from typing import final
17
+ from typing import Mapping
18
+ from typing import overload
19
+ from typing import Pattern
20
+ from typing import Sequence
21
+ from typing import Tuple
22
+ from typing import Type
23
+ from typing import TYPE_CHECKING
24
+ from typing import TypeVar
25
+
26
+ import _pytest._code
27
+ from _pytest.outcomes import fail
28
+
29
+
30
+ if TYPE_CHECKING:
31
+ from numpy import ndarray
32
+
33
+
34
+ def _compare_approx(
35
+ full_object: object,
36
+ message_data: Sequence[tuple[str, str, str]],
37
+ number_of_elements: int,
38
+ different_ids: Sequence[object],
39
+ max_abs_diff: float,
40
+ max_rel_diff: float,
41
+ ) -> list[str]:
42
+ message_list = list(message_data)
43
+ message_list.insert(0, ("Index", "Obtained", "Expected"))
44
+ max_sizes = [0, 0, 0]
45
+ for index, obtained, expected in message_list:
46
+ max_sizes[0] = max(max_sizes[0], len(index))
47
+ max_sizes[1] = max(max_sizes[1], len(obtained))
48
+ max_sizes[2] = max(max_sizes[2], len(expected))
49
+ explanation = [
50
+ f"comparison failed. Mismatched elements: {len(different_ids)} / {number_of_elements}:",
51
+ f"Max absolute difference: {max_abs_diff}",
52
+ f"Max relative difference: {max_rel_diff}",
53
+ ] + [
54
+ f"{indexes:<{max_sizes[0]}} | {obtained:<{max_sizes[1]}} | {expected:<{max_sizes[2]}}"
55
+ for indexes, obtained, expected in message_list
56
+ ]
57
+ return explanation
58
+
59
+
60
+ # builtin pytest.approx helper
61
+
62
+
63
+ class ApproxBase:
64
+ """Provide shared utilities for making approximate comparisons between
65
+ numbers or sequences of numbers."""
66
+
67
+ # Tell numpy to use our `__eq__` operator instead of its.
68
+ __array_ufunc__ = None
69
+ __array_priority__ = 100
70
+
71
+ def __init__(self, expected, rel=None, abs=None, nan_ok: bool = False) -> None:
72
+ __tracebackhide__ = True
73
+ self.expected = expected
74
+ self.abs = abs
75
+ self.rel = rel
76
+ self.nan_ok = nan_ok
77
+ self._check_type()
78
+
79
+ def __repr__(self) -> str:
80
+ raise NotImplementedError
81
+
82
+ def _repr_compare(self, other_side: Any) -> list[str]:
83
+ return [
84
+ "comparison failed",
85
+ f"Obtained: {other_side}",
86
+ f"Expected: {self}",
87
+ ]
88
+
89
+ def __eq__(self, actual) -> bool:
90
+ return all(
91
+ a == self._approx_scalar(x) for a, x in self._yield_comparisons(actual)
92
+ )
93
+
94
+ def __bool__(self):
95
+ __tracebackhide__ = True
96
+ raise AssertionError(
97
+ "approx() is not supported in a boolean context.\nDid you mean: `assert a == approx(b)`?"
98
+ )
99
+
100
+ # Ignore type because of https://github.com/python/mypy/issues/4266.
101
+ __hash__ = None # type: ignore
102
+
103
+ def __ne__(self, actual) -> bool:
104
+ return not (actual == self)
105
+
106
+ def _approx_scalar(self, x) -> ApproxScalar:
107
+ if isinstance(x, Decimal):
108
+ return ApproxDecimal(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)
109
+ return ApproxScalar(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)
110
+
111
+ def _yield_comparisons(self, actual):
112
+ """Yield all the pairs of numbers to be compared.
113
+
114
+ This is used to implement the `__eq__` method.
115
+ """
116
+ raise NotImplementedError
117
+
118
+ def _check_type(self) -> None:
119
+ """Raise a TypeError if the expected value is not a valid type."""
120
+ # This is only a concern if the expected value is a sequence. In every
121
+ # other case, the approx() function ensures that the expected value has
122
+ # a numeric type. For this reason, the default is to do nothing. The
123
+ # classes that deal with sequences should reimplement this method to
124
+ # raise if there are any non-numeric elements in the sequence.
125
+
126
+
127
+ def _recursive_sequence_map(f, x):
128
+ """Recursively map a function over a sequence of arbitrary depth"""
129
+ if isinstance(x, (list, tuple)):
130
+ seq_type = type(x)
131
+ return seq_type(_recursive_sequence_map(f, xi) for xi in x)
132
+ elif _is_sequence_like(x):
133
+ return [_recursive_sequence_map(f, xi) for xi in x]
134
+ else:
135
+ return f(x)
136
+
137
+
138
+ class ApproxNumpy(ApproxBase):
139
+ """Perform approximate comparisons where the expected value is numpy array."""
140
+
141
+ def __repr__(self) -> str:
142
+ list_scalars = _recursive_sequence_map(
143
+ self._approx_scalar, self.expected.tolist()
144
+ )
145
+ return f"approx({list_scalars!r})"
146
+
147
+ def _repr_compare(self, other_side: ndarray | list[Any]) -> list[str]:
148
+ import itertools
149
+ import math
150
+
151
+ def get_value_from_nested_list(
152
+ nested_list: list[Any], nd_index: tuple[Any, ...]
153
+ ) -> Any:
154
+ """
155
+ Helper function to get the value out of a nested list, given an n-dimensional index.
156
+ This mimics numpy's indexing, but for raw nested python lists.
157
+ """
158
+ value: Any = nested_list
159
+ for i in nd_index:
160
+ value = value[i]
161
+ return value
162
+
163
+ np_array_shape = self.expected.shape
164
+ approx_side_as_seq = _recursive_sequence_map(
165
+ self._approx_scalar, self.expected.tolist()
166
+ )
167
+
168
+ # convert other_side to numpy array to ensure shape attribute is available
169
+ other_side_as_array = _as_numpy_array(other_side)
170
+ assert other_side_as_array is not None
171
+
172
+ if np_array_shape != other_side_as_array.shape:
173
+ return [
174
+ "Impossible to compare arrays with different shapes.",
175
+ f"Shapes: {np_array_shape} and {other_side_as_array.shape}",
176
+ ]
177
+
178
+ number_of_elements = self.expected.size
179
+ max_abs_diff = -math.inf
180
+ max_rel_diff = -math.inf
181
+ different_ids = []
182
+ for index in itertools.product(*(range(i) for i in np_array_shape)):
183
+ approx_value = get_value_from_nested_list(approx_side_as_seq, index)
184
+ other_value = get_value_from_nested_list(other_side_as_array, index)
185
+ if approx_value != other_value:
186
+ abs_diff = abs(approx_value.expected - other_value)
187
+ max_abs_diff = max(max_abs_diff, abs_diff)
188
+ if other_value == 0.0:
189
+ max_rel_diff = math.inf
190
+ else:
191
+ max_rel_diff = max(max_rel_diff, abs_diff / abs(other_value))
192
+ different_ids.append(index)
193
+
194
+ message_data = [
195
+ (
196
+ str(index),
197
+ str(get_value_from_nested_list(other_side_as_array, index)),
198
+ str(get_value_from_nested_list(approx_side_as_seq, index)),
199
+ )
200
+ for index in different_ids
201
+ ]
202
+ return _compare_approx(
203
+ self.expected,
204
+ message_data,
205
+ number_of_elements,
206
+ different_ids,
207
+ max_abs_diff,
208
+ max_rel_diff,
209
+ )
210
+
211
+ def __eq__(self, actual) -> bool:
212
+ import numpy as np
213
+
214
+ # self.expected is supposed to always be an array here.
215
+
216
+ if not np.isscalar(actual):
217
+ try:
218
+ actual = np.asarray(actual)
219
+ except Exception as e:
220
+ raise TypeError(f"cannot compare '{actual}' to numpy.ndarray") from e
221
+
222
+ if not np.isscalar(actual) and actual.shape != self.expected.shape:
223
+ return False
224
+
225
+ return super().__eq__(actual)
226
+
227
+ def _yield_comparisons(self, actual):
228
+ import numpy as np
229
+
230
+ # `actual` can either be a numpy array or a scalar, it is treated in
231
+ # `__eq__` before being passed to `ApproxBase.__eq__`, which is the
232
+ # only method that calls this one.
233
+
234
+ if np.isscalar(actual):
235
+ for i in np.ndindex(self.expected.shape):
236
+ yield actual, self.expected[i].item()
237
+ else:
238
+ for i in np.ndindex(self.expected.shape):
239
+ yield actual[i].item(), self.expected[i].item()
240
+
241
+
242
+ class ApproxMapping(ApproxBase):
243
+ """Perform approximate comparisons where the expected value is a mapping
244
+ with numeric values (the keys can be anything)."""
245
+
246
+ def __repr__(self) -> str:
247
+ return f"approx({({k: self._approx_scalar(v) for k, v in self.expected.items()})!r})"
248
+
249
+ def _repr_compare(self, other_side: Mapping[object, float]) -> list[str]:
250
+ import math
251
+
252
+ approx_side_as_map = {
253
+ k: self._approx_scalar(v) for k, v in self.expected.items()
254
+ }
255
+
256
+ number_of_elements = len(approx_side_as_map)
257
+ max_abs_diff = -math.inf
258
+ max_rel_diff = -math.inf
259
+ different_ids = []
260
+ for (approx_key, approx_value), other_value in zip(
261
+ approx_side_as_map.items(), other_side.values()
262
+ ):
263
+ if approx_value != other_value:
264
+ if approx_value.expected is not None and other_value is not None:
265
+ try:
266
+ max_abs_diff = max(
267
+ max_abs_diff, abs(approx_value.expected - other_value)
268
+ )
269
+ if approx_value.expected == 0.0:
270
+ max_rel_diff = math.inf
271
+ else:
272
+ max_rel_diff = max(
273
+ max_rel_diff,
274
+ abs(
275
+ (approx_value.expected - other_value)
276
+ / approx_value.expected
277
+ ),
278
+ )
279
+ except ZeroDivisionError:
280
+ pass
281
+ different_ids.append(approx_key)
282
+
283
+ message_data = [
284
+ (str(key), str(other_side[key]), str(approx_side_as_map[key]))
285
+ for key in different_ids
286
+ ]
287
+
288
+ return _compare_approx(
289
+ self.expected,
290
+ message_data,
291
+ number_of_elements,
292
+ different_ids,
293
+ max_abs_diff,
294
+ max_rel_diff,
295
+ )
296
+
297
+ def __eq__(self, actual) -> bool:
298
+ try:
299
+ if set(actual.keys()) != set(self.expected.keys()):
300
+ return False
301
+ except AttributeError:
302
+ return False
303
+
304
+ return super().__eq__(actual)
305
+
306
+ def _yield_comparisons(self, actual):
307
+ for k in self.expected.keys():
308
+ yield actual[k], self.expected[k]
309
+
310
+ def _check_type(self) -> None:
311
+ __tracebackhide__ = True
312
+ for key, value in self.expected.items():
313
+ if isinstance(value, type(self.expected)):
314
+ msg = "pytest.approx() does not support nested dictionaries: key={!r} value={!r}\n full mapping={}"
315
+ raise TypeError(msg.format(key, value, pprint.pformat(self.expected)))
316
+
317
+
318
+ class ApproxSequenceLike(ApproxBase):
319
+ """Perform approximate comparisons where the expected value is a sequence of numbers."""
320
+
321
+ def __repr__(self) -> str:
322
+ seq_type = type(self.expected)
323
+ if seq_type not in (tuple, list):
324
+ seq_type = list
325
+ return f"approx({seq_type(self._approx_scalar(x) for x in self.expected)!r})"
326
+
327
+ def _repr_compare(self, other_side: Sequence[float]) -> list[str]:
328
+ import math
329
+
330
+ if len(self.expected) != len(other_side):
331
+ return [
332
+ "Impossible to compare lists with different sizes.",
333
+ f"Lengths: {len(self.expected)} and {len(other_side)}",
334
+ ]
335
+
336
+ approx_side_as_map = _recursive_sequence_map(self._approx_scalar, self.expected)
337
+
338
+ number_of_elements = len(approx_side_as_map)
339
+ max_abs_diff = -math.inf
340
+ max_rel_diff = -math.inf
341
+ different_ids = []
342
+ for i, (approx_value, other_value) in enumerate(
343
+ zip(approx_side_as_map, other_side)
344
+ ):
345
+ if approx_value != other_value:
346
+ abs_diff = abs(approx_value.expected - other_value)
347
+ max_abs_diff = max(max_abs_diff, abs_diff)
348
+ if other_value == 0.0:
349
+ max_rel_diff = math.inf
350
+ else:
351
+ max_rel_diff = max(max_rel_diff, abs_diff / abs(other_value))
352
+ different_ids.append(i)
353
+
354
+ message_data = [
355
+ (str(i), str(other_side[i]), str(approx_side_as_map[i]))
356
+ for i in different_ids
357
+ ]
358
+
359
+ return _compare_approx(
360
+ self.expected,
361
+ message_data,
362
+ number_of_elements,
363
+ different_ids,
364
+ max_abs_diff,
365
+ max_rel_diff,
366
+ )
367
+
368
+ def __eq__(self, actual) -> bool:
369
+ try:
370
+ if len(actual) != len(self.expected):
371
+ return False
372
+ except TypeError:
373
+ return False
374
+ return super().__eq__(actual)
375
+
376
+ def _yield_comparisons(self, actual):
377
+ return zip(actual, self.expected)
378
+
379
+ def _check_type(self) -> None:
380
+ __tracebackhide__ = True
381
+ for index, x in enumerate(self.expected):
382
+ if isinstance(x, type(self.expected)):
383
+ msg = "pytest.approx() does not support nested data structures: {!r} at index {}\n full sequence: {}"
384
+ raise TypeError(msg.format(x, index, pprint.pformat(self.expected)))
385
+
386
+
387
+ class ApproxScalar(ApproxBase):
388
+ """Perform approximate comparisons where the expected value is a single number."""
389
+
390
+ # Using Real should be better than this Union, but not possible yet:
391
+ # https://github.com/python/typeshed/pull/3108
392
+ DEFAULT_ABSOLUTE_TOLERANCE: float | Decimal = 1e-12
393
+ DEFAULT_RELATIVE_TOLERANCE: float | Decimal = 1e-6
394
+
395
+ def __repr__(self) -> str:
396
+ """Return a string communicating both the expected value and the
397
+ tolerance for the comparison being made.
398
+
399
+ For example, ``1.0 ± 1e-6``, ``(3+4j) ± 5e-6 ∠ ±180°``.
400
+ """
401
+ # Don't show a tolerance for values that aren't compared using
402
+ # tolerances, i.e. non-numerics and infinities. Need to call abs to
403
+ # handle complex numbers, e.g. (inf + 1j).
404
+ if (
405
+ isinstance(self.expected, bool)
406
+ or (not isinstance(self.expected, (Complex, Decimal)))
407
+ or math.isinf(abs(self.expected) or isinstance(self.expected, bool))
408
+ ):
409
+ return str(self.expected)
410
+
411
+ # If a sensible tolerance can't be calculated, self.tolerance will
412
+ # raise a ValueError. In this case, display '???'.
413
+ try:
414
+ vetted_tolerance = f"{self.tolerance:.1e}"
415
+ if (
416
+ isinstance(self.expected, Complex)
417
+ and self.expected.imag
418
+ and not math.isinf(self.tolerance)
419
+ ):
420
+ vetted_tolerance += " ∠ ±180°"
421
+ except ValueError:
422
+ vetted_tolerance = "???"
423
+
424
+ return f"{self.expected} ± {vetted_tolerance}"
425
+
426
+ def __eq__(self, actual) -> bool:
427
+ """Return whether the given value is equal to the expected value
428
+ within the pre-specified tolerance."""
429
+ asarray = _as_numpy_array(actual)
430
+ if asarray is not None:
431
+ # Call ``__eq__()`` manually to prevent infinite-recursion with
432
+ # numpy<1.13. See #3748.
433
+ return all(self.__eq__(a) for a in asarray.flat)
434
+
435
+ # Short-circuit exact equality, except for bool
436
+ if isinstance(self.expected, bool) and not isinstance(actual, bool):
437
+ return False
438
+ elif actual == self.expected:
439
+ return True
440
+
441
+ # If either type is non-numeric, fall back to strict equality.
442
+ # NB: we need Complex, rather than just Number, to ensure that __abs__,
443
+ # __sub__, and __float__ are defined. Also, consider bool to be
444
+ # nonnumeric, even though it has the required arithmetic.
445
+ if isinstance(self.expected, bool) or not (
446
+ isinstance(self.expected, (Complex, Decimal))
447
+ and isinstance(actual, (Complex, Decimal))
448
+ ):
449
+ return False
450
+
451
+ # Allow the user to control whether NaNs are considered equal to each
452
+ # other or not. The abs() calls are for compatibility with complex
453
+ # numbers.
454
+ if math.isnan(abs(self.expected)):
455
+ return self.nan_ok and math.isnan(abs(actual))
456
+
457
+ # Infinity shouldn't be approximately equal to anything but itself, but
458
+ # if there's a relative tolerance, it will be infinite and infinity
459
+ # will seem approximately equal to everything. The equal-to-itself
460
+ # case would have been short circuited above, so here we can just
461
+ # return false if the expected value is infinite. The abs() call is
462
+ # for compatibility with complex numbers.
463
+ if math.isinf(abs(self.expected)):
464
+ return False
465
+
466
+ # Return true if the two numbers are within the tolerance.
467
+ result: bool = abs(self.expected - actual) <= self.tolerance
468
+ return result
469
+
470
+ # Ignore type because of https://github.com/python/mypy/issues/4266.
471
+ __hash__ = None # type: ignore
472
+
473
+ @property
474
+ def tolerance(self):
475
+ """Return the tolerance for the comparison.
476
+
477
+ This could be either an absolute tolerance or a relative tolerance,
478
+ depending on what the user specified or which would be larger.
479
+ """
480
+
481
+ def set_default(x, default):
482
+ return x if x is not None else default
483
+
484
+ # Figure out what the absolute tolerance should be. ``self.abs`` is
485
+ # either None or a value specified by the user.
486
+ absolute_tolerance = set_default(self.abs, self.DEFAULT_ABSOLUTE_TOLERANCE)
487
+
488
+ if absolute_tolerance < 0:
489
+ raise ValueError(
490
+ f"absolute tolerance can't be negative: {absolute_tolerance}"
491
+ )
492
+ if math.isnan(absolute_tolerance):
493
+ raise ValueError("absolute tolerance can't be NaN.")
494
+
495
+ # If the user specified an absolute tolerance but not a relative one,
496
+ # just return the absolute tolerance.
497
+ if self.rel is None:
498
+ if self.abs is not None:
499
+ return absolute_tolerance
500
+
501
+ # Figure out what the relative tolerance should be. ``self.rel`` is
502
+ # either None or a value specified by the user. This is done after
503
+ # we've made sure the user didn't ask for an absolute tolerance only,
504
+ # because we don't want to raise errors about the relative tolerance if
505
+ # we aren't even going to use it.
506
+ relative_tolerance = set_default(
507
+ self.rel, self.DEFAULT_RELATIVE_TOLERANCE
508
+ ) * abs(self.expected)
509
+
510
+ if relative_tolerance < 0:
511
+ raise ValueError(
512
+ f"relative tolerance can't be negative: {relative_tolerance}"
513
+ )
514
+ if math.isnan(relative_tolerance):
515
+ raise ValueError("relative tolerance can't be NaN.")
516
+
517
+ # Return the larger of the relative and absolute tolerances.
518
+ return max(relative_tolerance, absolute_tolerance)
519
+
520
+
521
+ class ApproxDecimal(ApproxScalar):
522
+ """Perform approximate comparisons where the expected value is a Decimal."""
523
+
524
+ DEFAULT_ABSOLUTE_TOLERANCE = Decimal("1e-12")
525
+ DEFAULT_RELATIVE_TOLERANCE = Decimal("1e-6")
526
+
527
+
528
+ def approx(expected, rel=None, abs=None, nan_ok: bool = False) -> ApproxBase:
529
+ """Assert that two numbers (or two ordered sequences of numbers) are equal to each other
530
+ within some tolerance.
531
+
532
+ Due to the :doc:`python:tutorial/floatingpoint`, numbers that we
533
+ would intuitively expect to be equal are not always so::
534
+
535
+ >>> 0.1 + 0.2 == 0.3
536
+ False
537
+
538
+ This problem is commonly encountered when writing tests, e.g. when making
539
+ sure that floating-point values are what you expect them to be. One way to
540
+ deal with this problem is to assert that two floating-point numbers are
541
+ equal to within some appropriate tolerance::
542
+
543
+ >>> abs((0.1 + 0.2) - 0.3) < 1e-6
544
+ True
545
+
546
+ However, comparisons like this are tedious to write and difficult to
547
+ understand. Furthermore, absolute comparisons like the one above are
548
+ usually discouraged because there's no tolerance that works well for all
549
+ situations. ``1e-6`` is good for numbers around ``1``, but too small for
550
+ very big numbers and too big for very small ones. It's better to express
551
+ the tolerance as a fraction of the expected value, but relative comparisons
552
+ like that are even more difficult to write correctly and concisely.
553
+
554
+ The ``approx`` class performs floating-point comparisons using a syntax
555
+ that's as intuitive as possible::
556
+
557
+ >>> from pytest import approx
558
+ >>> 0.1 + 0.2 == approx(0.3)
559
+ True
560
+
561
+ The same syntax also works for ordered sequences of numbers::
562
+
563
+ >>> (0.1 + 0.2, 0.2 + 0.4) == approx((0.3, 0.6))
564
+ True
565
+
566
+ ``numpy`` arrays::
567
+
568
+ >>> import numpy as np # doctest: +SKIP
569
+ >>> np.array([0.1, 0.2]) + np.array([0.2, 0.4]) == approx(np.array([0.3, 0.6])) # doctest: +SKIP
570
+ True
571
+
572
+ And for a ``numpy`` array against a scalar::
573
+
574
+ >>> import numpy as np # doctest: +SKIP
575
+ >>> np.array([0.1, 0.2]) + np.array([0.2, 0.1]) == approx(0.3) # doctest: +SKIP
576
+ True
577
+
578
+ Only ordered sequences are supported, because ``approx`` needs
579
+ to infer the relative position of the sequences without ambiguity. This means
580
+ ``sets`` and other unordered sequences are not supported.
581
+
582
+ Finally, dictionary *values* can also be compared::
583
+
584
+ >>> {'a': 0.1 + 0.2, 'b': 0.2 + 0.4} == approx({'a': 0.3, 'b': 0.6})
585
+ True
586
+
587
+ The comparison will be true if both mappings have the same keys and their
588
+ respective values match the expected tolerances.
589
+
590
+ **Tolerances**
591
+
592
+ By default, ``approx`` considers numbers within a relative tolerance of
593
+ ``1e-6`` (i.e. one part in a million) of its expected value to be equal.
594
+ This treatment would lead to surprising results if the expected value was
595
+ ``0.0``, because nothing but ``0.0`` itself is relatively close to ``0.0``.
596
+ To handle this case less surprisingly, ``approx`` also considers numbers
597
+ within an absolute tolerance of ``1e-12`` of its expected value to be
598
+ equal. Infinity and NaN are special cases. Infinity is only considered
599
+ equal to itself, regardless of the relative tolerance. NaN is not
600
+ considered equal to anything by default, but you can make it be equal to
601
+ itself by setting the ``nan_ok`` argument to True. (This is meant to
602
+ facilitate comparing arrays that use NaN to mean "no data".)
603
+
604
+ Both the relative and absolute tolerances can be changed by passing
605
+ arguments to the ``approx`` constructor::
606
+
607
+ >>> 1.0001 == approx(1)
608
+ False
609
+ >>> 1.0001 == approx(1, rel=1e-3)
610
+ True
611
+ >>> 1.0001 == approx(1, abs=1e-3)
612
+ True
613
+
614
+ If you specify ``abs`` but not ``rel``, the comparison will not consider
615
+ the relative tolerance at all. In other words, two numbers that are within
616
+ the default relative tolerance of ``1e-6`` will still be considered unequal
617
+ if they exceed the specified absolute tolerance. If you specify both
618
+ ``abs`` and ``rel``, the numbers will be considered equal if either
619
+ tolerance is met::
620
+
621
+ >>> 1 + 1e-8 == approx(1)
622
+ True
623
+ >>> 1 + 1e-8 == approx(1, abs=1e-12)
624
+ False
625
+ >>> 1 + 1e-8 == approx(1, rel=1e-6, abs=1e-12)
626
+ True
627
+
628
+ You can also use ``approx`` to compare nonnumeric types, or dicts and
629
+ sequences containing nonnumeric types, in which case it falls back to
630
+ strict equality. This can be useful for comparing dicts and sequences that
631
+ can contain optional values::
632
+
633
+ >>> {"required": 1.0000005, "optional": None} == approx({"required": 1, "optional": None})
634
+ True
635
+ >>> [None, 1.0000005] == approx([None,1])
636
+ True
637
+ >>> ["foo", 1.0000005] == approx([None,1])
638
+ False
639
+
640
+ If you're thinking about using ``approx``, then you might want to know how
641
+ it compares to other good ways of comparing floating-point numbers. All of
642
+ these algorithms are based on relative and absolute tolerances and should
643
+ agree for the most part, but they do have meaningful differences:
644
+
645
+ - ``math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)``: True if the relative
646
+ tolerance is met w.r.t. either ``a`` or ``b`` or if the absolute
647
+ tolerance is met. Because the relative tolerance is calculated w.r.t.
648
+ both ``a`` and ``b``, this test is symmetric (i.e. neither ``a`` nor
649
+ ``b`` is a "reference value"). You have to specify an absolute tolerance
650
+ if you want to compare to ``0.0`` because there is no tolerance by
651
+ default. More information: :py:func:`math.isclose`.
652
+
653
+ - ``numpy.isclose(a, b, rtol=1e-5, atol=1e-8)``: True if the difference
654
+ between ``a`` and ``b`` is less that the sum of the relative tolerance
655
+ w.r.t. ``b`` and the absolute tolerance. Because the relative tolerance
656
+ is only calculated w.r.t. ``b``, this test is asymmetric and you can
657
+ think of ``b`` as the reference value. Support for comparing sequences
658
+ is provided by :py:func:`numpy.allclose`. More information:
659
+ :std:doc:`numpy:reference/generated/numpy.isclose`.
660
+
661
+ - ``unittest.TestCase.assertAlmostEqual(a, b)``: True if ``a`` and ``b``
662
+ are within an absolute tolerance of ``1e-7``. No relative tolerance is
663
+ considered , so this function is not appropriate for very large or very
664
+ small numbers. Also, it's only available in subclasses of ``unittest.TestCase``
665
+ and it's ugly because it doesn't follow PEP8. More information:
666
+ :py:meth:`unittest.TestCase.assertAlmostEqual`.
667
+
668
+ - ``a == pytest.approx(b, rel=1e-6, abs=1e-12)``: True if the relative
669
+ tolerance is met w.r.t. ``b`` or if the absolute tolerance is met.
670
+ Because the relative tolerance is only calculated w.r.t. ``b``, this test
671
+ is asymmetric and you can think of ``b`` as the reference value. In the
672
+ special case that you explicitly specify an absolute tolerance but not a
673
+ relative tolerance, only the absolute tolerance is considered.
674
+
675
+ .. note::
676
+
677
+ ``approx`` can handle numpy arrays, but we recommend the
678
+ specialised test helpers in :std:doc:`numpy:reference/routines.testing`
679
+ if you need support for comparisons, NaNs, or ULP-based tolerances.
680
+
681
+ To match strings using regex, you can use
682
+ `Matches <https://github.com/asottile/re-assert#re_assertmatchespattern-str-args-kwargs>`_
683
+ from the
684
+ `re_assert package <https://github.com/asottile/re-assert>`_.
685
+
686
+ .. warning::
687
+
688
+ .. versionchanged:: 3.2
689
+
690
+ In order to avoid inconsistent behavior, :py:exc:`TypeError` is
691
+ raised for ``>``, ``>=``, ``<`` and ``<=`` comparisons.
692
+ The example below illustrates the problem::
693
+
694
+ assert approx(0.1) > 0.1 + 1e-10 # calls approx(0.1).__gt__(0.1 + 1e-10)
695
+ assert 0.1 + 1e-10 > approx(0.1) # calls approx(0.1).__lt__(0.1 + 1e-10)
696
+
697
+ In the second example one expects ``approx(0.1).__le__(0.1 + 1e-10)``
698
+ to be called. But instead, ``approx(0.1).__lt__(0.1 + 1e-10)`` is used to
699
+ comparison. This is because the call hierarchy of rich comparisons
700
+ follows a fixed behavior. More information: :py:meth:`object.__ge__`
701
+
702
+ .. versionchanged:: 3.7.1
703
+ ``approx`` raises ``TypeError`` when it encounters a dict value or
704
+ sequence element of nonnumeric type.
705
+
706
+ .. versionchanged:: 6.1.0
707
+ ``approx`` falls back to strict equality for nonnumeric types instead
708
+ of raising ``TypeError``.
709
+ """
710
+ # Delegate the comparison to a class that knows how to deal with the type
711
+ # of the expected value (e.g. int, float, list, dict, numpy.array, etc).
712
+ #
713
+ # The primary responsibility of these classes is to implement ``__eq__()``
714
+ # and ``__repr__()``. The former is used to actually check if some
715
+ # "actual" value is equivalent to the given expected value within the
716
+ # allowed tolerance. The latter is used to show the user the expected
717
+ # value and tolerance, in the case that a test failed.
718
+ #
719
+ # The actual logic for making approximate comparisons can be found in
720
+ # ApproxScalar, which is used to compare individual numbers. All of the
721
+ # other Approx classes eventually delegate to this class. The ApproxBase
722
+ # class provides some convenient methods and overloads, but isn't really
723
+ # essential.
724
+
725
+ __tracebackhide__ = True
726
+
727
+ if isinstance(expected, Decimal):
728
+ cls: type[ApproxBase] = ApproxDecimal
729
+ elif isinstance(expected, Mapping):
730
+ cls = ApproxMapping
731
+ elif _is_numpy_array(expected):
732
+ expected = _as_numpy_array(expected)
733
+ cls = ApproxNumpy
734
+ elif _is_sequence_like(expected):
735
+ cls = ApproxSequenceLike
736
+ elif isinstance(expected, Collection) and not isinstance(expected, (str, bytes)):
737
+ msg = f"pytest.approx() only supports ordered sequences, but got: {expected!r}"
738
+ raise TypeError(msg)
739
+ else:
740
+ cls = ApproxScalar
741
+
742
+ return cls(expected, rel, abs, nan_ok)
743
+
744
+
745
+ def _is_sequence_like(expected: object) -> bool:
746
+ return (
747
+ hasattr(expected, "__getitem__")
748
+ and isinstance(expected, Sized)
749
+ and not isinstance(expected, (str, bytes))
750
+ )
751
+
752
+
753
+ def _is_numpy_array(obj: object) -> bool:
754
+ """
755
+ Return true if the given object is implicitly convertible to ndarray,
756
+ and numpy is already imported.
757
+ """
758
+ return _as_numpy_array(obj) is not None
759
+
760
+
761
+ def _as_numpy_array(obj: object) -> ndarray | None:
762
+ """
763
+ Return an ndarray if the given object is implicitly convertible to ndarray,
764
+ and numpy is already imported, otherwise None.
765
+ """
766
+ import sys
767
+
768
+ np: Any = sys.modules.get("numpy")
769
+ if np is not None:
770
+ # avoid infinite recursion on numpy scalars, which have __array__
771
+ if np.isscalar(obj):
772
+ return None
773
+ elif isinstance(obj, np.ndarray):
774
+ return obj
775
+ elif hasattr(obj, "__array__") or hasattr("obj", "__array_interface__"):
776
+ return np.asarray(obj)
777
+ return None
778
+
779
+
780
+ # builtin pytest.raises helper
781
+
782
+ E = TypeVar("E", bound=BaseException)
783
+
784
+
785
+ @overload
786
+ def raises(
787
+ expected_exception: type[E] | tuple[type[E], ...],
788
+ *,
789
+ match: str | Pattern[str] | None = ...,
790
+ ) -> RaisesContext[E]: ...
791
+
792
+
793
+ @overload
794
+ def raises(
795
+ expected_exception: type[E] | tuple[type[E], ...],
796
+ func: Callable[..., Any],
797
+ *args: Any,
798
+ **kwargs: Any,
799
+ ) -> _pytest._code.ExceptionInfo[E]: ...
800
+
801
+
802
+ def raises(
803
+ expected_exception: type[E] | tuple[type[E], ...], *args: Any, **kwargs: Any
804
+ ) -> RaisesContext[E] | _pytest._code.ExceptionInfo[E]:
805
+ r"""Assert that a code block/function call raises an exception type, or one of its subclasses.
806
+
807
+ :param expected_exception:
808
+ The expected exception type, or a tuple if one of multiple possible
809
+ exception types are expected. Note that subclasses of the passed exceptions
810
+ will also match.
811
+
812
+ :kwparam str | re.Pattern[str] | None match:
813
+ If specified, a string containing a regular expression,
814
+ or a regular expression object, that is tested against the string
815
+ representation of the exception and its :pep:`678` `__notes__`
816
+ using :func:`re.search`.
817
+
818
+ To match a literal string that may contain :ref:`special characters
819
+ <re-syntax>`, the pattern can first be escaped with :func:`re.escape`.
820
+
821
+ (This is only used when ``pytest.raises`` is used as a context manager,
822
+ and passed through to the function otherwise.
823
+ When using ``pytest.raises`` as a function, you can use:
824
+ ``pytest.raises(Exc, func, match="passed on").match("my pattern")``.)
825
+
826
+ Use ``pytest.raises`` as a context manager, which will capture the exception of the given
827
+ type, or any of its subclasses::
828
+
829
+ >>> import pytest
830
+ >>> with pytest.raises(ZeroDivisionError):
831
+ ... 1/0
832
+
833
+ If the code block does not raise the expected exception (:class:`ZeroDivisionError` in the example
834
+ above), or no exception at all, the check will fail instead.
835
+
836
+ You can also use the keyword argument ``match`` to assert that the
837
+ exception matches a text or regex::
838
+
839
+ >>> with pytest.raises(ValueError, match='must be 0 or None'):
840
+ ... raise ValueError("value must be 0 or None")
841
+
842
+ >>> with pytest.raises(ValueError, match=r'must be \d+$'):
843
+ ... raise ValueError("value must be 42")
844
+
845
+ The ``match`` argument searches the formatted exception string, which includes any
846
+ `PEP-678 <https://peps.python.org/pep-0678/>`__ ``__notes__``:
847
+
848
+ >>> with pytest.raises(ValueError, match=r"had a note added"): # doctest: +SKIP
849
+ ... e = ValueError("value must be 42")
850
+ ... e.add_note("had a note added")
851
+ ... raise e
852
+
853
+ The context manager produces an :class:`ExceptionInfo` object which can be used to inspect the
854
+ details of the captured exception::
855
+
856
+ >>> with pytest.raises(ValueError) as exc_info:
857
+ ... raise ValueError("value must be 42")
858
+ >>> assert exc_info.type is ValueError
859
+ >>> assert exc_info.value.args[0] == "value must be 42"
860
+
861
+ .. warning::
862
+
863
+ Given that ``pytest.raises`` matches subclasses, be wary of using it to match :class:`Exception` like this::
864
+
865
+ with pytest.raises(Exception): # Careful, this will catch ANY exception raised.
866
+ some_function()
867
+
868
+ Because :class:`Exception` is the base class of almost all exceptions, it is easy for this to hide
869
+ real bugs, where the user wrote this expecting a specific exception, but some other exception is being
870
+ raised due to a bug introduced during a refactoring.
871
+
872
+ Avoid using ``pytest.raises`` to catch :class:`Exception` unless certain that you really want to catch
873
+ **any** exception raised.
874
+
875
+ .. note::
876
+
877
+ When using ``pytest.raises`` as a context manager, it's worthwhile to
878
+ note that normal context manager rules apply and that the exception
879
+ raised *must* be the final line in the scope of the context manager.
880
+ Lines of code after that, within the scope of the context manager will
881
+ not be executed. For example::
882
+
883
+ >>> value = 15
884
+ >>> with pytest.raises(ValueError) as exc_info:
885
+ ... if value > 10:
886
+ ... raise ValueError("value must be <= 10")
887
+ ... assert exc_info.type is ValueError # This will not execute.
888
+
889
+ Instead, the following approach must be taken (note the difference in
890
+ scope)::
891
+
892
+ >>> with pytest.raises(ValueError) as exc_info:
893
+ ... if value > 10:
894
+ ... raise ValueError("value must be <= 10")
895
+ ...
896
+ >>> assert exc_info.type is ValueError
897
+
898
+ **Using with** ``pytest.mark.parametrize``
899
+
900
+ When using :ref:`pytest.mark.parametrize ref`
901
+ it is possible to parametrize tests such that
902
+ some runs raise an exception and others do not.
903
+
904
+ See :ref:`parametrizing_conditional_raising` for an example.
905
+
906
+ .. seealso::
907
+
908
+ :ref:`assertraises` for more examples and detailed discussion.
909
+
910
+ **Legacy form**
911
+
912
+ It is possible to specify a callable by passing a to-be-called lambda::
913
+
914
+ >>> raises(ZeroDivisionError, lambda: 1/0)
915
+ <ExceptionInfo ...>
916
+
917
+ or you can specify an arbitrary callable with arguments::
918
+
919
+ >>> def f(x): return 1/x
920
+ ...
921
+ >>> raises(ZeroDivisionError, f, 0)
922
+ <ExceptionInfo ...>
923
+ >>> raises(ZeroDivisionError, f, x=0)
924
+ <ExceptionInfo ...>
925
+
926
+ The form above is fully supported but discouraged for new code because the
927
+ context manager form is regarded as more readable and less error-prone.
928
+
929
+ .. note::
930
+ Similar to caught exception objects in Python, explicitly clearing
931
+ local references to returned ``ExceptionInfo`` objects can
932
+ help the Python interpreter speed up its garbage collection.
933
+
934
+ Clearing those references breaks a reference cycle
935
+ (``ExceptionInfo`` --> caught exception --> frame stack raising
936
+ the exception --> current frame stack --> local variables -->
937
+ ``ExceptionInfo``) which makes Python keep all objects referenced
938
+ from that cycle (including all local variables in the current
939
+ frame) alive until the next cyclic garbage collection run.
940
+ More detailed information can be found in the official Python
941
+ documentation for :ref:`the try statement <python:try>`.
942
+ """
943
+ __tracebackhide__ = True
944
+
945
+ if not expected_exception:
946
+ raise ValueError(
947
+ f"Expected an exception type or a tuple of exception types, but got `{expected_exception!r}`. "
948
+ f"Raising exceptions is already understood as failing the test, so you don't need "
949
+ f"any special code to say 'this should never raise an exception'."
950
+ )
951
+ if isinstance(expected_exception, type):
952
+ expected_exceptions: tuple[type[E], ...] = (expected_exception,)
953
+ else:
954
+ expected_exceptions = expected_exception
955
+ for exc in expected_exceptions:
956
+ if not isinstance(exc, type) or not issubclass(exc, BaseException):
957
+ msg = "expected exception must be a BaseException type, not {}" # type: ignore[unreachable]
958
+ not_a = exc.__name__ if isinstance(exc, type) else type(exc).__name__
959
+ raise TypeError(msg.format(not_a))
960
+
961
+ message = f"DID NOT RAISE {expected_exception}"
962
+
963
+ if not args:
964
+ match: str | Pattern[str] | None = kwargs.pop("match", None)
965
+ if kwargs:
966
+ msg = "Unexpected keyword arguments passed to pytest.raises: "
967
+ msg += ", ".join(sorted(kwargs))
968
+ msg += "\nUse context-manager form instead?"
969
+ raise TypeError(msg)
970
+ return RaisesContext(expected_exception, message, match)
971
+ else:
972
+ func = args[0]
973
+ if not callable(func):
974
+ raise TypeError(f"{func!r} object (type: {type(func)}) must be callable")
975
+ try:
976
+ func(*args[1:], **kwargs)
977
+ except expected_exception as e:
978
+ return _pytest._code.ExceptionInfo.from_exception(e)
979
+ fail(message)
980
+
981
+
982
+ # This doesn't work with mypy for now. Use fail.Exception instead.
983
+ raises.Exception = fail.Exception # type: ignore
984
+
985
+
986
+ @final
987
+ class RaisesContext(ContextManager[_pytest._code.ExceptionInfo[E]]):
988
+ def __init__(
989
+ self,
990
+ expected_exception: type[E] | tuple[type[E], ...],
991
+ message: str,
992
+ match_expr: str | Pattern[str] | None = None,
993
+ ) -> None:
994
+ self.expected_exception = expected_exception
995
+ self.message = message
996
+ self.match_expr = match_expr
997
+ self.excinfo: _pytest._code.ExceptionInfo[E] | None = None
998
+ if self.match_expr is not None:
999
+ re_error = None
1000
+ try:
1001
+ re.compile(self.match_expr)
1002
+ except re.error as e:
1003
+ re_error = e
1004
+ if re_error is not None:
1005
+ fail(f"Invalid regex pattern provided to 'match': {re_error}")
1006
+
1007
+ def __enter__(self) -> _pytest._code.ExceptionInfo[E]:
1008
+ self.excinfo = _pytest._code.ExceptionInfo.for_later()
1009
+ return self.excinfo
1010
+
1011
+ def __exit__(
1012
+ self,
1013
+ exc_type: type[BaseException] | None,
1014
+ exc_val: BaseException | None,
1015
+ exc_tb: TracebackType | None,
1016
+ ) -> bool:
1017
+ __tracebackhide__ = True
1018
+ if exc_type is None:
1019
+ fail(self.message)
1020
+ assert self.excinfo is not None
1021
+ if not issubclass(exc_type, self.expected_exception):
1022
+ return False
1023
+ # Cast to narrow the exception type now that it's verified.
1024
+ exc_info = cast(Tuple[Type[E], E, TracebackType], (exc_type, exc_val, exc_tb))
1025
+ self.excinfo.fill_unfilled(exc_info)
1026
+ if self.match_expr is not None:
1027
+ self.excinfo.match(self.match_expr)
1028
+ return True
vllm/lib/python3.10/site-packages/_pytest/python_path.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+
5
+ import pytest
6
+ from pytest import Config
7
+ from pytest import Parser
8
+
9
+
10
+ def pytest_addoption(parser: Parser) -> None:
11
+ parser.addini("pythonpath", type="paths", help="Add paths to sys.path", default=[])
12
+
13
+
14
+ @pytest.hookimpl(tryfirst=True)
15
+ def pytest_load_initial_conftests(early_config: Config) -> None:
16
+ # `pythonpath = a b` will set `sys.path` to `[a, b, x, y, z, ...]`
17
+ for path in reversed(early_config.getini("pythonpath")):
18
+ sys.path.insert(0, str(path))
19
+
20
+
21
+ @pytest.hookimpl(trylast=True)
22
+ def pytest_unconfigure(config: Config) -> None:
23
+ for path in config.getini("pythonpath"):
24
+ path_str = str(path)
25
+ if path_str in sys.path:
26
+ sys.path.remove(path_str)