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.messages.NetconfHelloMessage;
52 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
53 import org.opendaylight.netconf.api.xml.XmlUtil;
54 import org.opendaylight.netconf.nettyutil.handler.ChunkedFramingMechanismEncoder;
55 import org.opendaylight.netconf.nettyutil.handler.EOMFramingMechanismEncoder;
56 import org.opendaylight.netconf.nettyutil.handler.FramingMechanismHandlerFactory;
57 import org.opendaylight.netconf.nettyutil.handler.NetconfChunkAggregator;
58 import org.opendaylight.netconf.nettyutil.handler.NetconfEOMAggregator;
59 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
60 import org.opendaylight.netconf.util.messages.FramingMechanism;
61
62 @RunWith(MockitoJUnitRunner.StrictStubs.class)
63 public class AbstractNetconfSessionNegotiatorTest {
64     @Mock
65     private NetconfSessionListener<TestingNetconfSession> listener;
66     @Mock
67     private Promise<TestingNetconfSession> promise;
68     @Mock
69     private SslHandler sslHandler;
70     @Mock
71     private Timer timer;
72     @Mock
73     private Timeout timeout;
74     private EmbeddedChannel channel;
75     private TestSessionNegotiator negotiator;
76     private NetconfHelloMessage hello;
77     private NetconfHelloMessage helloBase11;
78     private NetconfXMLToHelloMessageDecoder xmlToHello;
79
80     @Before
81     public void setUp() {
82         channel = new EmbeddedChannel();
83         xmlToHello = new NetconfXMLToHelloMessageDecoder();
84         channel.pipeline().addLast(AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
85                 new ChannelInboundHandlerAdapter());
86         channel.pipeline().addLast(AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, xmlToHello);
87         channel.pipeline().addLast(NETCONF_MESSAGE_FRAME_ENCODER,
88                 FramingMechanismHandlerFactory.createHandler(FramingMechanism.EOM));
89         channel.pipeline().addLast(NETCONF_MESSAGE_AGGREGATOR, new NetconfEOMAggregator());
90         hello = NetconfHelloMessage.createClientHello(Set.of(), Optional.empty());
91         helloBase11 = NetconfHelloMessage.createClientHello(
92             Set.of(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1), Optional.empty());
93         doReturn(promise).when(promise).setFailure(any());
94         negotiator = new TestSessionNegotiator(helloBase11, promise, channel, timer, listener, 100L);
95     }
96
97     @Test
98     public void testStartNegotiation() {
99         enableTimerTask();
100         negotiator.startNegotiation();
101         assertEquals(helloBase11, channel.readOutbound());
102     }
103
104     @Test
105     public void testStartNegotiationSsl() throws Exception {
106         doReturn(true).when(sslHandler).isSharable();
107         doNothing().when(sslHandler).handlerAdded(any());
108         doNothing().when(sslHandler).write(any(), any(), any());
109         final Future<EmbeddedChannel> handshakeFuture = channel.eventLoop().newSucceededFuture(channel);
110         doReturn(handshakeFuture).when(sslHandler).handshakeFuture();
111         doNothing().when(sslHandler).flush(any());
112         channel.pipeline().addLast(sslHandler);
113
114         enableTimerTask();
115         negotiator.startNegotiation();
116         verify(sslHandler).write(any(), eq(helloBase11), any());
117     }
118
119     @Test
120     public void testStartNegotiationNotEstablished() throws Exception {
121         final ChannelOutboundHandler closedDetector = spy(new CloseDetector());
122         channel.pipeline().addLast("closedDetector", closedDetector);
123         doReturn(false).when(promise).isDone();
124         doReturn(false).when(promise).isCancelled();
125
126         final ArgumentCaptor<TimerTask> captor = ArgumentCaptor.forClass(TimerTask.class);
127         doReturn(timeout).when(timer).newTimeout(captor.capture(), eq(100L), eq(TimeUnit.MILLISECONDS));
128         negotiator.startNegotiation();
129
130         captor.getValue().run(timeout);
131         channel.runPendingTasks();
132         verify(closedDetector).close(any(), any());
133     }
134
135     @Test
136     public void testGetSessionForHelloMessage() throws Exception {
137         enableTimerTask();
138         negotiator.startNegotiation();
139         final TestingNetconfSession session = negotiator.getSessionForHelloMessage(hello);
140         assertNotNull(session);
141         assertThat(channel.pipeline().get(NETCONF_MESSAGE_AGGREGATOR), instanceOf(NetconfEOMAggregator.class));
142         assertThat(channel.pipeline().get(NETCONF_MESSAGE_FRAME_ENCODER), instanceOf(EOMFramingMechanismEncoder.class));
143     }
144
145     @Test
146     public void testGetSessionForHelloMessageBase11() throws Exception {
147         enableTimerTask();
148         negotiator.startNegotiation();
149         final TestingNetconfSession session = negotiator.getSessionForHelloMessage(helloBase11);
150         assertNotNull(session);
151         assertThat(channel.pipeline().get(NETCONF_MESSAGE_AGGREGATOR), instanceOf(NetconfChunkAggregator.class));
152         assertThat(channel.pipeline().get(NETCONF_MESSAGE_FRAME_ENCODER),
153             instanceOf(ChunkedFramingMechanismEncoder.class));
154     }
155
156     @Test
157     public void testReplaceHelloMessageInboundHandler() throws Exception {
158         final List<Object> out = new ArrayList<>();
159         final byte[] msg = "<rpc/>".getBytes();
160         final ByteBuf msgBuf = Unpooled.wrappedBuffer(msg);
161         final ByteBuf helloBuf = Unpooled.wrappedBuffer(XmlUtil.toString(hello.getDocument()).getBytes());
162
163         enableTimerTask();
164         negotiator.startNegotiation();
165
166         xmlToHello.decode(null, helloBuf, out);
167         xmlToHello.decode(null, msgBuf, out);
168         final TestingNetconfSession session = mock(TestingNetconfSession.class);
169         doNothing().when(session).handleMessage(any());
170         negotiator.replaceHelloMessageInboundHandler(session);
171         verify(session, times(1)).handleMessage(any());
172     }
173
174     @Test
175     public void testNegotiationFail() {
176         enableTimerTask();
177         doReturn(true).when(timeout).cancel();
178         negotiator.startNegotiation();
179         final RuntimeException cause = new RuntimeException("failure cause");
180         channel.pipeline().fireExceptionCaught(cause);
181         verify(promise).setFailure(cause);
182     }
183
184     private void enableTimerTask() {
185         doReturn(timeout).when(timer).newTimeout(any(), eq(100L), eq(TimeUnit.MILLISECONDS));
186     }
187
188     private static class CloseDetector extends ChannelOutboundHandlerAdapter {
189         @Override
190         public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) {
191             // Override needed so @Skip from superclass is not effective
192         }
193     }
194 }