Use Object.requireNonNull
[netconf.git] / netconf / mdsal-netconf-connector / src / test / java / org / opendaylight / netconf / mdsal / connector / ops / get / FilterContentValidatorTest.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. 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.netconf.mdsal.connector.ops.get;
9
10 import static java.util.Objects.requireNonNull;
11 import static org.mockito.Mockito.doReturn;
12 import static org.mockito.Mockito.mock;
13
14 import java.nio.file.Files;
15 import java.nio.file.Path;
16 import java.nio.file.Paths;
17 import java.util.ArrayList;
18 import java.util.Arrays;
19 import java.util.Collection;
20 import java.util.HashMap;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
25 import org.junit.Assert;
26 import org.junit.Before;
27 import org.junit.Test;
28 import org.junit.runner.RunWith;
29 import org.junit.runners.Parameterized;
30 import org.junit.runners.model.InitializationError;
31 import org.opendaylight.netconf.api.xml.XmlElement;
32 import org.opendaylight.netconf.api.xml.XmlUtil;
33 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
34 import org.opendaylight.yangtools.yang.common.QName;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
36 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
37 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
38 import org.w3c.dom.Document;
39
40 @RunWith(value = Parameterized.class)
41 public class FilterContentValidatorTest {
42
43     private static final int TEST_CASE_COUNT = 13;
44     private static final Pattern LIST_ENTRY_PATTERN =
45             Pattern.compile("(?<listName>.*)\\[\\{(?<keys>(.*)(, .*)*)\\}\\]");
46     private static final Pattern KEY_VALUE_PATTERN =
47             Pattern.compile("(?<key>\\(.*\\).*)=(?<value>.*)");
48     private final XmlElement filterContent;
49     private final String expected;
50     private FilterContentValidator validator;
51
52     @Parameterized.Parameters
53     public static Collection<Object[]> data() throws Exception {
54         final List<Object[]> result = new ArrayList<>();
55         final Path path = Paths.get(FilterContentValidatorTest.class.getResource("/filter/expected.txt").toURI());
56         final List<String> expected = Files.readAllLines(path);
57         if (expected.size() != TEST_CASE_COUNT) {
58             throw new InitializationError("Number of lines in results file must be same as test case count");
59         }
60         for (int i = 1; i <= TEST_CASE_COUNT; i++) {
61             final Document document = XmlUtil.readXmlToDocument(FilterContentValidatorTest.class.getResourceAsStream(
62                     "/filter/f" + i + ".xml"));
63             result.add(new Object[]{document, expected.get(i - 1)});
64         }
65         return result;
66     }
67
68     public FilterContentValidatorTest(final Document filterContent, final String expected) {
69         this.filterContent = XmlElement.fromDomDocument(filterContent);
70         this.expected = expected;
71     }
72
73     @Before
74     public void setUp() throws Exception {
75         final SchemaContext context = YangParserTestUtils.parseYangResources(FilterContentValidatorTest.class,
76             "/yang/filter-validator-test-mod-0.yang", "/yang/filter-validator-test-augment.yang",
77             "/yang/mdsal-netconf-mapping-test.yang");
78
79         final CurrentSchemaContext currentContext = mock(CurrentSchemaContext.class);
80         doReturn(context).when(currentContext).getCurrentContext();
81         validator = new FilterContentValidator(currentContext);
82     }
83
84     @SuppressWarnings("checkstyle:IllegalCatch")
85     @Test
86     public void testValidate() throws Exception {
87         if (expected.startsWith("success")) {
88             final String expId = expected.replace("success=", "");
89             final YangInstanceIdentifier actual = validator.validate(filterContent);
90             Assert.assertEquals(fromString(expId), actual);
91         } else if (expected.startsWith("error")) {
92             try {
93                 validator.validate(filterContent);
94                 Assert.fail(XmlUtil.toString(filterContent) + " is not valid and should throw exception.");
95             } catch (final Exception e) {
96                 final String expectedExceptionClass = expected.replace("error=", "");
97                 Assert.assertEquals(expectedExceptionClass, e.getClass().getName());
98             }
99         }
100     }
101
102     private static YangInstanceIdentifier fromString(final String input) {
103         //remove first /
104         final String yid = input.substring(1);
105         final List<String> pathElements = Arrays.asList(yid.split("/"));
106         final YangInstanceIdentifier.InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
107         //if not specified, PathArguments inherit namespace and revision from previous PathArgument
108         QName prev = null;
109         for (final String pathElement : pathElements) {
110             final Matcher matcher = LIST_ENTRY_PATTERN.matcher(pathElement);
111             if (matcher.matches()) {
112                 prev = parseListEntry(builder, prev, matcher);
113             } else {
114                 final QName qName = createNodeQName(prev, pathElement);
115                 builder.node(qName);
116                 prev = qName;
117             }
118         }
119         return builder.build();
120     }
121
122     private static QName parseListEntry(final YangInstanceIdentifier.InstanceIdentifierBuilder builder,
123                                         final QName prev, final Matcher matcher) {
124         final Map<QName, Object> keys = new HashMap<>();
125         final String listName = matcher.group("listName");
126         final QName listQName = createNodeQName(prev, listName);
127         final String keysString = matcher.group("keys");
128         final String[] split = keysString.split(",");
129         for (final String s : split) {
130             final Matcher keyMatcher = KEY_VALUE_PATTERN.matcher(s.trim());
131             if (keyMatcher.matches()) {
132                 final QName keyName = QName.create(keyMatcher.group("key"));
133                 final String keyValue = keyMatcher.group("value");
134                 keys.put(keyName, keyValue);
135             }
136         }
137         builder.nodeWithKey(listQName, keys);
138         return prev;
139     }
140
141     private static QName createNodeQName(final QName prev, final String input) {
142         try {
143             return QName.create(input);
144         } catch (IllegalArgumentException e) {
145             return QName.create(requireNonNull(prev), input);
146         }
147     }
148 }