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

The following examples show how to use com.squareup.okhttp.mockwebserver.MockWebServer#enqueue() . 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: QueueApiMockTest.java    From jenkins-rest with Apache License 2.0 6 votes vote down vote up
public void testGetCancelledQueueItem() throws Exception {
    MockWebServer server = mockWebServer();
    String body = payloadFromResource("/queueItemCancelled.json");
    server.enqueue(new MockResponse().setBody(body).setResponseCode(200));
    JenkinsApi jenkinsApi = api(server.getUrl("/"));
    int queueItemId = 143;
    QueueItem queueItem = jenkinsApi.queueApi().queueItem(queueItemId);
    try {
        assertTrue(queueItem.cancelled());
        assertNull(queueItem.why());
        assertNull(queueItem.executable());
        assertSent(server, "GET", "/queue/item/" + queueItemId + "/api/json");
    } finally {
        jenkinsApi.close();
        server.shutdown();
    }
}
 
Example 2
Source File: BuildStatusApiMockTest.java    From bitbucket-rest with Apache License 2.0 6 votes vote down vote up
public void testGetStatus() throws Exception {
    final MockWebServer server = mockWebServer();

    server.enqueue(new MockResponse().setBody(payloadFromResource("/build-status.json")).setResponseCode(200));
    try (final BitbucketApi baseApi = api(server.getUrl("/"))) {
        
        final StatusPage statusPage = baseApi.buildStatusApi().status(commitHash, 0, 100);
        assertThat(statusPage).isNotNull();
        assertThat(statusPage.errors()).isEmpty();
        assertThat(statusPage.size() == 2).isTrue();
        assertThat(statusPage.values().get(0).state().equals(Status.StatusState.FAILED)).isTrue();

        final Map<String, ?> queryParams = ImmutableMap.of("limit", 100, "start", 0);
        assertSent(server, "GET", restBuildStatusPath + BitbucketApiMetadata.API_VERSION
                + commitPath, queryParams);
    } finally {
        server.shutdown();
    }
}
 
Example 3
Source File: ProjectApiMockTest.java    From bitbucket-rest with Apache License 2.0 6 votes vote down vote up
public void testGetProjectList() throws Exception {
    final MockWebServer server = mockWebServer();

    server.enqueue(new MockResponse()
            .setBody(payloadFromResource("/project-page-full.json"))
            .setResponseCode(200));
    try (final BitbucketApi baseApi = api(server.getUrl("/"))) {

        final ProjectPage projectPage = baseApi.projectApi().list(null, null, null, null);

        assertThat(projectPage).isNotNull();
        assertThat(projectPage.errors()).isEmpty();

        assertThat(projectPage.size()).isLessThanOrEqualTo(projectPage.limit());
        assertThat(projectPage.start()).isEqualTo(0);
        assertThat(projectPage.isLastPage()).isTrue();

        assertThat(projectPage.values()).hasSize(projectPage.size());
        assertThat(projectPage.values()).hasOnlyElementsOfType(Project.class);
        assertSent(server, localMethod, restBasePath + BitbucketApiMetadata.API_VERSION + localPath);
    } finally {
        server.shutdown();
    }
}
 
Example 4
Source File: CommentsApiMockTest.java    From bitbucket-rest with Apache License 2.0 6 votes vote down vote up
public void testGetComment() throws Exception {
    final MockWebServer server = mockWebServer();

    server.enqueue(new MockResponse().setBody(payloadFromResource("/comments.json")).setResponseCode(200));
    try (final BitbucketApi baseApi = api(server.getUrl("/"))) {
        
        final Comments pr = baseApi.commentsApi().get(projectKey, repoKey, 101, 1);
        assertThat(pr).isNotNull();
        assertThat(pr.errors()).isEmpty();
        assertThat(pr.text()).isEqualTo(measuredReplyKeyword);
        assertThat(pr.links()).isNull();
        assertSent(server, getMethod, restApiPath + BitbucketApiMetadata.API_VERSION
                + "/projects/PRJ/repos/my-repo/pull-requests/101/comments/1");
    } finally {
        server.shutdown();
    }
}
 
