Java Code Examples for com.squareup.okhttp.mockwebserver.MockWebServer#start()

The following examples show how to use com.squareup.okhttp.mockwebserver.MockWebServer#start() . 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: WorkingWithRetrofitTest.java    From rxsnappy with Apache License 2.0 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    RxSnappy.init(getContext());
    mockWebServer = new MockWebServer();
    mockWebServer.start(9812);

    OkHttpClient okHttpClient = new OkHttpClient();
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setClient(new OkClient(okHttpClient))
            .setEndpoint(mockWebServer.getUrl("/").toString())
            .build();

    testRestAdapter = restAdapter.create(TestRestAdapter.class);

    rxSnappyClient = new RxSnappyClient();
}
 
Example 2
Source File: ChromeServiceImplTest.java    From chrome-devtools-java-client with Apache License 2.0 6 votes vote down vote up
@Test(expected = ChromeServiceException.class)
public void testActivateTabOnNotFoundResponse()
    throws IOException, ChromeServiceException, InterruptedException {
  MockWebServer server = new MockWebServer();
  ObjectMapper objectMapper = new ObjectMapper();

  ChromeTab tab =
      objectMapper.readerFor(ChromeTab.class).readValue(getFixture("chrome/tab.json"));

  server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_FOUND));
  server.start();

  try {
    ChromeServiceImpl service = new ChromeServiceImpl(server.getHostName(), server.getPort());
    service.activateTab(tab);
  } finally {
    server.shutdown();
  }
}
 
Example 3
Source File: ChromeServiceImplTest.java    From chrome-devtools-java-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloseTab() throws IOException, ChromeServiceException, InterruptedException {
  MockWebServer server = new MockWebServer();

  ObjectMapper objectMapper = new ObjectMapper();
  ChromeTab tab =
      objectMapper.readerFor(ChromeTab.class).readValue(getFixture("chrome/tab.json"));

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

  ChromeServiceImpl service = new ChromeServiceImpl(server.getHostName(), server.getPort());

  service.closeTab(tab);

  RecordedRequest request = server.takeRequest();
  assertEquals(1, server.getRequestCount());
  assertEquals(
      "GET /json/close/(2C5C79DD1137419CC8839D61D91CEB2A) HTTP/1.1", request.getRequestLine());

  server.shutdown();
}
 
Example 4
Source File: ChromeServiceImplTest.java    From chrome-devtools-java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateTab() throws IOException, ChromeServiceException, InterruptedException {
  MockWebServer server = new MockWebServer();

  InputStream fixture = getFixture("chrome/tab.json");
  server.enqueue(new MockResponse().setBody(ChromeServiceImpl.inputStreamToString(fixture)));

  server.start();

  ChromeServiceImpl service = new ChromeServiceImpl(server.getHostName(), server.getPort());

  ChromeTab tab = service.createTab("some-tab-name");

  RecordedRequest request = server.takeRequest();
  assertEquals(1, server.getRequestCount());
  assertEquals("GET /json/new?some-tab-name HTTP/1.1", request.getRequestLine());

  assertEquals("", tab.getDescription());
  assertEquals(
      "/devtools/inspector.html?ws=localhost:9222/devtools/page/(2C5C79DD1137419CC8839D61D91CEB2A)",
      tab.getDevtoolsFrontendUrl());
  assertEquals(
      "https://www.google.ba/images/branding/product/ico/googleg_lodp.ico", tab.getFaviconUrl());
  assertEquals("(2C5C79DD1137419CC8839D61D91CEB2A)", tab.getId());
  assertEquals("Google", tab.getTitle());
  assertEquals("page", tab.getType());
  assertTrue(tab.isPageType());
  assertEquals("https://www.google.ba/?gws_rd=cr&dcr=0&ei=93piWq2oKqqJmgWIzbdg", tab.getUrl());
  assertEquals(
      "ws://localhost:9222/devtools/page/(2C5C79DD1137419CC8839D61D91CEB2A)",
      tab.getWebSocketDebuggerUrl());

  server.shutdown();
}
 
Example 5
Source File: ApiInterfaceTest.java    From android-step-by-step with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    super.setUp();
    server = new MockWebServer();
    server.start();
    final Dispatcher dispatcher = new Dispatcher() {

        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {

            if (request.getPath().equals("/users/" + TestConst.TEST_OWNER + "/repos")) {
                return new MockResponse().setResponseCode(200)
                        .setBody(testUtils.readString("json/repos.json"));
            } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/branches")) {
                return new MockResponse().setResponseCode(200)
                        .setBody(testUtils.readString("json/branches.json"));
            } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/contributors")) {
                return new MockResponse().setResponseCode(200)
                        .setBody(testUtils.readString("json/contributors.json"));
            }
            return new MockResponse().setResponseCode(404);
        }
    };

    server.setDispatcher(dispatcher);
    HttpUrl baseUrl = server.url("/");
    apiInterface = ApiModule.getApiInterface(baseUrl.toString());
}
 
