okhttp3.mockwebserver.MockWebServer Java Examples

The following examples show how to use okhttp3.mockwebserver.MockWebServer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EmitterTest.java    From snowplow-android-tracker with Apache License 2.0 6 votes vote down vote up
public void testEmitTwoGetEvents() throws InterruptedException, IOException {
    MockWebServer mockServer = getMockServer();
    EmittableEvents emittableEvents = getEmittableEvents(mockServer, 2);
    Emitter emitter = getEmitter(getMockServerURI(mockServer), HttpMethod.GET, BufferOption.Single, RequestSecurity.HTTP);

    LinkedList<RequestResult> result = emitter.performAsyncEmit(emitter.buildRequests(emittableEvents));
    assertEquals(2, result.size());
    assertEquals(0, result.getFirst().getEventIds().getFirst().intValue());
    assertEquals(1, result.get(1).getEventIds().getFirst().intValue());

    RecordedRequest req = mockServer.takeRequest(2, TimeUnit.SECONDS);
    assertGETRequest(req);

    req = mockServer.takeRequest(2, TimeUnit.SECONDS);
    assertGETRequest(req);

    mockServer.shutdown();
}
 
Example #2
Source File: ServerTest.java    From java-stellar-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testCheckMemoRequiredWithMemo() throws IOException, AccountRequiresMemoException {
    MockWebServer mockWebServer = new MockWebServer();
    mockWebServer.setDispatcher(buildTestCheckMemoRequiredMockDispatcher());
    mockWebServer.start();
    HttpUrl baseUrl = mockWebServer.url("");
    Server server = new Server(baseUrl.toString());

    KeyPair source = KeyPair.fromSecretSeed("SDQXFKA32UVQHUTLYJ42N56ZUEM5PNVVI4XE7EA5QFMLA2DHDCQX3GPY");
    Account account = new Account(source.getAccountId(), 1L);
    Transaction transaction = new Transaction.Builder(account, Network.PUBLIC)
            .addOperation(new PaymentOperation.Builder(DESTINATION_ACCOUNT_MEMO_REQUIRED_A, new AssetTypeNative(), "10").build())
            .addOperation(new PathPaymentStrictReceiveOperation.Builder(new AssetTypeNative(), "10", DESTINATION_ACCOUNT_MEMO_REQUIRED_B, new AssetTypeCreditAlphaNum4("BTC", "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2"), "5").build())
            .addOperation(new PathPaymentStrictSendOperation.Builder(new AssetTypeNative(), "10", DESTINATION_ACCOUNT_MEMO_REQUIRED_C, new AssetTypeCreditAlphaNum4("BTC", "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2"), "5").build())
            .addOperation(new AccountMergeOperation.Builder(DESTINATION_ACCOUNT_MEMO_REQUIRED_D).build())
            .setTimeout(Transaction.Builder.TIMEOUT_INFINITE)
            .addMemo(new MemoText("Hello, Stellar."))
            .setBaseFee(100)
            .build();
    transaction.sign(source);
    server.submitTransaction(transaction);
    server.submitTransaction(feeBump(transaction));
}
 
Example #3
Source File: MockWebServerUtil.java    From appcenter-plugin with MIT License 6 votes vote down vote up
private static void enqueueSuccess(final @Nonnull MockWebServer mockAppCenterServer, final @Nonnull MockWebServer mockUploadServer) {
    mockAppCenterServer.enqueue(new MockResponse().setResponseCode(HTTP_CREATED).setBody("{\n" +
        "  \"upload_id\": \"string\",\n" +
        "  \"upload_url\": \"" + mockUploadServer.url("/").toString() + "\",\n" +
        "  \"asset_id\": \"string\",\n" +
        "  \"asset_domain\": \"string\",\n" +
        "  \"asset_token\": \"string\"\n" +
        "}"));
    mockUploadServer.enqueue(new MockResponse().setResponseCode(HTTP_OK));
    mockAppCenterServer.enqueue(new MockResponse().setResponseCode(HTTP_OK).setBody("{\n" +
        "  \"release_id\": 0,\n" +
        "  \"release_url\": \"string\"\n" +
        "}"));
    mockAppCenterServer.enqueue(new MockResponse().setResponseCode(HTTP_OK).setBody("{\n" +
        "  \"release_notes\": \"string\"\n" +
        "}"));
}
 
