60220246a25412d2602277a23f3869ff39951459
[yangtools.git] / data / yang-data-impl / src / test / java / org / opendaylight / yangtools / yang / data / impl / codec / YT1097Test.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.data.impl.codec;
9
10 import static org.hamcrest.CoreMatchers.instanceOf;
11 import static org.hamcrest.MatcherAssert.assertThat;
12 import static org.junit.Assert.assertEquals;
13
14 import org.junit.Test;
15 import org.opendaylight.yangtools.yang.common.QName;
16 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
17 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
18 import org.opendaylight.yangtools.yang.model.api.Module;
19 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
20
21 public class YT1097Test {
22     @Test
23     public void testBooleanStringUnion() {
24         final Module module = YangParserTestUtils.parseYang("""
25             module yt1097 {
26               namespace yt1097;
27               prefix yt1097;
28
29               leaf foo {
30                 type union {
31                   type boolean;
32                   type string;
33                 }
34               }
35             }""").findModule("yt1097").orElseThrow();
36         final DataSchemaNode foo = module.findDataChildByName(QName.create(module.getQNameModule(), "foo"))
37                 .orElseThrow();
38         assertThat(foo, instanceOf(LeafSchemaNode.class));
39
40         final TypeDefinitionAwareCodec<?, ?> codec = TypeDefinitionAwareCodec.from(((LeafSchemaNode) foo).getType());
41         assertThat(codec, instanceOf(UnionStringCodec.class));
42
43         assertDecoded(codec, Boolean.TRUE, "true");
44         assertDecoded(codec, Boolean.FALSE, "false");
45         assertDecoded(codec, "True");
46         assertDecoded(codec, "TRUE");
47         assertDecoded(codec, "False");
48         assertDecoded(codec, "FALSE");
49     }
50
51     private static void assertDecoded(final TypeDefinitionAwareCodec<?, ?> codec, final String input) {
52         assertDecoded(codec, input, input);
53     }
54
55     private static void assertDecoded(final TypeDefinitionAwareCodec<?, ?> codec, final Object expected,
56             final String input) {
57         final Object result = codec.deserialize(input);
58         assertThat(result, instanceOf(expected.getClass()));
59         assertEquals(expected, result);
60     }
61 }