7657f6c5d30ef0062ec51c212006655e4bd17c19
[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.Lists;
23 import com.google.common.collect.Sets;
24 import java.io.FileNotFoundException;
25 import java.net.URI;
26 import java.text.ParseException;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Map.Entry;
33 import java.util.Optional;
34 import java.util.Set;
35 import javax.ws.rs.core.MultivaluedHashMap;
36 import javax.ws.rs.core.MultivaluedMap;
37 import javax.ws.rs.core.UriBuilder;
38 import javax.ws.rs.core.UriInfo;
39 import org.junit.AfterClass;
40 import org.junit.BeforeClass;
41 import org.junit.Test;
42 import org.mockito.Mockito;
43 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
44 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
45 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
46 import org.opendaylight.mdsal.dom.api.DOMRpcService;
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.context.NormalizedNodeContext;
54 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
55 import org.opendaylight.restconf.common.errors.RestconfError;
56 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
57 import org.opendaylight.restconf.common.errors.RestconfError.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.model.api.EffectiveModelContext;
67 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
68 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
70 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
71
72 /**
73  * See {@link InvokeRpcMethodTest}.
74  */
75 public class RestconfImplTest {
76
77     private static EffectiveModelContext schemaContext;
78
79     private final BrokerFacade brokerFacade = mock(BrokerFacade.class);
80     private final ControllerContext controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
81     private final RestconfImpl restconfImpl = RestconfImpl.newInstance(brokerFacade, controllerContext);
82
83     @BeforeClass
84     public static void init() throws FileNotFoundException, ReactorException {
85         schemaContext = TestUtils.loadSchemaContext("/full-versions/yangs");
86     }
87
88     @AfterClass
89     public static void cleanUp() {
90         WebSocketServer.destroyInstance(); // NETCONF-604
91     }
92
93     @Test
94     public void binaryKeyTest() {
95         final List<Byte> al = new ArrayList<>();
96         al.add((byte) 1);
97         binaryKeyTest(al, al);
98     }
99
100     private static void binaryKeyTest(final List<Byte> al, final List<Byte> al2) {
101
102         final QName keyDef = QName.create("test:key:binary", "2017-08-14", "b1");
103
104         final Map<QName, Object> uriKeyValues = new HashMap<>();
105         uriKeyValues.put(keyDef, al.toArray());
106
107         final MapEntryNode payload = mock(MapEntryNode.class);
108         final NodeIdentifierWithPredicates nodeIdWithPred =
109                 NodeIdentifierWithPredicates.of(keyDef, keyDef, al2.toArray());
110         when(payload.getIdentifier()).thenReturn(nodeIdWithPred);
111
112         final List<QName> keyDefinitions = new ArrayList<>();
113         keyDefinitions.add(keyDef);
114         RestconfImpl.isEqualUriAndPayloadKeyValues(uriKeyValues, payload, keyDefinitions);
115     }
116
117     @Test
118     public void binaryKeyFailTest() {
119         final List<Byte> al = new ArrayList<>();
120         al.add((byte) 1);
121         final List<Byte> al2 = new ArrayList<>();
122         try {
123             binaryKeyTest(al, al2);
124         } catch (final RestconfDocumentedException e) {
125             final RestconfError err = e.getErrors().iterator().next();
126             assertEquals(ErrorType.PROTOCOL, err.getErrorType());
127             assertEquals(ErrorTag.INVALID_VALUE, err.getErrorTag());
128         }
129     }
130
131     @SuppressWarnings("unchecked")
132     @Test
133     public void testExample() throws FileNotFoundException, ParseException {
134         @SuppressWarnings("rawtypes")
135         final NormalizedNode normalizedNodeData = TestUtils.prepareNormalizedNodeWithIetfInterfacesInterfacesData();
136         when(brokerFacade.readOperationalData(isNull())).thenReturn(normalizedNodeData);
137         assertEquals(normalizedNodeData,
138                 brokerFacade.readOperationalData(null));
139     }
140
141     @Test
142     public void testRpcForMountpoint() throws Exception {
143         final UriInfo uriInfo = mock(UriInfo.class);
144         doReturn(new MultivaluedHashMap<>()).when(uriInfo).getQueryParameters(anyBoolean());
145
146         final NormalizedNodeContext ctx = mock(NormalizedNodeContext.class);
147         final InstanceIdentifierContext<?> iiCtx = mock(InstanceIdentifierContext.class);
148         doReturn(iiCtx).when(ctx).getInstanceIdentifierContext();
149         final SchemaNode schemaNode = mock(SchemaNode.class);
150         doReturn(schemaNode).when(iiCtx).getSchemaNode();
151         doReturn(mock(SchemaPath.class)).when(schemaNode).getPath();
152         doReturn(QName.create("namespace", "2010-10-10", "localname")).when(schemaNode).getQName();
153
154         final DOMMountPoint mount = mock(DOMMountPoint.class);
155         doReturn(mount).when(iiCtx).getMountPoint();
156         final DOMRpcService rpcService = mock(DOMRpcService.class);
157         doReturn(Optional.of(rpcService)).when(mount).getService(DOMRpcService.class);
158         doReturn(immediateFluentFuture(mock(DOMRpcResult.class))).when(rpcService)
159                 .invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
160         this.restconfImpl.invokeRpc("randomId", ctx, uriInfo);
161         this.restconfImpl.invokeRpc("ietf-netconf", ctx, uriInfo);
162         verify(rpcService, times(2)).invokeRpc(any(SchemaPath.class), isNull());
163     }
164
165     /**
166      * Create notification stream for toaster module.
167      */
168     @Test
169     public void createNotificationStreamTest() {
170         final NormalizedNodeContext payload = mock(NormalizedNodeContext.class);
171         final InstanceIdentifierContext<?> iiCtx = mock(InstanceIdentifierContext.class);
172         doReturn(iiCtx).when(payload).getInstanceIdentifierContext();
173
174         final SchemaNode schemaNode = mock(SchemaNode.class,
175                 Mockito.withSettings().extraInterfaces(RpcDefinition.class));
176         doReturn(schemaNode).when(iiCtx).getSchemaNode();
177         doReturn(mock(SchemaPath.class)).when(schemaNode).getPath();
178
179         doReturn(QName.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote",
180                 "2014-01-14", "create-notification-stream")).when(schemaNode).getQName();
181         doReturn(null).when(iiCtx).getMountPoint();
182
183         final Set<DataContainerChild<?, ?>> children = new HashSet<>();
184         final DataContainerChild<?, ?> child = mock(DataContainerChild.class,
185                 Mockito.withSettings().extraInterfaces(LeafSetNode.class));
186
187         final LeafSetEntryNode entryNode = mock(LeafSetEntryNode.class);
188         when(entryNode.getValue()).thenReturn("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)toastDone");
189         when(((LeafSetNode) child).getValue()).thenReturn(Sets.newHashSet(entryNode));
190         children.add(child);
191
192         final NormalizedNode<?, ?> normalizedNode = mock(NormalizedNode.class,
193                 Mockito.withSettings().extraInterfaces(ContainerNode.class));
194         doReturn(normalizedNode).when(payload).getData();
195         doReturn(children).when(normalizedNode).getValue();
196
197         // register notification
198         final NormalizedNodeContext context = this.restconfImpl
199                 .invokeRpc("sal-remote:create-notification-stream", payload, null);
200         assertNotNull(context);
201     }
202
203     /**
204      * Subscribe for notification stream of toaster module.
205      */
206     @Test
207     public void subscribeToNotificationStreamTest() throws Exception {
208         final String identifier = "create-notification-stream/toaster:toastDone";
209
210         // register test notification stream
211         final SchemaPath path = SchemaPath.create(
212                 true, QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
213         Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML", controllerContext);
214
215         final UriInfo uriInfo = mock(UriInfo.class);
216         final UriBuilder uriBuilder = mock(UriBuilder.class);
217         when(uriBuilder.port(8181)).thenReturn(uriBuilder);
218         when(uriBuilder.replacePath(identifier)).thenReturn(uriBuilder);
219         when(uriBuilder.build()).thenReturn(new URI(""));
220         when(uriBuilder.scheme("ws")).thenReturn(uriBuilder);
221         when(uriInfo.getAbsolutePathBuilder()).thenReturn(uriBuilder);
222         final MultivaluedMap<String, String> map = mock(MultivaluedMap.class);
223         final Set<Entry<String, List<String>>> set = new HashSet<>();
224         when(map.entrySet()).thenReturn(set);
225         when(uriInfo.getQueryParameters()).thenReturn(map);
226
227         // subscribe to stream and verify response
228         final NormalizedNodeContext response = this.restconfImpl.subscribeToStream(identifier, uriInfo);
229
230         // remove test notification stream
231         Notificator.removeAllListeners();
232     }
233 }