Debian Codegraph @

tests/i/test_scan_api.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 """Test the cylc scan Python API (which is equivalent to the CLI)."""
17
18 import json
19 from pathlib import Path
20 from shutil import (
21 copytree,
22 rmtree
23 )
24
25 import pytest
26
27 from cylc.flow.scripts.scan import (
28 main,
29 ScanOptions
30 )
31 from cylc.flow.workflow_files import (
32 ContactFileFields,
33 WorkflowFiles,
34 dump_contact_file,
35 load_contact_file
36 )
37
38
39 @pytest.fixture(scope='module')
40 async def flows(mod_flow, mod_scheduler, mod_run, mod_one_conf):
41 """Three workflows in different states.
42
43 One stopped, one paused and one that thinks its running.
44
45 TODO:
46 Start one of the workflows with tasks in funny states
47 in order to test the state totals functionality properly.
48
49 Requires: https://github.com/cylc/cylc-flow/pull/3668
50
51 """
52 # a simple workflow we will leave stopped
53 mod_flow(mod_one_conf, name='-stopped-')
54
55 # a simply hierarchically registered workflow we will leave stopped
56 mod_flow(mod_one_conf, name='a/b/c')
57
58 # a simple workflow we will leave paused
59 reg1 = mod_flow(mod_one_conf, name='-paused-')
60 schd1 = mod_scheduler(reg1, paused_start=True)
61
62 # a workflow with some metadata we will make look like it's running
63 reg2 = mod_flow(
64 {
65 'meta': {
66 'title': 'Foo',
67 'description': '''
68 Here we find a
69 multi
70 line
71 description
72 '''
73 },
74 'scheduler': {
75 'allow implicit tasks': True
76 },
77 'scheduling': {
78 'graph': {
79 'R1': 'foo'
80 }
81 },
82 'runtime': {
83 'foo': {
84 'simulation': {'default run length': 'PT10S'}
85 }
86 }
87 },
88 name='-running-'
89 )
90 schd2 = mod_scheduler(reg2, paused_start=False)
91
92 # run cylc run
93 async with mod_run(schd1):
94 async with mod_run(schd2):
95 yield
96
97
98 async def test_state_filter(flows, mod_test_dir):
99 """It should filter flows by state."""
100 # one stopped flow
101 opts = ScanOptions(states='stopped', sort=True)
102 lines = []
103 await main(opts, write=lines.append, scan_dir=mod_test_dir)
104 assert len(lines) == 2
105 assert '-stopped-' in lines[0]
106 assert 'a/b/c' in lines[1]
107
108 # one paused flow
109 opts = ScanOptions(states='paused')
110 lines = []
111 await main(opts, write=lines.append, scan_dir=mod_test_dir)
112 assert len(lines) == 1
113 assert '-paused-' in lines[0]
114
115 # one running flow
116 opts = ScanOptions(states='running')
117 lines = []
118 await main(opts, write=lines.append, scan_dir=mod_test_dir)
119 assert len(lines) == 1
120 assert '-running-' in lines[0]
121
122 # two active flows
123 opts = ScanOptions(states='paused,running')
124 lines = []
125 await main(opts, write=lines.append, scan_dir=mod_test_dir)
126 assert len(lines) == 2
127
128 # three registered flows
129 opts = ScanOptions(states='paused,running,stopped')
130 lines = []
131 await main(opts, write=lines.append, scan_dir=mod_test_dir)
132 assert len(lines) == 4
133
134
135 async def test_name_filter(flows, mod_test_dir):
136 """It should filter flows by name regex."""
137 # one stopped flow
138 opts = ScanOptions(states='all', name=['.*paused.*'])
139 lines = []
140 await main(opts, write=lines.append, scan_dir=mod_test_dir)
141 assert len(lines) == 1
142 assert '-paused-' in lines[0]
143
144
145 async def test_name_sort(flows, mod_test_dir):
146 """It should sort flows by name."""
147 # one stopped flow
148 opts = ScanOptions(states='all', sort=True)
149 lines = []
150 await main(opts, write=lines.append, scan_dir=mod_test_dir)
151 assert len(lines) == 4
152 assert '-paused-' in lines[0]
153 assert '-running-' in lines[1]
154 assert '-stopped-' in lines[2]
155 assert 'a/b/c' in lines[3]
156
157
158 async def test_format_json(flows, mod_test_dir):
159 """It should dump results in json format."""
160 # one stopped flow
161 opts = ScanOptions(states='all', format='json')
162 lines = []
163 await main(opts, write=lines.append, scan_dir=mod_test_dir)
164 data = json.loads(lines[0])
165 assert len(data) == 4
166 assert data[0]['name']
167
168
169 async def test_format_tree(flows, run_dir, ses_test_dir, mod_test_dir):
170 """It should dump results in an ascii tree format."""
171 # one stopped flow
172 opts = ScanOptions(states='running', format='tree')
173 workflows = []
174 await main(opts, write=workflows.append, scan_dir=mod_test_dir)
175 assert len(workflows) == 1
176 lines = workflows[0].splitlines()
177 # this flow is hierarchically registered in the run dir already
178 # it should be registered as <session test dir>/<module test dir>/<name>
179 assert ses_test_dir.name in lines[0]
180 assert mod_test_dir.name in lines[1]
181 assert '-running-' in lines[2]
182
183
184 async def test_format_rich(flows, mod_test_dir):
185 """It should print results in a long human-friendly format."""
186 # one stopped flow (--colour-blind)
187 opts = ScanOptions(states='running', format='rich', colour_blind=True)
188 workflows = []
189 await main(opts, write=workflows.append, scan_dir=mod_test_dir)
190 assert len(workflows) == 1
191 lines = workflows[0].splitlines()
192
193 # test that the multi-line description was output correctly
194 # with trailing lines indented correctly
195 desc_lines = [
196 'Here we find a',
197 'multi',
198 'line',
199 'description'
200 ]
201 prev_ind = -1
202 prev_offset = -1
203 for expected in desc_lines:
204 for ind, line in enumerate(lines):
205 if expected in line:
206 offset = line.index(expected)
207 if prev_ind < 1:
208 prev_ind = ind
209 prev_offset = offset
210 else:
211 if ind != prev_ind + 1:
212 raise Exception(
213 f'Lines found in wrong order: {line}')
214 if offset != prev_offset:
215 raise Exception('Line incorrectly indented: {line}')
216 break
217 else:
218 raise Exception(f'Missing line: {line}')
219
220 # test that the state totals show one task running (colour_blind mode)
221 for line in lines:
222 if 'running:1' in line:
223 break
224 else:
225 raise Exception('missing state totals line (colour_blind)')
226
227 # one stopped flow (--colour=always)
228 opts = ScanOptions(states='running', format='rich')
229 workflows = []
230 await main(
231 opts, write=workflows.append, scan_dir=mod_test_dir, color='always'
232 )
233 assert len(workflows) == 1
234 lines = workflows[0].splitlines()
235
236 # test that the state totals show one task running (colour mode)
237 for line in lines:
238 if '1 ■' in line:
239 break
240 else:
241 raise Exception('missing state totals line (colourful)')
242
243
244 async def test_scan_cleans_stuck_contact_files(
245 start,
246 scheduler,
247 flow,
248 one_conf,
249 run_dir,
250 test_dir,
251 ):
252 """Ensure scan tidies up contact files from crashed flows."""
253 # create a flow
254 id_ = flow(one_conf, name='-crashed-')
255 schd = scheduler(id_)
256 srv_dir = Path(run_dir, id_, WorkflowFiles.Service.DIRNAME)
257 tmp_dir = test_dir / 'srv'
258 cont = srv_dir / WorkflowFiles.Service.CONTACT
259
260 # run the flow, copy the contact, stop the flow, copy back the contact
261 async with start(schd):
262 copytree(srv_dir, tmp_dir)
263 rmtree(srv_dir)
264 copytree(tmp_dir, srv_dir)
265 rmtree(tmp_dir)
266
267 # the old contact file check uses the CLI command that the flow was run
268 # with to check whether the flow is running. Because this is an
269 # integration test the process is the pytest process and it is still
270 # running so we need to change the command so that Cylc sees the flow as
271 # having crashed
272 contact_info = load_contact_file(id_)
273 contact_info[ContactFileFields.COMMAND] += 'xyz'
274 dump_contact_file(id_, contact_info)
275
276 # make sure this flow shows for a regular filesystem-only scan
277 opts = ScanOptions(states='running,paused', format='name')
278 flows = []
279 await main(opts, write=flows.append, scan_dir=test_dir)
280 assert len(flows) == 1
281 assert '-crashed-' in flows[0]
282
283 # the contact file should still be there
284 assert cont.exists()
285
286 # make sure this flow shows for a regular filesystem-only scan
287 opts = ScanOptions(states='running,paused', format='name', ping=True)
288 flows = []
289 await main(opts, write=flows.append, scan_dir=test_dir)
290 assert len(flows) == 0
291
292 # the contact file should have been removed by the scan
293 assert not cont.exists()
294
295
296 async def test_scan_fail_well_when_client_unreachable(
297 start,
298 scheduler,
299 flow,
300 one_conf,
301 run_dir,
302 test_dir,
303 caplog,
304 ):
305 """It handles WorkflowRuntimeClient.async_request raising a WorkflowStopped
306 elegently.
307 """
308 # create a flow
309 id_ = flow(one_conf, name='-crashed-')
310 schd = scheduler(id_)
311 srv_dir = Path(run_dir, id_, WorkflowFiles.Service.DIRNAME)
312 tmp_dir = test_dir / 'srv'
313
314 # run the flow, copy the contact, stop the flow, copy back the contact
315 async with start(schd):
316 copytree(srv_dir, tmp_dir)
317 rmtree(srv_dir)
318 copytree(tmp_dir, srv_dir)
319 rmtree(tmp_dir)
320
321 # the old contact file check uses the CLI command that the flow was run
322 # with to check whether the flow is running. Because this is an
323 # integration test the process is the pytest process and it is still
324 # running so we need to change the command so that Cylc sees the flow as
325 # having crashed
326 contact_info = load_contact_file(id_)
327 contact_info[ContactFileFields.COMMAND] += 'xyz'
328 dump_contact_file(id_, contact_info)
329
330 # Run Cylc Scan
331 opts = ScanOptions(states='all', format='rich', ping=True)
332 flows = []
333 await main(opts, write=flows.append, scan_dir=test_dir)
334
335 # Check that the records contain a message but not an error
336 rec = caplog.records[-1]
337 assert not rec.exc_text
338 assert 'Workflow not running' in rec.msg