Debian Codegraph @

tests/test_render.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
•1 # -*- coding: utf-8 -*-
2
3 from __future__ import unicode_literals
4
5 import unittest
6 import os, sys, io, os.path, tempfile
7 from copy import copy
8 from contextlib import contextmanager
9 from jinja2.exceptions import UndefinedError
10
11 from j2cli.cli import render_command
12
13 @contextmanager
14 def mktemp(contents):
15 """ Create a temporary file with the given contents, and yield its path """
16 _, path = tempfile.mkstemp()
17 fp = io.open(path, 'wt+', encoding='utf-8')
18 fp.write(contents)
19 fp.flush()
20 try:
21 yield path
22 finally:
23 fp.close()
24 os.unlink(path)
25
26
27 @contextmanager
28 def mock_environ(new_env):
29 old_env = copy(os.environ)
30 os.environ.update(new_env)
31 yield
32 os.environ.clear()
33 os.environ.update(old_env)
34
35
36 class RenderTest(unittest.TestCase):
37 def setUp(self):
38 os.chdir(
39 os.path.dirname(__file__)
40 )
41
42 def _testme(self, argv, expected_output, stdin=None, env=None):
43 """ Helper test shortcut """
44 with mock_environ(env or {}):
45 result = render_command(os.getcwd(), env or {}, stdin, argv)
46 if isinstance(result, bytes):
47 result = result.decode('utf-8')
48 self.assertEqual(result, expected_output)
49
50 #: The expected output
51 expected_output = """server {
52 listen 80;
53 server_name localhost;
54
55 root /var/www/project;
56 index index.htm;
57
58 access_log /var/log/nginx//http.access.log combined;
59 error_log /var/log/nginx//http.error.log;
60 }
61 """
62
63 def _testme_std(self, argv, stdin=None, env=None):
64 self._testme(argv, self.expected_output, stdin, env)
65
66 def test_ini(self):
67 # Filename
68 self._testme_std(['resources/nginx.j2', 'resources/data.ini'])
69 # Format
70 self._testme_std(['--format=ini', 'resources/nginx.j2', 'resources/data.ini'])
71 # Stdin
72 self._testme_std(['--format=ini', 'resources/nginx.j2'], stdin=open('resources/data.ini'))
73 self._testme_std(['--format=ini', 'resources/nginx.j2', '-'], stdin=open('resources/data.ini'))
74
75 def test_json(self):
76 # Filename
77 self._testme_std(['resources/nginx.j2', 'resources/data.json'])
78 # Format
79 self._testme_std(['--format=json', 'resources/nginx.j2', 'resources/data.json'])
80 # Stdin
81 self._testme_std(['--format=json', 'resources/nginx.j2'], stdin=open('resources/data.json'))
82 self._testme_std(['--format=json', 'resources/nginx.j2', '-'], stdin=open('resources/data.json'))
83
84 def test_yaml(self):
85 try:
86 import yaml
87 except ImportError:
88 raise unittest.SkipTest('Yaml lib not installed')
89
90 # Filename
91 self._testme_std(['resources/nginx.j2', 'resources/data.yml'])
92 self._testme_std(['resources/nginx.j2', 'resources/data.yaml'])
93 # Format
94 self._testme_std(['--format=yaml', 'resources/nginx.j2', 'resources/data.yml'])
95 # Stdin
96 self._testme_std(['--format=yaml', 'resources/nginx.j2'], stdin=open('resources/data.yml'))
97 self._testme_std(['--format=yaml', 'resources/nginx.j2', '-'], stdin=open('resources/data.yml'))
98
99 def test_env(self):
100 # Filename
101 self._testme_std(['--format=env', 'resources/nginx-env.j2', 'resources/data.env'])
102 self._testme_std([ 'resources/nginx-env.j2', 'resources/data.env'])
103 # Format
104 self._testme_std(['--format=env', 'resources/nginx-env.j2', 'resources/data.env'])
105 self._testme_std([ 'resources/nginx-env.j2', 'resources/data.env'])
106 # Stdin
107 self._testme_std(['--format=env', 'resources/nginx-env.j2', '-'], stdin=open('resources/data.env'))
108 self._testme_std([ 'resources/nginx-env.j2', '-'], stdin=open('resources/data.env'))
109
110 # Environment!
111 # In this case, it's not explicitly provided, but implicitly gotten from the environment
112 env = dict(NGINX_HOSTNAME='localhost', NGINX_WEBROOT='/var/www/project', NGINX_LOGS='/var/log/nginx/')
113 self._testme_std(['--format=env', 'resources/nginx-env.j2'], env=env)
114 self._testme_std([ 'resources/nginx-env.j2'], env=env)
115
116 def test_import_env(self):
117 # Import environment into a variable
118 with mktemp('{{ a }}/{{ env.B }}') as template:
119 with mktemp('{"a":1}') as context:
120 self._testme(['--format=json', '--import-env=env', template, context], '1/2', env=dict(B='2'))
121 # Import environment into global scope
122 with mktemp('{{ a }}/{{ B }}') as template:
123 with mktemp('{"a":1,"B":1}') as context:
124 self._testme(['--format=json', '--import-env=', template, context], '1/2', env=dict(B='2'))
125
126 def test_env_file__equals_sign_in_value(self):
127 # Test whether environment variables with "=" in the value are parsed correctly
128 with mktemp('{{ A|default('') }}/{{ B }}/{{ C }}') as template:
129 with mktemp('A\nB=1\nC=val=1\n') as context:
130 self._testme(['--format=env', template, context], '/1/val=1')
131
132 def test_unicode(self):
133 # Test how unicode is handled
134 # I'm using Russian language for unicode :)
135 with mktemp('Проверка {{ a }} связи!') as template:
136 with mktemp('{"a": "широкополосной"}') as context:
137 self._testme(['--format=json', template, context], 'Проверка широкополосной связи!')
138
139 # Test case from issue #17: unicode environment variables
140 if sys.version_info[0] == 2:
141 # Python 2: environment variables are bytes
142 self._testme(['resources/name.j2'], u'Hello Jürgen!\n', env=dict(name=b'J\xc3\xbcrgen'))
143 else:
144 # Python 3: environment variables are unicode strings
145 self._testme(['resources/name.j2'], u'Hello Jürgen!\n', env=dict(name=u'Jürgen'))
146
147 def test_filters__env(self):
148 with mktemp('user_login: kolypto') as yml_file:
149 with mktemp('{{ user_login }}:{{ "USER_PASS"|env }}') as template:
150 # Test: template with an env variable
151 self._testme(['--format=yaml', template, yml_file], 'kolypto:qwerty123', env=dict(USER_PASS='qwerty123'))
152
153 # environment cleaned up
154 assert 'USER_PASS' not in os.environ
155
156 # Test: KeyError
157 with self.assertRaises(KeyError):
158 self._testme(['--format=yaml', template, yml_file], 'kolypto:qwerty123', env=dict())
159
160 # Test: default
161 with mktemp('{{ user_login }}:{{ "USER_PASS"|env("-none-") }}') as template:
162 self._testme(['--format=yaml', template, yml_file], 'kolypto:-none-', env=dict())
163
164 # Test: using as a function
165 with mktemp('{{ user_login }}:{{ env("USER_PASS") }}') as template:
166 self._testme(['--format=yaml', template, yml_file], 'kolypto:qwerty123', env=dict(USER_PASS='qwerty123'))
167
168 with self.assertRaises(KeyError):
169 # Variable not set
170 self._testme(['--format=yaml', template, yml_file], '', env=dict())
171
172 # Test: using as a function, with a default
173 with mktemp('{{ user_login }}:{{ env("USER_PASS", "-none-") }}') as template:
174 self._testme(['--format=yaml', template, yml_file], 'kolypto:qwerty123', env=dict(USER_PASS='qwerty123'))
175 self._testme(['--format=yaml', template, yml_file], 'kolypto:-none-', env=dict())
176
177
178 def test_custom_filters(self):
179 with mktemp('{{ a|parentheses }}') as template:
180 self._testme(['--format=env', '--filters=resources/custom_filters.py', template], '(1)', env=dict(a='1'))
181
182 def test_custom_tests(self):
183 with mktemp('{% if a|int is custom_odd %}odd{% endif %}') as template:
184 self._testme(['--format=env', '--tests=resources/custom_tests.py', template], 'odd', env=dict(a='1'))
185
186 def test_output_file(self):
187 with mktemp('{{ a }}') as template:
188 try:
189 self._testme(['-o', '/tmp/j2-out', template], '', env=dict(a='123'))
190 self.assertEqual('123', io.open('/tmp/j2-out', 'r').read())
191 finally:
192 os.unlink('/tmp/j2-out')
193
194 def test_undefined(self):
195 """ Test --undefined """
196 # `name` undefined: error
197 self.assertRaises(UndefinedError, self._testme, ['resources/name.j2'], u'Hello !\n', env=dict())
198 # `name` undefined: no error
199 self._testme(['--undefined', 'resources/name.j2'], u'Hello !\n', env=dict())
200
201 def test_jinja2_extensions(self):
202 """ Test that an extension is enabled """
203 with mktemp('{% do [] %}') as template:
204 # `do` tag is an extension
205 self._testme([template], '')
206
207
208 def test_customize(self):
209 """ Test --customize """
210 # Test: j2_environment_params()
211 # Custom tag start/end
212 with mktemp('<% if 1 %>1<% else %>2<% endif %>') as template:
213 self._testme(['--customize=resources/customize.py', template], '1')
214
215 # Test: j2_environment()
216 # custom function: my_function
217 with mktemp('<< my_function("hey") >>') as template:
218 self._testme(['--customize=resources/customize.py', template], 'my function says "hey"')
219
220 # Test: alter_context()
221 # Extra variable: ADD=127
222 with mktemp('<< ADD >>') as template:
223 self._testme(['--customize=resources/customize.py', template], '127')
224
225 # Test: extra_filters()
226 with mktemp('<< ADD|parentheses >>') as template:
227 self._testme(['--customize=resources/customize.py', template], '(127)')
228
229 # Test: extra_tests()
230 with mktemp('<% if ADD|int is custom_odd %>odd<% endif %>') as template:
231 self._testme(['--customize=resources/customize.py', template], 'odd')
232
233 # reset
234 # otherwise it will load the same module even though its name has changed
235 del sys.modules['customize-module']
236
237 # Test: no hooks in a file
238 # Got to restore to the original configuration and use {% %} again
239 with mktemp('{% if 1 %}1{% endif %}') as template:
240 self._testme(['--customize=test_render.py', template], '1')