View Javadoc

1   /**
2    * Copyright (c) 2008-2012, http://www.snakeyaml.org
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 org.yaml.snakeyaml.issues.issue139;
17  
18  import java.util.Map;
19  
20  import junit.framework.TestCase;
21  
22  import org.yaml.snakeyaml.Util;
23  import org.yaml.snakeyaml.Yaml;
24  
25  public class MergeValueTest extends TestCase {
26  
27      public void testNotUniqueSimple() {
28          String simple = "{key: 1, key: 2}";
29          Yaml yaml = new Yaml();
30          @SuppressWarnings("unchecked")
31          Map<String, Integer> map = (Map<String, Integer>) yaml.load(simple);
32          assertEquals(1, map.size());
33          assertEquals(new Integer(2), map.get("key"));
34      }
35  
36      public void testMerge() {
37          check("issues/issue139-1.yaml");// merge with unique keys
38          check("issues/issue139-2.yaml");// merge with same key
39      }
40  
41      private void check(String name) {
42          String input = Util.getLocalResource(name);
43          // System.out.println(input);
44          Yaml yaml = new Yaml();
45          @SuppressWarnings("unchecked")
46          Map<String, Object> map = (Map<String, Object>) yaml.load(input);
47          assertEquals(2, map.size());
48          assertTrue(map.containsKey("common"));
49          assertTrue(map.containsKey("production"));
50          assertEquals(map.get("common"), map.get("production"));
51      }
52  
53      /**
54       * http://yaml.org/type/merge.html: If the value associated with the key is
55       * a single mapping node, each of its key/value pairs is inserted into the
56       * current mapping, <b>unless the key already exists in it</b>.
57       */
58      @SuppressWarnings("unchecked")
59      public void testMergeUnlessAlreadyExists() {
60          String input = Util.getLocalResource("issues/issue139-3.yaml");
61          // System.out.println(input);
62          Yaml yaml = new Yaml();
63          Map<String, Object> map = (Map<String, Object>) yaml.load(input);
64          assertEquals(2, map.size());
65          Map<String, Integer> common = (Map<String, Integer>) map.get("common");
66          Map<String, Integer> production = (Map<String, Integer>) map.get("production");
67          assertEquals(new Integer(2), common.get("key"));
68          assertEquals(new Integer(3), production.get("key"));
69      }
70  }