Example 5
Source File: CommentsApiMockTest.java    From bitbucket-rest with Apache License 2.0 6 votes vote down vote up
public void testComment() throws Exception {
    final MockWebServer server = mockWebServer();

    server.enqueue(new MockResponse().setBody(payloadFromResource("/comments.json")).setResponseCode(201));
    try (final BitbucketApi baseApi = api(server.getUrl("/"))) {

        final Comments pr = baseApi.commentsApi().comment(projectKey, repoKey, 101, measuredReplyKeyword);
        assertThat(pr).isNotNull();
        assertThat(pr.errors()).isEmpty();
        assertThat(pr.text()).isEqualTo(measuredReplyKeyword);
        assertThat(pr.links()).isNull();
        assertSent(server, "POST", restApiPath + BitbucketApiMetadata.API_VERSION
                + "/projects/PRJ/repos/my-repo/pull-requests/101/comments");
    } finally {
        server.shutdown();
    }
}
 
Example 6
Source File: CommitsApiMockTest.java    From bitbucket-rest with Apache License 2.0 6 votes vote down vote up
public void testListCommits() throws Exception {
    final MockWebServer server = mockWebServer();

    server.enqueue(new MockResponse().setBody(payloadFromResource("/pull-request-commits.json"))
            .setResponseCode(200));
    try (final BitbucketApi baseApi = api(server.getUrl("/"))) {

        final CommitPage pcr = baseApi.commitsApi().list(projectKey, repoKey, true, null, null, null, null, null, null, 1, null);
        assertThat(pcr).isNotNull();
        assertThat(pcr.errors()).isEmpty();
        assertThat(pcr.values()).hasSize(1);
        assertThat(pcr.totalCount()).isEqualTo(1);

        final Map<String, ?> queryParams = ImmutableMap.of("withCounts", true, limitKeyword, 1);
        assertSent(server, getMethod, restApiPath + BitbucketApiMetadata.API_VERSION
                + "/projects/PRJ/repos/myrepo/commits", queryParams);
    } finally {
        server.shutdown();
    }
}
 
Example 7
Source File: QueueApiMockTest.java    From jenkins-rest with Apache License 2.0 6 votes vote down vote up
public void testGetRunningQueueItem() throws Exception {
    MockWebServer server = mockWebServer();
    String body = payloadFromResource("/queueItemRunning.json");
    server.enqueue(new MockResponse().setBody(body).setResponseCode(200));
    JenkinsApi jenkinsApi = api(server.getUrl("/"));
    int queueItemId = 143;
    int buildNumber = 14;
    QueueItem queueItem = jenkinsApi.queueApi().queueItem(queueItemId);
    Map <String, String> map = Maps.newHashMap();
    map.put("a", "4");
    try {
        assertEquals(queueItem.params(), map);
        assertFalse(queueItem.cancelled());
        assertNull(queueItem.why());
        assertNotNull(queueItem.executable());
        assertEquals((int) queueItem.executable().number(), (int) buildNumber);
        assertEquals(queueItem.executable().url(), "http://localhost:8082/job/test/" + buildNumber + "/");
        assertSent(server, "GET", "/queue/item/" + queueItemId + "/api/json");
    } finally {
        jenkinsApi.close();
        server.shutdown();
    }
}
 
Example 8
Source File: BranchApiMockTest.java    From bitbucket-rest with Apache License 2.0 6 votes vote down vote up
public void testListBranchePermissions() throws Exception {
    final MockWebServer server = mockWebServer();

    server.enqueue(new MockResponse().setBody(payloadFromResource("/branch-permission-list.json")).setResponseCode(200));
    try (final BitbucketApi baseApi = api(server.getUrl("/"))) {

        final BranchRestrictionPage branch = baseApi.branchApi().listBranchRestriction(projectKey, repoKey, null, 1);
        assertThat(branch).isNotNull();
        assertThat(branch.errors().isEmpty()).isTrue();
        assertThat(branch.values().size() > 0).isTrue();
        assertThat(839L == branch.values().get(0).id()).isTrue();
        assertThat(2 == branch.values().get(0).accessKeys().size()).isTrue();

        final Map<String, ?> queryParams = ImmutableMap.of(localLimit, 1);
        assertSent(server, localGetMethod, branchPermissionsPath
                + localProjectsPath + projectKey + localReposPath + repoKey + "/restrictions", queryParams);
    } finally {
        server.shutdown();
    }
}
 
