1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.yaml.snakeyaml.issues.issue73;
17
18 import java.util.Set;
19 import java.util.TreeSet;
20
21 import junit.framework.TestCase;
22
23 import org.yaml.snakeyaml.DumperOptions;
24 import org.yaml.snakeyaml.DumperOptions.FlowStyle;
25 import org.yaml.snakeyaml.Util;
26 import org.yaml.snakeyaml.Yaml;
27 import org.yaml.snakeyaml.introspector.BeanAccess;
28 import org.yaml.snakeyaml.nodes.Node;
29 import org.yaml.snakeyaml.nodes.Tag;
30 import org.yaml.snakeyaml.representer.Represent;
31 import org.yaml.snakeyaml.representer.Representer;
32
33 public class DumpSetAsSequenceExampleTest extends TestCase {
34
35 public void testDumpFlow() {
36 DumperOptions options = new DumperOptions();
37 options.setAllowReadOnlyProperties(true);
38 Yaml yaml = new Yaml(new SetRepresenter(), options);
39 String output = yaml.dump(createBlog());
40
41 assertEquals(Util.getLocalResource("issues/issue73-dump7.txt"), output);
42
43 check(output);
44 }
45
46 public void testDumpBlock() {
47 DumperOptions options = new DumperOptions();
48 options.setAllowReadOnlyProperties(true);
49 options.setDefaultFlowStyle(FlowStyle.BLOCK);
50 Yaml yaml = new Yaml(new SetRepresenter(), options);
51 String output = yaml.dump(createBlog());
52
53 assertEquals(Util.getLocalResource("issues/issue73-dump8.txt"), output);
54
55 check(output);
56 }
57
58 private class SetRepresenter extends Representer {
59 public SetRepresenter() {
60 this.multiRepresenters.put(Set.class, new RepresentIterable());
61 }
62
63 private class RepresentIterable implements Represent {
64 @SuppressWarnings("unchecked")
65 public Node representData(Object data) {
66 return representSequence(getTag(data.getClass(), Tag.SEQ), (Iterable<Object>) data,
67 null);
68
69 }
70 }
71 }
72
73 private Blog createBlog() {
74 Blog blog = new Blog("Test Me!");
75 blog.addPost(new Post("Title1", "text 1"));
76 blog.addPost(new Post("Title2", "text text 2"));
77 blog.numbers.add(19);
78 blog.numbers.add(17);
79 TreeSet<String> labels = new TreeSet<String>();
80 labels.add("Java");
81 labels.add("YAML");
82 labels.add("SnakeYAML");
83 blog.setLabels(labels);
84 return blog;
85 }
86
87 private void check(String doc) {
88 Yaml yamlLoader = new Yaml();
89 yamlLoader.setBeanAccess(BeanAccess.FIELD);
90 Blog blog = (Blog) yamlLoader.load(doc);
91 assertEquals("Test Me!", blog.getName());
92 assertEquals(2, blog.numbers.size());
93 assertEquals(2, blog.getPosts().size());
94 for (Post post : blog.getPosts()) {
95 assertEquals(Post.class, post.getClass());
96 }
97 }
98 }