Use ControllerContext non-statically
[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.Matchers.any;
13 import static org.mockito.Matchers.anyBoolean;
14 import static org.mockito.Mockito.doReturn;
15 import static org.mockito.Mockito.mock;
16 import static org.mockito.Mockito.times;
17 import static org.mockito.Mockito.verify;
18 import static org.mockito.Mockito.when;
19
20 import com.google.common.base.Optional;
21 import com.google.common.collect.Lists;
22 import com.google.common.collect.Sets;
23 import com.google.common.util.concurrent.Futures;
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.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.Before;
39 import org.junit.BeforeClass;
40 import org.junit.Test;
41 import org.mockito.Mockito;
42 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
43 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
44 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
45 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
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;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
59 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
61 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
65 import org.opendaylight.yangtools.yang.model.api.Module;
66 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
67 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
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 SchemaContext schemaContext;
78
79     private RestconfImpl restconfImpl;
80     private final ControllerContext controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
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     @Before
90     public void initMethod() {
91         this.restconfImpl = RestconfImpl.getInstance();
92         this.restconfImpl.setControllerContext(controllerContext);
93     }
94
95     @Test
96     public void binaryKeyTest() {
97         final List<Byte> al = new ArrayList<>();
98         al.add(new Byte((byte) 1));
99         binaryKeyTest(al, al);
100     }
101
102     private void binaryKeyTest(final List<Byte> al, final List<Byte> al2) {
103
104         final QName keyDef = QName.create("test:key:binary", "2017-08-14", "b1");
105
106         final Map<QName, Object> uriKeyValues = new HashMap<>();
107         uriKeyValues.put(keyDef, al.toArray());
108
109         final MapEntryNode payload = mock(MapEntryNode.class);
110         final NodeIdentifierWithPredicates nodeIdWithPred =
111                 new NodeIdentifierWithPredicates(keyDef, keyDef, al2.toArray());
112         when(payload.getIdentifier()).thenReturn(nodeIdWithPred);
113
114         final List<QName> keyDefinitions = new ArrayList<>();
115         keyDefinitions.add(keyDef);
116         RestconfImpl.isEqualUriAndPayloadKeyValues(uriKeyValues, payload, keyDefinitions);
117     }
118
119     @Test
120     public void binaryKeyFailTest() {
121         final List<Byte> al = new ArrayList<>();
122         al.add(new Byte((byte) 1));
123         final List<Byte> al2 = new ArrayList<>();
124         try {
125             binaryKeyTest(al, al2);
126         } catch (final RestconfDocumentedException e) {
127             final RestconfError err = e.getErrors().iterator().next();
128             assertEquals(ErrorType.PROTOCOL, err.getErrorType());
129             assertEquals(ErrorTag.INVALID_VALUE, err.getErrorTag());
130         }
131     }
132
133     @SuppressWarnings("unchecked")
134     @Test
135     public void testExample() throws FileNotFoundException, ParseException {
136         @SuppressWarnings("rawtypes")
137         final NormalizedNode normalizedNodeData = TestUtils.prepareNormalizedNodeWithIetfInterfacesInterfacesData();
138         final BrokerFacade brokerFacade = mock(BrokerFacade.class);
139         when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(normalizedNodeData);
140         assertEquals(normalizedNodeData,
141                 brokerFacade.readOperationalData(null));
142     }
143
144     @Test
145     public void testRpcForMountpoint() throws Exception {
146         final UriInfo uriInfo = mock(UriInfo.class);
147         doReturn(new MultivaluedHashMap<>()).when(uriInfo).getQueryParameters(anyBoolean());
148
149         final NormalizedNodeContext ctx = mock(NormalizedNodeContext.class);
150         final InstanceIdentifierContext iiCtx = mock(InstanceIdentifierContext.class);
151         doReturn(iiCtx).when(ctx).getInstanceIdentifierContext();
152         final SchemaNode schemaNode = mock(SchemaNode.class);
153         doReturn(schemaNode).when(iiCtx).getSchemaNode();
154         doReturn(mock(SchemaPath.class)).when(schemaNode).getPath();
155         doReturn(QName.create("namespace", "2010-10-10", "localname")).when(schemaNode).getQName();
156
157         final DOMMountPoint mount = mock(DOMMountPoint.class);
158         doReturn(mount).when(iiCtx).getMountPoint();
159         final DOMRpcService rpcService = mock(DOMRpcService.class);
160         doReturn(Optional.of(rpcService)).when(mount).getService(DOMRpcService.class);
161         doReturn(Futures.immediateCheckedFuture(mock(DOMRpcResult.class))).when(rpcService)
162                 .invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
163         this.restconfImpl.invokeRpc("randomId", ctx, uriInfo);
164         this.restconfImpl.invokeRpc("ietf-netconf", ctx, uriInfo);
165         verify(rpcService, times(2)).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
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         final InstanceIdentifierContext iiCtx = mock(InstanceIdentifierContext.class);
175         doReturn(iiCtx).when(payload).getInstanceIdentifierContext();
176
177         final SchemaNode schemaNode = mock(SchemaNode.class,
178                 Mockito.withSettings().extraInterfaces(RpcDefinition.class));
179         doReturn(schemaNode).when(iiCtx).getSchemaNode();
180         doReturn(mock(SchemaPath.class)).when(schemaNode).getPath();
181
182         doReturn(QName.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote",
183                 "2014-01-14", "create-notification-stream")).when(schemaNode).getQName();
184         doReturn(null).when(iiCtx).getMountPoint();
185
186         final Set<DataContainerChild<?, ?>> children = Sets.newHashSet();
187         final DataContainerChild<?, ?> child = mock(DataContainerChild.class,
188                 Mockito.withSettings().extraInterfaces(LeafSetNode.class));
189
190         final LeafSetEntryNode entryNode = mock(LeafSetEntryNode.class);
191         when(entryNode.getValue()).thenReturn("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)toastDone");
192         when(((LeafSetNode) child).getValue()).thenReturn(Sets.newHashSet(entryNode));
193         children.add(child);
194
195         final NormalizedNode<?, ?> normalizedNode = mock(NormalizedNode.class,
196                 Mockito.withSettings().extraInterfaces(ContainerNode.class));
197         doReturn(normalizedNode).when(payload).getData();
198         doReturn(children).when(normalizedNode).getValue();
199
200         // register notification
201         final NormalizedNodeContext context = this.restconfImpl
202                 .invokeRpc("sal-remote:create-notification-stream", payload, null);
203         assertNotNull(context);
204     }
205
206     /**
207      * Subscribe for notification stream of toaster module.
208      */
209     @Test
210     public void subscribeToNotificationStreamTest() throws Exception {
211         final String identifier = "create-notification-stream/toaster:toastDone";
212
213         // register test notification stream
214         final SchemaPath path = SchemaPath.create(
215                 true, QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
216         Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML", controllerContext);
217
218         final UriInfo uriInfo = mock(UriInfo.class);
219         final UriBuilder uriBuilder = mock(UriBuilder.class);
220         when(uriBuilder.port(8181)).thenReturn(uriBuilder);
221         when(uriBuilder.replacePath(identifier)).thenReturn(uriBuilder);
222         when(uriBuilder.build()).thenReturn(new URI(""));
223         when(uriBuilder.scheme("ws")).thenReturn(uriBuilder);
224         when(uriInfo.getAbsolutePathBuilder()).thenReturn(uriBuilder);
225         final MultivaluedMap<String, String> map = mock(MultivaluedMap.class);
226         final Set<Entry<String, List<String>>> set = new HashSet<>();
227         when(map.entrySet()).thenReturn(set);
228         when(uriInfo.getQueryParameters()).thenReturn(map);
229
230         final BrokerFacade brokerFacade = mock(BrokerFacade.class);
231         this.restconfImpl.setBroker(brokerFacade);
232
233         // subscribe to stream and verify response
234         final NormalizedNodeContext response = this.restconfImpl.subscribeToStream(identifier, uriInfo);
235
236         // remove test notification stream
237         Notificator.removeAllListeners();
238     }
239 }