Example 6
Source File: SubscriptionsTest.java    From actioncable-client-java with MIT License 5 votes vote down vote up
@Test(timeout = TIMEOUT)
public void createBeforeOpeningConnection() throws URISyntaxException, IOException, InterruptedException {
    final BlockingQueue<String> events = new LinkedBlockingQueue<String>();

    final MockWebServer mockWebServer = new MockWebServer();
    final MockResponse response = new MockResponse();
    response.withWebSocketUpgrade(new DefaultWebSocketListener() {
        @Override
        public void onMessage(BufferedSource payload, WebSocket.PayloadType type) throws IOException {
            events.offer("onMessage:" + payload.readUtf8());
            payload.close();
        }
    });
    mockWebServer.enqueue(response);
    mockWebServer.start();

    final Consumer consumer = new Consumer(mockWebServer.url("/").uri());

    final Subscriptions subscriptions = consumer.getSubscriptions();
    final Subscription subscription = subscriptions.create(new Channel("CommentsChannel"));

    consumer.connect();

    // Callback test
    assertThat(events.take(), is("onMessage:" + Command.subscribe(subscription.getIdentifier()).toJson()));

    mockWebServer.shutdown();
}
 
Example 7
Source File: MockHostModule.java    From Dagger-2-Example with Apache License 2.0 5 votes vote down vote up
public MockHostModule() {
    mockWebServer = new MockWebServer();
    try {
        mockWebServer.start();
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("Failed to start mockWebServer!");
    }
}
 
Example 8
Source File: StethoInterceptorTest.java    From stetho with MIT License 5 votes vote down vote up
@Test
public void testWithRequestCompression() throws IOException {
  AtomicReference<NetworkEventReporter.InspectorRequest> capturedRequest =
      hookAlmostRealRequestWillBeSent(mMockEventReporter);

  MockWebServer server = new MockWebServer();
  server.start();
  server.enqueue(new MockResponse()
      .setBody("Success!"));

  final byte[] decompressed = "Request text".getBytes();
  final byte[] compressed = compress(decompressed);
  assertNotEquals(
      "Bogus test: decompressed and compressed lengths match",
      compressed.length, decompressed.length);

  RequestBody compressedBody = RequestBody.create(
      MediaType.parse("text/plain"),
      compress(decompressed));
  Request request = new Request.Builder()
      .url(server.getUrl("/"))
      .addHeader("Content-Encoding", "gzip")
      .post(compressedBody)
      .build();
  Response response = mClientWithInterceptor.newCall(request).execute();

  // Force a read to complete the flow.
  response.body().string();

  assertArrayEquals(decompressed, capturedRequest.get().body());
  Mockito.verify(mMockEventReporter)
      .dataSent(
          anyString(),
          eq(decompressed.length),
          eq(compressed.length));

  server.shutdown();
}
 
Example 9
Source File: OpenWeatherClientTest.java    From MVPAndroidBootstrap with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    ShadowLog.stream = System.out;
    mockWebServer = new MockWebServer();
    mockWebServer.start(9999);
    TestHelper.setFinalStatic(OpenWeatherClient.class.getField("ENDPOINT"), mockWebServer.getUrl("/").toString());
    openWeatherClient = OpenWeatherClient_.getInstance_(RuntimeEnvironment.application);
}
 
Example 10
Source File: SampleServer.java    From httplite with Apache License 2.0 5 votes vote down vote up
public void run() throws IOException {
    MockWebServer server = new MockWebServer();
    server.useHttps(sslContext.getSocketFactory(), false);
    server.setDispatcher(this);
    InetAddress address = HttpUtil.getHostAddress();
    server.start(address,port);
    System.out.println(String.format("Started server for: http://%s:%d/", address.getHostAddress(), port));
}
 
