summaryrefslogtreecommitdiffstats
path: root/mobile/android/test_runner/src/main/java/org/mozilla/geckoview/test_runner/TestRunnerApiEngine.java
blob: 7d6a72d62fe9bc7b3458d914a3511258443daf23 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */

package org.mozilla.geckoview.test_runner;

import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.json.JSONException;
import org.json.JSONObject;
import org.mozilla.geckoview.GeckoResult;
import org.mozilla.geckoview.WebExtension;

// Receives API calls from AppUiTestDelegate.jsm and forwards the calls to the
// Api impl.
public class TestRunnerApiEngine implements WebExtension.MessageDelegate {
  private static final String LOGTAG = "TestRunnerAPI";

  public interface Api {
    GeckoResult<Void> clickBrowserAction(String extensionId);

    GeckoResult<Void> clickPageAction(String extensionId);

    GeckoResult<Void> closePopup();

    GeckoResult<Void> awaitExtensionPopup(String extensionId);
  }

  private final Api mImpl;

  public TestRunnerApiEngine(final Api impl) {
    mImpl = impl;
  }

  @SuppressWarnings("unchecked")
  private GeckoResult<Object> handleMessage(final JSONObject message) throws JSONException {
    final String type = message.getString("type");

    Log.i(LOGTAG, "Test API: " + type);

    if ("clickBrowserAction".equals(type)) {
      return (GeckoResult) mImpl.clickBrowserAction(message.getString("extensionId"));
    } else if ("clickPageAction".equals(type)) {
      return (GeckoResult) mImpl.clickPageAction(message.getString("extensionId"));
    } else if ("closeBrowserAction".equals(type)) {
      return (GeckoResult) mImpl.closePopup();
    } else if ("closePageAction".equals(type)) {
      return (GeckoResult) mImpl.closePopup();
    } else if ("awaitExtensionPanel".equals(type)) {
      return (GeckoResult) mImpl.awaitExtensionPopup(message.getString("extensionId"));
    }

    return GeckoResult.fromException(new RuntimeException("Unrecognized command " + type));
  }

  @Nullable
  @Override
  public GeckoResult<Object> onMessage(
      @NonNull final String nativeApp,
      @NonNull final Object message,
      @NonNull final WebExtension.MessageSender sender) {
    try {
      return handleMessage((JSONObject) message);
    } catch (final JSONException ex) {
      throw new RuntimeException(ex);
    }
  }
}