2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * =============================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 * ============LICENSE_END=========================================================
25 package org.onap.appc.ccadaptor;
27 import static org.junit.Assert.assertEquals;
28 import static org.junit.Assert.assertTrue;
29 import static org.junit.Assert.assertFalse;
30 import static org.junit.Assert.fail;
31 import static org.mockito.BDDMockito.given;
32 import static org.mockito.Matchers.any;
33 import static org.mockito.Matchers.anyInt;
34 import static org.mockito.Matchers.anyString;
35 import static org.mockito.Mockito.doThrow;
36 import static org.mockito.Mockito.inOrder;
37 import static org.mockito.Mockito.times;
38 import static org.mockito.Mockito.verify;
39 import static org.mockito.Mockito.verifyNoMoreInteractions;
41 import com.jcraft.jsch.ChannelShell;
42 import com.jcraft.jsch.ChannelSubsystem;
43 import com.jcraft.jsch.JSch;
44 import com.jcraft.jsch.JSchException;
45 import com.jcraft.jsch.Session;
46 import com.jcraft.jsch.UserInfo;
48 import java.io.FileNotFoundException;
49 import java.io.IOException;
50 import java.io.InputStream;
53 import org.junit.Assert;
54 import org.junit.Before;
55 import org.junit.Ignore;
56 import org.junit.Test;
57 import org.junit.runner.RunWith;
58 import org.mockito.InOrder;
59 import org.mockito.Mock;
60 import org.mockito.runners.MockitoJUnitRunner;
61 import org.apache.commons.io.IOUtils;
63 @RunWith(MockitoJUnitRunner.class)
64 public class SshJcraftWrapperTest {
66 private static final String USER = "username";
67 private static final String PASS = "pass";
68 private static final String HOST = "hostname";
69 private static final String SUBSYSTEM = "netconf";
70 private static final String PROMPT = "]]>]]>";
71 private static final int PORT_NUM = 23;
72 private static final int SESSION_TIMEOUT = 30_000;
74 private SshJcraftWrapper cut;
76 private JSch jSchMock;
78 private Session session;
80 private ChannelShell channelShell;
82 private ChannelSubsystem channelSubsystem;
84 private InputStream channelIs;
87 public void setUpTest() throws Exception {
88 InputStream is = IOUtils.toInputStream("test input stream:~#", "UTF-8");
89 given(channelShell.getInputStream()).willReturn(is);
90 given(channelSubsystem.getInputStream()).willReturn(is);
91 given(session.openChannel(SshJcraftWrapper.CHANNEL_SHELL_TYPE)).willReturn(channelShell);
92 given(session.openChannel(SshJcraftWrapper.CHANNEL_SUBSYSTEM_TYPE)).willReturn(channelSubsystem);
93 given(jSchMock.getSession(anyString(), anyString(), anyInt())).willReturn(session);
94 cut = new SshJcraftWrapper(jSchMock);
99 public void TestCheckIfReceivedStringMatchesDelimeter(){
100 SshJcraftWrapper wrapper = new SshJcraftWrapper();
101 wrapper.getTheDate();
102 boolean result = wrapper.checkIfReceivedStringMatchesDelimeter("#", "test#", "test#");
103 Assert.assertEquals(true, result);
108 public void testRemoveWhiteSpaceAndNewLineCharactersAroundString(){
109 SshJcraftWrapper wrapper = new SshJcraftWrapper();
110 String nameSpace = wrapper.removeWhiteSpaceAndNewLineCharactersAroundString("namespace ");
111 Assert.assertEquals("namespace", nameSpace);
116 public void testStripOffCmdFromRouterResponse(){
117 SshJcraftWrapper wrapper = new SshJcraftWrapper();
118 String result = wrapper.stripOffCmdFromRouterResponse("test\nsuccess");
119 Assert.assertEquals("success\n", result);
123 public void testGetLastFewLinesOfFile() throws FileNotFoundException, IOException{
124 SshJcraftWrapper wrapper = new SshJcraftWrapper();
125 URL path = SshJcraftWrapperTest.class.getResource("Test");
126 File file = new File(path.getFile());
127 String value = wrapper.getLastFewLinesOfFile(file,1);
128 Assert.assertEquals("\nTest data 3", value);
132 @Test(expected=Exception.class)
133 public void testSetRouterCommandType() throws IOException{
134 SshJcraftWrapper wrapper = new SshJcraftWrapper();
135 wrapper.setRouterCommandType("test");
136 wrapper.receiveUntil("test", 2, "test");
141 public void testValues() throws IOException{
142 SshJcraftWrapper wrapper = new SshJcraftWrapper();
143 wrapper.setEquipNameCode("testcode");
144 wrapper.setRouterCommandType("testcommand");
145 String equipName = wrapper.getEquipNameCode();
146 wrapper.getHostName();
147 wrapper.getPassWord();
148 wrapper.getRouterName();
149 wrapper.getUserName();
150 wrapper.getTheDate();
151 Assert.assertEquals("testcode", equipName);
155 @Test(expected=Exception.class)
156 public void testSetRouterCommandType2() throws IOException{
157 SshJcraftWrapper wrapper = new SshJcraftWrapper();
158 wrapper.appendToRouterFile("test", 2);
159 StringBuilder sb = new StringBuilder();
161 wrapper.appendToRouterFile("Test.txt", sb);
162 wrapper.receiveUntilBufferFlush(3, 4, "test");
166 @Test(expected=Exception.class)
167 public void testSetRouterCommandType3() throws IOException{
168 SshJcraftWrapper wrapper = new SshJcraftWrapper();
169 wrapper.checkIfReceivedStringMatchesDelimeter(3, "test");
173 @Test(expected = IOException.class)
174 public void connect_shouldThrowIOException_whenJSchFails() throws Exception {
176 given(jSchMock.getSession(anyString(), anyString(), anyInt())).willThrow(new JSchException());
179 cut.connect(HOST, USER, PASS);
182 fail("IOException should be thrown");
186 public void connect_shouldSetVariables() throws Exception {
188 cut.connect(HOST, USER, PASS);
191 assertEquals(HOST, cut.getHostName());
192 assertEquals(HOST, cut.getRouterName());
193 assertEquals(USER, cut.getUserName());
194 assertEquals(PASS, cut.getPassWord());
198 public void connect_shouldSetUpSessionWithProperInvocationOrder() throws Exception {
200 InOrder inOrder = inOrder(session, channelShell);
203 cut.connect(HOST, USER, PASS);
206 verifySessionConfigurationOrderForChannelShellOpenning(
207 inOrder, USER, HOST, PASS, SshJcraftWrapper.DEFAULT_PORT, SESSION_TIMEOUT);
211 public void connect_shouldFinishSuccessfully_whenExceptionThrownDuringReceivingPhase() throws Exception {
213 doThrow(new JSchException()).when(session).setTimeout(anyInt());
216 cut.connect(HOST, USER, PASS);
219 verify(session).setTimeout(anyInt());
222 @Test(expected = IOException.class)
223 public void connect_withSubsystem_shouldThrowIOException_whenJSchFails() throws Exception {
225 given(jSchMock.getSession(anyString(), anyString(), anyInt())).willThrow(new JSchException());
228 cut.connect(HOST, USER, PASS, SESSION_TIMEOUT, PORT_NUM, SUBSYSTEM);
231 fail("IOException should be thrown");
235 public void connect_withSubsystem_shouldSetRouterName() throws Exception {
237 cut.connect(HOST, USER, PASS, SESSION_TIMEOUT, PORT_NUM, SUBSYSTEM);
240 assertEquals(HOST, cut.getRouterName());
244 public void connect_withSubsystem_shouldSetUpSessionWithProperInvocationOrder() throws Exception {
246 InOrder inOrder = inOrder(session, channelSubsystem);
249 cut.connect(HOST, USER, PASS, SESSION_TIMEOUT, PORT_NUM, SUBSYSTEM);
252 verify(jSchMock).getSession(USER, HOST, PORT_NUM);
253 inOrder.verify(session).setPassword(PASS);
254 inOrder.verify(session).setUserInfo(any(UserInfo.class));
255 inOrder.verify(session).setConfig(SshJcraftWrapper.STRICT_HOST_CHECK_KEY, SshJcraftWrapper.STRICT_HOST_CHECK_VALUE);
256 inOrder.verify(session).connect(SESSION_TIMEOUT);
257 inOrder.verify(session).setServerAliveCountMax(0);
258 inOrder.verify(session).openChannel(SshJcraftWrapper.CHANNEL_SUBSYSTEM_TYPE);
259 inOrder.verify(channelSubsystem).getInputStream();
260 inOrder.verify(channelSubsystem).connect(anyInt());
261 inOrder.verifyNoMoreInteractions();
262 verifyNoMoreInteractions(jSchMock);
265 @Test(expected = IOException.class)
266 public void connect_withPrompt_shouldThrowIOException_whenJSchFails() throws Exception {
268 given(jSchMock.getSession(anyString(), anyString(), anyInt())).willThrow(new JSchException());
271 cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT);
274 fail("IOException should be thrown");
278 public void connect_withPrompt_shouldSetVariables() throws Exception {
280 cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT);
283 assertEquals(HOST, cut.getHostName());
284 assertEquals(HOST, cut.getRouterName());
285 assertEquals(USER, cut.getUserName());
286 assertEquals(PASS, cut.getPassWord());
290 public void connect_withPrompt_shouldFinishSuccessfully_whenExceptionThrownDuringReceivingPhase() throws Exception {
292 doThrow(new JSchException()).when(session).setTimeout(anyInt());
295 cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT);
298 verify(session).setTimeout(anyInt());
302 public void connect_withPrompt_shouldSetUpSessionWithProperInvocationOrder() throws Exception {
304 InOrder inOrder = inOrder(session, channelShell);
307 cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT);
310 verifySessionConfigurationOrderForChannelShellOpenning(
311 inOrder, USER, HOST, PASS, SshJcraftWrapper.DEFAULT_PORT, SESSION_TIMEOUT);
314 @Test(expected = IOException.class)
315 public void connect_withPort_shouldThrowIOException_whenJSchFails() throws Exception {
317 given(jSchMock.getSession(anyString(), anyString(), anyInt())).willThrow(new JSchException());
320 cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT, PORT_NUM);
323 fail("IOException should be thrown");
327 public void connect_withPort_shouldSetVariables() throws Exception {
329 cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT, PORT_NUM);
332 assertEquals(HOST, cut.getHostName());
333 assertEquals(HOST, cut.getRouterName());
334 assertEquals(USER, cut.getUserName());
335 assertEquals(PASS, cut.getPassWord());
339 public void connect_withPort_shouldFinishSuccessfully_whenExceptionThrownDuringReceivingPhase() throws Exception {
341 doThrow(new JSchException()).when(session).setTimeout(anyInt());
344 cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT, PORT_NUM);
347 verify(session).setTimeout(anyInt());
351 public void connect_withPort_shouldSetUpSessionWithProperInvocationOrder() throws Exception {
353 InOrder inOrder = inOrder(session, channelShell);
356 cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT, PORT_NUM);
359 verifySessionConfigurationOrderForChannelShellOpenning(inOrder, USER, HOST, PASS, PORT_NUM, SESSION_TIMEOUT);
362 private void verifySessionConfigurationOrderForChannelShellOpenning(InOrder inOrder, String user, String host, String pass, int port, int sessionTimeout) throws Exception {
363 verify(jSchMock).getSession(user, host, port);
364 inOrder.verify(session).setPassword(pass);
365 inOrder.verify(session).setUserInfo(any(UserInfo.class));
366 inOrder.verify(session).setConfig(SshJcraftWrapper.STRICT_HOST_CHECK_KEY, SshJcraftWrapper.STRICT_HOST_CHECK_VALUE);
367 inOrder.verify(session).connect(sessionTimeout);
368 inOrder.verify(session).setServerAliveCountMax(0);
369 inOrder.verify(session).openChannel(SshJcraftWrapper.CHANNEL_SHELL_TYPE);
370 inOrder.verify(channelShell).getInputStream();
371 inOrder.verify(channelShell).connect();
372 inOrder.verify(session).setTimeout(anyInt());
373 inOrder.verifyNoMoreInteractions();
374 verifyNoMoreInteractions(jSchMock);
378 public void closeConnection_shouldCloseReaderChannelAndSession_inAGivenOrder() throws Exception {
380 provideConnectedSubsystemInstance();
381 InOrder inOrder = inOrder(channelIs, channelSubsystem, session);
384 cut.closeConnection();
387 inOrder.verify(channelIs).close();
388 inOrder.verify(channelSubsystem).disconnect();
389 inOrder.verify(session).disconnect();
390 inOrder.verifyNoMoreInteractions();
394 public void closeConnection_shouldCloseChannelAndSession_whenClosingReaderFails() throws Exception {
396 doThrow(new IOException("failed to close reader")).when(channelIs).close();
397 provideConnectedSubsystemInstance();
400 cut.closeConnection();
403 verify(channelIs).close();
404 verify(channelSubsystem).disconnect();
405 verify(session).disconnect();
409 public void closeConnection_shouldBeIdempotent_whenRunOnNewInstance() throws Exception {
411 assertFalse(cut.isConnected());
414 cut.closeConnection();
417 assertFalse(cut.isConnected());
421 public void closeConnection_shouldBeIdempotent_whenRunTwiceOnConnectedInstance() throws Exception {
423 provideConnectedSubsystemInstance();
426 cut.closeConnection();
427 cut.closeConnection();
430 assertFalse(cut.isConnected());
434 public void closeConnection_shouldCloseResourcesOnce_whenRunTwiceOnConnectedInstance() throws Exception {
436 provideConnectedSubsystemInstance();
439 cut.closeConnection();
440 cut.closeConnection();
443 verify(channelIs, times(1)).close();
444 verify(channelSubsystem, times(1)).disconnect();
445 verify(session, times(1)).disconnect();
448 private void provideConnectedSubsystemInstance() throws Exception {
449 given(channelSubsystem.getInputStream()).willReturn(channelIs);
450 cut.connect(HOST, USER, PASS, SESSION_TIMEOUT, PORT_NUM, SUBSYSTEM);
451 assertTrue(cut.isConnected());