1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.yaml.snakeyaml.emitter.template;
18
19 import java.io.StringWriter;
20 import java.util.ArrayList;
21 import java.util.List;
22
23 import junit.framework.TestCase;
24
25 import org.apache.velocity.Template;
26 import org.apache.velocity.VelocityContext;
27 import org.apache.velocity.app.VelocityEngine;
28 import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
29 import org.yaml.snakeyaml.DumperOptions;
30 import org.yaml.snakeyaml.Util;
31 import org.yaml.snakeyaml.Yaml;
32 import org.yaml.snakeyaml.immutable.Point;
33
34 public class VelocityTest extends TestCase {
35 public void testNoTemplate() {
36 DumperOptions options = new DumperOptions();
37 options.setAllowReadOnlyProperties(true);
38 Yaml yaml = new Yaml(options);
39 String output = yaml.dumpAsMap(createBean());
40
41 assertEquals(Util.getLocalResource("template/etalon1.yaml"), output);
42 }
43
44 public void testTemplate1() throws Exception {
45 VelocityContext context = new VelocityContext();
46 MyBean bean = createBean();
47 context.put("bean", bean);
48 Yaml yaml = new Yaml();
49 context.put("list", yaml.dump(bean.getList()));
50 VelocityEngine ve = new VelocityEngine();
51 ve.setProperty("file.resource.loader.class", ClasspathResourceLoader.class.getName());
52 ve.init();
53 Template t = ve.getTemplate("template/mybean1.vm");
54 StringWriter writer = new StringWriter();
55 t.merge(context, writer);
56 String output = writer.toString().trim().replaceAll("\\r\\n", "\n");
57
58 String etalon = Util.getLocalResource("template/etalon2-template.yaml").trim();
59 assertEquals(etalon.length(), output.length());
60 assertEquals(etalon, output);
61
62 Yaml loader = new Yaml();
63 MyBean parsedBean = loader.loadAs(output, MyBean.class);
64 assertEquals(bean, parsedBean);
65 }
66
67 private MyBean createBean() {
68 MyBean bean = new MyBean();
69 bean.setId("id123");
70 List<String> list = new ArrayList<String>();
71 list.add("aaa");
72 list.add("bbb");
73 list.add("ccc");
74 bean.setList(list);
75 Point p = new Point(1.0, 2.0);
76 bean.setPoint(p);
77 return bean;
78 }
79 }