Example #4
Source File: MapboxOptimizationTest.java    From mapbox-java with MIT License 6 votes vote down vote up
@Before
public void setUp() throws IOException {
  server = new MockWebServer();

  server.setDispatcher(new okhttp3.mockwebserver.Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {

      String resource = OPTIMIZATION_FIXTURE;

      try {
        String body = loadJsonFixture(resource);
        return new MockResponse().setBody(body);
      } catch (IOException ioException) {
        throw new RuntimeException(ioException);
      }
    }
  });
  server.start();
  mockUrl = server.url("");
}
 
Example #5
Source File: IndexTests.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Uses a mock web server to record a _find request using the specified options
 *
 * @param builder query to make
 * @return the JsonElement from the use_index property of the JsonObject POSTed with the request
 * @throws Exception
 */
private JsonElement getUseIndexFromRequest(QueryBuilder builder) throws Exception {
    JsonElement useIndexRequestProperty = null;
    MockWebServer mockWebServer = new MockWebServer();
    // Return 200 OK with empty array of docs (once for each request)
    mockWebServer.enqueue(new MockResponse().setBody("{ \"docs\" : []}"));
    mockWebServer.start();
    try {
        CloudantClient client = CloudantClientHelper.newMockWebServerClientBuilder
                (mockWebServer).build();
        Database db = client.database("mock", false);
        db.query(builder.build(), Movie.class);
        RecordedRequest request = mockWebServer.takeRequest(1, TimeUnit.SECONDS);
        JsonObject body = new Gson().fromJson(request.getBody().readUtf8(), JsonObject.class);
        useIndexRequestProperty = body.get("use_index");
    } finally {
        mockWebServer.shutdown();
    }
    return useIndexRequestProperty;
}
 
Example #6
Source File: TinifyTest.java    From tinify-java with MIT License 6 votes vote down vote up
@Before
public void setup() throws IOException {
    Logger.getLogger(MockWebServer.class.getName()).setLevel(Level.WARNING);

    server = new MockWebServer();
    server.start();
    new MockUp<HttpUrl>()
    {
        @Mock
        @SuppressWarnings("unused")
        HttpUrl parse(Invocation inv, String url)
        {
            if (url.contains("localhost")) {
                return inv.proceed();
            } else {
                return new HttpUrl.Builder()
                        .scheme("http")
                        .host(server.getHostName())
                        .port(server.getPort())
                        .encodedPath(url.replaceFirst(Client.API_ENDPOINT, ""))
                        .build();
            }
        }
    };
}
 
Example #7
Source File: PushGatewayProviderTest.java    From graylog-plugin-metrics-reporter with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void getReturnsPushGatewayProvider() throws Exception {
    final MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_ACCEPTED));
    server.start();

    final MetricsPrometheusReporterConfiguration configuration = new MetricsPrometheusReporterConfiguration() {
        @Override
        public HostAndPort getAddress() {
            return HostAndPort.fromParts(server.getHostName(), server.getPort());
        }
    };
    final PushGatewayProvider provider = new PushGatewayProvider(configuration);
    final PushGateway pushGateway = provider.get();
    pushGateway.push(CollectorRegistry.defaultRegistry, "test");

    final RecordedRequest request = server.takeRequest();
    assertEquals("PUT", request.getMethod());
    assertEquals("/metrics/job/test", request.getPath());
    assertEquals("text/plain; version=0.0.4; charset=utf-8", request.getHeader("Content-Type"));
    assertEquals(0L, request.getBodySize());
}
 
Example #8
Source File: WebViewDataTest.java    From focus-android with Mozilla Public License 2.0 6 votes vote down vote up
private void assertPathsHaveBeenRequested(MockWebServer webServer, String... paths) throws InterruptedException {
    final List<String> expectedPaths = new ArrayList<>(paths.length);
    Collections.addAll(expectedPaths, paths);

    RecordedRequest request;

    while ((request = webServer.takeRequest(waitingTime, TimeUnit.MILLISECONDS)) != null) {
        if (!expectedPaths.remove(request.getPath())) {
            throw new AssertionError("Unknown path requested: " + request.getPath());
        }
    }

    if (!expectedPaths.isEmpty()) {
        throw new AssertionError("Expected paths not requested: " + expectedPaths);
    }
}
 
Example #9
Source File: WebAPITest.java    From JavaSteam with MIT License 6 votes vote down vote up
@Before
public void setUp() throws IOException {
    lock = new CountDownLatch(1);
    server = new MockWebServer();

    server.enqueue(new MockResponse().setBody("" +
            "\"root\"" +
            "{" +
            "    \"name\" \"stringvalue\"" +
            "}"));

    server.start();

    baseUrl = server.url("/");

    config = SteamConfiguration.create(new Consumer<ISteamConfigurationBuilder>() {
        @Override
        public void accept(ISteamConfigurationBuilder b) {
            b.withWebAPIBaseAddress(baseUrl.toString());
        }
    });
}
 
