Simplify RestconfImplTest mocking
[netconf.git] / restconf / restconf-nb-bierman02 / src / test / java / org / opendaylight / controller / sal / restconf / impl / test / RestconfImplTest.java
1 /*
2  * Copyright (c) 2014 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.controller.sal.restconf.impl.test;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.mockito.ArgumentMatchers.any;
13 import static org.mockito.ArgumentMatchers.anyBoolean;
14 import static org.mockito.ArgumentMatchers.isNull;
15 import static org.mockito.Mockito.doReturn;
16 import static org.mockito.Mockito.mock;
17 import static org.mockito.Mockito.times;
18 import static org.mockito.Mockito.verify;
19 import static org.mockito.Mockito.when;
20 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
21
22 import com.google.common.collect.Iterables;
23 import java.io.FileNotFoundException;
24 import java.net.URI;
25 import java.text.ParseException;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Map.Entry;
32 import java.util.Optional;
33 import java.util.Set;
34 import javax.ws.rs.core.MultivaluedHashMap;
35 import javax.ws.rs.core.MultivaluedMap;
36 import javax.ws.rs.core.UriBuilder;
37 import javax.ws.rs.core.UriInfo;
38 import org.junit.AfterClass;
39 import org.junit.BeforeClass;
40 import org.junit.Test;
41 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
42 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
43 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
44 import org.opendaylight.mdsal.dom.api.DOMRpcService;
45 import org.opendaylight.netconf.sal.rest.api.Draft02;
46 import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeContext;
47 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
48 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
49 import org.opendaylight.netconf.sal.restconf.impl.RestconfImpl;
50 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
51 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
52 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
53 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
54 import org.opendaylight.restconf.common.errors.RestconfError;
55 import org.opendaylight.yangtools.yang.common.Empty;
56 import org.opendaylight.yangtools.yang.common.ErrorTag;
57 import org.opendaylight.yangtools.yang.common.ErrorType;
58 import org.opendaylight.yangtools.yang.common.QName;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
60 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
62 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
67 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaAwareBuilders;
68 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
70 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
71 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
72 import org.opendaylight.yangtools.yang.model.api.Module;
73 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
74 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
75 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
76 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
77 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
78
79 /**
80  * See {@link InvokeRpcMethodTest}.
81  */
82 public class RestconfImplTest {
83
84     private static EffectiveModelContext schemaContext;
85
86     private final BrokerFacade brokerFacade = mock(BrokerFacade.class);
87     private final ControllerContext controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
88     private final RestconfImpl restconfImpl = RestconfImpl.newInstance(brokerFacade, controllerContext);
89
90     @BeforeClass
91     public static void init() throws FileNotFoundException, ReactorException {
92         schemaContext = TestUtils.loadSchemaContext("/full-versions/yangs", "/modules/restconf-module-testing");
93     }
94
95     @AfterClass
96     public static void cleanUp() {
97         WebSocketServer.destroyInstance(); // NETCONF-604
98     }
99
100     @Test
101     public void binaryKeyTest() {
102         final List<Byte> al = new ArrayList<>();
103         al.add((byte) 1);
104         binaryKeyTest(al, al);
105     }
106
107     private static void binaryKeyTest(final List<Byte> al, final List<Byte> al2) {
108
109         final QName keyDef = QName.create("test:key:binary", "2017-08-14", "b1");
110
111         final Map<QName, Object> uriKeyValues = new HashMap<>();
112         uriKeyValues.put(keyDef, al.toArray());
113
114         final MapEntryNode payload = mock(MapEntryNode.class);
115         final NodeIdentifierWithPredicates nodeIdWithPred =
116                 NodeIdentifierWithPredicates.of(keyDef, keyDef, al2.toArray());
117         when(payload.getIdentifier()).thenReturn(nodeIdWithPred);
118
119         final List<QName> keyDefinitions = new ArrayList<>();
120         keyDefinitions.add(keyDef);
121         RestconfImpl.isEqualUriAndPayloadKeyValues(uriKeyValues, payload, keyDefinitions);
122     }
123
124     @Test
125     public void binaryKeyFailTest() {
126         final List<Byte> al = new ArrayList<>();
127         al.add((byte) 1);
128         final List<Byte> al2 = new ArrayList<>();
129         try {
130             binaryKeyTest(al, al2);
131         } catch (final RestconfDocumentedException e) {
132             final RestconfError err = e.getErrors().iterator().next();
133             assertEquals(ErrorType.PROTOCOL, err.getErrorType());
134             assertEquals(ErrorTag.INVALID_VALUE, err.getErrorTag());
135         }
136     }
137
138     @Test
139     public void testExample() throws FileNotFoundException, ParseException {
140         final NormalizedNode normalizedNodeData = TestUtils.prepareNormalizedNodeWithIetfInterfacesInterfacesData();
141         when(brokerFacade.readOperationalData(isNull())).thenReturn(normalizedNodeData);
142         assertEquals(normalizedNodeData,
143                 brokerFacade.readOperationalData(null));
144     }
145
146     @Test
147     public void testRpcForMountpoint() throws Exception {
148         final UriInfo uriInfo = mock(UriInfo.class);
149         doReturn(new MultivaluedHashMap<>()).when(uriInfo).getQueryParameters(anyBoolean());
150
151         final NormalizedNodeContext ctx = mock(NormalizedNodeContext.class);
152         final SchemaNode schemaNode = mock(SchemaNode.class);
153         doReturn(mock(SchemaPath.class)).when(schemaNode).getPath();
154         doReturn(QName.create("namespace", "2010-10-10", "localname")).when(schemaNode).getQName();
155
156         final DOMMountPoint mount = mock(DOMMountPoint.class);
157         doReturn(new InstanceIdentifierContext(null, schemaNode, mount, null)).when(ctx).getInstanceIdentifierContext();
158
159         final DOMRpcService rpcService = mock(DOMRpcService.class);
160         doReturn(Optional.of(rpcService)).when(mount).getService(DOMRpcService.class);
161         doReturn(immediateFluentFuture(mock(DOMRpcResult.class))).when(rpcService)
162                 .invokeRpc(any(QName.class), any(NormalizedNode.class));
163         restconfImpl.invokeRpc("randomId", ctx, uriInfo);
164         restconfImpl.invokeRpc("ietf-netconf", ctx, uriInfo);
165         verify(rpcService, times(2)).invokeRpc(any(QName.class), any());
166     }
167
168     /**
169      * Create notification stream for toaster module.
170      */
171     @Test
172     public void createNotificationStreamTest() {
173         final NormalizedNodeContext payload = mock(NormalizedNodeContext.class);
174
175         final RpcDefinition schemaNode = mock(RpcDefinition.class);
176         doReturn(mock(SchemaPath.class)).when(schemaNode).getPath();
177         doReturn(new InstanceIdentifierContext(null, schemaNode, null, null)).when(payload)
178                 .getInstanceIdentifierContext();
179
180         doReturn(QName.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote",
181                 "2014-01-14", "create-notification-stream")).when(schemaNode).getQName();
182
183         final Set<DataContainerChild> children = new HashSet<>();
184         final LeafSetNode child = mock(LeafSetNode.class);
185
186         final LeafSetEntryNode entryNode = mock(LeafSetEntryNode.class);
187         when(entryNode.body()).thenReturn("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)toastDone");
188         when(child.body()).thenReturn(Set.of(entryNode));
189         children.add(child);
190
191         final ContainerNode normalizedNode = mock(ContainerNode.class);
192         doReturn(normalizedNode).when(payload).getData();
193         doReturn(children).when(normalizedNode).body();
194
195         // register notification
196         final NormalizedNodeContext context = restconfImpl
197                 .invokeRpc("sal-remote:create-notification-stream", payload, null);
198         assertNotNull(context);
199     }
200
201     /**
202      * Tests stream entry node.
203      */
204     @Test
205     public void toStreamEntryNodeTest() {
206         final Module restconfModule = controllerContext.getRestconfModule();
207         final DataSchemaNode streamSchemaNode = controllerContext
208                 .getRestconfModuleRestConfSchemaNode(restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
209         final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
210         final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues =
211             SchemaAwareBuilders.mapEntryBuilder(listStreamSchemaNode);
212         List<DataSchemaNode> instanceDataChildrenByName =
213                 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "name");
214         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
215         streamNodeValues.withChild(SchemaAwareBuilders.leafBuilder((LeafSchemaNode) nameSchemaNode)
216             .withValue("")
217             .build());
218
219         instanceDataChildrenByName =
220                 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "description");
221         final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
222         streamNodeValues.withChild(SchemaAwareBuilders.leafBuilder((LeafSchemaNode) nameSchemaNode)
223             .withValue("DESCRIPTION_PLACEHOLDER")
224             .build());
225
226         instanceDataChildrenByName =
227                 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-support");
228         final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
229         streamNodeValues.withChild(
230             SchemaAwareBuilders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode).withValue(Boolean.TRUE).build());
231
232         instanceDataChildrenByName =
233                 ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "replay-log-creation-time");
234         final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
235         streamNodeValues.withChild(
236             SchemaAwareBuilders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode).withValue("").build());
237         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listStreamSchemaNode, "events");
238         final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
239         streamNodeValues.withChild(
240             SchemaAwareBuilders.leafBuilder((LeafSchemaNode) eventsSchemaNode).withValue(Empty.value()).build());
241         assertNotNull(streamNodeValues.build());
242     }
243
244     /**
245      * Subscribe for notification stream of toaster module.
246      */
247     @Test
248     public void subscribeToNotificationStreamTest() throws Exception {
249         final String identifier = "create-notification-stream/toaster:toastDone";
250
251         // register test notification stream
252         final Absolute path = Absolute.of(
253                 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
254         Notificator.createNotificationListener(List.of(path), identifier, "XML", controllerContext);
255
256         final UriInfo uriInfo = mock(UriInfo.class);
257         final UriBuilder uriBuilder = mock(UriBuilder.class);
258         when(uriBuilder.port(8181)).thenReturn(uriBuilder);
259         when(uriBuilder.replacePath(identifier)).thenReturn(uriBuilder);
260         when(uriBuilder.build()).thenReturn(new URI(""));
261         when(uriBuilder.scheme("ws")).thenReturn(uriBuilder);
262         when(uriInfo.getAbsolutePathBuilder()).thenReturn(uriBuilder);
263         final MultivaluedMap<String, String> map = mock(MultivaluedMap.class);
264         final Set<Entry<String, List<String>>> set = new HashSet<>();
265         when(map.entrySet()).thenReturn(set);
266         when(uriInfo.getQueryParameters()).thenReturn(map);
267
268         // subscribe to stream and verify response
269         final NormalizedNodeContext response = restconfImpl.subscribeToStream(identifier, uriInfo);
270
271         // remove test notification stream
272         Notificator.removeAllListeners();
273     }
274 }