Debian Codegraph @

tests/unit/parsec/test_jinja2support.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 import sys
19 from textwrap import dedent
20
21 import jinja2
22 import pytest
23
24 from cylc.flow.parsec.jinja2support import (
25 Jinja2AssertionError,
26 Jinja2Error,
27 PyModuleLoader,
28 assert_helper,
29 jinja2environment,
30 jinja2process,
31 raise_helper,
32 )
33 from cylc.flow.util import sstrip
34
35
36 def test_raise_helper():
37 message = 'Ops'
38 with pytest.raises(Jinja2AssertionError) as cm:
39 raise_helper(message=message)
40
41 assert str(cm.value) == "Ops"
42
43
44 def test_assert_helper():
45 assert_helper(logical=True, message="Doesn't matter") # harmless
46
47 with pytest.raises(Exception):
48 assert_helper(logical=False, message="Doesn't matter")
49
50
51 @pytest.fixture
52 def custom_filter_global_and_test(tmp_path: Path):
53 """Provide custom Jinja2 filter, global and test."""
54 (filters_dir := tmp_path / 'Jinja2Filters').mkdir()
55 with open(filters_dir / "exclaim.py", "w") as tf:
56 tf.write(dedent(r"""
57 def exclaim(val):
58 return f"{val}!!!"
59 """))
60
61 (globals_dir := tmp_path / 'Jinja2Globals').mkdir()
62 with open(globals_dir / "assassins.py", "w") as tf:
63 tf.write(r"assassins = 'creed'")
64
65 (tests_dir := tmp_path / 'Jinja2Tests').mkdir()
66 with open(tests_dir / "big.py", "w") as tf:
67 tf.write(dedent(r"""
68 def big(n: int) -> bool:
69 return n > 9000
70 """))
71
72
73 def test_jinja2environment(tmp_path: Path, custom_filter_global_and_test):
74 env = jinja2environment(tmp_path)
75 # our jinja env contains the following keys in the global namespace
76 assert 'environ' in env.globals
77 assert 'raise' in env.globals
78 assert 'assert' in env.globals
79
80 assert env.filters['exclaim']('UP') == 'UP!!!'
81 assert env.globals['assassins'] == 'creed'
82 assert env.tests['big'](5) is False
83
84
85 def test_jinja2process(tmp_path, custom_filter_global_and_test):
86 lines = [
87 r"skipped",
88 r"My name is {{ name }}",
89 r"",
90 r"Custom global: {{ assassins }}",
91 r"Custom filter: {{ 'UP' | exclaim }}",
92 r"Custom test: {% if 5 is big %}big{% else %}small{% endif %}",
93 ]
94 variables = {'name': 'Cylc'}
95 assert jinja2process(None, lines, tmp_path, variables) == [
96 "My name is Cylc",
97 "Custom global: creed",
98 "Custom filter: UP!!!",
99 "Custom test: small",
100 ]
101
102
103 def test_jinja2process_missing_variables(tmp_path):
104 lines = ["skipped", "My name is {{ name }}", ""]
105 with pytest.raises(Jinja2Error) as exc:
106 jinja2process(None, lines, tmp_path, template_vars=None)
107 assert 'jinja2.UndefinedError' in str(exc)
108
109
110 def test_pymoduleloader(tmp_path):
111 filters_dir = tmp_path / 'Jinja2filters'
112 filters_dir.mkdir()
113 with open(filters_dir / 'jinja2jinja.py', 'bw+') as tf:
114 tf.write(
115 "def jinja2jinja():\n raise Exception('It works!')".encode())
116 tf.seek(0)
117 env = jinja2environment(tmp_path)
118
119 module_loader = PyModuleLoader()
120 template = module_loader.load(environment=env, name='sys')
121 assert sys.path == template.module.path
122
123 template2 = module_loader.load(
124 environment=env, name='__python__.sys')
125
126 assert template.module.path == template2.module.path
127
128
129 def test_pymoduleloader_invalid_module(tmp_path):
130 filters_dir = tmp_path / 'Jinja2filters'
131 filters_dir.mkdir()
132 with open(filters_dir / 'jinja2jinja.py', 'bw+') as tf:
133 tf.write(
134 "def jinja2jinja():\n raise Exception('It works!')".encode())
135 tf.seek(0)
136 env = jinja2environment(tmp_path)
137
138 module_loader = PyModuleLoader()
139 with pytest.raises(jinja2.TemplateNotFound):
140 module_loader.load(environment=env, name='no way jose')
141
142
143 def test_restore_deprecated_interfaces(tmp_path, log_filter):
144 """It should log warnings when back-supported Jinja2 interfaces are used.
145
146 See https://github.com/cylc/cylc-flow/pull/7325
147 """
148 # flow.cylc
149 flow_cylc = tmp_path / 'flow.cylc'
150 flow_cylc.write_text(sstrip('''
151 #!Jinja2
152 # {{ 1 | foo }}
153 '''))
154
155 # Jinja2Filters/foo.py
156 (tmp_path / 'Jinja2Filters').mkdir()
157 ((tmp_path / 'Jinja2Filters') / 'foo.py').write_text(sstrip('''
158 from jinja2 import contextfilter
159
160 @contextfilter # NOTE: contextfilter is deprecated!
161 def foo(x, y):
162 return y * 2
163 ''' + '\n'))
164
165 # process Jinja2 template
166 assert jinja2process(
167 flow_cylc,
168 flow_cylc.read_text().splitlines(),
169 str(tmp_path),
170 ) == ['# 2']
171
172 # warning should be raised
173 assert log_filter(
174 contains=(
175 'The Jinja2 function contextfilter was renamed to pass_context'
176 )
177 )