2495c64d0f36e1a00738714550a5556a432b2794
[appc.git] / appc-config / appc-config-adaptor / provider / src / test / java / org / onap / appc / ccadaptor / SshJcraftWrapperTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
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
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
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.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.ccadaptor;
26
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;
40
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;
47 import java.io.File;
48 import java.io.FileNotFoundException;
49 import java.io.IOException;
50 import java.io.InputStream;
51 import java.net.URL;
52
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;
62
63 @RunWith(MockitoJUnitRunner.class)
64 public class SshJcraftWrapperTest {
65
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;
73
74     private SshJcraftWrapper cut;
75     @Mock
76     private JSch jSchMock;
77     @Mock
78     private Session session;
79     @Mock
80     private ChannelShell channelShell;
81     @Mock
82     private ChannelSubsystem channelSubsystem;
83     @Mock
84     private InputStream channelIs;
85
86     @Before
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);
95     }
96
97     @Ignore
98     @Test
99     public void TestCheckIfReceivedStringMatchesDelimeter(){
100         SshJcraftWrapper wrapper = new SshJcraftWrapper();
101         wrapper.getTheDate();
102         boolean result = wrapper.checkIfReceivedStringMatchesDelimeter("#", "test#", "test#");
103         Assert.assertEquals(true, result);
104     }
105
106     @Ignore
107     @Test
108     public void testRemoveWhiteSpaceAndNewLineCharactersAroundString(){
109         SshJcraftWrapper wrapper = new SshJcraftWrapper();
110         String nameSpace = wrapper.removeWhiteSpaceAndNewLineCharactersAroundString("namespace ");
111         Assert.assertEquals("namespace", nameSpace);
112     }
113
114     @Ignore
115     @Test
116     public void testStripOffCmdFromRouterResponse(){
117         SshJcraftWrapper wrapper = new SshJcraftWrapper();
118         String result = wrapper.stripOffCmdFromRouterResponse("test\nsuccess");
119         Assert.assertEquals("success\n", result);            
120     }
121     
122     //@Test
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);
129     }
130
131     @Ignore
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");
137     }
138
139     @Ignore
140     @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);
152     }
153
154     @Ignore
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();
160         sb.append("test");
161         wrapper.appendToRouterFile("Test.txt", sb);
162         wrapper.receiveUntilBufferFlush(3, 4, "test");        
163     }
164
165     @Ignore
166     @Test(expected=Exception.class)
167     public void testSetRouterCommandType3() throws IOException{
168         SshJcraftWrapper wrapper = new SshJcraftWrapper();
169         wrapper.checkIfReceivedStringMatchesDelimeter(3, "test");
170     }
171
172     //real jUnits
173     @Test(expected = IOException.class)
174     public void connect_shouldThrowIOException_whenJSchFails() throws Exception {
175         //given
176         given(jSchMock.getSession(anyString(), anyString(), anyInt())).willThrow(new JSchException());
177
178         //when
179         cut.connect(HOST, USER, PASS);
180
181         //then
182         fail("IOException should be thrown");
183     }
184
185     @Test
186     public void connect_shouldSetVariables() throws Exception {
187         //when
188         cut.connect(HOST, USER, PASS);
189
190         //then
191         assertEquals(HOST, cut.getHostName());
192         assertEquals(HOST, cut.getRouterName());
193         assertEquals(USER, cut.getUserName());
194         assertEquals(PASS, cut.getPassWord());
195     }
196
197     @Test
198     public void connect_shouldSetUpSessionWithProperInvocationOrder() throws Exception {
199         //given
200         InOrder inOrder =  inOrder(session, channelShell);
201
202         //when
203         cut.connect(HOST, USER, PASS);
204
205         //then
206         verifySessionConfigurationOrderForChannelShellOpenning(
207             inOrder, USER, HOST, PASS, SshJcraftWrapper.DEFAULT_PORT, SESSION_TIMEOUT);
208     }
209
210     @Test
211     public void connect_shouldFinishSuccessfully_whenExceptionThrownDuringReceivingPhase() throws Exception {
212         //given
213         doThrow(new JSchException()).when(session).setTimeout(anyInt());
214
215         //when
216         cut.connect(HOST, USER, PASS);
217
218         //then
219         verify(session).setTimeout(anyInt());
220     }
221
222     @Test(expected = IOException.class)
223     public void connect_withSubsystem_shouldThrowIOException_whenJSchFails() throws Exception {
224         //given
225         given(jSchMock.getSession(anyString(), anyString(), anyInt())).willThrow(new JSchException());
226
227         //when
228         cut.connect(HOST, USER, PASS, SESSION_TIMEOUT, PORT_NUM, SUBSYSTEM);
229
230         //then
231         fail("IOException should be thrown");
232     }
233
234     @Test
235     public void connect_withSubsystem_shouldSetRouterName() throws Exception {
236         //when
237         cut.connect(HOST, USER, PASS, SESSION_TIMEOUT, PORT_NUM, SUBSYSTEM);
238
239         //then
240         assertEquals(HOST, cut.getRouterName());
241     }
242
243     @Test
244     public void connect_withSubsystem_shouldSetUpSessionWithProperInvocationOrder() throws Exception {
245         //given
246         InOrder inOrder =  inOrder(session, channelSubsystem);
247
248         //when
249         cut.connect(HOST, USER, PASS, SESSION_TIMEOUT, PORT_NUM, SUBSYSTEM);
250
251         //then
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);
263     }
264
265     @Test(expected = IOException.class)
266     public void connect_withPrompt_shouldThrowIOException_whenJSchFails() throws Exception {
267         //given
268         given(jSchMock.getSession(anyString(), anyString(), anyInt())).willThrow(new JSchException());
269
270         //when
271         cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT);
272
273         //then
274         fail("IOException should be thrown");
275     }
276
277     @Test
278     public void connect_withPrompt_shouldSetVariables() throws Exception {
279         //when
280         cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT);
281
282         //then
283         assertEquals(HOST, cut.getHostName());
284         assertEquals(HOST, cut.getRouterName());
285         assertEquals(USER, cut.getUserName());
286         assertEquals(PASS, cut.getPassWord());
287     }
288
289     @Test
290     public void connect_withPrompt_shouldFinishSuccessfully_whenExceptionThrownDuringReceivingPhase() throws Exception {
291         //given
292         doThrow(new JSchException()).when(session).setTimeout(anyInt());
293
294         //when
295         cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT);
296
297         //then
298         verify(session).setTimeout(anyInt());
299     }
300
301     @Test
302     public void connect_withPrompt_shouldSetUpSessionWithProperInvocationOrder() throws Exception {
303         //given
304         InOrder inOrder =  inOrder(session, channelShell);
305
306         //when
307         cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT);
308
309         //then
310         verifySessionConfigurationOrderForChannelShellOpenning(
311             inOrder, USER, HOST, PASS, SshJcraftWrapper.DEFAULT_PORT, SESSION_TIMEOUT);
312     }
313
314     @Test(expected = IOException.class)
315     public void connect_withPort_shouldThrowIOException_whenJSchFails() throws Exception {
316         //given
317         given(jSchMock.getSession(anyString(), anyString(), anyInt())).willThrow(new JSchException());
318
319         //when
320         cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT, PORT_NUM);
321
322         //then
323         fail("IOException should be thrown");
324     }
325
326     @Test
327     public void connect_withPort_shouldSetVariables() throws Exception {
328         //when
329         cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT, PORT_NUM);
330
331         //then
332         assertEquals(HOST, cut.getHostName());
333         assertEquals(HOST, cut.getRouterName());
334         assertEquals(USER, cut.getUserName());
335         assertEquals(PASS, cut.getPassWord());
336     }
337
338     @Test
339     public void connect_withPort_shouldFinishSuccessfully_whenExceptionThrownDuringReceivingPhase() throws Exception {
340         //given
341         doThrow(new JSchException()).when(session).setTimeout(anyInt());
342
343         //when
344         cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT, PORT_NUM);
345
346         //then
347         verify(session).setTimeout(anyInt());
348     }
349
350     @Test
351     public void connect_withPort_shouldSetUpSessionWithProperInvocationOrder() throws Exception {
352         //given
353         InOrder inOrder =  inOrder(session, channelShell);
354
355         //when
356         cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT, PORT_NUM);
357
358         //then
359         verifySessionConfigurationOrderForChannelShellOpenning(inOrder, USER, HOST, PASS, PORT_NUM, SESSION_TIMEOUT);
360     }
361
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);
375     }
376
377     @Test
378     public void closeConnection_shouldCloseReaderChannelAndSession_inAGivenOrder() throws Exception {
379         //given
380         provideConnectedSubsystemInstance();
381         InOrder inOrder = inOrder(channelIs, channelSubsystem, session);
382
383         //when
384         cut.closeConnection();
385
386         //then
387         inOrder.verify(channelIs).close();
388         inOrder.verify(channelSubsystem).disconnect();
389         inOrder.verify(session).disconnect();
390         inOrder.verifyNoMoreInteractions();
391     }
392
393     @Test
394     public void closeConnection_shouldCloseChannelAndSession_whenClosingReaderFails() throws Exception {
395         //given
396         doThrow(new IOException("failed to close reader")).when(channelIs).close();
397         provideConnectedSubsystemInstance();
398
399         //when
400         cut.closeConnection();
401
402         //then
403         verify(channelIs).close();
404         verify(channelSubsystem).disconnect();
405         verify(session).disconnect();
406     }
407
408     @Test
409     public void closeConnection_shouldBeIdempotent_whenRunOnNewInstance() throws Exception {
410         //given
411         assertFalse(cut.isConnected());
412
413         //when
414         cut.closeConnection();
415
416         //then
417         assertFalse(cut.isConnected());
418     }
419
420     @Test
421     public void closeConnection_shouldBeIdempotent_whenRunTwiceOnConnectedInstance() throws Exception {
422         //given
423         provideConnectedSubsystemInstance();
424
425         //when
426         cut.closeConnection();
427         cut.closeConnection();
428
429         //then
430         assertFalse(cut.isConnected());
431     }
432
433     @Test
434     public void closeConnection_shouldCloseResourcesOnce_whenRunTwiceOnConnectedInstance() throws Exception {
435         //given
436         provideConnectedSubsystemInstance();
437
438         //when
439         cut.closeConnection();
440         cut.closeConnection();
441
442         //then
443         verify(channelIs, times(1)).close();
444         verify(channelSubsystem, times(1)).disconnect();
445         verify(session, times(1)).disconnect();
446     }
447
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());
452     }
453
454 }