TestHttpServerClient.java revision 424c4d7b64af9d0d8fd9624f381f469654d5e3d2
1// Copyright 2013 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5package org.chromium.chrome.test.util; 6 7import junit.framework.Assert; 8 9import org.chromium.chrome.browser.util.StreamUtil; 10 11import java.io.IOException; 12import java.io.InputStream; 13import java.net.MalformedURLException; 14import java.net.URL; 15 16/** 17 * A test utility class to get URLs that point to the test HTTP server, and to verify that it is up 18 * and giving expected responses to given URLs. 19 */ 20public final class TestHttpServerClient { 21 private static final int SERVER_PORT = 8000; 22 23 private TestHttpServerClient() { 24 } 25 26 /** 27 * Construct a suitable URL for loading a test data file from the hosts' HTTP server. 28 * 29 * @param path path relative to the document root. 30 * @return an HTTP url. 31 */ 32 public static String getUrl(String path) { 33 return "http://localhost:" + SERVER_PORT + "/" + path; 34 } 35 36 /** 37 * Establishes a connection with the test server at default URL and verifies that it is running. 38 */ 39 public static void checkServerIsUp() { 40 checkServerIsUp(getUrl("chrome/test/data/android/ok.txt"), "OK Computer"); 41 } 42 43 /** 44 * Establishes a connection with the test server at a given URL and verifies that it is running 45 * by making sure that the expected response is received. 46 */ 47 public static void checkServerIsUp(String serverUrl, String expectedResponse) { 48 InputStream is = null; 49 try { 50 URL testUrl = new URL(serverUrl); 51 is = testUrl.openStream(); 52 byte[] buffer = new byte[128]; 53 int length = is.read(buffer); 54 Assert.assertNotSame("Failed to access test HTTP Server at URL: " + serverUrl, 55 -1, expectedResponse.length()); 56 Assert.assertEquals("Failed to access test HTTP Server at URL: " + serverUrl, 57 expectedResponse, new String(buffer, 0, length).trim()); 58 } catch (MalformedURLException e) { 59 Assert.fail( 60 "Failed to check test HTTP server at URL: " + serverUrl + ". Status: " + e); 61 } catch (IOException e) { 62 Assert.fail( 63 "Failed to check test HTTP server at URL: " + serverUrl + ". Status: " + e); 64 } finally { 65 StreamUtil.closeQuietly(is); 66 } 67 } 68} 69