Source

wheezy.template / src / wheezy / template / ext / tests / test_core.py

  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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545

""" Unit tests for ``wheezy.templates.ext.core``.
"""

import unittest


class CleanSourceTestCase(unittest.TestCase):
    """ Test the ``clean_source``.
    """

    def setUp(self):
        from wheezy.template.ext.core import CoreExtension
        self.clean_source = CoreExtension().preprocessors[0]

    def test_new_line(self):
        """ Replace windows new line with linux new line.
        """
        assert 'a\nb' == self.clean_source('a\r\nb')

    def test_clean_leading_whitespace(self):
        """ Remove leading whitespace before @<stmt>, e.g. @if, @for, etc.
        """
        from wheezy.template.ext.core import all_tokens
        for token in all_tokens:
            assert '@' + token == self.clean_source('  @' + token)
            assert '\n@' + token == self.clean_source('\n  @' + token)
            assert 'a\n@' + token == self.clean_source('a\n  @' + token)

    def test_leave_leading_whitespace(self):
        """ Leave leading whitespace before @<var> tokens.
        """
        assert 'a\n\n   @b' == self.clean_source('a\n\n   @b')
        assert 'a\n @b' == self.clean_source('a\n @b')
        assert 'a\n@b' == self.clean_source('a\n@b')
        assert 'a@b' == self.clean_source('a@b')
        assert '  @b' == self.clean_source('  @b')

    def test_ignore(self):
        """ Ignore double @.
        """
        assert 'a\n  @@b' == self.clean_source('a\n  @@b')
        assert '  @@b' == self.clean_source('  @@b')


class LexerTestCase(unittest.TestCase):
    """ Test the ``CoreExtension`` lexers.
    """

    def setUp(self):
        from wheezy.template.engine import Engine
        from wheezy.template.ext.core import CoreExtension
        from wheezy.template.loader import DictLoader
        self.engine = Engine(
            loader=DictLoader({}),
            extensions=[CoreExtension()])

    def tokenize(self, source):
        return self.engine.lexer.tokenize(source)

    def test_stmt_token(self):
        """ Test statement token.
        """
        tokens = self.tokenize('@require(title, users)\n')
        assert (1, 'require', 'require(title, users)') == tokens[0]

    def test_comment_token(self):
        """ Test statement token.
        """
        tokens = self.tokenize('@#ignore\\\n@end\n')
        assert (1, '#', '#ignore@end') == tokens[0]

    def test_var_token(self):
        """ Test variable token.
        """
        tokens = self.tokenize('@user.name ')
        assert (1, 'var', 'user.name') == tokens[0]
        tokens = self.tokenize('@user.pref[i].fmt() ')
        assert (1, 'var', 'user.pref[i].fmt()') == tokens[0]

    def test_var_token_filter(self):
        """ Test variable token filter.
        """
        tokens = self.tokenize('@user.age!s')
        assert (1, 'var', 'user.age!!s') == tokens[0]
        tokens = self.tokenize('@user.age!s!h')
        assert (1, 'var', 'user.age!!s!h') == tokens[0]
        # escape or ignore !
        tokens = self.tokenize('@user.age!s!')
        assert (1, 'var', 'user.age!!s') == tokens[0]
        tokens = self.tokenize('@user.age!!s')
        assert (1, 'var', 'user.age') == tokens[0]
        tokens = self.tokenize('@user! ')
        assert (1, 'var', 'user') == tokens[0]

    def test_markup_token(self):
        """ Test markup token.
        """
        tokens = self.tokenize(' test ')
        assert 1 == len(tokens)
        assert (1, 'markup', ' test ') == tokens[0]
        tokens = self.tokenize('x@n')
        assert (1, 'markup', 'x') == tokens[0]

    def test_markup_token_escape(self):
        """ Test markup token with escape.
        """
        tokens = self.tokenize('support@@acme.org')
        assert 1 == len(tokens)
        assert (1, 'markup', 'support@acme.org') == tokens[0]


class ParserTestCase(unittest.TestCase):
    """ Test the ``CoreExtension`` parsers.
    """

    def setUp(self):
        from wheezy.template.engine import Engine
        from wheezy.template.ext.core import CoreExtension
        from wheezy.template.loader import DictLoader
        self.engine = Engine(
            loader=DictLoader({}),
            extensions=[CoreExtension()])

    def parse(self, source):
        return list(self.engine.parser.parse(
            self.engine.lexer.tokenize(source)))

    def test_require(self):
        """ Test parse_require.
        """
        nodes = self.parse('@require(title, users)\n')
        assert [(1, 'require', ['title', 'users'])] == nodes

    def test_extends(self):
        """ Test parse_extends.
        """
        nodes = self.parse('@extends("shared/master.html")\n')
        assert [(1, 'extends', ('"shared/master.html"', []))] == nodes

    def test_include(self):
        """ Test parse_include.
        """
        nodes = self.parse('@include("shared/scripts.html")\n')
        assert [(1, 'out', [
            (1, 'include', '"shared/scripts.html"')
        ])] == nodes

    def test_markup(self):
        """ Test parse_markup.
        """
        nodes = self.parse("""
 Welcome, @name!
""")
        assert [(1, 'out', [
            (1, 'markup', "'\\n Welcome, '"),
            (2, 'var', ('name', None)),
            (2, 'markup', "'!\\n'")
        ])] == nodes

    def test_var(self):
        """ Test parse_markup.
        """
        nodes = self.parse("""@name!h!""")
        assert [(1, 'out', [
            (1, 'var', ('name', ['h'])),
            (1, 'markup', "'!'")
        ])] == nodes
        nodes = self.parse("""@name!s!h!""")
        assert [(1, 'out', [
            (1, 'var', ('name', ['s', 'h'])),
            (1, 'markup', "'!'")
        ])] == nodes


