Debian Codegraph @

tests/integration/scripts/test_reinstall.py

raw
1 #!/usr/bin/env python3
2
3 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
4 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19 import asyncio
20 from contextlib import asynccontextmanager
21 from pathlib import Path
22 import re
23 from secrets import token_hex
24 from types import SimpleNamespace
25
26 from ansimarkup import strip as cstrip
27 import pytest
28
29 from cylc.flow.exceptions import WorkflowFilesError
30 from cylc.flow.install import reinstall_workflow
31 from cylc.flow.option_parsers import Options
32 from cylc.flow.scripts.reinstall import (
33 get_option_parser as reinstall_gop,
34 reinstall_cli,
35 )
36 from cylc.flow.workflow_files import WorkflowFiles
37
38 from ..utils.entry_points import EntryPointWrapper
39
40
41 ReInstallOptions = Options(reinstall_gop())
42
43 # cli opts
44
45 # interactive: yes no
46 # rose: yes no
47 # workflow_running: yes no
48
49
50 @pytest.fixture(autouse=True)
51 def color_strip(monkeypatch: pytest.MonkeyPatch):
52 """Strip colour as the normal colour stripping doesn't apply to tests."""
53 monkeypatch.setattr('cylc.flow.scripts.reinstall.cparse', cstrip)
54
55
56 @pytest.fixture
57 def interactive(monkeypatch):
58 monkeypatch.setattr(
59 'cylc.flow.scripts.reinstall.is_terminal',
60 lambda: True,
61 )
62
63
64 @pytest.fixture
65 def non_interactive(monkeypatch):
66 monkeypatch.setattr(
67 'cylc.flow.scripts.reinstall.is_terminal',
68 lambda: False,
69 )
70
71
72 @pytest.fixture
73 def answer_prompt(monkeypatch: pytest.MonkeyPatch):
74 """Answer reinstall prompt."""
75
76 def inner(answer: str):
77 monkeypatch.setattr(
78 'cylc.flow.scripts.reinstall._input', lambda x: answer
79 )
80
81 return inner
82
83
84 @pytest.fixture
85 def one_src(tmp_path):
86 src_dir = tmp_path / 'src'
87 src_dir.mkdir()
88 (src_dir / 'flow.cylc').touch()
89 (src_dir / 'rose-suite.conf').touch()
90 return SimpleNamespace(path=src_dir)
91
92
93 @pytest.fixture
94 def one_run(one_src, test_dir, run_dir):
95 w_run_dir = test_dir / token_hex(4)
96 w_run_dir.mkdir()
97 (w_run_dir / 'flow.cylc').touch()
98 (w_run_dir / 'rose-suite.conf').touch()
99 install_dir = (w_run_dir / WorkflowFiles.Install.DIRNAME)
100 install_dir.mkdir(parents=True)
101 (install_dir / WorkflowFiles.Install.SOURCE).symlink_to(
102 one_src.path,
103 target_is_directory=True,
104 )
105 return SimpleNamespace(
106 path=w_run_dir,
107 id=str(w_run_dir.relative_to(run_dir)),
108 )
109
110
111 async def test_rejects_random_workflows(one, one_run):
112 """It should only work with workflows installed by cylc install."""
113 with pytest.raises(WorkflowFilesError) as exc_ctx:
114 await reinstall_cli(opts=ReInstallOptions(), workflow_id=one.workflow)
115 assert 'was not installed with cylc install' in str(exc_ctx.value)
116
117
118 async def test_invalid_source_dir(one_src, one_run):
119 """It should detect & fail for an invalid source symlink"""
120 source_link = Path(
121 one_run.path,
122 WorkflowFiles.Install.DIRNAME,
123 WorkflowFiles.Install.SOURCE,
124 )
125 source_link.unlink()
126 source_link.symlink_to(one_src.path / 'flow.cylc')
127
128 with pytest.raises(WorkflowFilesError) as exc_ctx:
129 await reinstall_cli(opts=ReInstallOptions(), workflow_id=one_run.id)
130 assert 'Workflow source dir is not accessible' in str(exc_ctx.value)
131
132
133 async def test_no_changes_needed(one_src, one_run, capsys, interactive):
134 """It should not reinstall if no changes are needed.
135
136 This is not a hard requirement, in practice rsync output may differ
137 from expectation so this is a nice-to-have, not expected to work 100%
138 of the time.
139 """
140 assert not await reinstall_cli(
141 opts=ReInstallOptions(), workflow_id=one_run.id
142 )
143 assert 'up to date with' in capsys.readouterr().out
144
145
146 async def test_non_interactive(
147 one_src, one_run, capsys, capcall, non_interactive
148 ):
149 """It should not perform a dry-run or prompt in non-interactive mode."""
150 # capture reinstall calls
151 reinstall_calls = capcall(
152 'cylc.flow.scripts.reinstall.reinstall_workflow',
153 reinstall_workflow,
154 )
155 # give it something to reinstall
156 (one_src.path / 'a').touch()
157 # reinstall
158 assert await reinstall_cli(opts=ReInstallOptions(), workflow_id=one_run.id)
159 # only one rsync call should have been made (i.e. no --dry-run)
160 assert len(reinstall_calls) == 1
161 assert 'Successfully reinstalled' in capsys.readouterr().out
162
163
164 async def test_interactive(
165 one_src,
166 one_run,
167 capsys,
168 capcall,
169 interactive,
170 answer_prompt
171 ):
172 """It should perform a dry-run and prompt in interactive mode."""
173 # capture reinstall calls
174 reinstall_calls = capcall(
175 'cylc.flow.scripts.reinstall.reinstall_workflow',
176 reinstall_workflow,
177 )
178 # give it something to reinstall
179 (one_src.path / 'a').touch()
180
181 answer_prompt('n')
182 assert (
183 await reinstall_cli(opts=ReInstallOptions(), workflow_id=one_run.id)
184 is False
185 )
186
187 # only one rsync call should have been made (i.e. the --dry-run)
188 assert [call[1].get('dry_run') for call in reinstall_calls] == [True]
189 assert 'reinstall cancelled' in capsys.readouterr().out
190 reinstall_calls.clear()
191
192 answer_prompt('y')
193 assert await reinstall_cli(opts=ReInstallOptions(), workflow_id=one_run.id)
194
195 # two rsync calls should have been made (i.e. the --dry-run and the real)
196 assert [call[1].get('dry_run') for call in reinstall_calls] == [
197 True, False
198 ]
199 assert 'Successfully reinstalled' in capsys.readouterr().out
200
201
202 async def test_workflow_running(
203 one_src,
204 one_run,
205 monkeypatch,
206 capsys,
207 non_interactive,
208 ):
209 """It should advise running "cylc reload" where applicable."""
210 # the message we are expecting
211 reload_message = f'Run "cylc reload {one_run.id}"'
212
213 # reinstall with a stopped workflow (reload message shouldn't show)
214 assert await reinstall_cli(opts=ReInstallOptions(), workflow_id=one_run.id)
215 assert reload_message not in capsys.readouterr().out
216
217 # reinstall with a running workflow (reload message should show)
218 monkeypatch.setattr(
219 # make it look like the workflow is running
220 'cylc.flow.scripts.reinstall.load_contact_file',
221 lambda x: None,
222 )
223 assert await reinstall_cli(opts=ReInstallOptions(), workflow_id=one_run.id)
224 assert reload_message in capsys.readouterr().out
225
226
227 async def test_rsync_stuff(one_src, one_run, capsys, non_interactive):
228 """Make sure rsync is working correctly."""
229 # src contains files: a, b
230 (one_src.path / 'a').touch()
231 with open(one_src.path / 'b', 'w+') as b_file:
232 b_file.write('x')
233 (one_src.path / 'b').touch()
234
235 # run contains files: b, c (where b is different to the source copy)
236 (one_run.path / 'b').touch()
237 (one_run.path / 'c').touch()
238
239 await reinstall_cli(opts=ReInstallOptions(), workflow_id=one_run.id)
240
241 # a should have been left
242 assert (one_run.path / 'a').exists()
243 # b should have been updated
244 assert (one_run.path / 'b').exists()
245 with open(one_run.path / 'b', 'r') as b_file:
246 assert b_file.read() == 'x'
247 # c should have been removed
248 assert not (one_run.path / 'c').exists()
249
250
251 async def test_rose_warning(
252 one_src, one_run, capsys, interactive, answer_prompt
253 ):
254 """It should warn that Rose installed files will be deleted.
255
256 See https://github.com/cylc/cylc-rose/issues/149
257 """
258 # fragment of the message we expect
259 rose_message = (
260 'Files created by Rose file installation will show as deleted'
261 )
262
263 answer_prompt('n')
264 (one_src.path / 'a').touch() # give it something to install
265
266 # reinstall (with rose-suite.conf file)
267 await reinstall_cli(opts=ReInstallOptions(), workflow_id=one_run.id)
268 assert rose_message in capsys.readouterr().err
269
270 # reinstall (no rose-suite.conf file)
271 (one_src.path / 'rose-suite.conf').unlink()
272 await reinstall_cli(opts=ReInstallOptions(), workflow_id=one_run.id)
273 assert rose_message not in capsys.readouterr().err
274
275
276 async def test_keyboard_interrupt(
277 one_src,
278 one_run,
279 interactive,
280 monkeypatch,
281 capsys
282 ):
283 """It should handle a KeyboardInterrupt during dry-run elegantly.
284
285 E.G. A user may ctrl+c rather than answering "n" (for no). To make it
286 clear a canceled message should show.
287 """
288 def raise_keyboard_interrupt():
289 raise KeyboardInterrupt()
290
291 # currently the first call in the dry-run branch
292 monkeypatch.setattr(
293 'cylc.flow.scripts.reinstall.is_terminal',
294 raise_keyboard_interrupt,
295 )
296
297 await reinstall_cli(opts=ReInstallOptions(), workflow_id=one_run.id)
298 assert 'reinstall cancelled' in capsys.readouterr().out
299
300
301 async def test_rsync_fail(one_src, one_run, mock_glbl_cfg, non_interactive):
302 """It should raise an error on rsync failure."""
303 mock_glbl_cfg(
304 'cylc.flow.install.glbl_cfg',
305 '''
306 [platforms]
307 [[localhost]]
308 rsync command = false
309 ''',
310 )
311
312 (one_src.path / 'a').touch() # give it something to install
313 with pytest.raises(WorkflowFilesError) as exc_ctx:
314 await reinstall_cli(opts=ReInstallOptions(), workflow_id=one_run.id)
315 assert 'An error occurred reinstalling' in str(exc_ctx.value)
316
317
318 async def test_permissions_change(
319 one_src,
320 one_run,
321 interactive,
322 answer_prompt,
323 capsys: pytest.CaptureFixture,
324 ):
325 """It detects permissions changes."""
326 # Add script file:
327 script_path: Path = one_src.path / 'myscript'
328 script_path.touch()
329 await reinstall_cli(
330 opts=ReInstallOptions(skip_interactive=True), workflow_id=one_run.id
331 )
332 assert (one_run.path / 'myscript').is_file()
333 capsys.readouterr() # clears capsys
334
335 # Change permissions (e.g. user forgot to make it executable before)
336 script_path.chmod(0o777)
337 # Answer "no" to reinstall prompt (we just want to test dry run)
338 answer_prompt('n')
339 await reinstall_cli(
340 opts=ReInstallOptions(), workflow_id=one_run.id
341 )
342 out, _ = capsys.readouterr()
343 # On some systems may get "recv" instead of "send"
344 assert re.search(r'(send|recv) myscript\n', out)
345
346
347 @pytest.fixture
348 def my_install_plugin(monkeypatch):
349 """This configures a single post_install plugin.
350
351 The plugin starts an async task, then returns.
352 """
353 progress = []
354
355 @EntryPointWrapper
356 def post_install_basic(*_, **__):
357 """Simple plugin that returns one env var and one template var."""
358 async def my_async():
359 # the async task
360 await asyncio.sleep(2)
361 progress.append('end')
362
363 # start the async task
364 progress.append('start')
365 asyncio.get_event_loop().create_task(my_async())
366 progress.append('return')
367
368 # return a blank result
369 return {
370 'env': {},
371 'template_variables': {},
372 }
373
374 monkeypatch.setattr(
375 'cylc.flow.plugins.iter_entry_points',
376 lambda namespace: (
377 [post_install_basic] if namespace == 'cylc.post_install' else []
378 )
379 )
380
381 return progress
382
383
384 async def test_async_block(
385 one_src,
386 one_run,
387 my_install_plugin,
388 monkeypatch,
389 ):
390 """Ensure async tasks created by post_install plugins are awaited.
391
392 The cylc-rose plugin may create asyncio tasks when run but cannot await
393 them (because it isn't async itself). To get around this we have
394 "cylc reinstall" use "async_block" which detects tasks created in the
395 background and awaits them.
396
397 This test ensures that the async_block mechanism is correctly plugged in
398 to "cylc reinstall".
399
400 See https://github.com/cylc/cylc-rose/issues/274
401 """
402 # this is what it should do
403 (one_src.path / 'a').touch() # give it something to install
404 assert my_install_plugin == []
405 await reinstall_cli(opts=ReInstallOptions(), workflow_id=one_run.id)
406 # the presence of "end" means that the task was awaited
407 assert my_install_plugin == ['start', 'return', 'end']
408
409 # substitute the "async_block" (which waits for asyncio tasks started in
410 # the background) for a fake implementation (which doesn't)
411
412 @asynccontextmanager
413 async def async_block():
414 yield
415
416 monkeypatch.setattr(
417 'cylc.flow.plugins._async_block',
418 async_block,
419 )
420
421 # this is what it would have done without async block
422 (one_src.path / 'b').touch() # give it something else to install
423 my_install_plugin.clear()
424 assert my_install_plugin == []
425 await reinstall_cli(opts=ReInstallOptions(), workflow_id=one_run.id)
426 # the absence of "end" means that the task was not awaited
427 assert my_install_plugin == ['start', 'return']