ADAPT-Chase commited on
Commit
551221d
·
verified ·
1 Parent(s): fd357f4

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +27 -0
  2. platform/dataops/dto/.venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/INSTALLER +1 -0
  3. platform/dataops/dto/.venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/LICENSE.txt +28 -0
  4. platform/dataops/dto/.venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/METADATA +92 -0
  5. platform/dataops/dto/.venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/RECORD +14 -0
  6. platform/dataops/dto/.venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/WHEEL +6 -0
  7. platform/dataops/dto/.venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/top_level.txt +1 -0
  8. platform/dataops/dto/.venv/lib/python3.12/site-packages/PyNaCl-1.5.0.dist-info/INSTALLER +1 -0
  9. platform/dataops/dto/.venv/lib/python3.12/site-packages/PyNaCl-1.5.0.dist-info/LICENSE +174 -0
  10. platform/dataops/dto/.venv/lib/python3.12/site-packages/PyNaCl-1.5.0.dist-info/METADATA +245 -0
  11. platform/dataops/dto/.venv/lib/python3.12/site-packages/PyNaCl-1.5.0.dist-info/RECORD +68 -0
  12. platform/dataops/dto/.venv/lib/python3.12/site-packages/PyNaCl-1.5.0.dist-info/WHEEL +7 -0
  13. platform/dataops/dto/.venv/lib/python3.12/site-packages/PyNaCl-1.5.0.dist-info/top_level.txt +2 -0
  14. platform/dataops/dto/.venv/lib/python3.12/site-packages/PyYAML-6.0.1.dist-info/INSTALLER +1 -0
  15. platform/dataops/dto/.venv/lib/python3.12/site-packages/PyYAML-6.0.1.dist-info/LICENSE +20 -0
  16. platform/dataops/dto/.venv/lib/python3.12/site-packages/PyYAML-6.0.1.dist-info/METADATA +46 -0
  17. platform/dataops/dto/.venv/lib/python3.12/site-packages/PyYAML-6.0.1.dist-info/RECORD +44 -0
  18. platform/dataops/dto/.venv/lib/python3.12/site-packages/PyYAML-6.0.1.dist-info/REQUESTED +0 -0
  19. platform/dataops/dto/.venv/lib/python3.12/site-packages/PyYAML-6.0.1.dist-info/WHEEL +6 -0
  20. platform/dataops/dto/.venv/lib/python3.12/site-packages/PyYAML-6.0.1.dist-info/top_level.txt +2 -0
  21. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__init__.py +9 -0
  22. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_argcomplete.py +116 -0
  23. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_version.py +16 -0
  24. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/cacheprovider.py +602 -0
  25. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/capture.py +1082 -0
  26. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/compat.py +435 -0
  27. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/debugging.py +391 -0
  28. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/deprecated.py +146 -0
  29. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/doctest.py +771 -0
  30. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/faulthandler.py +94 -0
  31. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/fixtures.py +1713 -0
  32. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/freeze_support.py +44 -0
  33. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/helpconfig.py +270 -0
  34. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/hookspec.py +979 -0
  35. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/junitxml.py +700 -0
  36. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/legacypath.py +479 -0
  37. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/logging.py +920 -0
  38. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/main.py +913 -0
  39. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/monkeypatch.py +421 -0
  40. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/nodes.py +783 -0
  41. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/nose.py +50 -0
  42. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/outcomes.py +311 -0
  43. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/pastebin.py +110 -0
  44. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/pathlib.py +804 -0
  45. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/py.typed +0 -0
  46. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/pytester.py +1789 -0
  47. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/pytester_assertions.py +75 -0
  48. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/python.py +1843 -0
  49. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/python_api.py +996 -0
  50. platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/python_path.py +24 -0
.gitattributes CHANGED
@@ -3260,3 +3260,30 @@ platform/dataops/dto/.venv/lib/python3.12/site-packages/nacl/_sodium.abi3.so fil
3260
  platform/dataops/dto/.venv/lib/python3.12/site-packages/__pycache__/typing_extensions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
3261
  platform/dataops/dto/.venv/lib/python3.12/site-packages/rpds/rpds.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3262
  platform/dataops/dto/.venv/lib/python3.12/site-packages/regex/_regex.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3260
  platform/dataops/dto/.venv/lib/python3.12/site-packages/__pycache__/typing_extensions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
3261
  platform/dataops/dto/.venv/lib/python3.12/site-packages/rpds/rpds.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3262
  platform/dataops/dto/.venv/lib/python3.12/site-packages/regex/_regex.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3263
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/yaml/_yaml.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3264
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/propcache/_helpers_c.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3265
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/numpy.libs/libopenblas64_p-r0-0cf96a72.3.23.dev.so filter=lfs diff=lfs merge=lfs -text
3266
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/numpy.libs/libquadmath-96973f99.so.0.0.0 filter=lfs diff=lfs merge=lfs -text
3267
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/numpy.libs/libgfortran-040039e1.so.5.0.0 filter=lfs diff=lfs merge=lfs -text
3268
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/multidict/_multidict.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3269
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/frozenlist/_frozenlist.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3270
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/coverage/tracer.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3271
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/charset_normalizer/md__mypyc.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3272
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/bcrypt/_bcrypt.abi3.so filter=lfs diff=lfs merge=lfs -text
3273
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/global.dat filter=lfs diff=lfs merge=lfs -text
3274
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/yarl/_quoting_c.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3275
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/pool.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3276
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/deserializers.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3277
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/c_shard_info.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3278
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cqltypes.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3279
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/concurrent.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3280
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/obj_parser.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3281
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/row_parser.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3282
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/connection.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3283
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/query.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3284
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/metadata.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3285
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/numpy_parser.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3286
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/parsing.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3287
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cluster.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3288
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/util.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3289
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/protocol.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
platform/dataops/dto/.venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
platform/dataops/dto/.venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/LICENSE.txt ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2010 Pallets
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are
5
+ met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+
10
+ 2. Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+
14
+ 3. Neither the name of the copyright holder nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
21
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
24
+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
platform/dataops/dto/.venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/METADATA ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: MarkupSafe
3
+ Version: 3.0.2
4
+ Summary: Safely add untrusted strings to HTML/XML markup.
5
+ Maintainer-email: Pallets <contact@palletsprojects.com>
6
+ License: Copyright 2010 Pallets
7
+
8
+ Redistribution and use in source and binary forms, with or without
9
+ modification, are permitted provided that the following conditions are
10
+ met:
11
+
12
+ 1. Redistributions of source code must retain the above copyright
13
+ notice, this list of conditions and the following disclaimer.
14
+
15
+ 2. Redistributions in binary form must reproduce the above copyright
16
+ notice, this list of conditions and the following disclaimer in the
17
+ documentation and/or other materials provided with the distribution.
18
+
19
+ 3. Neither the name of the copyright holder nor the names of its
20
+ contributors may be used to endorse or promote products derived from
21
+ this software without specific prior written permission.
22
+
23
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
26
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29
+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34
+
35
+ Project-URL: Donate, https://palletsprojects.com/donate
36
+ Project-URL: Documentation, https://markupsafe.palletsprojects.com/
37
+ Project-URL: Changes, https://markupsafe.palletsprojects.com/changes/
38
+ Project-URL: Source, https://github.com/pallets/markupsafe/
39
+ Project-URL: Chat, https://discord.gg/pallets
40
+ Classifier: Development Status :: 5 - Production/Stable
41
+ Classifier: Environment :: Web Environment
42
+ Classifier: Intended Audience :: Developers
43
+ Classifier: License :: OSI Approved :: BSD License
44
+ Classifier: Operating System :: OS Independent
45
+ Classifier: Programming Language :: Python
46
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
47
+ Classifier: Topic :: Text Processing :: Markup :: HTML
48
+ Classifier: Typing :: Typed
49
+ Requires-Python: >=3.9
50
+ Description-Content-Type: text/markdown
51
+ License-File: LICENSE.txt
52
+
53
+ # MarkupSafe
54
+
55
+ MarkupSafe implements a text object that escapes characters so it is
56
+ safe to use in HTML and XML. Characters that have special meanings are
57
+ replaced so that they display as the actual characters. This mitigates
58
+ injection attacks, meaning untrusted user input can safely be displayed
59
+ on a page.
60
+
61
+
62
+ ## Examples
63
+
64
+ ```pycon
65
+ >>> from markupsafe import Markup, escape
66
+
67
+ >>> # escape replaces special characters and wraps in Markup
68
+ >>> escape("<script>alert(document.cookie);</script>")
69
+ Markup('&lt;script&gt;alert(document.cookie);&lt;/script&gt;')
70
+
71
+ >>> # wrap in Markup to mark text "safe" and prevent escaping
72
+ >>> Markup("<strong>Hello</strong>")
73
+ Markup('<strong>hello</strong>')
74
+
75
+ >>> escape(Markup("<strong>Hello</strong>"))
76
+ Markup('<strong>hello</strong>')
77
+
78
+ >>> # Markup is a str subclass
79
+ >>> # methods and operators escape their arguments
80
+ >>> template = Markup("Hello <em>{name}</em>")
81
+ >>> template.format(name='"World"')
82
+ Markup('Hello <em>&#34;World&#34;</em>')
83
+ ```
84
+
85
+ ## Donate
86
+
87
+ The Pallets organization develops and supports MarkupSafe and other
88
+ popular packages. In order to grow the community of contributors and
89
+ users, and allow the maintainers to devote more time to the projects,
90
+ [please donate today][].
91
+
92
+ [please donate today]: https://palletsprojects.com/donate
platform/dataops/dto/.venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/RECORD ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MarkupSafe-3.0.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ MarkupSafe-3.0.2.dist-info/LICENSE.txt,sha256=SJqOEQhQntmKN7uYPhHg9-HTHwvY-Zp5yESOf_N9B-o,1475
3
+ MarkupSafe-3.0.2.dist-info/METADATA,sha256=aAwbZhSmXdfFuMM-rEHpeiHRkBOGESyVLJIuwzHP-nw,3975
4
+ MarkupSafe-3.0.2.dist-info/RECORD,,
5
+ MarkupSafe-3.0.2.dist-info/WHEEL,sha256=OVgtqZzfzIXXtylXP90gxCZ6CKBCwKYyHM8PpMEjN1M,151
6
+ MarkupSafe-3.0.2.dist-info/top_level.txt,sha256=qy0Plje5IJuvsCBjejJyhDCjEAdcDLK_2agVcex8Z6U,11
7
+ markupsafe/__init__.py,sha256=sr-U6_27DfaSrj5jnHYxWN-pvhM27sjlDplMDPZKm7k,13214
8
+ markupsafe/__pycache__/__init__.cpython-312.pyc,,
9
+ markupsafe/__pycache__/_native.cpython-312.pyc,,
10
+ markupsafe/_native.py,sha256=hSLs8Jmz5aqayuengJJ3kdT5PwNpBWpKrmQSdipndC8,210
11
+ markupsafe/_speedups.c,sha256=O7XulmTo-epI6n2FtMVOrJXl8EAaIwD2iNYmBI5SEoQ,4149
12
+ markupsafe/_speedups.cpython-312-x86_64-linux-gnu.so,sha256=t1DBZlpsjFA30BOOvXfXfT1wvO_4cS16VbHz1-49q5U,43432
13
+ markupsafe/_speedups.pyi,sha256=ENd1bYe7gbBUf2ywyYWOGUpnXOHNJ-cgTNqetlW8h5k,41
14
+ markupsafe/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
platform/dataops/dto/.venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.2.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp312-cp312-manylinux_2_17_x86_64
5
+ Tag: cp312-cp312-manylinux2014_x86_64
6
+
platform/dataops/dto/.venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ markupsafe
platform/dataops/dto/.venv/lib/python3.12/site-packages/PyNaCl-1.5.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
platform/dataops/dto/.venv/lib/python3.12/site-packages/PyNaCl-1.5.0.dist-info/LICENSE ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
platform/dataops/dto/.venv/lib/python3.12/site-packages/PyNaCl-1.5.0.dist-info/METADATA ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: PyNaCl
3
+ Version: 1.5.0
4
+ Summary: Python binding to the Networking and Cryptography (NaCl) library
5
+ Home-page: https://github.com/pyca/pynacl/
6
+ Author: The PyNaCl developers
7
+ Author-email: cryptography-dev@python.org
8
+ License: Apache License 2.0
9
+ Platform: UNKNOWN
10
+ Classifier: Programming Language :: Python :: Implementation :: CPython
11
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.6
14
+ Classifier: Programming Language :: Python :: 3.7
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Requires-Python: >=3.6
19
+ Requires-Dist: cffi (>=1.4.1)
20
+ Provides-Extra: docs
21
+ Requires-Dist: sphinx (>=1.6.5) ; extra == 'docs'
22
+ Requires-Dist: sphinx-rtd-theme ; extra == 'docs'
23
+ Provides-Extra: tests
24
+ Requires-Dist: pytest (!=3.3.0,>=3.2.1) ; extra == 'tests'
25
+ Requires-Dist: hypothesis (>=3.27.0) ; extra == 'tests'
26
+
27
+ ===============================================
28
+ PyNaCl: Python binding to the libsodium library
29
+ ===============================================
30
+
31
+ .. image:: https://img.shields.io/pypi/v/pynacl.svg
32
+ :target: https://pypi.org/project/PyNaCl/
33
+ :alt: Latest Version
34
+
35
+ .. image:: https://codecov.io/github/pyca/pynacl/coverage.svg?branch=main
36
+ :target: https://codecov.io/github/pyca/pynacl?branch=main
37
+
38
+ .. image:: https://img.shields.io/pypi/pyversions/pynacl.svg
39
+ :target: https://pypi.org/project/PyNaCl/
40
+ :alt: Compatible Python Versions
41
+
42
+ PyNaCl is a Python binding to `libsodium`_, which is a fork of the
43
+ `Networking and Cryptography library`_. These libraries have a stated goal of
44
+ improving usability, security and speed. It supports Python 3.6+ as well as
45
+ PyPy 3.
46
+
47
+ .. _libsodium: https://github.com/jedisct1/libsodium
48
+ .. _Networking and Cryptography library: https://nacl.cr.yp.to/
49
+
50
+ Features
51
+ --------
52
+
53
+ * Digital signatures
54
+ * Secret-key encryption
55
+ * Public-key encryption
56
+ * Hashing and message authentication
57
+ * Password based key derivation and password hashing
58
+
59
+ `Changelog`_
60
+ ------------
61
+
62
+ .. _Changelog: https://pynacl.readthedocs.io/en/stable/changelog/
63
+
64
+ Installation
65
+ ============
66
+
67
+ Binary wheel install
68
+ --------------------
69
+
70
+ PyNaCl ships as a binary wheel on macOS, Windows and Linux ``manylinux1`` [#many]_ ,
71
+ so all dependencies are included. Make sure you have an up-to-date pip
72
+ and run:
73
+
74
+ .. code-block:: console
75
+
76
+ $ pip install pynacl
77
+
78
+ Faster wheel build
79
+ ------------------
80
+
81
+ You can define the environment variable ``LIBSODIUM_MAKE_ARGS`` to pass arguments to ``make``
82
+ and enable `parallelization`_:
83
+
84
+ .. code-block:: console
85
+
86
+ $ LIBSODIUM_MAKE_ARGS=-j4 pip install pynacl
87
+
88
+ Linux source build
89
+ ------------------
90
+
91
+ PyNaCl relies on `libsodium`_, a portable C library. A copy is bundled
92
+ with PyNaCl so to install you can run:
93
+
94
+ .. code-block:: console
95
+
96
+ $ pip install pynacl
97
+
98
+ If you'd prefer to use the version of ``libsodium`` provided by your
99
+ distribution, you can disable the bundled copy during install by running:
100
+
101
+ .. code-block:: console
102
+
103
+ $ SODIUM_INSTALL=system pip install pynacl
104
+
105
+ .. warning:: Usage of the legacy ``easy_install`` command provided by setuptools
106
+ is generally discouraged, and is completely unsupported in PyNaCl's case.
107
+
108
+ .. _parallelization: https://www.gnu.org/software/make/manual/html_node/Parallel.html
109
+
110
+ .. _libsodium: https://github.com/jedisct1/libsodium
111
+
112
+ .. [#many] `manylinux1 wheels <https://www.python.org/dev/peps/pep-0513/>`_
113
+ are built on a baseline linux environment based on Centos 5.11
114
+ and should work on most x86 and x86_64 glibc based linux environments.
115
+
116
+ Changelog
117
+ =========
118
+
119
+ 1.5.0 (2022-01-07)
120
+ ------------------
121
+
122
+ * **BACKWARDS INCOMPATIBLE:** Removed support for Python 2.7 and Python 3.5.
123
+ * **BACKWARDS INCOMPATIBLE:** We no longer distribute ``manylinux1``
124
+ wheels.
125
+ * Added ``manylinux2014``, ``manylinux_2_24``, ``musllinux``, and macOS
126
+ ``universal2`` wheels (the latter supports macOS ``arm64``).
127
+ * Update ``libsodium`` to 1.0.18-stable (July 25, 2021 release).
128
+ * Add inline type hints.
129
+
130
+ 1.4.0 (2020-05-25)
131
+ ------------------
132
+
133
+ * Update ``libsodium`` to 1.0.18.
134
+ * **BACKWARDS INCOMPATIBLE:** We no longer distribute 32-bit ``manylinux1``
135
+ wheels. Continuing to produce them was a maintenance burden.
136
+ * Added support for Python 3.8, and removed support for Python 3.4.
137
+ * Add low level bindings for extracting the seed and the public key
138
+ from crypto_sign_ed25519 secret key
139
+ * Add low level bindings for deterministic random generation.
140
+ * Add ``wheel`` and ``setuptools`` setup_requirements in ``setup.py`` (#485)
141
+ * Fix checks on very slow builders (#481, #495)
142
+ * Add low-level bindings to ed25519 arithmetic functions
143
+ * Update low-level blake2b state implementation
144
+ * Fix wrong short-input behavior of SealedBox.decrypt() (#517)
145
+ * Raise CryptPrefixError exception instead of InvalidkeyError when trying
146
+ to check a password against a verifier stored in a unknown format (#519)
147
+ * Add support for minimal builds of libsodium. Trying to call functions
148
+ not available in a minimal build will raise an UnavailableError
149
+ exception. To compile a minimal build of the bundled libsodium, set
150
+ the SODIUM_INSTALL_MINIMAL environment variable to any non-empty
151
+ string (e.g. ``SODIUM_INSTALL_MINIMAL=1``) for setup.
152
+
153
+ 1.3.0 2018-09-26
154
+ ----------------
155
+
156
+ * Added support for Python 3.7.
157
+ * Update ``libsodium`` to 1.0.16.
158
+ * Run and test all code examples in PyNaCl docs through sphinx's
159
+ doctest builder.
160
+ * Add low-level bindings for chacha20-poly1305 AEAD constructions.
161
+ * Add low-level bindings for the chacha20-poly1305 secretstream constructions.
162
+ * Add low-level bindings for ed25519ph pre-hashed signing construction.
163
+ * Add low-level bindings for constant-time increment and addition
164
+ on fixed-precision big integers represented as little-endian
165
+ byte sequences.
166
+ * Add low-level bindings for the ISO/IEC 7816-4 compatible padding API.
167
+ * Add low-level bindings for libsodium's crypto_kx... key exchange
168
+ construction.
169
+ * Set hypothesis deadline to None in tests/test_pwhash.py to avoid
170
+ incorrect test failures on slower processor architectures. GitHub
171
+ issue #370
172
+
173
+ 1.2.1 - 2017-12-04
174
+ ------------------
175
+
176
+ * Update hypothesis minimum allowed version.
177
+ * Infrastructure: add proper configuration for readthedocs builder
178
+ runtime environment.
179
+
180
+ 1.2.0 - 2017-11-01
181
+ ------------------
182
+
183
+ * Update ``libsodium`` to 1.0.15.
184
+ * Infrastructure: add jenkins support for automatic build of
185
+ ``manylinux1`` binary wheels
186
+ * Added support for ``SealedBox`` construction.
187
+ * Added support for ``argon2i`` and ``argon2id`` password hashing constructs
188
+ and restructured high-level password hashing implementation to expose
189
+ the same interface for all hashers.
190
+ * Added support for 128 bit ``siphashx24`` variant of ``siphash24``.
191
+ * Added support for ``from_seed`` APIs for X25519 keypair generation.
192
+ * Dropped support for Python 3.3.
193
+
194
+ 1.1.2 - 2017-03-31
195
+ ------------------
196
+
197
+ * reorder link time library search path when using bundled
198
+ libsodium
199
+
200
+ 1.1.1 - 2017-03-15
201
+ ------------------
202
+
203
+ * Fixed a circular import bug in ``nacl.utils``.
204
+
205
+ 1.1.0 - 2017-03-14
206
+ ------------------
207
+
208
+ * Dropped support for Python 2.6.
209
+ * Added ``shared_key()`` method on ``Box``.
210
+ * You can now pass ``None`` to ``nonce`` when encrypting with ``Box`` or
211
+ ``SecretBox`` and it will automatically generate a random nonce.
212
+ * Added support for ``siphash24``.
213
+ * Added support for ``blake2b``.
214
+ * Added support for ``scrypt``.
215
+ * Update ``libsodium`` to 1.0.11.
216
+ * Default to the bundled ``libsodium`` when compiling.
217
+ * All raised exceptions are defined mixing-in
218
+ ``nacl.exceptions.CryptoError``
219
+
220
+ 1.0.1 - 2016-01-24
221
+ ------------------
222
+
223
+ * Fix an issue with absolute paths that prevented the creation of wheels.
224
+
225
+ 1.0 - 2016-01-23
226
+ ----------------
227
+
228
+ * PyNaCl has been ported to use the new APIs available in cffi 1.0+.
229
+ Due to this change we no longer support PyPy releases older than 2.6.
230
+ * Python 3.2 support has been dropped.
231
+ * Functions to convert between Ed25519 and Curve25519 keys have been added.
232
+
233
+ 0.3.0 - 2015-03-04
234
+ ------------------
235
+
236
+ * The low-level API (`nacl.c.*`) has been changed to match the
237
+ upstream NaCl C/C++ conventions (as well as those of other NaCl bindings).
238
+ The order of arguments and return values has changed significantly. To
239
+ avoid silent failures, `nacl.c` has been removed, and replaced with
240
+ `nacl.bindings` (with the new argument ordering). If you have code which
241
+ calls these functions (e.g. `nacl.c.crypto_box_keypair()`), you must review
242
+ the new docstrings and update your code/imports to match the new
243
+ conventions.
244
+
245
+
platform/dataops/dto/.venv/lib/python3.12/site-packages/PyNaCl-1.5.0.dist-info/RECORD ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ PyNaCl-1.5.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ PyNaCl-1.5.0.dist-info/LICENSE,sha256=0xdK1j5yHUydzLitQyCEiZLTFDabxGMZcgtYAskVP-k,9694
3
+ PyNaCl-1.5.0.dist-info/METADATA,sha256=OJaXCiHgNRywLY9cj3X2euddUPZ4dnyyqAQMU01X4j0,8634
4
+ PyNaCl-1.5.0.dist-info/RECORD,,
5
+ PyNaCl-1.5.0.dist-info/WHEEL,sha256=TIQeZFe3DwXBO5UGlCH1aKpf5Cx6FJLbIUqd-Sq2juI,185
6
+ PyNaCl-1.5.0.dist-info/top_level.txt,sha256=wfdEOI_G2RIzmzsMyhpqP17HUh6Jcqi99to9aHLEslo,13
7
+ nacl/__init__.py,sha256=0IUunzBT8_Jn0DUdHacBExOYeAEMggo8slkfjo7O0XM,1116
8
+ nacl/__pycache__/__init__.cpython-312.pyc,,
9
+ nacl/__pycache__/encoding.cpython-312.pyc,,
10
+ nacl/__pycache__/exceptions.cpython-312.pyc,,
11
+ nacl/__pycache__/hash.cpython-312.pyc,,
12
+ nacl/__pycache__/hashlib.cpython-312.pyc,,
13
+ nacl/__pycache__/public.cpython-312.pyc,,
14
+ nacl/__pycache__/secret.cpython-312.pyc,,
15
+ nacl/__pycache__/signing.cpython-312.pyc,,
16
+ nacl/__pycache__/utils.cpython-312.pyc,,
17
+ nacl/_sodium.abi3.so,sha256=uJ6RwSnbb9wO4esR0bVUqrfFHtBOGm34IQIdmaE1fGY,2740136
18
+ nacl/bindings/__init__.py,sha256=BDlStrds2EuUS4swOL4pnf92PWVS_CHRCptX3KhEX-s,16997
19
+ nacl/bindings/__pycache__/__init__.cpython-312.pyc,,
20
+ nacl/bindings/__pycache__/crypto_aead.cpython-312.pyc,,
21
+ nacl/bindings/__pycache__/crypto_box.cpython-312.pyc,,
22
+ nacl/bindings/__pycache__/crypto_core.cpython-312.pyc,,
23
+ nacl/bindings/__pycache__/crypto_generichash.cpython-312.pyc,,
24
+ nacl/bindings/__pycache__/crypto_hash.cpython-312.pyc,,
25
+ nacl/bindings/__pycache__/crypto_kx.cpython-312.pyc,,
26
+ nacl/bindings/__pycache__/crypto_pwhash.cpython-312.pyc,,
27
+ nacl/bindings/__pycache__/crypto_scalarmult.cpython-312.pyc,,
28
+ nacl/bindings/__pycache__/crypto_secretbox.cpython-312.pyc,,
29
+ nacl/bindings/__pycache__/crypto_secretstream.cpython-312.pyc,,
30
+ nacl/bindings/__pycache__/crypto_shorthash.cpython-312.pyc,,
31
+ nacl/bindings/__pycache__/crypto_sign.cpython-312.pyc,,
32
+ nacl/bindings/__pycache__/randombytes.cpython-312.pyc,,
33
+ nacl/bindings/__pycache__/sodium_core.cpython-312.pyc,,
34
+ nacl/bindings/__pycache__/utils.cpython-312.pyc,,
35
+ nacl/bindings/crypto_aead.py,sha256=BIw1k_JCfr5ylZk0RF5rCFIM1fhfLkEa-aiWkrfffNE,15597
36
+ nacl/bindings/crypto_box.py,sha256=Ox0NG2t4MsGhBAa7Kgah4o0gc99ULMsqkdX56ofOouY,10139
37
+ nacl/bindings/crypto_core.py,sha256=6u9G3y7H-QrawO785UkFFFtwDoCkeHE63GOUl9p5-eA,13736
38
+ nacl/bindings/crypto_generichash.py,sha256=9mX0DGIIzicr-uXrqFM1nU4tirasbixDwbcdfV7W1fc,8852
39
+ nacl/bindings/crypto_hash.py,sha256=Rg1rsEwE3azhsQT-dNVPA4NB9VogJAKn1EfxYt0pPe0,2175
40
+ nacl/bindings/crypto_kx.py,sha256=oZNVlNgROpHOa1XQ_uZe0tqIkdfuApeJlRnwR23_74k,6723
41
+ nacl/bindings/crypto_pwhash.py,sha256=laVDo4xFUuGyEjtZAU510AklBF6ablBy7Z3HN1WDYjY,18848
42
+ nacl/bindings/crypto_scalarmult.py,sha256=_DX-mst2uCnzjo6fP5HRTnhv1BC95B9gmJc3L_or16g,8244
43
+ nacl/bindings/crypto_secretbox.py,sha256=KgZ1VvkCJDlQ85jtfe9c02VofPvuEgZEhWni-aX3MsM,2914
44
+ nacl/bindings/crypto_secretstream.py,sha256=G0FgZS01qA5RzWzm5Bdms8Yy_lvgdZDoUYYBActPmvQ,11165
45
+ nacl/bindings/crypto_shorthash.py,sha256=PQU7djHTLDGdVs-w_TsivjFHHp5EK5k2Yh6p-6z0T60,2603
46
+ nacl/bindings/crypto_sign.py,sha256=53j2im9E4F79qT_2U8IfCAc3lzg0VMwEjvAPEUccVDg,10342
47
+ nacl/bindings/randombytes.py,sha256=uBK3W4WcjgnjZdWanrX0fjYZpr9KHbBgNMl9rui-Ojc,1563
48
+ nacl/bindings/sodium_core.py,sha256=9Y9CX--sq-TaPaQRPRpx8SWDSS9PJOja_Cqb-yqyJNQ,1039
49
+ nacl/bindings/utils.py,sha256=KDwQnadXeNMbqEA1SmpNyCVo5k8MiUQa07QM66VzfXM,4298
50
+ nacl/encoding.py,sha256=qTAPc2MXSkdh4cqDVY0ra6kHyViHMCmEo_re7cgGk5w,2915
51
+ nacl/exceptions.py,sha256=GZH32aJtZgqCO4uz0LRsev8z0WyvAYuV3YVqT9AAQq4,2451
52
+ nacl/hash.py,sha256=EYBOe6UVc9SUQINEmyuRSa1QGRSvdwdrBzTL1tdFLU8,6392
53
+ nacl/hashlib.py,sha256=L5Fv75St8AMPvb-GhA4YqX5p1mC_Sb4HhC1NxNQMpJA,4400
54
+ nacl/public.py,sha256=RVGCWQRjIJOmW-8sNrVLtsDjMMGx30i6UyfViGCnQNA,14792
55
+ nacl/pwhash/__init__.py,sha256=XSDXd7wQHNLEHl0mkHfVb5lFQsp6ygHkhen718h0BSM,2675
56
+ nacl/pwhash/__pycache__/__init__.cpython-312.pyc,,
57
+ nacl/pwhash/__pycache__/_argon2.cpython-312.pyc,,
58
+ nacl/pwhash/__pycache__/argon2i.cpython-312.pyc,,
59
+ nacl/pwhash/__pycache__/argon2id.cpython-312.pyc,,
60
+ nacl/pwhash/__pycache__/scrypt.cpython-312.pyc,,
61
+ nacl/pwhash/_argon2.py,sha256=jL1ChR9biwYh3RSuc-LJ2-W4DlVLHpir-XHGX8cpeJQ,1779
62
+ nacl/pwhash/argon2i.py,sha256=IIvIuO9siKUu5-Wpz0SGiltLQv7Du_mi9BUE8INRK_4,4405
63
+ nacl/pwhash/argon2id.py,sha256=H22i8O4j9Ws4L3JsXl9TRcJzDcyaVumhQRPzINAgJWM,4433
64
+ nacl/pwhash/scrypt.py,sha256=fMr3Qht1a1EY8aebNNntfLRjinIPXtKYKKrrBhY5LDc,6986
65
+ nacl/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
66
+ nacl/secret.py,sha256=kauBNuP-0rb3TjU2EMBMu5Vnmzjnscp1bRqMspy5LzU,12108
67
+ nacl/signing.py,sha256=kbTEUyHLUMaNLv1nCjxzGxCs82Qs5w8gxE_CnEwPuIU,8337
68
+ nacl/utils.py,sha256=gmlTD1x9ZNwzHd8LpALH1CHud-Htv8ejRb3y7TyS9f0,2341
platform/dataops/dto/.venv/lib/python3.12/site-packages/PyNaCl-1.5.0.dist-info/WHEEL ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.37.1)
3
+ Root-Is-Purelib: false
4
+ Tag: cp36-abi3-manylinux_2_17_x86_64
5
+ Tag: cp36-abi3-manylinux2014_x86_64
6
+ Tag: cp36-abi3-manylinux_2_24_x86_64
7
+
platform/dataops/dto/.venv/lib/python3.12/site-packages/PyNaCl-1.5.0.dist-info/top_level.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ _sodium
2
+ nacl
platform/dataops/dto/.venv/lib/python3.12/site-packages/PyYAML-6.0.1.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
platform/dataops/dto/.venv/lib/python3.12/site-packages/PyYAML-6.0.1.dist-info/LICENSE ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2017-2021 Ingy döt Net
2
+ Copyright (c) 2006-2016 Kirill Simonov
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
5
+ this software and associated documentation files (the "Software"), to deal in
6
+ the Software without restriction, including without limitation the rights to
7
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8
+ of the Software, and to permit persons to whom the Software is furnished to do
9
+ so, subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ SOFTWARE.
platform/dataops/dto/.venv/lib/python3.12/site-packages/PyYAML-6.0.1.dist-info/METADATA ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: PyYAML
3
+ Version: 6.0.1
4
+ Summary: YAML parser and emitter for Python
5
+ Home-page: https://pyyaml.org/
6
+ Download-URL: https://pypi.org/project/PyYAML/
7
+ Author: Kirill Simonov
8
+ Author-email: xi@resolvent.net
9
+ License: MIT
10
+ Project-URL: Bug Tracker, https://github.com/yaml/pyyaml/issues
11
+ Project-URL: CI, https://github.com/yaml/pyyaml/actions
12
+ Project-URL: Documentation, https://pyyaml.org/wiki/PyYAMLDocumentation
13
+ Project-URL: Mailing lists, http://lists.sourceforge.net/lists/listinfo/yaml-core
14
+ Project-URL: Source Code, https://github.com/yaml/pyyaml
15
+ Platform: Any
16
+ Classifier: Development Status :: 5 - Production/Stable
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: License :: OSI Approved :: MIT License
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Programming Language :: Cython
21
+ Classifier: Programming Language :: Python
22
+ Classifier: Programming Language :: Python :: 3
23
+ Classifier: Programming Language :: Python :: 3.6
24
+ Classifier: Programming Language :: Python :: 3.7
25
+ Classifier: Programming Language :: Python :: 3.8
26
+ Classifier: Programming Language :: Python :: 3.9
27
+ Classifier: Programming Language :: Python :: 3.10
28
+ Classifier: Programming Language :: Python :: 3.11
29
+ Classifier: Programming Language :: Python :: Implementation :: CPython
30
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
31
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
32
+ Classifier: Topic :: Text Processing :: Markup
33
+ Requires-Python: >=3.6
34
+ License-File: LICENSE
35
+
36
+ YAML is a data serialization format designed for human readability
37
+ and interaction with scripting languages. PyYAML is a YAML parser
38
+ and emitter for Python.
39
+
40
+ PyYAML features a complete YAML 1.1 parser, Unicode support, pickle
41
+ support, capable extension API, and sensible error messages. PyYAML
42
+ supports standard YAML tags and provides Python-specific tags that
43
+ allow to represent an arbitrary Python object.
44
+
45
+ PyYAML is applicable for a broad range of tasks from complex
46
+ configuration files to object serialization and persistence.
platform/dataops/dto/.venv/lib/python3.12/site-packages/PyYAML-6.0.1.dist-info/RECORD ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ PyYAML-6.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ PyYAML-6.0.1.dist-info/LICENSE,sha256=jTko-dxEkP1jVwfLiOsmvXZBAqcoKVQwfT5RZ6V36KQ,1101
3
+ PyYAML-6.0.1.dist-info/METADATA,sha256=UNNF8-SzzwOKXVo-kV5lXUGH2_wDWMBmGxqISpp5HQk,2058
4
+ PyYAML-6.0.1.dist-info/RECORD,,
5
+ PyYAML-6.0.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ PyYAML-6.0.1.dist-info/WHEEL,sha256=4ZiCdXIWMxJyEClivrQv1QAHZpQh8kVYU92_ZAVwaok,152
7
+ PyYAML-6.0.1.dist-info/top_level.txt,sha256=rpj0IVMTisAjh_1vG3Ccf9v5jpCQwAz6cD1IVU5ZdhQ,11
8
+ _yaml/__init__.py,sha256=04Ae_5osxahpJHa3XBZUAf4wi6XX32gR8D6X6p64GEA,1402
9
+ _yaml/__pycache__/__init__.cpython-312.pyc,,
10
+ yaml/__init__.py,sha256=bhl05qSeO-1ZxlSRjGrvl2m9nrXb1n9-GQatTN0Mrqc,12311
11
+ yaml/__pycache__/__init__.cpython-312.pyc,,
12
+ yaml/__pycache__/composer.cpython-312.pyc,,
13
+ yaml/__pycache__/constructor.cpython-312.pyc,,
14
+ yaml/__pycache__/cyaml.cpython-312.pyc,,
15
+ yaml/__pycache__/dumper.cpython-312.pyc,,
16
+ yaml/__pycache__/emitter.cpython-312.pyc,,
17
+ yaml/__pycache__/error.cpython-312.pyc,,
18
+ yaml/__pycache__/events.cpython-312.pyc,,
19
+ yaml/__pycache__/loader.cpython-312.pyc,,
20
+ yaml/__pycache__/nodes.cpython-312.pyc,,
21
+ yaml/__pycache__/parser.cpython-312.pyc,,
22
+ yaml/__pycache__/reader.cpython-312.pyc,,
23
+ yaml/__pycache__/representer.cpython-312.pyc,,
24
+ yaml/__pycache__/resolver.cpython-312.pyc,,
25
+ yaml/__pycache__/scanner.cpython-312.pyc,,
26
+ yaml/__pycache__/serializer.cpython-312.pyc,,
27
+ yaml/__pycache__/tokens.cpython-312.pyc,,
28
+ yaml/_yaml.cpython-312-x86_64-linux-gnu.so,sha256=FDFeHFHmIrXrKTyUeQkvzmAVJ8FABnf58koZWEivTLo,2367192
29
+ yaml/composer.py,sha256=_Ko30Wr6eDWUeUpauUGT3Lcg9QPBnOPVlTnIMRGJ9FM,4883
30
+ yaml/constructor.py,sha256=kNgkfaeLUkwQYY_Q6Ff1Tz2XVw_pG1xVE9Ak7z-viLA,28639
31
+ yaml/cyaml.py,sha256=6ZrAG9fAYvdVe2FK_w0hmXoG7ZYsoYUwapG8CiC72H0,3851
32
+ yaml/dumper.py,sha256=PLctZlYwZLp7XmeUdwRuv4nYOZ2UBnDIUy8-lKfLF-o,2837
33
+ yaml/emitter.py,sha256=jghtaU7eFwg31bG0B7RZea_29Adi9CKmXq_QjgQpCkQ,43006
34
+ yaml/error.py,sha256=Ah9z-toHJUbE9j-M8YpxgSRM5CgLCcwVzJgLLRF2Fxo,2533
35
+ yaml/events.py,sha256=50_TksgQiE4up-lKo_V-nBy-tAIxkIPQxY5qDhKCeHw,2445
36
+ yaml/loader.py,sha256=UVa-zIqmkFSCIYq_PgSGm4NSJttHY2Rf_zQ4_b1fHN0,2061
37
+ yaml/nodes.py,sha256=gPKNj8pKCdh2d4gr3gIYINnPOaOxGhJAUiYhGRnPE84,1440
38
+ yaml/parser.py,sha256=ilWp5vvgoHFGzvOZDItFoGjD6D42nhlZrZyjAwa0oJo,25495
39
+ yaml/reader.py,sha256=0dmzirOiDG4Xo41RnuQS7K9rkY3xjHiVasfDMNTqCNw,6794
40
+ yaml/representer.py,sha256=IuWP-cAW9sHKEnS0gCqSa894k1Bg4cgTxaDwIcbRQ-Y,14190
41
+ yaml/resolver.py,sha256=9L-VYfm4mWHxUD1Vg4X7rjDRK_7VZd6b92wzq7Y2IKY,9004
42
+ yaml/scanner.py,sha256=YEM3iLZSaQwXcQRg2l2R4MdT0zGP2F9eHkKGKnHyWQY,51279
43
+ yaml/serializer.py,sha256=ChuFgmhU01hj4xgI8GaKv6vfM2Bujwa9i7d2FAHj7cA,4165
44
+ yaml/tokens.py,sha256=lTQIzSVw8Mg9wv459-TjiOQe6wVziqaRlqX2_89rp54,2573
platform/dataops/dto/.venv/lib/python3.12/site-packages/PyYAML-6.0.1.dist-info/REQUESTED ADDED
File without changes
platform/dataops/dto/.venv/lib/python3.12/site-packages/PyYAML-6.0.1.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.41.2)
3
+ Root-Is-Purelib: false
4
+ Tag: cp312-cp312-manylinux_2_17_x86_64
5
+ Tag: cp312-cp312-manylinux2014_x86_64
6
+
platform/dataops/dto/.venv/lib/python3.12/site-packages/PyYAML-6.0.1.dist-info/top_level.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ _yaml
2
+ yaml
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = ["__version__", "version_tuple"]
2
+
3
+ try:
4
+ from ._version import version as __version__, version_tuple
5
+ except ImportError: # pragma: no cover
6
+ # broken installation, we don't even try
7
+ # unknown only works because we do poor mans version compare
8
+ __version__ = "unknown"
9
+ version_tuple = (0, 0, "unknown") # type:ignore[assignment]
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/_argcomplete.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Allow bash-completion for argparse with argcomplete if installed.
2
+
3
+ Needs argcomplete>=0.5.6 for python 3.2/3.3 (older versions fail
4
+ to find the magic string, so _ARGCOMPLETE env. var is never set, and
5
+ this does not need special code).
6
+
7
+ Function try_argcomplete(parser) should be called directly before
8
+ the call to ArgumentParser.parse_args().
9
+
10
+ The filescompleter is what you normally would use on the positional
11
+ arguments specification, in order to get "dirname/" after "dirn<TAB>"
12
+ instead of the default "dirname ":
13
+
14
+ optparser.add_argument(Config._file_or_dir, nargs='*').completer=filescompleter
15
+
16
+ Other, application specific, completers should go in the file
17
+ doing the add_argument calls as they need to be specified as .completer
18
+ attributes as well. (If argcomplete is not installed, the function the
19
+ attribute points to will not be used).
20
+
21
+ SPEEDUP
22
+ =======
23
+
24
+ The generic argcomplete script for bash-completion
25
+ (/etc/bash_completion.d/python-argcomplete.sh)
26
+ uses a python program to determine startup script generated by pip.
27
+ You can speed up completion somewhat by changing this script to include
28
+ # PYTHON_ARGCOMPLETE_OK
29
+ so the python-argcomplete-check-easy-install-script does not
30
+ need to be called to find the entry point of the code and see if that is
31
+ marked with PYTHON_ARGCOMPLETE_OK.
32
+
33
+ INSTALL/DEBUGGING
34
+ =================
35
+
36
+ To include this support in another application that has setup.py generated
37
+ scripts:
38
+
39
+ - Add the line:
40
+ # PYTHON_ARGCOMPLETE_OK
41
+ near the top of the main python entry point.
42
+
43
+ - Include in the file calling parse_args():
44
+ from _argcomplete import try_argcomplete, filescompleter
45
+ Call try_argcomplete just before parse_args(), and optionally add
46
+ filescompleter to the positional arguments' add_argument().
47
+
48
+ If things do not work right away:
49
+
50
+ - Switch on argcomplete debugging with (also helpful when doing custom
51
+ completers):
52
+ export _ARC_DEBUG=1
53
+
54
+ - Run:
55
+ python-argcomplete-check-easy-install-script $(which appname)
56
+ echo $?
57
+ will echo 0 if the magic line has been found, 1 if not.
58
+
59
+ - Sometimes it helps to find early on errors using:
60
+ _ARGCOMPLETE=1 _ARC_DEBUG=1 appname
61
+ which should throw a KeyError: 'COMPLINE' (which is properly set by the
62
+ global argcomplete script).
63
+ """
64
+ import argparse
65
+ import os
66
+ import sys
67
+ from glob import glob
68
+ from typing import Any
69
+ from typing import List
70
+ from typing import Optional
71
+
72
+
73
+ class FastFilesCompleter:
74
+ """Fast file completer class."""
75
+
76
+ def __init__(self, directories: bool = True) -> None:
77
+ self.directories = directories
78
+
79
+ def __call__(self, prefix: str, **kwargs: Any) -> List[str]:
80
+ # Only called on non option completions.
81
+ if os.sep in prefix[1:]:
82
+ prefix_dir = len(os.path.dirname(prefix) + os.sep)
83
+ else:
84
+ prefix_dir = 0
85
+ completion = []
86
+ globbed = []
87
+ if "*" not in prefix and "?" not in prefix:
88
+ # We are on unix, otherwise no bash.
89
+ if not prefix or prefix[-1] == os.sep:
90
+ globbed.extend(glob(prefix + ".*"))
91
+ prefix += "*"
92
+ globbed.extend(glob(prefix))
93
+ for x in sorted(globbed):
94
+ if os.path.isdir(x):
95
+ x += "/"
96
+ # Append stripping the prefix (like bash, not like compgen).
97
+ completion.append(x[prefix_dir:])
98
+ return completion
99
+
100
+
101
+ if os.environ.get("_ARGCOMPLETE"):
102
+ try:
103
+ import argcomplete.completers
104
+ except ImportError:
105
+ sys.exit(-1)
106
+ filescompleter: Optional[FastFilesCompleter] = FastFilesCompleter()
107
+
108
+ def try_argcomplete(parser: argparse.ArgumentParser) -> None:
109
+ argcomplete.autocomplete(parser, always_complete_options=False)
110
+
111
+ else:
112
+
113
+ def try_argcomplete(parser: argparse.ArgumentParser) -> None:
114
+ pass
115
+
116
+ filescompleter = None
platform/dataops/dto/.venv/lib/python3.12/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 = '7.4.3'
16
+ __version_tuple__ = version_tuple = (7, 4, 3)
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/cacheprovider.py ADDED
@@ -0,0 +1,602 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of the cache provider."""
2
+ # This plugin was not named "cache" to avoid conflicts with the external
3
+ # pytest-cache version.
4
+ import dataclasses
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ from typing import Dict
9
+ from typing import Generator
10
+ from typing import Iterable
11
+ from typing import List
12
+ from typing import Optional
13
+ from typing import Set
14
+ from typing import Union
15
+
16
+ from .pathlib import resolve_from_str
17
+ from .pathlib import rm_rf
18
+ from .reports import CollectReport
19
+ from _pytest import nodes
20
+ from _pytest._io import TerminalWriter
21
+ from _pytest.compat import final
22
+ from _pytest.config import Config
23
+ from _pytest.config import ExitCode
24
+ from _pytest.config import hookimpl
25
+ from _pytest.config.argparsing import Parser
26
+ from _pytest.deprecated import check_ispytest
27
+ from _pytest.fixtures import fixture
28
+ from _pytest.fixtures import FixtureRequest
29
+ from _pytest.main import Session
30
+ from _pytest.nodes import File
31
+ from _pytest.python import Package
32
+ from _pytest.reports import TestReport
33
+
34
+ README_CONTENT = """\
35
+ # pytest cache directory #
36
+
37
+ This directory contains data from the pytest's cache plugin,
38
+ which provides the `--lf` and `--ff` options, as well as the `cache` fixture.
39
+
40
+ **Do not** commit this to version control.
41
+
42
+ See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information.
43
+ """
44
+
45
+ CACHEDIR_TAG_CONTENT = b"""\
46
+ Signature: 8a477f597d28d172789f06886806bc55
47
+ # This file is a cache directory tag created by pytest.
48
+ # For information about cache directory tags, see:
49
+ # https://bford.info/cachedir/spec.html
50
+ """
51
+
52
+
53
+ @final
54
+ @dataclasses.dataclass
55
+ class Cache:
56
+ """Instance of the `cache` fixture."""
57
+
58
+ _cachedir: Path = dataclasses.field(repr=False)
59
+ _config: Config = dataclasses.field(repr=False)
60
+
61
+ # Sub-directory under cache-dir for directories created by `mkdir()`.
62
+ _CACHE_PREFIX_DIRS = "d"
63
+
64
+ # Sub-directory under cache-dir for values created by `set()`.
65
+ _CACHE_PREFIX_VALUES = "v"
66
+
67
+ def __init__(
68
+ self, cachedir: Path, config: Config, *, _ispytest: bool = False
69
+ ) -> None:
70
+ check_ispytest(_ispytest)
71
+ self._cachedir = cachedir
72
+ self._config = config
73
+
74
+ @classmethod
75
+ def for_config(cls, config: Config, *, _ispytest: bool = False) -> "Cache":
76
+ """Create the Cache instance for a Config.
77
+
78
+ :meta private:
79
+ """
80
+ check_ispytest(_ispytest)
81
+ cachedir = cls.cache_dir_from_config(config, _ispytest=True)
82
+ if config.getoption("cacheclear") and cachedir.is_dir():
83
+ cls.clear_cache(cachedir, _ispytest=True)
84
+ return cls(cachedir, config, _ispytest=True)
85
+
86
+ @classmethod
87
+ def clear_cache(cls, cachedir: Path, _ispytest: bool = False) -> None:
88
+ """Clear the sub-directories used to hold cached directories and values.
89
+
90
+ :meta private:
91
+ """
92
+ check_ispytest(_ispytest)
93
+ for prefix in (cls._CACHE_PREFIX_DIRS, cls._CACHE_PREFIX_VALUES):
94
+ d = cachedir / prefix
95
+ if d.is_dir():
96
+ rm_rf(d)
97
+
98
+ @staticmethod
99
+ def cache_dir_from_config(config: Config, *, _ispytest: bool = False) -> Path:
100
+ """Get the path to the cache directory for a Config.
101
+
102
+ :meta private:
103
+ """
104
+ check_ispytest(_ispytest)
105
+ return resolve_from_str(config.getini("cache_dir"), config.rootpath)
106
+
107
+ def warn(self, fmt: str, *, _ispytest: bool = False, **args: object) -> None:
108
+ """Issue a cache warning.
109
+
110
+ :meta private:
111
+ """
112
+ check_ispytest(_ispytest)
113
+ import warnings
114
+ from _pytest.warning_types import PytestCacheWarning
115
+
116
+ warnings.warn(
117
+ PytestCacheWarning(fmt.format(**args) if args else fmt),
118
+ self._config.hook,
119
+ stacklevel=3,
120
+ )
121
+
122
+ def mkdir(self, name: str) -> Path:
123
+ """Return a directory path object with the given name.
124
+
125
+ If the directory does not yet exist, it will be created. You can use
126
+ it to manage files to e.g. store/retrieve database dumps across test
127
+ sessions.
128
+
129
+ .. versionadded:: 7.0
130
+
131
+ :param name:
132
+ Must be a string not containing a ``/`` separator.
133
+ Make sure the name contains your plugin or application
134
+ identifiers to prevent clashes with other cache users.
135
+ """
136
+ path = Path(name)
137
+ if len(path.parts) > 1:
138
+ raise ValueError("name is not allowed to contain path separators")
139
+ res = self._cachedir.joinpath(self._CACHE_PREFIX_DIRS, path)
140
+ res.mkdir(exist_ok=True, parents=True)
141
+ return res
142
+
143
+ def _getvaluepath(self, key: str) -> Path:
144
+ return self._cachedir.joinpath(self._CACHE_PREFIX_VALUES, Path(key))
145
+
146
+ def get(self, key: str, default):
147
+ """Return the cached value for the given key.
148
+
149
+ If no value was yet cached or the value cannot be read, the specified
150
+ default is returned.
151
+
152
+ :param key:
153
+ Must be a ``/`` separated value. Usually the first
154
+ name is the name of your plugin or your application.
155
+ :param default:
156
+ The value to return in case of a cache-miss or invalid cache value.
157
+ """
158
+ path = self._getvaluepath(key)
159
+ try:
160
+ with path.open("r", encoding="UTF-8") as f:
161
+ return json.load(f)
162
+ except (ValueError, OSError):
163
+ return default
164
+
165
+ def set(self, key: str, value: object) -> None:
166
+ """Save value for the given key.
167
+
168
+ :param key:
169
+ Must be a ``/`` separated value. Usually the first
170
+ name is the name of your plugin or your application.
171
+ :param value:
172
+ Must be of any combination of basic python types,
173
+ including nested types like lists of dictionaries.
174
+ """
175
+ path = self._getvaluepath(key)
176
+ try:
177
+ if path.parent.is_dir():
178
+ cache_dir_exists_already = True
179
+ else:
180
+ cache_dir_exists_already = self._cachedir.exists()
181
+ path.parent.mkdir(exist_ok=True, parents=True)
182
+ except OSError as exc:
183
+ self.warn(
184
+ f"could not create cache path {path}: {exc}",
185
+ _ispytest=True,
186
+ )
187
+ return
188
+ if not cache_dir_exists_already:
189
+ self._ensure_supporting_files()
190
+ data = json.dumps(value, ensure_ascii=False, indent=2)
191
+ try:
192
+ f = path.open("w", encoding="UTF-8")
193
+ except OSError as exc:
194
+ self.warn(
195
+ f"cache could not write path {path}: {exc}",
196
+ _ispytest=True,
197
+ )
198
+ else:
199
+ with f:
200
+ f.write(data)
201
+
202
+ def _ensure_supporting_files(self) -> None:
203
+ """Create supporting files in the cache dir that are not really part of the cache."""
204
+ readme_path = self._cachedir / "README.md"
205
+ readme_path.write_text(README_CONTENT, encoding="UTF-8")
206
+
207
+ gitignore_path = self._cachedir.joinpath(".gitignore")
208
+ msg = "# Created by pytest automatically.\n*\n"
209
+ gitignore_path.write_text(msg, encoding="UTF-8")
210
+
211
+ cachedir_tag_path = self._cachedir.joinpath("CACHEDIR.TAG")
212
+ cachedir_tag_path.write_bytes(CACHEDIR_TAG_CONTENT)
213
+
214
+
215
+ class LFPluginCollWrapper:
216
+ def __init__(self, lfplugin: "LFPlugin") -> None:
217
+ self.lfplugin = lfplugin
218
+ self._collected_at_least_one_failure = False
219
+
220
+ @hookimpl(hookwrapper=True)
221
+ def pytest_make_collect_report(self, collector: nodes.Collector):
222
+ if isinstance(collector, (Session, Package)):
223
+ out = yield
224
+ res: CollectReport = out.get_result()
225
+
226
+ # Sort any lf-paths to the beginning.
227
+ lf_paths = self.lfplugin._last_failed_paths
228
+
229
+ # Use stable sort to priorize last failed.
230
+ def sort_key(node: Union[nodes.Item, nodes.Collector]) -> bool:
231
+ # Package.path is the __init__.py file, we need the directory.
232
+ if isinstance(node, Package):
233
+ path = node.path.parent
234
+ else:
235
+ path = node.path
236
+ return path in lf_paths
237
+
238
+ res.result = sorted(
239
+ res.result,
240
+ key=sort_key,
241
+ reverse=True,
242
+ )
243
+ return
244
+
245
+ elif isinstance(collector, File):
246
+ if collector.path in self.lfplugin._last_failed_paths:
247
+ out = yield
248
+ res = out.get_result()
249
+ result = res.result
250
+ lastfailed = self.lfplugin.lastfailed
251
+
252
+ # Only filter with known failures.
253
+ if not self._collected_at_least_one_failure:
254
+ if not any(x.nodeid in lastfailed for x in result):
255
+ return
256
+ self.lfplugin.config.pluginmanager.register(
257
+ LFPluginCollSkipfiles(self.lfplugin), "lfplugin-collskip"
258
+ )
259
+ self._collected_at_least_one_failure = True
260
+
261
+ session = collector.session
262
+ result[:] = [
263
+ x
264
+ for x in result
265
+ if x.nodeid in lastfailed
266
+ # Include any passed arguments (not trivial to filter).
267
+ or session.isinitpath(x.path)
268
+ # Keep all sub-collectors.
269
+ or isinstance(x, nodes.Collector)
270
+ ]
271
+ return
272
+ yield
273
+
274
+
275
+ class LFPluginCollSkipfiles:
276
+ def __init__(self, lfplugin: "LFPlugin") -> None:
277
+ self.lfplugin = lfplugin
278
+
279
+ @hookimpl
280
+ def pytest_make_collect_report(
281
+ self, collector: nodes.Collector
282
+ ) -> Optional[CollectReport]:
283
+ # Packages are Files, but we only want to skip test-bearing Files,
284
+ # so don't filter Packages.
285
+ if isinstance(collector, File) and not isinstance(collector, Package):
286
+ if collector.path not in self.lfplugin._last_failed_paths:
287
+ self.lfplugin._skipped_files += 1
288
+
289
+ return CollectReport(
290
+ collector.nodeid, "passed", longrepr=None, result=[]
291
+ )
292
+ return None
293
+
294
+
295
+ class LFPlugin:
296
+ """Plugin which implements the --lf (run last-failing) option."""
297
+
298
+ def __init__(self, config: Config) -> None:
299
+ self.config = config
300
+ active_keys = "lf", "failedfirst"
301
+ self.active = any(config.getoption(key) for key in active_keys)
302
+ assert config.cache
303
+ self.lastfailed: Dict[str, bool] = config.cache.get("cache/lastfailed", {})
304
+ self._previously_failed_count: Optional[int] = None
305
+ self._report_status: Optional[str] = None
306
+ self._skipped_files = 0 # count skipped files during collection due to --lf
307
+
308
+ if config.getoption("lf"):
309
+ self._last_failed_paths = self.get_last_failed_paths()
310
+ config.pluginmanager.register(
311
+ LFPluginCollWrapper(self), "lfplugin-collwrapper"
312
+ )
313
+
314
+ def get_last_failed_paths(self) -> Set[Path]:
315
+ """Return a set with all Paths of the previously failed nodeids and
316
+ their parents."""
317
+ rootpath = self.config.rootpath
318
+ result = set()
319
+ for nodeid in self.lastfailed:
320
+ path = rootpath / nodeid.split("::")[0]
321
+ result.add(path)
322
+ result.update(path.parents)
323
+ return {x for x in result if x.exists()}
324
+
325
+ def pytest_report_collectionfinish(self) -> Optional[str]:
326
+ if self.active and self.config.getoption("verbose") >= 0:
327
+ return "run-last-failure: %s" % self._report_status
328
+ return None
329
+
330
+ def pytest_runtest_logreport(self, report: TestReport) -> None:
331
+ if (report.when == "call" and report.passed) or report.skipped:
332
+ self.lastfailed.pop(report.nodeid, None)
333
+ elif report.failed:
334
+ self.lastfailed[report.nodeid] = True
335
+
336
+ def pytest_collectreport(self, report: CollectReport) -> None:
337
+ passed = report.outcome in ("passed", "skipped")
338
+ if passed:
339
+ if report.nodeid in self.lastfailed:
340
+ self.lastfailed.pop(report.nodeid)
341
+ self.lastfailed.update((item.nodeid, True) for item in report.result)
342
+ else:
343
+ self.lastfailed[report.nodeid] = True
344
+
345
+ @hookimpl(hookwrapper=True, tryfirst=True)
346
+ def pytest_collection_modifyitems(
347
+ self, config: Config, items: List[nodes.Item]
348
+ ) -> Generator[None, None, None]:
349
+ yield
350
+
351
+ if not self.active:
352
+ return
353
+
354
+ if self.lastfailed:
355
+ previously_failed = []
356
+ previously_passed = []
357
+ for item in items:
358
+ if item.nodeid in self.lastfailed:
359
+ previously_failed.append(item)
360
+ else:
361
+ previously_passed.append(item)
362
+ self._previously_failed_count = len(previously_failed)
363
+
364
+ if not previously_failed:
365
+ # Running a subset of all tests with recorded failures
366
+ # only outside of it.
367
+ self._report_status = "%d known failures not in selected tests" % (
368
+ len(self.lastfailed),
369
+ )
370
+ else:
371
+ if self.config.getoption("lf"):
372
+ items[:] = previously_failed
373
+ config.hook.pytest_deselected(items=previously_passed)
374
+ else: # --failedfirst
375
+ items[:] = previously_failed + previously_passed
376
+
377
+ noun = "failure" if self._previously_failed_count == 1 else "failures"
378
+ suffix = " first" if self.config.getoption("failedfirst") else ""
379
+ self._report_status = "rerun previous {count} {noun}{suffix}".format(
380
+ count=self._previously_failed_count, suffix=suffix, noun=noun
381
+ )
382
+
383
+ if self._skipped_files > 0:
384
+ files_noun = "file" if self._skipped_files == 1 else "files"
385
+ self._report_status += " (skipped {files} {files_noun})".format(
386
+ files=self._skipped_files, files_noun=files_noun
387
+ )
388
+ else:
389
+ self._report_status = "no previously failed tests, "
390
+ if self.config.getoption("last_failed_no_failures") == "none":
391
+ self._report_status += "deselecting all items."
392
+ config.hook.pytest_deselected(items=items[:])
393
+ items[:] = []
394
+ else:
395
+ self._report_status += "not deselecting items."
396
+
397
+ def pytest_sessionfinish(self, session: Session) -> None:
398
+ config = self.config
399
+ if config.getoption("cacheshow") or hasattr(config, "workerinput"):
400
+ return
401
+
402
+ assert config.cache is not None
403
+ saved_lastfailed = config.cache.get("cache/lastfailed", {})
404
+ if saved_lastfailed != self.lastfailed:
405
+ config.cache.set("cache/lastfailed", self.lastfailed)
406
+
407
+
408
+ class NFPlugin:
409
+ """Plugin which implements the --nf (run new-first) option."""
410
+
411
+ def __init__(self, config: Config) -> None:
412
+ self.config = config
413
+ self.active = config.option.newfirst
414
+ assert config.cache is not None
415
+ self.cached_nodeids = set(config.cache.get("cache/nodeids", []))
416
+
417
+ @hookimpl(hookwrapper=True, tryfirst=True)
418
+ def pytest_collection_modifyitems(
419
+ self, items: List[nodes.Item]
420
+ ) -> Generator[None, None, None]:
421
+ yield
422
+
423
+ if self.active:
424
+ new_items: Dict[str, nodes.Item] = {}
425
+ other_items: Dict[str, nodes.Item] = {}
426
+ for item in items:
427
+ if item.nodeid not in self.cached_nodeids:
428
+ new_items[item.nodeid] = item
429
+ else:
430
+ other_items[item.nodeid] = item
431
+
432
+ items[:] = self._get_increasing_order(
433
+ new_items.values()
434
+ ) + self._get_increasing_order(other_items.values())
435
+ self.cached_nodeids.update(new_items)
436
+ else:
437
+ self.cached_nodeids.update(item.nodeid for item in items)
438
+
439
+ def _get_increasing_order(self, items: Iterable[nodes.Item]) -> List[nodes.Item]:
440
+ return sorted(items, key=lambda item: item.path.stat().st_mtime, reverse=True) # type: ignore[no-any-return]
441
+
442
+ def pytest_sessionfinish(self) -> None:
443
+ config = self.config
444
+ if config.getoption("cacheshow") or hasattr(config, "workerinput"):
445
+ return
446
+
447
+ if config.getoption("collectonly"):
448
+ return
449
+
450
+ assert config.cache is not None
451
+ config.cache.set("cache/nodeids", sorted(self.cached_nodeids))
452
+
453
+
454
+ def pytest_addoption(parser: Parser) -> None:
455
+ group = parser.getgroup("general")
456
+ group.addoption(
457
+ "--lf",
458
+ "--last-failed",
459
+ action="store_true",
460
+ dest="lf",
461
+ help="Rerun only the tests that failed "
462
+ "at the last run (or all if none failed)",
463
+ )
464
+ group.addoption(
465
+ "--ff",
466
+ "--failed-first",
467
+ action="store_true",
468
+ dest="failedfirst",
469
+ help="Run all tests, but run the last failures first. "
470
+ "This may re-order tests and thus lead to "
471
+ "repeated fixture setup/teardown.",
472
+ )
473
+ group.addoption(
474
+ "--nf",
475
+ "--new-first",
476
+ action="store_true",
477
+ dest="newfirst",
478
+ help="Run tests from new files first, then the rest of the tests "
479
+ "sorted by file mtime",
480
+ )
481
+ group.addoption(
482
+ "--cache-show",
483
+ action="append",
484
+ nargs="?",
485
+ dest="cacheshow",
486
+ help=(
487
+ "Show cache contents, don't perform collection or tests. "
488
+ "Optional argument: glob (default: '*')."
489
+ ),
490
+ )
491
+ group.addoption(
492
+ "--cache-clear",
493
+ action="store_true",
494
+ dest="cacheclear",
495
+ help="Remove all cache contents at start of test run",
496
+ )
497
+ cache_dir_default = ".pytest_cache"
498
+ if "TOX_ENV_DIR" in os.environ:
499
+ cache_dir_default = os.path.join(os.environ["TOX_ENV_DIR"], cache_dir_default)
500
+ parser.addini("cache_dir", default=cache_dir_default, help="Cache directory path")
501
+ group.addoption(
502
+ "--lfnf",
503
+ "--last-failed-no-failures",
504
+ action="store",
505
+ dest="last_failed_no_failures",
506
+ choices=("all", "none"),
507
+ default="all",
508
+ help="With ``--lf``, determines whether to execute tests when there "
509
+ "are no previously (known) failures or when no "
510
+ "cached ``lastfailed`` data was found. "
511
+ "``all`` (the default) runs the full test suite again. "
512
+ "``none`` just emits a message about no known failures and exits successfully.",
513
+ )
514
+
515
+
516
+ def pytest_cmdline_main(config: Config) -> Optional[Union[int, ExitCode]]:
517
+ if config.option.cacheshow and not config.option.help:
518
+ from _pytest.main import wrap_session
519
+
520
+ return wrap_session(config, cacheshow)
521
+ return None
522
+
523
+
524
+ @hookimpl(tryfirst=True)
525
+ def pytest_configure(config: Config) -> None:
526
+ config.cache = Cache.for_config(config, _ispytest=True)
527
+ config.pluginmanager.register(LFPlugin(config), "lfplugin")
528
+ config.pluginmanager.register(NFPlugin(config), "nfplugin")
529
+
530
+
531
+ @fixture
532
+ def cache(request: FixtureRequest) -> Cache:
533
+ """Return a cache object that can persist state between testing sessions.
534
+
535
+ cache.get(key, default)
536
+ cache.set(key, value)
537
+
538
+ Keys must be ``/`` separated strings, where the first part is usually the
539
+ name of your plugin or application to avoid clashes with other cache users.
540
+
541
+ Values can be any object handled by the json stdlib module.
542
+ """
543
+ assert request.config.cache is not None
544
+ return request.config.cache
545
+
546
+
547
+ def pytest_report_header(config: Config) -> Optional[str]:
548
+ """Display cachedir with --cache-show and if non-default."""
549
+ if config.option.verbose > 0 or config.getini("cache_dir") != ".pytest_cache":
550
+ assert config.cache is not None
551
+ cachedir = config.cache._cachedir
552
+ # TODO: evaluate generating upward relative paths
553
+ # starting with .., ../.. if sensible
554
+
555
+ try:
556
+ displaypath = cachedir.relative_to(config.rootpath)
557
+ except ValueError:
558
+ displaypath = cachedir
559
+ return f"cachedir: {displaypath}"
560
+ return None
561
+
562
+
563
+ def cacheshow(config: Config, session: Session) -> int:
564
+ from pprint import pformat
565
+
566
+ assert config.cache is not None
567
+
568
+ tw = TerminalWriter()
569
+ tw.line("cachedir: " + str(config.cache._cachedir))
570
+ if not config.cache._cachedir.is_dir():
571
+ tw.line("cache is empty")
572
+ return 0
573
+
574
+ glob = config.option.cacheshow[0]
575
+ if glob is None:
576
+ glob = "*"
577
+
578
+ dummy = object()
579
+ basedir = config.cache._cachedir
580
+ vdir = basedir / Cache._CACHE_PREFIX_VALUES
581
+ tw.sep("-", "cache values for %r" % glob)
582
+ for valpath in sorted(x for x in vdir.rglob(glob) if x.is_file()):
583
+ key = str(valpath.relative_to(vdir))
584
+ val = config.cache.get(key, dummy)
585
+ if val is dummy:
586
+ tw.line("%s contains unreadable content, will be ignored" % key)
587
+ else:
588
+ tw.line("%s contains:" % key)
589
+ for line in pformat(val).splitlines():
590
+ tw.line(" " + line)
591
+
592
+ ddir = basedir / Cache._CACHE_PREFIX_DIRS
593
+ if ddir.is_dir():
594
+ contents = sorted(ddir.rglob(glob))
595
+ tw.sep("-", "cache directories for %r" % glob)
596
+ for p in contents:
597
+ # if p.is_dir():
598
+ # print("%s/" % p.relative_to(basedir))
599
+ if p.is_file():
600
+ key = str(p.relative_to(basedir))
601
+ tw.line(f"{key} is a file of length {p.stat().st_size:d}")
602
+ return 0
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/capture.py ADDED
@@ -0,0 +1,1082 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-test stdout/stderr capturing mechanism."""
2
+ import abc
3
+ import collections
4
+ import contextlib
5
+ import io
6
+ import os
7
+ import sys
8
+ from io import UnsupportedOperation
9
+ from tempfile import TemporaryFile
10
+ from types import TracebackType
11
+ from typing import Any
12
+ from typing import AnyStr
13
+ from typing import BinaryIO
14
+ from typing import Generator
15
+ from typing import Generic
16
+ from typing import Iterable
17
+ from typing import Iterator
18
+ from typing import List
19
+ from typing import NamedTuple
20
+ from typing import Optional
21
+ from typing import TextIO
22
+ from typing import Tuple
23
+ from typing import Type
24
+ from typing import TYPE_CHECKING
25
+ from typing import Union
26
+
27
+ from _pytest.compat import final
28
+ from _pytest.config import Config
29
+ from _pytest.config import hookimpl
30
+ from _pytest.config.argparsing import Parser
31
+ from _pytest.deprecated import check_ispytest
32
+ from _pytest.fixtures import fixture
33
+ from _pytest.fixtures import SubRequest
34
+ from _pytest.nodes import Collector
35
+ from _pytest.nodes import File
36
+ from _pytest.nodes import Item
37
+
38
+ if TYPE_CHECKING:
39
+ from typing_extensions import Final
40
+ from typing_extensions import Literal
41
+
42
+ _CaptureMethod = Literal["fd", "sys", "no", "tee-sys"]
43
+
44
+
45
+ def pytest_addoption(parser: Parser) -> None:
46
+ group = parser.getgroup("general")
47
+ group._addoption(
48
+ "--capture",
49
+ action="store",
50
+ default="fd",
51
+ metavar="method",
52
+ choices=["fd", "sys", "no", "tee-sys"],
53
+ help="Per-test capturing method: one of fd|sys|no|tee-sys",
54
+ )
55
+ group._addoption(
56
+ "-s",
57
+ action="store_const",
58
+ const="no",
59
+ dest="capture",
60
+ help="Shortcut for --capture=no",
61
+ )
62
+
63
+
64
+ def _colorama_workaround() -> None:
65
+ """Ensure colorama is imported so that it attaches to the correct stdio
66
+ handles on Windows.
67
+
68
+ colorama uses the terminal on import time. So if something does the
69
+ first import of colorama while I/O capture is active, colorama will
70
+ fail in various ways.
71
+ """
72
+ if sys.platform.startswith("win32"):
73
+ try:
74
+ import colorama # noqa: F401
75
+ except ImportError:
76
+ pass
77
+
78
+
79
+ def _windowsconsoleio_workaround(stream: TextIO) -> None:
80
+ """Workaround for Windows Unicode console handling.
81
+
82
+ Python 3.6 implemented Unicode console handling for Windows. This works
83
+ by reading/writing to the raw console handle using
84
+ ``{Read,Write}ConsoleW``.
85
+
86
+ The problem is that we are going to ``dup2`` over the stdio file
87
+ descriptors when doing ``FDCapture`` and this will ``CloseHandle`` the
88
+ handles used by Python to write to the console. Though there is still some
89
+ weirdness and the console handle seems to only be closed randomly and not
90
+ on the first call to ``CloseHandle``, or maybe it gets reopened with the
91
+ same handle value when we suspend capturing.
92
+
93
+ The workaround in this case will reopen stdio with a different fd which
94
+ also means a different handle by replicating the logic in
95
+ "Py_lifecycle.c:initstdio/create_stdio".
96
+
97
+ :param stream:
98
+ In practice ``sys.stdout`` or ``sys.stderr``, but given
99
+ here as parameter for unittesting purposes.
100
+
101
+ See https://github.com/pytest-dev/py/issues/103.
102
+ """
103
+ if not sys.platform.startswith("win32") or hasattr(sys, "pypy_version_info"):
104
+ return
105
+
106
+ # Bail out if ``stream`` doesn't seem like a proper ``io`` stream (#2666).
107
+ if not hasattr(stream, "buffer"): # type: ignore[unreachable]
108
+ return
109
+
110
+ buffered = hasattr(stream.buffer, "raw")
111
+ raw_stdout = stream.buffer.raw if buffered else stream.buffer # type: ignore[attr-defined]
112
+
113
+ if not isinstance(raw_stdout, io._WindowsConsoleIO): # type: ignore[attr-defined]
114
+ return
115
+
116
+ def _reopen_stdio(f, mode):
117
+ if not buffered and mode[0] == "w":
118
+ buffering = 0
119
+ else:
120
+ buffering = -1
121
+
122
+ return io.TextIOWrapper(
123
+ open(os.dup(f.fileno()), mode, buffering),
124
+ f.encoding,
125
+ f.errors,
126
+ f.newlines,
127
+ f.line_buffering,
128
+ )
129
+
130
+ sys.stdin = _reopen_stdio(sys.stdin, "rb")
131
+ sys.stdout = _reopen_stdio(sys.stdout, "wb")
132
+ sys.stderr = _reopen_stdio(sys.stderr, "wb")
133
+
134
+
135
+ @hookimpl(hookwrapper=True)
136
+ def pytest_load_initial_conftests(early_config: Config):
137
+ ns = early_config.known_args_namespace
138
+ if ns.capture == "fd":
139
+ _windowsconsoleio_workaround(sys.stdout)
140
+ _colorama_workaround()
141
+ pluginmanager = early_config.pluginmanager
142
+ capman = CaptureManager(ns.capture)
143
+ pluginmanager.register(capman, "capturemanager")
144
+
145
+ # Make sure that capturemanager is properly reset at final shutdown.
146
+ early_config.add_cleanup(capman.stop_global_capturing)
147
+
148
+ # Finally trigger conftest loading but while capturing (issue #93).
149
+ capman.start_global_capturing()
150
+ outcome = yield
151
+ capman.suspend_global_capture()
152
+ if outcome.excinfo is not None:
153
+ out, err = capman.read_global_capture()
154
+ sys.stdout.write(out)
155
+ sys.stderr.write(err)
156
+
157
+
158
+ # IO Helpers.
159
+
160
+
161
+ class EncodedFile(io.TextIOWrapper):
162
+ __slots__ = ()
163
+
164
+ @property
165
+ def name(self) -> str:
166
+ # Ensure that file.name is a string. Workaround for a Python bug
167
+ # fixed in >=3.7.4: https://bugs.python.org/issue36015
168
+ return repr(self.buffer)
169
+
170
+ @property
171
+ def mode(self) -> str:
172
+ # TextIOWrapper doesn't expose a mode, but at least some of our
173
+ # tests check it.
174
+ return self.buffer.mode.replace("b", "")
175
+
176
+
177
+ class CaptureIO(io.TextIOWrapper):
178
+ def __init__(self) -> None:
179
+ super().__init__(io.BytesIO(), encoding="UTF-8", newline="", write_through=True)
180
+
181
+ def getvalue(self) -> str:
182
+ assert isinstance(self.buffer, io.BytesIO)
183
+ return self.buffer.getvalue().decode("UTF-8")
184
+
185
+
186
+ class TeeCaptureIO(CaptureIO):
187
+ def __init__(self, other: TextIO) -> None:
188
+ self._other = other
189
+ super().__init__()
190
+
191
+ def write(self, s: str) -> int:
192
+ super().write(s)
193
+ return self._other.write(s)
194
+
195
+
196
+ class DontReadFromInput(TextIO):
197
+ @property
198
+ def encoding(self) -> str:
199
+ return sys.__stdin__.encoding
200
+
201
+ def read(self, size: int = -1) -> str:
202
+ raise OSError(
203
+ "pytest: reading from stdin while output is captured! Consider using `-s`."
204
+ )
205
+
206
+ readline = read
207
+
208
+ def __next__(self) -> str:
209
+ return self.readline()
210
+
211
+ def readlines(self, hint: Optional[int] = -1) -> List[str]:
212
+ raise OSError(
213
+ "pytest: reading from stdin while output is captured! Consider using `-s`."
214
+ )
215
+
216
+ def __iter__(self) -> Iterator[str]:
217
+ return self
218
+
219
+ def fileno(self) -> int:
220
+ raise UnsupportedOperation("redirected stdin is pseudofile, has no fileno()")
221
+
222
+ def flush(self) -> None:
223
+ raise UnsupportedOperation("redirected stdin is pseudofile, has no flush()")
224
+
225
+ def isatty(self) -> bool:
226
+ return False
227
+
228
+ def close(self) -> None:
229
+ pass
230
+
231
+ def readable(self) -> bool:
232
+ return False
233
+
234
+ def seek(self, offset: int, whence: int = 0) -> int:
235
+ raise UnsupportedOperation("redirected stdin is pseudofile, has no seek(int)")
236
+
237
+ def seekable(self) -> bool:
238
+ return False
239
+
240
+ def tell(self) -> int:
241
+ raise UnsupportedOperation("redirected stdin is pseudofile, has no tell()")
242
+
243
+ def truncate(self, size: Optional[int] = None) -> int:
244
+ raise UnsupportedOperation("cannot truncate stdin")
245
+
246
+ def write(self, data: str) -> int:
247
+ raise UnsupportedOperation("cannot write to stdin")
248
+
249
+ def writelines(self, lines: Iterable[str]) -> None:
250
+ raise UnsupportedOperation("Cannot write to stdin")
251
+
252
+ def writable(self) -> bool:
253
+ return False
254
+
255
+ def __enter__(self) -> "DontReadFromInput":
256
+ return self
257
+
258
+ def __exit__(
259
+ self,
260
+ type: Optional[Type[BaseException]],
261
+ value: Optional[BaseException],
262
+ traceback: Optional[TracebackType],
263
+ ) -> None:
264
+ pass
265
+
266
+ @property
267
+ def buffer(self) -> BinaryIO:
268
+ # The str/bytes doesn't actually matter in this type, so OK to fake.
269
+ return self # type: ignore[return-value]
270
+
271
+
272
+ # Capture classes.
273
+
274
+
275
+ class CaptureBase(abc.ABC, Generic[AnyStr]):
276
+ EMPTY_BUFFER: AnyStr
277
+
278
+ @abc.abstractmethod
279
+ def __init__(self, fd: int) -> None:
280
+ raise NotImplementedError()
281
+
282
+ @abc.abstractmethod
283
+ def start(self) -> None:
284
+ raise NotImplementedError()
285
+
286
+ @abc.abstractmethod
287
+ def done(self) -> None:
288
+ raise NotImplementedError()
289
+
290
+ @abc.abstractmethod
291
+ def suspend(self) -> None:
292
+ raise NotImplementedError()
293
+
294
+ @abc.abstractmethod
295
+ def resume(self) -> None:
296
+ raise NotImplementedError()
297
+
298
+ @abc.abstractmethod
299
+ def writeorg(self, data: AnyStr) -> None:
300
+ raise NotImplementedError()
301
+
302
+ @abc.abstractmethod
303
+ def snap(self) -> AnyStr:
304
+ raise NotImplementedError()
305
+
306
+
307
+ patchsysdict = {0: "stdin", 1: "stdout", 2: "stderr"}
308
+
309
+
310
+ class NoCapture(CaptureBase[str]):
311
+ EMPTY_BUFFER = ""
312
+
313
+ def __init__(self, fd: int) -> None:
314
+ pass
315
+
316
+ def start(self) -> None:
317
+ pass
318
+
319
+ def done(self) -> None:
320
+ pass
321
+
322
+ def suspend(self) -> None:
323
+ pass
324
+
325
+ def resume(self) -> None:
326
+ pass
327
+
328
+ def snap(self) -> str:
329
+ return ""
330
+
331
+ def writeorg(self, data: str) -> None:
332
+ pass
333
+
334
+
335
+ class SysCaptureBase(CaptureBase[AnyStr]):
336
+ def __init__(
337
+ self, fd: int, tmpfile: Optional[TextIO] = None, *, tee: bool = False
338
+ ) -> None:
339
+ name = patchsysdict[fd]
340
+ self._old: TextIO = getattr(sys, name)
341
+ self.name = name
342
+ if tmpfile is None:
343
+ if name == "stdin":
344
+ tmpfile = DontReadFromInput()
345
+ else:
346
+ tmpfile = CaptureIO() if not tee else TeeCaptureIO(self._old)
347
+ self.tmpfile = tmpfile
348
+ self._state = "initialized"
349
+
350
+ def repr(self, class_name: str) -> str:
351
+ return "<{} {} _old={} _state={!r} tmpfile={!r}>".format(
352
+ class_name,
353
+ self.name,
354
+ hasattr(self, "_old") and repr(self._old) or "<UNSET>",
355
+ self._state,
356
+ self.tmpfile,
357
+ )
358
+
359
+ def __repr__(self) -> str:
360
+ return "<{} {} _old={} _state={!r} tmpfile={!r}>".format(
361
+ self.__class__.__name__,
362
+ self.name,
363
+ hasattr(self, "_old") and repr(self._old) or "<UNSET>",
364
+ self._state,
365
+ self.tmpfile,
366
+ )
367
+
368
+ def _assert_state(self, op: str, states: Tuple[str, ...]) -> None:
369
+ assert (
370
+ self._state in states
371
+ ), "cannot {} in state {!r}: expected one of {}".format(
372
+ op, self._state, ", ".join(states)
373
+ )
374
+
375
+ def start(self) -> None:
376
+ self._assert_state("start", ("initialized",))
377
+ setattr(sys, self.name, self.tmpfile)
378
+ self._state = "started"
379
+
380
+ def done(self) -> None:
381
+ self._assert_state("done", ("initialized", "started", "suspended", "done"))
382
+ if self._state == "done":
383
+ return
384
+ setattr(sys, self.name, self._old)
385
+ del self._old
386
+ self.tmpfile.close()
387
+ self._state = "done"
388
+
389
+ def suspend(self) -> None:
390
+ self._assert_state("suspend", ("started", "suspended"))
391
+ setattr(sys, self.name, self._old)
392
+ self._state = "suspended"
393
+
394
+ def resume(self) -> None:
395
+ self._assert_state("resume", ("started", "suspended"))
396
+ if self._state == "started":
397
+ return
398
+ setattr(sys, self.name, self.tmpfile)
399
+ self._state = "started"
400
+
401
+
402
+ class SysCaptureBinary(SysCaptureBase[bytes]):
403
+ EMPTY_BUFFER = b""
404
+
405
+ def snap(self) -> bytes:
406
+ self._assert_state("snap", ("started", "suspended"))
407
+ self.tmpfile.seek(0)
408
+ res = self.tmpfile.buffer.read()
409
+ self.tmpfile.seek(0)
410
+ self.tmpfile.truncate()
411
+ return res
412
+
413
+ def writeorg(self, data: bytes) -> None:
414
+ self._assert_state("writeorg", ("started", "suspended"))
415
+ self._old.flush()
416
+ self._old.buffer.write(data)
417
+ self._old.buffer.flush()
418
+
419
+
420
+ class SysCapture(SysCaptureBase[str]):
421
+ EMPTY_BUFFER = ""
422
+
423
+ def snap(self) -> str:
424
+ self._assert_state("snap", ("started", "suspended"))
425
+ assert isinstance(self.tmpfile, CaptureIO)
426
+ res = self.tmpfile.getvalue()
427
+ self.tmpfile.seek(0)
428
+ self.tmpfile.truncate()
429
+ return res
430
+
431
+ def writeorg(self, data: str) -> None:
432
+ self._assert_state("writeorg", ("started", "suspended"))
433
+ self._old.write(data)
434
+ self._old.flush()
435
+
436
+
437
+ class FDCaptureBase(CaptureBase[AnyStr]):
438
+ def __init__(self, targetfd: int) -> None:
439
+ self.targetfd = targetfd
440
+
441
+ try:
442
+ os.fstat(targetfd)
443
+ except OSError:
444
+ # FD capturing is conceptually simple -- create a temporary file,
445
+ # redirect the FD to it, redirect back when done. But when the
446
+ # target FD is invalid it throws a wrench into this lovely scheme.
447
+ #
448
+ # Tests themselves shouldn't care if the FD is valid, FD capturing
449
+ # should work regardless of external circumstances. So falling back
450
+ # to just sys capturing is not a good option.
451
+ #
452
+ # Further complications are the need to support suspend() and the
453
+ # possibility of FD reuse (e.g. the tmpfile getting the very same
454
+ # target FD). The following approach is robust, I believe.
455
+ self.targetfd_invalid: Optional[int] = os.open(os.devnull, os.O_RDWR)
456
+ os.dup2(self.targetfd_invalid, targetfd)
457
+ else:
458
+ self.targetfd_invalid = None
459
+ self.targetfd_save = os.dup(targetfd)
460
+
461
+ if targetfd == 0:
462
+ self.tmpfile = open(os.devnull, encoding="utf-8")
463
+ self.syscapture: CaptureBase[str] = SysCapture(targetfd)
464
+ else:
465
+ self.tmpfile = EncodedFile(
466
+ TemporaryFile(buffering=0),
467
+ encoding="utf-8",
468
+ errors="replace",
469
+ newline="",
470
+ write_through=True,
471
+ )
472
+ if targetfd in patchsysdict:
473
+ self.syscapture = SysCapture(targetfd, self.tmpfile)
474
+ else:
475
+ self.syscapture = NoCapture(targetfd)
476
+
477
+ self._state = "initialized"
478
+
479
+ def __repr__(self) -> str:
480
+ return "<{} {} oldfd={} _state={!r} tmpfile={!r}>".format(
481
+ self.__class__.__name__,
482
+ self.targetfd,
483
+ self.targetfd_save,
484
+ self._state,
485
+ self.tmpfile,
486
+ )
487
+
488
+ def _assert_state(self, op: str, states: Tuple[str, ...]) -> None:
489
+ assert (
490
+ self._state in states
491
+ ), "cannot {} in state {!r}: expected one of {}".format(
492
+ op, self._state, ", ".join(states)
493
+ )
494
+
495
+ def start(self) -> None:
496
+ """Start capturing on targetfd using memorized tmpfile."""
497
+ self._assert_state("start", ("initialized",))
498
+ os.dup2(self.tmpfile.fileno(), self.targetfd)
499
+ self.syscapture.start()
500
+ self._state = "started"
501
+
502
+ def done(self) -> None:
503
+ """Stop capturing, restore streams, return original capture file,
504
+ seeked to position zero."""
505
+ self._assert_state("done", ("initialized", "started", "suspended", "done"))
506
+ if self._state == "done":
507
+ return
508
+ os.dup2(self.targetfd_save, self.targetfd)
509
+ os.close(self.targetfd_save)
510
+ if self.targetfd_invalid is not None:
511
+ if self.targetfd_invalid != self.targetfd:
512
+ os.close(self.targetfd)
513
+ os.close(self.targetfd_invalid)
514
+ self.syscapture.done()
515
+ self.tmpfile.close()
516
+ self._state = "done"
517
+
518
+ def suspend(self) -> None:
519
+ self._assert_state("suspend", ("started", "suspended"))
520
+ if self._state == "suspended":
521
+ return
522
+ self.syscapture.suspend()
523
+ os.dup2(self.targetfd_save, self.targetfd)
524
+ self._state = "suspended"
525
+
526
+ def resume(self) -> None:
527
+ self._assert_state("resume", ("started", "suspended"))
528
+ if self._state == "started":
529
+ return
530
+ self.syscapture.resume()
531
+ os.dup2(self.tmpfile.fileno(), self.targetfd)
532
+ self._state = "started"
533
+
534
+
535
+ class FDCaptureBinary(FDCaptureBase[bytes]):
536
+ """Capture IO to/from a given OS-level file descriptor.
537
+
538
+ snap() produces `bytes`.
539
+ """
540
+
541
+ EMPTY_BUFFER = b""
542
+
543
+ def snap(self) -> bytes:
544
+ self._assert_state("snap", ("started", "suspended"))
545
+ self.tmpfile.seek(0)
546
+ res = self.tmpfile.buffer.read()
547
+ self.tmpfile.seek(0)
548
+ self.tmpfile.truncate()
549
+ return res
550
+
551
+ def writeorg(self, data: bytes) -> None:
552
+ """Write to original file descriptor."""
553
+ self._assert_state("writeorg", ("started", "suspended"))
554
+ os.write(self.targetfd_save, data)
555
+
556
+
557
+ class FDCapture(FDCaptureBase[str]):
558
+ """Capture IO to/from a given OS-level file descriptor.
559
+
560
+ snap() produces text.
561
+ """
562
+
563
+ EMPTY_BUFFER = ""
564
+
565
+ def snap(self) -> str:
566
+ self._assert_state("snap", ("started", "suspended"))
567
+ self.tmpfile.seek(0)
568
+ res = self.tmpfile.read()
569
+ self.tmpfile.seek(0)
570
+ self.tmpfile.truncate()
571
+ return res
572
+
573
+ def writeorg(self, data: str) -> None:
574
+ """Write to original file descriptor."""
575
+ self._assert_state("writeorg", ("started", "suspended"))
576
+ # XXX use encoding of original stream
577
+ os.write(self.targetfd_save, data.encode("utf-8"))
578
+
579
+
580
+ # MultiCapture
581
+
582
+
583
+ # Generic NamedTuple only supported since Python 3.11.
584
+ if sys.version_info >= (3, 11) or TYPE_CHECKING:
585
+
586
+ @final
587
+ class CaptureResult(NamedTuple, Generic[AnyStr]):
588
+ """The result of :method:`CaptureFixture.readouterr`."""
589
+
590
+ out: AnyStr
591
+ err: AnyStr
592
+
593
+ else:
594
+
595
+ class CaptureResult(
596
+ collections.namedtuple("CaptureResult", ["out", "err"]), Generic[AnyStr]
597
+ ):
598
+ """The result of :method:`CaptureFixture.readouterr`."""
599
+
600
+ __slots__ = ()
601
+
602
+
603
+ class MultiCapture(Generic[AnyStr]):
604
+ _state = None
605
+ _in_suspended = False
606
+
607
+ def __init__(
608
+ self,
609
+ in_: Optional[CaptureBase[AnyStr]],
610
+ out: Optional[CaptureBase[AnyStr]],
611
+ err: Optional[CaptureBase[AnyStr]],
612
+ ) -> None:
613
+ self.in_: Optional[CaptureBase[AnyStr]] = in_
614
+ self.out: Optional[CaptureBase[AnyStr]] = out
615
+ self.err: Optional[CaptureBase[AnyStr]] = err
616
+
617
+ def __repr__(self) -> str:
618
+ return "<MultiCapture out={!r} err={!r} in_={!r} _state={!r} _in_suspended={!r}>".format(
619
+ self.out,
620
+ self.err,
621
+ self.in_,
622
+ self._state,
623
+ self._in_suspended,
624
+ )
625
+
626
+ def start_capturing(self) -> None:
627
+ self._state = "started"
628
+ if self.in_:
629
+ self.in_.start()
630
+ if self.out:
631
+ self.out.start()
632
+ if self.err:
633
+ self.err.start()
634
+
635
+ def pop_outerr_to_orig(self) -> Tuple[AnyStr, AnyStr]:
636
+ """Pop current snapshot out/err capture and flush to orig streams."""
637
+ out, err = self.readouterr()
638
+ if out:
639
+ assert self.out is not None
640
+ self.out.writeorg(out)
641
+ if err:
642
+ assert self.err is not None
643
+ self.err.writeorg(err)
644
+ return out, err
645
+
646
+ def suspend_capturing(self, in_: bool = False) -> None:
647
+ self._state = "suspended"
648
+ if self.out:
649
+ self.out.suspend()
650
+ if self.err:
651
+ self.err.suspend()
652
+ if in_ and self.in_:
653
+ self.in_.suspend()
654
+ self._in_suspended = True
655
+
656
+ def resume_capturing(self) -> None:
657
+ self._state = "started"
658
+ if self.out:
659
+ self.out.resume()
660
+ if self.err:
661
+ self.err.resume()
662
+ if self._in_suspended:
663
+ assert self.in_ is not None
664
+ self.in_.resume()
665
+ self._in_suspended = False
666
+
667
+ def stop_capturing(self) -> None:
668
+ """Stop capturing and reset capturing streams."""
669
+ if self._state == "stopped":
670
+ raise ValueError("was already stopped")
671
+ self._state = "stopped"
672
+ if self.out:
673
+ self.out.done()
674
+ if self.err:
675
+ self.err.done()
676
+ if self.in_:
677
+ self.in_.done()
678
+
679
+ def is_started(self) -> bool:
680
+ """Whether actively capturing -- not suspended or stopped."""
681
+ return self._state == "started"
682
+
683
+ def readouterr(self) -> CaptureResult[AnyStr]:
684
+ out = self.out.snap() if self.out else ""
685
+ err = self.err.snap() if self.err else ""
686
+ # TODO: This type error is real, need to fix.
687
+ return CaptureResult(out, err) # type: ignore[arg-type]
688
+
689
+
690
+ def _get_multicapture(method: "_CaptureMethod") -> MultiCapture[str]:
691
+ if method == "fd":
692
+ return MultiCapture(in_=FDCapture(0), out=FDCapture(1), err=FDCapture(2))
693
+ elif method == "sys":
694
+ return MultiCapture(in_=SysCapture(0), out=SysCapture(1), err=SysCapture(2))
695
+ elif method == "no":
696
+ return MultiCapture(in_=None, out=None, err=None)
697
+ elif method == "tee-sys":
698
+ return MultiCapture(
699
+ in_=None, out=SysCapture(1, tee=True), err=SysCapture(2, tee=True)
700
+ )
701
+ raise ValueError(f"unknown capturing method: {method!r}")
702
+
703
+
704
+ # CaptureManager and CaptureFixture
705
+
706
+
707
+ class CaptureManager:
708
+ """The capture plugin.
709
+
710
+ Manages that the appropriate capture method is enabled/disabled during
711
+ collection and each test phase (setup, call, teardown). After each of
712
+ those points, the captured output is obtained and attached to the
713
+ collection/runtest report.
714
+
715
+ There are two levels of capture:
716
+
717
+ * global: enabled by default and can be suppressed by the ``-s``
718
+ option. This is always enabled/disabled during collection and each test
719
+ phase.
720
+
721
+ * fixture: when a test function or one of its fixture depend on the
722
+ ``capsys`` or ``capfd`` fixtures. In this case special handling is
723
+ needed to ensure the fixtures take precedence over the global capture.
724
+ """
725
+
726
+ def __init__(self, method: "_CaptureMethod") -> None:
727
+ self._method: Final = method
728
+ self._global_capturing: Optional[MultiCapture[str]] = None
729
+ self._capture_fixture: Optional[CaptureFixture[Any]] = None
730
+
731
+ def __repr__(self) -> str:
732
+ return "<CaptureManager _method={!r} _global_capturing={!r} _capture_fixture={!r}>".format(
733
+ self._method, self._global_capturing, self._capture_fixture
734
+ )
735
+
736
+ def is_capturing(self) -> Union[str, bool]:
737
+ if self.is_globally_capturing():
738
+ return "global"
739
+ if self._capture_fixture:
740
+ return "fixture %s" % self._capture_fixture.request.fixturename
741
+ return False
742
+
743
+ # Global capturing control
744
+
745
+ def is_globally_capturing(self) -> bool:
746
+ return self._method != "no"
747
+
748
+ def start_global_capturing(self) -> None:
749
+ assert self._global_capturing is None
750
+ self._global_capturing = _get_multicapture(self._method)
751
+ self._global_capturing.start_capturing()
752
+
753
+ def stop_global_capturing(self) -> None:
754
+ if self._global_capturing is not None:
755
+ self._global_capturing.pop_outerr_to_orig()
756
+ self._global_capturing.stop_capturing()
757
+ self._global_capturing = None
758
+
759
+ def resume_global_capture(self) -> None:
760
+ # During teardown of the python process, and on rare occasions, capture
761
+ # attributes can be `None` while trying to resume global capture.
762
+ if self._global_capturing is not None:
763
+ self._global_capturing.resume_capturing()
764
+
765
+ def suspend_global_capture(self, in_: bool = False) -> None:
766
+ if self._global_capturing is not None:
767
+ self._global_capturing.suspend_capturing(in_=in_)
768
+
769
+ def suspend(self, in_: bool = False) -> None:
770
+ # Need to undo local capsys-et-al if it exists before disabling global capture.
771
+ self.suspend_fixture()
772
+ self.suspend_global_capture(in_)
773
+
774
+ def resume(self) -> None:
775
+ self.resume_global_capture()
776
+ self.resume_fixture()
777
+
778
+ def read_global_capture(self) -> CaptureResult[str]:
779
+ assert self._global_capturing is not None
780
+ return self._global_capturing.readouterr()
781
+
782
+ # Fixture Control
783
+
784
+ def set_fixture(self, capture_fixture: "CaptureFixture[Any]") -> None:
785
+ if self._capture_fixture:
786
+ current_fixture = self._capture_fixture.request.fixturename
787
+ requested_fixture = capture_fixture.request.fixturename
788
+ capture_fixture.request.raiseerror(
789
+ "cannot use {} and {} at the same time".format(
790
+ requested_fixture, current_fixture
791
+ )
792
+ )
793
+ self._capture_fixture = capture_fixture
794
+
795
+ def unset_fixture(self) -> None:
796
+ self._capture_fixture = None
797
+
798
+ def activate_fixture(self) -> None:
799
+ """If the current item is using ``capsys`` or ``capfd``, activate
800
+ them so they take precedence over the global capture."""
801
+ if self._capture_fixture:
802
+ self._capture_fixture._start()
803
+
804
+ def deactivate_fixture(self) -> None:
805
+ """Deactivate the ``capsys`` or ``capfd`` fixture of this item, if any."""
806
+ if self._capture_fixture:
807
+ self._capture_fixture.close()
808
+
809
+ def suspend_fixture(self) -> None:
810
+ if self._capture_fixture:
811
+ self._capture_fixture._suspend()
812
+
813
+ def resume_fixture(self) -> None:
814
+ if self._capture_fixture:
815
+ self._capture_fixture._resume()
816
+
817
+ # Helper context managers
818
+
819
+ @contextlib.contextmanager
820
+ def global_and_fixture_disabled(self) -> Generator[None, None, None]:
821
+ """Context manager to temporarily disable global and current fixture capturing."""
822
+ do_fixture = self._capture_fixture and self._capture_fixture._is_started()
823
+ if do_fixture:
824
+ self.suspend_fixture()
825
+ do_global = self._global_capturing and self._global_capturing.is_started()
826
+ if do_global:
827
+ self.suspend_global_capture()
828
+ try:
829
+ yield
830
+ finally:
831
+ if do_global:
832
+ self.resume_global_capture()
833
+ if do_fixture:
834
+ self.resume_fixture()
835
+
836
+ @contextlib.contextmanager
837
+ def item_capture(self, when: str, item: Item) -> Generator[None, None, None]:
838
+ self.resume_global_capture()
839
+ self.activate_fixture()
840
+ try:
841
+ yield
842
+ finally:
843
+ self.deactivate_fixture()
844
+ self.suspend_global_capture(in_=False)
845
+
846
+ out, err = self.read_global_capture()
847
+ item.add_report_section(when, "stdout", out)
848
+ item.add_report_section(when, "stderr", err)
849
+
850
+ # Hooks
851
+
852
+ @hookimpl(hookwrapper=True)
853
+ def pytest_make_collect_report(self, collector: Collector):
854
+ if isinstance(collector, File):
855
+ self.resume_global_capture()
856
+ outcome = yield
857
+ self.suspend_global_capture()
858
+ out, err = self.read_global_capture()
859
+ rep = outcome.get_result()
860
+ if out:
861
+ rep.sections.append(("Captured stdout", out))
862
+ if err:
863
+ rep.sections.append(("Captured stderr", err))
864
+ else:
865
+ yield
866
+
867
+ @hookimpl(hookwrapper=True)
868
+ def pytest_runtest_setup(self, item: Item) -> Generator[None, None, None]:
869
+ with self.item_capture("setup", item):
870
+ yield
871
+
872
+ @hookimpl(hookwrapper=True)
873
+ def pytest_runtest_call(self, item: Item) -> Generator[None, None, None]:
874
+ with self.item_capture("call", item):
875
+ yield
876
+
877
+ @hookimpl(hookwrapper=True)
878
+ def pytest_runtest_teardown(self, item: Item) -> Generator[None, None, None]:
879
+ with self.item_capture("teardown", item):
880
+ yield
881
+
882
+ @hookimpl(tryfirst=True)
883
+ def pytest_keyboard_interrupt(self) -> None:
884
+ self.stop_global_capturing()
885
+
886
+ @hookimpl(tryfirst=True)
887
+ def pytest_internalerror(self) -> None:
888
+ self.stop_global_capturing()
889
+
890
+
891
+ class CaptureFixture(Generic[AnyStr]):
892
+ """Object returned by the :fixture:`capsys`, :fixture:`capsysbinary`,
893
+ :fixture:`capfd` and :fixture:`capfdbinary` fixtures."""
894
+
895
+ def __init__(
896
+ self,
897
+ captureclass: Type[CaptureBase[AnyStr]],
898
+ request: SubRequest,
899
+ *,
900
+ _ispytest: bool = False,
901
+ ) -> None:
902
+ check_ispytest(_ispytest)
903
+ self.captureclass: Type[CaptureBase[AnyStr]] = captureclass
904
+ self.request = request
905
+ self._capture: Optional[MultiCapture[AnyStr]] = None
906
+ self._captured_out: AnyStr = self.captureclass.EMPTY_BUFFER
907
+ self._captured_err: AnyStr = self.captureclass.EMPTY_BUFFER
908
+
909
+ def _start(self) -> None:
910
+ if self._capture is None:
911
+ self._capture = MultiCapture(
912
+ in_=None,
913
+ out=self.captureclass(1),
914
+ err=self.captureclass(2),
915
+ )
916
+ self._capture.start_capturing()
917
+
918
+ def close(self) -> None:
919
+ if self._capture is not None:
920
+ out, err = self._capture.pop_outerr_to_orig()
921
+ self._captured_out += out
922
+ self._captured_err += err
923
+ self._capture.stop_capturing()
924
+ self._capture = None
925
+
926
+ def readouterr(self) -> CaptureResult[AnyStr]:
927
+ """Read and return the captured output so far, resetting the internal
928
+ buffer.
929
+
930
+ :returns:
931
+ The captured content as a namedtuple with ``out`` and ``err``
932
+ string attributes.
933
+ """
934
+ captured_out, captured_err = self._captured_out, self._captured_err
935
+ if self._capture is not None:
936
+ out, err = self._capture.readouterr()
937
+ captured_out += out
938
+ captured_err += err
939
+ self._captured_out = self.captureclass.EMPTY_BUFFER
940
+ self._captured_err = self.captureclass.EMPTY_BUFFER
941
+ return CaptureResult(captured_out, captured_err)
942
+
943
+ def _suspend(self) -> None:
944
+ """Suspend this fixture's own capturing temporarily."""
945
+ if self._capture is not None:
946
+ self._capture.suspend_capturing()
947
+
948
+ def _resume(self) -> None:
949
+ """Resume this fixture's own capturing temporarily."""
950
+ if self._capture is not None:
951
+ self._capture.resume_capturing()
952
+
953
+ def _is_started(self) -> bool:
954
+ """Whether actively capturing -- not disabled or closed."""
955
+ if self._capture is not None:
956
+ return self._capture.is_started()
957
+ return False
958
+
959
+ @contextlib.contextmanager
960
+ def disabled(self) -> Generator[None, None, None]:
961
+ """Temporarily disable capturing while inside the ``with`` block."""
962
+ capmanager: CaptureManager = self.request.config.pluginmanager.getplugin(
963
+ "capturemanager"
964
+ )
965
+ with capmanager.global_and_fixture_disabled():
966
+ yield
967
+
968
+
969
+ # The fixtures.
970
+
971
+
972
+ @fixture
973
+ def capsys(request: SubRequest) -> Generator[CaptureFixture[str], None, None]:
974
+ r"""Enable text capturing of writes to ``sys.stdout`` and ``sys.stderr``.
975
+
976
+ The captured output is made available via ``capsys.readouterr()`` method
977
+ calls, which return a ``(out, err)`` namedtuple.
978
+ ``out`` and ``err`` will be ``text`` objects.
979
+
980
+ Returns an instance of :class:`CaptureFixture[str] <pytest.CaptureFixture>`.
981
+
982
+ Example:
983
+
984
+ .. code-block:: python
985
+
986
+ def test_output(capsys):
987
+ print("hello")
988
+ captured = capsys.readouterr()
989
+ assert captured.out == "hello\n"
990
+ """
991
+ capman: CaptureManager = request.config.pluginmanager.getplugin("capturemanager")
992
+ capture_fixture = CaptureFixture(SysCapture, request, _ispytest=True)
993
+ capman.set_fixture(capture_fixture)
994
+ capture_fixture._start()
995
+ yield capture_fixture
996
+ capture_fixture.close()
997
+ capman.unset_fixture()
998
+
999
+
1000
+ @fixture
1001
+ def capsysbinary(request: SubRequest) -> Generator[CaptureFixture[bytes], None, None]:
1002
+ r"""Enable bytes capturing of writes to ``sys.stdout`` and ``sys.stderr``.
1003
+
1004
+ The captured output is made available via ``capsysbinary.readouterr()``
1005
+ method calls, which return a ``(out, err)`` namedtuple.
1006
+ ``out`` and ``err`` will be ``bytes`` objects.
1007
+
1008
+ Returns an instance of :class:`CaptureFixture[bytes] <pytest.CaptureFixture>`.
1009
+
1010
+ Example:
1011
+
1012
+ .. code-block:: python
1013
+
1014
+ def test_output(capsysbinary):
1015
+ print("hello")
1016
+ captured = capsysbinary.readouterr()
1017
+ assert captured.out == b"hello\n"
1018
+ """
1019
+ capman: CaptureManager = request.config.pluginmanager.getplugin("capturemanager")
1020
+ capture_fixture = CaptureFixture(SysCaptureBinary, request, _ispytest=True)
1021
+ capman.set_fixture(capture_fixture)
1022
+ capture_fixture._start()
1023
+ yield capture_fixture
1024
+ capture_fixture.close()
1025
+ capman.unset_fixture()
1026
+
1027
+
1028
+ @fixture
1029
+ def capfd(request: SubRequest) -> Generator[CaptureFixture[str], None, None]:
1030
+ r"""Enable text capturing of writes to file descriptors ``1`` and ``2``.
1031
+
1032
+ The captured output is made available via ``capfd.readouterr()`` method
1033
+ calls, which return a ``(out, err)`` namedtuple.
1034
+ ``out`` and ``err`` will be ``text`` objects.
1035
+
1036
+ Returns an instance of :class:`CaptureFixture[str] <pytest.CaptureFixture>`.
1037
+
1038
+ Example:
1039
+
1040
+ .. code-block:: python
1041
+
1042
+ def test_system_echo(capfd):
1043
+ os.system('echo "hello"')
1044
+ captured = capfd.readouterr()
1045
+ assert captured.out == "hello\n"
1046
+ """
1047
+ capman: CaptureManager = request.config.pluginmanager.getplugin("capturemanager")
1048
+ capture_fixture = CaptureFixture(FDCapture, request, _ispytest=True)
1049
+ capman.set_fixture(capture_fixture)
1050
+ capture_fixture._start()
1051
+ yield capture_fixture
1052
+ capture_fixture.close()
1053
+ capman.unset_fixture()
1054
+
1055
+
1056
+ @fixture
1057
+ def capfdbinary(request: SubRequest) -> Generator[CaptureFixture[bytes], None, None]:
1058
+ r"""Enable bytes capturing of writes to file descriptors ``1`` and ``2``.
1059
+
1060
+ The captured output is made available via ``capfd.readouterr()`` method
1061
+ calls, which return a ``(out, err)`` namedtuple.
1062
+ ``out`` and ``err`` will be ``byte`` objects.
1063
+
1064
+ Returns an instance of :class:`CaptureFixture[bytes] <pytest.CaptureFixture>`.
1065
+
1066
+ Example:
1067
+
1068
+ .. code-block:: python
1069
+
1070
+ def test_system_echo(capfdbinary):
1071
+ os.system('echo "hello"')
1072
+ captured = capfdbinary.readouterr()
1073
+ assert captured.out == b"hello\n"
1074
+
1075
+ """
1076
+ capman: CaptureManager = request.config.pluginmanager.getplugin("capturemanager")
1077
+ capture_fixture = CaptureFixture(FDCaptureBinary, request, _ispytest=True)
1078
+ capman.set_fixture(capture_fixture)
1079
+ capture_fixture._start()
1080
+ yield capture_fixture
1081
+ capture_fixture.close()
1082
+ capman.unset_fixture()
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/compat.py ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Python version compatibility code."""
2
+ from __future__ import annotations
3
+
4
+ import dataclasses
5
+ import enum
6
+ import functools
7
+ import inspect
8
+ import os
9
+ import sys
10
+ from inspect import Parameter
11
+ from inspect import signature
12
+ from pathlib import Path
13
+ from typing import Any
14
+ from typing import Callable
15
+ from typing import Generic
16
+ from typing import NoReturn
17
+ from typing import TYPE_CHECKING
18
+ from typing import TypeVar
19
+
20
+ import py
21
+
22
+ # fmt: off
23
+ # Workaround for https://github.com/sphinx-doc/sphinx/issues/10351.
24
+ # If `overload` is imported from `compat` instead of from `typing`,
25
+ # Sphinx doesn't recognize it as `overload` and the API docs for
26
+ # overloaded functions look good again. But type checkers handle
27
+ # it fine.
28
+ # fmt: on
29
+ if True:
30
+ from typing import overload as overload
31
+
32
+ if TYPE_CHECKING:
33
+ from typing_extensions import Final
34
+
35
+
36
+ _T = TypeVar("_T")
37
+ _S = TypeVar("_S")
38
+
39
+ #: constant to prepare valuing pylib path replacements/lazy proxies later on
40
+ # intended for removal in pytest 8.0 or 9.0
41
+
42
+ # fmt: off
43
+ # intentional space to create a fake difference for the verification
44
+ LEGACY_PATH = py.path. local
45
+ # fmt: on
46
+
47
+
48
+ def legacy_path(path: str | os.PathLike[str]) -> LEGACY_PATH:
49
+ """Internal wrapper to prepare lazy proxies for legacy_path instances"""
50
+ return LEGACY_PATH(path)
51
+
52
+
53
+ # fmt: off
54
+ # Singleton type for NOTSET, as described in:
55
+ # https://www.python.org/dev/peps/pep-0484/#support-for-singleton-types-in-unions
56
+ class NotSetType(enum.Enum):
57
+ token = 0
58
+ NOTSET: Final = NotSetType.token # noqa: E305
59
+ # fmt: on
60
+
61
+ if sys.version_info >= (3, 8):
62
+ import importlib.metadata
63
+
64
+ importlib_metadata = importlib.metadata
65
+ else:
66
+ import importlib_metadata as importlib_metadata # noqa: F401
67
+
68
+
69
+ def _format_args(func: Callable[..., Any]) -> str:
70
+ return str(signature(func))
71
+
72
+
73
+ def is_generator(func: object) -> bool:
74
+ genfunc = inspect.isgeneratorfunction(func)
75
+ return genfunc and not iscoroutinefunction(func)
76
+
77
+
78
+ def iscoroutinefunction(func: object) -> bool:
79
+ """Return True if func is a coroutine function (a function defined with async
80
+ def syntax, and doesn't contain yield), or a function decorated with
81
+ @asyncio.coroutine.
82
+
83
+ Note: copied and modified from Python 3.5's builtin couroutines.py to avoid
84
+ importing asyncio directly, which in turns also initializes the "logging"
85
+ module as a side-effect (see issue #8).
86
+ """
87
+ return inspect.iscoroutinefunction(func) or getattr(func, "_is_coroutine", False)
88
+
89
+
90
+ def is_async_function(func: object) -> bool:
91
+ """Return True if the given function seems to be an async function or
92
+ an async generator."""
93
+ return iscoroutinefunction(func) or inspect.isasyncgenfunction(func)
94
+
95
+
96
+ def getlocation(function, curdir: str | None = None) -> str:
97
+ function = get_real_func(function)
98
+ fn = Path(inspect.getfile(function))
99
+ lineno = function.__code__.co_firstlineno
100
+ if curdir is not None:
101
+ try:
102
+ relfn = fn.relative_to(curdir)
103
+ except ValueError:
104
+ pass
105
+ else:
106
+ return "%s:%d" % (relfn, lineno + 1)
107
+ return "%s:%d" % (fn, lineno + 1)
108
+
109
+
110
+ def num_mock_patch_args(function) -> int:
111
+ """Return number of arguments used up by mock arguments (if any)."""
112
+ patchings = getattr(function, "patchings", None)
113
+ if not patchings:
114
+ return 0
115
+
116
+ mock_sentinel = getattr(sys.modules.get("mock"), "DEFAULT", object())
117
+ ut_mock_sentinel = getattr(sys.modules.get("unittest.mock"), "DEFAULT", object())
118
+
119
+ return len(
120
+ [
121
+ p
122
+ for p in patchings
123
+ if not p.attribute_name
124
+ and (p.new is mock_sentinel or p.new is ut_mock_sentinel)
125
+ ]
126
+ )
127
+
128
+
129
+ def getfuncargnames(
130
+ function: Callable[..., Any],
131
+ *,
132
+ name: str = "",
133
+ is_method: bool = False,
134
+ cls: type | None = None,
135
+ ) -> tuple[str, ...]:
136
+ """Return the names of a function's mandatory arguments.
137
+
138
+ Should return the names of all function arguments that:
139
+ * Aren't bound to an instance or type as in instance or class methods.
140
+ * Don't have default values.
141
+ * Aren't bound with functools.partial.
142
+ * Aren't replaced with mocks.
143
+
144
+ The is_method and cls arguments indicate that the function should
145
+ be treated as a bound method even though it's not unless, only in
146
+ the case of cls, the function is a static method.
147
+
148
+ The name parameter should be the original name in which the function was collected.
149
+ """
150
+ # TODO(RonnyPfannschmidt): This function should be refactored when we
151
+ # revisit fixtures. The fixture mechanism should ask the node for
152
+ # the fixture names, and not try to obtain directly from the
153
+ # function object well after collection has occurred.
154
+
155
+ # The parameters attribute of a Signature object contains an
156
+ # ordered mapping of parameter names to Parameter instances. This
157
+ # creates a tuple of the names of the parameters that don't have
158
+ # defaults.
159
+ try:
160
+ parameters = signature(function).parameters
161
+ except (ValueError, TypeError) as e:
162
+ from _pytest.outcomes import fail
163
+
164
+ fail(
165
+ f"Could not determine arguments of {function!r}: {e}",
166
+ pytrace=False,
167
+ )
168
+
169
+ arg_names = tuple(
170
+ p.name
171
+ for p in parameters.values()
172
+ if (
173
+ p.kind is Parameter.POSITIONAL_OR_KEYWORD
174
+ or p.kind is Parameter.KEYWORD_ONLY
175
+ )
176
+ and p.default is Parameter.empty
177
+ )
178
+ if not name:
179
+ name = function.__name__
180
+
181
+ # If this function should be treated as a bound method even though
182
+ # it's passed as an unbound method or function, remove the first
183
+ # parameter name.
184
+ if is_method or (
185
+ # Not using `getattr` because we don't want to resolve the staticmethod.
186
+ # Not using `cls.__dict__` because we want to check the entire MRO.
187
+ cls
188
+ and not isinstance(
189
+ inspect.getattr_static(cls, name, default=None), staticmethod
190
+ )
191
+ ):
192
+ arg_names = arg_names[1:]
193
+ # Remove any names that will be replaced with mocks.
194
+ if hasattr(function, "__wrapped__"):
195
+ arg_names = arg_names[num_mock_patch_args(function) :]
196
+ return arg_names
197
+
198
+
199
+ def get_default_arg_names(function: Callable[..., Any]) -> tuple[str, ...]:
200
+ # Note: this code intentionally mirrors the code at the beginning of
201
+ # getfuncargnames, to get the arguments which were excluded from its result
202
+ # because they had default values.
203
+ return tuple(
204
+ p.name
205
+ for p in signature(function).parameters.values()
206
+ if p.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY)
207
+ and p.default is not Parameter.empty
208
+ )
209
+
210
+
211
+ _non_printable_ascii_translate_table = {
212
+ i: f"\\x{i:02x}" for i in range(128) if i not in range(32, 127)
213
+ }
214
+ _non_printable_ascii_translate_table.update(
215
+ {ord("\t"): "\\t", ord("\r"): "\\r", ord("\n"): "\\n"}
216
+ )
217
+
218
+
219
+ def _translate_non_printable(s: str) -> str:
220
+ return s.translate(_non_printable_ascii_translate_table)
221
+
222
+
223
+ STRING_TYPES = bytes, str
224
+
225
+
226
+ def _bytes_to_ascii(val: bytes) -> str:
227
+ return val.decode("ascii", "backslashreplace")
228
+
229
+
230
+ def ascii_escaped(val: bytes | str) -> str:
231
+ r"""If val is pure ASCII, return it as an str, otherwise, escape
232
+ bytes objects into a sequence of escaped bytes:
233
+
234
+ b'\xc3\xb4\xc5\xd6' -> r'\xc3\xb4\xc5\xd6'
235
+
236
+ and escapes unicode objects into a sequence of escaped unicode
237
+ ids, e.g.:
238
+
239
+ r'4\nV\U00043efa\x0eMXWB\x1e\u3028\u15fd\xcd\U0007d944'
240
+
241
+ Note:
242
+ The obvious "v.decode('unicode-escape')" will return
243
+ valid UTF-8 unicode if it finds them in bytes, but we
244
+ want to return escaped bytes for any byte, even if they match
245
+ a UTF-8 string.
246
+ """
247
+ if isinstance(val, bytes):
248
+ ret = _bytes_to_ascii(val)
249
+ else:
250
+ ret = val.encode("unicode_escape").decode("ascii")
251
+ return _translate_non_printable(ret)
252
+
253
+
254
+ @dataclasses.dataclass
255
+ class _PytestWrapper:
256
+ """Dummy wrapper around a function object for internal use only.
257
+
258
+ Used to correctly unwrap the underlying function object when we are
259
+ creating fixtures, because we wrap the function object ourselves with a
260
+ decorator to issue warnings when the fixture function is called directly.
261
+ """
262
+
263
+ obj: Any
264
+
265
+
266
+ def get_real_func(obj):
267
+ """Get the real function object of the (possibly) wrapped object by
268
+ functools.wraps or functools.partial."""
269
+ start_obj = obj
270
+ for i in range(100):
271
+ # __pytest_wrapped__ is set by @pytest.fixture when wrapping the fixture function
272
+ # to trigger a warning if it gets called directly instead of by pytest: we don't
273
+ # want to unwrap further than this otherwise we lose useful wrappings like @mock.patch (#3774)
274
+ new_obj = getattr(obj, "__pytest_wrapped__", None)
275
+ if isinstance(new_obj, _PytestWrapper):
276
+ obj = new_obj.obj
277
+ break
278
+ new_obj = getattr(obj, "__wrapped__", None)
279
+ if new_obj is None:
280
+ break
281
+ obj = new_obj
282
+ else:
283
+ from _pytest._io.saferepr import saferepr
284
+
285
+ raise ValueError(
286
+ ("could not find real function of {start}\nstopped at {current}").format(
287
+ start=saferepr(start_obj), current=saferepr(obj)
288
+ )
289
+ )
290
+ if isinstance(obj, functools.partial):
291
+ obj = obj.func
292
+ return obj
293
+
294
+
295
+ def get_real_method(obj, holder):
296
+ """Attempt to obtain the real function object that might be wrapping
297
+ ``obj``, while at the same time returning a bound method to ``holder`` if
298
+ the original object was a bound method."""
299
+ try:
300
+ is_method = hasattr(obj, "__func__")
301
+ obj = get_real_func(obj)
302
+ except Exception: # pragma: no cover
303
+ return obj
304
+ if is_method and hasattr(obj, "__get__") and callable(obj.__get__):
305
+ obj = obj.__get__(holder)
306
+ return obj
307
+
308
+
309
+ def getimfunc(func):
310
+ try:
311
+ return func.__func__
312
+ except AttributeError:
313
+ return func
314
+
315
+
316
+ def safe_getattr(object: Any, name: str, default: Any) -> Any:
317
+ """Like getattr but return default upon any Exception or any OutcomeException.
318
+
319
+ Attribute access can potentially fail for 'evil' Python objects.
320
+ See issue #214.
321
+ It catches OutcomeException because of #2490 (issue #580), new outcomes
322
+ are derived from BaseException instead of Exception (for more details
323
+ check #2707).
324
+ """
325
+ from _pytest.outcomes import TEST_OUTCOME
326
+
327
+ try:
328
+ return getattr(object, name, default)
329
+ except TEST_OUTCOME:
330
+ return default
331
+
332
+
333
+ def safe_isclass(obj: object) -> bool:
334
+ """Ignore any exception via isinstance on Python 3."""
335
+ try:
336
+ return inspect.isclass(obj)
337
+ except Exception:
338
+ return False
339
+
340
+
341
+ if TYPE_CHECKING:
342
+ if sys.version_info >= (3, 8):
343
+ from typing import final as final
344
+ else:
345
+ from typing_extensions import final as final
346
+ elif sys.version_info >= (3, 8):
347
+ from typing import final as final
348
+ else:
349
+
350
+ def final(f):
351
+ return f
352
+
353
+
354
+ if sys.version_info >= (3, 8):
355
+ from functools import cached_property as cached_property
356
+ else:
357
+
358
+ class cached_property(Generic[_S, _T]):
359
+ __slots__ = ("func", "__doc__")
360
+
361
+ def __init__(self, func: Callable[[_S], _T]) -> None:
362
+ self.func = func
363
+ self.__doc__ = func.__doc__
364
+
365
+ @overload
366
+ def __get__(
367
+ self, instance: None, owner: type[_S] | None = ...
368
+ ) -> cached_property[_S, _T]:
369
+ ...
370
+
371
+ @overload
372
+ def __get__(self, instance: _S, owner: type[_S] | None = ...) -> _T:
373
+ ...
374
+
375
+ def __get__(self, instance, owner=None):
376
+ if instance is None:
377
+ return self
378
+ value = instance.__dict__[self.func.__name__] = self.func(instance)
379
+ return value
380
+
381
+
382
+ def get_user_id() -> int | None:
383
+ """Return the current process's real user id or None if it could not be
384
+ determined.
385
+
386
+ :return: The user id or None if it could not be determined.
387
+ """
388
+ # mypy follows the version and platform checking expectation of PEP 484:
389
+ # https://mypy.readthedocs.io/en/stable/common_issues.html?highlight=platform#python-version-and-system-platform-checks
390
+ # Containment checks are too complex for mypy v1.5.0 and cause failure.
391
+ if sys.platform == "win32" or sys.platform == "emscripten":
392
+ # win32 does not have a getuid() function.
393
+ # Emscripten has a return 0 stub.
394
+ return None
395
+ else:
396
+ # On other platforms, a return value of -1 is assumed to indicate that
397
+ # the current process's real user id could not be determined.
398
+ ERROR = -1
399
+ uid = os.getuid()
400
+ return uid if uid != ERROR else None
401
+
402
+
403
+ # Perform exhaustiveness checking.
404
+ #
405
+ # Consider this example:
406
+ #
407
+ # MyUnion = Union[int, str]
408
+ #
409
+ # def handle(x: MyUnion) -> int {
410
+ # if isinstance(x, int):
411
+ # return 1
412
+ # elif isinstance(x, str):
413
+ # return 2
414
+ # else:
415
+ # raise Exception('unreachable')
416
+ #
417
+ # Now suppose we add a new variant:
418
+ #
419
+ # MyUnion = Union[int, str, bytes]
420
+ #
421
+ # After doing this, we must remember ourselves to go and update the handle
422
+ # function to handle the new variant.
423
+ #
424
+ # With `assert_never` we can do better:
425
+ #
426
+ # // raise Exception('unreachable')
427
+ # return assert_never(x)
428
+ #
429
+ # Now, if we forget to handle the new variant, the type-checker will emit a
430
+ # compile-time error, instead of the runtime error we would have gotten
431
+ # previously.
432
+ #
433
+ # This also work for Enums (if you use `is` to compare) and Literals.
434
+ def assert_never(value: NoReturn) -> NoReturn:
435
+ assert False, f"Unhandled value: {value} ({type(value).__name__})"
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/debugging.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Interactive debugging with PDB, the Python Debugger."""
2
+ import argparse
3
+ import functools
4
+ import sys
5
+ import types
6
+ import unittest
7
+ from typing import Any
8
+ from typing import Callable
9
+ from typing import Generator
10
+ from typing import List
11
+ from typing import Optional
12
+ from typing import Tuple
13
+ from typing import Type
14
+ from typing import TYPE_CHECKING
15
+ from typing import Union
16
+
17
+ from _pytest import outcomes
18
+ from _pytest._code import ExceptionInfo
19
+ from _pytest.config import Config
20
+ from _pytest.config import ConftestImportFailure
21
+ from _pytest.config import hookimpl
22
+ from _pytest.config import PytestPluginManager
23
+ from _pytest.config.argparsing import Parser
24
+ from _pytest.config.exceptions import UsageError
25
+ from _pytest.nodes import Node
26
+ from _pytest.reports import BaseReport
27
+
28
+ if TYPE_CHECKING:
29
+ from _pytest.capture import CaptureManager
30
+ from _pytest.runner import CallInfo
31
+
32
+
33
+ def _validate_usepdb_cls(value: str) -> Tuple[str, str]:
34
+ """Validate syntax of --pdbcls option."""
35
+ try:
36
+ modname, classname = value.split(":")
37
+ except ValueError as e:
38
+ raise argparse.ArgumentTypeError(
39
+ f"{value!r} is not in the format 'modname:classname'"
40
+ ) from e
41
+ return (modname, classname)
42
+
43
+
44
+ def pytest_addoption(parser: Parser) -> None:
45
+ group = parser.getgroup("general")
46
+ group._addoption(
47
+ "--pdb",
48
+ dest="usepdb",
49
+ action="store_true",
50
+ help="Start the interactive Python debugger on errors or KeyboardInterrupt",
51
+ )
52
+ group._addoption(
53
+ "--pdbcls",
54
+ dest="usepdb_cls",
55
+ metavar="modulename:classname",
56
+ type=_validate_usepdb_cls,
57
+ help="Specify a custom interactive Python debugger for use with --pdb."
58
+ "For example: --pdbcls=IPython.terminal.debugger:TerminalPdb",
59
+ )
60
+ group._addoption(
61
+ "--trace",
62
+ dest="trace",
63
+ action="store_true",
64
+ help="Immediately break when running each test",
65
+ )
66
+
67
+
68
+ def pytest_configure(config: Config) -> None:
69
+ import pdb
70
+
71
+ if config.getvalue("trace"):
72
+ config.pluginmanager.register(PdbTrace(), "pdbtrace")
73
+ if config.getvalue("usepdb"):
74
+ config.pluginmanager.register(PdbInvoke(), "pdbinvoke")
75
+
76
+ pytestPDB._saved.append(
77
+ (pdb.set_trace, pytestPDB._pluginmanager, pytestPDB._config)
78
+ )
79
+ pdb.set_trace = pytestPDB.set_trace
80
+ pytestPDB._pluginmanager = config.pluginmanager
81
+ pytestPDB._config = config
82
+
83
+ # NOTE: not using pytest_unconfigure, since it might get called although
84
+ # pytest_configure was not (if another plugin raises UsageError).
85
+ def fin() -> None:
86
+ (
87
+ pdb.set_trace,
88
+ pytestPDB._pluginmanager,
89
+ pytestPDB._config,
90
+ ) = pytestPDB._saved.pop()
91
+
92
+ config.add_cleanup(fin)
93
+
94
+
95
+ class pytestPDB:
96
+ """Pseudo PDB that defers to the real pdb."""
97
+
98
+ _pluginmanager: Optional[PytestPluginManager] = None
99
+ _config: Optional[Config] = None
100
+ _saved: List[
101
+ Tuple[Callable[..., None], Optional[PytestPluginManager], Optional[Config]]
102
+ ] = []
103
+ _recursive_debug = 0
104
+ _wrapped_pdb_cls: Optional[Tuple[Type[Any], Type[Any]]] = None
105
+
106
+ @classmethod
107
+ def _is_capturing(cls, capman: Optional["CaptureManager"]) -> Union[str, bool]:
108
+ if capman:
109
+ return capman.is_capturing()
110
+ return False
111
+
112
+ @classmethod
113
+ def _import_pdb_cls(cls, capman: Optional["CaptureManager"]):
114
+ if not cls._config:
115
+ import pdb
116
+
117
+ # Happens when using pytest.set_trace outside of a test.
118
+ return pdb.Pdb
119
+
120
+ usepdb_cls = cls._config.getvalue("usepdb_cls")
121
+
122
+ if cls._wrapped_pdb_cls and cls._wrapped_pdb_cls[0] == usepdb_cls:
123
+ return cls._wrapped_pdb_cls[1]
124
+
125
+ if usepdb_cls:
126
+ modname, classname = usepdb_cls
127
+
128
+ try:
129
+ __import__(modname)
130
+ mod = sys.modules[modname]
131
+
132
+ # Handle --pdbcls=pdb:pdb.Pdb (useful e.g. with pdbpp).
133
+ parts = classname.split(".")
134
+ pdb_cls = getattr(mod, parts[0])
135
+ for part in parts[1:]:
136
+ pdb_cls = getattr(pdb_cls, part)
137
+ except Exception as exc:
138
+ value = ":".join((modname, classname))
139
+ raise UsageError(
140
+ f"--pdbcls: could not import {value!r}: {exc}"
141
+ ) from exc
142
+ else:
143
+ import pdb
144
+
145
+ pdb_cls = pdb.Pdb
146
+
147
+ wrapped_cls = cls._get_pdb_wrapper_class(pdb_cls, capman)
148
+ cls._wrapped_pdb_cls = (usepdb_cls, wrapped_cls)
149
+ return wrapped_cls
150
+
151
+ @classmethod
152
+ def _get_pdb_wrapper_class(cls, pdb_cls, capman: Optional["CaptureManager"]):
153
+ import _pytest.config
154
+
155
+ # Type ignored because mypy doesn't support "dynamic"
156
+ # inheritance like this.
157
+ class PytestPdbWrapper(pdb_cls): # type: ignore[valid-type,misc]
158
+ _pytest_capman = capman
159
+ _continued = False
160
+
161
+ def do_debug(self, arg):
162
+ cls._recursive_debug += 1
163
+ ret = super().do_debug(arg)
164
+ cls._recursive_debug -= 1
165
+ return ret
166
+
167
+ def do_continue(self, arg):
168
+ ret = super().do_continue(arg)
169
+ if cls._recursive_debug == 0:
170
+ assert cls._config is not None
171
+ tw = _pytest.config.create_terminal_writer(cls._config)
172
+ tw.line()
173
+
174
+ capman = self._pytest_capman
175
+ capturing = pytestPDB._is_capturing(capman)
176
+ if capturing:
177
+ if capturing == "global":
178
+ tw.sep(">", "PDB continue (IO-capturing resumed)")
179
+ else:
180
+ tw.sep(
181
+ ">",
182
+ "PDB continue (IO-capturing resumed for %s)"
183
+ % capturing,
184
+ )
185
+ assert capman is not None
186
+ capman.resume()
187
+ else:
188
+ tw.sep(">", "PDB continue")
189
+ assert cls._pluginmanager is not None
190
+ cls._pluginmanager.hook.pytest_leave_pdb(config=cls._config, pdb=self)
191
+ self._continued = True
192
+ return ret
193
+
194
+ do_c = do_cont = do_continue
195
+
196
+ def do_quit(self, arg):
197
+ """Raise Exit outcome when quit command is used in pdb.
198
+
199
+ This is a bit of a hack - it would be better if BdbQuit
200
+ could be handled, but this would require to wrap the
201
+ whole pytest run, and adjust the report etc.
202
+ """
203
+ ret = super().do_quit(arg)
204
+
205
+ if cls._recursive_debug == 0:
206
+ outcomes.exit("Quitting debugger")
207
+
208
+ return ret
209
+
210
+ do_q = do_quit
211
+ do_exit = do_quit
212
+
213
+ def setup(self, f, tb):
214
+ """Suspend on setup().
215
+
216
+ Needed after do_continue resumed, and entering another
217
+ breakpoint again.
218
+ """
219
+ ret = super().setup(f, tb)
220
+ if not ret and self._continued:
221
+ # pdb.setup() returns True if the command wants to exit
222
+ # from the interaction: do not suspend capturing then.
223
+ if self._pytest_capman:
224
+ self._pytest_capman.suspend_global_capture(in_=True)
225
+ return ret
226
+
227
+ def get_stack(self, f, t):
228
+ stack, i = super().get_stack(f, t)
229
+ if f is None:
230
+ # Find last non-hidden frame.
231
+ i = max(0, len(stack) - 1)
232
+ while i and stack[i][0].f_locals.get("__tracebackhide__", False):
233
+ i -= 1
234
+ return stack, i
235
+
236
+ return PytestPdbWrapper
237
+
238
+ @classmethod
239
+ def _init_pdb(cls, method, *args, **kwargs):
240
+ """Initialize PDB debugging, dropping any IO capturing."""
241
+ import _pytest.config
242
+
243
+ if cls._pluginmanager is None:
244
+ capman: Optional[CaptureManager] = None
245
+ else:
246
+ capman = cls._pluginmanager.getplugin("capturemanager")
247
+ if capman:
248
+ capman.suspend(in_=True)
249
+
250
+ if cls._config:
251
+ tw = _pytest.config.create_terminal_writer(cls._config)
252
+ tw.line()
253
+
254
+ if cls._recursive_debug == 0:
255
+ # Handle header similar to pdb.set_trace in py37+.
256
+ header = kwargs.pop("header", None)
257
+ if header is not None:
258
+ tw.sep(">", header)
259
+ else:
260
+ capturing = cls._is_capturing(capman)
261
+ if capturing == "global":
262
+ tw.sep(">", f"PDB {method} (IO-capturing turned off)")
263
+ elif capturing:
264
+ tw.sep(
265
+ ">",
266
+ "PDB %s (IO-capturing turned off for %s)"
267
+ % (method, capturing),
268
+ )
269
+ else:
270
+ tw.sep(">", f"PDB {method}")
271
+
272
+ _pdb = cls._import_pdb_cls(capman)(**kwargs)
273
+
274
+ if cls._pluginmanager:
275
+ cls._pluginmanager.hook.pytest_enter_pdb(config=cls._config, pdb=_pdb)
276
+ return _pdb
277
+
278
+ @classmethod
279
+ def set_trace(cls, *args, **kwargs) -> None:
280
+ """Invoke debugging via ``Pdb.set_trace``, dropping any IO capturing."""
281
+ frame = sys._getframe().f_back
282
+ _pdb = cls._init_pdb("set_trace", *args, **kwargs)
283
+ _pdb.set_trace(frame)
284
+
285
+
286
+ class PdbInvoke:
287
+ def pytest_exception_interact(
288
+ self, node: Node, call: "CallInfo[Any]", report: BaseReport
289
+ ) -> None:
290
+ capman = node.config.pluginmanager.getplugin("capturemanager")
291
+ if capman:
292
+ capman.suspend_global_capture(in_=True)
293
+ out, err = capman.read_global_capture()
294
+ sys.stdout.write(out)
295
+ sys.stdout.write(err)
296
+ assert call.excinfo is not None
297
+
298
+ if not isinstance(call.excinfo.value, unittest.SkipTest):
299
+ _enter_pdb(node, call.excinfo, report)
300
+
301
+ def pytest_internalerror(self, excinfo: ExceptionInfo[BaseException]) -> None:
302
+ tb = _postmortem_traceback(excinfo)
303
+ post_mortem(tb)
304
+
305
+
306
+ class PdbTrace:
307
+ @hookimpl(hookwrapper=True)
308
+ def pytest_pyfunc_call(self, pyfuncitem) -> Generator[None, None, None]:
309
+ wrap_pytest_function_for_tracing(pyfuncitem)
310
+ yield
311
+
312
+
313
+ def wrap_pytest_function_for_tracing(pyfuncitem):
314
+ """Change the Python function object of the given Function item by a
315
+ wrapper which actually enters pdb before calling the python function
316
+ itself, effectively leaving the user in the pdb prompt in the first
317
+ statement of the function."""
318
+ _pdb = pytestPDB._init_pdb("runcall")
319
+ testfunction = pyfuncitem.obj
320
+
321
+ # we can't just return `partial(pdb.runcall, testfunction)` because (on
322
+ # python < 3.7.4) runcall's first param is `func`, which means we'd get
323
+ # an exception if one of the kwargs to testfunction was called `func`.
324
+ @functools.wraps(testfunction)
325
+ def wrapper(*args, **kwargs):
326
+ func = functools.partial(testfunction, *args, **kwargs)
327
+ _pdb.runcall(func)
328
+
329
+ pyfuncitem.obj = wrapper
330
+
331
+
332
+ def maybe_wrap_pytest_function_for_tracing(pyfuncitem):
333
+ """Wrap the given pytestfunct item for tracing support if --trace was given in
334
+ the command line."""
335
+ if pyfuncitem.config.getvalue("trace"):
336
+ wrap_pytest_function_for_tracing(pyfuncitem)
337
+
338
+
339
+ def _enter_pdb(
340
+ node: Node, excinfo: ExceptionInfo[BaseException], rep: BaseReport
341
+ ) -> BaseReport:
342
+ # XXX we re-use the TerminalReporter's terminalwriter
343
+ # because this seems to avoid some encoding related troubles
344
+ # for not completely clear reasons.
345
+ tw = node.config.pluginmanager.getplugin("terminalreporter")._tw
346
+ tw.line()
347
+
348
+ showcapture = node.config.option.showcapture
349
+
350
+ for sectionname, content in (
351
+ ("stdout", rep.capstdout),
352
+ ("stderr", rep.capstderr),
353
+ ("log", rep.caplog),
354
+ ):
355
+ if showcapture in (sectionname, "all") and content:
356
+ tw.sep(">", "captured " + sectionname)
357
+ if content[-1:] == "\n":
358
+ content = content[:-1]
359
+ tw.line(content)
360
+
361
+ tw.sep(">", "traceback")
362
+ rep.toterminal(tw)
363
+ tw.sep(">", "entering PDB")
364
+ tb = _postmortem_traceback(excinfo)
365
+ rep._pdbshown = True # type: ignore[attr-defined]
366
+ post_mortem(tb)
367
+ return rep
368
+
369
+
370
+ def _postmortem_traceback(excinfo: ExceptionInfo[BaseException]) -> types.TracebackType:
371
+ from doctest import UnexpectedException
372
+
373
+ if isinstance(excinfo.value, UnexpectedException):
374
+ # A doctest.UnexpectedException is not useful for post_mortem.
375
+ # Use the underlying exception instead:
376
+ return excinfo.value.exc_info[2]
377
+ elif isinstance(excinfo.value, ConftestImportFailure):
378
+ # A config.ConftestImportFailure is not useful for post_mortem.
379
+ # Use the underlying exception instead:
380
+ return excinfo.value.excinfo[2]
381
+ else:
382
+ assert excinfo._excinfo is not None
383
+ return excinfo._excinfo[2]
384
+
385
+
386
+ def post_mortem(t: types.TracebackType) -> None:
387
+ p = pytestPDB._init_pdb("post_mortem")
388
+ p.reset()
389
+ p.interaction(None, t)
390
+ if p.quitting:
391
+ outcomes.exit("Quitting debugger")
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/deprecated.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deprecation messages and bits of code used elsewhere in the codebase that
2
+ is planned to be removed in the next pytest release.
3
+
4
+ Keeping it in a central location makes it easy to track what is deprecated and should
5
+ be removed when the time comes.
6
+
7
+ All constants defined in this module should be either instances of
8
+ :class:`PytestWarning`, or :class:`UnformattedWarning`
9
+ in case of warnings which need to format their messages.
10
+ """
11
+ from warnings import warn
12
+
13
+ from _pytest.warning_types import PytestDeprecationWarning
14
+ from _pytest.warning_types import PytestRemovedIn8Warning
15
+ from _pytest.warning_types import UnformattedWarning
16
+
17
+ # set of plugins which have been integrated into the core; we use this list to ignore
18
+ # them during registration to avoid conflicts
19
+ DEPRECATED_EXTERNAL_PLUGINS = {
20
+ "pytest_catchlog",
21
+ "pytest_capturelog",
22
+ "pytest_faulthandler",
23
+ }
24
+
25
+ NOSE_SUPPORT = UnformattedWarning(
26
+ PytestRemovedIn8Warning,
27
+ "Support for nose tests is deprecated and will be removed in a future release.\n"
28
+ "{nodeid} is using nose method: `{method}` ({stage})\n"
29
+ "See docs: https://docs.pytest.org/en/stable/deprecations.html#support-for-tests-written-for-nose",
30
+ )
31
+
32
+ NOSE_SUPPORT_METHOD = UnformattedWarning(
33
+ PytestRemovedIn8Warning,
34
+ "Support for nose tests is deprecated and will be removed in a future release.\n"
35
+ "{nodeid} is using nose-specific method: `{method}(self)`\n"
36
+ "To remove this warning, rename it to `{method}_method(self)`\n"
37
+ "See docs: https://docs.pytest.org/en/stable/deprecations.html#support-for-tests-written-for-nose",
38
+ )
39
+
40
+
41
+ # This can be* removed pytest 8, but it's harmless and common, so no rush to remove.
42
+ # * If you're in the future: "could have been".
43
+ YIELD_FIXTURE = PytestDeprecationWarning(
44
+ "@pytest.yield_fixture is deprecated.\n"
45
+ "Use @pytest.fixture instead; they are the same."
46
+ )
47
+
48
+ WARNING_CMDLINE_PREPARSE_HOOK = PytestRemovedIn8Warning(
49
+ "The pytest_cmdline_preparse hook is deprecated and will be removed in a future release. \n"
50
+ "Please use pytest_load_initial_conftests hook instead."
51
+ )
52
+
53
+ FSCOLLECTOR_GETHOOKPROXY_ISINITPATH = PytestRemovedIn8Warning(
54
+ "The gethookproxy() and isinitpath() methods of FSCollector and Package are deprecated; "
55
+ "use self.session.gethookproxy() and self.session.isinitpath() instead. "
56
+ )
57
+
58
+ STRICT_OPTION = PytestRemovedIn8Warning(
59
+ "The --strict option is deprecated, use --strict-markers instead."
60
+ )
61
+
62
+ # This deprecation is never really meant to be removed.
63
+ PRIVATE = PytestDeprecationWarning("A private pytest class or function was used.")
64
+
65
+ ARGUMENT_PERCENT_DEFAULT = PytestRemovedIn8Warning(
66
+ 'pytest now uses argparse. "%default" should be changed to "%(default)s"',
67
+ )
68
+
69
+ ARGUMENT_TYPE_STR_CHOICE = UnformattedWarning(
70
+ PytestRemovedIn8Warning,
71
+ "`type` argument to addoption() is the string {typ!r}."
72
+ " For choices this is optional and can be omitted, "
73
+ " but when supplied should be a type (for example `str` or `int`)."
74
+ " (options: {names})",
75
+ )
76
+
77
+ ARGUMENT_TYPE_STR = UnformattedWarning(
78
+ PytestRemovedIn8Warning,
79
+ "`type` argument to addoption() is the string {typ!r}, "
80
+ " but when supplied should be a type (for example `str` or `int`)."
81
+ " (options: {names})",
82
+ )
83
+
84
+
85
+ HOOK_LEGACY_PATH_ARG = UnformattedWarning(
86
+ PytestRemovedIn8Warning,
87
+ "The ({pylib_path_arg}: py.path.local) argument is deprecated, please use ({pathlib_path_arg}: pathlib.Path)\n"
88
+ "see https://docs.pytest.org/en/latest/deprecations.html"
89
+ "#py-path-local-arguments-for-hooks-replaced-with-pathlib-path",
90
+ )
91
+
92
+ NODE_CTOR_FSPATH_ARG = UnformattedWarning(
93
+ PytestRemovedIn8Warning,
94
+ "The (fspath: py.path.local) argument to {node_type_name} is deprecated. "
95
+ "Please use the (path: pathlib.Path) argument instead.\n"
96
+ "See https://docs.pytest.org/en/latest/deprecations.html"
97
+ "#fspath-argument-for-node-constructors-replaced-with-pathlib-path",
98
+ )
99
+
100
+ WARNS_NONE_ARG = PytestRemovedIn8Warning(
101
+ "Passing None has been deprecated.\n"
102
+ "See https://docs.pytest.org/en/latest/how-to/capture-warnings.html"
103
+ "#additional-use-cases-of-warnings-in-tests"
104
+ " for alternatives in common use cases."
105
+ )
106
+
107
+ KEYWORD_MSG_ARG = UnformattedWarning(
108
+ PytestRemovedIn8Warning,
109
+ "pytest.{func}(msg=...) is now deprecated, use pytest.{func}(reason=...) instead",
110
+ )
111
+
112
+ INSTANCE_COLLECTOR = PytestRemovedIn8Warning(
113
+ "The pytest.Instance collector type is deprecated and is no longer used. "
114
+ "See https://docs.pytest.org/en/latest/deprecations.html#the-pytest-instance-collector",
115
+ )
116
+ HOOK_LEGACY_MARKING = UnformattedWarning(
117
+ PytestDeprecationWarning,
118
+ "The hook{type} {fullname} uses old-style configuration options (marks or attributes).\n"
119
+ "Please use the pytest.hook{type}({hook_opts}) decorator instead\n"
120
+ " to configure the hooks.\n"
121
+ " See https://docs.pytest.org/en/latest/deprecations.html"
122
+ "#configuring-hook-specs-impls-using-markers",
123
+ )
124
+
125
+ # You want to make some `__init__` or function "private".
126
+ #
127
+ # def my_private_function(some, args):
128
+ # ...
129
+ #
130
+ # Do this:
131
+ #
132
+ # def my_private_function(some, args, *, _ispytest: bool = False):
133
+ # check_ispytest(_ispytest)
134
+ # ...
135
+ #
136
+ # Change all internal/allowed calls to
137
+ #
138
+ # my_private_function(some, args, _ispytest=True)
139
+ #
140
+ # All other calls will get the default _ispytest=False and trigger
141
+ # the warning (possibly error in the future).
142
+
143
+
144
+ def check_ispytest(ispytest: bool) -> None:
145
+ if not ispytest:
146
+ warn(PRIVATE, stacklevel=3)
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/doctest.py ADDED
@@ -0,0 +1,771 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Discover and run doctests in modules and test files."""
2
+ import bdb
3
+ import functools
4
+ import inspect
5
+ import os
6
+ import platform
7
+ import sys
8
+ import traceback
9
+ import types
10
+ import warnings
11
+ from contextlib import contextmanager
12
+ from pathlib import Path
13
+ from typing import Any
14
+ from typing import Callable
15
+ from typing import Dict
16
+ from typing import Generator
17
+ from typing import Iterable
18
+ from typing import List
19
+ from typing import Optional
20
+ from typing import Pattern
21
+ from typing import Sequence
22
+ from typing import Tuple
23
+ from typing import Type
24
+ from typing import TYPE_CHECKING
25
+ from typing import Union
26
+
27
+ from _pytest import outcomes
28
+ from _pytest._code.code import ExceptionInfo
29
+ from _pytest._code.code import ReprFileLocation
30
+ from _pytest._code.code import TerminalRepr
31
+ from _pytest._io import TerminalWriter
32
+ from _pytest.compat import safe_getattr
33
+ from _pytest.config import Config
34
+ from _pytest.config.argparsing import Parser
35
+ from _pytest.fixtures import fixture
36
+ from _pytest.fixtures import FixtureRequest
37
+ from _pytest.nodes import Collector
38
+ from _pytest.nodes import Item
39
+ from _pytest.outcomes import OutcomeException
40
+ from _pytest.outcomes import skip
41
+ from _pytest.pathlib import fnmatch_ex
42
+ from _pytest.pathlib import import_path
43
+ from _pytest.python import Module
44
+ from _pytest.python_api import approx
45
+ from _pytest.warning_types import PytestWarning
46
+
47
+ if TYPE_CHECKING:
48
+ import doctest
49
+
50
+ DOCTEST_REPORT_CHOICE_NONE = "none"
51
+ DOCTEST_REPORT_CHOICE_CDIFF = "cdiff"
52
+ DOCTEST_REPORT_CHOICE_NDIFF = "ndiff"
53
+ DOCTEST_REPORT_CHOICE_UDIFF = "udiff"
54
+ DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE = "only_first_failure"
55
+
56
+ DOCTEST_REPORT_CHOICES = (
57
+ DOCTEST_REPORT_CHOICE_NONE,
58
+ DOCTEST_REPORT_CHOICE_CDIFF,
59
+ DOCTEST_REPORT_CHOICE_NDIFF,
60
+ DOCTEST_REPORT_CHOICE_UDIFF,
61
+ DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE,
62
+ )
63
+
64
+ # Lazy definition of runner class
65
+ RUNNER_CLASS = None
66
+ # Lazy definition of output checker class
67
+ CHECKER_CLASS: Optional[Type["doctest.OutputChecker"]] = None
68
+
69
+
70
+ def pytest_addoption(parser: Parser) -> None:
71
+ parser.addini(
72
+ "doctest_optionflags",
73
+ "Option flags for doctests",
74
+ type="args",
75
+ default=["ELLIPSIS"],
76
+ )
77
+ parser.addini(
78
+ "doctest_encoding", "Encoding used for doctest files", default="utf-8"
79
+ )
80
+ group = parser.getgroup("collect")
81
+ group.addoption(
82
+ "--doctest-modules",
83
+ action="store_true",
84
+ default=False,
85
+ help="Run doctests in all .py modules",
86
+ dest="doctestmodules",
87
+ )
88
+ group.addoption(
89
+ "--doctest-report",
90
+ type=str.lower,
91
+ default="udiff",
92
+ help="Choose another output format for diffs on doctest failure",
93
+ choices=DOCTEST_REPORT_CHOICES,
94
+ dest="doctestreport",
95
+ )
96
+ group.addoption(
97
+ "--doctest-glob",
98
+ action="append",
99
+ default=[],
100
+ metavar="pat",
101
+ help="Doctests file matching pattern, default: test*.txt",
102
+ dest="doctestglob",
103
+ )
104
+ group.addoption(
105
+ "--doctest-ignore-import-errors",
106
+ action="store_true",
107
+ default=False,
108
+ help="Ignore doctest ImportErrors",
109
+ dest="doctest_ignore_import_errors",
110
+ )
111
+ group.addoption(
112
+ "--doctest-continue-on-failure",
113
+ action="store_true",
114
+ default=False,
115
+ help="For a given doctest, continue to run after the first failure",
116
+ dest="doctest_continue_on_failure",
117
+ )
118
+
119
+
120
+ def pytest_unconfigure() -> None:
121
+ global RUNNER_CLASS
122
+
123
+ RUNNER_CLASS = None
124
+
125
+
126
+ def pytest_collect_file(
127
+ file_path: Path,
128
+ parent: Collector,
129
+ ) -> Optional[Union["DoctestModule", "DoctestTextfile"]]:
130
+ config = parent.config
131
+ if file_path.suffix == ".py":
132
+ if config.option.doctestmodules and not any(
133
+ (_is_setup_py(file_path), _is_main_py(file_path))
134
+ ):
135
+ mod: DoctestModule = DoctestModule.from_parent(parent, path=file_path)
136
+ return mod
137
+ elif _is_doctest(config, file_path, parent):
138
+ txt: DoctestTextfile = DoctestTextfile.from_parent(parent, path=file_path)
139
+ return txt
140
+ return None
141
+
142
+
143
+ def _is_setup_py(path: Path) -> bool:
144
+ if path.name != "setup.py":
145
+ return False
146
+ contents = path.read_bytes()
147
+ return b"setuptools" in contents or b"distutils" in contents
148
+
149
+
150
+ def _is_doctest(config: Config, path: Path, parent: Collector) -> bool:
151
+ if path.suffix in (".txt", ".rst") and parent.session.isinitpath(path):
152
+ return True
153
+ globs = config.getoption("doctestglob") or ["test*.txt"]
154
+ return any(fnmatch_ex(glob, path) for glob in globs)
155
+
156
+
157
+ def _is_main_py(path: Path) -> bool:
158
+ return path.name == "__main__.py"
159
+
160
+
161
+ class ReprFailDoctest(TerminalRepr):
162
+ def __init__(
163
+ self, reprlocation_lines: Sequence[Tuple[ReprFileLocation, Sequence[str]]]
164
+ ) -> None:
165
+ self.reprlocation_lines = reprlocation_lines
166
+
167
+ def toterminal(self, tw: TerminalWriter) -> None:
168
+ for reprlocation, lines in self.reprlocation_lines:
169
+ for line in lines:
170
+ tw.line(line)
171
+ reprlocation.toterminal(tw)
172
+
173
+
174
+ class MultipleDoctestFailures(Exception):
175
+ def __init__(self, failures: Sequence["doctest.DocTestFailure"]) -> None:
176
+ super().__init__()
177
+ self.failures = failures
178
+
179
+
180
+ def _init_runner_class() -> Type["doctest.DocTestRunner"]:
181
+ import doctest
182
+
183
+ class PytestDoctestRunner(doctest.DebugRunner):
184
+ """Runner to collect failures.
185
+
186
+ Note that the out variable in this case is a list instead of a
187
+ stdout-like object.
188
+ """
189
+
190
+ def __init__(
191
+ self,
192
+ checker: Optional["doctest.OutputChecker"] = None,
193
+ verbose: Optional[bool] = None,
194
+ optionflags: int = 0,
195
+ continue_on_failure: bool = True,
196
+ ) -> None:
197
+ super().__init__(checker=checker, verbose=verbose, optionflags=optionflags)
198
+ self.continue_on_failure = continue_on_failure
199
+
200
+ def report_failure(
201
+ self,
202
+ out,
203
+ test: "doctest.DocTest",
204
+ example: "doctest.Example",
205
+ got: str,
206
+ ) -> None:
207
+ failure = doctest.DocTestFailure(test, example, got)
208
+ if self.continue_on_failure:
209
+ out.append(failure)
210
+ else:
211
+ raise failure
212
+
213
+ def report_unexpected_exception(
214
+ self,
215
+ out,
216
+ test: "doctest.DocTest",
217
+ example: "doctest.Example",
218
+ exc_info: Tuple[Type[BaseException], BaseException, types.TracebackType],
219
+ ) -> None:
220
+ if isinstance(exc_info[1], OutcomeException):
221
+ raise exc_info[1]
222
+ if isinstance(exc_info[1], bdb.BdbQuit):
223
+ outcomes.exit("Quitting debugger")
224
+ failure = doctest.UnexpectedException(test, example, exc_info)
225
+ if self.continue_on_failure:
226
+ out.append(failure)
227
+ else:
228
+ raise failure
229
+
230
+ return PytestDoctestRunner
231
+
232
+
233
+ def _get_runner(
234
+ checker: Optional["doctest.OutputChecker"] = None,
235
+ verbose: Optional[bool] = None,
236
+ optionflags: int = 0,
237
+ continue_on_failure: bool = True,
238
+ ) -> "doctest.DocTestRunner":
239
+ # We need this in order to do a lazy import on doctest
240
+ global RUNNER_CLASS
241
+ if RUNNER_CLASS is None:
242
+ RUNNER_CLASS = _init_runner_class()
243
+ # Type ignored because the continue_on_failure argument is only defined on
244
+ # PytestDoctestRunner, which is lazily defined so can't be used as a type.
245
+ return RUNNER_CLASS( # type: ignore
246
+ checker=checker,
247
+ verbose=verbose,
248
+ optionflags=optionflags,
249
+ continue_on_failure=continue_on_failure,
250
+ )
251
+
252
+
253
+ class DoctestItem(Item):
254
+ def __init__(
255
+ self,
256
+ name: str,
257
+ parent: "Union[DoctestTextfile, DoctestModule]",
258
+ runner: Optional["doctest.DocTestRunner"] = None,
259
+ dtest: Optional["doctest.DocTest"] = None,
260
+ ) -> None:
261
+ super().__init__(name, parent)
262
+ self.runner = runner
263
+ self.dtest = dtest
264
+ self.obj = None
265
+ self.fixture_request: Optional[FixtureRequest] = None
266
+
267
+ @classmethod
268
+ def from_parent( # type: ignore
269
+ cls,
270
+ parent: "Union[DoctestTextfile, DoctestModule]",
271
+ *,
272
+ name: str,
273
+ runner: "doctest.DocTestRunner",
274
+ dtest: "doctest.DocTest",
275
+ ):
276
+ # incompatible signature due to imposed limits on subclass
277
+ """The public named constructor."""
278
+ return super().from_parent(name=name, parent=parent, runner=runner, dtest=dtest)
279
+
280
+ def setup(self) -> None:
281
+ if self.dtest is not None:
282
+ self.fixture_request = _setup_fixtures(self)
283
+ globs = dict(getfixture=self.fixture_request.getfixturevalue)
284
+ for name, value in self.fixture_request.getfixturevalue(
285
+ "doctest_namespace"
286
+ ).items():
287
+ globs[name] = value
288
+ self.dtest.globs.update(globs)
289
+
290
+ def runtest(self) -> None:
291
+ assert self.dtest is not None
292
+ assert self.runner is not None
293
+ _check_all_skipped(self.dtest)
294
+ self._disable_output_capturing_for_darwin()
295
+ failures: List["doctest.DocTestFailure"] = []
296
+ # Type ignored because we change the type of `out` from what
297
+ # doctest expects.
298
+ self.runner.run(self.dtest, out=failures) # type: ignore[arg-type]
299
+ if failures:
300
+ raise MultipleDoctestFailures(failures)
301
+
302
+ def _disable_output_capturing_for_darwin(self) -> None:
303
+ """Disable output capturing. Otherwise, stdout is lost to doctest (#985)."""
304
+ if platform.system() != "Darwin":
305
+ return
306
+ capman = self.config.pluginmanager.getplugin("capturemanager")
307
+ if capman:
308
+ capman.suspend_global_capture(in_=True)
309
+ out, err = capman.read_global_capture()
310
+ sys.stdout.write(out)
311
+ sys.stderr.write(err)
312
+
313
+ # TODO: Type ignored -- breaks Liskov Substitution.
314
+ def repr_failure( # type: ignore[override]
315
+ self,
316
+ excinfo: ExceptionInfo[BaseException],
317
+ ) -> Union[str, TerminalRepr]:
318
+ import doctest
319
+
320
+ failures: Optional[
321
+ Sequence[Union[doctest.DocTestFailure, doctest.UnexpectedException]]
322
+ ] = None
323
+ if isinstance(
324
+ excinfo.value, (doctest.DocTestFailure, doctest.UnexpectedException)
325
+ ):
326
+ failures = [excinfo.value]
327
+ elif isinstance(excinfo.value, MultipleDoctestFailures):
328
+ failures = excinfo.value.failures
329
+
330
+ if failures is None:
331
+ return super().repr_failure(excinfo)
332
+
333
+ reprlocation_lines = []
334
+ for failure in failures:
335
+ example = failure.example
336
+ test = failure.test
337
+ filename = test.filename
338
+ if test.lineno is None:
339
+ lineno = None
340
+ else:
341
+ lineno = test.lineno + example.lineno + 1
342
+ message = type(failure).__name__
343
+ # TODO: ReprFileLocation doesn't expect a None lineno.
344
+ reprlocation = ReprFileLocation(filename, lineno, message) # type: ignore[arg-type]
345
+ checker = _get_checker()
346
+ report_choice = _get_report_choice(self.config.getoption("doctestreport"))
347
+ if lineno is not None:
348
+ assert failure.test.docstring is not None
349
+ lines = failure.test.docstring.splitlines(False)
350
+ # add line numbers to the left of the error message
351
+ assert test.lineno is not None
352
+ lines = [
353
+ "%03d %s" % (i + test.lineno + 1, x) for (i, x) in enumerate(lines)
354
+ ]
355
+ # trim docstring error lines to 10
356
+ lines = lines[max(example.lineno - 9, 0) : example.lineno + 1]
357
+ else:
358
+ lines = [
359
+ "EXAMPLE LOCATION UNKNOWN, not showing all tests of that example"
360
+ ]
361
+ indent = ">>>"
362
+ for line in example.source.splitlines():
363
+ lines.append(f"??? {indent} {line}")
364
+ indent = "..."
365
+ if isinstance(failure, doctest.DocTestFailure):
366
+ lines += checker.output_difference(
367
+ example, failure.got, report_choice
368
+ ).split("\n")
369
+ else:
370
+ inner_excinfo = ExceptionInfo.from_exc_info(failure.exc_info)
371
+ lines += ["UNEXPECTED EXCEPTION: %s" % repr(inner_excinfo.value)]
372
+ lines += [
373
+ x.strip("\n") for x in traceback.format_exception(*failure.exc_info)
374
+ ]
375
+ reprlocation_lines.append((reprlocation, lines))
376
+ return ReprFailDoctest(reprlocation_lines)
377
+
378
+ def reportinfo(self) -> Tuple[Union["os.PathLike[str]", str], Optional[int], str]:
379
+ assert self.dtest is not None
380
+ return self.path, self.dtest.lineno, "[doctest] %s" % self.name
381
+
382
+
383
+ def _get_flag_lookup() -> Dict[str, int]:
384
+ import doctest
385
+
386
+ return dict(
387
+ DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1,
388
+ DONT_ACCEPT_BLANKLINE=doctest.DONT_ACCEPT_BLANKLINE,
389
+ NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE,
390
+ ELLIPSIS=doctest.ELLIPSIS,
391
+ IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL,
392
+ COMPARISON_FLAGS=doctest.COMPARISON_FLAGS,
393
+ ALLOW_UNICODE=_get_allow_unicode_flag(),
394
+ ALLOW_BYTES=_get_allow_bytes_flag(),
395
+ NUMBER=_get_number_flag(),
396
+ )
397
+
398
+
399
+ def get_optionflags(parent):
400
+ optionflags_str = parent.config.getini("doctest_optionflags")
401
+ flag_lookup_table = _get_flag_lookup()
402
+ flag_acc = 0
403
+ for flag in optionflags_str:
404
+ flag_acc |= flag_lookup_table[flag]
405
+ return flag_acc
406
+
407
+
408
+ def _get_continue_on_failure(config):
409
+ continue_on_failure = config.getvalue("doctest_continue_on_failure")
410
+ if continue_on_failure:
411
+ # We need to turn off this if we use pdb since we should stop at
412
+ # the first failure.
413
+ if config.getvalue("usepdb"):
414
+ continue_on_failure = False
415
+ return continue_on_failure
416
+
417
+
418
+ class DoctestTextfile(Module):
419
+ obj = None
420
+
421
+ def collect(self) -> Iterable[DoctestItem]:
422
+ import doctest
423
+
424
+ # Inspired by doctest.testfile; ideally we would use it directly,
425
+ # but it doesn't support passing a custom checker.
426
+ encoding = self.config.getini("doctest_encoding")
427
+ text = self.path.read_text(encoding)
428
+ filename = str(self.path)
429
+ name = self.path.name
430
+ globs = {"__name__": "__main__"}
431
+
432
+ optionflags = get_optionflags(self)
433
+
434
+ runner = _get_runner(
435
+ verbose=False,
436
+ optionflags=optionflags,
437
+ checker=_get_checker(),
438
+ continue_on_failure=_get_continue_on_failure(self.config),
439
+ )
440
+
441
+ parser = doctest.DocTestParser()
442
+ test = parser.get_doctest(text, globs, name, filename, 0)
443
+ if test.examples:
444
+ yield DoctestItem.from_parent(
445
+ self, name=test.name, runner=runner, dtest=test
446
+ )
447
+
448
+
449
+ def _check_all_skipped(test: "doctest.DocTest") -> None:
450
+ """Raise pytest.skip() if all examples in the given DocTest have the SKIP
451
+ option set."""
452
+ import doctest
453
+
454
+ all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples)
455
+ if all_skipped:
456
+ skip("all tests skipped by +SKIP option")
457
+
458
+
459
+ def _is_mocked(obj: object) -> bool:
460
+ """Return if an object is possibly a mock object by checking the
461
+ existence of a highly improbable attribute."""
462
+ return (
463
+ safe_getattr(obj, "pytest_mock_example_attribute_that_shouldnt_exist", None)
464
+ is not None
465
+ )
466
+
467
+
468
+ @contextmanager
469
+ def _patch_unwrap_mock_aware() -> Generator[None, None, None]:
470
+ """Context manager which replaces ``inspect.unwrap`` with a version
471
+ that's aware of mock objects and doesn't recurse into them."""
472
+ real_unwrap = inspect.unwrap
473
+
474
+ def _mock_aware_unwrap(
475
+ func: Callable[..., Any], *, stop: Optional[Callable[[Any], Any]] = None
476
+ ) -> Any:
477
+ try:
478
+ if stop is None or stop is _is_mocked:
479
+ return real_unwrap(func, stop=_is_mocked)
480
+ _stop = stop
481
+ return real_unwrap(func, stop=lambda obj: _is_mocked(obj) or _stop(func))
482
+ except Exception as e:
483
+ warnings.warn(
484
+ "Got %r when unwrapping %r. This is usually caused "
485
+ "by a violation of Python's object protocol; see e.g. "
486
+ "https://github.com/pytest-dev/pytest/issues/5080" % (e, func),
487
+ PytestWarning,
488
+ )
489
+ raise
490
+
491
+ inspect.unwrap = _mock_aware_unwrap
492
+ try:
493
+ yield
494
+ finally:
495
+ inspect.unwrap = real_unwrap
496
+
497
+
498
+ class DoctestModule(Module):
499
+ def collect(self) -> Iterable[DoctestItem]:
500
+ import doctest
501
+
502
+ class MockAwareDocTestFinder(doctest.DocTestFinder):
503
+ """A hackish doctest finder that overrides stdlib internals to fix a stdlib bug.
504
+
505
+ https://github.com/pytest-dev/pytest/issues/3456
506
+ https://bugs.python.org/issue25532
507
+ """
508
+
509
+ def _find_lineno(self, obj, source_lines):
510
+ """Doctest code does not take into account `@property`, this
511
+ is a hackish way to fix it. https://bugs.python.org/issue17446
512
+
513
+ Wrapped Doctests will need to be unwrapped so the correct
514
+ line number is returned. This will be reported upstream. #8796
515
+ """
516
+ if isinstance(obj, property):
517
+ obj = getattr(obj, "fget", obj)
518
+
519
+ if hasattr(obj, "__wrapped__"):
520
+ # Get the main obj in case of it being wrapped
521
+ obj = inspect.unwrap(obj)
522
+
523
+ # Type ignored because this is a private function.
524
+ return super()._find_lineno( # type:ignore[misc]
525
+ obj,
526
+ source_lines,
527
+ )
528
+
529
+ def _find(
530
+ self, tests, obj, name, module, source_lines, globs, seen
531
+ ) -> None:
532
+ if _is_mocked(obj):
533
+ return
534
+ with _patch_unwrap_mock_aware():
535
+ # Type ignored because this is a private function.
536
+ super()._find( # type:ignore[misc]
537
+ tests, obj, name, module, source_lines, globs, seen
538
+ )
539
+
540
+ if sys.version_info < (3, 13):
541
+
542
+ def _from_module(self, module, object):
543
+ """`cached_property` objects are never considered a part
544
+ of the 'current module'. As such they are skipped by doctest.
545
+ Here we override `_from_module` to check the underlying
546
+ function instead. https://github.com/python/cpython/issues/107995
547
+ """
548
+ if hasattr(functools, "cached_property") and isinstance(
549
+ object, functools.cached_property
550
+ ):
551
+ object = object.func
552
+
553
+ # Type ignored because this is a private function.
554
+ return super()._from_module(module, object) # type: ignore[misc]
555
+
556
+ else: # pragma: no cover
557
+ pass
558
+
559
+ if self.path.name == "conftest.py":
560
+ module = self.config.pluginmanager._importconftest(
561
+ self.path,
562
+ self.config.getoption("importmode"),
563
+ rootpath=self.config.rootpath,
564
+ )
565
+ else:
566
+ try:
567
+ module = import_path(
568
+ self.path,
569
+ root=self.config.rootpath,
570
+ mode=self.config.getoption("importmode"),
571
+ )
572
+ except ImportError:
573
+ if self.config.getvalue("doctest_ignore_import_errors"):
574
+ skip("unable to import module %r" % self.path)
575
+ else:
576
+ raise
577
+ # Uses internal doctest module parsing mechanism.
578
+ finder = MockAwareDocTestFinder()
579
+ optionflags = get_optionflags(self)
580
+ runner = _get_runner(
581
+ verbose=False,
582
+ optionflags=optionflags,
583
+ checker=_get_checker(),
584
+ continue_on_failure=_get_continue_on_failure(self.config),
585
+ )
586
+
587
+ for test in finder.find(module, module.__name__):
588
+ if test.examples: # skip empty doctests
589
+ yield DoctestItem.from_parent(
590
+ self, name=test.name, runner=runner, dtest=test
591
+ )
592
+
593
+
594
+ def _setup_fixtures(doctest_item: DoctestItem) -> FixtureRequest:
595
+ """Used by DoctestTextfile and DoctestItem to setup fixture information."""
596
+
597
+ def func() -> None:
598
+ pass
599
+
600
+ doctest_item.funcargs = {} # type: ignore[attr-defined]
601
+ fm = doctest_item.session._fixturemanager
602
+ doctest_item._fixtureinfo = fm.getfixtureinfo( # type: ignore[attr-defined]
603
+ node=doctest_item, func=func, cls=None, funcargs=False
604
+ )
605
+ fixture_request = FixtureRequest(doctest_item, _ispytest=True)
606
+ fixture_request._fillfixtures()
607
+ return fixture_request
608
+
609
+
610
+ def _init_checker_class() -> Type["doctest.OutputChecker"]:
611
+ import doctest
612
+ import re
613
+
614
+ class LiteralsOutputChecker(doctest.OutputChecker):
615
+ # Based on doctest_nose_plugin.py from the nltk project
616
+ # (https://github.com/nltk/nltk) and on the "numtest" doctest extension
617
+ # by Sebastien Boisgerault (https://github.com/boisgera/numtest).
618
+
619
+ _unicode_literal_re = re.compile(r"(\W|^)[uU]([rR]?[\'\"])", re.UNICODE)
620
+ _bytes_literal_re = re.compile(r"(\W|^)[bB]([rR]?[\'\"])", re.UNICODE)
621
+ _number_re = re.compile(
622
+ r"""
623
+ (?P<number>
624
+ (?P<mantissa>
625
+ (?P<integer1> [+-]?\d*)\.(?P<fraction>\d+)
626
+ |
627
+ (?P<integer2> [+-]?\d+)\.
628
+ )
629
+ (?:
630
+ [Ee]
631
+ (?P<exponent1> [+-]?\d+)
632
+ )?
633
+ |
634
+ (?P<integer3> [+-]?\d+)
635
+ (?:
636
+ [Ee]
637
+ (?P<exponent2> [+-]?\d+)
638
+ )
639
+ )
640
+ """,
641
+ re.VERBOSE,
642
+ )
643
+
644
+ def check_output(self, want: str, got: str, optionflags: int) -> bool:
645
+ if super().check_output(want, got, optionflags):
646
+ return True
647
+
648
+ allow_unicode = optionflags & _get_allow_unicode_flag()
649
+ allow_bytes = optionflags & _get_allow_bytes_flag()
650
+ allow_number = optionflags & _get_number_flag()
651
+
652
+ if not allow_unicode and not allow_bytes and not allow_number:
653
+ return False
654
+
655
+ def remove_prefixes(regex: Pattern[str], txt: str) -> str:
656
+ return re.sub(regex, r"\1\2", txt)
657
+
658
+ if allow_unicode:
659
+ want = remove_prefixes(self._unicode_literal_re, want)
660
+ got = remove_prefixes(self._unicode_literal_re, got)
661
+
662
+ if allow_bytes:
663
+ want = remove_prefixes(self._bytes_literal_re, want)
664
+ got = remove_prefixes(self._bytes_literal_re, got)
665
+
666
+ if allow_number:
667
+ got = self._remove_unwanted_precision(want, got)
668
+
669
+ return super().check_output(want, got, optionflags)
670
+
671
+ def _remove_unwanted_precision(self, want: str, got: str) -> str:
672
+ wants = list(self._number_re.finditer(want))
673
+ gots = list(self._number_re.finditer(got))
674
+ if len(wants) != len(gots):
675
+ return got
676
+ offset = 0
677
+ for w, g in zip(wants, gots):
678
+ fraction: Optional[str] = w.group("fraction")
679
+ exponent: Optional[str] = w.group("exponent1")
680
+ if exponent is None:
681
+ exponent = w.group("exponent2")
682
+ precision = 0 if fraction is None else len(fraction)
683
+ if exponent is not None:
684
+ precision -= int(exponent)
685
+ if float(w.group()) == approx(float(g.group()), abs=10**-precision):
686
+ # They're close enough. Replace the text we actually
687
+ # got with the text we want, so that it will match when we
688
+ # check the string literally.
689
+ got = (
690
+ got[: g.start() + offset] + w.group() + got[g.end() + offset :]
691
+ )
692
+ offset += w.end() - w.start() - (g.end() - g.start())
693
+ return got
694
+
695
+ return LiteralsOutputChecker
696
+
697
+
698
+ def _get_checker() -> "doctest.OutputChecker":
699
+ """Return a doctest.OutputChecker subclass that supports some
700
+ additional options:
701
+
702
+ * ALLOW_UNICODE and ALLOW_BYTES options to ignore u'' and b''
703
+ prefixes (respectively) in string literals. Useful when the same
704
+ doctest should run in Python 2 and Python 3.
705
+
706
+ * NUMBER to ignore floating-point differences smaller than the
707
+ precision of the literal number in the doctest.
708
+
709
+ An inner class is used to avoid importing "doctest" at the module
710
+ level.
711
+ """
712
+ global CHECKER_CLASS
713
+ if CHECKER_CLASS is None:
714
+ CHECKER_CLASS = _init_checker_class()
715
+ return CHECKER_CLASS()
716
+
717
+
718
+ def _get_allow_unicode_flag() -> int:
719
+ """Register and return the ALLOW_UNICODE flag."""
720
+ import doctest
721
+
722
+ return doctest.register_optionflag("ALLOW_UNICODE")
723
+
724
+
725
+ def _get_allow_bytes_flag() -> int:
726
+ """Register and return the ALLOW_BYTES flag."""
727
+ import doctest
728
+
729
+ return doctest.register_optionflag("ALLOW_BYTES")
730
+
731
+
732
+ def _get_number_flag() -> int:
733
+ """Register and return the NUMBER flag."""
734
+ import doctest
735
+
736
+ return doctest.register_optionflag("NUMBER")
737
+
738
+
739
+ def _get_report_choice(key: str) -> int:
740
+ """Return the actual `doctest` module flag value.
741
+
742
+ We want to do it as late as possible to avoid importing `doctest` and all
743
+ its dependencies when parsing options, as it adds overhead and breaks tests.
744
+ """
745
+ import doctest
746
+
747
+ return {
748
+ DOCTEST_REPORT_CHOICE_UDIFF: doctest.REPORT_UDIFF,
749
+ DOCTEST_REPORT_CHOICE_CDIFF: doctest.REPORT_CDIFF,
750
+ DOCTEST_REPORT_CHOICE_NDIFF: doctest.REPORT_NDIFF,
751
+ DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE: doctest.REPORT_ONLY_FIRST_FAILURE,
752
+ DOCTEST_REPORT_CHOICE_NONE: 0,
753
+ }[key]
754
+
755
+
756
+ @fixture(scope="session")
757
+ def doctest_namespace() -> Dict[str, Any]:
758
+ """Fixture that returns a :py:class:`dict` that will be injected into the
759
+ namespace of doctests.
760
+
761
+ Usually this fixture is used in conjunction with another ``autouse`` fixture:
762
+
763
+ .. code-block:: python
764
+
765
+ @pytest.fixture(autouse=True)
766
+ def add_np(doctest_namespace):
767
+ doctest_namespace["np"] = numpy
768
+
769
+ For more details: :ref:`doctest_namespace`.
770
+ """
771
+ return dict()
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/faulthandler.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from typing import Generator
4
+
5
+ import pytest
6
+ from _pytest.config import Config
7
+ from _pytest.config.argparsing import Parser
8
+ from _pytest.nodes import Item
9
+ from _pytest.stash import StashKey
10
+
11
+
12
+ fault_handler_stderr_fd_key = StashKey[int]()
13
+ fault_handler_originally_enabled_key = StashKey[bool]()
14
+
15
+
16
+ def pytest_addoption(parser: Parser) -> None:
17
+ help = (
18
+ "Dump the traceback of all threads if a test takes "
19
+ "more than TIMEOUT seconds to finish"
20
+ )
21
+ parser.addini("faulthandler_timeout", help, default=0.0)
22
+
23
+
24
+ def pytest_configure(config: Config) -> None:
25
+ import faulthandler
26
+
27
+ config.stash[fault_handler_stderr_fd_key] = os.dup(get_stderr_fileno())
28
+ config.stash[fault_handler_originally_enabled_key] = faulthandler.is_enabled()
29
+ faulthandler.enable(file=config.stash[fault_handler_stderr_fd_key])
30
+
31
+
32
+ def pytest_unconfigure(config: Config) -> None:
33
+ import faulthandler
34
+
35
+ faulthandler.disable()
36
+ # Close the dup file installed during pytest_configure.
37
+ if fault_handler_stderr_fd_key in config.stash:
38
+ os.close(config.stash[fault_handler_stderr_fd_key])
39
+ del config.stash[fault_handler_stderr_fd_key]
40
+ if config.stash.get(fault_handler_originally_enabled_key, False):
41
+ # Re-enable the faulthandler if it was originally enabled.
42
+ faulthandler.enable(file=get_stderr_fileno())
43
+
44
+
45
+ def get_stderr_fileno() -> int:
46
+ try:
47
+ fileno = sys.stderr.fileno()
48
+ # The Twisted Logger will return an invalid file descriptor since it is not backed
49
+ # by an FD. So, let's also forward this to the same code path as with pytest-xdist.
50
+ if fileno == -1:
51
+ raise AttributeError()
52
+ return fileno
53
+ except (AttributeError, ValueError):
54
+ # pytest-xdist monkeypatches sys.stderr with an object that is not an actual file.
55
+ # https://docs.python.org/3/library/faulthandler.html#issue-with-file-descriptors
56
+ # This is potentially dangerous, but the best we can do.
57
+ return sys.__stderr__.fileno()
58
+
59
+
60
+ def get_timeout_config_value(config: Config) -> float:
61
+ return float(config.getini("faulthandler_timeout") or 0.0)
62
+
63
+
64
+ @pytest.hookimpl(hookwrapper=True, trylast=True)
65
+ def pytest_runtest_protocol(item: Item) -> Generator[None, None, None]:
66
+ timeout = get_timeout_config_value(item.config)
67
+ if timeout > 0:
68
+ import faulthandler
69
+
70
+ stderr = item.config.stash[fault_handler_stderr_fd_key]
71
+ faulthandler.dump_traceback_later(timeout, file=stderr)
72
+ try:
73
+ yield
74
+ finally:
75
+ faulthandler.cancel_dump_traceback_later()
76
+ else:
77
+ yield
78
+
79
+
80
+ @pytest.hookimpl(tryfirst=True)
81
+ def pytest_enter_pdb() -> None:
82
+ """Cancel any traceback dumping due to timeout before entering pdb."""
83
+ import faulthandler
84
+
85
+ faulthandler.cancel_dump_traceback_later()
86
+
87
+
88
+ @pytest.hookimpl(tryfirst=True)
89
+ def pytest_exception_interact() -> None:
90
+ """Cancel any traceback dumping due to an interactive exception being
91
+ raised."""
92
+ import faulthandler
93
+
94
+ faulthandler.cancel_dump_traceback_later()
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/fixtures.py ADDED
@@ -0,0 +1,1713 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ import functools
3
+ import inspect
4
+ import os
5
+ import sys
6
+ import warnings
7
+ from collections import defaultdict
8
+ from collections import deque
9
+ from contextlib import suppress
10
+ from pathlib import Path
11
+ from types import TracebackType
12
+ from typing import Any
13
+ from typing import Callable
14
+ from typing import cast
15
+ from typing import Dict
16
+ from typing import Generator
17
+ from typing import Generic
18
+ from typing import Iterable
19
+ from typing import Iterator
20
+ from typing import List
21
+ from typing import MutableMapping
22
+ from typing import NoReturn
23
+ from typing import Optional
24
+ from typing import Sequence
25
+ from typing import Set
26
+ from typing import Tuple
27
+ from typing import Type
28
+ from typing import TYPE_CHECKING
29
+ from typing import TypeVar
30
+ from typing import Union
31
+
32
+ import _pytest
33
+ from _pytest import nodes
34
+ from _pytest._code import getfslineno
35
+ from _pytest._code.code import FormattedExcinfo
36
+ from _pytest._code.code import TerminalRepr
37
+ from _pytest._io import TerminalWriter
38
+ from _pytest.compat import _format_args
39
+ from _pytest.compat import _PytestWrapper
40
+ from _pytest.compat import assert_never
41
+ from _pytest.compat import final
42
+ from _pytest.compat import get_real_func
43
+ from _pytest.compat import get_real_method
44
+ from _pytest.compat import getfuncargnames
45
+ from _pytest.compat import getimfunc
46
+ from _pytest.compat import getlocation
47
+ from _pytest.compat import is_generator
48
+ from _pytest.compat import NOTSET
49
+ from _pytest.compat import NotSetType
50
+ from _pytest.compat import overload
51
+ from _pytest.compat import safe_getattr
52
+ from _pytest.config import _PluggyPlugin
53
+ from _pytest.config import Config
54
+ from _pytest.config.argparsing import Parser
55
+ from _pytest.deprecated import check_ispytest
56
+ from _pytest.deprecated import YIELD_FIXTURE
57
+ from _pytest.mark import Mark
58
+ from _pytest.mark import ParameterSet
59
+ from _pytest.mark.structures import MarkDecorator
60
+ from _pytest.outcomes import fail
61
+ from _pytest.outcomes import skip
62
+ from _pytest.outcomes import TEST_OUTCOME
63
+ from _pytest.pathlib import absolutepath
64
+ from _pytest.pathlib import bestrelpath
65
+ from _pytest.scope import HIGH_SCOPES
66
+ from _pytest.scope import Scope
67
+ from _pytest.stash import StashKey
68
+
69
+
70
+ if TYPE_CHECKING:
71
+ from typing import Deque
72
+
73
+ from _pytest.scope import _ScopeName
74
+ from _pytest.main import Session
75
+ from _pytest.python import CallSpec2
76
+ from _pytest.python import Metafunc
77
+
78
+
79
+ # The value of the fixture -- return/yield of the fixture function (type variable).
80
+ FixtureValue = TypeVar("FixtureValue")
81
+ # The type of the fixture function (type variable).
82
+ FixtureFunction = TypeVar("FixtureFunction", bound=Callable[..., object])
83
+ # The type of a fixture function (type alias generic in fixture value).
84
+ _FixtureFunc = Union[
85
+ Callable[..., FixtureValue], Callable[..., Generator[FixtureValue, None, None]]
86
+ ]
87
+ # The type of FixtureDef.cached_result (type alias generic in fixture value).
88
+ _FixtureCachedResult = Union[
89
+ Tuple[
90
+ # The result.
91
+ FixtureValue,
92
+ # Cache key.
93
+ object,
94
+ None,
95
+ ],
96
+ Tuple[
97
+ None,
98
+ # Cache key.
99
+ object,
100
+ # Exc info if raised.
101
+ Tuple[Type[BaseException], BaseException, TracebackType],
102
+ ],
103
+ ]
104
+
105
+
106
+ @dataclasses.dataclass(frozen=True)
107
+ class PseudoFixtureDef(Generic[FixtureValue]):
108
+ cached_result: "_FixtureCachedResult[FixtureValue]"
109
+ _scope: Scope
110
+
111
+
112
+ def pytest_sessionstart(session: "Session") -> None:
113
+ session._fixturemanager = FixtureManager(session)
114
+
115
+
116
+ def get_scope_package(
117
+ node: nodes.Item,
118
+ fixturedef: "FixtureDef[object]",
119
+ ) -> Optional[Union[nodes.Item, nodes.Collector]]:
120
+ from _pytest.python import Package
121
+
122
+ current: Optional[Union[nodes.Item, nodes.Collector]] = node
123
+ fixture_package_name = "{}/{}".format(fixturedef.baseid, "__init__.py")
124
+ while current and (
125
+ not isinstance(current, Package) or fixture_package_name != current.nodeid
126
+ ):
127
+ current = current.parent # type: ignore[assignment]
128
+ if current is None:
129
+ return node.session
130
+ return current
131
+
132
+
133
+ def get_scope_node(
134
+ node: nodes.Node, scope: Scope
135
+ ) -> Optional[Union[nodes.Item, nodes.Collector]]:
136
+ import _pytest.python
137
+
138
+ if scope is Scope.Function:
139
+ return node.getparent(nodes.Item)
140
+ elif scope is Scope.Class:
141
+ return node.getparent(_pytest.python.Class)
142
+ elif scope is Scope.Module:
143
+ return node.getparent(_pytest.python.Module)
144
+ elif scope is Scope.Package:
145
+ return node.getparent(_pytest.python.Package)
146
+ elif scope is Scope.Session:
147
+ return node.getparent(_pytest.main.Session)
148
+ else:
149
+ assert_never(scope)
150
+
151
+
152
+ # Used for storing artificial fixturedefs for direct parametrization.
153
+ name2pseudofixturedef_key = StashKey[Dict[str, "FixtureDef[Any]"]]()
154
+
155
+
156
+ def add_funcarg_pseudo_fixture_def(
157
+ collector: nodes.Collector, metafunc: "Metafunc", fixturemanager: "FixtureManager"
158
+ ) -> None:
159
+ # This function will transform all collected calls to functions
160
+ # if they use direct funcargs (i.e. direct parametrization)
161
+ # because we want later test execution to be able to rely on
162
+ # an existing FixtureDef structure for all arguments.
163
+ # XXX we can probably avoid this algorithm if we modify CallSpec2
164
+ # to directly care for creating the fixturedefs within its methods.
165
+ if not metafunc._calls[0].funcargs:
166
+ # This function call does not have direct parametrization.
167
+ return
168
+ # Collect funcargs of all callspecs into a list of values.
169
+ arg2params: Dict[str, List[object]] = {}
170
+ arg2scope: Dict[str, Scope] = {}
171
+ for callspec in metafunc._calls:
172
+ for argname, argvalue in callspec.funcargs.items():
173
+ assert argname not in callspec.params
174
+ callspec.params[argname] = argvalue
175
+ arg2params_list = arg2params.setdefault(argname, [])
176
+ callspec.indices[argname] = len(arg2params_list)
177
+ arg2params_list.append(argvalue)
178
+ if argname not in arg2scope:
179
+ scope = callspec._arg2scope.get(argname, Scope.Function)
180
+ arg2scope[argname] = scope
181
+ callspec.funcargs.clear()
182
+
183
+ # Register artificial FixtureDef's so that later at test execution
184
+ # time we can rely on a proper FixtureDef to exist for fixture setup.
185
+ arg2fixturedefs = metafunc._arg2fixturedefs
186
+ for argname, valuelist in arg2params.items():
187
+ # If we have a scope that is higher than function, we need
188
+ # to make sure we only ever create an according fixturedef on
189
+ # a per-scope basis. We thus store and cache the fixturedef on the
190
+ # node related to the scope.
191
+ scope = arg2scope[argname]
192
+ node = None
193
+ if scope is not Scope.Function:
194
+ node = get_scope_node(collector, scope)
195
+ if node is None:
196
+ assert scope is Scope.Class and isinstance(
197
+ collector, _pytest.python.Module
198
+ )
199
+ # Use module-level collector for class-scope (for now).
200
+ node = collector
201
+ if node is None:
202
+ name2pseudofixturedef = None
203
+ else:
204
+ default: Dict[str, FixtureDef[Any]] = {}
205
+ name2pseudofixturedef = node.stash.setdefault(
206
+ name2pseudofixturedef_key, default
207
+ )
208
+ if name2pseudofixturedef is not None and argname in name2pseudofixturedef:
209
+ arg2fixturedefs[argname] = [name2pseudofixturedef[argname]]
210
+ else:
211
+ fixturedef = FixtureDef(
212
+ fixturemanager=fixturemanager,
213
+ baseid="",
214
+ argname=argname,
215
+ func=get_direct_param_fixture_func,
216
+ scope=arg2scope[argname],
217
+ params=valuelist,
218
+ unittest=False,
219
+ ids=None,
220
+ )
221
+ arg2fixturedefs[argname] = [fixturedef]
222
+ if name2pseudofixturedef is not None:
223
+ name2pseudofixturedef[argname] = fixturedef
224
+
225
+
226
+ def getfixturemarker(obj: object) -> Optional["FixtureFunctionMarker"]:
227
+ """Return fixturemarker or None if it doesn't exist or raised
228
+ exceptions."""
229
+ return cast(
230
+ Optional[FixtureFunctionMarker],
231
+ safe_getattr(obj, "_pytestfixturefunction", None),
232
+ )
233
+
234
+
235
+ # Parametrized fixture key, helper alias for code below.
236
+ _Key = Tuple[object, ...]
237
+
238
+
239
+ def get_parametrized_fixture_keys(item: nodes.Item, scope: Scope) -> Iterator[_Key]:
240
+ """Return list of keys for all parametrized arguments which match
241
+ the specified scope."""
242
+ assert scope is not Scope.Function
243
+ try:
244
+ callspec = item.callspec # type: ignore[attr-defined]
245
+ except AttributeError:
246
+ pass
247
+ else:
248
+ cs: CallSpec2 = callspec
249
+ # cs.indices.items() is random order of argnames. Need to
250
+ # sort this so that different calls to
251
+ # get_parametrized_fixture_keys will be deterministic.
252
+ for argname, param_index in sorted(cs.indices.items()):
253
+ if cs._arg2scope[argname] != scope:
254
+ continue
255
+ if scope is Scope.Session:
256
+ key: _Key = (argname, param_index)
257
+ elif scope is Scope.Package:
258
+ key = (argname, param_index, item.path.parent)
259
+ elif scope is Scope.Module:
260
+ key = (argname, param_index, item.path)
261
+ elif scope is Scope.Class:
262
+ item_cls = item.cls # type: ignore[attr-defined]
263
+ key = (argname, param_index, item.path, item_cls)
264
+ else:
265
+ assert_never(scope)
266
+ yield key
267
+
268
+
269
+ # Algorithm for sorting on a per-parametrized resource setup basis.
270
+ # It is called for Session scope first and performs sorting
271
+ # down to the lower scopes such as to minimize number of "high scope"
272
+ # setups and teardowns.
273
+
274
+
275
+ def reorder_items(items: Sequence[nodes.Item]) -> List[nodes.Item]:
276
+ argkeys_cache: Dict[Scope, Dict[nodes.Item, Dict[_Key, None]]] = {}
277
+ items_by_argkey: Dict[Scope, Dict[_Key, Deque[nodes.Item]]] = {}
278
+ for scope in HIGH_SCOPES:
279
+ d: Dict[nodes.Item, Dict[_Key, None]] = {}
280
+ argkeys_cache[scope] = d
281
+ item_d: Dict[_Key, Deque[nodes.Item]] = defaultdict(deque)
282
+ items_by_argkey[scope] = item_d
283
+ for item in items:
284
+ keys = dict.fromkeys(get_parametrized_fixture_keys(item, scope), None)
285
+ if keys:
286
+ d[item] = keys
287
+ for key in keys:
288
+ item_d[key].append(item)
289
+ items_dict = dict.fromkeys(items, None)
290
+ return list(
291
+ reorder_items_atscope(items_dict, argkeys_cache, items_by_argkey, Scope.Session)
292
+ )
293
+
294
+
295
+ def fix_cache_order(
296
+ item: nodes.Item,
297
+ argkeys_cache: Dict[Scope, Dict[nodes.Item, Dict[_Key, None]]],
298
+ items_by_argkey: Dict[Scope, Dict[_Key, "Deque[nodes.Item]"]],
299
+ ) -> None:
300
+ for scope in HIGH_SCOPES:
301
+ for key in argkeys_cache[scope].get(item, []):
302
+ items_by_argkey[scope][key].appendleft(item)
303
+
304
+
305
+ def reorder_items_atscope(
306
+ items: Dict[nodes.Item, None],
307
+ argkeys_cache: Dict[Scope, Dict[nodes.Item, Dict[_Key, None]]],
308
+ items_by_argkey: Dict[Scope, Dict[_Key, "Deque[nodes.Item]"]],
309
+ scope: Scope,
310
+ ) -> Dict[nodes.Item, None]:
311
+ if scope is Scope.Function or len(items) < 3:
312
+ return items
313
+ ignore: Set[Optional[_Key]] = set()
314
+ items_deque = deque(items)
315
+ items_done: Dict[nodes.Item, None] = {}
316
+ scoped_items_by_argkey = items_by_argkey[scope]
317
+ scoped_argkeys_cache = argkeys_cache[scope]
318
+ while items_deque:
319
+ no_argkey_group: Dict[nodes.Item, None] = {}
320
+ slicing_argkey = None
321
+ while items_deque:
322
+ item = items_deque.popleft()
323
+ if item in items_done or item in no_argkey_group:
324
+ continue
325
+ argkeys = dict.fromkeys(
326
+ (k for k in scoped_argkeys_cache.get(item, []) if k not in ignore), None
327
+ )
328
+ if not argkeys:
329
+ no_argkey_group[item] = None
330
+ else:
331
+ slicing_argkey, _ = argkeys.popitem()
332
+ # We don't have to remove relevant items from later in the
333
+ # deque because they'll just be ignored.
334
+ matching_items = [
335
+ i for i in scoped_items_by_argkey[slicing_argkey] if i in items
336
+ ]
337
+ for i in reversed(matching_items):
338
+ fix_cache_order(i, argkeys_cache, items_by_argkey)
339
+ items_deque.appendleft(i)
340
+ break
341
+ if no_argkey_group:
342
+ no_argkey_group = reorder_items_atscope(
343
+ no_argkey_group, argkeys_cache, items_by_argkey, scope.next_lower()
344
+ )
345
+ for item in no_argkey_group:
346
+ items_done[item] = None
347
+ ignore.add(slicing_argkey)
348
+ return items_done
349
+
350
+
351
+ def get_direct_param_fixture_func(request: "FixtureRequest") -> Any:
352
+ return request.param
353
+
354
+
355
+ @dataclasses.dataclass
356
+ class FuncFixtureInfo:
357
+ __slots__ = ("argnames", "initialnames", "names_closure", "name2fixturedefs")
358
+
359
+ # Original function argument names.
360
+ argnames: Tuple[str, ...]
361
+ # Argnames that function immediately requires. These include argnames +
362
+ # fixture names specified via usefixtures and via autouse=True in fixture
363
+ # definitions.
364
+ initialnames: Tuple[str, ...]
365
+ names_closure: List[str]
366
+ name2fixturedefs: Dict[str, Sequence["FixtureDef[Any]"]]
367
+
368
+ def prune_dependency_tree(self) -> None:
369
+ """Recompute names_closure from initialnames and name2fixturedefs.
370
+
371
+ Can only reduce names_closure, which means that the new closure will
372
+ always be a subset of the old one. The order is preserved.
373
+
374
+ This method is needed because direct parametrization may shadow some
375
+ of the fixtures that were included in the originally built dependency
376
+ tree. In this way the dependency tree can get pruned, and the closure
377
+ of argnames may get reduced.
378
+ """
379
+ closure: Set[str] = set()
380
+ working_set = set(self.initialnames)
381
+ while working_set:
382
+ argname = working_set.pop()
383
+ # Argname may be smth not included in the original names_closure,
384
+ # in which case we ignore it. This currently happens with pseudo
385
+ # FixtureDefs which wrap 'get_direct_param_fixture_func(request)'.
386
+ # So they introduce the new dependency 'request' which might have
387
+ # been missing in the original tree (closure).
388
+ if argname not in closure and argname in self.names_closure:
389
+ closure.add(argname)
390
+ if argname in self.name2fixturedefs:
391
+ working_set.update(self.name2fixturedefs[argname][-1].argnames)
392
+
393
+ self.names_closure[:] = sorted(closure, key=self.names_closure.index)
394
+
395
+
396
+ class FixtureRequest:
397
+ """A request for a fixture from a test or fixture function.
398
+
399
+ A request object gives access to the requesting test context and has
400
+ an optional ``param`` attribute in case the fixture is parametrized
401
+ indirectly.
402
+ """
403
+
404
+ def __init__(self, pyfuncitem, *, _ispytest: bool = False) -> None:
405
+ check_ispytest(_ispytest)
406
+ self._pyfuncitem = pyfuncitem
407
+ #: Fixture for which this request is being performed.
408
+ self.fixturename: Optional[str] = None
409
+ self._scope = Scope.Function
410
+ self._fixture_defs: Dict[str, FixtureDef[Any]] = {}
411
+ fixtureinfo: FuncFixtureInfo = pyfuncitem._fixtureinfo
412
+ self._arg2fixturedefs = fixtureinfo.name2fixturedefs.copy()
413
+ self._arg2index: Dict[str, int] = {}
414
+ self._fixturemanager: FixtureManager = pyfuncitem.session._fixturemanager
415
+ # Notes on the type of `param`:
416
+ # -`request.param` is only defined in parametrized fixtures, and will raise
417
+ # AttributeError otherwise. Python typing has no notion of "undefined", so
418
+ # this cannot be reflected in the type.
419
+ # - Technically `param` is only (possibly) defined on SubRequest, not
420
+ # FixtureRequest, but the typing of that is still in flux so this cheats.
421
+ # - In the future we might consider using a generic for the param type, but
422
+ # for now just using Any.
423
+ self.param: Any
424
+
425
+ @property
426
+ def scope(self) -> "_ScopeName":
427
+ """Scope string, one of "function", "class", "module", "package", "session"."""
428
+ return self._scope.value
429
+
430
+ @property
431
+ def fixturenames(self) -> List[str]:
432
+ """Names of all active fixtures in this request."""
433
+ result = list(self._pyfuncitem._fixtureinfo.names_closure)
434
+ result.extend(set(self._fixture_defs).difference(result))
435
+ return result
436
+
437
+ @property
438
+ def node(self):
439
+ """Underlying collection node (depends on current request scope)."""
440
+ scope = self._scope
441
+ if scope is Scope.Function:
442
+ # This might also be a non-function Item despite its attribute name.
443
+ node: Optional[Union[nodes.Item, nodes.Collector]] = self._pyfuncitem
444
+ elif scope is Scope.Package:
445
+ # FIXME: _fixturedef is not defined on FixtureRequest (this class),
446
+ # but on FixtureRequest (a subclass).
447
+ node = get_scope_package(self._pyfuncitem, self._fixturedef) # type: ignore[attr-defined]
448
+ else:
449
+ node = get_scope_node(self._pyfuncitem, scope)
450
+ if node is None and scope is Scope.Class:
451
+ # Fallback to function item itself.
452
+ node = self._pyfuncitem
453
+ assert node, 'Could not obtain a node for scope "{}" for function {!r}'.format(
454
+ scope, self._pyfuncitem
455
+ )
456
+ return node
457
+
458
+ def _getnextfixturedef(self, argname: str) -> "FixtureDef[Any]":
459
+ fixturedefs = self._arg2fixturedefs.get(argname, None)
460
+ if fixturedefs is None:
461
+ # We arrive here because of a dynamic call to
462
+ # getfixturevalue(argname) usage which was naturally
463
+ # not known at parsing/collection time.
464
+ assert self._pyfuncitem.parent is not None
465
+ parentid = self._pyfuncitem.parent.nodeid
466
+ fixturedefs = self._fixturemanager.getfixturedefs(argname, parentid)
467
+ # TODO: Fix this type ignore. Either add assert or adjust types.
468
+ # Can this be None here?
469
+ self._arg2fixturedefs[argname] = fixturedefs # type: ignore[assignment]
470
+ # fixturedefs list is immutable so we maintain a decreasing index.
471
+ index = self._arg2index.get(argname, 0) - 1
472
+ if fixturedefs is None or (-index > len(fixturedefs)):
473
+ raise FixtureLookupError(argname, self)
474
+ self._arg2index[argname] = index
475
+ return fixturedefs[index]
476
+
477
+ @property
478
+ def config(self) -> Config:
479
+ """The pytest config object associated with this request."""
480
+ return self._pyfuncitem.config # type: ignore[no-any-return]
481
+
482
+ @property
483
+ def function(self):
484
+ """Test function object if the request has a per-function scope."""
485
+ if self.scope != "function":
486
+ raise AttributeError(
487
+ f"function not available in {self.scope}-scoped context"
488
+ )
489
+ return self._pyfuncitem.obj
490
+
491
+ @property
492
+ def cls(self):
493
+ """Class (can be None) where the test function was collected."""
494
+ if self.scope not in ("class", "function"):
495
+ raise AttributeError(f"cls not available in {self.scope}-scoped context")
496
+ clscol = self._pyfuncitem.getparent(_pytest.python.Class)
497
+ if clscol:
498
+ return clscol.obj
499
+
500
+ @property
501
+ def instance(self):
502
+ """Instance (can be None) on which test function was collected."""
503
+ # unittest support hack, see _pytest.unittest.TestCaseFunction.
504
+ try:
505
+ return self._pyfuncitem._testcase
506
+ except AttributeError:
507
+ function = getattr(self, "function", None)
508
+ return getattr(function, "__self__", None)
509
+
510
+ @property
511
+ def module(self):
512
+ """Python module object where the test function was collected."""
513
+ if self.scope not in ("function", "class", "module"):
514
+ raise AttributeError(f"module not available in {self.scope}-scoped context")
515
+ return self._pyfuncitem.getparent(_pytest.python.Module).obj
516
+
517
+ @property
518
+ def path(self) -> Path:
519
+ """Path where the test function was collected."""
520
+ if self.scope not in ("function", "class", "module", "package"):
521
+ raise AttributeError(f"path not available in {self.scope}-scoped context")
522
+ # TODO: Remove ignore once _pyfuncitem is properly typed.
523
+ return self._pyfuncitem.path # type: ignore
524
+
525
+ @property
526
+ def keywords(self) -> MutableMapping[str, Any]:
527
+ """Keywords/markers dictionary for the underlying node."""
528
+ node: nodes.Node = self.node
529
+ return node.keywords
530
+
531
+ @property
532
+ def session(self) -> "Session":
533
+ """Pytest session object."""
534
+ return self._pyfuncitem.session # type: ignore[no-any-return]
535
+
536
+ def addfinalizer(self, finalizer: Callable[[], object]) -> None:
537
+ """Add finalizer/teardown function to be called without arguments after
538
+ the last test within the requesting test context finished execution."""
539
+ # XXX usually this method is shadowed by fixturedef specific ones.
540
+ self.node.addfinalizer(finalizer)
541
+
542
+ def applymarker(self, marker: Union[str, MarkDecorator]) -> None:
543
+ """Apply a marker to a single test function invocation.
544
+
545
+ This method is useful if you don't want to have a keyword/marker
546
+ on all function invocations.
547
+
548
+ :param marker:
549
+ An object created by a call to ``pytest.mark.NAME(...)``.
550
+ """
551
+ self.node.add_marker(marker)
552
+
553
+ def raiseerror(self, msg: Optional[str]) -> NoReturn:
554
+ """Raise a FixtureLookupError exception.
555
+
556
+ :param msg:
557
+ An optional custom error message.
558
+ """
559
+ raise self._fixturemanager.FixtureLookupError(None, self, msg)
560
+
561
+ def _fillfixtures(self) -> None:
562
+ item = self._pyfuncitem
563
+ fixturenames = getattr(item, "fixturenames", self.fixturenames)
564
+ for argname in fixturenames:
565
+ if argname not in item.funcargs:
566
+ item.funcargs[argname] = self.getfixturevalue(argname)
567
+
568
+ def getfixturevalue(self, argname: str) -> Any:
569
+ """Dynamically run a named fixture function.
570
+
571
+ Declaring fixtures via function argument is recommended where possible.
572
+ But if you can only decide whether to use another fixture at test
573
+ setup time, you may use this function to retrieve it inside a fixture
574
+ or test function body.
575
+
576
+ This method can be used during the test setup phase or the test run
577
+ phase, but during the test teardown phase a fixture's value may not
578
+ be available.
579
+
580
+ :param argname:
581
+ The fixture name.
582
+ :raises pytest.FixtureLookupError:
583
+ If the given fixture could not be found.
584
+ """
585
+ fixturedef = self._get_active_fixturedef(argname)
586
+ assert fixturedef.cached_result is not None, (
587
+ f'The fixture value for "{argname}" is not available. '
588
+ "This can happen when the fixture has already been torn down."
589
+ )
590
+ return fixturedef.cached_result[0]
591
+
592
+ def _get_active_fixturedef(
593
+ self, argname: str
594
+ ) -> Union["FixtureDef[object]", PseudoFixtureDef[object]]:
595
+ try:
596
+ return self._fixture_defs[argname]
597
+ except KeyError:
598
+ try:
599
+ fixturedef = self._getnextfixturedef(argname)
600
+ except FixtureLookupError:
601
+ if argname == "request":
602
+ cached_result = (self, [0], None)
603
+ return PseudoFixtureDef(cached_result, Scope.Function)
604
+ raise
605
+ # Remove indent to prevent the python3 exception
606
+ # from leaking into the call.
607
+ self._compute_fixture_value(fixturedef)
608
+ self._fixture_defs[argname] = fixturedef
609
+ return fixturedef
610
+
611
+ def _get_fixturestack(self) -> List["FixtureDef[Any]"]:
612
+ current = self
613
+ values: List[FixtureDef[Any]] = []
614
+ while isinstance(current, SubRequest):
615
+ values.append(current._fixturedef) # type: ignore[has-type]
616
+ current = current._parent_request
617
+ values.reverse()
618
+ return values
619
+
620
+ def _compute_fixture_value(self, fixturedef: "FixtureDef[object]") -> None:
621
+ """Create a SubRequest based on "self" and call the execute method
622
+ of the given FixtureDef object.
623
+
624
+ This will force the FixtureDef object to throw away any previous
625
+ results and compute a new fixture value, which will be stored into
626
+ the FixtureDef object itself.
627
+ """
628
+ # prepare a subrequest object before calling fixture function
629
+ # (latter managed by fixturedef)
630
+ argname = fixturedef.argname
631
+ funcitem = self._pyfuncitem
632
+ scope = fixturedef._scope
633
+ try:
634
+ callspec = funcitem.callspec
635
+ except AttributeError:
636
+ callspec = None
637
+ if callspec is not None and argname in callspec.params:
638
+ param = callspec.params[argname]
639
+ param_index = callspec.indices[argname]
640
+ # If a parametrize invocation set a scope it will override
641
+ # the static scope defined with the fixture function.
642
+ with suppress(KeyError):
643
+ scope = callspec._arg2scope[argname]
644
+ else:
645
+ param = NOTSET
646
+ param_index = 0
647
+ has_params = fixturedef.params is not None
648
+ fixtures_not_supported = getattr(funcitem, "nofuncargs", False)
649
+ if has_params and fixtures_not_supported:
650
+ msg = (
651
+ "{name} does not support fixtures, maybe unittest.TestCase subclass?\n"
652
+ "Node id: {nodeid}\n"
653
+ "Function type: {typename}"
654
+ ).format(
655
+ name=funcitem.name,
656
+ nodeid=funcitem.nodeid,
657
+ typename=type(funcitem).__name__,
658
+ )
659
+ fail(msg, pytrace=False)
660
+ if has_params:
661
+ frame = inspect.stack()[3]
662
+ frameinfo = inspect.getframeinfo(frame[0])
663
+ source_path = absolutepath(frameinfo.filename)
664
+ source_lineno = frameinfo.lineno
665
+ try:
666
+ source_path_str = str(
667
+ source_path.relative_to(funcitem.config.rootpath)
668
+ )
669
+ except ValueError:
670
+ source_path_str = str(source_path)
671
+ msg = (
672
+ "The requested fixture has no parameter defined for test:\n"
673
+ " {}\n\n"
674
+ "Requested fixture '{}' defined in:\n{}"
675
+ "\n\nRequested here:\n{}:{}".format(
676
+ funcitem.nodeid,
677
+ fixturedef.argname,
678
+ getlocation(fixturedef.func, funcitem.config.rootpath),
679
+ source_path_str,
680
+ source_lineno,
681
+ )
682
+ )
683
+ fail(msg, pytrace=False)
684
+
685
+ subrequest = SubRequest(
686
+ self, scope, param, param_index, fixturedef, _ispytest=True
687
+ )
688
+
689
+ # Check if a higher-level scoped fixture accesses a lower level one.
690
+ subrequest._check_scope(argname, self._scope, scope)
691
+ try:
692
+ # Call the fixture function.
693
+ fixturedef.execute(request=subrequest)
694
+ finally:
695
+ self._schedule_finalizers(fixturedef, subrequest)
696
+
697
+ def _schedule_finalizers(
698
+ self, fixturedef: "FixtureDef[object]", subrequest: "SubRequest"
699
+ ) -> None:
700
+ # If fixture function failed it might have registered finalizers.
701
+ subrequest.node.addfinalizer(lambda: fixturedef.finish(request=subrequest))
702
+
703
+ def _check_scope(
704
+ self,
705
+ argname: str,
706
+ invoking_scope: Scope,
707
+ requested_scope: Scope,
708
+ ) -> None:
709
+ if argname == "request":
710
+ return
711
+ if invoking_scope > requested_scope:
712
+ # Try to report something helpful.
713
+ text = "\n".join(self._factorytraceback())
714
+ fail(
715
+ f"ScopeMismatch: You tried to access the {requested_scope.value} scoped "
716
+ f"fixture {argname} with a {invoking_scope.value} scoped request object, "
717
+ f"involved factories:\n{text}",
718
+ pytrace=False,
719
+ )
720
+
721
+ def _factorytraceback(self) -> List[str]:
722
+ lines = []
723
+ for fixturedef in self._get_fixturestack():
724
+ factory = fixturedef.func
725
+ fs, lineno = getfslineno(factory)
726
+ if isinstance(fs, Path):
727
+ session: Session = self._pyfuncitem.session
728
+ p = bestrelpath(session.path, fs)
729
+ else:
730
+ p = fs
731
+ args = _format_args(factory)
732
+ lines.append("%s:%d: def %s%s" % (p, lineno + 1, factory.__name__, args))
733
+ return lines
734
+
735
+ def __repr__(self) -> str:
736
+ return "<FixtureRequest for %r>" % (self.node)
737
+
738
+
739
+ @final
740
+ class SubRequest(FixtureRequest):
741
+ """A sub request for handling getting a fixture from a test function/fixture."""
742
+
743
+ def __init__(
744
+ self,
745
+ request: "FixtureRequest",
746
+ scope: Scope,
747
+ param: Any,
748
+ param_index: int,
749
+ fixturedef: "FixtureDef[object]",
750
+ *,
751
+ _ispytest: bool = False,
752
+ ) -> None:
753
+ check_ispytest(_ispytest)
754
+ self._parent_request = request
755
+ self.fixturename = fixturedef.argname
756
+ if param is not NOTSET:
757
+ self.param = param
758
+ self.param_index = param_index
759
+ self._scope = scope
760
+ self._fixturedef = fixturedef
761
+ self._pyfuncitem = request._pyfuncitem
762
+ self._fixture_defs = request._fixture_defs
763
+ self._arg2fixturedefs = request._arg2fixturedefs
764
+ self._arg2index = request._arg2index
765
+ self._fixturemanager = request._fixturemanager
766
+
767
+ def __repr__(self) -> str:
768
+ return f"<SubRequest {self.fixturename!r} for {self._pyfuncitem!r}>"
769
+
770
+ def addfinalizer(self, finalizer: Callable[[], object]) -> None:
771
+ """Add finalizer/teardown function to be called without arguments after
772
+ the last test within the requesting test context finished execution."""
773
+ self._fixturedef.addfinalizer(finalizer)
774
+
775
+ def _schedule_finalizers(
776
+ self, fixturedef: "FixtureDef[object]", subrequest: "SubRequest"
777
+ ) -> None:
778
+ # If the executing fixturedef was not explicitly requested in the argument list (via
779
+ # getfixturevalue inside the fixture call) then ensure this fixture def will be finished
780
+ # first.
781
+ if fixturedef.argname not in self.fixturenames:
782
+ fixturedef.addfinalizer(
783
+ functools.partial(self._fixturedef.finish, request=self)
784
+ )
785
+ super()._schedule_finalizers(fixturedef, subrequest)
786
+
787
+
788
+ @final
789
+ class FixtureLookupError(LookupError):
790
+ """Could not return a requested fixture (missing or invalid)."""
791
+
792
+ def __init__(
793
+ self, argname: Optional[str], request: FixtureRequest, msg: Optional[str] = None
794
+ ) -> None:
795
+ self.argname = argname
796
+ self.request = request
797
+ self.fixturestack = request._get_fixturestack()
798
+ self.msg = msg
799
+
800
+ def formatrepr(self) -> "FixtureLookupErrorRepr":
801
+ tblines: List[str] = []
802
+ addline = tblines.append
803
+ stack = [self.request._pyfuncitem.obj]
804
+ stack.extend(map(lambda x: x.func, self.fixturestack))
805
+ msg = self.msg
806
+ if msg is not None:
807
+ # The last fixture raise an error, let's present
808
+ # it at the requesting side.
809
+ stack = stack[:-1]
810
+ for function in stack:
811
+ fspath, lineno = getfslineno(function)
812
+ try:
813
+ lines, _ = inspect.getsourcelines(get_real_func(function))
814
+ except (OSError, IndexError, TypeError):
815
+ error_msg = "file %s, line %s: source code not available"
816
+ addline(error_msg % (fspath, lineno + 1))
817
+ else:
818
+ addline(f"file {fspath}, line {lineno + 1}")
819
+ for i, line in enumerate(lines):
820
+ line = line.rstrip()
821
+ addline(" " + line)
822
+ if line.lstrip().startswith("def"):
823
+ break
824
+
825
+ if msg is None:
826
+ fm = self.request._fixturemanager
827
+ available = set()
828
+ parentid = self.request._pyfuncitem.parent.nodeid
829
+ for name, fixturedefs in fm._arg2fixturedefs.items():
830
+ faclist = list(fm._matchfactories(fixturedefs, parentid))
831
+ if faclist:
832
+ available.add(name)
833
+ if self.argname in available:
834
+ msg = " recursive dependency involving fixture '{}' detected".format(
835
+ self.argname
836
+ )
837
+ else:
838
+ msg = f"fixture '{self.argname}' not found"
839
+ msg += "\n available fixtures: {}".format(", ".join(sorted(available)))
840
+ msg += "\n use 'pytest --fixtures [testpath]' for help on them."
841
+
842
+ return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname)
843
+
844
+
845
+ class FixtureLookupErrorRepr(TerminalRepr):
846
+ def __init__(
847
+ self,
848
+ filename: Union[str, "os.PathLike[str]"],
849
+ firstlineno: int,
850
+ tblines: Sequence[str],
851
+ errorstring: str,
852
+ argname: Optional[str],
853
+ ) -> None:
854
+ self.tblines = tblines
855
+ self.errorstring = errorstring
856
+ self.filename = filename
857
+ self.firstlineno = firstlineno
858
+ self.argname = argname
859
+
860
+ def toterminal(self, tw: TerminalWriter) -> None:
861
+ # tw.line("FixtureLookupError: %s" %(self.argname), red=True)
862
+ for tbline in self.tblines:
863
+ tw.line(tbline.rstrip())
864
+ lines = self.errorstring.split("\n")
865
+ if lines:
866
+ tw.line(
867
+ f"{FormattedExcinfo.fail_marker} {lines[0].strip()}",
868
+ red=True,
869
+ )
870
+ for line in lines[1:]:
871
+ tw.line(
872
+ f"{FormattedExcinfo.flow_marker} {line.strip()}",
873
+ red=True,
874
+ )
875
+ tw.line()
876
+ tw.line("%s:%d" % (os.fspath(self.filename), self.firstlineno + 1))
877
+
878
+
879
+ def fail_fixturefunc(fixturefunc, msg: str) -> NoReturn:
880
+ fs, lineno = getfslineno(fixturefunc)
881
+ location = f"{fs}:{lineno + 1}"
882
+ source = _pytest._code.Source(fixturefunc)
883
+ fail(msg + ":\n\n" + str(source.indent()) + "\n" + location, pytrace=False)
884
+
885
+
886
+ def call_fixture_func(
887
+ fixturefunc: "_FixtureFunc[FixtureValue]", request: FixtureRequest, kwargs
888
+ ) -> FixtureValue:
889
+ if is_generator(fixturefunc):
890
+ fixturefunc = cast(
891
+ Callable[..., Generator[FixtureValue, None, None]], fixturefunc
892
+ )
893
+ generator = fixturefunc(**kwargs)
894
+ try:
895
+ fixture_result = next(generator)
896
+ except StopIteration:
897
+ raise ValueError(f"{request.fixturename} did not yield a value") from None
898
+ finalizer = functools.partial(_teardown_yield_fixture, fixturefunc, generator)
899
+ request.addfinalizer(finalizer)
900
+ else:
901
+ fixturefunc = cast(Callable[..., FixtureValue], fixturefunc)
902
+ fixture_result = fixturefunc(**kwargs)
903
+ return fixture_result
904
+
905
+
906
+ def _teardown_yield_fixture(fixturefunc, it) -> None:
907
+ """Execute the teardown of a fixture function by advancing the iterator
908
+ after the yield and ensure the iteration ends (if not it means there is
909
+ more than one yield in the function)."""
910
+ try:
911
+ next(it)
912
+ except StopIteration:
913
+ pass
914
+ else:
915
+ fail_fixturefunc(fixturefunc, "fixture function has more than one 'yield'")
916
+
917
+
918
+ def _eval_scope_callable(
919
+ scope_callable: "Callable[[str, Config], _ScopeName]",
920
+ fixture_name: str,
921
+ config: Config,
922
+ ) -> "_ScopeName":
923
+ try:
924
+ # Type ignored because there is no typing mechanism to specify
925
+ # keyword arguments, currently.
926
+ result = scope_callable(fixture_name=fixture_name, config=config) # type: ignore[call-arg]
927
+ except Exception as e:
928
+ raise TypeError(
929
+ "Error evaluating {} while defining fixture '{}'.\n"
930
+ "Expected a function with the signature (*, fixture_name, config)".format(
931
+ scope_callable, fixture_name
932
+ )
933
+ ) from e
934
+ if not isinstance(result, str):
935
+ fail(
936
+ "Expected {} to return a 'str' while defining fixture '{}', but it returned:\n"
937
+ "{!r}".format(scope_callable, fixture_name, result),
938
+ pytrace=False,
939
+ )
940
+ return result
941
+
942
+
943
+ @final
944
+ class FixtureDef(Generic[FixtureValue]):
945
+ """A container for a fixture definition."""
946
+
947
+ def __init__(
948
+ self,
949
+ fixturemanager: "FixtureManager",
950
+ baseid: Optional[str],
951
+ argname: str,
952
+ func: "_FixtureFunc[FixtureValue]",
953
+ scope: Union[Scope, "_ScopeName", Callable[[str, Config], "_ScopeName"], None],
954
+ params: Optional[Sequence[object]],
955
+ unittest: bool = False,
956
+ ids: Optional[
957
+ Union[Tuple[Optional[object], ...], Callable[[Any], Optional[object]]]
958
+ ] = None,
959
+ ) -> None:
960
+ self._fixturemanager = fixturemanager
961
+ # The "base" node ID for the fixture.
962
+ #
963
+ # This is a node ID prefix. A fixture is only available to a node (e.g.
964
+ # a `Function` item) if the fixture's baseid is a parent of the node's
965
+ # nodeid (see the `iterparentnodeids` function for what constitutes a
966
+ # "parent" and a "prefix" in this context).
967
+ #
968
+ # For a fixture found in a Collector's object (e.g. a `Module`s module,
969
+ # a `Class`'s class), the baseid is the Collector's nodeid.
970
+ #
971
+ # For a fixture found in a conftest plugin, the baseid is the conftest's
972
+ # directory path relative to the rootdir.
973
+ #
974
+ # For other plugins, the baseid is the empty string (always matches).
975
+ self.baseid = baseid or ""
976
+ # Whether the fixture was found from a node or a conftest in the
977
+ # collection tree. Will be false for fixtures defined in non-conftest
978
+ # plugins.
979
+ self.has_location = baseid is not None
980
+ # The fixture factory function.
981
+ self.func = func
982
+ # The name by which the fixture may be requested.
983
+ self.argname = argname
984
+ if scope is None:
985
+ scope = Scope.Function
986
+ elif callable(scope):
987
+ scope = _eval_scope_callable(scope, argname, fixturemanager.config)
988
+ if isinstance(scope, str):
989
+ scope = Scope.from_user(
990
+ scope, descr=f"Fixture '{func.__name__}'", where=baseid
991
+ )
992
+ self._scope = scope
993
+ # If the fixture is directly parametrized, the parameter values.
994
+ self.params: Optional[Sequence[object]] = params
995
+ # If the fixture is directly parametrized, a tuple of explicit IDs to
996
+ # assign to the parameter values, or a callable to generate an ID given
997
+ # a parameter value.
998
+ self.ids = ids
999
+ # The names requested by the fixtures.
1000
+ self.argnames = getfuncargnames(func, name=argname, is_method=unittest)
1001
+ # Whether the fixture was collected from a unittest TestCase class.
1002
+ # Note that it really only makes sense to define autouse fixtures in
1003
+ # unittest TestCases.
1004
+ self.unittest = unittest
1005
+ # If the fixture was executed, the current value of the fixture.
1006
+ # Can change if the fixture is executed with different parameters.
1007
+ self.cached_result: Optional[_FixtureCachedResult[FixtureValue]] = None
1008
+ self._finalizers: List[Callable[[], object]] = []
1009
+
1010
+ @property
1011
+ def scope(self) -> "_ScopeName":
1012
+ """Scope string, one of "function", "class", "module", "package", "session"."""
1013
+ return self._scope.value
1014
+
1015
+ def addfinalizer(self, finalizer: Callable[[], object]) -> None:
1016
+ self._finalizers.append(finalizer)
1017
+
1018
+ def finish(self, request: SubRequest) -> None:
1019
+ exc = None
1020
+ try:
1021
+ while self._finalizers:
1022
+ try:
1023
+ func = self._finalizers.pop()
1024
+ func()
1025
+ except BaseException as e:
1026
+ # XXX Only first exception will be seen by user,
1027
+ # ideally all should be reported.
1028
+ if exc is None:
1029
+ exc = e
1030
+ if exc:
1031
+ raise exc
1032
+ finally:
1033
+ ihook = request.node.ihook
1034
+ ihook.pytest_fixture_post_finalizer(fixturedef=self, request=request)
1035
+ # Even if finalization fails, we invalidate the cached fixture
1036
+ # value and remove all finalizers because they may be bound methods
1037
+ # which will keep instances alive.
1038
+ self.cached_result = None
1039
+ self._finalizers = []
1040
+
1041
+ def execute(self, request: SubRequest) -> FixtureValue:
1042
+ # Get required arguments and register our own finish()
1043
+ # with their finalization.
1044
+ for argname in self.argnames:
1045
+ fixturedef = request._get_active_fixturedef(argname)
1046
+ if argname != "request":
1047
+ # PseudoFixtureDef is only for "request".
1048
+ assert isinstance(fixturedef, FixtureDef)
1049
+ fixturedef.addfinalizer(functools.partial(self.finish, request=request))
1050
+
1051
+ my_cache_key = self.cache_key(request)
1052
+ if self.cached_result is not None:
1053
+ # note: comparison with `==` can fail (or be expensive) for e.g.
1054
+ # numpy arrays (#6497).
1055
+ cache_key = self.cached_result[1]
1056
+ if my_cache_key is cache_key:
1057
+ if self.cached_result[2] is not None:
1058
+ _, val, tb = self.cached_result[2]
1059
+ raise val.with_traceback(tb)
1060
+ else:
1061
+ result = self.cached_result[0]
1062
+ return result
1063
+ # We have a previous but differently parametrized fixture instance
1064
+ # so we need to tear it down before creating a new one.
1065
+ self.finish(request)
1066
+ assert self.cached_result is None
1067
+
1068
+ ihook = request.node.ihook
1069
+ result = ihook.pytest_fixture_setup(fixturedef=self, request=request)
1070
+ return result
1071
+
1072
+ def cache_key(self, request: SubRequest) -> object:
1073
+ return request.param_index if not hasattr(request, "param") else request.param
1074
+
1075
+ def __repr__(self) -> str:
1076
+ return "<FixtureDef argname={!r} scope={!r} baseid={!r}>".format(
1077
+ self.argname, self.scope, self.baseid
1078
+ )
1079
+
1080
+
1081
+ def resolve_fixture_function(
1082
+ fixturedef: FixtureDef[FixtureValue], request: FixtureRequest
1083
+ ) -> "_FixtureFunc[FixtureValue]":
1084
+ """Get the actual callable that can be called to obtain the fixture
1085
+ value, dealing with unittest-specific instances and bound methods."""
1086
+ fixturefunc = fixturedef.func
1087
+ if fixturedef.unittest:
1088
+ if request.instance is not None:
1089
+ # Bind the unbound method to the TestCase instance.
1090
+ fixturefunc = fixturedef.func.__get__(request.instance) # type: ignore[union-attr]
1091
+ else:
1092
+ # The fixture function needs to be bound to the actual
1093
+ # request.instance so that code working with "fixturedef" behaves
1094
+ # as expected.
1095
+ if request.instance is not None:
1096
+ # Handle the case where fixture is defined not in a test class, but some other class
1097
+ # (for example a plugin class with a fixture), see #2270.
1098
+ if hasattr(fixturefunc, "__self__") and not isinstance(
1099
+ request.instance, fixturefunc.__self__.__class__ # type: ignore[union-attr]
1100
+ ):
1101
+ return fixturefunc
1102
+ fixturefunc = getimfunc(fixturedef.func)
1103
+ if fixturefunc != fixturedef.func:
1104
+ fixturefunc = fixturefunc.__get__(request.instance) # type: ignore[union-attr]
1105
+ return fixturefunc
1106
+
1107
+
1108
+ def pytest_fixture_setup(
1109
+ fixturedef: FixtureDef[FixtureValue], request: SubRequest
1110
+ ) -> FixtureValue:
1111
+ """Execution of fixture setup."""
1112
+ kwargs = {}
1113
+ for argname in fixturedef.argnames:
1114
+ fixdef = request._get_active_fixturedef(argname)
1115
+ assert fixdef.cached_result is not None
1116
+ result, arg_cache_key, exc = fixdef.cached_result
1117
+ request._check_scope(argname, request._scope, fixdef._scope)
1118
+ kwargs[argname] = result
1119
+
1120
+ fixturefunc = resolve_fixture_function(fixturedef, request)
1121
+ my_cache_key = fixturedef.cache_key(request)
1122
+ try:
1123
+ result = call_fixture_func(fixturefunc, request, kwargs)
1124
+ except TEST_OUTCOME:
1125
+ exc_info = sys.exc_info()
1126
+ assert exc_info[0] is not None
1127
+ if isinstance(
1128
+ exc_info[1], skip.Exception
1129
+ ) and not fixturefunc.__name__.startswith("xunit_setup"):
1130
+ exc_info[1]._use_item_location = True # type: ignore[attr-defined]
1131
+ fixturedef.cached_result = (None, my_cache_key, exc_info)
1132
+ raise
1133
+ fixturedef.cached_result = (result, my_cache_key, None)
1134
+ return result
1135
+
1136
+
1137
+ def _ensure_immutable_ids(
1138
+ ids: Optional[Union[Sequence[Optional[object]], Callable[[Any], Optional[object]]]]
1139
+ ) -> Optional[Union[Tuple[Optional[object], ...], Callable[[Any], Optional[object]]]]:
1140
+ if ids is None:
1141
+ return None
1142
+ if callable(ids):
1143
+ return ids
1144
+ return tuple(ids)
1145
+
1146
+
1147
+ def _params_converter(
1148
+ params: Optional[Iterable[object]],
1149
+ ) -> Optional[Tuple[object, ...]]:
1150
+ return tuple(params) if params is not None else None
1151
+
1152
+
1153
+ def wrap_function_to_error_out_if_called_directly(
1154
+ function: FixtureFunction,
1155
+ fixture_marker: "FixtureFunctionMarker",
1156
+ ) -> FixtureFunction:
1157
+ """Wrap the given fixture function so we can raise an error about it being called directly,
1158
+ instead of used as an argument in a test function."""
1159
+ message = (
1160
+ 'Fixture "{name}" called directly. Fixtures are not meant to be called directly,\n'
1161
+ "but are created automatically when test functions request them as parameters.\n"
1162
+ "See https://docs.pytest.org/en/stable/explanation/fixtures.html for more information about fixtures, and\n"
1163
+ "https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly about how to update your code."
1164
+ ).format(name=fixture_marker.name or function.__name__)
1165
+
1166
+ @functools.wraps(function)
1167
+ def result(*args, **kwargs):
1168
+ fail(message, pytrace=False)
1169
+
1170
+ # Keep reference to the original function in our own custom attribute so we don't unwrap
1171
+ # further than this point and lose useful wrappings like @mock.patch (#3774).
1172
+ result.__pytest_wrapped__ = _PytestWrapper(function) # type: ignore[attr-defined]
1173
+
1174
+ return cast(FixtureFunction, result)
1175
+
1176
+
1177
+ @final
1178
+ @dataclasses.dataclass(frozen=True)
1179
+ class FixtureFunctionMarker:
1180
+ scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]"
1181
+ params: Optional[Tuple[object, ...]]
1182
+ autouse: bool = False
1183
+ ids: Optional[
1184
+ Union[Tuple[Optional[object], ...], Callable[[Any], Optional[object]]]
1185
+ ] = None
1186
+ name: Optional[str] = None
1187
+
1188
+ _ispytest: dataclasses.InitVar[bool] = False
1189
+
1190
+ def __post_init__(self, _ispytest: bool) -> None:
1191
+ check_ispytest(_ispytest)
1192
+
1193
+ def __call__(self, function: FixtureFunction) -> FixtureFunction:
1194
+ if inspect.isclass(function):
1195
+ raise ValueError("class fixtures not supported (maybe in the future)")
1196
+
1197
+ if getattr(function, "_pytestfixturefunction", False):
1198
+ raise ValueError(
1199
+ "fixture is being applied more than once to the same function"
1200
+ )
1201
+
1202
+ function = wrap_function_to_error_out_if_called_directly(function, self)
1203
+
1204
+ name = self.name or function.__name__
1205
+ if name == "request":
1206
+ location = getlocation(function)
1207
+ fail(
1208
+ "'request' is a reserved word for fixtures, use another name:\n {}".format(
1209
+ location
1210
+ ),
1211
+ pytrace=False,
1212
+ )
1213
+
1214
+ # Type ignored because https://github.com/python/mypy/issues/2087.
1215
+ function._pytestfixturefunction = self # type: ignore[attr-defined]
1216
+ return function
1217
+
1218
+
1219
+ @overload
1220
+ def fixture(
1221
+ fixture_function: FixtureFunction,
1222
+ *,
1223
+ scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = ...,
1224
+ params: Optional[Iterable[object]] = ...,
1225
+ autouse: bool = ...,
1226
+ ids: Optional[
1227
+ Union[Sequence[Optional[object]], Callable[[Any], Optional[object]]]
1228
+ ] = ...,
1229
+ name: Optional[str] = ...,
1230
+ ) -> FixtureFunction:
1231
+ ...
1232
+
1233
+
1234
+ @overload
1235
+ def fixture( # noqa: F811
1236
+ fixture_function: None = ...,
1237
+ *,
1238
+ scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = ...,
1239
+ params: Optional[Iterable[object]] = ...,
1240
+ autouse: bool = ...,
1241
+ ids: Optional[
1242
+ Union[Sequence[Optional[object]], Callable[[Any], Optional[object]]]
1243
+ ] = ...,
1244
+ name: Optional[str] = None,
1245
+ ) -> FixtureFunctionMarker:
1246
+ ...
1247
+
1248
+
1249
+ def fixture( # noqa: F811
1250
+ fixture_function: Optional[FixtureFunction] = None,
1251
+ *,
1252
+ scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = "function",
1253
+ params: Optional[Iterable[object]] = None,
1254
+ autouse: bool = False,
1255
+ ids: Optional[
1256
+ Union[Sequence[Optional[object]], Callable[[Any], Optional[object]]]
1257
+ ] = None,
1258
+ name: Optional[str] = None,
1259
+ ) -> Union[FixtureFunctionMarker, FixtureFunction]:
1260
+ """Decorator to mark a fixture factory function.
1261
+
1262
+ This decorator can be used, with or without parameters, to define a
1263
+ fixture function.
1264
+
1265
+ The name of the fixture function can later be referenced to cause its
1266
+ invocation ahead of running tests: test modules or classes can use the
1267
+ ``pytest.mark.usefixtures(fixturename)`` marker.
1268
+
1269
+ Test functions can directly use fixture names as input arguments in which
1270
+ case the fixture instance returned from the fixture function will be
1271
+ injected.
1272
+
1273
+ Fixtures can provide their values to test functions using ``return`` or
1274
+ ``yield`` statements. When using ``yield`` the code block after the
1275
+ ``yield`` statement is executed as teardown code regardless of the test
1276
+ outcome, and must yield exactly once.
1277
+
1278
+ :param scope:
1279
+ The scope for which this fixture is shared; one of ``"function"``
1280
+ (default), ``"class"``, ``"module"``, ``"package"`` or ``"session"``.
1281
+
1282
+ This parameter may also be a callable which receives ``(fixture_name, config)``
1283
+ as parameters, and must return a ``str`` with one of the values mentioned above.
1284
+
1285
+ See :ref:`dynamic scope` in the docs for more information.
1286
+
1287
+ :param params:
1288
+ An optional list of parameters which will cause multiple invocations
1289
+ of the fixture function and all of the tests using it. The current
1290
+ parameter is available in ``request.param``.
1291
+
1292
+ :param autouse:
1293
+ If True, the fixture func is activated for all tests that can see it.
1294
+ If False (the default), an explicit reference is needed to activate
1295
+ the fixture.
1296
+
1297
+ :param ids:
1298
+ Sequence of ids each corresponding to the params so that they are
1299
+ part of the test id. If no ids are provided they will be generated
1300
+ automatically from the params.
1301
+
1302
+ :param name:
1303
+ The name of the fixture. This defaults to the name of the decorated
1304
+ function. If a fixture is used in the same module in which it is
1305
+ defined, the function name of the fixture will be shadowed by the
1306
+ function arg that requests the fixture; one way to resolve this is to
1307
+ name the decorated function ``fixture_<fixturename>`` and then use
1308
+ ``@pytest.fixture(name='<fixturename>')``.
1309
+ """
1310
+ fixture_marker = FixtureFunctionMarker(
1311
+ scope=scope,
1312
+ params=tuple(params) if params is not None else None,
1313
+ autouse=autouse,
1314
+ ids=None if ids is None else ids if callable(ids) else tuple(ids),
1315
+ name=name,
1316
+ _ispytest=True,
1317
+ )
1318
+
1319
+ # Direct decoration.
1320
+ if fixture_function:
1321
+ return fixture_marker(fixture_function)
1322
+
1323
+ return fixture_marker
1324
+
1325
+
1326
+ def yield_fixture(
1327
+ fixture_function=None,
1328
+ *args,
1329
+ scope="function",
1330
+ params=None,
1331
+ autouse=False,
1332
+ ids=None,
1333
+ name=None,
1334
+ ):
1335
+ """(Return a) decorator to mark a yield-fixture factory function.
1336
+
1337
+ .. deprecated:: 3.0
1338
+ Use :py:func:`pytest.fixture` directly instead.
1339
+ """
1340
+ warnings.warn(YIELD_FIXTURE, stacklevel=2)
1341
+ return fixture(
1342
+ fixture_function,
1343
+ *args,
1344
+ scope=scope,
1345
+ params=params,
1346
+ autouse=autouse,
1347
+ ids=ids,
1348
+ name=name,
1349
+ )
1350
+
1351
+
1352
+ @fixture(scope="session")
1353
+ def pytestconfig(request: FixtureRequest) -> Config:
1354
+ """Session-scoped fixture that returns the session's :class:`pytest.Config`
1355
+ object.
1356
+
1357
+ Example::
1358
+
1359
+ def test_foo(pytestconfig):
1360
+ if pytestconfig.getoption("verbose") > 0:
1361
+ ...
1362
+
1363
+ """
1364
+ return request.config
1365
+
1366
+
1367
+ def pytest_addoption(parser: Parser) -> None:
1368
+ parser.addini(
1369
+ "usefixtures",
1370
+ type="args",
1371
+ default=[],
1372
+ help="List of default fixtures to be used with this project",
1373
+ )
1374
+
1375
+
1376
+ class FixtureManager:
1377
+ """pytest fixture definitions and information is stored and managed
1378
+ from this class.
1379
+
1380
+ During collection fm.parsefactories() is called multiple times to parse
1381
+ fixture function definitions into FixtureDef objects and internal
1382
+ data structures.
1383
+
1384
+ During collection of test functions, metafunc-mechanics instantiate
1385
+ a FuncFixtureInfo object which is cached per node/func-name.
1386
+ This FuncFixtureInfo object is later retrieved by Function nodes
1387
+ which themselves offer a fixturenames attribute.
1388
+
1389
+ The FuncFixtureInfo object holds information about fixtures and FixtureDefs
1390
+ relevant for a particular function. An initial list of fixtures is
1391
+ assembled like this:
1392
+
1393
+ - ini-defined usefixtures
1394
+ - autouse-marked fixtures along the collection chain up from the function
1395
+ - usefixtures markers at module/class/function level
1396
+ - test function funcargs
1397
+
1398
+ Subsequently the funcfixtureinfo.fixturenames attribute is computed
1399
+ as the closure of the fixtures needed to setup the initial fixtures,
1400
+ i.e. fixtures needed by fixture functions themselves are appended
1401
+ to the fixturenames list.
1402
+
1403
+ Upon the test-setup phases all fixturenames are instantiated, retrieved
1404
+ by a lookup of their FuncFixtureInfo.
1405
+ """
1406
+
1407
+ FixtureLookupError = FixtureLookupError
1408
+ FixtureLookupErrorRepr = FixtureLookupErrorRepr
1409
+
1410
+ def __init__(self, session: "Session") -> None:
1411
+ self.session = session
1412
+ self.config: Config = session.config
1413
+ self._arg2fixturedefs: Dict[str, List[FixtureDef[Any]]] = {}
1414
+ self._holderobjseen: Set[object] = set()
1415
+ # A mapping from a nodeid to a list of autouse fixtures it defines.
1416
+ self._nodeid_autousenames: Dict[str, List[str]] = {
1417
+ "": self.config.getini("usefixtures"),
1418
+ }
1419
+ session.config.pluginmanager.register(self, "funcmanage")
1420
+
1421
+ def _get_direct_parametrize_args(self, node: nodes.Node) -> List[str]:
1422
+ """Return all direct parametrization arguments of a node, so we don't
1423
+ mistake them for fixtures.
1424
+
1425
+ Check https://github.com/pytest-dev/pytest/issues/5036.
1426
+
1427
+ These things are done later as well when dealing with parametrization
1428
+ so this could be improved.
1429
+ """
1430
+ parametrize_argnames: List[str] = []
1431
+ for marker in node.iter_markers(name="parametrize"):
1432
+ if not marker.kwargs.get("indirect", False):
1433
+ p_argnames, _ = ParameterSet._parse_parametrize_args(
1434
+ *marker.args, **marker.kwargs
1435
+ )
1436
+ parametrize_argnames.extend(p_argnames)
1437
+
1438
+ return parametrize_argnames
1439
+
1440
+ def getfixtureinfo(
1441
+ self, node: nodes.Node, func, cls, funcargs: bool = True
1442
+ ) -> FuncFixtureInfo:
1443
+ if funcargs and not getattr(node, "nofuncargs", False):
1444
+ argnames = getfuncargnames(func, name=node.name, cls=cls)
1445
+ else:
1446
+ argnames = ()
1447
+
1448
+ usefixtures = tuple(
1449
+ arg for mark in node.iter_markers(name="usefixtures") for arg in mark.args
1450
+ )
1451
+ initialnames = usefixtures + argnames
1452
+ fm = node.session._fixturemanager
1453
+ initialnames, names_closure, arg2fixturedefs = fm.getfixtureclosure(
1454
+ initialnames, node, ignore_args=self._get_direct_parametrize_args(node)
1455
+ )
1456
+ return FuncFixtureInfo(argnames, initialnames, names_closure, arg2fixturedefs)
1457
+
1458
+ def pytest_plugin_registered(self, plugin: _PluggyPlugin) -> None:
1459
+ nodeid = None
1460
+ try:
1461
+ p = absolutepath(plugin.__file__) # type: ignore[attr-defined]
1462
+ except AttributeError:
1463
+ pass
1464
+ else:
1465
+ # Construct the base nodeid which is later used to check
1466
+ # what fixtures are visible for particular tests (as denoted
1467
+ # by their test id).
1468
+ if p.name.startswith("conftest.py"):
1469
+ try:
1470
+ nodeid = str(p.parent.relative_to(self.config.rootpath))
1471
+ except ValueError:
1472
+ nodeid = ""
1473
+ if nodeid == ".":
1474
+ nodeid = ""
1475
+ if os.sep != nodes.SEP:
1476
+ nodeid = nodeid.replace(os.sep, nodes.SEP)
1477
+
1478
+ self.parsefactories(plugin, nodeid)
1479
+
1480
+ def _getautousenames(self, nodeid: str) -> Iterator[str]:
1481
+ """Return the names of autouse fixtures applicable to nodeid."""
1482
+ for parentnodeid in nodes.iterparentnodeids(nodeid):
1483
+ basenames = self._nodeid_autousenames.get(parentnodeid)
1484
+ if basenames:
1485
+ yield from basenames
1486
+
1487
+ def getfixtureclosure(
1488
+ self,
1489
+ fixturenames: Tuple[str, ...],
1490
+ parentnode: nodes.Node,
1491
+ ignore_args: Sequence[str] = (),
1492
+ ) -> Tuple[Tuple[str, ...], List[str], Dict[str, Sequence[FixtureDef[Any]]]]:
1493
+ # Collect the closure of all fixtures, starting with the given
1494
+ # fixturenames as the initial set. As we have to visit all
1495
+ # factory definitions anyway, we also return an arg2fixturedefs
1496
+ # mapping so that the caller can reuse it and does not have
1497
+ # to re-discover fixturedefs again for each fixturename
1498
+ # (discovering matching fixtures for a given name/node is expensive).
1499
+
1500
+ parentid = parentnode.nodeid
1501
+ fixturenames_closure = list(self._getautousenames(parentid))
1502
+
1503
+ def merge(otherlist: Iterable[str]) -> None:
1504
+ for arg in otherlist:
1505
+ if arg not in fixturenames_closure:
1506
+ fixturenames_closure.append(arg)
1507
+
1508
+ merge(fixturenames)
1509
+
1510
+ # At this point, fixturenames_closure contains what we call "initialnames",
1511
+ # which is a set of fixturenames the function immediately requests. We
1512
+ # need to return it as well, so save this.
1513
+ initialnames = tuple(fixturenames_closure)
1514
+
1515
+ arg2fixturedefs: Dict[str, Sequence[FixtureDef[Any]]] = {}
1516
+ lastlen = -1
1517
+ while lastlen != len(fixturenames_closure):
1518
+ lastlen = len(fixturenames_closure)
1519
+ for argname in fixturenames_closure:
1520
+ if argname in ignore_args:
1521
+ continue
1522
+ if argname in arg2fixturedefs:
1523
+ continue
1524
+ fixturedefs = self.getfixturedefs(argname, parentid)
1525
+ if fixturedefs:
1526
+ arg2fixturedefs[argname] = fixturedefs
1527
+ merge(fixturedefs[-1].argnames)
1528
+
1529
+ def sort_by_scope(arg_name: str) -> Scope:
1530
+ try:
1531
+ fixturedefs = arg2fixturedefs[arg_name]
1532
+ except KeyError:
1533
+ return Scope.Function
1534
+ else:
1535
+ return fixturedefs[-1]._scope
1536
+
1537
+ fixturenames_closure.sort(key=sort_by_scope, reverse=True)
1538
+ return initialnames, fixturenames_closure, arg2fixturedefs
1539
+
1540
+ def pytest_generate_tests(self, metafunc: "Metafunc") -> None:
1541
+ """Generate new tests based on parametrized fixtures used by the given metafunc"""
1542
+
1543
+ def get_parametrize_mark_argnames(mark: Mark) -> Sequence[str]:
1544
+ args, _ = ParameterSet._parse_parametrize_args(*mark.args, **mark.kwargs)
1545
+ return args
1546
+
1547
+ for argname in metafunc.fixturenames:
1548
+ # Get the FixtureDefs for the argname.
1549
+ fixture_defs = metafunc._arg2fixturedefs.get(argname)
1550
+ if not fixture_defs:
1551
+ # Will raise FixtureLookupError at setup time if not parametrized somewhere
1552
+ # else (e.g @pytest.mark.parametrize)
1553
+ continue
1554
+
1555
+ # If the test itself parametrizes using this argname, give it
1556
+ # precedence.
1557
+ if any(
1558
+ argname in get_parametrize_mark_argnames(mark)
1559
+ for mark in metafunc.definition.iter_markers("parametrize")
1560
+ ):
1561
+ continue
1562
+
1563
+ # In the common case we only look at the fixture def with the
1564
+ # closest scope (last in the list). But if the fixture overrides
1565
+ # another fixture, while requesting the super fixture, keep going
1566
+ # in case the super fixture is parametrized (#1953).
1567
+ for fixturedef in reversed(fixture_defs):
1568
+ # Fixture is parametrized, apply it and stop.
1569
+ if fixturedef.params is not None:
1570
+ metafunc.parametrize(
1571
+ argname,
1572
+ fixturedef.params,
1573
+ indirect=True,
1574
+ scope=fixturedef.scope,
1575
+ ids=fixturedef.ids,
1576
+ )
1577
+ break
1578
+
1579
+ # Not requesting the overridden super fixture, stop.
1580
+ if argname not in fixturedef.argnames:
1581
+ break
1582
+
1583
+ # Try next super fixture, if any.
1584
+
1585
+ def pytest_collection_modifyitems(self, items: List[nodes.Item]) -> None:
1586
+ # Separate parametrized setups.
1587
+ items[:] = reorder_items(items)
1588
+
1589
+ @overload
1590
+ def parsefactories(
1591
+ self,
1592
+ node_or_obj: nodes.Node,
1593
+ *,
1594
+ unittest: bool = ...,
1595
+ ) -> None:
1596
+ raise NotImplementedError()
1597
+
1598
+ @overload
1599
+ def parsefactories( # noqa: F811
1600
+ self,
1601
+ node_or_obj: object,
1602
+ nodeid: Optional[str],
1603
+ *,
1604
+ unittest: bool = ...,
1605
+ ) -> None:
1606
+ raise NotImplementedError()
1607
+
1608
+ def parsefactories( # noqa: F811
1609
+ self,
1610
+ node_or_obj: Union[nodes.Node, object],
1611
+ nodeid: Union[str, NotSetType, None] = NOTSET,
1612
+ *,
1613
+ unittest: bool = False,
1614
+ ) -> None:
1615
+ """Collect fixtures from a collection node or object.
1616
+
1617
+ Found fixtures are parsed into `FixtureDef`s and saved.
1618
+
1619
+ If `node_or_object` is a collection node (with an underlying Python
1620
+ object), the node's object is traversed and the node's nodeid is used to
1621
+ determine the fixtures' visibilty. `nodeid` must not be specified in
1622
+ this case.
1623
+
1624
+ If `node_or_object` is an object (e.g. a plugin), the object is
1625
+ traversed and the given `nodeid` is used to determine the fixtures'
1626
+ visibility. `nodeid` must be specified in this case; None and "" mean
1627
+ total visibility.
1628
+ """
1629
+ if nodeid is not NOTSET:
1630
+ holderobj = node_or_obj
1631
+ else:
1632
+ assert isinstance(node_or_obj, nodes.Node)
1633
+ holderobj = cast(object, node_or_obj.obj) # type: ignore[attr-defined]
1634
+ assert isinstance(node_or_obj.nodeid, str)
1635
+ nodeid = node_or_obj.nodeid
1636
+ if holderobj in self._holderobjseen:
1637
+ return
1638
+
1639
+ self._holderobjseen.add(holderobj)
1640
+ autousenames = []
1641
+ for name in dir(holderobj):
1642
+ # ugly workaround for one of the fspath deprecated property of node
1643
+ # todo: safely generalize
1644
+ if isinstance(holderobj, nodes.Node) and name == "fspath":
1645
+ continue
1646
+
1647
+ # The attribute can be an arbitrary descriptor, so the attribute
1648
+ # access below can raise. safe_getatt() ignores such exceptions.
1649
+ obj = safe_getattr(holderobj, name, None)
1650
+ marker = getfixturemarker(obj)
1651
+ if not isinstance(marker, FixtureFunctionMarker):
1652
+ # Magic globals with __getattr__ might have got us a wrong
1653
+ # fixture attribute.
1654
+ continue
1655
+
1656
+ if marker.name:
1657
+ name = marker.name
1658
+
1659
+ # During fixture definition we wrap the original fixture function
1660
+ # to issue a warning if called directly, so here we unwrap it in
1661
+ # order to not emit the warning when pytest itself calls the
1662
+ # fixture function.
1663
+ obj = get_real_method(obj, holderobj)
1664
+
1665
+ fixture_def = FixtureDef(
1666
+ fixturemanager=self,
1667
+ baseid=nodeid,
1668
+ argname=name,
1669
+ func=obj,
1670
+ scope=marker.scope,
1671
+ params=marker.params,
1672
+ unittest=unittest,
1673
+ ids=marker.ids,
1674
+ )
1675
+
1676
+ faclist = self._arg2fixturedefs.setdefault(name, [])
1677
+ if fixture_def.has_location:
1678
+ faclist.append(fixture_def)
1679
+ else:
1680
+ # fixturedefs with no location are at the front
1681
+ # so this inserts the current fixturedef after the
1682
+ # existing fixturedefs from external plugins but
1683
+ # before the fixturedefs provided in conftests.
1684
+ i = len([f for f in faclist if not f.has_location])
1685
+ faclist.insert(i, fixture_def)
1686
+ if marker.autouse:
1687
+ autousenames.append(name)
1688
+
1689
+ if autousenames:
1690
+ self._nodeid_autousenames.setdefault(nodeid or "", []).extend(autousenames)
1691
+
1692
+ def getfixturedefs(
1693
+ self, argname: str, nodeid: str
1694
+ ) -> Optional[Sequence[FixtureDef[Any]]]:
1695
+ """Get a list of fixtures which are applicable to the given node id.
1696
+
1697
+ :param str argname: Name of the fixture to search for.
1698
+ :param str nodeid: Full node id of the requesting test.
1699
+ :rtype: Sequence[FixtureDef]
1700
+ """
1701
+ try:
1702
+ fixturedefs = self._arg2fixturedefs[argname]
1703
+ except KeyError:
1704
+ return None
1705
+ return tuple(self._matchfactories(fixturedefs, nodeid))
1706
+
1707
+ def _matchfactories(
1708
+ self, fixturedefs: Iterable[FixtureDef[Any]], nodeid: str
1709
+ ) -> Iterator[FixtureDef[Any]]:
1710
+ parentnodeids = set(nodes.iterparentnodeids(nodeid))
1711
+ for fixturedef in fixturedefs:
1712
+ if fixturedef.baseid in parentnodeids:
1713
+ yield fixturedef
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/freeze_support.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Provides a function to report all internal modules for using freezing
2
+ tools."""
3
+ import types
4
+ from typing import Iterator
5
+ from typing import List
6
+ from typing import Union
7
+
8
+
9
+ def freeze_includes() -> List[str]:
10
+ """Return a list of module names used by pytest that should be
11
+ included by cx_freeze."""
12
+ import _pytest
13
+
14
+ result = list(_iter_all_modules(_pytest))
15
+ return result
16
+
17
+
18
+ def _iter_all_modules(
19
+ package: Union[str, types.ModuleType],
20
+ prefix: str = "",
21
+ ) -> Iterator[str]:
22
+ """Iterate over the names of all modules that can be found in the given
23
+ package, recursively.
24
+
25
+ >>> import _pytest
26
+ >>> list(_iter_all_modules(_pytest))
27
+ ['_pytest._argcomplete', '_pytest._code.code', ...]
28
+ """
29
+ import os
30
+ import pkgutil
31
+
32
+ if isinstance(package, str):
33
+ path = package
34
+ else:
35
+ # Type ignored because typeshed doesn't define ModuleType.__path__
36
+ # (only defined on packages).
37
+ package_path = package.__path__ # type: ignore[attr-defined]
38
+ path, prefix = package_path[0], package.__name__ + "."
39
+ for _, name, is_package in pkgutil.iter_modules([path]):
40
+ if is_package:
41
+ for m in _iter_all_modules(os.path.join(path, name), prefix=name + "."):
42
+ yield prefix + m
43
+ else:
44
+ yield prefix + name
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/helpconfig.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Version info, help messages, tracing configuration."""
2
+ import os
3
+ import sys
4
+ from argparse import Action
5
+ from typing import List
6
+ from typing import Optional
7
+ from typing import Union
8
+
9
+ import pytest
10
+ from _pytest.config import Config
11
+ from _pytest.config import ExitCode
12
+ from _pytest.config import PrintHelp
13
+ from _pytest.config.argparsing import Parser
14
+ from _pytest.terminal import TerminalReporter
15
+
16
+
17
+ class HelpAction(Action):
18
+ """An argparse Action that will raise an exception in order to skip the
19
+ rest of the argument parsing when --help is passed.
20
+
21
+ This prevents argparse from quitting due to missing required arguments
22
+ when any are defined, for example by ``pytest_addoption``.
23
+ This is similar to the way that the builtin argparse --help option is
24
+ implemented by raising SystemExit.
25
+ """
26
+
27
+ def __init__(self, option_strings, dest=None, default=False, help=None):
28
+ super().__init__(
29
+ option_strings=option_strings,
30
+ dest=dest,
31
+ const=True,
32
+ default=default,
33
+ nargs=0,
34
+ help=help,
35
+ )
36
+
37
+ def __call__(self, parser, namespace, values, option_string=None):
38
+ setattr(namespace, self.dest, self.const)
39
+
40
+ # We should only skip the rest of the parsing after preparse is done.
41
+ if getattr(parser._parser, "after_preparse", False):
42
+ raise PrintHelp
43
+
44
+
45
+ def pytest_addoption(parser: Parser) -> None:
46
+ group = parser.getgroup("debugconfig")
47
+ group.addoption(
48
+ "--version",
49
+ "-V",
50
+ action="count",
51
+ default=0,
52
+ dest="version",
53
+ help="Display pytest version and information about plugins. "
54
+ "When given twice, also display information about plugins.",
55
+ )
56
+ group._addoption(
57
+ "-h",
58
+ "--help",
59
+ action=HelpAction,
60
+ dest="help",
61
+ help="Show help message and configuration info",
62
+ )
63
+ group._addoption(
64
+ "-p",
65
+ action="append",
66
+ dest="plugins",
67
+ default=[],
68
+ metavar="name",
69
+ help="Early-load given plugin module name or entry point (multi-allowed). "
70
+ "To avoid loading of plugins, use the `no:` prefix, e.g. "
71
+ "`no:doctest`.",
72
+ )
73
+ group.addoption(
74
+ "--traceconfig",
75
+ "--trace-config",
76
+ action="store_true",
77
+ default=False,
78
+ help="Trace considerations of conftest.py files",
79
+ )
80
+ group.addoption(
81
+ "--debug",
82
+ action="store",
83
+ nargs="?",
84
+ const="pytestdebug.log",
85
+ dest="debug",
86
+ metavar="DEBUG_FILE_NAME",
87
+ help="Store internal tracing debug information in this log file. "
88
+ "This file is opened with 'w' and truncated as a result, care advised. "
89
+ "Default: pytestdebug.log.",
90
+ )
91
+ group._addoption(
92
+ "-o",
93
+ "--override-ini",
94
+ dest="override_ini",
95
+ action="append",
96
+ help='Override ini option with "option=value" style, '
97
+ "e.g. `-o xfail_strict=True -o cache_dir=cache`.",
98
+ )
99
+
100
+
101
+ @pytest.hookimpl(hookwrapper=True)
102
+ def pytest_cmdline_parse():
103
+ outcome = yield
104
+ config: Config = outcome.get_result()
105
+
106
+ if config.option.debug:
107
+ # --debug | --debug <file.log> was provided.
108
+ path = config.option.debug
109
+ debugfile = open(path, "w", encoding="utf-8")
110
+ debugfile.write(
111
+ "versions pytest-%s, "
112
+ "python-%s\ncwd=%s\nargs=%s\n\n"
113
+ % (
114
+ pytest.__version__,
115
+ ".".join(map(str, sys.version_info)),
116
+ os.getcwd(),
117
+ config.invocation_params.args,
118
+ )
119
+ )
120
+ config.trace.root.setwriter(debugfile.write)
121
+ undo_tracing = config.pluginmanager.enable_tracing()
122
+ sys.stderr.write("writing pytest debug information to %s\n" % path)
123
+
124
+ def unset_tracing() -> None:
125
+ debugfile.close()
126
+ sys.stderr.write("wrote pytest debug information to %s\n" % debugfile.name)
127
+ config.trace.root.setwriter(None)
128
+ undo_tracing()
129
+
130
+ config.add_cleanup(unset_tracing)
131
+
132
+
133
+ def showversion(config: Config) -> None:
134
+ if config.option.version > 1:
135
+ sys.stdout.write(
136
+ "This is pytest version {}, imported from {}\n".format(
137
+ pytest.__version__, pytest.__file__
138
+ )
139
+ )
140
+ plugininfo = getpluginversioninfo(config)
141
+ if plugininfo:
142
+ for line in plugininfo:
143
+ sys.stdout.write(line + "\n")
144
+ else:
145
+ sys.stdout.write(f"pytest {pytest.__version__}\n")
146
+
147
+
148
+ def pytest_cmdline_main(config: Config) -> Optional[Union[int, ExitCode]]:
149
+ if config.option.version > 0:
150
+ showversion(config)
151
+ return 0
152
+ elif config.option.help:
153
+ config._do_configure()
154
+ showhelp(config)
155
+ config._ensure_unconfigure()
156
+ return 0
157
+ return None
158
+
159
+
160
+ def showhelp(config: Config) -> None:
161
+ import textwrap
162
+
163
+ reporter: Optional[TerminalReporter] = config.pluginmanager.get_plugin(
164
+ "terminalreporter"
165
+ )
166
+ assert reporter is not None
167
+ tw = reporter._tw
168
+ tw.write(config._parser.optparser.format_help())
169
+ tw.line()
170
+ tw.line(
171
+ "[pytest] ini-options in the first "
172
+ "pytest.ini|tox.ini|setup.cfg|pyproject.toml file found:"
173
+ )
174
+ tw.line()
175
+
176
+ columns = tw.fullwidth # costly call
177
+ indent_len = 24 # based on argparse's max_help_position=24
178
+ indent = " " * indent_len
179
+ for name in config._parser._ininames:
180
+ help, type, default = config._parser._inidict[name]
181
+ if type is None:
182
+ type = "string"
183
+ if help is None:
184
+ raise TypeError(f"help argument cannot be None for {name}")
185
+ spec = f"{name} ({type}):"
186
+ tw.write(" %s" % spec)
187
+ spec_len = len(spec)
188
+ if spec_len > (indent_len - 3):
189
+ # Display help starting at a new line.
190
+ tw.line()
191
+ helplines = textwrap.wrap(
192
+ help,
193
+ columns,
194
+ initial_indent=indent,
195
+ subsequent_indent=indent,
196
+ break_on_hyphens=False,
197
+ )
198
+
199
+ for line in helplines:
200
+ tw.line(line)
201
+ else:
202
+ # Display help starting after the spec, following lines indented.
203
+ tw.write(" " * (indent_len - spec_len - 2))
204
+ wrapped = textwrap.wrap(help, columns - indent_len, break_on_hyphens=False)
205
+
206
+ if wrapped:
207
+ tw.line(wrapped[0])
208
+ for line in wrapped[1:]:
209
+ tw.line(indent + line)
210
+
211
+ tw.line()
212
+ tw.line("Environment variables:")
213
+ vars = [
214
+ ("PYTEST_ADDOPTS", "Extra command line options"),
215
+ ("PYTEST_PLUGINS", "Comma-separated plugins to load during startup"),
216
+ ("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "Set to disable plugin auto-loading"),
217
+ ("PYTEST_DEBUG", "Set to enable debug tracing of pytest's internals"),
218
+ ]
219
+ for name, help in vars:
220
+ tw.line(f" {name:<24} {help}")
221
+ tw.line()
222
+ tw.line()
223
+
224
+ tw.line("to see available markers type: pytest --markers")
225
+ tw.line("to see available fixtures type: pytest --fixtures")
226
+ tw.line(
227
+ "(shown according to specified file_or_dir or current dir "
228
+ "if not specified; fixtures with leading '_' are only shown "
229
+ "with the '-v' option"
230
+ )
231
+
232
+ for warningreport in reporter.stats.get("warnings", []):
233
+ tw.line("warning : " + warningreport.message, red=True)
234
+ return
235
+
236
+
237
+ conftest_options = [("pytest_plugins", "list of plugin names to load")]
238
+
239
+
240
+ def getpluginversioninfo(config: Config) -> List[str]:
241
+ lines = []
242
+ plugininfo = config.pluginmanager.list_plugin_distinfo()
243
+ if plugininfo:
244
+ lines.append("setuptools registered plugins:")
245
+ for plugin, dist in plugininfo:
246
+ loc = getattr(plugin, "__file__", repr(plugin))
247
+ content = f"{dist.project_name}-{dist.version} at {loc}"
248
+ lines.append(" " + content)
249
+ return lines
250
+
251
+
252
+ def pytest_report_header(config: Config) -> List[str]:
253
+ lines = []
254
+ if config.option.debug or config.option.traceconfig:
255
+ lines.append(f"using: pytest-{pytest.__version__}")
256
+
257
+ verinfo = getpluginversioninfo(config)
258
+ if verinfo:
259
+ lines.extend(verinfo)
260
+
261
+ if config.option.traceconfig:
262
+ lines.append("active plugins:")
263
+ items = config.pluginmanager.list_name_plugin()
264
+ for name, plugin in items:
265
+ if hasattr(plugin, "__file__"):
266
+ r = plugin.__file__
267
+ else:
268
+ r = repr(plugin)
269
+ lines.append(f" {name:<20}: {r}")
270
+ return lines
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/hookspec.py ADDED
@@ -0,0 +1,979 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hook specifications for pytest plugins which are invoked by pytest itself
2
+ and by builtin plugins."""
3
+ from pathlib import Path
4
+ from typing import Any
5
+ from typing import Dict
6
+ from typing import List
7
+ from typing import Mapping
8
+ from typing import Optional
9
+ from typing import Sequence
10
+ from typing import Tuple
11
+ from typing import TYPE_CHECKING
12
+ from typing import Union
13
+
14
+ from pluggy import HookspecMarker
15
+
16
+ from _pytest.deprecated import WARNING_CMDLINE_PREPARSE_HOOK
17
+
18
+ if TYPE_CHECKING:
19
+ import pdb
20
+ import warnings
21
+ from typing_extensions import Literal
22
+
23
+ from _pytest._code.code import ExceptionRepr
24
+ from _pytest._code.code import ExceptionInfo
25
+ from _pytest.config import Config
26
+ from _pytest.config import ExitCode
27
+ from _pytest.config import PytestPluginManager
28
+ from _pytest.config import _PluggyPlugin
29
+ from _pytest.config.argparsing import Parser
30
+ from _pytest.fixtures import FixtureDef
31
+ from _pytest.fixtures import SubRequest
32
+ from _pytest.main import Session
33
+ from _pytest.nodes import Collector
34
+ from _pytest.nodes import Item
35
+ from _pytest.outcomes import Exit
36
+ from _pytest.python import Class
37
+ from _pytest.python import Function
38
+ from _pytest.python import Metafunc
39
+ from _pytest.python import Module
40
+ from _pytest.reports import CollectReport
41
+ from _pytest.reports import TestReport
42
+ from _pytest.runner import CallInfo
43
+ from _pytest.terminal import TerminalReporter
44
+ from _pytest.terminal import TestShortLogReport
45
+ from _pytest.compat import LEGACY_PATH
46
+
47
+
48
+ hookspec = HookspecMarker("pytest")
49
+
50
+ # -------------------------------------------------------------------------
51
+ # Initialization hooks called for every plugin
52
+ # -------------------------------------------------------------------------
53
+
54
+
55
+ @hookspec(historic=True)
56
+ def pytest_addhooks(pluginmanager: "PytestPluginManager") -> None:
57
+ """Called at plugin registration time to allow adding new hooks via a call to
58
+ ``pluginmanager.add_hookspecs(module_or_class, prefix)``.
59
+
60
+ :param pytest.PytestPluginManager pluginmanager: The pytest plugin manager.
61
+
62
+ .. note::
63
+ This hook is incompatible with ``hookwrapper=True``.
64
+ """
65
+
66
+
67
+ @hookspec(historic=True)
68
+ def pytest_plugin_registered(
69
+ plugin: "_PluggyPlugin", manager: "PytestPluginManager"
70
+ ) -> None:
71
+ """A new pytest plugin got registered.
72
+
73
+ :param plugin: The plugin module or instance.
74
+ :param pytest.PytestPluginManager manager: pytest plugin manager.
75
+
76
+ .. note::
77
+ This hook is incompatible with ``hookwrapper=True``.
78
+ """
79
+
80
+
81
+ @hookspec(historic=True)
82
+ def pytest_addoption(parser: "Parser", pluginmanager: "PytestPluginManager") -> None:
83
+ """Register argparse-style options and ini-style config values,
84
+ called once at the beginning of a test run.
85
+
86
+ .. note::
87
+
88
+ This function should be implemented only in plugins or ``conftest.py``
89
+ files situated at the tests root directory due to how pytest
90
+ :ref:`discovers plugins during startup <pluginorder>`.
91
+
92
+ :param pytest.Parser parser:
93
+ To add command line options, call
94
+ :py:func:`parser.addoption(...) <pytest.Parser.addoption>`.
95
+ To add ini-file values call :py:func:`parser.addini(...)
96
+ <pytest.Parser.addini>`.
97
+
98
+ :param pytest.PytestPluginManager pluginmanager:
99
+ The pytest plugin manager, which can be used to install :py:func:`hookspec`'s
100
+ or :py:func:`hookimpl`'s and allow one plugin to call another plugin's hooks
101
+ to change how command line options are added.
102
+
103
+ Options can later be accessed through the
104
+ :py:class:`config <pytest.Config>` object, respectively:
105
+
106
+ - :py:func:`config.getoption(name) <pytest.Config.getoption>` to
107
+ retrieve the value of a command line option.
108
+
109
+ - :py:func:`config.getini(name) <pytest.Config.getini>` to retrieve
110
+ a value read from an ini-style file.
111
+
112
+ The config object is passed around on many internal objects via the ``.config``
113
+ attribute or can be retrieved as the ``pytestconfig`` fixture.
114
+
115
+ .. note::
116
+ This hook is incompatible with ``hookwrapper=True``.
117
+ """
118
+
119
+
120
+ @hookspec(historic=True)
121
+ def pytest_configure(config: "Config") -> None:
122
+ """Allow plugins and conftest files to perform initial configuration.
123
+
124
+ This hook is called for every plugin and initial conftest file
125
+ after command line options have been parsed.
126
+
127
+ After that, the hook is called for other conftest files as they are
128
+ imported.
129
+
130
+ .. note::
131
+ This hook is incompatible with ``hookwrapper=True``.
132
+
133
+ :param pytest.Config config: The pytest config object.
134
+ """
135
+
136
+
137
+ # -------------------------------------------------------------------------
138
+ # Bootstrapping hooks called for plugins registered early enough:
139
+ # internal and 3rd party plugins.
140
+ # -------------------------------------------------------------------------
141
+
142
+
143
+ @hookspec(firstresult=True)
144
+ def pytest_cmdline_parse(
145
+ pluginmanager: "PytestPluginManager", args: List[str]
146
+ ) -> Optional["Config"]:
147
+ """Return an initialized :class:`~pytest.Config`, parsing the specified args.
148
+
149
+ Stops at first non-None result, see :ref:`firstresult`.
150
+
151
+ .. note::
152
+ This hook will only be called for plugin classes passed to the
153
+ ``plugins`` arg when using `pytest.main`_ to perform an in-process
154
+ test run.
155
+
156
+ :param pluginmanager: The pytest plugin manager.
157
+ :param args: List of arguments passed on the command line.
158
+ :returns: A pytest config object.
159
+ """
160
+
161
+
162
+ @hookspec(warn_on_impl=WARNING_CMDLINE_PREPARSE_HOOK)
163
+ def pytest_cmdline_preparse(config: "Config", args: List[str]) -> None:
164
+ """(**Deprecated**) modify command line arguments before option parsing.
165
+
166
+ This hook is considered deprecated and will be removed in a future pytest version. Consider
167
+ using :hook:`pytest_load_initial_conftests` instead.
168
+
169
+ .. note::
170
+ This hook will not be called for ``conftest.py`` files, only for setuptools plugins.
171
+
172
+ :param config: The pytest config object.
173
+ :param args: Arguments passed on the command line.
174
+ """
175
+
176
+
177
+ @hookspec(firstresult=True)
178
+ def pytest_cmdline_main(config: "Config") -> Optional[Union["ExitCode", int]]:
179
+ """Called for performing the main command line action. The default
180
+ implementation will invoke the configure hooks and runtest_mainloop.
181
+
182
+ Stops at first non-None result, see :ref:`firstresult`.
183
+
184
+ :param config: The pytest config object.
185
+ :returns: The exit code.
186
+ """
187
+
188
+
189
+ def pytest_load_initial_conftests(
190
+ early_config: "Config", parser: "Parser", args: List[str]
191
+ ) -> None:
192
+ """Called to implement the loading of initial conftest files ahead
193
+ of command line option parsing.
194
+
195
+ .. note::
196
+ This hook will not be called for ``conftest.py`` files, only for setuptools plugins.
197
+
198
+ :param early_config: The pytest config object.
199
+ :param args: Arguments passed on the command line.
200
+ :param parser: To add command line options.
201
+ """
202
+
203
+
204
+ # -------------------------------------------------------------------------
205
+ # collection hooks
206
+ # -------------------------------------------------------------------------
207
+
208
+
209
+ @hookspec(firstresult=True)
210
+ def pytest_collection(session: "Session") -> Optional[object]:
211
+ """Perform the collection phase for the given session.
212
+
213
+ Stops at first non-None result, see :ref:`firstresult`.
214
+ The return value is not used, but only stops further processing.
215
+
216
+ The default collection phase is this (see individual hooks for full details):
217
+
218
+ 1. Starting from ``session`` as the initial collector:
219
+
220
+ 1. ``pytest_collectstart(collector)``
221
+ 2. ``report = pytest_make_collect_report(collector)``
222
+ 3. ``pytest_exception_interact(collector, call, report)`` if an interactive exception occurred
223
+ 4. For each collected node:
224
+
225
+ 1. If an item, ``pytest_itemcollected(item)``
226
+ 2. If a collector, recurse into it.
227
+
228
+ 5. ``pytest_collectreport(report)``
229
+
230
+ 2. ``pytest_collection_modifyitems(session, config, items)``
231
+
232
+ 1. ``pytest_deselected(items)`` for any deselected items (may be called multiple times)
233
+
234
+ 3. ``pytest_collection_finish(session)``
235
+ 4. Set ``session.items`` to the list of collected items
236
+ 5. Set ``session.testscollected`` to the number of collected items
237
+
238
+ You can implement this hook to only perform some action before collection,
239
+ for example the terminal plugin uses it to start displaying the collection
240
+ counter (and returns `None`).
241
+
242
+ :param session: The pytest session object.
243
+ """
244
+
245
+
246
+ def pytest_collection_modifyitems(
247
+ session: "Session", config: "Config", items: List["Item"]
248
+ ) -> None:
249
+ """Called after collection has been performed. May filter or re-order
250
+ the items in-place.
251
+
252
+ :param session: The pytest session object.
253
+ :param config: The pytest config object.
254
+ :param items: List of item objects.
255
+ """
256
+
257
+
258
+ def pytest_collection_finish(session: "Session") -> None:
259
+ """Called after collection has been performed and modified.
260
+
261
+ :param session: The pytest session object.
262
+ """
263
+
264
+
265
+ @hookspec(firstresult=True)
266
+ def pytest_ignore_collect(
267
+ collection_path: Path, path: "LEGACY_PATH", config: "Config"
268
+ ) -> Optional[bool]:
269
+ """Return True to prevent considering this path for collection.
270
+
271
+ This hook is consulted for all files and directories prior to calling
272
+ more specific hooks.
273
+
274
+ Stops at first non-None result, see :ref:`firstresult`.
275
+
276
+ :param collection_path: The path to analyze.
277
+ :param path: The path to analyze (deprecated).
278
+ :param config: The pytest config object.
279
+
280
+ .. versionchanged:: 7.0.0
281
+ The ``collection_path`` parameter was added as a :class:`pathlib.Path`
282
+ equivalent of the ``path`` parameter. The ``path`` parameter
283
+ has been deprecated.
284
+ """
285
+
286
+
287
+ def pytest_collect_file(
288
+ file_path: Path, path: "LEGACY_PATH", parent: "Collector"
289
+ ) -> "Optional[Collector]":
290
+ """Create a :class:`~pytest.Collector` for the given path, or None if not relevant.
291
+
292
+ The new node needs to have the specified ``parent`` as a parent.
293
+
294
+ :param file_path: The path to analyze.
295
+ :param path: The path to collect (deprecated).
296
+
297
+ .. versionchanged:: 7.0.0
298
+ The ``file_path`` parameter was added as a :class:`pathlib.Path`
299
+ equivalent of the ``path`` parameter. The ``path`` parameter
300
+ has been deprecated.
301
+ """
302
+
303
+
304
+ # logging hooks for collection
305
+
306
+
307
+ def pytest_collectstart(collector: "Collector") -> None:
308
+ """Collector starts collecting.
309
+
310
+ :param collector:
311
+ The collector.
312
+ """
313
+
314
+
315
+ def pytest_itemcollected(item: "Item") -> None:
316
+ """We just collected a test item.
317
+
318
+ :param item:
319
+ The item.
320
+ """
321
+
322
+
323
+ def pytest_collectreport(report: "CollectReport") -> None:
324
+ """Collector finished collecting.
325
+
326
+ :param report:
327
+ The collect report.
328
+ """
329
+
330
+
331
+ def pytest_deselected(items: Sequence["Item"]) -> None:
332
+ """Called for deselected test items, e.g. by keyword.
333
+
334
+ May be called multiple times.
335
+
336
+ :param items:
337
+ The items.
338
+ """
339
+
340
+
341
+ @hookspec(firstresult=True)
342
+ def pytest_make_collect_report(collector: "Collector") -> "Optional[CollectReport]":
343
+ """Perform :func:`collector.collect() <pytest.Collector.collect>` and return
344
+ a :class:`~pytest.CollectReport`.
345
+
346
+ Stops at first non-None result, see :ref:`firstresult`.
347
+
348
+ :param collector:
349
+ The collector.
350
+ """
351
+
352
+
353
+ # -------------------------------------------------------------------------
354
+ # Python test function related hooks
355
+ # -------------------------------------------------------------------------
356
+
357
+
358
+ @hookspec(firstresult=True)
359
+ def pytest_pycollect_makemodule(
360
+ module_path: Path, path: "LEGACY_PATH", parent
361
+ ) -> Optional["Module"]:
362
+ """Return a :class:`pytest.Module` collector or None for the given path.
363
+
364
+ This hook will be called for each matching test module path.
365
+ The :hook:`pytest_collect_file` hook needs to be used if you want to
366
+ create test modules for files that do not match as a test module.
367
+
368
+ Stops at first non-None result, see :ref:`firstresult`.
369
+
370
+ :param module_path: The path of the module to collect.
371
+ :param path: The path of the module to collect (deprecated).
372
+
373
+ .. versionchanged:: 7.0.0
374
+ The ``module_path`` parameter was added as a :class:`pathlib.Path`
375
+ equivalent of the ``path`` parameter.
376
+
377
+ The ``path`` parameter has been deprecated in favor of ``fspath``.
378
+ """
379
+
380
+
381
+ @hookspec(firstresult=True)
382
+ def pytest_pycollect_makeitem(
383
+ collector: Union["Module", "Class"], name: str, obj: object
384
+ ) -> Union[None, "Item", "Collector", List[Union["Item", "Collector"]]]:
385
+ """Return a custom item/collector for a Python object in a module, or None.
386
+
387
+ Stops at first non-None result, see :ref:`firstresult`.
388
+
389
+ :param collector:
390
+ The module/class collector.
391
+ :param name:
392
+ The name of the object in the module/class.
393
+ :param obj:
394
+ The object.
395
+ :returns:
396
+ The created items/collectors.
397
+ """
398
+
399
+
400
+ @hookspec(firstresult=True)
401
+ def pytest_pyfunc_call(pyfuncitem: "Function") -> Optional[object]:
402
+ """Call underlying test function.
403
+
404
+ Stops at first non-None result, see :ref:`firstresult`.
405
+
406
+ :param pyfuncitem:
407
+ The function item.
408
+ """
409
+
410
+
411
+ def pytest_generate_tests(metafunc: "Metafunc") -> None:
412
+ """Generate (multiple) parametrized calls to a test function.
413
+
414
+ :param metafunc:
415
+ The :class:`~pytest.Metafunc` helper for the test function.
416
+ """
417
+
418
+
419
+ @hookspec(firstresult=True)
420
+ def pytest_make_parametrize_id(
421
+ config: "Config", val: object, argname: str
422
+ ) -> Optional[str]:
423
+ """Return a user-friendly string representation of the given ``val``
424
+ that will be used by @pytest.mark.parametrize calls, or None if the hook
425
+ doesn't know about ``val``.
426
+
427
+ The parameter name is available as ``argname``, if required.
428
+
429
+ Stops at first non-None result, see :ref:`firstresult`.
430
+
431
+ :param config: The pytest config object.
432
+ :param val: The parametrized value.
433
+ :param str argname: The automatic parameter name produced by pytest.
434
+ """
435
+
436
+
437
+ # -------------------------------------------------------------------------
438
+ # runtest related hooks
439
+ # -------------------------------------------------------------------------
440
+
441
+
442
+ @hookspec(firstresult=True)
443
+ def pytest_runtestloop(session: "Session") -> Optional[object]:
444
+ """Perform the main runtest loop (after collection finished).
445
+
446
+ The default hook implementation performs the runtest protocol for all items
447
+ collected in the session (``session.items``), unless the collection failed
448
+ or the ``collectonly`` pytest option is set.
449
+
450
+ If at any point :py:func:`pytest.exit` is called, the loop is
451
+ terminated immediately.
452
+
453
+ If at any point ``session.shouldfail`` or ``session.shouldstop`` are set, the
454
+ loop is terminated after the runtest protocol for the current item is finished.
455
+
456
+ :param session: The pytest session object.
457
+
458
+ Stops at first non-None result, see :ref:`firstresult`.
459
+ The return value is not used, but only stops further processing.
460
+ """
461
+
462
+
463
+ @hookspec(firstresult=True)
464
+ def pytest_runtest_protocol(
465
+ item: "Item", nextitem: "Optional[Item]"
466
+ ) -> Optional[object]:
467
+ """Perform the runtest protocol for a single test item.
468
+
469
+ The default runtest protocol is this (see individual hooks for full details):
470
+
471
+ - ``pytest_runtest_logstart(nodeid, location)``
472
+
473
+ - Setup phase:
474
+ - ``call = pytest_runtest_setup(item)`` (wrapped in ``CallInfo(when="setup")``)
475
+ - ``report = pytest_runtest_makereport(item, call)``
476
+ - ``pytest_runtest_logreport(report)``
477
+ - ``pytest_exception_interact(call, report)`` if an interactive exception occurred
478
+
479
+ - Call phase, if the the setup passed and the ``setuponly`` pytest option is not set:
480
+ - ``call = pytest_runtest_call(item)`` (wrapped in ``CallInfo(when="call")``)
481
+ - ``report = pytest_runtest_makereport(item, call)``
482
+ - ``pytest_runtest_logreport(report)``
483
+ - ``pytest_exception_interact(call, report)`` if an interactive exception occurred
484
+
485
+ - Teardown phase:
486
+ - ``call = pytest_runtest_teardown(item, nextitem)`` (wrapped in ``CallInfo(when="teardown")``)
487
+ - ``report = pytest_runtest_makereport(item, call)``
488
+ - ``pytest_runtest_logreport(report)``
489
+ - ``pytest_exception_interact(call, report)`` if an interactive exception occurred
490
+
491
+ - ``pytest_runtest_logfinish(nodeid, location)``
492
+
493
+ :param item: Test item for which the runtest protocol is performed.
494
+ :param nextitem: The scheduled-to-be-next test item (or None if this is the end my friend).
495
+
496
+ Stops at first non-None result, see :ref:`firstresult`.
497
+ The return value is not used, but only stops further processing.
498
+ """
499
+
500
+
501
+ def pytest_runtest_logstart(
502
+ nodeid: str, location: Tuple[str, Optional[int], str]
503
+ ) -> None:
504
+ """Called at the start of running the runtest protocol for a single item.
505
+
506
+ See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.
507
+
508
+ :param nodeid: Full node ID of the item.
509
+ :param location: A tuple of ``(filename, lineno, testname)``
510
+ where ``filename`` is a file path relative to ``config.rootpath``
511
+ and ``lineno`` is 0-based.
512
+ """
513
+
514
+
515
+ def pytest_runtest_logfinish(
516
+ nodeid: str, location: Tuple[str, Optional[int], str]
517
+ ) -> None:
518
+ """Called at the end of running the runtest protocol for a single item.
519
+
520
+ See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.
521
+
522
+ :param nodeid: Full node ID of the item.
523
+ :param location: A tuple of ``(filename, lineno, testname)``
524
+ where ``filename`` is a file path relative to ``config.rootpath``
525
+ and ``lineno`` is 0-based.
526
+ """
527
+
528
+
529
+ def pytest_runtest_setup(item: "Item") -> None:
530
+ """Called to perform the setup phase for a test item.
531
+
532
+ The default implementation runs ``setup()`` on ``item`` and all of its
533
+ parents (which haven't been setup yet). This includes obtaining the
534
+ values of fixtures required by the item (which haven't been obtained
535
+ yet).
536
+
537
+ :param item:
538
+ The item.
539
+ """
540
+
541
+
542
+ def pytest_runtest_call(item: "Item") -> None:
543
+ """Called to run the test for test item (the call phase).
544
+
545
+ The default implementation calls ``item.runtest()``.
546
+
547
+ :param item:
548
+ The item.
549
+ """
550
+
551
+
552
+ def pytest_runtest_teardown(item: "Item", nextitem: Optional["Item"]) -> None:
553
+ """Called to perform the teardown phase for a test item.
554
+
555
+ The default implementation runs the finalizers and calls ``teardown()``
556
+ on ``item`` and all of its parents (which need to be torn down). This
557
+ includes running the teardown phase of fixtures required by the item (if
558
+ they go out of scope).
559
+
560
+ :param item:
561
+ The item.
562
+ :param nextitem:
563
+ The scheduled-to-be-next test item (None if no further test item is
564
+ scheduled). This argument is used to perform exact teardowns, i.e.
565
+ calling just enough finalizers so that nextitem only needs to call
566
+ setup functions.
567
+ """
568
+
569
+
570
+ @hookspec(firstresult=True)
571
+ def pytest_runtest_makereport(
572
+ item: "Item", call: "CallInfo[None]"
573
+ ) -> Optional["TestReport"]:
574
+ """Called to create a :class:`~pytest.TestReport` for each of
575
+ the setup, call and teardown runtest phases of a test item.
576
+
577
+ See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.
578
+
579
+ :param item: The item.
580
+ :param call: The :class:`~pytest.CallInfo` for the phase.
581
+
582
+ Stops at first non-None result, see :ref:`firstresult`.
583
+ """
584
+
585
+
586
+ def pytest_runtest_logreport(report: "TestReport") -> None:
587
+ """Process the :class:`~pytest.TestReport` produced for each
588
+ of the setup, call and teardown runtest phases of an item.
589
+
590
+ See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.
591
+ """
592
+
593
+
594
+ @hookspec(firstresult=True)
595
+ def pytest_report_to_serializable(
596
+ config: "Config",
597
+ report: Union["CollectReport", "TestReport"],
598
+ ) -> Optional[Dict[str, Any]]:
599
+ """Serialize the given report object into a data structure suitable for
600
+ sending over the wire, e.g. converted to JSON.
601
+
602
+ :param config: The pytest config object.
603
+ :param report: The report.
604
+ """
605
+
606
+
607
+ @hookspec(firstresult=True)
608
+ def pytest_report_from_serializable(
609
+ config: "Config",
610
+ data: Dict[str, Any],
611
+ ) -> Optional[Union["CollectReport", "TestReport"]]:
612
+ """Restore a report object previously serialized with
613
+ :hook:`pytest_report_to_serializable`.
614
+
615
+ :param config: The pytest config object.
616
+ """
617
+
618
+
619
+ # -------------------------------------------------------------------------
620
+ # Fixture related hooks
621
+ # -------------------------------------------------------------------------
622
+
623
+
624
+ @hookspec(firstresult=True)
625
+ def pytest_fixture_setup(
626
+ fixturedef: "FixtureDef[Any]", request: "SubRequest"
627
+ ) -> Optional[object]:
628
+ """Perform fixture setup execution.
629
+
630
+ :param fixturdef:
631
+ The fixture definition object.
632
+ :param request:
633
+ The fixture request object.
634
+ :returns:
635
+ The return value of the call to the fixture function.
636
+
637
+ Stops at first non-None result, see :ref:`firstresult`.
638
+
639
+ .. note::
640
+ If the fixture function returns None, other implementations of
641
+ this hook function will continue to be called, according to the
642
+ behavior of the :ref:`firstresult` option.
643
+ """
644
+
645
+
646
+ def pytest_fixture_post_finalizer(
647
+ fixturedef: "FixtureDef[Any]", request: "SubRequest"
648
+ ) -> None:
649
+ """Called after fixture teardown, but before the cache is cleared, so
650
+ the fixture result ``fixturedef.cached_result`` is still available (not
651
+ ``None``).
652
+
653
+ :param fixturdef:
654
+ The fixture definition object.
655
+ :param request:
656
+ The fixture request object.
657
+ """
658
+
659
+
660
+ # -------------------------------------------------------------------------
661
+ # test session related hooks
662
+ # -------------------------------------------------------------------------
663
+
664
+
665
+ def pytest_sessionstart(session: "Session") -> None:
666
+ """Called after the ``Session`` object has been created and before performing collection
667
+ and entering the run test loop.
668
+
669
+ :param session: The pytest session object.
670
+ """
671
+
672
+
673
+ def pytest_sessionfinish(
674
+ session: "Session",
675
+ exitstatus: Union[int, "ExitCode"],
676
+ ) -> None:
677
+ """Called after whole test run finished, right before returning the exit status to the system.
678
+
679
+ :param session: The pytest session object.
680
+ :param exitstatus: The status which pytest will return to the system.
681
+ """
682
+
683
+
684
+ def pytest_unconfigure(config: "Config") -> None:
685
+ """Called before test process is exited.
686
+
687
+ :param config: The pytest config object.
688
+ """
689
+
690
+
691
+ # -------------------------------------------------------------------------
692
+ # hooks for customizing the assert methods
693
+ # -------------------------------------------------------------------------
694
+
695
+
696
+ def pytest_assertrepr_compare(
697
+ config: "Config", op: str, left: object, right: object
698
+ ) -> Optional[List[str]]:
699
+ """Return explanation for comparisons in failing assert expressions.
700
+
701
+ Return None for no custom explanation, otherwise return a list
702
+ of strings. The strings will be joined by newlines but any newlines
703
+ *in* a string will be escaped. Note that all but the first line will
704
+ be indented slightly, the intention is for the first line to be a summary.
705
+
706
+ :param config: The pytest config object.
707
+ :param op: The operator, e.g. `"=="`, `"!="`, `"not in"`.
708
+ :param left: The left operand.
709
+ :param right: The right operand.
710
+ """
711
+
712
+
713
+ def pytest_assertion_pass(item: "Item", lineno: int, orig: str, expl: str) -> None:
714
+ """Called whenever an assertion passes.
715
+
716
+ .. versionadded:: 5.0
717
+
718
+ Use this hook to do some processing after a passing assertion.
719
+ The original assertion information is available in the `orig` string
720
+ and the pytest introspected assertion information is available in the
721
+ `expl` string.
722
+
723
+ This hook must be explicitly enabled by the ``enable_assertion_pass_hook``
724
+ ini-file option:
725
+
726
+ .. code-block:: ini
727
+
728
+ [pytest]
729
+ enable_assertion_pass_hook=true
730
+
731
+ You need to **clean the .pyc** files in your project directory and interpreter libraries
732
+ when enabling this option, as assertions will require to be re-written.
733
+
734
+ :param item: pytest item object of current test.
735
+ :param lineno: Line number of the assert statement.
736
+ :param orig: String with the original assertion.
737
+ :param expl: String with the assert explanation.
738
+ """
739
+
740
+
741
+ # -------------------------------------------------------------------------
742
+ # Hooks for influencing reporting (invoked from _pytest_terminal).
743
+ # -------------------------------------------------------------------------
744
+
745
+
746
+ def pytest_report_header( # type:ignore[empty-body]
747
+ config: "Config", start_path: Path, startdir: "LEGACY_PATH"
748
+ ) -> Union[str, List[str]]:
749
+ """Return a string or list of strings to be displayed as header info for terminal reporting.
750
+
751
+ :param config: The pytest config object.
752
+ :param start_path: The starting dir.
753
+ :param startdir: The starting dir (deprecated).
754
+
755
+ .. note::
756
+
757
+ Lines returned by a plugin are displayed before those of plugins which
758
+ ran before it.
759
+ If you want to have your line(s) displayed first, use
760
+ :ref:`trylast=True <plugin-hookorder>`.
761
+
762
+ .. note::
763
+
764
+ This function should be implemented only in plugins or ``conftest.py``
765
+ files situated at the tests root directory due to how pytest
766
+ :ref:`discovers plugins during startup <pluginorder>`.
767
+
768
+ .. versionchanged:: 7.0.0
769
+ The ``start_path`` parameter was added as a :class:`pathlib.Path`
770
+ equivalent of the ``startdir`` parameter. The ``startdir`` parameter
771
+ has been deprecated.
772
+ """
773
+
774
+
775
+ def pytest_report_collectionfinish( # type:ignore[empty-body]
776
+ config: "Config",
777
+ start_path: Path,
778
+ startdir: "LEGACY_PATH",
779
+ items: Sequence["Item"],
780
+ ) -> Union[str, List[str]]:
781
+ """Return a string or list of strings to be displayed after collection
782
+ has finished successfully.
783
+
784
+ These strings will be displayed after the standard "collected X items" message.
785
+
786
+ .. versionadded:: 3.2
787
+
788
+ :param config: The pytest config object.
789
+ :param start_path: The starting dir.
790
+ :param startdir: The starting dir (deprecated).
791
+ :param items: List of pytest items that are going to be executed; this list should not be modified.
792
+
793
+ .. note::
794
+
795
+ Lines returned by a plugin are displayed before those of plugins which
796
+ ran before it.
797
+ If you want to have your line(s) displayed first, use
798
+ :ref:`trylast=True <plugin-hookorder>`.
799
+
800
+ .. versionchanged:: 7.0.0
801
+ The ``start_path`` parameter was added as a :class:`pathlib.Path`
802
+ equivalent of the ``startdir`` parameter. The ``startdir`` parameter
803
+ has been deprecated.
804
+ """
805
+
806
+
807
+ @hookspec(firstresult=True)
808
+ def pytest_report_teststatus( # type:ignore[empty-body]
809
+ report: Union["CollectReport", "TestReport"], config: "Config"
810
+ ) -> "TestShortLogReport | Tuple[str, str, Union[str, Tuple[str, Mapping[str, bool]]]]":
811
+ """Return result-category, shortletter and verbose word for status
812
+ reporting.
813
+
814
+ The result-category is a category in which to count the result, for
815
+ example "passed", "skipped", "error" or the empty string.
816
+
817
+ The shortletter is shown as testing progresses, for example ".", "s",
818
+ "E" or the empty string.
819
+
820
+ The verbose word is shown as testing progresses in verbose mode, for
821
+ example "PASSED", "SKIPPED", "ERROR" or the empty string.
822
+
823
+ pytest may style these implicitly according to the report outcome.
824
+ To provide explicit styling, return a tuple for the verbose word,
825
+ for example ``"rerun", "R", ("RERUN", {"yellow": True})``.
826
+
827
+ :param report: The report object whose status is to be returned.
828
+ :param config: The pytest config object.
829
+ :returns: The test status.
830
+
831
+ Stops at first non-None result, see :ref:`firstresult`.
832
+ """
833
+
834
+
835
+ def pytest_terminal_summary(
836
+ terminalreporter: "TerminalReporter",
837
+ exitstatus: "ExitCode",
838
+ config: "Config",
839
+ ) -> None:
840
+ """Add a section to terminal summary reporting.
841
+
842
+ :param terminalreporter: The internal terminal reporter object.
843
+ :param exitstatus: The exit status that will be reported back to the OS.
844
+ :param config: The pytest config object.
845
+
846
+ .. versionadded:: 4.2
847
+ The ``config`` parameter.
848
+ """
849
+
850
+
851
+ @hookspec(historic=True)
852
+ def pytest_warning_recorded(
853
+ warning_message: "warnings.WarningMessage",
854
+ when: "Literal['config', 'collect', 'runtest']",
855
+ nodeid: str,
856
+ location: Optional[Tuple[str, int, str]],
857
+ ) -> None:
858
+ """Process a warning captured by the internal pytest warnings plugin.
859
+
860
+ :param warning_message:
861
+ The captured warning. This is the same object produced by :py:func:`warnings.catch_warnings`, and contains
862
+ the same attributes as the parameters of :py:func:`warnings.showwarning`.
863
+
864
+ :param when:
865
+ Indicates when the warning was captured. Possible values:
866
+
867
+ * ``"config"``: during pytest configuration/initialization stage.
868
+ * ``"collect"``: during test collection.
869
+ * ``"runtest"``: during test execution.
870
+
871
+ :param nodeid:
872
+ Full id of the item.
873
+
874
+ :param location:
875
+ When available, holds information about the execution context of the captured
876
+ warning (filename, linenumber, function). ``function`` evaluates to <module>
877
+ when the execution context is at the module level.
878
+
879
+ .. versionadded:: 6.0
880
+ """
881
+
882
+
883
+ # -------------------------------------------------------------------------
884
+ # Hooks for influencing skipping
885
+ # -------------------------------------------------------------------------
886
+
887
+
888
+ def pytest_markeval_namespace( # type:ignore[empty-body]
889
+ config: "Config",
890
+ ) -> Dict[str, Any]:
891
+ """Called when constructing the globals dictionary used for
892
+ evaluating string conditions in xfail/skipif markers.
893
+
894
+ This is useful when the condition for a marker requires
895
+ objects that are expensive or impossible to obtain during
896
+ collection time, which is required by normal boolean
897
+ conditions.
898
+
899
+ .. versionadded:: 6.2
900
+
901
+ :param config: The pytest config object.
902
+ :returns: A dictionary of additional globals to add.
903
+ """
904
+
905
+
906
+ # -------------------------------------------------------------------------
907
+ # error handling and internal debugging hooks
908
+ # -------------------------------------------------------------------------
909
+
910
+
911
+ def pytest_internalerror(
912
+ excrepr: "ExceptionRepr",
913
+ excinfo: "ExceptionInfo[BaseException]",
914
+ ) -> Optional[bool]:
915
+ """Called for internal errors.
916
+
917
+ Return True to suppress the fallback handling of printing an
918
+ INTERNALERROR message directly to sys.stderr.
919
+
920
+ :param excrepr: The exception repr object.
921
+ :param excinfo: The exception info.
922
+ """
923
+
924
+
925
+ def pytest_keyboard_interrupt(
926
+ excinfo: "ExceptionInfo[Union[KeyboardInterrupt, Exit]]",
927
+ ) -> None:
928
+ """Called for keyboard interrupt.
929
+
930
+ :param excinfo: The exception info.
931
+ """
932
+
933
+
934
+ def pytest_exception_interact(
935
+ node: Union["Item", "Collector"],
936
+ call: "CallInfo[Any]",
937
+ report: Union["CollectReport", "TestReport"],
938
+ ) -> None:
939
+ """Called when an exception was raised which can potentially be
940
+ interactively handled.
941
+
942
+ May be called during collection (see :hook:`pytest_make_collect_report`),
943
+ in which case ``report`` is a :class:`CollectReport`.
944
+
945
+ May be called during runtest of an item (see :hook:`pytest_runtest_protocol`),
946
+ in which case ``report`` is a :class:`TestReport`.
947
+
948
+ This hook is not called if the exception that was raised is an internal
949
+ exception like ``skip.Exception``.
950
+
951
+ :param node:
952
+ The item or collector.
953
+ :param call:
954
+ The call information. Contains the exception.
955
+ :param report:
956
+ The collection or test report.
957
+ """
958
+
959
+
960
+ def pytest_enter_pdb(config: "Config", pdb: "pdb.Pdb") -> None:
961
+ """Called upon pdb.set_trace().
962
+
963
+ Can be used by plugins to take special action just before the python
964
+ debugger enters interactive mode.
965
+
966
+ :param config: The pytest config object.
967
+ :param pdb: The Pdb instance.
968
+ """
969
+
970
+
971
+ def pytest_leave_pdb(config: "Config", pdb: "pdb.Pdb") -> None:
972
+ """Called when leaving pdb (e.g. with continue after pdb.set_trace()).
973
+
974
+ Can be used by plugins to take special action just after the python
975
+ debugger leaves interactive mode.
976
+
977
+ :param config: The pytest config object.
978
+ :param pdb: The Pdb instance.
979
+ """
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/junitxml.py ADDED
@@ -0,0 +1,700 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Report test results in JUnit-XML format, for use with Jenkins and build
2
+ integration servers.
3
+
4
+ Based on initial code from Ross Lawley.
5
+
6
+ Output conforms to
7
+ https://github.com/jenkinsci/xunit-plugin/blob/master/src/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd
8
+ """
9
+ import functools
10
+ import os
11
+ import platform
12
+ import re
13
+ import xml.etree.ElementTree as ET
14
+ from datetime import datetime
15
+ from typing import Callable
16
+ from typing import Dict
17
+ from typing import List
18
+ from typing import Match
19
+ from typing import Optional
20
+ from typing import Tuple
21
+ from typing import Union
22
+
23
+ import pytest
24
+ from _pytest import nodes
25
+ from _pytest import timing
26
+ from _pytest._code.code import ExceptionRepr
27
+ from _pytest._code.code import ReprFileLocation
28
+ from _pytest.config import Config
29
+ from _pytest.config import filename_arg
30
+ from _pytest.config.argparsing import Parser
31
+ from _pytest.fixtures import FixtureRequest
32
+ from _pytest.reports import TestReport
33
+ from _pytest.stash import StashKey
34
+ from _pytest.terminal import TerminalReporter
35
+
36
+
37
+ xml_key = StashKey["LogXML"]()
38
+
39
+
40
+ def bin_xml_escape(arg: object) -> str:
41
+ r"""Visually escape invalid XML characters.
42
+
43
+ For example, transforms
44
+ 'hello\aworld\b'
45
+ into
46
+ 'hello#x07world#x08'
47
+ Note that the #xABs are *not* XML escapes - missing the ampersand &#xAB.
48
+ The idea is to escape visually for the user rather than for XML itself.
49
+ """
50
+
51
+ def repl(matchobj: Match[str]) -> str:
52
+ i = ord(matchobj.group())
53
+ if i <= 0xFF:
54
+ return "#x%02X" % i
55
+ else:
56
+ return "#x%04X" % i
57
+
58
+ # The spec range of valid chars is:
59
+ # Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
60
+ # For an unknown(?) reason, we disallow #x7F (DEL) as well.
61
+ illegal_xml_re = (
62
+ "[^\u0009\u000A\u000D\u0020-\u007E\u0080-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]"
63
+ )
64
+ return re.sub(illegal_xml_re, repl, str(arg))
65
+
66
+
67
+ def merge_family(left, right) -> None:
68
+ result = {}
69
+ for kl, vl in left.items():
70
+ for kr, vr in right.items():
71
+ if not isinstance(vl, list):
72
+ raise TypeError(type(vl))
73
+ result[kl] = vl + vr
74
+ left.update(result)
75
+
76
+
77
+ families = {}
78
+ families["_base"] = {"testcase": ["classname", "name"]}
79
+ families["_base_legacy"] = {"testcase": ["file", "line", "url"]}
80
+
81
+ # xUnit 1.x inherits legacy attributes.
82
+ families["xunit1"] = families["_base"].copy()
83
+ merge_family(families["xunit1"], families["_base_legacy"])
84
+
85
+ # xUnit 2.x uses strict base attributes.
86
+ families["xunit2"] = families["_base"]
87
+
88
+
89
+ class _NodeReporter:
90
+ def __init__(self, nodeid: Union[str, TestReport], xml: "LogXML") -> None:
91
+ self.id = nodeid
92
+ self.xml = xml
93
+ self.add_stats = self.xml.add_stats
94
+ self.family = self.xml.family
95
+ self.duration = 0.0
96
+ self.properties: List[Tuple[str, str]] = []
97
+ self.nodes: List[ET.Element] = []
98
+ self.attrs: Dict[str, str] = {}
99
+
100
+ def append(self, node: ET.Element) -> None:
101
+ self.xml.add_stats(node.tag)
102
+ self.nodes.append(node)
103
+
104
+ def add_property(self, name: str, value: object) -> None:
105
+ self.properties.append((str(name), bin_xml_escape(value)))
106
+
107
+ def add_attribute(self, name: str, value: object) -> None:
108
+ self.attrs[str(name)] = bin_xml_escape(value)
109
+
110
+ def make_properties_node(self) -> Optional[ET.Element]:
111
+ """Return a Junit node containing custom properties, if any."""
112
+ if self.properties:
113
+ properties = ET.Element("properties")
114
+ for name, value in self.properties:
115
+ properties.append(ET.Element("property", name=name, value=value))
116
+ return properties
117
+ return None
118
+
119
+ def record_testreport(self, testreport: TestReport) -> None:
120
+ names = mangle_test_address(testreport.nodeid)
121
+ existing_attrs = self.attrs
122
+ classnames = names[:-1]
123
+ if self.xml.prefix:
124
+ classnames.insert(0, self.xml.prefix)
125
+ attrs: Dict[str, str] = {
126
+ "classname": ".".join(classnames),
127
+ "name": bin_xml_escape(names[-1]),
128
+ "file": testreport.location[0],
129
+ }
130
+ if testreport.location[1] is not None:
131
+ attrs["line"] = str(testreport.location[1])
132
+ if hasattr(testreport, "url"):
133
+ attrs["url"] = testreport.url
134
+ self.attrs = attrs
135
+ self.attrs.update(existing_attrs) # Restore any user-defined attributes.
136
+
137
+ # Preserve legacy testcase behavior.
138
+ if self.family == "xunit1":
139
+ return
140
+
141
+ # Filter out attributes not permitted by this test family.
142
+ # Including custom attributes because they are not valid here.
143
+ temp_attrs = {}
144
+ for key in self.attrs.keys():
145
+ if key in families[self.family]["testcase"]:
146
+ temp_attrs[key] = self.attrs[key]
147
+ self.attrs = temp_attrs
148
+
149
+ def to_xml(self) -> ET.Element:
150
+ testcase = ET.Element("testcase", self.attrs, time="%.3f" % self.duration)
151
+ properties = self.make_properties_node()
152
+ if properties is not None:
153
+ testcase.append(properties)
154
+ testcase.extend(self.nodes)
155
+ return testcase
156
+
157
+ def _add_simple(self, tag: str, message: str, data: Optional[str] = None) -> None:
158
+ node = ET.Element(tag, message=message)
159
+ node.text = bin_xml_escape(data)
160
+ self.append(node)
161
+
162
+ def write_captured_output(self, report: TestReport) -> None:
163
+ if not self.xml.log_passing_tests and report.passed:
164
+ return
165
+
166
+ content_out = report.capstdout
167
+ content_log = report.caplog
168
+ content_err = report.capstderr
169
+ if self.xml.logging == "no":
170
+ return
171
+ content_all = ""
172
+ if self.xml.logging in ["log", "all"]:
173
+ content_all = self._prepare_content(content_log, " Captured Log ")
174
+ if self.xml.logging in ["system-out", "out-err", "all"]:
175
+ content_all += self._prepare_content(content_out, " Captured Out ")
176
+ self._write_content(report, content_all, "system-out")
177
+ content_all = ""
178
+ if self.xml.logging in ["system-err", "out-err", "all"]:
179
+ content_all += self._prepare_content(content_err, " Captured Err ")
180
+ self._write_content(report, content_all, "system-err")
181
+ content_all = ""
182
+ if content_all:
183
+ self._write_content(report, content_all, "system-out")
184
+
185
+ def _prepare_content(self, content: str, header: str) -> str:
186
+ return "\n".join([header.center(80, "-"), content, ""])
187
+
188
+ def _write_content(self, report: TestReport, content: str, jheader: str) -> None:
189
+ tag = ET.Element(jheader)
190
+ tag.text = bin_xml_escape(content)
191
+ self.append(tag)
192
+
193
+ def append_pass(self, report: TestReport) -> None:
194
+ self.add_stats("passed")
195
+
196
+ def append_failure(self, report: TestReport) -> None:
197
+ # msg = str(report.longrepr.reprtraceback.extraline)
198
+ if hasattr(report, "wasxfail"):
199
+ self._add_simple("skipped", "xfail-marked test passes unexpectedly")
200
+ else:
201
+ assert report.longrepr is not None
202
+ reprcrash: Optional[ReprFileLocation] = getattr(
203
+ report.longrepr, "reprcrash", None
204
+ )
205
+ if reprcrash is not None:
206
+ message = reprcrash.message
207
+ else:
208
+ message = str(report.longrepr)
209
+ message = bin_xml_escape(message)
210
+ self._add_simple("failure", message, str(report.longrepr))
211
+
212
+ def append_collect_error(self, report: TestReport) -> None:
213
+ # msg = str(report.longrepr.reprtraceback.extraline)
214
+ assert report.longrepr is not None
215
+ self._add_simple("error", "collection failure", str(report.longrepr))
216
+
217
+ def append_collect_skipped(self, report: TestReport) -> None:
218
+ self._add_simple("skipped", "collection skipped", str(report.longrepr))
219
+
220
+ def append_error(self, report: TestReport) -> None:
221
+ assert report.longrepr is not None
222
+ reprcrash: Optional[ReprFileLocation] = getattr(
223
+ report.longrepr, "reprcrash", None
224
+ )
225
+ if reprcrash is not None:
226
+ reason = reprcrash.message
227
+ else:
228
+ reason = str(report.longrepr)
229
+
230
+ if report.when == "teardown":
231
+ msg = f'failed on teardown with "{reason}"'
232
+ else:
233
+ msg = f'failed on setup with "{reason}"'
234
+ self._add_simple("error", bin_xml_escape(msg), str(report.longrepr))
235
+
236
+ def append_skipped(self, report: TestReport) -> None:
237
+ if hasattr(report, "wasxfail"):
238
+ xfailreason = report.wasxfail
239
+ if xfailreason.startswith("reason: "):
240
+ xfailreason = xfailreason[8:]
241
+ xfailreason = bin_xml_escape(xfailreason)
242
+ skipped = ET.Element("skipped", type="pytest.xfail", message=xfailreason)
243
+ self.append(skipped)
244
+ else:
245
+ assert isinstance(report.longrepr, tuple)
246
+ filename, lineno, skipreason = report.longrepr
247
+ if skipreason.startswith("Skipped: "):
248
+ skipreason = skipreason[9:]
249
+ details = f"{filename}:{lineno}: {skipreason}"
250
+
251
+ skipped = ET.Element("skipped", type="pytest.skip", message=skipreason)
252
+ skipped.text = bin_xml_escape(details)
253
+ self.append(skipped)
254
+ self.write_captured_output(report)
255
+
256
+ def finalize(self) -> None:
257
+ data = self.to_xml()
258
+ self.__dict__.clear()
259
+ # Type ignored because mypy doesn't like overriding a method.
260
+ # Also the return value doesn't match...
261
+ self.to_xml = lambda: data # type: ignore[assignment]
262
+
263
+
264
+ def _warn_incompatibility_with_xunit2(
265
+ request: FixtureRequest, fixture_name: str
266
+ ) -> None:
267
+ """Emit a PytestWarning about the given fixture being incompatible with newer xunit revisions."""
268
+ from _pytest.warning_types import PytestWarning
269
+
270
+ xml = request.config.stash.get(xml_key, None)
271
+ if xml is not None and xml.family not in ("xunit1", "legacy"):
272
+ request.node.warn(
273
+ PytestWarning(
274
+ "{fixture_name} is incompatible with junit_family '{family}' (use 'legacy' or 'xunit1')".format(
275
+ fixture_name=fixture_name, family=xml.family
276
+ )
277
+ )
278
+ )
279
+
280
+
281
+ @pytest.fixture
282
+ def record_property(request: FixtureRequest) -> Callable[[str, object], None]:
283
+ """Add extra properties to the calling test.
284
+
285
+ User properties become part of the test report and are available to the
286
+ configured reporters, like JUnit XML.
287
+
288
+ The fixture is callable with ``name, value``. The value is automatically
289
+ XML-encoded.
290
+
291
+ Example::
292
+
293
+ def test_function(record_property):
294
+ record_property("example_key", 1)
295
+ """
296
+ _warn_incompatibility_with_xunit2(request, "record_property")
297
+
298
+ def append_property(name: str, value: object) -> None:
299
+ request.node.user_properties.append((name, value))
300
+
301
+ return append_property
302
+
303
+
304
+ @pytest.fixture
305
+ def record_xml_attribute(request: FixtureRequest) -> Callable[[str, object], None]:
306
+ """Add extra xml attributes to the tag for the calling test.
307
+
308
+ The fixture is callable with ``name, value``. The value is
309
+ automatically XML-encoded.
310
+ """
311
+ from _pytest.warning_types import PytestExperimentalApiWarning
312
+
313
+ request.node.warn(
314
+ PytestExperimentalApiWarning("record_xml_attribute is an experimental feature")
315
+ )
316
+
317
+ _warn_incompatibility_with_xunit2(request, "record_xml_attribute")
318
+
319
+ # Declare noop
320
+ def add_attr_noop(name: str, value: object) -> None:
321
+ pass
322
+
323
+ attr_func = add_attr_noop
324
+
325
+ xml = request.config.stash.get(xml_key, None)
326
+ if xml is not None:
327
+ node_reporter = xml.node_reporter(request.node.nodeid)
328
+ attr_func = node_reporter.add_attribute
329
+
330
+ return attr_func
331
+
332
+
333
+ def _check_record_param_type(param: str, v: str) -> None:
334
+ """Used by record_testsuite_property to check that the given parameter name is of the proper
335
+ type."""
336
+ __tracebackhide__ = True
337
+ if not isinstance(v, str):
338
+ msg = "{param} parameter needs to be a string, but {g} given" # type: ignore[unreachable]
339
+ raise TypeError(msg.format(param=param, g=type(v).__name__))
340
+
341
+
342
+ @pytest.fixture(scope="session")
343
+ def record_testsuite_property(request: FixtureRequest) -> Callable[[str, object], None]:
344
+ """Record a new ``<property>`` tag as child of the root ``<testsuite>``.
345
+
346
+ This is suitable to writing global information regarding the entire test
347
+ suite, and is compatible with ``xunit2`` JUnit family.
348
+
349
+ This is a ``session``-scoped fixture which is called with ``(name, value)``. Example:
350
+
351
+ .. code-block:: python
352
+
353
+ def test_foo(record_testsuite_property):
354
+ record_testsuite_property("ARCH", "PPC")
355
+ record_testsuite_property("STORAGE_TYPE", "CEPH")
356
+
357
+ :param name:
358
+ The property name.
359
+ :param value:
360
+ The property value. Will be converted to a string.
361
+
362
+ .. warning::
363
+
364
+ Currently this fixture **does not work** with the
365
+ `pytest-xdist <https://github.com/pytest-dev/pytest-xdist>`__ plugin. See
366
+ :issue:`7767` for details.
367
+ """
368
+
369
+ __tracebackhide__ = True
370
+
371
+ def record_func(name: str, value: object) -> None:
372
+ """No-op function in case --junitxml was not passed in the command-line."""
373
+ __tracebackhide__ = True
374
+ _check_record_param_type("name", name)
375
+
376
+ xml = request.config.stash.get(xml_key, None)
377
+ if xml is not None:
378
+ record_func = xml.add_global_property # noqa
379
+ return record_func
380
+
381
+
382
+ def pytest_addoption(parser: Parser) -> None:
383
+ group = parser.getgroup("terminal reporting")
384
+ group.addoption(
385
+ "--junitxml",
386
+ "--junit-xml",
387
+ action="store",
388
+ dest="xmlpath",
389
+ metavar="path",
390
+ type=functools.partial(filename_arg, optname="--junitxml"),
391
+ default=None,
392
+ help="Create junit-xml style report file at given path",
393
+ )
394
+ group.addoption(
395
+ "--junitprefix",
396
+ "--junit-prefix",
397
+ action="store",
398
+ metavar="str",
399
+ default=None,
400
+ help="Prepend prefix to classnames in junit-xml output",
401
+ )
402
+ parser.addini(
403
+ "junit_suite_name", "Test suite name for JUnit report", default="pytest"
404
+ )
405
+ parser.addini(
406
+ "junit_logging",
407
+ "Write captured log messages to JUnit report: "
408
+ "one of no|log|system-out|system-err|out-err|all",
409
+ default="no",
410
+ )
411
+ parser.addini(
412
+ "junit_log_passing_tests",
413
+ "Capture log information for passing tests to JUnit report: ",
414
+ type="bool",
415
+ default=True,
416
+ )
417
+ parser.addini(
418
+ "junit_duration_report",
419
+ "Duration time to report: one of total|call",
420
+ default="total",
421
+ ) # choices=['total', 'call'])
422
+ parser.addini(
423
+ "junit_family",
424
+ "Emit XML for schema: one of legacy|xunit1|xunit2",
425
+ default="xunit2",
426
+ )
427
+
428
+
429
+ def pytest_configure(config: Config) -> None:
430
+ xmlpath = config.option.xmlpath
431
+ # Prevent opening xmllog on worker nodes (xdist).
432
+ if xmlpath and not hasattr(config, "workerinput"):
433
+ junit_family = config.getini("junit_family")
434
+ config.stash[xml_key] = LogXML(
435
+ xmlpath,
436
+ config.option.junitprefix,
437
+ config.getini("junit_suite_name"),
438
+ config.getini("junit_logging"),
439
+ config.getini("junit_duration_report"),
440
+ junit_family,
441
+ config.getini("junit_log_passing_tests"),
442
+ )
443
+ config.pluginmanager.register(config.stash[xml_key])
444
+
445
+
446
+ def pytest_unconfigure(config: Config) -> None:
447
+ xml = config.stash.get(xml_key, None)
448
+ if xml:
449
+ del config.stash[xml_key]
450
+ config.pluginmanager.unregister(xml)
451
+
452
+
453
+ def mangle_test_address(address: str) -> List[str]:
454
+ path, possible_open_bracket, params = address.partition("[")
455
+ names = path.split("::")
456
+ # Convert file path to dotted path.
457
+ names[0] = names[0].replace(nodes.SEP, ".")
458
+ names[0] = re.sub(r"\.py$", "", names[0])
459
+ # Put any params back.
460
+ names[-1] += possible_open_bracket + params
461
+ return names
462
+
463
+
464
+ class LogXML:
465
+ def __init__(
466
+ self,
467
+ logfile,
468
+ prefix: Optional[str],
469
+ suite_name: str = "pytest",
470
+ logging: str = "no",
471
+ report_duration: str = "total",
472
+ family="xunit1",
473
+ log_passing_tests: bool = True,
474
+ ) -> None:
475
+ logfile = os.path.expanduser(os.path.expandvars(logfile))
476
+ self.logfile = os.path.normpath(os.path.abspath(logfile))
477
+ self.prefix = prefix
478
+ self.suite_name = suite_name
479
+ self.logging = logging
480
+ self.log_passing_tests = log_passing_tests
481
+ self.report_duration = report_duration
482
+ self.family = family
483
+ self.stats: Dict[str, int] = dict.fromkeys(
484
+ ["error", "passed", "failure", "skipped"], 0
485
+ )
486
+ self.node_reporters: Dict[
487
+ Tuple[Union[str, TestReport], object], _NodeReporter
488
+ ] = {}
489
+ self.node_reporters_ordered: List[_NodeReporter] = []
490
+ self.global_properties: List[Tuple[str, str]] = []
491
+
492
+ # List of reports that failed on call but teardown is pending.
493
+ self.open_reports: List[TestReport] = []
494
+ self.cnt_double_fail_tests = 0
495
+
496
+ # Replaces convenience family with real family.
497
+ if self.family == "legacy":
498
+ self.family = "xunit1"
499
+
500
+ def finalize(self, report: TestReport) -> None:
501
+ nodeid = getattr(report, "nodeid", report)
502
+ # Local hack to handle xdist report order.
503
+ workernode = getattr(report, "node", None)
504
+ reporter = self.node_reporters.pop((nodeid, workernode))
505
+
506
+ for propname, propvalue in report.user_properties:
507
+ reporter.add_property(propname, str(propvalue))
508
+
509
+ if reporter is not None:
510
+ reporter.finalize()
511
+
512
+ def node_reporter(self, report: Union[TestReport, str]) -> _NodeReporter:
513
+ nodeid: Union[str, TestReport] = getattr(report, "nodeid", report)
514
+ # Local hack to handle xdist report order.
515
+ workernode = getattr(report, "node", None)
516
+
517
+ key = nodeid, workernode
518
+
519
+ if key in self.node_reporters:
520
+ # TODO: breaks for --dist=each
521
+ return self.node_reporters[key]
522
+
523
+ reporter = _NodeReporter(nodeid, self)
524
+
525
+ self.node_reporters[key] = reporter
526
+ self.node_reporters_ordered.append(reporter)
527
+
528
+ return reporter
529
+
530
+ def add_stats(self, key: str) -> None:
531
+ if key in self.stats:
532
+ self.stats[key] += 1
533
+
534
+ def _opentestcase(self, report: TestReport) -> _NodeReporter:
535
+ reporter = self.node_reporter(report)
536
+ reporter.record_testreport(report)
537
+ return reporter
538
+
539
+ def pytest_runtest_logreport(self, report: TestReport) -> None:
540
+ """Handle a setup/call/teardown report, generating the appropriate
541
+ XML tags as necessary.
542
+
543
+ Note: due to plugins like xdist, this hook may be called in interlaced
544
+ order with reports from other nodes. For example:
545
+
546
+ Usual call order:
547
+ -> setup node1
548
+ -> call node1
549
+ -> teardown node1
550
+ -> setup node2
551
+ -> call node2
552
+ -> teardown node2
553
+
554
+ Possible call order in xdist:
555
+ -> setup node1
556
+ -> call node1
557
+ -> setup node2
558
+ -> call node2
559
+ -> teardown node2
560
+ -> teardown node1
561
+ """
562
+ close_report = None
563
+ if report.passed:
564
+ if report.when == "call": # ignore setup/teardown
565
+ reporter = self._opentestcase(report)
566
+ reporter.append_pass(report)
567
+ elif report.failed:
568
+ if report.when == "teardown":
569
+ # The following vars are needed when xdist plugin is used.
570
+ report_wid = getattr(report, "worker_id", None)
571
+ report_ii = getattr(report, "item_index", None)
572
+ close_report = next(
573
+ (
574
+ rep
575
+ for rep in self.open_reports
576
+ if (
577
+ rep.nodeid == report.nodeid
578
+ and getattr(rep, "item_index", None) == report_ii
579
+ and getattr(rep, "worker_id", None) == report_wid
580
+ )
581
+ ),
582
+ None,
583
+ )
584
+ if close_report:
585
+ # We need to open new testcase in case we have failure in
586
+ # call and error in teardown in order to follow junit
587
+ # schema.
588
+ self.finalize(close_report)
589
+ self.cnt_double_fail_tests += 1
590
+ reporter = self._opentestcase(report)
591
+ if report.when == "call":
592
+ reporter.append_failure(report)
593
+ self.open_reports.append(report)
594
+ if not self.log_passing_tests:
595
+ reporter.write_captured_output(report)
596
+ else:
597
+ reporter.append_error(report)
598
+ elif report.skipped:
599
+ reporter = self._opentestcase(report)
600
+ reporter.append_skipped(report)
601
+ self.update_testcase_duration(report)
602
+ if report.when == "teardown":
603
+ reporter = self._opentestcase(report)
604
+ reporter.write_captured_output(report)
605
+
606
+ self.finalize(report)
607
+ report_wid = getattr(report, "worker_id", None)
608
+ report_ii = getattr(report, "item_index", None)
609
+ close_report = next(
610
+ (
611
+ rep
612
+ for rep in self.open_reports
613
+ if (
614
+ rep.nodeid == report.nodeid
615
+ and getattr(rep, "item_index", None) == report_ii
616
+ and getattr(rep, "worker_id", None) == report_wid
617
+ )
618
+ ),
619
+ None,
620
+ )
621
+ if close_report:
622
+ self.open_reports.remove(close_report)
623
+
624
+ def update_testcase_duration(self, report: TestReport) -> None:
625
+ """Accumulate total duration for nodeid from given report and update
626
+ the Junit.testcase with the new total if already created."""
627
+ if self.report_duration == "total" or report.when == self.report_duration:
628
+ reporter = self.node_reporter(report)
629
+ reporter.duration += getattr(report, "duration", 0.0)
630
+
631
+ def pytest_collectreport(self, report: TestReport) -> None:
632
+ if not report.passed:
633
+ reporter = self._opentestcase(report)
634
+ if report.failed:
635
+ reporter.append_collect_error(report)
636
+ else:
637
+ reporter.append_collect_skipped(report)
638
+
639
+ def pytest_internalerror(self, excrepr: ExceptionRepr) -> None:
640
+ reporter = self.node_reporter("internal")
641
+ reporter.attrs.update(classname="pytest", name="internal")
642
+ reporter._add_simple("error", "internal error", str(excrepr))
643
+
644
+ def pytest_sessionstart(self) -> None:
645
+ self.suite_start_time = timing.time()
646
+
647
+ def pytest_sessionfinish(self) -> None:
648
+ dirname = os.path.dirname(os.path.abspath(self.logfile))
649
+ # exist_ok avoids filesystem race conditions between checking path existence and requesting creation
650
+ os.makedirs(dirname, exist_ok=True)
651
+
652
+ with open(self.logfile, "w", encoding="utf-8") as logfile:
653
+ suite_stop_time = timing.time()
654
+ suite_time_delta = suite_stop_time - self.suite_start_time
655
+
656
+ numtests = (
657
+ self.stats["passed"]
658
+ + self.stats["failure"]
659
+ + self.stats["skipped"]
660
+ + self.stats["error"]
661
+ - self.cnt_double_fail_tests
662
+ )
663
+ logfile.write('<?xml version="1.0" encoding="utf-8"?>')
664
+
665
+ suite_node = ET.Element(
666
+ "testsuite",
667
+ name=self.suite_name,
668
+ errors=str(self.stats["error"]),
669
+ failures=str(self.stats["failure"]),
670
+ skipped=str(self.stats["skipped"]),
671
+ tests=str(numtests),
672
+ time="%.3f" % suite_time_delta,
673
+ timestamp=datetime.fromtimestamp(self.suite_start_time).isoformat(),
674
+ hostname=platform.node(),
675
+ )
676
+ global_properties = self._get_global_properties_node()
677
+ if global_properties is not None:
678
+ suite_node.append(global_properties)
679
+ for node_reporter in self.node_reporters_ordered:
680
+ suite_node.append(node_reporter.to_xml())
681
+ testsuites = ET.Element("testsuites")
682
+ testsuites.append(suite_node)
683
+ logfile.write(ET.tostring(testsuites, encoding="unicode"))
684
+
685
+ def pytest_terminal_summary(self, terminalreporter: TerminalReporter) -> None:
686
+ terminalreporter.write_sep("-", f"generated xml file: {self.logfile}")
687
+
688
+ def add_global_property(self, name: str, value: object) -> None:
689
+ __tracebackhide__ = True
690
+ _check_record_param_type("name", name)
691
+ self.global_properties.append((name, bin_xml_escape(value)))
692
+
693
+ def _get_global_properties_node(self) -> Optional[ET.Element]:
694
+ """Return a Junit node containing custom properties, if any."""
695
+ if self.global_properties:
696
+ properties = ET.Element("properties")
697
+ for name, value in self.global_properties:
698
+ properties.append(ET.Element("property", name=name, value=value))
699
+ return properties
700
+ return None
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/legacypath.py ADDED
@@ -0,0 +1,479 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Add backward compatibility support for the legacy py path type."""
2
+ import dataclasses
3
+ import shlex
4
+ import subprocess
5
+ from pathlib import Path
6
+ from typing import List
7
+ from typing import Optional
8
+ from typing import TYPE_CHECKING
9
+ from typing import Union
10
+
11
+ from iniconfig import SectionWrapper
12
+
13
+ from _pytest.cacheprovider import Cache
14
+ from _pytest.compat import final
15
+ from _pytest.compat import LEGACY_PATH
16
+ from _pytest.compat import legacy_path
17
+ from _pytest.config import Config
18
+ from _pytest.config import hookimpl
19
+ from _pytest.config import PytestPluginManager
20
+ from _pytest.deprecated import check_ispytest
21
+ from _pytest.fixtures import fixture
22
+ from _pytest.fixtures import FixtureRequest
23
+ from _pytest.main import Session
24
+ from _pytest.monkeypatch import MonkeyPatch
25
+ from _pytest.nodes import Collector
26
+ from _pytest.nodes import Item
27
+ from _pytest.nodes import Node
28
+ from _pytest.pytester import HookRecorder
29
+ from _pytest.pytester import Pytester
30
+ from _pytest.pytester import RunResult
31
+ from _pytest.terminal import TerminalReporter
32
+ from _pytest.tmpdir import TempPathFactory
33
+
34
+ if TYPE_CHECKING:
35
+ from typing_extensions import Final
36
+
37
+ import pexpect
38
+
39
+
40
+ @final
41
+ class Testdir:
42
+ """
43
+ Similar to :class:`Pytester`, but this class works with legacy legacy_path objects instead.
44
+
45
+ All methods just forward to an internal :class:`Pytester` instance, converting results
46
+ to `legacy_path` objects as necessary.
47
+ """
48
+
49
+ __test__ = False
50
+
51
+ CLOSE_STDIN: "Final" = Pytester.CLOSE_STDIN
52
+ TimeoutExpired: "Final" = Pytester.TimeoutExpired
53
+
54
+ def __init__(self, pytester: Pytester, *, _ispytest: bool = False) -> None:
55
+ check_ispytest(_ispytest)
56
+ self._pytester = pytester
57
+
58
+ @property
59
+ def tmpdir(self) -> LEGACY_PATH:
60
+ """Temporary directory where tests are executed."""
61
+ return legacy_path(self._pytester.path)
62
+
63
+ @property
64
+ def test_tmproot(self) -> LEGACY_PATH:
65
+ return legacy_path(self._pytester._test_tmproot)
66
+
67
+ @property
68
+ def request(self):
69
+ return self._pytester._request
70
+
71
+ @property
72
+ def plugins(self):
73
+ return self._pytester.plugins
74
+
75
+ @plugins.setter
76
+ def plugins(self, plugins):
77
+ self._pytester.plugins = plugins
78
+
79
+ @property
80
+ def monkeypatch(self) -> MonkeyPatch:
81
+ return self._pytester._monkeypatch
82
+
83
+ def make_hook_recorder(self, pluginmanager) -> HookRecorder:
84
+ """See :meth:`Pytester.make_hook_recorder`."""
85
+ return self._pytester.make_hook_recorder(pluginmanager)
86
+
87
+ def chdir(self) -> None:
88
+ """See :meth:`Pytester.chdir`."""
89
+ return self._pytester.chdir()
90
+
91
+ def finalize(self) -> None:
92
+ """See :meth:`Pytester._finalize`."""
93
+ return self._pytester._finalize()
94
+
95
+ def makefile(self, ext, *args, **kwargs) -> LEGACY_PATH:
96
+ """See :meth:`Pytester.makefile`."""
97
+ if ext and not ext.startswith("."):
98
+ # pytester.makefile is going to throw a ValueError in a way that
99
+ # testdir.makefile did not, because
100
+ # pathlib.Path is stricter suffixes than py.path
101
+ # This ext arguments is likely user error, but since testdir has
102
+ # allowed this, we will prepend "." as a workaround to avoid breaking
103
+ # testdir usage that worked before
104
+ ext = "." + ext
105
+ return legacy_path(self._pytester.makefile(ext, *args, **kwargs))
106
+
107
+ def makeconftest(self, source) -> LEGACY_PATH:
108
+ """See :meth:`Pytester.makeconftest`."""
109
+ return legacy_path(self._pytester.makeconftest(source))
110
+
111
+ def makeini(self, source) -> LEGACY_PATH:
112
+ """See :meth:`Pytester.makeini`."""
113
+ return legacy_path(self._pytester.makeini(source))
114
+
115
+ def getinicfg(self, source: str) -> SectionWrapper:
116
+ """See :meth:`Pytester.getinicfg`."""
117
+ return self._pytester.getinicfg(source)
118
+
119
+ def makepyprojecttoml(self, source) -> LEGACY_PATH:
120
+ """See :meth:`Pytester.makepyprojecttoml`."""
121
+ return legacy_path(self._pytester.makepyprojecttoml(source))
122
+
123
+ def makepyfile(self, *args, **kwargs) -> LEGACY_PATH:
124
+ """See :meth:`Pytester.makepyfile`."""
125
+ return legacy_path(self._pytester.makepyfile(*args, **kwargs))
126
+
127
+ def maketxtfile(self, *args, **kwargs) -> LEGACY_PATH:
128
+ """See :meth:`Pytester.maketxtfile`."""
129
+ return legacy_path(self._pytester.maketxtfile(*args, **kwargs))
130
+
131
+ def syspathinsert(self, path=None) -> None:
132
+ """See :meth:`Pytester.syspathinsert`."""
133
+ return self._pytester.syspathinsert(path)
134
+
135
+ def mkdir(self, name) -> LEGACY_PATH:
136
+ """See :meth:`Pytester.mkdir`."""
137
+ return legacy_path(self._pytester.mkdir(name))
138
+
139
+ def mkpydir(self, name) -> LEGACY_PATH:
140
+ """See :meth:`Pytester.mkpydir`."""
141
+ return legacy_path(self._pytester.mkpydir(name))
142
+
143
+ def copy_example(self, name=None) -> LEGACY_PATH:
144
+ """See :meth:`Pytester.copy_example`."""
145
+ return legacy_path(self._pytester.copy_example(name))
146
+
147
+ def getnode(self, config: Config, arg) -> Optional[Union[Item, Collector]]:
148
+ """See :meth:`Pytester.getnode`."""
149
+ return self._pytester.getnode(config, arg)
150
+
151
+ def getpathnode(self, path):
152
+ """See :meth:`Pytester.getpathnode`."""
153
+ return self._pytester.getpathnode(path)
154
+
155
+ def genitems(self, colitems: List[Union[Item, Collector]]) -> List[Item]:
156
+ """See :meth:`Pytester.genitems`."""
157
+ return self._pytester.genitems(colitems)
158
+
159
+ def runitem(self, source):
160
+ """See :meth:`Pytester.runitem`."""
161
+ return self._pytester.runitem(source)
162
+
163
+ def inline_runsource(self, source, *cmdlineargs):
164
+ """See :meth:`Pytester.inline_runsource`."""
165
+ return self._pytester.inline_runsource(source, *cmdlineargs)
166
+
167
+ def inline_genitems(self, *args):
168
+ """See :meth:`Pytester.inline_genitems`."""
169
+ return self._pytester.inline_genitems(*args)
170
+
171
+ def inline_run(self, *args, plugins=(), no_reraise_ctrlc: bool = False):
172
+ """See :meth:`Pytester.inline_run`."""
173
+ return self._pytester.inline_run(
174
+ *args, plugins=plugins, no_reraise_ctrlc=no_reraise_ctrlc
175
+ )
176
+
177
+ def runpytest_inprocess(self, *args, **kwargs) -> RunResult:
178
+ """See :meth:`Pytester.runpytest_inprocess`."""
179
+ return self._pytester.runpytest_inprocess(*args, **kwargs)
180
+
181
+ def runpytest(self, *args, **kwargs) -> RunResult:
182
+ """See :meth:`Pytester.runpytest`."""
183
+ return self._pytester.runpytest(*args, **kwargs)
184
+
185
+ def parseconfig(self, *args) -> Config:
186
+ """See :meth:`Pytester.parseconfig`."""
187
+ return self._pytester.parseconfig(*args)
188
+
189
+ def parseconfigure(self, *args) -> Config:
190
+ """See :meth:`Pytester.parseconfigure`."""
191
+ return self._pytester.parseconfigure(*args)
192
+
193
+ def getitem(self, source, funcname="test_func"):
194
+ """See :meth:`Pytester.getitem`."""
195
+ return self._pytester.getitem(source, funcname)
196
+
197
+ def getitems(self, source):
198
+ """See :meth:`Pytester.getitems`."""
199
+ return self._pytester.getitems(source)
200
+
201
+ def getmodulecol(self, source, configargs=(), withinit=False):
202
+ """See :meth:`Pytester.getmodulecol`."""
203
+ return self._pytester.getmodulecol(
204
+ source, configargs=configargs, withinit=withinit
205
+ )
206
+
207
+ def collect_by_name(
208
+ self, modcol: Collector, name: str
209
+ ) -> Optional[Union[Item, Collector]]:
210
+ """See :meth:`Pytester.collect_by_name`."""
211
+ return self._pytester.collect_by_name(modcol, name)
212
+
213
+ def popen(
214
+ self,
215
+ cmdargs,
216
+ stdout=subprocess.PIPE,
217
+ stderr=subprocess.PIPE,
218
+ stdin=CLOSE_STDIN,
219
+ **kw,
220
+ ):
221
+ """See :meth:`Pytester.popen`."""
222
+ return self._pytester.popen(cmdargs, stdout, stderr, stdin, **kw)
223
+
224
+ def run(self, *cmdargs, timeout=None, stdin=CLOSE_STDIN) -> RunResult:
225
+ """See :meth:`Pytester.run`."""
226
+ return self._pytester.run(*cmdargs, timeout=timeout, stdin=stdin)
227
+
228
+ def runpython(self, script) -> RunResult:
229
+ """See :meth:`Pytester.runpython`."""
230
+ return self._pytester.runpython(script)
231
+
232
+ def runpython_c(self, command):
233
+ """See :meth:`Pytester.runpython_c`."""
234
+ return self._pytester.runpython_c(command)
235
+
236
+ def runpytest_subprocess(self, *args, timeout=None) -> RunResult:
237
+ """See :meth:`Pytester.runpytest_subprocess`."""
238
+ return self._pytester.runpytest_subprocess(*args, timeout=timeout)
239
+
240
+ def spawn_pytest(
241
+ self, string: str, expect_timeout: float = 10.0
242
+ ) -> "pexpect.spawn":
243
+ """See :meth:`Pytester.spawn_pytest`."""
244
+ return self._pytester.spawn_pytest(string, expect_timeout=expect_timeout)
245
+
246
+ def spawn(self, cmd: str, expect_timeout: float = 10.0) -> "pexpect.spawn":
247
+ """See :meth:`Pytester.spawn`."""
248
+ return self._pytester.spawn(cmd, expect_timeout=expect_timeout)
249
+
250
+ def __repr__(self) -> str:
251
+ return f"<Testdir {self.tmpdir!r}>"
252
+
253
+ def __str__(self) -> str:
254
+ return str(self.tmpdir)
255
+
256
+
257
+ class LegacyTestdirPlugin:
258
+ @staticmethod
259
+ @fixture
260
+ def testdir(pytester: Pytester) -> Testdir:
261
+ """
262
+ Identical to :fixture:`pytester`, and provides an instance whose methods return
263
+ legacy ``LEGACY_PATH`` objects instead when applicable.
264
+
265
+ New code should avoid using :fixture:`testdir` in favor of :fixture:`pytester`.
266
+ """
267
+ return Testdir(pytester, _ispytest=True)
268
+
269
+
270
+ @final
271
+ @dataclasses.dataclass
272
+ class TempdirFactory:
273
+ """Backward compatibility wrapper that implements :class:`py.path.local`
274
+ for :class:`TempPathFactory`.
275
+
276
+ .. note::
277
+ These days, it is preferred to use ``tmp_path_factory``.
278
+
279
+ :ref:`About the tmpdir and tmpdir_factory fixtures<tmpdir and tmpdir_factory>`.
280
+
281
+ """
282
+
283
+ _tmppath_factory: TempPathFactory
284
+
285
+ def __init__(
286
+ self, tmppath_factory: TempPathFactory, *, _ispytest: bool = False
287
+ ) -> None:
288
+ check_ispytest(_ispytest)
289
+ self._tmppath_factory = tmppath_factory
290
+
291
+ def mktemp(self, basename: str, numbered: bool = True) -> LEGACY_PATH:
292
+ """Same as :meth:`TempPathFactory.mktemp`, but returns a :class:`py.path.local` object."""
293
+ return legacy_path(self._tmppath_factory.mktemp(basename, numbered).resolve())
294
+
295
+ def getbasetemp(self) -> LEGACY_PATH:
296
+ """Same as :meth:`TempPathFactory.getbasetemp`, but returns a :class:`py.path.local` object."""
297
+ return legacy_path(self._tmppath_factory.getbasetemp().resolve())
298
+
299
+
300
+ class LegacyTmpdirPlugin:
301
+ @staticmethod
302
+ @fixture(scope="session")
303
+ def tmpdir_factory(request: FixtureRequest) -> TempdirFactory:
304
+ """Return a :class:`pytest.TempdirFactory` instance for the test session."""
305
+ # Set dynamically by pytest_configure().
306
+ return request.config._tmpdirhandler # type: ignore
307
+
308
+ @staticmethod
309
+ @fixture
310
+ def tmpdir(tmp_path: Path) -> LEGACY_PATH:
311
+ """Return a temporary directory path object which is unique to each test
312
+ function invocation, created as a sub directory of the base temporary
313
+ directory.
314
+
315
+ By default, a new base temporary directory is created each test session,
316
+ and old bases are removed after 3 sessions, to aid in debugging. If
317
+ ``--basetemp`` is used then it is cleared each session. See :ref:`base
318
+ temporary directory`.
319
+
320
+ The returned object is a `legacy_path`_ object.
321
+
322
+ .. note::
323
+ These days, it is preferred to use ``tmp_path``.
324
+
325
+ :ref:`About the tmpdir and tmpdir_factory fixtures<tmpdir and tmpdir_factory>`.
326
+
327
+ .. _legacy_path: https://py.readthedocs.io/en/latest/path.html
328
+ """
329
+ return legacy_path(tmp_path)
330
+
331
+
332
+ def Cache_makedir(self: Cache, name: str) -> LEGACY_PATH:
333
+ """Return a directory path object with the given name.
334
+
335
+ Same as :func:`mkdir`, but returns a legacy py path instance.
336
+ """
337
+ return legacy_path(self.mkdir(name))
338
+
339
+
340
+ def FixtureRequest_fspath(self: FixtureRequest) -> LEGACY_PATH:
341
+ """(deprecated) The file system path of the test module which collected this test."""
342
+ return legacy_path(self.path)
343
+
344
+
345
+ def TerminalReporter_startdir(self: TerminalReporter) -> LEGACY_PATH:
346
+ """The directory from which pytest was invoked.
347
+
348
+ Prefer to use ``startpath`` which is a :class:`pathlib.Path`.
349
+
350
+ :type: LEGACY_PATH
351
+ """
352
+ return legacy_path(self.startpath)
353
+
354
+
355
+ def Config_invocation_dir(self: Config) -> LEGACY_PATH:
356
+ """The directory from which pytest was invoked.
357
+
358
+ Prefer to use :attr:`invocation_params.dir <InvocationParams.dir>`,
359
+ which is a :class:`pathlib.Path`.
360
+
361
+ :type: LEGACY_PATH
362
+ """
363
+ return legacy_path(str(self.invocation_params.dir))
364
+
365
+
366
+ def Config_rootdir(self: Config) -> LEGACY_PATH:
367
+ """The path to the :ref:`rootdir <rootdir>`.
368
+
369
+ Prefer to use :attr:`rootpath`, which is a :class:`pathlib.Path`.
370
+
371
+ :type: LEGACY_PATH
372
+ """
373
+ return legacy_path(str(self.rootpath))
374
+
375
+
376
+ def Config_inifile(self: Config) -> Optional[LEGACY_PATH]:
377
+ """The path to the :ref:`configfile <configfiles>`.
378
+
379
+ Prefer to use :attr:`inipath`, which is a :class:`pathlib.Path`.
380
+
381
+ :type: Optional[LEGACY_PATH]
382
+ """
383
+ return legacy_path(str(self.inipath)) if self.inipath else None
384
+
385
+
386
+ def Session_stardir(self: Session) -> LEGACY_PATH:
387
+ """The path from which pytest was invoked.
388
+
389
+ Prefer to use ``startpath`` which is a :class:`pathlib.Path`.
390
+
391
+ :type: LEGACY_PATH
392
+ """
393
+ return legacy_path(self.startpath)
394
+
395
+
396
+ def Config__getini_unknown_type(
397
+ self, name: str, type: str, value: Union[str, List[str]]
398
+ ):
399
+ if type == "pathlist":
400
+ # TODO: This assert is probably not valid in all cases.
401
+ assert self.inipath is not None
402
+ dp = self.inipath.parent
403
+ input_values = shlex.split(value) if isinstance(value, str) else value
404
+ return [legacy_path(str(dp / x)) for x in input_values]
405
+ else:
406
+ raise ValueError(f"unknown configuration type: {type}", value)
407
+
408
+
409
+ def Node_fspath(self: Node) -> LEGACY_PATH:
410
+ """(deprecated) returns a legacy_path copy of self.path"""
411
+ return legacy_path(self.path)
412
+
413
+
414
+ def Node_fspath_set(self: Node, value: LEGACY_PATH) -> None:
415
+ self.path = Path(value)
416
+
417
+
418
+ @hookimpl(tryfirst=True)
419
+ def pytest_load_initial_conftests(early_config: Config) -> None:
420
+ """Monkeypatch legacy path attributes in several classes, as early as possible."""
421
+ mp = MonkeyPatch()
422
+ early_config.add_cleanup(mp.undo)
423
+
424
+ # Add Cache.makedir().
425
+ mp.setattr(Cache, "makedir", Cache_makedir, raising=False)
426
+
427
+ # Add FixtureRequest.fspath property.
428
+ mp.setattr(FixtureRequest, "fspath", property(FixtureRequest_fspath), raising=False)
429
+
430
+ # Add TerminalReporter.startdir property.
431
+ mp.setattr(
432
+ TerminalReporter, "startdir", property(TerminalReporter_startdir), raising=False
433
+ )
434
+
435
+ # Add Config.{invocation_dir,rootdir,inifile} properties.
436
+ mp.setattr(Config, "invocation_dir", property(Config_invocation_dir), raising=False)
437
+ mp.setattr(Config, "rootdir", property(Config_rootdir), raising=False)
438
+ mp.setattr(Config, "inifile", property(Config_inifile), raising=False)
439
+
440
+ # Add Session.startdir property.
441
+ mp.setattr(Session, "startdir", property(Session_stardir), raising=False)
442
+
443
+ # Add pathlist configuration type.
444
+ mp.setattr(Config, "_getini_unknown_type", Config__getini_unknown_type)
445
+
446
+ # Add Node.fspath property.
447
+ mp.setattr(Node, "fspath", property(Node_fspath, Node_fspath_set), raising=False)
448
+
449
+
450
+ @hookimpl
451
+ def pytest_configure(config: Config) -> None:
452
+ """Installs the LegacyTmpdirPlugin if the ``tmpdir`` plugin is also installed."""
453
+ if config.pluginmanager.has_plugin("tmpdir"):
454
+ mp = MonkeyPatch()
455
+ config.add_cleanup(mp.undo)
456
+ # Create TmpdirFactory and attach it to the config object.
457
+ #
458
+ # This is to comply with existing plugins which expect the handler to be
459
+ # available at pytest_configure time, but ideally should be moved entirely
460
+ # to the tmpdir_factory session fixture.
461
+ try:
462
+ tmp_path_factory = config._tmp_path_factory # type: ignore[attr-defined]
463
+ except AttributeError:
464
+ # tmpdir plugin is blocked.
465
+ pass
466
+ else:
467
+ _tmpdirhandler = TempdirFactory(tmp_path_factory, _ispytest=True)
468
+ mp.setattr(config, "_tmpdirhandler", _tmpdirhandler, raising=False)
469
+
470
+ config.pluginmanager.register(LegacyTmpdirPlugin, "legacypath-tmpdir")
471
+
472
+
473
+ @hookimpl
474
+ def pytest_plugin_registered(plugin: object, manager: PytestPluginManager) -> None:
475
+ # pytester is not loaded by default and is commonly loaded from a conftest,
476
+ # so checking for it in `pytest_configure` is not enough.
477
+ is_pytester = plugin is manager.get_plugin("pytester")
478
+ if is_pytester and not manager.is_registered(LegacyTestdirPlugin):
479
+ manager.register(LegacyTestdirPlugin, "legacypath-pytester")
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/logging.py ADDED
@@ -0,0 +1,920 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Access and control log capturing."""
2
+ import io
3
+ import logging
4
+ import os
5
+ import re
6
+ from contextlib import contextmanager
7
+ from contextlib import nullcontext
8
+ from datetime import datetime
9
+ from datetime import timedelta
10
+ from datetime import timezone
11
+ from io import StringIO
12
+ from logging import LogRecord
13
+ from pathlib import Path
14
+ from typing import AbstractSet
15
+ from typing import Dict
16
+ from typing import Generator
17
+ from typing import List
18
+ from typing import Mapping
19
+ from typing import Optional
20
+ from typing import Tuple
21
+ from typing import TYPE_CHECKING
22
+ from typing import TypeVar
23
+ from typing import Union
24
+
25
+ from _pytest import nodes
26
+ from _pytest._io import TerminalWriter
27
+ from _pytest.capture import CaptureManager
28
+ from _pytest.compat import final
29
+ from _pytest.config import _strtobool
30
+ from _pytest.config import Config
31
+ from _pytest.config import create_terminal_writer
32
+ from _pytest.config import hookimpl
33
+ from _pytest.config import UsageError
34
+ from _pytest.config.argparsing import Parser
35
+ from _pytest.deprecated import check_ispytest
36
+ from _pytest.fixtures import fixture
37
+ from _pytest.fixtures import FixtureRequest
38
+ from _pytest.main import Session
39
+ from _pytest.stash import StashKey
40
+ from _pytest.terminal import TerminalReporter
41
+
42
+ if TYPE_CHECKING:
43
+ logging_StreamHandler = logging.StreamHandler[StringIO]
44
+
45
+ from typing_extensions import Literal
46
+ else:
47
+ logging_StreamHandler = logging.StreamHandler
48
+
49
+ DEFAULT_LOG_FORMAT = "%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s"
50
+ DEFAULT_LOG_DATE_FORMAT = "%H:%M:%S"
51
+ _ANSI_ESCAPE_SEQ = re.compile(r"\x1b\[[\d;]+m")
52
+ caplog_handler_key = StashKey["LogCaptureHandler"]()
53
+ caplog_records_key = StashKey[Dict[str, List[logging.LogRecord]]]()
54
+
55
+
56
+ def _remove_ansi_escape_sequences(text: str) -> str:
57
+ return _ANSI_ESCAPE_SEQ.sub("", text)
58
+
59
+
60
+ class DatetimeFormatter(logging.Formatter):
61
+ """A logging formatter which formats record with
62
+ :func:`datetime.datetime.strftime` formatter instead of
63
+ :func:`time.strftime` in case of microseconds in format string.
64
+ """
65
+
66
+ def formatTime(self, record: LogRecord, datefmt=None) -> str:
67
+ if datefmt and "%f" in datefmt:
68
+ ct = self.converter(record.created)
69
+ tz = timezone(timedelta(seconds=ct.tm_gmtoff), ct.tm_zone)
70
+ # Construct `datetime.datetime` object from `struct_time`
71
+ # and msecs information from `record`
72
+ dt = datetime(*ct[0:6], microsecond=round(record.msecs * 1000), tzinfo=tz)
73
+ return dt.strftime(datefmt)
74
+ # Use `logging.Formatter` for non-microsecond formats
75
+ return super().formatTime(record, datefmt)
76
+
77
+
78
+ class ColoredLevelFormatter(DatetimeFormatter):
79
+ """A logging formatter which colorizes the %(levelname)..s part of the
80
+ log format passed to __init__."""
81
+
82
+ LOGLEVEL_COLOROPTS: Mapping[int, AbstractSet[str]] = {
83
+ logging.CRITICAL: {"red"},
84
+ logging.ERROR: {"red", "bold"},
85
+ logging.WARNING: {"yellow"},
86
+ logging.WARN: {"yellow"},
87
+ logging.INFO: {"green"},
88
+ logging.DEBUG: {"purple"},
89
+ logging.NOTSET: set(),
90
+ }
91
+ LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-.]?\d*(?:\.\d+)?s)")
92
+
93
+ def __init__(self, terminalwriter: TerminalWriter, *args, **kwargs) -> None:
94
+ super().__init__(*args, **kwargs)
95
+ self._terminalwriter = terminalwriter
96
+ self._original_fmt = self._style._fmt
97
+ self._level_to_fmt_mapping: Dict[int, str] = {}
98
+
99
+ for level, color_opts in self.LOGLEVEL_COLOROPTS.items():
100
+ self.add_color_level(level, *color_opts)
101
+
102
+ def add_color_level(self, level: int, *color_opts: str) -> None:
103
+ """Add or update color opts for a log level.
104
+
105
+ :param level:
106
+ Log level to apply a style to, e.g. ``logging.INFO``.
107
+ :param color_opts:
108
+ ANSI escape sequence color options. Capitalized colors indicates
109
+ background color, i.e. ``'green', 'Yellow', 'bold'`` will give bold
110
+ green text on yellow background.
111
+
112
+ .. warning::
113
+ This is an experimental API.
114
+ """
115
+
116
+ assert self._fmt is not None
117
+ levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt)
118
+ if not levelname_fmt_match:
119
+ return
120
+ levelname_fmt = levelname_fmt_match.group()
121
+
122
+ formatted_levelname = levelname_fmt % {"levelname": logging.getLevelName(level)}
123
+
124
+ # add ANSI escape sequences around the formatted levelname
125
+ color_kwargs = {name: True for name in color_opts}
126
+ colorized_formatted_levelname = self._terminalwriter.markup(
127
+ formatted_levelname, **color_kwargs
128
+ )
129
+ self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub(
130
+ colorized_formatted_levelname, self._fmt
131
+ )
132
+
133
+ def format(self, record: logging.LogRecord) -> str:
134
+ fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt)
135
+ self._style._fmt = fmt
136
+ return super().format(record)
137
+
138
+
139
+ class PercentStyleMultiline(logging.PercentStyle):
140
+ """A logging style with special support for multiline messages.
141
+
142
+ If the message of a record consists of multiple lines, this style
143
+ formats the message as if each line were logged separately.
144
+ """
145
+
146
+ def __init__(self, fmt: str, auto_indent: Union[int, str, bool, None]) -> None:
147
+ super().__init__(fmt)
148
+ self._auto_indent = self._get_auto_indent(auto_indent)
149
+
150
+ @staticmethod
151
+ def _get_auto_indent(auto_indent_option: Union[int, str, bool, None]) -> int:
152
+ """Determine the current auto indentation setting.
153
+
154
+ Specify auto indent behavior (on/off/fixed) by passing in
155
+ extra={"auto_indent": [value]} to the call to logging.log() or
156
+ using a --log-auto-indent [value] command line or the
157
+ log_auto_indent [value] config option.
158
+
159
+ Default behavior is auto-indent off.
160
+
161
+ Using the string "True" or "on" or the boolean True as the value
162
+ turns auto indent on, using the string "False" or "off" or the
163
+ boolean False or the int 0 turns it off, and specifying a
164
+ positive integer fixes the indentation position to the value
165
+ specified.
166
+
167
+ Any other values for the option are invalid, and will silently be
168
+ converted to the default.
169
+
170
+ :param None|bool|int|str auto_indent_option:
171
+ User specified option for indentation from command line, config
172
+ or extra kwarg. Accepts int, bool or str. str option accepts the
173
+ same range of values as boolean config options, as well as
174
+ positive integers represented in str form.
175
+
176
+ :returns:
177
+ Indentation value, which can be
178
+ -1 (automatically determine indentation) or
179
+ 0 (auto-indent turned off) or
180
+ >0 (explicitly set indentation position).
181
+ """
182
+
183
+ if auto_indent_option is None:
184
+ return 0
185
+ elif isinstance(auto_indent_option, bool):
186
+ if auto_indent_option:
187
+ return -1
188
+ else:
189
+ return 0
190
+ elif isinstance(auto_indent_option, int):
191
+ return int(auto_indent_option)
192
+ elif isinstance(auto_indent_option, str):
193
+ try:
194
+ return int(auto_indent_option)
195
+ except ValueError:
196
+ pass
197
+ try:
198
+ if _strtobool(auto_indent_option):
199
+ return -1
200
+ except ValueError:
201
+ return 0
202
+
203
+ return 0
204
+
205
+ def format(self, record: logging.LogRecord) -> str:
206
+ if "\n" in record.message:
207
+ if hasattr(record, "auto_indent"):
208
+ # Passed in from the "extra={}" kwarg on the call to logging.log().
209
+ auto_indent = self._get_auto_indent(record.auto_indent) # type: ignore[attr-defined]
210
+ else:
211
+ auto_indent = self._auto_indent
212
+
213
+ if auto_indent:
214
+ lines = record.message.splitlines()
215
+ formatted = self._fmt % {**record.__dict__, "message": lines[0]}
216
+
217
+ if auto_indent < 0:
218
+ indentation = _remove_ansi_escape_sequences(formatted).find(
219
+ lines[0]
220
+ )
221
+ else:
222
+ # Optimizes logging by allowing a fixed indentation.
223
+ indentation = auto_indent
224
+ lines[0] = formatted
225
+ return ("\n" + " " * indentation).join(lines)
226
+ return self._fmt % record.__dict__
227
+
228
+
229
+ def get_option_ini(config: Config, *names: str):
230
+ for name in names:
231
+ ret = config.getoption(name) # 'default' arg won't work as expected
232
+ if ret is None:
233
+ ret = config.getini(name)
234
+ if ret:
235
+ return ret
236
+
237
+
238
+ def pytest_addoption(parser: Parser) -> None:
239
+ """Add options to control log capturing."""
240
+ group = parser.getgroup("logging")
241
+
242
+ def add_option_ini(option, dest, default=None, type=None, **kwargs):
243
+ parser.addini(
244
+ dest, default=default, type=type, help="Default value for " + option
245
+ )
246
+ group.addoption(option, dest=dest, **kwargs)
247
+
248
+ add_option_ini(
249
+ "--log-level",
250
+ dest="log_level",
251
+ default=None,
252
+ metavar="LEVEL",
253
+ help=(
254
+ "Level of messages to catch/display."
255
+ " Not set by default, so it depends on the root/parent log handler's"
256
+ ' effective level, where it is "WARNING" by default.'
257
+ ),
258
+ )
259
+ add_option_ini(
260
+ "--log-format",
261
+ dest="log_format",
262
+ default=DEFAULT_LOG_FORMAT,
263
+ help="Log format used by the logging module",
264
+ )
265
+ add_option_ini(
266
+ "--log-date-format",
267
+ dest="log_date_format",
268
+ default=DEFAULT_LOG_DATE_FORMAT,
269
+ help="Log date format used by the logging module",
270
+ )
271
+ parser.addini(
272
+ "log_cli",
273
+ default=False,
274
+ type="bool",
275
+ help='Enable log display during test run (also known as "live logging")',
276
+ )
277
+ add_option_ini(
278
+ "--log-cli-level", dest="log_cli_level", default=None, help="CLI logging level"
279
+ )
280
+ add_option_ini(
281
+ "--log-cli-format",
282
+ dest="log_cli_format",
283
+ default=None,
284
+ help="Log format used by the logging module",
285
+ )
286
+ add_option_ini(
287
+ "--log-cli-date-format",
288
+ dest="log_cli_date_format",
289
+ default=None,
290
+ help="Log date format used by the logging module",
291
+ )
292
+ add_option_ini(
293
+ "--log-file",
294
+ dest="log_file",
295
+ default=None,
296
+ help="Path to a file when logging will be written to",
297
+ )
298
+ add_option_ini(
299
+ "--log-file-level",
300
+ dest="log_file_level",
301
+ default=None,
302
+ help="Log file logging level",
303
+ )
304
+ add_option_ini(
305
+ "--log-file-format",
306
+ dest="log_file_format",
307
+ default=DEFAULT_LOG_FORMAT,
308
+ help="Log format used by the logging module",
309
+ )
310
+ add_option_ini(
311
+ "--log-file-date-format",
312
+ dest="log_file_date_format",
313
+ default=DEFAULT_LOG_DATE_FORMAT,
314
+ help="Log date format used by the logging module",
315
+ )
316
+ add_option_ini(
317
+ "--log-auto-indent",
318
+ dest="log_auto_indent",
319
+ default=None,
320
+ help="Auto-indent multiline messages passed to the logging module. Accepts true|on, false|off or an integer.",
321
+ )
322
+ group.addoption(
323
+ "--log-disable",
324
+ action="append",
325
+ default=[],
326
+ dest="logger_disable",
327
+ help="Disable a logger by name. Can be passed multiple times.",
328
+ )
329
+
330
+
331
+ _HandlerType = TypeVar("_HandlerType", bound=logging.Handler)
332
+
333
+
334
+ # Not using @contextmanager for performance reasons.
335
+ class catching_logs:
336
+ """Context manager that prepares the whole logging machinery properly."""
337
+
338
+ __slots__ = ("handler", "level", "orig_level")
339
+
340
+ def __init__(self, handler: _HandlerType, level: Optional[int] = None) -> None:
341
+ self.handler = handler
342
+ self.level = level
343
+
344
+ def __enter__(self):
345
+ root_logger = logging.getLogger()
346
+ if self.level is not None:
347
+ self.handler.setLevel(self.level)
348
+ root_logger.addHandler(self.handler)
349
+ if self.level is not None:
350
+ self.orig_level = root_logger.level
351
+ root_logger.setLevel(min(self.orig_level, self.level))
352
+ return self.handler
353
+
354
+ def __exit__(self, type, value, traceback):
355
+ root_logger = logging.getLogger()
356
+ if self.level is not None:
357
+ root_logger.setLevel(self.orig_level)
358
+ root_logger.removeHandler(self.handler)
359
+
360
+
361
+ class LogCaptureHandler(logging_StreamHandler):
362
+ """A logging handler that stores log records and the log text."""
363
+
364
+ def __init__(self) -> None:
365
+ """Create a new log handler."""
366
+ super().__init__(StringIO())
367
+ self.records: List[logging.LogRecord] = []
368
+
369
+ def emit(self, record: logging.LogRecord) -> None:
370
+ """Keep the log records in a list in addition to the log text."""
371
+ self.records.append(record)
372
+ super().emit(record)
373
+
374
+ def reset(self) -> None:
375
+ self.records = []
376
+ self.stream = StringIO()
377
+
378
+ def clear(self) -> None:
379
+ self.records.clear()
380
+ self.stream = StringIO()
381
+
382
+ def handleError(self, record: logging.LogRecord) -> None:
383
+ if logging.raiseExceptions:
384
+ # Fail the test if the log message is bad (emit failed).
385
+ # The default behavior of logging is to print "Logging error"
386
+ # to stderr with the call stack and some extra details.
387
+ # pytest wants to make such mistakes visible during testing.
388
+ raise
389
+
390
+
391
+ @final
392
+ class LogCaptureFixture:
393
+ """Provides access and control of log capturing."""
394
+
395
+ def __init__(self, item: nodes.Node, *, _ispytest: bool = False) -> None:
396
+ check_ispytest(_ispytest)
397
+ self._item = item
398
+ self._initial_handler_level: Optional[int] = None
399
+ # Dict of log name -> log level.
400
+ self._initial_logger_levels: Dict[Optional[str], int] = {}
401
+ self._initial_disabled_logging_level: Optional[int] = None
402
+
403
+ def _finalize(self) -> None:
404
+ """Finalize the fixture.
405
+
406
+ This restores the log levels and the disabled logging levels changed by :meth:`set_level`.
407
+ """
408
+ # Restore log levels.
409
+ if self._initial_handler_level is not None:
410
+ self.handler.setLevel(self._initial_handler_level)
411
+ for logger_name, level in self._initial_logger_levels.items():
412
+ logger = logging.getLogger(logger_name)
413
+ logger.setLevel(level)
414
+ # Disable logging at the original disabled logging level.
415
+ if self._initial_disabled_logging_level is not None:
416
+ logging.disable(self._initial_disabled_logging_level)
417
+ self._initial_disabled_logging_level = None
418
+
419
+ @property
420
+ def handler(self) -> LogCaptureHandler:
421
+ """Get the logging handler used by the fixture."""
422
+ return self._item.stash[caplog_handler_key]
423
+
424
+ def get_records(
425
+ self, when: "Literal['setup', 'call', 'teardown']"
426
+ ) -> List[logging.LogRecord]:
427
+ """Get the logging records for one of the possible test phases.
428
+
429
+ :param when:
430
+ Which test phase to obtain the records from.
431
+ Valid values are: "setup", "call" and "teardown".
432
+
433
+ :returns: The list of captured records at the given stage.
434
+
435
+ .. versionadded:: 3.4
436
+ """
437
+ return self._item.stash[caplog_records_key].get(when, [])
438
+
439
+ @property
440
+ def text(self) -> str:
441
+ """The formatted log text."""
442
+ return _remove_ansi_escape_sequences(self.handler.stream.getvalue())
443
+
444
+ @property
445
+ def records(self) -> List[logging.LogRecord]:
446
+ """The list of log records."""
447
+ return self.handler.records
448
+
449
+ @property
450
+ def record_tuples(self) -> List[Tuple[str, int, str]]:
451
+ """A list of a stripped down version of log records intended
452
+ for use in assertion comparison.
453
+
454
+ The format of the tuple is:
455
+
456
+ (logger_name, log_level, message)
457
+ """
458
+ return [(r.name, r.levelno, r.getMessage()) for r in self.records]
459
+
460
+ @property
461
+ def messages(self) -> List[str]:
462
+ """A list of format-interpolated log messages.
463
+
464
+ Unlike 'records', which contains the format string and parameters for
465
+ interpolation, log messages in this list are all interpolated.
466
+
467
+ Unlike 'text', which contains the output from the handler, log
468
+ messages in this list are unadorned with levels, timestamps, etc,
469
+ making exact comparisons more reliable.
470
+
471
+ Note that traceback or stack info (from :func:`logging.exception` or
472
+ the `exc_info` or `stack_info` arguments to the logging functions) is
473
+ not included, as this is added by the formatter in the handler.
474
+
475
+ .. versionadded:: 3.7
476
+ """
477
+ return [r.getMessage() for r in self.records]
478
+
479
+ def clear(self) -> None:
480
+ """Reset the list of log records and the captured log text."""
481
+ self.handler.clear()
482
+
483
+ def _force_enable_logging(
484
+ self, level: Union[int, str], logger_obj: logging.Logger
485
+ ) -> int:
486
+ """Enable the desired logging level if the global level was disabled via ``logging.disabled``.
487
+
488
+ Only enables logging levels greater than or equal to the requested ``level``.
489
+
490
+ Does nothing if the desired ``level`` wasn't disabled.
491
+
492
+ :param level:
493
+ The logger level caplog should capture.
494
+ All logging is enabled if a non-standard logging level string is supplied.
495
+ Valid level strings are in :data:`logging._nameToLevel`.
496
+ :param logger_obj: The logger object to check.
497
+
498
+ :return: The original disabled logging level.
499
+ """
500
+ original_disable_level: int = logger_obj.manager.disable # type: ignore[attr-defined]
501
+
502
+ if isinstance(level, str):
503
+ # Try to translate the level string to an int for `logging.disable()`
504
+ level = logging.getLevelName(level)
505
+
506
+ if not isinstance(level, int):
507
+ # The level provided was not valid, so just un-disable all logging.
508
+ logging.disable(logging.NOTSET)
509
+ elif not logger_obj.isEnabledFor(level):
510
+ # Each level is `10` away from other levels.
511
+ # https://docs.python.org/3/library/logging.html#logging-levels
512
+ disable_level = max(level - 10, logging.NOTSET)
513
+ logging.disable(disable_level)
514
+
515
+ return original_disable_level
516
+
517
+ def set_level(self, level: Union[int, str], logger: Optional[str] = None) -> None:
518
+ """Set the threshold level of a logger for the duration of a test.
519
+
520
+ Logging messages which are less severe than this level will not be captured.
521
+
522
+ .. versionchanged:: 3.4
523
+ The levels of the loggers changed by this function will be
524
+ restored to their initial values at the end of the test.
525
+
526
+ Will enable the requested logging level if it was disabled via :meth:`logging.disable`.
527
+
528
+ :param level: The level.
529
+ :param logger: The logger to update. If not given, the root logger.
530
+ """
531
+ logger_obj = logging.getLogger(logger)
532
+ # Save the original log-level to restore it during teardown.
533
+ self._initial_logger_levels.setdefault(logger, logger_obj.level)
534
+ logger_obj.setLevel(level)
535
+ if self._initial_handler_level is None:
536
+ self._initial_handler_level = self.handler.level
537
+ self.handler.setLevel(level)
538
+ initial_disabled_logging_level = self._force_enable_logging(level, logger_obj)
539
+ if self._initial_disabled_logging_level is None:
540
+ self._initial_disabled_logging_level = initial_disabled_logging_level
541
+
542
+ @contextmanager
543
+ def at_level(
544
+ self, level: Union[int, str], logger: Optional[str] = None
545
+ ) -> Generator[None, None, None]:
546
+ """Context manager that sets the level for capturing of logs. After
547
+ the end of the 'with' statement the level is restored to its original
548
+ value.
549
+
550
+ Will enable the requested logging level if it was disabled via :meth:`logging.disable`.
551
+
552
+ :param level: The level.
553
+ :param logger: The logger to update. If not given, the root logger.
554
+ """
555
+ logger_obj = logging.getLogger(logger)
556
+ orig_level = logger_obj.level
557
+ logger_obj.setLevel(level)
558
+ handler_orig_level = self.handler.level
559
+ self.handler.setLevel(level)
560
+ original_disable_level = self._force_enable_logging(level, logger_obj)
561
+ try:
562
+ yield
563
+ finally:
564
+ logger_obj.setLevel(orig_level)
565
+ self.handler.setLevel(handler_orig_level)
566
+ logging.disable(original_disable_level)
567
+
568
+
569
+ @fixture
570
+ def caplog(request: FixtureRequest) -> Generator[LogCaptureFixture, None, None]:
571
+ """Access and control log capturing.
572
+
573
+ Captured logs are available through the following properties/methods::
574
+
575
+ * caplog.messages -> list of format-interpolated log messages
576
+ * caplog.text -> string containing formatted log output
577
+ * caplog.records -> list of logging.LogRecord instances
578
+ * caplog.record_tuples -> list of (logger_name, level, message) tuples
579
+ * caplog.clear() -> clear captured records and formatted log output string
580
+ """
581
+ result = LogCaptureFixture(request.node, _ispytest=True)
582
+ yield result
583
+ result._finalize()
584
+
585
+
586
+ def get_log_level_for_setting(config: Config, *setting_names: str) -> Optional[int]:
587
+ for setting_name in setting_names:
588
+ log_level = config.getoption(setting_name)
589
+ if log_level is None:
590
+ log_level = config.getini(setting_name)
591
+ if log_level:
592
+ break
593
+ else:
594
+ return None
595
+
596
+ if isinstance(log_level, str):
597
+ log_level = log_level.upper()
598
+ try:
599
+ return int(getattr(logging, log_level, log_level))
600
+ except ValueError as e:
601
+ # Python logging does not recognise this as a logging level
602
+ raise UsageError(
603
+ "'{}' is not recognized as a logging level name for "
604
+ "'{}'. Please consider passing the "
605
+ "logging level num instead.".format(log_level, setting_name)
606
+ ) from e
607
+
608
+
609
+ # run after terminalreporter/capturemanager are configured
610
+ @hookimpl(trylast=True)
611
+ def pytest_configure(config: Config) -> None:
612
+ config.pluginmanager.register(LoggingPlugin(config), "logging-plugin")
613
+
614
+
615
+ class LoggingPlugin:
616
+ """Attaches to the logging module and captures log messages for each test."""
617
+
618
+ def __init__(self, config: Config) -> None:
619
+ """Create a new plugin to capture log messages.
620
+
621
+ The formatter can be safely shared across all handlers so
622
+ create a single one for the entire test session here.
623
+ """
624
+ self._config = config
625
+
626
+ # Report logging.
627
+ self.formatter = self._create_formatter(
628
+ get_option_ini(config, "log_format"),
629
+ get_option_ini(config, "log_date_format"),
630
+ get_option_ini(config, "log_auto_indent"),
631
+ )
632
+ self.log_level = get_log_level_for_setting(config, "log_level")
633
+ self.caplog_handler = LogCaptureHandler()
634
+ self.caplog_handler.setFormatter(self.formatter)
635
+ self.report_handler = LogCaptureHandler()
636
+ self.report_handler.setFormatter(self.formatter)
637
+
638
+ # File logging.
639
+ self.log_file_level = get_log_level_for_setting(config, "log_file_level")
640
+ log_file = get_option_ini(config, "log_file") or os.devnull
641
+ if log_file != os.devnull:
642
+ directory = os.path.dirname(os.path.abspath(log_file))
643
+ if not os.path.isdir(directory):
644
+ os.makedirs(directory)
645
+
646
+ self.log_file_handler = _FileHandler(log_file, mode="w", encoding="UTF-8")
647
+ log_file_format = get_option_ini(config, "log_file_format", "log_format")
648
+ log_file_date_format = get_option_ini(
649
+ config, "log_file_date_format", "log_date_format"
650
+ )
651
+
652
+ log_file_formatter = DatetimeFormatter(
653
+ log_file_format, datefmt=log_file_date_format
654
+ )
655
+ self.log_file_handler.setFormatter(log_file_formatter)
656
+
657
+ # CLI/live logging.
658
+ self.log_cli_level = get_log_level_for_setting(
659
+ config, "log_cli_level", "log_level"
660
+ )
661
+ if self._log_cli_enabled():
662
+ terminal_reporter = config.pluginmanager.get_plugin("terminalreporter")
663
+ # Guaranteed by `_log_cli_enabled()`.
664
+ assert terminal_reporter is not None
665
+ capture_manager = config.pluginmanager.get_plugin("capturemanager")
666
+ # if capturemanager plugin is disabled, live logging still works.
667
+ self.log_cli_handler: Union[
668
+ _LiveLoggingStreamHandler, _LiveLoggingNullHandler
669
+ ] = _LiveLoggingStreamHandler(terminal_reporter, capture_manager)
670
+ else:
671
+ self.log_cli_handler = _LiveLoggingNullHandler()
672
+ log_cli_formatter = self._create_formatter(
673
+ get_option_ini(config, "log_cli_format", "log_format"),
674
+ get_option_ini(config, "log_cli_date_format", "log_date_format"),
675
+ get_option_ini(config, "log_auto_indent"),
676
+ )
677
+ self.log_cli_handler.setFormatter(log_cli_formatter)
678
+ self._disable_loggers(loggers_to_disable=config.option.logger_disable)
679
+
680
+ def _disable_loggers(self, loggers_to_disable: List[str]) -> None:
681
+ if not loggers_to_disable:
682
+ return
683
+
684
+ for name in loggers_to_disable:
685
+ logger = logging.getLogger(name)
686
+ logger.disabled = True
687
+
688
+ def _create_formatter(self, log_format, log_date_format, auto_indent):
689
+ # Color option doesn't exist if terminal plugin is disabled.
690
+ color = getattr(self._config.option, "color", "no")
691
+ if color != "no" and ColoredLevelFormatter.LEVELNAME_FMT_REGEX.search(
692
+ log_format
693
+ ):
694
+ formatter: logging.Formatter = ColoredLevelFormatter(
695
+ create_terminal_writer(self._config), log_format, log_date_format
696
+ )
697
+ else:
698
+ formatter = DatetimeFormatter(log_format, log_date_format)
699
+
700
+ formatter._style = PercentStyleMultiline(
701
+ formatter._style._fmt, auto_indent=auto_indent
702
+ )
703
+
704
+ return formatter
705
+
706
+ def set_log_path(self, fname: str) -> None:
707
+ """Set the filename parameter for Logging.FileHandler().
708
+
709
+ Creates parent directory if it does not exist.
710
+
711
+ .. warning::
712
+ This is an experimental API.
713
+ """
714
+ fpath = Path(fname)
715
+
716
+ if not fpath.is_absolute():
717
+ fpath = self._config.rootpath / fpath
718
+
719
+ if not fpath.parent.exists():
720
+ fpath.parent.mkdir(exist_ok=True, parents=True)
721
+
722
+ # https://github.com/python/mypy/issues/11193
723
+ stream: io.TextIOWrapper = fpath.open(mode="w", encoding="UTF-8") # type: ignore[assignment]
724
+ old_stream = self.log_file_handler.setStream(stream)
725
+ if old_stream:
726
+ old_stream.close()
727
+
728
+ def _log_cli_enabled(self):
729
+ """Return whether live logging is enabled."""
730
+ enabled = self._config.getoption(
731
+ "--log-cli-level"
732
+ ) is not None or self._config.getini("log_cli")
733
+ if not enabled:
734
+ return False
735
+
736
+ terminal_reporter = self._config.pluginmanager.get_plugin("terminalreporter")
737
+ if terminal_reporter is None:
738
+ # terminal reporter is disabled e.g. by pytest-xdist.
739
+ return False
740
+
741
+ return True
742
+
743
+ @hookimpl(hookwrapper=True, tryfirst=True)
744
+ def pytest_sessionstart(self) -> Generator[None, None, None]:
745
+ self.log_cli_handler.set_when("sessionstart")
746
+
747
+ with catching_logs(self.log_cli_handler, level=self.log_cli_level):
748
+ with catching_logs(self.log_file_handler, level=self.log_file_level):
749
+ yield
750
+
751
+ @hookimpl(hookwrapper=True, tryfirst=True)
752
+ def pytest_collection(self) -> Generator[None, None, None]:
753
+ self.log_cli_handler.set_when("collection")
754
+
755
+ with catching_logs(self.log_cli_handler, level=self.log_cli_level):
756
+ with catching_logs(self.log_file_handler, level=self.log_file_level):
757
+ yield
758
+
759
+ @hookimpl(hookwrapper=True)
760
+ def pytest_runtestloop(self, session: Session) -> Generator[None, None, None]:
761
+ if session.config.option.collectonly:
762
+ yield
763
+ return
764
+
765
+ if self._log_cli_enabled() and self._config.getoption("verbose") < 1:
766
+ # The verbose flag is needed to avoid messy test progress output.
767
+ self._config.option.verbose = 1
768
+
769
+ with catching_logs(self.log_cli_handler, level=self.log_cli_level):
770
+ with catching_logs(self.log_file_handler, level=self.log_file_level):
771
+ yield # Run all the tests.
772
+
773
+ @hookimpl
774
+ def pytest_runtest_logstart(self) -> None:
775
+ self.log_cli_handler.reset()
776
+ self.log_cli_handler.set_when("start")
777
+
778
+ @hookimpl
779
+ def pytest_runtest_logreport(self) -> None:
780
+ self.log_cli_handler.set_when("logreport")
781
+
782
+ def _runtest_for(self, item: nodes.Item, when: str) -> Generator[None, None, None]:
783
+ """Implement the internals of the pytest_runtest_xxx() hooks."""
784
+ with catching_logs(
785
+ self.caplog_handler,
786
+ level=self.log_level,
787
+ ) as caplog_handler, catching_logs(
788
+ self.report_handler,
789
+ level=self.log_level,
790
+ ) as report_handler:
791
+ caplog_handler.reset()
792
+ report_handler.reset()
793
+ item.stash[caplog_records_key][when] = caplog_handler.records
794
+ item.stash[caplog_handler_key] = caplog_handler
795
+
796
+ yield
797
+
798
+ log = report_handler.stream.getvalue().strip()
799
+ item.add_report_section(when, "log", log)
800
+
801
+ @hookimpl(hookwrapper=True)
802
+ def pytest_runtest_setup(self, item: nodes.Item) -> Generator[None, None, None]:
803
+ self.log_cli_handler.set_when("setup")
804
+
805
+ empty: Dict[str, List[logging.LogRecord]] = {}
806
+ item.stash[caplog_records_key] = empty
807
+ yield from self._runtest_for(item, "setup")
808
+
809
+ @hookimpl(hookwrapper=True)
810
+ def pytest_runtest_call(self, item: nodes.Item) -> Generator[None, None, None]:
811
+ self.log_cli_handler.set_when("call")
812
+
813
+ yield from self._runtest_for(item, "call")
814
+
815
+ @hookimpl(hookwrapper=True)
816
+ def pytest_runtest_teardown(self, item: nodes.Item) -> Generator[None, None, None]:
817
+ self.log_cli_handler.set_when("teardown")
818
+
819
+ yield from self._runtest_for(item, "teardown")
820
+ del item.stash[caplog_records_key]
821
+ del item.stash[caplog_handler_key]
822
+
823
+ @hookimpl
824
+ def pytest_runtest_logfinish(self) -> None:
825
+ self.log_cli_handler.set_when("finish")
826
+
827
+ @hookimpl(hookwrapper=True, tryfirst=True)
828
+ def pytest_sessionfinish(self) -> Generator[None, None, None]:
829
+ self.log_cli_handler.set_when("sessionfinish")
830
+
831
+ with catching_logs(self.log_cli_handler, level=self.log_cli_level):
832
+ with catching_logs(self.log_file_handler, level=self.log_file_level):
833
+ yield
834
+
835
+ @hookimpl
836
+ def pytest_unconfigure(self) -> None:
837
+ # Close the FileHandler explicitly.
838
+ # (logging.shutdown might have lost the weakref?!)
839
+ self.log_file_handler.close()
840
+
841
+
842
+ class _FileHandler(logging.FileHandler):
843
+ """A logging FileHandler with pytest tweaks."""
844
+
845
+ def handleError(self, record: logging.LogRecord) -> None:
846
+ # Handled by LogCaptureHandler.
847
+ pass
848
+
849
+
850
+ class _LiveLoggingStreamHandler(logging_StreamHandler):
851
+ """A logging StreamHandler used by the live logging feature: it will
852
+ write a newline before the first log message in each test.
853
+
854
+ During live logging we must also explicitly disable stdout/stderr
855
+ capturing otherwise it will get captured and won't appear in the
856
+ terminal.
857
+ """
858
+
859
+ # Officially stream needs to be a IO[str], but TerminalReporter
860
+ # isn't. So force it.
861
+ stream: TerminalReporter = None # type: ignore
862
+
863
+ def __init__(
864
+ self,
865
+ terminal_reporter: TerminalReporter,
866
+ capture_manager: Optional[CaptureManager],
867
+ ) -> None:
868
+ super().__init__(stream=terminal_reporter) # type: ignore[arg-type]
869
+ self.capture_manager = capture_manager
870
+ self.reset()
871
+ self.set_when(None)
872
+ self._test_outcome_written = False
873
+
874
+ def reset(self) -> None:
875
+ """Reset the handler; should be called before the start of each test."""
876
+ self._first_record_emitted = False
877
+
878
+ def set_when(self, when: Optional[str]) -> None:
879
+ """Prepare for the given test phase (setup/call/teardown)."""
880
+ self._when = when
881
+ self._section_name_shown = False
882
+ if when == "start":
883
+ self._test_outcome_written = False
884
+
885
+ def emit(self, record: logging.LogRecord) -> None:
886
+ ctx_manager = (
887
+ self.capture_manager.global_and_fixture_disabled()
888
+ if self.capture_manager
889
+ else nullcontext()
890
+ )
891
+ with ctx_manager:
892
+ if not self._first_record_emitted:
893
+ self.stream.write("\n")
894
+ self._first_record_emitted = True
895
+ elif self._when in ("teardown", "finish"):
896
+ if not self._test_outcome_written:
897
+ self._test_outcome_written = True
898
+ self.stream.write("\n")
899
+ if not self._section_name_shown and self._when:
900
+ self.stream.section("live log " + self._when, sep="-", bold=True)
901
+ self._section_name_shown = True
902
+ super().emit(record)
903
+
904
+ def handleError(self, record: logging.LogRecord) -> None:
905
+ # Handled by LogCaptureHandler.
906
+ pass
907
+
908
+
909
+ class _LiveLoggingNullHandler(logging.NullHandler):
910
+ """A logging handler used when live logging is disabled."""
911
+
912
+ def reset(self) -> None:
913
+ pass
914
+
915
+ def set_when(self, when: str) -> None:
916
+ pass
917
+
918
+ def handleError(self, record: logging.LogRecord) -> None:
919
+ # Handled by LogCaptureHandler.
920
+ pass
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/main.py ADDED
@@ -0,0 +1,913 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Core implementation of the testing process: init, session, runtest loop."""
2
+ import argparse
3
+ import dataclasses
4
+ import fnmatch
5
+ import functools
6
+ import importlib
7
+ import os
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import Callable
11
+ from typing import Dict
12
+ from typing import FrozenSet
13
+ from typing import Iterator
14
+ from typing import List
15
+ from typing import Optional
16
+ from typing import Sequence
17
+ from typing import Set
18
+ from typing import Tuple
19
+ from typing import Type
20
+ from typing import TYPE_CHECKING
21
+ from typing import Union
22
+
23
+ import _pytest._code
24
+ from _pytest import nodes
25
+ from _pytest.compat import final
26
+ from _pytest.compat import overload
27
+ from _pytest.config import Config
28
+ from _pytest.config import directory_arg
29
+ from _pytest.config import ExitCode
30
+ from _pytest.config import hookimpl
31
+ from _pytest.config import PytestPluginManager
32
+ from _pytest.config import UsageError
33
+ from _pytest.config.argparsing import Parser
34
+ from _pytest.fixtures import FixtureManager
35
+ from _pytest.outcomes import exit
36
+ from _pytest.pathlib import absolutepath
37
+ from _pytest.pathlib import bestrelpath
38
+ from _pytest.pathlib import fnmatch_ex
39
+ from _pytest.pathlib import safe_exists
40
+ from _pytest.pathlib import visit
41
+ from _pytest.reports import CollectReport
42
+ from _pytest.reports import TestReport
43
+ from _pytest.runner import collect_one_node
44
+ from _pytest.runner import SetupState
45
+
46
+
47
+ if TYPE_CHECKING:
48
+ from typing_extensions import Literal
49
+
50
+
51
+ def pytest_addoption(parser: Parser) -> None:
52
+ parser.addini(
53
+ "norecursedirs",
54
+ "Directory patterns to avoid for recursion",
55
+ type="args",
56
+ default=[
57
+ "*.egg",
58
+ ".*",
59
+ "_darcs",
60
+ "build",
61
+ "CVS",
62
+ "dist",
63
+ "node_modules",
64
+ "venv",
65
+ "{arch}",
66
+ ],
67
+ )
68
+ parser.addini(
69
+ "testpaths",
70
+ "Directories to search for tests when no files or directories are given on the "
71
+ "command line",
72
+ type="args",
73
+ default=[],
74
+ )
75
+ group = parser.getgroup("general", "Running and selection options")
76
+ group._addoption(
77
+ "-x",
78
+ "--exitfirst",
79
+ action="store_const",
80
+ dest="maxfail",
81
+ const=1,
82
+ help="Exit instantly on first error or failed test",
83
+ )
84
+ group = parser.getgroup("pytest-warnings")
85
+ group.addoption(
86
+ "-W",
87
+ "--pythonwarnings",
88
+ action="append",
89
+ help="Set which warnings to report, see -W option of Python itself",
90
+ )
91
+ parser.addini(
92
+ "filterwarnings",
93
+ type="linelist",
94
+ help="Each line specifies a pattern for "
95
+ "warnings.filterwarnings. "
96
+ "Processed after -W/--pythonwarnings.",
97
+ )
98
+ group._addoption(
99
+ "--maxfail",
100
+ metavar="num",
101
+ action="store",
102
+ type=int,
103
+ dest="maxfail",
104
+ default=0,
105
+ help="Exit after first num failures or errors",
106
+ )
107
+ group._addoption(
108
+ "--strict-config",
109
+ action="store_true",
110
+ help="Any warnings encountered while parsing the `pytest` section of the "
111
+ "configuration file raise errors",
112
+ )
113
+ group._addoption(
114
+ "--strict-markers",
115
+ action="store_true",
116
+ help="Markers not registered in the `markers` section of the configuration "
117
+ "file raise errors",
118
+ )
119
+ group._addoption(
120
+ "--strict",
121
+ action="store_true",
122
+ help="(Deprecated) alias to --strict-markers",
123
+ )
124
+ group._addoption(
125
+ "-c",
126
+ "--config-file",
127
+ metavar="FILE",
128
+ type=str,
129
+ dest="inifilename",
130
+ help="Load configuration from `FILE` instead of trying to locate one of the "
131
+ "implicit configuration files.",
132
+ )
133
+ group._addoption(
134
+ "--continue-on-collection-errors",
135
+ action="store_true",
136
+ default=False,
137
+ dest="continue_on_collection_errors",
138
+ help="Force test execution even if collection errors occur",
139
+ )
140
+ group._addoption(
141
+ "--rootdir",
142
+ action="store",
143
+ dest="rootdir",
144
+ help="Define root directory for tests. Can be relative path: 'root_dir', './root_dir', "
145
+ "'root_dir/another_dir/'; absolute path: '/home/user/root_dir'; path with variables: "
146
+ "'$HOME/root_dir'.",
147
+ )
148
+
149
+ group = parser.getgroup("collect", "collection")
150
+ group.addoption(
151
+ "--collectonly",
152
+ "--collect-only",
153
+ "--co",
154
+ action="store_true",
155
+ help="Only collect tests, don't execute them",
156
+ )
157
+ group.addoption(
158
+ "--pyargs",
159
+ action="store_true",
160
+ help="Try to interpret all arguments as Python packages",
161
+ )
162
+ group.addoption(
163
+ "--ignore",
164
+ action="append",
165
+ metavar="path",
166
+ help="Ignore path during collection (multi-allowed)",
167
+ )
168
+ group.addoption(
169
+ "--ignore-glob",
170
+ action="append",
171
+ metavar="path",
172
+ help="Ignore path pattern during collection (multi-allowed)",
173
+ )
174
+ group.addoption(
175
+ "--deselect",
176
+ action="append",
177
+ metavar="nodeid_prefix",
178
+ help="Deselect item (via node id prefix) during collection (multi-allowed)",
179
+ )
180
+ group.addoption(
181
+ "--confcutdir",
182
+ dest="confcutdir",
183
+ default=None,
184
+ metavar="dir",
185
+ type=functools.partial(directory_arg, optname="--confcutdir"),
186
+ help="Only load conftest.py's relative to specified dir",
187
+ )
188
+ group.addoption(
189
+ "--noconftest",
190
+ action="store_true",
191
+ dest="noconftest",
192
+ default=False,
193
+ help="Don't load any conftest.py files",
194
+ )
195
+ group.addoption(
196
+ "--keepduplicates",
197
+ "--keep-duplicates",
198
+ action="store_true",
199
+ dest="keepduplicates",
200
+ default=False,
201
+ help="Keep duplicate tests",
202
+ )
203
+ group.addoption(
204
+ "--collect-in-virtualenv",
205
+ action="store_true",
206
+ dest="collect_in_virtualenv",
207
+ default=False,
208
+ help="Don't ignore tests in a local virtualenv directory",
209
+ )
210
+ group.addoption(
211
+ "--import-mode",
212
+ default="prepend",
213
+ choices=["prepend", "append", "importlib"],
214
+ dest="importmode",
215
+ help="Prepend/append to sys.path when importing test modules and conftest "
216
+ "files. Default: prepend.",
217
+ )
218
+
219
+ group = parser.getgroup("debugconfig", "test session debugging and configuration")
220
+ group.addoption(
221
+ "--basetemp",
222
+ dest="basetemp",
223
+ default=None,
224
+ type=validate_basetemp,
225
+ metavar="dir",
226
+ help=(
227
+ "Base temporary directory for this test run. "
228
+ "(Warning: this directory is removed if it exists.)"
229
+ ),
230
+ )
231
+
232
+
233
+ def validate_basetemp(path: str) -> str:
234
+ # GH 7119
235
+ msg = "basetemp must not be empty, the current working directory or any parent directory of it"
236
+
237
+ # empty path
238
+ if not path:
239
+ raise argparse.ArgumentTypeError(msg)
240
+
241
+ def is_ancestor(base: Path, query: Path) -> bool:
242
+ """Return whether query is an ancestor of base."""
243
+ if base == query:
244
+ return True
245
+ return query in base.parents
246
+
247
+ # check if path is an ancestor of cwd
248
+ if is_ancestor(Path.cwd(), Path(path).absolute()):
249
+ raise argparse.ArgumentTypeError(msg)
250
+
251
+ # check symlinks for ancestors
252
+ if is_ancestor(Path.cwd().resolve(), Path(path).resolve()):
253
+ raise argparse.ArgumentTypeError(msg)
254
+
255
+ return path
256
+
257
+
258
+ def wrap_session(
259
+ config: Config, doit: Callable[[Config, "Session"], Optional[Union[int, ExitCode]]]
260
+ ) -> Union[int, ExitCode]:
261
+ """Skeleton command line program."""
262
+ session = Session.from_config(config)
263
+ session.exitstatus = ExitCode.OK
264
+ initstate = 0
265
+ try:
266
+ try:
267
+ config._do_configure()
268
+ initstate = 1
269
+ config.hook.pytest_sessionstart(session=session)
270
+ initstate = 2
271
+ session.exitstatus = doit(config, session) or 0
272
+ except UsageError:
273
+ session.exitstatus = ExitCode.USAGE_ERROR
274
+ raise
275
+ except Failed:
276
+ session.exitstatus = ExitCode.TESTS_FAILED
277
+ except (KeyboardInterrupt, exit.Exception):
278
+ excinfo = _pytest._code.ExceptionInfo.from_current()
279
+ exitstatus: Union[int, ExitCode] = ExitCode.INTERRUPTED
280
+ if isinstance(excinfo.value, exit.Exception):
281
+ if excinfo.value.returncode is not None:
282
+ exitstatus = excinfo.value.returncode
283
+ if initstate < 2:
284
+ sys.stderr.write(f"{excinfo.typename}: {excinfo.value.msg}\n")
285
+ config.hook.pytest_keyboard_interrupt(excinfo=excinfo)
286
+ session.exitstatus = exitstatus
287
+ except BaseException:
288
+ session.exitstatus = ExitCode.INTERNAL_ERROR
289
+ excinfo = _pytest._code.ExceptionInfo.from_current()
290
+ try:
291
+ config.notify_exception(excinfo, config.option)
292
+ except exit.Exception as exc:
293
+ if exc.returncode is not None:
294
+ session.exitstatus = exc.returncode
295
+ sys.stderr.write(f"{type(exc).__name__}: {exc}\n")
296
+ else:
297
+ if isinstance(excinfo.value, SystemExit):
298
+ sys.stderr.write("mainloop: caught unexpected SystemExit!\n")
299
+
300
+ finally:
301
+ # Explicitly break reference cycle.
302
+ excinfo = None # type: ignore
303
+ os.chdir(session.startpath)
304
+ if initstate >= 2:
305
+ try:
306
+ config.hook.pytest_sessionfinish(
307
+ session=session, exitstatus=session.exitstatus
308
+ )
309
+ except exit.Exception as exc:
310
+ if exc.returncode is not None:
311
+ session.exitstatus = exc.returncode
312
+ sys.stderr.write(f"{type(exc).__name__}: {exc}\n")
313
+ config._ensure_unconfigure()
314
+ return session.exitstatus
315
+
316
+
317
+ def pytest_cmdline_main(config: Config) -> Union[int, ExitCode]:
318
+ return wrap_session(config, _main)
319
+
320
+
321
+ def _main(config: Config, session: "Session") -> Optional[Union[int, ExitCode]]:
322
+ """Default command line protocol for initialization, session,
323
+ running tests and reporting."""
324
+ config.hook.pytest_collection(session=session)
325
+ config.hook.pytest_runtestloop(session=session)
326
+
327
+ if session.testsfailed:
328
+ return ExitCode.TESTS_FAILED
329
+ elif session.testscollected == 0:
330
+ return ExitCode.NO_TESTS_COLLECTED
331
+ return None
332
+
333
+
334
+ def pytest_collection(session: "Session") -> None:
335
+ session.perform_collect()
336
+
337
+
338
+ def pytest_runtestloop(session: "Session") -> bool:
339
+ if session.testsfailed and not session.config.option.continue_on_collection_errors:
340
+ raise session.Interrupted(
341
+ "%d error%s during collection"
342
+ % (session.testsfailed, "s" if session.testsfailed != 1 else "")
343
+ )
344
+
345
+ if session.config.option.collectonly:
346
+ return True
347
+
348
+ for i, item in enumerate(session.items):
349
+ nextitem = session.items[i + 1] if i + 1 < len(session.items) else None
350
+ item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem)
351
+ if session.shouldfail:
352
+ raise session.Failed(session.shouldfail)
353
+ if session.shouldstop:
354
+ raise session.Interrupted(session.shouldstop)
355
+ return True
356
+
357
+
358
+ def _in_venv(path: Path) -> bool:
359
+ """Attempt to detect if ``path`` is the root of a Virtual Environment by
360
+ checking for the existence of the appropriate activate script."""
361
+ bindir = path.joinpath("Scripts" if sys.platform.startswith("win") else "bin")
362
+ try:
363
+ if not bindir.is_dir():
364
+ return False
365
+ except OSError:
366
+ return False
367
+ activates = (
368
+ "activate",
369
+ "activate.csh",
370
+ "activate.fish",
371
+ "Activate",
372
+ "Activate.bat",
373
+ "Activate.ps1",
374
+ )
375
+ return any(fname.name in activates for fname in bindir.iterdir())
376
+
377
+
378
+ def pytest_ignore_collect(collection_path: Path, config: Config) -> Optional[bool]:
379
+ ignore_paths = config._getconftest_pathlist(
380
+ "collect_ignore", path=collection_path.parent, rootpath=config.rootpath
381
+ )
382
+ ignore_paths = ignore_paths or []
383
+ excludeopt = config.getoption("ignore")
384
+ if excludeopt:
385
+ ignore_paths.extend(absolutepath(x) for x in excludeopt)
386
+
387
+ if collection_path in ignore_paths:
388
+ return True
389
+
390
+ ignore_globs = config._getconftest_pathlist(
391
+ "collect_ignore_glob", path=collection_path.parent, rootpath=config.rootpath
392
+ )
393
+ ignore_globs = ignore_globs or []
394
+ excludeglobopt = config.getoption("ignore_glob")
395
+ if excludeglobopt:
396
+ ignore_globs.extend(absolutepath(x) for x in excludeglobopt)
397
+
398
+ if any(fnmatch.fnmatch(str(collection_path), str(glob)) for glob in ignore_globs):
399
+ return True
400
+
401
+ allow_in_venv = config.getoption("collect_in_virtualenv")
402
+ if not allow_in_venv and _in_venv(collection_path):
403
+ return True
404
+
405
+ if collection_path.is_dir():
406
+ norecursepatterns = config.getini("norecursedirs")
407
+ if any(fnmatch_ex(pat, collection_path) for pat in norecursepatterns):
408
+ return True
409
+
410
+ return None
411
+
412
+
413
+ def pytest_collection_modifyitems(items: List[nodes.Item], config: Config) -> None:
414
+ deselect_prefixes = tuple(config.getoption("deselect") or [])
415
+ if not deselect_prefixes:
416
+ return
417
+
418
+ remaining = []
419
+ deselected = []
420
+ for colitem in items:
421
+ if colitem.nodeid.startswith(deselect_prefixes):
422
+ deselected.append(colitem)
423
+ else:
424
+ remaining.append(colitem)
425
+
426
+ if deselected:
427
+ config.hook.pytest_deselected(items=deselected)
428
+ items[:] = remaining
429
+
430
+
431
+ class FSHookProxy:
432
+ def __init__(self, pm: PytestPluginManager, remove_mods) -> None:
433
+ self.pm = pm
434
+ self.remove_mods = remove_mods
435
+
436
+ def __getattr__(self, name: str):
437
+ x = self.pm.subset_hook_caller(name, remove_plugins=self.remove_mods)
438
+ self.__dict__[name] = x
439
+ return x
440
+
441
+
442
+ class Interrupted(KeyboardInterrupt):
443
+ """Signals that the test run was interrupted."""
444
+
445
+ __module__ = "builtins" # For py3.
446
+
447
+
448
+ class Failed(Exception):
449
+ """Signals a stop as failed test run."""
450
+
451
+
452
+ @dataclasses.dataclass
453
+ class _bestrelpath_cache(Dict[Path, str]):
454
+ __slots__ = ("path",)
455
+
456
+ path: Path
457
+
458
+ def __missing__(self, path: Path) -> str:
459
+ r = bestrelpath(self.path, path)
460
+ self[path] = r
461
+ return r
462
+
463
+
464
+ @final
465
+ class Session(nodes.FSCollector):
466
+ """The root of the collection tree.
467
+
468
+ ``Session`` collects the initial paths given as arguments to pytest.
469
+ """
470
+
471
+ Interrupted = Interrupted
472
+ Failed = Failed
473
+ # Set on the session by runner.pytest_sessionstart.
474
+ _setupstate: SetupState
475
+ # Set on the session by fixtures.pytest_sessionstart.
476
+ _fixturemanager: FixtureManager
477
+ exitstatus: Union[int, ExitCode]
478
+
479
+ def __init__(self, config: Config) -> None:
480
+ super().__init__(
481
+ path=config.rootpath,
482
+ fspath=None,
483
+ parent=None,
484
+ config=config,
485
+ session=self,
486
+ nodeid="",
487
+ )
488
+ self.testsfailed = 0
489
+ self.testscollected = 0
490
+ self.shouldstop: Union[bool, str] = False
491
+ self.shouldfail: Union[bool, str] = False
492
+ self.trace = config.trace.root.get("collection")
493
+ self._initialpaths: FrozenSet[Path] = frozenset()
494
+
495
+ self._bestrelpathcache: Dict[Path, str] = _bestrelpath_cache(config.rootpath)
496
+
497
+ self.config.pluginmanager.register(self, name="session")
498
+
499
+ @classmethod
500
+ def from_config(cls, config: Config) -> "Session":
501
+ session: Session = cls._create(config=config)
502
+ return session
503
+
504
+ def __repr__(self) -> str:
505
+ return "<%s %s exitstatus=%r testsfailed=%d testscollected=%d>" % (
506
+ self.__class__.__name__,
507
+ self.name,
508
+ getattr(self, "exitstatus", "<UNSET>"),
509
+ self.testsfailed,
510
+ self.testscollected,
511
+ )
512
+
513
+ @property
514
+ def startpath(self) -> Path:
515
+ """The path from which pytest was invoked.
516
+
517
+ .. versionadded:: 7.0.0
518
+ """
519
+ return self.config.invocation_params.dir
520
+
521
+ def _node_location_to_relpath(self, node_path: Path) -> str:
522
+ # bestrelpath is a quite slow function.
523
+ return self._bestrelpathcache[node_path]
524
+
525
+ @hookimpl(tryfirst=True)
526
+ def pytest_collectstart(self) -> None:
527
+ if self.shouldfail:
528
+ raise self.Failed(self.shouldfail)
529
+ if self.shouldstop:
530
+ raise self.Interrupted(self.shouldstop)
531
+
532
+ @hookimpl(tryfirst=True)
533
+ def pytest_runtest_logreport(
534
+ self, report: Union[TestReport, CollectReport]
535
+ ) -> None:
536
+ if report.failed and not hasattr(report, "wasxfail"):
537
+ self.testsfailed += 1
538
+ maxfail = self.config.getvalue("maxfail")
539
+ if maxfail and self.testsfailed >= maxfail:
540
+ self.shouldfail = "stopping after %d failures" % (self.testsfailed)
541
+
542
+ pytest_collectreport = pytest_runtest_logreport
543
+
544
+ def isinitpath(self, path: Union[str, "os.PathLike[str]"]) -> bool:
545
+ # Optimization: Path(Path(...)) is much slower than isinstance.
546
+ path_ = path if isinstance(path, Path) else Path(path)
547
+ return path_ in self._initialpaths
548
+
549
+ def gethookproxy(self, fspath: "os.PathLike[str]"):
550
+ # Optimization: Path(Path(...)) is much slower than isinstance.
551
+ path = fspath if isinstance(fspath, Path) else Path(fspath)
552
+ pm = self.config.pluginmanager
553
+ # Check if we have the common case of running
554
+ # hooks with all conftest.py files.
555
+ my_conftestmodules = pm._getconftestmodules(
556
+ path,
557
+ self.config.getoption("importmode"),
558
+ rootpath=self.config.rootpath,
559
+ )
560
+ remove_mods = pm._conftest_plugins.difference(my_conftestmodules)
561
+ if remove_mods:
562
+ # One or more conftests are not in use at this fspath.
563
+ from .config.compat import PathAwareHookProxy
564
+
565
+ proxy = PathAwareHookProxy(FSHookProxy(pm, remove_mods))
566
+ else:
567
+ # All plugins are active for this fspath.
568
+ proxy = self.config.hook
569
+ return proxy
570
+
571
+ def _recurse(self, direntry: "os.DirEntry[str]") -> bool:
572
+ if direntry.name == "__pycache__":
573
+ return False
574
+ fspath = Path(direntry.path)
575
+ ihook = self.gethookproxy(fspath.parent)
576
+ if ihook.pytest_ignore_collect(collection_path=fspath, config=self.config):
577
+ return False
578
+ return True
579
+
580
+ def _collectfile(
581
+ self, fspath: Path, handle_dupes: bool = True
582
+ ) -> Sequence[nodes.Collector]:
583
+ assert (
584
+ fspath.is_file()
585
+ ), "{!r} is not a file (isdir={!r}, exists={!r}, islink={!r})".format(
586
+ fspath, fspath.is_dir(), fspath.exists(), fspath.is_symlink()
587
+ )
588
+ ihook = self.gethookproxy(fspath)
589
+ if not self.isinitpath(fspath):
590
+ if ihook.pytest_ignore_collect(collection_path=fspath, config=self.config):
591
+ return ()
592
+
593
+ if handle_dupes:
594
+ keepduplicates = self.config.getoption("keepduplicates")
595
+ if not keepduplicates:
596
+ duplicate_paths = self.config.pluginmanager._duplicatepaths
597
+ if fspath in duplicate_paths:
598
+ return ()
599
+ else:
600
+ duplicate_paths.add(fspath)
601
+
602
+ return ihook.pytest_collect_file(file_path=fspath, parent=self) # type: ignore[no-any-return]
603
+
604
+ @overload
605
+ def perform_collect(
606
+ self, args: Optional[Sequence[str]] = ..., genitems: "Literal[True]" = ...
607
+ ) -> Sequence[nodes.Item]:
608
+ ...
609
+
610
+ @overload
611
+ def perform_collect( # noqa: F811
612
+ self, args: Optional[Sequence[str]] = ..., genitems: bool = ...
613
+ ) -> Sequence[Union[nodes.Item, nodes.Collector]]:
614
+ ...
615
+
616
+ def perform_collect( # noqa: F811
617
+ self, args: Optional[Sequence[str]] = None, genitems: bool = True
618
+ ) -> Sequence[Union[nodes.Item, nodes.Collector]]:
619
+ """Perform the collection phase for this session.
620
+
621
+ This is called by the default :hook:`pytest_collection` hook
622
+ implementation; see the documentation of this hook for more details.
623
+ For testing purposes, it may also be called directly on a fresh
624
+ ``Session``.
625
+
626
+ This function normally recursively expands any collectors collected
627
+ from the session to their items, and only items are returned. For
628
+ testing purposes, this may be suppressed by passing ``genitems=False``,
629
+ in which case the return value contains these collectors unexpanded,
630
+ and ``session.items`` is empty.
631
+ """
632
+ if args is None:
633
+ args = self.config.args
634
+
635
+ self.trace("perform_collect", self, args)
636
+ self.trace.root.indent += 1
637
+
638
+ self._notfound: List[Tuple[str, Sequence[nodes.Collector]]] = []
639
+ self._initial_parts: List[Tuple[Path, List[str]]] = []
640
+ self.items: List[nodes.Item] = []
641
+
642
+ hook = self.config.hook
643
+
644
+ items: Sequence[Union[nodes.Item, nodes.Collector]] = self.items
645
+ try:
646
+ initialpaths: List[Path] = []
647
+ for arg in args:
648
+ fspath, parts = resolve_collection_argument(
649
+ self.config.invocation_params.dir,
650
+ arg,
651
+ as_pypath=self.config.option.pyargs,
652
+ )
653
+ self._initial_parts.append((fspath, parts))
654
+ initialpaths.append(fspath)
655
+ self._initialpaths = frozenset(initialpaths)
656
+ rep = collect_one_node(self)
657
+ self.ihook.pytest_collectreport(report=rep)
658
+ self.trace.root.indent -= 1
659
+ if self._notfound:
660
+ errors = []
661
+ for arg, collectors in self._notfound:
662
+ if collectors:
663
+ errors.append(
664
+ f"not found: {arg}\n(no name {arg!r} in any of {collectors!r})"
665
+ )
666
+ else:
667
+ errors.append(f"found no collectors for {arg}")
668
+
669
+ raise UsageError(*errors)
670
+ if not genitems:
671
+ items = rep.result
672
+ else:
673
+ if rep.passed:
674
+ for node in rep.result:
675
+ self.items.extend(self.genitems(node))
676
+
677
+ self.config.pluginmanager.check_pending()
678
+ hook.pytest_collection_modifyitems(
679
+ session=self, config=self.config, items=items
680
+ )
681
+ finally:
682
+ hook.pytest_collection_finish(session=self)
683
+
684
+ self.testscollected = len(items)
685
+ return items
686
+
687
+ def collect(self) -> Iterator[Union[nodes.Item, nodes.Collector]]:
688
+ from _pytest.python import Package
689
+
690
+ # Keep track of any collected nodes in here, so we don't duplicate fixtures.
691
+ node_cache1: Dict[Path, Sequence[nodes.Collector]] = {}
692
+ node_cache2: Dict[Tuple[Type[nodes.Collector], Path], nodes.Collector] = {}
693
+
694
+ # Keep track of any collected collectors in matchnodes paths, so they
695
+ # are not collected more than once.
696
+ matchnodes_cache: Dict[Tuple[Type[nodes.Collector], str], CollectReport] = {}
697
+
698
+ # Directories of pkgs with dunder-init files.
699
+ pkg_roots: Dict[Path, Package] = {}
700
+
701
+ for argpath, names in self._initial_parts:
702
+ self.trace("processing argument", (argpath, names))
703
+ self.trace.root.indent += 1
704
+
705
+ # Start with a Session root, and delve to argpath item (dir or file)
706
+ # and stack all Packages found on the way.
707
+ # No point in finding packages when collecting doctests.
708
+ if not self.config.getoption("doctestmodules", False):
709
+ pm = self.config.pluginmanager
710
+ for parent in (argpath, *argpath.parents):
711
+ if not pm._is_in_confcutdir(argpath):
712
+ break
713
+
714
+ if parent.is_dir():
715
+ pkginit = parent / "__init__.py"
716
+ if pkginit.is_file() and pkginit not in node_cache1:
717
+ col = self._collectfile(pkginit, handle_dupes=False)
718
+ if col:
719
+ if isinstance(col[0], Package):
720
+ pkg_roots[parent] = col[0]
721
+ node_cache1[col[0].path] = [col[0]]
722
+
723
+ # If it's a directory argument, recurse and look for any Subpackages.
724
+ # Let the Package collector deal with subnodes, don't collect here.
725
+ if argpath.is_dir():
726
+ assert not names, f"invalid arg {(argpath, names)!r}"
727
+
728
+ seen_dirs: Set[Path] = set()
729
+ for direntry in visit(argpath, self._recurse):
730
+ if not direntry.is_file():
731
+ continue
732
+
733
+ path = Path(direntry.path)
734
+ dirpath = path.parent
735
+
736
+ if dirpath not in seen_dirs:
737
+ # Collect packages first.
738
+ seen_dirs.add(dirpath)
739
+ pkginit = dirpath / "__init__.py"
740
+ if pkginit.exists():
741
+ for x in self._collectfile(pkginit):
742
+ yield x
743
+ if isinstance(x, Package):
744
+ pkg_roots[dirpath] = x
745
+ if dirpath in pkg_roots:
746
+ # Do not collect packages here.
747
+ continue
748
+
749
+ for x in self._collectfile(path):
750
+ key2 = (type(x), x.path)
751
+ if key2 in node_cache2:
752
+ yield node_cache2[key2]
753
+ else:
754
+ node_cache2[key2] = x
755
+ yield x
756
+ else:
757
+ assert argpath.is_file()
758
+
759
+ if argpath in node_cache1:
760
+ col = node_cache1[argpath]
761
+ else:
762
+ collect_root = pkg_roots.get(argpath.parent, self)
763
+ col = collect_root._collectfile(argpath, handle_dupes=False)
764
+ if col:
765
+ node_cache1[argpath] = col
766
+
767
+ matching = []
768
+ work: List[
769
+ Tuple[Sequence[Union[nodes.Item, nodes.Collector]], Sequence[str]]
770
+ ] = [(col, names)]
771
+ while work:
772
+ self.trace("matchnodes", col, names)
773
+ self.trace.root.indent += 1
774
+
775
+ matchnodes, matchnames = work.pop()
776
+ for node in matchnodes:
777
+ if not matchnames:
778
+ matching.append(node)
779
+ continue
780
+ if not isinstance(node, nodes.Collector):
781
+ continue
782
+ key = (type(node), node.nodeid)
783
+ if key in matchnodes_cache:
784
+ rep = matchnodes_cache[key]
785
+ else:
786
+ rep = collect_one_node(node)
787
+ matchnodes_cache[key] = rep
788
+ if rep.passed:
789
+ submatchnodes = []
790
+ for r in rep.result:
791
+ # TODO: Remove parametrized workaround once collection structure contains
792
+ # parametrization.
793
+ if (
794
+ r.name == matchnames[0]
795
+ or r.name.split("[")[0] == matchnames[0]
796
+ ):
797
+ submatchnodes.append(r)
798
+ if submatchnodes:
799
+ work.append((submatchnodes, matchnames[1:]))
800
+ else:
801
+ # Report collection failures here to avoid failing to run some test
802
+ # specified in the command line because the module could not be
803
+ # imported (#134).
804
+ node.ihook.pytest_collectreport(report=rep)
805
+
806
+ self.trace("matchnodes finished -> ", len(matching), "nodes")
807
+ self.trace.root.indent -= 1
808
+
809
+ if not matching:
810
+ report_arg = "::".join((str(argpath), *names))
811
+ self._notfound.append((report_arg, col))
812
+ continue
813
+
814
+ # If __init__.py was the only file requested, then the matched
815
+ # node will be the corresponding Package (by default), and the
816
+ # first yielded item will be the __init__ Module itself, so
817
+ # just use that. If this special case isn't taken, then all the
818
+ # files in the package will be yielded.
819
+ if argpath.name == "__init__.py" and isinstance(matching[0], Package):
820
+ try:
821
+ yield next(iter(matching[0].collect()))
822
+ except StopIteration:
823
+ # The package collects nothing with only an __init__.py
824
+ # file in it, which gets ignored by the default
825
+ # "python_files" option.
826
+ pass
827
+ continue
828
+
829
+ yield from matching
830
+
831
+ self.trace.root.indent -= 1
832
+
833
+ def genitems(
834
+ self, node: Union[nodes.Item, nodes.Collector]
835
+ ) -> Iterator[nodes.Item]:
836
+ self.trace("genitems", node)
837
+ if isinstance(node, nodes.Item):
838
+ node.ihook.pytest_itemcollected(item=node)
839
+ yield node
840
+ else:
841
+ assert isinstance(node, nodes.Collector)
842
+ rep = collect_one_node(node)
843
+ if rep.passed:
844
+ for subnode in rep.result:
845
+ yield from self.genitems(subnode)
846
+ node.ihook.pytest_collectreport(report=rep)
847
+
848
+
849
+ def search_pypath(module_name: str) -> str:
850
+ """Search sys.path for the given a dotted module name, and return its file system path."""
851
+ try:
852
+ spec = importlib.util.find_spec(module_name)
853
+ # AttributeError: looks like package module, but actually filename
854
+ # ImportError: module does not exist
855
+ # ValueError: not a module name
856
+ except (AttributeError, ImportError, ValueError):
857
+ return module_name
858
+ if spec is None or spec.origin is None or spec.origin == "namespace":
859
+ return module_name
860
+ elif spec.submodule_search_locations:
861
+ return os.path.dirname(spec.origin)
862
+ else:
863
+ return spec.origin
864
+
865
+
866
+ def resolve_collection_argument(
867
+ invocation_path: Path, arg: str, *, as_pypath: bool = False
868
+ ) -> Tuple[Path, List[str]]:
869
+ """Parse path arguments optionally containing selection parts and return (fspath, names).
870
+
871
+ Command-line arguments can point to files and/or directories, and optionally contain
872
+ parts for specific tests selection, for example:
873
+
874
+ "pkg/tests/test_foo.py::TestClass::test_foo"
875
+
876
+ This function ensures the path exists, and returns a tuple:
877
+
878
+ (Path("/full/path/to/pkg/tests/test_foo.py"), ["TestClass", "test_foo"])
879
+
880
+ When as_pypath is True, expects that the command-line argument actually contains
881
+ module paths instead of file-system paths:
882
+
883
+ "pkg.tests.test_foo::TestClass::test_foo"
884
+
885
+ In which case we search sys.path for a matching module, and then return the *path* to the
886
+ found module.
887
+
888
+ If the path doesn't exist, raise UsageError.
889
+ If the path is a directory and selection parts are present, raise UsageError.
890
+ """
891
+ base, squacket, rest = str(arg).partition("[")
892
+ strpath, *parts = base.split("::")
893
+ if parts:
894
+ parts[-1] = f"{parts[-1]}{squacket}{rest}"
895
+ if as_pypath:
896
+ strpath = search_pypath(strpath)
897
+ fspath = invocation_path / strpath
898
+ fspath = absolutepath(fspath)
899
+ if not safe_exists(fspath):
900
+ msg = (
901
+ "module or package not found: {arg} (missing __init__.py?)"
902
+ if as_pypath
903
+ else "file or directory not found: {arg}"
904
+ )
905
+ raise UsageError(msg.format(arg=arg))
906
+ if parts and fspath.is_dir():
907
+ msg = (
908
+ "package argument cannot contain :: selection parts: {arg}"
909
+ if as_pypath
910
+ else "directory argument cannot contain :: selection parts: {arg}"
911
+ )
912
+ raise UsageError(msg.format(arg=arg))
913
+ return fspath, parts
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/monkeypatch.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Monkeypatching and mocking functionality."""
2
+ import os
3
+ import re
4
+ import sys
5
+ import warnings
6
+ from contextlib import contextmanager
7
+ from typing import Any
8
+ from typing import Generator
9
+ from typing import List
10
+ from typing import Mapping
11
+ from typing import MutableMapping
12
+ from typing import Optional
13
+ from typing import overload
14
+ from typing import Tuple
15
+ from typing import TypeVar
16
+ from typing import Union
17
+
18
+ from _pytest.compat import final
19
+ from _pytest.fixtures import fixture
20
+ from _pytest.warning_types import PytestWarning
21
+
22
+ RE_IMPORT_ERROR_NAME = re.compile(r"^No module named (.*)$")
23
+
24
+
25
+ K = TypeVar("K")
26
+ V = TypeVar("V")
27
+
28
+
29
+ @fixture
30
+ def monkeypatch() -> Generator["MonkeyPatch", None, None]:
31
+ """A convenient fixture for monkey-patching.
32
+
33
+ The fixture provides these methods to modify objects, dictionaries, or
34
+ :data:`os.environ`:
35
+
36
+ * :meth:`monkeypatch.setattr(obj, name, value, raising=True) <pytest.MonkeyPatch.setattr>`
37
+ * :meth:`monkeypatch.delattr(obj, name, raising=True) <pytest.MonkeyPatch.delattr>`
38
+ * :meth:`monkeypatch.setitem(mapping, name, value) <pytest.MonkeyPatch.setitem>`
39
+ * :meth:`monkeypatch.delitem(obj, name, raising=True) <pytest.MonkeyPatch.delitem>`
40
+ * :meth:`monkeypatch.setenv(name, value, prepend=None) <pytest.MonkeyPatch.setenv>`
41
+ * :meth:`monkeypatch.delenv(name, raising=True) <pytest.MonkeyPatch.delenv>`
42
+ * :meth:`monkeypatch.syspath_prepend(path) <pytest.MonkeyPatch.syspath_prepend>`
43
+ * :meth:`monkeypatch.chdir(path) <pytest.MonkeyPatch.chdir>`
44
+ * :meth:`monkeypatch.context() <pytest.MonkeyPatch.context>`
45
+
46
+ All modifications will be undone after the requesting test function or
47
+ fixture has finished. The ``raising`` parameter determines if a :class:`KeyError`
48
+ or :class:`AttributeError` will be raised if the set/deletion operation does not have the
49
+ specified target.
50
+
51
+ To undo modifications done by the fixture in a contained scope,
52
+ use :meth:`context() <pytest.MonkeyPatch.context>`.
53
+ """
54
+ mpatch = MonkeyPatch()
55
+ yield mpatch
56
+ mpatch.undo()
57
+
58
+
59
+ def resolve(name: str) -> object:
60
+ # Simplified from zope.dottedname.
61
+ parts = name.split(".")
62
+
63
+ used = parts.pop(0)
64
+ found: object = __import__(used)
65
+ for part in parts:
66
+ used += "." + part
67
+ try:
68
+ found = getattr(found, part)
69
+ except AttributeError:
70
+ pass
71
+ else:
72
+ continue
73
+ # We use explicit un-nesting of the handling block in order
74
+ # to avoid nested exceptions.
75
+ try:
76
+ __import__(used)
77
+ except ImportError as ex:
78
+ expected = str(ex).split()[-1]
79
+ if expected == used:
80
+ raise
81
+ else:
82
+ raise ImportError(f"import error in {used}: {ex}") from ex
83
+ found = annotated_getattr(found, part, used)
84
+ return found
85
+
86
+
87
+ def annotated_getattr(obj: object, name: str, ann: str) -> object:
88
+ try:
89
+ obj = getattr(obj, name)
90
+ except AttributeError as e:
91
+ raise AttributeError(
92
+ "{!r} object at {} has no attribute {!r}".format(
93
+ type(obj).__name__, ann, name
94
+ )
95
+ ) from e
96
+ return obj
97
+
98
+
99
+ def derive_importpath(import_path: str, raising: bool) -> Tuple[str, object]:
100
+ if not isinstance(import_path, str) or "." not in import_path:
101
+ raise TypeError(f"must be absolute import path string, not {import_path!r}")
102
+ module, attr = import_path.rsplit(".", 1)
103
+ target = resolve(module)
104
+ if raising:
105
+ annotated_getattr(target, attr, ann=module)
106
+ return attr, target
107
+
108
+
109
+ class Notset:
110
+ def __repr__(self) -> str:
111
+ return "<notset>"
112
+
113
+
114
+ notset = Notset()
115
+
116
+
117
+ @final
118
+ class MonkeyPatch:
119
+ """Helper to conveniently monkeypatch attributes/items/environment
120
+ variables/syspath.
121
+
122
+ Returned by the :fixture:`monkeypatch` fixture.
123
+
124
+ .. versionchanged:: 6.2
125
+ Can now also be used directly as `pytest.MonkeyPatch()`, for when
126
+ the fixture is not available. In this case, use
127
+ :meth:`with MonkeyPatch.context() as mp: <context>` or remember to call
128
+ :meth:`undo` explicitly.
129
+ """
130
+
131
+ def __init__(self) -> None:
132
+ self._setattr: List[Tuple[object, str, object]] = []
133
+ self._setitem: List[Tuple[Mapping[Any, Any], object, object]] = []
134
+ self._cwd: Optional[str] = None
135
+ self._savesyspath: Optional[List[str]] = None
136
+
137
+ @classmethod
138
+ @contextmanager
139
+ def context(cls) -> Generator["MonkeyPatch", None, None]:
140
+ """Context manager that returns a new :class:`MonkeyPatch` object
141
+ which undoes any patching done inside the ``with`` block upon exit.
142
+
143
+ Example:
144
+
145
+ .. code-block:: python
146
+
147
+ import functools
148
+
149
+
150
+ def test_partial(monkeypatch):
151
+ with monkeypatch.context() as m:
152
+ m.setattr(functools, "partial", 3)
153
+
154
+ Useful in situations where it is desired to undo some patches before the test ends,
155
+ such as mocking ``stdlib`` functions that might break pytest itself if mocked (for examples
156
+ of this see :issue:`3290`).
157
+ """
158
+ m = cls()
159
+ try:
160
+ yield m
161
+ finally:
162
+ m.undo()
163
+
164
+ @overload
165
+ def setattr(
166
+ self,
167
+ target: str,
168
+ name: object,
169
+ value: Notset = ...,
170
+ raising: bool = ...,
171
+ ) -> None:
172
+ ...
173
+
174
+ @overload
175
+ def setattr(
176
+ self,
177
+ target: object,
178
+ name: str,
179
+ value: object,
180
+ raising: bool = ...,
181
+ ) -> None:
182
+ ...
183
+
184
+ def setattr(
185
+ self,
186
+ target: Union[str, object],
187
+ name: Union[object, str],
188
+ value: object = notset,
189
+ raising: bool = True,
190
+ ) -> None:
191
+ """
192
+ Set attribute value on target, memorizing the old value.
193
+
194
+ For example:
195
+
196
+ .. code-block:: python
197
+
198
+ import os
199
+
200
+ monkeypatch.setattr(os, "getcwd", lambda: "/")
201
+
202
+ The code above replaces the :func:`os.getcwd` function by a ``lambda`` which
203
+ always returns ``"/"``.
204
+
205
+ For convenience, you can specify a string as ``target`` which
206
+ will be interpreted as a dotted import path, with the last part
207
+ being the attribute name:
208
+
209
+ .. code-block:: python
210
+
211
+ monkeypatch.setattr("os.getcwd", lambda: "/")
212
+
213
+ Raises :class:`AttributeError` if the attribute does not exist, unless
214
+ ``raising`` is set to False.
215
+
216
+ **Where to patch**
217
+
218
+ ``monkeypatch.setattr`` works by (temporarily) changing the object that a name points to with another one.
219
+ There can be many names pointing to any individual object, so for patching to work you must ensure
220
+ that you patch the name used by the system under test.
221
+
222
+ See the section :ref:`Where to patch <python:where-to-patch>` in the :mod:`unittest.mock`
223
+ docs for a complete explanation, which is meant for :func:`unittest.mock.patch` but
224
+ applies to ``monkeypatch.setattr`` as well.
225
+ """
226
+ __tracebackhide__ = True
227
+ import inspect
228
+
229
+ if isinstance(value, Notset):
230
+ if not isinstance(target, str):
231
+ raise TypeError(
232
+ "use setattr(target, name, value) or "
233
+ "setattr(target, value) with target being a dotted "
234
+ "import string"
235
+ )
236
+ value = name
237
+ name, target = derive_importpath(target, raising)
238
+ else:
239
+ if not isinstance(name, str):
240
+ raise TypeError(
241
+ "use setattr(target, name, value) with name being a string or "
242
+ "setattr(target, value) with target being a dotted "
243
+ "import string"
244
+ )
245
+
246
+ oldval = getattr(target, name, notset)
247
+ if raising and oldval is notset:
248
+ raise AttributeError(f"{target!r} has no attribute {name!r}")
249
+
250
+ # avoid class descriptors like staticmethod/classmethod
251
+ if inspect.isclass(target):
252
+ oldval = target.__dict__.get(name, notset)
253
+ self._setattr.append((target, name, oldval))
254
+ setattr(target, name, value)
255
+
256
+ def delattr(
257
+ self,
258
+ target: Union[object, str],
259
+ name: Union[str, Notset] = notset,
260
+ raising: bool = True,
261
+ ) -> None:
262
+ """Delete attribute ``name`` from ``target``.
263
+
264
+ If no ``name`` is specified and ``target`` is a string
265
+ it will be interpreted as a dotted import path with the
266
+ last part being the attribute name.
267
+
268
+ Raises AttributeError it the attribute does not exist, unless
269
+ ``raising`` is set to False.
270
+ """
271
+ __tracebackhide__ = True
272
+ import inspect
273
+
274
+ if isinstance(name, Notset):
275
+ if not isinstance(target, str):
276
+ raise TypeError(
277
+ "use delattr(target, name) or "
278
+ "delattr(target) with target being a dotted "
279
+ "import string"
280
+ )
281
+ name, target = derive_importpath(target, raising)
282
+
283
+ if not hasattr(target, name):
284
+ if raising:
285
+ raise AttributeError(name)
286
+ else:
287
+ oldval = getattr(target, name, notset)
288
+ # Avoid class descriptors like staticmethod/classmethod.
289
+ if inspect.isclass(target):
290
+ oldval = target.__dict__.get(name, notset)
291
+ self._setattr.append((target, name, oldval))
292
+ delattr(target, name)
293
+
294
+ def setitem(self, dic: Mapping[K, V], name: K, value: V) -> None:
295
+ """Set dictionary entry ``name`` to value."""
296
+ self._setitem.append((dic, name, dic.get(name, notset)))
297
+ # Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict
298
+ dic[name] = value # type: ignore[index]
299
+
300
+ def delitem(self, dic: Mapping[K, V], name: K, raising: bool = True) -> None:
301
+ """Delete ``name`` from dict.
302
+
303
+ Raises ``KeyError`` if it doesn't exist, unless ``raising`` is set to
304
+ False.
305
+ """
306
+ if name not in dic:
307
+ if raising:
308
+ raise KeyError(name)
309
+ else:
310
+ self._setitem.append((dic, name, dic.get(name, notset)))
311
+ # Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict
312
+ del dic[name] # type: ignore[attr-defined]
313
+
314
+ def setenv(self, name: str, value: str, prepend: Optional[str] = None) -> None:
315
+ """Set environment variable ``name`` to ``value``.
316
+
317
+ If ``prepend`` is a character, read the current environment variable
318
+ value and prepend the ``value`` adjoined with the ``prepend``
319
+ character.
320
+ """
321
+ if not isinstance(value, str):
322
+ warnings.warn( # type: ignore[unreachable]
323
+ PytestWarning(
324
+ "Value of environment variable {name} type should be str, but got "
325
+ "{value!r} (type: {type}); converted to str implicitly".format(
326
+ name=name, value=value, type=type(value).__name__
327
+ )
328
+ ),
329
+ stacklevel=2,
330
+ )
331
+ value = str(value)
332
+ if prepend and name in os.environ:
333
+ value = value + prepend + os.environ[name]
334
+ self.setitem(os.environ, name, value)
335
+
336
+ def delenv(self, name: str, raising: bool = True) -> None:
337
+ """Delete ``name`` from the environment.
338
+
339
+ Raises ``KeyError`` if it does not exist, unless ``raising`` is set to
340
+ False.
341
+ """
342
+ environ: MutableMapping[str, str] = os.environ
343
+ self.delitem(environ, name, raising=raising)
344
+
345
+ def syspath_prepend(self, path) -> None:
346
+ """Prepend ``path`` to ``sys.path`` list of import locations."""
347
+
348
+ if self._savesyspath is None:
349
+ self._savesyspath = sys.path[:]
350
+ sys.path.insert(0, str(path))
351
+
352
+ # https://github.com/pypa/setuptools/blob/d8b901bc/docs/pkg_resources.txt#L162-L171
353
+ # this is only needed when pkg_resources was already loaded by the namespace package
354
+ if "pkg_resources" in sys.modules:
355
+ from pkg_resources import fixup_namespace_packages
356
+
357
+ fixup_namespace_packages(str(path))
358
+
359
+ # A call to syspathinsert() usually means that the caller wants to
360
+ # import some dynamically created files, thus with python3 we
361
+ # invalidate its import caches.
362
+ # This is especially important when any namespace package is in use,
363
+ # since then the mtime based FileFinder cache (that gets created in
364
+ # this case already) gets not invalidated when writing the new files
365
+ # quickly afterwards.
366
+ from importlib import invalidate_caches
367
+
368
+ invalidate_caches()
369
+
370
+ def chdir(self, path: Union[str, "os.PathLike[str]"]) -> None:
371
+ """Change the current working directory to the specified path.
372
+
373
+ :param path:
374
+ The path to change into.
375
+ """
376
+ if self._cwd is None:
377
+ self._cwd = os.getcwd()
378
+ os.chdir(path)
379
+
380
+ def undo(self) -> None:
381
+ """Undo previous changes.
382
+
383
+ This call consumes the undo stack. Calling it a second time has no
384
+ effect unless you do more monkeypatching after the undo call.
385
+
386
+ There is generally no need to call `undo()`, since it is
387
+ called automatically during tear-down.
388
+
389
+ .. note::
390
+ The same `monkeypatch` fixture is used across a
391
+ single test function invocation. If `monkeypatch` is used both by
392
+ the test function itself and one of the test fixtures,
393
+ calling `undo()` will undo all of the changes made in
394
+ both functions.
395
+
396
+ Prefer to use :meth:`context() <pytest.MonkeyPatch.context>` instead.
397
+ """
398
+ for obj, name, value in reversed(self._setattr):
399
+ if value is not notset:
400
+ setattr(obj, name, value)
401
+ else:
402
+ delattr(obj, name)
403
+ self._setattr[:] = []
404
+ for dictionary, key, value in reversed(self._setitem):
405
+ if value is notset:
406
+ try:
407
+ # Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict
408
+ del dictionary[key] # type: ignore[attr-defined]
409
+ except KeyError:
410
+ pass # Was already deleted, so we have the desired state.
411
+ else:
412
+ # Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict
413
+ dictionary[key] = value # type: ignore[index]
414
+ self._setitem[:] = []
415
+ if self._savesyspath is not None:
416
+ sys.path[:] = self._savesyspath
417
+ self._savesyspath = None
418
+
419
+ if self._cwd is not None:
420
+ os.chdir(self._cwd)
421
+ self._cwd = None
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/nodes.py ADDED
@@ -0,0 +1,783 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import warnings
3
+ from inspect import signature
4
+ from pathlib import Path
5
+ from typing import Any
6
+ from typing import Callable
7
+ from typing import cast
8
+ from typing import Iterable
9
+ from typing import Iterator
10
+ from typing import List
11
+ from typing import MutableMapping
12
+ from typing import Optional
13
+ from typing import overload
14
+ from typing import Set
15
+ from typing import Tuple
16
+ from typing import Type
17
+ from typing import TYPE_CHECKING
18
+ from typing import TypeVar
19
+ from typing import Union
20
+
21
+ import _pytest._code
22
+ from _pytest._code import getfslineno
23
+ from _pytest._code.code import ExceptionInfo
24
+ from _pytest._code.code import TerminalRepr
25
+ from _pytest._code.code import Traceback
26
+ from _pytest.compat import cached_property
27
+ from _pytest.compat import LEGACY_PATH
28
+ from _pytest.config import Config
29
+ from _pytest.config import ConftestImportFailure
30
+ from _pytest.deprecated import FSCOLLECTOR_GETHOOKPROXY_ISINITPATH
31
+ from _pytest.deprecated import NODE_CTOR_FSPATH_ARG
32
+ from _pytest.mark.structures import Mark
33
+ from _pytest.mark.structures import MarkDecorator
34
+ from _pytest.mark.structures import NodeKeywords
35
+ from _pytest.outcomes import fail
36
+ from _pytest.pathlib import absolutepath
37
+ from _pytest.pathlib import commonpath
38
+ from _pytest.stash import Stash
39
+ from _pytest.warning_types import PytestWarning
40
+
41
+ if TYPE_CHECKING:
42
+ # Imported here due to circular import.
43
+ from _pytest.main import Session
44
+ from _pytest._code.code import _TracebackStyle
45
+
46
+
47
+ SEP = "/"
48
+
49
+ tracebackcutdir = Path(_pytest.__file__).parent
50
+
51
+
52
+ def iterparentnodeids(nodeid: str) -> Iterator[str]:
53
+ """Return the parent node IDs of a given node ID, inclusive.
54
+
55
+ For the node ID
56
+
57
+ "testing/code/test_excinfo.py::TestFormattedExcinfo::test_repr_source"
58
+
59
+ the result would be
60
+
61
+ ""
62
+ "testing"
63
+ "testing/code"
64
+ "testing/code/test_excinfo.py"
65
+ "testing/code/test_excinfo.py::TestFormattedExcinfo"
66
+ "testing/code/test_excinfo.py::TestFormattedExcinfo::test_repr_source"
67
+
68
+ Note that / components are only considered until the first ::.
69
+ """
70
+ pos = 0
71
+ first_colons: Optional[int] = nodeid.find("::")
72
+ if first_colons == -1:
73
+ first_colons = None
74
+ # The root Session node - always present.
75
+ yield ""
76
+ # Eagerly consume SEP parts until first colons.
77
+ while True:
78
+ at = nodeid.find(SEP, pos, first_colons)
79
+ if at == -1:
80
+ break
81
+ if at > 0:
82
+ yield nodeid[:at]
83
+ pos = at + len(SEP)
84
+ # Eagerly consume :: parts.
85
+ while True:
86
+ at = nodeid.find("::", pos)
87
+ if at == -1:
88
+ break
89
+ if at > 0:
90
+ yield nodeid[:at]
91
+ pos = at + len("::")
92
+ # The node ID itself.
93
+ if nodeid:
94
+ yield nodeid
95
+
96
+
97
+ def _check_path(path: Path, fspath: LEGACY_PATH) -> None:
98
+ if Path(fspath) != path:
99
+ raise ValueError(
100
+ f"Path({fspath!r}) != {path!r}\n"
101
+ "if both path and fspath are given they need to be equal"
102
+ )
103
+
104
+
105
+ def _imply_path(
106
+ node_type: Type["Node"],
107
+ path: Optional[Path],
108
+ fspath: Optional[LEGACY_PATH],
109
+ ) -> Path:
110
+ if fspath is not None:
111
+ warnings.warn(
112
+ NODE_CTOR_FSPATH_ARG.format(
113
+ node_type_name=node_type.__name__,
114
+ ),
115
+ stacklevel=6,
116
+ )
117
+ if path is not None:
118
+ if fspath is not None:
119
+ _check_path(path, fspath)
120
+ return path
121
+ else:
122
+ assert fspath is not None
123
+ return Path(fspath)
124
+
125
+
126
+ _NodeType = TypeVar("_NodeType", bound="Node")
127
+
128
+
129
+ class NodeMeta(type):
130
+ def __call__(self, *k, **kw):
131
+ msg = (
132
+ "Direct construction of {name} has been deprecated, please use {name}.from_parent.\n"
133
+ "See "
134
+ "https://docs.pytest.org/en/stable/deprecations.html#node-construction-changed-to-node-from-parent"
135
+ " for more details."
136
+ ).format(name=f"{self.__module__}.{self.__name__}")
137
+ fail(msg, pytrace=False)
138
+
139
+ def _create(self, *k, **kw):
140
+ try:
141
+ return super().__call__(*k, **kw)
142
+ except TypeError:
143
+ sig = signature(getattr(self, "__init__"))
144
+ known_kw = {k: v for k, v in kw.items() if k in sig.parameters}
145
+ from .warning_types import PytestDeprecationWarning
146
+
147
+ warnings.warn(
148
+ PytestDeprecationWarning(
149
+ f"{self} is not using a cooperative constructor and only takes {set(known_kw)}.\n"
150
+ "See https://docs.pytest.org/en/stable/deprecations.html"
151
+ "#constructors-of-custom-pytest-node-subclasses-should-take-kwargs "
152
+ "for more details."
153
+ )
154
+ )
155
+
156
+ return super().__call__(*k, **known_kw)
157
+
158
+
159
+ class Node(metaclass=NodeMeta):
160
+ r"""Base class of :class:`Collector` and :class:`Item`, the components of
161
+ the test collection tree.
162
+
163
+ ``Collector``\'s are the internal nodes of the tree, and ``Item``\'s are the
164
+ leaf nodes.
165
+ """
166
+
167
+ # Implemented in the legacypath plugin.
168
+ #: A ``LEGACY_PATH`` copy of the :attr:`path` attribute. Intended for usage
169
+ #: for methods not migrated to ``pathlib.Path`` yet, such as
170
+ #: :meth:`Item.reportinfo`. Will be deprecated in a future release, prefer
171
+ #: using :attr:`path` instead.
172
+ fspath: LEGACY_PATH
173
+
174
+ # Use __slots__ to make attribute access faster.
175
+ # Note that __dict__ is still available.
176
+ __slots__ = (
177
+ "name",
178
+ "parent",
179
+ "config",
180
+ "session",
181
+ "path",
182
+ "_nodeid",
183
+ "_store",
184
+ "__dict__",
185
+ )
186
+
187
+ def __init__(
188
+ self,
189
+ name: str,
190
+ parent: "Optional[Node]" = None,
191
+ config: Optional[Config] = None,
192
+ session: "Optional[Session]" = None,
193
+ fspath: Optional[LEGACY_PATH] = None,
194
+ path: Optional[Path] = None,
195
+ nodeid: Optional[str] = None,
196
+ ) -> None:
197
+ #: A unique name within the scope of the parent node.
198
+ self.name: str = name
199
+
200
+ #: The parent collector node.
201
+ self.parent = parent
202
+
203
+ if config:
204
+ #: The pytest config object.
205
+ self.config: Config = config
206
+ else:
207
+ if not parent:
208
+ raise TypeError("config or parent must be provided")
209
+ self.config = parent.config
210
+
211
+ if session:
212
+ #: The pytest session this node is part of.
213
+ self.session: Session = session
214
+ else:
215
+ if not parent:
216
+ raise TypeError("session or parent must be provided")
217
+ self.session = parent.session
218
+
219
+ if path is None and fspath is None:
220
+ path = getattr(parent, "path", None)
221
+ #: Filesystem path where this node was collected from (can be None).
222
+ self.path: Path = _imply_path(type(self), path, fspath=fspath)
223
+
224
+ # The explicit annotation is to avoid publicly exposing NodeKeywords.
225
+ #: Keywords/markers collected from all scopes.
226
+ self.keywords: MutableMapping[str, Any] = NodeKeywords(self)
227
+
228
+ #: The marker objects belonging to this node.
229
+ self.own_markers: List[Mark] = []
230
+
231
+ #: Allow adding of extra keywords to use for matching.
232
+ self.extra_keyword_matches: Set[str] = set()
233
+
234
+ if nodeid is not None:
235
+ assert "::()" not in nodeid
236
+ self._nodeid = nodeid
237
+ else:
238
+ if not self.parent:
239
+ raise TypeError("nodeid or parent must be provided")
240
+ self._nodeid = self.parent.nodeid + "::" + self.name
241
+
242
+ #: A place where plugins can store information on the node for their
243
+ #: own use.
244
+ self.stash: Stash = Stash()
245
+ # Deprecated alias. Was never public. Can be removed in a few releases.
246
+ self._store = self.stash
247
+
248
+ @classmethod
249
+ def from_parent(cls, parent: "Node", **kw):
250
+ """Public constructor for Nodes.
251
+
252
+ This indirection got introduced in order to enable removing
253
+ the fragile logic from the node constructors.
254
+
255
+ Subclasses can use ``super().from_parent(...)`` when overriding the
256
+ construction.
257
+
258
+ :param parent: The parent node of this Node.
259
+ """
260
+ if "config" in kw:
261
+ raise TypeError("config is not a valid argument for from_parent")
262
+ if "session" in kw:
263
+ raise TypeError("session is not a valid argument for from_parent")
264
+ return cls._create(parent=parent, **kw)
265
+
266
+ @property
267
+ def ihook(self):
268
+ """fspath-sensitive hook proxy used to call pytest hooks."""
269
+ return self.session.gethookproxy(self.path)
270
+
271
+ def __repr__(self) -> str:
272
+ return "<{} {}>".format(self.__class__.__name__, getattr(self, "name", None))
273
+
274
+ def warn(self, warning: Warning) -> None:
275
+ """Issue a warning for this Node.
276
+
277
+ Warnings will be displayed after the test session, unless explicitly suppressed.
278
+
279
+ :param Warning warning:
280
+ The warning instance to issue.
281
+
282
+ :raises ValueError: If ``warning`` instance is not a subclass of Warning.
283
+
284
+ Example usage:
285
+
286
+ .. code-block:: python
287
+
288
+ node.warn(PytestWarning("some message"))
289
+ node.warn(UserWarning("some message"))
290
+
291
+ .. versionchanged:: 6.2
292
+ Any subclass of :class:`Warning` is now accepted, rather than only
293
+ :class:`PytestWarning <pytest.PytestWarning>` subclasses.
294
+ """
295
+ # enforce type checks here to avoid getting a generic type error later otherwise.
296
+ if not isinstance(warning, Warning):
297
+ raise ValueError(
298
+ "warning must be an instance of Warning or subclass, got {!r}".format(
299
+ warning
300
+ )
301
+ )
302
+ path, lineno = get_fslocation_from_item(self)
303
+ assert lineno is not None
304
+ warnings.warn_explicit(
305
+ warning,
306
+ category=None,
307
+ filename=str(path),
308
+ lineno=lineno + 1,
309
+ )
310
+
311
+ # Methods for ordering nodes.
312
+
313
+ @property
314
+ def nodeid(self) -> str:
315
+ """A ::-separated string denoting its collection tree address."""
316
+ return self._nodeid
317
+
318
+ def __hash__(self) -> int:
319
+ return hash(self._nodeid)
320
+
321
+ def setup(self) -> None:
322
+ pass
323
+
324
+ def teardown(self) -> None:
325
+ pass
326
+
327
+ def listchain(self) -> List["Node"]:
328
+ """Return list of all parent collectors up to self, starting from
329
+ the root of collection tree.
330
+
331
+ :returns: The nodes.
332
+ """
333
+ chain = []
334
+ item: Optional[Node] = self
335
+ while item is not None:
336
+ chain.append(item)
337
+ item = item.parent
338
+ chain.reverse()
339
+ return chain
340
+
341
+ def add_marker(
342
+ self, marker: Union[str, MarkDecorator], append: bool = True
343
+ ) -> None:
344
+ """Dynamically add a marker object to the node.
345
+
346
+ :param marker:
347
+ The marker.
348
+ :param append:
349
+ Whether to append the marker, or prepend it.
350
+ """
351
+ from _pytest.mark import MARK_GEN
352
+
353
+ if isinstance(marker, MarkDecorator):
354
+ marker_ = marker
355
+ elif isinstance(marker, str):
356
+ marker_ = getattr(MARK_GEN, marker)
357
+ else:
358
+ raise ValueError("is not a string or pytest.mark.* Marker")
359
+ self.keywords[marker_.name] = marker_
360
+ if append:
361
+ self.own_markers.append(marker_.mark)
362
+ else:
363
+ self.own_markers.insert(0, marker_.mark)
364
+
365
+ def iter_markers(self, name: Optional[str] = None) -> Iterator[Mark]:
366
+ """Iterate over all markers of the node.
367
+
368
+ :param name: If given, filter the results by the name attribute.
369
+ :returns: An iterator of the markers of the node.
370
+ """
371
+ return (x[1] for x in self.iter_markers_with_node(name=name))
372
+
373
+ def iter_markers_with_node(
374
+ self, name: Optional[str] = None
375
+ ) -> Iterator[Tuple["Node", Mark]]:
376
+ """Iterate over all markers of the node.
377
+
378
+ :param name: If given, filter the results by the name attribute.
379
+ :returns: An iterator of (node, mark) tuples.
380
+ """
381
+ for node in reversed(self.listchain()):
382
+ for mark in node.own_markers:
383
+ if name is None or getattr(mark, "name", None) == name:
384
+ yield node, mark
385
+
386
+ @overload
387
+ def get_closest_marker(self, name: str) -> Optional[Mark]:
388
+ ...
389
+
390
+ @overload
391
+ def get_closest_marker(self, name: str, default: Mark) -> Mark:
392
+ ...
393
+
394
+ def get_closest_marker(
395
+ self, name: str, default: Optional[Mark] = None
396
+ ) -> Optional[Mark]:
397
+ """Return the first marker matching the name, from closest (for
398
+ example function) to farther level (for example module level).
399
+
400
+ :param default: Fallback return value if no marker was found.
401
+ :param name: Name to filter by.
402
+ """
403
+ return next(self.iter_markers(name=name), default)
404
+
405
+ def listextrakeywords(self) -> Set[str]:
406
+ """Return a set of all extra keywords in self and any parents."""
407
+ extra_keywords: Set[str] = set()
408
+ for item in self.listchain():
409
+ extra_keywords.update(item.extra_keyword_matches)
410
+ return extra_keywords
411
+
412
+ def listnames(self) -> List[str]:
413
+ return [x.name for x in self.listchain()]
414
+
415
+ def addfinalizer(self, fin: Callable[[], object]) -> None:
416
+ """Register a function to be called without arguments when this node is
417
+ finalized.
418
+
419
+ This method can only be called when this node is active
420
+ in a setup chain, for example during self.setup().
421
+ """
422
+ self.session._setupstate.addfinalizer(fin, self)
423
+
424
+ def getparent(self, cls: Type[_NodeType]) -> Optional[_NodeType]:
425
+ """Get the next parent node (including self) which is an instance of
426
+ the given class.
427
+
428
+ :param cls: The node class to search for.
429
+ :returns: The node, if found.
430
+ """
431
+ current: Optional[Node] = self
432
+ while current and not isinstance(current, cls):
433
+ current = current.parent
434
+ assert current is None or isinstance(current, cls)
435
+ return current
436
+
437
+ def _traceback_filter(self, excinfo: ExceptionInfo[BaseException]) -> Traceback:
438
+ return excinfo.traceback
439
+
440
+ def _repr_failure_py(
441
+ self,
442
+ excinfo: ExceptionInfo[BaseException],
443
+ style: "Optional[_TracebackStyle]" = None,
444
+ ) -> TerminalRepr:
445
+ from _pytest.fixtures import FixtureLookupError
446
+
447
+ if isinstance(excinfo.value, ConftestImportFailure):
448
+ excinfo = ExceptionInfo.from_exc_info(excinfo.value.excinfo)
449
+ if isinstance(excinfo.value, fail.Exception):
450
+ if not excinfo.value.pytrace:
451
+ style = "value"
452
+ if isinstance(excinfo.value, FixtureLookupError):
453
+ return excinfo.value.formatrepr()
454
+
455
+ tbfilter: Union[bool, Callable[[ExceptionInfo[BaseException]], Traceback]]
456
+ if self.config.getoption("fulltrace", False):
457
+ style = "long"
458
+ tbfilter = False
459
+ else:
460
+ tbfilter = self._traceback_filter
461
+ if style == "auto":
462
+ style = "long"
463
+ # XXX should excinfo.getrepr record all data and toterminal() process it?
464
+ if style is None:
465
+ if self.config.getoption("tbstyle", "auto") == "short":
466
+ style = "short"
467
+ else:
468
+ style = "long"
469
+
470
+ if self.config.getoption("verbose", 0) > 1:
471
+ truncate_locals = False
472
+ else:
473
+ truncate_locals = True
474
+
475
+ # excinfo.getrepr() formats paths relative to the CWD if `abspath` is False.
476
+ # It is possible for a fixture/test to change the CWD while this code runs, which
477
+ # would then result in the user seeing confusing paths in the failure message.
478
+ # To fix this, if the CWD changed, always display the full absolute path.
479
+ # It will be better to just always display paths relative to invocation_dir, but
480
+ # this requires a lot of plumbing (#6428).
481
+ try:
482
+ abspath = Path(os.getcwd()) != self.config.invocation_params.dir
483
+ except OSError:
484
+ abspath = True
485
+
486
+ return excinfo.getrepr(
487
+ funcargs=True,
488
+ abspath=abspath,
489
+ showlocals=self.config.getoption("showlocals", False),
490
+ style=style,
491
+ tbfilter=tbfilter,
492
+ truncate_locals=truncate_locals,
493
+ )
494
+
495
+ def repr_failure(
496
+ self,
497
+ excinfo: ExceptionInfo[BaseException],
498
+ style: "Optional[_TracebackStyle]" = None,
499
+ ) -> Union[str, TerminalRepr]:
500
+ """Return a representation of a collection or test failure.
501
+
502
+ .. seealso:: :ref:`non-python tests`
503
+
504
+ :param excinfo: Exception information for the failure.
505
+ """
506
+ return self._repr_failure_py(excinfo, style)
507
+
508
+
509
+ def get_fslocation_from_item(node: "Node") -> Tuple[Union[str, Path], Optional[int]]:
510
+ """Try to extract the actual location from a node, depending on available attributes:
511
+
512
+ * "location": a pair (path, lineno)
513
+ * "obj": a Python object that the node wraps.
514
+ * "fspath": just a path
515
+
516
+ :rtype: A tuple of (str|Path, int) with filename and 0-based line number.
517
+ """
518
+ # See Item.location.
519
+ location: Optional[Tuple[str, Optional[int], str]] = getattr(node, "location", None)
520
+ if location is not None:
521
+ return location[:2]
522
+ obj = getattr(node, "obj", None)
523
+ if obj is not None:
524
+ return getfslineno(obj)
525
+ return getattr(node, "fspath", "unknown location"), -1
526
+
527
+
528
+ class Collector(Node):
529
+ """Base class of all collectors.
530
+
531
+ Collector create children through `collect()` and thus iteratively build
532
+ the collection tree.
533
+ """
534
+
535
+ class CollectError(Exception):
536
+ """An error during collection, contains a custom message."""
537
+
538
+ def collect(self) -> Iterable[Union["Item", "Collector"]]:
539
+ """Collect children (items and collectors) for this collector."""
540
+ raise NotImplementedError("abstract")
541
+
542
+ # TODO: This omits the style= parameter which breaks Liskov Substitution.
543
+ def repr_failure( # type: ignore[override]
544
+ self, excinfo: ExceptionInfo[BaseException]
545
+ ) -> Union[str, TerminalRepr]:
546
+ """Return a representation of a collection failure.
547
+
548
+ :param excinfo: Exception information for the failure.
549
+ """
550
+ if isinstance(excinfo.value, self.CollectError) and not self.config.getoption(
551
+ "fulltrace", False
552
+ ):
553
+ exc = excinfo.value
554
+ return str(exc.args[0])
555
+
556
+ # Respect explicit tbstyle option, but default to "short"
557
+ # (_repr_failure_py uses "long" with "fulltrace" option always).
558
+ tbstyle = self.config.getoption("tbstyle", "auto")
559
+ if tbstyle == "auto":
560
+ tbstyle = "short"
561
+
562
+ return self._repr_failure_py(excinfo, style=tbstyle)
563
+
564
+ def _traceback_filter(self, excinfo: ExceptionInfo[BaseException]) -> Traceback:
565
+ if hasattr(self, "path"):
566
+ traceback = excinfo.traceback
567
+ ntraceback = traceback.cut(path=self.path)
568
+ if ntraceback == traceback:
569
+ ntraceback = ntraceback.cut(excludepath=tracebackcutdir)
570
+ return excinfo.traceback.filter(excinfo)
571
+ return excinfo.traceback
572
+
573
+
574
+ def _check_initialpaths_for_relpath(session: "Session", path: Path) -> Optional[str]:
575
+ for initial_path in session._initialpaths:
576
+ if commonpath(path, initial_path) == initial_path:
577
+ rel = str(path.relative_to(initial_path))
578
+ return "" if rel == "." else rel
579
+ return None
580
+
581
+
582
+ class FSCollector(Collector):
583
+ """Base class for filesystem collectors."""
584
+
585
+ def __init__(
586
+ self,
587
+ fspath: Optional[LEGACY_PATH] = None,
588
+ path_or_parent: Optional[Union[Path, Node]] = None,
589
+ path: Optional[Path] = None,
590
+ name: Optional[str] = None,
591
+ parent: Optional[Node] = None,
592
+ config: Optional[Config] = None,
593
+ session: Optional["Session"] = None,
594
+ nodeid: Optional[str] = None,
595
+ ) -> None:
596
+ if path_or_parent:
597
+ if isinstance(path_or_parent, Node):
598
+ assert parent is None
599
+ parent = cast(FSCollector, path_or_parent)
600
+ elif isinstance(path_or_parent, Path):
601
+ assert path is None
602
+ path = path_or_parent
603
+
604
+ path = _imply_path(type(self), path, fspath=fspath)
605
+ if name is None:
606
+ name = path.name
607
+ if parent is not None and parent.path != path:
608
+ try:
609
+ rel = path.relative_to(parent.path)
610
+ except ValueError:
611
+ pass
612
+ else:
613
+ name = str(rel)
614
+ name = name.replace(os.sep, SEP)
615
+ self.path = path
616
+
617
+ if session is None:
618
+ assert parent is not None
619
+ session = parent.session
620
+
621
+ if nodeid is None:
622
+ try:
623
+ nodeid = str(self.path.relative_to(session.config.rootpath))
624
+ except ValueError:
625
+ nodeid = _check_initialpaths_for_relpath(session, path)
626
+
627
+ if nodeid and os.sep != SEP:
628
+ nodeid = nodeid.replace(os.sep, SEP)
629
+
630
+ super().__init__(
631
+ name=name,
632
+ parent=parent,
633
+ config=config,
634
+ session=session,
635
+ nodeid=nodeid,
636
+ path=path,
637
+ )
638
+
639
+ @classmethod
640
+ def from_parent(
641
+ cls,
642
+ parent,
643
+ *,
644
+ fspath: Optional[LEGACY_PATH] = None,
645
+ path: Optional[Path] = None,
646
+ **kw,
647
+ ):
648
+ """The public constructor."""
649
+ return super().from_parent(parent=parent, fspath=fspath, path=path, **kw)
650
+
651
+ def gethookproxy(self, fspath: "os.PathLike[str]"):
652
+ warnings.warn(FSCOLLECTOR_GETHOOKPROXY_ISINITPATH, stacklevel=2)
653
+ return self.session.gethookproxy(fspath)
654
+
655
+ def isinitpath(self, path: Union[str, "os.PathLike[str]"]) -> bool:
656
+ warnings.warn(FSCOLLECTOR_GETHOOKPROXY_ISINITPATH, stacklevel=2)
657
+ return self.session.isinitpath(path)
658
+
659
+
660
+ class File(FSCollector):
661
+ """Base class for collecting tests from a file.
662
+
663
+ :ref:`non-python tests`.
664
+ """
665
+
666
+
667
+ class Item(Node):
668
+ """Base class of all test invocation items.
669
+
670
+ Note that for a single function there might be multiple test invocation items.
671
+ """
672
+
673
+ nextitem = None
674
+
675
+ def __init__(
676
+ self,
677
+ name,
678
+ parent=None,
679
+ config: Optional[Config] = None,
680
+ session: Optional["Session"] = None,
681
+ nodeid: Optional[str] = None,
682
+ **kw,
683
+ ) -> None:
684
+ # The first two arguments are intentionally passed positionally,
685
+ # to keep plugins who define a node type which inherits from
686
+ # (pytest.Item, pytest.File) working (see issue #8435).
687
+ # They can be made kwargs when the deprecation above is done.
688
+ super().__init__(
689
+ name,
690
+ parent,
691
+ config=config,
692
+ session=session,
693
+ nodeid=nodeid,
694
+ **kw,
695
+ )
696
+ self._report_sections: List[Tuple[str, str, str]] = []
697
+
698
+ #: A list of tuples (name, value) that holds user defined properties
699
+ #: for this test.
700
+ self.user_properties: List[Tuple[str, object]] = []
701
+
702
+ self._check_item_and_collector_diamond_inheritance()
703
+
704
+ def _check_item_and_collector_diamond_inheritance(self) -> None:
705
+ """
706
+ Check if the current type inherits from both File and Collector
707
+ at the same time, emitting a warning accordingly (#8447).
708
+ """
709
+ cls = type(self)
710
+
711
+ # We inject an attribute in the type to avoid issuing this warning
712
+ # for the same class more than once, which is not helpful.
713
+ # It is a hack, but was deemed acceptable in order to avoid
714
+ # flooding the user in the common case.
715
+ attr_name = "_pytest_diamond_inheritance_warning_shown"
716
+ if getattr(cls, attr_name, False):
717
+ return
718
+ setattr(cls, attr_name, True)
719
+
720
+ problems = ", ".join(
721
+ base.__name__ for base in cls.__bases__ if issubclass(base, Collector)
722
+ )
723
+ if problems:
724
+ warnings.warn(
725
+ f"{cls.__name__} is an Item subclass and should not be a collector, "
726
+ f"however its bases {problems} are collectors.\n"
727
+ "Please split the Collectors and the Item into separate node types.\n"
728
+ "Pytest Doc example: https://docs.pytest.org/en/latest/example/nonpython.html\n"
729
+ "example pull request on a plugin: https://github.com/asmeurer/pytest-flakes/pull/40/",
730
+ PytestWarning,
731
+ )
732
+
733
+ def runtest(self) -> None:
734
+ """Run the test case for this item.
735
+
736
+ Must be implemented by subclasses.
737
+
738
+ .. seealso:: :ref:`non-python tests`
739
+ """
740
+ raise NotImplementedError("runtest must be implemented by Item subclass")
741
+
742
+ def add_report_section(self, when: str, key: str, content: str) -> None:
743
+ """Add a new report section, similar to what's done internally to add
744
+ stdout and stderr captured output::
745
+
746
+ item.add_report_section("call", "stdout", "report section contents")
747
+
748
+ :param str when:
749
+ One of the possible capture states, ``"setup"``, ``"call"``, ``"teardown"``.
750
+ :param str key:
751
+ Name of the section, can be customized at will. Pytest uses ``"stdout"`` and
752
+ ``"stderr"`` internally.
753
+ :param str content:
754
+ The full contents as a string.
755
+ """
756
+ if content:
757
+ self._report_sections.append((when, key, content))
758
+
759
+ def reportinfo(self) -> Tuple[Union["os.PathLike[str]", str], Optional[int], str]:
760
+ """Get location information for this item for test reports.
761
+
762
+ Returns a tuple with three elements:
763
+
764
+ - The path of the test (default ``self.path``)
765
+ - The 0-based line number of the test (default ``None``)
766
+ - A name of the test to be shown (default ``""``)
767
+
768
+ .. seealso:: :ref:`non-python tests`
769
+ """
770
+ return self.path, None, ""
771
+
772
+ @cached_property
773
+ def location(self) -> Tuple[str, Optional[int], str]:
774
+ """
775
+ Returns a tuple of ``(relfspath, lineno, testname)`` for this item
776
+ where ``relfspath`` is file path relative to ``config.rootpath``
777
+ and lineno is a 0-based line number.
778
+ """
779
+ location = self.reportinfo()
780
+ path = absolutepath(os.fspath(location[0]))
781
+ relfspath = self.session._node_location_to_relpath(path)
782
+ assert type(location[2]) is str
783
+ return (relfspath, location[1], location[2])
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/nose.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run testsuites written for nose."""
2
+ import warnings
3
+
4
+ from _pytest.config import hookimpl
5
+ from _pytest.deprecated import NOSE_SUPPORT
6
+ from _pytest.fixtures import getfixturemarker
7
+ from _pytest.nodes import Item
8
+ from _pytest.python import Function
9
+ from _pytest.unittest import TestCaseFunction
10
+
11
+
12
+ @hookimpl(trylast=True)
13
+ def pytest_runtest_setup(item: Item) -> None:
14
+ if not isinstance(item, Function):
15
+ return
16
+ # Don't do nose style setup/teardown on direct unittest style classes.
17
+ if isinstance(item, TestCaseFunction):
18
+ return
19
+
20
+ # Capture the narrowed type of item for the teardown closure,
21
+ # see https://github.com/python/mypy/issues/2608
22
+ func = item
23
+
24
+ call_optional(func.obj, "setup", func.nodeid)
25
+ func.addfinalizer(lambda: call_optional(func.obj, "teardown", func.nodeid))
26
+
27
+ # NOTE: Module- and class-level fixtures are handled in python.py
28
+ # with `pluginmanager.has_plugin("nose")` checks.
29
+ # It would have been nicer to implement them outside of core, but
30
+ # it's not straightforward.
31
+
32
+
33
+ def call_optional(obj: object, name: str, nodeid: str) -> bool:
34
+ method = getattr(obj, name, None)
35
+ if method is None:
36
+ return False
37
+ is_fixture = getfixturemarker(method) is not None
38
+ if is_fixture:
39
+ return False
40
+ if not callable(method):
41
+ return False
42
+ # Warn about deprecation of this plugin.
43
+ method_name = getattr(method, "__name__", str(method))
44
+ warnings.warn(
45
+ NOSE_SUPPORT.format(nodeid=nodeid, method=method_name, stage=name), stacklevel=2
46
+ )
47
+ # If there are any problems allow the exception to raise rather than
48
+ # silently ignoring it.
49
+ method()
50
+ return True
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/outcomes.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exception classes and constants handling test outcomes as well as
2
+ functions creating them."""
3
+ import sys
4
+ import warnings
5
+ from typing import Any
6
+ from typing import Callable
7
+ from typing import cast
8
+ from typing import NoReturn
9
+ from typing import Optional
10
+ from typing import Type
11
+ from typing import TypeVar
12
+
13
+ from _pytest.deprecated import KEYWORD_MSG_ARG
14
+
15
+ TYPE_CHECKING = False # Avoid circular import through compat.
16
+
17
+ if TYPE_CHECKING:
18
+ from typing_extensions import Protocol
19
+ else:
20
+ # typing.Protocol is only available starting from Python 3.8. It is also
21
+ # available from typing_extensions, but we don't want a runtime dependency
22
+ # on that. So use a dummy runtime implementation.
23
+ from typing import Generic
24
+
25
+ Protocol = Generic
26
+
27
+
28
+ class OutcomeException(BaseException):
29
+ """OutcomeException and its subclass instances indicate and contain info
30
+ about test and collection outcomes."""
31
+
32
+ def __init__(self, msg: Optional[str] = None, pytrace: bool = True) -> None:
33
+ if msg is not None and not isinstance(msg, str):
34
+ error_msg = ( # type: ignore[unreachable]
35
+ "{} expected string as 'msg' parameter, got '{}' instead.\n"
36
+ "Perhaps you meant to use a mark?"
37
+ )
38
+ raise TypeError(error_msg.format(type(self).__name__, type(msg).__name__))
39
+ super().__init__(msg)
40
+ self.msg = msg
41
+ self.pytrace = pytrace
42
+
43
+ def __repr__(self) -> str:
44
+ if self.msg is not None:
45
+ return self.msg
46
+ return f"<{self.__class__.__name__} instance>"
47
+
48
+ __str__ = __repr__
49
+
50
+
51
+ TEST_OUTCOME = (OutcomeException, Exception)
52
+
53
+
54
+ class Skipped(OutcomeException):
55
+ # XXX hackish: on 3k we fake to live in the builtins
56
+ # in order to have Skipped exception printing shorter/nicer
57
+ __module__ = "builtins"
58
+
59
+ def __init__(
60
+ self,
61
+ msg: Optional[str] = None,
62
+ pytrace: bool = True,
63
+ allow_module_level: bool = False,
64
+ *,
65
+ _use_item_location: bool = False,
66
+ ) -> None:
67
+ super().__init__(msg=msg, pytrace=pytrace)
68
+ self.allow_module_level = allow_module_level
69
+ # If true, the skip location is reported as the item's location,
70
+ # instead of the place that raises the exception/calls skip().
71
+ self._use_item_location = _use_item_location
72
+
73
+
74
+ class Failed(OutcomeException):
75
+ """Raised from an explicit call to pytest.fail()."""
76
+
77
+ __module__ = "builtins"
78
+
79
+
80
+ class Exit(Exception):
81
+ """Raised for immediate program exits (no tracebacks/summaries)."""
82
+
83
+ def __init__(
84
+ self, msg: str = "unknown reason", returncode: Optional[int] = None
85
+ ) -> None:
86
+ self.msg = msg
87
+ self.returncode = returncode
88
+ super().__init__(msg)
89
+
90
+
91
+ # Elaborate hack to work around https://github.com/python/mypy/issues/2087.
92
+ # Ideally would just be `exit.Exception = Exit` etc.
93
+
94
+ _F = TypeVar("_F", bound=Callable[..., object])
95
+ _ET = TypeVar("_ET", bound=Type[BaseException])
96
+
97
+
98
+ class _WithException(Protocol[_F, _ET]):
99
+ Exception: _ET
100
+ __call__: _F
101
+
102
+
103
+ def _with_exception(exception_type: _ET) -> Callable[[_F], _WithException[_F, _ET]]:
104
+ def decorate(func: _F) -> _WithException[_F, _ET]:
105
+ func_with_exception = cast(_WithException[_F, _ET], func)
106
+ func_with_exception.Exception = exception_type
107
+ return func_with_exception
108
+
109
+ return decorate
110
+
111
+
112
+ # Exposed helper methods.
113
+
114
+
115
+ @_with_exception(Exit)
116
+ def exit(
117
+ reason: str = "", returncode: Optional[int] = None, *, msg: Optional[str] = None
118
+ ) -> NoReturn:
119
+ """Exit testing process.
120
+
121
+ :param reason:
122
+ The message to show as the reason for exiting pytest. reason has a default value
123
+ only because `msg` is deprecated.
124
+
125
+ :param returncode:
126
+ Return code to be used when exiting pytest.
127
+
128
+ :param msg:
129
+ Same as ``reason``, but deprecated. Will be removed in a future version, use ``reason`` instead.
130
+ """
131
+ __tracebackhide__ = True
132
+ from _pytest.config import UsageError
133
+
134
+ if reason and msg:
135
+ raise UsageError(
136
+ "cannot pass reason and msg to exit(), `msg` is deprecated, use `reason`."
137
+ )
138
+ if not reason:
139
+ if msg is None:
140
+ raise UsageError("exit() requires a reason argument")
141
+ warnings.warn(KEYWORD_MSG_ARG.format(func="exit"), stacklevel=2)
142
+ reason = msg
143
+ raise Exit(reason, returncode)
144
+
145
+
146
+ @_with_exception(Skipped)
147
+ def skip(
148
+ reason: str = "", *, allow_module_level: bool = False, msg: Optional[str] = None
149
+ ) -> NoReturn:
150
+ """Skip an executing test with the given message.
151
+
152
+ This function should be called only during testing (setup, call or teardown) or
153
+ during collection by using the ``allow_module_level`` flag. This function can
154
+ be called in doctests as well.
155
+
156
+ :param reason:
157
+ The message to show the user as reason for the skip.
158
+
159
+ :param allow_module_level:
160
+ Allows this function to be called at module level.
161
+ Raising the skip exception at module level will stop
162
+ the execution of the module and prevent the collection of all tests in the module,
163
+ even those defined before the `skip` call.
164
+
165
+ Defaults to False.
166
+
167
+ :param msg:
168
+ Same as ``reason``, but deprecated. Will be removed in a future version, use ``reason`` instead.
169
+
170
+ .. note::
171
+ It is better to use the :ref:`pytest.mark.skipif ref` marker when
172
+ possible to declare a test to be skipped under certain conditions
173
+ like mismatching platforms or dependencies.
174
+ Similarly, use the ``# doctest: +SKIP`` directive (see :py:data:`doctest.SKIP`)
175
+ to skip a doctest statically.
176
+ """
177
+ __tracebackhide__ = True
178
+ reason = _resolve_msg_to_reason("skip", reason, msg)
179
+ raise Skipped(msg=reason, allow_module_level=allow_module_level)
180
+
181
+
182
+ @_with_exception(Failed)
183
+ def fail(reason: str = "", pytrace: bool = True, msg: Optional[str] = None) -> NoReturn:
184
+ """Explicitly fail an executing test with the given message.
185
+
186
+ :param reason:
187
+ The message to show the user as reason for the failure.
188
+
189
+ :param pytrace:
190
+ If False, msg represents the full failure information and no
191
+ python traceback will be reported.
192
+
193
+ :param msg:
194
+ Same as ``reason``, but deprecated. Will be removed in a future version, use ``reason`` instead.
195
+ """
196
+ __tracebackhide__ = True
197
+ reason = _resolve_msg_to_reason("fail", reason, msg)
198
+ raise Failed(msg=reason, pytrace=pytrace)
199
+
200
+
201
+ def _resolve_msg_to_reason(
202
+ func_name: str, reason: str, msg: Optional[str] = None
203
+ ) -> str:
204
+ """
205
+ Handles converting the deprecated msg parameter if provided into
206
+ reason, raising a deprecation warning. This function will be removed
207
+ when the optional msg argument is removed from here in future.
208
+
209
+ :param str func_name:
210
+ The name of the offending function, this is formatted into the deprecation message.
211
+
212
+ :param str reason:
213
+ The reason= passed into either pytest.fail() or pytest.skip()
214
+
215
+ :param str msg:
216
+ The msg= passed into either pytest.fail() or pytest.skip(). This will
217
+ be converted into reason if it is provided to allow pytest.skip(msg=) or
218
+ pytest.fail(msg=) to continue working in the interim period.
219
+
220
+ :returns:
221
+ The value to use as reason.
222
+
223
+ """
224
+ __tracebackhide__ = True
225
+ if msg is not None:
226
+ if reason:
227
+ from pytest import UsageError
228
+
229
+ raise UsageError(
230
+ f"Passing both ``reason`` and ``msg`` to pytest.{func_name}(...) is not permitted."
231
+ )
232
+ warnings.warn(KEYWORD_MSG_ARG.format(func=func_name), stacklevel=3)
233
+ reason = msg
234
+ return reason
235
+
236
+
237
+ class XFailed(Failed):
238
+ """Raised from an explicit call to pytest.xfail()."""
239
+
240
+
241
+ @_with_exception(XFailed)
242
+ def xfail(reason: str = "") -> NoReturn:
243
+ """Imperatively xfail an executing test or setup function with the given reason.
244
+
245
+ This function should be called only during testing (setup, call or teardown).
246
+
247
+ :param reason:
248
+ The message to show the user as reason for the xfail.
249
+
250
+ .. note::
251
+ It is better to use the :ref:`pytest.mark.xfail ref` marker when
252
+ possible to declare a test to be xfailed under certain conditions
253
+ like known bugs or missing features.
254
+ """
255
+ __tracebackhide__ = True
256
+ raise XFailed(reason)
257
+
258
+
259
+ def importorskip(
260
+ modname: str, minversion: Optional[str] = None, reason: Optional[str] = None
261
+ ) -> Any:
262
+ """Import and return the requested module ``modname``, or skip the
263
+ current test if the module cannot be imported.
264
+
265
+ :param modname:
266
+ The name of the module to import.
267
+ :param minversion:
268
+ If given, the imported module's ``__version__`` attribute must be at
269
+ least this minimal version, otherwise the test is still skipped.
270
+ :param reason:
271
+ If given, this reason is shown as the message when the module cannot
272
+ be imported.
273
+
274
+ :returns:
275
+ The imported module. This should be assigned to its canonical name.
276
+
277
+ Example::
278
+
279
+ docutils = pytest.importorskip("docutils")
280
+ """
281
+ import warnings
282
+
283
+ __tracebackhide__ = True
284
+ compile(modname, "", "eval") # to catch syntaxerrors
285
+
286
+ with warnings.catch_warnings():
287
+ # Make sure to ignore ImportWarnings that might happen because
288
+ # of existing directories with the same name we're trying to
289
+ # import but without a __init__.py file.
290
+ warnings.simplefilter("ignore")
291
+ try:
292
+ __import__(modname)
293
+ except ImportError as exc:
294
+ if reason is None:
295
+ reason = f"could not import {modname!r}: {exc}"
296
+ raise Skipped(reason, allow_module_level=True) from None
297
+ mod = sys.modules[modname]
298
+ if minversion is None:
299
+ return mod
300
+ verattr = getattr(mod, "__version__", None)
301
+ if minversion is not None:
302
+ # Imported lazily to improve start-up time.
303
+ from packaging.version import Version
304
+
305
+ if verattr is None or Version(verattr) < Version(minversion):
306
+ raise Skipped(
307
+ "module %r has __version__ %r, required is: %r"
308
+ % (modname, verattr, minversion),
309
+ allow_module_level=True,
310
+ )
311
+ return mod
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/pastebin.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Submit failure or test session information to a pastebin service."""
2
+ import tempfile
3
+ from io import StringIO
4
+ from typing import IO
5
+ from typing import Union
6
+
7
+ import pytest
8
+ from _pytest.config import Config
9
+ from _pytest.config import create_terminal_writer
10
+ from _pytest.config.argparsing import Parser
11
+ from _pytest.stash import StashKey
12
+ from _pytest.terminal import TerminalReporter
13
+
14
+
15
+ pastebinfile_key = StashKey[IO[bytes]]()
16
+
17
+
18
+ def pytest_addoption(parser: Parser) -> None:
19
+ group = parser.getgroup("terminal reporting")
20
+ group._addoption(
21
+ "--pastebin",
22
+ metavar="mode",
23
+ action="store",
24
+ dest="pastebin",
25
+ default=None,
26
+ choices=["failed", "all"],
27
+ help="Send failed|all info to bpaste.net pastebin service",
28
+ )
29
+
30
+
31
+ @pytest.hookimpl(trylast=True)
32
+ def pytest_configure(config: Config) -> None:
33
+ if config.option.pastebin == "all":
34
+ tr = config.pluginmanager.getplugin("terminalreporter")
35
+ # If no terminal reporter plugin is present, nothing we can do here;
36
+ # this can happen when this function executes in a worker node
37
+ # when using pytest-xdist, for example.
38
+ if tr is not None:
39
+ # pastebin file will be UTF-8 encoded binary file.
40
+ config.stash[pastebinfile_key] = tempfile.TemporaryFile("w+b")
41
+ oldwrite = tr._tw.write
42
+
43
+ def tee_write(s, **kwargs):
44
+ oldwrite(s, **kwargs)
45
+ if isinstance(s, str):
46
+ s = s.encode("utf-8")
47
+ config.stash[pastebinfile_key].write(s)
48
+
49
+ tr._tw.write = tee_write
50
+
51
+
52
+ def pytest_unconfigure(config: Config) -> None:
53
+ if pastebinfile_key in config.stash:
54
+ pastebinfile = config.stash[pastebinfile_key]
55
+ # Get terminal contents and delete file.
56
+ pastebinfile.seek(0)
57
+ sessionlog = pastebinfile.read()
58
+ pastebinfile.close()
59
+ del config.stash[pastebinfile_key]
60
+ # Undo our patching in the terminal reporter.
61
+ tr = config.pluginmanager.getplugin("terminalreporter")
62
+ del tr._tw.__dict__["write"]
63
+ # Write summary.
64
+ tr.write_sep("=", "Sending information to Paste Service")
65
+ pastebinurl = create_new_paste(sessionlog)
66
+ tr.write_line("pastebin session-log: %s\n" % pastebinurl)
67
+
68
+
69
+ def create_new_paste(contents: Union[str, bytes]) -> str:
70
+ """Create a new paste using the bpaste.net service.
71
+
72
+ :contents: Paste contents string.
73
+ :returns: URL to the pasted contents, or an error message.
74
+ """
75
+ import re
76
+ from urllib.request import urlopen
77
+ from urllib.parse import urlencode
78
+
79
+ params = {"code": contents, "lexer": "text", "expiry": "1week"}
80
+ url = "https://bpa.st"
81
+ try:
82
+ response: str = (
83
+ urlopen(url, data=urlencode(params).encode("ascii")).read().decode("utf-8")
84
+ )
85
+ except OSError as exc_info: # urllib errors
86
+ return "bad response: %s" % exc_info
87
+ m = re.search(r'href="/raw/(\w+)"', response)
88
+ if m:
89
+ return f"{url}/show/{m.group(1)}"
90
+ else:
91
+ return "bad response: invalid format ('" + response + "')"
92
+
93
+
94
+ def pytest_terminal_summary(terminalreporter: TerminalReporter) -> None:
95
+ if terminalreporter.config.option.pastebin != "failed":
96
+ return
97
+ if "failed" in terminalreporter.stats:
98
+ terminalreporter.write_sep("=", "Sending information to Paste Service")
99
+ for rep in terminalreporter.stats["failed"]:
100
+ try:
101
+ msg = rep.longrepr.reprtraceback.reprentries[-1].reprfileloc
102
+ except AttributeError:
103
+ msg = terminalreporter._getfailureheadline(rep)
104
+ file = StringIO()
105
+ tw = create_terminal_writer(terminalreporter.config, file)
106
+ rep.toterminal(tw)
107
+ s = file.getvalue()
108
+ assert len(s)
109
+ pastebinurl = create_new_paste(s)
110
+ terminalreporter.write_line(f"{msg} --> {pastebinurl}")
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/pathlib.py ADDED
@@ -0,0 +1,804 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import atexit
2
+ import contextlib
3
+ import fnmatch
4
+ import importlib.util
5
+ import itertools
6
+ import os
7
+ import shutil
8
+ import sys
9
+ import types
10
+ import uuid
11
+ import warnings
12
+ from enum import Enum
13
+ from errno import EBADF
14
+ from errno import ELOOP
15
+ from errno import ENOENT
16
+ from errno import ENOTDIR
17
+ from functools import partial
18
+ from os.path import expanduser
19
+ from os.path import expandvars
20
+ from os.path import isabs
21
+ from os.path import sep
22
+ from pathlib import Path
23
+ from pathlib import PurePath
24
+ from posixpath import sep as posix_sep
25
+ from types import ModuleType
26
+ from typing import Callable
27
+ from typing import Dict
28
+ from typing import Iterable
29
+ from typing import Iterator
30
+ from typing import List
31
+ from typing import Optional
32
+ from typing import Set
33
+ from typing import Tuple
34
+ from typing import Type
35
+ from typing import TypeVar
36
+ from typing import Union
37
+
38
+ from _pytest.compat import assert_never
39
+ from _pytest.outcomes import skip
40
+ from _pytest.warning_types import PytestWarning
41
+
42
+ LOCK_TIMEOUT = 60 * 60 * 24 * 3
43
+
44
+
45
+ _AnyPurePath = TypeVar("_AnyPurePath", bound=PurePath)
46
+
47
+ # The following function, variables and comments were
48
+ # copied from cpython 3.9 Lib/pathlib.py file.
49
+
50
+ # EBADF - guard against macOS `stat` throwing EBADF
51
+ _IGNORED_ERRORS = (ENOENT, ENOTDIR, EBADF, ELOOP)
52
+
53
+ _IGNORED_WINERRORS = (
54
+ 21, # ERROR_NOT_READY - drive exists but is not accessible
55
+ 1921, # ERROR_CANT_RESOLVE_FILENAME - fix for broken symlink pointing to itself
56
+ )
57
+
58
+
59
+ def _ignore_error(exception):
60
+ return (
61
+ getattr(exception, "errno", None) in _IGNORED_ERRORS
62
+ or getattr(exception, "winerror", None) in _IGNORED_WINERRORS
63
+ )
64
+
65
+
66
+ def get_lock_path(path: _AnyPurePath) -> _AnyPurePath:
67
+ return path.joinpath(".lock")
68
+
69
+
70
+ def on_rm_rf_error(
71
+ func,
72
+ path: str,
73
+ excinfo: Union[
74
+ BaseException,
75
+ Tuple[Type[BaseException], BaseException, Optional[types.TracebackType]],
76
+ ],
77
+ *,
78
+ start_path: Path,
79
+ ) -> bool:
80
+ """Handle known read-only errors during rmtree.
81
+
82
+ The returned value is used only by our own tests.
83
+ """
84
+ if isinstance(excinfo, BaseException):
85
+ exc = excinfo
86
+ else:
87
+ exc = excinfo[1]
88
+
89
+ # Another process removed the file in the middle of the "rm_rf" (xdist for example).
90
+ # More context: https://github.com/pytest-dev/pytest/issues/5974#issuecomment-543799018
91
+ if isinstance(exc, FileNotFoundError):
92
+ return False
93
+
94
+ if not isinstance(exc, PermissionError):
95
+ warnings.warn(
96
+ PytestWarning(f"(rm_rf) error removing {path}\n{type(exc)}: {exc}")
97
+ )
98
+ return False
99
+
100
+ if func not in (os.rmdir, os.remove, os.unlink):
101
+ if func not in (os.open,):
102
+ warnings.warn(
103
+ PytestWarning(
104
+ "(rm_rf) unknown function {} when removing {}:\n{}: {}".format(
105
+ func, path, type(exc), exc
106
+ )
107
+ )
108
+ )
109
+ return False
110
+
111
+ # Chmod + retry.
112
+ import stat
113
+
114
+ def chmod_rw(p: str) -> None:
115
+ mode = os.stat(p).st_mode
116
+ os.chmod(p, mode | stat.S_IRUSR | stat.S_IWUSR)
117
+
118
+ # For files, we need to recursively go upwards in the directories to
119
+ # ensure they all are also writable.
120
+ p = Path(path)
121
+ if p.is_file():
122
+ for parent in p.parents:
123
+ chmod_rw(str(parent))
124
+ # Stop when we reach the original path passed to rm_rf.
125
+ if parent == start_path:
126
+ break
127
+ chmod_rw(str(path))
128
+
129
+ func(path)
130
+ return True
131
+
132
+
133
+ def ensure_extended_length_path(path: Path) -> Path:
134
+ """Get the extended-length version of a path (Windows).
135
+
136
+ On Windows, by default, the maximum length of a path (MAX_PATH) is 260
137
+ characters, and operations on paths longer than that fail. But it is possible
138
+ to overcome this by converting the path to "extended-length" form before
139
+ performing the operation:
140
+ https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#maximum-path-length-limitation
141
+
142
+ On Windows, this function returns the extended-length absolute version of path.
143
+ On other platforms it returns path unchanged.
144
+ """
145
+ if sys.platform.startswith("win32"):
146
+ path = path.resolve()
147
+ path = Path(get_extended_length_path_str(str(path)))
148
+ return path
149
+
150
+
151
+ def get_extended_length_path_str(path: str) -> str:
152
+ """Convert a path to a Windows extended length path."""
153
+ long_path_prefix = "\\\\?\\"
154
+ unc_long_path_prefix = "\\\\?\\UNC\\"
155
+ if path.startswith((long_path_prefix, unc_long_path_prefix)):
156
+ return path
157
+ # UNC
158
+ if path.startswith("\\\\"):
159
+ return unc_long_path_prefix + path[2:]
160
+ return long_path_prefix + path
161
+
162
+
163
+ def rm_rf(path: Path) -> None:
164
+ """Remove the path contents recursively, even if some elements
165
+ are read-only."""
166
+ path = ensure_extended_length_path(path)
167
+ onerror = partial(on_rm_rf_error, start_path=path)
168
+ if sys.version_info >= (3, 12):
169
+ shutil.rmtree(str(path), onexc=onerror)
170
+ else:
171
+ shutil.rmtree(str(path), onerror=onerror)
172
+
173
+
174
+ def find_prefixed(root: Path, prefix: str) -> Iterator[Path]:
175
+ """Find all elements in root that begin with the prefix, case insensitive."""
176
+ l_prefix = prefix.lower()
177
+ for x in root.iterdir():
178
+ if x.name.lower().startswith(l_prefix):
179
+ yield x
180
+
181
+
182
+ def extract_suffixes(iter: Iterable[PurePath], prefix: str) -> Iterator[str]:
183
+ """Return the parts of the paths following the prefix.
184
+
185
+ :param iter: Iterator over path names.
186
+ :param prefix: Expected prefix of the path names.
187
+ """
188
+ p_len = len(prefix)
189
+ for p in iter:
190
+ yield p.name[p_len:]
191
+
192
+
193
+ def find_suffixes(root: Path, prefix: str) -> Iterator[str]:
194
+ """Combine find_prefixes and extract_suffixes."""
195
+ return extract_suffixes(find_prefixed(root, prefix), prefix)
196
+
197
+
198
+ def parse_num(maybe_num) -> int:
199
+ """Parse number path suffixes, returns -1 on error."""
200
+ try:
201
+ return int(maybe_num)
202
+ except ValueError:
203
+ return -1
204
+
205
+
206
+ def _force_symlink(
207
+ root: Path, target: Union[str, PurePath], link_to: Union[str, Path]
208
+ ) -> None:
209
+ """Helper to create the current symlink.
210
+
211
+ It's full of race conditions that are reasonably OK to ignore
212
+ for the context of best effort linking to the latest test run.
213
+
214
+ The presumption being that in case of much parallelism
215
+ the inaccuracy is going to be acceptable.
216
+ """
217
+ current_symlink = root.joinpath(target)
218
+ try:
219
+ current_symlink.unlink()
220
+ except OSError:
221
+ pass
222
+ try:
223
+ current_symlink.symlink_to(link_to)
224
+ except Exception:
225
+ pass
226
+
227
+
228
+ def make_numbered_dir(root: Path, prefix: str, mode: int = 0o700) -> Path:
229
+ """Create a directory with an increased number as suffix for the given prefix."""
230
+ for i in range(10):
231
+ # try up to 10 times to create the folder
232
+ max_existing = max(map(parse_num, find_suffixes(root, prefix)), default=-1)
233
+ new_number = max_existing + 1
234
+ new_path = root.joinpath(f"{prefix}{new_number}")
235
+ try:
236
+ new_path.mkdir(mode=mode)
237
+ except Exception:
238
+ pass
239
+ else:
240
+ _force_symlink(root, prefix + "current", new_path)
241
+ return new_path
242
+ else:
243
+ raise OSError(
244
+ "could not create numbered dir with prefix "
245
+ "{prefix} in {root} after 10 tries".format(prefix=prefix, root=root)
246
+ )
247
+
248
+
249
+ def create_cleanup_lock(p: Path) -> Path:
250
+ """Create a lock to prevent premature folder cleanup."""
251
+ lock_path = get_lock_path(p)
252
+ try:
253
+ fd = os.open(str(lock_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
254
+ except FileExistsError as e:
255
+ raise OSError(f"cannot create lockfile in {p}") from e
256
+ else:
257
+ pid = os.getpid()
258
+ spid = str(pid).encode()
259
+ os.write(fd, spid)
260
+ os.close(fd)
261
+ if not lock_path.is_file():
262
+ raise OSError("lock path got renamed after successful creation")
263
+ return lock_path
264
+
265
+
266
+ def register_cleanup_lock_removal(lock_path: Path, register=atexit.register):
267
+ """Register a cleanup function for removing a lock, by default on atexit."""
268
+ pid = os.getpid()
269
+
270
+ def cleanup_on_exit(lock_path: Path = lock_path, original_pid: int = pid) -> None:
271
+ current_pid = os.getpid()
272
+ if current_pid != original_pid:
273
+ # fork
274
+ return
275
+ try:
276
+ lock_path.unlink()
277
+ except OSError:
278
+ pass
279
+
280
+ return register(cleanup_on_exit)
281
+
282
+
283
+ def maybe_delete_a_numbered_dir(path: Path) -> None:
284
+ """Remove a numbered directory if its lock can be obtained and it does
285
+ not seem to be in use."""
286
+ path = ensure_extended_length_path(path)
287
+ lock_path = None
288
+ try:
289
+ lock_path = create_cleanup_lock(path)
290
+ parent = path.parent
291
+
292
+ garbage = parent.joinpath(f"garbage-{uuid.uuid4()}")
293
+ path.rename(garbage)
294
+ rm_rf(garbage)
295
+ except OSError:
296
+ # known races:
297
+ # * other process did a cleanup at the same time
298
+ # * deletable folder was found
299
+ # * process cwd (Windows)
300
+ return
301
+ finally:
302
+ # If we created the lock, ensure we remove it even if we failed
303
+ # to properly remove the numbered dir.
304
+ if lock_path is not None:
305
+ try:
306
+ lock_path.unlink()
307
+ except OSError:
308
+ pass
309
+
310
+
311
+ def ensure_deletable(path: Path, consider_lock_dead_if_created_before: float) -> bool:
312
+ """Check if `path` is deletable based on whether the lock file is expired."""
313
+ if path.is_symlink():
314
+ return False
315
+ lock = get_lock_path(path)
316
+ try:
317
+ if not lock.is_file():
318
+ return True
319
+ except OSError:
320
+ # we might not have access to the lock file at all, in this case assume
321
+ # we don't have access to the entire directory (#7491).
322
+ return False
323
+ try:
324
+ lock_time = lock.stat().st_mtime
325
+ except Exception:
326
+ return False
327
+ else:
328
+ if lock_time < consider_lock_dead_if_created_before:
329
+ # We want to ignore any errors while trying to remove the lock such as:
330
+ # - PermissionDenied, like the file permissions have changed since the lock creation;
331
+ # - FileNotFoundError, in case another pytest process got here first;
332
+ # and any other cause of failure.
333
+ with contextlib.suppress(OSError):
334
+ lock.unlink()
335
+ return True
336
+ return False
337
+
338
+
339
+ def try_cleanup(path: Path, consider_lock_dead_if_created_before: float) -> None:
340
+ """Try to cleanup a folder if we can ensure it's deletable."""
341
+ if ensure_deletable(path, consider_lock_dead_if_created_before):
342
+ maybe_delete_a_numbered_dir(path)
343
+
344
+
345
+ def cleanup_candidates(root: Path, prefix: str, keep: int) -> Iterator[Path]:
346
+ """List candidates for numbered directories to be removed - follows py.path."""
347
+ max_existing = max(map(parse_num, find_suffixes(root, prefix)), default=-1)
348
+ max_delete = max_existing - keep
349
+ paths = find_prefixed(root, prefix)
350
+ paths, paths2 = itertools.tee(paths)
351
+ numbers = map(parse_num, extract_suffixes(paths2, prefix))
352
+ for path, number in zip(paths, numbers):
353
+ if number <= max_delete:
354
+ yield path
355
+
356
+
357
+ def cleanup_dead_symlinks(root: Path):
358
+ for left_dir in root.iterdir():
359
+ if left_dir.is_symlink():
360
+ if not left_dir.resolve().exists():
361
+ left_dir.unlink()
362
+
363
+
364
+ def cleanup_numbered_dir(
365
+ root: Path, prefix: str, keep: int, consider_lock_dead_if_created_before: float
366
+ ) -> None:
367
+ """Cleanup for lock driven numbered directories."""
368
+ if not root.exists():
369
+ return
370
+ for path in cleanup_candidates(root, prefix, keep):
371
+ try_cleanup(path, consider_lock_dead_if_created_before)
372
+ for path in root.glob("garbage-*"):
373
+ try_cleanup(path, consider_lock_dead_if_created_before)
374
+
375
+ cleanup_dead_symlinks(root)
376
+
377
+
378
+ def make_numbered_dir_with_cleanup(
379
+ root: Path,
380
+ prefix: str,
381
+ keep: int,
382
+ lock_timeout: float,
383
+ mode: int,
384
+ ) -> Path:
385
+ """Create a numbered dir with a cleanup lock and remove old ones."""
386
+ e = None
387
+ for i in range(10):
388
+ try:
389
+ p = make_numbered_dir(root, prefix, mode)
390
+ # Only lock the current dir when keep is not 0
391
+ if keep != 0:
392
+ lock_path = create_cleanup_lock(p)
393
+ register_cleanup_lock_removal(lock_path)
394
+ except Exception as exc:
395
+ e = exc
396
+ else:
397
+ consider_lock_dead_if_created_before = p.stat().st_mtime - lock_timeout
398
+ # Register a cleanup for program exit
399
+ atexit.register(
400
+ cleanup_numbered_dir,
401
+ root,
402
+ prefix,
403
+ keep,
404
+ consider_lock_dead_if_created_before,
405
+ )
406
+ return p
407
+ assert e is not None
408
+ raise e
409
+
410
+
411
+ def resolve_from_str(input: str, rootpath: Path) -> Path:
412
+ input = expanduser(input)
413
+ input = expandvars(input)
414
+ if isabs(input):
415
+ return Path(input)
416
+ else:
417
+ return rootpath.joinpath(input)
418
+
419
+
420
+ def fnmatch_ex(pattern: str, path: Union[str, "os.PathLike[str]"]) -> bool:
421
+ """A port of FNMatcher from py.path.common which works with PurePath() instances.
422
+
423
+ The difference between this algorithm and PurePath.match() is that the
424
+ latter matches "**" glob expressions for each part of the path, while
425
+ this algorithm uses the whole path instead.
426
+
427
+ For example:
428
+ "tests/foo/bar/doc/test_foo.py" matches pattern "tests/**/doc/test*.py"
429
+ with this algorithm, but not with PurePath.match().
430
+
431
+ This algorithm was ported to keep backward-compatibility with existing
432
+ settings which assume paths match according this logic.
433
+
434
+ References:
435
+ * https://bugs.python.org/issue29249
436
+ * https://bugs.python.org/issue34731
437
+ """
438
+ path = PurePath(path)
439
+ iswin32 = sys.platform.startswith("win")
440
+
441
+ if iswin32 and sep not in pattern and posix_sep in pattern:
442
+ # Running on Windows, the pattern has no Windows path separators,
443
+ # and the pattern has one or more Posix path separators. Replace
444
+ # the Posix path separators with the Windows path separator.
445
+ pattern = pattern.replace(posix_sep, sep)
446
+
447
+ if sep not in pattern:
448
+ name = path.name
449
+ else:
450
+ name = str(path)
451
+ if path.is_absolute() and not os.path.isabs(pattern):
452
+ pattern = f"*{os.sep}{pattern}"
453
+ return fnmatch.fnmatch(name, pattern)
454
+
455
+
456
+ def parts(s: str) -> Set[str]:
457
+ parts = s.split(sep)
458
+ return {sep.join(parts[: i + 1]) or sep for i in range(len(parts))}
459
+
460
+
461
+ def symlink_or_skip(src, dst, **kwargs):
462
+ """Make a symlink, or skip the test in case symlinks are not supported."""
463
+ try:
464
+ os.symlink(str(src), str(dst), **kwargs)
465
+ except OSError as e:
466
+ skip(f"symlinks not supported: {e}")
467
+
468
+
469
+ class ImportMode(Enum):
470
+ """Possible values for `mode` parameter of `import_path`."""
471
+
472
+ prepend = "prepend"
473
+ append = "append"
474
+ importlib = "importlib"
475
+
476
+
477
+ class ImportPathMismatchError(ImportError):
478
+ """Raised on import_path() if there is a mismatch of __file__'s.
479
+
480
+ This can happen when `import_path` is called multiple times with different filenames that has
481
+ the same basename but reside in packages
482
+ (for example "/tests1/test_foo.py" and "/tests2/test_foo.py").
483
+ """
484
+
485
+
486
+ def import_path(
487
+ p: Union[str, "os.PathLike[str]"],
488
+ *,
489
+ mode: Union[str, ImportMode] = ImportMode.prepend,
490
+ root: Path,
491
+ ) -> ModuleType:
492
+ """Import and return a module from the given path, which can be a file (a module) or
493
+ a directory (a package).
494
+
495
+ The import mechanism used is controlled by the `mode` parameter:
496
+
497
+ * `mode == ImportMode.prepend`: the directory containing the module (or package, taking
498
+ `__init__.py` files into account) will be put at the *start* of `sys.path` before
499
+ being imported with `importlib.import_module`.
500
+
501
+ * `mode == ImportMode.append`: same as `prepend`, but the directory will be appended
502
+ to the end of `sys.path`, if not already in `sys.path`.
503
+
504
+ * `mode == ImportMode.importlib`: uses more fine control mechanisms provided by `importlib`
505
+ to import the module, which avoids having to muck with `sys.path` at all. It effectively
506
+ allows having same-named test modules in different places.
507
+
508
+ :param root:
509
+ Used as an anchor when mode == ImportMode.importlib to obtain
510
+ a unique name for the module being imported so it can safely be stored
511
+ into ``sys.modules``.
512
+
513
+ :raises ImportPathMismatchError:
514
+ If after importing the given `path` and the module `__file__`
515
+ are different. Only raised in `prepend` and `append` modes.
516
+ """
517
+ mode = ImportMode(mode)
518
+
519
+ path = Path(p)
520
+
521
+ if not path.exists():
522
+ raise ImportError(path)
523
+
524
+ if mode is ImportMode.importlib:
525
+ module_name = module_name_from_path(path, root)
526
+ with contextlib.suppress(KeyError):
527
+ return sys.modules[module_name]
528
+
529
+ for meta_importer in sys.meta_path:
530
+ spec = meta_importer.find_spec(module_name, [str(path.parent)])
531
+ if spec is not None:
532
+ break
533
+ else:
534
+ spec = importlib.util.spec_from_file_location(module_name, str(path))
535
+
536
+ if spec is None:
537
+ raise ImportError(f"Can't find module {module_name} at location {path}")
538
+ mod = importlib.util.module_from_spec(spec)
539
+ sys.modules[module_name] = mod
540
+ spec.loader.exec_module(mod) # type: ignore[union-attr]
541
+ insert_missing_modules(sys.modules, module_name)
542
+ return mod
543
+
544
+ pkg_path = resolve_package_path(path)
545
+ if pkg_path is not None:
546
+ pkg_root = pkg_path.parent
547
+ names = list(path.with_suffix("").relative_to(pkg_root).parts)
548
+ if names[-1] == "__init__":
549
+ names.pop()
550
+ module_name = ".".join(names)
551
+ else:
552
+ pkg_root = path.parent
553
+ module_name = path.stem
554
+
555
+ # Change sys.path permanently: restoring it at the end of this function would cause surprising
556
+ # problems because of delayed imports: for example, a conftest.py file imported by this function
557
+ # might have local imports, which would fail at runtime if we restored sys.path.
558
+ if mode is ImportMode.append:
559
+ if str(pkg_root) not in sys.path:
560
+ sys.path.append(str(pkg_root))
561
+ elif mode is ImportMode.prepend:
562
+ if str(pkg_root) != sys.path[0]:
563
+ sys.path.insert(0, str(pkg_root))
564
+ else:
565
+ assert_never(mode)
566
+
567
+ importlib.import_module(module_name)
568
+
569
+ mod = sys.modules[module_name]
570
+ if path.name == "__init__.py":
571
+ return mod
572
+
573
+ ignore = os.environ.get("PY_IGNORE_IMPORTMISMATCH", "")
574
+ if ignore != "1":
575
+ module_file = mod.__file__
576
+ if module_file is None:
577
+ raise ImportPathMismatchError(module_name, module_file, path)
578
+
579
+ if module_file.endswith((".pyc", ".pyo")):
580
+ module_file = module_file[:-1]
581
+ if module_file.endswith(os.sep + "__init__.py"):
582
+ module_file = module_file[: -(len(os.sep + "__init__.py"))]
583
+
584
+ try:
585
+ is_same = _is_same(str(path), module_file)
586
+ except FileNotFoundError:
587
+ is_same = False
588
+
589
+ if not is_same:
590
+ raise ImportPathMismatchError(module_name, module_file, path)
591
+
592
+ return mod
593
+
594
+
595
+ # Implement a special _is_same function on Windows which returns True if the two filenames
596
+ # compare equal, to circumvent os.path.samefile returning False for mounts in UNC (#7678).
597
+ if sys.platform.startswith("win"):
598
+
599
+ def _is_same(f1: str, f2: str) -> bool:
600
+ return Path(f1) == Path(f2) or os.path.samefile(f1, f2)
601
+
602
+ else:
603
+
604
+ def _is_same(f1: str, f2: str) -> bool:
605
+ return os.path.samefile(f1, f2)
606
+
607
+
608
+ def module_name_from_path(path: Path, root: Path) -> str:
609
+ """
610
+ Return a dotted module name based on the given path, anchored on root.
611
+
612
+ For example: path="projects/src/tests/test_foo.py" and root="/projects", the
613
+ resulting module name will be "src.tests.test_foo".
614
+ """
615
+ path = path.with_suffix("")
616
+ try:
617
+ relative_path = path.relative_to(root)
618
+ except ValueError:
619
+ # If we can't get a relative path to root, use the full path, except
620
+ # for the first part ("d:\\" or "/" depending on the platform, for example).
621
+ path_parts = path.parts[1:]
622
+ else:
623
+ # Use the parts for the relative path to the root path.
624
+ path_parts = relative_path.parts
625
+
626
+ # Module name for packages do not contain the __init__ file, unless
627
+ # the `__init__.py` file is at the root.
628
+ if len(path_parts) >= 2 and path_parts[-1] == "__init__":
629
+ path_parts = path_parts[:-1]
630
+
631
+ return ".".join(path_parts)
632
+
633
+
634
+ def insert_missing_modules(modules: Dict[str, ModuleType], module_name: str) -> None:
635
+ """
636
+ Used by ``import_path`` to create intermediate modules when using mode=importlib.
637
+
638
+ When we want to import a module as "src.tests.test_foo" for example, we need
639
+ to create empty modules "src" and "src.tests" after inserting "src.tests.test_foo",
640
+ otherwise "src.tests.test_foo" is not importable by ``__import__``.
641
+ """
642
+ module_parts = module_name.split(".")
643
+ child_module: Union[ModuleType, None] = None
644
+ module: Union[ModuleType, None] = None
645
+ child_name: str = ""
646
+ while module_name:
647
+ if module_name not in modules:
648
+ try:
649
+ # If sys.meta_path is empty, calling import_module will issue
650
+ # a warning and raise ModuleNotFoundError. To avoid the
651
+ # warning, we check sys.meta_path explicitly and raise the error
652
+ # ourselves to fall back to creating a dummy module.
653
+ if not sys.meta_path:
654
+ raise ModuleNotFoundError
655
+ module = importlib.import_module(module_name)
656
+ except ModuleNotFoundError:
657
+ module = ModuleType(
658
+ module_name,
659
+ doc="Empty module created by pytest's importmode=importlib.",
660
+ )
661
+ else:
662
+ module = modules[module_name]
663
+ if child_module:
664
+ # Add child attribute to the parent that can reference the child
665
+ # modules.
666
+ if not hasattr(module, child_name):
667
+ setattr(module, child_name, child_module)
668
+ modules[module_name] = module
669
+ # Keep track of the child module while moving up the tree.
670
+ child_module, child_name = module, module_name.rpartition(".")[-1]
671
+ module_parts.pop(-1)
672
+ module_name = ".".join(module_parts)
673
+
674
+
675
+ def resolve_package_path(path: Path) -> Optional[Path]:
676
+ """Return the Python package path by looking for the last
677
+ directory upwards which still contains an __init__.py.
678
+
679
+ Returns None if it can not be determined.
680
+ """
681
+ result = None
682
+ for parent in itertools.chain((path,), path.parents):
683
+ if parent.is_dir():
684
+ if not parent.joinpath("__init__.py").is_file():
685
+ break
686
+ if not parent.name.isidentifier():
687
+ break
688
+ result = parent
689
+ return result
690
+
691
+
692
+ def scandir(path: Union[str, "os.PathLike[str]"]) -> List["os.DirEntry[str]"]:
693
+ """Scan a directory recursively, in breadth-first order.
694
+
695
+ The returned entries are sorted.
696
+ """
697
+ entries = []
698
+ with os.scandir(path) as s:
699
+ # Skip entries with symlink loops and other brokenness, so the caller
700
+ # doesn't have to deal with it.
701
+ for entry in s:
702
+ try:
703
+ entry.is_file()
704
+ except OSError as err:
705
+ if _ignore_error(err):
706
+ continue
707
+ raise
708
+ entries.append(entry)
709
+ entries.sort(key=lambda entry: entry.name)
710
+ return entries
711
+
712
+
713
+ def visit(
714
+ path: Union[str, "os.PathLike[str]"], recurse: Callable[["os.DirEntry[str]"], bool]
715
+ ) -> Iterator["os.DirEntry[str]"]:
716
+ """Walk a directory recursively, in breadth-first order.
717
+
718
+ The `recurse` predicate determines whether a directory is recursed.
719
+
720
+ Entries at each directory level are sorted.
721
+ """
722
+ entries = scandir(path)
723
+ yield from entries
724
+ for entry in entries:
725
+ if entry.is_dir() and recurse(entry):
726
+ yield from visit(entry.path, recurse)
727
+
728
+
729
+ def absolutepath(path: Union[Path, str]) -> Path:
730
+ """Convert a path to an absolute path using os.path.abspath.
731
+
732
+ Prefer this over Path.resolve() (see #6523).
733
+ Prefer this over Path.absolute() (not public, doesn't normalize).
734
+ """
735
+ return Path(os.path.abspath(str(path)))
736
+
737
+
738
+ def commonpath(path1: Path, path2: Path) -> Optional[Path]:
739
+ """Return the common part shared with the other path, or None if there is
740
+ no common part.
741
+
742
+ If one path is relative and one is absolute, returns None.
743
+ """
744
+ try:
745
+ return Path(os.path.commonpath((str(path1), str(path2))))
746
+ except ValueError:
747
+ return None
748
+
749
+
750
+ def bestrelpath(directory: Path, dest: Path) -> str:
751
+ """Return a string which is a relative path from directory to dest such
752
+ that directory/bestrelpath == dest.
753
+
754
+ The paths must be either both absolute or both relative.
755
+
756
+ If no such path can be determined, returns dest.
757
+ """
758
+ assert isinstance(directory, Path)
759
+ assert isinstance(dest, Path)
760
+ if dest == directory:
761
+ return os.curdir
762
+ # Find the longest common directory.
763
+ base = commonpath(directory, dest)
764
+ # Can be the case on Windows for two absolute paths on different drives.
765
+ # Can be the case for two relative paths without common prefix.
766
+ # Can be the case for a relative path and an absolute path.
767
+ if not base:
768
+ return str(dest)
769
+ reldirectory = directory.relative_to(base)
770
+ reldest = dest.relative_to(base)
771
+ return os.path.join(
772
+ # Back from directory to base.
773
+ *([os.pardir] * len(reldirectory.parts)),
774
+ # Forward from base to dest.
775
+ *reldest.parts,
776
+ )
777
+
778
+
779
+ # Originates from py. path.local.copy(), with siginficant trims and adjustments.
780
+ # TODO(py38): Replace with shutil.copytree(..., symlinks=True, dirs_exist_ok=True)
781
+ def copytree(source: Path, target: Path) -> None:
782
+ """Recursively copy a source directory to target."""
783
+ assert source.is_dir()
784
+ for entry in visit(source, recurse=lambda entry: not entry.is_symlink()):
785
+ x = Path(entry)
786
+ relpath = x.relative_to(source)
787
+ newx = target / relpath
788
+ newx.parent.mkdir(exist_ok=True)
789
+ if x.is_symlink():
790
+ newx.symlink_to(os.readlink(x))
791
+ elif x.is_file():
792
+ shutil.copyfile(x, newx)
793
+ elif x.is_dir():
794
+ newx.mkdir(exist_ok=True)
795
+
796
+
797
+ def safe_exists(p: Path) -> bool:
798
+ """Like Path.exists(), but account for input arguments that might be too long (#11394)."""
799
+ try:
800
+ return p.exists()
801
+ except (ValueError, OSError):
802
+ # ValueError: stat: path too long for Windows
803
+ # OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect
804
+ return False
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/py.typed ADDED
File without changes
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/pytester.py ADDED
@@ -0,0 +1,1789 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """(Disabled by default) support for testing pytest and pytest plugins.
2
+
3
+ PYTEST_DONT_REWRITE
4
+ """
5
+ import collections.abc
6
+ import contextlib
7
+ import gc
8
+ import importlib
9
+ import locale
10
+ import os
11
+ import platform
12
+ import re
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ import traceback
17
+ from fnmatch import fnmatch
18
+ from io import StringIO
19
+ from pathlib import Path
20
+ from typing import Any
21
+ from typing import Callable
22
+ from typing import Dict
23
+ from typing import Generator
24
+ from typing import IO
25
+ from typing import Iterable
26
+ from typing import List
27
+ from typing import Optional
28
+ from typing import overload
29
+ from typing import Sequence
30
+ from typing import TextIO
31
+ from typing import Tuple
32
+ from typing import Type
33
+ from typing import TYPE_CHECKING
34
+ from typing import Union
35
+ from weakref import WeakKeyDictionary
36
+
37
+ from iniconfig import IniConfig
38
+ from iniconfig import SectionWrapper
39
+
40
+ from _pytest import timing
41
+ from _pytest._code import Source
42
+ from _pytest.capture import _get_multicapture
43
+ from _pytest.compat import final
44
+ from _pytest.compat import NOTSET
45
+ from _pytest.compat import NotSetType
46
+ from _pytest.config import _PluggyPlugin
47
+ from _pytest.config import Config
48
+ from _pytest.config import ExitCode
49
+ from _pytest.config import hookimpl
50
+ from _pytest.config import main
51
+ from _pytest.config import PytestPluginManager
52
+ from _pytest.config.argparsing import Parser
53
+ from _pytest.deprecated import check_ispytest
54
+ from _pytest.fixtures import fixture
55
+ from _pytest.fixtures import FixtureRequest
56
+ from _pytest.main import Session
57
+ from _pytest.monkeypatch import MonkeyPatch
58
+ from _pytest.nodes import Collector
59
+ from _pytest.nodes import Item
60
+ from _pytest.outcomes import fail
61
+ from _pytest.outcomes import importorskip
62
+ from _pytest.outcomes import skip
63
+ from _pytest.pathlib import bestrelpath
64
+ from _pytest.pathlib import copytree
65
+ from _pytest.pathlib import make_numbered_dir
66
+ from _pytest.reports import CollectReport
67
+ from _pytest.reports import TestReport
68
+ from _pytest.tmpdir import TempPathFactory
69
+ from _pytest.warning_types import PytestWarning
70
+
71
+
72
+ if TYPE_CHECKING:
73
+ from typing_extensions import Final
74
+ from typing_extensions import Literal
75
+
76
+ import pexpect
77
+
78
+
79
+ pytest_plugins = ["pytester_assertions"]
80
+
81
+
82
+ IGNORE_PAM = [ # filenames added when obtaining details about the current user
83
+ "/var/lib/sss/mc/passwd"
84
+ ]
85
+
86
+
87
+ def pytest_addoption(parser: Parser) -> None:
88
+ parser.addoption(
89
+ "--lsof",
90
+ action="store_true",
91
+ dest="lsof",
92
+ default=False,
93
+ help="Run FD checks if lsof is available",
94
+ )
95
+
96
+ parser.addoption(
97
+ "--runpytest",
98
+ default="inprocess",
99
+ dest="runpytest",
100
+ choices=("inprocess", "subprocess"),
101
+ help=(
102
+ "Run pytest sub runs in tests using an 'inprocess' "
103
+ "or 'subprocess' (python -m main) method"
104
+ ),
105
+ )
106
+
107
+ parser.addini(
108
+ "pytester_example_dir", help="Directory to take the pytester example files from"
109
+ )
110
+
111
+
112
+ def pytest_configure(config: Config) -> None:
113
+ if config.getvalue("lsof"):
114
+ checker = LsofFdLeakChecker()
115
+ if checker.matching_platform():
116
+ config.pluginmanager.register(checker)
117
+
118
+ config.addinivalue_line(
119
+ "markers",
120
+ "pytester_example_path(*path_segments): join the given path "
121
+ "segments to `pytester_example_dir` for this test.",
122
+ )
123
+
124
+
125
+ class LsofFdLeakChecker:
126
+ def get_open_files(self) -> List[Tuple[str, str]]:
127
+ out = subprocess.run(
128
+ ("lsof", "-Ffn0", "-p", str(os.getpid())),
129
+ stdout=subprocess.PIPE,
130
+ stderr=subprocess.DEVNULL,
131
+ check=True,
132
+ text=True,
133
+ encoding=locale.getpreferredencoding(False),
134
+ ).stdout
135
+
136
+ def isopen(line: str) -> bool:
137
+ return line.startswith("f") and (
138
+ "deleted" not in line
139
+ and "mem" not in line
140
+ and "txt" not in line
141
+ and "cwd" not in line
142
+ )
143
+
144
+ open_files = []
145
+
146
+ for line in out.split("\n"):
147
+ if isopen(line):
148
+ fields = line.split("\0")
149
+ fd = fields[0][1:]
150
+ filename = fields[1][1:]
151
+ if filename in IGNORE_PAM:
152
+ continue
153
+ if filename.startswith("/"):
154
+ open_files.append((fd, filename))
155
+
156
+ return open_files
157
+
158
+ def matching_platform(self) -> bool:
159
+ try:
160
+ subprocess.run(("lsof", "-v"), check=True)
161
+ except (OSError, subprocess.CalledProcessError):
162
+ return False
163
+ else:
164
+ return True
165
+
166
+ @hookimpl(hookwrapper=True, tryfirst=True)
167
+ def pytest_runtest_protocol(self, item: Item) -> Generator[None, None, None]:
168
+ lines1 = self.get_open_files()
169
+ yield
170
+ if hasattr(sys, "pypy_version_info"):
171
+ gc.collect()
172
+ lines2 = self.get_open_files()
173
+
174
+ new_fds = {t[0] for t in lines2} - {t[0] for t in lines1}
175
+ leaked_files = [t for t in lines2 if t[0] in new_fds]
176
+ if leaked_files:
177
+ error = [
178
+ "***** %s FD leakage detected" % len(leaked_files),
179
+ *(str(f) for f in leaked_files),
180
+ "*** Before:",
181
+ *(str(f) for f in lines1),
182
+ "*** After:",
183
+ *(str(f) for f in lines2),
184
+ "***** %s FD leakage detected" % len(leaked_files),
185
+ "*** function %s:%s: %s " % item.location,
186
+ "See issue #2366",
187
+ ]
188
+ item.warn(PytestWarning("\n".join(error)))
189
+
190
+
191
+ # used at least by pytest-xdist plugin
192
+
193
+
194
+ @fixture
195
+ def _pytest(request: FixtureRequest) -> "PytestArg":
196
+ """Return a helper which offers a gethookrecorder(hook) method which
197
+ returns a HookRecorder instance which helps to make assertions about called
198
+ hooks."""
199
+ return PytestArg(request)
200
+
201
+
202
+ class PytestArg:
203
+ def __init__(self, request: FixtureRequest) -> None:
204
+ self._request = request
205
+
206
+ def gethookrecorder(self, hook) -> "HookRecorder":
207
+ hookrecorder = HookRecorder(hook._pm)
208
+ self._request.addfinalizer(hookrecorder.finish_recording)
209
+ return hookrecorder
210
+
211
+
212
+ def get_public_names(values: Iterable[str]) -> List[str]:
213
+ """Only return names from iterator values without a leading underscore."""
214
+ return [x for x in values if x[0] != "_"]
215
+
216
+
217
+ @final
218
+ class RecordedHookCall:
219
+ """A recorded call to a hook.
220
+
221
+ The arguments to the hook call are set as attributes.
222
+ For example:
223
+
224
+ .. code-block:: python
225
+
226
+ calls = hook_recorder.getcalls("pytest_runtest_setup")
227
+ # Suppose pytest_runtest_setup was called once with `item=an_item`.
228
+ assert calls[0].item is an_item
229
+ """
230
+
231
+ def __init__(self, name: str, kwargs) -> None:
232
+ self.__dict__.update(kwargs)
233
+ self._name = name
234
+
235
+ def __repr__(self) -> str:
236
+ d = self.__dict__.copy()
237
+ del d["_name"]
238
+ return f"<RecordedHookCall {self._name!r}(**{d!r})>"
239
+
240
+ if TYPE_CHECKING:
241
+ # The class has undetermined attributes, this tells mypy about it.
242
+ def __getattr__(self, key: str):
243
+ ...
244
+
245
+
246
+ @final
247
+ class HookRecorder:
248
+ """Record all hooks called in a plugin manager.
249
+
250
+ Hook recorders are created by :class:`Pytester`.
251
+
252
+ This wraps all the hook calls in the plugin manager, recording each call
253
+ before propagating the normal calls.
254
+ """
255
+
256
+ def __init__(
257
+ self, pluginmanager: PytestPluginManager, *, _ispytest: bool = False
258
+ ) -> None:
259
+ check_ispytest(_ispytest)
260
+
261
+ self._pluginmanager = pluginmanager
262
+ self.calls: List[RecordedHookCall] = []
263
+ self.ret: Optional[Union[int, ExitCode]] = None
264
+
265
+ def before(hook_name: str, hook_impls, kwargs) -> None:
266
+ self.calls.append(RecordedHookCall(hook_name, kwargs))
267
+
268
+ def after(outcome, hook_name: str, hook_impls, kwargs) -> None:
269
+ pass
270
+
271
+ self._undo_wrapping = pluginmanager.add_hookcall_monitoring(before, after)
272
+
273
+ def finish_recording(self) -> None:
274
+ self._undo_wrapping()
275
+
276
+ def getcalls(self, names: Union[str, Iterable[str]]) -> List[RecordedHookCall]:
277
+ """Get all recorded calls to hooks with the given names (or name)."""
278
+ if isinstance(names, str):
279
+ names = names.split()
280
+ return [call for call in self.calls if call._name in names]
281
+
282
+ def assert_contains(self, entries: Sequence[Tuple[str, str]]) -> None:
283
+ __tracebackhide__ = True
284
+ i = 0
285
+ entries = list(entries)
286
+ backlocals = sys._getframe(1).f_locals
287
+ while entries:
288
+ name, check = entries.pop(0)
289
+ for ind, call in enumerate(self.calls[i:]):
290
+ if call._name == name:
291
+ print("NAMEMATCH", name, call)
292
+ if eval(check, backlocals, call.__dict__):
293
+ print("CHECKERMATCH", repr(check), "->", call)
294
+ else:
295
+ print("NOCHECKERMATCH", repr(check), "-", call)
296
+ continue
297
+ i += ind + 1
298
+ break
299
+ print("NONAMEMATCH", name, "with", call)
300
+ else:
301
+ fail(f"could not find {name!r} check {check!r}")
302
+
303
+ def popcall(self, name: str) -> RecordedHookCall:
304
+ __tracebackhide__ = True
305
+ for i, call in enumerate(self.calls):
306
+ if call._name == name:
307
+ del self.calls[i]
308
+ return call
309
+ lines = [f"could not find call {name!r}, in:"]
310
+ lines.extend([" %s" % x for x in self.calls])
311
+ fail("\n".join(lines))
312
+
313
+ def getcall(self, name: str) -> RecordedHookCall:
314
+ values = self.getcalls(name)
315
+ assert len(values) == 1, (name, values)
316
+ return values[0]
317
+
318
+ # functionality for test reports
319
+
320
+ @overload
321
+ def getreports(
322
+ self,
323
+ names: "Literal['pytest_collectreport']",
324
+ ) -> Sequence[CollectReport]:
325
+ ...
326
+
327
+ @overload
328
+ def getreports(
329
+ self,
330
+ names: "Literal['pytest_runtest_logreport']",
331
+ ) -> Sequence[TestReport]:
332
+ ...
333
+
334
+ @overload
335
+ def getreports(
336
+ self,
337
+ names: Union[str, Iterable[str]] = (
338
+ "pytest_collectreport",
339
+ "pytest_runtest_logreport",
340
+ ),
341
+ ) -> Sequence[Union[CollectReport, TestReport]]:
342
+ ...
343
+
344
+ def getreports(
345
+ self,
346
+ names: Union[str, Iterable[str]] = (
347
+ "pytest_collectreport",
348
+ "pytest_runtest_logreport",
349
+ ),
350
+ ) -> Sequence[Union[CollectReport, TestReport]]:
351
+ return [x.report for x in self.getcalls(names)]
352
+
353
+ def matchreport(
354
+ self,
355
+ inamepart: str = "",
356
+ names: Union[str, Iterable[str]] = (
357
+ "pytest_runtest_logreport",
358
+ "pytest_collectreport",
359
+ ),
360
+ when: Optional[str] = None,
361
+ ) -> Union[CollectReport, TestReport]:
362
+ """Return a testreport whose dotted import path matches."""
363
+ values = []
364
+ for rep in self.getreports(names=names):
365
+ if not when and rep.when != "call" and rep.passed:
366
+ # setup/teardown passing reports - let's ignore those
367
+ continue
368
+ if when and rep.when != when:
369
+ continue
370
+ if not inamepart or inamepart in rep.nodeid.split("::"):
371
+ values.append(rep)
372
+ if not values:
373
+ raise ValueError(
374
+ "could not find test report matching %r: "
375
+ "no test reports at all!" % (inamepart,)
376
+ )
377
+ if len(values) > 1:
378
+ raise ValueError(
379
+ "found 2 or more testreports matching {!r}: {}".format(
380
+ inamepart, values
381
+ )
382
+ )
383
+ return values[0]
384
+
385
+ @overload
386
+ def getfailures(
387
+ self,
388
+ names: "Literal['pytest_collectreport']",
389
+ ) -> Sequence[CollectReport]:
390
+ ...
391
+
392
+ @overload
393
+ def getfailures(
394
+ self,
395
+ names: "Literal['pytest_runtest_logreport']",
396
+ ) -> Sequence[TestReport]:
397
+ ...
398
+
399
+ @overload
400
+ def getfailures(
401
+ self,
402
+ names: Union[str, Iterable[str]] = (
403
+ "pytest_collectreport",
404
+ "pytest_runtest_logreport",
405
+ ),
406
+ ) -> Sequence[Union[CollectReport, TestReport]]:
407
+ ...
408
+
409
+ def getfailures(
410
+ self,
411
+ names: Union[str, Iterable[str]] = (
412
+ "pytest_collectreport",
413
+ "pytest_runtest_logreport",
414
+ ),
415
+ ) -> Sequence[Union[CollectReport, TestReport]]:
416
+ return [rep for rep in self.getreports(names) if rep.failed]
417
+
418
+ def getfailedcollections(self) -> Sequence[CollectReport]:
419
+ return self.getfailures("pytest_collectreport")
420
+
421
+ def listoutcomes(
422
+ self,
423
+ ) -> Tuple[
424
+ Sequence[TestReport],
425
+ Sequence[Union[CollectReport, TestReport]],
426
+ Sequence[Union[CollectReport, TestReport]],
427
+ ]:
428
+ passed = []
429
+ skipped = []
430
+ failed = []
431
+ for rep in self.getreports(
432
+ ("pytest_collectreport", "pytest_runtest_logreport")
433
+ ):
434
+ if rep.passed:
435
+ if rep.when == "call":
436
+ assert isinstance(rep, TestReport)
437
+ passed.append(rep)
438
+ elif rep.skipped:
439
+ skipped.append(rep)
440
+ else:
441
+ assert rep.failed, f"Unexpected outcome: {rep!r}"
442
+ failed.append(rep)
443
+ return passed, skipped, failed
444
+
445
+ def countoutcomes(self) -> List[int]:
446
+ return [len(x) for x in self.listoutcomes()]
447
+
448
+ def assertoutcome(self, passed: int = 0, skipped: int = 0, failed: int = 0) -> None:
449
+ __tracebackhide__ = True
450
+ from _pytest.pytester_assertions import assertoutcome
451
+
452
+ outcomes = self.listoutcomes()
453
+ assertoutcome(
454
+ outcomes,
455
+ passed=passed,
456
+ skipped=skipped,
457
+ failed=failed,
458
+ )
459
+
460
+ def clear(self) -> None:
461
+ self.calls[:] = []
462
+
463
+
464
+ @fixture
465
+ def linecomp() -> "LineComp":
466
+ """A :class: `LineComp` instance for checking that an input linearly
467
+ contains a sequence of strings."""
468
+ return LineComp()
469
+
470
+
471
+ @fixture(name="LineMatcher")
472
+ def LineMatcher_fixture(request: FixtureRequest) -> Type["LineMatcher"]:
473
+ """A reference to the :class: `LineMatcher`.
474
+
475
+ This is instantiable with a list of lines (without their trailing newlines).
476
+ This is useful for testing large texts, such as the output of commands.
477
+ """
478
+ return LineMatcher
479
+
480
+
481
+ @fixture
482
+ def pytester(
483
+ request: FixtureRequest, tmp_path_factory: TempPathFactory, monkeypatch: MonkeyPatch
484
+ ) -> "Pytester":
485
+ """
486
+ Facilities to write tests/configuration files, execute pytest in isolation, and match
487
+ against expected output, perfect for black-box testing of pytest plugins.
488
+
489
+ It attempts to isolate the test run from external factors as much as possible, modifying
490
+ the current working directory to ``path`` and environment variables during initialization.
491
+
492
+ It is particularly useful for testing plugins. It is similar to the :fixture:`tmp_path`
493
+ fixture but provides methods which aid in testing pytest itself.
494
+ """
495
+ return Pytester(request, tmp_path_factory, monkeypatch, _ispytest=True)
496
+
497
+
498
+ @fixture
499
+ def _sys_snapshot() -> Generator[None, None, None]:
500
+ snappaths = SysPathsSnapshot()
501
+ snapmods = SysModulesSnapshot()
502
+ yield
503
+ snapmods.restore()
504
+ snappaths.restore()
505
+
506
+
507
+ @fixture
508
+ def _config_for_test() -> Generator[Config, None, None]:
509
+ from _pytest.config import get_config
510
+
511
+ config = get_config()
512
+ yield config
513
+ config._ensure_unconfigure() # cleanup, e.g. capman closing tmpfiles.
514
+
515
+
516
+ # Regex to match the session duration string in the summary: "74.34s".
517
+ rex_session_duration = re.compile(r"\d+\.\d\ds")
518
+ # Regex to match all the counts and phrases in the summary line: "34 passed, 111 skipped".
519
+ rex_outcome = re.compile(r"(\d+) (\w+)")
520
+
521
+
522
+ @final
523
+ class RunResult:
524
+ """The result of running a command from :class:`~pytest.Pytester`."""
525
+
526
+ def __init__(
527
+ self,
528
+ ret: Union[int, ExitCode],
529
+ outlines: List[str],
530
+ errlines: List[str],
531
+ duration: float,
532
+ ) -> None:
533
+ try:
534
+ self.ret: Union[int, ExitCode] = ExitCode(ret)
535
+ """The return value."""
536
+ except ValueError:
537
+ self.ret = ret
538
+ self.outlines = outlines
539
+ """List of lines captured from stdout."""
540
+ self.errlines = errlines
541
+ """List of lines captured from stderr."""
542
+ self.stdout = LineMatcher(outlines)
543
+ """:class:`~pytest.LineMatcher` of stdout.
544
+
545
+ Use e.g. :func:`str(stdout) <pytest.LineMatcher.__str__()>` to reconstruct stdout, or the commonly used
546
+ :func:`stdout.fnmatch_lines() <pytest.LineMatcher.fnmatch_lines()>` method.
547
+ """
548
+ self.stderr = LineMatcher(errlines)
549
+ """:class:`~pytest.LineMatcher` of stderr."""
550
+ self.duration = duration
551
+ """Duration in seconds."""
552
+
553
+ def __repr__(self) -> str:
554
+ return (
555
+ "<RunResult ret=%s len(stdout.lines)=%d len(stderr.lines)=%d duration=%.2fs>"
556
+ % (self.ret, len(self.stdout.lines), len(self.stderr.lines), self.duration)
557
+ )
558
+
559
+ def parseoutcomes(self) -> Dict[str, int]:
560
+ """Return a dictionary of outcome noun -> count from parsing the terminal
561
+ output that the test process produced.
562
+
563
+ The returned nouns will always be in plural form::
564
+
565
+ ======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s ====
566
+
567
+ Will return ``{"failed": 1, "passed": 1, "warnings": 1, "errors": 1}``.
568
+ """
569
+ return self.parse_summary_nouns(self.outlines)
570
+
571
+ @classmethod
572
+ def parse_summary_nouns(cls, lines) -> Dict[str, int]:
573
+ """Extract the nouns from a pytest terminal summary line.
574
+
575
+ It always returns the plural noun for consistency::
576
+
577
+ ======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s ====
578
+
579
+ Will return ``{"failed": 1, "passed": 1, "warnings": 1, "errors": 1}``.
580
+ """
581
+ for line in reversed(lines):
582
+ if rex_session_duration.search(line):
583
+ outcomes = rex_outcome.findall(line)
584
+ ret = {noun: int(count) for (count, noun) in outcomes}
585
+ break
586
+ else:
587
+ raise ValueError("Pytest terminal summary report not found")
588
+
589
+ to_plural = {
590
+ "warning": "warnings",
591
+ "error": "errors",
592
+ }
593
+ return {to_plural.get(k, k): v for k, v in ret.items()}
594
+
595
+ def assert_outcomes(
596
+ self,
597
+ passed: int = 0,
598
+ skipped: int = 0,
599
+ failed: int = 0,
600
+ errors: int = 0,
601
+ xpassed: int = 0,
602
+ xfailed: int = 0,
603
+ warnings: Optional[int] = None,
604
+ deselected: Optional[int] = None,
605
+ ) -> None:
606
+ """
607
+ Assert that the specified outcomes appear with the respective
608
+ numbers (0 means it didn't occur) in the text output from a test run.
609
+
610
+ ``warnings`` and ``deselected`` are only checked if not None.
611
+ """
612
+ __tracebackhide__ = True
613
+ from _pytest.pytester_assertions import assert_outcomes
614
+
615
+ outcomes = self.parseoutcomes()
616
+ assert_outcomes(
617
+ outcomes,
618
+ passed=passed,
619
+ skipped=skipped,
620
+ failed=failed,
621
+ errors=errors,
622
+ xpassed=xpassed,
623
+ xfailed=xfailed,
624
+ warnings=warnings,
625
+ deselected=deselected,
626
+ )
627
+
628
+
629
+ class CwdSnapshot:
630
+ def __init__(self) -> None:
631
+ self.__saved = os.getcwd()
632
+
633
+ def restore(self) -> None:
634
+ os.chdir(self.__saved)
635
+
636
+
637
+ class SysModulesSnapshot:
638
+ def __init__(self, preserve: Optional[Callable[[str], bool]] = None) -> None:
639
+ self.__preserve = preserve
640
+ self.__saved = dict(sys.modules)
641
+
642
+ def restore(self) -> None:
643
+ if self.__preserve:
644
+ self.__saved.update(
645
+ (k, m) for k, m in sys.modules.items() if self.__preserve(k)
646
+ )
647
+ sys.modules.clear()
648
+ sys.modules.update(self.__saved)
649
+
650
+
651
+ class SysPathsSnapshot:
652
+ def __init__(self) -> None:
653
+ self.__saved = list(sys.path), list(sys.meta_path)
654
+
655
+ def restore(self) -> None:
656
+ sys.path[:], sys.meta_path[:] = self.__saved
657
+
658
+
659
+ @final
660
+ class Pytester:
661
+ """
662
+ Facilities to write tests/configuration files, execute pytest in isolation, and match
663
+ against expected output, perfect for black-box testing of pytest plugins.
664
+
665
+ It attempts to isolate the test run from external factors as much as possible, modifying
666
+ the current working directory to :attr:`path` and environment variables during initialization.
667
+ """
668
+
669
+ __test__ = False
670
+
671
+ CLOSE_STDIN: "Final" = NOTSET
672
+
673
+ class TimeoutExpired(Exception):
674
+ pass
675
+
676
+ def __init__(
677
+ self,
678
+ request: FixtureRequest,
679
+ tmp_path_factory: TempPathFactory,
680
+ monkeypatch: MonkeyPatch,
681
+ *,
682
+ _ispytest: bool = False,
683
+ ) -> None:
684
+ check_ispytest(_ispytest)
685
+ self._request = request
686
+ self._mod_collections: WeakKeyDictionary[
687
+ Collector, List[Union[Item, Collector]]
688
+ ] = WeakKeyDictionary()
689
+ if request.function:
690
+ name: str = request.function.__name__
691
+ else:
692
+ name = request.node.name
693
+ self._name = name
694
+ self._path: Path = tmp_path_factory.mktemp(name, numbered=True)
695
+ #: A list of plugins to use with :py:meth:`parseconfig` and
696
+ #: :py:meth:`runpytest`. Initially this is an empty list but plugins can
697
+ #: be added to the list. The type of items to add to the list depends on
698
+ #: the method using them so refer to them for details.
699
+ self.plugins: List[Union[str, _PluggyPlugin]] = []
700
+ self._cwd_snapshot = CwdSnapshot()
701
+ self._sys_path_snapshot = SysPathsSnapshot()
702
+ self._sys_modules_snapshot = self.__take_sys_modules_snapshot()
703
+ self.chdir()
704
+ self._request.addfinalizer(self._finalize)
705
+ self._method = self._request.config.getoption("--runpytest")
706
+ self._test_tmproot = tmp_path_factory.mktemp(f"tmp-{name}", numbered=True)
707
+
708
+ self._monkeypatch = mp = monkeypatch
709
+ mp.setenv("PYTEST_DEBUG_TEMPROOT", str(self._test_tmproot))
710
+ # Ensure no unexpected caching via tox.
711
+ mp.delenv("TOX_ENV_DIR", raising=False)
712
+ # Discard outer pytest options.
713
+ mp.delenv("PYTEST_ADDOPTS", raising=False)
714
+ # Ensure no user config is used.
715
+ tmphome = str(self.path)
716
+ mp.setenv("HOME", tmphome)
717
+ mp.setenv("USERPROFILE", tmphome)
718
+ # Do not use colors for inner runs by default.
719
+ mp.setenv("PY_COLORS", "0")
720
+
721
+ @property
722
+ def path(self) -> Path:
723
+ """Temporary directory path used to create files/run tests from, etc."""
724
+ return self._path
725
+
726
+ def __repr__(self) -> str:
727
+ return f"<Pytester {self.path!r}>"
728
+
729
+ def _finalize(self) -> None:
730
+ """
731
+ Clean up global state artifacts.
732
+
733
+ Some methods modify the global interpreter state and this tries to
734
+ clean this up. It does not remove the temporary directory however so
735
+ it can be looked at after the test run has finished.
736
+ """
737
+ self._sys_modules_snapshot.restore()
738
+ self._sys_path_snapshot.restore()
739
+ self._cwd_snapshot.restore()
740
+
741
+ def __take_sys_modules_snapshot(self) -> SysModulesSnapshot:
742
+ # Some zope modules used by twisted-related tests keep internal state
743
+ # and can't be deleted; we had some trouble in the past with
744
+ # `zope.interface` for example.
745
+ #
746
+ # Preserve readline due to https://bugs.python.org/issue41033.
747
+ # pexpect issues a SIGWINCH.
748
+ def preserve_module(name):
749
+ return name.startswith(("zope", "readline"))
750
+
751
+ return SysModulesSnapshot(preserve=preserve_module)
752
+
753
+ def make_hook_recorder(self, pluginmanager: PytestPluginManager) -> HookRecorder:
754
+ """Create a new :class:`HookRecorder` for a :class:`PytestPluginManager`."""
755
+ pluginmanager.reprec = reprec = HookRecorder(pluginmanager, _ispytest=True) # type: ignore[attr-defined]
756
+ self._request.addfinalizer(reprec.finish_recording)
757
+ return reprec
758
+
759
+ def chdir(self) -> None:
760
+ """Cd into the temporary directory.
761
+
762
+ This is done automatically upon instantiation.
763
+ """
764
+ os.chdir(self.path)
765
+
766
+ def _makefile(
767
+ self,
768
+ ext: str,
769
+ lines: Sequence[Union[Any, bytes]],
770
+ files: Dict[str, str],
771
+ encoding: str = "utf-8",
772
+ ) -> Path:
773
+ items = list(files.items())
774
+
775
+ if ext and not ext.startswith("."):
776
+ raise ValueError(
777
+ f"pytester.makefile expects a file extension, try .{ext} instead of {ext}"
778
+ )
779
+
780
+ def to_text(s: Union[Any, bytes]) -> str:
781
+ return s.decode(encoding) if isinstance(s, bytes) else str(s)
782
+
783
+ if lines:
784
+ source = "\n".join(to_text(x) for x in lines)
785
+ basename = self._name
786
+ items.insert(0, (basename, source))
787
+
788
+ ret = None
789
+ for basename, value in items:
790
+ p = self.path.joinpath(basename).with_suffix(ext)
791
+ p.parent.mkdir(parents=True, exist_ok=True)
792
+ source_ = Source(value)
793
+ source = "\n".join(to_text(line) for line in source_.lines)
794
+ p.write_text(source.strip(), encoding=encoding)
795
+ if ret is None:
796
+ ret = p
797
+ assert ret is not None
798
+ return ret
799
+
800
+ def makefile(self, ext: str, *args: str, **kwargs: str) -> Path:
801
+ r"""Create new text file(s) in the test directory.
802
+
803
+ :param ext:
804
+ The extension the file(s) should use, including the dot, e.g. `.py`.
805
+ :param args:
806
+ All args are treated as strings and joined using newlines.
807
+ The result is written as contents to the file. The name of the
808
+ file is based on the test function requesting this fixture.
809
+ :param kwargs:
810
+ Each keyword is the name of a file, while the value of it will
811
+ be written as contents of the file.
812
+ :returns:
813
+ The first created file.
814
+
815
+ Examples:
816
+
817
+ .. code-block:: python
818
+
819
+ pytester.makefile(".txt", "line1", "line2")
820
+
821
+ pytester.makefile(".ini", pytest="[pytest]\naddopts=-rs\n")
822
+
823
+ To create binary files, use :meth:`pathlib.Path.write_bytes` directly:
824
+
825
+ .. code-block:: python
826
+
827
+ filename = pytester.path.joinpath("foo.bin")
828
+ filename.write_bytes(b"...")
829
+ """
830
+ return self._makefile(ext, args, kwargs)
831
+
832
+ def makeconftest(self, source: str) -> Path:
833
+ """Write a contest.py file.
834
+
835
+ :param source: The contents.
836
+ :returns: The conftest.py file.
837
+ """
838
+ return self.makepyfile(conftest=source)
839
+
840
+ def makeini(self, source: str) -> Path:
841
+ """Write a tox.ini file.
842
+
843
+ :param source: The contents.
844
+ :returns: The tox.ini file.
845
+ """
846
+ return self.makefile(".ini", tox=source)
847
+
848
+ def getinicfg(self, source: str) -> SectionWrapper:
849
+ """Return the pytest section from the tox.ini config file."""
850
+ p = self.makeini(source)
851
+ return IniConfig(str(p))["pytest"]
852
+
853
+ def makepyprojecttoml(self, source: str) -> Path:
854
+ """Write a pyproject.toml file.
855
+
856
+ :param source: The contents.
857
+ :returns: The pyproject.ini file.
858
+
859
+ .. versionadded:: 6.0
860
+ """
861
+ return self.makefile(".toml", pyproject=source)
862
+
863
+ def makepyfile(self, *args, **kwargs) -> Path:
864
+ r"""Shortcut for .makefile() with a .py extension.
865
+
866
+ Defaults to the test name with a '.py' extension, e.g test_foobar.py, overwriting
867
+ existing files.
868
+
869
+ Examples:
870
+
871
+ .. code-block:: python
872
+
873
+ def test_something(pytester):
874
+ # Initial file is created test_something.py.
875
+ pytester.makepyfile("foobar")
876
+ # To create multiple files, pass kwargs accordingly.
877
+ pytester.makepyfile(custom="foobar")
878
+ # At this point, both 'test_something.py' & 'custom.py' exist in the test directory.
879
+
880
+ """
881
+ return self._makefile(".py", args, kwargs)
882
+
883
+ def maketxtfile(self, *args, **kwargs) -> Path:
884
+ r"""Shortcut for .makefile() with a .txt extension.
885
+
886
+ Defaults to the test name with a '.txt' extension, e.g test_foobar.txt, overwriting
887
+ existing files.
888
+
889
+ Examples:
890
+
891
+ .. code-block:: python
892
+
893
+ def test_something(pytester):
894
+ # Initial file is created test_something.txt.
895
+ pytester.maketxtfile("foobar")
896
+ # To create multiple files, pass kwargs accordingly.
897
+ pytester.maketxtfile(custom="foobar")
898
+ # At this point, both 'test_something.txt' & 'custom.txt' exist in the test directory.
899
+
900
+ """
901
+ return self._makefile(".txt", args, kwargs)
902
+
903
+ def syspathinsert(
904
+ self, path: Optional[Union[str, "os.PathLike[str]"]] = None
905
+ ) -> None:
906
+ """Prepend a directory to sys.path, defaults to :attr:`path`.
907
+
908
+ This is undone automatically when this object dies at the end of each
909
+ test.
910
+
911
+ :param path:
912
+ The path.
913
+ """
914
+ if path is None:
915
+ path = self.path
916
+
917
+ self._monkeypatch.syspath_prepend(str(path))
918
+
919
+ def mkdir(self, name: Union[str, "os.PathLike[str]"]) -> Path:
920
+ """Create a new (sub)directory.
921
+
922
+ :param name:
923
+ The name of the directory, relative to the pytester path.
924
+ :returns:
925
+ The created directory.
926
+ """
927
+ p = self.path / name
928
+ p.mkdir()
929
+ return p
930
+
931
+ def mkpydir(self, name: Union[str, "os.PathLike[str]"]) -> Path:
932
+ """Create a new python package.
933
+
934
+ This creates a (sub)directory with an empty ``__init__.py`` file so it
935
+ gets recognised as a Python package.
936
+ """
937
+ p = self.path / name
938
+ p.mkdir()
939
+ p.joinpath("__init__.py").touch()
940
+ return p
941
+
942
+ def copy_example(self, name: Optional[str] = None) -> Path:
943
+ """Copy file from project's directory into the testdir.
944
+
945
+ :param name:
946
+ The name of the file to copy.
947
+ :return:
948
+ Path to the copied directory (inside ``self.path``).
949
+ """
950
+ example_dir_ = self._request.config.getini("pytester_example_dir")
951
+ if example_dir_ is None:
952
+ raise ValueError("pytester_example_dir is unset, can't copy examples")
953
+ example_dir: Path = self._request.config.rootpath / example_dir_
954
+
955
+ for extra_element in self._request.node.iter_markers("pytester_example_path"):
956
+ assert extra_element.args
957
+ example_dir = example_dir.joinpath(*extra_element.args)
958
+
959
+ if name is None:
960
+ func_name = self._name
961
+ maybe_dir = example_dir / func_name
962
+ maybe_file = example_dir / (func_name + ".py")
963
+
964
+ if maybe_dir.is_dir():
965
+ example_path = maybe_dir
966
+ elif maybe_file.is_file():
967
+ example_path = maybe_file
968
+ else:
969
+ raise LookupError(
970
+ f"{func_name} can't be found as module or package in {example_dir}"
971
+ )
972
+ else:
973
+ example_path = example_dir.joinpath(name)
974
+
975
+ if example_path.is_dir() and not example_path.joinpath("__init__.py").is_file():
976
+ copytree(example_path, self.path)
977
+ return self.path
978
+ elif example_path.is_file():
979
+ result = self.path.joinpath(example_path.name)
980
+ shutil.copy(example_path, result)
981
+ return result
982
+ else:
983
+ raise LookupError(
984
+ f'example "{example_path}" is not found as a file or directory'
985
+ )
986
+
987
+ def getnode(
988
+ self, config: Config, arg: Union[str, "os.PathLike[str]"]
989
+ ) -> Union[Collector, Item]:
990
+ """Get the collection node of a file.
991
+
992
+ :param config:
993
+ A pytest config.
994
+ See :py:meth:`parseconfig` and :py:meth:`parseconfigure` for creating it.
995
+ :param arg:
996
+ Path to the file.
997
+ :returns:
998
+ The node.
999
+ """
1000
+ session = Session.from_config(config)
1001
+ assert "::" not in str(arg)
1002
+ p = Path(os.path.abspath(arg))
1003
+ config.hook.pytest_sessionstart(session=session)
1004
+ res = session.perform_collect([str(p)], genitems=False)[0]
1005
+ config.hook.pytest_sessionfinish(session=session, exitstatus=ExitCode.OK)
1006
+ return res
1007
+
1008
+ def getpathnode(
1009
+ self, path: Union[str, "os.PathLike[str]"]
1010
+ ) -> Union[Collector, Item]:
1011
+ """Return the collection node of a file.
1012
+
1013
+ This is like :py:meth:`getnode` but uses :py:meth:`parseconfigure` to
1014
+ create the (configured) pytest Config instance.
1015
+
1016
+ :param path:
1017
+ Path to the file.
1018
+ :returns:
1019
+ The node.
1020
+ """
1021
+ path = Path(path)
1022
+ config = self.parseconfigure(path)
1023
+ session = Session.from_config(config)
1024
+ x = bestrelpath(session.path, path)
1025
+ config.hook.pytest_sessionstart(session=session)
1026
+ res = session.perform_collect([x], genitems=False)[0]
1027
+ config.hook.pytest_sessionfinish(session=session, exitstatus=ExitCode.OK)
1028
+ return res
1029
+
1030
+ def genitems(self, colitems: Sequence[Union[Item, Collector]]) -> List[Item]:
1031
+ """Generate all test items from a collection node.
1032
+
1033
+ This recurses into the collection node and returns a list of all the
1034
+ test items contained within.
1035
+
1036
+ :param colitems:
1037
+ The collection nodes.
1038
+ :returns:
1039
+ The collected items.
1040
+ """
1041
+ session = colitems[0].session
1042
+ result: List[Item] = []
1043
+ for colitem in colitems:
1044
+ result.extend(session.genitems(colitem))
1045
+ return result
1046
+
1047
+ def runitem(self, source: str) -> Any:
1048
+ """Run the "test_func" Item.
1049
+
1050
+ The calling test instance (class containing the test method) must
1051
+ provide a ``.getrunner()`` method which should return a runner which
1052
+ can run the test protocol for a single item, e.g.
1053
+ :py:func:`_pytest.runner.runtestprotocol`.
1054
+ """
1055
+ # used from runner functional tests
1056
+ item = self.getitem(source)
1057
+ # the test class where we are called from wants to provide the runner
1058
+ testclassinstance = self._request.instance
1059
+ runner = testclassinstance.getrunner()
1060
+ return runner(item)
1061
+
1062
+ def inline_runsource(self, source: str, *cmdlineargs) -> HookRecorder:
1063
+ """Run a test module in process using ``pytest.main()``.
1064
+
1065
+ This run writes "source" into a temporary file and runs
1066
+ ``pytest.main()`` on it, returning a :py:class:`HookRecorder` instance
1067
+ for the result.
1068
+
1069
+ :param source: The source code of the test module.
1070
+ :param cmdlineargs: Any extra command line arguments to use.
1071
+ """
1072
+ p = self.makepyfile(source)
1073
+ values = list(cmdlineargs) + [p]
1074
+ return self.inline_run(*values)
1075
+
1076
+ def inline_genitems(self, *args) -> Tuple[List[Item], HookRecorder]:
1077
+ """Run ``pytest.main(['--collectonly'])`` in-process.
1078
+
1079
+ Runs the :py:func:`pytest.main` function to run all of pytest inside
1080
+ the test process itself like :py:meth:`inline_run`, but returns a
1081
+ tuple of the collected items and a :py:class:`HookRecorder` instance.
1082
+ """
1083
+ rec = self.inline_run("--collect-only", *args)
1084
+ items = [x.item for x in rec.getcalls("pytest_itemcollected")]
1085
+ return items, rec
1086
+
1087
+ def inline_run(
1088
+ self,
1089
+ *args: Union[str, "os.PathLike[str]"],
1090
+ plugins=(),
1091
+ no_reraise_ctrlc: bool = False,
1092
+ ) -> HookRecorder:
1093
+ """Run ``pytest.main()`` in-process, returning a HookRecorder.
1094
+
1095
+ Runs the :py:func:`pytest.main` function to run all of pytest inside
1096
+ the test process itself. This means it can return a
1097
+ :py:class:`HookRecorder` instance which gives more detailed results
1098
+ from that run than can be done by matching stdout/stderr from
1099
+ :py:meth:`runpytest`.
1100
+
1101
+ :param args:
1102
+ Command line arguments to pass to :py:func:`pytest.main`.
1103
+ :param plugins:
1104
+ Extra plugin instances the ``pytest.main()`` instance should use.
1105
+ :param no_reraise_ctrlc:
1106
+ Typically we reraise keyboard interrupts from the child run. If
1107
+ True, the KeyboardInterrupt exception is captured.
1108
+ """
1109
+ # (maybe a cpython bug?) the importlib cache sometimes isn't updated
1110
+ # properly between file creation and inline_run (especially if imports
1111
+ # are interspersed with file creation)
1112
+ importlib.invalidate_caches()
1113
+
1114
+ plugins = list(plugins)
1115
+ finalizers = []
1116
+ try:
1117
+ # Any sys.module or sys.path changes done while running pytest
1118
+ # inline should be reverted after the test run completes to avoid
1119
+ # clashing with later inline tests run within the same pytest test,
1120
+ # e.g. just because they use matching test module names.
1121
+ finalizers.append(self.__take_sys_modules_snapshot().restore)
1122
+ finalizers.append(SysPathsSnapshot().restore)
1123
+
1124
+ # Important note:
1125
+ # - our tests should not leave any other references/registrations
1126
+ # laying around other than possibly loaded test modules
1127
+ # referenced from sys.modules, as nothing will clean those up
1128
+ # automatically
1129
+
1130
+ rec = []
1131
+
1132
+ class Collect:
1133
+ def pytest_configure(x, config: Config) -> None:
1134
+ rec.append(self.make_hook_recorder(config.pluginmanager))
1135
+
1136
+ plugins.append(Collect())
1137
+ ret = main([str(x) for x in args], plugins=plugins)
1138
+ if len(rec) == 1:
1139
+ reprec = rec.pop()
1140
+ else:
1141
+
1142
+ class reprec: # type: ignore
1143
+ pass
1144
+
1145
+ reprec.ret = ret
1146
+
1147
+ # Typically we reraise keyboard interrupts from the child run
1148
+ # because it's our user requesting interruption of the testing.
1149
+ if ret == ExitCode.INTERRUPTED and not no_reraise_ctrlc:
1150
+ calls = reprec.getcalls("pytest_keyboard_interrupt")
1151
+ if calls and calls[-1].excinfo.type == KeyboardInterrupt:
1152
+ raise KeyboardInterrupt()
1153
+ return reprec
1154
+ finally:
1155
+ for finalizer in finalizers:
1156
+ finalizer()
1157
+
1158
+ def runpytest_inprocess(
1159
+ self, *args: Union[str, "os.PathLike[str]"], **kwargs: Any
1160
+ ) -> RunResult:
1161
+ """Return result of running pytest in-process, providing a similar
1162
+ interface to what self.runpytest() provides."""
1163
+ syspathinsert = kwargs.pop("syspathinsert", False)
1164
+
1165
+ if syspathinsert:
1166
+ self.syspathinsert()
1167
+ now = timing.time()
1168
+ capture = _get_multicapture("sys")
1169
+ capture.start_capturing()
1170
+ try:
1171
+ try:
1172
+ reprec = self.inline_run(*args, **kwargs)
1173
+ except SystemExit as e:
1174
+ ret = e.args[0]
1175
+ try:
1176
+ ret = ExitCode(e.args[0])
1177
+ except ValueError:
1178
+ pass
1179
+
1180
+ class reprec: # type: ignore
1181
+ ret = ret
1182
+
1183
+ except Exception:
1184
+ traceback.print_exc()
1185
+
1186
+ class reprec: # type: ignore
1187
+ ret = ExitCode(3)
1188
+
1189
+ finally:
1190
+ out, err = capture.readouterr()
1191
+ capture.stop_capturing()
1192
+ sys.stdout.write(out)
1193
+ sys.stderr.write(err)
1194
+
1195
+ assert reprec.ret is not None
1196
+ res = RunResult(
1197
+ reprec.ret, out.splitlines(), err.splitlines(), timing.time() - now
1198
+ )
1199
+ res.reprec = reprec # type: ignore
1200
+ return res
1201
+
1202
+ def runpytest(
1203
+ self, *args: Union[str, "os.PathLike[str]"], **kwargs: Any
1204
+ ) -> RunResult:
1205
+ """Run pytest inline or in a subprocess, depending on the command line
1206
+ option "--runpytest" and return a :py:class:`~pytest.RunResult`."""
1207
+ new_args = self._ensure_basetemp(args)
1208
+ if self._method == "inprocess":
1209
+ return self.runpytest_inprocess(*new_args, **kwargs)
1210
+ elif self._method == "subprocess":
1211
+ return self.runpytest_subprocess(*new_args, **kwargs)
1212
+ raise RuntimeError(f"Unrecognized runpytest option: {self._method}")
1213
+
1214
+ def _ensure_basetemp(
1215
+ self, args: Sequence[Union[str, "os.PathLike[str]"]]
1216
+ ) -> List[Union[str, "os.PathLike[str]"]]:
1217
+ new_args = list(args)
1218
+ for x in new_args:
1219
+ if str(x).startswith("--basetemp"):
1220
+ break
1221
+ else:
1222
+ new_args.append("--basetemp=%s" % self.path.parent.joinpath("basetemp"))
1223
+ return new_args
1224
+
1225
+ def parseconfig(self, *args: Union[str, "os.PathLike[str]"]) -> Config:
1226
+ """Return a new pytest :class:`pytest.Config` instance from given
1227
+ commandline args.
1228
+
1229
+ This invokes the pytest bootstrapping code in _pytest.config to create a
1230
+ new :py:class:`pytest.PytestPluginManager` and call the
1231
+ :hook:`pytest_cmdline_parse` hook to create a new :class:`pytest.Config`
1232
+ instance.
1233
+
1234
+ If :attr:`plugins` has been populated they should be plugin modules
1235
+ to be registered with the plugin manager.
1236
+ """
1237
+ import _pytest.config
1238
+
1239
+ new_args = self._ensure_basetemp(args)
1240
+ new_args = [str(x) for x in new_args]
1241
+
1242
+ config = _pytest.config._prepareconfig(new_args, self.plugins) # type: ignore[arg-type]
1243
+ # we don't know what the test will do with this half-setup config
1244
+ # object and thus we make sure it gets unconfigured properly in any
1245
+ # case (otherwise capturing could still be active, for example)
1246
+ self._request.addfinalizer(config._ensure_unconfigure)
1247
+ return config
1248
+
1249
+ def parseconfigure(self, *args: Union[str, "os.PathLike[str]"]) -> Config:
1250
+ """Return a new pytest configured Config instance.
1251
+
1252
+ Returns a new :py:class:`pytest.Config` instance like
1253
+ :py:meth:`parseconfig`, but also calls the :hook:`pytest_configure`
1254
+ hook.
1255
+ """
1256
+ config = self.parseconfig(*args)
1257
+ config._do_configure()
1258
+ return config
1259
+
1260
+ def getitem(
1261
+ self, source: Union[str, "os.PathLike[str]"], funcname: str = "test_func"
1262
+ ) -> Item:
1263
+ """Return the test item for a test function.
1264
+
1265
+ Writes the source to a python file and runs pytest's collection on
1266
+ the resulting module, returning the test item for the requested
1267
+ function name.
1268
+
1269
+ :param source:
1270
+ The module source.
1271
+ :param funcname:
1272
+ The name of the test function for which to return a test item.
1273
+ :returns:
1274
+ The test item.
1275
+ """
1276
+ items = self.getitems(source)
1277
+ for item in items:
1278
+ if item.name == funcname:
1279
+ return item
1280
+ assert 0, "{!r} item not found in module:\n{}\nitems: {}".format(
1281
+ funcname, source, items
1282
+ )
1283
+
1284
+ def getitems(self, source: Union[str, "os.PathLike[str]"]) -> List[Item]:
1285
+ """Return all test items collected from the module.
1286
+
1287
+ Writes the source to a Python file and runs pytest's collection on
1288
+ the resulting module, returning all test items contained within.
1289
+ """
1290
+ modcol = self.getmodulecol(source)
1291
+ return self.genitems([modcol])
1292
+
1293
+ def getmodulecol(
1294
+ self,
1295
+ source: Union[str, "os.PathLike[str]"],
1296
+ configargs=(),
1297
+ *,
1298
+ withinit: bool = False,
1299
+ ):
1300
+ """Return the module collection node for ``source``.
1301
+
1302
+ Writes ``source`` to a file using :py:meth:`makepyfile` and then
1303
+ runs the pytest collection on it, returning the collection node for the
1304
+ test module.
1305
+
1306
+ :param source:
1307
+ The source code of the module to collect.
1308
+
1309
+ :param configargs:
1310
+ Any extra arguments to pass to :py:meth:`parseconfigure`.
1311
+
1312
+ :param withinit:
1313
+ Whether to also write an ``__init__.py`` file to the same
1314
+ directory to ensure it is a package.
1315
+ """
1316
+ if isinstance(source, os.PathLike):
1317
+ path = self.path.joinpath(source)
1318
+ assert not withinit, "not supported for paths"
1319
+ else:
1320
+ kw = {self._name: str(source)}
1321
+ path = self.makepyfile(**kw)
1322
+ if withinit:
1323
+ self.makepyfile(__init__="#")
1324
+ self.config = config = self.parseconfigure(path, *configargs)
1325
+ return self.getnode(config, path)
1326
+
1327
+ def collect_by_name(
1328
+ self, modcol: Collector, name: str
1329
+ ) -> Optional[Union[Item, Collector]]:
1330
+ """Return the collection node for name from the module collection.
1331
+
1332
+ Searches a module collection node for a collection node matching the
1333
+ given name.
1334
+
1335
+ :param modcol: A module collection node; see :py:meth:`getmodulecol`.
1336
+ :param name: The name of the node to return.
1337
+ """
1338
+ if modcol not in self._mod_collections:
1339
+ self._mod_collections[modcol] = list(modcol.collect())
1340
+ for colitem in self._mod_collections[modcol]:
1341
+ if colitem.name == name:
1342
+ return colitem
1343
+ return None
1344
+
1345
+ def popen(
1346
+ self,
1347
+ cmdargs: Sequence[Union[str, "os.PathLike[str]"]],
1348
+ stdout: Union[int, TextIO] = subprocess.PIPE,
1349
+ stderr: Union[int, TextIO] = subprocess.PIPE,
1350
+ stdin: Union[NotSetType, bytes, IO[Any], int] = CLOSE_STDIN,
1351
+ **kw,
1352
+ ):
1353
+ """Invoke :py:class:`subprocess.Popen`.
1354
+
1355
+ Calls :py:class:`subprocess.Popen` making sure the current working
1356
+ directory is in ``PYTHONPATH``.
1357
+
1358
+ You probably want to use :py:meth:`run` instead.
1359
+ """
1360
+ env = os.environ.copy()
1361
+ env["PYTHONPATH"] = os.pathsep.join(
1362
+ filter(None, [os.getcwd(), env.get("PYTHONPATH", "")])
1363
+ )
1364
+ kw["env"] = env
1365
+
1366
+ if stdin is self.CLOSE_STDIN:
1367
+ kw["stdin"] = subprocess.PIPE
1368
+ elif isinstance(stdin, bytes):
1369
+ kw["stdin"] = subprocess.PIPE
1370
+ else:
1371
+ kw["stdin"] = stdin
1372
+
1373
+ popen = subprocess.Popen(cmdargs, stdout=stdout, stderr=stderr, **kw)
1374
+ if stdin is self.CLOSE_STDIN:
1375
+ assert popen.stdin is not None
1376
+ popen.stdin.close()
1377
+ elif isinstance(stdin, bytes):
1378
+ assert popen.stdin is not None
1379
+ popen.stdin.write(stdin)
1380
+
1381
+ return popen
1382
+
1383
+ def run(
1384
+ self,
1385
+ *cmdargs: Union[str, "os.PathLike[str]"],
1386
+ timeout: Optional[float] = None,
1387
+ stdin: Union[NotSetType, bytes, IO[Any], int] = CLOSE_STDIN,
1388
+ ) -> RunResult:
1389
+ """Run a command with arguments.
1390
+
1391
+ Run a process using :py:class:`subprocess.Popen` saving the stdout and
1392
+ stderr.
1393
+
1394
+ :param cmdargs:
1395
+ The sequence of arguments to pass to :py:class:`subprocess.Popen`,
1396
+ with path-like objects being converted to :py:class:`str`
1397
+ automatically.
1398
+ :param timeout:
1399
+ The period in seconds after which to timeout and raise
1400
+ :py:class:`Pytester.TimeoutExpired`.
1401
+ :param stdin:
1402
+ Optional standard input.
1403
+
1404
+ - If it is :py:attr:`CLOSE_STDIN` (Default), then this method calls
1405
+ :py:class:`subprocess.Popen` with ``stdin=subprocess.PIPE``, and
1406
+ the standard input is closed immediately after the new command is
1407
+ started.
1408
+
1409
+ - If it is of type :py:class:`bytes`, these bytes are sent to the
1410
+ standard input of the command.
1411
+
1412
+ - Otherwise, it is passed through to :py:class:`subprocess.Popen`.
1413
+ For further information in this case, consult the document of the
1414
+ ``stdin`` parameter in :py:class:`subprocess.Popen`.
1415
+ :returns:
1416
+ The result.
1417
+ """
1418
+ __tracebackhide__ = True
1419
+
1420
+ cmdargs = tuple(os.fspath(arg) for arg in cmdargs)
1421
+ p1 = self.path.joinpath("stdout")
1422
+ p2 = self.path.joinpath("stderr")
1423
+ print("running:", *cmdargs)
1424
+ print(" in:", Path.cwd())
1425
+
1426
+ with p1.open("w", encoding="utf8") as f1, p2.open("w", encoding="utf8") as f2:
1427
+ now = timing.time()
1428
+ popen = self.popen(
1429
+ cmdargs,
1430
+ stdin=stdin,
1431
+ stdout=f1,
1432
+ stderr=f2,
1433
+ close_fds=(sys.platform != "win32"),
1434
+ )
1435
+ if popen.stdin is not None:
1436
+ popen.stdin.close()
1437
+
1438
+ def handle_timeout() -> None:
1439
+ __tracebackhide__ = True
1440
+
1441
+ timeout_message = (
1442
+ "{seconds} second timeout expired running:"
1443
+ " {command}".format(seconds=timeout, command=cmdargs)
1444
+ )
1445
+
1446
+ popen.kill()
1447
+ popen.wait()
1448
+ raise self.TimeoutExpired(timeout_message)
1449
+
1450
+ if timeout is None:
1451
+ ret = popen.wait()
1452
+ else:
1453
+ try:
1454
+ ret = popen.wait(timeout)
1455
+ except subprocess.TimeoutExpired:
1456
+ handle_timeout()
1457
+
1458
+ with p1.open(encoding="utf8") as f1, p2.open(encoding="utf8") as f2:
1459
+ out = f1.read().splitlines()
1460
+ err = f2.read().splitlines()
1461
+
1462
+ self._dump_lines(out, sys.stdout)
1463
+ self._dump_lines(err, sys.stderr)
1464
+
1465
+ with contextlib.suppress(ValueError):
1466
+ ret = ExitCode(ret)
1467
+ return RunResult(ret, out, err, timing.time() - now)
1468
+
1469
+ def _dump_lines(self, lines, fp):
1470
+ try:
1471
+ for line in lines:
1472
+ print(line, file=fp)
1473
+ except UnicodeEncodeError:
1474
+ print(f"couldn't print to {fp} because of encoding")
1475
+
1476
+ def _getpytestargs(self) -> Tuple[str, ...]:
1477
+ return sys.executable, "-mpytest"
1478
+
1479
+ def runpython(self, script: "os.PathLike[str]") -> RunResult:
1480
+ """Run a python script using sys.executable as interpreter."""
1481
+ return self.run(sys.executable, script)
1482
+
1483
+ def runpython_c(self, command: str) -> RunResult:
1484
+ """Run ``python -c "command"``."""
1485
+ return self.run(sys.executable, "-c", command)
1486
+
1487
+ def runpytest_subprocess(
1488
+ self, *args: Union[str, "os.PathLike[str]"], timeout: Optional[float] = None
1489
+ ) -> RunResult:
1490
+ """Run pytest as a subprocess with given arguments.
1491
+
1492
+ Any plugins added to the :py:attr:`plugins` list will be added using the
1493
+ ``-p`` command line option. Additionally ``--basetemp`` is used to put
1494
+ any temporary files and directories in a numbered directory prefixed
1495
+ with "runpytest-" to not conflict with the normal numbered pytest
1496
+ location for temporary files and directories.
1497
+
1498
+ :param args:
1499
+ The sequence of arguments to pass to the pytest subprocess.
1500
+ :param timeout:
1501
+ The period in seconds after which to timeout and raise
1502
+ :py:class:`Pytester.TimeoutExpired`.
1503
+ :returns:
1504
+ The result.
1505
+ """
1506
+ __tracebackhide__ = True
1507
+ p = make_numbered_dir(root=self.path, prefix="runpytest-", mode=0o700)
1508
+ args = ("--basetemp=%s" % p,) + args
1509
+ plugins = [x for x in self.plugins if isinstance(x, str)]
1510
+ if plugins:
1511
+ args = ("-p", plugins[0]) + args
1512
+ args = self._getpytestargs() + args
1513
+ return self.run(*args, timeout=timeout)
1514
+
1515
+ def spawn_pytest(
1516
+ self, string: str, expect_timeout: float = 10.0
1517
+ ) -> "pexpect.spawn":
1518
+ """Run pytest using pexpect.
1519
+
1520
+ This makes sure to use the right pytest and sets up the temporary
1521
+ directory locations.
1522
+
1523
+ The pexpect child is returned.
1524
+ """
1525
+ basetemp = self.path / "temp-pexpect"
1526
+ basetemp.mkdir(mode=0o700)
1527
+ invoke = " ".join(map(str, self._getpytestargs()))
1528
+ cmd = f"{invoke} --basetemp={basetemp} {string}"
1529
+ return self.spawn(cmd, expect_timeout=expect_timeout)
1530
+
1531
+ def spawn(self, cmd: str, expect_timeout: float = 10.0) -> "pexpect.spawn":
1532
+ """Run a command using pexpect.
1533
+
1534
+ The pexpect child is returned.
1535
+ """
1536
+ pexpect = importorskip("pexpect", "3.0")
1537
+ if hasattr(sys, "pypy_version_info") and "64" in platform.machine():
1538
+ skip("pypy-64 bit not supported")
1539
+ if not hasattr(pexpect, "spawn"):
1540
+ skip("pexpect.spawn not available")
1541
+ logfile = self.path.joinpath("spawn.out").open("wb")
1542
+
1543
+ child = pexpect.spawn(cmd, logfile=logfile, timeout=expect_timeout)
1544
+ self._request.addfinalizer(logfile.close)
1545
+ return child
1546
+
1547
+
1548
+ class LineComp:
1549
+ def __init__(self) -> None:
1550
+ self.stringio = StringIO()
1551
+ """:class:`python:io.StringIO()` instance used for input."""
1552
+
1553
+ def assert_contains_lines(self, lines2: Sequence[str]) -> None:
1554
+ """Assert that ``lines2`` are contained (linearly) in :attr:`stringio`'s value.
1555
+
1556
+ Lines are matched using :func:`LineMatcher.fnmatch_lines <pytest.LineMatcher.fnmatch_lines>`.
1557
+ """
1558
+ __tracebackhide__ = True
1559
+ val = self.stringio.getvalue()
1560
+ self.stringio.truncate(0)
1561
+ self.stringio.seek(0)
1562
+ lines1 = val.split("\n")
1563
+ LineMatcher(lines1).fnmatch_lines(lines2)
1564
+
1565
+
1566
+ class LineMatcher:
1567
+ """Flexible matching of text.
1568
+
1569
+ This is a convenience class to test large texts like the output of
1570
+ commands.
1571
+
1572
+ The constructor takes a list of lines without their trailing newlines, i.e.
1573
+ ``text.splitlines()``.
1574
+ """
1575
+
1576
+ def __init__(self, lines: List[str]) -> None:
1577
+ self.lines = lines
1578
+ self._log_output: List[str] = []
1579
+
1580
+ def __str__(self) -> str:
1581
+ """Return the entire original text.
1582
+
1583
+ .. versionadded:: 6.2
1584
+ You can use :meth:`str` in older versions.
1585
+ """
1586
+ return "\n".join(self.lines)
1587
+
1588
+ def _getlines(self, lines2: Union[str, Sequence[str], Source]) -> Sequence[str]:
1589
+ if isinstance(lines2, str):
1590
+ lines2 = Source(lines2)
1591
+ if isinstance(lines2, Source):
1592
+ lines2 = lines2.strip().lines
1593
+ return lines2
1594
+
1595
+ def fnmatch_lines_random(self, lines2: Sequence[str]) -> None:
1596
+ """Check lines exist in the output in any order (using :func:`python:fnmatch.fnmatch`)."""
1597
+ __tracebackhide__ = True
1598
+ self._match_lines_random(lines2, fnmatch)
1599
+
1600
+ def re_match_lines_random(self, lines2: Sequence[str]) -> None:
1601
+ """Check lines exist in the output in any order (using :func:`python:re.match`)."""
1602
+ __tracebackhide__ = True
1603
+ self._match_lines_random(lines2, lambda name, pat: bool(re.match(pat, name)))
1604
+
1605
+ def _match_lines_random(
1606
+ self, lines2: Sequence[str], match_func: Callable[[str, str], bool]
1607
+ ) -> None:
1608
+ __tracebackhide__ = True
1609
+ lines2 = self._getlines(lines2)
1610
+ for line in lines2:
1611
+ for x in self.lines:
1612
+ if line == x or match_func(x, line):
1613
+ self._log("matched: ", repr(line))
1614
+ break
1615
+ else:
1616
+ msg = "line %r not found in output" % line
1617
+ self._log(msg)
1618
+ self._fail(msg)
1619
+
1620
+ def get_lines_after(self, fnline: str) -> Sequence[str]:
1621
+ """Return all lines following the given line in the text.
1622
+
1623
+ The given line can contain glob wildcards.
1624
+ """
1625
+ for i, line in enumerate(self.lines):
1626
+ if fnline == line or fnmatch(line, fnline):
1627
+ return self.lines[i + 1 :]
1628
+ raise ValueError("line %r not found in output" % fnline)
1629
+
1630
+ def _log(self, *args) -> None:
1631
+ self._log_output.append(" ".join(str(x) for x in args))
1632
+
1633
+ @property
1634
+ def _log_text(self) -> str:
1635
+ return "\n".join(self._log_output)
1636
+
1637
+ def fnmatch_lines(
1638
+ self, lines2: Sequence[str], *, consecutive: bool = False
1639
+ ) -> None:
1640
+ """Check lines exist in the output (using :func:`python:fnmatch.fnmatch`).
1641
+
1642
+ The argument is a list of lines which have to match and can use glob
1643
+ wildcards. If they do not match a pytest.fail() is called. The
1644
+ matches and non-matches are also shown as part of the error message.
1645
+
1646
+ :param lines2: String patterns to match.
1647
+ :param consecutive: Match lines consecutively?
1648
+ """
1649
+ __tracebackhide__ = True
1650
+ self._match_lines(lines2, fnmatch, "fnmatch", consecutive=consecutive)
1651
+
1652
+ def re_match_lines(
1653
+ self, lines2: Sequence[str], *, consecutive: bool = False
1654
+ ) -> None:
1655
+ """Check lines exist in the output (using :func:`python:re.match`).
1656
+
1657
+ The argument is a list of lines which have to match using ``re.match``.
1658
+ If they do not match a pytest.fail() is called.
1659
+
1660
+ The matches and non-matches are also shown as part of the error message.
1661
+
1662
+ :param lines2: string patterns to match.
1663
+ :param consecutive: match lines consecutively?
1664
+ """
1665
+ __tracebackhide__ = True
1666
+ self._match_lines(
1667
+ lines2,
1668
+ lambda name, pat: bool(re.match(pat, name)),
1669
+ "re.match",
1670
+ consecutive=consecutive,
1671
+ )
1672
+
1673
+ def _match_lines(
1674
+ self,
1675
+ lines2: Sequence[str],
1676
+ match_func: Callable[[str, str], bool],
1677
+ match_nickname: str,
1678
+ *,
1679
+ consecutive: bool = False,
1680
+ ) -> None:
1681
+ """Underlying implementation of ``fnmatch_lines`` and ``re_match_lines``.
1682
+
1683
+ :param Sequence[str] lines2:
1684
+ List of string patterns to match. The actual format depends on
1685
+ ``match_func``.
1686
+ :param match_func:
1687
+ A callable ``match_func(line, pattern)`` where line is the
1688
+ captured line from stdout/stderr and pattern is the matching
1689
+ pattern.
1690
+ :param str match_nickname:
1691
+ The nickname for the match function that will be logged to stdout
1692
+ when a match occurs.
1693
+ :param consecutive:
1694
+ Match lines consecutively?
1695
+ """
1696
+ if not isinstance(lines2, collections.abc.Sequence):
1697
+ raise TypeError(f"invalid type for lines2: {type(lines2).__name__}")
1698
+ lines2 = self._getlines(lines2)
1699
+ lines1 = self.lines[:]
1700
+ extralines = []
1701
+ __tracebackhide__ = True
1702
+ wnick = len(match_nickname) + 1
1703
+ started = False
1704
+ for line in lines2:
1705
+ nomatchprinted = False
1706
+ while lines1:
1707
+ nextline = lines1.pop(0)
1708
+ if line == nextline:
1709
+ self._log("exact match:", repr(line))
1710
+ started = True
1711
+ break
1712
+ elif match_func(nextline, line):
1713
+ self._log("%s:" % match_nickname, repr(line))
1714
+ self._log(
1715
+ "{:>{width}}".format("with:", width=wnick), repr(nextline)
1716
+ )
1717
+ started = True
1718
+ break
1719
+ else:
1720
+ if consecutive and started:
1721
+ msg = f"no consecutive match: {line!r}"
1722
+ self._log(msg)
1723
+ self._log(
1724
+ "{:>{width}}".format("with:", width=wnick), repr(nextline)
1725
+ )
1726
+ self._fail(msg)
1727
+ if not nomatchprinted:
1728
+ self._log(
1729
+ "{:>{width}}".format("nomatch:", width=wnick), repr(line)
1730
+ )
1731
+ nomatchprinted = True
1732
+ self._log("{:>{width}}".format("and:", width=wnick), repr(nextline))
1733
+ extralines.append(nextline)
1734
+ else:
1735
+ msg = f"remains unmatched: {line!r}"
1736
+ self._log(msg)
1737
+ self._fail(msg)
1738
+ self._log_output = []
1739
+
1740
+ def no_fnmatch_line(self, pat: str) -> None:
1741
+ """Ensure captured lines do not match the given pattern, using ``fnmatch.fnmatch``.
1742
+
1743
+ :param str pat: The pattern to match lines.
1744
+ """
1745
+ __tracebackhide__ = True
1746
+ self._no_match_line(pat, fnmatch, "fnmatch")
1747
+
1748
+ def no_re_match_line(self, pat: str) -> None:
1749
+ """Ensure captured lines do not match the given pattern, using ``re.match``.
1750
+
1751
+ :param str pat: The regular expression to match lines.
1752
+ """
1753
+ __tracebackhide__ = True
1754
+ self._no_match_line(
1755
+ pat, lambda name, pat: bool(re.match(pat, name)), "re.match"
1756
+ )
1757
+
1758
+ def _no_match_line(
1759
+ self, pat: str, match_func: Callable[[str, str], bool], match_nickname: str
1760
+ ) -> None:
1761
+ """Ensure captured lines does not have a the given pattern, using ``fnmatch.fnmatch``.
1762
+
1763
+ :param str pat: The pattern to match lines.
1764
+ """
1765
+ __tracebackhide__ = True
1766
+ nomatch_printed = False
1767
+ wnick = len(match_nickname) + 1
1768
+ for line in self.lines:
1769
+ if match_func(line, pat):
1770
+ msg = f"{match_nickname}: {pat!r}"
1771
+ self._log(msg)
1772
+ self._log("{:>{width}}".format("with:", width=wnick), repr(line))
1773
+ self._fail(msg)
1774
+ else:
1775
+ if not nomatch_printed:
1776
+ self._log("{:>{width}}".format("nomatch:", width=wnick), repr(pat))
1777
+ nomatch_printed = True
1778
+ self._log("{:>{width}}".format("and:", width=wnick), repr(line))
1779
+ self._log_output = []
1780
+
1781
+ def _fail(self, msg: str) -> None:
1782
+ __tracebackhide__ = True
1783
+ log_text = self._log_text
1784
+ self._log_output = []
1785
+ fail(log_text)
1786
+
1787
+ def str(self) -> str:
1788
+ """Return the entire original text."""
1789
+ return str(self)
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/pytester_assertions.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helper plugin for pytester; should not be loaded on its own."""
2
+ # This plugin contains assertions used by pytester. pytester cannot
3
+ # contain them itself, since it is imported by the `pytest` module,
4
+ # hence cannot be subject to assertion rewriting, which requires a
5
+ # module to not be already imported.
6
+ from typing import Dict
7
+ from typing import Optional
8
+ from typing import Sequence
9
+ from typing import Tuple
10
+ from typing import Union
11
+
12
+ from _pytest.reports import CollectReport
13
+ from _pytest.reports import TestReport
14
+
15
+
16
+ def assertoutcome(
17
+ outcomes: Tuple[
18
+ Sequence[TestReport],
19
+ Sequence[Union[CollectReport, TestReport]],
20
+ Sequence[Union[CollectReport, TestReport]],
21
+ ],
22
+ passed: int = 0,
23
+ skipped: int = 0,
24
+ failed: int = 0,
25
+ ) -> None:
26
+ __tracebackhide__ = True
27
+
28
+ realpassed, realskipped, realfailed = outcomes
29
+ obtained = {
30
+ "passed": len(realpassed),
31
+ "skipped": len(realskipped),
32
+ "failed": len(realfailed),
33
+ }
34
+ expected = {"passed": passed, "skipped": skipped, "failed": failed}
35
+ assert obtained == expected, outcomes
36
+
37
+
38
+ def assert_outcomes(
39
+ outcomes: Dict[str, int],
40
+ passed: int = 0,
41
+ skipped: int = 0,
42
+ failed: int = 0,
43
+ errors: int = 0,
44
+ xpassed: int = 0,
45
+ xfailed: int = 0,
46
+ warnings: Optional[int] = None,
47
+ deselected: Optional[int] = None,
48
+ ) -> None:
49
+ """Assert that the specified outcomes appear with the respective
50
+ numbers (0 means it didn't occur) in the text output from a test run."""
51
+ __tracebackhide__ = True
52
+
53
+ obtained = {
54
+ "passed": outcomes.get("passed", 0),
55
+ "skipped": outcomes.get("skipped", 0),
56
+ "failed": outcomes.get("failed", 0),
57
+ "errors": outcomes.get("errors", 0),
58
+ "xpassed": outcomes.get("xpassed", 0),
59
+ "xfailed": outcomes.get("xfailed", 0),
60
+ }
61
+ expected = {
62
+ "passed": passed,
63
+ "skipped": skipped,
64
+ "failed": failed,
65
+ "errors": errors,
66
+ "xpassed": xpassed,
67
+ "xfailed": xfailed,
68
+ }
69
+ if warnings is not None:
70
+ obtained["warnings"] = outcomes.get("warnings", 0)
71
+ expected["warnings"] = warnings
72
+ if deselected is not None:
73
+ obtained["deselected"] = outcomes.get("deselected", 0)
74
+ expected["deselected"] = deselected
75
+ assert obtained == expected
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/python.py ADDED
@@ -0,0 +1,1843 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Python test discovery, setup and run of test functions."""
2
+ import dataclasses
3
+ import enum
4
+ import fnmatch
5
+ import inspect
6
+ import itertools
7
+ import os
8
+ import sys
9
+ import types
10
+ import warnings
11
+ from collections import Counter
12
+ from collections import defaultdict
13
+ from functools import partial
14
+ from pathlib import Path
15
+ from typing import Any
16
+ from typing import Callable
17
+ from typing import Dict
18
+ from typing import Generator
19
+ from typing import Iterable
20
+ from typing import Iterator
21
+ from typing import List
22
+ from typing import Mapping
23
+ from typing import Optional
24
+ from typing import Pattern
25
+ from typing import Sequence
26
+ from typing import Set
27
+ from typing import Tuple
28
+ from typing import TYPE_CHECKING
29
+ from typing import Union
30
+
31
+ import _pytest
32
+ from _pytest import fixtures
33
+ from _pytest import nodes
34
+ from _pytest._code import filter_traceback
35
+ from _pytest._code import getfslineno
36
+ from _pytest._code.code import ExceptionInfo
37
+ from _pytest._code.code import TerminalRepr
38
+ from _pytest._code.code import Traceback
39
+ from _pytest._io import TerminalWriter
40
+ from _pytest._io.saferepr import saferepr
41
+ from _pytest.compat import ascii_escaped
42
+ from _pytest.compat import assert_never
43
+ from _pytest.compat import final
44
+ from _pytest.compat import get_default_arg_names
45
+ from _pytest.compat import get_real_func
46
+ from _pytest.compat import getimfunc
47
+ from _pytest.compat import getlocation
48
+ from _pytest.compat import is_async_function
49
+ from _pytest.compat import is_generator
50
+ from _pytest.compat import LEGACY_PATH
51
+ from _pytest.compat import NOTSET
52
+ from _pytest.compat import safe_getattr
53
+ from _pytest.compat import safe_isclass
54
+ from _pytest.compat import STRING_TYPES
55
+ from _pytest.config import Config
56
+ from _pytest.config import ExitCode
57
+ from _pytest.config import hookimpl
58
+ from _pytest.config.argparsing import Parser
59
+ from _pytest.deprecated import check_ispytest
60
+ from _pytest.deprecated import INSTANCE_COLLECTOR
61
+ from _pytest.deprecated import NOSE_SUPPORT_METHOD
62
+ from _pytest.fixtures import FuncFixtureInfo
63
+ from _pytest.main import Session
64
+ from _pytest.mark import MARK_GEN
65
+ from _pytest.mark import ParameterSet
66
+ from _pytest.mark.structures import get_unpacked_marks
67
+ from _pytest.mark.structures import Mark
68
+ from _pytest.mark.structures import MarkDecorator
69
+ from _pytest.mark.structures import normalize_mark_list
70
+ from _pytest.outcomes import fail
71
+ from _pytest.outcomes import skip
72
+ from _pytest.pathlib import bestrelpath
73
+ from _pytest.pathlib import fnmatch_ex
74
+ from _pytest.pathlib import import_path
75
+ from _pytest.pathlib import ImportPathMismatchError
76
+ from _pytest.pathlib import parts
77
+ from _pytest.pathlib import visit
78
+ from _pytest.scope import Scope
79
+ from _pytest.warning_types import PytestCollectionWarning
80
+ from _pytest.warning_types import PytestReturnNotNoneWarning
81
+ from _pytest.warning_types import PytestUnhandledCoroutineWarning
82
+
83
+ if TYPE_CHECKING:
84
+ from typing_extensions import Literal
85
+
86
+ from _pytest.scope import _ScopeName
87
+
88
+
89
+ _PYTEST_DIR = Path(_pytest.__file__).parent
90
+
91
+
92
+ def pytest_addoption(parser: Parser) -> None:
93
+ group = parser.getgroup("general")
94
+ group.addoption(
95
+ "--fixtures",
96
+ "--funcargs",
97
+ action="store_true",
98
+ dest="showfixtures",
99
+ default=False,
100
+ help="Show available fixtures, sorted by plugin appearance "
101
+ "(fixtures with leading '_' are only shown with '-v')",
102
+ )
103
+ group.addoption(
104
+ "--fixtures-per-test",
105
+ action="store_true",
106
+ dest="show_fixtures_per_test",
107
+ default=False,
108
+ help="Show fixtures per test",
109
+ )
110
+ parser.addini(
111
+ "python_files",
112
+ type="args",
113
+ # NOTE: default is also used in AssertionRewritingHook.
114
+ default=["test_*.py", "*_test.py"],
115
+ help="Glob-style file patterns for Python test module discovery",
116
+ )
117
+ parser.addini(
118
+ "python_classes",
119
+ type="args",
120
+ default=["Test"],
121
+ help="Prefixes or glob names for Python test class discovery",
122
+ )
123
+ parser.addini(
124
+ "python_functions",
125
+ type="args",
126
+ default=["test"],
127
+ help="Prefixes or glob names for Python test function and method discovery",
128
+ )
129
+ parser.addini(
130
+ "disable_test_id_escaping_and_forfeit_all_rights_to_community_support",
131
+ type="bool",
132
+ default=False,
133
+ help="Disable string escape non-ASCII characters, might cause unwanted "
134
+ "side effects(use at your own risk)",
135
+ )
136
+
137
+
138
+ def pytest_cmdline_main(config: Config) -> Optional[Union[int, ExitCode]]:
139
+ if config.option.showfixtures:
140
+ showfixtures(config)
141
+ return 0
142
+ if config.option.show_fixtures_per_test:
143
+ show_fixtures_per_test(config)
144
+ return 0
145
+ return None
146
+
147
+
148
+ def pytest_generate_tests(metafunc: "Metafunc") -> None:
149
+ for marker in metafunc.definition.iter_markers(name="parametrize"):
150
+ metafunc.parametrize(*marker.args, **marker.kwargs, _param_mark=marker)
151
+
152
+
153
+ def pytest_configure(config: Config) -> None:
154
+ config.addinivalue_line(
155
+ "markers",
156
+ "parametrize(argnames, argvalues): call a test function multiple "
157
+ "times passing in different arguments in turn. argvalues generally "
158
+ "needs to be a list of values if argnames specifies only one name "
159
+ "or a list of tuples of values if argnames specifies multiple names. "
160
+ "Example: @parametrize('arg1', [1,2]) would lead to two calls of the "
161
+ "decorated test function, one with arg1=1 and another with arg1=2."
162
+ "see https://docs.pytest.org/en/stable/how-to/parametrize.html for more info "
163
+ "and examples.",
164
+ )
165
+ config.addinivalue_line(
166
+ "markers",
167
+ "usefixtures(fixturename1, fixturename2, ...): mark tests as needing "
168
+ "all of the specified fixtures. see "
169
+ "https://docs.pytest.org/en/stable/explanation/fixtures.html#usefixtures ",
170
+ )
171
+
172
+
173
+ def async_warn_and_skip(nodeid: str) -> None:
174
+ msg = "async def functions are not natively supported and have been skipped.\n"
175
+ msg += (
176
+ "You need to install a suitable plugin for your async framework, for example:\n"
177
+ )
178
+ msg += " - anyio\n"
179
+ msg += " - pytest-asyncio\n"
180
+ msg += " - pytest-tornasync\n"
181
+ msg += " - pytest-trio\n"
182
+ msg += " - pytest-twisted"
183
+ warnings.warn(PytestUnhandledCoroutineWarning(msg.format(nodeid)))
184
+ skip(reason="async def function and no async plugin installed (see warnings)")
185
+
186
+
187
+ @hookimpl(trylast=True)
188
+ def pytest_pyfunc_call(pyfuncitem: "Function") -> Optional[object]:
189
+ testfunction = pyfuncitem.obj
190
+ if is_async_function(testfunction):
191
+ async_warn_and_skip(pyfuncitem.nodeid)
192
+ funcargs = pyfuncitem.funcargs
193
+ testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames}
194
+ result = testfunction(**testargs)
195
+ if hasattr(result, "__await__") or hasattr(result, "__aiter__"):
196
+ async_warn_and_skip(pyfuncitem.nodeid)
197
+ elif result is not None:
198
+ warnings.warn(
199
+ PytestReturnNotNoneWarning(
200
+ f"Expected None, but {pyfuncitem.nodeid} returned {result!r}, which will be an error in a "
201
+ "future version of pytest. Did you mean to use `assert` instead of `return`?"
202
+ )
203
+ )
204
+ return True
205
+
206
+
207
+ def pytest_collect_file(file_path: Path, parent: nodes.Collector) -> Optional["Module"]:
208
+ if file_path.suffix == ".py":
209
+ if not parent.session.isinitpath(file_path):
210
+ if not path_matches_patterns(
211
+ file_path, parent.config.getini("python_files") + ["__init__.py"]
212
+ ):
213
+ return None
214
+ ihook = parent.session.gethookproxy(file_path)
215
+ module: Module = ihook.pytest_pycollect_makemodule(
216
+ module_path=file_path, parent=parent
217
+ )
218
+ return module
219
+ return None
220
+
221
+
222
+ def path_matches_patterns(path: Path, patterns: Iterable[str]) -> bool:
223
+ """Return whether path matches any of the patterns in the list of globs given."""
224
+ return any(fnmatch_ex(pattern, path) for pattern in patterns)
225
+
226
+
227
+ def pytest_pycollect_makemodule(module_path: Path, parent) -> "Module":
228
+ if module_path.name == "__init__.py":
229
+ pkg: Package = Package.from_parent(parent, path=module_path)
230
+ return pkg
231
+ mod: Module = Module.from_parent(parent, path=module_path)
232
+ return mod
233
+
234
+
235
+ @hookimpl(trylast=True)
236
+ def pytest_pycollect_makeitem(
237
+ collector: Union["Module", "Class"], name: str, obj: object
238
+ ) -> Union[None, nodes.Item, nodes.Collector, List[Union[nodes.Item, nodes.Collector]]]:
239
+ assert isinstance(collector, (Class, Module)), type(collector)
240
+ # Nothing was collected elsewhere, let's do it here.
241
+ if safe_isclass(obj):
242
+ if collector.istestclass(obj, name):
243
+ klass: Class = Class.from_parent(collector, name=name, obj=obj)
244
+ return klass
245
+ elif collector.istestfunction(obj, name):
246
+ # mock seems to store unbound methods (issue473), normalize it.
247
+ obj = getattr(obj, "__func__", obj)
248
+ # We need to try and unwrap the function if it's a functools.partial
249
+ # or a functools.wrapped.
250
+ # We mustn't if it's been wrapped with mock.patch (python 2 only).
251
+ if not (inspect.isfunction(obj) or inspect.isfunction(get_real_func(obj))):
252
+ filename, lineno = getfslineno(obj)
253
+ warnings.warn_explicit(
254
+ message=PytestCollectionWarning(
255
+ "cannot collect %r because it is not a function." % name
256
+ ),
257
+ category=None,
258
+ filename=str(filename),
259
+ lineno=lineno + 1,
260
+ )
261
+ elif getattr(obj, "__test__", True):
262
+ if is_generator(obj):
263
+ res: Function = Function.from_parent(collector, name=name)
264
+ reason = "yield tests were removed in pytest 4.0 - {name} will be ignored".format(
265
+ name=name
266
+ )
267
+ res.add_marker(MARK_GEN.xfail(run=False, reason=reason))
268
+ res.warn(PytestCollectionWarning(reason))
269
+ return res
270
+ else:
271
+ return list(collector._genfunctions(name, obj))
272
+ return None
273
+
274
+
275
+ class PyobjMixin(nodes.Node):
276
+ """this mix-in inherits from Node to carry over the typing information
277
+
278
+ as its intended to always mix in before a node
279
+ its position in the mro is unaffected"""
280
+
281
+ _ALLOW_MARKERS = True
282
+
283
+ @property
284
+ def module(self):
285
+ """Python module object this node was collected from (can be None)."""
286
+ node = self.getparent(Module)
287
+ return node.obj if node is not None else None
288
+
289
+ @property
290
+ def cls(self):
291
+ """Python class object this node was collected from (can be None)."""
292
+ node = self.getparent(Class)
293
+ return node.obj if node is not None else None
294
+
295
+ @property
296
+ def instance(self):
297
+ """Python instance object the function is bound to.
298
+
299
+ Returns None if not a test method, e.g. for a standalone test function,
300
+ a staticmethod, a class or a module.
301
+ """
302
+ node = self.getparent(Function)
303
+ return getattr(node.obj, "__self__", None) if node is not None else None
304
+
305
+ @property
306
+ def obj(self):
307
+ """Underlying Python object."""
308
+ obj = getattr(self, "_obj", None)
309
+ if obj is None:
310
+ self._obj = obj = self._getobj()
311
+ # XXX evil hack
312
+ # used to avoid Function marker duplication
313
+ if self._ALLOW_MARKERS:
314
+ self.own_markers.extend(get_unpacked_marks(self.obj))
315
+ # This assumes that `obj` is called before there is a chance
316
+ # to add custom keys to `self.keywords`, so no fear of overriding.
317
+ self.keywords.update((mark.name, mark) for mark in self.own_markers)
318
+ return obj
319
+
320
+ @obj.setter
321
+ def obj(self, value):
322
+ self._obj = value
323
+
324
+ def _getobj(self):
325
+ """Get the underlying Python object. May be overwritten by subclasses."""
326
+ # TODO: Improve the type of `parent` such that assert/ignore aren't needed.
327
+ assert self.parent is not None
328
+ obj = self.parent.obj # type: ignore[attr-defined]
329
+ return getattr(obj, self.name)
330
+
331
+ def getmodpath(self, stopatmodule: bool = True, includemodule: bool = False) -> str:
332
+ """Return Python path relative to the containing module."""
333
+ chain = self.listchain()
334
+ chain.reverse()
335
+ parts = []
336
+ for node in chain:
337
+ name = node.name
338
+ if isinstance(node, Module):
339
+ name = os.path.splitext(name)[0]
340
+ if stopatmodule:
341
+ if includemodule:
342
+ parts.append(name)
343
+ break
344
+ parts.append(name)
345
+ parts.reverse()
346
+ return ".".join(parts)
347
+
348
+ def reportinfo(self) -> Tuple[Union["os.PathLike[str]", str], Optional[int], str]:
349
+ # XXX caching?
350
+ obj = self.obj
351
+ compat_co_firstlineno = getattr(obj, "compat_co_firstlineno", None)
352
+ if isinstance(compat_co_firstlineno, int):
353
+ # nose compatibility
354
+ file_path = sys.modules[obj.__module__].__file__
355
+ assert file_path is not None
356
+ if file_path.endswith(".pyc"):
357
+ file_path = file_path[:-1]
358
+ path: Union["os.PathLike[str]", str] = file_path
359
+ lineno = compat_co_firstlineno
360
+ else:
361
+ path, lineno = getfslineno(obj)
362
+ modpath = self.getmodpath()
363
+ assert isinstance(lineno, int)
364
+ return path, lineno, modpath
365
+
366
+
367
+ # As an optimization, these builtin attribute names are pre-ignored when
368
+ # iterating over an object during collection -- the pytest_pycollect_makeitem
369
+ # hook is not called for them.
370
+ # fmt: off
371
+ class _EmptyClass: pass # noqa: E701
372
+ IGNORED_ATTRIBUTES = frozenset.union( # noqa: E305
373
+ frozenset(),
374
+ # Module.
375
+ dir(types.ModuleType("empty_module")),
376
+ # Some extra module attributes the above doesn't catch.
377
+ {"__builtins__", "__file__", "__cached__"},
378
+ # Class.
379
+ dir(_EmptyClass),
380
+ # Instance.
381
+ dir(_EmptyClass()),
382
+ )
383
+ del _EmptyClass
384
+ # fmt: on
385
+
386
+
387
+ class PyCollector(PyobjMixin, nodes.Collector):
388
+ def funcnamefilter(self, name: str) -> bool:
389
+ return self._matches_prefix_or_glob_option("python_functions", name)
390
+
391
+ def isnosetest(self, obj: object) -> bool:
392
+ """Look for the __test__ attribute, which is applied by the
393
+ @nose.tools.istest decorator.
394
+ """
395
+ # We explicitly check for "is True" here to not mistakenly treat
396
+ # classes with a custom __getattr__ returning something truthy (like a
397
+ # function) as test classes.
398
+ return safe_getattr(obj, "__test__", False) is True
399
+
400
+ def classnamefilter(self, name: str) -> bool:
401
+ return self._matches_prefix_or_glob_option("python_classes", name)
402
+
403
+ def istestfunction(self, obj: object, name: str) -> bool:
404
+ if self.funcnamefilter(name) or self.isnosetest(obj):
405
+ if isinstance(obj, (staticmethod, classmethod)):
406
+ # staticmethods and classmethods need to be unwrapped.
407
+ obj = safe_getattr(obj, "__func__", False)
408
+ return callable(obj) and fixtures.getfixturemarker(obj) is None
409
+ else:
410
+ return False
411
+
412
+ def istestclass(self, obj: object, name: str) -> bool:
413
+ return self.classnamefilter(name) or self.isnosetest(obj)
414
+
415
+ def _matches_prefix_or_glob_option(self, option_name: str, name: str) -> bool:
416
+ """Check if the given name matches the prefix or glob-pattern defined
417
+ in ini configuration."""
418
+ for option in self.config.getini(option_name):
419
+ if name.startswith(option):
420
+ return True
421
+ # Check that name looks like a glob-string before calling fnmatch
422
+ # because this is called for every name in each collected module,
423
+ # and fnmatch is somewhat expensive to call.
424
+ elif ("*" in option or "?" in option or "[" in option) and fnmatch.fnmatch(
425
+ name, option
426
+ ):
427
+ return True
428
+ return False
429
+
430
+ def collect(self) -> Iterable[Union[nodes.Item, nodes.Collector]]:
431
+ if not getattr(self.obj, "__test__", True):
432
+ return []
433
+
434
+ # Avoid random getattrs and peek in the __dict__ instead.
435
+ dicts = [getattr(self.obj, "__dict__", {})]
436
+ if isinstance(self.obj, type):
437
+ for basecls in self.obj.__mro__:
438
+ dicts.append(basecls.__dict__)
439
+
440
+ # In each class, nodes should be definition ordered.
441
+ # __dict__ is definition ordered.
442
+ seen: Set[str] = set()
443
+ dict_values: List[List[Union[nodes.Item, nodes.Collector]]] = []
444
+ ihook = self.ihook
445
+ for dic in dicts:
446
+ values: List[Union[nodes.Item, nodes.Collector]] = []
447
+ # Note: seems like the dict can change during iteration -
448
+ # be careful not to remove the list() without consideration.
449
+ for name, obj in list(dic.items()):
450
+ if name in IGNORED_ATTRIBUTES:
451
+ continue
452
+ if name in seen:
453
+ continue
454
+ seen.add(name)
455
+ res = ihook.pytest_pycollect_makeitem(
456
+ collector=self, name=name, obj=obj
457
+ )
458
+ if res is None:
459
+ continue
460
+ elif isinstance(res, list):
461
+ values.extend(res)
462
+ else:
463
+ values.append(res)
464
+ dict_values.append(values)
465
+
466
+ # Between classes in the class hierarchy, reverse-MRO order -- nodes
467
+ # inherited from base classes should come before subclasses.
468
+ result = []
469
+ for values in reversed(dict_values):
470
+ result.extend(values)
471
+ return result
472
+
473
+ def _genfunctions(self, name: str, funcobj) -> Iterator["Function"]:
474
+ modulecol = self.getparent(Module)
475
+ assert modulecol is not None
476
+ module = modulecol.obj
477
+ clscol = self.getparent(Class)
478
+ cls = clscol and clscol.obj or None
479
+
480
+ definition = FunctionDefinition.from_parent(self, name=name, callobj=funcobj)
481
+ fixtureinfo = definition._fixtureinfo
482
+
483
+ # pytest_generate_tests impls call metafunc.parametrize() which fills
484
+ # metafunc._calls, the outcome of the hook.
485
+ metafunc = Metafunc(
486
+ definition=definition,
487
+ fixtureinfo=fixtureinfo,
488
+ config=self.config,
489
+ cls=cls,
490
+ module=module,
491
+ _ispytest=True,
492
+ )
493
+ methods = []
494
+ if hasattr(module, "pytest_generate_tests"):
495
+ methods.append(module.pytest_generate_tests)
496
+ if cls is not None and hasattr(cls, "pytest_generate_tests"):
497
+ methods.append(cls().pytest_generate_tests)
498
+ self.ihook.pytest_generate_tests.call_extra(methods, dict(metafunc=metafunc))
499
+
500
+ if not metafunc._calls:
501
+ yield Function.from_parent(self, name=name, fixtureinfo=fixtureinfo)
502
+ else:
503
+ # Add funcargs() as fixturedefs to fixtureinfo.arg2fixturedefs.
504
+ fm = self.session._fixturemanager
505
+ fixtures.add_funcarg_pseudo_fixture_def(self, metafunc, fm)
506
+
507
+ # Add_funcarg_pseudo_fixture_def may have shadowed some fixtures
508
+ # with direct parametrization, so make sure we update what the
509
+ # function really needs.
510
+ fixtureinfo.prune_dependency_tree()
511
+
512
+ for callspec in metafunc._calls:
513
+ subname = f"{name}[{callspec.id}]"
514
+ yield Function.from_parent(
515
+ self,
516
+ name=subname,
517
+ callspec=callspec,
518
+ fixtureinfo=fixtureinfo,
519
+ keywords={callspec.id: True},
520
+ originalname=name,
521
+ )
522
+
523
+
524
+ class Module(nodes.File, PyCollector):
525
+ """Collector for test classes and functions in a Python module."""
526
+
527
+ def _getobj(self):
528
+ return self._importtestmodule()
529
+
530
+ def collect(self) -> Iterable[Union[nodes.Item, nodes.Collector]]:
531
+ self._inject_setup_module_fixture()
532
+ self._inject_setup_function_fixture()
533
+ self.session._fixturemanager.parsefactories(self)
534
+ return super().collect()
535
+
536
+ def _inject_setup_module_fixture(self) -> None:
537
+ """Inject a hidden autouse, module scoped fixture into the collected module object
538
+ that invokes setUpModule/tearDownModule if either or both are available.
539
+
540
+ Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with
541
+ other fixtures (#517).
542
+ """
543
+ has_nose = self.config.pluginmanager.has_plugin("nose")
544
+ setup_module = _get_first_non_fixture_func(
545
+ self.obj, ("setUpModule", "setup_module")
546
+ )
547
+ if setup_module is None and has_nose:
548
+ # The name "setup" is too common - only treat as fixture if callable.
549
+ setup_module = _get_first_non_fixture_func(self.obj, ("setup",))
550
+ if not callable(setup_module):
551
+ setup_module = None
552
+ teardown_module = _get_first_non_fixture_func(
553
+ self.obj, ("tearDownModule", "teardown_module")
554
+ )
555
+ if teardown_module is None and has_nose:
556
+ teardown_module = _get_first_non_fixture_func(self.obj, ("teardown",))
557
+ # Same as "setup" above - only treat as fixture if callable.
558
+ if not callable(teardown_module):
559
+ teardown_module = None
560
+
561
+ if setup_module is None and teardown_module is None:
562
+ return
563
+
564
+ @fixtures.fixture(
565
+ autouse=True,
566
+ scope="module",
567
+ # Use a unique name to speed up lookup.
568
+ name=f"_xunit_setup_module_fixture_{self.obj.__name__}",
569
+ )
570
+ def xunit_setup_module_fixture(request) -> Generator[None, None, None]:
571
+ if setup_module is not None:
572
+ _call_with_optional_argument(setup_module, request.module)
573
+ yield
574
+ if teardown_module is not None:
575
+ _call_with_optional_argument(teardown_module, request.module)
576
+
577
+ self.obj.__pytest_setup_module = xunit_setup_module_fixture
578
+
579
+ def _inject_setup_function_fixture(self) -> None:
580
+ """Inject a hidden autouse, function scoped fixture into the collected module object
581
+ that invokes setup_function/teardown_function if either or both are available.
582
+
583
+ Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with
584
+ other fixtures (#517).
585
+ """
586
+ setup_function = _get_first_non_fixture_func(self.obj, ("setup_function",))
587
+ teardown_function = _get_first_non_fixture_func(
588
+ self.obj, ("teardown_function",)
589
+ )
590
+ if setup_function is None and teardown_function is None:
591
+ return
592
+
593
+ @fixtures.fixture(
594
+ autouse=True,
595
+ scope="function",
596
+ # Use a unique name to speed up lookup.
597
+ name=f"_xunit_setup_function_fixture_{self.obj.__name__}",
598
+ )
599
+ def xunit_setup_function_fixture(request) -> Generator[None, None, None]:
600
+ if request.instance is not None:
601
+ # in this case we are bound to an instance, so we need to let
602
+ # setup_method handle this
603
+ yield
604
+ return
605
+ if setup_function is not None:
606
+ _call_with_optional_argument(setup_function, request.function)
607
+ yield
608
+ if teardown_function is not None:
609
+ _call_with_optional_argument(teardown_function, request.function)
610
+
611
+ self.obj.__pytest_setup_function = xunit_setup_function_fixture
612
+
613
+ def _importtestmodule(self):
614
+ # We assume we are only called once per module.
615
+ importmode = self.config.getoption("--import-mode")
616
+ try:
617
+ mod = import_path(self.path, mode=importmode, root=self.config.rootpath)
618
+ except SyntaxError as e:
619
+ raise self.CollectError(
620
+ ExceptionInfo.from_current().getrepr(style="short")
621
+ ) from e
622
+ except ImportPathMismatchError as e:
623
+ raise self.CollectError(
624
+ "import file mismatch:\n"
625
+ "imported module %r has this __file__ attribute:\n"
626
+ " %s\n"
627
+ "which is not the same as the test file we want to collect:\n"
628
+ " %s\n"
629
+ "HINT: remove __pycache__ / .pyc files and/or use a "
630
+ "unique basename for your test file modules" % e.args
631
+ ) from e
632
+ except ImportError as e:
633
+ exc_info = ExceptionInfo.from_current()
634
+ if self.config.getoption("verbose") < 2:
635
+ exc_info.traceback = exc_info.traceback.filter(filter_traceback)
636
+ exc_repr = (
637
+ exc_info.getrepr(style="short")
638
+ if exc_info.traceback
639
+ else exc_info.exconly()
640
+ )
641
+ formatted_tb = str(exc_repr)
642
+ raise self.CollectError(
643
+ "ImportError while importing test module '{path}'.\n"
644
+ "Hint: make sure your test modules/packages have valid Python names.\n"
645
+ "Traceback:\n"
646
+ "{traceback}".format(path=self.path, traceback=formatted_tb)
647
+ ) from e
648
+ except skip.Exception as e:
649
+ if e.allow_module_level:
650
+ raise
651
+ raise self.CollectError(
652
+ "Using pytest.skip outside of a test will skip the entire module. "
653
+ "If that's your intention, pass `allow_module_level=True`. "
654
+ "If you want to skip a specific test or an entire class, "
655
+ "use the @pytest.mark.skip or @pytest.mark.skipif decorators."
656
+ ) from e
657
+ self.config.pluginmanager.consider_module(mod)
658
+ return mod
659
+
660
+
661
+ class Package(Module):
662
+ """Collector for files and directories in a Python packages -- directories
663
+ with an `__init__.py` file."""
664
+
665
+ def __init__(
666
+ self,
667
+ fspath: Optional[LEGACY_PATH],
668
+ parent: nodes.Collector,
669
+ # NOTE: following args are unused:
670
+ config=None,
671
+ session=None,
672
+ nodeid=None,
673
+ path: Optional[Path] = None,
674
+ ) -> None:
675
+ # NOTE: Could be just the following, but kept as-is for compat.
676
+ # nodes.FSCollector.__init__(self, fspath, parent=parent)
677
+ session = parent.session
678
+ nodes.FSCollector.__init__(
679
+ self,
680
+ fspath=fspath,
681
+ path=path,
682
+ parent=parent,
683
+ config=config,
684
+ session=session,
685
+ nodeid=nodeid,
686
+ )
687
+ self.name = self.path.parent.name
688
+
689
+ def setup(self) -> None:
690
+ # Not using fixtures to call setup_module here because autouse fixtures
691
+ # from packages are not called automatically (#4085).
692
+ setup_module = _get_first_non_fixture_func(
693
+ self.obj, ("setUpModule", "setup_module")
694
+ )
695
+ if setup_module is not None:
696
+ _call_with_optional_argument(setup_module, self.obj)
697
+
698
+ teardown_module = _get_first_non_fixture_func(
699
+ self.obj, ("tearDownModule", "teardown_module")
700
+ )
701
+ if teardown_module is not None:
702
+ func = partial(_call_with_optional_argument, teardown_module, self.obj)
703
+ self.addfinalizer(func)
704
+
705
+ def _recurse(self, direntry: "os.DirEntry[str]") -> bool:
706
+ if direntry.name == "__pycache__":
707
+ return False
708
+ fspath = Path(direntry.path)
709
+ ihook = self.session.gethookproxy(fspath.parent)
710
+ if ihook.pytest_ignore_collect(collection_path=fspath, config=self.config):
711
+ return False
712
+ return True
713
+
714
+ def _collectfile(
715
+ self, fspath: Path, handle_dupes: bool = True
716
+ ) -> Sequence[nodes.Collector]:
717
+ assert (
718
+ fspath.is_file()
719
+ ), "{!r} is not a file (isdir={!r}, exists={!r}, islink={!r})".format(
720
+ fspath, fspath.is_dir(), fspath.exists(), fspath.is_symlink()
721
+ )
722
+ ihook = self.session.gethookproxy(fspath)
723
+ if not self.session.isinitpath(fspath):
724
+ if ihook.pytest_ignore_collect(collection_path=fspath, config=self.config):
725
+ return ()
726
+
727
+ if handle_dupes:
728
+ keepduplicates = self.config.getoption("keepduplicates")
729
+ if not keepduplicates:
730
+ duplicate_paths = self.config.pluginmanager._duplicatepaths
731
+ if fspath in duplicate_paths:
732
+ return ()
733
+ else:
734
+ duplicate_paths.add(fspath)
735
+
736
+ return ihook.pytest_collect_file(file_path=fspath, parent=self) # type: ignore[no-any-return]
737
+
738
+ def collect(self) -> Iterable[Union[nodes.Item, nodes.Collector]]:
739
+ this_path = self.path.parent
740
+
741
+ # Always collect the __init__ first.
742
+ if path_matches_patterns(self.path, self.config.getini("python_files")):
743
+ yield Module.from_parent(self, path=self.path)
744
+
745
+ pkg_prefixes: Set[Path] = set()
746
+ for direntry in visit(str(this_path), recurse=self._recurse):
747
+ path = Path(direntry.path)
748
+
749
+ # We will visit our own __init__.py file, in which case we skip it.
750
+ if direntry.is_file():
751
+ if direntry.name == "__init__.py" and path.parent == this_path:
752
+ continue
753
+
754
+ parts_ = parts(direntry.path)
755
+ if any(
756
+ str(pkg_prefix) in parts_ and pkg_prefix / "__init__.py" != path
757
+ for pkg_prefix in pkg_prefixes
758
+ ):
759
+ continue
760
+
761
+ if direntry.is_file():
762
+ yield from self._collectfile(path)
763
+ elif not direntry.is_dir():
764
+ # Broken symlink or invalid/missing file.
765
+ continue
766
+ elif path.joinpath("__init__.py").is_file():
767
+ pkg_prefixes.add(path)
768
+
769
+
770
+ def _call_with_optional_argument(func, arg) -> None:
771
+ """Call the given function with the given argument if func accepts one argument, otherwise
772
+ calls func without arguments."""
773
+ arg_count = func.__code__.co_argcount
774
+ if inspect.ismethod(func):
775
+ arg_count -= 1
776
+ if arg_count:
777
+ func(arg)
778
+ else:
779
+ func()
780
+
781
+
782
+ def _get_first_non_fixture_func(obj: object, names: Iterable[str]) -> Optional[object]:
783
+ """Return the attribute from the given object to be used as a setup/teardown
784
+ xunit-style function, but only if not marked as a fixture to avoid calling it twice.
785
+ """
786
+ for name in names:
787
+ meth: Optional[object] = getattr(obj, name, None)
788
+ if meth is not None and fixtures.getfixturemarker(meth) is None:
789
+ return meth
790
+ return None
791
+
792
+
793
+ class Class(PyCollector):
794
+ """Collector for test methods (and nested classes) in a Python class."""
795
+
796
+ @classmethod
797
+ def from_parent(cls, parent, *, name, obj=None, **kw):
798
+ """The public constructor."""
799
+ return super().from_parent(name=name, parent=parent, **kw)
800
+
801
+ def newinstance(self):
802
+ return self.obj()
803
+
804
+ def collect(self) -> Iterable[Union[nodes.Item, nodes.Collector]]:
805
+ if not safe_getattr(self.obj, "__test__", True):
806
+ return []
807
+ if hasinit(self.obj):
808
+ assert self.parent is not None
809
+ self.warn(
810
+ PytestCollectionWarning(
811
+ "cannot collect test class %r because it has a "
812
+ "__init__ constructor (from: %s)"
813
+ % (self.obj.__name__, self.parent.nodeid)
814
+ )
815
+ )
816
+ return []
817
+ elif hasnew(self.obj):
818
+ assert self.parent is not None
819
+ self.warn(
820
+ PytestCollectionWarning(
821
+ "cannot collect test class %r because it has a "
822
+ "__new__ constructor (from: %s)"
823
+ % (self.obj.__name__, self.parent.nodeid)
824
+ )
825
+ )
826
+ return []
827
+
828
+ self._inject_setup_class_fixture()
829
+ self._inject_setup_method_fixture()
830
+
831
+ self.session._fixturemanager.parsefactories(self.newinstance(), self.nodeid)
832
+
833
+ return super().collect()
834
+
835
+ def _inject_setup_class_fixture(self) -> None:
836
+ """Inject a hidden autouse, class scoped fixture into the collected class object
837
+ that invokes setup_class/teardown_class if either or both are available.
838
+
839
+ Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with
840
+ other fixtures (#517).
841
+ """
842
+ setup_class = _get_first_non_fixture_func(self.obj, ("setup_class",))
843
+ teardown_class = _get_first_non_fixture_func(self.obj, ("teardown_class",))
844
+ if setup_class is None and teardown_class is None:
845
+ return
846
+
847
+ @fixtures.fixture(
848
+ autouse=True,
849
+ scope="class",
850
+ # Use a unique name to speed up lookup.
851
+ name=f"_xunit_setup_class_fixture_{self.obj.__qualname__}",
852
+ )
853
+ def xunit_setup_class_fixture(cls) -> Generator[None, None, None]:
854
+ if setup_class is not None:
855
+ func = getimfunc(setup_class)
856
+ _call_with_optional_argument(func, self.obj)
857
+ yield
858
+ if teardown_class is not None:
859
+ func = getimfunc(teardown_class)
860
+ _call_with_optional_argument(func, self.obj)
861
+
862
+ self.obj.__pytest_setup_class = xunit_setup_class_fixture
863
+
864
+ def _inject_setup_method_fixture(self) -> None:
865
+ """Inject a hidden autouse, function scoped fixture into the collected class object
866
+ that invokes setup_method/teardown_method if either or both are available.
867
+
868
+ Using a fixture to invoke these methods ensures we play nicely and unsurprisingly with
869
+ other fixtures (#517).
870
+ """
871
+ has_nose = self.config.pluginmanager.has_plugin("nose")
872
+ setup_name = "setup_method"
873
+ setup_method = _get_first_non_fixture_func(self.obj, (setup_name,))
874
+ emit_nose_setup_warning = False
875
+ if setup_method is None and has_nose:
876
+ setup_name = "setup"
877
+ emit_nose_setup_warning = True
878
+ setup_method = _get_first_non_fixture_func(self.obj, (setup_name,))
879
+ teardown_name = "teardown_method"
880
+ teardown_method = _get_first_non_fixture_func(self.obj, (teardown_name,))
881
+ emit_nose_teardown_warning = False
882
+ if teardown_method is None and has_nose:
883
+ teardown_name = "teardown"
884
+ emit_nose_teardown_warning = True
885
+ teardown_method = _get_first_non_fixture_func(self.obj, (teardown_name,))
886
+ if setup_method is None and teardown_method is None:
887
+ return
888
+
889
+ @fixtures.fixture(
890
+ autouse=True,
891
+ scope="function",
892
+ # Use a unique name to speed up lookup.
893
+ name=f"_xunit_setup_method_fixture_{self.obj.__qualname__}",
894
+ )
895
+ def xunit_setup_method_fixture(self, request) -> Generator[None, None, None]:
896
+ method = request.function
897
+ if setup_method is not None:
898
+ func = getattr(self, setup_name)
899
+ _call_with_optional_argument(func, method)
900
+ if emit_nose_setup_warning:
901
+ warnings.warn(
902
+ NOSE_SUPPORT_METHOD.format(
903
+ nodeid=request.node.nodeid, method="setup"
904
+ ),
905
+ stacklevel=2,
906
+ )
907
+ yield
908
+ if teardown_method is not None:
909
+ func = getattr(self, teardown_name)
910
+ _call_with_optional_argument(func, method)
911
+ if emit_nose_teardown_warning:
912
+ warnings.warn(
913
+ NOSE_SUPPORT_METHOD.format(
914
+ nodeid=request.node.nodeid, method="teardown"
915
+ ),
916
+ stacklevel=2,
917
+ )
918
+
919
+ self.obj.__pytest_setup_method = xunit_setup_method_fixture
920
+
921
+
922
+ class InstanceDummy:
923
+ """Instance used to be a node type between Class and Function. It has been
924
+ removed in pytest 7.0. Some plugins exist which reference `pytest.Instance`
925
+ only to ignore it; this dummy class keeps them working. This will be removed
926
+ in pytest 8."""
927
+
928
+
929
+ def __getattr__(name: str) -> object:
930
+ if name == "Instance":
931
+ warnings.warn(INSTANCE_COLLECTOR, 2)
932
+ return InstanceDummy
933
+ raise AttributeError(f"module {__name__} has no attribute {name}")
934
+
935
+
936
+ def hasinit(obj: object) -> bool:
937
+ init: object = getattr(obj, "__init__", None)
938
+ if init:
939
+ return init != object.__init__
940
+ return False
941
+
942
+
943
+ def hasnew(obj: object) -> bool:
944
+ new: object = getattr(obj, "__new__", None)
945
+ if new:
946
+ return new != object.__new__
947
+ return False
948
+
949
+
950
+ @final
951
+ @dataclasses.dataclass(frozen=True)
952
+ class IdMaker:
953
+ """Make IDs for a parametrization."""
954
+
955
+ __slots__ = (
956
+ "argnames",
957
+ "parametersets",
958
+ "idfn",
959
+ "ids",
960
+ "config",
961
+ "nodeid",
962
+ "func_name",
963
+ )
964
+
965
+ # The argnames of the parametrization.
966
+ argnames: Sequence[str]
967
+ # The ParameterSets of the parametrization.
968
+ parametersets: Sequence[ParameterSet]
969
+ # Optionally, a user-provided callable to make IDs for parameters in a
970
+ # ParameterSet.
971
+ idfn: Optional[Callable[[Any], Optional[object]]]
972
+ # Optionally, explicit IDs for ParameterSets by index.
973
+ ids: Optional[Sequence[Optional[object]]]
974
+ # Optionally, the pytest config.
975
+ # Used for controlling ASCII escaping, and for calling the
976
+ # :hook:`pytest_make_parametrize_id` hook.
977
+ config: Optional[Config]
978
+ # Optionally, the ID of the node being parametrized.
979
+ # Used only for clearer error messages.
980
+ nodeid: Optional[str]
981
+ # Optionally, the ID of the function being parametrized.
982
+ # Used only for clearer error messages.
983
+ func_name: Optional[str]
984
+
985
+ def make_unique_parameterset_ids(self) -> List[str]:
986
+ """Make a unique identifier for each ParameterSet, that may be used to
987
+ identify the parametrization in a node ID.
988
+
989
+ Format is <prm_1_token>-...-<prm_n_token>[counter], where prm_x_token is
990
+ - user-provided id, if given
991
+ - else an id derived from the value, applicable for certain types
992
+ - else <argname><parameterset index>
993
+ The counter suffix is appended only in case a string wouldn't be unique
994
+ otherwise.
995
+ """
996
+ resolved_ids = list(self._resolve_ids())
997
+ # All IDs must be unique!
998
+ if len(resolved_ids) != len(set(resolved_ids)):
999
+ # Record the number of occurrences of each ID.
1000
+ id_counts = Counter(resolved_ids)
1001
+ # Map the ID to its next suffix.
1002
+ id_suffixes: Dict[str, int] = defaultdict(int)
1003
+ # Suffix non-unique IDs to make them unique.
1004
+ for index, id in enumerate(resolved_ids):
1005
+ if id_counts[id] > 1:
1006
+ resolved_ids[index] = f"{id}{id_suffixes[id]}"
1007
+ id_suffixes[id] += 1
1008
+ return resolved_ids
1009
+
1010
+ def _resolve_ids(self) -> Iterable[str]:
1011
+ """Resolve IDs for all ParameterSets (may contain duplicates)."""
1012
+ for idx, parameterset in enumerate(self.parametersets):
1013
+ if parameterset.id is not None:
1014
+ # ID provided directly - pytest.param(..., id="...")
1015
+ yield parameterset.id
1016
+ elif self.ids and idx < len(self.ids) and self.ids[idx] is not None:
1017
+ # ID provided in the IDs list - parametrize(..., ids=[...]).
1018
+ yield self._idval_from_value_required(self.ids[idx], idx)
1019
+ else:
1020
+ # ID not provided - generate it.
1021
+ yield "-".join(
1022
+ self._idval(val, argname, idx)
1023
+ for val, argname in zip(parameterset.values, self.argnames)
1024
+ )
1025
+
1026
+ def _idval(self, val: object, argname: str, idx: int) -> str:
1027
+ """Make an ID for a parameter in a ParameterSet."""
1028
+ idval = self._idval_from_function(val, argname, idx)
1029
+ if idval is not None:
1030
+ return idval
1031
+ idval = self._idval_from_hook(val, argname)
1032
+ if idval is not None:
1033
+ return idval
1034
+ idval = self._idval_from_value(val)
1035
+ if idval is not None:
1036
+ return idval
1037
+ return self._idval_from_argname(argname, idx)
1038
+
1039
+ def _idval_from_function(
1040
+ self, val: object, argname: str, idx: int
1041
+ ) -> Optional[str]:
1042
+ """Try to make an ID for a parameter in a ParameterSet using the
1043
+ user-provided id callable, if given."""
1044
+ if self.idfn is None:
1045
+ return None
1046
+ try:
1047
+ id = self.idfn(val)
1048
+ except Exception as e:
1049
+ prefix = f"{self.nodeid}: " if self.nodeid is not None else ""
1050
+ msg = "error raised while trying to determine id of parameter '{}' at position {}"
1051
+ msg = prefix + msg.format(argname, idx)
1052
+ raise ValueError(msg) from e
1053
+ if id is None:
1054
+ return None
1055
+ return self._idval_from_value(id)
1056
+
1057
+ def _idval_from_hook(self, val: object, argname: str) -> Optional[str]:
1058
+ """Try to make an ID for a parameter in a ParameterSet by calling the
1059
+ :hook:`pytest_make_parametrize_id` hook."""
1060
+ if self.config:
1061
+ id: Optional[str] = self.config.hook.pytest_make_parametrize_id(
1062
+ config=self.config, val=val, argname=argname
1063
+ )
1064
+ return id
1065
+ return None
1066
+
1067
+ def _idval_from_value(self, val: object) -> Optional[str]:
1068
+ """Try to make an ID for a parameter in a ParameterSet from its value,
1069
+ if the value type is supported."""
1070
+ if isinstance(val, STRING_TYPES):
1071
+ return _ascii_escaped_by_config(val, self.config)
1072
+ elif val is None or isinstance(val, (float, int, bool, complex)):
1073
+ return str(val)
1074
+ elif isinstance(val, Pattern):
1075
+ return ascii_escaped(val.pattern)
1076
+ elif val is NOTSET:
1077
+ # Fallback to default. Note that NOTSET is an enum.Enum.
1078
+ pass
1079
+ elif isinstance(val, enum.Enum):
1080
+ return str(val)
1081
+ elif isinstance(getattr(val, "__name__", None), str):
1082
+ # Name of a class, function, module, etc.
1083
+ name: str = getattr(val, "__name__")
1084
+ return name
1085
+ return None
1086
+
1087
+ def _idval_from_value_required(self, val: object, idx: int) -> str:
1088
+ """Like _idval_from_value(), but fails if the type is not supported."""
1089
+ id = self._idval_from_value(val)
1090
+ if id is not None:
1091
+ return id
1092
+
1093
+ # Fail.
1094
+ if self.func_name is not None:
1095
+ prefix = f"In {self.func_name}: "
1096
+ elif self.nodeid is not None:
1097
+ prefix = f"In {self.nodeid}: "
1098
+ else:
1099
+ prefix = ""
1100
+ msg = (
1101
+ f"{prefix}ids contains unsupported value {saferepr(val)} (type: {type(val)!r}) at index {idx}. "
1102
+ "Supported types are: str, bytes, int, float, complex, bool, enum, regex or anything with a __name__."
1103
+ )
1104
+ fail(msg, pytrace=False)
1105
+
1106
+ @staticmethod
1107
+ def _idval_from_argname(argname: str, idx: int) -> str:
1108
+ """Make an ID for a parameter in a ParameterSet from the argument name
1109
+ and the index of the ParameterSet."""
1110
+ return str(argname) + str(idx)
1111
+
1112
+
1113
+ @final
1114
+ @dataclasses.dataclass(frozen=True)
1115
+ class CallSpec2:
1116
+ """A planned parameterized invocation of a test function.
1117
+
1118
+ Calculated during collection for a given test function's Metafunc.
1119
+ Once collection is over, each callspec is turned into a single Item
1120
+ and stored in item.callspec.
1121
+ """
1122
+
1123
+ # arg name -> arg value which will be passed to the parametrized test
1124
+ # function (direct parameterization).
1125
+ funcargs: Dict[str, object] = dataclasses.field(default_factory=dict)
1126
+ # arg name -> arg value which will be passed to a fixture of the same name
1127
+ # (indirect parametrization).
1128
+ params: Dict[str, object] = dataclasses.field(default_factory=dict)
1129
+ # arg name -> arg index.
1130
+ indices: Dict[str, int] = dataclasses.field(default_factory=dict)
1131
+ # Used for sorting parametrized resources.
1132
+ _arg2scope: Dict[str, Scope] = dataclasses.field(default_factory=dict)
1133
+ # Parts which will be added to the item's name in `[..]` separated by "-".
1134
+ _idlist: List[str] = dataclasses.field(default_factory=list)
1135
+ # Marks which will be applied to the item.
1136
+ marks: List[Mark] = dataclasses.field(default_factory=list)
1137
+
1138
+ def setmulti(
1139
+ self,
1140
+ *,
1141
+ valtypes: Mapping[str, "Literal['params', 'funcargs']"],
1142
+ argnames: Iterable[str],
1143
+ valset: Iterable[object],
1144
+ id: str,
1145
+ marks: Iterable[Union[Mark, MarkDecorator]],
1146
+ scope: Scope,
1147
+ param_index: int,
1148
+ ) -> "CallSpec2":
1149
+ funcargs = self.funcargs.copy()
1150
+ params = self.params.copy()
1151
+ indices = self.indices.copy()
1152
+ arg2scope = self._arg2scope.copy()
1153
+ for arg, val in zip(argnames, valset):
1154
+ if arg in params or arg in funcargs:
1155
+ raise ValueError(f"duplicate parametrization of {arg!r}")
1156
+ valtype_for_arg = valtypes[arg]
1157
+ if valtype_for_arg == "params":
1158
+ params[arg] = val
1159
+ elif valtype_for_arg == "funcargs":
1160
+ funcargs[arg] = val
1161
+ else:
1162
+ assert_never(valtype_for_arg)
1163
+ indices[arg] = param_index
1164
+ arg2scope[arg] = scope
1165
+ return CallSpec2(
1166
+ funcargs=funcargs,
1167
+ params=params,
1168
+ indices=indices,
1169
+ _arg2scope=arg2scope,
1170
+ _idlist=[*self._idlist, id],
1171
+ marks=[*self.marks, *normalize_mark_list(marks)],
1172
+ )
1173
+
1174
+ def getparam(self, name: str) -> object:
1175
+ try:
1176
+ return self.params[name]
1177
+ except KeyError as e:
1178
+ raise ValueError(name) from e
1179
+
1180
+ @property
1181
+ def id(self) -> str:
1182
+ return "-".join(self._idlist)
1183
+
1184
+
1185
+ @final
1186
+ class Metafunc:
1187
+ """Objects passed to the :hook:`pytest_generate_tests` hook.
1188
+
1189
+ They help to inspect a test function and to generate tests according to
1190
+ test configuration or values specified in the class or module where a
1191
+ test function is defined.
1192
+ """
1193
+
1194
+ def __init__(
1195
+ self,
1196
+ definition: "FunctionDefinition",
1197
+ fixtureinfo: fixtures.FuncFixtureInfo,
1198
+ config: Config,
1199
+ cls=None,
1200
+ module=None,
1201
+ *,
1202
+ _ispytest: bool = False,
1203
+ ) -> None:
1204
+ check_ispytest(_ispytest)
1205
+
1206
+ #: Access to the underlying :class:`_pytest.python.FunctionDefinition`.
1207
+ self.definition = definition
1208
+
1209
+ #: Access to the :class:`pytest.Config` object for the test session.
1210
+ self.config = config
1211
+
1212
+ #: The module object where the test function is defined in.
1213
+ self.module = module
1214
+
1215
+ #: Underlying Python test function.
1216
+ self.function = definition.obj
1217
+
1218
+ #: Set of fixture names required by the test function.
1219
+ self.fixturenames = fixtureinfo.names_closure
1220
+
1221
+ #: Class object where the test function is defined in or ``None``.
1222
+ self.cls = cls
1223
+
1224
+ self._arg2fixturedefs = fixtureinfo.name2fixturedefs
1225
+
1226
+ # Result of parametrize().
1227
+ self._calls: List[CallSpec2] = []
1228
+
1229
+ def parametrize(
1230
+ self,
1231
+ argnames: Union[str, Sequence[str]],
1232
+ argvalues: Iterable[Union[ParameterSet, Sequence[object], object]],
1233
+ indirect: Union[bool, Sequence[str]] = False,
1234
+ ids: Optional[
1235
+ Union[Iterable[Optional[object]], Callable[[Any], Optional[object]]]
1236
+ ] = None,
1237
+ scope: "Optional[_ScopeName]" = None,
1238
+ *,
1239
+ _param_mark: Optional[Mark] = None,
1240
+ ) -> None:
1241
+ """Add new invocations to the underlying test function using the list
1242
+ of argvalues for the given argnames. Parametrization is performed
1243
+ during the collection phase. If you need to setup expensive resources
1244
+ see about setting indirect to do it rather than at test setup time.
1245
+
1246
+ Can be called multiple times per test function (but only on different
1247
+ argument names), in which case each call parametrizes all previous
1248
+ parametrizations, e.g.
1249
+
1250
+ ::
1251
+
1252
+ unparametrized: t
1253
+ parametrize ["x", "y"]: t[x], t[y]
1254
+ parametrize [1, 2]: t[x-1], t[x-2], t[y-1], t[y-2]
1255
+
1256
+ :param argnames:
1257
+ A comma-separated string denoting one or more argument names, or
1258
+ a list/tuple of argument strings.
1259
+
1260
+ :param argvalues:
1261
+ The list of argvalues determines how often a test is invoked with
1262
+ different argument values.
1263
+
1264
+ If only one argname was specified argvalues is a list of values.
1265
+ If N argnames were specified, argvalues must be a list of
1266
+ N-tuples, where each tuple-element specifies a value for its
1267
+ respective argname.
1268
+
1269
+ :param indirect:
1270
+ A list of arguments' names (subset of argnames) or a boolean.
1271
+ If True the list contains all names from the argnames. Each
1272
+ argvalue corresponding to an argname in this list will
1273
+ be passed as request.param to its respective argname fixture
1274
+ function so that it can perform more expensive setups during the
1275
+ setup phase of a test rather than at collection time.
1276
+
1277
+ :param ids:
1278
+ Sequence of (or generator for) ids for ``argvalues``,
1279
+ or a callable to return part of the id for each argvalue.
1280
+
1281
+ With sequences (and generators like ``itertools.count()``) the
1282
+ returned ids should be of type ``string``, ``int``, ``float``,
1283
+ ``bool``, or ``None``.
1284
+ They are mapped to the corresponding index in ``argvalues``.
1285
+ ``None`` means to use the auto-generated id.
1286
+
1287
+ If it is a callable it will be called for each entry in
1288
+ ``argvalues``, and the return value is used as part of the
1289
+ auto-generated id for the whole set (where parts are joined with
1290
+ dashes ("-")).
1291
+ This is useful to provide more specific ids for certain items, e.g.
1292
+ dates. Returning ``None`` will use an auto-generated id.
1293
+
1294
+ If no ids are provided they will be generated automatically from
1295
+ the argvalues.
1296
+
1297
+ :param scope:
1298
+ If specified it denotes the scope of the parameters.
1299
+ The scope is used for grouping tests by parameter instances.
1300
+ It will also override any fixture-function defined scope, allowing
1301
+ to set a dynamic scope using test context or configuration.
1302
+ """
1303
+ argnames, parametersets = ParameterSet._for_parametrize(
1304
+ argnames,
1305
+ argvalues,
1306
+ self.function,
1307
+ self.config,
1308
+ nodeid=self.definition.nodeid,
1309
+ )
1310
+ del argvalues
1311
+
1312
+ if "request" in argnames:
1313
+ fail(
1314
+ "'request' is a reserved name and cannot be used in @pytest.mark.parametrize",
1315
+ pytrace=False,
1316
+ )
1317
+
1318
+ if scope is not None:
1319
+ scope_ = Scope.from_user(
1320
+ scope, descr=f"parametrize() call in {self.function.__name__}"
1321
+ )
1322
+ else:
1323
+ scope_ = _find_parametrized_scope(argnames, self._arg2fixturedefs, indirect)
1324
+
1325
+ self._validate_if_using_arg_names(argnames, indirect)
1326
+
1327
+ arg_values_types = self._resolve_arg_value_types(argnames, indirect)
1328
+
1329
+ # Use any already (possibly) generated ids with parametrize Marks.
1330
+ if _param_mark and _param_mark._param_ids_from:
1331
+ generated_ids = _param_mark._param_ids_from._param_ids_generated
1332
+ if generated_ids is not None:
1333
+ ids = generated_ids
1334
+
1335
+ ids = self._resolve_parameter_set_ids(
1336
+ argnames, ids, parametersets, nodeid=self.definition.nodeid
1337
+ )
1338
+
1339
+ # Store used (possibly generated) ids with parametrize Marks.
1340
+ if _param_mark and _param_mark._param_ids_from and generated_ids is None:
1341
+ object.__setattr__(_param_mark._param_ids_from, "_param_ids_generated", ids)
1342
+
1343
+ # Create the new calls: if we are parametrize() multiple times (by applying the decorator
1344
+ # more than once) then we accumulate those calls generating the cartesian product
1345
+ # of all calls.
1346
+ newcalls = []
1347
+ for callspec in self._calls or [CallSpec2()]:
1348
+ for param_index, (param_id, param_set) in enumerate(
1349
+ zip(ids, parametersets)
1350
+ ):
1351
+ newcallspec = callspec.setmulti(
1352
+ valtypes=arg_values_types,
1353
+ argnames=argnames,
1354
+ valset=param_set.values,
1355
+ id=param_id,
1356
+ marks=param_set.marks,
1357
+ scope=scope_,
1358
+ param_index=param_index,
1359
+ )
1360
+ newcalls.append(newcallspec)
1361
+ self._calls = newcalls
1362
+
1363
+ def _resolve_parameter_set_ids(
1364
+ self,
1365
+ argnames: Sequence[str],
1366
+ ids: Optional[
1367
+ Union[Iterable[Optional[object]], Callable[[Any], Optional[object]]]
1368
+ ],
1369
+ parametersets: Sequence[ParameterSet],
1370
+ nodeid: str,
1371
+ ) -> List[str]:
1372
+ """Resolve the actual ids for the given parameter sets.
1373
+
1374
+ :param argnames:
1375
+ Argument names passed to ``parametrize()``.
1376
+ :param ids:
1377
+ The `ids` parameter of the ``parametrize()`` call (see docs).
1378
+ :param parametersets:
1379
+ The parameter sets, each containing a set of values corresponding
1380
+ to ``argnames``.
1381
+ :param nodeid str:
1382
+ The nodeid of the definition item that generated this
1383
+ parametrization.
1384
+ :returns:
1385
+ List with ids for each parameter set given.
1386
+ """
1387
+ if ids is None:
1388
+ idfn = None
1389
+ ids_ = None
1390
+ elif callable(ids):
1391
+ idfn = ids
1392
+ ids_ = None
1393
+ else:
1394
+ idfn = None
1395
+ ids_ = self._validate_ids(ids, parametersets, self.function.__name__)
1396
+ id_maker = IdMaker(
1397
+ argnames,
1398
+ parametersets,
1399
+ idfn,
1400
+ ids_,
1401
+ self.config,
1402
+ nodeid=nodeid,
1403
+ func_name=self.function.__name__,
1404
+ )
1405
+ return id_maker.make_unique_parameterset_ids()
1406
+
1407
+ def _validate_ids(
1408
+ self,
1409
+ ids: Iterable[Optional[object]],
1410
+ parametersets: Sequence[ParameterSet],
1411
+ func_name: str,
1412
+ ) -> List[Optional[object]]:
1413
+ try:
1414
+ num_ids = len(ids) # type: ignore[arg-type]
1415
+ except TypeError:
1416
+ try:
1417
+ iter(ids)
1418
+ except TypeError as e:
1419
+ raise TypeError("ids must be a callable or an iterable") from e
1420
+ num_ids = len(parametersets)
1421
+
1422
+ # num_ids == 0 is a special case: https://github.com/pytest-dev/pytest/issues/1849
1423
+ if num_ids != len(parametersets) and num_ids != 0:
1424
+ msg = "In {}: {} parameter sets specified, with different number of ids: {}"
1425
+ fail(msg.format(func_name, len(parametersets), num_ids), pytrace=False)
1426
+
1427
+ return list(itertools.islice(ids, num_ids))
1428
+
1429
+ def _resolve_arg_value_types(
1430
+ self,
1431
+ argnames: Sequence[str],
1432
+ indirect: Union[bool, Sequence[str]],
1433
+ ) -> Dict[str, "Literal['params', 'funcargs']"]:
1434
+ """Resolve if each parametrized argument must be considered a
1435
+ parameter to a fixture or a "funcarg" to the function, based on the
1436
+ ``indirect`` parameter of the parametrized() call.
1437
+
1438
+ :param List[str] argnames: List of argument names passed to ``parametrize()``.
1439
+ :param indirect: Same as the ``indirect`` parameter of ``parametrize()``.
1440
+ :rtype: Dict[str, str]
1441
+ A dict mapping each arg name to either:
1442
+ * "params" if the argname should be the parameter of a fixture of the same name.
1443
+ * "funcargs" if the argname should be a parameter to the parametrized test function.
1444
+ """
1445
+ if isinstance(indirect, bool):
1446
+ valtypes: Dict[str, Literal["params", "funcargs"]] = dict.fromkeys(
1447
+ argnames, "params" if indirect else "funcargs"
1448
+ )
1449
+ elif isinstance(indirect, Sequence):
1450
+ valtypes = dict.fromkeys(argnames, "funcargs")
1451
+ for arg in indirect:
1452
+ if arg not in argnames:
1453
+ fail(
1454
+ "In {}: indirect fixture '{}' doesn't exist".format(
1455
+ self.function.__name__, arg
1456
+ ),
1457
+ pytrace=False,
1458
+ )
1459
+ valtypes[arg] = "params"
1460
+ else:
1461
+ fail(
1462
+ "In {func}: expected Sequence or boolean for indirect, got {type}".format(
1463
+ type=type(indirect).__name__, func=self.function.__name__
1464
+ ),
1465
+ pytrace=False,
1466
+ )
1467
+ return valtypes
1468
+
1469
+ def _validate_if_using_arg_names(
1470
+ self,
1471
+ argnames: Sequence[str],
1472
+ indirect: Union[bool, Sequence[str]],
1473
+ ) -> None:
1474
+ """Check if all argnames are being used, by default values, or directly/indirectly.
1475
+
1476
+ :param List[str] argnames: List of argument names passed to ``parametrize()``.
1477
+ :param indirect: Same as the ``indirect`` parameter of ``parametrize()``.
1478
+ :raises ValueError: If validation fails.
1479
+ """
1480
+ default_arg_names = set(get_default_arg_names(self.function))
1481
+ func_name = self.function.__name__
1482
+ for arg in argnames:
1483
+ if arg not in self.fixturenames:
1484
+ if arg in default_arg_names:
1485
+ fail(
1486
+ "In {}: function already takes an argument '{}' with a default value".format(
1487
+ func_name, arg
1488
+ ),
1489
+ pytrace=False,
1490
+ )
1491
+ else:
1492
+ if isinstance(indirect, Sequence):
1493
+ name = "fixture" if arg in indirect else "argument"
1494
+ else:
1495
+ name = "fixture" if indirect else "argument"
1496
+ fail(
1497
+ f"In {func_name}: function uses no {name} '{arg}'",
1498
+ pytrace=False,
1499
+ )
1500
+
1501
+
1502
+ def _find_parametrized_scope(
1503
+ argnames: Sequence[str],
1504
+ arg2fixturedefs: Mapping[str, Sequence[fixtures.FixtureDef[object]]],
1505
+ indirect: Union[bool, Sequence[str]],
1506
+ ) -> Scope:
1507
+ """Find the most appropriate scope for a parametrized call based on its arguments.
1508
+
1509
+ When there's at least one direct argument, always use "function" scope.
1510
+
1511
+ When a test function is parametrized and all its arguments are indirect
1512
+ (e.g. fixtures), return the most narrow scope based on the fixtures used.
1513
+
1514
+ Related to issue #1832, based on code posted by @Kingdread.
1515
+ """
1516
+ if isinstance(indirect, Sequence):
1517
+ all_arguments_are_fixtures = len(indirect) == len(argnames)
1518
+ else:
1519
+ all_arguments_are_fixtures = bool(indirect)
1520
+
1521
+ if all_arguments_are_fixtures:
1522
+ fixturedefs = arg2fixturedefs or {}
1523
+ used_scopes = [
1524
+ fixturedef[0]._scope
1525
+ for name, fixturedef in fixturedefs.items()
1526
+ if name in argnames
1527
+ ]
1528
+ # Takes the most narrow scope from used fixtures.
1529
+ return min(used_scopes, default=Scope.Function)
1530
+
1531
+ return Scope.Function
1532
+
1533
+
1534
+ def _ascii_escaped_by_config(val: Union[str, bytes], config: Optional[Config]) -> str:
1535
+ if config is None:
1536
+ escape_option = False
1537
+ else:
1538
+ escape_option = config.getini(
1539
+ "disable_test_id_escaping_and_forfeit_all_rights_to_community_support"
1540
+ )
1541
+ # TODO: If escaping is turned off and the user passes bytes,
1542
+ # will return a bytes. For now we ignore this but the
1543
+ # code *probably* doesn't handle this case.
1544
+ return val if escape_option else ascii_escaped(val) # type: ignore
1545
+
1546
+
1547
+ def _pretty_fixture_path(func) -> str:
1548
+ cwd = Path.cwd()
1549
+ loc = Path(getlocation(func, str(cwd)))
1550
+ prefix = Path("...", "_pytest")
1551
+ try:
1552
+ return str(prefix / loc.relative_to(_PYTEST_DIR))
1553
+ except ValueError:
1554
+ return bestrelpath(cwd, loc)
1555
+
1556
+
1557
+ def show_fixtures_per_test(config):
1558
+ from _pytest.main import wrap_session
1559
+
1560
+ return wrap_session(config, _show_fixtures_per_test)
1561
+
1562
+
1563
+ def _show_fixtures_per_test(config: Config, session: Session) -> None:
1564
+ import _pytest.config
1565
+
1566
+ session.perform_collect()
1567
+ curdir = Path.cwd()
1568
+ tw = _pytest.config.create_terminal_writer(config)
1569
+ verbose = config.getvalue("verbose")
1570
+
1571
+ def get_best_relpath(func) -> str:
1572
+ loc = getlocation(func, str(curdir))
1573
+ return bestrelpath(curdir, Path(loc))
1574
+
1575
+ def write_fixture(fixture_def: fixtures.FixtureDef[object]) -> None:
1576
+ argname = fixture_def.argname
1577
+ if verbose <= 0 and argname.startswith("_"):
1578
+ return
1579
+ prettypath = _pretty_fixture_path(fixture_def.func)
1580
+ tw.write(f"{argname}", green=True)
1581
+ tw.write(f" -- {prettypath}", yellow=True)
1582
+ tw.write("\n")
1583
+ fixture_doc = inspect.getdoc(fixture_def.func)
1584
+ if fixture_doc:
1585
+ write_docstring(
1586
+ tw, fixture_doc.split("\n\n")[0] if verbose <= 0 else fixture_doc
1587
+ )
1588
+ else:
1589
+ tw.line(" no docstring available", red=True)
1590
+
1591
+ def write_item(item: nodes.Item) -> None:
1592
+ # Not all items have _fixtureinfo attribute.
1593
+ info: Optional[FuncFixtureInfo] = getattr(item, "_fixtureinfo", None)
1594
+ if info is None or not info.name2fixturedefs:
1595
+ # This test item does not use any fixtures.
1596
+ return
1597
+ tw.line()
1598
+ tw.sep("-", f"fixtures used by {item.name}")
1599
+ # TODO: Fix this type ignore.
1600
+ tw.sep("-", f"({get_best_relpath(item.function)})") # type: ignore[attr-defined]
1601
+ # dict key not used in loop but needed for sorting.
1602
+ for _, fixturedefs in sorted(info.name2fixturedefs.items()):
1603
+ assert fixturedefs is not None
1604
+ if not fixturedefs:
1605
+ continue
1606
+ # Last item is expected to be the one used by the test item.
1607
+ write_fixture(fixturedefs[-1])
1608
+
1609
+ for session_item in session.items:
1610
+ write_item(session_item)
1611
+
1612
+
1613
+ def showfixtures(config: Config) -> Union[int, ExitCode]:
1614
+ from _pytest.main import wrap_session
1615
+
1616
+ return wrap_session(config, _showfixtures_main)
1617
+
1618
+
1619
+ def _showfixtures_main(config: Config, session: Session) -> None:
1620
+ import _pytest.config
1621
+
1622
+ session.perform_collect()
1623
+ curdir = Path.cwd()
1624
+ tw = _pytest.config.create_terminal_writer(config)
1625
+ verbose = config.getvalue("verbose")
1626
+
1627
+ fm = session._fixturemanager
1628
+
1629
+ available = []
1630
+ seen: Set[Tuple[str, str]] = set()
1631
+
1632
+ for argname, fixturedefs in fm._arg2fixturedefs.items():
1633
+ assert fixturedefs is not None
1634
+ if not fixturedefs:
1635
+ continue
1636
+ for fixturedef in fixturedefs:
1637
+ loc = getlocation(fixturedef.func, str(curdir))
1638
+ if (fixturedef.argname, loc) in seen:
1639
+ continue
1640
+ seen.add((fixturedef.argname, loc))
1641
+ available.append(
1642
+ (
1643
+ len(fixturedef.baseid),
1644
+ fixturedef.func.__module__,
1645
+ _pretty_fixture_path(fixturedef.func),
1646
+ fixturedef.argname,
1647
+ fixturedef,
1648
+ )
1649
+ )
1650
+
1651
+ available.sort()
1652
+ currentmodule = None
1653
+ for baseid, module, prettypath, argname, fixturedef in available:
1654
+ if currentmodule != module:
1655
+ if not module.startswith("_pytest."):
1656
+ tw.line()
1657
+ tw.sep("-", f"fixtures defined from {module}")
1658
+ currentmodule = module
1659
+ if verbose <= 0 and argname.startswith("_"):
1660
+ continue
1661
+ tw.write(f"{argname}", green=True)
1662
+ if fixturedef.scope != "function":
1663
+ tw.write(" [%s scope]" % fixturedef.scope, cyan=True)
1664
+ tw.write(f" -- {prettypath}", yellow=True)
1665
+ tw.write("\n")
1666
+ doc = inspect.getdoc(fixturedef.func)
1667
+ if doc:
1668
+ write_docstring(tw, doc.split("\n\n")[0] if verbose <= 0 else doc)
1669
+ else:
1670
+ tw.line(" no docstring available", red=True)
1671
+ tw.line()
1672
+
1673
+
1674
+ def write_docstring(tw: TerminalWriter, doc: str, indent: str = " ") -> None:
1675
+ for line in doc.split("\n"):
1676
+ tw.line(indent + line)
1677
+
1678
+
1679
+ class Function(PyobjMixin, nodes.Item):
1680
+ """Item responsible for setting up and executing a Python test function.
1681
+
1682
+ :param name:
1683
+ The full function name, including any decorations like those
1684
+ added by parametrization (``my_func[my_param]``).
1685
+ :param parent:
1686
+ The parent Node.
1687
+ :param config:
1688
+ The pytest Config object.
1689
+ :param callspec:
1690
+ If given, this is function has been parametrized and the callspec contains
1691
+ meta information about the parametrization.
1692
+ :param callobj:
1693
+ If given, the object which will be called when the Function is invoked,
1694
+ otherwise the callobj will be obtained from ``parent`` using ``originalname``.
1695
+ :param keywords:
1696
+ Keywords bound to the function object for "-k" matching.
1697
+ :param session:
1698
+ The pytest Session object.
1699
+ :param fixtureinfo:
1700
+ Fixture information already resolved at this fixture node..
1701
+ :param originalname:
1702
+ The attribute name to use for accessing the underlying function object.
1703
+ Defaults to ``name``. Set this if name is different from the original name,
1704
+ for example when it contains decorations like those added by parametrization
1705
+ (``my_func[my_param]``).
1706
+ """
1707
+
1708
+ # Disable since functions handle it themselves.
1709
+ _ALLOW_MARKERS = False
1710
+
1711
+ def __init__(
1712
+ self,
1713
+ name: str,
1714
+ parent,
1715
+ config: Optional[Config] = None,
1716
+ callspec: Optional[CallSpec2] = None,
1717
+ callobj=NOTSET,
1718
+ keywords: Optional[Mapping[str, Any]] = None,
1719
+ session: Optional[Session] = None,
1720
+ fixtureinfo: Optional[FuncFixtureInfo] = None,
1721
+ originalname: Optional[str] = None,
1722
+ ) -> None:
1723
+ super().__init__(name, parent, config=config, session=session)
1724
+
1725
+ if callobj is not NOTSET:
1726
+ self.obj = callobj
1727
+
1728
+ #: Original function name, without any decorations (for example
1729
+ #: parametrization adds a ``"[...]"`` suffix to function names), used to access
1730
+ #: the underlying function object from ``parent`` (in case ``callobj`` is not given
1731
+ #: explicitly).
1732
+ #:
1733
+ #: .. versionadded:: 3.0
1734
+ self.originalname = originalname or name
1735
+
1736
+ # Note: when FunctionDefinition is introduced, we should change ``originalname``
1737
+ # to a readonly property that returns FunctionDefinition.name.
1738
+
1739
+ self.own_markers.extend(get_unpacked_marks(self.obj))
1740
+ if callspec:
1741
+ self.callspec = callspec
1742
+ self.own_markers.extend(callspec.marks)
1743
+
1744
+ # todo: this is a hell of a hack
1745
+ # https://github.com/pytest-dev/pytest/issues/4569
1746
+ # Note: the order of the updates is important here; indicates what
1747
+ # takes priority (ctor argument over function attributes over markers).
1748
+ # Take own_markers only; NodeKeywords handles parent traversal on its own.
1749
+ self.keywords.update((mark.name, mark) for mark in self.own_markers)
1750
+ self.keywords.update(self.obj.__dict__)
1751
+ if keywords:
1752
+ self.keywords.update(keywords)
1753
+
1754
+ if fixtureinfo is None:
1755
+ fixtureinfo = self.session._fixturemanager.getfixtureinfo(
1756
+ self, self.obj, self.cls, funcargs=True
1757
+ )
1758
+ self._fixtureinfo: FuncFixtureInfo = fixtureinfo
1759
+ self.fixturenames = fixtureinfo.names_closure
1760
+ self._initrequest()
1761
+
1762
+ @classmethod
1763
+ def from_parent(cls, parent, **kw): # todo: determine sound type limitations
1764
+ """The public constructor."""
1765
+ return super().from_parent(parent=parent, **kw)
1766
+
1767
+ def _initrequest(self) -> None:
1768
+ self.funcargs: Dict[str, object] = {}
1769
+ self._request = fixtures.FixtureRequest(self, _ispytest=True)
1770
+
1771
+ @property
1772
+ def function(self):
1773
+ """Underlying python 'function' object."""
1774
+ return getimfunc(self.obj)
1775
+
1776
+ def _getobj(self):
1777
+ assert self.parent is not None
1778
+ if isinstance(self.parent, Class):
1779
+ # Each Function gets a fresh class instance.
1780
+ parent_obj = self.parent.newinstance()
1781
+ else:
1782
+ parent_obj = self.parent.obj # type: ignore[attr-defined]
1783
+ return getattr(parent_obj, self.originalname)
1784
+
1785
+ @property
1786
+ def _pyfuncitem(self):
1787
+ """(compatonly) for code expecting pytest-2.2 style request objects."""
1788
+ return self
1789
+
1790
+ def runtest(self) -> None:
1791
+ """Execute the underlying test function."""
1792
+ self.ihook.pytest_pyfunc_call(pyfuncitem=self)
1793
+
1794
+ def setup(self) -> None:
1795
+ self._request._fillfixtures()
1796
+
1797
+ def _traceback_filter(self, excinfo: ExceptionInfo[BaseException]) -> Traceback:
1798
+ if hasattr(self, "_obj") and not self.config.getoption("fulltrace", False):
1799
+ code = _pytest._code.Code.from_function(get_real_func(self.obj))
1800
+ path, firstlineno = code.path, code.firstlineno
1801
+ traceback = excinfo.traceback
1802
+ ntraceback = traceback.cut(path=path, firstlineno=firstlineno)
1803
+ if ntraceback == traceback:
1804
+ ntraceback = ntraceback.cut(path=path)
1805
+ if ntraceback == traceback:
1806
+ ntraceback = ntraceback.filter(filter_traceback)
1807
+ if not ntraceback:
1808
+ ntraceback = traceback
1809
+ ntraceback = ntraceback.filter(excinfo)
1810
+
1811
+ # issue364: mark all but first and last frames to
1812
+ # only show a single-line message for each frame.
1813
+ if self.config.getoption("tbstyle", "auto") == "auto":
1814
+ if len(ntraceback) > 2:
1815
+ ntraceback = Traceback(
1816
+ entry
1817
+ if i == 0 or i == len(ntraceback) - 1
1818
+ else entry.with_repr_style("short")
1819
+ for i, entry in enumerate(ntraceback)
1820
+ )
1821
+
1822
+ return ntraceback
1823
+ return excinfo.traceback
1824
+
1825
+ # TODO: Type ignored -- breaks Liskov Substitution.
1826
+ def repr_failure( # type: ignore[override]
1827
+ self,
1828
+ excinfo: ExceptionInfo[BaseException],
1829
+ ) -> Union[str, TerminalRepr]:
1830
+ style = self.config.getoption("tbstyle", "auto")
1831
+ if style == "auto":
1832
+ style = "long"
1833
+ return self._repr_failure_py(excinfo, style=style)
1834
+
1835
+
1836
+ class FunctionDefinition(Function):
1837
+ """This class is a stop gap solution until we evolve to have actual function
1838
+ definition nodes and manage to get rid of ``metafunc``."""
1839
+
1840
+ def runtest(self) -> None:
1841
+ raise RuntimeError("function definitions are not supposed to be run as tests")
1842
+
1843
+ setup = runtest
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/python_api.py ADDED
@@ -0,0 +1,996 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import pprint
3
+ from collections.abc import Collection
4
+ from collections.abc import Sized
5
+ from decimal import Decimal
6
+ from numbers import Complex
7
+ from types import TracebackType
8
+ from typing import Any
9
+ from typing import Callable
10
+ from typing import cast
11
+ from typing import ContextManager
12
+ from typing import List
13
+ from typing import Mapping
14
+ from typing import Optional
15
+ from typing import Pattern
16
+ from typing import Sequence
17
+ from typing import Tuple
18
+ from typing import Type
19
+ from typing import TYPE_CHECKING
20
+ from typing import TypeVar
21
+ from typing import Union
22
+
23
+ if TYPE_CHECKING:
24
+ from numpy import ndarray
25
+
26
+
27
+ import _pytest._code
28
+ from _pytest.compat import final
29
+ from _pytest.compat import STRING_TYPES
30
+ from _pytest.compat import overload
31
+ from _pytest.outcomes import fail
32
+
33
+
34
+ def _non_numeric_type_error(value, at: Optional[str]) -> TypeError:
35
+ at_str = f" at {at}" if at else ""
36
+ return TypeError(
37
+ "cannot make approximate comparisons to non-numeric values: {!r} {}".format(
38
+ value, at_str
39
+ )
40
+ )
41
+
42
+
43
+ def _compare_approx(
44
+ full_object: object,
45
+ message_data: Sequence[Tuple[str, str, str]],
46
+ number_of_elements: int,
47
+ different_ids: Sequence[object],
48
+ max_abs_diff: float,
49
+ max_rel_diff: float,
50
+ ) -> List[str]:
51
+ message_list = list(message_data)
52
+ message_list.insert(0, ("Index", "Obtained", "Expected"))
53
+ max_sizes = [0, 0, 0]
54
+ for index, obtained, expected in message_list:
55
+ max_sizes[0] = max(max_sizes[0], len(index))
56
+ max_sizes[1] = max(max_sizes[1], len(obtained))
57
+ max_sizes[2] = max(max_sizes[2], len(expected))
58
+ explanation = [
59
+ f"comparison failed. Mismatched elements: {len(different_ids)} / {number_of_elements}:",
60
+ f"Max absolute difference: {max_abs_diff}",
61
+ f"Max relative difference: {max_rel_diff}",
62
+ ] + [
63
+ f"{indexes:<{max_sizes[0]}} | {obtained:<{max_sizes[1]}} | {expected:<{max_sizes[2]}}"
64
+ for indexes, obtained, expected in message_list
65
+ ]
66
+ return explanation
67
+
68
+
69
+ # builtin pytest.approx helper
70
+
71
+
72
+ class ApproxBase:
73
+ """Provide shared utilities for making approximate comparisons between
74
+ numbers or sequences of numbers."""
75
+
76
+ # Tell numpy to use our `__eq__` operator instead of its.
77
+ __array_ufunc__ = None
78
+ __array_priority__ = 100
79
+
80
+ def __init__(self, expected, rel=None, abs=None, nan_ok: bool = False) -> None:
81
+ __tracebackhide__ = True
82
+ self.expected = expected
83
+ self.abs = abs
84
+ self.rel = rel
85
+ self.nan_ok = nan_ok
86
+ self._check_type()
87
+
88
+ def __repr__(self) -> str:
89
+ raise NotImplementedError
90
+
91
+ def _repr_compare(self, other_side: Any) -> List[str]:
92
+ return [
93
+ "comparison failed",
94
+ f"Obtained: {other_side}",
95
+ f"Expected: {self}",
96
+ ]
97
+
98
+ def __eq__(self, actual) -> bool:
99
+ return all(
100
+ a == self._approx_scalar(x) for a, x in self._yield_comparisons(actual)
101
+ )
102
+
103
+ def __bool__(self):
104
+ __tracebackhide__ = True
105
+ raise AssertionError(
106
+ "approx() is not supported in a boolean context.\nDid you mean: `assert a == approx(b)`?"
107
+ )
108
+
109
+ # Ignore type because of https://github.com/python/mypy/issues/4266.
110
+ __hash__ = None # type: ignore
111
+
112
+ def __ne__(self, actual) -> bool:
113
+ return not (actual == self)
114
+
115
+ def _approx_scalar(self, x) -> "ApproxScalar":
116
+ if isinstance(x, Decimal):
117
+ return ApproxDecimal(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)
118
+ return ApproxScalar(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)
119
+
120
+ def _yield_comparisons(self, actual):
121
+ """Yield all the pairs of numbers to be compared.
122
+
123
+ This is used to implement the `__eq__` method.
124
+ """
125
+ raise NotImplementedError
126
+
127
+ def _check_type(self) -> None:
128
+ """Raise a TypeError if the expected value is not a valid type."""
129
+ # This is only a concern if the expected value is a sequence. In every
130
+ # other case, the approx() function ensures that the expected value has
131
+ # a numeric type. For this reason, the default is to do nothing. The
132
+ # classes that deal with sequences should reimplement this method to
133
+ # raise if there are any non-numeric elements in the sequence.
134
+
135
+
136
+ def _recursive_sequence_map(f, x):
137
+ """Recursively map a function over a sequence of arbitrary depth"""
138
+ if isinstance(x, (list, tuple)):
139
+ seq_type = type(x)
140
+ return seq_type(_recursive_sequence_map(f, xi) for xi in x)
141
+ else:
142
+ return f(x)
143
+
144
+
145
+ class ApproxNumpy(ApproxBase):
146
+ """Perform approximate comparisons where the expected value is numpy array."""
147
+
148
+ def __repr__(self) -> str:
149
+ list_scalars = _recursive_sequence_map(
150
+ self._approx_scalar, self.expected.tolist()
151
+ )
152
+ return f"approx({list_scalars!r})"
153
+
154
+ def _repr_compare(self, other_side: "ndarray") -> List[str]:
155
+ import itertools
156
+ import math
157
+
158
+ def get_value_from_nested_list(
159
+ nested_list: List[Any], nd_index: Tuple[Any, ...]
160
+ ) -> Any:
161
+ """
162
+ Helper function to get the value out of a nested list, given an n-dimensional index.
163
+ This mimics numpy's indexing, but for raw nested python lists.
164
+ """
165
+ value: Any = nested_list
166
+ for i in nd_index:
167
+ value = value[i]
168
+ return value
169
+
170
+ np_array_shape = self.expected.shape
171
+ approx_side_as_seq = _recursive_sequence_map(
172
+ self._approx_scalar, self.expected.tolist()
173
+ )
174
+
175
+ if np_array_shape != other_side.shape:
176
+ return [
177
+ "Impossible to compare arrays with different shapes.",
178
+ f"Shapes: {np_array_shape} and {other_side.shape}",
179
+ ]
180
+
181
+ number_of_elements = self.expected.size
182
+ max_abs_diff = -math.inf
183
+ max_rel_diff = -math.inf
184
+ different_ids = []
185
+ for index in itertools.product(*(range(i) for i in np_array_shape)):
186
+ approx_value = get_value_from_nested_list(approx_side_as_seq, index)
187
+ other_value = get_value_from_nested_list(other_side, index)
188
+ if approx_value != other_value:
189
+ abs_diff = abs(approx_value.expected - other_value)
190
+ max_abs_diff = max(max_abs_diff, abs_diff)
191
+ if other_value == 0.0:
192
+ max_rel_diff = math.inf
193
+ else:
194
+ max_rel_diff = max(max_rel_diff, abs_diff / abs(other_value))
195
+ different_ids.append(index)
196
+
197
+ message_data = [
198
+ (
199
+ str(index),
200
+ str(get_value_from_nested_list(other_side, index)),
201
+ str(get_value_from_nested_list(approx_side_as_seq, index)),
202
+ )
203
+ for index in different_ids
204
+ ]
205
+ return _compare_approx(
206
+ self.expected,
207
+ message_data,
208
+ number_of_elements,
209
+ different_ids,
210
+ max_abs_diff,
211
+ max_rel_diff,
212
+ )
213
+
214
+ def __eq__(self, actual) -> bool:
215
+ import numpy as np
216
+
217
+ # self.expected is supposed to always be an array here.
218
+
219
+ if not np.isscalar(actual):
220
+ try:
221
+ actual = np.asarray(actual)
222
+ except Exception as e:
223
+ raise TypeError(f"cannot compare '{actual}' to numpy.ndarray") from e
224
+
225
+ if not np.isscalar(actual) and actual.shape != self.expected.shape:
226
+ return False
227
+
228
+ return super().__eq__(actual)
229
+
230
+ def _yield_comparisons(self, actual):
231
+ import numpy as np
232
+
233
+ # `actual` can either be a numpy array or a scalar, it is treated in
234
+ # `__eq__` before being passed to `ApproxBase.__eq__`, which is the
235
+ # only method that calls this one.
236
+
237
+ if np.isscalar(actual):
238
+ for i in np.ndindex(self.expected.shape):
239
+ yield actual, self.expected[i].item()
240
+ else:
241
+ for i in np.ndindex(self.expected.shape):
242
+ yield actual[i].item(), self.expected[i].item()
243
+
244
+
245
+ class ApproxMapping(ApproxBase):
246
+ """Perform approximate comparisons where the expected value is a mapping
247
+ with numeric values (the keys can be anything)."""
248
+
249
+ def __repr__(self) -> str:
250
+ return "approx({!r})".format(
251
+ {k: self._approx_scalar(v) for k, v in self.expected.items()}
252
+ )
253
+
254
+ def _repr_compare(self, other_side: Mapping[object, float]) -> List[str]:
255
+ import math
256
+
257
+ approx_side_as_map = {
258
+ k: self._approx_scalar(v) for k, v in self.expected.items()
259
+ }
260
+
261
+ number_of_elements = len(approx_side_as_map)
262
+ max_abs_diff = -math.inf
263
+ max_rel_diff = -math.inf
264
+ different_ids = []
265
+ for (approx_key, approx_value), other_value in zip(
266
+ approx_side_as_map.items(), other_side.values()
267
+ ):
268
+ if approx_value != other_value:
269
+ if approx_value.expected is not None and other_value is not None:
270
+ max_abs_diff = max(
271
+ max_abs_diff, abs(approx_value.expected - other_value)
272
+ )
273
+ if approx_value.expected == 0.0:
274
+ max_rel_diff = math.inf
275
+ else:
276
+ max_rel_diff = max(
277
+ max_rel_diff,
278
+ abs(
279
+ (approx_value.expected - other_value)
280
+ / approx_value.expected
281
+ ),
282
+ )
283
+ different_ids.append(approx_key)
284
+
285
+ message_data = [
286
+ (str(key), str(other_side[key]), str(approx_side_as_map[key]))
287
+ for key in different_ids
288
+ ]
289
+
290
+ return _compare_approx(
291
+ self.expected,
292
+ message_data,
293
+ number_of_elements,
294
+ different_ids,
295
+ max_abs_diff,
296
+ max_rel_diff,
297
+ )
298
+
299
+ def __eq__(self, actual) -> bool:
300
+ try:
301
+ if set(actual.keys()) != set(self.expected.keys()):
302
+ return False
303
+ except AttributeError:
304
+ return False
305
+
306
+ return super().__eq__(actual)
307
+
308
+ def _yield_comparisons(self, actual):
309
+ for k in self.expected.keys():
310
+ yield actual[k], self.expected[k]
311
+
312
+ def _check_type(self) -> None:
313
+ __tracebackhide__ = True
314
+ for key, value in self.expected.items():
315
+ if isinstance(value, type(self.expected)):
316
+ msg = "pytest.approx() does not support nested dictionaries: key={!r} value={!r}\n full mapping={}"
317
+ raise TypeError(msg.format(key, value, pprint.pformat(self.expected)))
318
+
319
+
320
+ class ApproxSequenceLike(ApproxBase):
321
+ """Perform approximate comparisons where the expected value is a sequence of numbers."""
322
+
323
+ def __repr__(self) -> str:
324
+ seq_type = type(self.expected)
325
+ if seq_type not in (tuple, list):
326
+ seq_type = list
327
+ return "approx({!r})".format(
328
+ seq_type(self._approx_scalar(x) for x in self.expected)
329
+ )
330
+
331
+ def _repr_compare(self, other_side: Sequence[float]) -> List[str]:
332
+ import math
333
+
334
+ if len(self.expected) != len(other_side):
335
+ return [
336
+ "Impossible to compare lists with different sizes.",
337
+ f"Lengths: {len(self.expected)} and {len(other_side)}",
338
+ ]
339
+
340
+ approx_side_as_map = _recursive_sequence_map(self._approx_scalar, self.expected)
341
+
342
+ number_of_elements = len(approx_side_as_map)
343
+ max_abs_diff = -math.inf
344
+ max_rel_diff = -math.inf
345
+ different_ids = []
346
+ for i, (approx_value, other_value) in enumerate(
347
+ zip(approx_side_as_map, other_side)
348
+ ):
349
+ if approx_value != other_value:
350
+ abs_diff = abs(approx_value.expected - other_value)
351
+ max_abs_diff = max(max_abs_diff, abs_diff)
352
+ if other_value == 0.0:
353
+ max_rel_diff = math.inf
354
+ else:
355
+ max_rel_diff = max(max_rel_diff, abs_diff / abs(other_value))
356
+ different_ids.append(i)
357
+
358
+ message_data = [
359
+ (str(i), str(other_side[i]), str(approx_side_as_map[i]))
360
+ for i in different_ids
361
+ ]
362
+
363
+ return _compare_approx(
364
+ self.expected,
365
+ message_data,
366
+ number_of_elements,
367
+ different_ids,
368
+ max_abs_diff,
369
+ max_rel_diff,
370
+ )
371
+
372
+ def __eq__(self, actual) -> bool:
373
+ try:
374
+ if len(actual) != len(self.expected):
375
+ return False
376
+ except TypeError:
377
+ return False
378
+ return super().__eq__(actual)
379
+
380
+ def _yield_comparisons(self, actual):
381
+ return zip(actual, self.expected)
382
+
383
+ def _check_type(self) -> None:
384
+ __tracebackhide__ = True
385
+ for index, x in enumerate(self.expected):
386
+ if isinstance(x, type(self.expected)):
387
+ msg = "pytest.approx() does not support nested data structures: {!r} at index {}\n full sequence: {}"
388
+ raise TypeError(msg.format(x, index, pprint.pformat(self.expected)))
389
+
390
+
391
+ class ApproxScalar(ApproxBase):
392
+ """Perform approximate comparisons where the expected value is a single number."""
393
+
394
+ # Using Real should be better than this Union, but not possible yet:
395
+ # https://github.com/python/typeshed/pull/3108
396
+ DEFAULT_ABSOLUTE_TOLERANCE: Union[float, Decimal] = 1e-12
397
+ DEFAULT_RELATIVE_TOLERANCE: Union[float, Decimal] = 1e-6
398
+
399
+ def __repr__(self) -> str:
400
+ """Return a string communicating both the expected value and the
401
+ tolerance for the comparison being made.
402
+
403
+ For example, ``1.0 ± 1e-6``, ``(3+4j) ± 5e-6 ∠ ±180°``.
404
+ """
405
+ # Don't show a tolerance for values that aren't compared using
406
+ # tolerances, i.e. non-numerics and infinities. Need to call abs to
407
+ # handle complex numbers, e.g. (inf + 1j).
408
+ if (not isinstance(self.expected, (Complex, Decimal))) or math.isinf(
409
+ abs(self.expected) # type: ignore[arg-type]
410
+ ):
411
+ return str(self.expected)
412
+
413
+ # If a sensible tolerance can't be calculated, self.tolerance will
414
+ # raise a ValueError. In this case, display '???'.
415
+ try:
416
+ vetted_tolerance = f"{self.tolerance:.1e}"
417
+ if (
418
+ isinstance(self.expected, Complex)
419
+ and self.expected.imag
420
+ and not math.isinf(self.tolerance)
421
+ ):
422
+ vetted_tolerance += " ∠ ±180°"
423
+ except ValueError:
424
+ vetted_tolerance = "???"
425
+
426
+ return f"{self.expected} ± {vetted_tolerance}"
427
+
428
+ def __eq__(self, actual) -> bool:
429
+ """Return whether the given value is equal to the expected value
430
+ within the pre-specified tolerance."""
431
+ asarray = _as_numpy_array(actual)
432
+ if asarray is not None:
433
+ # Call ``__eq__()`` manually to prevent infinite-recursion with
434
+ # numpy<1.13. See #3748.
435
+ return all(self.__eq__(a) for a in asarray.flat)
436
+
437
+ # Short-circuit exact equality.
438
+ if actual == self.expected:
439
+ return True
440
+
441
+ # If either type is non-numeric, fall back to strict equality.
442
+ # NB: we need Complex, rather than just Number, to ensure that __abs__,
443
+ # __sub__, and __float__ are defined.
444
+ if not (
445
+ isinstance(self.expected, (Complex, Decimal))
446
+ and isinstance(actual, (Complex, Decimal))
447
+ ):
448
+ return False
449
+
450
+ # Allow the user to control whether NaNs are considered equal to each
451
+ # other or not. The abs() calls are for compatibility with complex
452
+ # numbers.
453
+ if math.isnan(abs(self.expected)): # type: ignore[arg-type]
454
+ return self.nan_ok and math.isnan(abs(actual)) # type: ignore[arg-type]
455
+
456
+ # Infinity shouldn't be approximately equal to anything but itself, but
457
+ # if there's a relative tolerance, it will be infinite and infinity
458
+ # will seem approximately equal to everything. The equal-to-itself
459
+ # case would have been short circuited above, so here we can just
460
+ # return false if the expected value is infinite. The abs() call is
461
+ # for compatibility with complex numbers.
462
+ if math.isinf(abs(self.expected)): # type: ignore[arg-type]
463
+ return False
464
+
465
+ # Return true if the two numbers are within the tolerance.
466
+ result: bool = abs(self.expected - actual) <= self.tolerance
467
+ return result
468
+
469
+ # Ignore type because of https://github.com/python/mypy/issues/4266.
470
+ __hash__ = None # type: ignore
471
+
472
+ @property
473
+ def tolerance(self):
474
+ """Return the tolerance for the comparison.
475
+
476
+ This could be either an absolute tolerance or a relative tolerance,
477
+ depending on what the user specified or which would be larger.
478
+ """
479
+
480
+ def set_default(x, default):
481
+ return x if x is not None else default
482
+
483
+ # Figure out what the absolute tolerance should be. ``self.abs`` is
484
+ # either None or a value specified by the user.
485
+ absolute_tolerance = set_default(self.abs, self.DEFAULT_ABSOLUTE_TOLERANCE)
486
+
487
+ if absolute_tolerance < 0:
488
+ raise ValueError(
489
+ f"absolute tolerance can't be negative: {absolute_tolerance}"
490
+ )
491
+ if math.isnan(absolute_tolerance):
492
+ raise ValueError("absolute tolerance can't be NaN.")
493
+
494
+ # If the user specified an absolute tolerance but not a relative one,
495
+ # just return the absolute tolerance.
496
+ if self.rel is None:
497
+ if self.abs is not None:
498
+ return absolute_tolerance
499
+
500
+ # Figure out what the relative tolerance should be. ``self.rel`` is
501
+ # either None or a value specified by the user. This is done after
502
+ # we've made sure the user didn't ask for an absolute tolerance only,
503
+ # because we don't want to raise errors about the relative tolerance if
504
+ # we aren't even going to use it.
505
+ relative_tolerance = set_default(
506
+ self.rel, self.DEFAULT_RELATIVE_TOLERANCE
507
+ ) * abs(self.expected)
508
+
509
+ if relative_tolerance < 0:
510
+ raise ValueError(
511
+ f"relative tolerance can't be negative: {relative_tolerance}"
512
+ )
513
+ if math.isnan(relative_tolerance):
514
+ raise ValueError("relative tolerance can't be NaN.")
515
+
516
+ # Return the larger of the relative and absolute tolerances.
517
+ return max(relative_tolerance, absolute_tolerance)
518
+
519
+
520
+ class ApproxDecimal(ApproxScalar):
521
+ """Perform approximate comparisons where the expected value is a Decimal."""
522
+
523
+ DEFAULT_ABSOLUTE_TOLERANCE = Decimal("1e-12")
524
+ DEFAULT_RELATIVE_TOLERANCE = Decimal("1e-6")
525
+
526
+
527
+ def approx(expected, rel=None, abs=None, nan_ok: bool = False) -> ApproxBase:
528
+ """Assert that two numbers (or two ordered sequences of numbers) are equal to each other
529
+ within some tolerance.
530
+
531
+ Due to the :doc:`python:tutorial/floatingpoint`, numbers that we
532
+ would intuitively expect to be equal are not always so::
533
+
534
+ >>> 0.1 + 0.2 == 0.3
535
+ False
536
+
537
+ This problem is commonly encountered when writing tests, e.g. when making
538
+ sure that floating-point values are what you expect them to be. One way to
539
+ deal with this problem is to assert that two floating-point numbers are
540
+ equal to within some appropriate tolerance::
541
+
542
+ >>> abs((0.1 + 0.2) - 0.3) < 1e-6
543
+ True
544
+
545
+ However, comparisons like this are tedious to write and difficult to
546
+ understand. Furthermore, absolute comparisons like the one above are
547
+ usually discouraged because there's no tolerance that works well for all
548
+ situations. ``1e-6`` is good for numbers around ``1``, but too small for
549
+ very big numbers and too big for very small ones. It's better to express
550
+ the tolerance as a fraction of the expected value, but relative comparisons
551
+ like that are even more difficult to write correctly and concisely.
552
+
553
+ The ``approx`` class performs floating-point comparisons using a syntax
554
+ that's as intuitive as possible::
555
+
556
+ >>> from pytest import approx
557
+ >>> 0.1 + 0.2 == approx(0.3)
558
+ True
559
+
560
+ The same syntax also works for ordered sequences of numbers::
561
+
562
+ >>> (0.1 + 0.2, 0.2 + 0.4) == approx((0.3, 0.6))
563
+ True
564
+
565
+ ``numpy`` arrays::
566
+
567
+ >>> import numpy as np # doctest: +SKIP
568
+ >>> np.array([0.1, 0.2]) + np.array([0.2, 0.4]) == approx(np.array([0.3, 0.6])) # doctest: +SKIP
569
+ True
570
+
571
+ And for a ``numpy`` array against a scalar::
572
+
573
+ >>> import numpy as np # doctest: +SKIP
574
+ >>> np.array([0.1, 0.2]) + np.array([0.2, 0.1]) == approx(0.3) # doctest: +SKIP
575
+ True
576
+
577
+ Only ordered sequences are supported, because ``approx`` needs
578
+ to infer the relative position of the sequences without ambiguity. This means
579
+ ``sets`` and other unordered sequences are not supported.
580
+
581
+ Finally, dictionary *values* can also be compared::
582
+
583
+ >>> {'a': 0.1 + 0.2, 'b': 0.2 + 0.4} == approx({'a': 0.3, 'b': 0.6})
584
+ True
585
+
586
+ The comparison will be true if both mappings have the same keys and their
587
+ respective values match the expected tolerances.
588
+
589
+ **Tolerances**
590
+
591
+ By default, ``approx`` considers numbers within a relative tolerance of
592
+ ``1e-6`` (i.e. one part in a million) of its expected value to be equal.
593
+ This treatment would lead to surprising results if the expected value was
594
+ ``0.0``, because nothing but ``0.0`` itself is relatively close to ``0.0``.
595
+ To handle this case less surprisingly, ``approx`` also considers numbers
596
+ within an absolute tolerance of ``1e-12`` of its expected value to be
597
+ equal. Infinity and NaN are special cases. Infinity is only considered
598
+ equal to itself, regardless of the relative tolerance. NaN is not
599
+ considered equal to anything by default, but you can make it be equal to
600
+ itself by setting the ``nan_ok`` argument to True. (This is meant to
601
+ facilitate comparing arrays that use NaN to mean "no data".)
602
+
603
+ Both the relative and absolute tolerances can be changed by passing
604
+ arguments to the ``approx`` constructor::
605
+
606
+ >>> 1.0001 == approx(1)
607
+ False
608
+ >>> 1.0001 == approx(1, rel=1e-3)
609
+ True
610
+ >>> 1.0001 == approx(1, abs=1e-3)
611
+ True
612
+
613
+ If you specify ``abs`` but not ``rel``, the comparison will not consider
614
+ the relative tolerance at all. In other words, two numbers that are within
615
+ the default relative tolerance of ``1e-6`` will still be considered unequal
616
+ if they exceed the specified absolute tolerance. If you specify both
617
+ ``abs`` and ``rel``, the numbers will be considered equal if either
618
+ tolerance is met::
619
+
620
+ >>> 1 + 1e-8 == approx(1)
621
+ True
622
+ >>> 1 + 1e-8 == approx(1, abs=1e-12)
623
+ False
624
+ >>> 1 + 1e-8 == approx(1, rel=1e-6, abs=1e-12)
625
+ True
626
+
627
+ You can also use ``approx`` to compare nonnumeric types, or dicts and
628
+ sequences containing nonnumeric types, in which case it falls back to
629
+ strict equality. This can be useful for comparing dicts and sequences that
630
+ can contain optional values::
631
+
632
+ >>> {"required": 1.0000005, "optional": None} == approx({"required": 1, "optional": None})
633
+ True
634
+ >>> [None, 1.0000005] == approx([None,1])
635
+ True
636
+ >>> ["foo", 1.0000005] == approx([None,1])
637
+ False
638
+
639
+ If you're thinking about using ``approx``, then you might want to know how
640
+ it compares to other good ways of comparing floating-point numbers. All of
641
+ these algorithms are based on relative and absolute tolerances and should
642
+ agree for the most part, but they do have meaningful differences:
643
+
644
+ - ``math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)``: True if the relative
645
+ tolerance is met w.r.t. either ``a`` or ``b`` or if the absolute
646
+ tolerance is met. Because the relative tolerance is calculated w.r.t.
647
+ both ``a`` and ``b``, this test is symmetric (i.e. neither ``a`` nor
648
+ ``b`` is a "reference value"). You have to specify an absolute tolerance
649
+ if you want to compare to ``0.0`` because there is no tolerance by
650
+ default. More information: :py:func:`math.isclose`.
651
+
652
+ - ``numpy.isclose(a, b, rtol=1e-5, atol=1e-8)``: True if the difference
653
+ between ``a`` and ``b`` is less that the sum of the relative tolerance
654
+ w.r.t. ``b`` and the absolute tolerance. Because the relative tolerance
655
+ is only calculated w.r.t. ``b``, this test is asymmetric and you can
656
+ think of ``b`` as the reference value. Support for comparing sequences
657
+ is provided by :py:func:`numpy.allclose`. More information:
658
+ :std:doc:`numpy:reference/generated/numpy.isclose`.
659
+
660
+ - ``unittest.TestCase.assertAlmostEqual(a, b)``: True if ``a`` and ``b``
661
+ are within an absolute tolerance of ``1e-7``. No relative tolerance is
662
+ considered , so this function is not appropriate for very large or very
663
+ small numbers. Also, it's only available in subclasses of ``unittest.TestCase``
664
+ and it's ugly because it doesn't follow PEP8. More information:
665
+ :py:meth:`unittest.TestCase.assertAlmostEqual`.
666
+
667
+ - ``a == pytest.approx(b, rel=1e-6, abs=1e-12)``: True if the relative
668
+ tolerance is met w.r.t. ``b`` or if the absolute tolerance is met.
669
+ Because the relative tolerance is only calculated w.r.t. ``b``, this test
670
+ is asymmetric and you can think of ``b`` as the reference value. In the
671
+ special case that you explicitly specify an absolute tolerance but not a
672
+ relative tolerance, only the absolute tolerance is considered.
673
+
674
+ .. note::
675
+
676
+ ``approx`` can handle numpy arrays, but we recommend the
677
+ specialised test helpers in :std:doc:`numpy:reference/routines.testing`
678
+ if you need support for comparisons, NaNs, or ULP-based tolerances.
679
+
680
+ To match strings using regex, you can use
681
+ `Matches <https://github.com/asottile/re-assert#re_assertmatchespattern-str-args-kwargs>`_
682
+ from the
683
+ `re_assert package <https://github.com/asottile/re-assert>`_.
684
+
685
+ .. warning::
686
+
687
+ .. versionchanged:: 3.2
688
+
689
+ In order to avoid inconsistent behavior, :py:exc:`TypeError` is
690
+ raised for ``>``, ``>=``, ``<`` and ``<=`` comparisons.
691
+ The example below illustrates the problem::
692
+
693
+ assert approx(0.1) > 0.1 + 1e-10 # calls approx(0.1).__gt__(0.1 + 1e-10)
694
+ assert 0.1 + 1e-10 > approx(0.1) # calls approx(0.1).__lt__(0.1 + 1e-10)
695
+
696
+ In the second example one expects ``approx(0.1).__le__(0.1 + 1e-10)``
697
+ to be called. But instead, ``approx(0.1).__lt__(0.1 + 1e-10)`` is used to
698
+ comparison. This is because the call hierarchy of rich comparisons
699
+ follows a fixed behavior. More information: :py:meth:`object.__ge__`
700
+
701
+ .. versionchanged:: 3.7.1
702
+ ``approx`` raises ``TypeError`` when it encounters a dict value or
703
+ sequence element of nonnumeric type.
704
+
705
+ .. versionchanged:: 6.1.0
706
+ ``approx`` falls back to strict equality for nonnumeric types instead
707
+ of raising ``TypeError``.
708
+ """
709
+
710
+ # Delegate the comparison to a class that knows how to deal with the type
711
+ # of the expected value (e.g. int, float, list, dict, numpy.array, etc).
712
+ #
713
+ # The primary responsibility of these classes is to implement ``__eq__()``
714
+ # and ``__repr__()``. The former is used to actually check if some
715
+ # "actual" value is equivalent to the given expected value within the
716
+ # allowed tolerance. The latter is used to show the user the expected
717
+ # value and tolerance, in the case that a test failed.
718
+ #
719
+ # The actual logic for making approximate comparisons can be found in
720
+ # ApproxScalar, which is used to compare individual numbers. All of the
721
+ # other Approx classes eventually delegate to this class. The ApproxBase
722
+ # class provides some convenient methods and overloads, but isn't really
723
+ # essential.
724
+
725
+ __tracebackhide__ = True
726
+
727
+ if isinstance(expected, Decimal):
728
+ cls: Type[ApproxBase] = ApproxDecimal
729
+ elif isinstance(expected, Mapping):
730
+ cls = ApproxMapping
731
+ elif _is_numpy_array(expected):
732
+ expected = _as_numpy_array(expected)
733
+ cls = ApproxNumpy
734
+ elif (
735
+ hasattr(expected, "__getitem__")
736
+ and isinstance(expected, Sized)
737
+ # Type ignored because the error is wrong -- not unreachable.
738
+ and not isinstance(expected, STRING_TYPES) # type: ignore[unreachable]
739
+ ):
740
+ cls = ApproxSequenceLike
741
+ elif (
742
+ isinstance(expected, Collection)
743
+ # Type ignored because the error is wrong -- not unreachable.
744
+ and not isinstance(expected, STRING_TYPES) # type: ignore[unreachable]
745
+ ):
746
+ msg = f"pytest.approx() only supports ordered sequences, but got: {repr(expected)}"
747
+ raise TypeError(msg)
748
+ else:
749
+ cls = ApproxScalar
750
+
751
+ return cls(expected, rel, abs, nan_ok)
752
+
753
+
754
+ def _is_numpy_array(obj: object) -> bool:
755
+ """
756
+ Return true if the given object is implicitly convertible to ndarray,
757
+ and numpy is already imported.
758
+ """
759
+ return _as_numpy_array(obj) is not None
760
+
761
+
762
+ def _as_numpy_array(obj: object) -> Optional["ndarray"]:
763
+ """
764
+ Return an ndarray if the given object is implicitly convertible to ndarray,
765
+ and numpy is already imported, otherwise None.
766
+ """
767
+ import sys
768
+
769
+ np: Any = sys.modules.get("numpy")
770
+ if np is not None:
771
+ # avoid infinite recursion on numpy scalars, which have __array__
772
+ if np.isscalar(obj):
773
+ return None
774
+ elif isinstance(obj, np.ndarray):
775
+ return obj
776
+ elif hasattr(obj, "__array__") or hasattr("obj", "__array_interface__"):
777
+ return np.asarray(obj)
778
+ return None
779
+
780
+
781
+ # builtin pytest.raises helper
782
+
783
+ E = TypeVar("E", bound=BaseException)
784
+
785
+
786
+ @overload
787
+ def raises(
788
+ expected_exception: Union[Type[E], Tuple[Type[E], ...]],
789
+ *,
790
+ match: Optional[Union[str, Pattern[str]]] = ...,
791
+ ) -> "RaisesContext[E]":
792
+ ...
793
+
794
+
795
+ @overload
796
+ def raises( # noqa: F811
797
+ expected_exception: Union[Type[E], Tuple[Type[E], ...]],
798
+ func: Callable[..., Any],
799
+ *args: Any,
800
+ **kwargs: Any,
801
+ ) -> _pytest._code.ExceptionInfo[E]:
802
+ ...
803
+
804
+
805
+ def raises( # noqa: F811
806
+ expected_exception: Union[Type[E], Tuple[Type[E], ...]], *args: Any, **kwargs: Any
807
+ ) -> Union["RaisesContext[E]", _pytest._code.ExceptionInfo[E]]:
808
+ r"""Assert that a code block/function call raises an exception.
809
+
810
+ :param typing.Type[E] | typing.Tuple[typing.Type[E], ...] expected_exception:
811
+ The expected exception type, or a tuple if one of multiple possible
812
+ exception types are expected.
813
+ :kwparam str | typing.Pattern[str] | None match:
814
+ If specified, a string containing a regular expression,
815
+ or a regular expression object, that is tested against the string
816
+ representation of the exception using :func:`re.search`.
817
+
818
+ To match a literal string that may contain :ref:`special characters
819
+ <re-syntax>`, the pattern can first be escaped with :func:`re.escape`.
820
+
821
+ (This is only used when :py:func:`pytest.raises` is used as a context manager,
822
+ and passed through to the function otherwise.
823
+ When using :py:func:`pytest.raises` as a function, you can use:
824
+ ``pytest.raises(Exc, func, match="passed on").match("my pattern")``.)
825
+
826
+ .. currentmodule:: _pytest._code
827
+
828
+ Use ``pytest.raises`` as a context manager, which will capture the exception of the given
829
+ type::
830
+
831
+ >>> import pytest
832
+ >>> with pytest.raises(ZeroDivisionError):
833
+ ... 1/0
834
+
835
+ If the code block does not raise the expected exception (``ZeroDivisionError`` in the example
836
+ above), or no exception at all, the check will fail instead.
837
+
838
+ You can also use the keyword argument ``match`` to assert that the
839
+ exception matches a text or regex::
840
+
841
+ >>> with pytest.raises(ValueError, match='must be 0 or None'):
842
+ ... raise ValueError("value must be 0 or None")
843
+
844
+ >>> with pytest.raises(ValueError, match=r'must be \d+$'):
845
+ ... raise ValueError("value must be 42")
846
+
847
+ The context manager produces an :class:`ExceptionInfo` object which can be used to inspect the
848
+ details of the captured exception::
849
+
850
+ >>> with pytest.raises(ValueError) as exc_info:
851
+ ... raise ValueError("value must be 42")
852
+ >>> assert exc_info.type is ValueError
853
+ >>> assert exc_info.value.args[0] == "value must be 42"
854
+
855
+ .. note::
856
+
857
+ When using ``pytest.raises`` as a context manager, it's worthwhile to
858
+ note that normal context manager rules apply and that the exception
859
+ raised *must* be the final line in the scope of the context manager.
860
+ Lines of code after that, within the scope of the context manager will
861
+ not be executed. For example::
862
+
863
+ >>> value = 15
864
+ >>> with pytest.raises(ValueError) as exc_info:
865
+ ... if value > 10:
866
+ ... raise ValueError("value must be <= 10")
867
+ ... assert exc_info.type is ValueError # this will not execute
868
+
869
+ Instead, the following approach must be taken (note the difference in
870
+ scope)::
871
+
872
+ >>> with pytest.raises(ValueError) as exc_info:
873
+ ... if value > 10:
874
+ ... raise ValueError("value must be <= 10")
875
+ ...
876
+ >>> assert exc_info.type is ValueError
877
+
878
+ **Using with** ``pytest.mark.parametrize``
879
+
880
+ When using :ref:`pytest.mark.parametrize ref`
881
+ it is possible to parametrize tests such that
882
+ some runs raise an exception and others do not.
883
+
884
+ See :ref:`parametrizing_conditional_raising` for an example.
885
+
886
+ **Legacy form**
887
+
888
+ It is possible to specify a callable by passing a to-be-called lambda::
889
+
890
+ >>> raises(ZeroDivisionError, lambda: 1/0)
891
+ <ExceptionInfo ...>
892
+
893
+ or you can specify an arbitrary callable with arguments::
894
+
895
+ >>> def f(x): return 1/x
896
+ ...
897
+ >>> raises(ZeroDivisionError, f, 0)
898
+ <ExceptionInfo ...>
899
+ >>> raises(ZeroDivisionError, f, x=0)
900
+ <ExceptionInfo ...>
901
+
902
+ The form above is fully supported but discouraged for new code because the
903
+ context manager form is regarded as more readable and less error-prone.
904
+
905
+ .. note::
906
+ Similar to caught exception objects in Python, explicitly clearing
907
+ local references to returned ``ExceptionInfo`` objects can
908
+ help the Python interpreter speed up its garbage collection.
909
+
910
+ Clearing those references breaks a reference cycle
911
+ (``ExceptionInfo`` --> caught exception --> frame stack raising
912
+ the exception --> current frame stack --> local variables -->
913
+ ``ExceptionInfo``) which makes Python keep all objects referenced
914
+ from that cycle (including all local variables in the current
915
+ frame) alive until the next cyclic garbage collection run.
916
+ More detailed information can be found in the official Python
917
+ documentation for :ref:`the try statement <python:try>`.
918
+ """
919
+ __tracebackhide__ = True
920
+
921
+ if not expected_exception:
922
+ raise ValueError(
923
+ f"Expected an exception type or a tuple of exception types, but got `{expected_exception!r}`. "
924
+ f"Raising exceptions is already understood as failing the test, so you don't need "
925
+ f"any special code to say 'this should never raise an exception'."
926
+ )
927
+ if isinstance(expected_exception, type):
928
+ expected_exceptions: Tuple[Type[E], ...] = (expected_exception,)
929
+ else:
930
+ expected_exceptions = expected_exception
931
+ for exc in expected_exceptions:
932
+ if not isinstance(exc, type) or not issubclass(exc, BaseException):
933
+ msg = "expected exception must be a BaseException type, not {}" # type: ignore[unreachable]
934
+ not_a = exc.__name__ if isinstance(exc, type) else type(exc).__name__
935
+ raise TypeError(msg.format(not_a))
936
+
937
+ message = f"DID NOT RAISE {expected_exception}"
938
+
939
+ if not args:
940
+ match: Optional[Union[str, Pattern[str]]] = kwargs.pop("match", None)
941
+ if kwargs:
942
+ msg = "Unexpected keyword arguments passed to pytest.raises: "
943
+ msg += ", ".join(sorted(kwargs))
944
+ msg += "\nUse context-manager form instead?"
945
+ raise TypeError(msg)
946
+ return RaisesContext(expected_exception, message, match)
947
+ else:
948
+ func = args[0]
949
+ if not callable(func):
950
+ raise TypeError(f"{func!r} object (type: {type(func)}) must be callable")
951
+ try:
952
+ func(*args[1:], **kwargs)
953
+ except expected_exception as e:
954
+ return _pytest._code.ExceptionInfo.from_exception(e)
955
+ fail(message)
956
+
957
+
958
+ # This doesn't work with mypy for now. Use fail.Exception instead.
959
+ raises.Exception = fail.Exception # type: ignore
960
+
961
+
962
+ @final
963
+ class RaisesContext(ContextManager[_pytest._code.ExceptionInfo[E]]):
964
+ def __init__(
965
+ self,
966
+ expected_exception: Union[Type[E], Tuple[Type[E], ...]],
967
+ message: str,
968
+ match_expr: Optional[Union[str, Pattern[str]]] = None,
969
+ ) -> None:
970
+ self.expected_exception = expected_exception
971
+ self.message = message
972
+ self.match_expr = match_expr
973
+ self.excinfo: Optional[_pytest._code.ExceptionInfo[E]] = None
974
+
975
+ def __enter__(self) -> _pytest._code.ExceptionInfo[E]:
976
+ self.excinfo = _pytest._code.ExceptionInfo.for_later()
977
+ return self.excinfo
978
+
979
+ def __exit__(
980
+ self,
981
+ exc_type: Optional[Type[BaseException]],
982
+ exc_val: Optional[BaseException],
983
+ exc_tb: Optional[TracebackType],
984
+ ) -> bool:
985
+ __tracebackhide__ = True
986
+ if exc_type is None:
987
+ fail(self.message)
988
+ assert self.excinfo is not None
989
+ if not issubclass(exc_type, self.expected_exception):
990
+ return False
991
+ # Cast to narrow the exception type now that it's verified.
992
+ exc_info = cast(Tuple[Type[E], E, TracebackType], (exc_type, exc_val, exc_tb))
993
+ self.excinfo.fill_unfilled(exc_info)
994
+ if self.match_expr is not None:
995
+ self.excinfo.match(self.match_expr)
996
+ return True
platform/dataops/dto/.venv/lib/python3.12/site-packages/_pytest/python_path.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+ from pytest import Config
5
+ from pytest import Parser
6
+
7
+
8
+ def pytest_addoption(parser: Parser) -> None:
9
+ parser.addini("pythonpath", type="paths", help="Add paths to sys.path", default=[])
10
+
11
+
12
+ @pytest.hookimpl(tryfirst=True)
13
+ def pytest_load_initial_conftests(early_config: Config) -> None:
14
+ # `pythonpath = a b` will set `sys.path` to `[a, b, x, y, z, ...]`
15
+ for path in reversed(early_config.getini("pythonpath")):
16
+ sys.path.insert(0, str(path))
17
+
18
+
19
+ @pytest.hookimpl(trylast=True)
20
+ def pytest_unconfigure(config: Config) -> None:
21
+ for path in config.getini("pythonpath"):
22
+ path_str = str(path)
23
+ if path_str in sys.path:
24
+ sys.path.remove(path_str)