Example 9
Source File: SyncApiMockTest.java    From bitbucket-rest with Apache License 2.0 6 votes vote down vote up
public void testEnabled() throws Exception {
    final MockWebServer server = mockWebServer();
    server.enqueue(new MockResponse().setBody(payloadFromResource("/sync-enabled.json")).setResponseCode(200));

    try (final BitbucketApi baseApi = api(server.getUrl("/"));) {

        final SyncStatus status = baseApi.syncApi().enable(projectKey, repoKey, true);
        assertThat(status.available()).isTrue();
        assertThat(status.enabled()).isTrue();
        assertThat(status.divergedRefs()).isNotEmpty();
        assertThat(status.divergedRefs().get(0).state()).isEqualTo("DIVERGED");
        assertThat(status.errors()).isEmpty();

        assertSent(server, postMethod, restApiPath + BitbucketApiMetadata.API_VERSION + syncPath);
    } finally {
        server.shutdown();
    }
}
 
Example 10
Source File: BuildStatusApiMockTest.java    From bitbucket-rest with Apache License 2.0 6 votes vote down vote up
public void testAddBuildStatusOnError() throws Exception {
    final MockWebServer server = mockWebServer();

    server.enqueue(new MockResponse().setBody(payloadFromResource("/errors.json")).setResponseCode(404));
    try (final BitbucketApi baseApi = api(server.getUrl("/"))) {
        
        final CreateBuildStatus cbs = CreateBuildStatus.create(CreateBuildStatus.STATE.SUCCESSFUL, 
                                "REPO-MASTER", 
                                "REPO-MASTER-42", 
                                "https://bamboo.example.com/browse/REPO-MASTER-42", 
                                "Changes by John Doe");
        final RequestStatus success = baseApi.buildStatusApi().add(commitHash, cbs);
        assertThat(success).isNotNull();
        assertThat(success.value()).isFalse();
        assertThat(success.errors()).isNotEmpty();
        
        assertSent(server, "POST", restBuildStatusPath + BitbucketApiMetadata.API_VERSION
                + commitPath);
    } finally {
        server.shutdown();
    }
}
 
Example 11
Source File: BranchApiMockTest.java    From bitbucket-rest with Apache License 2.0 6 votes vote down vote up
public void testUpdateBranchModelConfiguration() throws Exception {
    final MockWebServer server = mockWebServer();

    server.enqueue(new MockResponse().setBody(payloadFromResource("/branch-model-configuration.json")).setResponseCode(200));
    try (final BitbucketApi baseApi = api(server.getUrl("/"))) {

        final BranchConfiguration branchConfiguration = BranchConfiguration.create(testKeyword, false);
        final List<Type> types = Lists.newArrayList(Type.create(Type.TypeId.BUGFIX, testKeyword, testKeyword, true));

        final CreateBranchModelConfiguration bcm = CreateBranchModelConfiguration.create(branchConfiguration, null, types);

        final BranchModelConfiguration configuration = baseApi.branchApi().updateModelConfiguration(projectKey, repoKey, bcm);
        assertThat(configuration).isNotNull();
        assertThat(configuration.errors().isEmpty()).isTrue();
        assertThat(configuration.types().size() > 0).isTrue();
        assertSent(server, "PUT", localRestPath + BitbucketApiMetadata.API_VERSION
                + localProjectsPath + projectKey + localReposPath + repoKey + branchModelPath);
    } finally {
        server.shutdown();
    }
}
 
Example 12
Source File: BranchApiMockTest.java    From bitbucket-rest with Apache License 2.0 6 votes vote down vote up
public void testGetDefaultBranch() throws Exception {
    final MockWebServer server = mockWebServer();

    server.enqueue(new MockResponse().setBody(payloadFromResource("/branch-default.json")).setResponseCode(200));
    try (final BitbucketApi baseApi = api(server.getUrl("/"))) {

        final Branch branch = baseApi.branchApi().getDefault(projectKey, repoKey);
        assertThat(branch).isNotNull();
        assertThat(branch.errors().isEmpty()).isTrue();
        assertThat(branch.id()).isNotNull();
        assertSent(server, localGetMethod, restBasePath + BitbucketApiMetadata.API_VERSION
                + localProjectsPath + projectKey + localReposPath + repoKey + localBranchesPath + "/default");
    } finally {
        server.shutdown();
    }
}
 