Example #10
Source File: ClientTest.java    From tinify-java with MIT License 6 votes vote down vote up
@Before
public void setup() throws IOException {
    Logger.getLogger(MockWebServer.class.getName()).setLevel(Level.WARNING);

    server = new MockWebServer();
    server.start();
    subject = new Client(key);
    new MockUp<HttpUrl>()
    {
        @Mock
        @SuppressWarnings("unused")
        HttpUrl parse(Invocation inv, String url)
        {
            if (url.contains("localhost")) {
                return inv.proceed();
            } else {
                return new HttpUrl.Builder()
                        .scheme("http")
                        .host(server.getHostName())
                        .port(server.getPort())
                        .encodedPath("/shrink")
                        .build();
            }
        }
    };
}
 
Example #11
Source File: AllowListScreenshots.java    From focus-android with Mozilla Public License 2.0 6 votes vote down vote up
@Before
public void setUpWebServer() throws IOException {
    webServer = new MockWebServer();

    // Test page
    webServer.enqueue(new MockResponse()
            .setBody(TestHelper.readTestAsset("image_test.html")));
    webServer.enqueue(new MockResponse()
            .setBody(TestHelper.readTestAsset("rabbit.jpg")));
    webServer.enqueue(new MockResponse()
            .setBody(TestHelper.readTestAsset("download.jpg")));
    // Download
    webServer.enqueue(new MockResponse()
            .setBody(TestHelper.readTestAsset("image_test.html")));
    webServer.enqueue(new MockResponse()
            .setBody(TestHelper.readTestAsset("rabbit.jpg")));
    webServer.enqueue(new MockResponse()
            .setBody(TestHelper.readTestAsset("download.jpg")));
}
 
Example #12
Source File: SixpackTest.java    From sixpack-java with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testGetClientIdInterceptor() throws IOException {
    String clientId = "test-client-id";

    MockWebServer webServer = new MockWebServer();
    webServer.enqueue(new MockResponse());
    webServer.start();
    HttpUrl url = webServer.url("/");

    Interceptor clientIdInterceptor = Sixpack.getClientIdInterceptor(clientId);
    assertNotNull(clientIdInterceptor);

    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(clientIdInterceptor)
            .build();

    Response response = client.newCall(new Request.Builder().url(url).build()).execute();

    assertEquals(clientId, response.request().url().queryParameter("client_id"));
}
 
Example #13
Source File: CustomTabTest.java    From focus-android with Mozilla Public License 2.0 6 votes vote down vote up
private void startWebServer() {
    final Context appContext = InstrumentationRegistry.getInstrumentation()
            .getTargetContext()
            .getApplicationContext();

    PreferenceManager.getDefaultSharedPreferences(appContext)
            .edit()
            .putBoolean(FIRSTRUN_PREF, true)
            .apply();

    webServer = new MockWebServer();

    try {
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("plain_test.html")));
        webServer.start();
    } catch (IOException e) {
        throw new AssertionError("Could not start web server", e);
    }
}
 
Example #14
Source File: IsochroneTestUtils.java    From mapbox-java with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    server = new MockWebServer();
    server.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            try {
                String response = loadJsonFixture(ISOCHRONE_WITH_POLYGONS_VALID);
                if (request.getPath().contains("polygons=false")) {
                    response = loadJsonFixture(ISOCHRONE_NO_POLYGONS_VALID);
                }
                return new MockResponse().setBody(response);
            } catch (IOException ioException) {
                throw new RuntimeException(ioException);
            }
        }
    });
    server.start();
    mockUrl = server.url("");
}
 
Example #15
Source File: TilequeryTestUtils.java    From mapbox-java with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    server = new MockWebServer();
    server.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            try {
                String response = loadJsonFixture(TILEQUERY_VALID);
                if (request.getPath().contains("limit")) {
                    response = loadJsonFixture(TILEQUERY_ALL_PARAM_VALID);
                }
                return new MockResponse().setBody(response);
            } catch (IOException ioException) {
                throw new RuntimeException(ioException);
            }
        }
    });
    server.start();
    mockUrl = server.url("");
}
 
