1 // Copyright 2020 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.url;
6 
7 import java.util.Collections;
8 import java.util.HashMap;
9 import java.util.Map;
10 
11 /**
12  * A Helper class for JUnit tests to be able to use GURLs without requiring native initialization.
13  * This should be used sparingly, when converting junit tests to Batched Instrumentation tests is
14  * not feasible.
15  *
16  * If any more complex GURL behaviour is tested, like comparing Origins, the test should be written
17  * as an Instrumentation test instead - you should never mock GURL.
18  */
19 public class JUnitTestGURLs {
20     // In order to add a test URL:
21     // 1. Add the URL String as a constant here.
22     // 2. Add the constant to the map below, with a placeholder string for the GURL serialization.
23     // 3. Run JUnitTestGURLsTest (eg. './tools/autotest.py -C out/Debug JUnitTestGURLsTest').
24     // 4. Check logcat output or test exception for the correct serialization String, and place it
25     //    in the map.
26     public static final String EXAMPLE_URL = "https://www.example.com";
27     public static final String URL_1 = "https://www.one.com";
28     public static final String URL_2 = "https://www.two.com";
29 
30     // Map of URL string to GURL serialization.
31     /* package */ static final Map<String, String> sGURLMap;
32     static {
33         Map<String, String> map = new HashMap<>();
map.put(EXAMPLE_URL, R + R)34         map.put(EXAMPLE_URL,
35                 "82,1,true,0,5,0,-1,0,-1,8,15,0,-1,23,1,0,-1,0,-1,"
36                         + "false,false,https://www.example.com/");
map.put(URL_1, R + R)37         map.put(URL_1,
38                 "78,1,true,0,5,0,-1,0,-1,8,11,0,-1,19,1,0,-1,0,-1,"
39                         + "false,false,https://www.one.com/");
map.put(URL_2, R + R)40         map.put(URL_2,
41                 "78,1,true,0,5,0,-1,0,-1,8,11,0,-1,19,1,0,-1,0,-1,"
42                         + "false,false,https://www.two.com/");
43         sGURLMap = Collections.unmodifiableMap(map);
44     }
45 
46     /**
47      * @return the GURL resulting from parsing the provided url. Must be registered in |sGURLMap|.
48      */
getGURL(String url)49     public static GURL getGURL(String url) {
50         String serialized = sGURLMap.get(url);
51         if (serialized == null) {
52             throw new IllegalArgumentException("URL " + url + " not found");
53         }
54         serialized = serialized.replace(',', GURL.SERIALIZER_DELIMITER);
55         GURL gurl = GURL.deserialize(serialized);
56         // If you're here looking to use an empty GURL, just use GURL.emptyGURL() directly.
57         if (gurl.isEmpty()) {
58             throw new RuntimeException("Could not deserialize: " + serialized);
59         }
60         return gurl;
61     }
62 }
63