com.squareup.okhttp.mockwebserver.MockResponse Java Examples

The following examples show how to use com.squareup.okhttp.mockwebserver.MockResponse. 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: 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 #2
Source File: AdViewFriendlyObstructionTests.java    From mobile-sdk-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testBannerAddFriendlyObstruction() {
    server.enqueue(new MockResponse().setResponseCode(200).setBody(TestResponsesUT.banner())); // First queue a regular HTML banner response
    assertFriendlyObstruction(bannerAdView, 0);
    SDKSettings.setOMEnabled(true);
    View v1 = new View(activity);
    View v2 = new View(activity);
    View v3 = new View(activity);
    v1.setAlpha(0f);
    v2.setAlpha(0f);
    v3.setAlpha(0f);
    bannerAdView.addFriendlyObstruction(v1);
    bannerAdView.addFriendlyObstruction(v2);
    bannerAdView.addFriendlyObstruction(v3);
    executeBannerRequest();
    assertFriendlyObstruction(bannerAdView, 3);
}
 
Example #3
Source File: ConnectivityAwereUrlClientTest.java    From MVPAndroidBootstrap with Apache License 2.0 6 votes vote down vote up
@Test
public void test400Retry() throws Exception {

    assertThat(connectivityAwareUrlClient).isNotNull();
    mockWebServer.enqueue(new MockResponse()
            .setResponseCode(400));
    mockWebServer.enqueue(new MockResponse()
            .setResponseCode(400));
    mockWebServer.enqueue(new MockResponse()
            .setResponseCode(400));

    boolean isThrown = false;
    try {

        sodaService.cola("pepsi");
        fail("shoud not reach this");
    }catch (RetrofitError error){
        if(error.getCause() instanceof ConnectionError){
            isThrown = true;
        }else{
            fail("shoud not reach this");
        }
    }

    assertThat(isThrown).isTrue();
}
 
Example #4
Source File: ClientBasicFlowsTest.java    From ob1k with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void testStream() throws Exception {

  final String singleResponse = "Hello World";
  final int repeats = 3;
  final String streamBody = Strings.repeat(singleResponse, repeats);

  dispatcher.enqueue(new MockResponse().setChunkedBody(streamBody, streamBody.length() / repeats));

  final HttpClient httpClient = HttpClient.createDefault();
  final String url = server.url("/helloWorldStream").toString();
  final BlockingObservable<Response> responseStream = httpClient.get(url).asStream().toBlocking();

  final AtomicInteger counter = new AtomicInteger(0);
  final AtomicReference<Response> lastResponse = new AtomicReference<>();

  responseStream.forEach(response -> {
    counter.incrementAndGet();
    lastResponse.set(response);
  });

  assertEquals("response elements size equals to repeats", repeats, counter.get());
  assertEquals("chunks contain singleResponse", singleResponse, lastResponse.get().getResponseBody());
}
 
Example #5
Source File: UltraDNSZoneApiMockTest.java    From denominator with Apache License 2.0 6 votes vote down vote up
@Test
public void putWhenPresent() throws Exception {
  server.enqueue(new MockResponse().setBody(getAccountsListOfUserResponse));
  server.enqueueError(1802, "Zone already exists in the system.");
  server.enqueue(new MockResponse().setBody(getResourceRecordsOfDNameByTypeResponsePresent));
  server.enqueue(new MockResponse());

  ZoneApi api = server.connect().api().zones();

  Zone zone = Zone.create(null, "denominator.io.", 3601, "[email protected]");
  assertThat(api.put(zone)).isEqualTo(zone.name());

  server.assertSoapBody(getAccountsListOfUser);
  server.assertSoapBody(
      "<v01:createPrimaryZone><transactionID/><accountId>AAAAAAAAAAAAAAAA</accountId><zoneName>denominator.io.</zoneName><forceImport>false</forceImport></v01:createPrimaryZone>");
  server.assertSoapBody(
      "<v01:getResourceRecordsOfDNameByType><zoneName>denominator.io.</zoneName><hostName>denominator.io.</hostName><rrType>6</rrType></v01:getResourceRecordsOfDNameByType>");
  server.assertSoapBody(
      "<v01:updateResourceRecord><transactionID /><resourceRecord Guid=\"04053D8E57C7A22F\" ZoneName=\"denominator.io.\" Type=\"6\" DName=\"denominator.io.\" TTL=\"3601\"><InfoValues Info1Value=\"pdns75.ultradns.com.\" Info2Value=\"[email protected]\" Info3Value=\"2013022200\" Info4Value=\"86400\" Info5Value=\"86400\" Info6Value=\"86400\" Info7Value=\"3601\" /></resourceRecord></v01:updateResourceRecord>");
}
 
