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