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

项目:Auth0.Android    文件:AuthenticationAPIClientTest.java   
@Test
public void shouldSendEmailLinkAndroidWithCustomConnection() throws Exception {
    mockAPI.willReturnSuccessfulPasswordlessStart();

    final MockAuthenticationCallback<Void> callback = new MockAuthenticationCallback<>();
    client.passwordlessWithEmail(SUPPORT_AUTH0_COM, PasswordlessType.ANDROID_LINK, MY_CONNECTION)
            .start(callback);

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
    assertThat(request.getPath(), equalTo("/passwordless/start"));

    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("client_id", CLIENT_ID));
    assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM));
    assertThat(body, hasEntry("send", "link_android"));
    assertThat(body, hasEntry("connection", MY_CONNECTION));

    assertThat(callback, hasNoError());
}
项目:Auth0.Android    文件:AuthenticationAPIClientTest.java   
@Test
public void shouldRenewAuthWithDelegationIfNotOIDCConformant() throws Exception {
    Auth0 auth0 = new Auth0(CLIENT_ID, mockAPI.getDomain(), mockAPI.getDomain());
    auth0.setOIDCConformant(false);
    AuthenticationAPIClient client = new AuthenticationAPIClient(auth0);

    mockAPI.willReturnSuccessfulLogin();
    final MockAuthenticationCallback<Credentials> callback = new MockAuthenticationCallback<>();
    client.renewAuth("refreshToken")
            .start(callback);

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
    assertThat(request.getPath(), equalTo("/delegation"));

    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("client_id", CLIENT_ID));
    assertThat(body, hasEntry("refresh_token", "refreshToken"));
    assertThat(body, hasEntry("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"));

    assertThat(callback, hasPayloadOfType(Credentials.class));
}
项目:Auth0.Android    文件:UsersAPIClientTest.java   
@Test
public void shouldGetUserProfile() throws Exception {
    mockAPI.willReturnUserProfile();

    final MockManagementCallback<UserProfile> callback = new MockManagementCallback<>();
    client.getProfile(USER_ID_PRIMARY)
            .start(callback);

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getPath(), equalTo("/api/v2/users/" + USER_ID_PRIMARY));

    assertThat(request.getHeader(HEADER_AUTHORIZATION), equalTo(BEARER + TOKEN_PRIMARY));
    assertThat(request.getMethod(), equalTo(METHOD_GET));

    assertThat(callback, hasPayloadOfType(UserProfile.class));
}
项目: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"));
}
项目:Auth0.Android    文件:UsersAPIClientTest.java   
@Test
public void shouldUpdateUserMetadata() throws Exception {
    mockAPI.willReturnUserProfile();

    final Map<String, Object> metadata = new HashMap<>();
    metadata.put("boolValue", true);
    metadata.put("name", "my_name");
    metadata.put("list", Arrays.asList("my", "name", "is"));

    final MockManagementCallback<UserProfile> callback = new MockManagementCallback<>();
    client.updateMetadata(USER_ID_PRIMARY, metadata)
            .start(callback);

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getPath(), equalTo("/api/v2/users/" + USER_ID_PRIMARY));

    assertThat(request.getHeader(HEADER_AUTHORIZATION), equalTo(BEARER + TOKEN_PRIMARY));
    assertThat(request.getMethod(), equalTo(METHOD_PATCH));
    Map<String, Object> body = bodyFromRequest(request);

    assertThat(body, hasKey(KEY_USER_METADATA));
    assertThat(((Map<String, Object>) body.get(KEY_USER_METADATA)), is(equalTo(metadata)));

    assertThat(callback, hasPayloadOfType(UserProfile.class));
}
项目: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"));
}
项目:Auth0.Android    文件:AuthenticationAPIClientTest.java   
@Test
public void shouldFetchProfileAfterLoginRequest() throws Exception {
    mockAPI.willReturnSuccessfulLogin()
            .willReturnTokenInfo();

    MockAuthenticationCallback<Authentication> callback = new MockAuthenticationCallback<>();
    client.getProfileAfter(client.login(SUPPORT_AUTH0_COM, "voidpassword", MY_CONNECTION))
            .start(callback);

    final RecordedRequest firstRequest = mockAPI.takeRequest();
    assertThat(firstRequest.getPath(), equalTo("/oauth/ro"));

    Map<String, String> body = bodyFromRequest(firstRequest);
    assertThat(body, hasEntry("username", SUPPORT_AUTH0_COM));
    assertThat(body, hasEntry("password", "voidpassword"));
    assertThat(body, hasEntry("connection", MY_CONNECTION));

    final RecordedRequest secondRequest = mockAPI.takeRequest();
    assertThat(secondRequest.getHeader("Authorization"), is("Bearer " + AuthenticationAPI.ACCESS_TOKEN));
    assertThat(secondRequest.getPath(), equalTo("/userinfo"));

    assertThat(callback, hasPayloadOfType(Authentication.class));
}
项目: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"));
}
项目:httplite    文件:MiscHandle.java   
private MockResponse handleDownload(RecordedRequest request, String root) {
    File rootDir = new File(root);
    File[] files = rootDir.listFiles();
    if(files!=null)
    try {
        for (File file:files){
            if(file.isFile()&&file.length()>500000){
                return GetHandle.fileToResponse(file.getAbsolutePath(),file);
            }
        }
    } catch (Exception e) {
        return new MockResponse()
                .setStatus("HTTP/1.1 500")
                .addHeader("content-type: text/plain; charset=utf-8")
                .setBody("SERVER ERROR: " + e);
    }
    return new MockResponse()
            .setStatus("HTTP/1.1 404")
            .addHeader("content-type: text/plain; charset=utf-8")
            .setBody("NOT FOUND: " + request.getPath());
}
项目:httplite    文件:MiscHandle.java   
private String createBodyInfo(RecordedRequest request) {
    if(HttpUtil.getMimeType(request).equals("application/json")){
        Charset charset = HttpUtil.getChartset(request);
        String json = request.getBody().readString(charset);
        System.out.println("createBodyInfo:"+json);
        return String.format("JsonBody charSet:%s,body:%s",charset.displayName(),json);
    }else if(HttpUtil.getMimeType(request).equals("application/x-www-form-urlencoded")){
        System.out.println("FormBody");
        String s;
        StringBuilder sb = new StringBuilder();
        try {
            while ((s = request.getBody().readUtf8Line())!=null){
                sb.append(URLDecoder.decode(s, Util.UTF_8.name()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("createBodyInfo:"+sb.toString());
        return "FormBody:"+sb.toString();
    }else if(RecordedUpload.isMultipartContent(request)){
        return handleMultipart(request);
    }
    return HttpUtil.getMimeType(request);
}
项目:Auth0.Android    文件:AuthenticationAPIClientTest.java   
@Test
public void shouldSendSMSLinkWithCustomConnection() throws Exception {
    mockAPI.willReturnSuccessfulPasswordlessStart();

    final MockAuthenticationCallback<Void> callback = new MockAuthenticationCallback<>();
    client.passwordlessWithSMS("+1123123123", PasswordlessType.WEB_LINK, MY_CONNECTION)
            .start(callback);

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
    assertThat(request.getPath(), equalTo("/passwordless/start"));

    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("client_id", CLIENT_ID));
    assertThat(body, hasEntry("phone_number", "+1123123123"));
    assertThat(body, hasEntry("send", "link"));
    assertThat(body, hasEntry("connection", MY_CONNECTION));

    assertThat(callback, hasNoError());
}
项目: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);
    }
}
项目:httplite    文件:HttpUtil.java   
public static Charset getChartset(RecordedRequest request){
    Headers headers = request.getHeaders();
    String value = headers.get("content-type");
    String[] array = value.split(";");
    Charset charset = null;
    try {
        if(array.length>1&&array[1].startsWith("charset=")){
            String charSetStr = array[1].split("=")[1];
            charset = Charset.forName(charSetStr);
        }
    } catch (Exception e) {
        System.out.println("ContentType:"+value);
        e.printStackTrace();
    }
    if(charset==null){
        charset = Charset.forName("utf-8");
    }
    return charset;
}
项目: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());
}
项目:Auth0.Android    文件:AuthenticationAPIClientTest.java   
@Test
public void shouldSendSMSLinkAndroidWithCustomConnection() throws Exception {
    mockAPI.willReturnSuccessfulPasswordlessStart();

    final MockAuthenticationCallback<Void> callback = new MockAuthenticationCallback<>();
    client.passwordlessWithSMS("+1123123123", PasswordlessType.ANDROID_LINK, MY_CONNECTION)
            .start(callback);

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
    assertThat(request.getPath(), equalTo("/passwordless/start"));

    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("client_id", CLIENT_ID));
    assertThat(body, hasEntry("phone_number", "+1123123123"));
    assertThat(body, hasEntry("send", "link_android"));
    assertThat(body, hasEntry("connection", MY_CONNECTION));

    assertThat(callback, hasNoError());
}
项目: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());
}
项目: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    文件:BaseBitbucketMockTest.java   
protected RecordedRequest assertSent(final MockWebServer server, 
        final String method, 
        final String expectedPath, 
        final Map<String, ?> queryParams) throws InterruptedException {

    final RecordedRequest request = server.takeRequest();
    assertThat(request.getMethod()).isEqualTo(method);
    assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo(APPLICATION_JSON);

    final String path = request.getPath();
    final String rawPath = path.contains("?") ? path.substring(0, path.indexOf('?')) : path;
    assertThat(rawPath).isEqualTo(expectedPath);

    final Map<String, String> normalizedParams = Maps.transformValues(queryParams, Functions.toStringFunction());
    assertThat(normalizedParams).isEqualTo(extractParams(path));

    return request;
}
项目:Auth0.Android    文件:AuthenticationAPIClientTest.java   
@Test
public void shouldRenewAuthWithOAuthTokenIfOIDCConformant() throws Exception {
    Auth0 auth0 = new Auth0(CLIENT_ID, mockAPI.getDomain(), mockAPI.getDomain());
    auth0.setOIDCConformant(true);
    AuthenticationAPIClient client = new AuthenticationAPIClient(auth0);

    mockAPI.willReturnSuccessfulLogin();
    final MockAuthenticationCallback<Credentials> callback = new MockAuthenticationCallback<>();
    client.renewAuth("refreshToken")
            .start(callback);

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
    assertThat(request.getPath(), equalTo("/oauth/token"));

    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("client_id", CLIENT_ID));
    assertThat(body, hasEntry("refresh_token", "refreshToken"));
    assertThat(body, hasEntry("grant_type", "refresh_token"));

    assertThat(callback, hasPayloadOfType(Credentials.class));
}
项目:Auth0.Android    文件:BaseAuthenticationRequestTest.java   
@Test
public void shouldSetRealm() throws Exception {
    HttpUrl url = HttpUrl.parse(mockAPI.getDomain())
            .newBuilder()
            .addPathSegment(OAUTH_PATH)
            .addPathSegment(TOKEN_PATH)
            .build();
    AuthenticationRequest req = createRequest(url);
    mockAPI.willReturnSuccessfulLogin();
    req.setRealm("users")
            .execute();

    final RecordedRequest request = mockAPI.takeRequest();
    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("realm", "users"));
}
项目:Auth0.Android    文件:BaseAuthenticationRequestTest.java   
@Test
public void shouldWhiteListOAuth2ParametersOnLegacyEndpoints() throws Exception {
    HashMap<String, Object> parameters = new HashMap<>();
    parameters.put("extra", "value");
    parameters.put("realm", "users");
    HttpUrl url = HttpUrl.parse(mockAPI.getDomain())
            .newBuilder()
            .addPathSegment(OAUTH_PATH)
            .addPathSegment(RESOURCE_OWNER_PATH)
            .build();
    AuthenticationRequest req = createRequest(url);
    mockAPI.willReturnSuccessfulLogin();
    req.addAuthenticationParameters(parameters)
            .execute();

    final RecordedRequest request = mockAPI.takeRequest();
    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("extra", "value"));
    assertThat(body, not(hasKey("realm")));
}
项目:Auth0.Android    文件:AuthenticationAPIClientTest.java   
@Test
public void shouldRevokeToken() throws Exception {
    Auth0 auth0 = new Auth0(CLIENT_ID, mockAPI.getDomain(), mockAPI.getDomain());
    AuthenticationAPIClient client = new AuthenticationAPIClient(auth0);

    mockAPI.willReturnSuccessfulEmptyBody();
    final MockAuthenticationCallback<Void> callback = new MockAuthenticationCallback<>();
    client.revokeToken("refreshToken")
            .start(callback);

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
    assertThat(request.getPath(), equalTo("/oauth/revoke"));

    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("client_id", CLIENT_ID));
    assertThat(body, hasEntry("token", "refreshToken"));

    assertThat(callback, hasNoError());
}
项目:Auth0.Android    文件:AuthenticationAPIClientTest.java   
@Test
public void shouldLoginWithUserAndPassword() throws Exception {
    mockAPI.willReturnSuccessfulLogin();

    final MockAuthenticationCallback<Credentials> callback = new MockAuthenticationCallback<>();

    client.login(SUPPORT_AUTH0_COM, "voidpassword", MY_CONNECTION)
            .start(callback);

    assertThat(callback, hasPayloadOfType(Credentials.class));

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("connection", MY_CONNECTION));
    assertThat(body, not(hasKey("realm")));
}
项目:Auth0.Android    文件:AuthenticationAPIClientTest.java   
@Test
public void shouldSendSMSLinkAndroidSync() throws Exception {
    mockAPI.willReturnSuccessfulPasswordlessStart();

    client.passwordlessWithSMS("+1123123123", PasswordlessType.ANDROID_LINK)
            .execute();

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
    assertThat(request.getPath(), equalTo("/passwordless/start"));

    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("client_id", CLIENT_ID));
    assertThat(body, hasEntry("phone_number", "+1123123123"));
    assertThat(body, hasEntry("send", "link_android"));
    assertThat(body, hasEntry("connection", "sms"));
}
项目:Auth0.Android    文件:UsersAPIClientTest.java   
@Test
public void shouldLinkAccount() throws Exception {
    mockAPI.willReturnSuccessfulLink();

    final MockManagementCallback<List<UserIdentity>> callback = new MockManagementCallback<>();
    client.link(USER_ID_PRIMARY, TOKEN_SECONDARY)
            .start(callback);

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getPath(), equalTo("/api/v2/users/" + USER_ID_PRIMARY + "/identities"));

    assertThat(request.getHeader(HEADER_AUTHORIZATION), equalTo(BEARER + TOKEN_PRIMARY));
    assertThat(request.getMethod(), equalTo(METHOD_POST));
    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry(KEY_LINK_WITH, TOKEN_SECONDARY));


    TypeToken<List<UserIdentity>> typeToken = new TypeToken<List<UserIdentity>>() {
    };
    assertThat(callback, hasPayloadOfType(typeToken));
    assertThat(callback.getPayload().size(), is(2));
}
项目:Auth0.Android    文件:AuthenticationAPIClientTest.java   
@Test
public void shouldLoginWithUserAndPasswordSyncUsingOAuthTokenEndpoint() throws Exception {
    mockAPI.willReturnSuccessfulLogin();

    final Credentials credentials = client
            .login(SUPPORT_AUTH0_COM, "some-password")
            .execute();
    assertThat(credentials, is(notNullValue()));

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getPath(), is("/oauth/token"));
    assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("client_id", CLIENT_ID));
    assertThat(body, hasEntry("grant_type", "password"));
    assertThat(body, hasEntry("username", SUPPORT_AUTH0_COM));
    assertThat(body, hasEntry("password", "some-password"));
    assertThat(body, not(hasKey("realm")));
    assertThat(body, not(hasKey("connection")));
    assertThat(body, not(hasKey("scope")));
    assertThat(body, not(hasKey("audience")));
}
项目:Auth0.Android    文件:AuthenticationAPIClientTest.java   
@Test
public void shouldFetchTokenInfo() throws Exception {
    mockAPI.willReturnTokenInfo();
    final MockAuthenticationCallback<UserProfile> callback = new MockAuthenticationCallback<>();

    client.tokenInfo("ID_TOKEN")
            .start(callback);

    assertThat(callback, hasPayloadOfType(UserProfile.class));

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
    assertThat(request.getPath(), equalTo("/tokeninfo"));

    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("id_token", "ID_TOKEN"));
}
项目:Auth0.Android    文件:AuthenticationAPIClientTest.java   
@Test
public void shouldFetchTokenInfoSync() throws Exception {
    mockAPI.willReturnTokenInfo();

    final UserProfile profile = client
            .tokenInfo("ID_TOKEN")
            .execute();

    assertThat(profile, is(notNullValue()));

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
    assertThat(request.getPath(), equalTo("/tokeninfo"));

    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("id_token", "ID_TOKEN"));
}
项目:Auth0.Android    文件:UsersAPIClientTest.java   
@Test
public void shouldUnlinkAccount() throws Exception {
    mockAPI.willReturnSuccessfulUnlink();

    final MockManagementCallback<List<UserIdentity>> callback = new MockManagementCallback<>();
    client.unlink(USER_ID_PRIMARY, USER_ID_SECONDARY, PROVIDER)
            .start(callback);

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getPath(), equalTo("/api/v2/users/" + USER_ID_PRIMARY + "/identities/" + PROVIDER + "/" + USER_ID_SECONDARY));

    assertThat(request.getHeader(HEADER_AUTHORIZATION), equalTo(BEARER + TOKEN_PRIMARY));
    assertThat(request.getMethod(), equalTo(METHOD_DELETE));
    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, is(nullValue()));


    TypeToken<List<UserIdentity>> typeToken = new TypeToken<List<UserIdentity>>() {
    };
    assertThat(callback, hasPayloadOfType(typeToken));
    assertThat(callback.getPayload().size(), is(1));
}
项目:Auth0.Android    文件:AuthenticationAPIClientTest.java   
@Test
public void shouldLoginWithOAuthAccessTokenSync() throws Exception {
    mockAPI.willReturnSuccessfulLogin();

    final Credentials credentials = client
            .loginWithOAuthAccessToken("fbtoken", "facebook")
            .execute();

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
    assertThat(request.getPath(), equalTo("/oauth/access_token"));

    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("connection", "facebook"));
    assertThat(body, hasEntry("access_token", "fbtoken"));
    assertThat(body, hasEntry("scope", OPENID));

    assertThat(credentials, is(notNullValue()));
}
项目:Auth0.Android    文件:AuthenticationAPIClientTest.java   
@Test
public void shouldLoginWithPhoneNumberWithCustomConnection() throws Exception {
    mockAPI.willReturnSuccessfulLogin();

    final MockAuthenticationCallback<Credentials> callback = new MockAuthenticationCallback<>();
    client.loginWithPhoneNumber("+10101010101", "1234", MY_CONNECTION)
            .start(callback);

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
    assertThat(request.getPath(), equalTo("/oauth/ro"));

    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("connection", MY_CONNECTION));
    assertThat(body, hasEntry("username", "+10101010101"));
    assertThat(body, hasEntry("password", "1234"));
    assertThat(body, hasEntry("scope", OPENID));

    assertThat(callback, hasPayloadOfType(Credentials.class));
}
项目:Auth0.Android    文件:AuthenticationAPIClientTest.java   
@Test
public void shouldLoginWithPhoneNumber() throws Exception {
    mockAPI.willReturnSuccessfulLogin();

    final MockAuthenticationCallback<Credentials> callback = new MockAuthenticationCallback<>();
    client.loginWithPhoneNumber("+10101010101", "1234")
            .start(callback);

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
    assertThat(request.getPath(), equalTo("/oauth/ro"));

    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("connection", "sms"));
    assertThat(body, hasEntry("username", "+10101010101"));
    assertThat(body, hasEntry("password", "1234"));
    assertThat(body, hasEntry("scope", OPENID));

    assertThat(callback, hasPayloadOfType(Credentials.class));
}
项目:Auth0.Android    文件:AuthenticationAPIClientTest.java   
@Test
public void shouldLoginWithPhoneNumberSync() throws Exception {
    mockAPI.willReturnSuccessfulLogin();

    final Credentials credentials = client
            .loginWithPhoneNumber("+10101010101", "1234")
            .execute();

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
    assertThat(request.getPath(), equalTo("/oauth/ro"));

    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("connection", "sms"));
    assertThat(body, hasEntry("username", "+10101010101"));
    assertThat(body, hasEntry("password", "1234"));
    assertThat(body, hasEntry("scope", OPENID));

    assertThat(credentials, is(notNullValue()));
}
项目:Auth0.Android    文件:AuthenticationAPIClientTest.java   
@Test
public void shouldLoginWithEmailOnly() throws Exception {
    mockAPI.willReturnSuccessfulLogin();

    final MockAuthenticationCallback<Credentials> callback = new MockAuthenticationCallback<>();
    client.loginWithEmail(SUPPORT_AUTH0_COM, "1234")
            .start(callback);

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
    assertThat(request.getPath(), equalTo("/oauth/ro"));

    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("connection", "email"));
    assertThat(body, hasEntry("username", SUPPORT_AUTH0_COM));
    assertThat(body, hasEntry("password", "1234"));
    assertThat(body, hasEntry("scope", OPENID));

    assertThat(callback, hasPayloadOfType(Credentials.class));
}
项目:Auth0.Android    文件:AuthenticationAPIClientTest.java   
@Test
public void shouldLoginWithEmailOnlySync() throws Exception {
    mockAPI
            .willReturnSuccessfulLogin()
            .willReturnTokenInfo();

    final Credentials credentials = client
            .loginWithEmail(SUPPORT_AUTH0_COM, "1234")
            .execute();

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
    assertThat(request.getPath(), equalTo("/oauth/ro"));

    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("connection", "email"));
    assertThat(body, hasEntry("username", SUPPORT_AUTH0_COM));
    assertThat(body, hasEntry("password", "1234"));
    assertThat(body, hasEntry("scope", OPENID));

    assertThat(credentials, is(notNullValue()));
}
项目:Auth0.Android    文件:AuthenticationAPIClientTest.java   
@Test
public void shouldCreateUser() throws Exception {
    mockAPI.willReturnSuccessfulSignUp();

    final MockAuthenticationCallback<DatabaseUser> callback = new MockAuthenticationCallback<>();
    client.createUser(SUPPORT_AUTH0_COM, PASSWORD, SUPPORT, MY_CONNECTION)
            .start(callback);

    final RecordedRequest request = mockAPI.takeRequest();
    assertThat(request.getHeader("Accept-Language"), is(getDefaultLocale()));
    assertThat(request.getPath(), equalTo("/dbconnections/signup"));

    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("email", SUPPORT_AUTH0_COM));
    assertThat(body, hasEntry("username", SUPPORT));
    assertThat(body, hasEntry("password", PASSWORD));
    assertThat(body, hasEntry("connection", MY_CONNECTION));

    assertThat(callback, hasPayloadOfType(DatabaseUser.class));
}