Example 11
Source File: SubscriptionTest.java    From actioncable-client-java with MIT License 5 votes vote down vote up
@Test(timeout = TIMEOUT)
public void performWithDataByCustomInterface() throws URISyntaxException, InterruptedException, IOException {
    final BlockingQueue<String> events = new LinkedBlockingQueue<String>();

    final MockWebServer mockWebServer = new MockWebServer();
    final MockResponse response = new MockResponse();
    response.withWebSocketUpgrade(new DefaultWebSocketListener() {
        @Override
        public void onMessage(BufferedSource payload, WebSocket.PayloadType type) throws IOException {
            events.offer(payload.readUtf8());
            payload.close();
        }
    });
    mockWebServer.enqueue(response);
    mockWebServer.start();

    final Consumer consumer = new Consumer(mockWebServer.url("/").uri());
    final Subscription subscription = consumer.getSubscriptions().create(new Channel("CommentsChannel"), CustomSubscription.class);
    consumer.connect();

    events.take(); // { command: subscribe }

    final JsonObject data = new JsonObject();
    data.addProperty("foo", "bar");
    subscription.perform("follow", data);

    final JsonObject expected = new JsonObject();
    expected.addProperty("command", "message");
    expected.addProperty("identifier", subscription.getIdentifier());
    expected.addProperty("data", data.toString());
    assertThat(events.take(), is(expected.toString()));

    mockWebServer.shutdown();
}
 
Example 12
Source File: ChromeServiceImplTest.java    From chrome-devtools-java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testVersion() throws IOException, ChromeServiceException, InterruptedException {
  MockWebServer server = new MockWebServer();

  InputStream fixture = getFixture("chrome/version.json");
  server.enqueue(new MockResponse().setBody(ChromeServiceImpl.inputStreamToString(fixture)));

  server.start();

  ChromeServiceImpl service = new ChromeServiceImpl(server.getHostName(), server.getPort());

  ChromeVersion version = service.getVersion();

  RecordedRequest request = server.takeRequest();
  assertEquals(1, server.getRequestCount());
  assertEquals("GET /json/version HTTP/1.1", request.getRequestLine());

  assertEquals("Chrome/63.0.3239.132", version.getBrowser());
  assertEquals("1.2", version.getProtocolVersion());
  assertEquals(
      "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
      version.getUserAgent());
  assertEquals("6.3.292.49", version.getV8Version());
  assertEquals("537.36 (@2e6edcfee630baa3775f37cb11796b1603a64360)", version.getWebKitVersion());
  assertEquals(
      "ws://localhost:9222/devtools/browser/63318df0-09e4-4143-910e-f89525dda26b",
      version.getWebSocketDebuggerUrl());

  server.shutdown();
}
 
Example 13
Source File: ConnectionTest.java    From actioncable-client-java with MIT License 5 votes vote down vote up
@Test(timeout = TIMEOUT)
public void isOpenWhenOnOpenAndFailure() throws InterruptedException, IOException {
    final MockWebServer mockWebServer = new MockWebServer();
    final MockResponse response = new MockResponse();
    response.setResponseCode(500);
    response.setStatus("HTTP/1.1 500 Internal Server Error");
    mockWebServer.enqueue(response);
    mockWebServer.start();

    final URI uri = mockWebServer.url("/").uri();
    final Connection connection = new Connection(uri, new Consumer.Options());

    final BlockingQueue<String> events = new LinkedBlockingQueue<String>();

    connection.setListener(new DefaultConnectionListener() {
        @Override
        public void onOpen() {
            events.offer("onOpen");
        }

        @Override
        public void onFailure(Exception e) {
            events.offer("onFailed");
        }
    });

    assertThat(connection.isOpen(), is(false));

    connection.open();

    assertThat(events.take(), is("onFailed"));

    assertThat(connection.isOpen(), is(false));

    mockWebServer.shutdown();
}
 
Example 14
Source File: SubscriptionTest.java    From actioncable-client-java with MIT License 5 votes vote down vote up
@Test(timeout = TIMEOUT)
public void performWithDataByDefaultInterface() throws URISyntaxException, InterruptedException, IOException {
    final BlockingQueue<String> events = new LinkedBlockingQueue<String>();

    final MockWebServer mockWebServer = new MockWebServer();
    final MockResponse response = new MockResponse();
    response.withWebSocketUpgrade(new DefaultWebSocketListener() {
        @Override
        public void onMessage(BufferedSource payload, WebSocket.PayloadType type) throws IOException {
            events.offer(payload.readUtf8());
            payload.close();
        }
    });
    mockWebServer.enqueue(response);
    mockWebServer.start();

    final Consumer consumer = new Consumer(mockWebServer.url("/").uri());
    final Subscription subscription = consumer.getSubscriptions().create(new Channel("CommentsChannel"));
    consumer.connect();

    events.take(); // { command: subscribe }

    final JsonObject data = new JsonObject();
    data.addProperty("foo", "bar");
    subscription.perform("follow", data);

    final JsonObject expected = new JsonObject();
    expected.addProperty("command", "message");
    expected.addProperty("identifier", subscription.getIdentifier());
    expected.addProperty("data", data.toString());
    assertThat(events.take(), is(expected.toString()));

    mockWebServer.shutdown();
}
 
