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