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