Example #6
Source File: JsonElementRequestTest.java    From jus with Apache License 2.0 6 votes vote down vote up
@Test
public void aJsonArray() throws IOException, InterruptedException, ExecutionException {
    server.enqueue(new MockResponse().setBody(
            "[{\"theName\":\"value1\"}, " +
                    "{\"theName\":\"value2\"}]"));

    JsonObjectArrayWrapper<RespWrapper> body =
            service.aJsonArray(new JsonObjectArrayWrapper()
                    .wrap(JsonArray.readFrom("[\"name\",\"value\"]").asJsonArray(),
                            ReqWrapper.class))
                    .getFuture().get();
    assertThat(body.get(0).getTheName()).isEqualTo("value1");
    assertThat(body.get(1).getTheName()).isEqualTo("value2");

    RecordedRequest request = server.takeRequest();

    assertThat(request.getBody().readUtf8()).isEqualTo("[\"name\",\"value\"]");
    assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
    assertThat(request.getHeader("Accept")).isEqualTo("application/json");
}
 
Example #7
Source File: DesignateTest.java    From denominator with Apache License 2.0 6 votes vote down vote up
@Test
public void limitsSuccess() throws Exception {
  server.enqueueAuthResponse();
  server.enqueue(new MockResponse().setBody("{\n"
                                            + "  \"limits\": {\n"
                                            + "    \"absolute\": {\n"
                                            + "      \"maxDomains\": 20,\n"
                                            + "      \"maxDomainRecords\": 5000\n"
                                            + "    }\n"
                                            + "  }\n"
                                            + "}"));

  assertThat(mockApi().limits()).hasSize(1);

  server.assertAuthRequest();
  server.assertRequest()
      .hasMethod("GET")
      .hasPath("/v1/limits");
}
 
Example #8
Source File: SimpleRequestTest.java    From jus with Apache License 2.0 6 votes vote down vote up
@Test
public void http404Sync() throws IOException, InterruptedException {
    server.enqueue(new MockResponse().setResponseCode(404).setBody("Hi"));

    Request<String> request = example.getString();
    try {
        request.enqueue().getFuture().get();
    } catch (ExecutionException e) {
        JusError error = (JusError) e.getCause();
        assertThat(error).isNotNull();
        assertThat(error.networkResponse.statusCode).isEqualTo(404);
        assertThat(error.networkResponse.getBodyAsString()).isEqualTo("Hi");
    }
    Response<String> response = request.getRawResponse();
    assertThat(response.isSuccess()).isFalse();
    assertThat(response.result).isNull();
    assertThat(response.error).isNotNull();
    assertThat(response.error.networkResponse.statusCode).isEqualTo(404);
    assertThat(response.error.networkResponse.getBodyAsString()).isEqualTo("Hi");
}
 
Example #9
Source File: ImgurPhotoExporterTest.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
@Test
public void testAlbumPhotosExport() throws Exception {
  server.enqueue(new MockResponse().setBody(albumsResponse));
  server.enqueue(new MockResponse().setBody(album1ImagesResponse));

  // export albums
  exporter.export(UUID.randomUUID(), token, Optional.empty());

  // export album photos
  ExportResult<PhotosContainerResource> result =
      exporter.export(
          UUID.randomUUID(),
          token,
          Optional.of(new ExportInformation(null, new IdOnlyContainerResource("albumId1"))));

  assertThat(result.getExportedData().getPhotos())
      .containsExactly(ALBUM_PHOTO_1, ALBUM_PHOTO_2)
      .inOrder();
}
 
