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