jasonfan commited on
Commit
bf21701
·
verified ·
1 Parent(s): 09d838f

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. miniconda3/envs/ladir/lib/python3.10/site-packages/zope_event-6.1.dist-info/licenses/LICENSE.txt +44 -0
  2. miniconda3/envs/ladir/lib/python3.10/site-packages/zope_event-6.1.dist-info/top_level.txt +1 -0
  3. miniconda3/envs/ladir/lib/python3.10/site-packages/zope_interface-8.2.dist-info/INSTALLER +1 -0
  4. miniconda3/envs/ladir/lib/python3.10/site-packages/zope_interface-8.2.dist-info/METADATA +1288 -0
  5. miniconda3/envs/ladir/lib/python3.10/site-packages/zope_interface-8.2.dist-info/RECORD +108 -0
  6. miniconda3/envs/ladir/lib/python3.10/site-packages/zope_interface-8.2.dist-info/WHEEL +8 -0
  7. miniconda3/envs/ladir/lib/python3.10/site-packages/zope_interface-8.2.dist-info/licenses/LICENSE.txt +44 -0
  8. miniconda3/envs/ladir/lib/python3.10/site-packages/zope_interface-8.2.dist-info/top_level.txt +1 -0
  9. miniconda3/envs/ladir/lib/python3.10/site-packages/ztijwthelper/__init__.py +23 -0
  10. miniconda3/envs/ladir/lib/python3.10/site-packages/ztijwthelper/__version__.py +3 -0
  11. miniconda3/envs/ladir/lib/python3.10/site-packages/ztijwthelper/exception.py +4 -0
  12. miniconda3/envs/ladir/lib/python3.10/site-packages/ztijwthelper/memfd.py +40 -0
  13. miniconda3/envs/ladir/lib/python3.10/site-packages/ztijwthelper/metric.py +41 -0
  14. miniconda3/envs/ladir/lib/python3.10/site-packages/ztijwthelper/models.py +183 -0
  15. miniconda3/envs/ladir/lib/python3.10/site-packages/ztijwthelper/rw_lock.py +32 -0
  16. miniconda3/envs/ladir/lib/python3.10/site-packages/ztijwthelper/spiffe_id.py +35 -0
  17. miniconda3/envs/ladir/lib/python3.10/site-packages/ztijwthelper/zti_jwt_helper.py +478 -0
  18. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/__init__.py +1 -0
  19. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/__version__.py +3 -0
  20. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/error.py +2 -0
  21. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/__init__.py +0 -0
  22. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/proto/__init__.py +0 -0
  23. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/proto/workload/__init__.py +2 -0
  24. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/proto/workload/workload_pb2.py +59 -0
  25. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/proto/workload/workload_pb2_grpc.py +170 -0
  26. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/proto/workload_py2/__init__.py +2 -0
  27. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/proto/workload_py2/workload_pb2.py +665 -0
  28. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/proto/workload_py2/workload_pb2_grpc.py +170 -0
  29. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/spiffeid/__init__.py +1 -0
  30. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/spiffeid/id.py +87 -0
  31. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/svid/__init__.py +0 -0
  32. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/svid/x509svid/__init__.py +2 -0
  33. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/svid/x509svid/svid.py +83 -0
  34. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/svid/x509svid/verify.py +43 -0
  35. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spire/__init__.py +0 -0
  36. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spire/api/__init__.py +0 -0
  37. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spire/api/workload/__init__.py +2 -0
  38. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spire/api/workload/jwt_client.py +49 -0
  39. miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spire/api/workload/x509_client.py +200 -0
  40. miniconda3/envs/ladir/lib/python3.10/sqlite3/__init__.py +71 -0
  41. miniconda3/envs/ladir/lib/python3.10/sqlite3/dbapi2.py +103 -0
  42. miniconda3/envs/ladir/lib/python3.10/sqlite3/dump.py +82 -0
  43. miniconda3/envs/ladir/lib/python3.10/test/__init__.py +1 -0
  44. miniconda3/envs/ladir/lib/python3.10/test/support/__init__.py +2166 -0
  45. miniconda3/envs/ladir/lib/python3.10/test/support/bytecode_helper.py +42 -0
  46. miniconda3/envs/ladir/lib/python3.10/test/support/hashlib_helper.py +51 -0
  47. miniconda3/envs/ladir/lib/python3.10/test/support/import_helper.py +220 -0
  48. miniconda3/envs/ladir/lib/python3.10/test/support/interpreters.py +197 -0
  49. miniconda3/envs/ladir/lib/python3.10/test/support/logging_helper.py +29 -0
  50. miniconda3/envs/ladir/lib/python3.10/test/support/os_helper.py +623 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/zope_event-6.1.dist-info/licenses/LICENSE.txt ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Zope Public License (ZPL) Version 2.1
