1 package org.apache.velocity.test;
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 public class DefineTestCase extends BaseTestCase
27 {
28 public DefineTestCase(String name)
29 {
30 super(name);
31 }
32
33 protected String defAndEval(String block)
34 {
35 return defAndEval("def", block);
36 }
37
38 protected String defAndEval(String key, String block)
39 {
40 return evaluate("#define( $"+key+" )"+block+"#end$"+key);
41 }
42
43 public void testSimple()
44 {
45 assertEquals("abc", defAndEval("abc"));
46 assertEvalEquals("abc abc abc", "#define( $a )abc#end$a $a $a");
47 }
48
49 public void testNotSimple()
50 {
51 assertEquals("true", defAndEval("#if( $def )true#end"));
52 assertEquals("123", defAndEval("#foreach( $i in [1..3] )$i#end"));
53 assertEquals("hello world", defAndEval("#macro( test )hello world#end#test()"));
54 }
55
56 public void testOverridingDefinitionInternally()
57 {
58 assertEvalEquals("truefalse", "#define( $or )true#set( $or = false )#end$or$or");
59 }
60
61 public void testLateBinding()
62 {
63 context.put("baz", "foo");
64 assertEvalEquals("foobar", "#define( $lb )$baz#end${lb}#set( $baz = 'bar' )${lb}");
65 }
66
67 public void testRerendering()
68 {
69 context.put("inc", new Inc());
70 assertEvalEquals("1 2 3", "#define( $i )$inc#end$i $i $i");
71 }
72
73 public void testAssignation()
74 {
75 assertEvalEquals("[][hello]","#define( $orig )hello#end[#set( $assig = $orig )][$assig]");
76 }
77
78 public void testNonRenderingUsage()
79 {
80 String template = "#define($foo)\n" +
81 " foo_contents\n" +
82 "#end\n" +
83 "#if ($foo)\n" +
84 " found foo\n" +
85 "#end";
86 assertEvalEquals(" found foo\n", template);
87 }
88
89 public void testRecursionLimit()
90 {
91 try
92 {
93 assertEvalEquals("$r", "#define( $r )$r#end$r");
94 }
95 catch (Exception t)
96 {
97 fail("Recursion should not have thrown an exception");
98 }
99 catch (Error e)
100 {
101 fail("Infinite recursion should not be possible.");
102 }
103 }
104
105 public void testThingsOfQuestionableMorality()
106 {
107
108 assertEquals("foobar", defAndEval("foo", "foo#define( $foo )bar#end$foo"));
109 }
110
111
112 public static class Inc
113 {
114 int foo = 1;
115 public String toString()
116 {
117 return String.valueOf(foo++);
118 }
119 }
120 }