File: test_templating.py

package info (click to toggle)
cloud-init 25.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 12,412 kB
  • sloc: python: 135,894; sh: 3,883; makefile: 141; javascript: 30; xml: 22
file content (305 lines) | stat: -rw-r--r-- 10,209 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# Copyright (C) 2014 Yahoo! Inc.
#
# Author: Joshua Harlow <harlowja@yahoo-inc.com>
#
# This file is part of cloud-init. See LICENSE file for license information.

import logging
import textwrap
from unittest import mock

import pytest

from cloudinit import templater
from cloudinit.templater import JinjaSyntaxParsingException
from cloudinit.util import load_binary_file, write_file
from tests.unittests import helpers as test_helpers


class TestTemplates:

    jinja_utf8 = b"It\xe2\x80\x99s not ascii, {{name}}\n"
    jinja_utf8_rbob = b"It\xe2\x80\x99s not ascii, bob\n".decode("utf-8")

    @staticmethod
    def add_header(renderer, data):
        """Return text (py2 unicode/py3 str) with template header."""
        if isinstance(data, bytes):
            data = data.decode("utf-8")
        return "## template: %s\n" % renderer + data

    def test_render_basic(self):
        in_data = textwrap.dedent(
            """
            ${b}

            c = d
            """
        )
        in_data = in_data.strip()
        expected_data = textwrap.dedent(
            """
            2

            c = d
            """
        )
        out_data = templater.basic_render(in_data, {"b": 2})
        assert expected_data.strip() == out_data

    def test_render_jinja(self):
        blob = """## template:jinja
{{a}},{{b}}"""
        c = templater.render_string(blob, {"a": 1, "b": 2})
        assert "1,2" == c

    def test_render_default(self):
        blob = """$a,$b"""
        c = templater.render_string(blob, {"a": 1, "b": 2})
        assert "1,2" == c

    def test_render_basic_deeper(self):
        hn = "myfoohost.yahoo.com"
        expected_data = "h=%s\nc=d\n" % hn
        in_data = "h=$hostname.canonical_name\nc=d\n"
        params = {
            "hostname": {
                "canonical_name": hn,
            },
        }
        out_data = templater.render_string(in_data, params)
        assert expected_data == out_data

    def test_render_basic_no_parens(self):
        hn = "myfoohost"
        in_data = "h=$hostname\nc=d\n"
        expected_data = "h=%s\nc=d\n" % hn
        out_data = templater.basic_render(in_data, {"hostname": hn})
        assert expected_data == out_data

    def test_render_basic_parens(self):
        hn = "myfoohost"
        in_data = "h = ${hostname}\nc=d\n"
        expected_data = "h = %s\nc=d\n" % hn
        out_data = templater.basic_render(in_data, {"hostname": hn})
        assert expected_data == out_data

    def test_render_basic2(self):
        mirror = "mymirror"
        codename = "zany"
        in_data = "deb $mirror $codename-updates main contrib non-free"
        ex_data = "deb %s %s-updates main contrib non-free" % (
            mirror,
            codename,
        )

        out_data = templater.basic_render(
            in_data, {"mirror": mirror, "codename": codename}
        )
        assert ex_data == out_data

    def test_jinja_nonascii_render_to_string(self):
        """Test jinja render_to_string with non-ascii content."""
        assert (
            templater.render_string(
                self.add_header("jinja", self.jinja_utf8), {"name": "bob"}
            )
            == self.jinja_utf8_rbob
        )

    def test_jinja_nonascii_render_undefined_variables_to_default_py3(self):
        """Test py3 jinja render_to_string with undefined variable default."""
        assert templater.render_string(
            self.add_header("jinja", self.jinja_utf8), {}
        ) == self.jinja_utf8_rbob.replace("bob", "CI_MISSING_JINJA_VAR/name")

    def test_jinja_nonascii_render_to_file(self, tmp_path):
        """Test jinja render_to_file of a filename with non-ascii content."""
        tmpl_fn = str(tmp_path / "j-render-to-file.template")
        out_fn = str(tmp_path / "j-render-to-file.out")
        write_file(
            filename=tmpl_fn,
            omode="wb",
            content=self.add_header("jinja", self.jinja_utf8).encode("utf-8"),
        )
        templater.render_to_file(tmpl_fn, out_fn, {"name": "bob"})
        result = load_binary_file(out_fn).decode("utf-8")
        assert result == self.jinja_utf8_rbob

    def test_jinja_nonascii_render_from_file(self, tmp_path):
        """Test jinja render_from_file with non-ascii content."""
        tmpl_fn = str(tmp_path / "j-render-from-file.template")
        write_file(
            tmpl_fn,
            omode="wb",
            content=self.add_header("jinja", self.jinja_utf8).encode("utf-8"),
        )
        result = templater.render_from_file(tmpl_fn, {"name": "bob"})
        assert result == self.jinja_utf8_rbob

    @test_helpers.skipIfJinja()
    def test_jinja_warns_on_missing_dep_and_uses_basic_renderer(
        self, caplog, tmp_path
    ):
        """Test jinja render_from_file will fallback to basic renderer."""
        tmpl_fn = tmp_path("j-render-from-file.template")
        write_file(
            tmpl_fn,
            omode="wb",
            content=self.add_header("jinja", self.jinja_utf8).encode("utf-8"),
        )
        result = templater.render_from_file(tmpl_fn, {"name": "bob"})
        assert result == self.jinja_utf8.decode()
        assert (
            mock.ANY,
            logging.WARNING,
            "Jinja not available as the selected renderer for desired"
            " template, reverting to the basic renderer.",
        ) in caplog.record_tuples

    def test_jinja_do_extension_render_to_string(self):
        """Test jinja render_to_string using do extension."""
        expected_result = "[1, 2, 3]"
        jinja_template = (
            "{% set r = [] %} {% set input = [1,2,3] %} "
            "{% for i in input %} {% do r.append(i) %} {% endfor %} {{r}}"
        )
        assert (
            templater.render_string(
                self.add_header("jinja", jinja_template), {}
            ).strip()
            == expected_result
        )


