File: test_filters.py

package info (click to toggle)
mako 1.0.6%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 1,556 kB
  • ctags: 1,495
  • sloc: python: 11,807; makefile: 167
file content (390 lines) | stat: -rw-r--r-- 10,863 bytes parent folder | download | duplicates (3)
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
# -*- coding: utf-8 -*-

from mako.template import Template
import unittest
from test import TemplateTest, eq_, requires_python_2
from test.util import result_lines, flatten_result
from mako.compat import u
from mako import compat

class FilterTest(TemplateTest):
    def test_basic(self):
        t = Template("""
        ${x | myfilter}
""")
        assert flatten_result(t.render(x="this is x", myfilter=lambda t: "MYFILTER->%s<-MYFILTER" % t)) == "MYFILTER->this is x<-MYFILTER"

    def test_expr(self):
        """test filters that are themselves expressions"""
        t = Template("""
        ${x | myfilter(y)}
""")
        def myfilter(y):
            return lambda x: "MYFILTER->%s<-%s" % (x, y)
        assert flatten_result(t.render(x="this is x", myfilter=myfilter, y="this is y")) == "MYFILTER->this is x<-this is y"

    def test_convert_str(self):
        """test that string conversion happens in expressions before sending to filters"""
        t = Template("""
            ${x | trim}
        """)
        assert flatten_result(t.render(x=5)) == "5"

    def test_quoting(self):
        t = Template("""
            foo ${bar | h}
        """)

        eq_(
            flatten_result(t.render(bar="<'some bar'>")),
            "foo &lt;&#39;some bar&#39;&gt;"
        )

    def test_url_escaping(self):
        t = Template("""
            http://example.com/?bar=${bar | u}&v=1
        """)

        eq_(
            flatten_result(t.render(bar=u"酒吧bar")),
            "http://example.com/?bar=%E9%85%92%E5%90%A7bar&v=1"
        )

    def test_entity(self):
        t = Template("foo ${bar | entity}")
        eq_(
            flatten_result(t.render(bar="<'some bar'>")),
            "foo &lt;'some bar'&gt;"
        )

    @requires_python_2
    def test_quoting_non_unicode(self):
        t = Template("""
            foo ${bar | h}
        """, disable_unicode=True,
        output_encoding=None)

        eq_(
            flatten_result(t.render(bar="<'привет'>")),
            "foo &lt;&#39;привет&#39;&gt;"
        )

    @requires_python_2
    def test_url_escaping_non_unicode(self):
        t = Template("""
            http://example.com/?bar=${bar | u}&v=1
        """, disable_unicode=True,
        output_encoding=None)

        eq_(
            flatten_result(t.render(bar="酒吧bar")),
            "http://example.com/?bar=%E9%85%92%E5%90%A7bar&v=1"
        )


    def test_def(self):
        t = Template("""
            <%def name="foo()" filter="myfilter">
                this is foo
            </%def>
            ${foo()}
""")

        eq_(
            flatten_result(t.render(x="this is x",
                        myfilter=lambda t: "MYFILTER->%s<-MYFILTER" % t)),
            "MYFILTER-> this is foo <-MYFILTER"
        )

    def test_import(self):
        t = Template("""
        <%!
            from mako import filters
        %>\
        trim this string: ${"  some string to trim   " | filters.trim} continue\
        """)

        assert t.render().strip()=="trim this string: some string to trim continue"

    def test_import_2(self):
        t = Template("""
        trim this string: ${"  some string to trim   " | filters.trim} continue\
        """, imports=["from mako import filters"])
        #print t.code
        assert t.render().strip()=="trim this string: some string to trim continue"

    def test_encode_filter(self):
        t = Template("""# coding: utf-8
            some stuff.... ${x}
        """, default_filters=['decode.utf8'])
        eq_(
            t.render_unicode(x=u("voix m’a réveillé")).strip(),
            u("some stuff.... voix m’a réveillé")
        )

    def test_encode_filter_non_str(self):
        t = Template("""# coding: utf-8
            some stuff.... ${x}
        """, default_filters=['decode.utf8'])
        eq_(
            t.render_unicode(x=3).strip(),
            u("some stuff.... 3")
        )

    @requires_python_2
    def test_encode_filter_non_str_we_return_bytes(self):
        class Foo(object):
            def __str__(self):
                return compat.b("å")
        t = Template("""# coding: utf-8
            some stuff.... ${x}
        """, default_filters=['decode.utf8'])
        eq_(
            t.render_unicode(x=Foo()).strip(),
            u("some stuff.... å")
        )

    def test_custom_default(self):
        t = Template("""
        <%!
            def myfilter(x):
                return "->" + x + "<-"
        %>

            hi ${'there'}
        """, default_filters=['myfilter'])
        assert t.render().strip()=="hi ->there<-"

    def test_global(self):
        t = Template("""
            <%page expression_filter="h"/>
            ${"<tag>this is html</tag>"}
        """)
        assert t.render().strip()  == "&lt;tag&gt;this is html&lt;/tag&gt;"

    def test_block_via_context(self):
        t = Template("""
            <%block name="foo" filter="myfilter">
                some text
            </%block>
        """)
        def myfilter(text):
            return "MYTEXT" + text
        eq_(
            result_lines(t.render(myfilter=myfilter)),
            ["MYTEXT", "some text"]
        )

    def test_def_via_context(self):
        t = Template("""
            <%def name="foo()" filter="myfilter">
                some text
            </%def>
            ${foo()}
        """)
        def myfilter(text):
            return "MYTEXT" + text
        eq_(
            result_lines(t.render(myfilter=myfilter)),
            ["MYTEXT", "some text"]
        )

    def test_text_via_context(self):
        t = Template("""
            <%text filter="myfilter">
                some text
            </%text>
        """)
        def myfilter(text):
            return "MYTEXT" + text
        eq_(
            result_lines(t.render(myfilter=myfilter)),
            ["MYTEXT", "some text"]
        )


    def test_nflag(self):
        t = Template("""
            ${"<tag>this is html</tag>" | n}
        """, default_filters=['h', 'unicode'])
        assert t.render().strip()  == "<tag>this is html</tag>"

        t = Template("""
            <%page expression_filter="h"/>
            ${"<tag>this is html</tag>" | n}
        """)
        assert t.render().strip()  == "<tag>this is html</tag>"

        t = Template("""
            <%page expression_filter="h"/>
            ${"<tag>this is html</tag>" | n, h}
        """)
        assert t.render().strip()  == "&lt;tag&gt;this is html&lt;/tag&gt;"

    def test_non_expression(self):
        t = Template("""
        <%!
            def a(text):
                return "this is a"
            def b(text):
                return "this is b"
        %>

        ${foo()}
        <%def name="foo()" buffered="True">
            this is text
        </%def>
        """, buffer_filters=['a'])
        assert t.render().strip() == "this is a"

        t = Template("""
        <%!
            def a(text):
                return "this is a"
            def b(text):
                return "this is b"
        %>

        ${'hi'}
        ${foo()}
        <%def name="foo()" buffered="True">
            this is text
        </%def>
        """, buffer_filters=['a'], default_filters=['b'])
        assert flatten_result(t.render()) == "this is b this is b"

        t = Template("""
        <%!
            class Foo(object):
                foo = True
                def __str__(self):
                    return "this is a"
            def a(text):
                return Foo()
            def b(text):
                if hasattr(text, 'foo'):
                    return str(text)
                else:
                    return "this is b"
        %>

        ${'hi'}
        ${foo()}
        <%def name="foo()" buffered="True">
            this is text
        </%def>
        """, buffer_filters=['a'], default_filters=['b'])
        assert flatten_result(t.render()) == "this is b this is a"

        t = Template("""
        <%!
            def a(text):
                return "this is a"
            def b(text):
                return "this is b"
        %>

        ${foo()}
        ${bar()}
        <%def name="foo()" filter="b">
            this is text
        </%def>
        <%def name="bar()" filter="b" buffered="True">
            this is text
        </%def>
        """, buffer_filters=['a'])
        assert flatten_result(t.render()) == "this is b this is a"


    def test_builtins(self):
        t = Template("""
            ${"this is <text>" | h}
""")
        assert flatten_result(t.render()) == "this is &lt;text&gt;"

        t = Template("""
            http://foo.com/arg1=${"hi! this is a string." | u}
""")
        assert flatten_result(t.render()) == "http://foo.com/arg1=hi%21+this+is+a+string."

