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