Debian Codegraph @

tests/i/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 """Default fixtures for functional tests."""
17
18 import asyncio
19 from functools import partial
20 from pathlib import Path
21 import re
22 from shutil import rmtree
23 from time import time
24 from typing import (
25 TYPE_CHECKING,
26 List,
27 Set,
28 Tuple,
29 Union,
30 )
31
32 import pytest
33
34 from cylc.flow.config import WorkflowConfig
35 from cylc.flow.id import Tokens
36 from cylc.flow.network.client import WorkflowRuntimeClient
37 from cylc.flow.option_parsers import Options
38 from cylc.flow.pathutil import get_cylc_run_dir
39 from cylc.flow.run_modes import RunMode
40 from cylc.flow.rundb import CylcWorkflowDAO
41 from cylc.flow.scripts.install import (
42 get_option_parser as install_gop,
43 install as cylc_install,
44 )
45 from cylc.flow.scripts.show import (
46 ShowOptions,
47 prereqs_and_outputs_query,
48 )
49 from cylc.flow.scripts.validate import ValidateOptions
50 from cylc.flow.task_state import (
51 TASK_STATUS_SUBMITTED,
52 TASK_STATUS_SUCCEEDED,
53 )
54 from cylc.flow.util import serialise_set
55 from cylc.flow.wallclock import get_current_time_string
56 from cylc.flow.workflow_files import infer_latest_run_from_id
57 from cylc.flow.workflow_status import StopMode
58
59 from .utils import _rm_if_empty
60 from .utils.flow_tools import (
61 _make_flow,
62 _make_scheduler,
63 _make_src_flow,
64 _run_flow,
65 _start_flow,
66 )
67
68
69 if TYPE_CHECKING:
70 from cylc.flow.scheduler import Scheduler
71 from cylc.flow.task_proxy import TaskProxy
72
73
74 InstallOpts = Options(install_gop())
75
76
77 @pytest.hookimpl(tryfirst=True, hookwrapper=True)
78 def pytest_runtest_makereport(item, call):
79 """Expose the result of tests to their fixtures.
80
81 This will add a variable to the "node" object which differs depending on
82 the scope of the test.
83
84 scope=function
85 `_function_outcome` will be set to the result of the test function.
86 scope=module
87 `_module_outcome will be set to a list of all test results in
88 the module.
89
90 https://github.com/pytest-dev/pytest/issues/230#issuecomment-402580536
91
92 """
93 outcome = yield
94 rep = outcome.get_result()
95
96 # scope==function
97 item._function_outcome = rep
98
99 # scope==module
100 _module_outcomes = getattr(item.module, '_module_outcomes', {})
101 _module_outcomes[(item.nodeid, rep.when)] = rep
102 item.module._module_outcomes = _module_outcomes
103
104
105 def _pytest_passed(request: pytest.FixtureRequest) -> bool:
106 """Returns True if the test(s) a fixture was used in passed."""
107 if hasattr(request.node, '_function_outcome'):
108 return request.node._function_outcome.outcome in {'passed', 'skipped'}
109 return all((
110 report.outcome in {'passed', 'skipped'}
111 for report in request.node.obj._module_outcomes.values()
112 ))
113
114
115 @pytest.fixture(scope='session')
116 def run_dir():
117 """The cylc run directory for this host."""
118 path = Path(get_cylc_run_dir())
119 path.mkdir(exist_ok=True)
120 yield path
121
122
123 @pytest.fixture(scope='session')
124 def ses_test_dir(request, run_dir):
125 """The root run dir for test flows in this test session."""
126 timestamp = get_current_time_string(use_basic_format=True)
127 uuid = f'cit-{timestamp}'
128 path = Path(run_dir, uuid)
129 path.mkdir(exist_ok=True)
130 yield path
131 _rm_if_empty(path)
132
133
134 @pytest.fixture(scope='module')
135 def mod_test_dir(request, ses_test_dir):
136 """The root run dir for test flows in this test module."""
137 path = Path(
138 ses_test_dir,
139 # Shorten path by dropping `integration.` prefix:
140 re.sub(r'^integration\.', '', request.module.__name__)
141 )
142 path.mkdir(parents=True, exist_ok=True)
143 yield path
144 if _pytest_passed(request):
145 # test passed -> remove all files
146 rmtree(path, ignore_errors=False)
147 else:
148 # test failed -> remove the test dir if empty
149 _rm_if_empty(path)
150
151
152 @pytest.fixture
153 def test_dir(request, mod_test_dir):
154 """The root run dir for test flows in this test function."""
155 path = Path(mod_test_dir, request.function.__name__)
156 path.mkdir(parents=True, exist_ok=True)
157 yield path
158 if _pytest_passed(request):
159 # test passed -> remove all files
160 rmtree(path, ignore_errors=False)
161 else:
162 # test failed -> remove the test dir if empty
163 _rm_if_empty(path)
164
165
166 @pytest.fixture(scope='module')
167 def mod_flow(run_dir, mod_test_dir):
168 """A function for creating module-level flows."""
169 yield partial(_make_flow, run_dir, mod_test_dir)
170
171
172 @pytest.fixture
173 def flow(run_dir, test_dir):
174 """A function for creating function-level flows."""
175 yield partial(_make_flow, run_dir, test_dir)
176
177
178 @pytest.fixture(scope='module')
179 def mod_scheduler():
180 """Return a Scheduler object for a flow.
181
182 Usage: see scheduler() below
183 """
184 with _make_scheduler() as _scheduler:
185 yield _scheduler
186
187
188 @pytest.fixture
189 def scheduler():
190 """Return a Scheduler object for a flow.
191
192 Args:
193 id_ (str): Workflow name.
194 **opts (Any): Options to be passed to the Scheduler.
195 """
196 with _make_scheduler() as _scheduler:
197 yield _scheduler
198
199
200 @pytest.fixture(scope='module')
201 def mod_start():
202 """Start a scheduler but don't set it running (module scope)."""
203 return partial(_start_flow, None)
204
205
206 @pytest.fixture
207 def start(caplog: pytest.LogCaptureFixture):
208 """Start a scheduler but don't set it running."""
209 return partial(_start_flow, caplog)
210
211
212 @pytest.fixture(scope='module')
213 def mod_run():
214 """Start a scheduler and set it running (module scope)."""
215 return partial(_run_flow, None)
216
217
218 @pytest.fixture
219 def run(caplog: pytest.LogCaptureFixture):
220 """Start a scheduler and set it running."""
221 return partial(_run_flow, caplog)
222
223
224 @pytest.fixture
225 def one_conf():
226 return {
227 'scheduler': {
228 'allow implicit tasks': True
229 },
230 'scheduling': {
231 'graph': {
232 'R1': 'one'
233 }
234 }
235 }
236
237
238 @pytest.fixture(scope='module')
239 def mod_one_conf():
240 return {
241 'scheduler': {
242 'allow implicit tasks': True
243 },
244 'scheduling': {
245 'graph': {
246 'R1': 'one'
247 }
248 }
249 }
250
251
252 @pytest.fixture
253 def one(one_conf, flow, scheduler):
254 """Return a Scheduler for the simple "R1 = one" graph."""
255 id_ = flow(one_conf)
256 schd = scheduler(id_)
257 return schd
258
259
260 @pytest.fixture(scope='module')
261 def mod_one(mod_one_conf, mod_flow, mod_scheduler):
262 id_ = mod_flow(mod_one_conf)
263 schd = mod_scheduler(id_)
264 return schd
265
266
267 @pytest.fixture(scope='module')
268 def event_loop():
269 """This fixture defines the event loop used for each test.
270
271 The default scoping for this fixture is "function" which means that all
272 async fixtures must have "function" scoping.
273
274 Defining `event_loop` as a module scoped fixture opens the door to
275 module scoped fixtures but means all tests in a module will run in the same
276 event loop. This is fine, it's actually an efficiency win but also
277 something to be aware of.
278
279 See: https://github.com/pytest-dev/pytest-asyncio/issues/171
280
281 """
282 loop = asyncio.get_event_loop_policy().new_event_loop()
283 yield loop
284 # gracefully exit async generators
285 loop.run_until_complete(loop.shutdown_asyncgens())
286 # cancel any tasks still running in this event loop
287 for task in asyncio.all_tasks(loop):
288 task.cancel()
289 loop.close()
290
291
292 @pytest.fixture
293 def db_select():
294 """Select columns from workflow database.
295
296 Args:
297 schd: The Scheduler object for the workflow.
298 process_db_queue: Whether to process the scheduler's db queue before
299 querying.
300 table: The name of the database table to query.
301 *columns (optional): The columns to select from the table. To select
302 all columns, omit or use '*'.
303 **where (optional): Kwargs specifying <column>='<value>' for use in
304 WHERE clauses. If more than one specified, they will be chained
305 together using an AND operator.
306 """
307
308 def _check_columns(table: str, *columns: str) -> None:
309 all_columns = [x[0] for x in CylcWorkflowDAO.TABLES_ATTRS[table]]
310 for col in columns:
311 if col not in all_columns:
312 raise ValueError(f"Column '{col}' not in table '{table}'")
313
314 def _inner(
315 schd: 'Scheduler',
316 process_db_queue: bool,
317 table: str,
318 *columns: str,
319 **where: str
320 ) -> List[Tuple[str, ...]]:
321
322 if process_db_queue:
323 schd.process_workflow_db_queue()
324
325 if table not in CylcWorkflowDAO.TABLES_ATTRS:
326 raise ValueError(f"Table '{table}' not in database")
327 if not columns:
328 columns = ('*',)
329 elif columns != ('*',):
330 _check_columns(table, *columns)
331
332 stmt = f'SELECT {",".join(columns)} FROM {table}'
333 stmt_args = []
334 if where:
335 _check_columns(table, *where.keys())
336 where_stmt = ' AND '.join([
337 f'{col}=?' for col in where.keys()
338 ])
339 stmt += f' WHERE {where_stmt}'
340 stmt_args = list(where.values())
341
342 with schd.workflow_db_mgr.get_pri_dao() as pri_dao:
343 return list(pri_dao.connect().execute(stmt, stmt_args))
344
345 return _inner
346
347
348 @pytest.fixture
349 def gql_query():
350 """Execute a GraphQL query given a workflow runtime client."""
351 async def _gql_query(
352 client: 'WorkflowRuntimeClient', query_str: str
353 ) -> object:
354 ret = await client.async_request(
355 'graphql', {
356 'request_string': 'query { ' + query_str + ' }'
357 }
358 )
359 return ret
360 return _gql_query
361
362
363 @pytest.fixture
364 def validate(run_dir):
365 """Provides a function for validating workflow configurations.
366
367 Attempts to load the configuration, will raise exceptions if there are
368 errors.
369
370 Args:
371 id_ - The flow to validate
372 kwargs - Arguments to pass to ValidateOptions
373 """
374 def _validate(id_: Union[str, Path], **kwargs) -> WorkflowConfig:
375 id_ = str(id_)
376 return WorkflowConfig(
377 id_,
378 str(Path(run_dir, id_, 'flow.cylc')),
379 ValidateOptions(**kwargs)
380 )
381
382 return _validate
383
384
385 @pytest.fixture(scope='module')
386 def mod_validate(run_dir):
387 """Provides a function for validating workflow configurations.
388
389 Attempts to load the configuration, will raise exceptions if there are
390 errors.
391
392 Args:
393 id_ - The flow to validate
394 kwargs - Arguments to pass to ValidateOptions
395 """
396 def _validate(id_: Union[str, Path], **kwargs) -> WorkflowConfig:
397 id_ = str(id_)
398 return WorkflowConfig(
399 id_,
400 str(Path(run_dir, id_, 'flow.cylc')),
401 ValidateOptions(**kwargs)
402 )
403
404 return _validate
405
406
407 @pytest.fixture
408 def capture_submission():
409 """Suppress job submission and capture submitted tasks.
410
411 Provides a function to run on a Scheduler *whilst started*, use like so:
412
413 async with start(schd):
414 submitted_tasks = capture_submission(schd)
415
416 or:
417
418 async with run(schd):
419 submitted_tasks = capture_submission(schd)
420
421 """
422
423 def _disable_submission(schd: 'Scheduler') -> 'Set[TaskProxy]':
424 submitted_tasks: 'Set[TaskProxy]' = set()
425
426 def _submit_task_jobs(itasks):
427 for itask in itasks:
428 itask.state_reset(TASK_STATUS_SUBMITTED)
429 submitted_tasks.update(itasks)
430 return itasks
431
432 schd.submit_task_jobs = _submit_task_jobs # type: ignore
433 return submitted_tasks
434
435 return _disable_submission
436
437
438 @pytest.fixture
439 def capture_polling():
440 """Suppress job polling and capture polled tasks.
441
442 Provides a function to run on a started Scheduler.
443
444 async with start(schd):
445 polled_tasks = capture_polling(schd)
446
447 or:
448
449 async with run(schd):
450 polled_tasks = capture_polling(schd)
451
452 """
453 def _disable_polling(schd: 'Scheduler') -> 'Set[TaskProxy]':
454 polled_tasks: 'Set[TaskProxy]' = set()
455
456 def run_job_cmd(
457 _1, itasks, _3, _4=None
458 ):
459 polled_tasks.update(itasks)
460 return itasks
461
462 schd.task_job_mgr._run_job_cmd = run_job_cmd # type: ignore
463 return polled_tasks
464
465 return _disable_polling
466
467
468 @pytest.fixture(scope='module')
469 def mod_workflow_source(mod_flow, tmp_path_factory):
470 """Create a workflow source directory.
471
472 Args:
473 cfg: Can be passed a config dictionary.
474
475 Yields:
476 Path to source directory.
477 """
478 def _inner(cfg):
479 src_dir = _make_src_flow(tmp_path_factory.getbasetemp(), cfg)
480 return src_dir
481 yield _inner
482
483
484 @pytest.fixture
485 def workflow_source(mod_flow, tmp_path):
486 """Create a workflow source directory.
487
488 Args:
489 cfg: Can be passed a config dictionary.
490
491 Yields:
492 Path to source directory.
493 """
494 def _inner(cfg):
495 src_dir = _make_src_flow(tmp_path, cfg)
496 return src_dir
497 yield _inner
498
499
500 @pytest.fixture
501 def install(test_dir, run_dir):
502 """Install a workflow from source
503
504 Args:
505 (Actually args for _inner, but what the fixture appears to take to
506 the user)
507 source: Directory containing the source.
508 **kwargs: Options for cylc install.
509
510 Returns:
511 Workflow id, including run directory.
512 """
513 async def _inner(source, **kwargs):
514 opts = InstallOpts(**kwargs)
515 # Note we append the source.name to the string rather than creating
516 # a subfolder because the extra layer of directories would exceed
517 # Cylc install's default limit.
518 opts.workflow_name = (
519 f'{str(test_dir.relative_to(run_dir))}.{source.name}')
520 workflow_id, _ = await cylc_install(opts, str(source))
521 workflow_id = infer_latest_run_from_id(workflow_id)
522 return workflow_id
523 yield _inner
524
525
526 @pytest.fixture
527 def reflog():
528 """Integration test version of the --reflog CLI option.
529
530 This returns a set which captures task triggers.
531
532 Note, you'll need to call this on the scheduler *after* you have started
533 it.
534
535 N.B. Trigger order is not stable; using a set ensures that tests check
536 trigger logic rather than binding to specific trigger order which could
537 change in the future, breaking the test.
538
539 Args:
540 schd:
541 The scheduler to capture triggering information for.
542 flow_nums:
543 If True, the flow numbers of the task being triggered will be added
544 to the end of each entry.
545
546 Returns:
547 tuple
548
549 (task, triggers):
550 If flow_nums == False
551 (task, flow_nums, triggers):
552 If flow_nums == True
553
554 task:
555 The [relative] task ID e.g. "1/a".
556 flow_nums:
557 The serialised flow nums e.g. ["1"].
558 triggers:
559 Sorted tuple of the trigger IDs, e.g. ("1/a", "2/b").
560
561 """
562
563 def _reflog(schd: 'Scheduler', flow_nums: bool = False) -> Set[tuple]:
564 submit_task_jobs = schd.submit_task_jobs
565 triggers = set()
566
567 def _submit_task_jobs(*args, **kwargs):
568 itasks = submit_task_jobs(*args, **kwargs)
569 for itask in itasks:
570 deps = tuple(sorted(itask.state.get_resolved_dependencies()))
571 if flow_nums:
572 triggers.add(
573 (
574 itask.identity,
575 serialise_set(itask.flow_nums),
576 deps or None,
577 )
578 )
579 else:
580 triggers.add((itask.identity, deps or None))
581 return itasks
582
583 schd.submit_task_jobs = _submit_task_jobs
584
585 return triggers
586
587 return _reflog
588
589
590 async def _complete(
591 schd: 'Scheduler',
592 *wait_tokens: Union[Tokens, str],
593 stop_mode=StopMode.AUTO,
594 timeout: int = 60,
595 allow_paused: bool = False,
596 ) -> None:
597 """Wait for the workflow, or tasks within it to complete.
598
599 Args:
600 schd:
601 The scheduler to await.
602 wait_tokens:
603 If specified, this will wait for the tasks represented by these
604 tokens to be marked as completed by the task pool. Can use
605 relative task ids as strings (e.g. '1/a') rather than tokens for
606 convenience.
607 stop_mode:
608 If tokens_list is not provided, this will wait for the scheduler
609 to be shutdown with the specified mode (default = AUTO, i.e.
610 workflow completed normally).
611 timeout:
612 Max time to wait for the condition to be met.
613
614 Note, if you need to increase this, you might want to rethink your
615 test.
616
617 Note, use this timeout rather than wrapping the complete call with
618 async.timeout (handles shutdown logic more cleanly).
619 allow_paused:
620 This function will raise an Exception if the scheduler is paused
621 (because this usually means the sepecified tasks cannot complete)
622 unless allow_paused==True.
623
624 Raises:
625 AssertionError: In the event the scheduler shut down or the operation
626 timed out.
627
628 """
629 if schd.is_paused and not allow_paused:
630 raise Exception(
631 "You are waiting for a paused scheduler - if this is intended "
632 "then use `complete(..., allow_paused=True)`"
633 )
634
635 start_time = time()
636
637 tokens_list: List[Tokens] = []
638 for tokens in wait_tokens:
639 if isinstance(tokens, str):
640 tokens = Tokens(tokens, relative=True)
641 tokens_list.append(tokens.task)
642
643 # capture task completion
644 remove_if_complete = schd.pool.remove_if_complete
645
646 def _remove_if_complete(itask, output=None):
647 ret = remove_if_complete(itask)
648 if ret and itask.tokens.task in tokens_list:
649 tokens_list.remove(itask.tokens.task)
650 return ret
651
652 # capture workflow shutdown request
653 set_stop = schd._set_stop
654 stop_requested = False
655
656 def _set_stop(mode=None):
657 nonlocal stop_requested
658 if mode == stop_mode:
659 stop_requested = True
660 return set_stop(mode)
661 else:
662 set_stop(mode)
663 raise Exception(f'Workflow bailed with stop mode = {mode}')
664
665 # determine the completion condition
666 def done():
667 if wait_tokens:
668 if not tokens_list:
669 return True
670 if not schd.contact_data:
671 raise AssertionError(
672 "Scheduler shut down before tasks completed: " +
673 ", ".join(map(str, tokens_list))
674 )
675 return False
676 # otherwise wait for the scheduler to shut down
677 return stop_requested or not schd.contact_data
678
679 with pytest.MonkeyPatch.context() as mp:
680 mp.setattr(schd.pool, 'remove_if_complete', _remove_if_complete)
681 mp.setattr(schd, '_set_stop', _set_stop)
682
683 # wait for the condition to be met
684 while not done():
685 # allow the main loop to advance
686 await asyncio.sleep(0)
687 if (time() - start_time) > timeout:
688 msg = "Timeout waiting for "
689 if wait_tokens:
690 msg += ", ".join(map(str, tokens_list))
691 else:
692 msg += "workflow to shut down"
693 raise AssertionError(msg)
694
695
696 @pytest.fixture
697 def complete():
698 return _complete
699
700
701 @pytest.fixture(scope='module')
702 def mod_complete():
703 return _complete
704
705
706 @pytest.fixture
707 def reftest(run, reflog, complete):
708 """Fixture that runs a simple reftest.
709
710 Combines the `reflog` and `complete` fixtures.
711 """
712 async def _reftest(
713 schd: 'Scheduler',
714 flow_nums: bool = False,
715 ) -> Set[tuple]:
716 async with run(schd):
717 triggers = reflog(schd, flow_nums)
718 await complete(schd)
719
720 return triggers
721
722 return _reftest
723
724
725 @pytest.fixture
726 def cylc_show():
727 """Fixture that runs `cylc show` on a scheduler, returning JSON object."""
728
729 async def _cylc_show(schd: 'Scheduler', *task_ids: str) -> dict:
730 pclient = WorkflowRuntimeClient(schd.workflow)
731 await schd.update_data_structure()
732 json_filter: dict = {}
733 await prereqs_and_outputs_query(
734 schd.id,
735 [Tokens(id_, relative=True) for id_ in task_ids],
736 pclient,
737 ShowOptions(json=True),
738 json_filter,
739 )
740 return json_filter
741
742 return _cylc_show
743
744
745 @pytest.fixture
746 def capture_live_submissions(capcall, monkeypatch):
747 """Capture live submission attempts.
748
749 This prevents real jobs from being submitted to the system.
750
751 If you call this fixture from a test, it will return a set of tasks that
752 would have been submitted had this fixture not been used.
753 """
754 def fake_submit(self, itasks, *_):
755 self.submit_nonlive_task_jobs(itasks, RunMode.SIMULATION)
756 for itask in itasks:
757 for status in (TASK_STATUS_SUBMITTED, TASK_STATUS_SUCCEEDED):
758 self.task_events_mgr.process_message(
759 itask,
760 'INFO',
761 status,
762 '2000-01-01T00:00:00Z',
763 '(received)',
764 )
765 return itasks
766
767 # suppress and capture live submissions
768 submit_live_calls = capcall(
769 'cylc.flow.task_job_mgr.TaskJobManager.submit_livelike_task_jobs',
770 fake_submit)
771
772 def get_submissions():
773 return {
774 itask.identity
775 for ((_self, itasks, *_), _kwargs) in submit_live_calls
776 for itask in itasks
777 }
778
779 return get_submissions