2Btainment commited on
Commit
335d704
·
verified ·
1 Parent(s): 1cfc10d

feat(ui): central live preview SPACE + iframe/proxy hardening

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