Example #10
Source File: Route53ProviderDynamicUpdateMockTest.java    From denominator with Apache License 2.0 6 votes vote down vote up
@Test
public void dynamicEndpointUpdates() throws Exception {
  final AtomicReference<String> url = new AtomicReference<String>(server.url());
  server.enqueue(new MockResponse().setBody(hostedZones));

  DNSApi api = Denominator.create(new Route53Provider() {
    @Override
    public String url() {
      return url.get();
    }
  }, credentials(server.credentials())).api();

  api.zones().iterator();
  server.assertRequest();

  MockRoute53Server server2 = new MockRoute53Server();
  url.set(server2.url());
  server2.enqueue(new MockResponse().setBody(hostedZones));

  api.zones().iterator();

  server2.assertRequest();
  server2.shutdown();
}
 
Example #11
Source File: BranchApiMockTest.java    From bitbucket-rest with Apache License 2.0 6 votes vote down vote up
public void testGetBranchInfo() throws Exception {
    final MockWebServer server = mockWebServer();

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

        final BranchPage branchPage = baseApi.branchApi().info(projectKey, repoKey, commitId);
        assertThat(branchPage).isNotNull();
        assertThat(branchPage.errors().isEmpty()).isTrue();
        assertThat(branchPage.size() > 0).isTrue();
        assertSent(server, localGetMethod, localRestPath + BitbucketApiMetadata.API_VERSION
                + localProjectsPath + projectKey + localReposPath + repoKey + localInfoPath + "/" + commitId);
    } finally {
        server.shutdown();
    }
}
 
Example #12
Source File: AdListenerTest.java    From mobile-sdk-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testBannerNativeAdLoaded() {
    bannerAdView.setAutoRefreshInterval(30000);
    bannerAdView.setLoadsInBackground(false);
    bannerAdView.setOpensNativeBrowser(false);
    bannerAdView.setClickThroughAction(ANClickThroughAction.RETURN_URL);
    server.enqueue(new MockResponse().setResponseCode(200).setBody(TestResponsesUT.anNativeWithoutImages()));
    Assert.assertEquals(AdType.UNKNOWN, bannerAdView.getAdType());
    requestManager = new AdViewRequestManager(bannerAdView);
    requestManager.execute();
    Robolectric.flushBackgroundThreadScheduler();
    Robolectric.flushForegroundThreadScheduler();
    Assert.assertEquals(30000, bannerAdView.getAutoRefreshInterval());
    Assert.assertEquals(AdType.NATIVE, bannerAdView.getAdType());
    assertCallbacks(true);
    assertOpensInNativeBrowser();
    assertLoadsInBackground();
    assertClickThroughAction();
    assertClickThroughAction(ANClickThroughAction.RETURN_URL);
}
 
Example #13
Source File: QueueApiMockTest.java    From jenkins-rest with Apache License 2.0 6 votes vote down vote up
public void testCancelQueueItem() throws Exception {
    MockWebServer server = mockWebServer();
    server.enqueue(new MockResponse().setResponseCode(404));
    JenkinsApi jenkinsApi = api(server.getUrl("/"));
    int queueItemId = 143;
    RequestStatus result = jenkinsApi.queueApi().cancel(queueItemId);
    try {
        assertNotNull(result);
        assertTrue(result.value());
        assertTrue(result.errors().isEmpty());
        assertSentWithFormData(server, "POST", "/queue/cancelItem", "id=" + queueItemId);
    } finally {
        jenkinsApi.close();
        server.shutdown();
    }
}
 
Example #14
Source File: ProjectApiMockTest.java    From bitbucket-rest with Apache License 2.0 6 votes vote down vote up
public void testGetProjectListNonExistent() throws Exception {
    final MockWebServer server = mockWebServer();

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

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

        assertThat(projectPage).isNotNull();
        assertThat(projectPage.errors()).isNotEmpty();
        assertSent(server, localMethod, restBasePath + BitbucketApiMetadata.API_VERSION + localPath);
    } finally {
        server.shutdown();
    }
}
 
