root/livinglogic.python.xist/test/test_ul4.py @ 3530:90b34c166214

Revision 3530:90b34c166214, 30.2 KB (checked in by Walter Doerwald <walter@…>, 11 years ago)

Add a zip() function and tuple unpacking in for loops with three variables.

Line 
1#! /usr/bin/env/python
2# -*- coding: utf-8 -*-
3
4## Copyright 2008 by LivingLogic AG, Bayreuth/Germany
5## Copyright 2008 by Walter Dörwald
6##
7## All Rights Reserved
8##
9## See ll/__init__.py for the license
10
11
12import re, datetime, StringIO
13
14import py.test
15
16from ll import ul4c
17
18
19def check(result, source, templates={}, **variables):
20    # Check with template compiled from source
21    t1 = ul4c.compile(source)
22    assert result == t1.renders(templates, **variables)
23
24    # Check with template loaded again via the string interface
25    t2 = ul4c.loads(t1.dumps())
26    assert result == t2.renders(templates, **variables)
27
28    # Check with template loaded again via the stream interface
29    stream = StringIO.StringIO()
30    t1.dump(stream)
31    stream.seek(0)
32    t3 = ul4c.load(stream)
33    assert result == t3.renders(templates, **variables)
34
35
36def checkle(result, source, templates={}, **variables):
37    # Check with template compiled from source
38    t1 = ul4c.compile(source)
39    assert result <= t1.renders(templates, **variables)
40
41    # Check with template loaded again via the string interface
42    t2 = ul4c.loads(t1.dumps())
43    assert result <= t2.renders(templates, **variables)
44
45    # Check with template loaded again via the stream interface
46    stream = StringIO.StringIO()
47    t1.dump(stream)
48    stream.seek(0)
49    t3 = ul4c.load(stream)
50    assert result <= t3.renders(templates, **variables)
51
52
53def checkcompileerror(msg, source):
54    try:
55        ul4c.compile(source)
56    except Exception, exc:
57        assert re.search(msg, str(exc)) is not None
58    else:
59        py.test.fail("Didn't raise exception")
60
61
62def checkrunerror(msg, source, templates={}, **variables):
63    # Check with template compiled from source
64    t1 = ul4c.compile(source)
65    try:
66        t1.renders(templates, **variables)
67    except Exception, exc:
68        assert re.search(msg, "%s.%s: %s" % (exc.__class__.__module__, exc.__class__.__name__, exc)) is not None
69    else:
70        py.test.fail("Didn't raise exception")
71
72    # Check with template loaded again via the string interface
73    t2 = ul4c.loads(t1.dumps())
74    try:
75        t2.renders(templates, **variables)
76    except Exception, exc:
77        assert re.search(msg, "%s.%s: %s" % (exc.__class__.__module__, exc.__class__.__name__, exc)) is not None
78    else:
79        py.test.fail("Didn't raise exception")
80
81    # Check with template loaded again via the stream interface
82    stream = StringIO.StringIO()
83    t1.dump(stream)
84    stream.seek(0)
85    t3 = ul4c.load(stream)
86    try:
87        t3.renders(templates, **variables)
88    except Exception, exc:
89        assert re.search(msg, "%s.%s: %s" % (exc.__class__.__module__, exc.__class__.__name__, exc)) is not None
90    else:
91        py.test.fail("Didn't raise exception")
92
93
94def test_format():
95    tmpl = ul4c.compile("<?for (i, item) in enumerate(data)?><?print (i+1).format('>3d')?>. <?print item[0].format('.<10')?> <?print item[1]?>\n<?end for?>")
96    assert str(tmpl) == unicode(tmpl)
97
98
99def test_text():
100    check('gurk', 'gurk')
101    check(u'gurk', u'gurk')
102    check(u'g\xfcrk', u'g\xfcrk')
103
104
105def test_none():
106    check('', '<?print None?>')
107
108    check('no', '<?if None?>yes<?else?>no<?end if?>')
109
110
111def test_false():
112    check('False', '<?print False?>')
113
114    check('no', '<?if False?>yes<?else?>no<?end if?>')
115
116
117def test_true():
118    check('True', '<?print True?>')
119
120    check('yes', '<?if True?>yes<?else?>no<?end if?>')
121
122
123def test_int():
124    check('0', '<?print 0?>')
125    check('42', '<?print 42?>')
126    check('-42', '<?print -42?>')
127    check('255', '<?print 0xff?>')
128    check('255', '<?print 0Xff?>')
129    check('-255', '<?print -0xff?>')
130    check('-255', '<?print -0Xff?>')
131    check('63', '<?print 0o77?>')
132    check('63', '<?print 0O77?>')
133    check('-63', '<?print -0o77?>')
134    check('-63', '<?print -0O77?>')
135    check('7', '<?print 0b111?>')
136    check('7', '<?print 0B111?>')
137    check('-7', '<?print -0b111?>')
138    check('-7', '<?print -0B111?>')
139
140    check('no', '<?if 0?>yes<?else?>no<?end if?>')
141    check('yes', '<?if 1?>yes<?else?>no<?end if?>')
142    check('yes', '<?if -1?>yes<?else?>no<?end if?>')
143
144
145def test_float():
146    check('0.0', '<?print 0.?>')
147    check('42.0', '<?print 42.?>')
148    check('-42.0', '<?print -42.?>')
149    check('1e+42', '<?print 1E42?>')
150    check('1e+42', '<?print 1e42?>')
151    check('-1e+42', '<?print -1E42?>')
152    check('-1e+42', '<?print -1e42?>')
153
154    check('no', '<?if 0.?>yes<?else?>no<?end if?>')
155    check('yes', '<?if 1.?>yes<?else?>no<?end if?>')
156    check('yes', '<?if -1.?>yes<?else?>no<?end if?>')
157
158
159def test_string():
160    check('foo', '<?print "foo"?>')
161    check('\n', '<?print "\\n"?>')
162    check('\r', '<?print "\\r"?>')
163    check('\t', '<?print "\\t"?>')
164    check('\f', '<?print "\\f"?>')
165    check('\b', '<?print "\\b"?>')
166    check('\a', '<?print "\\a"?>')
167    check('\x1b', '<?print "\\e"?>')
168    check('"', '<?print "\\""?>')
169    check("'", '<?print "\\\'"?>')
170    check(u'\u20ac', u'<?print "\u20ac"?>')
171    check(u'\xff', u'<?print "\\xff"?>')
172    check(u'\u20ac', u'''<?print "\\u20ac"?>''')
173    checkcompileerror("Unterminated string", '<?print "?>')
174    check("\\xxx", '<?print "\\xxx"?>')
175    check("a\nb", '<?print "a\nb"?>')
176
177    check('no', '<?if ""?>yes<?else?>no<?end if?>')
178    check('yes', '<?if "foo"?>yes<?else?>no<?end if?>')
179
180
181def test_date():
182    check('2000-02-29T00:00:00', '<?print 2000-02-29T.isoformat()?>')
183    check('2000-02-29T12:34:00', '<?print 2000-02-29T12:34.isoformat()?>')
184    check('2000-02-29T12:34:56', '<?print 2000-02-29T12:34:56.isoformat()?>')
185    check('2000-02-29T12:34:56.987654', '<?print 2000-02-29T12:34:56.987654.isoformat()?>')
186    check('yes', '<?if 2000-02-29T12:34:56.987654?>yes<?else?>no<?end if?>')
187
188
189def test_list():
190    check('', '<?for item in []?><?print item?>;<?end for?>')
191    check('1;', '<?for item in [1]?><?print item?>;<?end for?>')
192    check('1;', '<?for item in [1,]?><?print item?>;<?end for?>')
193    check('1;2;', '<?for item in [1, 2]?><?print item?>;<?end for?>')
194    check('1;2;', '<?for item in [1, 2,]?><?print item?>;<?end for?>')
195    check('no', '<?if []?>yes<?else?>no<?end if?>')
196    check('yes', '<?if [1]?>yes<?else?>no<?end if?>')
197
198
199def test_dict():
200    check('', '<?for (key, value) in {}.items()?><?print key?>:<?print value?>\n<?end for?>')
201    check('1:2\n', '<?for (key, value) in {1:2}.items()?><?print key?>:<?print value?>\n<?end for?>')
202    check('1:2\n', '<?for (key, value) in {1:2,}.items()?><?print key?>:<?print value?>\n<?end for?>')
203    # With duplicate keys, later ones simply overwrite earlier ones
204    check('1:3\n', '<?for (key, value) in {1:2, 1: 3}.items()?><?print key?>:<?print value?>\n<?end for?>')
205    check('no', '<?if {}?>yes<?else?>no<?end if?>')
206    check('yes', '<?if {1:2}?>yes<?else?>no<?end if?>')
207
208
209def test_code_storevar():
210    check('42', '<?code x = 42?><?print x?>')
211    check('xyzzy', '<?code x = "xyzzy"?><?print x?>')
212
213
214def test_code_addvar():
215    check('40', '<?code x = 17?><?code x += 23?><?print x?>')
216    check('xyzzy', '<?code x = "xyz"?><?code x += "zy"?><?print x?>')
217
218
219def test_code_subvar():
220    check('-6', '<?code x = 17?><?code x -= 23?><?print x?>')
221
222
223def test_code_mulvar():
224    check('391', '<?code x = 17?><?code x *= 23?><?print x?>')
225    check(17*'xyzzy', '<?code x = 17?><?code x *= "xyzzy"?><?print x?>')
226    check(17*'xyzzy', '<?code x = "xyzzy"?><?code x *= 17?><?print x?>')
227
228
229def test_code_floordivvar():
230    check('2', '<?code x = 5?><?code x //= 2?><?print x?>')
231    check('-3', '<?code x = -5?><?code x //= 2?><?print x?>')
232
233
234def test_code_truedivvar():
235    check('2.5', '<?code x = 5?><?code x /= 2?><?print x?>')
236    check('-2.5', '<?code x = -5?><?code x /= 2?><?print x?>')
237
238
239def test_code_modvar():
240    check('4', '<?code x = 1729?><?code x %= 23?><?print x?>')
241
242
243def test_code_delvar():
244    checkrunerror('KeyError', '<?code x = 1729?><?code del x?><?print x?>')
245
246
247def test_for_string():
248    check('', '<?for c in data?>(<?print c?>)<?end for?>', data="")
249    check('(g)(u)(r)(k)', '<?for c in data?>(<?print c?>)<?end for?>', data="gurk")
250
251
252def test_for_list():
253    check('', '<?for c in data?>(<?print c?>)<?end for?>', data="")
254    check('(g)(u)(r)(k)', '<?for c in data?>(<?print c?>)<?end for?>', data=["g", "u", "r", "k"])
255
256
257def test_for_dict():
258    check('', '<?for c in data?>(<?print c?>)<?end for?>', data={})
259    check('(a)(b)(c)', '<?for c in sorted(data)?>(<?print c?>)<?end for?>', data=dict(a=1, b=2, c=3))
260
261
262def test_for_nested():
263    check('[(1)(2)][(3)(4)]', '<?for list in data?>[<?for n in list?>(<?print n?>)<?end for?>]<?end for?>', data=[[1, 2], [3, 4]])
264
265
266def test_break():
267    check('1, 2, ', '<?for i in [1,2,3]?><?print i?>, <?if i==2?><?break?><?end if?><?end for?>')
268
269
270def test_break_nested():
271    check('1, 1, 2, 1, 2, 3, ', '<?for i in [1,2,3,4]?><?for j in [1,2,3,4]?><?print j?>, <?if j>=i?><?break?><?end if?><?end for?><?if i>=3?><?break?><?end if?><?end for?>')
272
273
274def test_continue():
275    check('1, 3, ', '<?for i in [1,2,3]?><?if i==2?><?continue?><?end if?><?print i?>, <?end for?>')
276
277
278def test_continue_nested():
279    check('1, 3, \n1, 3, \n', '<?for i in [1,2,3]?><?if i==2?><?continue?><?end if?><?for j in [1,2,3]?><?if j==2?><?continue?><?end if?><?print j?>, <?end for?>\n<?end for?>')
280
281
282def test_if():
283    check('42', '<?if data?><?print data?><?end if?>', data=42)
284
285
286def test_else():
287    check('42', '<?if data?><?print data?><?else?>no<?end if?>', data=42)
288    check('no', '<?if data?><?print data?><?else?>no<?end if?>', data=0)
289
290
291def test_block_errors():
292    checkcompileerror("in .<.for x in data.>..*block unclosed", '<?for x in data?>')
293    checkcompileerror("endif doesn't match any if", '<?for x in data?><?end if?>')
294    checkcompileerror("not in any block", '<?end?>')
295    checkcompileerror("not in any block", '<?end for?>')
296    checkcompileerror("not in any block", '<?end if?>')
297    checkcompileerror("else doesn't match any if", '<?else?>')
298    checkcompileerror("in .<.if data.>..*block unclosed", '<?if data?>')
299    checkcompileerror("in .<.if data.>..*block unclosed", '<?if data?><?else?>')
300    checkcompileerror("duplicate else", '<?if data?><?else?><?else?>')
301    checkcompileerror("else already seen in elif", '<?if data?><?else?><?elif data?>')
302    checkcompileerror("else already seen in elif", '<?if data?><?elif data?><?elif data?><?else?><?elif data?>')
303
304
305def test_empty():
306    checkcompileerror("expression required", '<?print?>')
307    checkcompileerror("expression required", '<?if?>')
308    checkcompileerror("expression required", '<<?if x?><?elif?><?end if?>')
309    checkcompileerror("loop expression required", '<?for?>')
310    checkcompileerror("statement required", '<?code?>')
311    checkcompileerror("render statement required", '<?render?>')
312
313
314def test_add():
315    check('42', '<?print 21+21?>')
316    check('42', '<?code x=21?><?code y=21?><?print x+y?>')
317    check('foobar', '<?code x="foo"?><?code y="bar"?><?print x+y?>')
318    check('(f)(o)(o)(b)(a)(r)', '<?for i in data.foo+data.bar?>(<?print i?>)<?end for?>', data=dict(foo="foo", bar="bar"))
319
320
321def test_sub():
322    check('0', '<?print 21-21?>')
323    check('0', '<?code x=21?><?code y=21?><?print x-y?>')
324
325
326
327def test_mul():
328    check(str(17*23), '<?print 17*23?>')
329    check(str(17*23), '<?code x=17?><?code y=23?><?print x*y?>')
330    check(17*"foo", '<?print 17*"foo"?>')
331    check(17*"foo", '<?code x=17?><?code y="foo"?><?print x*y?>')
332    check("foo"*17, '<?code x="foo"?><?code y=17?><?print x*y?>')
333    check("foo"*17, '<?print "foo"*17?>')
334    check("(foo)(bar)(foo)(bar)(foo)(bar)", '<?for i in 3*data?>(<?print i?>)<?end for?>', data=["foo", "bar"])
335
336
337def test_truediv():
338    check("0.5", '<?print 1/2?>')
339    check("0.5", '<?code x=1?><?code y=2?><?print x/y?>')
340
341
342def test_floordiv():
343    check("0", '<?print 1//2?>')
344    check("0", '<?code x=1?><?code y=2?><?print x//y?>')
345
346
347def test_mod():
348    check(str(42%17), '<?print 42%17?>')
349    check(str(42%17), '<?code x=42?><?code y=17?><?print x%y?>')
350
351
352def test_eq():
353    check("False", '<?print 17==23?>')
354    check("True", '<?print 17==17?>')
355    check("False", '<?print x==23?>', x=17)
356    check("True", '<?print x==23?>', x=23)
357
358
359def test_ne():
360    check("True", '<?print 17!=23?>')
361    check("False", '<?print 17!=17?>')
362    check("True", '<?print x!=23?>', x=17)
363    check("False", '<?print x!=23?>', x=23)
364
365
366def test_lt():
367    check("True", '<?print 1<2?>')
368    check("False", '<?print 2<2?>')
369    check("False", '<?print 3<2?>')
370    check("True", '<?print x<2?>', x=1)
371    check("False", '<?print x<2?>', x=2)
372    check("False", '<?print x<2?>', x=3)
373
374
375def test_le():
376    check("True", '<?print 1<=2?>')
377    check("True", '<?print 2<=2?>')
378    check("False", '<?print 3<=2?>')
379    check("True", '<?print x<=2?>', x=1)
380    check("True", '<?print x<=2?>', x=2)
381    check("False", '<?print x<=2?>', x=3)
382
383
384def test_gt():
385    check("False", '<?print 1>2?>')
386    check("False", '<?print 2>2?>')
387    check("True", '<?print 3>2?>')
388    check("False", '<?print x>2?>', x=1)
389    check("False", '<?print x>2?>', x=2)
390    check("True", '<?print x>2?>', x=3)
391
392
393def test_and():
394    check("False", '<?print x and y?>', x=False, y=False)
395    check("False", '<?print x and y?>', x=False, y=True)
396    check("0", '<?print x and y?>', x=0, y=True)
397
398
399def test_or():
400    check("False", '<?print x or y?>', x=False, y=False)
401    check("True", '<?print x or y?>', x=False, y=True)
402    check("42", '<?print x or y?>', x=42, y=True)
403
404
405def test_not():
406    check("True", '<?print not x?>', x=False)
407    check("False", '<?print not x?>', x=42)
408
409
410def test_ge():
411    check("False", '<?print 1>=2?>')
412    check("True", '<?print 2>=2?>')
413    check("True", '<?print 3>=2?>')
414    check("False", '<?print x>=2?>', x=1)
415    check("True", '<?print x>=2?>', x=2)
416    check("True", '<?print x>=2?>', x=3)
417
418
419def test_getitem():
420    check("u", "<?print 'gurk'[1]?>")
421    check("u", "<?print x[1]?>", x="gurk")
422    check("u", "<?print 'gurk'[-3]?>")
423    check("u", "<?print x[-3]?>", x="gurk")
424    checkcompileerror("IndexError", "<?print 'gurk'[4]?>")
425    checkrunerror("IndexError", "<?print x[4]?>", x="gurk")
426    checkcompileerror("IndexError", "<?print 'gurk'[-5]?>")
427    checkrunerror("IndexError", "<?print x[-5]?>", x="gurk")
428
429
430def test_getslice12():
431    check("ur", "<?print 'gurk'[1:3]?>")
432    check("ur", "<?print x[1:3]?>", x="gurk")
433    check("ur", "<?print 'gurk'[-3:-1]?>")
434    check("ur", "<?print x[-3:-1]?>", x="gurk")
435    check("", "<?print 'gurk'[4:10]?>")
436    check("", "<?print x[4:10]?>", x="gurk")
437    check("", "<?print 'gurk'[-10:-5]?>")
438    check("", "<?print x[-10:-5]?>", x="gurk")
439
440
441def test_getslice1():
442    check("urk", "<?print 'gurk'[1:]?>")
443    check("urk", "<?print x[1:]?>", x="gurk")
444    check("urk", "<?print 'gurk'[-3:]?>")
445    check("urk", "<?print x[-3:]?>", x="gurk")
446    check("", "<?print 'gurk'[4:]?>")
447    check("", "<?print x[4:]?>", x="gurk")
448    check("gurk", "<?print 'gurk'[-10:]?>")
449    check("gurk", "<?print x[-10:]?>", x="gurk")
450
451
452def test_getslice2():
453    check("gur", "<?print 'gurk'[:3]?>")
454    check("gur", "<?print x[:3]?>", x="gurk")
455    check("gur", "<?print 'gurk'[:-1]?>")
456    check("gur", "<?print x[:-1]?>", x="gurk")
457    check("gurk", "<?print 'gurk'[:10]?>")
458    check("gurk", "<?print x[:10]?>", x="gurk")
459    check("", "<?print 'gurk'[:-5]?>")
460    check("", "<?print x[:-5]?>", x="gurk")
461
462
463def test_nested():
464    sc = "4"
465    sv = "x"
466    n = 4
467    for i in xrange(8): # when using 10 compiling the variable will run out of registers
468        sc = "(%s)+(%s)" % (sc, sc)
469        sv = "(%s)+(%s)" % (sv, sv)
470        n = n+n
471    check(str(n), '<?print %s?>' % sc)
472    check(str(n), '<?code x=4?><?print %s?>' % sv)
473
474
475def test_precedence():
476    check("14", '<?print 2+3*4?>')
477    check("20", '<?print (2+3)*4?>')
478    check("10", '<?print -2+-3*-4?>')
479    check("14", '<?print --2+--3*--4?>')
480    check("14", '<?print (-(-2))+(-((-3)*-(-4)))?>')
481    check("42", '<?print 2*data.value?>', data=dict(value=21))
482    check("42", '<?print data.value[0]?>', data=dict(value=[42]))
483    check("42", '<?print data[0].value?>', data=[dict(value=42)])
484    check("42", '<?print data[0][0][0]?>', data=[[[42]]])
485    check("42", '<?print data.value.value[0]?>', data=dict(value=dict(value=[42])))
486    check("42", '<?print data.value.value[0].value.value[0]?>', data=dict(value=dict(value=[dict(value=dict(value=[42]))])))
487
488
489def test_bracket():
490    sc = "4"
491    sv = "x"
492    for i in xrange(10):
493        sc = "(%s)" % sc
494        sv = "(%s)" % sv
495
496    check("4", '<?print %s?>' % sc)
497    check("4", '<?code x=4?><?print %s?>' % sv)
498
499
500def test_function_now():
501    checkrunerror("function u?'now' unknown", "<?print now(1)?>")
502    checkrunerror("function u?'now' unknown", "<?print now(1, 2)?>")
503    now = unicode(datetime.datetime.now())
504    checkle(now, "<?print now()?>")
505
506
507def test_function_xmlescape():
508    checkrunerror("function u?'xmlescape' unknown", "<?print xmlescape()?>")
509    checkrunerror("function u?'xmlescape' unknown", "<?print xmlescape(1, 2)?>")
510    check("&lt;&gt;&amp;&#39;&quot;gurk", "<?print xmlescape(data)?>", data='<>&\'"gurk')
511
512
513def test_function_csvescape():
514    checkrunerror("function u?'csvescape' unknown", "<?print csvescape()?>")
515    checkrunerror("function u?'csvescape' unknown", "<?print csvescape(1, 2)?>")
516    check("", "<?print csvescape(data)?>", data=None)
517    check("False", "<?print csvescape(data)?>", data=False)
518    check("True", "<?print csvescape(data)?>", data=True)
519    check("42", "<?print csvescape(data)?>", data=42)
520    # no check for float
521    check("abc", "<?print csvescape(data)?>", data="abc")
522    check('"a,b,c"', "<?print csvescape(data)?>", data="a,b,c")
523    check('"a""b""c"', "<?print csvescape(data)?>", data='a"b"c')
524    check('"a\nb\nc"', "<?print csvescape(data)?>", data="a\nb\nc")
525
526
527def test_function_str():
528    checkrunerror("function u?'str' unknown", "<?print str()?>")
529    checkrunerror("function u?'str' unknown", "<?print str(1, 2)?>")
530    check("", "<?print str(data)?>", data=None)
531    check("True", "<?print str(data)?>", data=True)
532    check("False", "<?print str(data)?>", data=False)
533    check("42", "<?print str(data)?>", data=42)
534    check("4.2", "<?print str(data)?>", data=4.2)
535    check("foo", "<?print str(data)?>", data="foo")
536
537
538def test_function_int():
539    checkrunerror("function u?'int' unknown", "<?print int()?>")
540    checkrunerror("function u?'int' unknown", "<?print int(1, 2)?>")
541    checkrunerror("int\\(\\) argument must be a string or a number, not 'NoneType'", "<?print int(data)?>", data=None)
542    check("1", "<?print int(data)?>", data=True)
543    check("0", "<?print int(data)?>", data=False)
544    check("42", "<?print int(data)?>", data=42)
545    check("4", "<?print int(data)?>", data=4.2)
546    check("42", "<?print int(data)?>", data="42")
547    checkrunerror("invalid literal for int\\(\\) with base 10: 'foo'", "<?print int(data)?>", data="foo")
548
549
550def test_function_len():
551    checkrunerror("function u?'len' unknown", "<?print len()?>")
552    checkrunerror("function u?'len' unknown", "<?print len(1, 2)?>")
553    checkrunerror("object of type 'NoneType' has no len", "<?print len(data)?>", data=None)
554    checkrunerror("object of type 'bool' has no len", "<?print len(data)?>", data=True)
555    checkrunerror("object of type 'bool' has no len", "<?print len(data)?>", data=False)
556    checkrunerror("object of type 'int' has no len", "<?print len(data)?>", data=42)
557    checkrunerror("object of type 'float' has no len", "<?print len(data)?>", data=4.2)
558    check("42", "<?print len(data)?>", data=42*"?")
559    check("42", "<?print len(data)?>", data=42*[None])
560    check("42", "<?print len(data)?>", data=dict.fromkeys(xrange(42)))
561
562
563def test_function_enumerate():
564    checkrunerror("function u?'enumerate' unknown", "<?print enumerate()?>")
565    checkrunerror("function u?'enumerate' unknown", "<?print enumerate(1, 2)?>")
566    code = "<?for (i, value) in enumerate(data)?><?print i?>:<?print value?>\n<?end for?>"
567    checkrunerror("'NoneType' object is not iterable", code, data=None)
568    checkrunerror("'bool' object is not iterable", code, data=True)
569    checkrunerror("'bool' object is not iterable", code, data=False)
570    checkrunerror("'int' object is not iterable", code, data=42)
571    checkrunerror("'float' object is not iterable", code, data=4.2)
572    check("0:f\n1:o\n2:o\n", code, data="foo")
573    check("0:foo\n1:bar\n", code, data=["foo", "bar"])
574    check("0:foo\n", code, data=dict(foo=True))
575
576
577def test_function_isnone():
578    checkrunerror("function u?'isnone' unknown", "<?print isnone()?>")
579    checkrunerror("function u?'isnone' unknown", "<?print isnone(1, 2)?>")
580    code = "<?print isnone(data)?>"
581    check("True", code, data=None)
582    check("False", code, data=True)
583    check("False", code, data=False)
584    check("False", code, data=42)
585    check("False", code, data=4.2)
586    check("False", code, data="foo")
587    check("False", code, data=datetime.datetime.now())
588    check("False", code, data=())
589    check("False", code, data=[])
590    check("False", code, data={})
591
592
593def test_function_isbool():
594    checkrunerror("function u?'isbool' unknown", "<?print isbool()?>")
595    checkrunerror("function u?'isbool' unknown", "<?print isbool(1, 2)?>")
596    code = "<?print isbool(data)?>"
597    check("False", code, data=None)
598    check("True", code, data=True)
599    check("True", code, data=False)
600    check("False", code, data=42)
601    check("False", code, data=4.2)
602    check("False", code, data="foo")
603    check("False", code, data=datetime.datetime.now())
604    check("False", code, data=())
605    check("False", code, data=[])
606    check("False", code, data={})
607
608
609def test_function_isint():
610    checkrunerror("function u?'isint' unknown", "<?print isint()?>")
611    checkrunerror("function u?'isint' unknown", "<?print isint(1, 2)?>")
612    code = "<?print isint(data)?>"
613    check("False", code, data=None)
614    check("False", code, data=True)
615    check("False", code, data=False)
616    check("True", code, data=42)
617    check("False", code, data=4.2)
618    check("False", code, data="foo")
619    check("False", code, data=datetime.datetime.now())
620    check("False", code, data=())
621    check("False", code, data=[])
622    check("False", code, data={})
623
624
625def test_function_isfloat():
626    checkrunerror("function u?'isfloat' unknown", "<?print isfloat()?>")
627    checkrunerror("function u?'isfloat' unknown", "<?print isfloat(1, 2)?>")
628    code = "<?print isfloat(data)?>"
629    check("False", code, data=None)
630    check("False", code, data=True)
631    check("False", code, data=False)
632    check("False", code, data=42)
633    check("True", code, data=4.2)
634    check("False", code, data="foo")
635    check("False", code, data=datetime.datetime.now())
636    check("False", code, data=())
637    check("False", code, data=[])
638    check("False", code, data={})
639
640
641def test_function_isstr():
642    checkrunerror("function u?'isstr' unknown", "<?print isstr()?>")
643    checkrunerror("function u?'isstr' unknown", "<?print isstr(1, 2)?>")
644    code = "<?print isstr(data)?>"
645    check("False", code, data=None)
646    check("False", code, data=True)
647    check("False", code, data=False)
648    check("False", code, data=42)
649    check("False", code, data=4.2)
650    check("True", code, data="foo")
651    check("False", code, data=datetime.datetime.now())
652    check("False", code, data=())
653    check("False", code, data=[])
654    check("False", code, data={})
655
656
657def test_function_isdate():
658    checkrunerror("function u?'isdate' unknown", "<?print isdate()?>")
659    checkrunerror("function u?'isdate' unknown", "<?print isdate(1, 2)?>")
660    code = "<?print isdate(data)?>"
661    check("False", code, data=None)
662    check("False", code, data=True)
663    check("False", code, data=False)
664    check("False", code, data=42)
665    check("False", code, data=4.2)
666    check("False", code, data="foo")
667    check("True", code, data=datetime.datetime.now())
668    check("False", code, data=())
669    check("False", code, data=[])
670    check("False", code, data={})
671
672
673def test_function_islist():
674    checkrunerror("function u?'islist' unknown", "<?print islist()?>")
675    checkrunerror("function u?'islist' unknown", "<?print islist(1, 2)?>")
676    code = "<?print islist(data)?>"
677    check("False", code, data=None)
678    check("False", code, data=True)
679    check("False", code, data=False)
680    check("False", code, data=42)
681    check("False", code, data=4.2)
682    check("False", code, data="foo")
683    check("False", code, data=datetime.datetime.now())
684    check("True", code, data=())
685    check("True", code, data=[])
686    check("False", code, data={})
687
688
689def test_function_isdict():
690    checkrunerror("function u?'isdict' unknown", "<?print isdict()?>")
691    checkrunerror("function u?'isdict' unknown", "<?print isdict(1, 2)?>")
692    code = "<?print isdict(data)?>"
693    check("False", code, data=None)
694    check("False", code, data=True)
695    check("False", code, data=False)
696    check("False", code, data=42)
697    check("False", code, data=4.2)
698    check("False", code, data="foo")
699    check("False", code, data=datetime.datetime.now())
700    check("False", code, data=())
701    check("False", code, data=[])
702    check("True", code, data={})
703
704
705def test_function_get():
706    checkrunerror("function u?'get' unknown", "<?print get()?>")
707    check("", "<?print get('x')?>")
708    check("42", "<?print get('x')?>", x=42)
709    check("17", "<?print get('x', 17)?>")
710    check("42", "<?print get('x', 17)?>", x=42)
711
712
713def test_function_repr():
714    checkrunerror("function u?'repr' unknown", "<?print repr()?>")
715    checkrunerror("function u?'repr' unknown", "<?print repr(1, 2)?>")
716    code = "<?print repr(data)?>"
717    check("None", code, data=None)
718    check("True", code, data=True)
719    check("False", code, data=False)
720    check("42", code, data=42)
721    # no test for float
722    check("'foo'", code, data="foo")
723    # no test for tuples, lists and dicts
724
725
726def test_function_chr():
727    checkrunerror("function u?'chr' unknown", "<?print chr()?>")
728    checkrunerror("function u?'chr' unknown", "<?print chr(1, 2)?>")
729    code = "<?print chr(data)?>"
730    check("\x00", code, data=0)
731    check("a", code, data=ord("a"))
732    check(u"\u20ac", code, data=0x20ac)
733
734
735def test_function_ord():
736    checkrunerror("function u?'ord' unknown", "<?print ord()?>")
737    checkrunerror("function u?'ord' unknown", "<?print ord(1, 2)?>")
738    code = "<?print ord(data)?>"
739    check("0", code, data="\x00")
740    check(str(ord("a")), code, data="a")
741    check(str(0x20ac), code, data=u"\u20ac")
742
743
744def test_function_hex():
745    checkrunerror("function u?'hex' unknown", "<?print hex()?>")
746    checkrunerror("function u?'hex' unknown", "<?print hex(1, 2)?>")
747    code = "<?print hex(data)?>"
748    check("0x0", code, data=0)
749    check("0xff", code, data=0xff)
750    check("0xffff", code, data=0xffff)
751    check("-0xffff", code, data=-0xffff)
752
753
754def test_function_oct():
755    checkrunerror("function u?'oct' unknown", "<?print oct()?>")
756    checkrunerror("function u?'oct' unknown", "<?print oct(1, 2)?>")
757    code = "<?print oct(data)?>"
758    check("0o0", code, data=0)
759    check("0o77", code, data=077)
760    check("0o7777", code, data=07777)
761    check("-0o7777", code, data=-07777)
762
763
764def test_function_bin():
765    checkrunerror("function u?'bin' unknown", "<?print bin()?>")
766    checkrunerror("function u?'bin' unknown", "<?print bin(1, 2)?>")
767    code = "<?print bin(data)?>"
768    check("0b0", code, data=0)
769    check("0b11", code, data=3)
770    check("-0b1111", code, data=-15)
771
772
773def test_function_sorted():
774    checkrunerror("function u?'sorted' unknown", "<?print sorted()?>")
775    checkrunerror("function u?'sorted' unknown", "<?print sorted(1, 2)?>")
776    code = "<?for i in sorted(data)?><?print i?><?end for?>"
777    check("gkru", code, data="gurk")
778    check("24679", code, data="92746")
779    check("012", code, data={0: "zero", 1: "one", 2: "two"})
780
781
782def test_function_range():
783    checkrunerror("function u?'sorted' unknown", "<?print sorted()?>")
784    code = "<?for i in range(data)?><?print i?><?end for?>"
785    check("", code, data=-10)
786    check("", code, data=0)
787    check("0", code, data=1)
788    check("01234", code, data=5)
789    code = "<?for i in range(data[0], data[1])?><?print i?><?end for?>"
790    check("", code, data=[0, -10])
791    check("", code, data=[0, 0])
792    check("01234", code, data=[0, 5])
793    check("-5-4-3-2-101234", code, data=[-5, 5])
794    code = "<?for i in range(data[0], data[1], data[2])?><?print i?><?end for?>"
795    check("", code, data=[0, -10, 1])
796    check("", code, data=[0, 0, 1])
797    check("02468", code, data=[0, 10, 2])
798    check("", code, data=[0, 10, -2])
799    check("108642", code, data=[10, 0, -2])
800    check("", code, data=[10, 0, 2])
801
802
803def test_function_zip():
804    checkrunerror("function u?'zip' unknown", "<?print zip()?>")
805    checkrunerror("function u?'zip' unknown", "<?print zip(1)?>")
806    code = "<?for (ix, iy) in zip(x, y)?><?print ix?>-<?print iy?>;<?end for?>"
807    check("", code, x=[], y=[])
808    check("1-3;2-4;", code, x=[1, 2], y=[3, 4])
809    check("1-4;2-5;", code, x=[1, 2, 3], y=[4, 5])
810    code = "<?for (ix, iy, iz) in zip(x, y, z)?><?print ix?>-<?print iy?>+<?print iz?>;<?end for?>"
811    check("", code, x=[], y=[], z=[])
812    check("1-3+5;2-4+6;", code, x=[1, 2], y=[3, 4], z=[5, 6])
813    check("1-4+6;", code, x=[1, 2, 3], y=[4, 5], z=[6])
814
815
816def test_method_upper():
817    check("GURK", "<?print 'gurk'.upper()?>")
818
819
820def test_method_lower():
821    check("gurk", "<?print 'GURK'.lower()?>")
822
823
824def test_method_capitalize():
825    check("Gurk", "<?print 'gURK'.capitalize()?>")
826
827
828def test_method_startswith():
829    check("True", "<?print 'gurkhurz'.startswith('gurk')?>")
830    check("False", "<?print 'gurkhurz'.startswith('hurz')?>")
831
832
833def test_method_endswith():
834    check("True", "<?print 'gurkhurz'.endswith('hurz')?>")
835    check("False", "<?print 'gurkhurz'.endswith('gurk')?>")
836
837
838def test_method_strip():
839    check("gurk", r"<?print ' \t\r\ngurk \t\r\n'.strip()?>")
840    check("gurk", r"<?print 'xyzzygurkxyzzy'.strip('xyz')?>")
841
842
843def test_method_lstrip():
844    check("gurk \t\r\n", r"<?print ' \t\r\ngurk \t\r\n'.lstrip()?>")
845    check("gurkxyzzy", r"<?print 'xyzzygurkxyzzy'.lstrip('xyz')?>")
846
847
848def test_method_rstrip():
849    check(" \t\r\ngurk", r"<?print ' \t\r\ngurk \t\r\n'.rstrip()?>")
850    check("xyzzygurk", r"<?print 'xyzzygurkxyzzy'.rstrip('xyz')?>")
851
852
853def test_method_split():
854    check("(g)(u)(r)(k)", r"<?for item in ' \t\r\ng \t\r\nu \t\r\nr \t\r\nk \t\r\n'.split()?>(<?print item?>)<?end for?>")
855    check("(g)(u \t\r\nr \t\r\nk \t\r\n)", r"<?for item in ' \t\r\ng \t\r\nu \t\r\nr \t\r\nk \t\r\n'.split(None, 1)?>(<?print item?>)<?end for?>")
856    check("()(g)(u)(r)(k)()", r"<?for item in 'xxgxxuxxrxxkxx'.split('xx')?>(<?print item?>)<?end for?>")
857    check("()(g)(uxxrxxkxx)", r"<?for item in 'xxgxxuxxrxxkxx'.split('xx', 2)?>(<?print item?>)<?end for?>")
858
859
860def test_method_rsplit():
861    check("(g)(u)(r)(k)", r"<?for item in ' \t\r\ng \t\r\nu \t\r\nr \t\r\nk \t\r\n'.rsplit()?>(<?print item?>)<?end for?>")
862    check("( \t\r\ng \t\r\nu \t\r\nr)(k)", r"<?for item in ' \t\r\ng \t\r\nu \t\r\nr \t\r\nk \t\r\n'.rsplit(None, 1)?>(<?print item?>)<?end for?>")
863    check("()(g)(u)(r)(k)()", r"<?for item in 'xxgxxuxxrxxkxx'.rsplit('xx')?>(<?print item?>)<?end for?>")
864    check("(xxgxxuxxr)(k)()", r"<?for item in 'xxgxxuxxrxxkxx'.rsplit('xx', 2)?>(<?print item?>)<?end for?>")
865
866
867def test_method_replace():
868    check('goork', r"<?print 'gurk'.replace('u', 'oo')?>")
869
870
871def test_method_format():
872    now = datetime.datetime.now()
873    format = "%Y-%m-%d %H:%M:%S"
874    check(now.strftime(format), r"<?print data.format('%s')?>" % format, data=now)
875
876
877def test_method_isoformat():
878    now = datetime.datetime.now()
879    check(now.isoformat(), r"<?print data.isoformat()?>", data=now)
880
881
882def test_method_get():
883    check("42", "<?print {}.get('foo', 42)?>")
884    check("17", "<?print {'foo': 17}.get('foo', 42)?>")
885    check("", "<?print {}.get('foo')?>")
886    check("17", "<?print {'foo': 17}.get('foo')?>")
887
888
889def test_render():
890    t = ul4c.compile('<?print prefix?><?print data?><?print suffix?>')
891    check('(f)(o)(o)', '<?for c in data?><?render t(data=c, prefix="(", suffix=")")?><?end for?>', dict(t=t), data='foo')
892
893
894def test_render_var():
895    t = ul4c.compile('<?code x += 1?><?print x?>')
896    check('42,43,42', '<?print x?>,<?render t(x=x)?>,<?print x?>', dict(t=t), x=42)
897
898
899def test_parse():
900    check('42', '<?print data.Noner?>', data=dict(Noner=42))
901
902
903def test_nested_exceptions():
904    tmpl1 = ul4c.compile("<?print 2*x?>")
905    tmpl2 = ul4c.compile("<?render tmpl1(x=x)?>")
906    tmpl3 = ul4c.compile("<?render tmpl2(x=x)?>")
907
908    checkrunerror(r"TypeError .*render tmpl3.*render tmpl2.*render tmpl1.*print 2.*unsupported operand type", "<?render tmpl3(x=x)?>", dict(tmpl1=tmpl1, tmpl2=tmpl2, tmpl3=tmpl3), x=None)
Note: See TracBrowser for help on using the browser.