1 package test.mustache; 2 3 import java.io.IOException; 4 import java.util.ArrayList; 5 import java.util.Arrays; 6 import java.util.Collections; 7 import java.util.List; 8 import java.util.Map; 9 10 import org.testng.Assert; 11 import org.testng.annotations.DataProvider; 12 import org.testng.annotations.Test; 13 import org.testng.collections.Maps; 14 import org.testng.mustache.Mustache; 15 16 @Test 17 public class MustacheTest { 18 19 public static class Person { 20 public String name; Person(String n)21 public Person(String n) { 22 name = n; 23 } 24 } 25 26 public static class Age { 27 public int age; Age(int a)28 public Age(int a) { 29 this.age = a; 30 } 31 } 32 33 private static final List<Person> PEOPLE = new ArrayList<>( 34 Arrays.asList(new Person("Carl"), new Person("Christopher"))); 35 36 private static final List<Age> AGES = new ArrayList<>( 37 Arrays.asList(new Age(42), new Age(43))); 38 39 @DataProvider dp()40 public Object[][] dp() { 41 return new Object[][] { 42 // Simple 43 new Object[] { 44 create("one", "ello", "two", "orld"), 45 "H{{one}} W{{two}}", 46 "Hello World" 47 }, 48 // Null condition 49 new Object[] { 50 Collections.emptyMap(), 51 "E{{#foo}}xxx{{/foo}}lephant", 52 "Elephant" 53 }, 54 // Null condition with new line 55 new Object[] { 56 Collections.emptyMap(), 57 "Hello\n{{#foo}}@\n{{/foo}}World", 58 "Hello\nWorld" 59 }, 60 // Simple scope 61 new Object[] { 62 create("person", new Person("John"), "day", "Monday"), 63 "Hello {{#person}}{{name}}{{/person}}, {{day}}", 64 "Hello John, Monday" 65 }, 66 // Scope with shadowing 67 new Object[] { 68 create("person", new Person("John"), "name", "Carl"), 69 "Hello {{#person}}{{name}}{{/person}}, {{name}}", 70 "Hello John, Carl" 71 }, 72 // Test iteration 73 new Object[] { 74 create("people", PEOPLE), 75 "People:@{{#people}}-{{/people}}!", 76 "People:@--!", 77 }, 78 // Nested scopes 79 new Object[] { 80 create("people", PEOPLE, "ages", AGES), 81 ":@{{#people}}{{name}}{{#ages}}{{age}}{{/ages}}@{{/people}}!_", 82 ":@Carl4243@Christopher4243@!_", 83 }, 84 }; 85 } 86 create(Object... objects)87 private Map<String, Object> create(Object... objects) { 88 Map<String, Object> result = Maps.newHashMap(); 89 for (int i = 0; i < objects.length; i += 2) { 90 result.put((String) objects[i], objects[i + 1]); 91 } 92 return result; 93 } 94 95 @Test(dataProvider = "dp") runTest(Map<String, Object> model, String template, String expected)96 public void runTest(Map<String, Object> model, String template, String expected) 97 throws IOException { 98 // InputStream is = new StringInputStream(template); 99 Assert.assertEquals(new Mustache().run(template, model), expected); 100 } 101 102 } 103