2 * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.netconf.sal.connect.netconf;
11 import static org.mockito.Matchers.any;
12 import static org.mockito.Matchers.anyCollectionOf;
13 import static org.mockito.Mockito.doAnswer;
14 import static org.mockito.Mockito.doNothing;
15 import static org.mockito.Mockito.doReturn;
16 import static org.mockito.Mockito.mock;
17 import static org.mockito.Mockito.timeout;
18 import static org.mockito.Mockito.times;
19 import static org.mockito.Mockito.verify;
21 import com.google.common.base.Optional;
22 import com.google.common.collect.HashMultimap;
23 import com.google.common.collect.Iterables;
24 import com.google.common.collect.Lists;
25 import com.google.common.collect.Sets;
26 import com.google.common.util.concurrent.Futures;
27 import java.io.InputStream;
28 import java.net.InetSocketAddress;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.List;
34 import java.util.concurrent.ExecutorService;
35 import java.util.concurrent.Executors;
36 import org.junit.Test;
37 import org.mockito.Mockito;
38 import org.mockito.invocation.InvocationOnMock;
39 import org.mockito.stubbing.Answer;
40 import org.opendaylight.controller.config.util.xml.XmlUtil;
41 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
42 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
43 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
44 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
45 import org.opendaylight.netconf.api.NetconfMessage;
46 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
47 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
48 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
49 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
50 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
51 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
52 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
53 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
54 import org.opendaylight.yangtools.yang.common.QName;
55 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
57 import org.opendaylight.yangtools.yang.model.api.Module;
58 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
59 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
60 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
61 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
62 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
63 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
64 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
65 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
66 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
67 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
68 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
70 public class NetconfDeviceTest {
72 private static final NetconfMessage notification;
74 private static final ContainerNode compositeNode;
78 compositeNode = mockClass(ContainerNode.class);
79 } catch (final Exception e) {
80 throw new RuntimeException(e);
83 notification = new NetconfMessage(XmlUtil.readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
84 } catch (Exception e) {
85 throw new ExceptionInInitializerError(e);
89 private static final DOMRpcResult rpcResultC = new DefaultDOMRpcResult(compositeNode);
91 public static final String TEST_NAMESPACE = "test:namespace";
92 public static final String TEST_MODULE = "test-module";
93 public static final String TEST_REVISION = "2013-07-22";
94 public static final SourceIdentifier TEST_SID = new SourceIdentifier(TEST_MODULE, Optional.of(TEST_REVISION));
95 public static final String TEST_CAPABILITY = TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION;
97 public static final SourceIdentifier TEST_SID2 = new SourceIdentifier(TEST_MODULE + "2", Optional.of(TEST_REVISION));
98 public static final String TEST_CAPABILITY2 = TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&revision=" + TEST_REVISION;
100 private static final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver = new NetconfStateSchemas.NetconfStateSchemasResolver() {
103 public NetconfStateSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
104 return NetconfStateSchemas.EMPTY;
109 public void testNetconfDeviceFailFirstSchemaFailSecondEmpty() throws Exception {
110 final ArrayList<String> capList = Lists.newArrayList(TEST_CAPABILITY);
112 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
113 final NetconfDeviceCommunicator listener = getListener();
115 final SchemaContextFactory schemaFactory = getSchemaFactory();
117 // Make fallback attempt to fail due to empty resolved sources
118 final SchemaResolutionException schemaResolutionException
119 = new SchemaResolutionException("fail first",
120 Collections.<SourceIdentifier>emptyList(), HashMultimap.<SourceIdentifier, ModuleImport>create());
121 doReturn(Futures.immediateFailedCheckedFuture(
122 schemaResolutionException))
123 .when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
125 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
126 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaFactory, stateSchemasResolver);
127 final NetconfDevice device = new NetconfDevice(schemaResourcesDTO, getId(), facade, getExecutor(),true);
128 // Monitoring not supported
129 final NetconfSessionPreferences sessionCaps = getSessionCaps(false, capList);
130 device.onRemoteSessionUp(sessionCaps, listener);
132 Mockito.verify(facade, Mockito.timeout(5000)).onDeviceDisconnected();
133 Mockito.verify(listener, Mockito.timeout(5000)).close();
134 Mockito.verify(schemaFactory, times(1)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
138 public void testNetconfDeviceMissingSource() throws Exception {
139 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
140 final NetconfDeviceCommunicator listener = getListener();
141 final SchemaContext schema = getSchema();
143 final SchemaContextFactory schemaFactory = getSchemaFactory();
145 // Make fallback attempt to fail due to empty resolved sources
146 final MissingSchemaSourceException schemaResolutionException = new MissingSchemaSourceException("fail first", TEST_SID);
147 doAnswer(new Answer<Object>() {
149 public Object answer(final InvocationOnMock invocation) throws Throwable {
150 if(((Collection<?>) invocation.getArguments()[0]).size() == 2) {
151 return Futures.immediateFailedCheckedFuture(schemaResolutionException);
153 return Futures.immediateCheckedFuture(schema);
156 }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
158 final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver = new NetconfStateSchemas.NetconfStateSchemasResolver() {
160 public NetconfStateSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
161 final Module first = Iterables.getFirst(schema.getModules(), null);
162 final QName qName = QName.create(first.getQNameModule(), first.getName());
163 final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
164 final NetconfStateSchemas.RemoteYangSchema source2 = new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
165 return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
169 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
170 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaFactory, stateSchemasResolver);
172 final NetconfDevice device = new NetconfDevice(schemaResourcesDTO, getId(), facade, getExecutor(), true);
173 // Monitoring supported
174 final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
175 device.onRemoteSessionUp(sessionCaps, listener);
177 Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
178 Mockito.verify(schemaFactory, times(2)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
181 private SchemaSourceRegistry getSchemaRegistry() {
182 final SchemaSourceRegistry mock = mock(SchemaSourceRegistry.class);
183 final SchemaSourceRegistration<?> mockReg = mock(SchemaSourceRegistration.class);
184 doNothing().when(mockReg).close();
185 doReturn(mockReg).when(mock).registerSchemaSource(any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class), any(PotentialSchemaSource.class));
190 public void testNotificationBeforeSchema() throws Exception {
191 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
192 final NetconfDeviceCommunicator listener = getListener();
194 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
195 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaFactory(), stateSchemasResolver);
196 final NetconfDevice device = new NetconfDevice(schemaResourcesDTO, getId(), facade, getExecutor(), true);
198 device.onNotification(notification);
199 device.onNotification(notification);
201 verify(facade, times(0)).onNotification(any(DOMNotification.class));
203 final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
204 Lists.newArrayList(TEST_CAPABILITY));
206 final DOMRpcService deviceRpc = mock(DOMRpcService.class);
208 device.handleSalInitializationSuccess(NetconfToNotificationTest.getNotificationSchemaContext(getClass()), sessionCaps, deviceRpc);
210 verify(facade, timeout(10000).times(2)).onNotification(any(DOMNotification.class));
212 device.onNotification(notification);
213 verify(facade, timeout(10000).times(3)).onNotification(any(DOMNotification.class));
217 public void testNetconfDeviceReconnect() throws Exception {
218 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
219 final NetconfDeviceCommunicator listener = getListener();
221 final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
223 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
224 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaContextProviderFactory, stateSchemasResolver);
225 final NetconfDevice device = new NetconfDevice(schemaResourcesDTO, getId(), facade, getExecutor(), true);
226 final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
227 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION));
228 device.onRemoteSessionUp(sessionCaps, listener);
230 verify(schemaContextProviderFactory, timeout(5000)).createSchemaContext(any(Collection.class));
231 verify(facade, timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
233 device.onRemoteSessionDown();
234 verify(facade, timeout(5000)).onDeviceDisconnected();
236 device.onRemoteSessionUp(sessionCaps, listener);
238 verify(schemaContextProviderFactory, timeout(5000).times(2)).createSchemaContext(any(Collection.class));
239 verify(facade, timeout(5000).times(2)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
242 private SchemaContextFactory getSchemaFactory() {
243 final SchemaContextFactory schemaFactory = mockClass(SchemaContextFactory.class);
244 doReturn(Futures.immediateCheckedFuture(getSchema())).when(schemaFactory).createSchemaContext(any(Collection.class));
245 return schemaFactory;
248 public static SchemaContext getSchema() {
249 final YangParserImpl parser = new YangParserImpl();
250 final List<InputStream> modelsToParse = Lists.newArrayList(
251 NetconfDeviceTest.class.getResourceAsStream("/schemas/test-module.yang")
253 final Set<Module> models = parser.parseYangModelsFromStreams(modelsToParse);
254 return parser.resolveSchemaContext(models);
257 private RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
258 final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler = mockCloseableClass(RemoteDeviceHandler.class);
259 doNothing().when(remoteDeviceHandler).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
260 doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
261 doNothing().when(remoteDeviceHandler).onNotification(any(DOMNotification.class));
262 return remoteDeviceHandler;
265 private <T extends AutoCloseable> T mockCloseableClass(final Class<T> remoteDeviceHandlerClass) throws Exception {
266 final T mock = mockClass(remoteDeviceHandlerClass);
267 doNothing().when(mock).close();
271 private static <T> T mockClass(final Class<T> remoteDeviceHandlerClass) {
272 final T mock = mock(remoteDeviceHandlerClass);
273 Mockito.doReturn(remoteDeviceHandlerClass.getSimpleName()).when(mock).toString();
277 public RemoteDeviceId getId() {
278 return new RemoteDeviceId("test-D", InetSocketAddress.createUnresolved("localhost", 22));
281 public ExecutorService getExecutor() {
282 return Executors.newSingleThreadExecutor();
285 public MessageTransformer<NetconfMessage> getMessageTransformer() throws Exception {
286 final MessageTransformer<NetconfMessage> messageTransformer = mockClass(MessageTransformer.class);
287 doReturn(notification).when(messageTransformer).toRpcRequest(any(SchemaPath.class), any(NormalizedNode.class));
288 doReturn(rpcResultC).when(messageTransformer).toRpcResult(any(NetconfMessage.class), any(SchemaPath.class));
289 doReturn(compositeNode).when(messageTransformer).toNotification(any(NetconfMessage.class));
290 return messageTransformer;
293 public NetconfSessionPreferences getSessionCaps(final boolean addMonitor, final Collection<String> additionalCapabilities) {
294 final ArrayList<String> capabilities = Lists.newArrayList(
295 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
296 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
299 capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
302 capabilities.addAll(additionalCapabilities);
304 return NetconfSessionPreferences.fromStrings(
308 public NetconfDeviceCommunicator getListener() throws Exception {
309 final NetconfDeviceCommunicator remoteDeviceCommunicator = mockCloseableClass(NetconfDeviceCommunicator.class);
310 // doReturn(Futures.immediateFuture(rpcResult)).when(remoteDeviceCommunicator).sendRequest(any(NetconfMessage.class), any(QName.class));
311 return remoteDeviceCommunicator;