source: trunk/autoquest-httpmonitor-test/src/test/java/de/ugoe/cs/autoquest/httpmonitor/AbstractTC.java @ 1614

Last change on this file since 1614 was 1614, checked in by pharms, 10 years ago
  • bugfix and test for correct query handling
File size: 9.1 KB
Line 
1//   Copyright 2012 Georg-August-Universität Göttingen, Germany
2//
3//   Licensed under the Apache License, Version 2.0 (the "License");
4//   you may not use this file except in compliance with the License.
5//   You may obtain a copy of the License at
6//
7//       http://www.apache.org/licenses/LICENSE-2.0
8//
9//   Unless required by applicable law or agreed to in writing, software
10//   distributed under the License is distributed on an "AS IS" BASIS,
11//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//   See the License for the specific language governing permissions and
13//   limitations under the License.
14
15package de.ugoe.cs.autoquest.httpmonitor;
16
17import static org.junit.Assert.assertEquals;
18import static org.junit.Assert.assertNotNull;
19import static org.junit.Assert.assertTrue;
20import static org.junit.Assert.fail;
21
22import java.io.BufferedReader;
23import java.io.File;
24import java.io.IOException;
25import java.io.InputStream;
26import java.io.InputStreamReader;
27import java.util.logging.Level;
28
29import org.apache.catalina.Context;
30import org.apache.catalina.startup.Tomcat;
31import org.apache.http.HttpEntity;
32import org.apache.http.HttpResponse;
33import org.apache.http.client.methods.HttpGet;
34import org.apache.http.client.methods.HttpPost;
35import org.apache.http.client.methods.HttpRequestBase;
36import org.apache.http.entity.ContentType;
37import org.apache.http.entity.StringEntity;
38import org.apache.http.impl.client.DefaultHttpClient;
39import org.junit.After;
40import org.junit.Before;
41
42import de.ugoe.cs.autoquest.eventcore.Event;
43import de.ugoe.cs.autoquest.plugin.http.eventcore.HTTPEventType;
44import de.ugoe.cs.autoquest.plugin.http.eventcore.HTTPTarget;
45import de.ugoe.cs.autoquest.plugin.http.logdata.HttpExchange;
46import de.ugoe.cs.autoquest.plugin.http.logdata.Method;
47import de.ugoe.cs.util.console.TextConsole;
48
49/**
50 *
51 */
52public abstract class AbstractTC {
53   
54    /**
55     *
56     */
57    protected static final TextConsole CONSOLE = new TextConsole(Level.FINEST);
58   
59    /**
60     *
61     */
62    protected final static String LOG_FILE_DIR = "target/tmp/logfiles/";
63   
64    /**
65     *
66     */
67    protected static final int DUMMY_SERVER_PORT = 19098;
68   
69    /**
70     *
71     */
72    protected static final int PROXY_PORT = 19099;
73   
74    /**
75     *
76     */
77    protected static final int MONITOR_PORT = 19100;
78   
79    /**
80     * the servlet of the dummy web server responding to requests
81     */
82    private DummyServlet dummyServlet;
83   
84    /** */
85    private static Tomcat tomcat = new Tomcat();
86   
87    /**
88     *
89     */
90    static String readStreamContentToString(InputStream stream) throws IOException {
91        return readToString(new BufferedReader(new InputStreamReader(stream)));
92    }
93   
94    /**
95     *
96     */
97    static String readToString(BufferedReader reader) throws IOException {
98        StringBuffer message = new StringBuffer();
99       
100        String line = reader.readLine();
101        while (line != null) {
102            System.err.println(line);
103            if (message.length() > 0) {
104                message.append('\n');
105            }
106            message.append(line);
107            line = reader.readLine();
108        }
109       
110        return message.toString();
111    }
112
113    /**
114     *
115     */
116    @Before
117    public void setUp() throws Exception {
118        // setup a simple HTTP server
119        dummyServlet = new DummyServlet();
120       
121        /*dummyServer = new Server(DUMMY_SERVER_PORT);
122       
123        ServletContextHandler root =
124            new ServletContextHandler(dummyServer, "/dummyServer", ServletContextHandler.SESSIONS);
125
126       
127        root.addServlet(new ServletHolder(dummyServlet), "/*");
128       
129        dummyServer.start();*/
130       
131        File tomcatDir = new File("target/test/tomcat");
132        File webappRootDir = new File(tomcatDir, "webapp");
133       
134        tomcat = new Tomcat();
135        tomcat.setPort(DUMMY_SERVER_PORT);
136        tomcat.setBaseDir(tomcatDir.getAbsolutePath());
137
138        File warFile = new File(webappRootDir, "dummyService.war");
139        tomcat.addWebapp("/dummyWebapp", warFile.getAbsolutePath());
140        System.out.println("configuring Dummy Service from " + warFile.getAbsolutePath());
141       
142        File servletRootDir = new File(tomcatDir, "servlet");
143        servletRootDir.mkdirs();
144        Context ctx = tomcat.addContext("/", servletRootDir.getAbsolutePath());
145        Tomcat.addServlet(ctx, "dummyServlet", dummyServlet);
146        ctx.addServletMapping("/dummyServlet", "dummyServlet");
147       
148        tomcat.start();
149       
150        setUpHook();
151    }
152
153    /**
154     *
155     */
156    protected abstract void setUpHook() throws Exception;
157
158    /**
159     *
160     */
161    @After
162    public void tearDown() throws Exception {
163        // give all started servers a second to finalize their internal work after the test
164        // execution. This prevents some unnecessary exceptions due to requests already processed
165        // by the test case but not finalized on server side.
166        Thread.sleep(1000);
167        tearDownHook();
168
169        if (tomcat != null) {
170            try {
171                tomcat.stop();
172                tomcat.getServer().await();
173                tomcat.destroy();
174            }
175            finally {
176                tomcat = null;
177            }
178        }
179       
180        deleteFiles(new File(LOG_FILE_DIR));
181    }
182
183    /**
184     *
185     */
186    protected abstract void tearDownHook() throws Exception;
187
188    /**
189     *
190     */
191    protected String sendDummyMessage(String type, String query, String message, String respMsg)
192        throws Exception
193    {
194        dummyServlet.setResponse(respMsg);
195       
196        System.err.println("sending message: " + message);
197        DefaultHttpClient httpclient = new DefaultHttpClient();
198        HttpRequestBase httpRequest = null;
199       
200        String uri = "http://localhost:" + PROXY_PORT + "/dummyServlet";
201       
202        if (query != null) {
203            uri += "?" + query;
204        }
205       
206        if ("POST".equals(type)) {
207            httpRequest = new HttpPost(uri);
208            HttpEntity entity = new StringEntity(message, ContentType.TEXT_PLAIN);
209            ((HttpPost) httpRequest).setEntity(entity);
210        }
211        else if ("GET".equals(type)) {
212            httpRequest = new HttpGet(uri);
213        }
214       
215        try {
216            HttpResponse response = httpclient.execute(httpRequest);
217           
218            assertEquals(message, dummyServlet.getRequest());
219            assertEquals(query, dummyServlet.getQuery());
220            System.err.println(response.getStatusLine());
221            String responseStr = readStreamContentToString(response.getEntity().getContent());
222            System.err.println("received response: " + responseStr);
223            return responseStr;
224        }
225        finally {
226            httpRequest.releaseConnection();
227        }
228    }
229   
230    /**
231     *
232     */
233    protected void assertEvent(Event  event,
234                               String method,
235                               String query,
236                               String message,
237                               String response)
238    {
239        assertNotNull(event);
240        assertNotNull(event.getType());
241        assertNotNull(event.getTarget());
242       
243        assertTrue(event.getType() instanceof HTTPEventType);
244        assertTrue(event.getTarget() instanceof HTTPTarget);
245       
246        assertExchange(((HTTPEventType) event.getType()).getExchange(),
247                       method, query, message, response);
248    }
249   
250    /**
251     *
252     */
253    protected void assertExchange(HttpExchange exchange,
254                                  String       method,
255                                  String       query,
256                                  String       message,
257                                  String       response)
258    {
259        assertEquals(Method.fromValue(method), exchange.getRequest().getMethod());
260       
261        if (query != null) {
262            assertEquals(query, exchange.getRequest().getQuery());
263        }
264        else if (exchange.getRequest().getQuery() != null) {
265            System.err.println(exchange.getRequest().getQuery());
266            fail("unexpected query");
267        }
268       
269        if (message != null) {
270            assertEquals(message, exchange.getRequest().getContent().getData());
271        }
272        else if (exchange.getRequest().getContent() != null) {
273            System.err.println(exchange.getRequest().getContent().getData());
274        }
275       
276        if (response != null) {
277            assertEquals(response, exchange.getResponse().getContent().getData());
278        }
279        else if (exchange.getResponse().getContent() != null) {
280            System.err.println(exchange.getResponse().getContent().getData());
281        }
282    }
283
284    /**
285     *
286     */
287    protected void deleteFiles(File file) {
288        if (file.exists()) {
289            if (file.isDirectory()) {
290                for (File child : file.listFiles()) {
291                    deleteFiles(child);
292                }
293            }
294           
295            try {
296                file.delete();
297            }
298            catch (Exception e) {
299                // ignore and delete as much as possible
300            }
301        }
302    }
303
304}
Note: See TracBrowser for help on using the repository browser.