View Javadoc

    1   /**
    2    * Copyright (c) 2008-2011, 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
    17  package examples;
    18
    19  import java.io.IOException;
    20  import java.util.List;
    21
    22  import junit.framework.TestCase;
    23
    24  import org.yaml.snakeyaml.Yaml;
    25  import org.yaml.snakeyaml.constructor.SafeConstructor;
    26
    27  public class SafeConstructorExampleTest extends TestCase {
    28      @SuppressWarnings("unchecked")
    29      public void testConstruct() throws IOException {
    30          String doc = "- 5\n- Person\n- true";
    31          Yaml yaml = new Yaml(new SafeConstructor());
    32          List<Object> list = (List<Object>) yaml.load(doc);
    33          assertEquals(3, list.size());
    34          assertEquals(new Integer(5), list.get(0));
    35          assertEquals("Person", list.get(1));
    36          assertEquals(Boolean.TRUE, list.get(2));
    37      }
    38
    39      public void testSafeConstruct() throws IOException {
    40          String doc = "- 5\n- !org.yaml.snakeyaml.constructor.Person\n  firstName: Andrey\n  age: 99\n- true";
    41          Yaml yaml = new Yaml(new SafeConstructor());
    42          try {
    43              yaml.load(doc);
    44              fail("Custom Java classes should not be created.");
    45          } catch (Exception e) {
    46              assertEquals(
    47                      "null; could not determine a constructor for the tag !org.yaml.snakeyaml.constructor.Person",
    48                      e.getMessage());
    49          }
    50      }
    51  }