Example #16
Source File: TelemetryInterceptorTest.java    From auth0-java with MIT License 6 votes vote down vote up
@Test
public void shouldNotAddTelemetryHeaderIfDisabled() throws Exception {
    TelemetryInterceptor interceptor = new TelemetryInterceptor(telemetry);
    interceptor.setEnabled(false);
    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .build();

    MockWebServer server = new MockWebServer();
    server.start();
    server.enqueue(new MockResponse());

    Request request = new Request.Builder()
            .get()
            .url(server.url("/"))
            .build();
    client.newCall(request).execute();

    RecordedRequest finalRequest = server.takeRequest();
    assertThat(finalRequest.getHeader("Auth0-Client"), is(nullValue()));

    server.shutdown();
}
 
Example #17
Source File: FederationTest.java    From java-stellar-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testResolveSuccess() throws IOException {
  MockWebServer mockWebServer = new MockWebServer();
  mockWebServer.start();

  HttpUrl baseUrl = mockWebServer.url("");
  String domain = String.format("%s:%d", baseUrl.host(), baseUrl.port());

    String stellarToml =
            "FEDERATION_SERVER = \"http://"+domain+"/federation\"";
    String successResponse =
            "{\"stellar_address\":\"bob*"+domain+"\",\"account_id\":\"GCW667JUHCOP5Y7KY6KGDHNPHFM4CS3FCBQ7QWDUALXTX3PGXLSOEALY\"}";

  mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(stellarToml));
  mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(successResponse));

  FederationResponse response = Federation.resolve("bob*"+domain);
  assertEquals(response.getStellarAddress(), "bob*"+domain);
  assertEquals(response.getAccountId(), "GCW667JUHCOP5Y7KY6KGDHNPHFM4CS3FCBQ7QWDUALXTX3PGXLSOEALY");
  assertNull(response.getMemoType());
  assertNull(response.getMemo());
}
 
Example #18
Source File: TestQueryRunner.java    From presto with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void setup()
        throws IOException
{
    server = new MockWebServer();
    server.start();
}
 
Example #19
Source File: EmbeddedApollo.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Override
protected void before() throws Throwable {
  clear();
  server = new MockWebServer();
  final Dispatcher dispatcher = new Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
      if (request.getPath().startsWith("/notifications/v2")) {
        String notifications = request.getRequestUrl().queryParameter("notifications");
        return new MockResponse().setResponseCode(200).setBody(mockLongPollBody(notifications));
      }
      if (request.getPath().startsWith("/configs")) {
        List<String> pathSegments = request.getRequestUrl().pathSegments();
        // appId and cluster might be used in the future
        String appId = pathSegments.get(1);
        String cluster = pathSegments.get(2);
        String namespace = pathSegments.get(3);
        return new MockResponse().setResponseCode(200).setBody(loadConfigFor(namespace));
      }
      return new MockResponse().setResponseCode(404);
    }
  };

  server.setDispatcher(dispatcher);
  server.start();

  mockConfigServiceUrl("http://localhost:" + server.getPort());

  super.before();
}
 
Example #20
Source File: CliProxyEnvVarIT.java    From digdag with Apache License 2.0 5 votes vote down vote up
private void assertCliUsesProxy(Map<String, String> env, MockWebServer server, HttpProxyRequestTracker proxyRequestTracker)
{
    String endpoint = server.url("/").toString();
    logger.info("server endpoint: {}, env: {}", endpoint, env);
    server.enqueue(VERSION_RESPONSE);
    CommandStatus versionStatus = main(env, "version", "-c", "/dev/null", "-e", endpoint, "--disable-cert-validation");
    assertThat(versionStatus.errUtf8(), versionStatus.code(), is(0));
    assertThat(server.getRequestCount(), is(1));
    assertThat(proxyRequestTracker.clientRequestsReceived.get(), is(1));
    assertThat(versionStatus.outUtf8(), Matchers.containsString("Server version: " + buildVersion()));
}
 
Example #21
Source File: ExchangeRateTest.java    From xmrwallet with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    mockWebServer = new MockWebServer();
    mockWebServer.start();

    waiter = new Waiter();

    MockitoAnnotations.initMocks(this);

    exchangeApi = new ExchangeApiImpl(okHttpClient, mockWebServer.url("/"));
}
 
Example #22
Source File: XmrToApiQueryOrderTest.java    From xmrwallet with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    mockWebServer = new MockWebServer();
    mockWebServer.start();

    waiter = new Waiter();

    MockitoAnnotations.initMocks(this);

    xmrToApi = new XmrToApiImpl(okHttpClient, mockWebServer.url("/"));
}
 