class TestJinjaSyntaxParsingException:
    def test_jinja_syntax_parsing_exception_message(self):
        """
        Test that the message of the JinjaSyntaxParsingException is written and
        formatted as expected, and that the template is filled in correctly.
        """
        jinja_template = (
            "## template: jinja\n"
            "#cloud-config\n"
            "runcmd:\n"
            "{% if 1 == 1 % }\n"
            '  - echo "1 is equal to 1"\n'
            "{% endif %}\n"
        )
        expected_error_msg = (
            "Unable to parse Jinja template due to syntax error: "
            "unexpected '}' on line 4: {% if 1 == 1 % }"
        )
        with pytest.raises(JinjaSyntaxParsingException) as excinfo:
            templater.render_string(jinja_template, {})
        assert str(excinfo.value) == expected_error_msg

    @pytest.mark.parametrize(
        "line_no,replace_tuple,syntax_error",
        (
            (
                4,
                ("%}", "% }"),
                "unexpected '}'",
            ),
            (
                6,
                ("%}", "% }"),
                "expected token 'end of statement block', got '%'",
            ),
            (
                8,
                ("%}", "% }"),
                "expected token 'end of statement block', got '%'",
            ),
            (
                4,
                ("%}", "}}"),
                "unexpected '}'",
            ),
            (
                6,
                ("%}", "}}"),
                "unexpected '}'",
            ),
            (
                8,
                ("%}", "}}"),
                "unexpected '}'",
            ),
            (
                4,
                ("==", "="),
                "expected token 'end of statement block', got '='",
            ),
            (
                7,
                ("}}", "} }"),
                "unexpected '}'",
            ),
        ),
    )
    def test_functionality_for_various_syntax_errors(
        self, line_no, replace_tuple, syntax_error
    ):
        """
        Test a variety of jinja syntax errors and make sure the exceptions
        are raised with the correct syntax error, line number, and line content
        as expected.
        """
        jinja_template = (
            "## template: jinja\n"
            "#cloud-config\n"
            "runcmd:\n"
            '{% if v1.cloud_name == "unknown" %}\n'
            '  - echo "Cloud name is unknown"\n'
            "{% else %}\n"
            '  - echo "Cloud name is known: {{ v1.cloud_name }}"\n'
            "{% endif %}\n"
        )
        # replace "%}" in line_no with "% }"
        jinja_template = jinja_template.replace(
            jinja_template.split("\n")[line_no - 1],
            jinja_template.split("\n")[line_no - 1].replace(*replace_tuple),
        )

        with pytest.raises(JinjaSyntaxParsingException) as excinfo:
            templater.render_string(jinja_template, {})
        error: JinjaSyntaxParsingException = excinfo.value
        assert error.lineno == line_no
        assert error.message == syntax_error
        assert (
            error.source.splitlines()[line_no - 2]  # -2 because of header
            == jinja_template.splitlines()[line_no - 1]
        )

    def test_format_error_message_with_content_line(self):
        expected_error_msg = (
            "Unable to parse Jinja template due to syntax error: "
            "unexpected '}' on line 4: {% if 1 == 1 % }"
        )
        error_msg = JinjaSyntaxParsingException.format_error_message(
            syntax_error="unexpected '}'",
            line_number=4,
            line_content="{% if 1 == 1 % }",
        )
        assert error_msg == expected_error_msg

    @pytest.mark.parametrize(
        "line_content",
        (
            "",
            None,
        ),
    )
    def test_format_error_message_without_content_line(self, line_content):
        expected_error_msg = (
            "Unable to parse Jinja template due to syntax error: "
            "unexpected '}' on line 4"
        )
        error_msg = JinjaSyntaxParsingException.format_error_message(
            syntax_error="unexpected '}'",
            line_number=4,
            line_content=line_content,
        )
        assert error_msg == expected_error_msg