Java 类com.squareup.okhttp.mockwebserver.MockResponse 实例源码

项目:delta-sdk-java    文件:DeltaApiClientTest.java   
@Test
public void shouldReturnValidResponseGivenValidClientRegisterRequest()
        throws Exception {
    MockResponse mockResponse = new MockResponse()
            .setBody(FileUtil.readFile("register.json"));
    mockWebServer.enqueue(mockResponse);

    final String testSigningKey = "testSigningKey";

    final String testEncryptionKey = "testEncryptionKey";

    CreateIdentityRequest request = new CreateIdentityRequest(
            testSigningKey, testEncryptionKey, null, null);

    String clientId = apiClient.createIdentity(request).getIdentityId();

    Map expectedRequestBody = ImmutableMap.of(
            ATTR_CRYPTO_PUBLIC_KEY, testEncryptionKey,
            ATTR_SIGNING_PUBLIC_KEY, testSigningKey);

    assertThat(getBodyAsMap(mockWebServer.takeRequest()), equalTo(expectedRequestBody));

    assertEquals(clientId, IDENTITY_ID);
}
项目:bitbucket-rest    文件:DefaultReviewersApiMockTest.java   
public void testDeleteCondition() throws Exception {
    final MockWebServer server = mockWebServer();

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

        final RequestStatus success = baseApi.defaultReviewersApi().deleteCondition(projectKey, repoKey, 10L);
        assertThat(success).isNotNull();
        assertThat(success.value()).isTrue();
        assertThat(success.errors()).isEmpty();
        assertSent(server, "DELETE", defaultReviewersPath + BitbucketApiMetadata.API_VERSION
                + projectsPath + projectKey + reposPath + repoKey + "/condition/10");
    } finally {
        server.shutdown();
    }
}
项目:bitbucket-rest    文件:DefaultReviewersApiMockTest.java   
public void testDeleteConditionOnError() throws Exception {
    final MockWebServer server = mockWebServer();

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

        final RequestStatus success = baseApi.defaultReviewersApi().deleteCondition(projectKey, repoKey, 10L);
        assertThat(success).isNotNull();
        assertThat(success.value()).isFalse();
        assertThat(success.errors()).isNotEmpty();
        assertSent(server, "DELETE", defaultReviewersPath + BitbucketApiMetadata.API_VERSION
                + projectsPath + projectKey + reposPath + repoKey + "/condition/10");
    } finally {
        server.shutdown();
    }
}
项目:bitbucket-rest    文件:BranchApiMockTest.java   
public void testDeleteBranchModelConfiguration() throws Exception {
    final MockWebServer server = mockWebServer();

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

        final RequestStatus success = baseApi.branchApi().deleteModelConfiguration(projectKey, repoKey);
        assertThat(success).isNotNull();
        assertThat(success.value()).isTrue();
        assertThat(success.errors()).isEmpty();
        assertSent(server, localDeleteMethod, localRestPath + BitbucketApiMetadata.API_VERSION
                + localProjectsPath + projectKey + localReposPath + repoKey + branchModelPath);
    } finally {
        server.shutdown();
    }
}
项目:bitbucket-rest    文件:DefaultReviewersApiMockTest.java   
public void testUpdateConditionOnError() throws Exception {
    final MockWebServer server = mockWebServer();

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

        final Long requiredApprover = 1L;
        final Matcher matcherSrc = Matcher.create(Matcher.MatcherId.ANY, true);
        final Matcher matcherDst = Matcher.create(Matcher.MatcherId.ANY, true);
        final List<User> listUser = new ArrayList<>();
        listUser.add(User.create(projectKey, testEmail, 1, projectKey, true, projectKey, normalKeyword));
        final CreateCondition condition = CreateCondition.create(10L, matcherSrc, matcherDst, listUser, requiredApprover);

        final Condition returnCondition = baseApi.defaultReviewersApi().updateCondition(projectKey, "123456", 10L, condition);
        assertThat(returnCondition).isNotNull();
        assertThat(returnCondition.errors()).isNotEmpty();
        assertThat(returnCondition.errors().size()).isEqualTo(1);

        assertSent(server, "PUT", defaultReviewersPath + BitbucketApiMetadata.API_VERSION
                + projectsPath + projectKey + "/repos/123456/condition/10");
    } finally {
        server.shutdown();
    }
}
项目:delta-sdk-java    文件:DeltaApiClientTest.java   
@SuppressWarnings("unchecked")
@Test
public void shouldReturnValidResponseGivenValidSecretCreationRequest() throws Exception {
    // set up mock server
    mockWebServer.enqueue(new MockResponse().setBody(FileUtil.readFile("createSecret.json")));

    // create request
    String content = "base64String";
    String secretKey = BaseEncoding.base64().encode(SharedTestKeys.SECRET_KEY_A.getEncoded());
    CreateSecretRequest createSecretRequest = new CreateSecretRequest(IDENTITY_ID, content, new EncryptionDetails(secretKey, "1"));

    // make a test call
    CreateSecretResponse response = createDeltaApiClient().createSecret(createSecretRequest);

    // assert response
    assertEquals(SECRET_ID, response.getSecretId());

    // assert the request we made during the test call
    RecordedRequest request = mockWebServer.takeRequest(1, TimeUnit.SECONDS);
    assertEquals(IDENTITY_ID, getAuthIdentity(request.getHeader(AUTHORIZATION)));
    Map<String, Object> requestBody = getBodyAsMap(request);
    assertEquals(content, requestBody.get("content"));
    Map<String, String> encryptionDetails = (Map<String, String>) requestBody.get("encryptionDetails");
    assertEquals("1", encryptionDetails.get("initialisationVector"));
    assertEquals(secretKey, encryptionDetails.get("symmetricKey"));
}
项目:delta-sdk-java    文件:DeltaApiClientTest.java   
@Test
public void shouldReturnValidResponseGivenValidGetSecretRequest() throws Exception {
    // set up mock server
    mockWebServer.enqueue(new MockResponse().setBody(FileUtil.readFile("getSecret.json")));
    SecretRequest secretRequest = new SecretRequest(IDENTITY_ID, SECRET_ID);

    // make a test call
    GetSecretResponse response = createDeltaApiClient().getSecret(secretRequest);

    // assert the response
    assertEquals(SECRET_ID, response.getId());
    assertEquals("2016-08-23T17:02:47Z", response.getCreated());
    assertEquals("b15e50ea-ce07-4a3d-a4fc-0cd6b4d9ab13", response.getCreatedBy());
    assertEquals(IDENTITY_ID, response.getRsaKeyOwner());

    // assert the request we made during the test call
    RecordedRequest request = mockWebServer.takeRequest(1, TimeUnit.SECONDS);
    assertEquals(IDENTITY_ID, getAuthIdentity(request.getHeader(AUTHORIZATION)));
    assertTrue(request.getPath().endsWith("/" + SECRET_ID));
}
项目:delta-sdk-java    文件:DeltaApiClientTest.java   
@Test
public void shouldReturnValidResponseGivenValidGetSecretContentRequest() throws Exception {
    // set up mock server
    mockWebServer.enqueue(new MockResponse().setBody(FileUtil.readFile("getSecretContent.json")));
    SecretRequest secretRequest = new SecretRequest(IDENTITY_ID, SECRET_ID);

    // make a test call
    String response = createDeltaApiClient().getSecretContent(secretRequest);

    // assert the response
    assertEquals("base64String", response);

    // assert the request we made during the test call
    RecordedRequest request = mockWebServer.takeRequest(1, TimeUnit.SECONDS);
    assertEquals(IDENTITY_ID, getAuthIdentity(request.getHeader(AUTHORIZATION)));
    assertTrue(request.getPath().endsWith("/" + SECRET_ID + "/content"));
}
项目:delta-sdk-java    文件:DeltaApiClientTest.java   
@Test
public void shouldReturnValidResponseGivenValidGetSecretMetadataRequest() throws Exception {
    // set up mock server
    mockWebServer.enqueue(new MockResponse()
            .setBody(FileUtil.readFile("getSecretMetadata.json"))
            .addHeader(HttpHeaders.ETAG, "2"));
    SecretRequest secretRequest = new SecretRequest(IDENTITY_ID, SECRET_ID);

    // make a test call
    GetSecretMetadataResponse response = createDeltaApiClient().getSecretMetadata(secretRequest);

    // assert the response
    assertEquals(METADATA, response.getMetadata());

    // assert the request we made during the test call
    RecordedRequest request = mockWebServer.takeRequest(1, TimeUnit.SECONDS);
    assertEquals(IDENTITY_ID, getAuthIdentity(request.getHeader(AUTHORIZATION)));
    assertTrue(request.getPath().endsWith("/" + SECRET_ID + "/metadata"));
}
项目:bitbucket-rest    文件:ProjectApiMockTest.java   
public void testDeleteProjectNonExistent() 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 String projectKey = "NOTEXIST";
        final RequestStatus success = baseApi.projectApi().delete(projectKey);
        assertThat(success).isNotNull();
        assertThat(success.value()).isFalse();
        assertThat(success.errors()).isNotEmpty();
        assertSent(server, "DELETE", "/rest/api/" + BitbucketApiMetadata.API_VERSION + "/projects/" + projectKey);
    } finally {
        server.shutdown();
    }
}
项目:delta-sdk-java    文件:DeltaApiClientTest.java   
@Test
public void shouldReturnValidResponseGivenValidGetDerivedSecretsRequest() throws Exception {
    // set up mock server
    mockWebServer.enqueue(new MockResponse().setBody(FileUtil.readFile("getDerivedSecrets.json")));
    GetDerivedSecretsRequest getDerivedSecretsRequest = new GetDerivedSecretsRequest(IDENTITY_ID, SECRET_ID, 0, 10);

    // make a test call
    List<GetSecretsResponse> response = createDeltaApiClient().getDerivedSecrets(getDerivedSecretsRequest);

    // assert the response
    assertEquals(1, response.size());
    GetSecretsResponse secret = response.get(0);
    assertEquals(SECRET_ID, secret.getId());
    assertEquals("https://example.server/secrets/067e6162-3b6f-4ae2-a171-2470b63dff00", secret.getHref());
    assertEquals("b15e50ea-ce07-4a3d-a4fc-0cd6b4d9ab13", secret.getCreatedBy());
    assertEquals("2016-08-23T17:02:47Z", secret.getCreated());
    assertEquals("eb4f44d0-1b47-4981-9661-1c1101d7a049", secret.getBaseSecret());
    assertEquals(METADATA, secret.getMetadata());

    // assert the request we made during the test call
    RecordedRequest request = mockWebServer.takeRequest(1, TimeUnit.SECONDS);
    assertEquals(IDENTITY_ID, getAuthIdentity(request.getHeader(AUTHORIZATION)));
    assertEquals("GET", request.getMethod());
    assertTrue(request.getPath()
            .endsWith("/secrets?baseSecret=" + SECRET_ID + "&createdBy=" + IDENTITY_ID + "&page=0&pageSize=10"));
}
项目:delta-sdk-java    文件:DeltaApiClientTest.java   
@Test
public void shouldReturnValidResponseGivenValidUpdateIdentityMetadataRequest() throws Exception {
    // set up mock server
    mockWebServer.enqueue(new MockResponse().setBody(FileUtil.readFile("getIdentitiesByMetadata.json")));
    UpdateIdentityMetadataRequest updateIdentityMetadataRequest = new UpdateIdentityMetadataRequest(
            IDENTITY_ID,
            "identity2",
            10L,
            METADATA);

    // make a test call
    createDeltaApiClient().updateIdentityMetadata(updateIdentityMetadataRequest);

    // assert the request we made during the test call
    RecordedRequest request = mockWebServer.takeRequest(1, TimeUnit.SECONDS);
    assertEquals(IDENTITY_ID, getAuthIdentity(request.getHeader(AUTHORIZATION)));
    assertEquals("PUT", request.getMethod());
    assertTrue(request.getPath().endsWith("/identity2"));
}
项目:nordnet-next-api    文件:TestSessionInit.java   
@Ignore("There is a problem in this test as the sessionKey gets updated by the integration tests and failing this tests.")
@Test
public void sessionInitShouldReturnSessionKey() throws IOException {
    HttpUrl baseUrl = server.url("/next/2/");

    JSONObject sessionInitRecorded = recordedResponses.sessionInit();
    server.enqueue(new MockResponse().setBody(sessionInitRecorded.toString()));

    Properties properties = resourceReader.getProperties("test.properties");
    properties.setProperty("baseurl", baseUrl.toString());

    Session session = new Session(properties);
    Login loginObject = session.getLoginObject();

    assertThat("The sessionkey from login object should match the recorded session key",
            loginObject.getSessionKey(), equalTo(sessionInitRecorded.getString("session_key")));

    assertThat("Only one request was made to the mock server",
            server.getRequestCount(), equalTo(1));
}
项目:bitbucket-rest    文件:BranchApiMockTest.java   
public void testGetBranchModel() throws Exception {
    final MockWebServer server = mockWebServer();

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

        final BranchModel branchModel = baseApi.branchApi().model(projectKey, repoKey);
        assertThat(branchModel).isNotNull();
        System.out.println(branchModel.errors());
        assertThat(branchModel.errors().isEmpty()).isTrue();
        assertThat(branchModel.types().size() > 0).isTrue();
        assertSent(server, localGetMethod, localRestPath + BitbucketApiMetadata.API_VERSION
                + localProjectsPath + projectKey + localReposPath + repoKey + "/branchmodel");
    } finally {
        server.shutdown();
    }
}
项目:bitbucket-rest    文件:BranchApiMockTest.java   
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();
    }
}
项目:httplite    文件:SampleServer.java   
@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);
    }
}
项目:bitbucket-rest    文件:BranchApiMockTest.java   
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();
    }
}
项目:wiremock-android    文件:MockWebServerTest.java   
/**
 * Test okhttp mockwebserver
 */