class BufferTest(unittest.TestCase):
    def test_buffered_def(self):
        t = Template("""
            <%def name="foo()" buffered="True">
                this is foo
            </%def>
            ${"hi->" + foo() + "<-hi"}
""")
        assert flatten_result(t.render()) == "hi-> this is foo <-hi"

    def test_unbuffered_def(self):
        t = Template("""
            <%def name="foo()" buffered="False">
                this is foo
            </%def>
            ${"hi->" + foo() + "<-hi"}
""")
        assert flatten_result(t.render()) == "this is foo hi-><-hi"

    def test_capture(self):
        t = Template("""
            <%def name="foo()" buffered="False">
                this is foo
            </%def>
            ${"hi->" + capture(foo) + "<-hi"}
""")
        assert flatten_result(t.render()) == "hi-> this is foo <-hi"

    def test_capture_exception(self):
        template = Template("""
            <%def name="a()">
                this is a
                <%
                    raise TypeError("hi")
                %>
            </%def>
            <%
                c = capture(a)
            %>
            a->${c}<-a
        """)
        try:
            template.render()
            assert False
        except TypeError:
            assert True

    def test_buffered_exception(self):
        template = Template("""
            <%def name="a()" buffered="True">
                <%
                    raise TypeError("hi")
                %>
            </%def>

            ${a()}

""")
        try:
            print(template.render())
            assert False
        except TypeError:
            assert True

    def test_capture_ccall(self):
        t = Template("""
            <%def name="foo()">
                <%
                    x = capture(caller.body)
                %>
                this is foo.  body: ${x}
            </%def>

            <%call expr="foo()">
                ccall body
            </%call>
""")

        #print t.render()
        assert flatten_result(t.render()) == "this is foo. body: ccall body"