class BuilderTestCase(unittest.TestCase):
    """ Test the ``CoreExtension`` generators.
    """

    def setUp(self):
        from wheezy.template.engine import Engine
        from wheezy.template.ext.core import CoreExtension
        from wheezy.template.loader import DictLoader
        self.engine = Engine(
            loader=DictLoader({}),
            extensions=[CoreExtension()])

    def build_source(self, source):
        nodes = list(self.engine.parser.parse(
            self.engine.lexer.tokenize(source)))
        return self.engine.builder.build_source(nodes)

    def build_render(self, source):
        nodes = list(self.engine.parser.parse(
            self.engine.lexer.tokenize(source)))
        return self.engine.builder.build_render(nodes)

    def build_extends(self, name, source):
        nodes = list(self.engine.parser.parse(
            self.engine.lexer.tokenize(source)))
        return self.engine.builder.build_extends(name, nodes)

    def test_markup(self):
        assert "w('Hello')" == self.build_source('Hello')

    def test_comment(self):
        assert """\
w('Hello')
# comment
w(' World')""" == self.build_source("""\
Hello\\
@# comment
 World""")

    def test_require(self):
        assert """\
title = ctx['title']; username = ctx['username']
w(username)""" == self.build_source("""\
@require(title, username)
@username""")

    def test_out(self):
        """ Test build_out.
        """
        assert "w('Welcome, '); w(username); w('!')" == self.build_source(
            'Welcome, @username!')
        assert """\
w('\\n<i>\\n    ')

w(username); w('\\n</i>')""" == self.build_source("""
<i>
    @username
</i>""")

    def test_if(self):
        """ Test if elif else statements.
        """
        assert """\
if n > 0:
    w('    Positive\\n')
elif n == 0:
    w('    Zero\\n')
else:
    w('    Negative\\n')""" == self.build_source("""\
@if n > 0:
    Positive
@elif n == 0:
    Zero
@else:
    Negative
@end
""")

    def test_for(self):
        assert """\
for color in colors:
    w('    '); w(color); w('\\n')""" == self.build_source("""\
@for color in colors:
    @color
@end
""")

    def test_def(self):
        """ Test def statement.
        """
        assert """\
def link(url, text):
    _b = []; w = _b.append; w('        <a href="'); w(url); \
w('">'); w(text); w('</a>\\n')
    return ''.join(_b)
super_defs['link'] = link; link = local_defs.setdefault('link', link)
w('    Please '); w(link('/en/signin', 'sign in')); w('.\\n')\
""" == self.build_source("""\
    @def link(url, text):
        <a href="@url">@text</a>
        @#ignore
    @end
    Please @link('/en/signin', 'sign in').
""")

    def test_def_empty(self):
        """ Test def statement.
        """
        assert """\
def title():return ''
super_defs['title'] = title; title = local_defs.setdefault('title', title)
w(title()); w('.')""" == self.build_source("""\
@def title():
@end
@title().""")

    def test_render(self):
        """ Test build_render.
        """
        assert """\
def render(ctx, local_defs, super_defs):

    return 'Hello'""" == self.build_render("Hello")

    def test_extends(self):
        """ Test build_extends.
        """
        assert """\
def render(ctx, local_defs, super_defs):
    return _r("base.html", ctx, local_defs, super_defs)\
""" == self.build_render("""\
@extends("base.html")
""")