Example #15
Source File: SampleServer.java    From httplite with Apache License 2.0 6 votes vote down vote up
@Override public MockResponse dispatch(RecordedRequest request) {
    System.out.println("Headers:"+request.getHeaders().toMultimap());
    String handleParam = request.getHeaders().get("handle");
    String method = request.getMethod().toUpperCase();
    MethodHandle handle = null;
    if(handleParam!=null){
        handle = mHandleMap.get(handleParam.toUpperCase());
    }
    System.out.printf("Path:%s,Method:%s\n",request.getPath(),method);
    if(handle==null){
        handle = mHandleMap.get(method);
    }
    if(handle!=null){
        return handle.handle(request,root);
    }else{
        return new MockResponse()
                .setStatus("HTTP/1.1 500")
                .addHeader("content-type: text/plain; charset=utf-8")
                .setBody("NO method handle for: " + method);
    }
}
 
Example #16
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 #17
Source File: VideoAdTest.java    From mobile-sdk-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetVideoOrientationLandscape() throws Exception {
    ShadowCustomWebView.aspectRatio = "1.7778"; // 16:9
    server.enqueue(new MockResponse().setResponseCode(200).setBody(TestUTResponses.video()));

    videoAd.loadAd();
    Lock.pause(1000);
    waitForTasks();
    Robolectric.flushForegroundThreadScheduler();
    Robolectric.flushBackgroundThreadScheduler();

    waitForTasks();
    Robolectric.getBackgroundThreadScheduler().advanceToNextPostedRunnable();
    Robolectric.getForegroundThreadScheduler().advanceToNextPostedRunnable();
    assertAdLoaded(true);
    Clog.w(TestUtil.testLogTag, "VideoAdTest videoAd.getVideoOrientation()" +videoAd.getVideoOrientation());
    assertTrue(videoAd.getVideoOrientation().equals(VideoOrientation.LANDSCAPE));
}
 
Example #18
Source File: MRAIDTest.java    From mobile-sdk-android with Apache License 2.0 6 votes vote down vote up
private void loadMraidBanner(String testName) {
    server.enqueue(new MockResponse().setResponseCode(200).setBody(TestResponsesUT.mraidBanner(testName)));
    requestManager = new AdViewRequestManager(bannerAdView);
    requestManager.execute();
    // let AdFetcher queue AdRequest
    waitForTasks();
    // Flush AAID tasks before AdRequest tasks twice to make sure AdRequest gets executed
    Robolectric.flushForegroundThreadScheduler();
    Robolectric.flushBackgroundThreadScheduler();
    Robolectric.flushForegroundThreadScheduler();
    Robolectric.flushBackgroundThreadScheduler();
    Robolectric.flushForegroundThreadScheduler();

    assertTrue(bannerAdView.getChildAt(0) instanceof WebView);
    webView = (WebView) bannerAdView.getChildAt(0);
}
 
Example #19
Source File: BranchApiMockTest.java    From bitbucket-rest with Apache License 2.0 6 votes vote down vote up
public void testGetBranchModelConfigurationOnError() throws Exception {
    final MockWebServer server = mockWebServer();

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

        final BranchModelConfiguration configuration = baseApi.branchApi().getModelConfiguration(projectKey, repoKey);
        assertThat(configuration).isNotNull();
        assertThat(configuration.errors()).isNotEmpty();
        assertThat(configuration.production()).isNull();
        assertThat(configuration.development()).isNull();
        assertSent(server, localGetMethod, localRestPath + BitbucketApiMetadata.API_VERSION
                + localProjectsPath + projectKey + localReposPath + repoKey + branchModelPath);
    } finally {
        server.shutdown();
    }
}
 
Example #20
Source File: DesignateResourceRecordSetApiMockTest.java    From denominator with Apache License 2.0 6 votes vote down vote up
@Test
public void putCreatesRecord() throws Exception {
  server.enqueueAuthResponse();
  server.enqueue(new MockResponse().setBody("{ \"records\": [] }"));
  server.enqueue(new MockResponse().setBody(aRecordResponse));

  ResourceRecordSetApi api = server.connect().api().basicRecordSetsInZone(domainId);
  api.put(a("www.denominator.io.", 3600, "192.0.2.1"));

  server.assertAuthRequest();
  server.assertRequest()
      .hasMethod("GET")
      .hasPath(format("/v1/domains/%s/records", domainId));
  server.assertRequest()
      .hasMethod("POST")
      .hasPath(format("/v1/domains/%s/records", domainId))
      .hasBody("{\n"
               + "  \"name\": \"www.denominator.io.\",\n"
               + "  \"type\": \"A\",\n"
               + "  \"ttl\": 3600,\n"
               + "  \"data\": \"192.0.2.1\"\n"
               + "}");
}
 
