116139dc3d1ee694cbe6d460861f6cce28bde681
[netconf.git] / restconf / restconf-nb-rfc8040 / src / test / java / org / opendaylight / restconf / nb / rfc8040 / utils / mapping / RestconfMappingNodeUtilTest.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.restconf.nb.rfc8040.utils.mapping;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.mockito.Mockito.when;
13
14 import java.net.URI;
15 import java.time.Instant;
16 import java.time.OffsetDateTime;
17 import java.time.ZoneId;
18 import java.time.format.DateTimeFormatter;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.HashMap;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Set;
25 import org.junit.Assert;
26 import org.junit.Before;
27 import org.junit.BeforeClass;
28 import org.junit.Rule;
29 import org.junit.Test;
30 import org.junit.rules.ExpectedException;
31 import org.mockito.Mock;
32 import org.mockito.MockitoAnnotations;
33 import org.opendaylight.restconf.nb.rfc8040.Rfc8040.IetfYangLibrary;
34 import org.opendaylight.restconf.nb.rfc8040.Rfc8040.MonitoringModule;
35 import org.opendaylight.restconf.nb.rfc8040.Rfc8040.MonitoringModule.QueryParams;
36 import org.opendaylight.restconf.nb.rfc8040.Rfc8040.RestconfModule;
37 import org.opendaylight.restconf.nb.rfc8040.TestRestconfUtils;
38 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
39 import org.opendaylight.yangtools.yang.common.QName;
40 import org.opendaylight.yangtools.yang.common.Revision;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
44 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
46 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
52 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.Module;
55 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
56 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59
60 /**
61  * Unit tests for {@link RestconfMappingNodeUtil}.
62  */
63 public class RestconfMappingNodeUtilTest {
64
65     private static final Logger LOG = LoggerFactory.getLogger(RestconfMappingNodeUtilTest.class);
66
67     @Rule
68     public ExpectedException thrown = ExpectedException.none();
69
70     @Mock private ListSchemaNode mockStreamList;
71     @Mock private LeafSchemaNode leafName;
72     @Mock private LeafSchemaNode leafDescription;
73     @Mock private LeafSchemaNode leafReplaySupport;
74     @Mock private LeafSchemaNode leafReplayLog;
75     @Mock private LeafSchemaNode leafEvents;
76
77     private static Set<Module> modules;
78     private static SchemaContext schemaContext;
79     private static SchemaContext schemaContextMonitoring;
80
81     private static Set<Module> modulesRest;
82
83     @BeforeClass
84     public static void loadTestSchemaContextAndModules() throws Exception {
85         schemaContext =
86                 YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/modules/restconf-module-testing"));
87         schemaContextMonitoring = YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/modules"));
88         modules = schemaContextMonitoring.getModules();
89         modulesRest = YangParserTestUtils
90                 .parseYangFiles(TestRestconfUtils.loadFiles("/modules/restconf-module-testing")).getModules();
91     }
92
93     @Before
94     public void setup() throws Exception {
95         MockitoAnnotations.initMocks(this);
96
97         when(this.leafName.getQName()).thenReturn(QName.create("", RestconfMappingNodeConstants.NAME));
98         when(this.leafDescription.getQName()).thenReturn(QName.create("", RestconfMappingNodeConstants.DESCRIPTION));
99         when(this.leafReplaySupport.getQName()).thenReturn(
100                 QName.create("", RestconfMappingNodeConstants.REPLAY_SUPPORT));
101         when(this.leafReplayLog.getQName()).thenReturn(QName.create("", RestconfMappingNodeConstants.REPLAY_LOG));
102         when(this.leafEvents.getQName()).thenReturn(QName.create("", RestconfMappingNodeConstants.EVENTS));
103     }
104
105     /**
106      * Test of writing modules into {@link RestconfModule#MODULE_LIST_SCHEMA_NODE} and checking if modules were
107      * correctly written.
108      */
109     @Test
110     public void restconfMappingNodeTest() {
111         // write modules into list module in Restconf
112         final Module ietfYangLibMod = schemaContext.findModule(IetfYangLibrary.MODULE_QNAME).get();
113         final NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> mods =
114                 RestconfMappingNodeUtil.mapModulesByIetfYangLibraryYang(RestconfMappingNodeUtilTest.modules,
115                         ietfYangLibMod, schemaContext, "1");
116
117         // verify loaded modules
118         verifyLoadedModules((ContainerNode) mods);
119     }
120
121     @Test
122     public void restconfStateCapabilitesTest() {
123         final Module monitoringModule = schemaContextMonitoring.findModule(MonitoringModule.MODULE_QNAME).get();
124         final NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> normNode =
125                 RestconfMappingNodeUtil.mapCapabilites(monitoringModule);
126         assertNotNull(normNode);
127         final List<Object> listOfValues = new ArrayList<>();
128
129         for (final DataContainerChild<? extends PathArgument, ?> child : normNode.getValue()) {
130             if (child.getNodeType().equals(MonitoringModule.CONT_CAPABILITES_QNAME)) {
131                 for (final DataContainerChild<? extends PathArgument, ?> dataContainerChild : ((ContainerNode) child)
132                         .getValue()) {
133                     for (final Object entry : ((LeafSetNode<?>) dataContainerChild).getValue()) {
134                         listOfValues.add(((LeafSetEntryNode<?>) entry).getValue());
135                     }
136                 }
137             }
138         }
139         Assert.assertTrue(listOfValues.contains(QueryParams.DEPTH));
140         Assert.assertTrue(listOfValues.contains(QueryParams.FIELDS));
141         Assert.assertTrue(listOfValues.contains(QueryParams.FILTER));
142         Assert.assertTrue(listOfValues.contains(QueryParams.REPLAY));
143         Assert.assertTrue(listOfValues.contains(QueryParams.WITH_DEFAULTS));
144     }
145
146     @Test
147     public void toStreamEntryNodeTest() throws Exception {
148         final YangInstanceIdentifier path = ParserIdentifier.toInstanceIdentifier(
149                 "nested-module:depth1-cont/depth2-leaf1", schemaContextMonitoring, null).getInstanceIdentifier();
150         final Instant start = Instant.now();
151         final String outputType = "XML";
152         final URI uri = new URI("uri");
153         final Module monitoringModule = schemaContextMonitoring.findModule(MonitoringModule.MODULE_QNAME).orElse(null);
154         final boolean exist = true;
155
156         final Map<QName, Object> map =
157                 prepareMap(path.getLastPathArgument().getNodeType().getLocalName(), uri, start, outputType);
158
159         final NormalizedNode<?, ?> mappedData =
160                 RestconfMappingNodeUtil.mapDataChangeNotificationStreamByIetfRestconfMonitoring(
161                         path, start, outputType, uri, monitoringModule, exist, schemaContextMonitoring);
162         assertNotNull(mappedData);
163         testData(map, mappedData);
164     }
165
166     @Test
167     public void toStreamEntryNodeNotifiTest() throws Exception {
168         final Instant start = Instant.now();
169         final String outputType = "JSON";
170         final URI uri = new URI("uri");
171         final Module monitoringModule = schemaContextMonitoring.findModule(MonitoringModule.MODULE_QNAME).orElse(null);
172         final boolean exist = true;
173
174         final Map<QName, Object> map = prepareMap("notifi", uri, start, outputType);
175         map.put(MonitoringModule.LEAF_DESCR_STREAM_QNAME, "Notifi");
176
177         final QName notifiQName = QName.create("urn:nested:module", "2014-06-03", "notifi");
178         final NormalizedNode<?, ?> mappedData =
179                 RestconfMappingNodeUtil.mapYangNotificationStreamByIetfRestconfMonitoring(notifiQName,
180                     schemaContextMonitoring.getNotifications(), start, outputType, uri, monitoringModule, exist);
181         assertNotNull(mappedData);
182         testData(map, mappedData);
183     }
184
185     private static Map<QName, Object> prepareMap(final String name, final URI uri, final Instant start,
186             final String outputType) {
187         final Map<QName, Object> map = new HashMap<>();
188         map.put(MonitoringModule.LEAF_NAME_STREAM_QNAME, name);
189         map.put(MonitoringModule.LEAF_LOCATION_ACCESS_QNAME, uri.toString());
190         map.put(MonitoringModule.LEAF_REPLAY_SUPP_STREAM_QNAME, Boolean.TRUE);
191         map.put(MonitoringModule.LEAF_START_TIME_STREAM_QNAME, DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(
192             OffsetDateTime.ofInstant(start, ZoneId.systemDefault())));
193         map.put(MonitoringModule.LEAF_ENCODING_ACCESS_QNAME, outputType);
194         return map;
195     }
196
197     private static void testData(final Map<QName, Object> map, final NormalizedNode<?, ?> mappedData) {
198         for (final DataContainerChild<? extends PathArgument, ?> child : ((MapEntryNode) mappedData).getValue()) {
199             if (child instanceof LeafNode) {
200                 final LeafNode<?> leaf = (LeafNode<?>) child;
201                 Assert.assertTrue(map.containsKey(leaf.getNodeType()));
202                 Assert.assertEquals(map.get(leaf.getNodeType()), leaf.getValue());
203             }
204         }
205     }
206
207     /**
208      * Verify loaded modules.
209      *
210      * @param containerNode
211      *             modules
212      */
213     private static void verifyLoadedModules(final ContainerNode containerNode) {
214
215         final Map<String, String> loadedModules = new HashMap<>();
216
217         for (final DataContainerChild<? extends PathArgument, ?> child : containerNode.getValue()) {
218             if (child instanceof LeafNode) {
219                 assertEquals(IetfYangLibrary.MODULE_SET_ID_LEAF_QNAME, child.getNodeType());
220             }
221             if (child instanceof MapNode) {
222                 assertEquals(IetfYangLibrary.MODULE_QNAME_LIST, child.getNodeType());
223                 for (final MapEntryNode mapEntryNode : ((MapNode) child).getValue()) {
224                     String name = "";
225                     String revision = "";
226                     for (final DataContainerChild<? extends PathArgument, ?> dataContainerChild : mapEntryNode
227                             .getValue()) {
228                         switch (dataContainerChild.getNodeType().getLocalName()) {
229                             case IetfYangLibrary.SPECIFIC_MODULE_NAME_LEAF:
230                                 name = String.valueOf(dataContainerChild.getValue());
231                                 break;
232                             case IetfYangLibrary.SPECIFIC_MODULE_REVISION_LEAF:
233                                 revision = String.valueOf(dataContainerChild.getValue());
234                                 break;
235                             default :
236                                 LOG.info("Unknown local name '{}' of node.",
237                                         dataContainerChild.getNodeType().getLocalName());
238                                 break;
239                         }
240                     }
241                     loadedModules.put(name, revision);
242                 }
243             }
244         }
245
246         verifyLoadedModules(RestconfMappingNodeUtilTest.modulesRest, loadedModules);
247     }
248
249     /**
250      * Verify if correct modules were loaded into Restconf module by comparison with modules from
251      * <code>SchemaContext</code>.
252      * @param expectedModules Modules from <code>SchemaContext</code>
253      * @param loadedModules Loaded modules into Restconf module
254      */
255     private static void verifyLoadedModules(final Set<Module> expectedModules,
256             final Map<String, String> loadedModules) {
257         assertEquals("Number of loaded modules is not as expected", expectedModules.size(), loadedModules.size());
258         for (final Module m : expectedModules) {
259             final String name = m.getName();
260
261             final String revision = loadedModules.get(name);
262             assertNotNull("Expected module not found", revision);
263             assertEquals("Incorrect revision of loaded module", Revision.ofNullable(revision), m.getRevision());
264
265             loadedModules.remove(name);
266         }
267     }
268 }