class TemplateTestCase(unittest.TestCase):
    """ Test the ``CoreExtension`` compiled templates.
    """

    def setUp(self):
        from wheezy.template.engine import Engine
        from wheezy.template.ext.core import CoreExtension
        from wheezy.template.loader import DictLoader
        self.templates = {}
        self.engine = Engine(
            loader=DictLoader(templates=self.templates),
            extensions=[CoreExtension()])

    def render(self, ctx, source):
        self.templates['test.html'] = source
        template = self.engine.get_template('test.html')
        return template.render(ctx)

    def test_markup(self):
        ctx = {}
        assert 'Hello' == self.render(ctx, 'Hello')

    def test_comment(self):
        assert 'Hello World' == self.render({}, """\
Hello\\
@# comment
 World""")

    def test_var(self):
        ctx = {
            'username': 'John'
        }
        assert 'Welcome, John!' == self.render(ctx, """\
@require(username)
Welcome, @username!""")

    def test_if(self):
        template = """\
@require(n)
@if n > 0:
    Positive\\
@elif n == 0:
    Zero\\
@else:
    Negative\\
@end
"""
        assert '    Positive' == self.render({'n': 1}, template)
        assert '    Zero' == self.render({'n': 0}, template)
        assert '    Negative' == self.render({'n': -1}, template)

    def test_for(self):
        ctx = {
            'colors': ['red', 'yellow']
        }
        assert '    red\n    yellow\n' == self.render(ctx, """\
@require(colors)
@for color in colors:
    @color
@end
""")

    def test_def(self):
        assert 'Welcome, John!' == self.render({}, """\
@def welcome(name):
Welcome, @name!\\
@end
@welcome('John')""")

    def test_def_empty(self):
        assert '.' == self.render({}, """\
@def title():
@end
@title().""")

    def test_def_syntax_error_compound(self):
        self.assertRaises(SyntaxError, lambda: self.render({}, """\
@def welcome(name):
@if name:
Welcome, @name!\\
@end
@end
@welcome('John')"""))

    def test_def_no_syntax_error(self):
        assert 'Welcome, John!' == self.render({}, """\
@def welcome(name):
@#ignore
@if name:
Welcome, @name!\\
@end
@end
@welcome('John')""")


class MultiTemplateTestCase(unittest.TestCase):
    """ Test the ``CoreExtension`` compiled templates.
    """

    def setUp(self):
        from wheezy.template.engine import Engine
        from wheezy.template.ext.core import CoreExtension
        from wheezy.template.loader import DictLoader
        self.templates = {}
        self.engine = Engine(
            loader=DictLoader(templates=self.templates),
            extensions=[CoreExtension()])

    def render(self, name, ctx):
        template = self.engine.get_template(name)
        return template.render(ctx)

    def test_extends(self):
        self.templates.update({
            'master.html': """\
@def say_hi(name):
    Hello, @name!
@end
@say_hi('John')""",

            'tmpl.html': """\
@extends('master.html')
@def say_hi(name):
    Hi, @name!
@end
"""
        })
        assert '    Hi, John!\n' == self.render('tmpl.html', {})
        assert '    Hello, John!\n' == self.render('master.html', {})

    def test_super(self):
        self.templates.update({
            'master.html': """\
@def say_hi(name):
    Hello, @name!\
@end
@say_hi('John')""",

            'tmpl.html': """\
@extends('master.html')
@def say_hi(name):
    @super_defs['say_hi'](name)!!\
@end
"""
        })
        assert '        Hello, John!!!' == self.render('tmpl.html', {})

    def test_include(self):
        self.templates.update({
            'footer.html': """\
@require(name)
Thanks, @name""",

            'tmpl.html': """\
Welcome to my site.
@include('footer.html')
"""
        })
        ctx = {'name': 'John'}
        assert """\
Welcome to my site.
Thanks, John""" == self.render('tmpl.html', ctx)
        assert 'Thanks, John' == self.render('footer.html', ctx)

    def test_import(self):
        self.templates.update({
            'helpers.html': """\
@def say_hi(name):
Hi, @name\
@end""",

            'tmpl.html': """\
@import 'helpers.html' as helpers
@helpers.say_hi('John')"""
        })
        assert """\
Hi, John""" == self.render('tmpl.html', {})

    def test_import_dynamic(self):
        self.templates.update({
            'helpers.html': """\
@def say_hi(name):
Hi, @name\
@end""",

            'tmpl.html': """\
@require(helpers_impl)
@import helpers_impl as helpers
@helpers.say_hi('John')"""
        })
        assert """\
Hi, John""" == self.render('tmpl.html', {'helpers_impl': 'helpers.html'})

    def test_from_import(self):
        self.templates.update({
            'helpers.html': """\
@def say_hi(name):
Hi, @name\
@end""",

            'tmpl.html': """\
@from 'helpers.html' import say_hi
@say_hi('John')"""
        })
        assert """\
Hi, John""" == self.render('tmpl.html', {})

    def test_from_import_dynamic(self):
        self.templates.update({
            'helpers.html': """\
@def say_hi(name):
Hi, @name\
@end""",

            'tmpl.html': """\
@require(helpers_impl)
@from helpers_impl import say_hi
@say_hi('John')"""
        })
        assert """\
Hi, John""" == self.render('tmpl.html', {'helpers_impl': 'helpers.html'})

    def test_from_import_as(self):
        self.templates.update({
            'share/helpers.html': """\
@def say_hi(name):
Hi, @name\
@end""",

            'tmpl.html': """\
@from 'share/helpers.html' import say_hi as hi
@hi('John')"""
        })
        assert """\
Hi, John""" == self.render('tmpl.html', {})