1 // Copyright 2012 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 5 package org.chromium.base.test.util; 6 7 import org.junit.Assert; 8 9 import org.chromium.base.PathUtils; 10 import org.chromium.base.annotations.CalledByNative; 11 import org.chromium.base.annotations.MainDex; 12 13 /** 14 * Collection of URL utilities. 15 */ 16 @MainDex 17 public class UrlUtils { 18 private static final String DATA_DIR = "/chrome/test/data/"; 19 20 /** 21 * Construct the full path of a test data file. 22 * @param path Pathname relative to external/chrome/test/data 23 */ getTestFilePath(String path)24 public static String getTestFilePath(String path) { 25 // TODO(jbudorick): Remove DATA_DIR once everything has been isolated. crbug/400499 26 return getIsolatedTestFilePath(DATA_DIR + path); 27 } 28 29 // TODO(jbudorick): Remove this function once everything has been isolated and switched back 30 // to getTestFilePath. crbug/400499 31 /** 32 * Construct the full path of a test data file. 33 * @param path Pathname relative to external/ 34 */ getIsolatedTestFilePath(String path)35 public static String getIsolatedTestFilePath(String path) { 36 return getIsolatedTestRoot() + "/" + path; 37 } 38 39 /** 40 * Returns the root of the test data directory. 41 */ 42 @CalledByNative getIsolatedTestRoot()43 public static String getIsolatedTestRoot() { 44 return PathUtils.getExternalStorageDirectory() + "/chromium_tests_root"; 45 } 46 47 /** 48 * Construct a suitable URL for loading a test data file. 49 * @param path Pathname relative to external/chrome/test/data 50 */ getTestFileUrl(String path)51 public static String getTestFileUrl(String path) { 52 return "file://" + getTestFilePath(path); 53 } 54 55 // TODO(jbudorick): Remove this function once everything has been isolated and switched back 56 // to getTestFileUrl. crbug/400499 57 /** 58 * Construct a suitable URL for loading a test data file. 59 * @param path Pathname relative to external/ 60 */ getIsolatedTestFileUrl(String path)61 public static String getIsolatedTestFileUrl(String path) { 62 return "file://" + getIsolatedTestFilePath(path); 63 } 64 65 /** 66 * Construct a data:text/html URI for loading from an inline HTML. 67 * @param html An unencoded HTML 68 * @return String An URI that contains the given HTML 69 */ encodeHtmlDataUri(String html)70 public static String encodeHtmlDataUri(String html) { 71 try { 72 // URLEncoder encodes into application/x-www-form-encoded, so 73 // ' '->'+' needs to be undone and replaced with ' '->'%20' 74 // to match the Data URI requirements. 75 String encoded = 76 "data:text/html;utf-8," + java.net.URLEncoder.encode(html, "UTF-8"); 77 encoded = encoded.replace("+", "%20"); 78 return encoded; 79 } catch (java.io.UnsupportedEncodingException e) { 80 Assert.fail("Unsupported encoding: " + e.getMessage()); 81 return null; 82 } 83 } 84 } 85