Debian Codegraph @

tests/i/test_examples.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 """Working documentation for the integration test framework.
17
18 Here are some examples which cover a range of uses (and also provide some
19 useful testing in the process 😀.)
20
21 """
22
23 import asyncio
24 import logging
25 from pathlib import Path
26
27 import pytest
28
29 from cylc.flow import __version__
30 from cylc.flow.scheduler import Scheduler
31
32
33 async def test_create_flow(flow, run_dir):
34 """Use the flow fixture to create workflows on the file system."""
35 # Ensure a flow.cylc file gets written out
36 id_ = flow({
37 'scheduler': {
38 'allow implicit tasks': True
39 },
40 'scheduling': {
41 'graph': {
42 'R1': 'foo'
43 }
44 }
45 })
46 workflow_dir = run_dir / id_
47 flow_file = workflow_dir / 'flow.cylc'
48
49 assert workflow_dir.exists()
50 assert flow_file.exists()
51
52
53 async def test_run(flow, scheduler, run, one_conf):
54 """Create a workflow, initialise the scheduler and run it."""
55 # Ensure the scheduler can survive for at least one second without crashing
56 id_ = flow(one_conf)
57 schd = scheduler(id_)
58 async with run(schd):
59 await asyncio.sleep(1) # this yields control to the main loop
60
61
62 async def test_logging(flow, scheduler, start, one_conf, log_filter):
63 """We can capture log records when we run a scheduler."""
64 # Ensure that the cylc version is logged on startup.
65 id_ = flow(one_conf)
66 schd = scheduler(id_)
67 async with start(schd):
68 # this returns a list of log records containing __version__
69 assert log_filter(contains=__version__)
70
71
72 async def test_scheduler_arguments(flow, scheduler, start, one_conf):
73 """We can provide options to the scheduler when we __init__ it.
74
75 These options match their command line equivalents.
76
77 Use the `dest` value specified in the option parser.
78
79 """
80 # Ensure the paused_start option is obeyed by the scheduler.
81 id_ = flow(one_conf)
82 schd = scheduler(id_, paused_start=True)
83 async with start(schd):
84 assert schd.is_paused
85 id_ = flow(one_conf)
86 schd = scheduler(id_, paused_start=False)
87 async with start(schd):
88 assert not schd.is_paused
89
90
91 async def test_shutdown(flow, scheduler, start, one_conf):
92 """Shut down a workflow.
93
94 The scheduler automatically shuts down once you exit the `async with`
95 block, however you can manually shut it down within this block if you
96 like.
97
98 """
99 # Ensure the TCP server shuts down with the scheduler.
100 id_ = flow(one_conf)
101 schd = scheduler(id_)
102 async with start(schd):
103 pass
104 assert schd.server.replier.socket.closed
105
106
107 async def test_install(flow, scheduler, one_conf, run_dir):
108 """You don't have to run workflows, it's usually best not to!
109
110 You can take the scheduler through the startup sequence as far as needed
111 for your test.
112
113 """
114 # Ensure the installation of the job script is completed.
115 id_ = flow(one_conf)
116 schd = scheduler(id_)
117 await schd.install()
118 assert Path(
119 run_dir, schd.workflow, '.service', 'etc', 'job.sh'
120 ).exists()
121
122
123 async def test_task_pool(one, start):
124 """You don't have to run the scheduler to play with the task pool.
125
126 There are two fixtures to start a scheduler:
127
128 `start`
129 Takes a scheduler through the startup sequence.
130 `run`
131 Takes a scheduler through the startup sequence, then sets the main loop
132 going.
133
134 Unless you need the Scheduler main loop running, use `start`.
135
136 This test uses a pre-prepared Scheduler called "one".
137
138 """
139 # Ensure that the correct number of tasks get added to the task pool.
140 async with start(one):
141 # pump the scheduler's heart manually
142 one.pool.release_runahead_tasks()
143 assert len(one.pool.active_tasks) == 1
144
145
146 async def test_exception(one, run, log_filter):
147 """Through an exception into the scheduler to see how it will react.
148
149 You have to do this from within the scheduler itself.
150 The easy way is to patch the object.
151
152 """
153 class MyException(Exception):
154 pass
155
156 # replace the main loop with something that raises an exception
157 def killer():
158 raise MyException('mess')
159
160 one._main_loop = killer
161
162 # make sure that this error causes the flow to shutdown
163 with pytest.raises(MyException):
164 async with run(one):
165 # The `run` fixture's shutdown logic waits for the main loop to run
166 pass
167
168 # make sure the exception was logged
169 assert len(log_filter(logging.CRITICAL, contains='mess')) == 1
170
171 # make sure the server socket has closed - a good indication of a
172 # successful clean shutdown
173 assert one.server.replier.socket.closed
174
175
176 @pytest.fixture(scope='module')
177 async def myflow(mod_flow, mod_scheduler, mod_one_conf):
178 """You can save setup/teardown time by reusing fixtures
179
180 Write a module-scoped fixture and it can be shared by all tests in the
181 current module.
182
183 The standard fixtures all have `mod_` alternatives to allow you to do
184 this.
185
186 Pytest has been configured to run all tests from the same module in the
187 same xdist worker, in other words, module scoped fixtures only get
188 created once per module, even when distributing tests.
189
190 Obviously this goes with the usual warnings about not mutating the
191 object you are testing in the tests.
192
193 """
194 id_ = mod_flow(mod_one_conf)
195 schd = mod_scheduler(id_)
196 return schd
197
198
199 def test_module_scoped_fixture(myflow):
200 """Ensure the host is set on __init__.
201
202 The myflow fixture will be shared between all test functions within this
203 Python module.
204
205 """
206 assert myflow.host
207
208
209 async def test_db_select(one, start, db_select):
210 """Demonstrate and test querying the workflow database."""
211 # run a workflow
212 schd: Scheduler = one
213 async with start(schd):
214 # Select all from workflow_params table:
215 assert ('UTC_mode', '0') in db_select(schd, False, 'workflow_params')
216
217 # Select name & status columns from task_states table:
218 results = db_select(schd, False, 'task_states', 'name', 'status')
219 assert results[0] == ('one', 'waiting')
220
221 # Select all columns where name==one & status==waiting from
222 # task_states table:
223 results = db_select(
224 schd, False, 'task_states', name='one', status='waiting')
225 assert len(results) == 1
226
227
228 async def test_reflog(flow, scheduler, run, reflog, complete):
229 """Test the triggering of tasks.
230
231 This is the integration test version of "reftest" in the funtional tests.
232
233 It works by capturing the triggers which caused each submission so that
234 they can be compared with the expected outcome.
235 """
236 id_ = flow({
237 'scheduling': {
238 'initial cycle point': '1',
239 'final cycle point': '1',
240 'cycling mode': 'integer',
241 'graph': {
242 'P1': '''
243 a => b => c
244 x => b => z
245 b[-P1] => b
246 '''
247 }
248 }
249 })
250 schd = scheduler(id_, paused_start=False)
251
252 async with run(schd):
253 triggers = reflog(schd) # Note: add flow_nums=True to capture flows
254 await complete(schd)
255
256 assert triggers == {
257 # 1/a was triggered by nothing (i.e. it's parentless)
258 ('1/a', None),
259 # 1/b was triggered by three tasks (note the pre-initial dependency)
260 ('1/b', ('0/b', '1/a', '1/x')),
261 ('1/c', ('1/b',)),
262 ('1/x', None),
263 ('1/z', ('1/b',)),
264 }
265
266
267 async def test_reftest(flow, scheduler, reftest):
268 """Test the triggering of tasks.
269
270 This uses the reftest fixture which combines the reflog and
271 complete fixtures. Suitable for use when you just want to do a simple
272 reftest.
273 """
274 id_ = flow({
275 'scheduling': {
276 'graph': {
277 'R1': 'a => b'
278 }
279 }
280 })
281 schd = scheduler(id_, paused_start=False)
282
283 assert await reftest(schd) == {
284 ('1/a', None),
285 ('1/b', ('1/a',)),
286 }
287
288
289 async def test_show(one: Scheduler, start, cylc_show):
290 """Demonstrate the `cylc_show` fixture"""
291 async with start(one):
292 out = await cylc_show(one, '1/one')
293 assert list(out.keys()) == ['1/one']
294 assert out['1/one']['state'] == 'waiting'