Debian Codegraph @

tests/i/tui/test_logs.py

raw
1 #!/usr/bin/env python3
2 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
3 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 import asyncio
19 from pathlib import Path
20 from typing import TYPE_CHECKING
21
22 from cylc.flow.cycling.integer import IntegerPoint
23 from cylc.flow.exceptions import ClientError
24 from cylc.flow.scheduler import Scheduler
25 from cylc.flow.task_job_logs import get_task_job_log
26 from cylc.flow.task_state import (
27 TASK_STATUS_FAILED,
28 TASK_STATUS_SUCCEEDED,
29 )
30 from cylc.flow.tui.data import _get_log
31
32 import pytest
33
34 if TYPE_CHECKING:
35 from cylc.flow.id import Tokens
36
37
38 def get_job_log(tokens: 'Tokens', suffix: str) -> Path:
39 """Return the path to a job log file.
40
41 Args:
42 tokens: Job tokens.
43 suffix: Filename.
44
45 """
46 return Path(get_task_job_log(
47 tokens['workflow'],
48 tokens['cycle'],
49 tokens['task'],
50 tokens['job'],
51 suffix=suffix,
52 ))
53
54
55 @pytest.fixture(scope='module')
56 def standarise_host_and_path(mod_monkeypatch):
57 """Replace variable content in the log view.
58
59 The log view displays the "Host" and "Path" of the log file. These will
60 differer from user to user, so we mock away the difference to produce
61 stable results.
62 """
63 def _parse_log_header(contents):
64 _header, text = contents.split('\n', 1)
65 return 'myhost', 'mypath', text
66
67 mod_monkeypatch.setattr(
68 'cylc.flow.tui.data._parse_log_header',
69 _parse_log_header,
70 )
71
72
73 @pytest.fixture
74 def wait_log_loaded(monkeypatch):
75 """Wait for Tui to successfully open a log file."""
76 # previous log open count
77 before = 0
78 # live log open count
79 count = 0
80
81 # wrap the Tui "_get_log" method to count the number of times it has
82 # returned
83 def __get_log(*args, **kwargs):
84 nonlocal count
85 try:
86 ret = _get_log(*args, **kwargs)
87 except ClientError as exc:
88 count += 1
89 raise exc
90 count += 1
91 return ret
92 monkeypatch.setattr(
93 'cylc.flow.tui.data._get_log',
94 __get_log,
95 )
96
97 async def _wait_log_loaded(tries: int = 25, delay: float = 0.1):
98 """Wait for the log file to be loaded.
99
100 Args:
101 tries: The number of (re)tries to attempt before failing.
102 delay: The delay between retries.
103
104 """
105 nonlocal before
106 for _try in range(tries):
107 if count > before:
108 await asyncio.sleep(0)
109 before += 1
110 return
111 await asyncio.sleep(delay)
112 raise Exception(f'Log file was not loaded within {delay * tries}s')
113
114 return _wait_log_loaded
115
116
117 @pytest.fixture(scope='module')
118 async def workflow(
119 mod_flow, mod_scheduler, mod_start, standarise_host_and_path
120 ):
121 """Test fixture providing a workflow with some log files to poke at."""
122 id_ = mod_flow({
123 'scheduling': {
124 'graph': {
125 'R1': 'a',
126 }
127 },
128 'runtime': {
129 'a': {},
130 }
131 }, name='one')
132 schd: Scheduler = mod_scheduler(id_)
133 async with mod_start(schd):
134 # create some log files for tests to inspect
135
136 # create a scheduler log
137 # (note the scheduler log doesn't get created in integration tests)
138 scheduler_log = Path(schd.workflow_log_dir, '01-start-01.log')
139 with open(scheduler_log, 'w+') as logfile:
140 logfile.write(
141 'this is the scheduler log file'
142 + '\n'
143 + '\n'.join(f'line {x}' for x in range(2, 1000))
144 )
145
146 # task 1/a
147 itask = schd.pool.get_task(IntegerPoint('1'), 'a')
148
149 # mark 1/a/01 as failed
150 job_1 = schd.tokens.duplicate(cycle='1', task='a', job='01')
151 schd.data_store_mgr.insert_job(
152 itask,
153 TASK_STATUS_SUCCEEDED,
154 {'submit_num': 1, 'platform': {'name': 'x'}}
155 )
156 schd.data_store_mgr.delta_job_state(itask, TASK_STATUS_FAILED)
157
158 # mark 1/a/02 as succeeded
159 itask.submit_num = 2
160 job_2 = schd.tokens.duplicate(cycle='1', task='a', job='02')
161 schd.data_store_mgr.insert_job(
162 itask,
163 TASK_STATUS_SUCCEEDED,
164 {'submit_num': 2, 'platform': {'name': 'x'}}
165 )
166 schd.data_store_mgr.delta_job_state(itask, TASK_STATUS_SUCCEEDED)
167 schd.data_store_mgr.delta_task_state(itask)
168
169 # mark 1/a as succeeded
170 itask.state_reset(TASK_STATUS_SUCCEEDED)
171 schd.data_store_mgr.delta_task_state(itask)
172
173 # 1/a/01 - job.out
174 job_1_out = get_job_log(job_1, 'job.out')
175 job_1_out.parent.mkdir(parents=True)
176 with open(job_1_out, 'w+') as log:
177 log.write(f'job: {job_1.relative_id}\nthis is a job log\n')
178
179 # 1/a/02 - job.out
180 job_2_out = get_job_log(job_2, 'job.out')
181 job_2_out.parent.mkdir(parents=True)
182 with open(job_2_out, 'w+') as log:
183 log.write(f'job: {job_2.relative_id}\nthis is a job log\n')
184
185 # 1/a/02 - job.err
186 job_2_err = get_job_log(job_2, 'job.err')
187 with open(job_2_err, 'w+') as log:
188 log.write(f'job: {job_2.relative_id}\nthis is a job error\n')
189
190 # 1/a/NN -> 1/a/02
191 (job_2_out.parent.parent / 'NN').symlink_to(
192 (job_2_out.parent.parent / '02'),
193 target_is_directory=True,
194 )
195
196 # populate the data store
197 await schd.update_data_structure()
198
199 yield schd
200
201
202 async def test_scheduler_logs(
203 workflow,
204 mod_rakiura,
205 wait_log_loaded,
206 ):
207 """Test viewing the scheduler log files."""
208 with mod_rakiura(size='80,30') as rk:
209 # wait for the workflow to appear (collapsed)
210 rk.wait_until_loaded('#spring')
211
212 # open the workflow in Tui
213 rk.user_input('down', 'right')
214 rk.wait_until_loaded(workflow.tokens.id)
215
216 # open the log view for the workflow
217 rk.user_input('enter')
218 rk.user_input('down', 'down', 'enter')
219
220 # wait for the default log file to load
221 await wait_log_loaded()
222 rk.compare_screenshot(
223 'scheduler-log-file',
224 'the scheduler log file should be open',
225 )
226
227 # jump to the bottom of the file
228 rk.user_input('end')
229 rk.compare_screenshot(
230 'scheduler-log-file-bottom',
231 'we should be looking at the bottom of the file'
232 )
233
234 # jump back to the top of the file
235 rk.user_input('home')
236 rk.compare_screenshot(
237 'scheduler-log-file',
238 'we should be looking at the bottom of the file'
239 )
240
241 # open the list of log files
242 rk.user_input('enter')
243 rk.compare_screenshot(
244 'log-file-selection',
245 'the list of available log files should be displayed'
246 )
247
248 # select the processed workflow configuration file
249 rk.user_input('down', 'enter')
250
251 # wait for the file to load
252 await wait_log_loaded()
253 rk.compare_screenshot(
254 'workflow-configuration-file',
255 'the workflow configuration file should be open'
256 )
257
258
259 async def test_task_logs(
260 workflow,
261 mod_rakiura,
262 wait_log_loaded,
263 ):
264 """Test viewing task log files.
265
266 I.E. Test viewing job log files by opening the log view on a task.
267 """
268 with mod_rakiura(size='80,30') as rk:
269 # wait for the workflow to appear (collapsed)
270 rk.wait_until_loaded('#spring')
271
272 # open the workflow in Tui
273 rk.user_input('down', 'right')
274 rk.wait_until_loaded(workflow.tokens.id)
275
276 # open the context menu for the task 1/a
277 rk.user_input('down', 'down', 'enter')
278
279 # open the log view for the task 1/a
280 rk.user_input('down', 'down', 'down', 'enter')
281
282 # wait for the default log file to load
283 await wait_log_loaded()
284 rk.compare_screenshot(
285 'latest-job.out',
286 'the job.out file for the second job should be open',
287 )
288
289 rk.user_input('enter')
290 rk.user_input('enter')
291
292 # wait for the job.err file to load
293 await wait_log_loaded()
294 rk.compare_screenshot(
295 'latest-job.err',
296 'the job.out file for the second job should be open',
297 )
298
299
300 async def test_job_logs(
301 workflow,
302 mod_rakiura,
303 wait_log_loaded,
304 ):
305 """Test viewing the job log files.
306
307 I.E. Test viewing job log files by opening the log view on a job.
308 """
309 with mod_rakiura(size='80,30') as rk:
310 # wait for the workflow to appear (collapsed)
311 rk.wait_until_loaded('#spring')
312
313 # open the workflow in Tui
314 rk.user_input('down', 'right')
315 rk.wait_until_loaded(workflow.tokens.id)
316
317 # open the context menu for the job 1/a/02
318 rk.user_input('down', 'down', 'right', 'down', 'enter')
319
320 # open the log view for the job 1/a/02
321 rk.user_input('down', 'down', 'down', 'enter')
322
323 # wait for the default log file to load
324 await wait_log_loaded()
325 rk.compare_screenshot(
326 '02-job.out',
327 'the job.out file for the *second* job should be open',
328 )
329
330 # close log view
331 rk.user_input('q')
332
333 # open the log view for the job 1/a/01
334 rk.user_input('down', 'enter')
335 rk.user_input('down', 'down', 'down', 'enter')
336
337 # wait for the default log file to load
338 await wait_log_loaded()
339 rk.compare_screenshot(
340 '01-job.out',
341 'the job.out file for the *first* job should be open',
342 )
343
344
345 async def test_errors(
346 workflow,
347 mod_rakiura,
348 wait_log_loaded,
349 monkeypatch,
350 ):
351 """Test error handing of cat-log commands."""
352 # make it look like cat-log commands are failing
353 def cli_cmd_fail(*args, **kwargs):
354 raise ClientError('Something went wrong :(')
355
356 monkeypatch.setattr(
357 'cylc.flow.tui.data.cli_cmd',
358 cli_cmd_fail,
359 )
360
361 with mod_rakiura(size='80,30') as rk:
362 # wait for the workflow to appear (collapsed)
363 rk.wait_until_loaded('#spring')
364
365 # open the log view on scheduler
366 rk.user_input('down', 'enter', 'down', 'down', 'enter')
367
368 # it will fail to open
369 await wait_log_loaded()
370 rk.compare_screenshot(
371 'open-error',
372 'the error message should be displayed in the log view header',
373 )
374
375 # open the file selector
376 rk.user_input('enter')
377
378 # it will fail to list avialable log files
379 rk.compare_screenshot(
380 'list-error',
381 'the error message should be displayed in a pop up',
382 )
383
384
385 async def test_external_editor(
386 workflow,
387 mod_rakiura,
388 wait_log_loaded,
389 monkeypatch,
390 capsys,
391 ):
392 """Test the "open in external editor" functionality.
393
394 This test covers the relevant code about as well as we can in an
395 integration test.
396
397 * The integration tests write HTML fragments to a file rather ANSI to a
398 terminal.
399 * Suspending / restoring the Tui session involves shell interaction that
400 we cannot simulate here.
401 * We're also not testing subprocesses in this integration test.
402
403 But this test passing tells us that the relevant code does indeed run
404 without falling over in a heap, so it will detect interface breakages and
405 the like which is useful.
406 """
407 fake_popen_instances = []
408
409 class FakePopen:
410 def __init__(self, cmd, *args, raises=None, **kwargs):
411 fake_popen_instances.append(self)
412 self.cmd = cmd
413 self.args = args
414 self.kwargs = kwargs
415 self.raises = raises
416
417 def wait(self):
418 if self.raises:
419 raise self.raises()
420 return 0
421
422 # mock out subprocess.Popen
423 monkeypatch.setattr(
424 'cylc.flow.tui.overlay.Popen',
425 FakePopen,
426 )
427 # mock out time.sleep
428 monkeypatch.setattr(
429 'cylc.flow.tui.overlay.sleep',
430 lambda x: None,
431 )
432
433 with mod_rakiura(size='80,30') as rk:
434 # wait for the workflow to appear (collapsed)
435 rk.wait_until_loaded('#spring')
436
437 # open the log view on scheduler
438 rk.user_input('down', 'enter', 'down', 'down', 'enter')
439
440 # it will fail to open
441 await wait_log_loaded()
442
443 assert len(fake_popen_instances) == 0
444 assert capsys.readouterr()[1] == ''
445
446 # select the open in "$EDITOR" option
447 rk.user_input('down', 'left', 'left', 'left')
448
449 # make a note of what the screen looks like
450 rk.compare_screenshot(
451 'before-opening-editor',
452 'The open in $EDITOR option should be selected',
453 )
454
455 # launch the external tool
456 rk.user_input('enter')
457
458 # the subprocess should be started and a message logged to stderr
459 assert len(fake_popen_instances) == 1
460 assert 'launching external tool' in capsys.readouterr()[1].lower()
461
462 # once the subprocess exist, the Tui session should be restored
463 # exactly as it was before
464 rk.compare_screenshot(
465 'before-opening-editor',
466 'The Tui session should restore exactly as it was before',
467 )
468
469 # get the subprocess to fail in a nasty way
470 from functools import partial
471 monkeypatch.setattr(
472 'cylc.flow.tui.overlay.Popen',
473 partial(FakePopen, raises=OSError),
474 )
475
476 # launch the external tool
477 rk.user_input('enter')
478
479 # the subprocess should be started, the error should be logged
480 # to stderr
481 assert len(fake_popen_instances) == 2
482 assert 'error running' in capsys.readouterr()[1].lower()
483
484 # once the subprocess exist, the Tui session should be restored
485 # exactly as it was before
486 rk.compare_screenshot(
487 'before-opening-editor',
488 'The Tui session should restore exactly as it was before',
489 )