Example #21
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 #22
Source File: Route53ResourceRecordSetApiMockTest.java    From denominator with Apache License 2.0 6 votes vote down vote up
@Test
public void putOneRecordReplacesRRSet() throws Exception {
  server.enqueue(new MockResponse().setBody(twoRecords));
  server.enqueue(new MockResponse().setBody(changeSynced));

  ResourceRecordSetApi api = server.connect().api().basicRecordSetsInZone("Z1PA6795UKMFR9");
  api.put(a("www.denominator.io.", 3600, "192.0.2.1"));

  server.assertRequest()
      .hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset?name=www.denominator.io.&type=A");
  server.assertRequest()
      .hasMethod("POST")
      .hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset")
      .hasXMLBody(
          "<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\"><ChangeBatch><Changes><Change><Action>DELETE</Action><ResourceRecordSet><Name>www.denominator.io.</Name><Type>A</Type><TTL>3600</TTL><ResourceRecords><ResourceRecord><Value>192.0.2.1</Value></ResourceRecord><ResourceRecord><Value>198.51.100.1</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></Change><Change><Action>CREATE</Action><ResourceRecordSet><Name>www.denominator.io.</Name><Type>A</Type><TTL>3600</TTL><ResourceRecords><ResourceRecord><Value>192.0.2.1</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></Change></Changes></ChangeBatch></ChangeResourceRecordSetsRequest>");
}
 
Example #23
Source File: MediatedNativeAdViewControllerTest.java    From mobile-sdk-android with Apache License 2.0 6 votes vote down vote up
@Test
    public void testTestNoFill() {

        String[] classNames = {"MediatedNativeNoFill", "MediatedNativeNoFill"};
        String[] responseURLs = {TestResponsesUT.RESPONSE_URL, TestResponsesUT.RESPONSE_URL};
        server.enqueue(new MockResponse().setResponseCode(200).setBody(TestResponsesUT.waterfall_CSM_Native(classNames, responseURLs)));
        server.enqueue(new MockResponse().setResponseCode(200).setBody(TestResponsesUT.blank()));// First ResponseURL
        server.enqueue(new MockResponse().setResponseCode(200).setBody(TestResponsesUT.blank()));// Second Response URL
//        server.enqueue(new MockResponse().setResponseCode(200).setBody(TestResponsesUT.blank()));// This is for No Ad URL

        executeUTRequest();
        Lock.pause(ShadowSettings.MEDIATED_NETWORK_TIMEOUT + 1000);
        executeAndAssertResponseURL(2, UNABLE_TO_FILL, CHECK_LATENCY_TRUE);
        //2 request are already taken out of queue current position of ResponseURL in queue is 1
        executeAndAssertResponseURL(1, UNABLE_TO_FILL, CHECK_LATENCY_TRUE);

//        Lock.pause(Settings.MEDIATED_NETWORK_TIMEOUT + 1000);

        assertCallbacks(false);
        assertNoAdURL();
    }
 
Example #24
Source File: BuildStatusApiMockTest.java    From bitbucket-rest with Apache License 2.0 6 votes vote down vote up
public void testGetStatusOnError() throws Exception {
    final MockWebServer server = mockWebServer();

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

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

    server.enqueue(new MockResponse().setBody(payloadFromResource("/build-summary.json")).setResponseCode(200));
    try (final BitbucketApi baseApi = api(server.getUrl("/"))) {
        
        final Summary summary = baseApi.buildStatusApi().summary(commitHash);
        assertThat(summary).isNotNull();
        assertThat(summary.failed() == 1).isTrue();
        assertThat(summary.inProgress() == 2).isTrue();
        assertThat(summary.successful() == 3).isTrue();

        assertSent(server, "GET", restBuildStatusPath + BitbucketApiMetadata.API_VERSION
                + "/commits/stats/306bcf274566f2e89f75ae6f7faf10beff38382012");
    } finally {
        server.shutdown();
    }
}
 
