Debian Codegraph @

src/test/java/com/google/escapevelocity/TemplateTest.java

raw
1 /*
2 * Copyright (C) 2018 Google, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package com.google.escapevelocity;
17
18 import static com.google.common.truth.Truth.assertThat;
19 import static com.google.common.truth.Truth.assertWithMessage;
20 import static org.junit.Assert.fail;
21
22 import com.google.common.collect.ImmutableList;
23 import com.google.common.collect.ImmutableMap;
24 import com.google.common.collect.ImmutableSetMultimap;
25 import com.google.common.truth.Expect;
26 import java.io.ByteArrayInputStream;
27 import java.io.FileNotFoundException;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.StringReader;
31 import java.io.StringWriter;
32 import java.io.UncheckedIOException;
33 import java.nio.charset.StandardCharsets;
34 import java.util.ArrayList;
35 import java.util.HashMap;
36 import java.util.Map;
37 import java.util.TreeMap;
38 import java.util.function.Supplier;
39 import org.apache.commons.collections.ExtendedProperties;
40 import org.apache.velocity.VelocityContext;
41 import org.apache.velocity.exception.ResourceNotFoundException;
42 import org.apache.velocity.exception.VelocityException;
43 import org.apache.velocity.runtime.RuntimeConstants;
44 import org.apache.velocity.runtime.RuntimeInstance;
45 import org.apache.velocity.runtime.log.NullLogChute;
46 import org.apache.velocity.runtime.parser.node.SimpleNode;
47 import org.apache.velocity.runtime.resource.Resource;
48 import org.apache.velocity.runtime.resource.loader.ResourceLoader;
49 import org.junit.Before;
50 import org.junit.Rule;
51 import org.junit.Test;
52 import org.junit.rules.TestName;
53 import org.junit.runner.RunWith;
54 import org.junit.runners.JUnit4;
55
56 /**
57 * @author [email protected] (Éamonn McManus)
58 */
59 @RunWith(JUnit4.class)
60 public class TemplateTest {
61 @Rule public TestName testName = new TestName();
62 @Rule public Expect expect = Expect.create();
63
64 private RuntimeInstance velocityRuntimeInstance;
65
66 @Before
67 public void initVelocityRuntimeInstance() {
68 velocityRuntimeInstance = newVelocityRuntimeInstance();
69 velocityRuntimeInstance.init();
70 }
71
72 private RuntimeInstance newVelocityRuntimeInstance() {
73 RuntimeInstance runtimeInstance = new RuntimeInstance();
74
75 // Ensure that $undefinedvar will produce an exception rather than outputting $undefinedvar.
76 runtimeInstance.setProperty(RuntimeConstants.RUNTIME_REFERENCES_STRICT, "true");
77
78 // Disable any logging that Velocity might otherwise see fit to do.
79 runtimeInstance.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, new NullLogChute());
80 runtimeInstance.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new NullLogChute());
81 return runtimeInstance;
82 }
83
84 private void compare(String template) {
85 compare(template, ImmutableMap.<String, Object>of());
86 }
87
88 private void compare(String template, Map<String, ?> vars) {
89 compare(template, () -> vars);
90 }
91
92 /**
93 * Checks that the given template and the given variables produce identical results with
94 * Velocity and EscapeVelocity. This uses a {@code Supplier} to define the variables to cover
95 * test cases that involve modifying the values of the variables. Otherwise the run using
96 * Velocity would change those values so that the run using EscapeVelocity would not be starting
97 * from the same point.
98 */
99 private void compare(String template, Supplier<? extends Map<String, ?>> varsSupplier) {
100 Map<String, ?> velocityVars = varsSupplier.get();
101 String velocityRendered = velocityRender(template, velocityVars);
102 Map<String, ?> escapeVelocityVars = varsSupplier.get();
103 String escapeVelocityRendered;
104 try {
105 escapeVelocityRendered =
106 Template.parseFrom(new StringReader(template)).evaluate(escapeVelocityVars);
107 } catch (Exception e) {
108 throw new AssertionError(
109 "EscapeVelocity failed, but Velocity succeeded and returned: <" + velocityRendered + ">",
110 e);
111 }
112 String failure = "from Velocity: <" + velocityRendered + ">\n"
113 + "from EscapeVelocity: <" + escapeVelocityRendered + ">\n";
114 expect.withMessage(failure).that(escapeVelocityRendered).isEqualTo(velocityRendered);
115 }
116
117 private String velocityRender(String template, Map<String, ?> vars) {
118 VelocityContext velocityContext = new VelocityContext(new TreeMap<>(vars));
119 StringWriter writer = new StringWriter();
120 SimpleNode parsedTemplate;
121 try {
122 parsedTemplate = velocityRuntimeInstance.parse(
123 new StringReader(template), testName.getMethodName());
124 } catch (org.apache.velocity.runtime.parser.ParseException e) {
125 throw new AssertionError(e);
126 }
127 boolean rendered = velocityRuntimeInstance.render(
128 velocityContext, writer, parsedTemplate.getTemplateName(), parsedTemplate);
129 assertThat(rendered).isTrue();
130 return writer.toString();
131 }
132
133 private void expectParseException(
134 String template,
135 String expectedMessageSubstring) {
136 Exception velocityException = null;
137 try {
138 SimpleNode parsedTemplate =
139 velocityRuntimeInstance.parse(new StringReader(template), testName.getMethodName());
140 VelocityContext velocityContext = new VelocityContext(new TreeMap<>());
141 velocityRuntimeInstance.render(
142 velocityContext, new StringWriter(), parsedTemplate.getTemplateName(), parsedTemplate);
143 fail("Velocity did not throw an exception for this template");
144 } catch (org.apache.velocity.runtime.parser.ParseException | VelocityException expected) {
145 velocityException = expected;
146 }
147 try {
148 Template.parseFrom(new StringReader(template));
149 fail("Velocity generated an exception, but EscapeVelocity did not: " + velocityException);
150 } catch (IOException e) {
151 throw new UncheckedIOException(e);
152 } catch (ParseException expected) {
153 assertWithMessage("Got expected exception, but message did not match")
154 .that(expected).hasMessageThat().contains(expectedMessageSubstring);
155 }
156 }
157
158 @Test
159 public void empty() {
160 compare("");
161 }
162
163 @Test
164 public void literalOnly() {
165 compare("In the reign of James the Second \n It was generally reckoned\n");
166 }
167
168 @Test
169 public void lineComment() {
170 compare("line 1 ##\n line 2");
171 }
172
173 @Test
174 public void blockComment() {
175 compare("line 1 #* blah\n line 2 * #\n line 3 *# \n line 4");
176 compare("foo #*# bar *# baz");
177 compare("foo #* one *# #* two *# #* three *#");
178 compare("foo #** bar *# #* baz **#");
179 }
180
181 @Test
182 public void ignoreHashIfNotDirectiveOrComment() {
183 compare("# if is not a directive because of the space");
184 compare("#<foo>");
185 compare("# <foo>");
186 compare("${foo}#${bar}", ImmutableMap.of("foo", "xxx", "bar", "yyy"));
187 }
188
189 @Test
190 public void blockQuote() {
191 compare("#[[]]#");
192 compare("x#[[]]#y");
193 compare("#[[$notAReference #notADirective]]#");
194 compare("#[[ [[ ]] ]# ]]#");
195 compare("#[ foo");
196 compare("x\n #[[foo\nbar\nbaz]]#y");
197 }
198
199 @Test
200 public void substituteNoBraces() {
201 compare(" $x ", ImmutableMap.of("x", 1729));
202 compare(" ! $x ! ", ImmutableMap.of("x", 1729));
203 }
204
205 @Test
206 public void dollarWithoutId() {
207 compare(" $? ");
208 compare(" $$ ");
209 compare(" $. ");
210 compare(" $[ ");
211 }
212
213 @Test
214 public void doubleDollar() {
215 // The first $ is plain text and the second one starts a reference.
216 compare(" $$foo ", ImmutableMap.of("foo", true));
217 compare(" $${foo} ", ImmutableMap.of("foo", true));
218 }
219
220 @Test
221 public void substituteWithBraces() {
222 compare("a${x}\nb", ImmutableMap.of("x", "1729"));
223 }
224
225 @Test
226 public void substitutePropertyNoBraces() {
227 compare("=$t.name=", ImmutableMap.of("t", Thread.currentThread()));
228 }
229
230 @Test
231 public void substitutePropertyWithBraces() {
232 compare("=${t.name}=", ImmutableMap.of("t", Thread.currentThread()));
233 }
234
235 @Test
236 public void substituteNotPropertyId() {
237 compare("$foo.!", ImmutableMap.of("foo", false));
238 }
239
240 @Test
241 public void substituteNestedProperty() {
242 compare("\n$t.name.empty\n", ImmutableMap.of("t", Thread.currentThread()));
243 }
244
245 @Test
246 public void substituteMethodNoArgs() {
247 compare("<$c.size()>", ImmutableMap.of("c", ImmutableMap.of()));
248 }
249
250 @Test
251 public void substituteMethodNoArgsSyntheticOverride() {
252 compare("<$c.isEmpty()>", ImmutableMap.of("c", ImmutableSetMultimap.of()));
253 }
254
255 @Test
256 public void substituteMethodOneArg() {
257 compare("<$list.get(0)>", ImmutableMap.of("list", ImmutableList.of("foo")));
258 }
259
260 @Test
261 public void substituteMethodOneNullArg() {
262 // This should evaluate map.containsKey(map.get("absent")), which is map.containsKey(null).
263 compare("<$map.containsKey($map.get(\"absent\"))>", ImmutableMap.of("map", ImmutableMap.of()));
264 }
265
266 @Test
267 public void substituteMethodTwoArgs() {
268 compare("\n$s.indexOf(\"bar\", 2)\n", ImmutableMap.of("s", "barbarbar"));
269 }
270
271 @Test
272 public void substituteMethodSyntheticOverloads() {
273 // If we aren't careful, we'll see both the inherited `Set<K> keySet()` from Map
274 // and the overridden `ImmutableSet<K> keySet()` in ImmutableMap.
275 compare("$map.keySet()", ImmutableMap.of("map", ImmutableMap.of("foo", "bar")));
276 }
277
278 @Test
279 public void substituteStaticMethod() {
280 compare("$Integer.toHexString(23)", ImmutableMap.of("Integer", Integer.class));
281 }
282
283 @Test
284 public void substituteStaticMethodAsInstanceMethod() {
285 compare("$i.toHexString(23)", ImmutableMap.of("i", 0));
286 }
287
288 @Test
289 public void substituteClassMethod() {
290 // This is Class.getName().
291 compare("$Integer.getName()", ImmutableMap.of("Integer", Integer.class));
292 }
293
294 /** See {@link #substituteClassOrInstanceMethod}. */
295 public static class GetName {
296 public static String getName() {
297 return "Noddy";
298 }
299 }
300
301 @Test
302 public void substituteClassOrInstanceMethod() {
303 // If the method exists as both an instance method on Class and a static method on the named
304 // class, it's the instance method that wins, so this is still Class.getName().
305 compare("$GetName.getName()", ImmutableMap.of("GetName", GetName.class));
306 }
307
308 @Test
309 public void substituteIndexNoBraces() {
310 compare("<$map[\"x\"]>", ImmutableMap.of("map", ImmutableMap.of("x", "y")));
311 }
312
313 @Test
314 public void substituteIndexWithBraces() {
315 compare("<${map[\"x\"]}>", ImmutableMap.of("map", ImmutableMap.of("x", "y")));
316 }
317
318 // Velocity allows you to write $map.foo instead of $map["foo"].
319 @Test
320 public void substituteMapProperty() {
321 compare("$map.foo", ImmutableMap.of("map", ImmutableMap.of("foo", "bar")));
322 // $map.empty is always equivalent to $map["empty"], never Map.isEmpty().
323 compare("$map.empty", ImmutableMap.of("map", ImmutableMap.of("empty", "foo")));
324 }
325
326 @Test
327 public void substituteIndexThenProperty() {
328 compare("<$map[2].name>", ImmutableMap.of("map", ImmutableMap.of(2, getClass())));
329 }
330
331 @Test
332 public void variableNameCantStartWithNonAscii() {
333 compare("<$Éamonn>", ImmutableMap.<String, Object>of());
334 }
335
336 @Test
337 public void variableNamesAreAscii() {
338 compare("<$Pádraig>", ImmutableMap.of("P", "(P)"));
339 }
340
341 @Test
342 public void variableNameCharacters() {
343 compare("<AZaz-foo_bar23>", ImmutableMap.of("AZaz-foo_bar23", "(P)"));
344 }
345
346 /**
347 * A public class with a public {@code get} method that has one argument. That means instances can
348 * be used like {@code $indexable["foo"]}.
349 */
350 public static class Indexable {
351 public String get(String y) {
352 return "[" + y + "]";
353 }
354 }
355
356 @Test
357 public void substituteExoticIndex() {
358 // Any class with a get(X) method can be used with $x[i]
359 compare("<$x[\"foo\"]>", ImmutableMap.of("x", new Indexable()));
360 }
361
362 @Test
363 public void substituteInString() {
364 String template =
365 "#foreach ($a in $list)"
366 + "#set ($s = \"THING_${foreach.index}\")"
367 + "$s,$s;"
368 + "#end";
369 compare(template, ImmutableMap.of("list", ImmutableList.of(1, 2, 3)));
370 compare("#set ($s = \"$x\") <$s>", ImmutableMap.of("x", "fred"));
371 compare("#set ($s = \"==$x$y\") <$s>", ImmutableMap.of("x", "fred", "y", "jim"));
372 compare("#set ($s = \"$x$y==\") <$s>", ImmutableMap.of("x", "fred", "y", "jim"));
373 }
374
375 @Test
376 public void stringOperationsOnSubstitution() {
377 compare("#set ($s = \"a${b}c\") $s.length()", ImmutableMap.of("b", 23));
378 }
379
380 @Test
381 public void singleQuoteNoSubstitution() {
382 compare("#set ($s = 'a${b}c') x${s}y", ImmutableMap.of("b", 23));
383 }
384
385 @Test
386 public void simpleSet() {
387 compare("$x#set ($x = 17)#set ($y = 23) ($x, $y)", ImmutableMap.of("x", 1));
388 }
389
390 @Test
391 public void newlineAfterSet() {
392 compare("foo #set ($x = 17)\nbar", ImmutableMap.<String, Object>of());
393 }
394
395 @Test
396 public void newlineInSet() {
397 compare("foo #set ($x\n = 17)\nbar $x", ImmutableMap.<String, Object>of());
398 }
399
400 @Test
401 public void expressions() {
402 compare("#set ($x = 1 + 1) $x");
403 compare("#set ($x = 1 + 2 * 3) $x");
404 compare("#set ($x = (1 + 1 == 2)) $x");
405 compare("#set ($x = (1 + 1 != 2)) $x");
406 compare("#set ($x = 22 - 7) $x");
407 compare("#set ($x = 22 / 7) $x");
408 compare("#set ($x = 22 % 7) $x");
409 }
410
411 @Test
412 public void associativity() {
413 compare("#set ($x = 3 - 2 - 1) $x");
414 compare("#set ($x = 16 / 4 / 4) $x");
415 }
416
417 @Test
418 public void precedence() {
419 compare("#set ($x = 1 + 2 + 3 * 4 * 5 + 6) $x");
420 compare("#set($x=1+2+3*4*5+6)$x");
421 compare("#set ($x = 1 + 2 * 3 == 3 * 2 + 1) $x");
422 }
423
424 @Test
425 public void and() {
426 compare("#set ($x = false && false) $x");
427 compare("#set ($x = false && true) $x");
428 compare("#set ($x = true && false) $x");
429 compare("#set ($x = true && true) $x");
430 }
431
432 @Test
433 public void or() {
434 compare("#set ($x = false || false) $x");
435 compare("#set ($x = false || true) $x");
436 compare("#set ($x = true || false) $x");
437 compare("#set ($x = true || true) $x");
438 }
439
440 @Test
441 public void not() {
442 compare("#set ($x = !true) $x");
443 compare("#set ($x = !false) $x");
444 }
445
446 @Test
447 public void truthValues() {
448 compare("#set ($x = $true && true) $x", ImmutableMap.of("true", true));
449 compare("#set ($x = $false && true) $x", ImmutableMap.of("false", false));
450 compare("#set ($x = $emptyCollection && true) $x",
451 ImmutableMap.of("emptyCollection", ImmutableList.of()));
452 compare("#set ($x = $emptyString && true) $x", ImmutableMap.of("emptyString", ""));
453 }
454
455 @Test
456 public void numbers() {
457 compare("#set ($x = 0) $x");
458 compare("#set ($x = -1) $x");
459 compare("#set ($x = " + Integer.MAX_VALUE + ") $x");
460 compare("#set ($x = " + Integer.MIN_VALUE + ") $x");
461 }
462
463 private static final String[] RELATIONS = {"==", "!=", "<", ">", "<=", ">="};
464
465 @Test
466 public void intRelations() {
467 int[] numbers = {-1, 0, 1, 17};
468 for (String relation : RELATIONS) {
469 for (int a : numbers) {
470 for (int b : numbers) {
471 compare("#set ($x = $a " + relation + " $b) $x",
472 ImmutableMap.<String, Object>of("a", a, "b", b));
473 }
474 }
475 }
476 }
477
478 @Test
479 public void relationPrecedence() {
480 compare("#set ($x = 1 < 2 == 2 < 1) $x");
481 compare("#set ($x = 2 < 1 == 2 < 1) $x");
482 }
483
484 /**
485 * Tests the surprising definition of equality mentioned in
486 * {@link ExpressionNode.BinaryExpressionNode}.
487 */
488 @Test
489 public void funkyEquals() {
490 compare("#set ($t = (123 == \"123\")) $t");
491 compare("#set ($f = (123 == \"1234\")) $f");
492 compare("#set ($x = ($sb1 == $sb2)) $x", ImmutableMap.of(
493 "sb1", (Object) new StringBuilder("123"),
494 "sb2", (Object) new StringBuilder("123")));
495 }
496
497 @Test
498 public void ifTrueNoElse() {
499 compare("x#if (true)y #end z");
500 compare("x#if (true)y #end z");
501 compare("x#if (true)y #end\nz");
502 compare("x#if (true)y #end\n z");
503 compare("x#if (true) y #end\nz");
504 compare("x#if (true)\ny #end\nz");
505 compare("x#if (true) y #end\nz");
506 compare("$x #if (true) y #end $x ", ImmutableMap.of("x", "!"));
507 }
508
509 @Test
510 public void ifFalseNoElse() {
511 compare("x#if (false)y #end z");
512 compare("x#if (false)y #end\nz");
513 compare("x#if (false)y #end\n z");
514 compare("x#if (false) y #end\nz");
515 compare("x#if (false)\ny #end\nz");
516 compare("x#if (false) y #end\nz");
517 }
518
519 @Test
520 public void ifTrueWithElse() {
521 compare("x#if (true) a #else b #end z");
522 }
523
524 @Test
525 public void ifFalseWithElse() {
526 compare("x#if (false) a #else b #end z");
527 }
528
529 @Test
530 public void ifTrueWithElseIf() {
531 compare("x#if (true) a #elseif (true) b #else c #end z");
532 }
533
534 @Test
535 public void ifFalseWithElseIfTrue() {
536 compare("x#if (false) a #elseif (true) b #else c #end z");
537 }
538
539 @Test
540 public void ifFalseWithElseIfFalse() {
541 compare("x#if (false) a #elseif (false) b #else c #end z");
542 }
543
544 @Test
545 public void ifBraces() {
546 compare("x#{if}(false)a#{elseif}(false)b #{else}c#{end}z");
547 }
548 @Test
549 public void ifUndefined() {
550 compare("#if ($undefined) really? #else indeed #end");
551 }
552
553 @Test
554 public void forEach() {
555 compare("x#foreach ($x in $c) <$x> #end y",
556 ImmutableMap.of("c", ImmutableList.of()));
557 compare("x#foreach ($x in $c) <$x> #end y",
558 ImmutableMap.of("c", ImmutableList.of("foo", "bar", "baz")));
559 compare("x#foreach ($x in $c) <$x> #end y",
560 ImmutableMap.of("c", new String[] {"foo", "bar", "baz"}));
561 compare("x#foreach ($x in $c) <$x> #end y",
562 ImmutableMap.of("c", ImmutableMap.of("foo", "bar", "baz", "buh")));
563 }
564
565 @Test
566 public void forEachHasNext() {
567 compare("x#foreach ($x in $c) <$x#if ($foreach.hasNext), #end> #end y",
568 ImmutableMap.of("c", ImmutableList.of()));
569 compare("x#foreach ($x in $c) <$x#if ($foreach.hasNext), #end> #end y",
570 ImmutableMap.of("c", ImmutableList.of("foo", "bar", "baz")));
571 }
572
573 @Test
574 public void nestedForEach() {
575 String template =
576 "$x #foreach ($x in $listOfLists)\n"
577 + " #foreach ($y in $x)\n"
578 + " ($y)#if ($foreach.hasNext), #end\n"
579 + " #end#if ($foreach.hasNext); #end\n"
580 + "#end\n"
581 + "$x\n";
582 Object listOfLists = ImmutableList.of(
583 ImmutableList.of("foo", "bar", "baz"), ImmutableList.of("fred", "jim", "sheila"));
584 compare(template, ImmutableMap.of("x", 23, "listOfLists", listOfLists));
585 }
586
587 @Test
588 public void forEachScope() {
589 String template =
590 "$x #foreach ($x in $list)\n"
591 + "[$x]\n"
592 + "#set ($x = \"bar\")\n"
593 + "#set ($othervar = \"baz\")\n"
594 + "#end\n"
595 + "$x $othervar";
596 compare(
597 template, ImmutableMap.of("x", "foo", "list", ImmutableList.of("blim", "blam", "blum")));
598 }
599
600 @Test
601 public void forEachIndex() {
602 String template =
603 "#foreach ($x in $list)"
604 + "[$foreach.index]"
605 + "#foreach ($y in $list)"
606 + "($foreach.index)==$x.$y=="
607 + "#end"
608 + "#end";
609 compare(template, ImmutableMap.of("list", ImmutableList.of("blim", "blam", "blum")));
610 }
611
612 @Test
613 public void setSpacing() {
614 // The spacing in the output from #set is eccentric.
615 compare("x#set ($x = 0)x");
616 compare("x #set ($x = 0)x");
617 compare("x #set ($x = 0) x");
618 compare("$x#set ($x = 0)x", ImmutableMap.of("x", "!"));
619
620 // Velocity WTF: the #set eats the space after $x and other references, so the output is <!x>.
621 compare("$x #set ($x = 0)x", ImmutableMap.of("x", "!"));
622 compare("$x.length() #set ($x = 0)x", ImmutableMap.of("x", "!"));
623 compare("$x.empty #set ($x = 0)x", ImmutableMap.of("x", "!"));
624 compare("$x[0] #set ($x = 0)x", ImmutableMap.of("x", ImmutableList.of("!")));
625
626 compare("x#set ($x = 0)\n $x!");
627
628 compare("x #set($x = 0) #set($x = 0) #set($x = 0) y");
629
630 compare("x ## comment\n #set($x = 0) y");
631 compare("x #* comment *# #set($x = 0) y");
632 }
633
634 @Test
635 public void simpleMacro() {
636 String template =
637 "xyz\n"
638 + "#macro (m)\n"
639 + "hello world\n"
640 + "#end\n"
641 + "#m() abc #m()\n";
642 compare(template);
643 }
644
645 @Test
646 public void macroWithArgs() {
647 String template =
648 "$x\n"
649 + "#macro (m $x $y)\n"
650 + " #if ($x < $y) less #else greater #end\n"
651 + "#end\n"
652 + "#m(17 23) #m(23 17) #m(17 17)\n"
653 + "$x";
654 compare(template, ImmutableMap.of("x", "tiddly"));
655 }
656
657 @Test
658 public void macroWithCommaSeparatedArgs() {
659 String template =
660 "$x\n"
661 + "#macro (m, $x, $y)\n"
662 + " #if ($x < $y) less #else greater #end\n"
663 + "#end\n"
664 + "#m(17 23) #m(23 17) #m(17 17)\n"
665 + "$x";
666 compare(template, ImmutableMap.of("x", "tiddly"));
667 }
668
669 /**
670 * Tests defining a macro inside a conditional. This proves that macros are not evaluated in the
671 * main control flow, but rather are extracted at parse time. It also tests what happens if there
672 * is more than one definition of the same macro. (It is not apparent from the test, but it is the
673 * first definition that is retained.)
674 */
675 @Test
676 public void conditionalMacroDefinition() {
677 String templateFalse =
678 "#if (false)\n"
679 + " #macro (m) foo #end\n"
680 + "#else\n"
681 + " #macro (m) bar #end\n"
682 + "#end\n"
683 + "#m()\n";
684 compare(templateFalse);
685
686 String templateTrue =
687 "#if (true)\n"
688 + " #macro (m) foo #end\n"
689 + "#else\n"
690 + " #macro (m) bar #end\n"
691 + "#end\n"
692 + "#m()\n";
693 compare(templateTrue);
694 }
695
696 /**
697 * Tests referencing a macro before it is defined. Since macros are extracted at parse time but
698 * references are only used at evaluation time, this works.
699 */
700 @Test
701 public void forwardMacroReference() {
702 String template =
703 "#m(17)\n"
704 + "#macro (m $x)\n"
705 + " !$x!\n"
706 + "#end";
707 compare(template);
708 }
709
710 @Test
711 public void macroArgsSeparatedBySpaces() {
712 String template =
713 "#macro (sum $x $y $z)\n"
714 + " #set ($sum = $x + $y + $z)\n"
715 + " $sum\n"
716 + "#end\n"
717 + "#sum ($list[0] $list.get(1) 5)\n";
718 compare(template, ImmutableMap.of("list", ImmutableList.of(3, 4)));
719 }
720
721 @Test
722 public void macroArgsSeparatedByCommas() {
723 String template =
724 "#macro (sum $x $y $z)\n"
725 + " #set ($sum = $x + $y + $z)\n"
726 + " $sum\n"
727 + "#end\n"
728 + "#sum ($list[0],$list.get(1),5)\n";
729 compare(template, ImmutableMap.of("list", ImmutableList.of(3, 4)));
730 }
731
732 // The following tests are based on http://wiki.apache.org/velocity/MacroEvaluationStrategy.
733 // They verify some of the trickier details of Velocity's call-by-name semantics.
734
735 @Test
736 public void callBySharing() {
737 // The example on the web page is wrong because $map.put('x', 'a') evaluates to null, which
738 // Velocity rejects as a render error. We fix this by ensuring that the returned previous value
739 // is not null.
740 // Here, the value of $y should not be affected by #set($x = "a"), even though the name passed
741 // to $x is $y.
742 String template =
743 "#macro(callBySharing $x $map)\n"
744 + " #set($x = \"a\")\n"
745 + " $map.put(\"x\", \"a\")\n"
746 + "#end\n"
747 + "#callBySharing($y $map)\n"
748 + "y is $y\n"
749 + "map[x] is $map[\"x\"]\n";
750 Supplier<Map<String, Object>> makeMap = new Supplier<Map<String, Object>>() {
751 @Override public Map<String, Object> get() {
752 return ImmutableMap.<String, Object>of(
753 "y", "y",
754 "map", new HashMap<String, Object>(ImmutableMap.of("x", (Object) "foo")));
755 }
756 };
757 compare(template, makeMap);
758 }
759
760 @Test
761 public void callByMacro() {
762 // Since #callByMacro1 never references its argument, $x.add("t") is never evaluated during it.
763 // Since #callByMacro2 references its argument twice, $x.add("t") is evaluated twice during it.
764 String template =
765 "#macro(callByMacro1 $p)\n"
766 + " not using\n"
767 + "#end\n"
768 + "#macro(callByMacro2 $p)\n"
769 + " using: $p\n"
770 + " using again: $p\n"
771 + " using again: $p\n"
772 + "#end\n"
773 + "#callByMacro1($x.add(\"t\"))\n"
774 + "x = $x\n"
775 + "#callByMacro2($x.add(\"t\"))\n"
776 + "x = $x\n";
777 Supplier<Map<String, Object>> makeMap = new Supplier<Map<String, Object>>() {
778 @Override public Map<String, Object> get() {
779 return ImmutableMap.<String, Object>of("x", new ArrayList<Object>());
780 }
781 };
782 compare(template, makeMap);
783 }
784
785 @Test
786 public void callByValue() {
787 // The assignments to the macro parameters $a and $b cause those parameters to be shadowed,
788 // so the output is: a b becomes b a.
789 String template =
790 "#macro(callByValueSwap $a $b)\n"
791 + " $a $b becomes\n"
792 + " #set($tmp = $a)\n"
793 + " #set($a = $b)\n"
794 + " #set($b = $tmp)\n"
795 + " $a $b\n"
796 + "#end"
797 + "#callByValueSwap(\"a\", \"b\")";
798 compare(template);
799 }
800
801 // First "Call by macro expansion example" doesn't apply as long as we don't have map literals.
802
803 @Test
804 public void nameCaptureSwap() {
805 // Here, the arguments $a and $b are variables rather than literals, which means that their
806 // values change when we set those variables. #set($tmp = $a) changes the meaning of $b since
807 // $b is the name $tmp. So #set($a = $b) shadows parameter $a with the value of $tmp, which we
808 // have just set to "a". Then #set($b = $tmp) shadows parameter $b also with the value of $tmp.
809 // The end result is: a b becomes a a.
810 String template =
811 "#macro(nameCaptureSwap $a $b)\n"
812 + " $a $b becomes\n"
813 + " #set($tmp = $a)\n"
814 + " #set($a = $b)\n"
815 + " #set($b = $tmp)\n"
816 + " $a $b\n"
817 + "#end\n"
818 + "#set($x = \"a\")\n"
819 + "#set($tmp = \"b\")\n"
820 + "#nameCaptureSwap($x $tmp)";
821 compare(template);
822 }
823
824 @Test
825 public void badBraceReference() {
826 String template = "line 1\nline 2\nbar${foo.!}baz";
827 expectParseException(template, "Expected }, on line 3, at text starting: .!}baz");
828 }
829
830 @Test
831 public void undefinedMacro() {
832 String template = "#oops()";
833 expectParseException(
834 template,
835 "#oops is neither a standard directive nor a macro that has been defined");
836 }
837
838 @Test
839 public void macroArgumentMismatch() {
840 String template =
841 "#macro (twoArgs $a $b) $a $b #end\n"
842 + "#twoArgs(23)\n";
843 expectParseException(template, "Wrong number of arguments to #twoArgs: expected 2, got 1");
844 }
845
846 @Test
847 public void unclosedBlockQuote() {
848 String template = "foo\nbar #[[\nblah\nblah";
849 expectParseException(template, "Unterminated #[[ - did not see matching ]]#, on line 2");
850 }
851
852 @Test
853 public void unclosedBlockComment() {
854 compare("foo\nbar #*\nblah\nblah");
855 }
856
857 /**
858 * A Velocity ResourceLoader that looks resources up in a map. This allows us to test directives
859 * that read "resources", for example {@code #parse}, without needing to make separate files to
860 * put them in.
861 */
862 private static final class MapResourceLoader extends ResourceLoader {
863 private final ImmutableMap<String, String> resourceMap;
864
865 MapResourceLoader(ImmutableMap<String, String> resourceMap) {
866 this.resourceMap = resourceMap;
867 }
868
869 @Override
870 public void init(ExtendedProperties configuration) {
871 }
872
873 @Override
874 public InputStream getResourceStream(String source) {
875 String resource = resourceMap.get(source);
876 if (resource == null) {
877 throw new ResourceNotFoundException(source);
878 }
879 return new ByteArrayInputStream(resource.getBytes(StandardCharsets.ISO_8859_1));
880 }
881
882 @Override
883 public boolean isSourceModified(Resource resource) {
884 return false;
885 }
886
887 @Override
888 public long getLastModified(Resource resource) {
889 return 0;
890 }
891 };
892
893 private String renderWithResources(
894 String templateResourceName,
895 ImmutableMap<String, String> resourceMap,
896 ImmutableMap<String, String> vars) {
897 MapResourceLoader mapResourceLoader = new MapResourceLoader(resourceMap);
898 RuntimeInstance runtimeInstance = newVelocityRuntimeInstance();
899 runtimeInstance.setProperty("resource.loader", "map");
900 runtimeInstance.setProperty("map.resource.loader.instance", mapResourceLoader);
901 runtimeInstance.init();
902 org.apache.velocity.Template velocityTemplate =
903 runtimeInstance.getTemplate(templateResourceName);
904 StringWriter velocityWriter = new StringWriter();
905 VelocityContext velocityContext = new VelocityContext(new TreeMap<>(vars));
906 velocityTemplate.merge(velocityContext, velocityWriter);
907 return velocityWriter.toString();
908 }
909
910 @Test
911 public void parseDirective() throws IOException {
912 // If outer.vm does #parse("nested.vm"), then we should be able to #set a variable in
913 // nested.vm and use it in outer.vm, and we should be able to define a #macro in nested.vm
914 // and call it in outer.vm.
915 ImmutableMap<String, String> resources = ImmutableMap.of(
916 "outer.vm",
917 "first line\n"
918 + "#parse (\"nested.vm\")\n"
919 + "<#decorate (\"left\" \"right\")>\n"
920 + "$baz skidoo\n"
921 + "last line\n",
922 "nested.vm",
923 "nested template first line\n"
924 + "[#if ($foo == $bar) equal #else not equal #end]\n"
925 + "#macro (decorate $a $b) < $a | $b > #end\n"
926 + "#set ($baz = 23)\n"
927 + "nested template last line\n");
928
929 ImmutableMap<String, String> vars = ImmutableMap.of("foo", "foovalue", "bar", "barvalue");
930
931 String velocityResult = renderWithResources("outer.vm", resources, vars);
932
933 Template.ResourceOpener resourceOpener = resourceName -> {
934 String resource = resources.get(resourceName);
935 if (resource == null) {
936 throw new FileNotFoundException(resourceName);
937 }
938 return new StringReader(resource);
939 };
940 Template template = Template.parseFrom("outer.vm", resourceOpener);
941
942 String result = template.evaluate(vars);
943 assertThat(result).isEqualTo(velocityResult);
944
945 ImmutableMap<String, String> badVars = ImmutableMap.of("foo", "foovalue");
946 try {
947 template.evaluate(badVars);
948 fail();
949 } catch (EvaluationException e) {
950 assertThat(e).hasMessageThat().isEqualTo(
951 "In expression on line 2 of nested.vm: Undefined reference $bar");
952 }
953 }
954 }