Example 15
Source File: ChromeServiceImplTest.java    From chrome-devtools-java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateTabWithAboutBlankPage()
    throws IOException, ChromeServiceException, InterruptedException {
  MockWebServer server = new MockWebServer();

  InputStream fixture = getFixture("chrome/tab.json");
  server.enqueue(new MockResponse().setBody(ChromeServiceImpl.inputStreamToString(fixture)));

  server.start();

  ChromeServiceImpl service = new ChromeServiceImpl(server.getHostName(), server.getPort());

  ChromeTab tab = service.createTab();

  RecordedRequest request = server.takeRequest();
  assertEquals(1, server.getRequestCount());
  assertEquals("GET /json/new?about:blank HTTP/1.1", request.getRequestLine());

  assertEquals("", tab.getDescription());
  assertEquals(
      "/devtools/inspector.html?ws=localhost:9222/devtools/page/(2C5C79DD1137419CC8839D61D91CEB2A)",
      tab.getDevtoolsFrontendUrl());
  assertEquals(
      "https://www.google.ba/images/branding/product/ico/googleg_lodp.ico", tab.getFaviconUrl());
  assertEquals("(2C5C79DD1137419CC8839D61D91CEB2A)", tab.getId());
  assertEquals("Google", tab.getTitle());
  assertEquals("page", tab.getType());
  assertTrue(tab.isPageType());
  assertEquals("https://www.google.ba/?gws_rd=cr&dcr=0&ei=93piWq2oKqqJmgWIzbdg", tab.getUrl());
  assertEquals(
      "ws://localhost:9222/devtools/page/(2C5C79DD1137419CC8839D61D91CEB2A)",
      tab.getWebSocketDebuggerUrl());

  server.shutdown();
}
 
Example 16
Source File: ChromeServiceImplTest.java    From chrome-devtools-java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTabs() throws IOException, ChromeServiceException, InterruptedException {
  MockWebServer server = new MockWebServer();

  InputStream fixture = getFixture("chrome/tabs.json");
  server.enqueue(new MockResponse().setBody(ChromeServiceImpl.inputStreamToString(fixture)));

  server.start();

  ChromeServiceImpl service = new ChromeServiceImpl(server.getHostName(), server.getPort());

  List<ChromeTab> tabs = service.getTabs();

  RecordedRequest request = server.takeRequest();
  assertEquals(1, server.getRequestCount());
  assertEquals("GET /json/list HTTP/1.1", request.getRequestLine());

  assertFalse(tabs.isEmpty());
  assertEquals(2, tabs.size());

  assertEquals("", tabs.get(0).getDescription());
  assertEquals(
      "/devtools/inspector.html?ws=localhost:9222/devtools/page/(2C5C79DD1137419CC8839D61D91CEB2A)",
      tabs.get(0).getDevtoolsFrontendUrl());
  assertEquals(
      "https://www.google.ba/images/branding/product/ico/googleg_lodp.ico",
      tabs.get(0).getFaviconUrl());
  assertEquals("(2C5C79DD1137419CC8839D61D91CEB2A)", tabs.get(0).getId());
  assertEquals("Google", tabs.get(0).getTitle());
  assertEquals("page", tabs.get(0).getType());
  assertTrue(tabs.get(0).isPageType());
  assertEquals(
      "https://www.google.ba/?gws_rd=cr&dcr=0&ei=93piWq2oKqqJmgWIzbdg", tabs.get(0).getUrl());
  assertEquals(
      "ws://localhost:9222/devtools/page/(2C5C79DD1137419CC8839D61D91CEB2A)",
      tabs.get(0).getWebSocketDebuggerUrl());

  server.shutdown();
}
 
Example 17
Source File: ConsulConfigurationSourceIntegrationTest.java    From cfg4j with Apache License 2.0 4 votes vote down vote up
private void runMockServer() throws IOException {
  server = new MockWebServer();
  server.setDispatcher(dispatcher);
  server.start(0);
}
 
