1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * https://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.net.telnet;
18
19 import java.io.InputStream;
20 import java.io.OutputStream;
21
22 import junit.framework.TestCase;
23
24 /**
25 * JUnit functional test for TelnetClient. Connects to the weather forecast service rainmaker.wunderground.com and asks for Los Angeles forecast.
26 */
27 public class TelnetClientFunctionalTest extends TestCase {
28 protected TelnetClient tc1;
29
30 /**
31 * test setUp
32 */
33 @Override
34 protected void setUp() {
35 tc1 = new TelnetClient();
36 }
37
38 /*
39 * Do the functional test: - connect to the weather service - press return on the first menu - send LAX on the second menu - send X to exit
40 */
41 public void testFunctionalTest() throws Exception {
42 boolean testresult = false;
43 tc1.connect("rainmaker.wunderground.com", 3000);
44
45 try (InputStream is = tc1.getInputStream(); final OutputStream os = tc1.getOutputStream()) {
46
47 boolean cont = waitForString(is, "Return to continue:", 30000);
48 if (cont) {
49 os.write("\n".getBytes());
50 os.flush();
51 cont = waitForString(is, "city code--", 30000);
52 }
53 if (cont) {
54 os.write("LAX\n".getBytes());
55 os.flush();
56 cont = waitForString(is, "Los Angeles", 30000);
57 }
58 if (cont) {
59 cont = waitForString(is, "X to exit:", 30000);
60 }
61 if (cont) {
62 os.write("X\n".getBytes());
63 os.flush();
64 tc1.disconnect();
65 testresult = true;
66 }
67
68 assertTrue(testresult);
69 }
70 }
71
72 /*
73 * Helper method. waits for a string with timeout
74 */
75 public boolean waitForString(final InputStream is, final String end, final long timeout) throws Exception {
76 final byte[] buffer = new byte[32];
77 final long starttime = System.currentTimeMillis();
78
79 String readbytes = "";
80 while (!readbytes.contains(end) && System.currentTimeMillis() - starttime < timeout) {
81 if (is.available() > 0) {
82 final int retRead = is.read(buffer);
83 readbytes += new String(buffer, 0, retRead);
84 } else {
85 Thread.sleep(500);
86 }
87 }
88
89 return readbytes.indexOf(end) >= 0;
90 }
91 }