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 * Construct a URL for loading a test data file with HTTP authentication fields. 38 * 39 * @param path path relative to the document root. 40 * @return an HTTP url. 41 */ 42 public static String getUrl(String path, String username, String password) { 43 return "http://" + username + ":" + password + "@localhost:" + SERVER_PORT + "/" + path; 44 } 45 46 /** 47 * Establishes a connection with the test server at default URL and verifies that it is running. 48 */ 49 public static void checkServerIsUp() { 50 checkServerIsUp(getUrl("chrome/test/data/android/ok.txt"), "OK Computer"); 51 } 52 53 /** 54 * Establishes a connection with the test server at a given URL and verifies that it is running 55 * by making sure that the expected response is received. 56 */ 57 public static void checkServerIsUp(String serverUrl, String expectedResponse) { 58 InputStream is = null; 59 try { 60 URL testUrl = new URL(serverUrl); 61 is = testUrl.openStream(); 62 byte[] buffer = new byte[128]; 63 int length = is.read(buffer); 64 Assert.assertNotSame("Failed to access test HTTP Server at URL: " + serverUrl, 65 -1, expectedResponse.length()); 66 Assert.assertEquals("Failed to access test HTTP Server at URL: " + serverUrl, 67 expectedResponse, new String(buffer, 0, length).trim()); 68 } catch (MalformedURLException e) { 69 Assert.fail( 70 "Failed to check test HTTP server at URL: " + serverUrl + ". Status: " + e); 71 } catch (IOException e) { 72 Assert.fail( 73 "Failed to check test HTTP server at URL: " + serverUrl + ". Status: " + e); 74 } finally { 75 StreamUtil.closeQuietly(is); 76 } 77 } 78} 79