2
+
3
+ A copyright notice accompanies this license document that identifies the
4
+ copyright holders.
5
+
6
+ This license has been certified as open source. It has also been designated as
7
+ GPL compatible by the Free Software Foundation (FSF).
8
+
9
+ Redistribution and use in source and binary forms, with or without
10
+ modification, are permitted provided that the following conditions are met:
11
+
12
+ 1. Redistributions in source code must retain the accompanying copyright
13
+ notice, this list of conditions, and the following disclaimer.
14
+
15
+ 2. Redistributions in binary form must reproduce the accompanying 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. Names of the copyright holders must not be used to endorse or promote
20
+ products derived from this software without prior written permission from the
21
+ copyright holders.
22
+
23
+ 4. The right to distribute this software or to use it for any purpose does not
24
+ give you the right to use Servicemarks (sm) or Trademarks (tm) of the
25
+ copyright
26
+ holders. Use of them is covered by separate agreement with the copyright
27
+ holders.
28
+
29
+ 5. If any files are modified, you must cause the modified files to carry
30
+ prominent notices stating that you changed the files and the date of any
31
+ change.
32
+
33
+ Disclaimer
34
+
35
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
36
+ OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37
+ OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
38
+ EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
39
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
40
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
41
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
42
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
43
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
44
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
miniconda3/envs/ladir/lib/python3.10/site-packages/zope_event-6.1.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ zope
miniconda3/envs/ladir/lib/python3.10/site-packages/zope_interface-8.2.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
miniconda3/envs/ladir/lib/python3.10/site-packages/zope_interface-8.2.dist-info/METADATA ADDED
@@ -0,0 +1,1288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: zope.interface
3
+ Version: 8.2
4
+ Summary: Interfaces for Python
5
+ Author-email: Zope Foundation and contributors <zope-dev@zope.dev>
6
+ Maintainer-email: Plone Foundation and contributors <zope-dev@zope.dev>
7
+ License-Expression: ZPL-2.1
8
+ Project-URL: Documentation, https://zopeinterface.readthedocs.io
9
+ Project-URL: Issues, https://github.com/zopefoundation/zope.interface/issues
10
+ Project-URL: Source, https://github.com/zopefoundation/zope.interface
11
+ Project-URL: Changelog, https://github.com/zopefoundation/zope.interface/blob/master/CHANGES.rst
12
+ Keywords: interface,components,plugins
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Programming Language :: Python :: Implementation :: CPython
25
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
26
+ Requires-Python: >=3.10
27
+ Description-Content-Type: text/x-rst
28
+ License-File: LICENSE.txt
29
+ Provides-Extra: docs
30
+ Requires-Dist: Sphinx; extra == "docs"
31
+ Requires-Dist: repoze.sphinx.autointerface; extra == "docs"
32
+ Requires-Dist: furo; extra == "docs"
33
+ Provides-Extra: test
34
+ Requires-Dist: coverage[toml]; extra == "test"
35
+ Requires-Dist: zope.event; extra == "test"
36
+ Requires-Dist: zope.testing; extra == "test"
37
+ Provides-Extra: testing
38
+ Requires-Dist: coverage[toml]; extra == "testing"
39
+ Requires-Dist: zope.event; extra == "testing"
40
+ Requires-Dist: zope.testing; extra == "testing"
41
+ Dynamic: license-file
42
+
43
+ ====================
44
+ ``zope.interface``
45
+ ====================
46
+
47
+ .. image:: https://img.shields.io/pypi/v/zope.interface.svg
48
+ :target: https://pypi.python.org/pypi/zope.interface/
49
+ :alt: Latest Version
50
+
51
+ .. image:: https://img.shields.io/pypi/pyversions/zope.interface.svg
52
+ :target: https://pypi.org/project/zope.interface/
53
+ :alt: Supported Python versions
54
+
55
+ .. image:: https://github.com/zopefoundation/zope.interface/actions/workflows/tests.yml/badge.svg
56
+ :target: https://github.com/zopefoundation/zope.interface/actions/workflows/tests.yml
57
+
58
+ .. image:: https://readthedocs.org/projects/zopeinterface/badge/?version=latest
59
+ :target: https://zopeinterface.readthedocs.io/en/latest/
60
+ :alt: Documentation Status
61
+
62
+ This package is intended to be independently reusable in any Python
63
+ project. It is maintained by the `Zope Toolkit project
64
+ <https://zopetoolkit.readthedocs.io/>`_.
65
+
66
+ This package provides an implementation of "object interfaces" for Python.
67
+ Interfaces are a mechanism for labeling objects as conforming to a given
68
+ API or contract. So, this package can be considered as implementation of
69
+ the `Design By Contract`_ methodology support in Python.
70
+
71
+ .. _Design By Contract: http://en.wikipedia.org/wiki/Design_by_contract
72
+
73
+ For detailed documentation, please see https://zopeinterface.readthedocs.io/en/latest/
74
+
75
+ Change log
76
+ ==========
77
+
78
+ 8.2 (2026-01-09)
79
+ ----------------
80
+
81
+ - Move all supported package metadata into ``pyproject.toml``.
82
+
83
+ - Ignore ``__annotate_func__`` added in Python 3.14b1.
84
+
85
+
86
+ 8.1.1 (2025-11-15)
87
+ ------------------
88
+
89
+ - Fix the GitHub workflow for publishing wheels, which failed for Linux/arm64.
90
+ (`#348 <https://github.com/zopefoundation/zope.interface/issues/348>`_)
91
+
92
+
93
+ 8.1 (2025-11-10)
94
+ ----------------
95
+
96
+ - Drop support for Python 3.9.
97
+
98
+ - Add support for Python 3.14.
99
+
100
+
101
+ 8.0.1 (2025-09-25)
102
+ ------------------
103
+
104
+ - Make tests resilient against different ways of calling them.
105
+
106
+ - Remove run-time dependency on ``setuptools``.
107
+
108
+
109
+ 8.0 (2025-09-12)
110
+ ----------------
111
+
112
+ - Replace ``pkg_resources`` namespace with PEP 420 native namespace.
113
+
114
+ - Drop support for Python 3.8.
115
+
116
+ - Allow using newer ``setuptools`` version.
117
+ (`#333 <https://github.com/zopefoundation/zope.interface/issues/333>`_)
118
+
119
+
120
+ 7.2 (2024-11-28)
121
+ ----------------
122
+
123
+ - Add preliminary support for Python 3.14a2, this means that
124
+ ``.common.builtins.IByteString`` and ``.common.collections.IByteString`` are
125
+ no longer available from this Python version onwards as Python 3.14 dropped
126
+ ``collections.abc.ByteString``.
127
+
128
+
129
+ 7.1.1 (2024-10-23)
130
+ ------------------
131
+
132
+ - Fix segmentation faults in `weakrefobject.c` on Python 3.12 and 3.13.
133
+ (`#323 <https://github.com/zopefoundation/zope.interface/issues/323>`_)
134
+
135
+
136
+ 7.1.0 (2024-10-10)
137
+ ------------------
138
+
139
+ - Declare support for Python 3.13.
140
+
141
+ - Fix segmentation faults on Python 3.13.
142
+ (`#323 <https://github.com/zopefoundation/zope.interface/issues/323>`_)
143
+
144
+
145
+ 7.0.3 (2024-08-27)
146
+ ------------------
147
+
148
+ - Fix `Assertion 'memb->type -- T_PYSSIZET' failed.` for Python < 3.12.
149
+ (`#319 <https://github.com/zopefoundation/zope.interface/issues/319>`_)
150
+
151
+
152
+ 7.0.2 (2024-08-26)
153
+ ------------------
154
+
155
+ - Fix reference-counting bug in C module initialization (broken in 7.0).
156
+ (`#316 <https://github.com/zopefoundation/zope.interface/issues/316>`_)
157
+
158
+
159
+ 7.0.1 (2024-08-06)
160
+ ------------------
161
+
162
+ - Fix subclassability of ``ObjectSpecificationDescriptor`` (broken in 7.0).
163
+ (`#312 <https://github.com/zopefoundation/zope.interface/issues/312>`_)
164
+
165
+
166
+ 7.0 (2024-08-06)
167
+ ----------------
168
+
169
+ - Enable heap-based types (PEP 384) for Python >= 3.11.
170
+
171
+ - Adopt multi-phase module initialization (PEP 489).
172
+
173
+ - Drop support for Python 3.7.
174
+
175
+
176
+ 6.4.post2 (2024-05-24)
177
+ ----------------------
178
+
179
+ - Publish missing Windows wheels, second attempt.
180
+ (`#295 <https://github.com/zopefoundation/zope.interface/issues/295>`_)
181
+
182
+
183
+ 6.4.post1 (2024-05-23)
184
+ ----------------------
185
+
186
+ - Publish missing Windows wheels.
187
+ (`#295 <https://github.com/zopefoundation/zope.interface/issues/295>`_)
188
+
189
+
190
+ 6.4.post0 (2024-05-22)
191
+ ----------------------
192
+
193
+ - The sdist of version 6.4 was uploaded to PyPI as
194
+ ``zope_interface-6.4.tar.gz`` instead of ``zope.interface-6.4-py2.tar.gz``
195
+ which cannot be installed by ``zc.buildout``. This release is a re-release
196
+ of version 6.4 with the correct sdist name.
197
+ (`#298 <https://github.com/zopefoundation/zope.interface/issues/298>`_)
198
+
199
+
200
+ 6.4 (2024-05-15)
201
+ ----------------
202
+
203
+ - Adjust for incompatible changes in Python 3.13b1.
204
+ (`#292 <https://github.com/zopefoundation/zope.interface/issues/292>`_)
205
+
206
+ - Build windows wheels on GHA.
207
+
208
+
209
+ 6.3 (2024-04-12)
210
+ ----------------
211
+
212
+ - Add preliminary support for Python 3.13 as of 3.13a6.
213
+
214
+
215
+ 6.2 (2024-02-16)
216
+ ----------------
217
+
218
+ - Add preliminary support for Python 3.13 as of 3.13a3.
219
+
220
+ - Add support to use the pipe (``|``) syntax for ``typing.Union``.
221
+ (`#280 <https://github.com/zopefoundation/zope.interface/issues/280>`_)
222
+
223
+
224
+ 6.1 (2023-10-05)
225
+ ----------------
226
+
227
+ - Build Linux binary wheels for Python 3.12.
228
+
229
+ - Add support for Python 3.12.
230
+
231
+ - Fix building of the docs for non-final versions.
232
+
233
+
234
+ 6.0 (2023-03-17)
235
+ ----------------
236
+
237
+ - Build Linux binary wheels for Python 3.11.
238
+
239
+ - Drop support for Python 2.7, 3.5, 3.6.
240
+
241
+ - Fix test deprecation warning on Python 3.11.
242
+
243
+ - Add preliminary support for Python 3.12 as of 3.12a5.
244
+
245
+ - Drop:
246
+
247
+ + `zope.interface.implements`
248
+ + `zope.interface.implementsOnly`
249
+ + `zope.interface.classProvides`
250
+
251
+
252
+ 5.5.2 (2022-11-17)
253
+ ------------------
254
+
255
+ - Add support for building arm64 wheels on macOS.
256
+
257
+
258
+ 5.5.1 (2022-11-03)
259
+ ------------------
260
+
261
+ - Add support for final Python 3.11 release.
262
+
263
+
264
+ 5.5.0 (2022-10-10)
265
+ ------------------
266
+
267
+ - Add support for Python 3.10 and 3.11 (as of 3.11.0rc2).
268
+
269
+ - Add missing Trove classifier showing support for Python 3.9.
270
+
271
+ - Add some more entries to ``zope.interface.interfaces.__all__``.
272
+
273
+ - Disable unsafe math optimizations in C code. See `pull request 262
274
+ <https://github.com/zopefoundation/zope.interface/pull/262>`_.
275
+
276
+
277
+ 5.4.0 (2021-04-15)
278
+ ------------------
279
+
280
+ - Make the C implementation of the ``__providedBy__`` descriptor stop
281
+ ignoring all errors raised when accessing the instance's
282
+ ``__provides__``. Now it behaves like the Python version and only
283
+ catches ``AttributeError``. The previous behaviour could lead to
284
+ crashing the interpreter in cases of recursion and errors. See
285
+ `issue 239 <https://github.com/zopefoundation/zope.interface/issues>`_.
286
+
287
+ - Update the ``repr()`` and ``str()`` of various objects to be shorter
288
+ and more informative. In many cases, the ``repr()`` is now something
289
+ that can be evaluated to produce an equal object. For example, what
290
+ was previously printed as ``<implementedBy builtins.list>`` is now
291
+ shown as ``classImplements(list, IMutableSequence, IIterable)``. See
292
+ `issue 236 <https://github.com/zopefoundation/zope.interface/issues/236>`_.
293
+
294
+ - Make ``Declaration.__add__`` (as in ``implementedBy(Cls) +
295
+ ISomething``) try harder to preserve a consistent resolution order
296
+ when the two arguments share overlapping pieces of the interface
297
+ inheritance hierarchy. Previously, the right hand side was always
298
+ put at the end of the resolution order, which could easily produce
299
+ invalid orders. See `issue 193
300
+ <https://github.com/zopefoundation/zope.interface/issues/193>`_.
301
+
302
+
303
+ 5.3.0 (2020-03-21)
304
+ ------------------
305
+
306
+ - No changes from 5.3.0a1
307
+
308
+
309
+ 5.3.0a1 (2021-03-18)
310
+ --------------------
311
+
312
+ - Improve the repr of ``zope.interface.Provides`` to remove ambiguity
313
+ about what is being provided. This is especially helpful diagnosing
314
+ IRO issues.
315
+
316
+ - Allow subclasses of ``BaseAdapterRegistry`` (including
317
+ ``AdapterRegistry`` and ``VerifyingAdapterRegistry``) to have
318
+ control over the data structures. This allows persistent
319
+ implementations such as those based on ZODB to choose more scalable
320
+ options (e.g., BTrees instead of dicts). See `issue 224
321
+ <https://github.com/zopefoundation/zope.interface/issues/224>`_.
322
+
323
+ - Fix a reference counting issue in ``BaseAdapterRegistry`` that could
324
+ lead to references to interfaces being kept around even when all
325
+ utilities/adapters/subscribers providing that interface have been
326
+ removed. This is mostly an issue for persistent implementations.
327
+ Note that this only corrects the issue moving forward, it does not
328
+ solve any already corrupted reference counts. See `issue 227
329
+ <https://github.com/zopefoundation/zope.interface/issues/227>`_.
330
+
331
+ - Add the method ``BaseAdapterRegistry.rebuild()``. This can be used
332
+ to fix the reference counting issue mentioned above, as well as to
333
+ update the data structures when custom data types have changed.
334
+
335
+ - Add the interface method ``IAdapterRegistry.subscribed()`` and
336
+ implementation ``BaseAdapterRegistry.subscribed()`` for querying
337
+ directly registered subscribers. See `issue 230
338
+ <https://github.com/zopefoundation/zope.interface/issues/230>`_.
339
+
340
+ - Add the maintenance method
341
+ ``Components.rebuildUtilityRegistryFromLocalCache()``. Most users
342
+ will not need this, but it can be useful if the ``Components.utilities``
343
+ registry is suspected to be out of sync with the ``Components``
344
+ object itself (this might happen to persistent ``Components``
345
+ implementations in the face of bugs).
346
+
347
+ - Fix the ``Provides`` and ``ClassProvides`` descriptors to stop
348
+ allowing redundant interfaces (those already implemented by the
349
+ underlying class or meta class) to produce an inconsistent
350
+ resolution order. This is similar to the change in ``@implementer``
351
+ in 5.1.0, and resolves inconsistent resolution orders with
352
+ ``zope.proxy`` and ``zope.location``. See `issue 207
353
+ <https://github.com/zopefoundation/zope.interface/issues/207>`_.
354
+
355
+
356
+ 5.2.0 (2020-11-05)
357
+ ------------------
358
+
359
+ - Add documentation section ``Persistency and Equality``
360
+ (`#218 <https://github.com/zopefoundation/zope.interface/issues/218>`_).
361
+
362
+ - Create arm64 wheels.
363
+
364
+ - Add support for Python 3.9.
365
+
366
+
367
+ 5.1.2 (2020-10-01)
368
+ ------------------
369
+
370
+ - Make sure to call each invariant only once when validating invariants.
371
+ Previously, invariants could be called multiple times because when an
372
+ invariant is defined in an interface, it's found by in all interfaces
373
+ inheriting from that interface. See `pull request 215
374
+ <https://github.com/zopefoundation/zope.interface/pull/215/>`_.
375
+
376
+
377
+ 5.1.1 (2020-09-30)
378
+ ------------------
379
+
380
+ - Fix the method definitions of ``IAdapterRegistry.subscribe``,
381
+ ``subscriptions`` and ``subscribers``. Previously, they all were
382
+ defined to accept a ``name`` keyword argument, but subscribers have
383
+ no names and the implementation of that interface did not accept
384
+ that argument. See `issue 208
385
+ <https://github.com/zopefoundation/zope.interface/issues/208>`_.
386
+
387
+ - Fix a potential reference leak in the C optimizations. Previously,
388
+ applications that dynamically created unique ``Specification``
389
+ objects (e.g., used ``@implementer`` on dynamic classes) could
390
+ notice a growth of small objects over time leading to increased
391
+ garbage collection times. See `issue 216
392
+ <https://github.com/zopefoundation/zope.interface/issues/216>`_.
393
+
394
+ .. caution::
395
+
396
+ This leak could prevent interfaces used as the bases of
397
+ other interfaces from being garbage collected. Those interfaces
398
+ will now be collected.
399
+
400
+ One way in which this would manifest was that ``weakref.ref``
401
+ objects (and things built upon them, like
402
+ ``Weak[Key|Value]Dictionary``) would continue to have access to
403
+ the original object even if there were no other visible
404
+ references to Python and the original object *should* have been
405
+ collected. This could be especially problematic for the
406
+ ``WeakKeyDictionary`` when combined with dynamic or local
407
+ (created in the scope of a function) interfaces, since interfaces
408
+ are hashed based just on their name and module name. See the
409
+ linked issue for an example of a resulting ``KeyError``.
410
+
411
+ Note that such potential errors are not new, they are just once
412
+ again a possibility.
413
+
414
+
415
+ 5.1.0 (2020-04-08)
416
+ ------------------
417
+
418
+ - Make ``@implementer(*iface)`` and ``classImplements(cls, *iface)``
419
+ ignore redundant interfaces. If the class already implements an
420
+ interface through inheritance, it is no longer redeclared
421
+ specifically for *cls*. This solves many instances of inconsistent
422
+ resolution orders, while still allowing the interface to be declared
423
+ for readability and maintenance purposes. See `issue 199
424
+ <https://github.com/zopefoundation/zope.interface/issues/199>`_.
425
+
426
+ - Remove all bare ``except:`` statements. Previously, when accessing
427
+ special attributes such as ``__provides__``, ``__providedBy__``,
428
+ ``__class__`` and ``__conform__``, this package wrapped such access
429
+ in a bare ``except:`` statement, meaning that many errors could pass
430
+ silently; typically this would result in a fallback path being taken
431
+ and sometimes (like with ``providedBy()``) the result would be
432
+ non-sensical. This is especially true when those attributes are
433
+ implemented with descriptors. Now, only ``AttributeError`` is
434
+ caught. This makes errors more obvious.
435
+
436
+ Obviously, this means that some exceptions will be propagated
437
+ differently than before. In particular, ``RuntimeError`` raised by
438
+ Acquisition in the case of circular containment will now be
439
+ propagated. Previously, when adapting such a broken object, a
440
+ ``TypeError`` would be the common result, but now it will be a more
441
+ informative ``RuntimeError``.
442
+
443
+ In addition, ZODB errors like ``POSKeyError`` could now be
444
+ propagated where previously they would ignored by this package.
445
+
446
+ See `issue 200 <https://github.com/zopefoundation/zope.interface/issues/200>`_.
447
+
448
+ - Require that the second argument (*bases*) to ``InterfaceClass`` is
449
+ a tuple. This only matters when directly using ``InterfaceClass`` to
450
+ create new interfaces dynamically. Previously, an individual
451
+ interface was allowed, but did not work correctly. Now it is
452
+ consistent with ``type`` and requires a tuple.
453
+
454
+ - Let interfaces define custom ``__adapt__`` methods. This implements
455
+ the other side of the :pep:`246` adaptation protocol: objects being
456
+ adapted could already implement ``__conform__`` if they know about
457
+ the interface, and now interfaces can implement ``__adapt__`` if
458
+ they know about particular objects. There is no performance penalty
459
+ for interfaces that do not supply custom ``__adapt__`` methods.
460
+
461
+ This includes the ability to add new methods, or override existing
462
+ interface methods using the new ``@interfacemethod`` decorator.
463
+
464
+ See `issue 3 <https://github.com/zopefoundation/zope.interface/issues/3>`_.
465
+
466
+ - Make the internal singleton object returned by APIs like
467
+ ``implementedBy`` and ``directlyProvidedBy`` for objects that
468
+ implement or provide no interfaces more immutable. Previously an
469
+ internal cache could be mutated. See `issue 204
470
+ <https://github.com/zopefoundation/zope.interface/issues/204>`_.
471
+
472
+
473
+ 5.0.2 (2020-03-30)
474
+ ------------------
475
+
476
+ - Ensure that objects that implement no interfaces (such as direct
477
+ subclasses of ``object``) still include ``Interface`` itself in
478
+ their ``__iro___`` and ``__sro___``. This fixes adapter registry
479
+ lookups for such objects when the adapter is registered for
480
+ ``Interface``. See `issue 197
481
+ <https://github.com/zopefoundation/zope.interface/issues/197>`_.
482
+
483
+
484
+ 5.0.1 (2020-03-21)
485
+ ------------------
486
+
487
+ - Ensure the resolution order for ``InterfaceClass`` is consistent.
488
+ See `issue 192 <https://github.com/zopefoundation/zope.interface/issues/192>`_.
489
+
490
+ - Ensure the resolution order for ``collections.OrderedDict`` is
491
+ consistent on CPython 2. (It was already consistent on Python 3 and PyPy).
492
+
493
+ - Fix the handling of the ``ZOPE_INTERFACE_STRICT_IRO`` environment
494
+ variable. Previously, ``ZOPE_INTERFACE_STRICT_RO`` was read, in
495
+ contrast with the documentation. See `issue 194
496
+ <https://github.com/zopefoundation/zope.interface/issues/194>`_.
497
+
498
+
499
+ 5.0.0 (2020-03-19)
500
+ ------------------
501
+
502
+ - Make an internal singleton object returned by APIs like
503
+ ``implementedBy`` and ``directlyProvidedBy`` immutable. Previously,
504
+ it was fully mutable and allowed changing its ``__bases___``. That
505
+ could potentially lead to wrong results in pathological corner
506
+ cases. See `issue 158
507
+ <https://github.com/zopefoundation/zope.interface/issues/158>`_.
508
+
509
+ - Support the ``PURE_PYTHON`` environment variable at runtime instead
510
+ of just at wheel build time. A value of 0 forces the C extensions to
511
+ be used (even on PyPy) failing if they aren't present. Any other
512
+ value forces the Python implementation to be used, ignoring the C
513
+ extensions. See `PR 151 <https://github.com/zopefoundation/zope.interface/pull/151>`_.
514
+
515
+ - Cache the result of ``__hash__`` method in ``InterfaceClass`` as a
516
+ speed optimization. The method is called very often (i.e several
517
+ hundred thousand times during Plone 5.2 startup). Because the hash value never
518
+ changes it can be cached. This improves test performance from 0.614s
519
+ down to 0.575s (1.07x faster). In a real world Plone case a reindex
520
+ index came down from 402s to 320s (1.26x faster). See `PR 156
521
+ <https://github.com/zopefoundation/zope.interface/pull/156>`_.
522
+
523
+ - Change the C classes ``SpecificationBase`` and its subclass
524
+ ``ClassProvidesBase`` to store implementation attributes in their structures
525
+ instead of their instance dictionaries. This eliminates the use of
526
+ an undocumented private C API function, and helps make some
527
+ instances require less memory. See `PR 154 <https://github.com/zopefoundation/zope.interface/pull/154>`_.
528
+
529
+ - Reduce memory usage in other ways based on observations of usage
530
+ patterns in Zope (3) and Plone code bases.
531
+
532
+ - Specifications with no dependents are common (more than 50%) so
533
+ avoid allocating a ``WeakKeyDictionary`` unless we need it.
534
+ - Likewise, tagged values are relatively rare, so don't allocate a
535
+ dictionary to hold them until they are used.
536
+ - Use ``__slots___`` or the C equivalent ``tp_members`` in more
537
+ common places. Note that this removes the ability to set arbitrary
538
+ instance variables on certain objects.
539
+ See `PR 155 <https://github.com/zopefoundation/zope.interface/pull/155>`_.
540
+
541
+ The changes in this release resulted in a 7% memory reduction after
542
+ loading about 6,000 modules that define about 2,200 interfaces.
543
+
544
+ .. caution::
545
+
546
+ Details of many private attributes have changed, and external use
547
+ of those private attributes may break. In particular, the
548
+ lifetime and default value of ``_v_attrs`` has changed.
549
+
550
+ - Remove support for hashing uninitialized interfaces. This could only
551
+ be done by subclassing ``InterfaceClass``. This has generated a
552
+ warning since it was first added in 2011 (3.6.5). Please call the
553
+ ``InterfaceClass`` constructor or otherwise set the appropriate
554
+ fields in your subclass before attempting to hash or sort it. See
555
+ `issue 157 <https://github.com/zopefoundation/zope.interface/issues/157>`_.
556
+
557
+ - Remove unneeded override of the ``__hash__`` method from
558
+ ``zope.interface.declarations.Implements``. Watching a reindex index
559
+ process in ZCatalog with on a Py-Spy after 10k samples the time for
560
+ ``.adapter._lookup`` was reduced from 27.5s to 18.8s (~1.5x faster).
561
+ Overall reindex index time shrunk from 369s to 293s (1.26x faster).
562
+ See `PR 161
563
+ <https://github.com/zopefoundation/zope.interface/pull/161>`_.
564
+
565
+ - Make the Python implementation closer to the C implementation by
566
+ ignoring all exceptions, not just ``AttributeError``, during (parts
567
+ of) interface adaptation. See `issue 163
568
+ <https://github.com/zopefoundation/zope.interface/issues/163>`_.
569
+
570
+ - Micro-optimization in ``.adapter._lookup`` , ``.adapter._lookupAll``
571
+ and ``.adapter._subscriptions``: By loading ``components.get`` into
572
+ a local variable before entering the loop a bytcode "LOAD_FAST 0
573
+ (components)" in the loop can be eliminated. In Plone, while running
574
+ all tests, average speedup of the "owntime" of ``_lookup`` is ~5x.
575
+ See `PR 167
576
+ <https://github.com/zopefoundation/zope.interface/pull/167>`_.
577
+
578
+ - Add ``__all__`` declarations to all modules. This helps tools that
579
+ do auto-completion and documentation and results in less cluttered
580
+ results. Wildcard ("*") are not recommended and may be affected. See
581
+ `issue 153
582
+ <https://github.com/zopefoundation/zope.interface/issues/153>`_.
583
+
584
+ - Fix ``verifyClass`` and ``verifyObject`` for builtin types like
585
+ ``dict`` that have methods taking an optional, unnamed argument with
586
+ no default value like ``dict.pop``. On PyPy3, the verification is
587
+ strict, but on PyPy2 (as on all versions of CPython) those methods
588
+ cannot be verified and are ignored. See `issue 118
589
+ <https://github.com/zopefoundation/zope.interface/issues/118>`_.
590
+
591
+ - Update the common interfaces ``IEnumerableMapping``,
592
+ ``IExtendedReadMapping``, ``IExtendedWriteMapping``,
593
+ ``IReadSequence`` and ``IUniqueMemberWriteSequence`` to no longer
594
+ require methods that were removed from Python 3 on Python 3, such as
595
+ ``__setslice___``. Now, ``dict``, ``list`` and ``tuple`` properly
596
+ verify as ``IFullMapping``, ``ISequence`` and ``IReadSequence,``
597
+ respectively on all versions of Python.
598
+
599
+ - Add human-readable ``__str___`` and ``__repr___`` to ``Attribute``
600
+ and ``Method``. These contain the name of the defining interface
601
+ and the attribute. For methods, it also includes the signature.
602
+
603
+ - Change the error strings raised by ``verifyObject`` and
604
+ ``verifyClass``. They now include more human-readable information
605
+ and exclude extraneous lines and spaces. See `issue 170
606
+ <https://github.com/zopefoundation/zope.interface/issues/170>`_.
607
+
608
+ .. caution:: This will break consumers (such as doctests) that
609
+ depended on the exact error messages.
610
+
611
+ - Make ``verifyObject`` and ``verifyClass`` report all errors, if the
612
+ candidate object has multiple detectable violations. Previously they
613
+ reported only the first error. See `issue
614
+ <https://github.com/zopefoundation/zope.interface/issues/171>`_.
615
+
616
+ Like the above, this will break consumers depending on the exact
617
+ output of error messages if more than one error is present.
618
+
619
+ - Add ``zope.interface.common.collections``,
620
+ ``zope.interface.common.numbers``, and ``zope.interface.common.io``.
621
+ These modules define interfaces based on the ABCs defined in the
622
+ standard library ``collections.abc``, ``numbers`` and ``io``
623
+ modules, respectively. Importing these modules will make the
624
+ standard library concrete classes that are registered with those
625
+ ABCs declare the appropriate interface. See `issue 138
626
+ <https://github.com/zopefoundation/zope.interface/issues/138>`_.
627
+
628
+ - Add ``zope.interface.common.builtins``. This module defines
629
+ interfaces of common builtin types, such as ``ITextString`` and
630
+ ``IByteString``, ``IDict``, etc. These interfaces extend the
631
+ appropriate interfaces from ``collections`` and ``numbers``, and the
632
+ standard library classes implement them after importing this module.
633
+ This is intended as a replacement for third-party packages like
634
+ `dolmen.builtins <https://pypi.org/project/dolmen.builtins/>`_.
635
+ See `issue 138 <https://github.com/zopefoundation/zope.interface/issues/138>`_.
636
+
637
+ - Make ``providedBy()`` and ``implementedBy()`` respect ``super``
638
+ objects. For instance, if class ``Derived`` implements ``IDerived``
639
+ and extends ``Base`` which in turn implements ``IBase``, then
640
+ ``providedBy(super(Derived, derived))`` will return ``[IBase]``.
641
+ Previously it would have returned ``[IDerived]`` (in general, it
642
+ would previously have returned whatever would have been returned
643
+ without ``super``).
644
+
645
+ Along with this change, adapter registries will unpack ``super``
646
+ objects into their ``__self___`` before passing it to the factory.
647
+ Together, this means that ``component.getAdapter(super(Derived,
648
+ self), ITarget)`` is now meaningful.
649
+
650
+ See `issue 11 <https://github.com/zopefoundation/zope.interface/issues/11>`_.
651
+
652
+ - Fix a potential interpreter crash in the low-level adapter
653
+ registry lookup functions. See issue 11.
654
+
655
+ - Adopt Python's standard `C3 resolution order
656
+ <https://www.python.org/download/releases/2.3/mro/>`_ to compute the
657
+ ``__iro__`` and ``__sro__`` of interfaces, with tweaks to support
658
+ additional cases that are common in interfaces but disallowed for
659
+ Python classes. Previously, an ad-hoc ordering that made no
660
+ particular guarantees was used.
661
+
662
+ This has many beneficial properties, including the fact that base
663
+ interface and base classes tend to appear near the end of the
664
+ resolution order instead of the beginning. The resolution order in
665
+ general should be more predictable and consistent.
666
+
667
+ .. caution::
668
+ In some cases, especially with complex interface inheritance
669
+ trees or when manually providing or implementing interfaces, the
670
+ resulting IRO may be quite different. This may affect adapter
671
+ lookup.
672
+
673
+ The C3 order enforces some constraints in order to be able to
674
+ guarantee a sensible ordering. Older versions of zope.interface did
675
+ not impose similar constraints, so it was possible to create
676
+ interfaces and declarations that are inconsistent with the C3
677
+ constraints. In that event, zope.interface will still produce a
678
+ resolution order equal to the old order, but it won't be guaranteed
679
+ to be fully C3 compliant. In the future, strict enforcement of C3
680
+ order may be the default.
681
+
682
+ A set of environment variables and module constants allows
683
+ controlling several aspects of this new behaviour. It is possible to
684
+ request warnings about inconsistent resolution orders encountered,
685
+ and even to forbid them. Differences between the C3 resolution order
686
+ and the previous order can be logged, and, in extreme cases, the
687
+ previous order can still be used (this ability will be removed in
688
+ the future). For details, see the documentation for
689
+ ``zope.interface.ro``.
690
+
691
+ - Make inherited tagged values in interfaces respect the resolution
692
+ order (``__iro__``), as method and attribute lookup does. Previously
693
+ tagged values could give inconsistent results. See `issue 190
694
+ <https://github.com/zopefoundation/zope.interface/issues/190>`_.
695
+
696
+ - Add ``getDirectTaggedValue`` (and related methods) to interfaces to
697
+ allow accessing tagged values irrespective of inheritance. See
698
+ `issue 190
699
+ <https://github.com/zopefoundation/zope.interface/issues/190>`_.
700
+
701
+ - Ensure that ``Interface`` is always the last item in the ``__iro__``
702
+ and ``__sro__``. This is usually the case, but if classes that do
703
+ not implement any interfaces are part of a class inheritance
704
+ hierarchy, ``Interface`` could be assigned too high a priority.
705
+ See `issue 8 <https://github.com/zopefoundation/zope.interface/issues/8>`_.
706
+
707
+ - Implement sorting, equality, and hashing in C for ``Interface``
708
+ objects. In micro benchmarks, this makes those operations 40% to 80%
709
+ faster. This translates to a 20% speed up in querying adapters.
710
+
711
+ Note that this changes certain implementation details. In
712
+ particular, ``InterfaceClass`` now has a non-default metaclass, and
713
+ it is enforced that ``__module__`` in instances of
714
+ ``InterfaceClass`` is read-only.
715
+
716
+ See `PR 183 <https://github.com/zopefoundation/zope.interface/pull/183>`_.
717
+
718
+
719
+ 4.7.2 (2020-03-10)
720
+ ------------------
721
+
722
+ - Remove deprecated use of setuptools features. See `issue 30
723
+ <https://github.com/zopefoundation/zope.interface/issues/30>`_.
724
+
725
+
726
+ 4.7.1 (2019-11-11)
727
+ ------------------
728
+
729
+ - Use Python 3 syntax in the documentation. See `issue 119
730
+ <https://github.com/zopefoundation/zope.interface/issues/119>`_.
731
+
732
+
733
+ 4.7.0 (2019-11-11)
734
+ ------------------
735
+
736
+ - Drop support for Python 3.4.
737
+
738
+ - Change ``queryTaggedValue``, ``getTaggedValue``,
739
+ ``getTaggedValueTags`` in interfaces. They now include inherited
740
+ values by following ``__bases__``. See `PR 144
741
+ <https://github.com/zopefoundation/zope.interface/pull/144>`_.
742
+
743
+ .. caution:: This may be a breaking change.
744
+
745
+ - Add support for Python 3.8.
746
+
747
+
748
+ 4.6.0 (2018-10-23)
749
+ ------------------
750
+
751
+ - Add support for Python 3.7
752
+
753
+ - Fix ``verifyObject`` for class objects with staticmethods on
754
+ Python 3. See `issue 126
755
+ <https://github.com/zopefoundation/zope.interface/issues/126>`_.
756
+
757
+
758
+ 4.5.0 (2018-04-19)
759
+ ------------------
760
+
761
+ - Drop support for 3.3, avoid accidental dependence breakage via setup.py.
762
+ See `PR 110 <https://github.com/zopefoundation/zope.interface/pull/110>`_.
763
+ - Allow registering and unregistering instance methods as listeners.
764
+ See `issue 12 <https://github.com/zopefoundation/zope.interface/issues/12>`_
765
+ and `PR 102 <https://github.com/zopefoundation/zope.interface/pull/102>`_.
766
+ - Synchronize and simplify zope/__init__.py. See `issue 114
767
+ <https://github.com/zopefoundation/zope.interface/issues/114>`_
768
+
769
+
770
+ 4.4.3 (2017-09-22)
771
+ ------------------
772
+
773
+ - Avoid exceptions when the ``__annotations__`` attribute is added to
774
+ interface definitions with Python 3.x type hints. See `issue 98
775
+ <https://github.com/zopefoundation/zope.interface/issues/98>`_.
776
+ - Fix the possibility of a rare crash in the C extension when
777
+ deallocating items. See `issue 100
778
+ <https://github.com/zopefoundation/zope.interface/issues/100>`_.
779
+
780
+
781
+ 4.4.2 (2017-06-14)
782
+ ------------------
783
+
784
+ - Fix a regression storing
785
+ ``zope.component.persistentregistry.PersistentRegistry`` instances.
786
+ See `issue 85 <https://github.com/zopefoundation/zope.interface/issues/85>`_.
787
+
788
+ - Fix a regression that could lead to the utility registration cache
789
+ of ``Components`` getting out of sync. See `issue 93
790
+ <https://github.com/zopefoundation/zope.interface/issues/93>`_.
791
+
792
+
793
+ 4.4.1 (2017-05-13)
794
+ ------------------
795
+
796
+ - Simplify the caching of utility-registration data. In addition to
797
+ simplification, avoids spurious test failures when checking for
798
+ leaks in tests with persistent registries. See `pull 84
799
+ <https://github.com/zopefoundation/zope.interface/pull/84>`_.
800
+
801
+ - Raise ``ValueError`` when non-text names are passed to adapter registry
802
+ methods: prevents corruption of lookup caches.
803
+
804
+
805
+ 4.4.0 (2017-04-21)
806
+ ------------------
807
+
808
+ - Avoid a warning from the C compiler.
809
+ (https://github.com/zopefoundation/zope.interface/issues/71)
810
+
811
+ - Add support for Python 3.6.
812
+
813
+
814
+ 4.3.3 (2016-12-13)
815
+ ------------------
816
+
817
+ - Correct typos and ReST formatting errors in documentation.
818
+
819
+ - Add API documentation for the adapter registry.
820
+
821
+ - Ensure that the ``LICENSE.txt`` file is included in built wheels.
822
+
823
+ - Fix C optimizations broken on Py3k. See the Python bug at:
824
+ http://bugs.python.org/issue15657
825
+ (https://github.com/zopefoundation/zope.interface/issues/60)
826
+
827
+
828
+ 4.3.2 (2016-09-05)
829
+ ------------------
830
+
831
+ - Fix equality testing of ``implementedBy`` objects and proxies.
832
+ (https://github.com/zopefoundation/zope.interface/issues/55)
833
+
834
+
835
+ 4.3.1 (2016-08-31)
836
+ ------------------
837
+
838
+ - Support Components subclasses that are not hashable.
839
+ (https://github.com/zopefoundation/zope.interface/issues/53)
840
+
841
+
842
+ 4.3.0 (2016-08-31)
843
+ ------------------
844
+
845
+ - Add the ability to sort the objects returned by ``implementedBy``.
846
+ This is compatible with the way interface classes sort so they can
847
+ be used together in ordered containers like BTrees.
848
+ (https://github.com/zopefoundation/zope.interface/issues/42)
849
+
850
+ - Make ``setuptools`` a hard dependency of ``setup.py``.
851
+ (https://github.com/zopefoundation/zope.interface/issues/13)
852
+
853
+ - Change a linear algorithm (O(n)) in ``Components.registerUtility`` and
854
+ ``Components.unregisterUtility`` into a dictionary lookup (O(1)) for
855
+ hashable components. This substantially improves the time taken to
856
+ manipulate utilities in large registries at the cost of some
857
+ additional memory usage. (https://github.com/zopefoundation/zope.interface/issues/46)
858
+
859
+
860
+ 4.2.0 (2016-06-10)
861
+ ------------------
862
+
863
+ - Add support for Python 3.5
864
+
865
+ - Drop support for Python 2.6 and 3.2.
866
+
867
+
868
+ 4.1.3 (2015-10-05)
869
+ ------------------
870
+
871
+ - Fix installation without a C compiler on Python 3.5
872
+ (https://github.com/zopefoundation/zope.interface/issues/24).
873
+
874
+
875
+ 4.1.2 (2014-12-27)
876
+ ------------------
877
+
878
+ - Add support for PyPy3.
879
+
880
+ - Remove unittest assertions deprecated in Python3.x.
881
+
882
+ - Add ``zope.interface.document.asReStructuredText``, which formats the
883
+ generated text for an interface using ReST double-backtick markers.
884
+
885
+
886
+ 4.1.1 (2014-03-19)
887
+ ------------------
888
+
889
+ - Add support for Python 3.4.
890
+
891
+
892
+ 4.1.0 (2014-02-05)
893
+ ------------------
894
+
895
+ - Update ``boostrap.py`` to version 2.2.
896
+
897
+ - Add ``@named(name)`` declaration, that specifies the component name, so it
898
+ does not have to be passed in during registration.
899
+
900
+
901
+ 4.0.5 (2013-02-28)
902
+ ------------------
903
+
904
+ - Fix a bug where a decorated method caused false positive failures on
905
+ ``verifyClass()``.
906
+
907
+
908
+ 4.0.4 (2013-02-21)
909
+ ------------------
910
+
911
+ - Fix a bug that was revealed by porting zope.traversing. During a loop, the
912
+ loop body modified a weakref dict causing a ``RuntimeError`` error.
913
+
914
+
915
+ 4.0.3 (2012-12-31)
916
+ ------------------
917
+
918
+ - Fleshed out PyPI Trove classifiers.
919
+
920
+
921
+ 4.0.2 (2012-11-21)
922
+ ------------------
923
+
924
+ - Add support for Python 3.3.
925
+
926
+ - Restored ability to install the package in the absence of ``setuptools``.
927
+
928
+ - LP #1055223: Fix test which depended on dictionary order and failed randomly
929
+ in Python 3.3.
930
+
931
+
932
+ 4.0.1 (2012-05-22)
933
+ ------------------
934
+
935
+ - Drop explicit ``DeprecationWarnings`` for "class advice" APIS (these
936
+ APIs are still deprecated under Python 2.x, and still raise an exception
937
+ under Python 3.x, but no longer cause a warning to be emitted under
938
+ Python 2.x).
939
+
940
+
941
+ 4.0.0 (2012-05-16)
942
+ ------------------
943
+
944
+ - Automated build of Sphinx HTML docs and running doctest snippets via tox.
945
+
946
+ - Deprecate the "class advice" APIs from ``zope.interface.declarations``:
947
+ ``implements``, ``implementsOnly``, and ``classProvides``. In their place,
948
+ prefer the equivalent class decorators: ``@implementer``,
949
+ ``@implementer_only``, and ``@provider``. Code which uses the deprecated
950
+ APIs will not work as expected under Py3k.
951
+
952
+ - Remove use of '2to3' and associated fixers when installing under Py3k.
953
+ The code is now in a "compatible subset" which supports Python 2.6, 2.7,
954
+ and 3.2, including PyPy 1.8 (the version compatible with the 2.7 language
955
+ spec).
956
+
957
+ - Drop explicit support for Python 2.4 / 2.5 / 3.1.
958
+
959
+ - Add support for PyPy.
960
+
961
+ - Add support for continuous integration using ``tox`` and ``jenkins``.
962
+
963
+ - Add 'setup.py dev' alias (runs ``setup.py develop`` plus installs
964
+ ``nose`` and ``coverage``).
965
+
966
+ - Add 'setup.py docs' alias (installs ``Sphinx`` and dependencies).
967
+
968
+ - Replace all unittest coverage previously accomplished via doctests with
969
+ unittests. The doctests have been moved into a ``docs`` section, managed
970
+ as a Sphinx collection.
971
+
972
+ - LP #910987: Ensure that the semantics of the ``lookup`` method of
973
+ ``zope.interface.adapter.LookupBase`` are the same in both the C and
974
+ Python implementations.
975
+
976
+ - LP #900906: Avoid exceptions due to tne new ``__qualname__`` attribute
977
+ added in Python 3.3 (see PEP 3155 for rationale). Thanks to Antoine
978
+ Pitrou for the patch.
979
+
980
+
981
+ 3.8.0 (2011-09-22)
982
+ ------------------
983
+
984
+ - New module ``zope.interface.registry``. This is code moved from
985
+ ``zope.component.registry`` which implements a basic nonperistent component
986
+ registry as ``zope.interface.registry.Components``. This class was moved
987
+ from ``zope.component`` to make porting systems (such as Pyramid) that rely
988
+ only on a basic component registry to Python 3 possible without needing to
989
+ port the entirety of the ``zope.component`` package. Backwards
990
+ compatibility import shims have been left behind in ``zope.component``, so
991
+ this change will not break any existing code.
992
+
993
+ - New ``tests_require`` dependency: ``zope.event`` to test events sent by
994
+ Components implementation. The ``zope.interface`` package does not have a
995
+ hard dependency on ``zope.event``, but if ``zope.event`` is importable, it
996
+ will send component registration events when methods of an instance of
997
+ ``zope.interface.registry.Components`` are called.
998
+
999
+ - New interfaces added to support ``zope.interface.registry.Components``
1000
+ addition: ``ComponentLookupError``, ``Invalid``, ``IObjectEvent``,
1001
+ ``ObjectEvent``, ``IComponentLookup``, ``IRegistration``,
1002
+ ``IUtilityRegistration``, ``IAdapterRegistration``,
1003
+ ``ISubscriptionAdapterRegistration``, ``IHandlerRegistration``,
1004
+ ``IRegistrationEvent``, ``RegistrationEvent``, ``IRegistered``,
1005
+ ``Registered``, ``IUnregistered``, ``Unregistered``,
1006
+ ``IComponentRegistry``, and ``IComponents``.
1007
+
1008
+ - No longer Python 2.4 compatible (tested under 2.5, 2.6, 2.7, and 3.2).
1009
+
1010
+
1011
+ 3.7.0 (2011-08-13)
1012
+ ------------------
1013
+
1014
+ - Move changes from 3.6.2 - 3.6.5 to a new 3.7.x release line.
1015
+
1016
+
1017
+ 3.6.7 (2011-08-20)
1018
+ ------------------
1019
+
1020
+ - Fix sporadic failures on x86-64 platforms in tests of rich comparisons
1021
+ of interfaces.
1022
+
1023
+
1024
+ 3.6.6 (2011-08-13)
1025
+ ------------------
1026
+
1027
+ - LP #570942: Now correctly compare interfaces from different modules but
1028
+ with the same names.
1029
+
1030
+ N.B.: This is a less intrusive / destabilizing fix than the one applied in
1031
+ 3.6.3: we only fix the underlying cmp-alike function, rather than adding
1032
+ the other "rich comparison" functions.
1033
+
1034
+ - Revert to software as released with 3.6.1 for "stable" 3.6 release branch.
1035
+
1036
+
1037
+ 3.6.5 (2011-08-11)
1038
+ ------------------
1039
+
1040
+ - LP #811792: work around buggy behavior in some subclasses of
1041
+ ``zope.interface.interface.InterfaceClass``, which invoke ``__hash__``
1042
+ before initializing ``__module__`` and ``__name__``. The workaround
1043
+ returns a fixed constant hash in such cases, and issues a ``UserWarning``.
1044
+
1045
+ - LP #804832: Under PyPy, ``zope.interface`` should not build its C
1046
+ extension. Also, prevent attempting to build it under Jython.
1047
+
1048
+ - Add a tox.ini for easier xplatform testing.
1049
+
1050
+ - Fix testing deprecation warnings issued when tested under Py3K.
1051
+
1052
+
1053
+ 3.6.4 (2011-07-04)
1054
+ ------------------
1055
+
1056
+ - LP 804951: InterfaceClass instances were unhashable under Python 3.x.
1057
+
1058
+
1059
+ 3.6.3 (2011-05-26)
1060
+ ------------------
1061
+
1062
+ - LP #570942: Now correctly compare interfaces from different modules but
1063
+ with the same names.
1064
+
1065
+
1066
+ 3.6.2 (2011-05-17)
1067
+ ------------------
1068
+
1069
+ - Moved detailed documentation out-of-line from PyPI page, linking instead to
1070
+ http://docs.zope.org/zope.interface .
1071
+
1072
+ - Fixes for small issues when running tests under Python 3.2 using
1073
+ ``zope.testrunner``.
1074
+
1075
+ - LP # 675064: Specify return value type for C optimizations module init
1076
+ under Python 3: undeclared value caused warnings, and segfaults on some
1077
+ 64 bit architectures.
1078
+
1079
+ - setup.py now raises RuntimeError if you don't have Distutils installed when
1080
+ running under Python 3.
1081
+
1082
+
1083
+ 3.6.1 (2010-05-03)
1084
+ ------------------
1085
+
1086
+ - A non-ASCII character in the changelog made 3.6.0 uninstallable on
1087
+ Python 3 systems with another default encoding than UTF-8.
1088
+
1089
+ - Fix compiler warnings under GCC 4.3.3.
1090
+
1091
+
1092
+ 3.6.0 (2010-04-29)
1093
+ ------------------
1094
+
1095
+ - LP #185974: Clear the cache used by ``Specificaton.get`` inside
1096
+ ``Specification.changed``. Thanks to Jacob Holm for the patch.
1097
+
1098
+ - Add support for Python 3.1. Contributors:
1099
+
1100
+ Lennart Regebro
1101
+ Martin v Loewis
1102
+ Thomas Lotze
1103
+ Wolfgang Schnerring
1104
+
1105
+ The 3.1 support is completely backwards compatible. However, the implements
1106
+ syntax used under Python 2.X does not work under 3.X, since it depends on
1107
+ how metaclasses are implemented and this has changed. Instead it now supports
1108
+ a decorator syntax (also under Python 2.X)::
1109
+
1110
+ class Foo:
1111
+ implements(IFoo)
1112
+ ...
1113
+
1114
+ can now also be written::
1115
+
1116
+ @implementer(IFoo):
1117
+ class Foo:
1118
+ ...
1119
+
1120
+ There are 2to3 fixers available to do this change automatically in the
1121
+ zope.fixers package.
1122
+
1123
+ - Python 2.3 is no longer supported.
1124
+
1125
+
1126
+ 3.5.4 (2009-12-23)
1127
+ ------------------
1128
+
1129
+ - Use the standard Python doctest module instead of zope.testing.doctest, which
1130
+ has been deprecated.
1131
+
1132
+
1133
+ 3.5.3 (2009-12-08)
1134
+ ------------------
1135
+
1136
+ - Fix an edge case: make providedBy() work when a class has '__provides__' in
1137
+ its __slots__ (see http://thread.gmane.org/gmane.comp.web.zope.devel/22490)
1138
+
1139
+
1140
+ 3.5.2 (2009-07-01)
1141
+ ------------------
1142
+
1143
+ - BaseAdapterRegistry.unregister, unsubscribe: Remove empty portions of
1144
+ the data structures when something is removed. This avoids leaving
1145
+ references to global objects (interfaces) that may be slated for
1146
+ removal from the calling application.
1147
+
1148
+
1149
+ 3.5.1 (2009-03-18)
1150
+ ------------------
1151
+
1152
+ - verifyObject: use getattr instead of hasattr to test for object attributes
1153
+ in order to let exceptions other than AttributeError raised by properties
1154
+ propagate to the caller
1155
+
1156
+ - Add Sphinx-based documentation building to the package buildout
1157
+ configuration. Use the ``bin/docs`` command after buildout.
1158
+
1159
+ - Improve package description a bit. Unify changelog entries formatting.
1160
+
1161
+ - Change package's mailing list address to zope-dev at zope.org as
1162
+ zope3-dev at zope.org is now retired.
1163
+
1164
+
1165
+ 3.5.0 (2008-10-26)
1166
+ ------------------
1167
+
1168
+ - Fix declaration of _zope_interface_coptimizations, it's not a top level
1169
+ package.
1170
+
1171
+ - Add a DocTestSuite for odd.py module, so their tests are run.
1172
+
1173
+ - Allow to bootstrap on Jython.
1174
+
1175
+ - Fix https://bugs.launchpad.net/zope3/3.3/+bug/98388: ISpecification
1176
+ was missing a declaration for __iro__.
1177
+
1178
+ - Add optional code optimizations support, which allows the building
1179
+ of C code optimizations to fail (Jython).
1180
+
1181
+ - Replace `_flatten` with a non-recursive implementation, effectively making
1182
+ it 3x faster.
1183
+
1184
+
1185
+ 3.4.1 (2007-10-02)
1186
+ ------------------
1187
+
1188
+ - Fix a setup bug that prevented installation from source on systems
1189
+ without setuptools.
1190
+
1191
+
1192
+ 3.4.0 (2007-07-19)
1193
+ ------------------
1194
+
1195
+ - Final release for 3.4.0.
1196
+
1197
+
1198
+ 3.4.0b3 (2007-05-22)
1199
+ --------------------
1200
+
1201
+
1202
+ - When checking whether an object is already registered, use identity
1203
+ comparison, to allow adding registering with picky custom comparison methods.
1204
+
1205
+
1206
+ 3.3.0.1 (2007-01-03)
1207
+ --------------------
1208
+
1209
+ - Made a reference to OverflowWarning, which disappeared in Python
1210
+ 2.5, conditional.
1211
+
1212
+
1213
+ 3.3.0 (2007/01/03)
1214
+ ------------------
1215
+
1216
+ New Features
1217
+ ------------
1218
+
1219
+ - Refactor the adapter-lookup algorithim to make it much simpler and faster.
1220
+
1221
+ Also, implement more of the adapter-lookup logic in C, making
1222
+ debugging of application code easier, since there is less
1223
+ infrastructre code to step through.
1224
+
1225
+ - Treat objects without interface declarations as if they
1226
+ declared that they provide ``zope.interface.Interface``.
1227
+
1228
+ - Add a number of richer new adapter-registration interfaces
1229
+ that provide greater control and introspection.
1230
+
1231
+ - Add a new interface decorator to zope.interface that allows the
1232
+ setting of tagged values on an interface at definition time (see
1233
+ zope.interface.taggedValue).
1234
+
1235
+ Bug Fixes
1236
+ ---------
1237
+
1238
+ - A bug in multi-adapter lookup sometimes caused incorrect adapters to
1239
+ be returned.
1240
+
1241
+
1242
+ 3.2.0.2 (2006-04-15)
1243
+ --------------------
1244
+
1245
+ - Fix packaging bug: 'package_dir' must be a *relative* path.
1246
+
1247
+
1248
+ 3.2.0.1 (2006-04-14)
1249
+ --------------------
1250
+
1251
+ - Packaging change: suppress inclusion of 'setup.cfg' in 'sdist' builds.
1252
+
1253
+
1254
+ 3.2.0 (2006-01-05)
1255
+ ------------------
1256
+
1257
+ - Corresponds to the version of the zope.interface package shipped as part of
1258
+ the Zope 3.2.0 release.
1259
+
1260
+
1261
+ 3.1.0 (2005-10-03)
1262
+ ------------------
1263
+
1264
+ - Corresponds to the version of the zope.interface package shipped as part of
1265
+ the Zope 3.1.0 release.
1266
+
1267
+ - Made attribute resolution order consistent with component lookup order,
1268
+ i.e. new-style class MRO semantics.
1269
+
1270
+ - Deprecate 'isImplementedBy' and 'isImplementedByInstancesOf' APIs in
1271
+ favor of 'implementedBy' and 'providedBy'.
1272
+
1273
+
1274
+ 3.0.1 (2005-07-27)
1275
+ ------------------
1276
+
1277
+ - Corresponds to the version of the zope.interface package shipped as part of
1278
+ the Zope X3.0.1 release.
1279
+
1280
+ - Fix a bug reported by James Knight, which caused adapter registries
1281
+ to fail occasionally to reflect declaration changes.
1282
+
1283
+
1284
+ 3.0.0 (2004-11-07)
1285
+ ------------------
1286
+
1287
+ - Corresponds to the version of the zope.interface package shipped as part of
1288
+ the Zope X3.0.0 release.
miniconda3/envs/ladir/lib/python3.10/site-packages/zope_interface-8.2.dist-info/RECORD ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ zope/interface/__init__.py,sha256=9Euz0jFaHg3kT84m2HzikMt7s_JIAjM8BlVctyUfNTk,3475
2
+ zope/interface/__pycache__/__init__.cpython-310.pyc,,
3
+ zope/interface/__pycache__/_compat.cpython-310.pyc,,
4
+ zope/interface/__pycache__/_flatten.cpython-310.pyc,,
5
+ zope/interface/__pycache__/adapter.cpython-310.pyc,,
6
+ zope/interface/__pycache__/advice.cpython-310.pyc,,
7
+ zope/interface/__pycache__/declarations.cpython-310.pyc,,
8
+ zope/interface/__pycache__/document.cpython-310.pyc,,
9
+ zope/interface/__pycache__/exceptions.cpython-310.pyc,,
10
+ zope/interface/__pycache__/interface.cpython-310.pyc,,
11
+ zope/interface/__pycache__/interfaces.cpython-310.pyc,,
12
+ zope/interface/__pycache__/registry.cpython-310.pyc,,
13
+ zope/interface/__pycache__/ro.cpython-310.pyc,,
14
+ zope/interface/__pycache__/verify.cpython-310.pyc,,
15
+ zope/interface/_compat.py,sha256=8FPCPdRAl2Mlkc45-FBvuN8i1kvYLEkIionVgjk2AP0,4413
16
+ zope/interface/_flatten.py,sha256=NKviK4ZyLBCjxXvz5voI9pV_ui2SLqUhubbqZkvgEcg,1059
17
+ zope/interface/_zope_interface_coptimizations.c,sha256=oCYrpT2efApCO-EbKs71YXyaSohAbTqdWQ7QEh49SNA,71198
18
+ zope/interface/_zope_interface_coptimizations.cpython-310-x86_64-linux-gnu.so,sha256=fL-GPybY5zXa7KJX1h9knqbxounbao8cR2hZ054Bjz8,186360
19
+ zope/interface/adapter.py,sha256=XN9PD8OrRmP1ZJy2gPvAMXtiOnKcHL34doH0HaKHguQ,36647
20
+ zope/interface/advice.py,sha256=YftOBzbXuWQ3AuJImMtYv4SYbE7ubJrjodXzTgYR-dk,3918
21
+ zope/interface/common/__init__.py,sha256=ho-q_3jeKVq-jO-5xrN9_Q4PR0o8PDwja5NYsO7qTI0,10644
22
+ zope/interface/common/__pycache__/__init__.cpython-310.pyc,,
23
+ zope/interface/common/__pycache__/builtins.cpython-310.pyc,,
24
+ zope/interface/common/__pycache__/collections.cpython-310.pyc,,
25
+ zope/interface/common/__pycache__/idatetime.cpython-310.pyc,,
26
+ zope/interface/common/__pycache__/interfaces.cpython-310.pyc,,
27
+ zope/interface/common/__pycache__/io.cpython-310.pyc,,
28
+ zope/interface/common/__pycache__/mapping.cpython-310.pyc,,
29
+ zope/interface/common/__pycache__/numbers.cpython-310.pyc,,
30
+ zope/interface/common/__pycache__/sequence.cpython-310.pyc,,
31
+ zope/interface/common/builtins.py,sha256=WRHf0D-xo2yWu4uP0zvpISdfuwBqwFFYiYuPLNiIYvQ,3135
32
+ zope/interface/common/collections.py,sha256=duvGnbFpUHwri5idqhYblEJrdDYuUvL3vIsZtXggQC4,6809
33
+ zope/interface/common/idatetime.py,sha256=sn5ccP9CiQAYzn6mptWf05uInZFp9o_DRu9_MaDXM5c,21039
34
+ zope/interface/common/interfaces.py,sha256=fT2pigpAZuqcm0bqVVNDlvSWtv9oKfsJ73ewrymUpIE,5908
35
+ zope/interface/common/io.py,sha256=if6Yzclu_T7qeUQNsXeIqREqgVTu-rjYB_VGZfYyz3Y,1242
36
+ zope/interface/common/mapping.py,sha256=XI9lO7Uwt_9sWDFyhDIk0Rjcr5nlu7SlD2KDyqdupdw,4687
37
+ zope/interface/common/numbers.py,sha256=D4kUnF5OgAk6CKcxaW86VH_OPLh1OXt_cF6WaOfvjLk,1682
38
+ zope/interface/common/sequence.py,sha256=SYvqSZpKRaX11vCADK6zGn0LqogPQ0u7INbqgTJ4sg8,5531
39
+ zope/interface/common/tests/__init__.py,sha256=Am8tpD6HZQx6pfW7N22-dloC83-dKLA45NiM9Lx7Xss,5553
40
+ zope/interface/common/tests/__pycache__/__init__.cpython-310.pyc,,
41
+ zope/interface/common/tests/__pycache__/basemapping.cpython-310.pyc,,
42
+ zope/interface/common/tests/__pycache__/test_builtins.cpython-310.pyc,,
43
+ zope/interface/common/tests/__pycache__/test_collections.cpython-310.pyc,,
44
+ zope/interface/common/tests/__pycache__/test_idatetime.cpython-310.pyc,,
45
+ zope/interface/common/tests/__pycache__/test_import_interfaces.cpython-310.pyc,,
46
+ zope/interface/common/tests/__pycache__/test_io.cpython-310.pyc,,
47
+ zope/interface/common/tests/__pycache__/test_numbers.cpython-310.pyc,,
48
+ zope/interface/common/tests/basemapping.py,sha256=iitIJEMm7LlS3vQU51RjoN3AeBUNNf0EGLXi_VklJAs,3768
49
+ zope/interface/common/tests/test_builtins.py,sha256=eftbVFY5-e7r310YTuf6LlL1Jl5HJ0EXTWZ2icAmrnY,1485
50
+ zope/interface/common/tests/test_collections.py,sha256=XlATWN4tuHLpl_4o0eocWiPV7GGFu5xH3RUN0fPZs0s,5829
51
+ zope/interface/common/tests/test_idatetime.py,sha256=qGr8FDbiVuDZHjyDIKcz7Vz6qNfoFzd9eHejMTfIyAg,1923
52
+ zope/interface/common/tests/test_import_interfaces.py,sha256=wCFk-2kc7r-kAeOXZn5th5Qw_6k_-pMvdguk5b4NstM,813
53
+ zope/interface/common/tests/test_io.py,sha256=gYJnFT52De1JAJruKK6dzyQIdLgYdQME9Yn6QTn2QyI,1686
54
+ zope/interface/common/tests/test_numbers.py,sha256=tPrvkFVYa2kSSxf8_j7XYctupfS4BI-ee_jQ5yU8zRM,1395
55
+ zope/interface/declarations.py,sha256=csCgY3nsiTjpkjdHs53DJGoeIGSeI_mUaTISYQB_9dQ,43512
56
+ zope/interface/document.py,sha256=mhSCJoxw7Whl-q-EMSkys--z3C7IyJ6TEsZ3psMqyJE,4139
57
+ zope/interface/exceptions.py,sha256=lW7SnsOT73LZI8w3aRdCRVUubfSy-CGztchnKqv1-5A,8566
58
+ zope/interface/interface.py,sha256=IXDKNZL0W_qG9nHYwXZ4RVhrMC-pkW5arnbbxrhJo38,39859
59
+ zope/interface/interfaces.py,sha256=9abPucc_lYWpELDFt28wnbjRVtQ8pS48srV8toZmLgk,50268
60
+ zope/interface/registry.py,sha256=eDnfUtTFp1z9f-4F-4ZQ9EATLheAYuCP9_coZ3XLdVw,25812
61
+ zope/interface/ro.py,sha256=NeImEPsautGBC1VtQAQ1J1BGXmksw6hoSNWD7gVmEaQ,24577
62
+ zope/interface/tests/__init__.py,sha256=Vu2CALgC5nADbRAZFb99LcDSXECcPCNdJDL-nv_6mZA,4242
63
+ zope/interface/tests/__pycache__/__init__.cpython-310.pyc,,
64
+ zope/interface/tests/__pycache__/advisory_testing.cpython-310.pyc,,
65
+ zope/interface/tests/__pycache__/dummy.cpython-310.pyc,,
66
+ zope/interface/tests/__pycache__/idummy.cpython-310.pyc,,
67
+ zope/interface/tests/__pycache__/m1.cpython-310.pyc,,
68
+ zope/interface/tests/__pycache__/odd.cpython-310.pyc,,
69
+ zope/interface/tests/__pycache__/test_adapter.cpython-310.pyc,,
70
+ zope/interface/tests/__pycache__/test_advice.cpython-310.pyc,,
71
+ zope/interface/tests/__pycache__/test_compile_flags.cpython-310.pyc,,
72
+ zope/interface/tests/__pycache__/test_declarations.cpython-310.pyc,,
73
+ zope/interface/tests/__pycache__/test_document.cpython-310.pyc,,
74
+ zope/interface/tests/__pycache__/test_element.cpython-310.pyc,,
75
+ zope/interface/tests/__pycache__/test_exceptions.cpython-310.pyc,,
76
+ zope/interface/tests/__pycache__/test_interface.cpython-310.pyc,,
77
+ zope/interface/tests/__pycache__/test_interfaces.cpython-310.pyc,,
78
+ zope/interface/tests/__pycache__/test_odd_declarations.cpython-310.pyc,,
79
+ zope/interface/tests/__pycache__/test_registry.cpython-310.pyc,,
80
+ zope/interface/tests/__pycache__/test_ro.cpython-310.pyc,,
81
+ zope/interface/tests/__pycache__/test_sorting.cpython-310.pyc,,
82
+ zope/interface/tests/__pycache__/test_verify.cpython-310.pyc,,
83
+ zope/interface/tests/advisory_testing.py,sha256=T2XF0DT8t9zi1JxnvR1u0WXpRtyOn5027VMyEcN7Ldc,900
84
+ zope/interface/tests/dummy.py,sha256=dd_cYIiPvYJDrEMQD0m2cl9SpkVMrQzMMu1yglSrnb8,913
85
+ zope/interface/tests/idummy.py,sha256=ESC_l4UqjCkiCeXWfcphVGtrP7PoNwwTTGzLpp6Doo4,890
86
+ zope/interface/tests/m1.py,sha256=clhSXmtaT8liCnM87Kp0bzAHfxIxr6gUBjXnVuxaUNI,850
87
+ zope/interface/tests/odd.py,sha256=nwjmxbHCFuI2UvY3Pwc7CfkmZWfXsn3oCb7r7C34DxU,2967
88
+ zope/interface/tests/test_adapter.py,sha256=pB3Y_oXXtdtDsKf0BYlvpW281nT1yendxtzWgWp9o_0,80508
89
+ zope/interface/tests/test_advice.py,sha256=gFhlbHvSWuC9kdlBPeXO_8_9ihkSU-ih0pVhoocdp4U,6036
90
+ zope/interface/tests/test_compile_flags.py,sha256=wU3vtmqgzll6HMPbzFErMpORoVghrcZ5krIV4x6rfo4,1290
91
+ zope/interface/tests/test_declarations.py,sha256=gzATuEoy4KZLB3gyZDV6YD5yv5hdVaBqJIRMFdC2U7E,79081
92
+ zope/interface/tests/test_document.py,sha256=0JIYe0GWvDPkr_IBACPw-8HsHNJyNNHBU_lUHYOXd9M,17220
93
+ zope/interface/tests/test_element.py,sha256=z9Q2hYwPVzMX05NpA_IeiHoAb4qhTiHI57XQI38w4zQ,1120
94
+ zope/interface/tests/test_exceptions.py,sha256=axXG_D_Ug3wdk1r3C_4dHOsOF4h-IvTt1RFyJfkAUz8,6495
95
+ zope/interface/tests/test_interface.py,sha256=aWQAkBNgvA2M_s-gPac1XOwpi5ltkcDFy5KHyy2Gga0,93419
96
+ zope/interface/tests/test_interfaces.py,sha256=l4SCfUmVfBO1UoZLsTOOvDyoYUM7Wex3J67uR7taFpQ,4395
97
+ zope/interface/tests/test_odd_declarations.py,sha256=0DBSBIoOUdSRcDnhiScexGhZ2mVydYWnlJOBvny76Uo,7660
98
+ zope/interface/tests/test_registry.py,sha256=8CyxRkJ46ITauSGp86y1gSN4KHvZNVPTVKgjD13aXBk,112599
99
+ zope/interface/tests/test_ro.py,sha256=Z1K4CbcTkTtuEOc3y3ceXLsKjwkmO_GqYqqwzqFgvms,15257
100
+ zope/interface/tests/test_sorting.py,sha256=-lMIltkIv7Dxu_HRuYtsa6HXVf1fk_jM0gUYHEvj0ac,2222
101
+ zope/interface/tests/test_verify.py,sha256=JnVLFlHGgVn8fC6u-WPW-mDtfmSuDA2PC0sglWuVBjI,19200
102
+ zope/interface/verify.py,sha256=cEaIWPcS6gT97RkQW2SQJxxuUP7wRrwYwsJtXqo8jdE,7333
103
+ zope_interface-8.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
104
+ zope_interface-8.2.dist-info/METADATA,sha256=D9pYt0cVkYFNPORUIJYIH82HONTG8GJaz1Hr9j7PbQc,45392
105
+ zope_interface-8.2.dist-info/RECORD,,
106
+ zope_interface-8.2.dist-info/WHEEL,sha256=Aiu96bhtsfzw3NvQvzxQNkf7f9Xl2wW2dtqHpSc6fW0,224
107
+ zope_interface-8.2.dist-info/licenses/LICENSE.txt,sha256=PmcdsR32h1FswdtbPWXkqjg-rKPCDOo_r1Og9zNdCjw,2070
108
+ zope_interface-8.2.dist-info/top_level.txt,sha256=QpUHvpO4wIuZDeEgKY8qZCtD-tAukB0fn_f6utzlb98,5
miniconda3/envs/ladir/lib/python3.10/site-packages/zope_interface-8.2.dist-info/WHEEL ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp310-cp310-manylinux_2_5_x86_64
5
+ Tag: cp310-cp310-manylinux1_x86_64
6
+ Tag: cp310-cp310-manylinux_2_17_x86_64
7
+ Tag: cp310-cp310-manylinux2014_x86_64
8
+
miniconda3/envs/ladir/lib/python3.10/site-packages/zope_interface-8.2.dist-info/licenses/LICENSE.txt ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Zope Public License (ZPL) Version 2.1
2
+
3
+ A copyright notice accompanies this license document that identifies the
4
+ copyright holders.
5
+
6
+ This license has been certified as open source. It has also been designated as
7
+ GPL compatible by the Free Software Foundation (FSF).
8
+
9
+ Redistribution and use in source and binary forms, with or without
10
+ modification, are permitted provided that the following conditions are met:
11
+
12
+ 1. Redistributions in source code must retain the accompanying copyright
13
+ notice, this list of conditions, and the following disclaimer.
14
+
15
+ 2. Redistributions in binary form must reproduce the accompanying 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. Names of the copyright holders must not be used to endorse or promote
20
+ products derived from this software without prior written permission from the
21
+ copyright holders.
22
+
23
+ 4. The right to distribute this software or to use it for any purpose does not
24
+ give you the right to use Servicemarks (sm) or Trademarks (tm) of the
25
+ copyright
26
+ holders. Use of them is covered by separate agreement with the copyright
27
+ holders.
28
+
29
+ 5. If any files are modified, you must cause the modified files to carry
30
+ prominent notices stating that you changed the files and the date of any
31
+ change.
32
+
33
+ Disclaimer
34
+
35
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
36
+ OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37
+ OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
38
+ EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
39
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
40
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
41
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
42
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
43
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
44
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
miniconda3/envs/ladir/lib/python3.10/site-packages/zope_interface-8.2.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ zope
miniconda3/envs/ladir/lib/python3.10/site-packages/ztijwthelper/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .__version__ import __version__
2
+ from .exception import ZtiJwtError
3
+ from .zti_jwt_helper import (
4
+ ZTIJwtHelper,
5
+ jwt_helper,
6
+ is_token_zti,
7
+ decode_jwt_svid,
8
+ decode_gdpr_or_jwt_svid,
9
+ )
10
+
11
+ __author__ = "Jeff Li"
12
+ __email__ = "jeff.li@byteddance.com"
13
+
14
+
15
+ __all__ = [
16
+ "__version__",
17
+ "ZtiJwtError",
18
+ "ZTIJwtHelper",
19
+ "jwt_helper",
20
+ "is_token_zti",
21
+ "decode_jwt_svid",
22
+ "decode_gdpr_or_jwt_svid",
23
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/ztijwthelper/__version__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ VERSION = (0, 0, 24)
2
+
3
+ __version__ = ".".join(map(str, VERSION))
miniconda3/envs/ladir/lib/python3.10/site-packages/ztijwthelper/exception.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ class ZtiJwtError(Exception):
2
+ def __init__(self, message=None):
3
+ Exception.__init__(self, message)
4
+ self.message = message
miniconda3/envs/ladir/lib/python3.10/site-packages/ztijwthelper/memfd.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import os
3
+ from .rw_lock import RWLock
4
+
5
+ try:
6
+ from bytedmemfd import memfd
7
+ except ImportError:
8
+ memfd = None
9
+
10
+ MEMFD_DEFAULT_NAME = "zti_jwt_helper"
11
+
12
+ class Memfd(object):
13
+ def __init__(self):
14
+ self.lock = RWLock()
15
+ self.memfd_fd = None
16
+
17
+ def unwrap_memfd(self):
18
+ if memfd is None or self.memfd_fd is None:
19
+ return
20
+ try:
21
+ self.lock.lock()
22
+ os.close(self.memfd_fd)
23
+ finally:
24
+ self.lock.un_lock()
25
+
26
+ def write_content_to_memfd(self, content):
27
+ if memfd is None:
28
+ return
29
+ try:
30
+ self.lock.lock()
31
+ if self.memfd_fd is not None:
32
+ os.close(self.memfd_fd)
33
+ self.memfd_fd = None
34
+ self.memfd_fd = memfd.memfd_create(MEMFD_DEFAULT_NAME, memfd.MFD_ALLOW_SEALING)
35
+ with io.open(self.memfd_fd, mode="wb+", buffering=0, closefd=False) as f:
36
+ f.write(content)
37
+ f.seek(0)
38
+ memfd.addseals(self.memfd_fd, memfd.F_SEAL_ALL)
39
+ finally:
40
+ self.lock.un_lock()
miniconda3/envs/ladir/lib/python3.10/site-packages/ztijwthelper/metric.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ from bytedance import metrics
4
+ from ztijwthelper.__version__ import __version__
5
+
6
+ logger = logging.getLogger(__name__)
7
+ ZTI_METRICS_PREFIX = "security.zti.jwt_helper"
8
+ GET_TOKEN_FAILED = "get_token_error"
9
+ GET_TOKEN_SUCCEED = "get_token"
10
+ GET_TOKEN_FROM_STRING = "get_token_from_string"
11
+ FETCH_TOKEN_FROM_PATH_FAILED = "fetch_token_path_error"
12
+ GET_TOKEN_FROM_AGENT_FAIL = "get_token_from_agent_fail"
13
+
14
+ # backward compatible with dps agent: need to deprecate in future version
15
+ GET_TOKEN_FROM_DPS_AGENT_SUCCEED = "get_token_from_dps_agent"
16
+ GET_TOKEN_FROM_DPS_AGENT_FAIL = "get_token_from_dps_agent_fail"
17
+
18
+
19
+ class MetricsClient(object):
20
+ def __init__(self):
21
+ self.mcli = metrics.Client(prefix=ZTI_METRICS_PREFIX)
22
+
23
+ def count(self, metric_name, **kwargs):
24
+ if metric_name == "":
25
+ return
26
+ try:
27
+ kwargs.update(
28
+ {
29
+ "ver": __version__,
30
+ "language": "python",
31
+ }
32
+ )
33
+ self.mcli.emit_counter(metric_name, 1, tags=kwargs)
34
+ except Exception as e:
35
+ logger.error("jwt metric emit count failed: {}".format(e))
36
+
37
+ def flush(self):
38
+ self.mcli.flush()
39
+
40
+
41
+ metrics_client = MetricsClient()
miniconda3/envs/ladir/lib/python3.10/site-packages/ztijwthelper/models.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding: utf-8
2
+
3
+ import time
4
+ import jwt
5
+ from .spiffe_id import ID
6
+
7
+
8
+ class ZeroTrustIdentity(object):
9
+ def __init__(
10
+ self,
11
+ spiffe_id=None,
12
+ expiry=None,
13
+ namespace=None,
14
+ region=None,
15
+ vdc=None,
16
+ identity=None,
17
+ legacy_id=None,
18
+ ):
19
+ self.spiffeID = spiffe_id
20
+ self.expiry = expiry
21
+ self.namespace = namespace
22
+ self.region = region
23
+ self.vdc = vdc
24
+ self.id = identity
25
+ self.legacyID = legacy_id
26
+
27
+ def __str__(self):
28
+ return (
29
+ "{ From str method of ZeroTrustIdentity: spiffeID = %s, "
30
+ "expiry = %s, namespace = %s, region = %s, "
31
+ "vdc = %s, id = %s, legacyID = %s }"
32
+ % (
33
+ self.spiffeID,
34
+ self.expiry,
35
+ self.namespace,
36
+ self.region,
37
+ self.vdc,
38
+ self.id,
39
+ self.legacyID,
40
+ )
41
+ )
42
+
43
+ def get_id(self):
44
+ return self.id
45
+
46
+ def map2identity(self, params):
47
+ spiffe_id_str = params.get("sub")
48
+ self.spiffeID = ID().from_str(spiffe_id_str)
49
+ self.expiry = params.get("exp")
50
+ legid_map = params.get("legid")
51
+ if legid_map:
52
+ self.legacyID = LegacyIdentity(**legid_map)
53
+ else:
54
+ self.legacyID = None
55
+
56
+ for schemas in self.spiffeID.get_path().split("/"):
57
+ schema = schemas.split(":")
58
+ if len(schema) != 2:
59
+ continue
60
+ if schema[0].lower() == "id":
61
+ self.id = schema[1]
62
+ if schema[0].lower() == "r":
63
+ self.region = schema[1]
64
+ if schema[0].lower() == "vdc":
65
+ self.vdc = schema[1]
66
+ if schema[0].lower() == "ns":
67
+ self.namespace = schema[1]
68
+ return self
69
+
70
+ def get_legacy_identity_from_zti(self):
71
+ if self.legacyID is not None:
72
+ return self.legacyID
73
+ # build up a new legacy identity from zti
74
+ identity = LegacyIdentity(
75
+ version=0, authority=self.namespace, expireTime=self.expiry
76
+ )
77
+ if self.namespace == "user":
78
+ identity.primary_auth_type = "user"
79
+ identity.user = self.id
80
+ else:
81
+ identity.primary_auth_type = "psm"
82
+ identity.psm = self.id
83
+ return identity
84
+
85
+
86
+ class LegacyIdentity(object):
87
+ def __init__(self, **kwargs):
88
+ self.version = kwargs.get("version")
89
+ self.authority = kwargs.get("authority")
90
+ self.authority_chain = kwargs.get("authorityChain")
91
+ self.primary_auth_type = kwargs.get("primaryAuthType")
92
+ self.psm = kwargs.get("psm")
93
+ self.user = kwargs.get("user")
94
+ self.expire_time = kwargs.get("expireTime")
95
+ self.extension = kwargs.get("extension")
96
+
97
+ def __str__(self):
98
+ return (
99
+ "{ From str method of LegacyIdentity: version = %s, "
100
+ "authority = %s, authorityChain = %s, primaryAuthType = %s, "
101
+ "psm = %s, user = %s, expireTime = %s, "
102
+ "extension = %s }"
103
+ % (
104
+ self.version,
105
+ self.authority,
106
+ self.authority_chain,
107
+ self.primary_auth_type,
108
+ self.psm,
109
+ self.user,
110
+ self.expire_time,
111
+ self.extension,
112
+ )
113
+ )
114
+
115
+ def to_json(self):
116
+ return {
117
+ "version": self.version,
118
+ "authority": self.authority,
119
+ "authorityChain": self.authority_chain or [],
120
+ "primaryAuthType": self.primary_auth_type,
121
+ "psm": self.psm,
122
+ "user": self.user,
123
+ "expireTime": str(self.expire_time),
124
+ "extension": self.extension or {},
125
+ }
126
+
127
+ class SyncInformation(object):
128
+ def __init__(self, token, token_source):
129
+ self.last_sync_time = time.strftime(
130
+ "%Y-%m-%dT%H:%M:%S.000000000%z", time.localtime()
131
+ )
132
+ self.token_source = token_source
133
+ header = jwt.get_unverified_header(token)
134
+ if "kid" not in header:
135
+ self.token_type = "gdpr"
136
+ claims = jwt.decode(token, verify=False, options={"verify_signature": False})
137
+ self.legacy_identity = LegacyIdentity(**claims)
138
+ return
139
+ claim = jwt.decode(
140
+ token,
141
+ options={
142
+ "verify_signature": False,
143
+ "verify_aud": False,
144
+ "verify_exp": False,
145
+ },
146
+ )
147
+ zti = ZeroTrustIdentity().map2identity(claim)
148
+ self.token_type = "zti"
149
+
150
+ self.legacy_identity = zti.get_legacy_identity_from_zti()
151
+ self.key_id = header["kid"]
152
+ self.trust_domain = zti.spiffeID.get_trust_domain()
153
+
154
+ def __str__(self):
155
+ return (
156
+ "{ From str method of SyncInformation: tokenType = %s, "
157
+ " tokenSource = %s, lastSyncTime = %s, keyID = %s, "
158
+ "trustDomain = %s, legacyIdentity = %s }"
159
+ % (
160
+ self.token_type,
161
+ self.token_source,
162
+ self.last_sync_time,
163
+ self.key_id,
164
+ self.trust_domain,
165
+ self.legacy_identity,
166
+ )
167
+ )
168
+
169
+ def to_json(self):
170
+ if self.token_type == "gdpr":
171
+ return {
172
+ "tokenType": self.token_type,
173
+ "tokenSource": self.token_source,
174
+ "lastSyncTime": self.last_sync_time,
175
+ }
176
+ return {
177
+ "tokenType": self.token_type,
178
+ "tokenSource": self.token_source,
179
+ "lastSyncTime": self.last_sync_time,
180
+ "keyID": self.key_id,
181
+ "trustDomain": self.trust_domain,
182
+ "legacyIdentity": self.legacy_identity.to_json(),
183
+ }
miniconda3/envs/ladir/lib/python3.10/site-packages/ztijwthelper/rw_lock.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding: utf-8
2
+
3
+ from __future__ import absolute_import
4
+ from __future__ import division
5
+ from __future__ import print_function
6
+ from __future__ import unicode_literals
7
+ import threading
8
+
9
+
10
+ class RWLock(object):
11
+ def __init__(self):
12
+ self.__monitor = threading.Lock()
13
+ self.__exclude = threading.Lock()
14
+ self.readers = 0
15
+
16
+ def r_lock(self):
17
+ with self.__monitor:
18
+ self.readers += 1
19
+ if self.readers == 1:
20
+ self.__exclude.acquire()
21
+
22
+ def r_un_lock(self):
23
+ with self.__monitor:
24
+ self.readers -= 1
25
+ if self.readers == 0:
26
+ self.__exclude.release()
27
+
28
+ def lock(self):
29
+ self.__exclude.acquire()
30
+
31
+ def un_lock(self):
32
+ self.__exclude.release()
miniconda3/envs/ladir/lib/python3.10/site-packages/ztijwthelper/spiffe_id.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from urllib3.util import url
2
+
3
+
4
+ class ID(object):
5
+ def __init__(self, trust_domain=None, path=None):
6
+ self.trust_domain = trust_domain
7
+ self.path = path
8
+
9
+ def __str__(self):
10
+ return "{ From str method of ID: trust_domain = %s, path = %s }" % (
11
+ self.trust_domain,
12
+ self.path,
13
+ )
14
+
15
+ def from_str(self, id_str):
16
+ uri = url.parse_url(id_str)
17
+ self.trust_domain = str(uri.hostname)
18
+ self.path = str(uri.path).lstrip("/").rstrip("/")
19
+ return self
20
+
21
+ def is_zero(self):
22
+ if not self.trust_domain:
23
+ return True
24
+ return False
25
+
26
+ def to_str(self):
27
+ if self.is_zero():
28
+ return ""
29
+ return self.trust_domain + "/" + self.path
30
+
31
+ def get_trust_domain(self):
32
+ return str(self.trust_domain)
33
+
34
+ def get_path(self):
35
+ return str(self.path)
miniconda3/envs/ladir/lib/python3.10/site-packages/ztijwthelper/zti_jwt_helper.py ADDED
@@ -0,0 +1,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import stat
2
+ import threading
3
+ from .models import ZeroTrustIdentity, LegacyIdentity, SyncInformation
4
+ from .rw_lock import RWLock
5
+ from .exception import ZtiJwtError
6
+ from ztispiffe.spire.api.workload import JWTClientConfig, JWTClient
7
+ from .memfd import Memfd
8
+ from .metric import (
9
+ metrics_client,
10
+ GET_TOKEN_FROM_STRING,
11
+ FETCH_TOKEN_FROM_PATH_FAILED,
12
+ GET_TOKEN_FROM_AGENT_FAIL,
13
+ GET_TOKEN_FAILED,
14
+ GET_TOKEN_SUCCEED,
15
+ GET_TOKEN_FROM_DPS_AGENT_SUCCEED,
16
+ GET_TOKEN_FROM_DPS_AGENT_FAIL,
17
+ )
18
+
19
+ json_lib = True
20
+ try:
21
+ import ujson as json
22
+ except ImportError:
23
+ try:
24
+ import json
25
+ except ImportError:
26
+ try:
27
+ import simplejson as json
28
+ except ImportError:
29
+ json_lib = False
30
+
31
+ import os
32
+ import socket
33
+ import time
34
+ import logging
35
+ import jwt
36
+ import bytedenv
37
+ import six
38
+ from deprecated import deprecated
39
+
40
+ _LOGGER = logging.getLogger(__name__)
41
+ DEFAULT_AGENT_SOCKET_PATH = [
42
+ "/var/run/zti-agent.sock",
43
+ "/var/run/zti-agent/sockets/agent.sock",
44
+ ]
45
+ DEFAULT_TIMEOUT_SECONDS = 5
46
+ SEC_TOKEN_PATH = "SEC_TOKEN_PATH"
47
+ SEC_TOKEN_STRING = "SEC_TOKEN_STRING"
48
+ ZTI_AGENT_SOCKET_PATH = "ZTI_AGENT_SOCKET_PATH"
49
+ METADATA = [("workload.spiffe.io", "true")]
50
+
51
+ # backward compatible with dps agent: need to deprecate in future version
52
+ DPS_AGENT_SOCKET_PATH = "/opt/tmp/sock/.unix_sock_agent_1234567890.sock"
53
+ DPS_AGENT_USER_ENV = "INFSEC_SEC_USER"
54
+ DPS_AGENT_PSM_ENV = "INFSEC_SEC_PSM"
55
+ DPS_AGENT_ENABLE_ENV = "GET_SEC_TOKEN_STRING_FROM_DAEMON"
56
+
57
+ DPS_DEFAULT_TIMEOUT_SECONDS = 1
58
+
59
+ DAEMON_UPDATE_INTERVAL = 2 * 60 * 60
60
+
61
+ TOKEN_SOURCE_STRING = "sec_token_string"
62
+ TOKEN_SOURCE_PATH = "sec_token_path"
63
+ TOKEN_SOURCE_DPS = "dps_agent"
64
+ TOKEN_SOURCE_ZTI = "zti_agent"
65
+
66
+ # Used to determine whether to fallback zti-agent
67
+ FALLBACK_ZTI_AGENT_ENV = "FALLBACK_ZTI_AGENT"
68
+
69
+
70
+ def singleton(cls, *args, **kw):
71
+ instances = {}
72
+
73
+ def _singleton(*args, **kw):
74
+ if cls not in instances:
75
+ instances[cls] = cls(*args, **kw)
76
+ # Allows instance variables to be modified by instantiation
77
+ instances[cls].__dict__.update(kw)
78
+ return instances[cls]
79
+
80
+ return _singleton
81
+
82
+
83
+ def decode_jwt_svid(token_str):
84
+ try:
85
+ claim = jwt.decode(
86
+ token_str,
87
+ options={
88
+ "verify_signature": False,
89
+ "verify_aud": False,
90
+ "verify_exp": False,
91
+ },
92
+ )
93
+ except Exception as e:
94
+ raise ZtiJwtError(e)
95
+
96
+ zti = ZeroTrustIdentity().map2identity(claim)
97
+ return zti
98
+
99
+
100
+ def decode_gdpr_or_jwt_svid(token_str):
101
+ if is_token_zti(token_str):
102
+ zti = decode_jwt_svid(token_str)
103
+ return zti.get_legacy_identity_from_zti()
104
+ else:
105
+ return __decode_gdpr(token_str)
106
+
107
+
108
+ def is_token_zti(token_str):
109
+ try:
110
+ header = jwt.get_unverified_header(token_str)
111
+ except Exception as e:
112
+ return False
113
+ kid = "kid"
114
+ if kid in header:
115
+ return True
116
+ return False
117
+
118
+
119
+ # Trim token string to remove special characters
120
+ def _trim_token(token_str):
121
+ if token_str is None:
122
+ return None
123
+
124
+ if six.PY3:
125
+ return "".join(
126
+ [
127
+ char
128
+ for char in token_str
129
+ if char not in ["\r", "\n", "\t", " ", '"', "'"]
130
+ ]
131
+ )
132
+
133
+ return "".join(
134
+ [filter(lambda char: char not in ["\r", "\n", "\t", " ", '"', "'"], token_str)]
135
+ )
136
+
137
+
138
+ def __decode_gdpr(token_str):
139
+ try:
140
+ claims = jwt.decode(
141
+ token_str, verify=False, options={"verify_signature": False}
142
+ )
143
+ except Exception as e:
144
+ raise ZtiJwtError(e)
145
+ return LegacyIdentity(**claims)
146
+
147
+
148
+ @singleton
149
+ class ZTIJwtHelper(object):
150
+
151
+ def __init__(self, update_interval_secs=180):
152
+ self.lock = RWLock()
153
+ self.thread_lock = threading.Lock()
154
+
155
+ # Global JWT SVID Token
156
+ self._global_token = None
157
+
158
+ self._token_path = None
159
+ self._token_string = None
160
+ self._jwt_client = None
161
+ self._agent_socket_path = None
162
+ self._last_update_time = 0
163
+ self.update_interval_secs = update_interval_secs
164
+
165
+ # backward compatible with dps agent: need to deprecate in future version
166
+ self.dps_agent_enabled = False
167
+ self.dps_agent_infsec_psm = None
168
+ self.dps_agent_infsec_user = None
169
+
170
+ self._service_identity = None
171
+ self._token_source = None
172
+
173
+ self._memfd = Memfd()
174
+
175
+ self._poll_every()
176
+
177
+ def __del__(self):
178
+ try:
179
+ self._memfd.unwrap_memfd()
180
+ self.daemon_thread.cancel()
181
+ except Exception:
182
+ pass
183
+ finally:
184
+ _LOGGER.info("ZTIJwtHelper is deleted")
185
+
186
+ def _run_refresh_once(self):
187
+ self._fresh()
188
+ threading.Timer(DAEMON_UPDATE_INTERVAL, self._run_refresh_once).start()
189
+
190
+ def _poll_every(self):
191
+ self.daemon_thread = threading.Timer(
192
+ DAEMON_UPDATE_INTERVAL, self._run_refresh_once
193
+ )
194
+ self.daemon_thread.daemon = True
195
+ self.daemon_thread.start()
196
+
197
+ def get_jwt_svid(self):
198
+ now = time.time()
199
+ if now - self._last_update_time > self.update_interval_secs:
200
+ self._fresh()
201
+
202
+ return self._get_token()
203
+
204
+ def _refresh_agent_socket_path(self):
205
+ agent_socket_path = os.getenv(ZTI_AGENT_SOCKET_PATH, None)
206
+ if (
207
+ agent_socket_path
208
+ and os.path.exists(agent_socket_path)
209
+ and os.stat(agent_socket_path).st_mode & stat.S_IFSOCK != 0
210
+ ):
211
+ if agent_socket_path != self._agent_socket_path:
212
+ self._set_agent_socket_path(agent_socket_path)
213
+ return
214
+ for path in DEFAULT_AGENT_SOCKET_PATH:
215
+ if os.path.exists(path) and os.stat(path).st_mode & stat.S_IFSOCK != 0:
216
+ if path != self._agent_socket_path:
217
+ self._set_agent_socket_path(path)
218
+ return
219
+
220
+ def _set_agent_socket_path(self, path):
221
+ try:
222
+ self.lock.lock()
223
+ _LOGGER.info("ZTI agent socket path is set to %s", path)
224
+ self._agent_socket_path = path
225
+ self._fresh_jwt_client()
226
+ finally:
227
+ self.lock.un_lock()
228
+
229
+ def get_token_string(self):
230
+ try:
231
+ self.lock.r_lock()
232
+ return (
233
+ self._token_string
234
+ if self._token_string
235
+ else os.getenv(SEC_TOKEN_STRING, None)
236
+ )
237
+ finally:
238
+ self.lock.r_un_lock()
239
+
240
+ def set_token_string(self, token):
241
+ try:
242
+ self.lock.lock()
243
+ self._token_string = token
244
+ finally:
245
+ self.lock.un_lock()
246
+
247
+ def get_token_path(self):
248
+ try:
249
+ self.lock.r_lock()
250
+ return (
251
+ self._token_path
252
+ if self._token_path
253
+ else os.getenv(SEC_TOKEN_PATH, None)
254
+ )
255
+ finally:
256
+ self.lock.r_un_lock()
257
+
258
+ def set_token_path(self, path):
259
+ try:
260
+ self.lock.lock()
261
+ self._token_path = path
262
+ finally:
263
+ self.lock.un_lock()
264
+
265
+ def set_service_identity(self, service_identity):
266
+ try:
267
+ self.lock.lock()
268
+ self._service_identity = service_identity
269
+ finally:
270
+ self.lock.un_lock()
271
+
272
+ def get_service_identity(self):
273
+ try:
274
+ self.lock.r_lock()
275
+ return self._service_identity
276
+ finally:
277
+ self.lock.r_un_lock()
278
+
279
+ def get_token_source(self):
280
+ try:
281
+ self.lock.r_lock()
282
+ return self._token_source
283
+ finally:
284
+ self.lock.r_un_lock()
285
+
286
+ def _fresh_env(self):
287
+ self._token_string = self.get_token_string()
288
+ self._token_path = self.get_token_path()
289
+
290
+ # backward compatible with dps agent: need to deprecate in future version
291
+ self.dps_agent_enabled = os.getenv(DPS_AGENT_ENABLE_ENV, None) == "1"
292
+ self.dps_agent_infsec_psm = os.getenv(DPS_AGENT_PSM_ENV, "")
293
+ self.dps_agent_infsec_user = os.getenv(DPS_AGENT_USER_ENV, "")
294
+
295
+ def _fresh_jwt_client(self):
296
+ config = JWTClientConfig(socket_addr="unix://" + self._agent_socket_path)
297
+ self._jwt_client = JWTClient(config)
298
+
299
+ def _fresh(self):
300
+ try:
301
+ self.thread_lock.acquire()
302
+ # dynamically update the token_path value
303
+ self._fresh_env()
304
+ fall_back_agent = False
305
+ token = None
306
+ if self._token_string:
307
+ self._token_source = TOKEN_SOURCE_STRING
308
+ token = self._token_string
309
+ metrics_client.count(metric_name=GET_TOKEN_FROM_STRING)
310
+ elif self.dps_agent_enabled and (
311
+ self.dps_agent_infsec_psm or self.dps_agent_infsec_user
312
+ ):
313
+ token = self._get_from_dps_agent()
314
+ self._token_source = TOKEN_SOURCE_DPS
315
+ metrics_client.count(metric_name=GET_TOKEN_FROM_DPS_AGENT_SUCCEED)
316
+ elif self._token_path:
317
+ token, fall_back_agent = self._get_from_file()
318
+ self._token_source = TOKEN_SOURCE_PATH
319
+
320
+ if not token or fall_back_agent:
321
+ self._refresh_agent_socket_path()
322
+ if self._agent_socket_path is not None:
323
+ token = self._get_from_agent()
324
+ self._token_source = TOKEN_SOURCE_ZTI
325
+
326
+ if token:
327
+ self._set_token(token)
328
+ self._refresh_identity(token)
329
+ except Exception as ex:
330
+ metrics_client.count(metric_name=GET_TOKEN_FAILED)
331
+ _LOGGER.warning("fresh failed, ex is %s" % ex)
332
+ finally:
333
+ self.thread_lock.release()
334
+
335
+ def _get_from_file(self):
336
+ try:
337
+ self.lock.r_lock()
338
+ # check if token file exists
339
+ if not os.path.exists(self._token_path):
340
+ metrics_client.count(metric_name=FETCH_TOKEN_FROM_PATH_FAILED)
341
+ if self._enable_fall_back():
342
+ return ("", True)
343
+ raise IOError("token file %s not exist" % self._token_path)
344
+
345
+ # check if token file is readable
346
+ if not os.access(self._token_path, os.R_OK):
347
+ metrics_client.count(metric_name=FETCH_TOKEN_FROM_PATH_FAILED)
348
+ if self._enable_fall_back():
349
+ return ("", True)
350
+ raise IOError("token file %s not readable" % self._token_path)
351
+
352
+ with open(self._token_path) as f:
353
+ data = f.read()
354
+ token_string = data.strip()
355
+
356
+ return (
357
+ (token_string, False)
358
+ if not self._enable_fall_back(token_string)
359
+ else ("", True)
360
+ )
361
+
362
+ finally:
363
+ self.lock.r_un_lock()
364
+
365
+ def _get_from_agent(self):
366
+ try:
367
+ serviceIdentity = self.get_service_identity() or bytedenv.get_psm()
368
+ jwt_resp = self._jwt_client.fetch_jwt_svid()
369
+ # we assume one workload should only have one identity
370
+ for ids in jwt_resp.svids:
371
+ # Parse the identity from the JWT SVID
372
+ if (
373
+ serviceIdentity == bytedenv.service.PSM_UNKNOWN
374
+ or serviceIdentity
375
+ == ZeroTrustIdentity()
376
+ .map2identity(
377
+ jwt.decode(
378
+ ids.svid,
379
+ options={
380
+ "verify_signature": False,
381
+ "verify_aud": False,
382
+ "verify_exp": False,
383
+ },
384
+ )
385
+ )
386
+ .id
387
+ ):
388
+ return ids.svid
389
+ return jwt_resp.svids[0].svid if len(jwt_resp.svids) > 0 else None
390
+ except Exception as e:
391
+ metrics_client.count(metric_name=GET_TOKEN_FROM_AGENT_FAIL)
392
+ _LOGGER.error("fail to fetch token from workload api with err: %s" % e)
393
+
394
+ @deprecated(
395
+ reason="backward compatible with dps agent: need to deprecate in future version"
396
+ )
397
+ def _get_from_dps_agent(self):
398
+ if not json_lib:
399
+ _LOGGER.error("none json lib is not installed, please install it")
400
+ return
401
+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
402
+ sock.settimeout(DPS_DEFAULT_TIMEOUT_SECONDS)
403
+ try:
404
+ sock.connect(DPS_AGENT_SOCKET_PATH)
405
+ except socket.error:
406
+ metrics_client.count(metric_name=GET_TOKEN_FROM_DPS_AGENT_FAIL)
407
+ raise ZtiJwtError("fail to connect to unix domain socket!")
408
+
409
+ req = json.dumps(
410
+ {
411
+ "cmd": 1,
412
+ "psm": self.dps_agent_infsec_psm,
413
+ "user": self.dps_agent_infsec_user,
414
+ }
415
+ )
416
+ try:
417
+ sock.sendall(req.encode("utf-8") + b"\n")
418
+ data = sock.recv(2048)
419
+ data = data.decode("utf-8")
420
+ return data.split("\n")[0]
421
+
422
+ except Exception as ex:
423
+ metrics_client.count(metric_name=GET_TOKEN_FROM_DPS_AGENT_FAIL)
424
+ raise ZtiJwtError("get from agent failed, ex is %s", ex)
425
+ finally:
426
+ sock.close()
427
+
428
+ def _set_token(self, token_str):
429
+ try:
430
+ self.lock.lock()
431
+ # Trim JWT Token by removing the special characters
432
+ self._global_token = _trim_token(token_str)
433
+ self._last_update_time = time.time()
434
+ finally:
435
+ self.lock.un_lock()
436
+
437
+ def _get_token(self):
438
+ try:
439
+ self.lock.r_lock()
440
+ token_str = self._global_token
441
+ (
442
+ metrics_client.count(metric_name=GET_TOKEN_FAILED)
443
+ if not token_str
444
+ else metrics_client.count(metric_name=GET_TOKEN_SUCCEED)
445
+ )
446
+
447
+ finally:
448
+ self.lock.r_un_lock()
449
+
450
+ return token_str
451
+
452
+ def _refresh_identity(self, token):
453
+ try:
454
+ self.lock.r_lock()
455
+ self._memfd.write_content_to_memfd(
456
+ json.dumps(
457
+ SyncInformation(token, token_source=self._token_source).to_json()
458
+ ).encode("utf-8")
459
+ )
460
+ except Exception as ex:
461
+ _LOGGER.error("refresh identity failed, ex is %s", ex)
462
+ finally:
463
+ self.lock.r_un_lock()
464
+
465
+ def _enable_fall_back(self, context=None):
466
+ if not context:
467
+ return False
468
+
469
+ if context != FALLBACK_ZTI_AGENT_ENV:
470
+ try:
471
+ jwt.decode(context, verify=False, options={"verify_signature": False})
472
+ return False
473
+ except:
474
+ return os.getenv(FALLBACK_ZTI_AGENT_ENV, "false") == "1"
475
+ return True
476
+
477
+
478
+ jwt_helper = ZTIJwtHelper()
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .error import SpiffeError
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/__version__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ VERSION = (0, 0, 17)
2
+
3
+ __version__ = ".".join(map(str, VERSION))
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/error.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ class SpiffeError(Exception):
2
+ pass
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/proto/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/proto/workload/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .workload_pb2 import *
2
+ from .workload_pb2_grpc import SpiffeWorkloadAPIStub
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/proto/workload/workload_pb2.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
3
+ # source: workload.proto
4
+ # Protobuf Python Version: 4.25.1
5
+ """Generated protocol buffer code."""
6
+ from google.protobuf import descriptor as _descriptor
7
+ from google.protobuf import descriptor_pool as _descriptor_pool
8
+ from google.protobuf import symbol_database as _symbol_database
9
+ from google.protobuf.internal import builder as _builder
10
+ # @@protoc_insertion_point(imports)
11
+
12
+ _sym_db = _symbol_database.Default()
13
+
14
+
15
+ from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2
16
+
17
+
18
+ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0eworkload.proto\x1a\x1cgoogle/protobuf/struct.proto\"\x11\n\x0fX509SVIDRequest\"\xb6\x01\n\x10X509SVIDResponse\x12\x18\n\x05svids\x18\x01 \x03(\x0b\x32\t.X509SVID\x12\x0b\n\x03\x63rl\x18\x02 \x03(\x0c\x12\x42\n\x11\x66\x65\x64\x65rated_bundles\x18\x03 \x03(\x0b\x32\'.X509SVIDResponse.FederatedBundlesEntry\x1a\x37\n\x15\x46\x65\x64\x65ratedBundlesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x0c:\x02\x38\x01\"W\n\x08X509SVID\x12\x11\n\tspiffe_id\x18\x01 \x01(\t\x12\x11\n\tx509_svid\x18\x02 \x01(\x0c\x12\x15\n\rx509_svid_key\x18\x03 \x01(\x0c\x12\x0e\n\x06\x62undle\x18\x04 \x01(\x0c\"\x14\n\x12X509BundlesRequest\"y\n\x13X509BundlesResponse\x12\x32\n\x07\x62undles\x18\x01 \x03(\x0b\x32!.X509BundlesResponse.BundlesEntry\x1a.\n\x0c\x42undlesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x0c:\x02\x38\x01\"*\n\x07JWTSVID\x12\x11\n\tspiffe_id\x18\x01 \x01(\t\x12\x0c\n\x04svid\x18\x02 \x01(\t\"5\n\x0eJWTSVIDRequest\x12\x10\n\x08\x61udience\x18\x01 \x03(\t\x12\x11\n\tspiffe_id\x18\x02 \x01(\t\"*\n\x0fJWTSVIDResponse\x12\x17\n\x05svids\x18\x01 \x03(\x0b\x32\x08.JWTSVID\"\x13\n\x11JWTBundlesRequest\"w\n\x12JWTBundlesResponse\x12\x31\n\x07\x62undles\x18\x01 \x03(\x0b\x32 .JWTBundlesResponse.BundlesEntry\x1a.\n\x0c\x42undlesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x0c:\x02\x38\x01\x32\xfd\x01\n\x11SpiffeWorkloadAPI\x12\x36\n\rFetchX509SVID\x12\x10.X509SVIDRequest\x1a\x11.X509SVIDResponse0\x01\x12?\n\x10\x46\x65tchX509Bundles\x12\x13.X509BundlesRequest\x1a\x14.X509BundlesResponse0\x01\x12\x31\n\x0c\x46\x65tchJWTSVID\x12\x0f.JWTSVIDRequest\x1a\x10.JWTSVIDResponse\x12<\n\x0f\x46\x65tchJWTBundles\x12\x12.JWTBundlesRequest\x1a\x13.JWTBundlesResponse0\x01\x62\x06proto3')
19
+
20
+ _globals = globals()
21
+ _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
22
+ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'workload_pb2', _globals)
23
+ if _descriptor._USE_C_DESCRIPTORS == False:
24
+ DESCRIPTOR._options = None
25
+ _globals['_X509SVIDRESPONSE_FEDERATEDBUNDLESENTRY']._options = None
26
+ _globals['_X509SVIDRESPONSE_FEDERATEDBUNDLESENTRY']._serialized_options = b'8\001'
27
+ _globals['_X509BUNDLESRESPONSE_BUNDLESENTRY']._options = None
28
+ _globals['_X509BUNDLESRESPONSE_BUNDLESENTRY']._serialized_options = b'8\001'
29
+ _globals['_JWTBUNDLESRESPONSE_BUNDLESENTRY']._options = None
30
+ _globals['_JWTBUNDLESRESPONSE_BUNDLESENTRY']._serialized_options = b'8\001'
31
+ _globals['_X509SVIDREQUEST']._serialized_start=48
32
+ _globals['_X509SVIDREQUEST']._serialized_end=65
33
+ _globals['_X509SVIDRESPONSE']._serialized_start=68
34
+ _globals['_X509SVIDRESPONSE']._serialized_end=250
35
+ _globals['_X509SVIDRESPONSE_FEDERATEDBUNDLESENTRY']._serialized_start=195
36
+ _globals['_X509SVIDRESPONSE_FEDERATEDBUNDLESENTRY']._serialized_end=250
37
+ _globals['_X509SVID']._serialized_start=252
38
+ _globals['_X509SVID']._serialized_end=339
39
+ _globals['_X509BUNDLESREQUEST']._serialized_start=341
40
+ _globals['_X509BUNDLESREQUEST']._serialized_end=361
41
+ _globals['_X509BUNDLESRESPONSE']._serialized_start=363
42
+ _globals['_X509BUNDLESRESPONSE']._serialized_end=484
43
+ _globals['_X509BUNDLESRESPONSE_BUNDLESENTRY']._serialized_start=438
44
+ _globals['_X509BUNDLESRESPONSE_BUNDLESENTRY']._serialized_end=484
45
+ _globals['_JWTSVID']._serialized_start=486
46
+ _globals['_JWTSVID']._serialized_end=528
47
+ _globals['_JWTSVIDREQUEST']._serialized_start=530
48
+ _globals['_JWTSVIDREQUEST']._serialized_end=583
49
+ _globals['_JWTSVIDRESPONSE']._serialized_start=585
50
+ _globals['_JWTSVIDRESPONSE']._serialized_end=627
51
+ _globals['_JWTBUNDLESREQUEST']._serialized_start=629
52
+ _globals['_JWTBUNDLESREQUEST']._serialized_end=648
53
+ _globals['_JWTBUNDLESRESPONSE']._serialized_start=650
54
+ _globals['_JWTBUNDLESRESPONSE']._serialized_end=769
55
+ _globals['_JWTBUNDLESRESPONSE_BUNDLESENTRY']._serialized_start=438
56
+ _globals['_JWTBUNDLESRESPONSE_BUNDLESENTRY']._serialized_end=484
57
+ _globals['_SPIFFEWORKLOADAPI']._serialized_start=772
58
+ _globals['_SPIFFEWORKLOADAPI']._serialized_end=1025
59
+ # @@protoc_insertion_point(module_scope)
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/proto/workload/workload_pb2_grpc.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
2
+ """Client and server classes corresponding to protobuf-defined services."""
3
+ import grpc
4
+
5
+ from . import workload_pb2 as workload__pb2
6
+
7
+
8
+ class SpiffeWorkloadAPIStub(object):
9
+ """Missing associated documentation comment in .proto file."""
10
+
11
+ def __init__(self, channel):
12
+ """Constructor.
13
+
14
+ Args:
15
+ channel: A grpc.Channel.
16
+ """
17
+ self.FetchX509SVID = channel.unary_stream(
18
+ '/SpiffeWorkloadAPI/FetchX509SVID',
19
+ request_serializer=workload__pb2.X509SVIDRequest.SerializeToString,
20
+ response_deserializer=workload__pb2.X509SVIDResponse.FromString,
21
+ )
22
+ self.FetchX509Bundles = channel.unary_stream(
23
+ '/SpiffeWorkloadAPI/FetchX509Bundles',
24
+ request_serializer=workload__pb2.X509BundlesRequest.SerializeToString,
25
+ response_deserializer=workload__pb2.X509BundlesResponse.FromString,
26
+ )
27
+ self.FetchJWTSVID = channel.unary_unary(
28
+ '/SpiffeWorkloadAPI/FetchJWTSVID',
29
+ request_serializer=workload__pb2.JWTSVIDRequest.SerializeToString,
30
+ response_deserializer=workload__pb2.JWTSVIDResponse.FromString,
31
+ )
32
+ self.FetchJWTBundles = channel.unary_stream(
33
+ '/SpiffeWorkloadAPI/FetchJWTBundles',
34
+ request_serializer=workload__pb2.JWTBundlesRequest.SerializeToString,
35
+ response_deserializer=workload__pb2.JWTBundlesResponse.FromString,
36
+ )
37
+
38
+
39
+ class SpiffeWorkloadAPIServicer(object):
40
+ """Missing associated documentation comment in .proto file."""
41
+
42
+ def FetchX509SVID(self, request, context):
43
+ """X.509-SVID Profile
44
+ Fetch all SPIFFE identities the workload is entitled to, as
45
+ well as related information like trust bundles and CRLs. As
46
+ this information changes, subsequent messages will be sent.
47
+ """
48
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
49
+ context.set_details('Method not implemented!')
50
+ raise NotImplementedError('Method not implemented!')
51
+
52
+ def FetchX509Bundles(self, request, context):
53
+ """Missing associated documentation comment in .proto file."""
54
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
55
+ context.set_details('Method not implemented!')
56
+ raise NotImplementedError('Method not implemented!')
57
+
58
+ def FetchJWTSVID(self, request, context):
59
+ """JWT-SVID Profile
60
+ """
61
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
62
+ context.set_details('Method not implemented!')
63
+ raise NotImplementedError('Method not implemented!')
64
+
65
+ def FetchJWTBundles(self, request, context):
66
+ """Missing associated documentation comment in .proto file."""
67
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
68
+ context.set_details('Method not implemented!')
69
+ raise NotImplementedError('Method not implemented!')
70
+
71
+
72
+ def add_SpiffeWorkloadAPIServicer_to_server(servicer, server):
73
+ rpc_method_handlers = {
74
+ 'FetchX509SVID': grpc.unary_stream_rpc_method_handler(
75
+ servicer.FetchX509SVID,
76
+ request_deserializer=workload__pb2.X509SVIDRequest.FromString,
77
+ response_serializer=workload__pb2.X509SVIDResponse.SerializeToString,
78
+ ),
79
+ 'FetchX509Bundles': grpc.unary_stream_rpc_method_handler(
80
+ servicer.FetchX509Bundles,
81
+ request_deserializer=workload__pb2.X509BundlesRequest.FromString,
82
+ response_serializer=workload__pb2.X509BundlesResponse.SerializeToString,
83
+ ),
84
+ 'FetchJWTSVID': grpc.unary_unary_rpc_method_handler(
85
+ servicer.FetchJWTSVID,
86
+ request_deserializer=workload__pb2.JWTSVIDRequest.FromString,
87
+ response_serializer=workload__pb2.JWTSVIDResponse.SerializeToString,
88
+ ),
89
+ 'FetchJWTBundles': grpc.unary_stream_rpc_method_handler(
90
+ servicer.FetchJWTBundles,
91
+ request_deserializer=workload__pb2.JWTBundlesRequest.FromString,
92
+ response_serializer=workload__pb2.JWTBundlesResponse.SerializeToString,
93
+ ),
94
+ }
95
+ generic_handler = grpc.method_handlers_generic_handler(
96
+ 'SpiffeWorkloadAPI', rpc_method_handlers)
97
+ server.add_generic_rpc_handlers((generic_handler,))
98
+
99
+
100
+ # This class is part of an EXPERIMENTAL API.
101
+ class SpiffeWorkloadAPI(object):
102
+ """Missing associated documentation comment in .proto file."""
103
+
104
+ @staticmethod
105
+ def FetchX509SVID(request,
106
+ target,
107
+ options=(),
108
+ channel_credentials=None,
109
+ call_credentials=None,
110
+ insecure=False,
111
+ compression=None,
112
+ wait_for_ready=None,
113
+ timeout=None,
114
+ metadata=None):
115
+ return grpc.experimental.unary_stream(request, target, '/SpiffeWorkloadAPI/FetchX509SVID',
116
+ workload__pb2.X509SVIDRequest.SerializeToString,
117
+ workload__pb2.X509SVIDResponse.FromString,
118
+ options, channel_credentials,
119
+ insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
120
+
121
+ @staticmethod
122
+ def FetchX509Bundles(request,
123
+ target,
124
+ options=(),
125
+ channel_credentials=None,
126
+ call_credentials=None,
127
+ insecure=False,
128
+ compression=None,
129
+ wait_for_ready=None,
130
+ timeout=None,
131
+ metadata=None):
132
+ return grpc.experimental.unary_stream(request, target, '/SpiffeWorkloadAPI/FetchX509Bundles',
133
+ workload__pb2.X509BundlesRequest.SerializeToString,
134
+ workload__pb2.X509BundlesResponse.FromString,
135
+ options, channel_credentials,
136
+ insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
137
+
138
+ @staticmethod
139
+ def FetchJWTSVID(request,
140
+ target,
141
+ options=(),
142
+ channel_credentials=None,
143
+ call_credentials=None,
144
+ insecure=False,
145
+ compression=None,
146
+ wait_for_ready=None,
147
+ timeout=None,
148
+ metadata=None):
149
+ return grpc.experimental.unary_unary(request, target, '/SpiffeWorkloadAPI/FetchJWTSVID',
150
+ workload__pb2.JWTSVIDRequest.SerializeToString,
151
+ workload__pb2.JWTSVIDResponse.FromString,
152
+ options, channel_credentials,
153
+ insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
154
+
155
+ @staticmethod
156
+ def FetchJWTBundles(request,
157
+ target,
158
+ options=(),
159
+ channel_credentials=None,
160
+ call_credentials=None,
161
+ insecure=False,
162
+ compression=None,
163
+ wait_for_ready=None,
164
+ timeout=None,
165
+ metadata=None):
166
+ return grpc.experimental.unary_stream(request, target, '/SpiffeWorkloadAPI/FetchJWTBundles',
167
+ workload__pb2.JWTBundlesRequest.SerializeToString,
168
+ workload__pb2.JWTBundlesResponse.FromString,
169
+ options, channel_credentials,
170
+ insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/proto/workload_py2/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .workload_pb2 import *
2
+ from .workload_pb2_grpc import SpiffeWorkloadAPIStub
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/proto/workload_py2/workload_pb2.py ADDED
@@ -0,0 +1,665 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
3
+ # source: workload.proto
4
+ """Generated protocol buffer code."""
5
+ from google.protobuf import descriptor as _descriptor
6
+ from google.protobuf import message as _message
7
+ from google.protobuf import reflection as _reflection
8
+ from google.protobuf import symbol_database as _symbol_database
9
+ # @@protoc_insertion_point(imports)
10
+
11
+ _sym_db = _symbol_database.Default()
12
+
13
+
14
+ from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2
15
+
16
+
17
+ DESCRIPTOR = _descriptor.FileDescriptor(
18
+ name='workload.proto',
19
+ package='',
20
+ syntax='proto3',
21
+ serialized_options=None,
22
+ create_key=_descriptor._internal_create_key,
23
+ serialized_pb=b'\n\x0eworkload.proto\x1a\x1cgoogle/protobuf/struct.proto\"\x11\n\x0fX509SVIDRequest\"\xb6\x01\n\x10X509SVIDResponse\x12\x18\n\x05svids\x18\x01 \x03(\x0b\x32\t.X509SVID\x12\x0b\n\x03\x63rl\x18\x02 \x03(\x0c\x12\x42\n\x11\x66\x65\x64\x65rated_bundles\x18\x03 \x03(\x0b\x32\'.X509SVIDResponse.FederatedBundlesEntry\x1a\x37\n\x15\x46\x65\x64\x65ratedBundlesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x0c:\x02\x38\x01\"W\n\x08X509SVID\x12\x11\n\tspiffe_id\x18\x01 \x01(\t\x12\x11\n\tx509_svid\x18\x02 \x01(\x0c\x12\x15\n\rx509_svid_key\x18\x03 \x01(\x0c\x12\x0e\n\x06\x62undle\x18\x04 \x01(\x0c\"\x14\n\x12X509BundlesRequest\"y\n\x13X509BundlesResponse\x12\x32\n\x07\x62undles\x18\x01 \x03(\x0b\x32!.X509BundlesResponse.BundlesEntry\x1a.\n\x0c\x42undlesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x0c:\x02\x38\x01\"*\n\x07JWTSVID\x12\x11\n\tspiffe_id\x18\x01 \x01(\t\x12\x0c\n\x04svid\x18\x02 \x01(\t\"5\n\x0eJWTSVIDRequest\x12\x10\n\x08\x61udience\x18\x01 \x03(\t\x12\x11\n\tspiffe_id\x18\x02 \x01(\t\"*\n\x0fJWTSVIDResponse\x12\x17\n\x05svids\x18\x01 \x03(\x0b\x32\x08.JWTSVID\"\x13\n\x11JWTBundlesRequest\"w\n\x12JWTBundlesResponse\x12\x31\n\x07\x62undles\x18\x01 \x03(\x0b\x32 .JWTBundlesResponse.BundlesEntry\x1a.\n\x0c\x42undlesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x0c:\x02\x38\x01\x32\xfd\x01\n\x11SpiffeWorkloadAPI\x12\x36\n\rFetchX509SVID\x12\x10.X509SVIDRequest\x1a\x11.X509SVIDResponse0\x01\x12?\n\x10\x46\x65tchX509Bundles\x12\x13.X509BundlesRequest\x1a\x14.X509BundlesResponse0\x01\x12\x31\n\x0c\x46\x65tchJWTSVID\x12\x0f.JWTSVIDRequest\x1a\x10.JWTSVIDResponse\x12<\n\x0f\x46\x65tchJWTBundles\x12\x12.JWTBundlesRequest\x1a\x13.JWTBundlesResponse0\x01\x62\x06proto3'
24
+ ,
25
+ dependencies=[google_dot_protobuf_dot_struct__pb2.DESCRIPTOR,])
26
+
27
+
28
+
29
+
30
+ _X509SVIDREQUEST = _descriptor.Descriptor(
31
+ name='X509SVIDRequest',
32
+ full_name='X509SVIDRequest',
33
+ filename=None,
34
+ file=DESCRIPTOR,
35
+ containing_type=None,
36
+ create_key=_descriptor._internal_create_key,
37
+ fields=[
38
+ ],
39
+ extensions=[
40
+ ],
41
+ nested_types=[],
42
+ enum_types=[
43
+ ],
44
+ serialized_options=None,
45
+ is_extendable=False,
46
+ syntax='proto3',
47
+ extension_ranges=[],
48
+ oneofs=[
49
+ ],
50
+ serialized_start=48,
51
+ serialized_end=65,
52
+ )
53
+
54
+
55
+ _X509SVIDRESPONSE_FEDERATEDBUNDLESENTRY = _descriptor.Descriptor(
56
+ name='FederatedBundlesEntry',
57
+ full_name='X509SVIDResponse.FederatedBundlesEntry',
58
+ filename=None,
59
+ file=DESCRIPTOR,
60
+ containing_type=None,
61
+ create_key=_descriptor._internal_create_key,
62
+ fields=[
63
+ _descriptor.FieldDescriptor(
64
+ name='key', full_name='X509SVIDResponse.FederatedBundlesEntry.key', index=0,
65
+ number=1, type=9, cpp_type=9, label=1,
66
+ has_default_value=False, default_value=b"".decode('utf-8'),
67
+ message_type=None, enum_type=None, containing_type=None,
68
+ is_extension=False, extension_scope=None,
69
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
70
+ _descriptor.FieldDescriptor(
71
+ name='value', full_name='X509SVIDResponse.FederatedBundlesEntry.value', index=1,
72
+ number=2, type=12, cpp_type=9, label=1,
73
+ has_default_value=False, default_value=b"",
74
+ message_type=None, enum_type=None, containing_type=None,
75
+ is_extension=False, extension_scope=None,
76
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
77
+ ],
78
+ extensions=[
79
+ ],
80
+ nested_types=[],
81
+ enum_types=[
82
+ ],
83
+ serialized_options=b'8\001',
84
+ is_extendable=False,
85
+ syntax='proto3',
86
+ extension_ranges=[],
87
+ oneofs=[
88
+ ],
89
+ serialized_start=195,
90
+ serialized_end=250,
91
+ )
92
+
93
+ _X509SVIDRESPONSE = _descriptor.Descriptor(
94
+ name='X509SVIDResponse',
95
+ full_name='X509SVIDResponse',
96
+ filename=None,
97
+ file=DESCRIPTOR,
98
+ containing_type=None,
99
+ create_key=_descriptor._internal_create_key,
100
+ fields=[
101
+ _descriptor.FieldDescriptor(
102
+ name='svids', full_name='X509SVIDResponse.svids', index=0,
103
+ number=1, type=11, cpp_type=10, label=3,
104
+ has_default_value=False, default_value=[],
105
+ message_type=None, enum_type=None, containing_type=None,
106
+ is_extension=False, extension_scope=None,
107
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
108
+ _descriptor.FieldDescriptor(
109
+ name='crl', full_name='X509SVIDResponse.crl', index=1,
110
+ number=2, type=12, cpp_type=9, label=3,
111
+ has_default_value=False, default_value=[],
112
+ message_type=None, enum_type=None, containing_type=None,
113
+ is_extension=False, extension_scope=None,
114
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
115
+ _descriptor.FieldDescriptor(
116
+ name='federated_bundles', full_name='X509SVIDResponse.federated_bundles', index=2,
117
+ number=3, type=11, cpp_type=10, label=3,
118
+ has_default_value=False, default_value=[],
119
+ message_type=None, enum_type=None, containing_type=None,
120
+ is_extension=False, extension_scope=None,
121
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
122
+ ],
123
+ extensions=[
124
+ ],
125
+ nested_types=[_X509SVIDRESPONSE_FEDERATEDBUNDLESENTRY, ],
126
+ enum_types=[
127
+ ],
128
+ serialized_options=None,
129
+ is_extendable=False,
130
+ syntax='proto3',
131
+ extension_ranges=[],
132
+ oneofs=[
133
+ ],
134
+ serialized_start=68,
135
+ serialized_end=250,
136
+ )
137
+
138
+
139
+ _X509SVID = _descriptor.Descriptor(
140
+ name='X509SVID',
141
+ full_name='X509SVID',
142
+ filename=None,
143
+ file=DESCRIPTOR,
144
+ containing_type=None,
145
+ create_key=_descriptor._internal_create_key,
146
+ fields=[
147
+ _descriptor.FieldDescriptor(
148
+ name='spiffe_id', full_name='X509SVID.spiffe_id', index=0,
149
+ number=1, type=9, cpp_type=9, label=1,
150
+ has_default_value=False, default_value=b"".decode('utf-8'),
151
+ message_type=None, enum_type=None, containing_type=None,
152
+ is_extension=False, extension_scope=None,
153
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
154
+ _descriptor.FieldDescriptor(
155
+ name='x509_svid', full_name='X509SVID.x509_svid', index=1,
156
+ number=2, type=12, cpp_type=9, label=1,
157
+ has_default_value=False, default_value=b"",
158
+ message_type=None, enum_type=None, containing_type=None,
159
+ is_extension=False, extension_scope=None,
160
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
161
+ _descriptor.FieldDescriptor(
162
+ name='x509_svid_key', full_name='X509SVID.x509_svid_key', index=2,
163
+ number=3, type=12, cpp_type=9, label=1,
164
+ has_default_value=False, default_value=b"",
165
+ message_type=None, enum_type=None, containing_type=None,
166
+ is_extension=False, extension_scope=None,
167
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
168
+ _descriptor.FieldDescriptor(
169
+ name='bundle', full_name='X509SVID.bundle', index=3,
170
+ number=4, type=12, cpp_type=9, label=1,
171
+ has_default_value=False, default_value=b"",
172
+ message_type=None, enum_type=None, containing_type=None,
173
+ is_extension=False, extension_scope=None,
174
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
175
+ ],
176
+ extensions=[
177
+ ],
178
+ nested_types=[],
179
+ enum_types=[
180
+ ],
181
+ serialized_options=None,
182
+ is_extendable=False,
183
+ syntax='proto3',
184
+ extension_ranges=[],
185
+ oneofs=[
186
+ ],
187
+ serialized_start=252,
188
+ serialized_end=339,
189
+ )
190
+
191
+
192
+ _X509BUNDLESREQUEST = _descriptor.Descriptor(
193
+ name='X509BundlesRequest',
194
+ full_name='X509BundlesRequest',
195
+ filename=None,
196
+ file=DESCRIPTOR,
197
+ containing_type=None,
198
+ create_key=_descriptor._internal_create_key,
199
+ fields=[
200
+ ],
201
+ extensions=[
202
+ ],
203
+ nested_types=[],
204
+ enum_types=[
205
+ ],
206
+ serialized_options=None,
207
+ is_extendable=False,
208
+ syntax='proto3',
209
+ extension_ranges=[],
210
+ oneofs=[
211
+ ],
212
+ serialized_start=341,
213
+ serialized_end=361,
214
+ )
215
+
216
+
217
+ _X509BUNDLESRESPONSE_BUNDLESENTRY = _descriptor.Descriptor(
218
+ name='BundlesEntry',
219
+ full_name='X509BundlesResponse.BundlesEntry',
220
+ filename=None,
221
+ file=DESCRIPTOR,
222
+ containing_type=None,
223
+ create_key=_descriptor._internal_create_key,
224
+ fields=[
225
+ _descriptor.FieldDescriptor(
226
+ name='key', full_name='X509BundlesResponse.BundlesEntry.key', index=0,
227
+ number=1, type=9, cpp_type=9, label=1,
228
+ has_default_value=False, default_value=b"".decode('utf-8'),
229
+ message_type=None, enum_type=None, containing_type=None,
230
+ is_extension=False, extension_scope=None,
231
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
232
+ _descriptor.FieldDescriptor(
233
+ name='value', full_name='X509BundlesResponse.BundlesEntry.value', index=1,
234
+ number=2, type=12, cpp_type=9, label=1,
235
+ has_default_value=False, default_value=b"",
236
+ message_type=None, enum_type=None, containing_type=None,
237
+ is_extension=False, extension_scope=None,
238
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
239
+ ],
240
+ extensions=[
241
+ ],
242
+ nested_types=[],
243
+ enum_types=[
244
+ ],
245
+ serialized_options=b'8\001',
246
+ is_extendable=False,
247
+ syntax='proto3',
248
+ extension_ranges=[],
249
+ oneofs=[
250
+ ],
251
+ serialized_start=438,
252
+ serialized_end=484,
253
+ )
254
+
255
+ _X509BUNDLESRESPONSE = _descriptor.Descriptor(
256
+ name='X509BundlesResponse',
257
+ full_name='X509BundlesResponse',
258
+ filename=None,
259
+ file=DESCRIPTOR,
260
+ containing_type=None,
261
+ create_key=_descriptor._internal_create_key,
262
+ fields=[
263
+ _descriptor.FieldDescriptor(
264
+ name='bundles', full_name='X509BundlesResponse.bundles', index=0,
265
+ number=1, type=11, cpp_type=10, label=3,
266
+ has_default_value=False, default_value=[],
267
+ message_type=None, enum_type=None, containing_type=None,
268
+ is_extension=False, extension_scope=None,
269
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
270
+ ],
271
+ extensions=[
272
+ ],
273
+ nested_types=[_X509BUNDLESRESPONSE_BUNDLESENTRY, ],
274
+ enum_types=[
275
+ ],
276
+ serialized_options=None,
277
+ is_extendable=False,
278
+ syntax='proto3',
279
+ extension_ranges=[],
280
+ oneofs=[
281
+ ],
282
+ serialized_start=363,
283
+ serialized_end=484,
284
+ )
285
+
286
+
287
+ _JWTSVID = _descriptor.Descriptor(
288
+ name='JWTSVID',
289
+ full_name='JWTSVID',
290
+ filename=None,
291
+ file=DESCRIPTOR,
292
+ containing_type=None,
293
+ create_key=_descriptor._internal_create_key,
294
+ fields=[
295
+ _descriptor.FieldDescriptor(
296
+ name='spiffe_id', full_name='JWTSVID.spiffe_id', index=0,
297
+ number=1, type=9, cpp_type=9, label=1,
298
+ has_default_value=False, default_value=b"".decode('utf-8'),
299
+ message_type=None, enum_type=None, containing_type=None,
300
+ is_extension=False, extension_scope=None,
301
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
302
+ _descriptor.FieldDescriptor(
303
+ name='svid', full_name='JWTSVID.svid', index=1,
304
+ number=2, type=9, cpp_type=9, label=1,
305
+ has_default_value=False, default_value=b"".decode('utf-8'),
306
+ message_type=None, enum_type=None, containing_type=None,
307
+ is_extension=False, extension_scope=None,
308
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
309
+ ],
310
+ extensions=[
311
+ ],
312
+ nested_types=[],
313
+ enum_types=[
314
+ ],
315
+ serialized_options=None,
316
+ is_extendable=False,
317
+ syntax='proto3',
318
+ extension_ranges=[],
319
+ oneofs=[
320
+ ],
321
+ serialized_start=486,
322
+ serialized_end=528,
323
+ )
324
+
325
+
326
+ _JWTSVIDREQUEST = _descriptor.Descriptor(
327
+ name='JWTSVIDRequest',
328
+ full_name='JWTSVIDRequest',
329
+ filename=None,
330
+ file=DESCRIPTOR,
331
+ containing_type=None,
332
+ create_key=_descriptor._internal_create_key,
333
+ fields=[
334
+ _descriptor.FieldDescriptor(
335
+ name='audience', full_name='JWTSVIDRequest.audience', index=0,
336
+ number=1, type=9, cpp_type=9, label=3,
337
+ has_default_value=False, default_value=[],
338
+ message_type=None, enum_type=None, containing_type=None,
339
+ is_extension=False, extension_scope=None,
340
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
341
+ _descriptor.FieldDescriptor(
342
+ name='spiffe_id', full_name='JWTSVIDRequest.spiffe_id', index=1,
343
+ number=2, type=9, cpp_type=9, label=1,
344
+ has_default_value=False, default_value=b"".decode('utf-8'),
345
+ message_type=None, enum_type=None, containing_type=None,
346
+ is_extension=False, extension_scope=None,
347
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
348
+ ],
349
+ extensions=[
350
+ ],
351
+ nested_types=[],
352
+ enum_types=[
353
+ ],
354
+ serialized_options=None,
355
+ is_extendable=False,
356
+ syntax='proto3',
357
+ extension_ranges=[],
358
+ oneofs=[
359
+ ],
360
+ serialized_start=530,
361
+ serialized_end=583,
362
+ )
363
+
364
+
365
+ _JWTSVIDRESPONSE = _descriptor.Descriptor(
366
+ name='JWTSVIDResponse',
367
+ full_name='JWTSVIDResponse',
368
+ filename=None,
369
+ file=DESCRIPTOR,
370
+ containing_type=None,
371
+ create_key=_descriptor._internal_create_key,
372
+ fields=[
373
+ _descriptor.FieldDescriptor(
374
+ name='svids', full_name='JWTSVIDResponse.svids', index=0,
375
+ number=1, type=11, cpp_type=10, label=3,
376
+ has_default_value=False, default_value=[],
377
+ message_type=None, enum_type=None, containing_type=None,
378
+ is_extension=False, extension_scope=None,
379
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
380
+ ],
381
+ extensions=[
382
+ ],
383
+ nested_types=[],
384
+ enum_types=[
385
+ ],
386
+ serialized_options=None,
387
+ is_extendable=False,
388
+ syntax='proto3',
389
+ extension_ranges=[],
390
+ oneofs=[
391
+ ],
392
+ serialized_start=585,
393
+ serialized_end=627,
394
+ )
395
+
396
+
397
+ _JWTBUNDLESREQUEST = _descriptor.Descriptor(
398
+ name='JWTBundlesRequest',
399
+ full_name='JWTBundlesRequest',
400
+ filename=None,
401
+ file=DESCRIPTOR,
402
+ containing_type=None,
403
+ create_key=_descriptor._internal_create_key,
404
+ fields=[
405
+ ],
406
+ extensions=[
407
+ ],
408
+ nested_types=[],
409
+ enum_types=[
410
+ ],
411
+ serialized_options=None,
412
+ is_extendable=False,
413
+ syntax='proto3',
414
+ extension_ranges=[],
415
+ oneofs=[
416
+ ],
417
+ serialized_start=629,
418
+ serialized_end=648,
419
+ )
420
+
421
+
422
+ _JWTBUNDLESRESPONSE_BUNDLESENTRY = _descriptor.Descriptor(
423
+ name='BundlesEntry',
424
+ full_name='JWTBundlesResponse.BundlesEntry',
425
+ filename=None,
426
+ file=DESCRIPTOR,
427
+ containing_type=None,
428
+ create_key=_descriptor._internal_create_key,
429
+ fields=[
430
+ _descriptor.FieldDescriptor(
431
+ name='key', full_name='JWTBundlesResponse.BundlesEntry.key', index=0,
432
+ number=1, type=9, cpp_type=9, label=1,
433
+ has_default_value=False, default_value=b"".decode('utf-8'),
434
+ message_type=None, enum_type=None, containing_type=None,
435
+ is_extension=False, extension_scope=None,
436
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
437
+ _descriptor.FieldDescriptor(
438
+ name='value', full_name='JWTBundlesResponse.BundlesEntry.value', index=1,
439
+ number=2, type=12, cpp_type=9, label=1,
440
+ has_default_value=False, default_value=b"",
441
+ message_type=None, enum_type=None, containing_type=None,
442
+ is_extension=False, extension_scope=None,
443
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
444
+ ],
445
+ extensions=[
446
+ ],
447
+ nested_types=[],
448
+ enum_types=[
449
+ ],
450
+ serialized_options=b'8\001',
451
+ is_extendable=False,
452
+ syntax='proto3',
453
+ extension_ranges=[],
454
+ oneofs=[
455
+ ],
456
+ serialized_start=438,
457
+ serialized_end=484,
458
+ )
459
+
460
+ _JWTBUNDLESRESPONSE = _descriptor.Descriptor(
461
+ name='JWTBundlesResponse',
462
+ full_name='JWTBundlesResponse',
463
+ filename=None,
464
+ file=DESCRIPTOR,
465
+ containing_type=None,
466
+ create_key=_descriptor._internal_create_key,
467
+ fields=[
468
+ _descriptor.FieldDescriptor(
469
+ name='bundles', full_name='JWTBundlesResponse.bundles', index=0,
470
+ number=1, type=11, cpp_type=10, label=3,
471
+ has_default_value=False, default_value=[],
472
+ message_type=None, enum_type=None, containing_type=None,
473
+ is_extension=False, extension_scope=None,
474
+ serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
475
+ ],
476
+ extensions=[
477
+ ],
478
+ nested_types=[_JWTBUNDLESRESPONSE_BUNDLESENTRY, ],
479
+ enum_types=[
480
+ ],
481
+ serialized_options=None,
482
+ is_extendable=False,
483
+ syntax='proto3',
484
+ extension_ranges=[],
485
+ oneofs=[
486
+ ],
487
+ serialized_start=650,
488
+ serialized_end=769,
489
+ )
490
+
491
+ _X509SVIDRESPONSE_FEDERATEDBUNDLESENTRY.containing_type = _X509SVIDRESPONSE
492
+ _X509SVIDRESPONSE.fields_by_name['svids'].message_type = _X509SVID
493
+ _X509SVIDRESPONSE.fields_by_name['federated_bundles'].message_type = _X509SVIDRESPONSE_FEDERATEDBUNDLESENTRY
494
+ _X509BUNDLESRESPONSE_BUNDLESENTRY.containing_type = _X509BUNDLESRESPONSE
495
+ _X509BUNDLESRESPONSE.fields_by_name['bundles'].message_type = _X509BUNDLESRESPONSE_BUNDLESENTRY
496
+ _JWTSVIDRESPONSE.fields_by_name['svids'].message_type = _JWTSVID
497
+ _JWTBUNDLESRESPONSE_BUNDLESENTRY.containing_type = _JWTBUNDLESRESPONSE
498
+ _JWTBUNDLESRESPONSE.fields_by_name['bundles'].message_type = _JWTBUNDLESRESPONSE_BUNDLESENTRY
499
+ DESCRIPTOR.message_types_by_name['X509SVIDRequest'] = _X509SVIDREQUEST
500
+ DESCRIPTOR.message_types_by_name['X509SVIDResponse'] = _X509SVIDRESPONSE
501
+ DESCRIPTOR.message_types_by_name['X509SVID'] = _X509SVID
502
+ DESCRIPTOR.message_types_by_name['X509BundlesRequest'] = _X509BUNDLESREQUEST
503
+ DESCRIPTOR.message_types_by_name['X509BundlesResponse'] = _X509BUNDLESRESPONSE
504
+ DESCRIPTOR.message_types_by_name['JWTSVID'] = _JWTSVID
505
+ DESCRIPTOR.message_types_by_name['JWTSVIDRequest'] = _JWTSVIDREQUEST
506
+ DESCRIPTOR.message_types_by_name['JWTSVIDResponse'] = _JWTSVIDRESPONSE
507
+ DESCRIPTOR.message_types_by_name['JWTBundlesRequest'] = _JWTBUNDLESREQUEST
508
+ DESCRIPTOR.message_types_by_name['JWTBundlesResponse'] = _JWTBUNDLESRESPONSE
509
+ _sym_db.RegisterFileDescriptor(DESCRIPTOR)
510
+
511
+ X509SVIDRequest = _reflection.GeneratedProtocolMessageType('X509SVIDRequest', (_message.Message,), {
512
+ 'DESCRIPTOR' : _X509SVIDREQUEST,
513
+ '__module__' : 'workload_pb2'
514
+ # @@protoc_insertion_point(class_scope:X509SVIDRequest)
515
+ })
516
+ _sym_db.RegisterMessage(X509SVIDRequest)
517
+
518
+ X509SVIDResponse = _reflection.GeneratedProtocolMessageType('X509SVIDResponse', (_message.Message,), {
519
+
520
+ 'FederatedBundlesEntry' : _reflection.GeneratedProtocolMessageType('FederatedBundlesEntry', (_message.Message,), {
521
+ 'DESCRIPTOR' : _X509SVIDRESPONSE_FEDERATEDBUNDLESENTRY,
522
+ '__module__' : 'workload_pb2'
523
+ # @@protoc_insertion_point(class_scope:X509SVIDResponse.FederatedBundlesEntry)
524
+ })
525
+ ,
526
+ 'DESCRIPTOR' : _X509SVIDRESPONSE,
527
+ '__module__' : 'workload_pb2'
528
+ # @@protoc_insertion_point(class_scope:X509SVIDResponse)
529
+ })
530
+ _sym_db.RegisterMessage(X509SVIDResponse)
531
+ _sym_db.RegisterMessage(X509SVIDResponse.FederatedBundlesEntry)
532
+
533
+ X509SVID = _reflection.GeneratedProtocolMessageType('X509SVID', (_message.Message,), {
534
+ 'DESCRIPTOR' : _X509SVID,
535
+ '__module__' : 'workload_pb2'
536
+ # @@protoc_insertion_point(class_scope:X509SVID)
537
+ })
538
+ _sym_db.RegisterMessage(X509SVID)
539
+
540
+ X509BundlesRequest = _reflection.GeneratedProtocolMessageType('X509BundlesRequest', (_message.Message,), {
541
+ 'DESCRIPTOR' : _X509BUNDLESREQUEST,
542
+ '__module__' : 'workload_pb2'
543
+ # @@protoc_insertion_point(class_scope:X509BundlesRequest)
544
+ })
545
+ _sym_db.RegisterMessage(X509BundlesRequest)
546
+
547
+ X509BundlesResponse = _reflection.GeneratedProtocolMessageType('X509BundlesResponse', (_message.Message,), {
548
+
549
+ 'BundlesEntry' : _reflection.GeneratedProtocolMessageType('BundlesEntry', (_message.Message,), {
550
+ 'DESCRIPTOR' : _X509BUNDLESRESPONSE_BUNDLESENTRY,
551
+ '__module__' : 'workload_pb2'
552
+ # @@protoc_insertion_point(class_scope:X509BundlesResponse.BundlesEntry)
553
+ })
554
+ ,
555
+ 'DESCRIPTOR' : _X509BUNDLESRESPONSE,
556
+ '__module__' : 'workload_pb2'
557
+ # @@protoc_insertion_point(class_scope:X509BundlesResponse)
558
+ })
559
+ _sym_db.RegisterMessage(X509BundlesResponse)
560
+ _sym_db.RegisterMessage(X509BundlesResponse.BundlesEntry)
561
+
562
+ JWTSVID = _reflection.GeneratedProtocolMessageType('JWTSVID', (_message.Message,), {
563
+ 'DESCRIPTOR' : _JWTSVID,
564
+ '__module__' : 'workload_pb2'
565
+ # @@protoc_insertion_point(class_scope:JWTSVID)
566
+ })
567
+ _sym_db.RegisterMessage(JWTSVID)
568
+
569
+ JWTSVIDRequest = _reflection.GeneratedProtocolMessageType('JWTSVIDRequest', (_message.Message,), {
570
+ 'DESCRIPTOR' : _JWTSVIDREQUEST,
571
+ '__module__' : 'workload_pb2'
572
+ # @@protoc_insertion_point(class_scope:JWTSVIDRequest)
573
+ })
574
+ _sym_db.RegisterMessage(JWTSVIDRequest)
575
+
576
+ JWTSVIDResponse = _reflection.GeneratedProtocolMessageType('JWTSVIDResponse', (_message.Message,), {
577
+ 'DESCRIPTOR' : _JWTSVIDRESPONSE,
578
+ '__module__' : 'workload_pb2'
579
+ # @@protoc_insertion_point(class_scope:JWTSVIDResponse)
580
+ })
581
+ _sym_db.RegisterMessage(JWTSVIDResponse)
582
+
583
+ JWTBundlesRequest = _reflection.GeneratedProtocolMessageType('JWTBundlesRequest', (_message.Message,), {
584
+ 'DESCRIPTOR' : _JWTBUNDLESREQUEST,
585
+ '__module__' : 'workload_pb2'
586
+ # @@protoc_insertion_point(class_scope:JWTBundlesRequest)
587
+ })
588
+ _sym_db.RegisterMessage(JWTBundlesRequest)
589
+
590
+ JWTBundlesResponse = _reflection.GeneratedProtocolMessageType('JWTBundlesResponse', (_message.Message,), {
591
+
592
+ 'BundlesEntry' : _reflection.GeneratedProtocolMessageType('BundlesEntry', (_message.Message,), {
593
+ 'DESCRIPTOR' : _JWTBUNDLESRESPONSE_BUNDLESENTRY,
594
+ '__module__' : 'workload_pb2'
595
+ # @@protoc_insertion_point(class_scope:JWTBundlesResponse.BundlesEntry)
596
+ })
597
+ ,
598
+ 'DESCRIPTOR' : _JWTBUNDLESRESPONSE,
599
+ '__module__' : 'workload_pb2'
600
+ # @@protoc_insertion_point(class_scope:JWTBundlesResponse)
601
+ })
602
+ _sym_db.RegisterMessage(JWTBundlesResponse)
603
+ _sym_db.RegisterMessage(JWTBundlesResponse.BundlesEntry)
604
+
605
+
606
+ _X509SVIDRESPONSE_FEDERATEDBUNDLESENTRY._options = None
607
+ _X509BUNDLESRESPONSE_BUNDLESENTRY._options = None
608
+ _JWTBUNDLESRESPONSE_BUNDLESENTRY._options = None
609
+
610
+ _SPIFFEWORKLOADAPI = _descriptor.ServiceDescriptor(
611
+ name='SpiffeWorkloadAPI',
612
+ full_name='SpiffeWorkloadAPI',
613
+ file=DESCRIPTOR,
614
+ index=0,
615
+ serialized_options=None,
616
+ create_key=_descriptor._internal_create_key,
617
+ serialized_start=772,
618
+ serialized_end=1025,
619
+ methods=[
620
+ _descriptor.MethodDescriptor(
621
+ name='FetchX509SVID',
622
+ full_name='SpiffeWorkloadAPI.FetchX509SVID',
623
+ index=0,
624
+ containing_service=None,
625
+ input_type=_X509SVIDREQUEST,
626
+ output_type=_X509SVIDRESPONSE,
627
+ serialized_options=None,
628
+ create_key=_descriptor._internal_create_key,
629
+ ),
630
+ _descriptor.MethodDescriptor(
631
+ name='FetchX509Bundles',
632
+ full_name='SpiffeWorkloadAPI.FetchX509Bundles',
633
+ index=1,
634
+ containing_service=None,
635
+ input_type=_X509BUNDLESREQUEST,
636
+ output_type=_X509BUNDLESRESPONSE,
637
+ serialized_options=None,
638
+ create_key=_descriptor._internal_create_key,
639
+ ),
640
+ _descriptor.MethodDescriptor(
641
+ name='FetchJWTSVID',
642
+ full_name='SpiffeWorkloadAPI.FetchJWTSVID',
643
+ index=2,
644
+ containing_service=None,
645
+ input_type=_JWTSVIDREQUEST,
646
+ output_type=_JWTSVIDRESPONSE,
647
+ serialized_options=None,
648
+ create_key=_descriptor._internal_create_key,
649
+ ),
650
+ _descriptor.MethodDescriptor(
651
+ name='FetchJWTBundles',
652
+ full_name='SpiffeWorkloadAPI.FetchJWTBundles',
653
+ index=3,
654
+ containing_service=None,
655
+ input_type=_JWTBUNDLESREQUEST,
656
+ output_type=_JWTBUNDLESRESPONSE,
657
+ serialized_options=None,
658
+ create_key=_descriptor._internal_create_key,
659
+ ),
660
+ ])
661
+ _sym_db.RegisterServiceDescriptor(_SPIFFEWORKLOADAPI)
662
+
663
+ DESCRIPTOR.services_by_name['SpiffeWorkloadAPI'] = _SPIFFEWORKLOADAPI
664
+
665
+ # @@protoc_insertion_point(module_scope)
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/proto/workload_py2/workload_pb2_grpc.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
2
+ """Client and server classes corresponding to protobuf-defined services."""
3
+ import grpc
4
+
5
+ from ..workload_py2 import workload_pb2 as workload__pb2
6
+
7
+
8
+ class SpiffeWorkloadAPIStub(object):
9
+ """Missing associated documentation comment in .proto file."""
10
+
11
+ def __init__(self, channel):
12
+ """Constructor.
13
+
14
+ Args:
15
+ channel: A grpc.Channel.
16
+ """
17
+ self.FetchX509SVID = channel.unary_stream(
18
+ '/SpiffeWorkloadAPI/FetchX509SVID',
19
+ request_serializer=workload__pb2.X509SVIDRequest.SerializeToString,
20
+ response_deserializer=workload__pb2.X509SVIDResponse.FromString,
21
+ )
22
+ self.FetchX509Bundles = channel.unary_stream(
23
+ '/SpiffeWorkloadAPI/FetchX509Bundles',
24
+ request_serializer=workload__pb2.X509BundlesRequest.SerializeToString,
25
+ response_deserializer=workload__pb2.X509BundlesResponse.FromString,
26
+ )
27
+ self.FetchJWTSVID = channel.unary_unary(
28
+ '/SpiffeWorkloadAPI/FetchJWTSVID',
29
+ request_serializer=workload__pb2.JWTSVIDRequest.SerializeToString,
30
+ response_deserializer=workload__pb2.JWTSVIDResponse.FromString,
31
+ )
32
+ self.FetchJWTBundles = channel.unary_stream(
33
+ '/SpiffeWorkloadAPI/FetchJWTBundles',
34
+ request_serializer=workload__pb2.JWTBundlesRequest.SerializeToString,
35
+ response_deserializer=workload__pb2.JWTBundlesResponse.FromString,
36
+ )
37
+
38
+
39
+ class SpiffeWorkloadAPIServicer(object):
40
+ """Missing associated documentation comment in .proto file."""
41
+
42
+ def FetchX509SVID(self, request, context):
43
+ """X.509-SVID Profile
44
+ Fetch all SPIFFE identities the workload is entitled to, as
45
+ well as related information like trust bundles and CRLs. As
46
+ this information changes, subsequent messages will be sent.
47
+ """
48
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
49
+ context.set_details('Method not implemented!')
50
+ raise NotImplementedError('Method not implemented!')
51
+
52
+ def FetchX509Bundles(self, request, context):
53
+ """Missing associated documentation comment in .proto file."""
54
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
55
+ context.set_details('Method not implemented!')
56
+ raise NotImplementedError('Method not implemented!')
57
+
58
+ def FetchJWTSVID(self, request, context):
59
+ """JWT-SVID Profile
60
+ """
61
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
62
+ context.set_details('Method not implemented!')
63
+ raise NotImplementedError('Method not implemented!')
64
+
65
+ def FetchJWTBundles(self, request, context):
66
+ """Missing associated documentation comment in .proto file."""
67
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
68
+ context.set_details('Method not implemented!')
69
+ raise NotImplementedError('Method not implemented!')
70
+
71
+
72
+ def add_SpiffeWorkloadAPIServicer_to_server(servicer, server):
73
+ rpc_method_handlers = {
74
+ 'FetchX509SVID': grpc.unary_stream_rpc_method_handler(
75
+ servicer.FetchX509SVID,
76
+ request_deserializer=workload__pb2.X509SVIDRequest.FromString,
77
+ response_serializer=workload__pb2.X509SVIDResponse.SerializeToString,
78
+ ),
79
+ 'FetchX509Bundles': grpc.unary_stream_rpc_method_handler(
80
+ servicer.FetchX509Bundles,
81
+ request_deserializer=workload__pb2.X509BundlesRequest.FromString,
82
+ response_serializer=workload__pb2.X509BundlesResponse.SerializeToString,
83
+ ),
84
+ 'FetchJWTSVID': grpc.unary_unary_rpc_method_handler(
85
+ servicer.FetchJWTSVID,
86
+ request_deserializer=workload__pb2.JWTSVIDRequest.FromString,
87
+ response_serializer=workload__pb2.JWTSVIDResponse.SerializeToString,
88
+ ),
89
+ 'FetchJWTBundles': grpc.unary_stream_rpc_method_handler(
90
+ servicer.FetchJWTBundles,
91
+ request_deserializer=workload__pb2.JWTBundlesRequest.FromString,
92
+ response_serializer=workload__pb2.JWTBundlesResponse.SerializeToString,
93
+ ),
94
+ }
95
+ generic_handler = grpc.method_handlers_generic_handler(
96
+ 'SpiffeWorkloadAPI', rpc_method_handlers)
97
+ server.add_generic_rpc_handlers((generic_handler,))
98
+
99
+
100
+ # This class is part of an EXPERIMENTAL API.
101
+ class SpiffeWorkloadAPI(object):
102
+ """Missing associated documentation comment in .proto file."""
103
+
104
+ @staticmethod
105
+ def FetchX509SVID(request,
106
+ target,
107
+ options=(),
108
+ channel_credentials=None,
109
+ call_credentials=None,
110
+ insecure=False,
111
+ compression=None,
112
+ wait_for_ready=None,
113
+ timeout=None,
114
+ metadata=None):
115
+ return grpc.experimental.unary_stream(request, target, '/SpiffeWorkloadAPI/FetchX509SVID',
116
+ workload__pb2.X509SVIDRequest.SerializeToString,
117
+ workload__pb2.X509SVIDResponse.FromString,
118
+ options, channel_credentials,
119
+ insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
120
+
121
+ @staticmethod
122
+ def FetchX509Bundles(request,
123
+ target,
124
+ options=(),
125
+ channel_credentials=None,
126
+ call_credentials=None,
127
+ insecure=False,
128
+ compression=None,
129
+ wait_for_ready=None,
130
+ timeout=None,
131
+ metadata=None):
132
+ return grpc.experimental.unary_stream(request, target, '/SpiffeWorkloadAPI/FetchX509Bundles',
133
+ workload__pb2.X509BundlesRequest.SerializeToString,
134
+ workload__pb2.X509BundlesResponse.FromString,
135
+ options, channel_credentials,
136
+ insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
137
+
138
+ @staticmethod
139
+ def FetchJWTSVID(request,
140
+ target,
141
+ options=(),
142
+ channel_credentials=None,
143
+ call_credentials=None,
144
+ insecure=False,
145
+ compression=None,
146
+ wait_for_ready=None,
147
+ timeout=None,
148
+ metadata=None):
149
+ return grpc.experimental.unary_unary(request, target, '/SpiffeWorkloadAPI/FetchJWTSVID',
150
+ workload__pb2.JWTSVIDRequest.SerializeToString,
151
+ workload__pb2.JWTSVIDResponse.FromString,
152
+ options, channel_credentials,
153
+ insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
154
+
155
+ @staticmethod
156
+ def FetchJWTBundles(request,
157
+ target,
158
+ options=(),
159
+ channel_credentials=None,
160
+ call_credentials=None,
161
+ insecure=False,
162
+ compression=None,
163
+ wait_for_ready=None,
164
+ timeout=None,
165
+ metadata=None):
166
+ return grpc.experimental.unary_stream(request, target, '/SpiffeWorkloadAPI/FetchJWTBundles',
167
+ workload__pb2.JWTBundlesRequest.SerializeToString,
168
+ workload__pb2.JWTBundlesResponse.FromString,
169
+ options, channel_credentials,
170
+ insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/spiffeid/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .id import ID
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/spiffeid/id.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import Enum
2
+
3
+ from cryptography import x509
4
+ from urllib3.util import url
5
+
6
+ from ... import SpiffeError
7
+
8
+
9
+ class ID(object):
10
+ def __init__(self, trust_domain=None, path=None):
11
+ self.trust_domain = trust_domain
12
+ self.path = path
13
+
14
+ def __str__(self):
15
+ return "{ From str method of ID: trust_domain = %s, path = %s }" % (self.trust_domain, self.path)
16
+
17
+ @classmethod
18
+ def from_str(cls, id_str):
19
+ return cls.from_uri(id_str)
20
+
21
+ @classmethod
22
+ def from_uri(cls, uri):
23
+ if not hasattr(uri, 'hostname') or not hasattr(uri, 'path'):
24
+ uri = url.parse_url(uri)
25
+ trust_domain = str(uri.hostname)
26
+ path = str(uri.path).lstrip('/').rstrip('/')
27
+ return cls(trust_domain, path)
28
+
29
+ def is_zero(self):
30
+ if not self.trust_domain:
31
+ return True
32
+ return False
33
+
34
+ def to_str(self):
35
+ if self.is_zero():
36
+ return ""
37
+ return self.trust_domain + '/' + self.path
38
+
39
+ def get_trust_domain(self):
40
+ return str(self.trust_domain)
41
+
42
+ def get_path(self):
43
+ return str(self.path)
44
+
45
+
46
+ class IdType(Enum):
47
+ ANY_TYPE = 1
48
+ TRUST_DOMAIN_ID = 2
49
+ WORKLOAD_ID = 3
50
+
51
+
52
+ class ValidationOptions:
53
+ def __init__(self, trust_domain='', trust_domain_required=False, id_type=IdType.ANY_TYPE):
54
+ self.trust_domain = trust_domain
55
+ self.trust_domain_required = trust_domain_required
56
+ self.id_type = id_type
57
+
58
+
59
+ def validate_uri(uri, options):
60
+ # type: (url.Url, ValidationOptions) -> None
61
+ if uri is None:
62
+ raise SpiffeError('spiffe id is empty')
63
+ if not isinstance(uri, url.Url):
64
+ raise SpiffeError('not a uri ({type})'.format(type=type(uri)))
65
+ if uri.scheme.lower() != 'spiffe':
66
+ raise SpiffeError('invalid scheme')
67
+ if not uri.host:
68
+ raise SpiffeError('trust domain is empty')
69
+ if uri.port is not None:
70
+ raise SpiffeError('port is not allowed')
71
+ if uri.fragment is not None:
72
+ raise SpiffeError('fragment is not allowed')
73
+ if uri.query is not None:
74
+ raise SpiffeError('query is not allowed')
75
+
76
+ if options.trust_domain_required:
77
+ if not options.trust_domain:
78
+ raise SpiffeError('trust domain to validate against cannot be empty')
79
+ if uri.host != options.trust_domain:
80
+ raise SpiffeError('{id} does not belong to trust domain {td}'.format(id=uri, td=options.trust_domain))
81
+
82
+ if options.id_type == IdType.TRUST_DOMAIN_ID:
83
+ if uri.path:
84
+ raise SpiffeError('path is not empty')
85
+ if options.id_type == IdType.WORKLOAD_ID:
86
+ if not uri.path:
87
+ raise SpiffeError('path is empty')
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/svid/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/svid/x509svid/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .svid import *
2
+ from .verify import *
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/svid/x509svid/svid.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+ from cryptography import x509
4
+
5
+ from ... import spiffeid
6
+ from .... import SpiffeError
7
+
8
+
9
+ class SvidError(SpiffeError):
10
+ pass
11
+
12
+
13
+ def id_from_cert(cert):
14
+ # type: (x509.Certificate) -> spiffeid.ID
15
+ sans = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value
16
+ uris = [san for san in sans if type(san) == x509.UniformResourceIdentifier]
17
+ if len(uris) == 0:
18
+ raise SpiffeError("certificate contains no URI SAN")
19
+ elif len(uris) > 1:
20
+ raise SpiffeError("certificate contains more than one URI SAN")
21
+ return spiffeid.ID().from_str(uris[0].value)
22
+
23
+
24
+ def validate_certificates(certs):
25
+ # type: (List[x509.Certificate]) -> spiffeid.ID
26
+ if len(certs) == 0:
27
+ raise SvidError('no certificates found')
28
+
29
+ leaf_id = validate_leaf_certificate(certs[0])
30
+
31
+ validate_signing_certificates(certs[1:])
32
+
33
+ return leaf_id
34
+
35
+
36
+ def validate_leaf_certificate(leaf):
37
+ # type: (x509.Certificate) -> spiffeid.ID
38
+ try:
39
+ leaf_id = id_from_cert(leaf)
40
+ except Exception as e:
41
+ raise SvidError('cannot get leaf certificate SPIFFE ID').with_traceback(e.__traceback__)
42
+
43
+ if is_ca(leaf):
44
+ raise SvidError('leaf certificate must not have CA flag set to true')
45
+
46
+ validate_leaf_cert_key_usage(leaf)
47
+
48
+ return leaf_id
49
+
50
+
51
+ def validate_signing_certificates(certs):
52
+ # type: (List[x509.Certificate]) -> None
53
+ for cert in certs:
54
+ if not is_ca(cert):
55
+ raise SvidError('signing certificate must have CA flag set to true')
56
+ validate_signing_cert_key_usage(cert)
57
+
58
+
59
+ def is_ca(cert):
60
+ # type: (x509.Certificate) -> bool
61
+ basic_constraints = cert.extensions.get_extension_for_class(x509.BasicConstraints).value
62
+ # type: x509.BasicConstraints
63
+ return basic_constraints.ca
64
+
65
+
66
+ def validate_leaf_cert_key_usage(leaf):
67
+ # type: (x509.Certificate) -> None
68
+ key_usage = leaf.extensions.get_extension_for_class(x509.KeyUsage).value
69
+ # type: x509.KeyUsage
70
+ if not key_usage.digital_signature:
71
+ raise SvidError('leaf certificate must have \'digital_signature\' set as key usage')
72
+ if key_usage.key_cert_sign:
73
+ raise SvidError('leaf certificate must not have \'key_cert_sign\' set as key usage')
74
+ if key_usage.crl_sign:
75
+ raise SvidError('leaf certificate must not have \'crl_sign\' set as key usage')
76
+
77
+
78
+ def validate_signing_cert_key_usage(leaf):
79
+ # type: (x509.Certificate) -> None
80
+ key_usage = leaf.extensions.get_extension_for_class(x509.KeyUsage).value
81
+ # type: x509.KeyUsage
82
+ if not key_usage.key_cert_sign:
83
+ raise SvidError('signing certificate must have \'key_cert_sign\' set as key usage')
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spiffe/svid/x509svid/verify.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Dict, Tuple
2
+
3
+ from OpenSSL import crypto
4
+ from cryptography import x509
5
+
6
+
7
+ from ...spiffeid import ID
8
+ from .svid import validate_leaf_certificate, SvidError
9
+
10
+
11
+ def verify(certs, bundle_source):
12
+ # type: (List[x509.Certificate], Dict[str, List[x509.Certificate]]) -> Tuple[ID, List[x509.Certificate]]
13
+ """
14
+ Verifies an X.509-SVID chain using the X.509 bundle source. It returns the SPIFFE ID of the X.509-SVID and
15
+ one or more chains back to a root in the bundle.
16
+
17
+ :param certs: the X.509-SVID chain to verify.
18
+ :param bundle_source: the X.509 bundle source to verify against.
19
+ :return: the SPIFFE ID of the X.509-SVID and verified chains back to a root in the bundle.
20
+ """
21
+ if len(certs) == 0:
22
+ raise SvidError('empty certificates chain')
23
+ if len(bundle_source) == 0:
24
+ raise SvidError('bundle source is required')
25
+
26
+ leaf_cert = certs[0]
27
+ leaf_id = validate_leaf_certificate(leaf_cert)
28
+
29
+ try:
30
+ bundle = bundle_source[leaf_id.get_trust_domain()]
31
+ except Exception as e:
32
+ raise SvidError('could not get X509 bundle: {name}'.format(name=leaf_id.get_trust_domain())).with_traceback(e.__traceback__)
33
+
34
+ store = crypto.X509Store()
35
+ for root in bundle:
36
+ store.add_cert(crypto.X509.from_cryptography(root))
37
+ for intermediate in certs[1:]:
38
+ store.add_cert(crypto.X509.from_cryptography(intermediate))
39
+
40
+ store_ctx = crypto.X509StoreContext(store, crypto.X509.from_cryptography(leaf_cert))
41
+ verified_chains = [cert.to_cryptography() for cert in store_ctx.get_verified_chain()]
42
+
43
+ return leaf_id, verified_chains
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spire/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spire/api/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spire/api/workload/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .x509_client import X509ClientConfig, X509Client
2
+ from .jwt_client import JWTClientConfig, JWTClient
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spire/api/workload/jwt_client.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import grpc
3
+
4
+ has_builder = False
5
+ try:
6
+ from google.protobuf.internal import builder as _
7
+ has_builder = True
8
+ except:
9
+ pass
10
+
11
+ import sys
12
+ if sys.version_info[0:2] >= (3, 5) and has_builder:
13
+ from ....spiffe.proto import workload
14
+ else:
15
+ from ....spiffe.proto import workload_py2 as workload
16
+
17
+
18
+ DEFAULT_AGENT_SOCKET_ADDR = "unix:///var/run/zti-agent.sock"
19
+ DEFAULT_TIMEOUT_SECONDS = 5
20
+ METADATA = [("workload.spiffe.io", "true")]
21
+
22
+
23
+ class JWTClientConfig(object):
24
+ def __init__(self, socket_addr=DEFAULT_AGENT_SOCKET_ADDR, logger=logging):
25
+ self.socket_addr = socket_addr
26
+ self.logger = logger
27
+
28
+
29
+ class JWTClient(object):
30
+ def __init__(self, config, grpc_options=None):
31
+ self.config = config
32
+ self.grpc_channel = grpc.insecure_channel(self.config.socket_addr, options=grpc_options)
33
+ self.stub = workload.SpiffeWorkloadAPIStub(self.grpc_channel)
34
+
35
+ def fetch_jwt_svid(self):
36
+ # type: () -> workload.JWTSVIDResponse
37
+ return self.stub.FetchJWTSVID(
38
+ workload.JWTSVIDRequest(audience=["zti"]),
39
+ metadata=METADATA,
40
+ timeout=DEFAULT_TIMEOUT_SECONDS,
41
+ )
42
+
43
+ def get_jwt_bundle(self):
44
+ # type: () -> workload.JWTBundlesResponse
45
+ return self.stub.FetchJWTBundles(
46
+ workload.JWTBundlesRequest(),
47
+ metadata=METADATA,
48
+ timeout=DEFAULT_TIMEOUT_SECONDS,
49
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/ztispiffe/spire/api/workload/x509_client.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ try:
2
+ import queue
3
+ except ImportError:
4
+ import Queue as queue
5
+
6
+ import logging
7
+ import threading
8
+ import time
9
+ from threading import Lock
10
+ from typing import List, Optional
11
+ import grpc
12
+
13
+ from .... import SpiffeError
14
+
15
+ has_builder = False
16
+ try:
17
+ from google.protobuf.internal import builder as _
18
+ has_builder = True
19
+ except:
20
+ pass
21
+
22
+ import sys
23
+ if sys.version_info[0:2] >= (3, 5) and has_builder:
24
+ from ....spiffe.proto import workload
25
+ else:
26
+ from ....spiffe.proto import workload_py2 as workload
27
+
28
+
29
+ class X509ClientError(SpiffeError):
30
+ pass
31
+
32
+
33
+ class X509ClientConfig(object):
34
+ def __init__(self, addr='', fail_on_error=False, timeout=300, backoff_cap=30, logger=logging):
35
+ self.__backoff_min__ = 1
36
+
37
+ self.addr = addr
38
+ self.fail_on_error = fail_on_error
39
+ self.timeout = timeout
40
+ self.backoff_cap = backoff_cap
41
+ self.logger = logger
42
+
43
+
44
+ class X509Client(object):
45
+ def __init__(self, config, grpc_options=None): # type: (X509ClientConfig, Optional[List[grpc.ChannelOption]]) -> None
46
+ self.config = config
47
+ # grpc options
48
+ self.grpc_options = grpc_options # type: Optional[List[grpc.ChannelOption]]
49
+ # type: queue.Queue[workload.X509SVIDResponse]
50
+ self.__update_queue = queue.Queue(1)
51
+ self.__lock = Lock()
52
+
53
+ self._current_svid = None
54
+
55
+ self._stream = None
56
+ # type: threading.Thread
57
+ self._stream_thread = None
58
+
59
+ # type: queue.Queue
60
+ self._stop_signal = None
61
+ self._error = None
62
+
63
+ def start(self, block=False):
64
+ self.__lock.acquire()
65
+
66
+ # raise exception if client has already started
67
+ if self._stream_thread is not None:
68
+ self.__lock.release()
69
+ raise X509ClientError("already started")
70
+
71
+ self._stop_signal = queue.Queue(1)
72
+ error_queue = queue.Queue(1)
73
+
74
+ self._stream_thread = threading.Thread(target=self._stream_x509_svid,
75
+ args=(self.__update_queue, self._stop_signal, error_queue))
76
+ self._stream_thread.start()
77
+ self.__lock.release()
78
+
79
+ if block:
80
+ error = error_queue.get()
81
+ self.stop()
82
+ if error is not None:
83
+ raise X509ClientError('X509Client exited').with_traceback(error.__traceback__)
84
+
85
+ def stop(self):
86
+ self.__lock.acquire()
87
+
88
+ # return if client has not started
89
+ if self._stream_thread is None:
90
+ self.__lock.release()
91
+ return
92
+
93
+ # stop the x509 streaming thread
94
+ self._stop_signal.put(1)
95
+ while True:
96
+ # if thread fails to join, try re-cancelling grpc stream channel because it blocks thread to finish
97
+ if self._stream is not None:
98
+ self._stream.cancel()
99
+ self._stream_thread.join(1)
100
+ if not self._stream_thread.is_alive():
101
+ break
102
+
103
+ self._stream_thread = None
104
+ self.__lock.release()
105
+
106
+ def is_alive(self):
107
+ self.__lock.acquire()
108
+ res = self._stream_thread is not None and self._stream_thread.is_alive()
109
+ self.__lock.release()
110
+ return res
111
+
112
+ def current_svid(self):
113
+ # type: () -> workload.X509SVIDResponse
114
+ resp = None
115
+ self.__lock.acquire()
116
+ if self._current_svid is not None:
117
+ resp = self._current_svid
118
+ else:
119
+ self.config.logger.error("no SVID received yet")
120
+ self.__lock.release()
121
+ return resp
122
+
123
+ def update_queue(self):
124
+ # type: () -> 'queue.Queue[workload.X509SVIDResponse]'
125
+ return self.__update_queue
126
+
127
+ def _stream_x509_svid(self, out, stop, exit_error):
128
+ # type: (queue.Queue, queue.Queue, queue.Queue) -> None
129
+ metadata = [("workload.spiffe.io", 'true')]
130
+ last_success = [time.time(), False]
131
+ backoff = [self.config.__backoff_min__]
132
+
133
+ def handle_exception(op, ex):
134
+ if ex.code() == grpc.StatusCode.INVALID_ARGUMENT:
135
+ self.config.logger.error("{op} failed with {ex}; aborting".format(op=op, ex=repr(str(ex))))
136
+ return ex
137
+ if self.config.fail_on_error:
138
+ self.config.logger.error("{op} failed with {ex}; aborting".format(op=op, ex=repr(str(ex))))
139
+ return ex
140
+
141
+ if last_success[1]:
142
+ last_success[1] = False
143
+ last_success[0] = time.time()
144
+
145
+ if self.config.timeout > 0:
146
+ elapsed_time = time.time() - last_success[0]
147
+ timeout_left = self.config.timeout - elapsed_time
148
+ if timeout_left <= 0:
149
+ self.config.logger.error(
150
+ "{op} failed with {ex}; aborting due to timeout (last success {time: .2f} seconds ago)".format(
151
+ op=op, ex=repr(str(ex)), time=elapsed_time))
152
+ return X509ClientError("timeout exceeded")
153
+ if backoff[0] > timeout_left:
154
+ backoff[0] = timeout_left
155
+
156
+ self.config.logger.error(msg="{op} failed with {ex}; retrying in {time:.2f} seconds"
157
+ .format(op=op, ex=repr(str(ex)), time=backoff[0]))
158
+ time.sleep(backoff[0])
159
+
160
+ backoff[0] = backoff[0] * 1.5
161
+ if backoff[0] > self.config.backoff_cap:
162
+ backoff[0] = self.config.backoff_cap
163
+ return None
164
+
165
+ channel = grpc.insecure_channel(self.config.addr, options=self.grpc_options)
166
+ stub = workload.SpiffeWorkloadAPIStub(channel)
167
+ self._stream = stub.FetchX509SVID(workload.X509SVIDRequest(), metadata=metadata)
168
+ while True:
169
+ try:
170
+ update = self._stream.next()
171
+ while True:
172
+ try:
173
+ if not out.empty():
174
+ out.get_nowait()
175
+ out.put_nowait(update)
176
+ break
177
+ except queue.Full or queue.Empty:
178
+ pass
179
+ self._current_svid = update
180
+ last_success[0] = time.time()
181
+ last_success[1] = True
182
+ backoff = [self.config.__backoff_min__]
183
+ except Exception as e:
184
+ # return successfully if the exception is triggered by stop signal
185
+ if not stop.empty():
186
+ exit_error.put(None)
187
+ return
188
+ # return exception if critical
189
+ ee = handle_exception("FetchX509SVID", e)
190
+ if ee is not None:
191
+ exit_error.put(ee)
192
+ return
193
+ # if grpc status code is 'UNAVAILABLE', recreate the grpc channel and stub
194
+ if hasattr(e, 'code') and callable(e.code):
195
+ if e.code() is grpc.StatusCode.UNAVAILABLE:
196
+ channel.close()
197
+ channel = grpc.insecure_channel(self.config.addr, options=self.grpc_options)
198
+ stub = workload.SpiffeWorkloadAPIStub(channel)
199
+ self._stream = stub.FetchX509SVID(workload.X509SVIDRequest(), metadata=metadata)
200
+
miniconda3/envs/ladir/lib/python3.10/sqlite3/__init__.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pysqlite2/__init__.py: the pysqlite2 package.
2
+ #
3
+ # Copyright (C) 2005 Gerhard Häring <gh@ghaering.de>
4
+ #
5
+ # This file is part of pysqlite.
6
+ #
7
+ # This software is provided 'as-is', without any express or implied
8
+ # warranty. In no event will the authors be held liable for any damages
9
+ # arising from the use of this software.
10
+ #
11
+ # Permission is granted to anyone to use this software for any purpose,
12
+ # including commercial applications, and to alter it and redistribute it
13
+ # freely, subject to the following restrictions:
14
+ #
15
+ # 1. The origin of this software must not be misrepresented; you must not
16
+ # claim that you wrote the original software. If you use this software
17
+ # in a product, an acknowledgment in the product documentation would be
18
+ # appreciated but is not required.
19
+ # 2. Altered source versions must be plainly marked as such, and must not be
20
+ # misrepresented as being the original software.
21
+ # 3. This notice may not be removed or altered from any source distribution.
22
+
23
+ """
24
+ The sqlite3 extension module provides a DB-API 2.0 (PEP 249) compliant
25
+ interface to the SQLite library, and requires SQLite 3.7.15 or newer.
26
+
27
+ To use the module, start by creating a database Connection object:
28
+
29
+ import sqlite3
30
+ cx = sqlite3.connect("test.db") # test.db will be created or opened
31
+
32
+ The special path name ":memory:" can be provided to connect to a transient
33
+ in-memory database:
34
+
35
+ cx = sqlite3.connect(":memory:") # connect to a database in RAM
36
+
37
+ Once a connection has been established, create a Cursor object and call
38
+ its execute() method to perform SQL queries:
39
+
40
+ cu = cx.cursor()
41
+
42
+ # create a table
43
+ cu.execute("create table lang(name, first_appeared)")
44
+
45
+ # insert values into a table
46
+ cu.execute("insert into lang values (?, ?)", ("C", 1972))
47
+
48
+ # execute a query and iterate over the result
49
+ for row in cu.execute("select * from lang"):
50
+ print(row)
51
+
52
+ cx.close()
53
+
54
+ The sqlite3 module is written by Gerhard Häring <gh@ghaering.de>.
55
+ """
56
+
57
+ from sqlite3.dbapi2 import *
58
+
59
+
60
+ # bpo-42264: OptimizedUnicode was deprecated in Python 3.10. It's scheduled
61
+ # for removal in Python 3.12.
62
+ def __getattr__(name):
63
+ if name == "OptimizedUnicode":
64
+ import warnings
65
+ msg = ("""
66
+ OptimizedUnicode is deprecated and will be removed in Python 3.12.
67
+ Since Python 3.3 it has simply been an alias for 'str'.
68
+ """)
69
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
70
+ return str
71
+ raise AttributeError(f"module 'sqlite3' has no attribute '{name}'")
miniconda3/envs/ladir/lib/python3.10/sqlite3/dbapi2.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pysqlite2/dbapi2.py: the DB-API 2.0 interface
2
+ #
3
+ # Copyright (C) 2004-2005 Gerhard Häring <gh@ghaering.de>
4
+ #
5
+ # This file is part of pysqlite.
6
+ #
7
+ # This software is provided 'as-is', without any express or implied
8
+ # warranty. In no event will the authors be held liable for any damages
9
+ # arising from the use of this software.
10
+ #
11
+ # Permission is granted to anyone to use this software for any purpose,
12
+ # including commercial applications, and to alter it and redistribute it
13
+ # freely, subject to the following restrictions:
14
+ #
15
+ # 1. The origin of this software must not be misrepresented; you must not
16
+ # claim that you wrote the original software. If you use this software
17
+ # in a product, an acknowledgment in the product documentation would be
18
+ # appreciated but is not required.
19
+ # 2. Altered source versions must be plainly marked as such, and must not be
20
+ # misrepresented as being the original software.
21
+ # 3. This notice may not be removed or altered from any source distribution.
22
+
23
+ import datetime
24
+ import time
25
+ import collections.abc
26
+
27
+ from _sqlite3 import *
28
+
29
+ paramstyle = "qmark"
30
+
31
+ threadsafety = 1
32
+
33
+ apilevel = "2.0"
34
+
35
+ Date = datetime.date
36
+
37
+ Time = datetime.time
38
+
39
+ Timestamp = datetime.datetime
40
+
41
+ def DateFromTicks(ticks):
42
+ return Date(*time.localtime(ticks)[:3])
43
+
44
+ def TimeFromTicks(ticks):
45
+ return Time(*time.localtime(ticks)[3:6])
46
+
47
+ def TimestampFromTicks(ticks):
48
+ return Timestamp(*time.localtime(ticks)[:6])
49
+
50
+ version_info = tuple([int(x) for x in version.split(".")])
51
+ sqlite_version_info = tuple([int(x) for x in sqlite_version.split(".")])
52
+
53
+ Binary = memoryview
54
+ collections.abc.Sequence.register(Row)
55
+
56
+ def register_adapters_and_converters():
57
+ def adapt_date(val):
58
+ return val.isoformat()
59
+
60
+ def adapt_datetime(val):
61
+ return val.isoformat(" ")
62
+
63
+ def convert_date(val):
64
+ return datetime.date(*map(int, val.split(b"-")))
65
+
66
+ def convert_timestamp(val):
67
+ datepart, timepart = val.split(b" ")
68
+ year, month, day = map(int, datepart.split(b"-"))
69
+ timepart_full = timepart.split(b".")
70
+ hours, minutes, seconds = map(int, timepart_full[0].split(b":"))
71
+ if len(timepart_full) == 2:
72
+ microseconds = int('{:0<6.6}'.format(timepart_full[1].decode()))
73
+ else:
74
+ microseconds = 0
75
+
76
+ val = datetime.datetime(year, month, day, hours, minutes, seconds, microseconds)
77
+ return val
78
+
79
+
80
+ register_adapter(datetime.date, adapt_date)
81
+ register_adapter(datetime.datetime, adapt_datetime)
82
+ register_converter("date", convert_date)
83
+ register_converter("timestamp", convert_timestamp)
84
+
85
+ register_adapters_and_converters()
86
+
87
+ # bpo-24464: enable_shared_cache was deprecated in Python 3.10. It's
88
+ # scheduled for removal in Python 3.12.
89
+ def enable_shared_cache(enable):
90
+ from _sqlite3 import enable_shared_cache as _old_enable_shared_cache
91
+ import warnings
92
+ msg = (
93
+ "enable_shared_cache is deprecated and will be removed in Python 3.12. "
94
+ "Shared cache is strongly discouraged by the SQLite 3 documentation. "
95
+ "If shared cache must be used, open the database in URI mode using"
96
+ "the cache=shared query parameter."
97
+ )
98
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
99
+ return _old_enable_shared_cache(enable)
100
+
101
+ # Clean up namespace
102
+
103
+ del(register_adapters_and_converters)
miniconda3/envs/ladir/lib/python3.10/sqlite3/dump.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Mimic the sqlite3 console shell's .dump command
2
+ # Author: Paul Kippes <kippesp@gmail.com>
3
+
4
+ # Every identifier in sql is quoted based on a comment in sqlite
5
+ # documentation "SQLite adds new keywords from time to time when it
6
+ # takes on new features. So to prevent your code from being broken by
7
+ # future enhancements, you should normally quote any identifier that
8
+ # is an English language word, even if you do not have to."
9
+
10
+ def _iterdump(connection):
11
+ """
12
+ Returns an iterator to the dump of the database in an SQL text format.
13
+
14
+ Used to produce an SQL dump of the database. Useful to save an in-memory
15
+ database for later restoration. This function should not be called
16
+ directly but instead called from the Connection method, iterdump().
17
+ """
18
+
19
+ cu = connection.cursor()
20
+ yield('BEGIN TRANSACTION;')
21
+
22
+ # sqlite_master table contains the SQL CREATE statements for the database.
23
+ q = """
24
+ SELECT "name", "type", "sql"
25
+ FROM "sqlite_master"
26
+ WHERE "sql" NOT NULL AND
27
+ "type" == 'table'
28
+ ORDER BY "name"
29
+ """
30
+ schema_res = cu.execute(q)
31
+ sqlite_sequence = []
32
+ for table_name, type, sql in schema_res.fetchall():
33
+ if table_name == 'sqlite_sequence':
34
+ rows = cu.execute('SELECT * FROM "sqlite_sequence";').fetchall()
35
+ sqlite_sequence = ['DELETE FROM "sqlite_sequence"']
36
+ sqlite_sequence += [
37
+ f'INSERT INTO "sqlite_sequence" VALUES(\'{row[0]}\',{row[1]})'
38
+ for row in rows
39
+ ]
40
+ continue
41
+ elif table_name == 'sqlite_stat1':
42
+ yield('ANALYZE "sqlite_master";')
43
+ elif table_name.startswith('sqlite_'):
44
+ continue
45
+ # NOTE: Virtual table support not implemented
46
+ #elif sql.startswith('CREATE VIRTUAL TABLE'):
47
+ # qtable = table_name.replace("'", "''")
48
+ # yield("INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"\
49
+ # "VALUES('table','{0}','{0}',0,'{1}');".format(
50
+ # qtable,
51
+ # sql.replace("''")))
52
+ else:
53
+ yield('{0};'.format(sql))
54
+
55
+ # Build the insert statement for each row of the current table
56
+ table_name_ident = table_name.replace('"', '""')
57
+ res = cu.execute('PRAGMA table_info("{0}")'.format(table_name_ident))
58
+ column_names = [str(table_info[1]) for table_info in res.fetchall()]
59
+ q = """SELECT 'INSERT INTO "{0}" VALUES({1})' FROM "{0}";""".format(
60
+ table_name_ident,
61
+ ",".join("""'||quote("{0}")||'""".format(col.replace('"', '""')) for col in column_names))
62
+ query_res = cu.execute(q)
63
+ for row in query_res:
64
+ yield("{0};".format(row[0]))
65
+
66
+ # Now when the type is 'index', 'trigger', or 'view'
67
+ q = """
68
+ SELECT "name", "type", "sql"
69
+ FROM "sqlite_master"
70
+ WHERE "sql" NOT NULL AND
71
+ "type" IN ('index', 'trigger', 'view')
72
+ """
73
+ schema_res = cu.execute(q)
74
+ for name, type, sql in schema_res.fetchall():
75
+ yield('{0};'.format(sql))
76
+
77
+ # gh-79009: Yield statements concerning the sqlite_sequence table at the
78
+ # end of the transaction.
79
+ for row in sqlite_sequence:
80
+ yield('{0};'.format(row))
81
+
82
+ yield('COMMIT;')
miniconda3/envs/ladir/lib/python3.10/test/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Dummy file to make this directory a package.
miniconda3/envs/ladir/lib/python3.10/test/support/__init__.py ADDED
@@ -0,0 +1,2166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Supporting definitions for the Python regression tests."""
2
+
3
+ if __name__ != 'test.support':
4
+ raise ImportError('support must be imported from the test package')
5
+
6
+ import contextlib
7
+ import functools
8
+ import os
9
+ import re
10
+ import stat
11
+ import sys
12
+ import sysconfig
13
+ import time
14
+ import types
15
+ import unittest
16
+ import warnings
17
+
18
+ from .testresult import get_test_runner
19
+
20
+
21
+ try:
22
+ from _testcapi import unicode_legacy_string
23
+ except ImportError:
24
+ unicode_legacy_string = None
25
+
26
+ __all__ = [
27
+ # globals
28
+ "PIPE_MAX_SIZE", "verbose", "max_memuse", "use_resources", "failfast",
29
+ # exceptions
30
+ "Error", "TestFailed", "TestDidNotRun", "ResourceDenied",
31
+ # io
32
+ "record_original_stdout", "get_original_stdout", "captured_stdout",
33
+ "captured_stdin", "captured_stderr",
34
+ # unittest
35
+ "is_resource_enabled", "requires", "requires_freebsd_version",
36
+ "requires_linux_version", "requires_mac_ver",
37
+ "check_syntax_error",
38
+ "BasicTestRunner", "run_unittest", "run_doctest",
39
+ "requires_gzip", "requires_bz2", "requires_lzma",
40
+ "bigmemtest", "bigaddrspacetest", "cpython_only", "get_attribute",
41
+ "requires_IEEE_754", "requires_zlib",
42
+ "anticipate_failure", "load_package_tests", "detect_api_mismatch",
43
+ "check__all__", "skip_if_buggy_ucrt_strfptime",
44
+ "check_disallow_instantiation", "check_sanitizer", "skip_if_sanitizer",
45
+ # sys
46
+ "is_jython", "is_android", "check_impl_detail", "unix_shell",
47
+ "setswitchinterval",
48
+ # network
49
+ "open_urlresource",
50
+ # processes
51
+ "reap_children",
52
+ # miscellaneous
53
+ "run_with_locale", "swap_item", "findfile",
54
+ "swap_attr", "Matcher", "set_memlimit", "SuppressCrashReport", "sortdict",
55
+ "run_with_tz", "PGO", "missing_compiler_executable",
56
+ "ALWAYS_EQ", "NEVER_EQ", "LARGEST", "SMALLEST",
57
+ "LOOPBACK_TIMEOUT", "INTERNET_TIMEOUT", "SHORT_TIMEOUT", "LONG_TIMEOUT",
58
+ ]
59
+
60
+
61
+ # Timeout in seconds for tests using a network server listening on the network
62
+ # local loopback interface like 127.0.0.1.
63
+ #
64
+ # The timeout is long enough to prevent test failure: it takes into account
65
+ # that the client and the server can run in different threads or even different
66
+ # processes.
67
+ #
68
+ # The timeout should be long enough for connect(), recv() and send() methods
69
+ # of socket.socket.
70
+ LOOPBACK_TIMEOUT = 5.0
71
+ if sys.platform == 'win32' and ' 32 bit (ARM)' in sys.version:
72
+ # bpo-37553: test_socket.SendfileUsingSendTest is taking longer than 2
73
+ # seconds on Windows ARM32 buildbot
74
+ LOOPBACK_TIMEOUT = 10
75
+ elif sys.platform == 'vxworks':
76
+ LOOPBACK_TIMEOUT = 10
77
+
78
+ # Timeout in seconds for network requests going to the internet. The timeout is
79
+ # short enough to prevent a test to wait for too long if the internet request
80
+ # is blocked for whatever reason.
81
+ #
82
+ # Usually, a timeout using INTERNET_TIMEOUT should not mark a test as failed,
83
+ # but skip the test instead: see transient_internet().
84
+ INTERNET_TIMEOUT = 60.0
85
+
86
+ # Timeout in seconds to mark a test as failed if the test takes "too long".
87
+ #
88
+ # The timeout value depends on the regrtest --timeout command line option.
89
+ #
90
+ # If a test using SHORT_TIMEOUT starts to fail randomly on slow buildbots, use
91
+ # LONG_TIMEOUT instead.
92
+ SHORT_TIMEOUT = 30.0
93
+
94
+ # Timeout in seconds to detect when a test hangs.
95
+ #
96
+ # It is long enough to reduce the risk of test failure on the slowest Python
97
+ # buildbots. It should not be used to mark a test as failed if the test takes
98
+ # "too long". The timeout value depends on the regrtest --timeout command line
99
+ # option.
100
+ LONG_TIMEOUT = 5 * 60.0
101
+
102
+
103
+ class Error(Exception):
104
+ """Base class for regression test exceptions."""
105
+
106
+ class TestFailed(Error):
107
+ """Test failed."""
108
+
109
+ class TestFailedWithDetails(TestFailed):
110
+ """Test failed."""
111
+ def __init__(self, msg, errors, failures):
112
+ self.msg = msg
113
+ self.errors = errors
114
+ self.failures = failures
115
+ super().__init__(msg, errors, failures)
116
+
117
+ def __str__(self):
118
+ return self.msg
119
+
120
+ class TestDidNotRun(Error):
121
+ """Test did not run any subtests."""
122
+
123
+ class ResourceDenied(unittest.SkipTest):
124
+ """Test skipped because it requested a disallowed resource.
125
+
126
+ This is raised when a test calls requires() for a resource that
127
+ has not be enabled. It is used to distinguish between expected
128
+ and unexpected skips.
129
+ """
130
+
131
+ def anticipate_failure(condition):
132
+ """Decorator to mark a test that is known to be broken in some cases
133
+
134
+ Any use of this decorator should have a comment identifying the
135
+ associated tracker issue.
136
+ """
137
+ if condition:
138
+ return unittest.expectedFailure
139
+ return lambda f: f
140
+
141
+ def load_package_tests(pkg_dir, loader, standard_tests, pattern):
142
+ """Generic load_tests implementation for simple test packages.
143
+
144
+ Most packages can implement load_tests using this function as follows:
145
+
146
+ def load_tests(*args):
147
+ return load_package_tests(os.path.dirname(__file__), *args)
148
+ """
149
+ if pattern is None:
150
+ pattern = "test*"
151
+ top_dir = os.path.dirname( # Lib
152
+ os.path.dirname( # test
153
+ os.path.dirname(__file__))) # support
154
+ package_tests = loader.discover(start_dir=pkg_dir,
155
+ top_level_dir=top_dir,
156
+ pattern=pattern)
157
+ standard_tests.addTests(package_tests)
158
+ return standard_tests
159
+
160
+
161
+ def get_attribute(obj, name):
162
+ """Get an attribute, raising SkipTest if AttributeError is raised."""
163
+ try:
164
+ attribute = getattr(obj, name)
165
+ except AttributeError:
166
+ raise unittest.SkipTest("object %r has no attribute %r" % (obj, name))
167
+ else:
168
+ return attribute
169
+
170
+ verbose = 1 # Flag set to 0 by regrtest.py
171
+ use_resources = None # Flag set to [] by regrtest.py
172
+ max_memuse = 0 # Disable bigmem tests (they will still be run with
173
+ # small sizes, to make sure they work.)
174
+ real_max_memuse = 0
175
+ junit_xml_list = None # list of testsuite XML elements
176
+ failfast = False
177
+
178
+ # _original_stdout is meant to hold stdout at the time regrtest began.
179
+ # This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
180
+ # The point is to have some flavor of stdout the user can actually see.
181
+ _original_stdout = None
182
+ def record_original_stdout(stdout):
183
+ global _original_stdout
184
+ _original_stdout = stdout
185
+
186
+ def get_original_stdout():
187
+ return _original_stdout or sys.stdout
188
+
189
+
190
+ def _force_run(path, func, *args):
191
+ try:
192
+ return func(*args)
193
+ except OSError as err:
194
+ if verbose >= 2:
195
+ print('%s: %s' % (err.__class__.__name__, err))
196
+ print('re-run %s%r' % (func.__name__, args))
197
+ os.chmod(path, stat.S_IRWXU)
198
+ return func(*args)
199
+
200
+
201
+ # Check whether a gui is actually available
202
+ def _is_gui_available():
203
+ if hasattr(_is_gui_available, 'result'):
204
+ return _is_gui_available.result
205
+ import platform
206
+ reason = None
207
+ if sys.platform.startswith('win') and platform.win32_is_iot():
208
+ reason = "gui is not available on Windows IoT Core"
209
+ elif sys.platform.startswith('win'):
210
+ # if Python is running as a service (such as the buildbot service),
211
+ # gui interaction may be disallowed
212
+ import ctypes
213
+ import ctypes.wintypes
214
+ UOI_FLAGS = 1
215
+ WSF_VISIBLE = 0x0001
216
+ class USEROBJECTFLAGS(ctypes.Structure):
217
+ _fields_ = [("fInherit", ctypes.wintypes.BOOL),
218
+ ("fReserved", ctypes.wintypes.BOOL),
219
+ ("dwFlags", ctypes.wintypes.DWORD)]
220
+ dll = ctypes.windll.user32
221
+ h = dll.GetProcessWindowStation()
222
+ if not h:
223
+ raise ctypes.WinError()
224
+ uof = USEROBJECTFLAGS()
225
+ needed = ctypes.wintypes.DWORD()
226
+ res = dll.GetUserObjectInformationW(h,
227
+ UOI_FLAGS,
228
+ ctypes.byref(uof),
229
+ ctypes.sizeof(uof),
230
+ ctypes.byref(needed))
231
+ if not res:
232
+ raise ctypes.WinError()
233
+ if not bool(uof.dwFlags & WSF_VISIBLE):
234
+ reason = "gui not available (WSF_VISIBLE flag not set)"
235
+ elif sys.platform == 'darwin':
236
+ # The Aqua Tk implementations on OS X can abort the process if
237
+ # being called in an environment where a window server connection
238
+ # cannot be made, for instance when invoked by a buildbot or ssh
239
+ # process not running under the same user id as the current console
240
+ # user. To avoid that, raise an exception if the window manager
241
+ # connection is not available.
242
+ from ctypes import cdll, c_int, pointer, Structure
243
+ from ctypes.util import find_library
244
+
245
+ app_services = cdll.LoadLibrary(find_library("ApplicationServices"))
246
+
247
+ if app_services.CGMainDisplayID() == 0:
248
+ reason = "gui tests cannot run without OS X window manager"
249
+ else:
250
+ class ProcessSerialNumber(Structure):
251
+ _fields_ = [("highLongOfPSN", c_int),
252
+ ("lowLongOfPSN", c_int)]
253
+ psn = ProcessSerialNumber()
254
+ psn_p = pointer(psn)
255
+ if ( (app_services.GetCurrentProcess(psn_p) < 0) or
256
+ (app_services.SetFrontProcess(psn_p) < 0) ):
257
+ reason = "cannot run without OS X gui process"
258
+
259
+ # check on every platform whether tkinter can actually do anything
260
+ if not reason:
261
+ try:
262
+ from tkinter import Tk
263
+ root = Tk()
264
+ root.withdraw()
265
+ root.update()
266
+ root.destroy()
267
+ except Exception as e:
268
+ err_string = str(e)
269
+ if len(err_string) > 50:
270
+ err_string = err_string[:50] + ' [...]'
271
+ reason = 'Tk unavailable due to {}: {}'.format(type(e).__name__,
272
+ err_string)
273
+
274
+ _is_gui_available.reason = reason
275
+ _is_gui_available.result = not reason
276
+
277
+ return _is_gui_available.result
278
+
279
+ def is_resource_enabled(resource):
280
+ """Test whether a resource is enabled.
281
+
282
+ Known resources are set by regrtest.py. If not running under regrtest.py,
283
+ all resources are assumed enabled unless use_resources has been set.
284
+ """
285
+ return use_resources is None or resource in use_resources
286
+
287
+ def requires(resource, msg=None):
288
+ """Raise ResourceDenied if the specified resource is not available."""
289
+ if not is_resource_enabled(resource):
290
+ if msg is None:
291
+ msg = "Use of the %r resource not enabled" % resource
292
+ raise ResourceDenied(msg)
293
+ if resource == 'gui' and not _is_gui_available():
294
+ raise ResourceDenied(_is_gui_available.reason)
295
+
296
+ def _get_kernel_version(sysname="Linux"):
297
+ import platform
298
+ if platform.system() != sysname:
299
+ return None
300
+ version_txt = platform.release().split('-', 1)[0]
301
+ try:
302
+ return tuple(map(int, version_txt.split('.')))
303
+ except ValueError:
304
+ return None
305
+
306
+ def _requires_unix_version(sysname, min_version):
307
+ """Decorator raising SkipTest if the OS is `sysname` and the version is less
308
+ than `min_version`.
309
+
310
+ For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if
311
+ the FreeBSD version is less than 7.2.
312
+ """
313
+ import platform
314
+ min_version_txt = '.'.join(map(str, min_version))
315
+ version_txt = platform.release().split('-', 1)[0]
316
+ if platform.system() == sysname:
317
+ try:
318
+ version = tuple(map(int, version_txt.split('.')))
319
+ except ValueError:
320
+ skip = False
321
+ else:
322
+ skip = version < min_version
323
+ else:
324
+ skip = False
325
+
326
+ return unittest.skipIf(
327
+ skip,
328
+ f"{sysname} version {min_version_txt} or higher required, not "
329
+ f"{version_txt}"
330
+ )
331
+
332
+
333
+ def requires_freebsd_version(*min_version):
334
+ """Decorator raising SkipTest if the OS is FreeBSD and the FreeBSD version is
335
+ less than `min_version`.
336
+
337
+ For example, @requires_freebsd_version(7, 2) raises SkipTest if the FreeBSD
338
+ version is less than 7.2.
339
+ """
340
+ return _requires_unix_version('FreeBSD', min_version)
341
+
342
+ def requires_linux_version(*min_version):
343
+ """Decorator raising SkipTest if the OS is Linux and the Linux version is
344
+ less than `min_version`.
345
+
346
+ For example, @requires_linux_version(2, 6, 32) raises SkipTest if the Linux
347
+ version is less than 2.6.32.
348
+ """
349
+ return _requires_unix_version('Linux', min_version)
350
+
351
+ def requires_mac_ver(*min_version):
352
+ """Decorator raising SkipTest if the OS is Mac OS X and the OS X
353
+ version if less than min_version.
354
+
355
+ For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
356
+ is lesser than 10.5.
357
+ """
358
+ def decorator(func):
359
+ @functools.wraps(func)
360
+ def wrapper(*args, **kw):
361
+ if sys.platform == 'darwin':
362
+ import platform
363
+ version_txt = platform.mac_ver()[0]
364
+ try:
365
+ version = tuple(map(int, version_txt.split('.')))
366
+ except ValueError:
367
+ pass
368
+ else:
369
+ if version < min_version:
370
+ min_version_txt = '.'.join(map(str, min_version))
371
+ raise unittest.SkipTest(
372
+ "Mac OS X %s or higher required, not %s"
373
+ % (min_version_txt, version_txt))
374
+ return func(*args, **kw)
375
+ wrapper.min_version = min_version
376
+ return wrapper
377
+ return decorator
378
+
379
+
380
+ def check_sanitizer(*, address=False, memory=False, ub=False):
381
+ """Returns True if Python is compiled with sanitizer support"""
382
+ if not (address or memory or ub):
383
+ raise ValueError('At least one of address, memory, or ub must be True')
384
+
385
+
386
+ _cflags = sysconfig.get_config_var('CFLAGS') or ''
387
+ _config_args = sysconfig.get_config_var('CONFIG_ARGS') or ''
388
+ memory_sanitizer = (
389
+ '-fsanitize=memory' in _cflags or
390
+ '--with-memory-sanitizer' in _config_args
391
+ )
392
+ address_sanitizer = (
393
+ '-fsanitize=address' in _cflags or
394
+ '--with-memory-sanitizer' in _config_args
395
+ )
396
+ ub_sanitizer = (
397
+ '-fsanitize=undefined' in _cflags or
398
+ '--with-undefined-behavior-sanitizer' in _config_args
399
+ )
400
+ return (
401
+ (memory and memory_sanitizer) or
402
+ (address and address_sanitizer) or
403
+ (ub and ub_sanitizer)
404
+ )
405
+
406
+
407
+ def skip_if_sanitizer(reason=None, *, address=False, memory=False, ub=False):
408
+ """Decorator raising SkipTest if running with a sanitizer active."""
409
+ if not reason:
410
+ reason = 'not working with sanitizers active'
411
+ skip = check_sanitizer(address=address, memory=memory, ub=ub)
412
+ return unittest.skipIf(skip, reason)
413
+
414
+
415
+ def system_must_validate_cert(f):
416
+ """Skip the test on TLS certificate validation failures."""
417
+ @functools.wraps(f)
418
+ def dec(*args, **kwargs):
419
+ try:
420
+ f(*args, **kwargs)
421
+ except OSError as e:
422
+ if "CERTIFICATE_VERIFY_FAILED" in str(e):
423
+ raise unittest.SkipTest("system does not contain "
424
+ "necessary certificates")
425
+ raise
426
+ return dec
427
+
428
+ # A constant likely larger than the underlying OS pipe buffer size, to
429
+ # make writes blocking.
430
+ # Windows limit seems to be around 512 B, and many Unix kernels have a
431
+ # 64 KiB pipe buffer size or 16 * PAGE_SIZE: take a few megs to be sure.
432
+ # (see issue #17835 for a discussion of this number).
433
+ PIPE_MAX_SIZE = 4 * 1024 * 1024 + 1
434
+
435
+ # A constant likely larger than the underlying OS socket buffer size, to make
436
+ # writes blocking.
437
+ # The socket buffer sizes can usually be tuned system-wide (e.g. through sysctl
438
+ # on Linux), or on a per-socket basis (SO_SNDBUF/SO_RCVBUF). See issue #18643
439
+ # for a discussion of this number.
440
+ SOCK_MAX_SIZE = 16 * 1024 * 1024 + 1
441
+
442
+ # decorator for skipping tests on non-IEEE 754 platforms
443
+ requires_IEEE_754 = unittest.skipUnless(
444
+ float.__getformat__("double").startswith("IEEE"),
445
+ "test requires IEEE 754 doubles")
446
+
447
+ def requires_zlib(reason='requires zlib'):
448
+ try:
449
+ import zlib
450
+ except ImportError:
451
+ zlib = None
452
+ return unittest.skipUnless(zlib, reason)
453
+
454
+ def requires_gzip(reason='requires gzip'):
455
+ try:
456
+ import gzip
457
+ except ImportError:
458
+ gzip = None
459
+ return unittest.skipUnless(gzip, reason)
460
+
461
+ def requires_bz2(reason='requires bz2'):
462
+ try:
463
+ import bz2
464
+ except ImportError:
465
+ bz2 = None
466
+ return unittest.skipUnless(bz2, reason)
467
+
468
+ def requires_lzma(reason='requires lzma'):
469
+ try:
470
+ import lzma
471
+ except ImportError:
472
+ lzma = None
473
+ return unittest.skipUnless(lzma, reason)
474
+
475
+ requires_legacy_unicode_capi = unittest.skipUnless(unicode_legacy_string,
476
+ 'requires legacy Unicode C API')
477
+
478
+ is_jython = sys.platform.startswith('java')
479
+
480
+ is_android = hasattr(sys, 'getandroidapilevel')
481
+
482
+ if sys.platform not in ('win32', 'vxworks'):
483
+ unix_shell = '/system/bin/sh' if is_android else '/bin/sh'
484
+ else:
485
+ unix_shell = None
486
+
487
+ # Define the URL of a dedicated HTTP server for the network tests.
488
+ # The URL must use clear-text HTTP: no redirection to encrypted HTTPS.
489
+ TEST_HTTP_URL = "http://www.pythontest.net"
490
+
491
+ # Set by libregrtest/main.py so we can skip tests that are not
492
+ # useful for PGO
493
+ PGO = False
494
+
495
+ # Set by libregrtest/main.py if we are running the extended (time consuming)
496
+ # PGO task. If this is True, PGO is also True.
497
+ PGO_EXTENDED = False
498
+
499
+ # TEST_HOME_DIR refers to the top level directory of the "test" package
500
+ # that contains Python's regression test suite
501
+ TEST_SUPPORT_DIR = os.path.dirname(os.path.abspath(__file__))
502
+ TEST_HOME_DIR = os.path.dirname(TEST_SUPPORT_DIR)
503
+
504
+ # TEST_DATA_DIR is used as a target download location for remote resources
505
+ TEST_DATA_DIR = os.path.join(TEST_HOME_DIR, "data")
506
+
507
+
508
+ def darwin_malloc_err_warning(test_name):
509
+ """Assure user that loud errors generated by macOS libc's malloc are
510
+ expected."""
511
+ if sys.platform != 'darwin':
512
+ return
513
+
514
+ import shutil
515
+ msg = ' NOTICE '
516
+ detail = (f'{test_name} may generate "malloc can\'t allocate region"\n'
517
+ 'warnings on macOS systems. This behavior is known. Do not\n'
518
+ 'report a bug unless tests are also failing. See bpo-40928.')
519
+
520
+ padding, _ = shutil.get_terminal_size()
521
+ print(msg.center(padding, '-'))
522
+ print(detail)
523
+ print('-' * padding)
524
+
525
+
526
+ def findfile(filename, subdir=None):
527
+ """Try to find a file on sys.path or in the test directory. If it is not
528
+ found the argument passed to the function is returned (this does not
529
+ necessarily signal failure; could still be the legitimate path).
530
+
531
+ Setting *subdir* indicates a relative path to use to find the file
532
+ rather than looking directly in the path directories.
533
+ """
534
+ if os.path.isabs(filename):
535
+ return filename
536
+ if subdir is not None:
537
+ filename = os.path.join(subdir, filename)
538
+ path = [TEST_HOME_DIR] + sys.path
539
+ for dn in path:
540
+ fn = os.path.join(dn, filename)
541
+ if os.path.exists(fn): return fn
542
+ return filename
543
+
544
+
545
+ def sortdict(dict):
546
+ "Like repr(dict), but in sorted order."
547
+ items = sorted(dict.items())
548
+ reprpairs = ["%r: %r" % pair for pair in items]
549
+ withcommas = ", ".join(reprpairs)
550
+ return "{%s}" % withcommas
551
+
552
+ def check_syntax_error(testcase, statement, errtext='', *, lineno=None, offset=None):
553
+ with testcase.assertRaisesRegex(SyntaxError, errtext) as cm:
554
+ compile(statement, '<test string>', 'exec')
555
+ err = cm.exception
556
+ testcase.assertIsNotNone(err.lineno)
557
+ if lineno is not None:
558
+ testcase.assertEqual(err.lineno, lineno)
559
+ testcase.assertIsNotNone(err.offset)
560
+ if offset is not None:
561
+ testcase.assertEqual(err.offset, offset)
562
+
563
+
564
+ def open_urlresource(url, *args, **kw):
565
+ import urllib.request, urllib.parse
566
+ from .os_helper import unlink
567
+ try:
568
+ import gzip
569
+ except ImportError:
570
+ gzip = None
571
+
572
+ check = kw.pop('check', None)
573
+
574
+ filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
575
+
576
+ fn = os.path.join(TEST_DATA_DIR, filename)
577
+
578
+ def check_valid_file(fn):
579
+ f = open(fn, *args, **kw)
580
+ if check is None:
581
+ return f
582
+ elif check(f):
583
+ f.seek(0)
584
+ return f
585
+ f.close()
586
+
587
+ if os.path.exists(fn):
588
+ f = check_valid_file(fn)
589
+ if f is not None:
590
+ return f
591
+ unlink(fn)
592
+
593
+ # Verify the requirement before downloading the file
594
+ requires('urlfetch')
595
+
596
+ if verbose:
597
+ print('\tfetching %s ...' % url, file=get_original_stdout())
598
+ opener = urllib.request.build_opener()
599
+ if gzip:
600
+ opener.addheaders.append(('Accept-Encoding', 'gzip'))
601
+ f = opener.open(url, timeout=INTERNET_TIMEOUT)
602
+ if gzip and f.headers.get('Content-Encoding') == 'gzip':
603
+ f = gzip.GzipFile(fileobj=f)
604
+ try:
605
+ with open(fn, "wb") as out:
606
+ s = f.read()
607
+ while s:
608
+ out.write(s)
609
+ s = f.read()
610
+ finally:
611
+ f.close()
612
+
613
+ f = check_valid_file(fn)
614
+ if f is not None:
615
+ return f
616
+ raise TestFailed('invalid resource %r' % fn)
617
+
618
+
619
+ @contextlib.contextmanager
620
+ def captured_output(stream_name):
621
+ """Return a context manager used by captured_stdout/stdin/stderr
622
+ that temporarily replaces the sys stream *stream_name* with a StringIO."""
623
+ import io
624
+ orig_stdout = getattr(sys, stream_name)
625
+ setattr(sys, stream_name, io.StringIO())
626
+ try:
627
+ yield getattr(sys, stream_name)
628
+ finally:
629
+ setattr(sys, stream_name, orig_stdout)
630
+
631
+ def captured_stdout():
632
+ """Capture the output of sys.stdout:
633
+
634
+ with captured_stdout() as stdout:
635
+ print("hello")
636
+ self.assertEqual(stdout.getvalue(), "hello\\n")
637
+ """
638
+ return captured_output("stdout")
639
+
640
+ def captured_stderr():
641
+ """Capture the output of sys.stderr:
642
+
643
+ with captured_stderr() as stderr:
644
+ print("hello", file=sys.stderr)
645
+ self.assertEqual(stderr.getvalue(), "hello\\n")
646
+ """
647
+ return captured_output("stderr")
648
+
649
+ def captured_stdin():
650
+ """Capture the input to sys.stdin:
651
+
652
+ with captured_stdin() as stdin:
653
+ stdin.write('hello\\n')
654
+ stdin.seek(0)
655
+ # call test code that consumes from sys.stdin
656
+ captured = input()
657
+ self.assertEqual(captured, "hello")
658
+ """
659
+ return captured_output("stdin")
660
+
661
+
662
+ def gc_collect():
663
+ """Force as many objects as possible to be collected.
664
+
665
+ In non-CPython implementations of Python, this is needed because timely
666
+ deallocation is not guaranteed by the garbage collector. (Even in CPython
667
+ this can be the case in case of reference cycles.) This means that __del__
668
+ methods may be called later than expected and weakrefs may remain alive for
669
+ longer than expected. This function tries its best to force all garbage
670
+ objects to disappear.
671
+ """
672
+ import gc
673
+ gc.collect()
674
+ if is_jython:
675
+ time.sleep(0.1)
676
+ gc.collect()
677
+ gc.collect()
678
+
679
+ @contextlib.contextmanager
680
+ def disable_gc():
681
+ import gc
682
+ have_gc = gc.isenabled()
683
+ gc.disable()
684
+ try:
685
+ yield
686
+ finally:
687
+ if have_gc:
688
+ gc.enable()
689
+
690
+
691
+ def python_is_optimized():
692
+ """Find if Python was built with optimizations."""
693
+ cflags = sysconfig.get_config_var('PY_CFLAGS') or ''
694
+ final_opt = ""
695
+ for opt in cflags.split():
696
+ if opt.startswith('-O'):
697
+ final_opt = opt
698
+ return final_opt not in ('', '-O0', '-Og')
699
+
700
+
701
+ _header = 'nP'
702
+ _align = '0n'
703
+ if hasattr(sys, "getobjects"):
704
+ _header = '2P' + _header
705
+ _align = '0P'
706
+ _vheader = _header + 'n'
707
+
708
+ def calcobjsize(fmt):
709
+ import struct
710
+ return struct.calcsize(_header + fmt + _align)
711
+
712
+ def calcvobjsize(fmt):
713
+ import struct
714
+ return struct.calcsize(_vheader + fmt + _align)
715
+
716
+
717
+ _TPFLAGS_HAVE_GC = 1<<14
718
+ _TPFLAGS_HEAPTYPE = 1<<9
719
+
720
+ def check_sizeof(test, o, size):
721
+ import _testinternalcapi
722
+ result = sys.getsizeof(o)
723
+ # add GC header size
724
+ if ((type(o) == type) and (o.__flags__ & _TPFLAGS_HEAPTYPE) or\
725
+ ((type(o) != type) and (type(o).__flags__ & _TPFLAGS_HAVE_GC))):
726
+ size += _testinternalcapi.SIZEOF_PYGC_HEAD
727
+ msg = 'wrong size for %s: got %d, expected %d' \
728
+ % (type(o), result, size)
729
+ test.assertEqual(result, size, msg)
730
+
731
+ def subTests(arg_names, arg_values, /, *, _do_cleanups=False):
732
+ """Run multiple subtests with different parameters.
733
+ """
734
+ single_param = False
735
+ if isinstance(arg_names, str):
736
+ arg_names = arg_names.replace(',',' ').split()
737
+ if len(arg_names) == 1:
738
+ single_param = True
739
+ arg_values = tuple(arg_values)
740
+ def decorator(func):
741
+ if isinstance(func, type):
742
+ raise TypeError('subTests() can only decorate methods, not classes')
743
+ @functools.wraps(func)
744
+ def wrapper(self, /, *args, **kwargs):
745
+ for values in arg_values:
746
+ if single_param:
747
+ values = (values,)
748
+ subtest_kwargs = dict(zip(arg_names, values))
749
+ with self.subTest(**subtest_kwargs):
750
+ func(self, *args, **kwargs, **subtest_kwargs)
751
+ if _do_cleanups:
752
+ self.doCleanups()
753
+ return wrapper
754
+ return decorator
755
+
756
+ #=======================================================================
757
+ # Decorator for running a function in a different locale, correctly resetting
758
+ # it afterwards.
759
+
760
+ @contextlib.contextmanager
761
+ def run_with_locale(catstr, *locales):
762
+ try:
763
+ import locale
764
+ category = getattr(locale, catstr)
765
+ orig_locale = locale.setlocale(category)
766
+ except AttributeError:
767
+ # if the test author gives us an invalid category string
768
+ raise
769
+ except:
770
+ # cannot retrieve original locale, so do nothing
771
+ locale = orig_locale = None
772
+ else:
773
+ for loc in locales:
774
+ try:
775
+ locale.setlocale(category, loc)
776
+ break
777
+ except:
778
+ pass
779
+
780
+ try:
781
+ yield
782
+ finally:
783
+ if locale and orig_locale:
784
+ locale.setlocale(category, orig_locale)
785
+
786
+ #=======================================================================
787
+ # Decorator for running a function in a specific timezone, correctly
788
+ # resetting it afterwards.
789
+
790
+ def run_with_tz(tz):
791
+ def decorator(func):
792
+ def inner(*args, **kwds):
793
+ try:
794
+ tzset = time.tzset
795
+ except AttributeError:
796
+ raise unittest.SkipTest("tzset required")
797
+ if 'TZ' in os.environ:
798
+ orig_tz = os.environ['TZ']
799
+ else:
800
+ orig_tz = None
801
+ os.environ['TZ'] = tz
802
+ tzset()
803
+
804
+ # now run the function, resetting the tz on exceptions
805
+ try:
806
+ return func(*args, **kwds)
807
+ finally:
808
+ if orig_tz is None:
809
+ del os.environ['TZ']
810
+ else:
811
+ os.environ['TZ'] = orig_tz
812
+ time.tzset()
813
+
814
+ inner.__name__ = func.__name__
815
+ inner.__doc__ = func.__doc__
816
+ return inner
817
+ return decorator
818
+
819
+ #=======================================================================
820
+ # Big-memory-test support. Separate from 'resources' because memory use
821
+ # should be configurable.
822
+
823
+ # Some handy shorthands. Note that these are used for byte-limits as well
824
+ # as size-limits, in the various bigmem tests
825
+ _1M = 1024*1024
826
+ _1G = 1024 * _1M
827
+ _2G = 2 * _1G
828
+ _4G = 4 * _1G
829
+
830
+ MAX_Py_ssize_t = sys.maxsize
831
+
832
+ def set_memlimit(limit):
833
+ global max_memuse
834
+ global real_max_memuse
835
+ sizes = {
836
+ 'k': 1024,
837
+ 'm': _1M,
838
+ 'g': _1G,
839
+ 't': 1024*_1G,
840
+ }
841
+ m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
842
+ re.IGNORECASE | re.VERBOSE)
843
+ if m is None:
844
+ raise ValueError('Invalid memory limit %r' % (limit,))
845
+ memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
846
+ real_max_memuse = memlimit
847
+ if memlimit > MAX_Py_ssize_t:
848
+ memlimit = MAX_Py_ssize_t
849
+ if memlimit < _2G - 1:
850
+ raise ValueError('Memory limit %r too low to be useful' % (limit,))
851
+ max_memuse = memlimit
852
+
853
+ class _MemoryWatchdog:
854
+ """An object which periodically watches the process' memory consumption
855
+ and prints it out.
856
+ """
857
+
858
+ def __init__(self):
859
+ self.procfile = '/proc/{pid}/statm'.format(pid=os.getpid())
860
+ self.started = False
861
+
862
+ def start(self):
863
+ import warnings
864
+ try:
865
+ f = open(self.procfile, 'r')
866
+ except OSError as e:
867
+ warnings.warn('/proc not available for stats: {}'.format(e),
868
+ RuntimeWarning)
869
+ sys.stderr.flush()
870
+ return
871
+
872
+ import subprocess
873
+ with f:
874
+ watchdog_script = findfile("memory_watchdog.py")
875
+ self.mem_watchdog = subprocess.Popen([sys.executable, watchdog_script],
876
+ stdin=f,
877
+ stderr=subprocess.DEVNULL)
878
+ self.started = True
879
+
880
+ def stop(self):
881
+ if self.started:
882
+ self.mem_watchdog.terminate()
883
+ self.mem_watchdog.wait()
884
+
885
+
886
+ def bigmemtest(size, memuse, dry_run=True):
887
+ """Decorator for bigmem tests.
888
+
889
+ 'size' is a requested size for the test (in arbitrary, test-interpreted
890
+ units.) 'memuse' is the number of bytes per unit for the test, or a good
891
+ estimate of it. For example, a test that needs two byte buffers, of 4 GiB
892
+ each, could be decorated with @bigmemtest(size=_4G, memuse=2).
893
+
894
+ The 'size' argument is normally passed to the decorated test method as an
895
+ extra argument. If 'dry_run' is true, the value passed to the test method
896
+ may be less than the requested value. If 'dry_run' is false, it means the
897
+ test doesn't support dummy runs when -M is not specified.
898
+ """
899
+ def decorator(f):
900
+ def wrapper(self):
901
+ size = wrapper.size
902
+ memuse = wrapper.memuse
903
+ if not real_max_memuse:
904
+ maxsize = 5147
905
+ else:
906
+ maxsize = size
907
+
908
+ if ((real_max_memuse or not dry_run)
909
+ and real_max_memuse < maxsize * memuse):
910
+ raise unittest.SkipTest(
911
+ "not enough memory: %.1fG minimum needed"
912
+ % (size * memuse / (1024 ** 3)))
913
+
914
+ if real_max_memuse and verbose:
915
+ print()
916
+ print(" ... expected peak memory use: {peak:.1f}G"
917
+ .format(peak=size * memuse / (1024 ** 3)))
918
+ watchdog = _MemoryWatchdog()
919
+ watchdog.start()
920
+ else:
921
+ watchdog = None
922
+
923
+ try:
924
+ return f(self, maxsize)
925
+ finally:
926
+ if watchdog:
927
+ watchdog.stop()
928
+
929
+ wrapper.size = size
930
+ wrapper.memuse = memuse
931
+ return wrapper
932
+ return decorator
933
+
934
+ def bigaddrspacetest(f):
935
+ """Decorator for tests that fill the address space."""
936
+ def wrapper(self):
937
+ if max_memuse < MAX_Py_ssize_t:
938
+ if MAX_Py_ssize_t >= 2**63 - 1 and max_memuse >= 2**31:
939
+ raise unittest.SkipTest(
940
+ "not enough memory: try a 32-bit build instead")
941
+ else:
942
+ raise unittest.SkipTest(
943
+ "not enough memory: %.1fG minimum needed"
944
+ % (MAX_Py_ssize_t / (1024 ** 3)))
945
+ else:
946
+ return f(self)
947
+ return wrapper
948
+
949
+ #=======================================================================
950
+ # unittest integration.
951
+
952
+ class BasicTestRunner:
953
+ def run(self, test):
954
+ result = unittest.TestResult()
955
+ test(result)
956
+ return result
957
+
958
+ def _id(obj):
959
+ return obj
960
+
961
+ def requires_resource(resource):
962
+ if resource == 'gui' and not _is_gui_available():
963
+ return unittest.skip(_is_gui_available.reason)
964
+ if is_resource_enabled(resource):
965
+ return _id
966
+ else:
967
+ return unittest.skip("resource {0!r} is not enabled".format(resource))
968
+
969
+ def cpython_only(test):
970
+ """
971
+ Decorator for tests only applicable on CPython.
972
+ """
973
+ return impl_detail(cpython=True)(test)
974
+
975
+ def impl_detail(msg=None, **guards):
976
+ if check_impl_detail(**guards):
977
+ return _id
978
+ if msg is None:
979
+ guardnames, default = _parse_guards(guards)
980
+ if default:
981
+ msg = "implementation detail not available on {0}"
982
+ else:
983
+ msg = "implementation detail specific to {0}"
984
+ guardnames = sorted(guardnames.keys())
985
+ msg = msg.format(' or '.join(guardnames))
986
+ return unittest.skip(msg)
987
+
988
+ def _parse_guards(guards):
989
+ # Returns a tuple ({platform_name: run_me}, default_value)
990
+ if not guards:
991
+ return ({'cpython': True}, False)
992
+ is_true = list(guards.values())[0]
993
+ assert list(guards.values()) == [is_true] * len(guards) # all True or all False
994
+ return (guards, not is_true)
995
+
996
+ # Use the following check to guard CPython's implementation-specific tests --
997
+ # or to run them only on the implementation(s) guarded by the arguments.
998
+ def check_impl_detail(**guards):
999
+ """This function returns True or False depending on the host platform.
1000
+ Examples:
1001
+ if check_impl_detail(): # only on CPython (default)
1002
+ if check_impl_detail(jython=True): # only on Jython
1003
+ if check_impl_detail(cpython=False): # everywhere except on CPython
1004
+ """
1005
+ guards, default = _parse_guards(guards)
1006
+ return guards.get(sys.implementation.name, default)
1007
+
1008
+
1009
+ def no_tracing(func):
1010
+ """Decorator to temporarily turn off tracing for the duration of a test."""
1011
+ if not hasattr(sys, 'gettrace'):
1012
+ return func
1013
+ else:
1014
+ @functools.wraps(func)
1015
+ def wrapper(*args, **kwargs):
1016
+ original_trace = sys.gettrace()
1017
+ try:
1018
+ sys.settrace(None)
1019
+ return func(*args, **kwargs)
1020
+ finally:
1021
+ sys.settrace(original_trace)
1022
+ return wrapper
1023
+
1024
+
1025
+ def refcount_test(test):
1026
+ """Decorator for tests which involve reference counting.
1027
+
1028
+ To start, the decorator does not run the test if is not run by CPython.
1029
+ After that, any trace function is unset during the test to prevent
1030
+ unexpected refcounts caused by the trace function.
1031
+
1032
+ """
1033
+ return no_tracing(cpython_only(test))
1034
+
1035
+
1036
+ def _filter_suite(suite, pred):
1037
+ """Recursively filter test cases in a suite based on a predicate."""
1038
+ newtests = []
1039
+ for test in suite._tests:
1040
+ if isinstance(test, unittest.TestSuite):
1041
+ _filter_suite(test, pred)
1042
+ newtests.append(test)
1043
+ else:
1044
+ if pred(test):
1045
+ newtests.append(test)
1046
+ suite._tests = newtests
1047
+
1048
+ def _run_suite(suite):
1049
+ """Run tests from a unittest.TestSuite-derived class."""
1050
+ runner = get_test_runner(sys.stdout,
1051
+ verbosity=verbose,
1052
+ capture_output=(junit_xml_list is not None))
1053
+
1054
+ result = runner.run(suite)
1055
+
1056
+ if junit_xml_list is not None:
1057
+ junit_xml_list.append(result.get_xml_element())
1058
+
1059
+ if not result.testsRun and not result.skipped:
1060
+ raise TestDidNotRun
1061
+ if not result.wasSuccessful():
1062
+ if len(result.errors) == 1 and not result.failures:
1063
+ err = result.errors[0][1]
1064
+ elif len(result.failures) == 1 and not result.errors:
1065
+ err = result.failures[0][1]
1066
+ else:
1067
+ err = "multiple errors occurred"
1068
+ if not verbose: err += "; run in verbose mode for details"
1069
+ errors = [(str(tc), exc_str) for tc, exc_str in result.errors]
1070
+ failures = [(str(tc), exc_str) for tc, exc_str in result.failures]
1071
+ raise TestFailedWithDetails(err, errors, failures)
1072
+
1073
+
1074
+ # By default, don't filter tests
1075
+ _match_test_func = None
1076
+
1077
+ _accept_test_patterns = None
1078
+ _ignore_test_patterns = None
1079
+
1080
+
1081
+ def match_test(test):
1082
+ # Function used by support.run_unittest() and regrtest --list-cases
1083
+ if _match_test_func is None:
1084
+ return True
1085
+ else:
1086
+ return _match_test_func(test.id())
1087
+
1088
+
1089
+ def _is_full_match_test(pattern):
1090
+ # If a pattern contains at least one dot, it's considered
1091
+ # as a full test identifier.
1092
+ # Example: 'test.test_os.FileTests.test_access'.
1093
+ #
1094
+ # ignore patterns which contain fnmatch patterns: '*', '?', '[...]'
1095
+ # or '[!...]'. For example, ignore 'test_access*'.
1096
+ return ('.' in pattern) and (not re.search(r'[?*\[\]]', pattern))
1097
+
1098
+
1099
+ def set_match_tests(accept_patterns=None, ignore_patterns=None):
1100
+ global _match_test_func, _accept_test_patterns, _ignore_test_patterns
1101
+
1102
+
1103
+ if accept_patterns is None:
1104
+ accept_patterns = ()
1105
+ if ignore_patterns is None:
1106
+ ignore_patterns = ()
1107
+
1108
+ accept_func = ignore_func = None
1109
+
1110
+ if accept_patterns != _accept_test_patterns:
1111
+ accept_patterns, accept_func = _compile_match_function(accept_patterns)
1112
+ if ignore_patterns != _ignore_test_patterns:
1113
+ ignore_patterns, ignore_func = _compile_match_function(ignore_patterns)
1114
+
1115
+ # Create a copy since patterns can be mutable and so modified later
1116
+ _accept_test_patterns = tuple(accept_patterns)
1117
+ _ignore_test_patterns = tuple(ignore_patterns)
1118
+
1119
+ if accept_func is not None or ignore_func is not None:
1120
+ def match_function(test_id):
1121
+ accept = True
1122
+ ignore = False
1123
+ if accept_func:
1124
+ accept = accept_func(test_id)
1125
+ if ignore_func:
1126
+ ignore = ignore_func(test_id)
1127
+ return accept and not ignore
1128
+
1129
+ _match_test_func = match_function
1130
+
1131
+
1132
+ def _compile_match_function(patterns):
1133
+ if not patterns:
1134
+ func = None
1135
+ # set_match_tests(None) behaves as set_match_tests(())
1136
+ patterns = ()
1137
+ elif all(map(_is_full_match_test, patterns)):
1138
+ # Simple case: all patterns are full test identifier.
1139
+ # The test.bisect_cmd utility only uses such full test identifiers.
1140
+ func = set(patterns).__contains__
1141
+ else:
1142
+ import fnmatch
1143
+ regex = '|'.join(map(fnmatch.translate, patterns))
1144
+ # The search *is* case sensitive on purpose:
1145
+ # don't use flags=re.IGNORECASE
1146
+ regex_match = re.compile(regex).match
1147
+
1148
+ def match_test_regex(test_id):
1149
+ if regex_match(test_id):
1150
+ # The regex matches the whole identifier, for example
1151
+ # 'test.test_os.FileTests.test_access'.
1152
+ return True
1153
+ else:
1154
+ # Try to match parts of the test identifier.
1155
+ # For example, split 'test.test_os.FileTests.test_access'
1156
+ # into: 'test', 'test_os', 'FileTests' and 'test_access'.
1157
+ return any(map(regex_match, test_id.split(".")))
1158
+
1159
+ func = match_test_regex
1160
+
1161
+ return patterns, func
1162
+
1163
+
1164
+ def run_unittest(*classes):
1165
+ """Run tests from unittest.TestCase-derived classes."""
1166
+ valid_types = (unittest.TestSuite, unittest.TestCase)
1167
+ suite = unittest.TestSuite()
1168
+ for cls in classes:
1169
+ if isinstance(cls, str):
1170
+ if cls in sys.modules:
1171
+ suite.addTest(unittest.findTestCases(sys.modules[cls]))
1172
+ else:
1173
+ raise ValueError("str arguments must be keys in sys.modules")
1174
+ elif isinstance(cls, valid_types):
1175
+ suite.addTest(cls)
1176
+ else:
1177
+ suite.addTest(unittest.makeSuite(cls))
1178
+ _filter_suite(suite, match_test)
1179
+ _run_suite(suite)
1180
+
1181
+ #=======================================================================
1182
+ # Check for the presence of docstrings.
1183
+
1184
+ # Rather than trying to enumerate all the cases where docstrings may be
1185
+ # disabled, we just check for that directly
1186
+
1187
+ def _check_docstrings():
1188
+ """Just used to check if docstrings are enabled"""
1189
+
1190
+ MISSING_C_DOCSTRINGS = (check_impl_detail() and
1191
+ sys.platform != 'win32' and
1192
+ not sysconfig.get_config_var('WITH_DOC_STRINGS'))
1193
+
1194
+ HAVE_DOCSTRINGS = (_check_docstrings.__doc__ is not None and
1195
+ not MISSING_C_DOCSTRINGS)
1196
+
1197
+ requires_docstrings = unittest.skipUnless(HAVE_DOCSTRINGS,
1198
+ "test requires docstrings")
1199
+
1200
+
1201
+ #=======================================================================
1202
+ # doctest driver.
1203
+
1204
+ def run_doctest(module, verbosity=None, optionflags=0):
1205
+ """Run doctest on the given module. Return (#failures, #tests).
1206
+
1207
+ If optional argument verbosity is not specified (or is None), pass
1208
+ support's belief about verbosity on to doctest. Else doctest's
1209
+ usual behavior is used (it searches sys.argv for -v).
1210
+ """
1211
+
1212
+ import doctest
1213
+
1214
+ if verbosity is None:
1215
+ verbosity = verbose
1216
+ else:
1217
+ verbosity = None
1218
+
1219
+ f, t = doctest.testmod(module, verbose=verbosity, optionflags=optionflags)
1220
+ if f:
1221
+ raise TestFailed("%d of %d doctests failed" % (f, t))
1222
+ if verbose:
1223
+ print('doctest (%s) ... %d tests with zero failures' %
1224
+ (module.__name__, t))
1225
+ return f, t
1226
+
1227
+
1228
+ #=======================================================================
1229
+ # Support for saving and restoring the imported modules.
1230
+
1231
+ def print_warning(msg):
1232
+ # bpo-39983: Print into sys.__stderr__ to display the warning even
1233
+ # when sys.stderr is captured temporarily by a test
1234
+ for line in msg.splitlines():
1235
+ print(f"Warning -- {line}", file=sys.__stderr__, flush=True)
1236
+
1237
+
1238
+ # Flag used by saved_test_environment of test.libregrtest.save_env,
1239
+ # to check if a test modified the environment. The flag should be set to False
1240
+ # before running a new test.
1241
+ #
1242
+ # For example, threading_helper.threading_cleanup() sets the flag is the function fails
1243
+ # to cleanup threads.
1244
+ environment_altered = False
1245
+
1246
+ def reap_children():
1247
+ """Use this function at the end of test_main() whenever sub-processes
1248
+ are started. This will help ensure that no extra children (zombies)
1249
+ stick around to hog resources and create problems when looking
1250
+ for refleaks.
1251
+ """
1252
+ global environment_altered
1253
+
1254
+ # Need os.waitpid(-1, os.WNOHANG): Windows is not supported
1255
+ if not (hasattr(os, 'waitpid') and hasattr(os, 'WNOHANG')):
1256
+ return
1257
+
1258
+ # Reap all our dead child processes so we don't leave zombies around.
1259
+ # These hog resources and might be causing some of the buildbots to die.
1260
+ while True:
1261
+ try:
1262
+ # Read the exit status of any child process which already completed
1263
+ pid, status = os.waitpid(-1, os.WNOHANG)
1264
+ except OSError:
1265
+ break
1266
+
1267
+ if pid == 0:
1268
+ break
1269
+
1270
+ print_warning(f"reap_children() reaped child process {pid}")
1271
+ environment_altered = True
1272
+
1273
+
1274
+ @contextlib.contextmanager
1275
+ def swap_attr(obj, attr, new_val):
1276
+ """Temporary swap out an attribute with a new object.
1277
+
1278
+ Usage:
1279
+ with swap_attr(obj, "attr", 5):
1280
+ ...
1281
+
1282
+ This will set obj.attr to 5 for the duration of the with: block,
1283
+ restoring the old value at the end of the block. If `attr` doesn't
1284
+ exist on `obj`, it will be created and then deleted at the end of the
1285
+ block.
1286
+
1287
+ The old value (or None if it doesn't exist) will be assigned to the
1288
+ target of the "as" clause, if there is one.
1289
+ """
1290
+ if hasattr(obj, attr):
1291
+ real_val = getattr(obj, attr)
1292
+ setattr(obj, attr, new_val)
1293
+ try:
1294
+ yield real_val
1295
+ finally:
1296
+ setattr(obj, attr, real_val)
1297
+ else:
1298
+ setattr(obj, attr, new_val)
1299
+ try:
1300
+ yield
1301
+ finally:
1302
+ if hasattr(obj, attr):
1303
+ delattr(obj, attr)
1304
+
1305
+ @contextlib.contextmanager
1306
+ def swap_item(obj, item, new_val):
1307
+ """Temporary swap out an item with a new object.
1308
+
1309
+ Usage:
1310
+ with swap_item(obj, "item", 5):
1311
+ ...
1312
+
1313
+ This will set obj["item"] to 5 for the duration of the with: block,
1314
+ restoring the old value at the end of the block. If `item` doesn't
1315
+ exist on `obj`, it will be created and then deleted at the end of the
1316
+ block.
1317
+
1318
+ The old value (or None if it doesn't exist) will be assigned to the
1319
+ target of the "as" clause, if there is one.
1320
+ """
1321
+ if item in obj:
1322
+ real_val = obj[item]
1323
+ obj[item] = new_val
1324
+ try:
1325
+ yield real_val
1326
+ finally:
1327
+ obj[item] = real_val
1328
+ else:
1329
+ obj[item] = new_val
1330
+ try:
1331
+ yield
1332
+ finally:
1333
+ if item in obj:
1334
+ del obj[item]
1335
+
1336
+ def args_from_interpreter_flags():
1337
+ """Return a list of command-line arguments reproducing the current
1338
+ settings in sys.flags and sys.warnoptions."""
1339
+ import subprocess
1340
+ return subprocess._args_from_interpreter_flags()
1341
+
1342
+ def optim_args_from_interpreter_flags():
1343
+ """Return a list of command-line arguments reproducing the current
1344
+ optimization settings in sys.flags."""
1345
+ import subprocess
1346
+ return subprocess._optim_args_from_interpreter_flags()
1347
+
1348
+
1349
+ class Matcher(object):
1350
+
1351
+ _partial_matches = ('msg', 'message')
1352
+
1353
+ def matches(self, d, **kwargs):
1354
+ """
1355
+ Try to match a single dict with the supplied arguments.
1356
+
1357
+ Keys whose values are strings and which are in self._partial_matches
1358
+ will be checked for partial (i.e. substring) matches. You can extend
1359
+ this scheme to (for example) do regular expression matching, etc.
1360
+ """
1361
+ result = True
1362
+ for k in kwargs:
1363
+ v = kwargs[k]
1364
+ dv = d.get(k)
1365
+ if not self.match_value(k, dv, v):
1366
+ result = False
1367
+ break
1368
+ return result
1369
+
1370
+ def match_value(self, k, dv, v):
1371
+ """
1372
+ Try to match a single stored value (dv) with a supplied value (v).
1373
+ """
1374
+ if type(v) != type(dv):
1375
+ result = False
1376
+ elif type(dv) is not str or k not in self._partial_matches:
1377
+ result = (v == dv)
1378
+ else:
1379
+ result = dv.find(v) >= 0
1380
+ return result
1381
+
1382
+
1383
+ _buggy_ucrt = None
1384
+ def skip_if_buggy_ucrt_strfptime(test):
1385
+ """
1386
+ Skip decorator for tests that use buggy strptime/strftime
1387
+
1388
+ If the UCRT bugs are present time.localtime().tm_zone will be
1389
+ an empty string, otherwise we assume the UCRT bugs are fixed
1390
+
1391
+ See bpo-37552 [Windows] strptime/strftime return invalid
1392
+ results with UCRT version 17763.615
1393
+ """
1394
+ import locale
1395
+ global _buggy_ucrt
1396
+ if _buggy_ucrt is None:
1397
+ if(sys.platform == 'win32' and
1398
+ locale.getdefaultlocale()[1] == 'cp65001' and
1399
+ time.localtime().tm_zone == ''):
1400
+ _buggy_ucrt = True
1401
+ else:
1402
+ _buggy_ucrt = False
1403
+ return unittest.skip("buggy MSVC UCRT strptime/strftime")(test) if _buggy_ucrt else test
1404
+
1405
+ class PythonSymlink:
1406
+ """Creates a symlink for the current Python executable"""
1407
+ def __init__(self, link=None):
1408
+ from .os_helper import TESTFN
1409
+
1410
+ self.link = link or os.path.abspath(TESTFN)
1411
+ self._linked = []
1412
+ self.real = os.path.realpath(sys.executable)
1413
+ self._also_link = []
1414
+
1415
+ self._env = None
1416
+
1417
+ self._platform_specific()
1418
+
1419
+ if sys.platform == "win32":
1420
+ def _platform_specific(self):
1421
+ import glob
1422
+ import _winapi
1423
+
1424
+ if os.path.lexists(self.real) and not os.path.exists(self.real):
1425
+ # App symlink appears to not exist, but we want the
1426
+ # real executable here anyway
1427
+ self.real = _winapi.GetModuleFileName(0)
1428
+
1429
+ dll = _winapi.GetModuleFileName(sys.dllhandle)
1430
+ src_dir = os.path.dirname(dll)
1431
+ dest_dir = os.path.dirname(self.link)
1432
+ self._also_link.append((
1433
+ dll,
1434
+ os.path.join(dest_dir, os.path.basename(dll))
1435
+ ))
1436
+ for runtime in glob.glob(os.path.join(glob.escape(src_dir), "vcruntime*.dll")):
1437
+ self._also_link.append((
1438
+ runtime,
1439
+ os.path.join(dest_dir, os.path.basename(runtime))
1440
+ ))
1441
+
1442
+ self._env = {k.upper(): os.getenv(k) for k in os.environ}
1443
+ self._env["PYTHONHOME"] = os.path.dirname(self.real)
1444
+ if sysconfig.is_python_build(True):
1445
+ self._env["PYTHONPATH"] = os.path.dirname(os.__file__)
1446
+ else:
1447
+ def _platform_specific(self):
1448
+ pass
1449
+
1450
+ def __enter__(self):
1451
+ os.symlink(self.real, self.link)
1452
+ self._linked.append(self.link)
1453
+ for real, link in self._also_link:
1454
+ os.symlink(real, link)
1455
+ self._linked.append(link)
1456
+ return self
1457
+
1458
+ def __exit__(self, exc_type, exc_value, exc_tb):
1459
+ for link in self._linked:
1460
+ try:
1461
+ os.remove(link)
1462
+ except IOError as ex:
1463
+ if verbose:
1464
+ print("failed to clean up {}: {}".format(link, ex))
1465
+
1466
+ def _call(self, python, args, env, returncode):
1467
+ import subprocess
1468
+ cmd = [python, *args]
1469
+ p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
1470
+ stderr=subprocess.PIPE, env=env)
1471
+ r = p.communicate()
1472
+ if p.returncode != returncode:
1473
+ if verbose:
1474
+ print(repr(r[0]))
1475
+ print(repr(r[1]), file=sys.stderr)
1476
+ raise RuntimeError(
1477
+ 'unexpected return code: {0} (0x{0:08X})'.format(p.returncode))
1478
+ return r
1479
+
1480
+ def call_real(self, *args, returncode=0):
1481
+ return self._call(self.real, args, None, returncode)
1482
+
1483
+ def call_link(self, *args, returncode=0):
1484
+ return self._call(self.link, args, self._env, returncode)
1485
+
1486
+
1487
+ def skip_if_pgo_task(test):
1488
+ """Skip decorator for tests not run in (non-extended) PGO task"""
1489
+ ok = not PGO or PGO_EXTENDED
1490
+ msg = "Not run for (non-extended) PGO task"
1491
+ return test if ok else unittest.skip(msg)(test)
1492
+
1493
+
1494
+ def detect_api_mismatch(ref_api, other_api, *, ignore=()):
1495
+ """Returns the set of items in ref_api not in other_api, except for a
1496
+ defined list of items to be ignored in this check.
1497
+
1498
+ By default this skips private attributes beginning with '_' but
1499
+ includes all magic methods, i.e. those starting and ending in '__'.
1500
+ """
1501
+ missing_items = set(dir(ref_api)) - set(dir(other_api))
1502
+ if ignore:
1503
+ missing_items -= set(ignore)
1504
+ missing_items = set(m for m in missing_items
1505
+ if not m.startswith('_') or m.endswith('__'))
1506
+ return missing_items
1507
+
1508
+
1509
+ def check__all__(test_case, module, name_of_module=None, extra=(),
1510
+ not_exported=()):
1511
+ """Assert that the __all__ variable of 'module' contains all public names.
1512
+
1513
+ The module's public names (its API) are detected automatically based on
1514
+ whether they match the public name convention and were defined in
1515
+ 'module'.
1516
+
1517
+ The 'name_of_module' argument can specify (as a string or tuple thereof)
1518
+ what module(s) an API could be defined in in order to be detected as a
1519
+ public API. One case for this is when 'module' imports part of its public
1520
+ API from other modules, possibly a C backend (like 'csv' and its '_csv').
1521
+
1522
+ The 'extra' argument can be a set of names that wouldn't otherwise be
1523
+ automatically detected as "public", like objects without a proper
1524
+ '__module__' attribute. If provided, it will be added to the
1525
+ automatically detected ones.
1526
+
1527
+ The 'not_exported' argument can be a set of names that must not be treated
1528
+ as part of the public API even though their names indicate otherwise.
1529
+
1530
+ Usage:
1531
+ import bar
1532
+ import foo
1533
+ import unittest
1534
+ from test import support
1535
+
1536
+ class MiscTestCase(unittest.TestCase):
1537
+ def test__all__(self):
1538
+ support.check__all__(self, foo)
1539
+
1540
+ class OtherTestCase(unittest.TestCase):
1541
+ def test__all__(self):
1542
+ extra = {'BAR_CONST', 'FOO_CONST'}
1543
+ not_exported = {'baz'} # Undocumented name.
1544
+ # bar imports part of its API from _bar.
1545
+ support.check__all__(self, bar, ('bar', '_bar'),
1546
+ extra=extra, not_exported=not_exported)
1547
+
1548
+ """
1549
+
1550
+ if name_of_module is None:
1551
+ name_of_module = (module.__name__, )
1552
+ elif isinstance(name_of_module, str):
1553
+ name_of_module = (name_of_module, )
1554
+
1555
+ expected = set(extra)
1556
+
1557
+ for name in dir(module):
1558
+ if name.startswith('_') or name in not_exported:
1559
+ continue
1560
+ obj = getattr(module, name)
1561
+ if (getattr(obj, '__module__', None) in name_of_module or
1562
+ (not hasattr(obj, '__module__') and
1563
+ not isinstance(obj, types.ModuleType))):
1564
+ expected.add(name)
1565
+ test_case.assertCountEqual(module.__all__, expected)
1566
+
1567
+
1568
+ def suppress_msvcrt_asserts(verbose=False):
1569
+ try:
1570
+ import msvcrt
1571
+ except ImportError:
1572
+ return
1573
+
1574
+ msvcrt.SetErrorMode(msvcrt.SEM_FAILCRITICALERRORS
1575
+ | msvcrt.SEM_NOALIGNMENTFAULTEXCEPT
1576
+ | msvcrt.SEM_NOGPFAULTERRORBOX
1577
+ | msvcrt.SEM_NOOPENFILEERRORBOX)
1578
+
1579
+ # CrtSetReportMode() is only available in debug build
1580
+ if hasattr(msvcrt, 'CrtSetReportMode'):
1581
+ for m in [msvcrt.CRT_WARN, msvcrt.CRT_ERROR, msvcrt.CRT_ASSERT]:
1582
+ if verbose:
1583
+ msvcrt.CrtSetReportMode(m, msvcrt.CRTDBG_MODE_FILE)
1584
+ msvcrt.CrtSetReportFile(m, msvcrt.CRTDBG_FILE_STDERR)
1585
+ else:
1586
+ msvcrt.CrtSetReportMode(m, 0)
1587
+
1588
+
1589
+ class SuppressCrashReport:
1590
+ """Try to prevent a crash report from popping up.
1591
+
1592
+ On Windows, don't display the Windows Error Reporting dialog. On UNIX,
1593
+ disable the creation of coredump file.
1594
+ """
1595
+ old_value = None
1596
+ old_modes = None
1597
+
1598
+ def __enter__(self):
1599
+ """On Windows, disable Windows Error Reporting dialogs using
1600
+ SetErrorMode() and CrtSetReportMode().
1601
+
1602
+ On UNIX, try to save the previous core file size limit, then set
1603
+ soft limit to 0.
1604
+ """
1605
+ if sys.platform.startswith('win'):
1606
+ # see http://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx
1607
+ try:
1608
+ import msvcrt
1609
+ except ImportError:
1610
+ return
1611
+
1612
+ self.old_value = msvcrt.GetErrorMode()
1613
+
1614
+ msvcrt.SetErrorMode(self.old_value | msvcrt.SEM_NOGPFAULTERRORBOX)
1615
+
1616
+ # bpo-23314: Suppress assert dialogs in debug builds.
1617
+ # CrtSetReportMode() is only available in debug build.
1618
+ if hasattr(msvcrt, 'CrtSetReportMode'):
1619
+ self.old_modes = {}
1620
+ for report_type in [msvcrt.CRT_WARN,
1621
+ msvcrt.CRT_ERROR,
1622
+ msvcrt.CRT_ASSERT]:
1623
+ old_mode = msvcrt.CrtSetReportMode(report_type,
1624
+ msvcrt.CRTDBG_MODE_FILE)
1625
+ old_file = msvcrt.CrtSetReportFile(report_type,
1626
+ msvcrt.CRTDBG_FILE_STDERR)
1627
+ self.old_modes[report_type] = old_mode, old_file
1628
+
1629
+ else:
1630
+ try:
1631
+ import resource
1632
+ self.resource = resource
1633
+ except ImportError:
1634
+ self.resource = None
1635
+ if self.resource is not None:
1636
+ try:
1637
+ self.old_value = self.resource.getrlimit(self.resource.RLIMIT_CORE)
1638
+ self.resource.setrlimit(self.resource.RLIMIT_CORE,
1639
+ (0, self.old_value[1]))
1640
+ except (ValueError, OSError):
1641
+ pass
1642
+
1643
+ if sys.platform == 'darwin':
1644
+ import subprocess
1645
+ # Check if the 'Crash Reporter' on OSX was configured
1646
+ # in 'Developer' mode and warn that it will get triggered
1647
+ # when it is.
1648
+ #
1649
+ # This assumes that this context manager is used in tests
1650
+ # that might trigger the next manager.
1651
+ cmd = ['/usr/bin/defaults', 'read',
1652
+ 'com.apple.CrashReporter', 'DialogType']
1653
+ proc = subprocess.Popen(cmd,
1654
+ stdout=subprocess.PIPE,
1655
+ stderr=subprocess.PIPE)
1656
+ with proc:
1657
+ stdout = proc.communicate()[0]
1658
+ if stdout.strip() == b'developer':
1659
+ print("this test triggers the Crash Reporter, "
1660
+ "that is intentional", end='', flush=True)
1661
+
1662
+ return self
1663
+
1664
+ def __exit__(self, *ignore_exc):
1665
+ """Restore Windows ErrorMode or core file behavior to initial value."""
1666
+ if self.old_value is None:
1667
+ return
1668
+
1669
+ if sys.platform.startswith('win'):
1670
+ import msvcrt
1671
+ msvcrt.SetErrorMode(self.old_value)
1672
+
1673
+ if self.old_modes:
1674
+ for report_type, (old_mode, old_file) in self.old_modes.items():
1675
+ msvcrt.CrtSetReportMode(report_type, old_mode)
1676
+ msvcrt.CrtSetReportFile(report_type, old_file)
1677
+ else:
1678
+ if self.resource is not None:
1679
+ try:
1680
+ self.resource.setrlimit(self.resource.RLIMIT_CORE, self.old_value)
1681
+ except (ValueError, OSError):
1682
+ pass
1683
+
1684
+
1685
+ def patch(test_instance, object_to_patch, attr_name, new_value):
1686
+ """Override 'object_to_patch'.'attr_name' with 'new_value'.
1687
+
1688
+ Also, add a cleanup procedure to 'test_instance' to restore
1689
+ 'object_to_patch' value for 'attr_name'.
1690
+ The 'attr_name' should be a valid attribute for 'object_to_patch'.
1691
+
1692
+ """
1693
+ # check that 'attr_name' is a real attribute for 'object_to_patch'
1694
+ # will raise AttributeError if it does not exist
1695
+ getattr(object_to_patch, attr_name)
1696
+
1697
+ # keep a copy of the old value
1698
+ attr_is_local = False
1699
+ try:
1700
+ old_value = object_to_patch.__dict__[attr_name]
1701
+ except (AttributeError, KeyError):
1702
+ old_value = getattr(object_to_patch, attr_name, None)
1703
+ else:
1704
+ attr_is_local = True
1705
+
1706
+ # restore the value when the test is done
1707
+ def cleanup():
1708
+ if attr_is_local:
1709
+ setattr(object_to_patch, attr_name, old_value)
1710
+ else:
1711
+ delattr(object_to_patch, attr_name)
1712
+
1713
+ test_instance.addCleanup(cleanup)
1714
+
1715
+ # actually override the attribute
1716
+ setattr(object_to_patch, attr_name, new_value)
1717
+
1718
+
1719
+ @contextlib.contextmanager
1720
+ def patch_list(orig):
1721
+ """Like unittest.mock.patch.dict, but for lists."""
1722
+ try:
1723
+ saved = orig[:]
1724
+ yield
1725
+ finally:
1726
+ orig[:] = saved
1727
+
1728
+
1729
+ def run_in_subinterp(code):
1730
+ """
1731
+ Run code in a subinterpreter. Raise unittest.SkipTest if the tracemalloc
1732
+ module is enabled.
1733
+ """
1734
+ # Issue #10915, #15751: PyGILState_*() functions don't work with
1735
+ # sub-interpreters, the tracemalloc module uses these functions internally
1736
+ try:
1737
+ import tracemalloc
1738
+ except ImportError:
1739
+ pass
1740
+ else:
1741
+ if tracemalloc.is_tracing():
1742
+ raise unittest.SkipTest("run_in_subinterp() cannot be used "
1743
+ "if tracemalloc module is tracing "
1744
+ "memory allocations")
1745
+ import _testcapi
1746
+ return _testcapi.run_in_subinterp(code)
1747
+
1748
+
1749
+ def check_free_after_iterating(test, iter, cls, args=()):
1750
+ class A(cls):
1751
+ def __del__(self):
1752
+ nonlocal done
1753
+ done = True
1754
+ try:
1755
+ next(it)
1756
+ except StopIteration:
1757
+ pass
1758
+
1759
+ done = False
1760
+ it = iter(A(*args))
1761
+ # Issue 26494: Shouldn't crash
1762
+ test.assertRaises(StopIteration, next, it)
1763
+ # The sequence should be deallocated just after the end of iterating
1764
+ gc_collect()
1765
+ test.assertTrue(done)
1766
+
1767
+
1768
+ def missing_compiler_executable(cmd_names=[]):
1769
+ """Check if the compiler components used to build the interpreter exist.
1770
+
1771
+ Check for the existence of the compiler executables whose names are listed
1772
+ in 'cmd_names' or all the compiler executables when 'cmd_names' is empty
1773
+ and return the first missing executable or None when none is found
1774
+ missing.
1775
+
1776
+ """
1777
+ # TODO (PEP 632): alternate check without using distutils
1778
+ from distutils import ccompiler, sysconfig, spawn, errors
1779
+ compiler = ccompiler.new_compiler()
1780
+ sysconfig.customize_compiler(compiler)
1781
+ if compiler.compiler_type == "msvc":
1782
+ # MSVC has no executables, so check whether initialization succeeds
1783
+ try:
1784
+ compiler.initialize()
1785
+ except errors.DistutilsPlatformError:
1786
+ return "msvc"
1787
+ for name in compiler.executables:
1788
+ if cmd_names and name not in cmd_names:
1789
+ continue
1790
+ cmd = getattr(compiler, name)
1791
+ if cmd_names:
1792
+ assert cmd is not None, \
1793
+ "the '%s' executable is not configured" % name
1794
+ elif not cmd:
1795
+ continue
1796
+ if spawn.find_executable(cmd[0]) is None:
1797
+ return cmd[0]
1798
+
1799
+
1800
+ _is_android_emulator = None
1801
+ def setswitchinterval(interval):
1802
+ # Setting a very low gil interval on the Android emulator causes python
1803
+ # to hang (issue #26939).
1804
+ minimum_interval = 1e-5
1805
+ if is_android and interval < minimum_interval:
1806
+ global _is_android_emulator
1807
+ if _is_android_emulator is None:
1808
+ import subprocess
1809
+ _is_android_emulator = (subprocess.check_output(
1810
+ ['getprop', 'ro.kernel.qemu']).strip() == b'1')
1811
+ if _is_android_emulator:
1812
+ interval = minimum_interval
1813
+ return sys.setswitchinterval(interval)
1814
+
1815
+
1816
+ @contextlib.contextmanager
1817
+ def disable_faulthandler():
1818
+ import faulthandler
1819
+
1820
+ # use sys.__stderr__ instead of sys.stderr, since regrtest replaces
1821
+ # sys.stderr with a StringIO which has no file descriptor when a test
1822
+ # is run with -W/--verbose3.
1823
+ fd = sys.__stderr__.fileno()
1824
+
1825
+ is_enabled = faulthandler.is_enabled()
1826
+ try:
1827
+ faulthandler.disable()
1828
+ yield
1829
+ finally:
1830
+ if is_enabled:
1831
+ faulthandler.enable(file=fd, all_threads=True)
1832
+
1833
+
1834
+ class SaveSignals:
1835
+ """
1836
+ Save and restore signal handlers.
1837
+
1838
+ This class is only able to save/restore signal handlers registered
1839
+ by the Python signal module: see bpo-13285 for "external" signal
1840
+ handlers.
1841
+ """
1842
+
1843
+ def __init__(self):
1844
+ import signal
1845
+ self.signal = signal
1846
+ self.signals = signal.valid_signals()
1847
+ # SIGKILL and SIGSTOP signals cannot be ignored nor caught
1848
+ for signame in ('SIGKILL', 'SIGSTOP'):
1849
+ try:
1850
+ signum = getattr(signal, signame)
1851
+ except AttributeError:
1852
+ continue
1853
+ self.signals.remove(signum)
1854
+ self.handlers = {}
1855
+
1856
+ def save(self):
1857
+ for signum in self.signals:
1858
+ handler = self.signal.getsignal(signum)
1859
+ if handler is None:
1860
+ # getsignal() returns None if a signal handler was not
1861
+ # registered by the Python signal module,
1862
+ # and the handler is not SIG_DFL nor SIG_IGN.
1863
+ #
1864
+ # Ignore the signal: we cannot restore the handler.
1865
+ continue
1866
+ self.handlers[signum] = handler
1867
+
1868
+ def restore(self):
1869
+ for signum, handler in self.handlers.items():
1870
+ self.signal.signal(signum, handler)
1871
+
1872
+
1873
+ def with_pymalloc():
1874
+ import _testcapi
1875
+ return _testcapi.WITH_PYMALLOC
1876
+
1877
+
1878
+ class _ALWAYS_EQ:
1879
+ """
1880
+ Object that is equal to anything.
1881
+ """
1882
+ def __eq__(self, other):
1883
+ return True
1884
+ def __ne__(self, other):
1885
+ return False
1886
+
1887
+ ALWAYS_EQ = _ALWAYS_EQ()
1888
+
1889
+ class _NEVER_EQ:
1890
+ """
1891
+ Object that is not equal to anything.
1892
+ """
1893
+ def __eq__(self, other):
1894
+ return False
1895
+ def __ne__(self, other):
1896
+ return True
1897
+ def __hash__(self):
1898
+ return 1
1899
+
1900
+ NEVER_EQ = _NEVER_EQ()
1901
+
1902
+ @functools.total_ordering
1903
+ class _LARGEST:
1904
+ """
1905
+ Object that is greater than anything (except itself).
1906
+ """
1907
+ def __eq__(self, other):
1908
+ return isinstance(other, _LARGEST)
1909
+ def __lt__(self, other):
1910
+ return False
1911
+
1912
+ LARGEST = _LARGEST()
1913
+
1914
+ @functools.total_ordering
1915
+ class _SMALLEST:
1916
+ """
1917
+ Object that is less than anything (except itself).
1918
+ """
1919
+ def __eq__(self, other):
1920
+ return isinstance(other, _SMALLEST)
1921
+ def __gt__(self, other):
1922
+ return False
1923
+
1924
+ SMALLEST = _SMALLEST()
1925
+
1926
+ def maybe_get_event_loop_policy():
1927
+ """Return the global event loop policy if one is set, else return None."""
1928
+ import asyncio.events
1929
+ return asyncio.events._event_loop_policy
1930
+
1931
+ # Helpers for testing hashing.
1932
+ NHASHBITS = sys.hash_info.width # number of bits in hash() result
1933
+ assert NHASHBITS in (32, 64)
1934
+
1935
+ # Return mean and sdev of number of collisions when tossing nballs balls
1936
+ # uniformly at random into nbins bins. By definition, the number of
1937
+ # collisions is the number of balls minus the number of occupied bins at
1938
+ # the end.
1939
+ def collision_stats(nbins, nballs):
1940
+ n, k = nbins, nballs
1941
+ # prob a bin empty after k trials = (1 - 1/n)**k
1942
+ # mean # empty is then n * (1 - 1/n)**k
1943
+ # so mean # occupied is n - n * (1 - 1/n)**k
1944
+ # so collisions = k - (n - n*(1 - 1/n)**k)
1945
+ #
1946
+ # For the variance:
1947
+ # n*(n-1)*(1-2/n)**k + meanempty - meanempty**2 =
1948
+ # n*(n-1)*(1-2/n)**k + meanempty * (1 - meanempty)
1949
+ #
1950
+ # Massive cancellation occurs, and, e.g., for a 64-bit hash code
1951
+ # 1-1/2**64 rounds uselessly to 1.0. Rather than make heroic (and
1952
+ # error-prone) efforts to rework the naive formulas to avoid those,
1953
+ # we use the `decimal` module to get plenty of extra precision.
1954
+ #
1955
+ # Note: the exact values are straightforward to compute with
1956
+ # rationals, but in context that's unbearably slow, requiring
1957
+ # multi-million bit arithmetic.
1958
+ import decimal
1959
+ with decimal.localcontext() as ctx:
1960
+ bits = n.bit_length() * 2 # bits in n**2
1961
+ # At least that many bits will likely cancel out.
1962
+ # Use that many decimal digits instead.
1963
+ ctx.prec = max(bits, 30)
1964
+ dn = decimal.Decimal(n)
1965
+ p1empty = ((dn - 1) / dn) ** k
1966
+ meanempty = n * p1empty
1967
+ occupied = n - meanempty
1968
+ collisions = k - occupied
1969
+ var = dn*(dn-1)*((dn-2)/dn)**k + meanempty * (1 - meanempty)
1970
+ return float(collisions), float(var.sqrt())
1971
+
1972
+
1973
+ class catch_unraisable_exception:
1974
+ """
1975
+ Context manager catching unraisable exception using sys.unraisablehook.
1976
+
1977
+ Storing the exception value (cm.unraisable.exc_value) creates a reference
1978
+ cycle. The reference cycle is broken explicitly when the context manager
1979
+ exits.
1980
+
1981
+ Storing the object (cm.unraisable.object) can resurrect it if it is set to
1982
+ an object which is being finalized. Exiting the context manager clears the
1983
+ stored object.
1984
+
1985
+ Usage:
1986
+
1987
+ with support.catch_unraisable_exception() as cm:
1988
+ # code creating an "unraisable exception"
1989
+ ...
1990
+
1991
+ # check the unraisable exception: use cm.unraisable
1992
+ ...
1993
+
1994
+ # cm.unraisable attribute no longer exists at this point
1995
+ # (to break a reference cycle)
1996
+ """
1997
+
1998
+ def __init__(self):
1999
+ self.unraisable = None
2000
+ self._old_hook = None
2001
+
2002
+ def _hook(self, unraisable):
2003
+ # Storing unraisable.object can resurrect an object which is being
2004
+ # finalized. Storing unraisable.exc_value creates a reference cycle.
2005
+ self.unraisable = unraisable
2006
+
2007
+ def __enter__(self):
2008
+ self._old_hook = sys.unraisablehook
2009
+ sys.unraisablehook = self._hook
2010
+ return self
2011
+
2012
+ def __exit__(self, *exc_info):
2013
+ sys.unraisablehook = self._old_hook
2014
+ del self.unraisable
2015
+
2016
+
2017
+ def wait_process(pid, *, exitcode, timeout=None):
2018
+ """
2019
+ Wait until process pid completes and check that the process exit code is
2020
+ exitcode.
2021
+
2022
+ Raise an AssertionError if the process exit code is not equal to exitcode.
2023
+
2024
+ If the process runs longer than timeout seconds (LONG_TIMEOUT by default),
2025
+ kill the process (if signal.SIGKILL is available) and raise an
2026
+ AssertionError. The timeout feature is not available on Windows.
2027
+ """
2028
+ if os.name != "nt":
2029
+ import signal
2030
+
2031
+ if timeout is None:
2032
+ timeout = LONG_TIMEOUT
2033
+ t0 = time.monotonic()
2034
+ sleep = 0.001
2035
+ max_sleep = 0.1
2036
+ while True:
2037
+ pid2, status = os.waitpid(pid, os.WNOHANG)
2038
+ if pid2 != 0:
2039
+ break
2040
+ # process is still running
2041
+
2042
+ dt = time.monotonic() - t0
2043
+ if dt > timeout:
2044
+ try:
2045
+ os.kill(pid, signal.SIGKILL)
2046
+ os.waitpid(pid, 0)
2047
+ except OSError:
2048
+ # Ignore errors like ChildProcessError or PermissionError
2049
+ pass
2050
+
2051
+ raise AssertionError(f"process {pid} is still running "
2052
+ f"after {dt:.1f} seconds")
2053
+
2054
+ sleep = min(sleep * 2, max_sleep)
2055
+ time.sleep(sleep)
2056
+ else:
2057
+ # Windows implementation
2058
+ pid2, status = os.waitpid(pid, 0)
2059
+
2060
+ exitcode2 = os.waitstatus_to_exitcode(status)
2061
+ if exitcode2 != exitcode:
2062
+ raise AssertionError(f"process {pid} exited with code {exitcode2}, "
2063
+ f"but exit code {exitcode} is expected")
2064
+
2065
+ # sanity check: it should not fail in practice
2066
+ if pid2 != pid:
2067
+ raise AssertionError(f"pid {pid2} != pid {pid}")
2068
+
2069
+ def skip_if_broken_multiprocessing_synchronize():
2070
+ """
2071
+ Skip tests if the multiprocessing.synchronize module is missing, if there
2072
+ is no available semaphore implementation, or if creating a lock raises an
2073
+ OSError (on Linux only).
2074
+ """
2075
+ from .import_helper import import_module
2076
+
2077
+ # Skip tests if the _multiprocessing extension is missing.
2078
+ import_module('_multiprocessing')
2079
+
2080
+ # Skip tests if there is no available semaphore implementation:
2081
+ # multiprocessing.synchronize requires _multiprocessing.SemLock.
2082
+ synchronize = import_module('multiprocessing.synchronize')
2083
+
2084
+ if sys.platform == "linux":
2085
+ try:
2086
+ # bpo-38377: On Linux, creating a semaphore fails with OSError
2087
+ # if the current user does not have the permission to create
2088
+ # a file in /dev/shm/ directory.
2089
+ synchronize.Lock(ctx=None)
2090
+ except OSError as exc:
2091
+ raise unittest.SkipTest(f"broken multiprocessing SemLock: {exc!r}")
2092
+
2093
+
2094
+ @contextlib.contextmanager
2095
+ def infinite_recursion(max_depth=75):
2096
+ original_depth = sys.getrecursionlimit()
2097
+ try:
2098
+ sys.setrecursionlimit(max_depth)
2099
+ yield
2100
+ finally:
2101
+ sys.setrecursionlimit(original_depth)
2102
+
2103
+
2104
+ def check_disallow_instantiation(testcase, tp, *args, **kwds):
2105
+ """
2106
+ Check that given type cannot be instantiated using *args and **kwds.
2107
+
2108
+ See bpo-43916: Add Py_TPFLAGS_DISALLOW_INSTANTIATION type flag.
2109
+ """
2110
+ mod = tp.__module__
2111
+ name = tp.__name__
2112
+ if mod != 'builtins':
2113
+ qualname = f"{mod}.{name}"
2114
+ else:
2115
+ qualname = f"{name}"
2116
+ msg = f"cannot create '{re.escape(qualname)}' instances"
2117
+ testcase.assertRaisesRegex(TypeError, msg, tp, *args, **kwds)
2118
+
2119
+
2120
+ def ignore_deprecations_from(module: str, *, like: str) -> object:
2121
+ token = object()
2122
+ warnings.filterwarnings(
2123
+ "ignore",
2124
+ category=DeprecationWarning,
2125
+ module=module,
2126
+ message=like + fr"(?#support{id(token)})",
2127
+ )
2128
+ return token
2129
+
2130
+
2131
+ def clear_ignored_deprecations(*tokens: object) -> None:
2132
+ if not tokens:
2133
+ raise ValueError("Provide token or tokens returned by ignore_deprecations_from")
2134
+
2135
+ new_filters = []
2136
+ endswith = tuple(rf"(?#support{id(token)})" for token in tokens)
2137
+ for action, message, category, module, lineno in warnings.filters:
2138
+ if action == "ignore" and category is DeprecationWarning:
2139
+ if isinstance(message, re.Pattern):
2140
+ msg = message.pattern
2141
+ else:
2142
+ msg = message or ""
2143
+ if msg.endswith(endswith):
2144
+ continue
2145
+ new_filters.append((action, message, category, module, lineno))
2146
+ if warnings.filters != new_filters:
2147
+ warnings.filters[:] = new_filters
2148
+ warnings._filters_mutated()
2149
+
2150
+
2151
+ @contextlib.contextmanager
2152
+ def adjust_int_max_str_digits(max_digits):
2153
+ """Temporarily change the integer string conversion length limit."""
2154
+ current = sys.get_int_max_str_digits()
2155
+ try:
2156
+ sys.set_int_max_str_digits(max_digits)
2157
+ yield
2158
+ finally:
2159
+ sys.set_int_max_str_digits(current)
2160
+
2161
+
2162
+ def control_characters_c0() -> list[str]:
2163
+ """Returns a list of C0 control characters as strings.
2164
+ C0 control characters defined as the byte range 0x00-0x1F, and 0x7F.
2165
+ """
2166
+ return [chr(c) for c in range(0x00, 0x20)] + ["\x7F"]
miniconda3/envs/ladir/lib/python3.10/test/support/bytecode_helper.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """bytecode_helper - support tools for testing correct bytecode generation"""
2
+
3
+ import unittest
4
+ import dis
5
+ import io
6
+
7
+ _UNSPECIFIED = object()
8
+
9
+ class BytecodeTestCase(unittest.TestCase):
10
+ """Custom assertion methods for inspecting bytecode."""
11
+
12
+ def get_disassembly_as_string(self, co):
13
+ s = io.StringIO()
14
+ dis.dis(co, file=s)
15
+ return s.getvalue()
16
+
17
+ def assertInBytecode(self, x, opname, argval=_UNSPECIFIED):
18
+ """Returns instr if opname is found, otherwise throws AssertionError"""
19
+ for instr in dis.get_instructions(x):
20
+ if instr.opname == opname:
21
+ if argval is _UNSPECIFIED or instr.argval == argval:
22
+ return instr
23
+ disassembly = self.get_disassembly_as_string(x)
24
+ if argval is _UNSPECIFIED:
25
+ msg = '%s not found in bytecode:\n%s' % (opname, disassembly)
26
+ else:
27
+ msg = '(%s,%r) not found in bytecode:\n%s'
28
+ msg = msg % (opname, argval, disassembly)
29
+ self.fail(msg)
30
+
31
+ def assertNotInBytecode(self, x, opname, argval=_UNSPECIFIED):
32
+ """Throws AssertionError if opname is found"""
33
+ for instr in dis.get_instructions(x):
34
+ if instr.opname == opname:
35
+ disassembly = self.get_disassembly_as_string(x)
36
+ if argval is _UNSPECIFIED:
37
+ msg = '%s occurs in bytecode:\n%s' % (opname, disassembly)
38
+ self.fail(msg)
39
+ elif instr.argval == argval:
40
+ msg = '(%s,%r) occurs in bytecode:\n%s'
41
+ msg = msg % (opname, argval, disassembly)
42
+ self.fail(msg)
miniconda3/envs/ladir/lib/python3.10/test/support/hashlib_helper.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import hashlib
3
+ import unittest
4
+
5
+ try:
6
+ import _hashlib
7
+ except ImportError:
8
+ _hashlib = None
9
+
10
+
11
+ def requires_hashdigest(digestname, openssl=None, usedforsecurity=True):
12
+ """Decorator raising SkipTest if a hashing algorithm is not available
13
+
14
+ The hashing algorithm could be missing or blocked by a strict crypto
15
+ policy.
16
+
17
+ If 'openssl' is True, then the decorator checks that OpenSSL provides
18
+ the algorithm. Otherwise the check falls back to built-in
19
+ implementations. The usedforsecurity flag is passed to the constructor.
20
+
21
+ ValueError: [digital envelope routines: EVP_DigestInit_ex] disabled for FIPS
22
+ ValueError: unsupported hash type md4
23
+ """
24
+ def decorator(func_or_class):
25
+ if isinstance(func_or_class, type):
26
+ setUpClass = func_or_class.__dict__.get('setUpClass')
27
+ if setUpClass is None:
28
+ def setUpClass(cls):
29
+ super(func_or_class, cls).setUpClass()
30
+ setUpClass.__qualname__ = func_or_class.__qualname__ + '.setUpClass'
31
+ setUpClass.__module__ = func_or_class.__module__
32
+ else:
33
+ setUpClass = setUpClass.__func__
34
+ setUpClass = classmethod(decorator(setUpClass))
35
+ func_or_class.setUpClass = setUpClass
36
+ return func_or_class
37
+
38
+ @functools.wraps(func_or_class)
39
+ def wrapper(*args, **kwargs):
40
+ try:
41
+ if openssl and _hashlib is not None:
42
+ _hashlib.new(digestname, usedforsecurity=usedforsecurity)
43
+ else:
44
+ hashlib.new(digestname, usedforsecurity=usedforsecurity)
45
+ except ValueError:
46
+ raise unittest.SkipTest(
47
+ f"hash digest '{digestname}' is not available."
48
+ )
49
+ return func_or_class(*args, **kwargs)
50
+ return wrapper
51
+ return decorator
miniconda3/envs/ladir/lib/python3.10/test/support/import_helper.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import importlib
3
+ import importlib.util
4
+ import os
5
+ import shutil
6
+ import sys
7
+ import unittest
8
+ import warnings
9
+
10
+ from .os_helper import unlink
11
+
12
+
13
+ @contextlib.contextmanager
14
+ def _ignore_deprecated_imports(ignore=True):
15
+ """Context manager to suppress package and module deprecation
16
+ warnings when importing them.
17
+
18
+ If ignore is False, this context manager has no effect.
19
+ """
20
+ if ignore:
21
+ with warnings.catch_warnings():
22
+ warnings.filterwarnings("ignore", ".+ (module|package)",
23
+ DeprecationWarning)
24
+ yield
25
+ else:
26
+ yield
27
+
28
+
29
+ def unload(name):
30
+ try:
31
+ del sys.modules[name]
32
+ except KeyError:
33
+ pass
34
+
35
+
36
+ def forget(modname):
37
+ """'Forget' a module was ever imported.
38
+
39
+ This removes the module from sys.modules and deletes any PEP 3147/488 or
40
+ legacy .pyc files.
41
+ """
42
+ unload(modname)
43
+ for dirname in sys.path:
44
+ source = os.path.join(dirname, modname + '.py')
45
+ # It doesn't matter if they exist or not, unlink all possible
46
+ # combinations of PEP 3147/488 and legacy pyc files.
47
+ unlink(source + 'c')
48
+ for opt in ('', 1, 2):
49
+ unlink(importlib.util.cache_from_source(source, optimization=opt))
50
+
51
+
52
+ def make_legacy_pyc(source):
53
+ """Move a PEP 3147/488 pyc file to its legacy pyc location.
54
+
55
+ :param source: The file system path to the source file. The source file
56
+ does not need to exist, however the PEP 3147/488 pyc file must exist.
57
+ :return: The file system path to the legacy pyc file.
58
+ """
59
+ pyc_file = importlib.util.cache_from_source(source)
60
+ up_one = os.path.dirname(os.path.abspath(source))
61
+ legacy_pyc = os.path.join(up_one, source + 'c')
62
+ shutil.move(pyc_file, legacy_pyc)
63
+ return legacy_pyc
64
+
65
+
66
+ def import_module(name, deprecated=False, *, required_on=()):
67
+ """Import and return the module to be tested, raising SkipTest if
68
+ it is not available.
69
+
70
+ If deprecated is True, any module or package deprecation messages
71
+ will be suppressed. If a module is required on a platform but optional for
72
+ others, set required_on to an iterable of platform prefixes which will be
73
+ compared against sys.platform.
74
+ """
75
+ with _ignore_deprecated_imports(deprecated):
76
+ try:
77
+ return importlib.import_module(name)
78
+ except ImportError as msg:
79
+ if sys.platform.startswith(tuple(required_on)):
80
+ raise
81
+ raise unittest.SkipTest(str(msg))
82
+
83
+
84
+ def _save_and_remove_modules(names):
85
+ orig_modules = {}
86
+ prefixes = tuple(name + '.' for name in names)
87
+ for modname in list(sys.modules):
88
+ if modname in names or modname.startswith(prefixes):
89
+ orig_modules[modname] = sys.modules.pop(modname)
90
+ return orig_modules
91
+
92
+
93
+ def import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
94
+ """Import and return a module, deliberately bypassing sys.modules.
95
+
96
+ This function imports and returns a fresh copy of the named Python module
97
+ by removing the named module from sys.modules before doing the import.
98
+ Note that unlike reload, the original module is not affected by
99
+ this operation.
100
+
101
+ *fresh* is an iterable of additional module names that are also removed
102
+ from the sys.modules cache before doing the import. If one of these
103
+ modules can't be imported, None is returned.
104
+
105
+ *blocked* is an iterable of module names that are replaced with None
106
+ in the module cache during the import to ensure that attempts to import
107
+ them raise ImportError.
108
+
109
+ The named module and any modules named in the *fresh* and *blocked*
110
+ parameters are saved before starting the import and then reinserted into
111
+ sys.modules when the fresh import is complete.
112
+
113
+ Module and package deprecation messages are suppressed during this import
114
+ if *deprecated* is True.
115
+
116
+ This function will raise ImportError if the named module cannot be
117
+ imported.
118
+ """
119
+ # NOTE: test_heapq, test_json and test_warnings include extra sanity checks
120
+ # to make sure that this utility function is working as expected
121
+ with _ignore_deprecated_imports(deprecated):
122
+ # Keep track of modules saved for later restoration as well
123
+ # as those which just need a blocking entry removed
124
+ fresh = list(fresh)
125
+ blocked = list(blocked)
126
+ names = {name, *fresh, *blocked}
127
+ orig_modules = _save_and_remove_modules(names)
128
+ for modname in blocked:
129
+ sys.modules[modname] = None
130
+
131
+ try:
132
+ # Return None when one of the "fresh" modules can not be imported.
133
+ try:
134
+ for modname in fresh:
135
+ __import__(modname)
136
+ except ImportError:
137
+ return None
138
+ return importlib.import_module(name)
139
+ finally:
140
+ _save_and_remove_modules(names)
141
+ sys.modules.update(orig_modules)
142
+
143
+
144
+ class CleanImport(object):
145
+ """Context manager to force import to return a new module reference.
146
+
147
+ This is useful for testing module-level behaviours, such as
148
+ the emission of a DeprecationWarning on import.
149
+
150
+ Use like this:
151
+
152
+ with CleanImport("foo"):
153
+ importlib.import_module("foo") # new reference
154
+ """
155
+
156
+ def __init__(self, *module_names):
157
+ self.original_modules = sys.modules.copy()
158
+ for module_name in module_names:
159
+ if module_name in sys.modules:
160
+ module = sys.modules[module_name]
161
+ # It is possible that module_name is just an alias for
162
+ # another module (e.g. stub for modules renamed in 3.x).
163
+ # In that case, we also need delete the real module to clear
164
+ # the import cache.
165
+ if module.__name__ != module_name:
166
+ del sys.modules[module.__name__]
167
+ del sys.modules[module_name]
168
+
169
+ def __enter__(self):
170
+ return self
171
+
172
+ def __exit__(self, *ignore_exc):
173
+ sys.modules.update(self.original_modules)
174
+
175
+
176
+ class DirsOnSysPath(object):
177
+ """Context manager to temporarily add directories to sys.path.
178
+
179
+ This makes a copy of sys.path, appends any directories given
180
+ as positional arguments, then reverts sys.path to the copied
181
+ settings when the context ends.
182
+
183
+ Note that *all* sys.path modifications in the body of the
184
+ context manager, including replacement of the object,
185
+ will be reverted at the end of the block.
186
+ """
187
+
188
+ def __init__(self, *paths):
189
+ self.original_value = sys.path[:]
190
+ self.original_object = sys.path
191
+ sys.path.extend(paths)
192
+
193
+ def __enter__(self):
194
+ return self
195
+
196
+ def __exit__(self, *ignore_exc):
197
+ sys.path = self.original_object
198
+ sys.path[:] = self.original_value
199
+
200
+
201
+ def modules_setup():
202
+ return sys.modules.copy(),
203
+
204
+
205
+ def modules_cleanup(oldmodules):
206
+ # Encoders/decoders are registered permanently within the internal
207
+ # codec cache. If we destroy the corresponding modules their
208
+ # globals will be set to None which will trip up the cached functions.
209
+ encodings = [(k, v) for k, v in sys.modules.items()
210
+ if k.startswith('encodings.')]
211
+ sys.modules.clear()
212
+ sys.modules.update(encodings)
213
+ # XXX: This kind of problem can affect more than just encodings.
214
+ # In particular extension modules (such as _ssl) don't cope
215
+ # with reloading properly. Really, test modules should be cleaning
216
+ # out the test specific modules they know they added (ala test_runpy)
217
+ # rather than relying on this function (as test_importhooks and test_pkg
218
+ # do currently). Implicitly imported *real* modules should be left alone
219
+ # (see issue 10556).
220
+ sys.modules.update(oldmodules)
miniconda3/envs/ladir/lib/python3.10/test/support/interpreters.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Subinterpreters High Level Module."""
2
+
3
+ import time
4
+ import _xxsubinterpreters as _interpreters
5
+
6
+ # aliases:
7
+ from _xxsubinterpreters import (
8
+ ChannelError, ChannelNotFoundError, ChannelEmptyError,
9
+ is_shareable,
10
+ )
11
+
12
+
13
+ __all__ = [
14
+ 'Interpreter', 'get_current', 'get_main', 'create', 'list_all',
15
+ 'SendChannel', 'RecvChannel',
16
+ 'create_channel', 'list_all_channels', 'is_shareable',
17
+ 'ChannelError', 'ChannelNotFoundError',
18
+ 'ChannelEmptyError',
19
+ ]
20
+
21
+
22
+ def create(*, isolated=True):
23
+ """Return a new (idle) Python interpreter."""
24
+ id = _interpreters.create(isolated=isolated)
25
+ return Interpreter(id, isolated=isolated)
26
+
27
+
28
+ def list_all():
29
+ """Return all existing interpreters."""
30
+ return [Interpreter(id) for id in _interpreters.list_all()]
31
+
32
+
33
+ def get_current():
34
+ """Return the currently running interpreter."""
35
+ id = _interpreters.get_current()
36
+ return Interpreter(id)
37
+
38
+
39
+ def get_main():
40
+ """Return the main interpreter."""
41
+ id = _interpreters.get_main()
42
+ return Interpreter(id)
43
+
44
+
45
+ class Interpreter:
46
+ """A single Python interpreter."""
47
+
48
+ def __init__(self, id, *, isolated=None):
49
+ if not isinstance(id, (int, _interpreters.InterpreterID)):
50
+ raise TypeError(f'id must be an int, got {id!r}')
51
+ self._id = id
52
+ self._isolated = isolated
53
+
54
+ def __repr__(self):
55
+ data = dict(id=int(self._id), isolated=self._isolated)
56
+ kwargs = (f'{k}={v!r}' for k, v in data.items())
57
+ return f'{type(self).__name__}({", ".join(kwargs)})'
58
+
59
+ def __hash__(self):
60
+ return hash(self._id)
61
+
62
+ def __eq__(self, other):
63
+ if not isinstance(other, Interpreter):
64
+ return NotImplemented
65
+ else:
66
+ return other._id == self._id
67
+
68
+ @property
69
+ def id(self):
70
+ return self._id
71
+
72
+ @property
73
+ def isolated(self):
74
+ if self._isolated is None:
75
+ # XXX The low-level function has not been added yet.
76
+ # See bpo-....
77
+ self._isolated = _interpreters.is_isolated(self._id)
78
+ return self._isolated
79
+
80
+ def is_running(self):
81
+ """Return whether or not the identified interpreter is running."""
82
+ return _interpreters.is_running(self._id)
83
+
84
+ def close(self):
85
+ """Finalize and destroy the interpreter.
86
+
87
+ Attempting to destroy the current interpreter results
88
+ in a RuntimeError.
89
+ """
90
+ return _interpreters.destroy(self._id)
91
+
92
+ def run(self, src_str, /, *, channels=None):
93
+ """Run the given source code in the interpreter.
94
+
95
+ This blocks the current Python thread until done.
96
+ """
97
+ _interpreters.run_string(self._id, src_str, channels)
98
+
99
+
100
+ def create_channel():
101
+ """Return (recv, send) for a new cross-interpreter channel.
102
+
103
+ The channel may be used to pass data safely between interpreters.
104
+ """
105
+ cid = _interpreters.channel_create()
106
+ recv, send = RecvChannel(cid), SendChannel(cid)
107
+ return recv, send
108
+
109
+
110
+ def list_all_channels():
111
+ """Return a list of (recv, send) for all open channels."""
112
+ return [(RecvChannel(cid), SendChannel(cid))
113
+ for cid in _interpreters.channel_list_all()]
114
+
115
+
116
+ class _ChannelEnd:
117
+ """The base class for RecvChannel and SendChannel."""
118
+
119
+ def __init__(self, id):
120
+ if not isinstance(id, (int, _interpreters.ChannelID)):
121
+ raise TypeError(f'id must be an int, got {id!r}')
122
+ self._id = id
123
+
124
+ def __repr__(self):
125
+ return f'{type(self).__name__}(id={int(self._id)})'
126
+
127
+ def __hash__(self):
128
+ return hash(self._id)
129
+
130
+ def __eq__(self, other):
131
+ if isinstance(self, RecvChannel):
132
+ if not isinstance(other, RecvChannel):
133
+ return NotImplemented
134
+ elif not isinstance(other, SendChannel):
135
+ return NotImplemented
136
+ return other._id == self._id
137
+
138
+ @property
139
+ def id(self):
140
+ return self._id
141
+
142
+
143
+ _NOT_SET = object()
144
+
145
+
146
+ class RecvChannel(_ChannelEnd):
147
+ """The receiving end of a cross-interpreter channel."""
148
+
149
+ def recv(self, *, _sentinel=object(), _delay=10 / 1000): # 10 milliseconds
150
+ """Return the next object from the channel.
151
+
152
+ This blocks until an object has been sent, if none have been
153
+ sent already.
154
+ """
155
+ obj = _interpreters.channel_recv(self._id, _sentinel)
156
+ while obj is _sentinel:
157
+ time.sleep(_delay)
158
+ obj = _interpreters.channel_recv(self._id, _sentinel)
159
+ return obj
160
+
161
+ def recv_nowait(self, default=_NOT_SET):
162
+ """Return the next object from the channel.
163
+
164
+ If none have been sent then return the default if one
165
+ is provided or fail with ChannelEmptyError. Otherwise this
166
+ is the same as recv().
167
+ """
168
+ if default is _NOT_SET:
169
+ return _interpreters.channel_recv(self._id)
170
+ else:
171
+ return _interpreters.channel_recv(self._id, default)
172
+
173
+
174
+ class SendChannel(_ChannelEnd):
175
+ """The sending end of a cross-interpreter channel."""
176
+
177
+ def send(self, obj):
178
+ """Send the object (i.e. its data) to the channel's receiving end.
179
+
180
+ This blocks until the object is received.
181
+ """
182
+ _interpreters.channel_send(self._id, obj)
183
+ # XXX We are missing a low-level channel_send_wait().
184
+ # See bpo-32604 and gh-19829.
185
+ # Until that shows up we fake it:
186
+ time.sleep(2)
187
+
188
+ def send_nowait(self, obj):
189
+ """Send the object to the channel's receiving end.
190
+
191
+ If the object is immediately received then return True
192
+ (else False). Otherwise this is the same as send().
193
+ """
194
+ # XXX Note that at the moment channel_send() only ever returns
195
+ # None. This should be fixed when channel_send_wait() is added.
196
+ # See bpo-32604 and gh-19829.
197
+ return _interpreters.channel_send(self._id, obj)
miniconda3/envs/ladir/lib/python3.10/test/support/logging_helper.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging.handlers
2
+
3
+ class TestHandler(logging.handlers.BufferingHandler):
4
+ def __init__(self, matcher):
5
+ # BufferingHandler takes a "capacity" argument
6
+ # so as to know when to flush. As we're overriding
7
+ # shouldFlush anyway, we can set a capacity of zero.
8
+ # You can call flush() manually to clear out the
9
+ # buffer.
10
+ logging.handlers.BufferingHandler.__init__(self, 0)
11
+ self.matcher = matcher
12
+
13
+ def shouldFlush(self):
14
+ return False
15
+
16
+ def emit(self, record):
17
+ self.format(record)
18
+ self.buffer.append(record.__dict__)
19
+
20
+ def matches(self, **kwargs):
21
+ """
22
+ Look for a saved dict whose keys/values match the supplied arguments.
23
+ """
24
+ result = False
25
+ for d in self.buffer:
26
+ if self.matcher.matches(d, **kwargs):
27
+ result = True
28
+ break
29
+ return result
miniconda3/envs/ladir/lib/python3.10/test/support/os_helper.py ADDED
@@ -0,0 +1,623 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections.abc
2
+ import contextlib
3
+ import errno
4
+ import os
5
+ import re
6
+ import stat
7
+ import sys
8
+ import time
9
+ import unittest
10
+ import warnings
11
+
12
+
13
+ # Filename used for testing
14
+ if os.name == 'java':
15
+ # Jython disallows @ in module names
16
+ TESTFN_ASCII = '$test'
17
+ else:
18
+ TESTFN_ASCII = '@test'
19
+
20
+ # Disambiguate TESTFN for parallel testing, while letting it remain a valid
21
+ # module name.
22
+ TESTFN_ASCII = "{}_{}_tmp".format(TESTFN_ASCII, os.getpid())
23
+
24
+ # TESTFN_UNICODE is a non-ascii filename
25
+ TESTFN_UNICODE = TESTFN_ASCII + "-\xe0\xf2\u0258\u0141\u011f"
26
+ if sys.platform == 'darwin':
27
+ # In Mac OS X's VFS API file names are, by definition, canonically
28
+ # decomposed Unicode, encoded using UTF-8. See QA1173:
29
+ # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
30
+ import unicodedata
31
+ TESTFN_UNICODE = unicodedata.normalize('NFD', TESTFN_UNICODE)
32
+
33
+ # TESTFN_UNENCODABLE is a filename (str type) that should *not* be able to be
34
+ # encoded by the filesystem encoding (in strict mode). It can be None if we
35
+ # cannot generate such filename.
36
+ TESTFN_UNENCODABLE = None
37
+ if os.name == 'nt':
38
+ # skip win32s (0) or Windows 9x/ME (1)
39
+ if sys.getwindowsversion().platform >= 2:
40
+ # Different kinds of characters from various languages to minimize the
41
+ # probability that the whole name is encodable to MBCS (issue #9819)
42
+ TESTFN_UNENCODABLE = TESTFN_ASCII + "-\u5171\u0141\u2661\u0363\uDC80"
43
+ try:
44
+ TESTFN_UNENCODABLE.encode(sys.getfilesystemencoding())
45
+ except UnicodeEncodeError:
46
+ pass
47
+ else:
48
+ print('WARNING: The filename %r CAN be encoded by the filesystem '
49
+ 'encoding (%s). Unicode filename tests may not be effective'
50
+ % (TESTFN_UNENCODABLE, sys.getfilesystemencoding()))
51
+ TESTFN_UNENCODABLE = None
52
+ # Mac OS X denies unencodable filenames (invalid utf-8)
53
+ elif sys.platform != 'darwin':
54
+ try:
55
+ # ascii and utf-8 cannot encode the byte 0xff
56
+ b'\xff'.decode(sys.getfilesystemencoding())
57
+ except UnicodeDecodeError:
58
+ # 0xff will be encoded using the surrogate character u+DCFF
59
+ TESTFN_UNENCODABLE = TESTFN_ASCII \
60
+ + b'-\xff'.decode(sys.getfilesystemencoding(), 'surrogateescape')
61
+ else:
62
+ # File system encoding (eg. ISO-8859-* encodings) can encode
63
+ # the byte 0xff. Skip some unicode filename tests.
64
+ pass
65
+
66
+ # FS_NONASCII: non-ASCII character encodable by os.fsencode(),
67
+ # or an empty string if there is no such character.
68
+ FS_NONASCII = ''
69
+ for character in (
70
+ # First try printable and common characters to have a readable filename.
71
+ # For each character, the encoding list are just example of encodings able
72
+ # to encode the character (the list is not exhaustive).
73
+
74
+ # U+00E6 (Latin Small Letter Ae): cp1252, iso-8859-1
75
+ '\u00E6',
76
+ # U+0130 (Latin Capital Letter I With Dot Above): cp1254, iso8859_3
77
+ '\u0130',
78
+ # U+0141 (Latin Capital Letter L With Stroke): cp1250, cp1257
79
+ '\u0141',
80
+ # U+03C6 (Greek Small Letter Phi): cp1253
81
+ '\u03C6',
82
+ # U+041A (Cyrillic Capital Letter Ka): cp1251
83
+ '\u041A',
84
+ # U+05D0 (Hebrew Letter Alef): Encodable to cp424
85
+ '\u05D0',
86
+ # U+060C (Arabic Comma): cp864, cp1006, iso8859_6, mac_arabic
87
+ '\u060C',
88
+ # U+062A (Arabic Letter Teh): cp720
89
+ '\u062A',
90
+ # U+0E01 (Thai Character Ko Kai): cp874
91
+ '\u0E01',
92
+
93
+ # Then try more "special" characters. "special" because they may be
94
+ # interpreted or displayed differently depending on the exact locale
95
+ # encoding and the font.
96
+
97
+ # U+00A0 (No-Break Space)
98
+ '\u00A0',
99
+ # U+20AC (Euro Sign)
100
+ '\u20AC',
101
+ ):
102
+ try:
103
+ # If Python is set up to use the legacy 'mbcs' in Windows,
104
+ # 'replace' error mode is used, and encode() returns b'?'
105
+ # for characters missing in the ANSI codepage
106
+ if os.fsdecode(os.fsencode(character)) != character:
107
+ raise UnicodeError
108
+ except UnicodeError:
109
+ pass
110
+ else:
111
+ FS_NONASCII = character
112
+ break
113
+
114
+ # Save the initial cwd
115
+ SAVEDCWD = os.getcwd()
116
+
117
+ # TESTFN_UNDECODABLE is a filename (bytes type) that should *not* be able to be
118
+ # decoded from the filesystem encoding (in strict mode). It can be None if we
119
+ # cannot generate such filename (ex: the latin1 encoding can decode any byte
120
+ # sequence). On UNIX, TESTFN_UNDECODABLE can be decoded by os.fsdecode() thanks
121
+ # to the surrogateescape error handler (PEP 383), but not from the filesystem
122
+ # encoding in strict mode.
123
+ TESTFN_UNDECODABLE = None
124
+ for name in (
125
+ # b'\xff' is not decodable by os.fsdecode() with code page 932. Windows
126
+ # accepts it to create a file or a directory, or don't accept to enter to
127
+ # such directory (when the bytes name is used). So test b'\xe7' first:
128
+ # it is not decodable from cp932.
129
+ b'\xe7w\xf0',
130
+ # undecodable from ASCII, UTF-8
131
+ b'\xff',
132
+ # undecodable from iso8859-3, iso8859-6, iso8859-7, cp424, iso8859-8, cp856
133
+ # and cp857
134
+ b'\xae\xd5'
135
+ # undecodable from UTF-8 (UNIX and Mac OS X)
136
+ b'\xed\xb2\x80', b'\xed\xb4\x80',
137
+ # undecodable from shift_jis, cp869, cp874, cp932, cp1250, cp1251, cp1252,
138
+ # cp1253, cp1254, cp1255, cp1257, cp1258
139
+ b'\x81\x98',
140
+ ):
141
+ try:
142
+ name.decode(sys.getfilesystemencoding())
143
+ except UnicodeDecodeError:
144
+ TESTFN_UNDECODABLE = os.fsencode(TESTFN_ASCII) + name
145
+ break
146
+
147
+ if FS_NONASCII:
148
+ TESTFN_NONASCII = TESTFN_ASCII + FS_NONASCII
149
+ else:
150
+ TESTFN_NONASCII = None
151
+ TESTFN = TESTFN_NONASCII or TESTFN_ASCII
152
+
153
+
154
+ def make_bad_fd():
155
+ """
156
+ Create an invalid file descriptor by opening and closing a file and return
157
+ its fd.
158
+ """
159
+ file = open(TESTFN, "wb")
160
+ try:
161
+ return file.fileno()
162
+ finally:
163
+ file.close()
164
+ unlink(TESTFN)
165
+
166
+
167
+ _can_symlink = None
168
+
169
+
170
+ def can_symlink():
171
+ global _can_symlink
172
+ if _can_symlink is not None:
173
+ return _can_symlink
174
+ symlink_path = TESTFN + "can_symlink"
175
+ try:
176
+ os.symlink(TESTFN, symlink_path)
177
+ can = True
178
+ except (OSError, NotImplementedError, AttributeError):
179
+ can = False
180
+ else:
181
+ os.remove(symlink_path)
182
+ _can_symlink = can
183
+ return can
184
+
185
+
186
+ def skip_unless_symlink(test):
187
+ """Skip decorator for tests that require functional symlink"""
188
+ ok = can_symlink()
189
+ msg = "Requires functional symlink implementation"
190
+ return test if ok else unittest.skip(msg)(test)
191
+
192
+
193
+ _can_xattr = None
194
+
195
+
196
+ def can_xattr():
197
+ import tempfile
198
+ global _can_xattr
199
+ if _can_xattr is not None:
200
+ return _can_xattr
201
+ if not hasattr(os, "setxattr"):
202
+ can = False
203
+ else:
204
+ import platform
205
+ tmp_dir = tempfile.mkdtemp()
206
+ tmp_fp, tmp_name = tempfile.mkstemp(dir=tmp_dir)
207
+ try:
208
+ with open(TESTFN, "wb") as fp:
209
+ try:
210
+ # TESTFN & tempfile may use different file systems with
211
+ # different capabilities
212
+ os.setxattr(tmp_fp, b"user.test", b"")
213
+ os.setxattr(tmp_name, b"trusted.foo", b"42")
214
+ os.setxattr(fp.fileno(), b"user.test", b"")
215
+ # Kernels < 2.6.39 don't respect setxattr flags.
216
+ kernel_version = platform.release()
217
+ m = re.match(r"2.6.(\d{1,2})", kernel_version)
218
+ can = m is None or int(m.group(1)) >= 39
219
+ except OSError:
220
+ can = False
221
+ finally:
222
+ unlink(TESTFN)
223
+ unlink(tmp_name)
224
+ rmdir(tmp_dir)
225
+ _can_xattr = can
226
+ return can
227
+
228
+
229
+ def skip_unless_xattr(test):
230
+ """Skip decorator for tests that require functional extended attributes"""
231
+ ok = can_xattr()
232
+ msg = "no non-broken extended attribute support"
233
+ return test if ok else unittest.skip(msg)(test)
234
+
235
+
236
+ def unlink(filename):
237
+ try:
238
+ _unlink(filename)
239
+ except (FileNotFoundError, NotADirectoryError):
240
+ pass
241
+
242
+
243
+ if sys.platform.startswith("win"):
244
+ def _waitfor(func, pathname, waitall=False):
245
+ # Perform the operation
246
+ func(pathname)
247
+ # Now setup the wait loop
248
+ if waitall:
249
+ dirname = pathname
250
+ else:
251
+ dirname, name = os.path.split(pathname)
252
+ dirname = dirname or '.'
253
+ # Check for `pathname` to be removed from the filesystem.
254
+ # The exponential backoff of the timeout amounts to a total
255
+ # of ~1 second after which the deletion is probably an error
256
+ # anyway.
257
+ # Testing on an i7@4.3GHz shows that usually only 1 iteration is
258
+ # required when contention occurs.
259
+ timeout = 0.001
260
+ while timeout < 1.0:
261
+ # Note we are only testing for the existence of the file(s) in
262
+ # the contents of the directory regardless of any security or
263
+ # access rights. If we have made it this far, we have sufficient
264
+ # permissions to do that much using Python's equivalent of the
265
+ # Windows API FindFirstFile.
266
+ # Other Windows APIs can fail or give incorrect results when
267
+ # dealing with files that are pending deletion.
268
+ L = os.listdir(dirname)
269
+ if not (L if waitall else name in L):
270
+ return
271
+ # Increase the timeout and try again
272
+ time.sleep(timeout)
273
+ timeout *= 2
274
+ warnings.warn('tests may fail, delete still pending for ' + pathname,
275
+ RuntimeWarning, stacklevel=4)
276
+
277
+ def _unlink(filename):
278
+ _waitfor(os.unlink, filename)
279
+
280
+ def _rmdir(dirname):
281
+ _waitfor(os.rmdir, dirname)
282
+
283
+ def _rmtree(path):
284
+ from test.support import _force_run
285
+
286
+ def _rmtree_inner(path):
287
+ for name in _force_run(path, os.listdir, path):
288
+ fullname = os.path.join(path, name)
289
+ try:
290
+ mode = os.lstat(fullname).st_mode
291
+ except OSError as exc:
292
+ print("support.rmtree(): os.lstat(%r) failed with %s"
293
+ % (fullname, exc),
294
+ file=sys.__stderr__)
295
+ mode = 0
296
+ if stat.S_ISDIR(mode):
297
+ _waitfor(_rmtree_inner, fullname, waitall=True)
298
+ _force_run(fullname, os.rmdir, fullname)
299
+ else:
300
+ _force_run(fullname, os.unlink, fullname)
301
+ _waitfor(_rmtree_inner, path, waitall=True)
302
+ _waitfor(lambda p: _force_run(p, os.rmdir, p), path)
303
+
304
+ def _longpath(path):
305
+ try:
306
+ import ctypes
307
+ except ImportError:
308
+ # No ctypes means we can't expands paths.
309
+ pass
310
+ else:
311
+ buffer = ctypes.create_unicode_buffer(len(path) * 2)
312
+ length = ctypes.windll.kernel32.GetLongPathNameW(path, buffer,
313
+ len(buffer))
314
+ if length:
315
+ return buffer[:length]
316
+ return path
317
+ else:
318
+ _unlink = os.unlink
319
+ _rmdir = os.rmdir
320
+
321
+ def _rmtree(path):
322
+ import shutil
323
+ try:
324
+ shutil.rmtree(path)
325
+ return
326
+ except OSError:
327
+ pass
328
+
329
+ def _rmtree_inner(path):
330
+ from test.support import _force_run
331
+ for name in _force_run(path, os.listdir, path):
332
+ fullname = os.path.join(path, name)
333
+ try:
334
+ mode = os.lstat(fullname).st_mode
335
+ except OSError:
336
+ mode = 0
337
+ if stat.S_ISDIR(mode):
338
+ _rmtree_inner(fullname)
339
+ _force_run(path, os.rmdir, fullname)
340
+ else:
341
+ _force_run(path, os.unlink, fullname)
342
+ _rmtree_inner(path)
343
+ os.rmdir(path)
344
+
345
+ def _longpath(path):
346
+ return path
347
+
348
+
349
+ def rmdir(dirname):
350
+ try:
351
+ _rmdir(dirname)
352
+ except FileNotFoundError:
353
+ pass
354
+
355
+
356
+ def rmtree(path):
357
+ try:
358
+ _rmtree(path)
359
+ except FileNotFoundError:
360
+ pass
361
+
362
+
363
+ @contextlib.contextmanager
364
+ def temp_dir(path=None, quiet=False):
365
+ """Return a context manager that creates a temporary directory.
366
+
367
+ Arguments:
368
+
369
+ path: the directory to create temporarily. If omitted or None,
370
+ defaults to creating a temporary directory using tempfile.mkdtemp.
371
+
372
+ quiet: if False (the default), the context manager raises an exception
373
+ on error. Otherwise, if the path is specified and cannot be
374
+ created, only a warning is issued.
375
+
376
+ """
377
+ import tempfile
378
+ dir_created = False
379
+ if path is None:
380
+ path = tempfile.mkdtemp()
381
+ dir_created = True
382
+ path = os.path.realpath(path)
383
+ else:
384
+ try:
385
+ os.mkdir(path)
386
+ dir_created = True
387
+ except OSError as exc:
388
+ if not quiet:
389
+ raise
390
+ warnings.warn(f'tests may fail, unable to create '
391
+ f'temporary directory {path!r}: {exc}',
392
+ RuntimeWarning, stacklevel=3)
393
+ if dir_created:
394
+ pid = os.getpid()
395
+ try:
396
+ yield path
397
+ finally:
398
+ # In case the process forks, let only the parent remove the
399
+ # directory. The child has a different process id. (bpo-30028)
400
+ if dir_created and pid == os.getpid():
401
+ rmtree(path)
402
+
403
+
404
+ @contextlib.contextmanager
405
+ def change_cwd(path, quiet=False):
406
+ """Return a context manager that changes the current working directory.
407
+
408
+ Arguments:
409
+
410
+ path: the directory to use as the temporary current working directory.
411
+
412
+ quiet: if False (the default), the context manager raises an exception
413
+ on error. Otherwise, it issues only a warning and keeps the current
414
+ working directory the same.
415
+
416
+ """
417
+ saved_dir = os.getcwd()
418
+ try:
419
+ os.chdir(os.path.realpath(path))
420
+ except OSError as exc:
421
+ if not quiet:
422
+ raise
423
+ warnings.warn(f'tests may fail, unable to change the current working '
424
+ f'directory to {path!r}: {exc}',
425
+ RuntimeWarning, stacklevel=3)
426
+ try:
427
+ yield os.getcwd()
428
+ finally:
429
+ os.chdir(saved_dir)
430
+
431
+
432
+ @contextlib.contextmanager
433
+ def temp_cwd(name='tempcwd', quiet=False):
434
+ """
435
+ Context manager that temporarily creates and changes the CWD.
436
+
437
+ The function temporarily changes the current working directory
438
+ after creating a temporary directory in the current directory with
439
+ name *name*. If *name* is None, the temporary directory is
440
+ created using tempfile.mkdtemp.
441
+
442
+ If *quiet* is False (default) and it is not possible to
443
+ create or change the CWD, an error is raised. If *quiet* is True,
444
+ only a warning is raised and the original CWD is used.
445
+
446
+ """
447
+ with temp_dir(path=name, quiet=quiet) as temp_path:
448
+ with change_cwd(temp_path, quiet=quiet) as cwd_dir:
449
+ yield cwd_dir
450
+
451
+
452
+ def create_empty_file(filename):
453
+ """Create an empty file. If the file already exists, truncate it."""
454
+ fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
455
+ os.close(fd)
456
+
457
+
458
+ @contextlib.contextmanager
459
+ def open_dir_fd(path):
460
+ """Open a file descriptor to a directory."""
461
+ assert os.path.isdir(path)
462
+ dir_fd = os.open(path, os.O_RDONLY)
463
+ try:
464
+ yield dir_fd
465
+ finally:
466
+ os.close(dir_fd)
467
+
468
+
469
+ def fs_is_case_insensitive(directory):
470
+ """Detects if the file system for the specified directory
471
+ is case-insensitive."""
472
+ import tempfile
473
+ with tempfile.NamedTemporaryFile(dir=directory) as base:
474
+ base_path = base.name
475
+ case_path = base_path.upper()
476
+ if case_path == base_path:
477
+ case_path = base_path.lower()
478
+ try:
479
+ return os.path.samefile(base_path, case_path)
480
+ except FileNotFoundError:
481
+ return False
482
+
483
+
484
+ class FakePath:
485
+ """Simple implementing of the path protocol.
486
+ """
487
+ def __init__(self, path):
488
+ self.path = path
489
+
490
+ def __repr__(self):
491
+ return f'<FakePath {self.path!r}>'
492
+
493
+ def __fspath__(self):
494
+ if (isinstance(self.path, BaseException) or
495
+ isinstance(self.path, type) and
496
+ issubclass(self.path, BaseException)):
497
+ raise self.path
498
+ else:
499
+ return self.path
500
+
501
+
502
+ def fd_count():
503
+ """Count the number of open file descriptors.
504
+ """
505
+ if sys.platform.startswith(('linux', 'freebsd')):
506
+ try:
507
+ names = os.listdir("/proc/self/fd")
508
+ # Subtract one because listdir() internally opens a file
509
+ # descriptor to list the content of the /proc/self/fd/ directory.
510
+ return len(names) - 1
511
+ except FileNotFoundError:
512
+ pass
513
+
514
+ MAXFD = 256
515
+ if hasattr(os, 'sysconf'):
516
+ try:
517
+ MAXFD = os.sysconf("SC_OPEN_MAX")
518
+ except OSError:
519
+ pass
520
+
521
+ old_modes = None
522
+ if sys.platform == 'win32':
523
+ # bpo-25306, bpo-31009: Call CrtSetReportMode() to not kill the process
524
+ # on invalid file descriptor if Python is compiled in debug mode
525
+ try:
526
+ import msvcrt
527
+ msvcrt.CrtSetReportMode
528
+ except (AttributeError, ImportError):
529
+ # no msvcrt or a release build
530
+ pass
531
+ else:
532
+ old_modes = {}
533
+ for report_type in (msvcrt.CRT_WARN,
534
+ msvcrt.CRT_ERROR,
535
+ msvcrt.CRT_ASSERT):
536
+ old_modes[report_type] = msvcrt.CrtSetReportMode(report_type,
537
+ 0)
538
+
539
+ try:
540
+ count = 0
541
+ for fd in range(MAXFD):
542
+ try:
543
+ # Prefer dup() over fstat(). fstat() can require input/output
544
+ # whereas dup() doesn't.
545
+ fd2 = os.dup(fd)
546
+ except OSError as e:
547
+ if e.errno != errno.EBADF:
548
+ raise
549
+ else:
550
+ os.close(fd2)
551
+ count += 1
552
+ finally:
553
+ if old_modes is not None:
554
+ for report_type in (msvcrt.CRT_WARN,
555
+ msvcrt.CRT_ERROR,
556
+ msvcrt.CRT_ASSERT):
557
+ msvcrt.CrtSetReportMode(report_type, old_modes[report_type])
558
+
559
+ return count
560
+
561
+
562
+ if hasattr(os, "umask"):
563
+ @contextlib.contextmanager
564
+ def temp_umask(umask):
565
+ """Context manager that temporarily sets the process umask."""
566
+ oldmask = os.umask(umask)
567
+ try:
568
+ yield
569
+ finally:
570
+ os.umask(oldmask)
571
+
572
+
573
+ class EnvironmentVarGuard(collections.abc.MutableMapping):
574
+
575
+ """Class to help protect the environment variable properly. Can be used as
576
+ a context manager."""
577
+
578
+ def __init__(self):
579
+ self._environ = os.environ
580
+ self._changed = {}
581
+
582
+ def __getitem__(self, envvar):
583
+ return self._environ[envvar]
584
+
585
+ def __setitem__(self, envvar, value):
586
+ # Remember the initial value on the first access
587
+ if envvar not in self._changed:
588
+ self._changed[envvar] = self._environ.get(envvar)
589
+ self._environ[envvar] = value
590
+
591
+ def __delitem__(self, envvar):
592
+ # Remember the initial value on the first access
593
+ if envvar not in self._changed:
594
+ self._changed[envvar] = self._environ.get(envvar)
595
+ if envvar in self._environ:
596
+ del self._environ[envvar]
597
+
598
+ def keys(self):
599
+ return self._environ.keys()
600
+
601
+ def __iter__(self):
602
+ return iter(self._environ)
603
+
604
+ def __len__(self):
605
+ return len(self._environ)
606
+
607
+ def set(self, envvar, value):
608
+ self[envvar] = value
609
+
610
+ def unset(self, envvar):
611
+ del self[envvar]
612
+
613
+ def __enter__(self):
614
+ return self
615
+
616
+ def __exit__(self, *ignore_exc):
617
+ for (k, v) in self._changed.items():
618
+ if v is None:
619
+ if k in self._environ:
620
+ del self._environ[k]
621
+ else:
622
+ self._environ[k] = v
623
+ os.environ = self._environ