Debian Codegraph @

tests/unit/test_job_file.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 # Tests for functions contained in cylc.flow.job_file.
18 # TODO remove the unittest dependency - it should not be necessary.
19
20 from contextlib import suppress
21 import io
22 import os
23 from pathlib import Path
24 import pytest
25 from tempfile import NamedTemporaryFile
26 from textwrap import dedent
27
28 from cylc.flow import (
29 __version__,
30 __file__ as cylc_flow_file,
31 )
32 from cylc.flow.job_file import (
33 JobFileWriter,
34 )
35 from cylc.flow.platforms import platform_from_name
36
37
38 @pytest.mark.parametrize(
39 'in_value, out_value',
40 [('~foo/bar bar', '~foo/"bar bar"'),
41 ('~/bar bar', '~/"bar bar"'),
42 ('~/a', '~/"a"'),
43 ('test', '"test"'),
44 ('~', '~'),
45 ('~a', '~a'),
46 ('foo%s', '"foo%s"'),
47 ('foo%(i)d', '"foo3"')]
48 )
49 def test_get_variable_value_definition(in_value, out_value):
50 """Test the value for single/tilde variables are correctly quoted, and
51 parameter environment templates are handled"""
52 param_dict = {'i': 3}
53 res = JobFileWriter._get_variable_value_definition(in_value, param_dict)
54 assert out_value == res
55
56
57 @pytest.fixture
58 def fixture_get_platform():
59 """ Allows pytest to cache default platform dictionary.
60
61 Args:
62 custom_settings (dict):
63 settings that you wish to override.
64
65 Returns:
66 platforms dictionary.
67 """
68 def inner_func(custom_settings=None):
69 platform = platform_from_name()
70 if custom_settings is not None:
71 platform.update(custom_settings)
72 return platform
73 yield inner_func
74
75
76 def test_write(fixture_get_platform):
77 """Test write function outputs jobscript file correctly."""
78 with NamedTemporaryFile() as local_job_file_path:
79 local_job_file_path = local_job_file_path.name
80 platform = fixture_get_platform(
81 {
82 "job runner command template": "woof",
83 }
84 )
85 job_conf = {
86 "platform": platform,
87 "task_id": "1/baa",
88 "workflow_name": "farm_noises",
89 "work_d": "farm_noises/work_d",
90 "uuid_str": "neigh",
91 'environment': {'cow': '~/moo',
92 'sheep': '~baa/baa',
93 'duck': '~quack'},
94 "job_d": "1/baa/01",
95 "try_num": 1,
96 "flow_nums": {1},
97 # "job_runner_name": "background",
98 "param_var": {"duck": "quack",
99 "mouse": "squeak"},
100 "execution_time_limit": "moo",
101 "namespace_hierarchy": ["root", "baa", "moo"],
102 "dependencies": ['moo', 'neigh', 'quack'],
103 "init-script": "This is the init script",
104 "env-script": "This is the env script",
105 "err-script": "This is the err script",
106 "pre-script": "This is the pre script",
107 "script": "This is the script",
108 "post-script": "This is the post script",
109 "exit-script": "This is the exit script",
110 }
111 JobFileWriter().write(local_job_file_path, job_conf)
112
113 assert (os.path.exists(local_job_file_path))
114 size_of_file = os.stat(local_job_file_path).st_size
115 # This test only needs to check that the file is created and is
116 # non-empty as each section is covered by individual unit tests.
117 assert size_of_file > 10
118
119 """Test the header is correctly written"""
120
121 expected = ('#!/bin/bash -l\n#\n# ++++ THIS IS A CYLC JOB SCRIPT '
122 '++++\n# Workflow: farm_noises\n# Task: 1/baa\n# Job '
123 'log directory: 1/baa/01\n# Job runner: '
124 'background\n# Job runner command template: woof\n#'
125 ' Execution time limit: moo')
126
127 platform = fixture_get_platform(
128 {"job runner command template": "woof"}
129 )
130 job_conf = {
131 "platform": platform,
132 "job runner": "background",
133 "execution_time_limit": "moo",
134 "workflow_name": "farm_noises",
135 "task_id": "1/baa",
136 "job_d": "1/baa/01"
137 }
138
139 with io.StringIO() as fake_file:
140 JobFileWriter()._write_header(fake_file, job_conf)
141 assert fake_file.getvalue() == expected
142
143
144 @pytest.mark.parametrize(
145 'job_conf,expected',
146 [
147 ( # basic
148 {
149 "platform": {
150 "job runner": "loadleveler",
151 "job runner command template": "test_workflow",
152 },
153 "directives": {"moo": "foo",
154 "cluck": "bar"},
155 "workflow_name": "farm_noises",
156 "task_id": "1/baa",
157 "job_d": "1/test_task_id/01",
158 "job_file_path": "directory/job",
159 "execution_time_limit": 60
160 },
161 ('\n\n# DIRECTIVES:\n# @ job_name = farm_noises.baa.1'
162 '\n# @ output = directory/job.out\n# @ error = directory/'
163 'job.err\n# @ wall_clock_limit = 120,60\n# @ moo = foo'
164 '\n# @ cluck = bar\n# @ queue')
165
166 ),
167 ( # Check no directives is correctly written
168 {
169 "platform": {
170 "job runner": "slurm",
171 "job runner command template": "test_workflow"
172 },
173 "directives": {},
174 "workflow_name": "farm_noises",
175 "task_id": "1/baa",
176 "job_d": "1/test_task_id/01",
177 "job_file_path": "directory/job",
178 "execution_time_limit": 60
179 },
180 (
181 '\n\n# DIRECTIVES:\n#SBATCH '
182 '--job-name=baa.1.farm_noises\n#SBATCH '
183 '--output=directory/job.out\n#SBATCH --error=directory/'
184 'job.err\n#SBATCH --time=1:00'
185 )
186
187 ),
188 ( # Check pbs max job name length
189 {
190 "platform": {
191 "job runner": "pbs",
192 "job runner command template": "test_workflow",
193 "job name length maximum": 15
194 },
195 "directives": {},
196 "workflow_name": "farm_noises",
197 "task_id": "1/baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
198 "job_d": "1/test_task_id/01",
199 "job_file_path": "directory/job",
200 "execution_time_limit": 60
201 },
202 ('\n\n# DIRECTIVES:\n#PBS -N baaaaaaaaaaaaaa\n#PBS -o '
203 'directory/job.out\n#PBS -e directory/job.err\n#PBS -l '
204 'walltime=60')
205 ),
206 ( # Check sge directives are correctly written
207 {
208 "platform": {
209 "job runner": "sge",
210 "job runner command template": "test_workflow",
211 },
212 "directives": {"-V": "",
213 "-q": "queuename",
214 "-l": "s_vmem=1G,s_cpu=60"},
215 "workflow_name": "farm_noises",
216 "task_id": "1/baa",
217 "job_d": "1/test_task_id/01",
218 "job_file_path": "$HOME/directory/job",
219 "execution_time_limit": 1000
220
221 },
222 ('\n\n# DIRECTIVES:\n#$ -N farm_noises.baa.1\n#$ -o directory/'
223 'job.out\n#$ -e directory/job.err\n#$ -l h_rt=0:16:40\n#$ -V\n#'
224 '$ -q queuename\n#$ -l s_vmem=1G,s_cpu=60'
225 )
226 )
227 ], ids=["1", "2", "3", "4"])
228 def test_write_directives(fixture_get_platform, job_conf: dict, expected: str):
229 """"Test the directives section of job script file is correctly
230 written"""
231 with io.StringIO() as fake_file:
232 JobFileWriter()._write_directives(fake_file, job_conf)
233 assert fake_file.getvalue() == expected
234
235
236 @pytest.mark.parametrize(
237 "job_runner",
238 ["at", "background", "loadleveler", "pbs", "sge", "slurm"])
239 def test_traps_for_each_job_runner(job_runner: str):
240 """Test traps for each job runner"""
241 platform = platform_from_name()
242 platform.update({
243 "job runner": f"{job_runner}",
244 })
245 job_conf = {
246 "platform": platform,
247 "directives": {},
248 "workflow_name": 'test_traps_for_each_job_runner',
249 }
250
251 with io.StringIO() as fake_file:
252 JobFileWriter()._write_prelude(fake_file, job_conf)
253 output = fake_file.getvalue()
254 assert "CYLC_FAIL_SIGNALS='EXIT ERR TERM XCPU" in output
255
256
257 @pytest.mark.parametrize(
258 'set_CYLC_ENV_NAME',
259 [
260 pytest.param(True, id='CYLC_ENV_NAME=True'),
261 pytest.param(False, id='CYLC_ENV_NAME=False'),
262 ]
263 )
264 def test_write_prelude(monkeypatch, fixture_get_platform, set_CYLC_ENV_NAME):
265 """Test the prelude section of job script file is correctly
266 written.
267 """
268 if set_CYLC_ENV_NAME:
269 monkeypatch.setenv('CYLC_ENV_NAME', 'myenv')
270 else:
271 with suppress(KeyError):
272 monkeypatch.delenv('CYLC_ENV_NAME')
273
274 monkeypatch.setattr('cylc.flow.flags.verbosity', 2)
275 expected = ('\nCYLC_FAIL_SIGNALS=\'EXIT ERR TERM XCPU\'\n'
276 'CYLC_VACATION_SIGNALS=\'USR1\'\nexport PATH=moo/baa:$PATH'
277 '\nexport CYLC_VERBOSE=true'
278 '\nexport CYLC_DEBUG=true'
279 f'\nexport CYLC_VERSION=\'{__version__}\'')
280 if set_CYLC_ENV_NAME:
281 expected += '\nexport CYLC_ENV_NAME=\'myenv\''
282 expected += '\nexport CYLC_WORKFLOW_ID="test_write_prelude"'
283 expected += '\nexport CYLC_WORKFLOW_INITIAL_CYCLE_POINT=\'20200101T0000Z\''
284 job_conf = {
285 "workflow_name": "test_write_prelude",
286 "platform": fixture_get_platform({
287 "job runner": "loadleveler",
288 "job runner command template": "test_workflow",
289 "host": "localhost",
290 "copyable environment variables": [
291 "CYLC_WORKFLOW_INITIAL_CYCLE_POINT"
292 ],
293 "cylc path": "moo/baa"
294 }),
295 "directives": {"restart": "yes"},
296 }
297 monkeypatch.setenv("CYLC_WORKFLOW_INITIAL_CYCLE_POINT", "20200101T0000Z")
298 monkeypatch.setenv("CYLC_WORKFLOW_NAME", "test_write_prelude")
299 monkeypatch.setenv("CYLC_WORKFLOW_NAME_BASE", "test_write_prelude")
300
301 with io.StringIO() as fake_file:
302 # copyable environment variables
303 JobFileWriter()._write_prelude(fake_file, job_conf)
304 assert fake_file.getvalue() == expected
305
306
307 def test_write_workflow_environment(fixture_get_platform, monkeypatch):
308 """Test workflow environment is correctly written in jobscript"""
309 # set some workflow environment conditions
310 monkeypatch.setattr('cylc.flow.flags.verbosity', 2)
311 workflow_env = {'CYLC_UTC': 'True',
312 'CYLC_CYCLING_MODE': 'integer',
313 'CYLC_WORKFLOW_NAME': 'blargh/quack',
314 'CYLC_WORKFLOW_NAME_BASE': 'quack'}
315 job_file_writer = JobFileWriter()
316 job_file_writer.set_workflow_env(workflow_env)
317 # workflow env not correctly setting...check this
318 expected = ('\n\ncylc__job__inst__cylc_env() {\n # CYLC WORKFLOW '
319 'ENVIRONMENT:\n export CYLC_CYCLING_MODE="integer"\n '
320 ' export CYLC_UTC="True"'
321 '\n export CYLC_WORKFLOW_NAME="blargh/quack"'
322 '\n export CYLC_WORKFLOW_NAME_BASE="quack"'
323 '\n export TZ="UTC"'
324 '\n export CYLC_WORKFLOW_UUID="neigh"')
325 job_conf = {
326 "platform": fixture_get_platform({
327 "host": "localhost",
328 }),
329 "workflow_name": "farm_noises",
330 "uuid_str": "neigh"
331 }
332 with io.StringIO() as fake_file:
333 job_file_writer._write_workflow_environment(fake_file, job_conf)
334 result = fake_file.getvalue()
335 assert result == expected
336
337
338 def test_write_script():
339 """Test script is correctly written in jobscript"""
340
341 expected = (
342 "\n\ncylc__job__inst__init_script() {\n# INIT-SCRIPT:\n"
343 "This is the init script\n}\n\ncylc__job__inst__env_script()"
344 " {\n# ENV-SCRIPT:\nThis is the env script\n}\n\n"
345 "cylc__job__inst__err_script() {\n# ERR-SCRIPT:\nThis is the err "
346 "script\n}\n\ncylc__job__inst__pre_script() {\n# PRE-SCRIPT:\n"
347 "This is the pre script\n}\n\ncylc__job__inst__script() {\n"
348 "# SCRIPT:\nThis is the script\n}\n\ncylc__job__inst__post_script"
349 "() {\n# POST-SCRIPT:\nThis is the post script\n}\n\n"
350 "cylc__job__inst__exit_script() {\n# EXIT-SCRIPT:\n"
351 "This is the exit script\n}")
352
353 job_conf = {
354 "init-script": "This is the init script",
355 "env-script": "This is the env script",
356 "err-script": "This is the err script",
357 "pre-script": "This is the pre script",
358 "script": "This is the script",
359 "post-script": "This is the post script",
360 "exit-script": "This is the exit script",
361 "workflow_name": "test_write_script",
362 }
363
364 with io.StringIO() as fake_file:
365 JobFileWriter()._write_script(fake_file, job_conf)
366 assert fake_file.getvalue() == expected
367
368
369 def test_no_script_section_with_comment_only_script():
370 """Test jobfilewriter does not generate script section when script is
371 comment only"""
372 expected = ("")
373
374 job_conf = {
375 "init-script": "",
376 "env-script": "",
377 "err-script": "",
378 "pre-script": "#This is the pre script/n #moo /n#baa",
379 "script": "",
380 "post-script": "",
381 "exit-script": "",
382 "workflow_name": "test_no_script_section_with_comment_only_script"
383 }
384
385 with io.StringIO() as fake_file:
386
387 JobFileWriter()._write_script(fake_file, job_conf)
388 blah = fake_file.getvalue()
389 print(blah)
390 assert fake_file.getvalue() == expected
391
392
393 def test_write_task_environment():
394 """Test task environment is correctly written in jobscript"""
395 # set some task environment conditions
396 expected = ('\n\n # CYLC TASK ENVIRONMENT:\n '
397 'export CYLC_TASK_COMMS_METHOD=ssh\n '
398 'export CYLC_TASK_JOB="1/moo/01"\n export '
399 'CYLC_TASK_NAMESPACE_HIERARCHY="baa moo"\n export '
400 'CYLC_TASK_TRY_NUMBER=1\n export '
401 'CYLC_TASK_FLOW_NUMBERS=1\n export '
402 'CYLC_TASK_PARAM_duck="quack"\n export '
403 'CYLC_TASK_PARAM_mouse="squeak"\n '
404 'CYLC_TASK_WORK_DIR_BASE=\'farm_noises/work_d\'\n}')
405 job_conf = {
406 "platform": {'communication method': 'ssh'},
407 "job_d": "1/moo/01",
408 "namespace_hierarchy": ["baa", "moo"],
409 "dependencies": ['moo', 'neigh', 'quack'],
410 "try_num": 1,
411 "flow_nums": {1},
412 "param_var": {"duck": "quack",
413 "mouse": "squeak"},
414 "work_d": "farm_noises/work_d",
415 "workflow_name": "test_write_task_environment",
416 }
417 with io.StringIO() as fake_file:
418 JobFileWriter()._write_task_environment(fake_file, job_conf)
419 assert fake_file.getvalue() == expected
420
421
422 def test_write_runtime_environment():
423 """Test runtime environment is correctly written in jobscript"""
424
425 expected = (
426 '\n\ncylc__job__inst__user_env() {\n # TASK RUNTIME '
427 'ENVIRONMENT:\n export cow sheep duck\n'
428 ' cow=~/"moo"\n sheep=~baa/"baa"\n '
429 'duck=~quack\n}')
430 job_conf = {
431 'environment': {
432 'cow': '~/moo',
433 'sheep': '~baa/baa',
434 'duck': '~quack'
435 },
436 "workflow_name": "test_write_runtime_environment",
437 }
438 with io.StringIO() as fake_file:
439 JobFileWriter()._write_runtime_environment(fake_file, job_conf)
440 assert fake_file.getvalue() == expected
441
442
443 def test_write_epilogue():
444 """Test epilogue is correctly written in jobscript"""
445 expected = '\n' + dedent('''
446 CYLC_RUN_DIR="${CYLC_RUN_DIR:-$HOME/cylc-run}"
447 . "${CYLC_RUN_DIR}/${CYLC_WORKFLOW_ID}/.service/etc/job.sh"
448 cylc__job__main
449
450 #EOF: 1/moo/01
451 ''')
452 job_conf = {'job_d': "1/moo/01"}
453 with io.StringIO() as fake_file:
454 JobFileWriter()._write_epilogue(fake_file, job_conf)
455 assert fake_file.getvalue() == expected
456
457
458 def test_write_global_init_scripts(fixture_get_platform):
459 """Test global init script is correctly written in jobscript"""
460
461 job_conf = {
462 "platform": fixture_get_platform({
463 "global init-script": (
464 'export COW=moo\n'
465 'export PIG=oink\n'
466 'export DONKEY=HEEHAW\n'
467 )
468 })
469 }
470 expected = '\n' + dedent('''
471 # GLOBAL INIT-SCRIPT:
472 export COW=moo
473 export PIG=oink
474 export DONKEY=HEEHAW
475 ''')
476 with io.StringIO() as fake_file:
477 JobFileWriter()._write_global_init_script(fake_file, job_conf)
478 assert fake_file.getvalue() == expected
479
480
481 def test_homeless_platform(fixture_get_platform):
482 """Ensure there are no uses of $HOME before the global init-script.
483
484 This is to allow users to configure a $HOME on machines with no $HOME
485 directory.
486 """
487 job_conf = {
488 "platform": fixture_get_platform({
489 'global init-script': 'some-script'
490 }),
491 "task_id": "1/a",
492 "workflow_name": "b",
493 "work_d": "c/d",
494 "uuid_str": "e",
495 'environment': {},
496 'cow': '~/moo',
497 "job_d": "1/a/01",
498 "try_num": 1,
499 "flow_nums": {1},
500 # "job_runner_name": "background",
501 "param_var": {},
502 "execution_time_limit": None,
503 "namespace_hierarchy": [],
504 "dependencies": [],
505 "init-script": "",
506 "env-script": "",
507 "err-script": "",
508 "pre-script": "",
509 "script": "",
510 "post-script": "",
511 "exit-script": "",
512 }
513
514 with NamedTemporaryFile() as local_job_file_path:
515 local_job_file_path = local_job_file_path.name
516 JobFileWriter().write(local_job_file_path, job_conf)
517 with open(local_job_file_path, 'r') as local_job_file:
518 job_script = local_job_file.read()
519
520 # ensure that $HOME is not used before the global init-script
521 for line in job_script.splitlines():
522 if line.startswith(' '):
523 # ignore env/script functions which aren't run until later
524 continue
525 if line == '# GLOBAL INIT-SCRIPT:':
526 # quit once we've hit the global init-script
527 break
528 if 'HOME' in line:
529 # bail if $HOME is used
530 raise Exception(f'$HOME found in {line}\n{job_script}')
531
532 # also ensure there is no use of $HOME in the job.sh script
533 with open(Path(cylc_flow_file).parent / 'etc/job.sh', 'r') as job_sh:
534 job_sh_txt = job_sh.read()
535 if 'HOME' in job_sh_txt:
536 raise Exception('$HOME found in job.sh\n{job_sh_txt}')