xref: /aosp_15_r20/external/snakeyaml/src/test/java/examples/CustomImplicitResolverTest.java (revision ac2a7c1bf4e14d82f3bd566dcc2d76d5b42faf34)
1 /**
2  * Copyright (c) 2008, SnakeYAML
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 package examples;
15 
16 import java.math.BigDecimal;
17 import java.util.Map;
18 import java.util.regex.Pattern;
19 import junit.framework.TestCase;
20 import org.yaml.snakeyaml.Yaml;
21 import org.yaml.snakeyaml.constructor.AbstractConstruct;
22 import org.yaml.snakeyaml.constructor.SafeConstructor;
23 import org.yaml.snakeyaml.nodes.Node;
24 import org.yaml.snakeyaml.nodes.ScalarNode;
25 import org.yaml.snakeyaml.nodes.Tag;
26 
27 /**
28  * Use custom implicit resolver when the runtime class is not defined.
29  * http://code.google.com/p/snakeyaml/issues/detail?id=75
30  */
31 public class CustomImplicitResolverTest extends TestCase {
32 
33   private final Tag CUSTOM_TAG = new Tag("!BigDecimalDividedBy100");
34   private final Pattern CUSTOM_PATTERN = Pattern.compile("\\d+%");
35 
36   @SuppressWarnings("unchecked")
testImplicit()37   public void testImplicit() {
38     Yaml yaml = new Yaml(new BigConstructor());
39     yaml.addImplicitResolver(CUSTOM_TAG, CUSTOM_PATTERN, "-0123456789");
40     Map<String, Object> obj = yaml.load("bar: 50%");
41     assertEquals("0.5", obj.get("bar").toString());
42     assertEquals(BigDecimal.class, obj.get("bar").getClass());
43   }
44 
testImplicitFailure()45   public void testImplicitFailure() {
46     Yaml yaml = new Yaml(new BigConstructor());
47     yaml.addImplicitResolver(CUSTOM_TAG, Pattern.compile("\\d+%"), "-0123456789");
48     try {
49       yaml.load("bar: !!float 50%");
50       fail("Both implicit and explicit are present.");
51     } catch (NumberFormatException e) {
52       assertEquals("For input string: \"50%\"", e.getMessage());
53     }
54   }
55 
56   class BigConstructor extends SafeConstructor {
57 
BigConstructor()58     public BigConstructor() {
59       this.yamlConstructors.put(CUSTOM_TAG, new ConstructBig());
60     }
61 
62     private class ConstructBig extends AbstractConstruct {
63 
construct(Node node)64       public Object construct(Node node) {
65         String val = constructScalar((ScalarNode) node);
66         return new BigDecimal(val.substring(0, val.length() - 1)).divide(new BigDecimal(100));
67       }
68     }
69   }
70 }
71