Merge "Make rest-perf-client modify the {DEVICE_PORT} tag in payloads"
[netconf.git] / netconf / netconf-client / src / test / java / org / opendaylight / netconf / client / NetconfClientSessionNegotiatorTest.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
9 package org.opendaylight.netconf.client;
10
11 import static junit.framework.Assert.assertEquals;
12 import static junit.framework.Assert.assertTrue;
13 import static org.junit.Assert.assertNotEquals;
14 import static org.mockito.Matchers.any;
15 import static org.mockito.Matchers.anyObject;
16 import static org.mockito.Matchers.anyString;
17 import static org.mockito.Mockito.doAnswer;
18 import static org.mockito.Mockito.doReturn;
19 import static org.mockito.Mockito.mock;
20 import static org.mockito.Mockito.times;
21 import static org.mockito.Mockito.verify;
22
23 import com.google.common.base.Optional;
24 import com.google.common.collect.ImmutableSet;
25 import io.netty.channel.Channel;
26 import io.netty.channel.ChannelFuture;
27 import io.netty.channel.ChannelHandler;
28 import io.netty.channel.ChannelHandlerContext;
29 import io.netty.channel.ChannelInboundHandlerAdapter;
30 import io.netty.channel.ChannelPipeline;
31 import io.netty.channel.ChannelProgressivePromise;
32 import io.netty.channel.EventLoop;
33 import io.netty.handler.ssl.SslHandler;
34 import io.netty.util.HashedWheelTimer;
35 import io.netty.util.Timer;
36 import io.netty.util.concurrent.GenericFutureListener;
37 import io.netty.util.concurrent.Promise;
38 import java.io.InputStream;
39 import java.util.Set;
40 import org.junit.Before;
41 import org.junit.Test;
42 import org.mockito.internal.util.collections.Sets;
43 import org.mockito.invocation.InvocationOnMock;
44 import org.mockito.stubbing.Answer;
45 import org.opendaylight.controller.config.util.xml.XmlUtil;
46 import org.opendaylight.netconf.api.NetconfClientSessionPreferences;
47 import org.opendaylight.netconf.api.NetconfMessage;
48 import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
49 import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
50 import org.opendaylight.netconf.nettyutil.handler.ChunkedFramingMechanismEncoder;
51 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
52 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
53 import org.opendaylight.netconf.nettyutil.handler.exi.NetconfStartExiMessage;
54 import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
55 import org.opendaylight.netconf.util.test.XmlFileLoader;
56 import org.openexi.proc.common.EXIOptions;
57 import org.w3c.dom.Document;
58
59 public class NetconfClientSessionNegotiatorTest {
60
61     private NetconfHelloMessage helloMessage;
62     private ChannelPipeline pipeline;
63     private ChannelFuture future;
64     private Channel channel;
65     private ChannelInboundHandlerAdapter channelInboundHandlerAdapter;
66
67     @Before
68     public void setUp() throws Exception {
69         helloMessage = NetconfHelloMessage.createClientHello(Sets.newSet("exi:1.0"), Optional.<NetconfHelloMessageAdditionalHeader>absent());
70         pipeline = mockChannelPipeline();
71         future = mockChannelFuture();
72         channel = mockChannel();
73         mockEventLoop();
74     }
75
76     private static ChannelHandler mockChannelHandler() {
77         ChannelHandler handler = mock(ChannelHandler.class);
78         return handler;
79     }
80
81     private Channel mockChannel() {
82         Channel channel = mock(Channel.class);
83         ChannelHandler channelHandler = mockChannelHandler();
84         doReturn("").when(channel).toString();
85         doReturn(future).when(channel).close();
86         doReturn(future).when(channel).writeAndFlush(anyObject());
87         doReturn(true).when(channel).isOpen();
88         doReturn(pipeline).when(channel).pipeline();
89         doReturn("").when(pipeline).toString();
90         doReturn(pipeline).when(pipeline).remove(any(ChannelHandler.class));
91         doReturn(channelHandler).when(pipeline).remove(anyString());
92         return channel;
93     }
94
95     private static ChannelFuture mockChannelFuture() {
96         ChannelFuture future = mock(ChannelFuture.class);
97         doReturn(future).when(future).addListener(any(GenericFutureListener.class));
98         return future;
99     }
100
101     private static ChannelPipeline mockChannelPipeline() {
102         ChannelPipeline pipeline = mock(ChannelPipeline.class);
103         ChannelHandler handler = mock(ChannelHandler.class);
104         doReturn(pipeline).when(pipeline).addAfter(anyString(), anyString(), any(ChannelHandler.class));
105         doReturn(null).when(pipeline).get(SslHandler.class);
106         doReturn(pipeline).when(pipeline).addLast(anyString(), any(ChannelHandler.class));
107         doReturn(handler).when(pipeline).replace(anyString(), anyString(), any(ChunkedFramingMechanismEncoder.class));
108
109         NetconfXMLToHelloMessageDecoder messageDecoder = new NetconfXMLToHelloMessageDecoder();
110         doReturn(messageDecoder).when(pipeline).replace(anyString(), anyString(), any(NetconfXMLToMessageDecoder.class));
111         doReturn(pipeline).when(pipeline).replace(any(ChannelHandler.class), anyString(), any(NetconfClientSession.class));
112         return pipeline;
113     }
114
115     private void mockEventLoop() {
116         final EventLoop eventLoop = mock(EventLoop.class);
117         doReturn(eventLoop).when(channel).eventLoop();
118         doAnswer(new Answer<Void>() {
119             @Override
120             public Void answer(InvocationOnMock invocation) throws Throwable {
121                 final Object[] args = invocation.getArguments();
122                 final Runnable runnable = (Runnable) args[0];
123                 runnable.run();
124                 return null;
125             }
126         }).when(eventLoop).execute(any(Runnable.class));
127     }
128
129     private NetconfClientSessionNegotiator createNetconfClientSessionNegotiator(final Promise<NetconfClientSession> promise,
130                                                                                 final NetconfMessage startExi) {
131         ChannelProgressivePromise progressivePromise = mock(ChannelProgressivePromise.class);
132         NetconfClientSessionPreferences preferences = new NetconfClientSessionPreferences(helloMessage, startExi);
133         doReturn(progressivePromise).when(promise).setFailure(any(Throwable.class));
134
135         long timeout = 10L;
136         NetconfClientSessionListener sessionListener = mock(NetconfClientSessionListener.class);
137         Timer timer = new HashedWheelTimer();
138         return new NetconfClientSessionNegotiator(preferences, promise, channel, timer, sessionListener, timeout);
139     }
140
141     private NetconfHelloMessage createHelloMsg(final String name) throws Exception {
142         final InputStream stream = NetconfClientSessionNegotiatorTest.class.getResourceAsStream(name);
143         final Document doc = XmlUtil.readXmlToDocument(stream);
144
145         return new NetconfHelloMessage(doc);
146     }
147
148     private Set<String> createCapabilities(String name) throws Exception {
149         NetconfHelloMessage hello = createHelloMsg(name);
150
151         return ImmutableSet.copyOf(NetconfMessageUtil.extractCapabilitiesFromHello(hello.getDocument()));
152     }
153
154     @Test
155     public void testNetconfClientSessionNegotiator() throws Exception {
156         Promise promise = mock(Promise.class);
157         doReturn(promise).when(promise).setSuccess(anyObject());
158         NetconfClientSessionNegotiator negotiator = createNetconfClientSessionNegotiator(promise, null);
159
160         negotiator.channelActive(null);
161         Set<String> caps = Sets.newSet("a", "b");
162         NetconfHelloMessage helloServerMessage = NetconfHelloMessage.createServerHello(caps, 10);
163         negotiator.handleMessage(helloServerMessage);
164         verify(promise).setSuccess(anyObject());
165     }
166
167     @Test
168     public void testNetconfClientSessionNegotiatorWithEXI() throws Exception {
169         Promise promise = mock(Promise.class);
170         EXIOptions exiOptions = new EXIOptions();
171         NetconfStartExiMessage exiMessage = NetconfStartExiMessage.create(exiOptions, "msg-id");
172         doReturn(promise).when(promise).setSuccess(anyObject());
173         NetconfClientSessionNegotiator negotiator = createNetconfClientSessionNegotiator(promise, exiMessage);
174
175         negotiator.channelActive(null);
176         Set<String> caps = Sets.newSet("exi:1.0");
177         NetconfHelloMessage helloMessage = NetconfHelloMessage.createServerHello(caps, 10);
178
179         doAnswer(new Answer<Object>() {
180             @Override
181             public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
182                 channelInboundHandlerAdapter = ((ChannelInboundHandlerAdapter) invocationOnMock.getArguments()[2]);
183                 return null;
184             }
185         }).when(pipeline).addAfter(anyString(), anyString(), any(ChannelHandler.class));
186
187         ChannelHandlerContext handlerContext = mock(ChannelHandlerContext.class);
188         doReturn(pipeline).when(handlerContext).pipeline();
189         negotiator.handleMessage(helloMessage);
190         Document expectedResult = XmlFileLoader.xmlFileToDocument("netconfMessages/rpc-reply_ok.xml");
191         channelInboundHandlerAdapter.channelRead(handlerContext, new NetconfMessage(expectedResult));
192
193         verify(promise).setSuccess(anyObject());
194
195         // two calls for exiMessage, 2 for hello message
196         verify(pipeline, times(4)).replace(anyString(), anyString(), any(ChannelHandler.class));
197     }
198
199     @Test
200     public void testNetconfClientSessionNegotiatorGetCached() throws Exception {
201         Promise promise = mock(Promise.class);
202         doReturn(promise).when(promise).setSuccess(anyObject());
203         NetconfClientSessionListener sessionListener = mock(NetconfClientSessionListener.class);
204         NetconfClientSessionNegotiator negotiator = createNetconfClientSessionNegotiator(promise, null);
205
206         Set<String> set =  createCapabilities("/helloMessage3.xml");
207
208         final Set<String> cachedS1 = (Set<String>) negotiator.getSession(sessionListener,channel,createHelloMsg("/helloMessage1.xml")).getServerCapabilities();
209
210         //helloMessage2 and helloMessage3 are the same with different order
211         final Set<String> cachedS2 = (Set<String>) negotiator.getSession(sessionListener,channel,createHelloMsg("/helloMessage2.xml")).getServerCapabilities();
212         final Set<String> cachedS3 = (Set<String>) negotiator.getSession(sessionListener,channel,createHelloMsg("/helloMessage3.xml")).getServerCapabilities();
213
214         assertEquals(cachedS3, set);
215         assertNotEquals(cachedS1, set);
216         assertEquals(cachedS2, set);
217         assertEquals(cachedS3, cachedS2);
218         assertNotEquals(cachedS3, cachedS1);
219         assertNotEquals(cachedS2, cachedS1);
220         assertTrue(cachedS2 == cachedS3);
221     }
222 }