1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.commons.net.telnet;
17
18 import junit.framework.TestCase;
19 import java.io.InputStream;
20 import java.io.OutputStream;
21
22 /***
23 * JUnit functional test for TelnetClient.
24 * Connects to the weather forecast service
25 * rainmaker.wunderground.com and asks for Los Angeles forecast.
26 * <p>
27 * @author Bruno D'Avanzo
28 ***/
29 public class TelnetClientFunctionalTest extends TestCase
30 {
31 protected TelnetClient tc1;
32
33 /***
34 * main for running the test.
35 ***/
36 public static void main(String args[])
37 {
38 junit.textui.TestRunner.run(TelnetClientFunctionalTest.class);
39 }
40
41 /***
42 * test setUp
43 ***/
44 protected void setUp()
45 {
46 tc1 = new TelnetClient();
47 }
48
49 /***
50 * Do the functional test:
51 * - connect to the weather service
52 * - press return on the first menu
53 * - send LAX on the second menu
54 * - send X to exit
55 ***/
56 public void testFunctionalTest() throws Exception
57 {
58 boolean testresult = false;
59 tc1.connect("rainmaker.wunderground.com", 3000);
60
61 InputStream is = tc1.getInputStream();
62 OutputStream os = tc1.getOutputStream();
63
64 boolean cont = waitForString(is, "Return to continue:", 30000);
65 if (cont)
66 {
67 os.write("\n".getBytes());
68 os.flush();
69 cont = waitForString(is, "city code--", 30000);
70 }
71 if (cont)
72 {
73 os.write("LAX\n".getBytes());
74 os.flush();
75 cont = waitForString(is, "Los Angeles", 30000);
76 }
77 if (cont)
78 {
79 cont = waitForString(is, "X to exit:", 30000);
80 }
81 if (cont)
82 {
83 os.write("X\n".getBytes());
84 os.flush();
85 tc1.disconnect();
86 testresult = true;
87 }
88
89 assertTrue(testresult);
90 }
91
92
93 /***
94 * Helper method. waits for a string with timeout
95 ***/
96 public boolean waitForString(InputStream is, String end, long timeout) throws Exception
97 {
98 byte buffer[] = new byte[32];
99 long starttime = System.currentTimeMillis();
100
101 String readbytes = new String();
102 while((readbytes.indexOf(end) < 0) &&
103 ((System.currentTimeMillis() - starttime) < timeout))
104 {
105 if(is.available() > 0)
106 {
107 int ret_read = is.read(buffer);
108 readbytes = readbytes + new String(buffer, 0, ret_read);
109 }
110 else
111 {
112 Thread.sleep(500);
113 }
114 }
115
116 if(readbytes.indexOf(end) >= 0)
117 {
118 return (true);
119 }
120 else
121 {
122 return (false);
123 }
124 }
125 }