Example 13
Source File: BranchApiMockTest.java    From bitbucket-rest with Apache License 2.0 6 votes vote down vote up
public void testGetDefaultBranchEmpty() throws Exception {
    final MockWebServer server = mockWebServer();

    server.enqueue(new MockResponse().setBody("null").setResponseCode(204));
    try (final BitbucketApi baseApi = api(server.getUrl("/"))) {

        final Branch branch = baseApi.branchApi().getDefault(projectKey, repoKey);
        assertThat(branch).isNotNull();
        assertThat(branch.errors().isEmpty()).isTrue();
        assertThat(branch.id()).isNull();
        assertSent(server, localGetMethod, restBasePath + BitbucketApiMetadata.API_VERSION
                + localProjectsPath + projectKey + localReposPath + repoKey + localBranchesPath + "/default");
    } finally {
        server.shutdown();
    }
}
 
Example 14
Source File: DropboxFoldersModuleTest.java    From CatanArchitecture with Apache License 2.0 5 votes vote down vote up
@Test public void mockWebServerWorking() throws Exception {
  MockWebServer server = new MockWebServer();
  Gson gson = new GsonBuilder().setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'").create();

  // Schedule some responses.
  server.enqueue(new MockResponse().addHeader("Content-Type", "application/json; charset=utf-8")
      .setBody(
          "{\"contents\":[{\"name\":\"Dropbox Foo\"},{\"name\":\"Dropbox test\"},{\"name\":\"Dropbox folDER\"}]}"));

  // Start the server.
  server.start();

  RestAdapter restAdapter = new RestAdapter.Builder().setExecutors(new Executor() {
    @Override public void execute(Runnable command) {
      command.run();
    }
  }, null)
      .setEndpoint(server.getUrl("/").toString())
      .setConverter(new GsonConverter(gson))
      .build();
  DropboxAPI apiService = restAdapter.create(DropboxAPI.class);

  EventsPort eventsPort = new InMemoryEventsAdapter();
  StoragePort storagePort = new DropboxStorageAdapter(eventsPort, apiService);
  FoldersModule foldersModule = new FoldersModule(storagePort, eventsPort);

  eventsPort.on(LoadFoldersFinished.class, new Callback<LoadFoldersFinished>() {
    @Override public void call(LoadFoldersFinished event) {
      assertEquals("Dropbox Foo", event.folders.get(0).obtainName());
      assertEquals("Dropbox test", event.folders.get(1).obtainName());
      assertEquals("Dropbox folDER", event.folders.get(2).obtainName());
    }
  });

  foldersModule.run();
  eventsPort.broadcast(new LoadFoldersCommand());

  // Shut down the server. Instances cannot be reused.
  server.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 testCloseTabClearsDevTools()
    throws IOException, ChromeServiceException, InterruptedException, WebSocketServiceException {
  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();

  expect(webSocketServiceFactory.createWebSocketService(tab.getWebSocketDebuggerUrl()))
      .andReturn(webSocketService);

  webSocketService.addMessageHandler(anyObject());
  webSocketService.close();

  replayAll();

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

  service.createDevToolsService(tab);

  service.closeTab(tab);

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

  server.shutdown();

  verifyAll();
}
 
Example 16
Source File: SubscriptionsTest.java    From actioncable-client-java with MIT License 5 votes vote down vote up
@Test(timeout = TIMEOUT)
public void createAfterOpeningConnection() 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());
    consumer.connect();

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

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

    mockWebServer.shutdown();
}
 
Example 17
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 18
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 19
Source File: FileApiMockTest.java    From bitbucket-rest with Apache License 2.0 5 votes vote down vote up
public void testLastModifiedAtPath() throws Exception {
    final MockWebServer server = mockWebServer();

    server.enqueue(new MockResponse().setBody(lastModifiedResposnseBody).setResponseCode(200));
    try (final BitbucketApi baseApi = api(server.getUrl("/"));) {
        final LastModified summary = baseApi.fileApi().lastModified(projectKey, repoKey, directoryPath, branch);
        assertThat(summary).isNotNull();
        assertThat(summary.latestCommit()).isNotNull();
        assertThat(summary.files().isEmpty()).isFalse();
        assertThat(summary.errors().isEmpty()).isTrue();
        assertSent(server, getMethod, lastModifiedPath + "/" + directoryPath, Collections.singletonMap("at", branch));
    } finally {
        server.shutdown();
    }
}
 
Example 20
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();

}