Expire negotiation on event loop
[netconf.git] / netconf / netconf-netty-util / src / test / java / org / opendaylight / netconf / nettyutil / AbstractNetconfSessionNegotiatorTest.java
1 /*
2  * Copyright (c) 2016 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.nettyutil;
9
10 import static org.hamcrest.CoreMatchers.instanceOf;
11 import static org.hamcrest.MatcherAssert.assertThat;
12 import static org.junit.Assert.assertEquals;
13 import static org.junit.Assert.assertNotNull;
14 import static org.mockito.ArgumentMatchers.any;
15 import static org.mockito.ArgumentMatchers.eq;
16 import static org.mockito.Mockito.doNothing;
17 import static org.mockito.Mockito.doReturn;
18 import static org.mockito.Mockito.mock;
19 import static org.mockito.Mockito.spy;
20 import static org.mockito.Mockito.times;
21 import static org.mockito.Mockito.verify;
22 import static org.opendaylight.netconf.nettyutil.AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR;
23 import static org.opendaylight.netconf.nettyutil.AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER;
24
25 import io.netty.buffer.ByteBuf;
26 import io.netty.buffer.Unpooled;
27 import io.netty.channel.ChannelHandlerContext;
28 import io.netty.channel.ChannelInboundHandlerAdapter;
29 import io.netty.channel.ChannelOutboundHandler;
30 import io.netty.channel.ChannelOutboundHandlerAdapter;
31 import io.netty.channel.ChannelPromise;
32 import io.netty.channel.embedded.EmbeddedChannel;
33 import io.netty.handler.ssl.SslHandler;
34 import io.netty.util.Timeout;
35 import io.netty.util.Timer;
36 import io.netty.util.TimerTask;
37 import io.netty.util.concurrent.Future;
38 import io.netty.util.concurrent.Promise;
39 import java.util.ArrayList;
40 import java.util.List;
41 import java.util.Optional;
42 import java.util.Set;
43 import java.util.concurrent.TimeUnit;
44 import org.junit.Before;
45 import org.junit.Test;
46 import org.junit.runner.RunWith;
47 import org.mockito.ArgumentCaptor;
48 import org.mockito.Mock;
49 import org.mockito.junit.MockitoJUnitRunner;
50 import org.opendaylight.netconf.api.NetconfSessionListener;
51 import org.opendaylight.netconf.api.NetconfSessionPreferences;
52 import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
53 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
54 import org.opendaylight.netconf.api.xml.XmlUtil;
55 import org.opendaylight.netconf.nettyutil.handler.ChunkedFramingMechanismEncoder;
56 import org.opendaylight.netconf.nettyutil.handler.EOMFramingMechanismEncoder;
57 import org.opendaylight.netconf.nettyutil.handler.FramingMechanismHandlerFactory;
58 import org.opendaylight.netconf.nettyutil.handler.NetconfChunkAggregator;
59 import org.opendaylight.netconf.nettyutil.handler.NetconfEOMAggregator;
60 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
61 import org.opendaylight.netconf.util.messages.FramingMechanism;
62
63 @RunWith(MockitoJUnitRunner.StrictStubs.class)
64 public class AbstractNetconfSessionNegotiatorTest {
65     @Mock
66     private NetconfSessionListener<TestingNetconfSession> listener;
67     @Mock
68     private Promise<TestingNetconfSession> promise;
69     @Mock
70     private SslHandler sslHandler;
71     @Mock
72     private Timer timer;
73     @Mock
74     private Timeout timeout;
75     private EmbeddedChannel channel;
76     private TestSessionNegotiator negotiator;
77     private NetconfHelloMessage hello;
78     private NetconfHelloMessage helloBase11;
79     private NetconfXMLToHelloMessageDecoder xmlToHello;
80     private NetconfSessionPreferences prefs;
81
82     @Before
83     public void setUp() {
84         channel = new EmbeddedChannel();
85         xmlToHello = new NetconfXMLToHelloMessageDecoder();
86         channel.pipeline().addLast(AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
87                 new ChannelInboundHandlerAdapter());
88         channel.pipeline().addLast(AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, xmlToHello);
89         channel.pipeline().addLast(NETCONF_MESSAGE_FRAME_ENCODER,
90                 FramingMechanismHandlerFactory.createHandler(FramingMechanism.EOM));
91         channel.pipeline().addLast(NETCONF_MESSAGE_AGGREGATOR, new NetconfEOMAggregator());
92         hello = NetconfHelloMessage.createClientHello(Set.of(), Optional.empty());
93         helloBase11 = NetconfHelloMessage.createClientHello(
94             Set.of(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1), Optional.empty());
95         prefs = new NetconfSessionPreferences(helloBase11);
96         doReturn(promise).when(promise).setFailure(any());
97         negotiator = new TestSessionNegotiator(prefs, promise, channel, timer, listener, 100L);
98     }
99
100     @Test
101     public void testStartNegotiation() {
102         enableTimerTask();
103         negotiator.startNegotiation();
104         assertEquals(helloBase11, channel.readOutbound());
105     }
106
107     @Test
108     public void testStartNegotiationSsl() throws Exception {
109         doReturn(true).when(sslHandler).isSharable();
110         doNothing().when(sslHandler).handlerAdded(any());
111         doNothing().when(sslHandler).write(any(), any(), any());
112         final Future<EmbeddedChannel> handshakeFuture = channel.eventLoop().newSucceededFuture(channel);
113         doReturn(handshakeFuture).when(sslHandler).handshakeFuture();
114         doNothing().when(sslHandler).flush(any());
115         channel.pipeline().addLast(sslHandler);
116
117         enableTimerTask();
118         negotiator.startNegotiation();
119         verify(sslHandler).write(any(), eq(helloBase11), any());
120     }
121
122     @Test
123     public void testStartNegotiationNotEstablished() throws Exception {
124         final ChannelOutboundHandler closedDetector = spy(new CloseDetector());
125         channel.pipeline().addLast("closedDetector", closedDetector);
126         doReturn(false).when(promise).isDone();
127         doReturn(false).when(promise).isCancelled();
128
129         final ArgumentCaptor<TimerTask> captor = ArgumentCaptor.forClass(TimerTask.class);
130         doReturn(timeout).when(timer).newTimeout(captor.capture(), eq(100L), eq(TimeUnit.MILLISECONDS));
131         negotiator.startNegotiation();
132
133         captor.getValue().run(timeout);
134         channel.runPendingTasks();
135         verify(closedDetector).close(any(), any());
136     }
137
138     @Test
139     public void testGetSessionPreferences() {
140         assertEquals(prefs, negotiator.getSessionPreferences());
141     }
142
143     @Test
144     public void testGetSessionForHelloMessage() throws Exception {
145         enableTimerTask();
146         negotiator.startNegotiation();
147         final TestingNetconfSession session = negotiator.getSessionForHelloMessage(hello);
148         assertNotNull(session);
149         assertThat(channel.pipeline().get(NETCONF_MESSAGE_AGGREGATOR), instanceOf(NetconfEOMAggregator.class));
150         assertThat(channel.pipeline().get(NETCONF_MESSAGE_FRAME_ENCODER), instanceOf(EOMFramingMechanismEncoder.class));
151     }
152
153     @Test
154     public void testGetSessionForHelloMessageBase11() throws Exception {
155         enableTimerTask();
156         negotiator.startNegotiation();
157         final TestingNetconfSession session = negotiator.getSessionForHelloMessage(helloBase11);
158         assertNotNull(session);
159         assertThat(channel.pipeline().get(NETCONF_MESSAGE_AGGREGATOR), instanceOf(NetconfChunkAggregator.class));
160         assertThat(channel.pipeline().get(NETCONF_MESSAGE_FRAME_ENCODER),
161             instanceOf(ChunkedFramingMechanismEncoder.class));
162     }
163
164     @Test
165     public void testReplaceHelloMessageInboundHandler() throws Exception {
166         final List<Object> out = new ArrayList<>();
167         final byte[] msg = "<rpc/>".getBytes();
168         final ByteBuf msgBuf = Unpooled.wrappedBuffer(msg);
169         final ByteBuf helloBuf = Unpooled.wrappedBuffer(XmlUtil.toString(hello.getDocument()).getBytes());
170
171         enableTimerTask();
172         negotiator.startNegotiation();
173
174         xmlToHello.decode(null, helloBuf, out);
175         xmlToHello.decode(null, msgBuf, out);
176         final TestingNetconfSession session = mock(TestingNetconfSession.class);
177         doNothing().when(session).handleMessage(any());
178         negotiator.replaceHelloMessageInboundHandler(session);
179         verify(session, times(1)).handleMessage(any());
180     }
181
182     @Test
183     public void testNegotiationFail() {
184         enableTimerTask();
185         doReturn(true).when(timeout).cancel();
186         negotiator.startNegotiation();
187         final RuntimeException cause = new RuntimeException("failure cause");
188         channel.pipeline().fireExceptionCaught(cause);
189         verify(promise).setFailure(cause);
190     }
191
192     private void enableTimerTask() {
193         doReturn(timeout).when(timer).newTimeout(any(), eq(100L), eq(TimeUnit.MILLISECONDS));
194     }
195
196     private static class CloseDetector extends ChannelOutboundHandlerAdapter {
197         @Override
198         public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) {
199             // Override needed so @Skip from superclass is not effective
200         }
201     }
202 }