Example #23
Source File: XmrToApiOrderParameterTest.java    From xmrwallet with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    mockWebServer = new MockWebServer();
    mockWebServer.start();

    waiter = new Waiter();

    MockitoAnnotations.initMocks(this);

    xmrToApi = new XmrToApiImpl(okHttpClient, mockWebServer.url("/"));
}
 
Example #24
Source File: AccountServiceTest.java    From africastalking-android with MIT License 5 votes vote down vote up
@Test
public void getUser() throws Exception {
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse().setBody("{\"UserData\": {\"balance\": \"2000\" } }"));
    server.start();
    assertNotNull("GetUser: Response is null", account.getUser());
    assertEquals("GetUser: Balance is not 2000", "2000", account.getUser().userData.balance.trim());
}
 
Example #25
Source File: DefaultMockServer.java    From mockwebserver with Apache License 2.0 5 votes vote down vote up
public DefaultMockServer(Context context, MockWebServer server, Map<ServerRequest, Queue<ServerResponse>> responses, Dispatcher dispatcher, boolean useHttps) {
  this.context = context;
  this.useHttps = useHttps;
  this.server = server;
  this.responses = responses;
  this.server.setDispatcher(dispatcher);
}
 
Example #26
Source File: ResponseMappingInterceptorTest.java    From genie with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setup() throws IOException {
    this.server = new MockWebServer();
    this.server.start();
    this.baseUrl = this.server.url("/api/v3/jobs");

    final OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.addInterceptor(new ResponseMappingInterceptor());
    this.client = builder.build();
}
 
Example #27
Source File: WebClientDataBufferAllocatingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void setUp() {

	this.factory = new ReactorResourceFactory();
	this.factory.afterPropertiesSet();

	this.server = new MockWebServer();
	this.webClient = WebClient
			.builder()
			.clientConnector(initConnector())
			.baseUrl(this.server.url("/").toString())
			.build();
}
 
Example #28
Source File: CacheListTest.java    From Forage with Mozilla Public License 2.0 5 votes vote down vote up
public void queueNetworkRequest(final MockWebServer mockWebServer) {
    String jsonResponse = "{\n" +
            "  \"CACHE1\":{\n" +
            "    \"code\":\"CACHE1\",\n" +
            "    \"name\":\"Cache Name 1\",\n" +
            "    \"location\":\"45|45\",\n" +
            "    \"type\":\"Traditional\",\n" +
            "    \"status\":\"Available\",\n" +
            "    \"terrain\":1,\n" +
            "    \"difficulty\":2.5,\n" +
            "    \"size2\":\"micro\",\n" +
            "    \"description\":\"<p>Cache Description 1<\\/p>\"\n" +
            "  },\n" +
            "  \"CACHE2\":{\n" +
            "    \"code\":\"CACHE2\",\n" +
            "    \"name\":\"Cache Name 2\",\n" +
            "    \"location\":\"0|0\",\n" +
            "    \"type\":\"Virtual\",\n" +
            "    \"status\":\"Available\",\n" +
            "    \"terrain\":1,\n" +
            "    \"difficulty\":1,\n" +
            "    \"size2\":\"none\",\n" +
            "    \"description\":\"<p>Cache Description 2<\\/p>\"\n" +
            "  }\n" +
            "}";
    mockWebServer.enqueue(new MockResponse().setBody(jsonResponse));

}
 
Example #29
Source File: EraseAllUserDataTest.java    From focus-android with Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected void beforeActivityLaunched() {
    super.beforeActivityLaunched();

    Context appContext = InstrumentationRegistry.getInstrumentation()
            .getTargetContext()
            .getApplicationContext();

    PreferenceManager.getDefaultSharedPreferences(appContext)
            .edit()
            .putBoolean(FIRSTRUN_PREF, true)
            .apply();

    // This test runs on both GV and WV.
    // Klar is used to test Geckoview. make sure it's set to Gecko
    TestHelper.selectGeckoForKlar();

    webServer = new MockWebServer();

    try {
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("plain_test.html")));
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("plain_test.html")));
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("plain_test.html")));

        webServer.start();
    } catch (IOException e) {
        throw new AssertionError("Could not start web server", e);
    }
}
 
Example #30
Source File: AbstractMockWebServerTestCase.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
	this.server = new MockWebServer();
	this.server.setDispatcher(new TestDispatcher());
	this.server.start();
	this.port = this.server.getPort();
	this.baseUrl = "http://localhost:" + this.port;
}