Example 18
Source File: NuroMetricTest.java    From SeaCloudsPlatform with Apache License 2.0 4 votes vote down vote up
@Test
public void nuroMetricTest() throws Exception{

    MockWebServer mockWebServer = new MockWebServer();   
    NuroMetric metric = new NuroMetric();
    double sample;
    
    for(int i=0; i<=NUMBER_OF_METRICS; i++){
        mockWebServer.enqueue(new MockResponse()
                .setBody(NuroInputExample.EXAMPLE_INPUT)
                .setHeader("Content-Type", MediaType.APPLICATION_JSON));            
    }

    
    mockWebServer.start();
    
    HttpUrl serverUrl = mockWebServer.url("/sensor.php");
                    
    metric.setMonitoredMetric("NUROServerLastMinuteAverageRunTime");     
    sample = metric.getSample("http://"+serverUrl.host()+":"+serverUrl.port(), TEST_APPLICATION_USER, TEST_APPLICATION_PASSWORD).doubleValue();
    Assert.assertTrue(sample == EXPECTED_LAST_MINUTE_AVERAGE_RUNTIME);
            
    metric.setMonitoredMetric("NUROServerLastMinuteAverageThroughput");
    sample = metric.getSample("http://"+serverUrl.host()+":"+serverUrl.port(), TEST_APPLICATION_USER, TEST_APPLICATION_PASSWORD).doubleValue();
    Assert.assertTrue(sample == EXPECTED_LAST_MINUTE_AVERAGE_THROUGHPUT);
    
    metric.setMonitoredMetric("NUROServerLastMinutePlayerCount");
    sample = metric.getSample("http://"+serverUrl.host()+":"+serverUrl.port(), TEST_APPLICATION_USER, TEST_APPLICATION_PASSWORD).doubleValue();
    Assert.assertTrue(sample == EXPECTED_LAST_MINUTE_PLAYER_COUNT);
    
    metric.setMonitoredMetric("NUROServerLastMinuteRequestCount");
    sample = metric.getSample("http://"+serverUrl.host()+":"+serverUrl.port(), TEST_APPLICATION_USER, TEST_APPLICATION_PASSWORD).doubleValue();
    Assert.assertTrue(sample == EXPECTED_LAST_MINUTE_REQUEST_COUNT);
    
    metric.setMonitoredMetric("NUROServerLastTenSecondsAverageRunTime");
    sample = metric.getSample("http://"+serverUrl.host()+":"+serverUrl.port(), TEST_APPLICATION_USER, TEST_APPLICATION_PASSWORD).doubleValue();
    Assert.assertTrue(sample == EXPECTED_LAST_TEN_SECONDS_AVERAGE_RUNTIME);
    
    metric.setMonitoredMetric("NUROServerLastTenSecondsAverageThroughput");
    sample = metric.getSample("http://"+serverUrl.host()+":"+serverUrl.port(), TEST_APPLICATION_USER, TEST_APPLICATION_PASSWORD).doubleValue();
    Assert.assertTrue(sample == EXPECTED_LAST_TEN_SECONDS_AVERAGE_THROUGHPUT);
    
    metric.setMonitoredMetric("NUROServerLastTenSecondsPlayerCount");
    sample = metric.getSample("http://"+serverUrl.host()+":"+serverUrl.port(), TEST_APPLICATION_USER, TEST_APPLICATION_PASSWORD).doubleValue();
    Assert.assertTrue(sample == EXPECTED_LAST_TEN_SECONDS_PLAYER_COUNT);
    
    metric.setMonitoredMetric("NUROServerLastTenSecondsRequestCount");
    sample = metric.getSample("http://"+serverUrl.host()+":"+serverUrl.port(), TEST_APPLICATION_USER, TEST_APPLICATION_PASSWORD).doubleValue();
    Assert.assertTrue(sample == EXPECTED_LAST_TEN_SECONDS_REQUEST_COUNT);
    
    mockWebServer.shutdown();

}
 
Example 19
Source File: BaseJenkinsMockTest.java    From jenkins-rest with Apache License 2.0 2 votes vote down vote up
/**
 * Create a MockWebServer with an initial bread-crumb response.
 *
 * @return instance of MockWebServer
 * @throws IOException
 *             if unable to start/play server
 */
public static MockWebServer mockWebServer() throws IOException {
    final MockWebServer server = new MockWebServer();
    server.start();
    return server;
}
 
Example 20
Source File: BaseBitbucketMockTest.java    From bitbucket-rest with Apache License 2.0 2 votes vote down vote up
/**
 * Create a MockWebServer.
 *
 * @return instance of MockWebServer
 * @throws IOException
 *             if unable to start/play server
 */
public static MockWebServer mockWebServer() throws IOException {
    final MockWebServer server = new MockWebServer();
    server.start();
    return server;
}