"Fossies" - the Fresh Open Source Software Archive 
Member "salt-3002.2/tests/support/pytest/helpers.py" (18 Nov 2020, 8868 Bytes) of package /linux/misc/salt-3002.2.tar.gz:
As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style:
standard) with prefixed line numbers.
Alternatively you can here
view or
download the uninterpreted source code file.
For more information about "helpers.py" see the
Fossies "Dox" file reference documentation and the latest
Fossies "Diffs" side-by-side code changes report:
3002.1_vs_3002.2.
1 """
2 tests.support.pytest.helpers
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 PyTest helpers functions
6 """
7 import logging
8 import os
9 import shutil
10 import tempfile
11 import textwrap
12 import types
13 import warnings
14 from contextlib import contextmanager
15
16 import pytest
17 import salt.utils.files
18 from tests.support.pytest.loader import LoaderModuleMock
19 from tests.support.runtests import RUNTIME_VARS
20
21 log = logging.getLogger(__name__)
22
23 if not RUNTIME_VARS.PYTEST_SESSION:
24 # XXX: Remove this try/except once we fully switch to pytest
25
26 class FakePyTestHelpersNamespace:
27 __slots__ = ()
28
29 def register(self, func):
30 return func
31
32 # Patch pytest so it all works under runtests.py
33 pytest.helpers = FakePyTestHelpersNamespace()
34
35
36 @pytest.helpers.register
37 @contextmanager
38 def temp_directory(name=None):
39 """
40 This helper creates a temporary directory. It should be used as a context manager
41 which returns the temporary directory path, and, once out of context, deletes it.
42
43 Can be directly imported and used, or, it can be used as a pytest helper function if
44 ``pytest-helpers-namespace`` is installed.
45
46 .. code-block:: python
47
48 import os
49 import pytest
50
51 def test_blah():
52 with pytest.helpers.temp_directory() as tpath:
53 print(tpath)
54 assert os.path.exists(tpath)
55
56 assert not os.path.exists(tpath)
57 """
58 try:
59 if name is not None:
60 directory_path = os.path.join(RUNTIME_VARS.TMP, name)
61 else:
62 directory_path = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
63
64 if not os.path.isdir(directory_path):
65 os.makedirs(directory_path)
66
67 yield directory_path
68 finally:
69 shutil.rmtree(directory_path, ignore_errors=True)
70
71
72 @pytest.helpers.register
73 @contextmanager
74 def temp_file(name=None, contents=None, directory=None, strip_first_newline=True):
75 """
76 This helper creates a temporary file. It should be used as a context manager
77 which returns the temporary file path, and, once out of context, deletes it.
78
79 Can be directly imported and used, or, it can be used as a pytest helper function if
80 ``pytest-helpers-namespace`` is installed.
81
82 .. code-block:: python
83
84 import os
85 import pytest
86
87 def test_blah():
88 with pytest.helpers.temp_file("blah.txt") as tpath:
89 print(tpath)
90 assert os.path.exists(tpath)
91
92 assert not os.path.exists(tpath)
93
94 Args:
95 name(str):
96 The temporary file name
97 contents(str):
98 The contents of the temporary file
99 directory(str):
100 The directory where to create the temporary file. If ``None``, then ``RUNTIME_VARS.TMP``
101 will be used.
102 strip_first_newline(bool):
103 Wether to strip the initial first new line char or not.
104 """
105 try:
106 if directory is None:
107 directory = RUNTIME_VARS.TMP
108
109 if name is not None:
110 file_path = os.path.join(directory, name)
111 else:
112 handle, file_path = tempfile.mkstemp(dir=directory)
113 os.close(handle)
114
115 file_directory = os.path.dirname(file_path)
116 if not os.path.isdir(file_directory):
117 os.makedirs(file_directory)
118
119 if contents is not None:
120 if contents:
121 if contents.startswith("\n") and strip_first_newline:
122 contents = contents[1:]
123 file_contents = textwrap.dedent(contents)
124 else:
125 file_contents = contents
126
127 with salt.utils.files.fopen(file_path, "w") as wfh:
128 wfh.write(file_contents)
129
130 yield file_path
131
132 finally:
133 try:
134 os.unlink(file_path)
135 except OSError:
136 # Already deleted
137 pass
138
139
140 @pytest.helpers.register
141 def temp_state_file(name, contents, saltenv="base", strip_first_newline=True):
142 """
143 This helper creates a temporary state file. It should be used as a context manager
144 which returns the temporary state file path, and, once out of context, deletes it.
145
146 Can be directly imported and used, or, it can be used as a pytest helper function if
147 ``pytest-helpers-namespace`` is installed.
148
149 .. code-block:: python
150
151 import os
152 import pytest
153
154 def test_blah():
155 with pytest.helpers.temp_state_file("blah.sls") as tpath:
156 print(tpath)
157 assert os.path.exists(tpath)
158
159 assert not os.path.exists(tpath)
160
161 Depending on the saltenv, it will be created under ``RUNTIME_VARS.TMP_STATE_TREE`` or
162 ``RUNTIME_VARS.TMP_PRODENV_STATE_TREE``.
163
164 Args:
165 name(str):
166 The temporary state file name
167 contents(str):
168 The contents of the temporary file
169 saltenv(str):
170 The salt env to use. Either ``base`` or ``prod``
171 strip_first_newline(bool):
172 Wether to strip the initial first new line char or not.
173 """
174
175 if saltenv == "base":
176 directory = RUNTIME_VARS.TMP_BASEENV_STATE_TREE
177 elif saltenv == "prod":
178 directory = RUNTIME_VARS.TMP_PRODENV_STATE_TREE
179 else:
180 raise RuntimeError(
181 '"saltenv" can only be "base" or "prod", not "{}"'.format(saltenv)
182 )
183 return temp_file(
184 name, contents, directory=directory, strip_first_newline=strip_first_newline
185 )
186
187
188 @pytest.helpers.register
189 def temp_pillar_file(name, contents, saltenv="base", strip_first_newline=True):
190 """
191 This helper creates a temporary pillar file. It should be used as a context manager
192 which returns the temporary pillar file path, and, once out of context, deletes it.
193
194 Can be directly imported and used, or, it can be used as a pytest helper function if
195 ``pytest-helpers-namespace`` is installed.
196
197 .. code-block:: python
198
199 import os
200 import pytest
201
202 def test_blah():
203 with pytest.helpers.temp_pillar_file("blah.sls") as tpath:
204 print(tpath)
205 assert os.path.exists(tpath)
206
207 assert not os.path.exists(tpath)
208
209 Depending on the saltenv, it will be created under ``RUNTIME_VARS.TMP_PILLAR_TREE`` or
210 ``RUNTIME_VARS.TMP_PRODENV_PILLAR_TREE``.
211
212 Args:
213 name(str):
214 The temporary state file name
215 contents(str):
216 The contents of the temporary file
217 saltenv(str):
218 The salt env to use. Either ``base`` or ``prod``
219 strip_first_newline(bool):
220 Wether to strip the initial first new line char or not.
221 """
222
223 if saltenv == "base":
224 directory = RUNTIME_VARS.TMP_BASEENV_PILLAR_TREE
225 elif saltenv == "prod":
226 directory = RUNTIME_VARS.TMP_PRODENV_PILLAR_TREE
227 else:
228 raise RuntimeError(
229 '"saltenv" can only be "base" or "prod", not "{}"'.format(saltenv)
230 )
231 return temp_file(
232 name, contents, directory=directory, strip_first_newline=strip_first_newline
233 )
234
235
236 @pytest.helpers.register
237 def loader_mock(*args, **kwargs):
238 if len(args) > 1:
239 loader_modules = args[1]
240 warnings.warn(
241 "'request' is not longer an accepted argument to 'loader_mock()'. Please stop passing it.",
242 category=DeprecationWarning,
243 )
244 else:
245 loader_modules = args[0]
246 return LoaderModuleMock(loader_modules, **kwargs)
247
248
249 @pytest.helpers.register
250 def salt_loader_module_functions(module):
251 if not isinstance(module, types.ModuleType):
252 raise RuntimeError(
253 "The passed 'module' argument must be an imported "
254 "imported module, not {}".format(type(module))
255 )
256 funcs = {}
257 func_alias = getattr(module, "__func_alias__", {})
258 virtualname = getattr(module, "__virtualname__")
259 for name in dir(module):
260 if name.startswith("_"):
261 continue
262 func = getattr(module, name)
263 if getattr(func, "__module__", None) != module.__name__:
264 # Not eve defined on the module being processed, carry on
265 continue
266 if not isinstance(func, types.FunctionType):
267 # Not a function? carry on
268 continue
269 funcname = func_alias.get(func.__name__) or func.__name__
270 funcs["{}.{}".format(virtualname, funcname)] = func
271 return funcs
272
273
274 @pytest.helpers.register
275 def remove_stale_minion_key(master, minion_id):
276 key_path = os.path.join(master.config["pki_dir"], "minions", minion_id)
277 if os.path.exists(key_path):
278 os.unlink(key_path)
279 else:
280 log.debug("The minion(id=%r) key was not found at %s", minion_id, key_path)
281
282
283 # Only allow star importing the functions defined in this module
284 __all__ = [
285 name
286 for (name, func) in locals().items()
287 if getattr(func, "__module__", None) == __name__
288 ]