Bug 5526 - Testing - Utils - Mapping
[netconf.git] / restconf / sal-rest-connector / src / test / java / org / opendaylight / restconf / rest / impl / services / RestconfStreamsServiceTest.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
9 package org.opendaylight.restconf.rest.impl.services;
10
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertFalse;
13 import static org.junit.Assert.assertNotNull;
14 import static org.junit.Assert.assertTrue;
15 import static org.junit.Assert.fail;
16 import static org.mockito.Mockito.when;
17 import static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.EMPTY;
18 import com.google.common.collect.Iterables;
19 import com.google.common.collect.Lists;
20 import java.util.AbstractMap;
21 import java.util.ArrayList;
22 import java.util.Arrays;
23 import java.util.Collection;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Map;
27 import org.junit.AfterClass;
28 import org.junit.Before;
29 import org.junit.BeforeClass;
30 import org.junit.Rule;
31 import org.junit.Test;
32 import org.junit.rules.ExpectedException;
33 import org.mockito.Mock;
34 import org.mockito.MockitoAnnotations;
35 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
36 import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
37 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
38 import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
39 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
40 import org.opendaylight.restconf.Draft11;
41 import org.opendaylight.restconf.handlers.SchemaContextHandler;
42 import org.opendaylight.restconf.rest.services.api.RestconfStreamsService;
43 import org.opendaylight.restconf.rest.services.impl.RestconfStreamsServiceImpl;
44 import org.opendaylight.restconf.utils.mapping.RestconfMappingNodeConstants;
45 import org.opendaylight.restconf.utils.mapping.RestconfMappingStreamConstants;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
48 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
50 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
51 import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableDataContainerAttrNode;
52 import org.opendaylight.yangtools.yang.model.api.Module;
53 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
54
55 /**
56  * Unit tests for {@link RestconfStreamsServiceImpl}
57  */
58 public class RestconfStreamsServiceTest {
59     private static final List<String> expectedStreams = Arrays.asList(new String[] {"stream-1", "stream-2", "stream-3"});
60
61     @Rule public ExpectedException thrown = ExpectedException.none();
62
63     @Mock private SchemaContextHandler contextHandler;
64     @Mock private SchemaContext mockSchemaContext;
65
66     // service under test
67     private RestconfStreamsService streamsService;
68
69     // schema context with testing Restconf modules
70     private SchemaContext schemaContext;
71
72     @Before
73     public void setup() throws Exception {
74         MockitoAnnotations.initMocks(this);
75
76         this.schemaContext = TestRestconfUtils.loadSchemaContext("/modules/restconf-module-testing");
77         this.streamsService = new RestconfStreamsServiceImpl(this.contextHandler);
78     }
79
80     @BeforeClass
81     public static void setupTestStreams() {
82         // clean
83         Notificator.removeAllListeners();
84
85         // put test streams
86         Notificator.createListener(EMPTY, RestconfStreamsServiceTest.expectedStreams.get(0));
87         Notificator.createListener(EMPTY, RestconfStreamsServiceTest.expectedStreams.get(1));
88         Notificator.createListener(EMPTY, RestconfStreamsServiceTest.expectedStreams.get(2));
89     }
90
91     @AfterClass
92     public static void removeTestStreams() {
93         Notificator.removeAllListeners();
94     }
95
96     /**
97      * Test of successful initialization of streams service.
98      */
99     @Test
100     public void restconfStreamsServiceImplInitTest() {
101         assertNotNull("Streams service should be initialized and not null", this.streamsService);
102     }
103
104     /**
105      * Positive test to get all available streams supported by the server. Loaded streams are compared to expected
106      * streams.
107      */
108     @Test
109     public void getAvailableStreamsTest() throws Exception {
110         // prepare conditions - get correct Restconf module
111         when(this.contextHandler.get()).thenReturn(this.mockSchemaContext);
112         when(this.mockSchemaContext.findModuleByNamespaceAndRevision(Draft11.RestconfModule.IETF_RESTCONF_QNAME
113                 .getNamespace(), Draft11.RestconfModule.IETF_RESTCONF_QNAME.getRevision()))
114                 .thenReturn(getTestingRestconfModule("ietf-restconf"));
115
116         // make test
117         final NormalizedNodeContext nodeContext = this.streamsService.getAvailableStreams(null);
118
119         // verify loaded streams
120         assertNotNull("Normalized node context should not be null", nodeContext);
121         verifyStreams(((ContainerNode) nodeContext.getData()).getValue());
122     }
123
124     /**
125      * Try to get all available streams supported by the server when current <code>SchemaContext</code> is
126      * <code>null</code> expecting <code>NullPointerException</code>.
127      */
128     @Test
129     public void getAvailableStreamsNullSchemaContextNegativeTest() {
130         // prepare conditions - returned SchemaContext is null
131         when(this.contextHandler.get()).thenReturn(null);
132
133         // make test
134         this.thrown.expect(NullPointerException.class);
135         this.streamsService.getAvailableStreams(null);
136     }
137
138     /**
139      * Try to get all available streams supported by the server when Restconf module is missing in
140      * <code>SchemaContext</code> expecting <code>NullPointerException</code>.
141      */
142     @Test
143     public void getAvailableStreamsMissingRestconfModuleNegativeTest() {
144         // prepare conditions - get null Restconf module
145         when(this.contextHandler.get()).thenReturn(this.mockSchemaContext);
146         when(this.mockSchemaContext.findModuleByNamespaceAndRevision(Draft11.RestconfModule.IETF_RESTCONF_QNAME
147                 .getNamespace(), Draft11.RestconfModule.IETF_RESTCONF_QNAME.getRevision())).thenReturn(null);
148
149         // make test
150         this.thrown.expect(NullPointerException.class);
151         this.streamsService.getAvailableStreams(null);
152     }
153
154     /**
155      * Try to get all available streams supported by the server when Restconf module does not contain list stream
156      * catching <code>RestconfDocumentedException</code>. Error type, error tag and error status code are validated
157      * against expected values.
158      */
159     @Test
160     public void getAvailableStreamsMissingListStreamNegativeTest() {
161         // prepare conditions - get Restconf module with missing list stream
162         when(this.contextHandler.get()).thenReturn(this.mockSchemaContext);
163         when(this.mockSchemaContext.findModuleByNamespaceAndRevision(Draft11.RestconfModule.IETF_RESTCONF_QNAME
164                 .getNamespace(), Draft11.RestconfModule.IETF_RESTCONF_QNAME.getRevision()))
165                 .thenReturn(getTestingRestconfModule("restconf-module-with-missing-list-stream"));
166
167         // make test and verify
168         try {
169             this.streamsService.getAvailableStreams(null);
170             fail("Test is expected to fail due to missing list stream");
171         } catch (final RestconfDocumentedException e) {
172             assertEquals("Error type is not correct",
173                     RestconfError.ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
174             assertEquals("Error tag is not correct",
175                     RestconfError.ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
176             assertEquals("Error status code is not correct",
177                     404, e.getErrors().get(0).getErrorTag().getStatusCode());
178         }
179     }
180
181     /**
182      * Try to get all available streams supported by the server when Restconf module does not contain container streams
183      * catching <code>RestconfDocumentedException</code>. Error type, error tag and error status code are validated
184      * against expected values.
185      */
186     @Test
187     public void getAvailableStreamsMissingContainerStreamsNegativeTest() {
188         // prepare conditions - get Restconf module with missing container streams
189         when(this.contextHandler.get()).thenReturn(this.mockSchemaContext);
190         when(this.mockSchemaContext.findModuleByNamespaceAndRevision(Draft11.RestconfModule.IETF_RESTCONF_QNAME
191                 .getNamespace(), Draft11.RestconfModule.IETF_RESTCONF_QNAME.getRevision()))
192                 .thenReturn(getTestingRestconfModule("restconf-module-with-missing-container-streams"));
193
194         // make test and verify
195         try {
196             this.streamsService.getAvailableStreams(null);
197             fail("Test is expected to fail due to missing container streams");
198         } catch (final RestconfDocumentedException e) {
199             assertEquals("Error type is not correct",
200                     RestconfError.ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
201             assertEquals("Error tag is not correct",
202                     RestconfError.ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
203             assertEquals("Error status code is not correct",
204                     404, e.getErrors().get(0).getErrorTag().getStatusCode());
205         }
206     }
207
208     /**
209      * Try to get all available streams supported by the server when Restconf module contains node with name 'stream'
210      * but it is not of type list. Test is expected to fail with <code>IllegalStateException</code>.
211      */
212     @Test
213     public void getAvailableStreamsIllegalListStreamNegativeTest() {
214         // prepare conditions - get Restconf module with illegal list stream
215         when(this.contextHandler.get()).thenReturn(this.mockSchemaContext);
216         when(this.mockSchemaContext.findModuleByNamespaceAndRevision(Draft11.RestconfModule.IETF_RESTCONF_QNAME
217                 .getNamespace(), Draft11.RestconfModule.IETF_RESTCONF_QNAME.getRevision()))
218                 .thenReturn(getTestingRestconfModule("restconf-module-with-illegal-list-stream"));
219
220         // make test
221         this.thrown.expect(IllegalStateException.class);
222         this.streamsService.getAvailableStreams(null);
223     }
224
225     /**
226      * Try to get all available streams supported by the server when Restconf module contains node with name 'streams'
227      * but it is not of type container. Test is expected to fail with <code>IllegalStateException</code>.
228      */
229     @Test
230     public void getAvailableStreamsIllegalContainerStreamsNegativeTest() {
231         // prepare conditions - get Restconf module with illegal container streams
232         when(this.contextHandler.get()).thenReturn(this.mockSchemaContext);
233         when(this.mockSchemaContext.findModuleByNamespaceAndRevision(Draft11.RestconfModule.IETF_RESTCONF_QNAME
234                 .getNamespace(), Draft11.RestconfModule.IETF_RESTCONF_QNAME.getRevision()))
235                 .thenReturn(getTestingRestconfModule("restconf-module-with-illegal-container-streams"));
236
237         // make test
238         this.thrown.expect(IllegalStateException.class);
239         this.streamsService.getAvailableStreams(null);
240     }
241
242     /**
243      * Try to get all available streams supported by the server when node 'description' in list stream in Restconf
244      * module is not of type leaf. Test is expected to fail with <code>IllegalStateException</code>.
245      */
246     @Test
247     public void getAvailableStreamsIllegalLeafDescriptionNegativeTest() {
248         // prepare conditions - get Restconf module with illegal leaf description in list stream
249         when(this.contextHandler.get()).thenReturn(this.mockSchemaContext);
250         when(this.mockSchemaContext.findModuleByNamespaceAndRevision(Draft11.RestconfModule.IETF_RESTCONF_QNAME
251                 .getNamespace(), Draft11.RestconfModule.IETF_RESTCONF_QNAME.getRevision()))
252                 .thenReturn(getTestingRestconfModule("restconf-module-with-illegal-leaf-description"));
253
254         // make test
255         this.thrown.expect(IllegalStateException.class);
256         this.streamsService.getAvailableStreams(null);
257     }
258
259     /**
260      * There are multiple testing Restconf modules for different test cases. It is possible to distinguish them by
261      * name or by namespace. This method is looking for Restconf test module by its name.
262      * @param s Testing Restconf module name
263      * @return Restconf module
264      */
265     private Module getTestingRestconfModule(final String s) {
266         return this.schemaContext.findModuleByName(s, Draft11.RestconfModule.IETF_RESTCONF_QNAME.getRevision());
267     }
268
269     /**
270      * Verify loaded streams
271      * @param streams Streams to be verified
272      */
273     private void verifyStreams(final Collection<DataContainerChild<? extends PathArgument, ?>> streams) {
274         assertNotNull("Collection of streams should not be empty", streams);
275         assertFalse("Collection of streams should not be empty", Iterables.isEmpty(streams));
276         final Iterator<DataContainerChild<? extends PathArgument, ?>> iterator = streams.iterator();
277
278         final List<String> loadedStreams = new ArrayList<>();
279         for (final Object stream : (Collection<?>) iterator.next().getValue()) {
280             final Iterator mapEntries = ((AbstractImmutableDataContainerAttrNode) stream)
281                     .getChildren().entrySet().iterator();
282
283             final List<String> allowedKeys = Lists.newArrayList(
284                     RestconfMappingNodeConstants.NAME,
285                     RestconfMappingNodeConstants.DESCRIPTION,
286                     RestconfMappingNodeConstants.REPLAY_SUPPORT,
287                     RestconfMappingNodeConstants.REPLAY_LOG,
288                     RestconfMappingNodeConstants.EVENTS);
289
290             while (mapEntries.hasNext()) {
291                 final Map.Entry e = ((AbstractMap.SimpleImmutableEntry) mapEntries.next());
292                 final String key = ((NodeIdentifier) e.getKey()).getNodeType().getLocalName();
293
294                 assertTrue("Not allowed key", allowedKeys.contains(key));
295
296                 switch (key) {
297                     case RestconfMappingNodeConstants.NAME :
298                         loadedStreams.add((String) ((LeafNode) e.getValue()).getValue());
299                         break;
300                     case RestconfMappingNodeConstants.DESCRIPTION :
301                         assertEquals("Stream description value is not as expected",
302                                 RestconfMappingStreamConstants.DESCRIPTION, ((LeafNode) e.getValue()).getValue());
303                         break;
304                     case RestconfMappingNodeConstants.REPLAY_SUPPORT :
305                         assertEquals("Stream replay support value is not as expected",
306                                 RestconfMappingStreamConstants.REPLAY_SUPPORT, ((LeafNode) e.getValue()).getValue());
307                         break;
308                     case RestconfMappingNodeConstants.REPLAY_LOG :
309                         assertEquals("Stream replay log value is not as expected",
310                                 RestconfMappingStreamConstants.REPLAY_LOG, ((LeafNode) e.getValue()).getValue());
311                         break;
312                     case RestconfMappingNodeConstants.EVENTS :
313                         assertEquals("Stream events value is not as expected",
314                                 RestconfMappingStreamConstants.EVENTS, ((LeafNode) e.getValue()).getValue());
315                         break;
316                 }
317             }
318         }
319
320         // sort and compare
321         loadedStreams.sort((s1, s2) -> s1.compareTo(s2));
322         assertEquals("Returned streams are not as expected", expectedStreams, loadedStreams);
323     }
324 }