Bug 1576730 - Reduce boilerplate in test api call. r=snorp
authorAgi Sferro <agi@sferro.dev>
Thu, 05 Sep 2019 15:56:41 +0000
changeset 491891 8c18ee635cc7074204c41b8186be86bce0a7107e
parent 491890 dc6b987ba5bfe5c1e0f3d6b25b0d51a4359feda8
child 491892 42c5861d697be73da3fa604a19355976e7b5d2d5
push id94579
push userasferro@mozilla.com
push dateThu, 05 Sep 2019 15:58:20 +0000
treeherderautoland@42c5861d697b [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewerssnorp
bugs1576730
milestone71.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1576730 - Reduce boilerplate in test api call. r=snorp Differential Revision: https://phabricator.services.mozilla.com/D44538
mobile/android/geckoview/src/androidTest/assets/web_extensions/test-support/background.js
mobile/android/geckoview/src/androidTest/java/org/mozilla/geckoview/test/rule/GeckoSessionTestRule.java
--- a/mobile/android/geckoview/src/androidTest/assets/web_extensions/test-support/background.js
+++ b/mobile/android/geckoview/src/androidTest/assets/web_extensions/test-support/background.js
@@ -1,75 +1,44 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 const port = browser.runtime.connectNative("browser");
 
-port.onMessage.addListener(async message => {
-  switch (message.type) {
-    case "SetPrefs":
-      {
-        const {
-          id,
-          args: { oldPrefs, newPrefs },
-        } = message;
-        sendResponse(id, browser.test.setPrefs(oldPrefs, newPrefs));
-      }
-      break;
-
-    case "RestorePrefs":
-      {
-        const {
-          id,
-          args: { oldPrefs },
-        } = message;
-        sendResponse(id, browser.test.restorePrefs(oldPrefs));
-      }
-      break;
+const APIS = {
+  AddHistogram: function({ id, value }) {
+    browser.test.addHistogram(id, value);
+  },
+  GetRequestedLocales: function() {
+    return browser.test.getRequestedLocales();
+  },
+  GetLinkColor: function({ uri, selector }) {
+    return browser.test.getLinkColor(uri, selector);
+  },
+  GetPrefs: function({ prefs }) {
+    return browser.test.getPrefs(prefs);
+  },
+  RestorePrefs: function({ oldPrefs }) {
+    return browser.test.restorePrefs(oldPrefs);
+  },
+  SetPrefs: function({ oldPrefs, newPrefs }) {
+    return browser.test.setPrefs(oldPrefs, newPrefs);
+  },
+};
 
-    case "GetPrefs":
-      {
-        const {
-          id,
-          args: { prefs },
-        } = message;
-        sendResponse(id, browser.test.getPrefs(prefs));
-      }
-      break;
-
-    case "GetLinkColor":
-      {
-        const {
-          id,
-          args: { uri, selector },
-        } = message;
-        sendResponse(id, browser.test.getLinkColor(uri, selector));
-      }
-      break;
+port.onMessage.addListener(async message => {
+  const impl = APIS[message.type];
+  apiCall(message, impl);
+});
 
-    case "GetRequestedLocales":
-      {
-        const { id } = message;
-        sendResponse(id, browser.test.getRequestedLocales());
-      }
-      break;
-
-    case "AddHistogram":
-      {
-        const {
-          id,
-          args: { id: histogramId, value },
-        } = message;
-        browser.test.addHistogram(histogramId, value);
-        sendResponse(id, null);
-      }
-      break;
-  }
-});
+function apiCall(message, impl) {
+  const { id, args } = message;
+  sendResponse(id, impl(args));
+}
 
 function sendResponse(id, response, exception) {
   Promise.resolve(response).then(
     value => sendSyncResponse(id, value),
     reason => sendSyncResponse(id, null, reason)
   );
 }
 
--- a/mobile/android/geckoview/src/androidTest/java/org/mozilla/geckoview/test/rule/GeckoSessionTestRule.java
+++ b/mobile/android/geckoview/src/androidTest/java/org/mozilla/geckoview/test/rule/GeckoSessionTestRule.java
@@ -609,55 +609,45 @@ public class GeckoSessionTestRule implem
 
         @NonNull
         public List<ExternalDelegate<?>> getExternalDelegates() {
             return mExternalDelegates;
         }
 
         /** Generate a JS function to set new prefs and return a set of saved prefs. */
         public void setPrefs(final @NonNull Map<String, ?> prefs) {
-            try {
+            mOldPrefs = (JSONObject) webExtensionApiCall("SetPrefs", args -> {
                 final JSONObject existingPrefs = mOldPrefs != null ? mOldPrefs : new JSONObject();
 
                 final JSONObject newPrefs = new JSONObject();
                 for (final Map.Entry<String, ?> pref : prefs.entrySet()) {
                     final Object value = pref.getValue();
                     if (value instanceof Boolean || value instanceof Number ||
                             value instanceof CharSequence) {
                         newPrefs.put(pref.getKey(), value);
                     } else {
                         throw new IllegalArgumentException("Unsupported pref value: " + value);
                     }
                 }
 
-                final JSONObject args = new JSONObject();
                 args.put("oldPrefs", existingPrefs);
                 args.put("newPrefs", newPrefs);
-
-                mOldPrefs = (JSONObject) webExtensionApiCall("SetPrefs", args);
-            } catch (JSONException ex) {
-                throw new RuntimeException(ex);
-            }
+            });
         }
 
         /** Generate a JS function to set new prefs and reset a set of saved prefs. */
         private void restorePrefs() {
             if (mOldPrefs == null) {
                 return;
             }
 
-            try {
-                final JSONObject args = new JSONObject();
+            webExtensionApiCall("RestorePrefs", args -> {
                 args.put("oldPrefs", mOldPrefs);
-                webExtensionApiCall("RestorePrefs", args);
-
                 mOldPrefs = null;
-            } catch (JSONException ex) {
-                throw new RuntimeException(ex);
-            }
+            });
         }
 
         public void clear() {
             for (int i = mExternalDelegates.size() - 1; i >= 0; i--) {
                 mExternalDelegates.get(i).unregister();
             }
             mExternalDelegates.clear();
             mDelegates.clear();
@@ -1992,43 +1982,33 @@ public class GeckoSessionTestRule implem
 
     /**
      * Get a list of Gecko prefs. Undefined prefs will return as null.
      *
      * @param prefs List of pref names.
      * @return Pref values as a list of values.
      */
     public JSONArray getPrefs(final @NonNull String... prefs) {
-        try {
-            final JSONObject args = new JSONObject();
+        return (JSONArray) webExtensionApiCall("GetPrefs", args -> {
             args.put("prefs", new JSONArray(Arrays.asList(prefs)));
-
-            return (JSONArray) webExtensionApiCall("GetPrefs", args);
-        } catch (JSONException ex) {
-            throw new RuntimeException(ex);
-        }
+        });
     }
 
     /**
      * Gets the color of a link for a given URI and selector.
      *
      * @param uri Page where the link is present.
      * @param selector Selector that matches the link
      * @return String representing the color, e.g. rgb(0, 0, 255)
      */
     public String getLinkColor(final String uri, final String selector) {
-        try {
-            final JSONObject args = new JSONObject();
+        return (String) webExtensionApiCall("GetLinkColor", args -> {
             args.put("uri", uri);
             args.put("selector", selector);
-
-            return (String) webExtensionApiCall("GetLinkColor", args);
-        } catch (JSONException ex) {
-            throw new RuntimeException(ex);
-        }
+        });
     }
 
     public List<String> getRequestedLocales() {
         try {
             JSONArray locales = (JSONArray) webExtensionApiCall("GetRequestedLocales", null);
             List<String> result = new ArrayList<>();
 
             for (int i = 0; i < locales.length(); i++) {
@@ -2043,38 +2023,47 @@ public class GeckoSessionTestRule implem
 
     /**
      * Adds value to the given histogram.
      *
      * @param id the histogram id to increment.
      * @param value to add to the histogram.
      */
     public void addHistogram(final String id, final long value) {
-        try {
-            final JSONObject args = new JSONObject();
+        webExtensionApiCall("AddHistogram", args -> {
             args.put("id", id);
             args.put("value", value);
-
-            webExtensionApiCall("AddHistogram", args);
-        } catch (JSONException ex) {
-            throw new RuntimeException(ex);
-        }
+        });
     }
 
-    private Object webExtensionApiCall(final String apiName, JSONObject args) throws JSONException {
+    private interface SetArgs {
+        void setArgs(JSONObject object) throws JSONException;
+    }
+
+    private Object webExtensionApiCall(final String apiName, SetArgs argsSetter) {
         // Ensure background script is connected
         UiThreadUtils.waitForCondition(() -> RuntimeCreator.backgroundPort() != null,
                 mTimeoutMillis);
 
         final String id = UUID.randomUUID().toString();
 
         final JSONObject message = new JSONObject();
-        message.put("id", id);
-        message.put("type", apiName);
-        message.put("args", args);
+
+        try {
+            final JSONObject args = new JSONObject();
+            if (argsSetter != null) {
+                argsSetter.setArgs(args);
+            }
+
+            message.put("id", id);
+            message.put("type", apiName);
+            message.put("args", args);
+        } catch (JSONException ex) {
+            throw new RuntimeException(ex);
+        }
 
         RuntimeCreator.backgroundPort().postMessage(message);
         return waitForMessage(id);
     }
 
     /**
      * Set a list of Gecko prefs for the rest of the test. Prefs set in {@link #setPrefsDuringNextWait} can
      * temporarily take precedence over prefs set in {@code setPrefsUntilTestEnd}.