Debian Codegraph @

tests/_util.py

raw symbols SCIP
1 # -*- coding: ascii -*-
2 u"""
3 :Copyright:
4
5 Copyright 2014 - 2025
6 Andr\xe9 Malo or his licensors, as applicable
7
8 :License:
9
10 Licensed under the Apache License, Version 2.0 (the "License");
11 you may not use this file except in compliance with the License.
12 You may obtain a copy of the License at
13
14 http://www.apache.org/licenses/LICENSE-2.0
15
16 Unless required by applicable law or agreed to in writing, software
17 distributed under the License is distributed on an "AS IS" BASIS,
18 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 See the License for the specific language governing permissions and
20 limitations under the License.
21
22 ================
23 Test Utilities
24 ================
25
26 Test utilities.
27 """
28 __author__ = u"Andr\xe9 Malo"
29
30 import contextlib as _contextlib
31 import sys as _sys
32 import types as _types
33
34 from pytest import skip # noqa pylint: disable = unused-import
35
36 try:
37 import mock
38 except ImportError:
39 from unittest import mock
40
41 try:
42 reload # pylint: disable = used-before-assignment
43 except NameError:
44 # pylint: disable = redefined-builtin
45 try:
46 from importlib import reload
47 except ImportError:
48 from imp import reload # noqa pylint: disable = deprecated-module
49
50 _unset = type("_unset", (object,), {})() # pylint: disable=invalid-name
51
52
53 # pylint: disable = useless-object-inheritance
54
55
56 class Bunch(object):
57 """Bunch object"""
58
59 def __init__(self, **kwargs):
60 self.__dict__.update(kwargs)
61
62
63 @_contextlib.contextmanager
64 def patched_import(what, how=_unset):
65 """
66 Context manager to mock an import statement temporarily
67
68 Parameters:
69 what (str):
70 Name of the module to mock
71
72 how (any):
73 How should it be replaced? If omitted or `unset`, a new MagicMock
74 instance is created. The result is yielded as context.
75 """
76 # basically stolen from opensource.perlig.de/tdi/
77
78 class_types = (type,)
79 if str is bytes:
80 # pylint: disable = no-member
81 class_types += (_types.ClassType,)
82
83 # pylint: disable = unnecessary-lambda-assignment
84 _is_exc = lambda obj: isinstance(obj, BaseException) or (
85 isinstance(obj, class_types) and issubclass(obj, BaseException)
86 )
87
88 class FinderLoader(object):
89 """Finder / Loader for meta path"""
90
91 def __init__(self, fullname, module):
92 self.module = module
93 self.name = fullname
94 extra = "%s." % fullname
95 for key in list(_sys.modules):
96 if key.startswith(extra):
97 del _sys.modules[key]
98 if fullname in _sys.modules:
99 del _sys.modules[fullname]
100
101 def find_spec(self, name, path=None, target=None):
102 """Find spec (Python 3.10+)"""
103 # pylint: disable = unused-argument
104 if name != self.name:
105 return None
106
107 from importlib import util
108
109 return util.spec_from_loader(name, self)
110
111 def find_module(self, fullname, path=None):
112 """Find the module"""
113 # pylint: disable = unused-argument
114 if fullname == self.name:
115 return self
116 return None
117
118 def load_module(self, fullname):
119 """Load the module"""
120 if _is_exc(self.module):
121 raise self.module
122 _sys.modules[fullname] = self.module
123 return self.module
124
125 def create_module(self, spec):
126 """Create module"""
127 if _is_exc(self.module):
128 raise self.module
129 return self.module
130
131 def exec_module(self, module):
132 """Execute module"""
133
134 realmodules = _sys.modules.copy()
135 try:
136 obj = FinderLoader(what, mock.MagicMock() if how is _unset else how)
137 realpath = _sys.meta_path[:]
138 try:
139 _sys.meta_path[:] = [obj] + realpath
140 old, parts = _unset, what.rsplit(".", 1)
141 if len(parts) == 2:
142 parent, base = parts[0], parts[1]
143 if parent in _sys.modules:
144 parent = _sys.modules[parent]
145 if hasattr(parent, base):
146 old = getattr(parent, base)
147 setattr(parent, base, obj.module)
148 try:
149 yield obj.module
150 finally:
151 if old is not _unset:
152 setattr(parent, base, old)
153 finally:
154 _sys.meta_path[:] = realpath
155 finally:
156 _sys.modules.clear()
157 _sys.modules.update(realmodules)
158
159
160 def uni(value):
161 """
162 Create unicode from raw string with unicode escapes
163
164 Parameters:
165 value (str):
166 String, which encodes to ascii and decodes as unicode_escape
167
168 Returns:
169 str: The decoded string
170 """
171 return value.encode("ascii").decode("unicode_escape")
172
173
174 class badstr(object): # pylint: disable = invalid-name
175 """bad string"""
176
177 def __str__(self):
178 raise RuntimeError("yo")
179
180
181 badstr = badstr()
182
183
184 class badbytes(object): # pylint: disable = invalid-name
185 """bad bytes"""
186
187 def __bytes__(self):
188 raise RuntimeError("yoyo")
189
190 if str is bytes:
191 __str__ = __bytes__
192
193
194 badbytes = badbytes()
195
196
197 class badbool(object): # pylint: disable = invalid-name
198 """bad bool"""
199
200 def __bool__(self):
201 raise RuntimeError("yoyo")
202
203 if str is bytes:
204 __nonzero__ = __bool__
205
206
207 badbool = badbool()
208
209
210 class baditer(object): # pylint: disable = invalid-name
211 """bad iter"""
212
213 def __init__(self, *what):
214 self._what = iter(what)
215
216 def __iter__(self):
217 return self
218
219 def __next__(self):
220 for item in self._what:
221 if isinstance(item, Exception):
222 raise item
223 return item
224
225 next = __next__
226
227
228 def calls(value):
229 """
230 Map calls to list of tuples
231
232 Parameters:
233 value (Mock):
234 The mock object to inspect
235
236 Returns:
237 list: The List of call tuples
238 """
239 return list(map(tuple, value.mock_calls))