@Test
public void testMockWebServer() {
    logger.debug("testWiremock");

    String city = "atlanta";
    String assetJson = AssetReaderUtil.asset(getActivity(), city + "-conditions.json");

    //script MockWebServer to return this JSON
    mMockWebServer.enqueue(new MockResponse().setBody(assetJson));

    String okhttpMockWebServerUrl = mMockWebServer.getUrl("/").toString();
    logger.debug("okhttp mockserver URL: " + okhttpMockWebServerUrl);

    String serviceEndpoint = "http://127.0.0.1:" + BuildConfig.PORT;
    logger.debug("MockWebServer Endpoint: " + serviceEndpoint);
    getActivity().setWeatherServiceManager(new WeatherServiceManager(serviceEndpoint));

    onView(ViewMatchers.withId(R.id.portEditText)).perform(typeText(city));
    onView(withId(R.id.button)).perform(click());
    onView(withId(R.id.textView)).check(matches(withText(containsString("GA"))));
}
项目:lbry-android    文件:ServerTest.java   
@Test
public void testGetCoins() throws ShapeShiftException, IOException, InterruptedException, JSONException {
    // Schedule some responses.
    server.enqueue(new MockResponse().setBody(GET_COINS_JSON));

    ShapeShiftCoins coinsReply = shapeShift.getCoins();
    assertFalse(coinsReply.isError);
    assertEquals(3, coinsReply.coins.size());
    assertEquals(1, coinsReply.availableCoinTypes.size());
    assertEquals(BTC, coinsReply.availableCoinTypes.get(0));
    JSONObject coinsJson = new JSONObject(GET_COINS_JSON);
    for (ShapeShiftCoin coin : coinsReply.coins) {
        JSONObject json = coinsJson.getJSONObject(coin.symbol);
        assertEquals(json.getString("name"), coin.name);
        assertEquals(json.getString("symbol"), coin.symbol);
        assertEquals(json.getString("image"), coin.image.toString());
        assertEquals(json.getString("status").equals("available"), coin.isAvailable);
    }

    // Optional: confirm that your app made the HTTP requests you were expecting.
    RecordedRequest request = server.takeRequest();
    assertEquals("/getcoins", request.getPath());
}
项目:lbry-android    文件:ServerTest.java   
@Test
public void testGetMarketInfo() throws ShapeShiftException, IOException, InterruptedException, JSONException {
    // Schedule some responses.
    server.enqueue(new MockResponse().setBody(MARKET_INFO_BTC_NBT_JSON));

    ShapeShiftMarketInfo marketInfoReply = shapeShift.getMarketInfo(BTC, NBT);
    assertFalse(marketInfoReply.isError);
    assertEquals("btc_nbt", marketInfoReply.pair);
    assertNotNull(marketInfoReply.rate);

    assertNotNull(marketInfoReply.rate);
    assertNotNull(marketInfoReply.limit);
    assertNotNull(marketInfoReply.minimum);

    assertEquals(NBT.value("99.99"), marketInfoReply.rate.convert(BTC.value("1")));
    assertEquals(BTC.value("4"), marketInfoReply.limit);
    assertEquals(BTC.value("0.00000104"), marketInfoReply.minimum);

    // Optional: confirm that your app made the HTTP requests you were expecting.
    RecordedRequest request = server.takeRequest();
    assertEquals("/marketinfo/btc_nbt", request.getPath());
}
项目:lbry-android    文件:ServerTest.java   
@Test
public void testGetRate() throws ShapeShiftException, IOException, InterruptedException, JSONException {
    // Schedule some responses.
    server.enqueue(new MockResponse().setBody(GET_RATE_BTC_LTC_JSON));

    ShapeShiftRate rateReply = shapeShift.getRate(BTC, LTC);
    assertFalse(rateReply.isError);
    assertEquals("btc_ltc", rateReply.pair);
    assertNotNull(rateReply.rate);

    assertEquals(LTC, rateReply.rate.convert(BTC.oneCoin()).type);
    assertEquals(BTC, rateReply.rate.convert(LTC.oneCoin()).type);

    // Optional: confirm that your app made the HTTP requests you were expecting.
    RecordedRequest request = server.takeRequest();
    assertEquals("/rate/btc_ltc", request.getPath());
}
项目:lbry-android    文件:ServerTest.java   
@Test
public void testGetLimit() throws ShapeShiftException, IOException, InterruptedException, JSONException {
    // Schedule some responses.
    server.enqueue(new MockResponse().setBody(GET_LIMIT_BTC_LTC_JSON));

    ShapeShiftLimit limitReply = shapeShift.getLimit(BTC, LTC);
    assertFalse(limitReply.isError);
    assertEquals("btc_ltc", limitReply.pair);
    assertNotNull(limitReply.limit);

    assertEquals(BTC, limitReply.limit.type);
    assertEquals("5", limitReply.limit.toPlainString());

    // Optional: confirm that your app made the HTTP requests you were expecting.
    RecordedRequest request = server.takeRequest();
    assertEquals("/limit/btc_ltc", request.getPath());
}
项目:lbry-android    文件:ServerTest.java   
@Test
public void testGetTime() throws ShapeShiftException, IOException, InterruptedException, JSONException, AddressMalformedException {
    // Schedule some responses.
    server.enqueue(new MockResponse().setBody(GET_TIME_PENDING_JSON));
    server.enqueue(new MockResponse().setBody(GET_TIME_EXPIRED_JSON));

    AbstractAddress address = NuBitsMain.get().newAddress("BPjxHqswNZB5vznbrAAxi5zGVq3ruhtBU8");

    ShapeShiftTime timeReply = shapeShift.getTime(address);
    assertFalse(timeReply.isError);
    assertEquals(ShapeShiftTime.Status.PENDING, timeReply.status);
    assertEquals(100, timeReply.secondsRemaining);

    timeReply = shapeShift.getTime(address);
    assertFalse(timeReply.isError);
    assertEquals(ShapeShiftTime.Status.EXPIRED, timeReply.status);
    assertEquals(0, timeReply.secondsRemaining);

    // Optional: confirm that your app made the HTTP requests you were expecting.
    RecordedRequest request = server.takeRequest();
    assertEquals("/timeremaining/BPjxHqswNZB5vznbrAAxi5zGVq3ruhtBU8", request.getPath());
    request = server.takeRequest();
    assertEquals("/timeremaining/BPjxHqswNZB5vznbrAAxi5zGVq3ruhtBU8", request.getPath());
}
项目:bitbucket-rest    文件:BranchApiMockTest.java   
public void testDeleteBranchesPermissions() throws Exception {
    final MockWebServer server = mockWebServer();

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

        final Long idToDelete = 839L;
        final RequestStatus success = baseApi.branchApi().deleteBranchRestriction(projectKey, repoKey, idToDelete);
        assertThat(success).isNotNull();
        assertThat(success.value()).isTrue();
        assertThat(success.errors()).isEmpty();
        assertSent(server, localDeleteMethod, branchPermissionsPath
                + localProjectsPath + projectKey + localReposPath + repoKey + "/restrictions/" + idToDelete);
    } finally {
        server.shutdown();
    }
}
项目:lbry-android    文件:ServerTest.java   
@Test
public void testNormalTransaction() throws ShapeShiftException, IOException, InterruptedException, JSONException, AddressMalformedException {
    // Schedule some responses.
    server.enqueue(new MockResponse().setBody(NORMAL_TRANSACTION_JSON));

    AbstractAddress withdrawal = DOGE.newAddress("DMHLQYG4j96V8cZX9WSuXxLs5RnZn6ibrV");
    AbstractAddress refund = BTC.newAddress("1Nz4xHJjNCnZFPjRUq8CN4BZEXTgLZfeUW");
    ShapeShiftNormalTx normalTxReply = shapeShift.exchange(withdrawal, refund);
    assertFalse(normalTxReply.isError);
    assertEquals("btc_doge", normalTxReply.pair);
    assertEquals("18ETaXCYhJ8sxurh41vpKC3E6Tu7oJ94q8", normalTxReply.deposit.toString());
    assertEquals(BTC, normalTxReply.deposit.getType());
    assertEquals(withdrawal.toString(), normalTxReply.withdrawal.toString());
    assertEquals(DOGE, normalTxReply.withdrawal.getType());

    // Optional: confirm that your app made the HTTP requests you were expecting.
    RecordedRequest request = server.takeRequest();
    assertEquals("/shift", request.getPath());
    JSONObject reqJson = new JSONObject(request.getBody().readUtf8());
    assertEquals(withdrawal.toString(), reqJson.getString("withdrawal"));
    assertEquals(refund.toString(), reqJson.getString("returnAddress"));
    assertEquals("btc_doge", reqJson.getString("pair"));
}
项目:bitbucket-rest    文件:CommentsApiMockTest.java   
public void testCreateComment() throws Exception {
    final MockWebServer server = mockWebServer();

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

        final Parent parent = Parent.create(1);
        final Anchor anchor = Anchor.create(1, Anchor.LineType.CONTEXT, Anchor.FileType.FROM, "path/to/file", "path/to/file");
        final CreateComment createComment = CreateComment.create(measuredReplyKeyword, parent, anchor);
        final Comments pr = baseApi.commentsApi().create(projectKey, repoKey, 101, createComment);
        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();
    }
}
项目:bitbucket-rest    文件:ProjectApiMockTest.java   
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();
    }
}
项目:bitbucket-rest    文件:BranchApiMockTest.java   
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();
    }
}
项目:bitbucket-rest    文件:BranchApiMockTest.java   
public void testListBranchesPermissionsNonExistent() throws Exception {
    final MockWebServer server = mockWebServer();

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

        final BranchRestrictionPage branch = baseApi.branchApi().listBranchRestriction(projectKey, repoKey, null, 1);
        assertThat(branch).isNotNull();
        assertThat(branch.errors().size() > 0).isTrue();

        final Map<String, ?> queryParams = ImmutableMap.of(localLimit, 1);
        assertSent(server, localGetMethod, branchPermissionsPath
                + localProjectsPath + projectKey + localReposPath + repoKey + "/restrictions", queryParams);
    } finally {
        server.shutdown();
    }
}
项目:bitbucket-rest    文件:BranchApiMockTest.java   
public void testUpdateBranchesPermissions() throws Exception {
    final MockWebServer server = mockWebServer();

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

        final List<String> groupPermission = new ArrayList<>();
        groupPermission.add("Test12354");
        final List<Long> listAccessKey = new ArrayList<>();
        listAccessKey.add(123L);
        final List<BranchRestriction> listBranchPermission = new ArrayList<>();
        listBranchPermission.add(BranchRestriction.createWithId(839L, BranchRestrictionEnumType.FAST_FORWARD_ONLY,
                Matcher.create(Matcher.MatcherId.RELEASE, true), new ArrayList<User>(), groupPermission,
                listAccessKey));

        final RequestStatus success = baseApi.branchApi().createBranchRestriction(projectKey, repoKey, listBranchPermission);
        assertThat(success).isNotNull();
        assertThat(success.value()).isTrue();
        assertThat(success.errors()).isEmpty();
        assertSent(server, "POST", branchPermissionsPath
                + localProjectsPath + projectKey + localReposPath + repoKey + "/restrictions");
    } finally {
        server.shutdown();
    }
}
项目:sonar-auth-github    文件:IntegrationTest.java   
@Test
public void callback_throws_ISE_if_error_when_requesting_user_profile() throws IOException, InterruptedException {
  github.enqueue(newSuccessfulAccessTokenResponse());
  // api.github.com/user crashes
  github.enqueue(new MockResponse().setResponseCode(500).setBody("{error}"));

  DumbCallbackContext callbackContext = new DumbCallbackContext(newRequest("the-verifier-code"));
  try {
    underTest.callback(callbackContext);
    fail("exception expected");
  } catch (IllegalStateException e) {
    assertThat(e.getMessage()).isEqualTo("Fail to execute request '" + gitHubSettings.apiURL() + "user'. HTTP code: 500, response: {error}");
  }

  assertThat(callbackContext.csrfStateVerified.get()).isTrue();
  assertThat(callbackContext.userIdentity).isNull();
  assertThat(callbackContext.redirectedToRequestedPage.get()).isFalse();
}
项目:bitbucket-rest    文件:AdminApiMockTest.java   
public void testGetListUserByGroup() throws Exception {
    final MockWebServer server = mockWebServer();

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

        final UserPage up = baseApi.adminApi().listUsersByGroup(localContext, null, 0, 2);
        assertThat(up).isNotNull();
        assertThat(up.errors()).isEmpty();
        assertThat(up.size() == 2).isTrue();
        assertThat(up.values().get(0).slug().equals("bob123")).isTrue();

        final Map<String, ?> queryParams = ImmutableMap.of("context", localContext, limitKeyword, 2, startKeyword, 0);
        assertSent(server, getMethod, restApiPath + BitbucketApiMetadata.API_VERSION
                + "/admin/groups/more-members", queryParams);
    } finally {
        server.shutdown();
    }
}
项目:bitbucket-rest    文件:DefaultReviewersApiMockTest.java   
public void testCreateCondition() throws Exception {
    final MockWebServer server = mockWebServer();

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

        final Long requiredApprover = 1L;
        final Matcher matcherSrc = Matcher.create(Matcher.MatcherId.ANY, true);
        final Matcher matcherDst = Matcher.create(Matcher.MatcherId.ANY, true);
        final List<User> listUser = new ArrayList<>();
        listUser.add(User.create(projectKey, testEmail, 1, projectKey, true, projectKey, normalKeyword));
        final CreateCondition condition = CreateCondition.create(null, matcherSrc, matcherDst, listUser, requiredApprover);

        final Condition returnCondition = baseApi.defaultReviewersApi().createCondition(projectKey, repoKey, condition);
        assertThat(returnCondition).isNotNull();
        assertThat(returnCondition.errors()).isEmpty();
        assertThat(returnCondition.id()).isEqualTo(3L);

        assertSent(server, "POST", defaultReviewersPath + BitbucketApiMetadata.API_VERSION
                + projectsPath + projectKey + reposPath + repoKey + "/condition");
    } finally {
        server.shutdown();
    }
}
项目:bitbucket-rest    文件:BuildStatusApiMockTest.java   
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();
    }
}
项目:bitbucket-rest    文件:BuildStatusApiMockTest.java   
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();
    }
}
项目:bitbucket-rest    文件:BranchApiMockTest.java   
public void testCreateBranch() throws Exception {
    final MockWebServer server = mockWebServer();

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

        final String branchName = "dev-branch";
        final String commitHash = "8d351a10fb428c0c1239530256e21cf24f136e73";

        final CreateBranch createBranch = CreateBranch.create(branchName, commitHash, null);
        final Branch branch = baseApi.branchApi().create(projectKey, repoKey, createBranch);
        assertThat(branch).isNotNull();
        assertThat(branch.errors().isEmpty()).isTrue();
        assertThat(branch.id().endsWith(branchName)).isTrue();
        assertThat(commitHash.equalsIgnoreCase(branch.latestChangeset())).isTrue();
        assertSent(server, "POST", localRestPath + BitbucketApiMetadata.API_VERSION
                + localProjectsPath + projectKey + localReposPath + repoKey + localBranchesPath);
    } finally {
        server.shutdown();
    }
}
项目:bitbucket-rest    文件:BuildStatusApiMockTest.java   
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();
    }
}