| 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 contextlib import suppress |
| 18 |
import os |
| 19 |
from pathlib import Path |
| 20 |
import re |
| 21 |
import sqlite3 |
| 22 |
from tempfile import NamedTemporaryFile |
| 23 |
from textwrap import dedent |
| 24 |
from types import SimpleNamespace |
| 25 |
import warnings |
| 26 |
|
| 27 |
import pytest |
| 28 |
from pytest import param |
| 29 |
|
| 30 |
from cylc.flow import __version__ as cylc_version |
| 31 |
from cylc.flow.parsec.OrderedDict import OrderedDictWithDefaults |
| 32 |
from cylc.flow.parsec.exceptions import ( |
| 33 |
FileParseError, |
| 34 |
IncludeFileNotFoundError, |
| 35 |
Jinja2Error, |
| 36 |
ParsecError, |
| 37 |
) |
| 38 |
from cylc.flow.parsec.fileparse import ( |
| 39 |
EXTRA_VARS_TEMPLATE, |
| 40 |
_get_fpath_for_source, |
| 41 |
_prepend_old_templatevars, |
| 42 |
addict, |
| 43 |
addsect, |
| 44 |
get_cylc_env_vars, |
| 45 |
merge_template_vars, |
| 46 |
multiline, |
| 47 |
parse, |
| 48 |
process_plugins, |
| 49 |
read_and_proc, |
| 50 |
) |
| 51 |
|
| 52 |
|
| 53 |
def test_file_parse_error(): |
| 54 |
error = FileParseError(reason="No reason") |
| 55 |
assert str(error) == "No reason" |
| 56 |
|
| 57 |
error = FileParseError("", index=2) |
| 58 |
assert str(error) == ( |
| 59 |
" (line 3)\n" |
| 60 |
"(line numbers match 'cylc view -p')" |
| 61 |
) |
| 62 |
|
| 63 |
error = FileParseError("", line="test") |
| 64 |
assert str(error) == ":\n test" |
| 65 |
|
| 66 |
error = FileParseError("ERROR", lines={"a": ["1", "2"], "b": ["3"]}) |
| 67 |
assert str(error) == '\n'.join([ |
| 68 |
'ERROR', |
| 69 |
'File a', |
| 70 |
' 1', |
| 71 |
' 2\t<--', |
| 72 |
'File b', |
| 73 |
' 3\t<--' |
| 74 |
]) |
| 75 |
|
| 76 |
|
| 77 |
def test_addsect(): |
| 78 |
cfg = OrderedDictWithDefaults() |
| 79 |
cfg["section1"] = OrderedDictWithDefaults() |
| 80 |
cfg["section1"]["subsection"] = OrderedDictWithDefaults() |
| 81 |
new_section_name = "test" |
| 82 |
existing_section_name = "section1" |
| 83 |
parents = ["section1"] |
| 84 |
|
| 85 |
empty_cfg = OrderedDictWithDefaults() |
| 86 |
|
| 87 |
addsect(empty_cfg, "", []) |
| 88 |
assert len(empty_cfg) == 1 |
| 89 |
assert "" in empty_cfg |
| 90 |
|
| 91 |
assert len(cfg) == 1 |
| 92 |
addsect(cfg, existing_section_name, []) |
| 93 |
assert len(cfg) == 1 |
| 94 |
|
| 95 |
assert "test" not in cfg["section1"] |
| 96 |
addsect(cfg, new_section_name, parents) |
| 97 |
assert len(cfg) == 1 |
| 98 |
assert "test" in cfg["section1"] |
| 99 |
|
| 100 |
|
| 101 |
def test_addict_error_line_already_encountered(): |
| 102 |
with pytest.raises(FileParseError): |
| 103 |
addict({"title": "a"}, "title", None, ["title"], 1) |
| 104 |
|
| 105 |
|
| 106 |
def test_addict_new_value_added(): |
| 107 |
for key, val in [ |
| 108 |
('a', '1'), |
| 109 |
('b', '2'), |
| 110 |
('c', '3') |
| 111 |
]: |
| 112 |
cfg = OrderedDictWithDefaults() |
| 113 |
addict(cfg, key, val, [], 0) |
| 114 |
assert key in cfg |
| 115 |
|
| 116 |
|
| 117 |
def test_addict_replace_value(): |
| 118 |
cfg = OrderedDictWithDefaults() |
| 119 |
cfg['country'] = 'ABC' |
| 120 |
addict(cfg, 'country', 'test', [], 0) |
| 121 |
assert cfg['country'] == 'test' |
| 122 |
|
| 123 |
|
| 124 |
def test_addict_replace_value_1(): |
| 125 |
""""Special case depending on key and parents, for |
| 126 |
|
| 127 |
- key is 'graph' AND parents['scheduling']['graph'] OR |
| 128 |
- len(parents)==3 AND parents['scheduling']['graph'][?] |
| 129 |
""" |
| 130 |
|
| 131 |
# set 1 key is graph, parents is wrong (T, F) |
| 132 |
cfg = OrderedDictWithDefaults() |
| 133 |
cfg['graph'] = 'ABC' |
| 134 |
addict(cfg, 'graph', 'test', [], 0) |
| 135 |
assert cfg['graph'] == 'test' |
| 136 |
|
| 137 |
# set 2 key is graph, parents right (T, T) |
| 138 |
cfg = { |
| 139 |
'scheduling': { |
| 140 |
'graph': { |
| 141 |
'graph': 'ABC' |
| 142 |
} |
| 143 |
} |
| 144 |
} |
| 145 |
addict(cfg, 'graph', 'test', ['scheduling', 'graph'], 0) |
| 146 |
assert ( |
| 147 |
cfg['scheduling']['graph']['graph'] |
| 148 |
) == ['ABC', 'test'] |
| 149 |
|
| 150 |
# other side of boolean expression |
| 151 |
|
| 152 |
# set 3 len(parents) is 3, parents is wrong (T, F) |
| 153 |
cfg = { |
| 154 |
'scheduling': { |
| 155 |
'graph': { |
| 156 |
'team': { |
| 157 |
'graph': 'ABC' |
| 158 |
} |
| 159 |
}, |
| 160 |
'notme': { |
| 161 |
'team': { |
| 162 |
'graph': '1' |
| 163 |
} |
| 164 |
} |
| 165 |
} |
| 166 |
} |
| 167 |
addict(cfg, 'graph', 'test', ['scheduling', 'notme', 'team'], 0) |
| 168 |
assert ( |
| 169 |
cfg['scheduling']['notme']['team']['graph'] |
| 170 |
) == 'test' |
| 171 |
|
| 172 |
# set 3 len(parents) is 3, parents is right (T, T) |
| 173 |
cfg = { |
| 174 |
'scheduling': { |
| 175 |
'graph': { |
| 176 |
'team': { |
| 177 |
'graph': 'ABC' |
| 178 |
} |
| 179 |
} |
| 180 |
} |
| 181 |
} |
| 182 |
addict(cfg, 'graph', 'test', ['scheduling', 'graph', 'team'], 0) |
| 183 |
assert cfg['scheduling']['graph']['team']['graph'] == ['ABC', 'test'] |
| 184 |
|
| 185 |
|
| 186 |
@pytest.mark.parametrize( |
| 187 |
'flines, value, index, maxline, exc, expected', |
| 188 |
( |
| 189 |
param( |
| 190 |
[], |
| 191 |
"'''single line'''", |
| 192 |
0, |
| 193 |
0, |
| 194 |
None, |
| 195 |
("'''single line'''", 0), |
| 196 |
id='single-line', |
| 197 |
), |
| 198 |
param( |
| 199 |
["'''single line"], |
| 200 |
"'''single line", # missing closing quote |
| 201 |
0, |
| 202 |
0, |
| 203 |
FileParseError, |
| 204 |
{ |
| 205 |
'reason': 'Multiline string not closed', |
| 206 |
'line': "'''single line", |
| 207 |
}, |
| 208 |
id='missing-closing-quote', |
| 209 |
), |
| 210 |
param( |
| 211 |
["'''", "single line"], |
| 212 |
"'''\n '''single line", # missing closing quote |
| 213 |
0, |
| 214 |
0, |
| 215 |
FileParseError, |
| 216 |
{'reason': 'Invalid line', 'line': "'''"}, |
| 217 |
id='missing-closing-quote2', |
| 218 |
), |
| 219 |
param( |
| 220 |
["", "another value"], # multiline, but we forgot to close quotes |
| 221 |
"'''a\n#b", |
| 222 |
0, |
| 223 |
1, |
| 224 |
FileParseError, |
| 225 |
{'reason': "Multiline string not closed"}, |
| 226 |
id='multiline-missing-closing-quote', |
| 227 |
), |
| 228 |
param( |
| 229 |
["", "c'''"], |
| 230 |
"'''a\n#b", |
| 231 |
0, |
| 232 |
1, |
| 233 |
None, |
| 234 |
("'''a\n#b\nc'''", 1), |
| 235 |
id='good-path', |
| 236 |
), |
| 237 |
param( |
| 238 |
["", "c'''"], # multiline, but we forgot to close quotes |
| 239 |
"'''a\n#b", |
| 240 |
0, |
| 241 |
10000, # no error. The function will stop before on the quotes |
| 242 |
None, |
| 243 |
("'''a\n#b\nc'''", 1), |
| 244 |
id='multiline-missing-closing-quote2', |
| 245 |
), |
| 246 |
param( |
| 247 |
["", "c", "hello", ""], # quotes out of balance |
| 248 |
"'''a\n#b", |
| 249 |
0, |
| 250 |
3, |
| 251 |
FileParseError, |
| 252 |
{'reason': "Multiline string not closed"}, |
| 253 |
id='unbalanced-quotes', |
| 254 |
), |
| 255 |
param( |
| 256 |
["", "c", "hello", ""], |
| 257 |
"'''a\n#b", |
| 258 |
0, |
| 259 |
4, # one too many |
| 260 |
IndexError, |
| 261 |
None, |
| 262 |
id='one-too-many', |
| 263 |
), |
| 264 |
param( |
| 265 |
["", "a'''c", "hello", ""], |
| 266 |
"'''a\n#b", |
| 267 |
0, |
| 268 |
3, |
| 269 |
FileParseError, |
| 270 |
{'reason': 'Invalid line', 'line': "a'''c"}, |
| 271 |
id='invalid-quotes', |
| 272 |
), |
| 273 |
), |
| 274 |
) |
| 275 |
def test_multiline(flines, value, index, maxline, exc, expected): |
| 276 |
if exc is not None: |
| 277 |
with pytest.raises(exc) as cm: |
| 278 |
multiline(flines, value, index, maxline) |
| 279 |
if isinstance(cm.value, FileParseError): |
| 280 |
exc = cm.value |
| 281 |
for key, attr in expected.items(): |
| 282 |
assert getattr(exc, key) == attr |
| 283 |
else: |
| 284 |
r = multiline(flines, value, index, maxline) |
| 285 |
assert r == expected |
| 286 |
|
| 287 |
|
| 288 |
def test_read_and_proc_no_template_engine(): |
| 289 |
with NamedTemporaryFile() as tf: |
| 290 |
fpath = tf.name |
| 291 |
template_vars = None |
| 292 |
viewcfg = { |
| 293 |
'jinja2': False, |
| 294 |
'contin': False, |
| 295 |
'inline': False, |
| 296 |
} |
| 297 |
tf.write("a=b\n".encode()) |
| 298 |
tf.flush() |
| 299 |
r = read_and_proc(fpath=fpath, template_vars=template_vars, |
| 300 |
viewcfg=viewcfg) |
| 301 |
assert r == ['a=b'] |
| 302 |
|
| 303 |
# last \\ is ignored, becoming just '' |
| 304 |
tf.write("c=\\\nd\n\\".encode()) |
| 305 |
tf.flush() |
| 306 |
|
| 307 |
viewcfg = { |
| 308 |
'jinja2': False, |
| 309 |
'contin': True, |
| 310 |
'inline': False, |
| 311 |
} |
| 312 |
r = read_and_proc(fpath=fpath, template_vars=template_vars, |
| 313 |
viewcfg=viewcfg) |
| 314 |
assert r == ['a=b', 'c=d', ''] |
| 315 |
|
| 316 |
|
| 317 |
def test_inline(): |
| 318 |
with NamedTemporaryFile() as tf: |
| 319 |
fpath = tf.name |
| 320 |
template_vars = None |
| 321 |
viewcfg = { |
| 322 |
'jinja2': False, |
| 323 |
'contin': False, |
| 324 |
'inline': True, |
| 325 |
'mark': None, |
| 326 |
'single': None, |
| 327 |
'label': None, |
| 328 |
} |
| 329 |
with NamedTemporaryFile() as include_file: |
| 330 |
include_file.write("c=d".encode()) |
| 331 |
include_file.flush() |
| 332 |
tf.write(("a=b\n%include \"{0}\"" |
| 333 |
.format(include_file.name)).encode()) |
| 334 |
tf.flush() |
| 335 |
r = read_and_proc(fpath=fpath, template_vars=template_vars, |
| 336 |
viewcfg=viewcfg) |
| 337 |
assert r == ['a=b', 'c=d'] |
| 338 |
|
| 339 |
|
| 340 |
def test_inline_error(): |
| 341 |
with NamedTemporaryFile() as tf: |
| 342 |
fpath = tf.name |
| 343 |
template_vars = None |
| 344 |
viewcfg = { |
| 345 |
'jinja2': False, |
| 346 |
'contin': False, |
| 347 |
'inline': True, |
| 348 |
'mark': None, |
| 349 |
'single': None, |
| 350 |
'label': None, |
| 351 |
} |
| 352 |
tf.write("a=b\n%include \"404.txt\"".encode()) |
| 353 |
tf.flush() |
| 354 |
with pytest.raises(IncludeFileNotFoundError) as cm: |
| 355 |
read_and_proc(fpath=fpath, template_vars=template_vars, |
| 356 |
viewcfg=viewcfg) |
| 357 |
assert "404.txt" in str(cm.value) |
| 358 |
|
| 359 |
|
| 360 |
def test_read_and_proc_jinja2(): |
| 361 |
with NamedTemporaryFile() as tf: |
| 362 |
fpath = tf.name |
| 363 |
template_vars = { |
| 364 |
'name': 'Cylc' |
| 365 |
} |
| 366 |
viewcfg = { |
| 367 |
'jinja2': True, |
| 368 |
'contin': False, |
| 369 |
'inline': False, |
| 370 |
} |
| 371 |
tf.write("#!jinja2\na={{ name }}\n".encode()) |
| 372 |
tf.flush() |
| 373 |
r = read_and_proc(fpath=fpath, template_vars=template_vars, |
| 374 |
viewcfg=viewcfg) |
| 375 |
assert r == ['a=Cylc'] |
| 376 |
|
| 377 |
|
| 378 |
def test_read_and_proc_cwd(tmp_path): |
| 379 |
"""The template processor should be able to read workflow files. |
| 380 |
|
| 381 |
This relies on moving to the config dir during file parsing. |
| 382 |
""" |
| 383 |
|
| 384 |
sdir = tmp_path / "sub" |
| 385 |
sdir.mkdir() |
| 386 |
|
| 387 |
for sub in ["a", "b", "c"]: |
| 388 |
(sdir / sub).touch() |
| 389 |
|
| 390 |
viewcfg = { |
| 391 |
'jinja2': True, |
| 392 |
'contin': False, |
| 393 |
'inline': False |
| 394 |
} |
| 395 |
|
| 396 |
tmpf = tmp_path / "a.conf" |
| 397 |
|
| 398 |
with open(tmpf, 'w') as tf: |
| 399 |
tf.write( |
| 400 |
'#!Jinja2' |
| 401 |
'\n{% from "os" import listdir %}' |
| 402 |
'\n{% for f in listdir("sub") %}' |
| 403 |
'\n{{f}}' |
| 404 |
'\n{% endfor %}' |
| 405 |
) |
| 406 |
|
| 407 |
with open(tmpf, 'r') as tf: |
| 408 |
r = read_and_proc(fpath=tf.name, viewcfg=viewcfg) |
| 409 |
|
| 410 |
assert sorted(r) == ['a', 'b', 'c'] |
| 411 |
|
| 412 |
|
| 413 |
def test_read_and_proc_jinja2_error(): |
| 414 |
with NamedTemporaryFile() as tf: |
| 415 |
fpath = tf.name |
| 416 |
template_vars = { |
| 417 |
'name': 'Cylc' |
| 418 |
} |
| 419 |
viewcfg = { |
| 420 |
'jinja2': True, |
| 421 |
'contin': False, |
| 422 |
'inline': False, |
| 423 |
} |
| 424 |
tf.write("#!jinja2\na={{ name \n".encode()) |
| 425 |
tf.flush() |
| 426 |
with pytest.raises(Jinja2Error) as cm: |
| 427 |
read_and_proc(fpath=fpath, template_vars=template_vars, |
| 428 |
viewcfg=viewcfg) |
| 429 |
assert ( |
| 430 |
"unexpected end of template, expected " |
| 431 |
"'end of print statement'." |
| 432 |
) in str(cm.value) |
| 433 |
|
| 434 |
|
| 435 |
def test_read_and_proc_jinja2_error_missing_shebang(): |
| 436 |
with NamedTemporaryFile() as tf: |
| 437 |
fpath = tf.name |
| 438 |
template_vars = { |
| 439 |
'name': 'Cylc' |
| 440 |
} |
| 441 |
viewcfg = { |
| 442 |
'jinja2': True, |
| 443 |
'contin': False, |
| 444 |
'inline': False, |
| 445 |
} |
| 446 |
# first line is missing shebang! |
| 447 |
tf.write("a={{ name }}\n".encode()) |
| 448 |
tf.flush() |
| 449 |
r = read_and_proc(fpath=fpath, template_vars=template_vars, |
| 450 |
viewcfg=viewcfg) |
| 451 |
assert r == ['a={{ name }}'] |
| 452 |
|
| 453 |
|
| 454 |
def test_read_and_proc_jinja2_warnings( |
| 455 |
monkeypatch: pytest.MonkeyPatch, |
| 456 |
tmp_path: Path, |
| 457 |
caplog: pytest.LogCaptureFixture, |
| 458 |
): |
| 459 |
"""Warnings from users' custom jinja2 filters etc should be logged.""" |
| 460 |
(fpath := tmp_path / 'flow.cylc').write_text(r"#!jinja2\n") |
| 461 |
msg = "Mock deprecation warning" |
| 462 |
|
| 463 |
def mock_jinja2process(fpath, *a, **k): |
| 464 |
if fpath.endswith('flow.cylc'): |
| 465 |
warnings.warn(msg, category=DeprecationWarning) |
| 466 |
return [] |
| 467 |
|
| 468 |
monkeypatch.setattr( |
| 469 |
'cylc.flow.parsec.jinja2support.jinja2process', mock_jinja2process |
| 470 |
) |
| 471 |
read_and_proc( |
| 472 |
fpath=str(fpath), |
| 473 |
viewcfg={'jinja2': True, 'contin': False, 'inline': False}, |
| 474 |
) |
| 475 |
assert len(caplog.records) == 1 |
| 476 |
rec = caplog.records[0] |
| 477 |
assert rec.levelname == 'WARNING' |
| 478 |
assert re.match( |
| 479 |
( |
| 480 |
r"The following warnings .* during Jinja2 preprocessing.*\s+" |
| 481 |
rf"{__file__}:\d+: DeprecationWarning: {msg}" |
| 482 |
), |
| 483 |
rec.message, |
| 484 |
) |
| 485 |
|
| 486 |
|
| 487 |
def test_read_and_proc_jinja2_warnings_invalid_escape( |
| 488 |
tmp_path: Path, caplog: pytest.LogCaptureFixture |
| 489 |
): |
| 490 |
"""When a warning comes from a j2 template expression, it should be logged |
| 491 |
with the cylc config filepath.""" |
| 492 |
(fpath := tmp_path / 'flow.cylc').write_text( |
| 493 |
dedent(r""" |
| 494 |
#!jinja2 |
| 495 |
{% from 'warnings' import warn %} |
| 496 |
{% do warn('Mock warning') %} |
| 497 |
""").lstrip() |
| 498 |
) |
| 499 |
read_and_proc( |
| 500 |
fpath=str(fpath), |
| 501 |
viewcfg={'jinja2': True, 'contin': False, 'inline': False}, |
| 502 |
) |
| 503 |
|
| 504 |
assert ( |
| 505 |
f"{fpath}:<jinja2 template>: UserWarning: Mock warning" in caplog.text |
| 506 |
) |
| 507 |
|
| 508 |
|
| 509 |
def test_parse_keys_only_singleline(): |
| 510 |
with NamedTemporaryFile() as of, NamedTemporaryFile() as tf: |
| 511 |
fpath = tf.name |
| 512 |
template_vars = { |
| 513 |
'name': 'Cylc' |
| 514 |
} |
| 515 |
tf.write("#!jinja2\na={{ name }}\n".encode()) |
| 516 |
tf.flush() |
| 517 |
r = parse(fpath=fpath, output_fname=of.name, |
| 518 |
template_vars=template_vars) |
| 519 |
expected = OrderedDictWithDefaults() |
| 520 |
expected['a'] = 'Cylc' |
| 521 |
assert r == expected |
| 522 |
of.flush() |
| 523 |
output_file_contents = of.read().decode() |
| 524 |
assert output_file_contents == 'a=Cylc\n' |
| 525 |
|
| 526 |
|
| 527 |
def test_parse_keys_only_multiline(): |
| 528 |
with NamedTemporaryFile() as of, NamedTemporaryFile() as tf: |
| 529 |
fpath = tf.name |
| 530 |
template_vars = { |
| 531 |
'name': 'Cylc' |
| 532 |
} |
| 533 |
tf.write( |
| 534 |
"#!jinja2\na='''value is \\\n{{ name }}'''\n".encode()) |
| 535 |
tf.flush() |
| 536 |
r = parse(fpath=fpath, output_fname=of.name, |
| 537 |
template_vars=template_vars) |
| 538 |
expected = OrderedDictWithDefaults() |
| 539 |
expected['a'] = "'''value is Cylc'''" |
| 540 |
assert r == expected |
| 541 |
|
| 542 |
|
| 543 |
def test_parse_invalid_line(): |
| 544 |
with NamedTemporaryFile() as of, NamedTemporaryFile() as tf: |
| 545 |
fpath = tf.name |
| 546 |
template_vars = { |
| 547 |
'name': 'Cylc' |
| 548 |
} |
| 549 |
tf.write("#!jinja2\n{{ name }}\n".encode()) |
| 550 |
tf.flush() |
| 551 |
with pytest.raises(FileParseError) as cm: |
| 552 |
parse(fpath=fpath, output_fname=of.name, |
| 553 |
template_vars=template_vars) |
| 554 |
exc = cm.value |
| 555 |
assert exc.reason == 'Invalid line' |
| 556 |
assert exc.line_num == 1 |
| 557 |
assert exc.line == 'Cylc' |
| 558 |
|
| 559 |
|
| 560 |
def test_parse_comments(): |
| 561 |
with NamedTemporaryFile() as of, NamedTemporaryFile() as tf: |
| 562 |
fpath = tf.name |
| 563 |
template_vars = { |
| 564 |
'name': 'Cylc' |
| 565 |
} |
| 566 |
tf.write("#!jinja2\na={{ name }}\n# comment!".encode()) |
| 567 |
tf.flush() |
| 568 |
r = parse(fpath=fpath, output_fname=of.name, |
| 569 |
template_vars=template_vars) |
| 570 |
expected = OrderedDictWithDefaults() |
| 571 |
expected['a'] = 'Cylc' |
| 572 |
assert r == expected |
| 573 |
of.flush() |
| 574 |
output_file_contents = of.read().decode() |
| 575 |
assert output_file_contents == 'a=Cylc\n# comment!\n' |
| 576 |
|
| 577 |
|
| 578 |
def test_parse_with_sections(): |
| 579 |
with NamedTemporaryFile() as of, NamedTemporaryFile() as tf: |
| 580 |
fpath = tf.name |
| 581 |
template_vars = { |
| 582 |
'name': 'Cylc' |
| 583 |
} |
| 584 |
tf.write(("#!jinja2\n[section1]\n" |
| 585 |
"a={{ name }}\n# comment!\n" |
| 586 |
"[[subsection1]]\n" |
| 587 |
"[[subsection2]]\n" |
| 588 |
"[section2]").encode()) |
| 589 |
tf.flush() |
| 590 |
r = parse(fpath=fpath, output_fname=of.name, |
| 591 |
template_vars=template_vars) |
| 592 |
expected = OrderedDictWithDefaults() |
| 593 |
expected['section1'] = OrderedDictWithDefaults() |
| 594 |
expected['section1']['a'] = 'Cylc' |
| 595 |
expected['section1']['subsection1'] = OrderedDictWithDefaults() |
| 596 |
expected['section1']['subsection2'] = OrderedDictWithDefaults() |
| 597 |
expected['section2'] = OrderedDictWithDefaults() |
| 598 |
assert r == expected |
| 599 |
of.flush() |
| 600 |
output_file_contents = of.read().decode() |
| 601 |
assert output_file_contents == ( |
| 602 |
'[section1]\na=Cylc\n# comment!\n' |
| 603 |
'[[subsection1]]\n' |
| 604 |
'[[subsection2]]\n' |
| 605 |
'[section2]\n' |
| 606 |
) |
| 607 |
|
| 608 |
|
| 609 |
def test_parse_with_sections_missing_bracket(): |
| 610 |
with NamedTemporaryFile() as tf: |
| 611 |
fpath = tf.name |
| 612 |
template_vars = { |
| 613 |
'name': 'Cylc' |
| 614 |
} |
| 615 |
tf.write( |
| 616 |
"#!jinja2\n[[section1]\na={{ name }}\n# comment!".encode()) |
| 617 |
tf.flush() |
| 618 |
with pytest.raises(FileParseError) as cm: |
| 619 |
parse(fpath=fpath, output_fname="", |
| 620 |
template_vars=template_vars) |
| 621 |
exc = cm.value |
| 622 |
assert exc.reason == 'bracket mismatch' |
| 623 |
assert exc.line == '[[section1]' |
| 624 |
|
| 625 |
|
| 626 |
def test_parse_with_sections_error_wrong_level(): |
| 627 |
with NamedTemporaryFile() as of, NamedTemporaryFile() as tf: |
| 628 |
fpath = tf.name |
| 629 |
template_vars = { |
| 630 |
'name': 'Cylc' |
| 631 |
} |
| 632 |
tf.write(("#!jinja2\n[section1]\n" |
| 633 |
"a={{ name }}\n# comment!\n" |
| 634 |
"[[[subsection1]]]\n") # expected [[]] instead! |
| 635 |
.encode()) |
| 636 |
tf.flush() |
| 637 |
with pytest.raises(FileParseError) as cm: |
| 638 |
parse(fpath=fpath, output_fname=of.name, |
| 639 |
template_vars=template_vars) |
| 640 |
exc = cm.value |
| 641 |
assert exc.line_num == 4 |
| 642 |
assert exc.line == '[[[subsection1]]]' |
| 643 |
|
| 644 |
|
| 645 |
def test_unclosed_multiline(): |
| 646 |
with NamedTemporaryFile() as tf: |
| 647 |
fpath = tf.name |
| 648 |
template_vars = { |
| 649 |
'name': 'Cylc' |
| 650 |
} |
| 651 |
tf.write((''' |
| 652 |
[scheduling] |
| 653 |
[[graph]] |
| 654 |
R1 = """ |
| 655 |
foo |
| 656 |
|
| 657 |
[runtime] |
| 658 |
[[foo]] |
| 659 |
script = """ |
| 660 |
echo hello world |
| 661 |
""" |
| 662 |
''').encode()) |
| 663 |
tf.flush() |
| 664 |
with pytest.raises(FileParseError) as cm: |
| 665 |
parse(fpath=fpath, output_fname="", |
| 666 |
template_vars=template_vars) |
| 667 |
exc = cm.value |
| 668 |
assert exc.reason == 'Invalid line' |
| 669 |
assert 'echo hello world' in exc.line |
| 670 |
assert 'Did you forget to close [scheduling][graph]R1?' in str(exc) |
| 671 |
|
| 672 |
|
| 673 |
@pytest.mark.parametrize( |
| 674 |
'expect, native_tvars, plugin_result, log', |
| 675 |
[ |
| 676 |
pytest.param( |
| 677 |
{'FOO': 123}, |
| 678 |
{'FOO': 123}, |
| 679 |
{ |
| 680 |
'templating_detected': None, |
| 681 |
'template_variables': {'FOO': 122} |
| 682 |
}, |
| 683 |
[], |
| 684 |
id='no templating engine set' |
| 685 |
), |
| 686 |
pytest.param( |
| 687 |
{'FOO': 125}, |
| 688 |
{'FOO': 125}, |
| 689 |
{ |
| 690 |
'templating_detected': 'qux', |
| 691 |
'template_variables': {'FOO': 124} |
| 692 |
}, |
| 693 |
['Overriding FOO: 124 -> 125'], |
| 694 |
id='Variable overridden' |
| 695 |
), |
| 696 |
pytest.param( |
| 697 |
{'FOO': 126}, |
| 698 |
{'FOO': 126}, |
| 699 |
{ |
| 700 |
'templating_detected': 'qux', |
| 701 |
'template_variables': {'FOO': 126} |
| 702 |
}, |
| 703 |
[], |
| 704 |
id='Variable overridden quietly' |
| 705 |
) |
| 706 |
] |
| 707 |
) |
| 708 |
def test_merge_template_vars(caplog, expect, native_tvars, plugin_result, log): |
| 709 |
assert merge_template_vars(native_tvars, plugin_result) == expect |
| 710 |
assert [r.msg for r in caplog.records] == log |
| 711 |
|
| 712 |
|
| 713 |
@pytest.fixture |
| 714 |
def _mock_old_template_vars_db(tmp_path): |
| 715 |
def _inner(create_srclink=True): |
| 716 |
# Create a fake workflow dir: |
| 717 |
(tmp_path / 'flow.cylc').touch() |
| 718 |
(tmp_path / 'log').mkdir() |
| 719 |
db_path = tmp_path / 'log/db' |
| 720 |
db_path.touch() |
| 721 |
|
| 722 |
# Set up a fake workflow database: |
| 723 |
conn = sqlite3.connect(str(db_path)) |
| 724 |
conn.execute( |
| 725 |
"CREATE TABLE workflow_template_vars" |
| 726 |
"(key TEXT, value TEXT, PRIMARY KEY(key)) ;" |
| 727 |
) |
| 728 |
conn.execute( |
| 729 |
"INSERT INTO workflow_template_vars VALUES" |
| 730 |
" ('Marius', '\"Consul\"')" |
| 731 |
) |
| 732 |
conn.execute( |
| 733 |
"CREATE TABLE workflow_params" |
| 734 |
"(key TEXT, value TEXT, PRIMARY KEY(key)) ;" |
| 735 |
) |
| 736 |
conn.execute( |
| 737 |
"INSERT INTO workflow_params VALUES" |
| 738 |
f" ('cylc_version', '{cylc_version}')" |
| 739 |
) |
| 740 |
conn.commit() |
| 741 |
conn.close() |
| 742 |
|
| 743 |
# Simulate being an installed rundir by creating a sourcelink: |
| 744 |
if create_srclink: |
| 745 |
src = (tmp_path / 'src') |
| 746 |
src.mkdir(exist_ok=True) |
| 747 |
link = tmp_path.parent / '_cylc-install/source' |
| 748 |
link.parent.mkdir(exist_ok=True) |
| 749 |
with suppress(FileExistsError): |
| 750 |
# We don't mind the link persisting. |
| 751 |
os.symlink(src, link) |
| 752 |
return tmp_path / 'flow.cylc' |
| 753 |
yield _inner |
| 754 |
|
| 755 |
|
| 756 |
@pytest.mark.parametrize( |
| 757 |
'expect, tvars', |
| 758 |
[ |
| 759 |
param( |
| 760 |
{'Marius': 'Consul', 'Julius': 'Pontifex'}, {'Julius': 'Pontifex'}, |
| 761 |
id='It adds a new key at the end' |
| 762 |
), |
| 763 |
param( |
| 764 |
{'Marius': 'Tribune'}, {'Marius': 'Tribune'}, |
| 765 |
id='It overrides an existing key' |
| 766 |
), |
| 767 |
] |
| 768 |
) |
| 769 |
def test__prepend_old_templatevars(_mock_old_template_vars_db, expect, tvars): |
| 770 |
# Create a target for a source symlink |
| 771 |
result = _prepend_old_templatevars( |
| 772 |
_mock_old_template_vars_db(), tvars) |
| 773 |
assert result == expect |
| 774 |
|
| 775 |
|
| 776 |
def test_get_fpath_for_source(tmp_path): |
| 777 |
# Create rundir and srcdir: |
| 778 |
srcdir = tmp_path / 'source' |
| 779 |
rundir = tmp_path / 'run' |
| 780 |
srcdir.mkdir() |
| 781 |
rundir.mkdir() |
| 782 |
(rundir / 'flow.cylc').touch() |
| 783 |
(srcdir / 'flow.cylc').touch() |
| 784 |
|
| 785 |
# Mock Options object: |
| 786 |
opts = SimpleNamespace() |
| 787 |
|
| 788 |
# It raises an error if source is not linked: |
| 789 |
with pytest.raises( |
| 790 |
ParsecError, match=f'Cannot validate {rundir} against source:' |
| 791 |
): |
| 792 |
opts.against_source = True |
| 793 |
_get_fpath_for_source(rundir / 'flow.cylc', opts) |
| 794 |
|
| 795 |
# Create symlinks: |
| 796 |
link = rundir / '_cylc-install/source' |
| 797 |
link.parent.mkdir(exist_ok=True) |
| 798 |
os.symlink(srcdir, link) |
| 799 |
|
| 800 |
# It does nothing if opts.against_source is False: |
| 801 |
opts.against_source = False |
| 802 |
assert _get_fpath_for_source( |
| 803 |
rundir / 'flow.cylc', opts) == rundir / 'flow.cylc' |
| 804 |
|
| 805 |
# It gets source dir if opts.against_source is True: |
| 806 |
opts.against_source = True |
| 807 |
assert _get_fpath_for_source( |
| 808 |
rundir / 'flow.cylc', opts) == str(srcdir / 'flow.cylc') |
| 809 |
|
| 810 |
|
| 811 |
def test_user_has_no_cwd(tmp_path): |
| 812 |
"""Test we can parse a config file even if cwd does not exist.""" |
| 813 |
cwd = tmp_path / "cwd" |
| 814 |
os.mkdir(cwd) |
| 815 |
os.chdir(cwd) |
| 816 |
os.rmdir(cwd) |
| 817 |
# (I am now located in a non-existent directory. Outrageous!) |
| 818 |
with NamedTemporaryFile() as tf: |
| 819 |
fpath = tf.name |
| 820 |
tf.write((''' |
| 821 |
[scheduling] |
| 822 |
[[graph]] |
| 823 |
R1 = "foo" |
| 824 |
''').encode()) |
| 825 |
tf.flush() |
| 826 |
# Should not raise FileNotFoundError from os.getcwd(): |
| 827 |
parse(fpath=fpath, output_fname="") |
| 828 |
|
| 829 |
|
| 830 |
def test_get_cylc_env_vars(monkeypatch): |
| 831 |
"""It should return CYLC env vars but not CYLC_VERSION or CYLC_ENV_NAME.""" |
| 832 |
monkeypatch.setattr( |
| 833 |
'os.environ', |
| 834 |
{ |
| 835 |
"CYLC_VERSION": "betwixt", |
| 836 |
"CYLC_ENV_NAME": "between", |
| 837 |
"CYLC_QUESTION": "que?", |
| 838 |
"CYLC_ANSWER": "42", |
| 839 |
"FOO": "foo" |
| 840 |
} |
| 841 |
) |
| 842 |
assert ( |
| 843 |
get_cylc_env_vars() == { |
| 844 |
"CYLC_QUESTION": "que?", |
| 845 |
"CYLC_ANSWER": "42", |
| 846 |
} |
| 847 |
) |
| 848 |
|
| 849 |
|
| 850 |
class EntryPointWrapper: |
| 851 |
"""Wraps a method to make it look like an entry point.""" |
| 852 |
|
| 853 |
def __init__(self, fcn): |
| 854 |
self.name = fcn.__name__ |
| 855 |
self.fcn = fcn |
| 856 |
|
| 857 |
def load(self): |
| 858 |
return self.fcn |
| 859 |
|
| 860 |
|
| 861 |
@EntryPointWrapper |
| 862 |
def pre_configure_basic(*_, **__): |
| 863 |
"""Simple plugin that returns one env var and one template var.""" |
| 864 |
return {'env': {'foo': 44}, 'template_variables': {}} |
| 865 |
|
| 866 |
|
| 867 |
def test_plugins_not_called_on_global_config(monkeypatch): |
| 868 |
monkeypatch.setattr( |
| 869 |
'cylc.flow.plugins.iter_entry_points', |
| 870 |
lambda x: [pre_configure_basic] |
| 871 |
) |
| 872 |
result = process_plugins('/pennine/way/flow.cylc', {}) |
| 873 |
assert result != EXTRA_VARS_TEMPLATE |
| 874 |
result = process_plugins('/appalachian/trail/global.cylc', {}) |
| 875 |
assert result == EXTRA_VARS_TEMPLATE |