Debian Codegraph @

tests/unit/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 """Standard pytest fixtures for unit tests."""
18
19 from pathlib import Path
20 from textwrap import dedent
21 from typing import (
22 Any,
23 Callable,
24 Optional,
25 Union,
26 )
27 from unittest.mock import (
28 Mock,
29 create_autospec,
30 )
31
32 import pytest
33
34 from cylc.flow.cycling.iso8601 import init as iso8601_init
35 from cylc.flow.cycling.loader import (
36 INTEGER_CYCLING_TYPE,
37 ISO8601_CYCLING_TYPE,
38 )
39 from cylc.flow.data_store_mgr import DataStoreMgr
40 from cylc.flow.install import (
41 link_runN,
42 unlink_runN,
43 )
44 from cylc.flow.scheduler import Scheduler
45 from cylc.flow.workflow_files import WorkflowFiles
46 from cylc.flow.xtrigger_mgr import XtriggerManager
47
48
49 # Type alias for monkeymock()
50 MonkeyMock = Callable[..., Mock]
51
52
53 @pytest.fixture
54 def monkeymock(monkeypatch: pytest.MonkeyPatch):
55 """Fixture that patches a function/attr with a Mock and returns that Mock.
56
57 Args:
58 pypath: The Python-style import path to be patched.
59 **kwargs: Any kwargs to set on the Mock.
60
61 Example:
62 mock_clean = monkeymock('cylc.flow.workflow_files.clean')
63 something() # calls workflow_files.clean
64 assert mock_clean.called is True
65 """
66 def _monkeymock(pypath: str, **kwargs: Any) -> Mock:
67 _mock = Mock(**kwargs)
68 monkeypatch.setattr(pypath, _mock)
69 return _mock
70 return _monkeymock
71
72
73 def _tmp_run_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
74 """Fixture that patches the cylc-run dir to the tests's
75 {tmp_path}/cylc-run, and optionally creates a workflow run dir inside.
76
77 Adds the runN symlink automatically if the workflow ID ends with /run__.
78
79 Args:
80 id_: Workflow name.
81 installed: If True, make it look like the workflow was installed
82 using cylc install (creates _cylc-install dir).
83 named: If True and installed is True, the _cylc-install dir will
84 be created in the parent to make it look like this is a
85 named run.
86
87 Example:
88 run_dir = tmp_run_dir('foo')
89 # Or:
90 cylc_run_dir = tmp_run_dir()
91 """
92 cylc_run_dir = tmp_path / 'cylc-run'
93 cylc_run_dir.mkdir(exist_ok=True)
94 monkeypatch.setattr('cylc.flow.pathutil._CYLC_RUN_DIR', cylc_run_dir)
95
96 def __tmp_run_dir(
97 id_: Optional[str] = None,
98 installed: bool = False,
99 named: bool = False
100 ) -> Path:
101 if not id_:
102 return cylc_run_dir
103
104 run_dir = cylc_run_dir.joinpath(id_)
105 run_dir.mkdir(parents=True, exist_ok=True)
106 (run_dir / WorkflowFiles.FLOW_FILE).touch(exist_ok=True)
107 (run_dir / WorkflowFiles.Service.DIRNAME).mkdir(exist_ok=True)
108 if run_dir.name.startswith('run'):
109 unlink_runN(run_dir.parent)
110 link_runN(run_dir)
111 if installed:
112 if named:
113 if len(Path(id_).parts) < 2:
114 raise ValueError("Named run requires two-level id_")
115 (run_dir.parent / WorkflowFiles.Install.DIRNAME).mkdir(
116 exist_ok=True)
117 else:
118 (run_dir / WorkflowFiles.Install.DIRNAME).mkdir(exist_ok=True)
119
120 return run_dir
121
122 return __tmp_run_dir
123
124
125 @pytest.fixture
126 def tmp_run_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
127 return _tmp_run_dir(tmp_path, monkeypatch)
128
129
130 @pytest.fixture(scope='module')
131 def mod_tmp_run_dir(tmp_path_factory: pytest.TempPathFactory):
132 """Module-scoped version of tmp_run_dir()"""
133 tmp_path = tmp_path_factory.getbasetemp()
134 with pytest.MonkeyPatch.context() as mp:
135 yield _tmp_run_dir(tmp_path, mp)
136
137
138 def _tmp_src_dir(tmp_path: Path):
139 """Fixture that creates a temporary workflow source dir.
140
141 (Actually the fixture is below, this is the re-usable meat of it.)
142
143 Args:
144 path: Path of source dir relative to cylc-src/.
145
146 Example:
147 src_dir = tmp_src_dir('foo')
148 """
149 def __tmp_src_dir(path: Union[Path, str]) -> Path:
150 cylc_src_dir = tmp_path / 'cylc-src'
151 cylc_src_dir.mkdir(exist_ok=True)
152 src_dir = cylc_src_dir / path
153 src_dir.mkdir(parents=True)
154 (src_dir / WorkflowFiles.FLOW_FILE).touch()
155 return src_dir
156 return __tmp_src_dir
157
158
159 @pytest.fixture
160 def tmp_src_dir(tmp_path: Path):
161 # This is the actual tmp_src_dir fixture
162 return _tmp_src_dir(tmp_path)
163
164
165 @pytest.fixture(scope='module')
166 def mod_tmp_src_dir(tmp_path_factory: pytest.TempPathFactory):
167 """Module-scoped version of tmp_src_dir()"""
168 tmp_path = tmp_path_factory.getbasetemp()
169 return _tmp_src_dir(tmp_path)
170
171
172 @pytest.fixture
173 def set_cycling_type(monkeypatch: pytest.MonkeyPatch):
174 """Initialize the Cylc cycling type.
175
176 Args:
177 ctype: The cycling type (integer or iso8601).
178 time_zone: If using ISO8601/datetime cycling type, you can specify a
179 custom time zone to use.
180 dump_format: If using ISO8601, specify custom dump format.
181 """
182
183 def _set_cycling_type(
184 ctype: str = INTEGER_CYCLING_TYPE,
185 time_zone: Optional[str] = 'Z',
186 dump_format: Optional[str] = None,
187 ) -> None:
188 class _DefaultCycler:
189 TYPE = ctype
190
191 monkeypatch.setattr(
192 'cylc.flow.cycling.loader.DefaultCycler', _DefaultCycler
193 )
194 if ctype == ISO8601_CYCLING_TYPE:
195 monkeypatch.setattr(
196 'cylc.flow.cycling.iso8601.WorkflowSpecifics',
197 iso8601_init(
198 time_zone=time_zone, custom_dump_format=dump_format
199 ),
200 )
201
202 return _set_cycling_type
203
204
205 @pytest.fixture
206 def xtrigger_mgr() -> XtriggerManager:
207 """A fixture to build an XtriggerManager which uses a mocked proc_pool,
208 and uses a mocked broadcast_mgr."""
209 workflow_name = "sample_workflow"
210 user = "john-foo"
211 schd = create_autospec(Scheduler, workflow=workflow_name, owner=user)
212 schd.proc_pool = Mock(put_command=lambda *a, **k: True)
213 schd.workflow_db_mgr = Mock(housekeep=lambda *a, **k: True)
214 schd.broadcast_mgr = Mock(put_broadcast=lambda *a, **k: True)
215 schd.data_store_mgr = DataStoreMgr(schd)
216 return XtriggerManager(schd)
217
218
219 @pytest.fixture()
220 def prevent_symlinking(monkeypatch: pytest.MonkeyPatch):
221 monkeypatch.setattr(
222 'cylc.flow.pathutil.make_symlink_dir',
223 lambda *_, **__: {}
224 )
225
226
227 def _tmp_flow_config(tmp_run_dir: Callable):
228 """Create a temporary flow config file for use in init'ing WorkflowConfig.
229 Args:
230 id_: Workflow name.
231 config: The flow file content.
232 Returns the path to the flow file.
233 """
234 def __tmp_flow_config(id_: str, config: str) -> 'Path':
235 run_dir: 'Path' = tmp_run_dir(id_)
236 flow_file = run_dir / WorkflowFiles.FLOW_FILE
237 flow_file.write_text(dedent(config).lstrip())
238 return flow_file
239 return __tmp_flow_config
240
241
242 @pytest.fixture
243 def tmp_flow_config(tmp_run_dir: Callable):
244 return _tmp_flow_config(tmp_run_dir)
245
246
247 @pytest.fixture(scope='module')
248 def mod_tmp_flow_config(mod_tmp_run_dir: Callable):
249 return _tmp_flow_config(mod_tmp_run_dir)