Debian Codegraph @

tests/unit/test_subprocpool.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
17 from pathlib import Path
18 from types import SimpleNamespace
19 from tempfile import (
20 NamedTemporaryFile,
21 SpooledTemporaryFile,
22 TemporaryFile,
23 TemporaryDirectory,
24 )
25
26 import pytest
27
28 from cylc.flow import LOG
29 from cylc.flow.id import Tokens
30 from cylc.flow.cycling.iso8601 import ISO8601Point
31 from cylc.flow.task_events_mgr import TaskJobLogsRetrieveContext
32 from cylc.flow.subprocctx import SubProcContext
33 from cylc.flow.subprocpool import (
34 SubProcPool,
35 _XTRIG_FUNC_CACHE,
36 get_xtrig_func,
37 )
38 from cylc.flow.task_outputs import (
39 TASK_OUTPUT_SUBMITTED,
40 TASK_OUTPUT_SUBMIT_FAILED,
41 TASK_OUTPUT_SUCCEEDED,
42 TASK_OUTPUT_FAILED,
43 TASK_OUTPUT_EXPIRED,
44 )
45 from cylc.flow.task_proxy import TaskProxy
46
47
48 def test_get_temporary_file():
49 """Test SubProcPool.get_temporary_file."""
50 assert isinstance(SubProcPool.get_temporary_file(), SpooledTemporaryFile)
51
52
53 def test_run_command_returns_0():
54 """Test basic usage, command returns 0"""
55 ctx = SubProcContext('truth', ['true'])
56 SubProcPool.run_command(ctx)
57 assert ctx.err == ''
58 assert ctx.out == ''
59 assert ctx.ret_code == 0
60
61
62 def test_run_command_returns_1():
63 """Test basic usage, command returns 1"""
64 ctx = SubProcContext('lies', ['false'])
65 SubProcPool.run_command(ctx)
66 assert ctx.err == ''
67 assert ctx.out == ''
68 assert ctx.ret_code == 1
69
70
71 def test_run_command_writes_to_out():
72 """Test basic usage, command writes to STDOUT"""
73 ctx = SubProcContext('parrot', ['echo', 'pirate', 'urrrr'])
74 SubProcPool.run_command(ctx)
75 assert ctx.err == ''
76 assert ctx.out == 'pirate urrrr\n'
77 assert ctx.ret_code == 0
78
79
80 def test_run_command_writes_to_err():
81 """Test basic usage, command writes to STDERR"""
82 ctx = SubProcContext(
83 'parrot2',
84 ['bash', '--noprofile', '--norc', '-c', 'echo pirate errrr >&2']
85 )
86 SubProcPool.run_command(ctx)
87 assert 'pirate errrr\n'
88 assert ctx.out == ''
89 assert ctx.ret_code == 0
90
91
92 def test_run_command_with_stdin_from_str():
93 """Test STDIN from string"""
94 ctx = SubProcContext('meow', ['cat'], stdin_str='catches mice.\n')
95 SubProcPool.run_command(ctx)
96 assert ctx.err == ''
97 assert ctx.out == 'catches mice.\n'
98 assert ctx.ret_code == 0
99
100
101 def test_run_command_with_stdin_from_unicode():
102 """Test STDIN from string with Unicode"""
103 ctx = SubProcContext('meow', ['cat'], stdin_str='喵\n')
104 SubProcPool.run_command(ctx)
105 assert ctx.err == ''
106 assert ctx.out == '喵\n'
107 assert ctx.ret_code == 0
108
109
110 def test_run_command_with_stdin_from_handle():
111 """Test STDIN from a single opened file handle"""
112 handle = TemporaryFile()
113 handle.write('catches mice.\n'.encode('UTF-8'))
114 handle.seek(0)
115 ctx = SubProcContext('meow', ['cat'], stdin_files=[handle])
116 SubProcPool.run_command(ctx)
117 assert ctx.err == ''
118 assert ctx.out == 'catches mice.\n'
119 assert ctx.ret_code == 0
120 handle.close()
121
122
123 def test_run_command_with_stdin_from_path():
124 """Test STDIN from a single file path"""
125 handle = NamedTemporaryFile()
126 handle.write('catches mice.\n'.encode('UTF-8'))
127 handle.seek(0)
128 ctx = SubProcContext('meow', ['cat'], stdin_files=[handle.name])
129 SubProcPool.run_command(ctx)
130 assert ctx.err == ''
131 assert ctx.out == 'catches mice.\n'
132 assert ctx.ret_code == 0
133 handle.close()
134
135
136 def test_run_command_with_stdin_from_handles():
137 """Test STDIN from multiple file handles"""
138 handles = []
139 for txt in ['catches mice.\n', 'eat fish.\n']:
140 handle = TemporaryFile()
141 handle.write(txt.encode('UTF-8'))
142 handle.seek(0)
143 handles.append(handle)
144 ctx = SubProcContext('meow', ['cat'], stdin_files=handles)
145 SubProcPool.run_command(ctx)
146 assert ctx.err == ''
147 assert ctx.out == 'catches mice.\neat fish.\n'
148 assert ctx.ret_code == 0
149 for handle in handles:
150 handle.close()
151
152
153 def test_run_command_with_stdin_from_paths():
154 """Test STDIN from multiple file paths"""
155 handles = []
156 for txt in ['catches mice.\n', 'eat fish.\n']:
157 handle = NamedTemporaryFile()
158 handle.write(txt.encode('UTF-8'))
159 handle.seek(0)
160 handles.append(handle)
161 ctx = SubProcContext(
162 'meow', ['cat'], stdin_files=[handle.name for handle in handles]
163 )
164 SubProcPool.run_command(ctx)
165 assert ctx.err == ''
166 assert ctx.out == 'catches mice.\neat fish.\n'
167 assert ctx.ret_code == 0
168 for handle in handles:
169 handle.close()
170
171
172 def test_xfunction():
173 """Test xtrigger function import."""
174 with TemporaryDirectory() as temp_dir:
175 python_dir = Path(temp_dir, "lib", "python")
176 python_dir.mkdir(parents=True)
177 the_answer_file = python_dir / "the_answer.py"
178 with the_answer_file.open(mode="w") as f:
179 f.write("""the_answer = lambda: 42""")
180 f.flush()
181 f_name = "the_answer"
182 fn = get_xtrig_func(f_name, f_name, temp_dir)
183 result = fn()
184 assert 42 == result
185
186
187 def test_xfunction_cache():
188 """Test xtrigger function import cache."""
189 with TemporaryDirectory() as temp_dir:
190 python_dir = Path(temp_dir, "lib", "python")
191 python_dir.mkdir(parents=True)
192 amandita_file = python_dir / "amandita.py"
193 with amandita_file.open(mode="w") as f:
194 f.write("""choco = lambda: 'chocolate'""")
195 f.flush()
196 m_name = "amandita" # module
197 f_name = "choco" # function
198 fn = get_xtrig_func(m_name, f_name, temp_dir)
199 result = fn()
200 assert 'chocolate' == result
201
202 # is in the cache
203 assert (m_name, f_name) in _XTRIG_FUNC_CACHE
204 # returned from cache
205 assert fn, get_xtrig_func(m_name, f_name == temp_dir)
206
207
208 def test_xfunction_import_error():
209 """Test for error on importing a xtrigger function.
210
211 To prevent the test eventually failing if the test function is added
212 and successfully imported, we use an invalid module name as per Python
213 spec.
214 """
215 with TemporaryDirectory() as temp_dir, pytest.raises(ModuleNotFoundError):
216 get_xtrig_func("invalid-module-name", "func-name", temp_dir)
217
218
219 def test_xfunction_attribute_error():
220 """Test for error on looking for an attribute in a xtrigger script."""
221 with TemporaryDirectory() as temp_dir:
222 python_dir = Path(temp_dir, "lib", "python")
223 python_dir.mkdir(parents=True)
224 the_answer_file = python_dir / "the_sword.py"
225 with the_answer_file.open(mode="w") as f:
226 f.write("""the_droid = lambda: 'excalibur'""")
227 f.flush()
228 f_name = "the_sword"
229 with pytest.raises(AttributeError):
230 get_xtrig_func(f_name, f_name, temp_dir)
231
232
233 @pytest.fixture
234 def mock_ctx():
235 def inner_(ret_code=None, host=None, cmd_key=None, cmd=None):
236 """Provide a SimpleNamespace which looks like a ctx object."""
237 inputs = locals()
238 defaults = {
239 'ret_code': 255,
240 'host': 'mouse',
241 'cmd_key': 'my-command',
242 'cmd': ['bistromathic', 'take-off'],
243 }
244 for key in inputs:
245 if inputs[key] is None:
246 inputs[key] = defaults[key]
247 ctx = SimpleNamespace(
248 cmd=inputs['cmd'],
249 timestamp=None,
250 ret_code=inputs['ret_code'],
251 host=inputs['host'],
252 cmd_key=inputs['cmd_key'],
253 )
254 return ctx
255
256 yield inner_
257
258
259 def _test_callback(ctx, foo=''):
260 """Very Simple test callback function"""
261 LOG.error(f'callback called.{foo}')
262
263
264 def _test_callback_255(ctx, foo=''):
265 """Very Simple test callback function"""
266 LOG.error(f'255 callback called.{foo}')
267
268
269 @pytest.mark.parametrize(
270 'expect, ret_code, cmd_key',
271 [
272 pytest.param('callback called', 0, 'ssh something', id="return 0"),
273 pytest.param('callback called', 1, 'ssh something', id="return 1"),
274 pytest.param(
275 'platform: None - Could not connect to mouse.',
276 255,
277 'ssh',
278 id="return 255",
279 ),
280 pytest.param(
281 'platform: localhost - Could not connect to mouse.',
282 255,
283 TaskJobLogsRetrieveContext(['ssh', 'something'], None, None),
284 id="return 255 (log-ret)",
285 ),
286 ],
287 )
288 def test__run_command_exit(caplog, mock_ctx, expect, ret_code, cmd_key):
289 """It runs a callback"""
290 ctx = mock_ctx(ret_code=ret_code, cmd_key=cmd_key, cmd=['ssh'])
291 SubProcPool._run_command_exit(
292 ctx, callback=_test_callback, callback_255=_test_callback_255
293 )
294 assert expect in caplog.records[0].msg
295 if ret_code == 255:
296 assert '255 callback called.' in caplog.records[1].msg
297
298
299 def test__run_command_exit_no_255_callback(caplog, mock_ctx):
300 """It runs the vanilla callback if no 255 callback provided"""
301 SubProcPool._run_command_exit(mock_ctx(), callback=_test_callback)
302 assert 'callback called' in caplog.records[0].msg
303
304
305 def test__run_command_exit_no_gettable_platform(caplog, mock_ctx):
306 """It logs being unable to select a platform"""
307 ret_ctx = TaskJobLogsRetrieveContext(
308 platform_name='rhenas', max_size=256, key='rhenas'
309 )
310 ctx = mock_ctx(cmd_key=ret_ctx, cmd=['ssh'], ret_code=255)
311 SubProcPool._run_command_exit(ctx, callback=_test_callback)
312 assert 'platform: rhenas' in caplog.records[0].msg
313
314
315 def test__run_command_exit_no_255_args(caplog, mock_ctx):
316 """It runs the 255 callback with the args of the callback if no
317 callback 255 args provided.
318 """
319 SubProcPool._run_command_exit(
320 mock_ctx(cmd=['ssh', 'Zaphod']),
321 callback=_test_callback,
322 callback_args=['Zaphod'],
323 callback_255=_test_callback_255,
324 )
325 assert '255' in caplog.records[1].msg
326
327
328 def test__run_command_exit_add_to_badhosts(mock_ctx):
329 """It updates the list of badhosts"""
330 badhosts = {'foo', 'bar'}
331 SubProcPool._run_command_exit(
332 mock_ctx(cmd=['ssh']),
333 bad_hosts=badhosts,
334 callback=print,
335 callback_args=['Welcome to Magrathea'],
336 )
337 assert badhosts == {'foo', 'bar', 'mouse'}
338
339
340 def test__run_command_exit_add_to_badhosts_log(caplog, mock_ctx):
341 """It gets platform name from the callback args."""
342 badhosts = {'foo', 'bar'}
343 SubProcPool._run_command_exit(
344 mock_ctx(cmd=['ssh']),
345 bad_hosts=badhosts,
346 callback=lambda x, t: print(str(x)),
347 callback_args=[
348 TaskProxy(
349 Tokens('~u/w//c/t/2'),
350 SimpleNamespace(
351 name='t',
352 dependencies={},
353 sequential='',
354 external_triggers=[],
355 xtrig_labels={},
356 expiration_offset=None,
357 outputs={
358 TASK_OUTPUT_SUBMITTED: [None, None],
359 TASK_OUTPUT_SUBMIT_FAILED: [None, None],
360 TASK_OUTPUT_SUCCEEDED: [None, None],
361 TASK_OUTPUT_FAILED: [None, None],
362 TASK_OUTPUT_EXPIRED: [None, None],
363 },
364 graph_children={},
365 rtconfig={'platform': 'foo'},
366 ),
367 ISO8601Point('1990'),
368 )
369 ],
370 )
371 assert 'platform: foo' in caplog.records[0].message
372 assert badhosts == {'foo', 'bar', 'mouse'}
373
374
375 def test__run_command_exit_rsync_fails(mock_ctx):
376 """It updates the list of badhosts"""
377 badhosts = {'foo', 'bar'}
378 ctx = mock_ctx(cmd=['rsync'], ret_code=42, cmd_key='file-install')
379 SubProcPool._run_command_exit(
380 ctx=ctx,
381 bad_hosts=badhosts,
382 callback=print,
383 callback_args=[
384 {
385 'name': 'Magrathea',
386 'ssh command': 'ssh',
387 'rsync command': 'rsync command',
388 },
389 'Welcome to Magrathea',
390 ],
391 )
392 assert badhosts == {'foo', 'bar', 'mouse'}
393
394
395 @pytest.mark.parametrize(
396 'expect, ctx_kwargs',
397 [
398 (True, {'cmd': ['ssh'], 'ret_code': 255}),
399 (False, {'cmd': ['foo'], 'ret_code': 255}),
400 (False, {'cmd': ['ssh'], 'ret_code': 42}),
401 ],
402 )
403 def test_ssh_255_fail(mock_ctx, expect, ctx_kwargs):
404 """It knows when a ctx has failed"""
405 output = SubProcPool.ssh_255_fail(mock_ctx(**ctx_kwargs))
406 assert output == expect
407
408
409 @pytest.mark.parametrize(
410 'expect, ctx_kwargs',
411 [
412 (True, {'cmd': ['rsync'], 'ret_code': 99, 'host': 'not_local'}),
413 (True, {'cmd': ['rsync'], 'ret_code': 255, 'host': 'not_local'}),
414 (False, {'cmd': ['make it-so'], 'ret_code': 255, 'host': 'not_local'}),
415 (False, {'cmd': ['rsync'], 'ret_code': 125, 'host': 'localhost'}),
416 ],
417 )
418 def test_rsync_255_fail(mock_ctx, expect, ctx_kwargs):
419 """It knows when a ctx has failed"""
420 output = SubProcPool.rsync_255_fail(
421 mock_ctx(**ctx_kwargs),
422 {'ssh command': 'ssh', 'rsync command': 'rsync command'},
423 )
424 assert output == expect