Debian Codegraph @

tests/conftest.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 import hashlib
18 import logging
19 from pathlib import Path
20 import re
21 from shutil import rmtree
22 import time
23 from typing import Callable, List, Optional, Tuple
24
25 import pytest
26
27 from cylc.flow import LOG, flags
28 from cylc.flow.cfgspec.glbl_cfg import glbl_cfg
29 from cylc.flow.cfgspec.globalcfg import SPEC
30 from cylc.flow.graphnode import GraphNodeParser
31 from cylc.flow.parsec.config import ParsecConfig
32 from cylc.flow.parsec.validate import cylc_config_validate
33
34
35 @pytest.fixture(autouse=True)
36 def before_each():
37 """Reset global state before every test."""
38 flags.verbosity = 0
39 flags.cylc7_back_compat = False
40 LOG.setLevel(logging.NOTSET)
41 # Reset graph node parser singleton:
42 GraphNodeParser.get_inst().clear()
43
44
45 @pytest.fixture(scope='module')
46 def mod_monkeypatch():
47 """A module-scoped version of the monkeypatch fixture."""
48 from _pytest.monkeypatch import MonkeyPatch
49 mpatch = MonkeyPatch()
50 yield mpatch
51 mpatch.undo()
52
53
54 @pytest.fixture
55 def mock_glbl_cfg(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
56 """A Pytest fixture for fiddling global config values.
57
58 * Hacks the specified `glbl_cfg` object.
59 * Can be called multiple times within a test function.
60
61 Args:
62 pypath (str):
63 The python-like path to the global configuation object you want
64 to fiddle.
65 E.G. if you want to hack the `glbl_cfg` in
66 `cylc.flow.scheduler` you would provide
67 `cylc.flow.scheduler.glbl_cfg`
68 global_config (str):
69 The globlal configuration as a multi-line string.
70
71 Example:
72 Change the value of `UTC mode` in the global config as seen from
73 `the scheduler` module.
74
75 def test_something(mock_glbl_cfg):
76 mock_glbl_cfg(
77 'cylc.flow.scheduler.glbl_cfg',
78 '''
79 [scheduler]
80 UTC mode = True
81 '''
82 )
83
84 """
85 # TODO: modify Parsec so we can use StringIO rather than a temp file.
86 def _mock_glbl_cfg(pypath: str, global_config: str) -> None:
87 global_config_path = tmp_path / 'global.cylc'
88 global_config_path.write_text(global_config)
89 glbl_cfg = ParsecConfig(SPEC, validator=cylc_config_validate)
90 glbl_cfg.loadcfg(global_config_path)
91
92 def _inner(cached=False):
93 return glbl_cfg
94
95 monkeypatch.setattr(pypath, _inner)
96
97 yield _mock_glbl_cfg
98 rmtree(tmp_path)
99
100
101 @pytest.fixture
102 def log_filter(caplog: pytest.LogCaptureFixture):
103 """Filter caplog record_tuples (also discarding the log name entry).
104
105 Args:
106 level: Filter out records if they aren't at this logging level.
107 contains: Filter out records if this string is not in the message.
108 regex: Filter out records if the message doesn't match this regex.
109 exact_match: Filter out records if the message does not exactly match
110 this string.
111 log: A caplog instance.
112 """
113 def _log_filter(
114 level: Optional[int] = None,
115 contains: Optional[str] = None,
116 regex: Optional[str] = None,
117 exact_match: Optional[str] = None,
118 log: Optional[pytest.LogCaptureFixture] = None
119 ) -> List[Tuple[int, str]]:
120 if log is None:
121 log = caplog
122 return [
123 (log_level, log_message)
124 for _, log_level, log_message in log.record_tuples
125 if (level is None or level == log_level)
126 and (contains is None or contains in log_message)
127 and (regex is None or re.search(regex, log_message))
128 and (exact_match is None or exact_match == log_message)
129 ]
130 return _log_filter
131
132
133 @pytest.fixture
134 def log_scan():
135 """Ensure log messages appear in the correct order.
136
137 TRY TO AVOID DOING THIS!
138
139 If you are trying to test a sequence of events you are likely better off
140 doing this a different way (e.g. mock the functions you are interested in
141 and test the call arguments/returns later).
142
143 However, there are some occasions where this might be necessary, e.g.
144 testing a monolithic synchronous function.
145
146 Args:
147 log: The caplog fixture.
148 items: Iterable of string messages to compare. All are tested
149 by "contains" i.e. "item in string".
150
151 """
152 def _log_scan(log, items):
153 records = iter(log.records)
154 record = next(records)
155 for item in items:
156 while item not in record.message:
157 try:
158 record = next(records)
159 except StopIteration:
160 raise Exception(f'Reached end of log looking for: {item}')
161
162 return _log_scan
163
164
165 @pytest.fixture(scope='session')
166 def port_range():
167 return glbl_cfg().get(['scheduler', 'run hosts', 'ports'])
168
169
170 @pytest.fixture
171 def capcall(monkeypatch):
172 """Capture function calls without running the function.
173
174 Returns a list which is populated with function calls.
175
176 Args:
177 function_string:
178 The function to replace as it would be specified to
179 monkeypatch.setattr.
180 mock:
181 * If True, the function will be replaced by a "return None".
182 * If False, the original function will be run.
183 * If a Callable is provided, this will be run in place of the
184 original function.
185
186 Returns:
187 [(args: Tuple, kwargs: Dict), ...]
188
189 Example:
190 def test_something(capcall):
191 capsys = capcall('sys.exit')
192 sys.exit(1)
193 assert capsys == [(1,), {}]
194
195 """
196
197 def _capcall(function_string: str, mock: bool | Callable = True):
198 calls = []
199
200 if mock is True:
201 fcn = lambda *args, **kwargs: None
202 elif mock is False:
203 fcn = import_object_from_string(function_string)
204 else:
205 fcn = mock
206
207 def _call(*args, **kwargs):
208 calls.append((args, kwargs))
209 return fcn(*args, **kwargs)
210
211 monkeypatch.setattr(function_string, _call)
212 return calls
213
214 return _capcall
215
216
217 def import_object_from_string(string):
218 """Import a Python object from a string path.
219
220 The path may reference a module, function, class, method, whatever.
221
222 Examples:
223 # import a module
224 >>> import_object_from_string('os')
225 <module 'os' ...>
226
227 # import a function
228 >>> import_object_from_string('os.path.walk')
229 <function walk at ...>
230
231 # import a constant from a namespace package
232 >>> import_object_from_string('cylc.flow.LOG')
233 <Logger cylc (WARNING)>
234
235 # import a class
236 >>> import_object_from_string('pathlib.Path')
237 <class 'pathlib.Path'>
238
239 # import a method
240 >>> import_object_from_string('pathlib.Path.exists')
241 <function Path.exists ...>
242
243 """
244 head = string
245 tail = []
246 while True:
247 try:
248 # try and import the thing
249 module = __import__(head)
250 except ModuleNotFoundError:
251 # if it's not something we can import, lop the last item off the
252 # end of the string and repeat
253 if '.' in head:
254 head, _tail = head.rsplit('.', 1)
255 tail.append(_tail)
256 else:
257 # we definitely can't import this
258 raise
259 else:
260 # we managed to import something
261 if '(namespace)' in str(module):
262 # with namespace packages you have to pull the module out of
263 # the package yourself
264 for part in head.split('.')[1:]:
265 module = getattr(module, part)
266 break
267
268 # extract the requested object from the module (if requested)
269 obj = module
270 for part in reversed(tail):
271 obj = getattr(obj, part)
272
273 return obj
274
275
276 @pytest.fixture
277 def set_timezone(monkeypatch):
278 """Fixture to temporarily set a timezone.
279
280 Will use a very implausible timezone if none is provided.
281 """
282 def patch(time_zone: str = 'XXX-19:17'):
283 monkeypatch.setenv('TZ', time_zone)
284 time.tzset()
285
286 try:
287 yield patch
288 finally:
289 # Reset to the original time zone after the test
290 monkeypatch.undo()
291 time.tzset()
292
293
294 @pytest.fixture(scope='module')
295 def mod_tmp_path(tmp_path_factory: pytest.TempPathFactory):
296 """A module scoped version of tmp_path.
297
298 Yields a temporary directory which will persist for all tests in the same
299 module.
300
301 Note:
302 Each invovation of this fixture yields a different directory, even if
303 they are in the same module.
304
305 I.e, the yielded directory will persist within the scope of the module,
306 rather than the yielded directory is consistent within the scope of the
307 module
308
309 """
310 yield tmp_path_factory.mktemp(hashlib.sha256().hexdigest()[:10])