Example #26
Source File: BuildStatusApiMockTest.java    From bitbucket-rest with Apache License 2.0 6 votes vote down vote up
public void testAddBuildStatus() throws Exception {
    final MockWebServer server = mockWebServer();

    server.enqueue(new MockResponse().setBody(payloadFromResource("/build-status-post.json")).setResponseCode(204));
    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()).isTrue();
        assertThat(success.errors()).isEmpty();
        
        assertSent(server, "POST", restBuildStatusPath + BitbucketApiMetadata.API_VERSION
                + commitPath);
    } finally {
        server.shutdown();
    }
}
 
Example #27
Source File: AWSEC2ComputeServiceApiMockTest.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
protected void runDeleteIncidentalResourcesGivingErrForSecurityGroup(String errCode) throws Exception {
   // Does not return delete_securitygroup.xml, but instead gives a 400 error.
   // Because super.builder has set TIMEOUT_CLEANUP_INCIDENTAL_RESOURCES to 0, it will not retry.

   enqueueRegions(DEFAULT_REGION);
   enqueueXml(DEFAULT_REGION, "/describe_securitygroups_extension_single.xml");
   enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(400).setBody("<Response><Errors><Error><Code>" + errCode + "</Code><Message>resource sg-3c6ef654 has a dependent object</Message></Error></Errors><RequestID>e4f4c78f-4455-43dd-b5cb-9af0bc4bc804</RequestID></Response>"));
   enqueueXml(DEFAULT_REGION, "/describe_placement_groups.xml");
   enqueueXml(DEFAULT_REGION, "/delete_placementgroup.xml");
   enqueueXml(DEFAULT_REGION, "/describe_placement_groups_empty.xml");

   AWSEC2ComputeService computeService = (AWSEC2ComputeService) computeService();

   computeService.cleanUpIncidentalResources(DEFAULT_REGION, "sg-3c6ef654");

   assertPosted(DEFAULT_REGION, "Action=DescribeRegions");
   assertPosted(DEFAULT_REGION, "Action=DescribeSecurityGroups&GroupName.1=jclouds%23sg-3c6ef654");
   assertPosted(DEFAULT_REGION, "Action=DeleteSecurityGroup&GroupName=jclouds%23sg-3c6ef654");
   assertPosted(DEFAULT_REGION, "Action=DescribePlacementGroups&GroupName.1=jclouds%23sg-3c6ef654%23us-east-1");
   assertPosted(DEFAULT_REGION, "Action=DeletePlacementGroup&GroupName=jclouds%23sg-3c6ef654%23us-east-1");
   assertPosted(DEFAULT_REGION, "Action=DescribePlacementGroups&GroupName.1=jclouds%23sg-3c6ef654%23us-east-1");
}
 
Example #28
Source File: DynECTZoneApiMockTest.java    From denominator with Apache License 2.0 5 votes vote down vote up
@Test
public void deleteWhenPresent() throws Exception {
  server.enqueueSessionResponse();
  server.enqueue(new MockResponse());

  ZoneApi api = server.connect().api().zones();
  api.delete("denominator.io.");

  server.assertSessionRequest();
  server.assertRequest().hasMethod("DELETE").hasPath("/Zone/denominator.io.");
}
 
Example #29
Source File: DesignateTest.java    From denominator with Apache License 2.0 5 votes vote down vote up
@Test
public void domainsPresent() throws Exception {
  server.enqueueAuthResponse();
  server.enqueue(new MockResponse().setBody(domainsResponse));

  assertThat(mockApi().domains()).containsExactly(
      Zone.create(domainId, "denominator.io.", 3601, "[email protected]")
  );

  server.assertAuthRequest();
  server.assertRequest()
      .hasMethod("GET")
      .hasPath("/v1/domains");
}
 
Example #30
Source File: SimpleRequestTest.java    From jus with Apache License 2.0 5 votes vote down vote up
@Test
public void cloningExecutedRequestDoesNotCopyState() throws IOException,
        ExecutionException, InterruptedException {

    server.enqueue(new MockResponse().setBody("Hi"));
    server.enqueue(new MockResponse().setBody("Hello"));

    Request<String> call = example.getString().enqueue();
    assertThat(call.getFuture().get()).isEqualTo("Hi");

    Request<String> cloned = call.clone();
    assertThat(cloned.enqueue().getFuture().get()).isEqualTo("Hello");
}