Java 类org.springframework.boot.test.web.client.TestRestTemplate 实例源码

项目:java-spring-web    文件:MVCJettyITest.java   
@BeforeClass
public static void beforeClass() throws Exception {
    jettyServer = new Server(0);

    WebAppContext webApp = new WebAppContext();
    webApp.setServer(jettyServer);
    webApp.setContextPath(CONTEXT_PATH);
    webApp.setWar("src/test/webapp");

    jettyServer.setHandler(webApp);
    jettyServer.start();
    serverPort = ((ServerConnector)jettyServer.getConnectors()[0]).getLocalPort();

    testRestTemplate = new TestRestTemplate(new RestTemplateBuilder()
            .rootUri("http://localhost:" + serverPort + CONTEXT_PATH));
}
项目:log-sink    文件:LogSinkAppIT.java   
@Test
public void testPushTaupageLog() throws Exception {
    final TestRestTemplate restOperations = new TestRestTemplate(CORRECT_USER, CORRECT_PASSWORD);

    stubFor(post(urlPathEqualTo("/api/instance-logs")).willReturn(aResponse().withStatus(201)));

    final URI url = URI.create("http://localhost:" + port + "/instance-logs");
    final ResponseEntity<String> response = restOperations.exchange(
            RequestEntity.post(url).contentType(APPLICATION_JSON).body(
                    instanceLogsPayload), String.class);
    assertThat(response.getStatusCode()).isEqualTo(CREATED);

    log.debug("Waiting for async tasks to finish");
    TimeUnit.SECONDS.sleep(1);

    verify(postRequestedFor(urlPathEqualTo("/api/instance-logs"))
                   .withRequestBody(equalToJson(intanceLogsJsonPayload))
                   .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890")));

    verify(putRequestedFor(urlPathEqualTo("/events/" + eventID))
                   .withRequestBody(equalToJson(new String(auditTrailJsonPayload)))
                   .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890")));

    log.info("METRICS:\n{}",
             restOperations.getForObject("http://localhost:" + managementPort + "/metrics", String.class));
}
项目:demo-spring-boot-security-oauth2    文件:GrantByImplicitProviderTest.java   
@Test
public void getJwtTokenByImplicitGrant() throws JsonParseException, JsonMappingException, IOException {
    String redirectUrl = "http://localhost:"+port+"/resources/user";
    ResponseEntity<String> response = new TestRestTemplate("user","password").postForEntity("http://localhost:" + port 
       + "oauth/authorize?response_type=token&client_id=normal-app&redirect_uri={redirectUrl}", null, String.class,redirectUrl);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    List<String> setCookie = response.getHeaders().get("Set-Cookie");
    String jSessionIdCookie = setCookie.get(0);
    String cookieValue = jSessionIdCookie.split(";")[0];

    HttpHeaders headers = new HttpHeaders();
    headers.add("Cookie", cookieValue);
    response = new TestRestTemplate("user","password").postForEntity("http://localhost:" + port 
            + "oauth/authorize?response_type=token&client_id=normal-app&redirect_uri={redirectUrl}&user_oauth_approval=true&authorize=Authorize",
            new HttpEntity<>(headers), String.class, redirectUrl);
    assertEquals(HttpStatus.FOUND, response.getStatusCode());
    assertNull(response.getBody());
    String location = response.getHeaders().get("Location").get(0);

    //FIXME: Is this a bug with redirect URL?
    location = location.replace("#", "?");

    response = new TestRestTemplate().getForEntity(location, String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
}
项目:demo-spring-boot-security-oauth2    文件:GrantByResourceOwnerPasswordCredentialTest.java   
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void getJwtTokenByClientCredentialForUser() throws JsonParseException, JsonMappingException, IOException {
    ResponseEntity<String> response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=user&password=password", null, String.class);
    String responseText = response.getBody();
    assertEquals(HttpStatus.OK, response.getStatusCode());
    HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);

    assertEquals("bearer", jwtMap.get("token_type"));
    assertEquals("read write", jwtMap.get("scope"));
    assertTrue(jwtMap.containsKey("access_token"));
    assertTrue(jwtMap.containsKey("expires_in"));
    assertTrue(jwtMap.containsKey("jti"));
    String accessToken = (String) jwtMap.get("access_token");

    Jwt jwtToken = JwtHelper.decode(accessToken);
    String claims = jwtToken.getClaims();
    HashMap claimsMap = new ObjectMapper().readValue(claims, HashMap.class);
    assertEquals("spring-boot-application", ((List<String>) claimsMap.get("aud")).get(0));
    assertEquals("trusted-app", claimsMap.get("client_id"));
    assertEquals("user", claimsMap.get("user_name"));
    assertEquals("read", ((List<String>) claimsMap.get("scope")).get(0));
    assertEquals("write", ((List<String>) claimsMap.get("scope")).get(1));
    assertEquals("ROLE_USER", ((List<String>) claimsMap.get("authorities")).get(0));
}
项目:demo-spring-boot-security-oauth2    文件:GrantByResourceOwnerPasswordCredentialTest.java   
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void getJwtTokenByClientCredentialForAdmin() throws JsonParseException, JsonMappingException, IOException {
    ResponseEntity<String> response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=admin&password=password", null, String.class);
    String responseText = response.getBody();
    assertEquals(HttpStatus.OK, response.getStatusCode());
    HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);

    assertEquals("bearer", jwtMap.get("token_type"));
    assertEquals("read write", jwtMap.get("scope"));
    assertTrue(jwtMap.containsKey("access_token"));
    assertTrue(jwtMap.containsKey("expires_in"));
    assertTrue(jwtMap.containsKey("jti"));
    String accessToken = (String) jwtMap.get("access_token");

    Jwt jwtToken = JwtHelper.decode(accessToken);
    String claims = jwtToken.getClaims();
    HashMap claimsMap = new ObjectMapper().readValue(claims, HashMap.class);
    assertEquals("spring-boot-application", ((List<String>) claimsMap.get("aud")).get(0));
    assertEquals("trusted-app", claimsMap.get("client_id"));
    assertEquals("admin", claimsMap.get("user_name"));
    assertEquals("read", ((List<String>) claimsMap.get("scope")).get(0));
    assertEquals("write", ((List<String>) claimsMap.get("scope")).get(1));
    assertEquals("ROLE_ADMIN", ((List<String>) claimsMap.get("authorities")).get(0));
}
项目:demo-spring-boot-security-oauth2    文件:GrantByResourceOwnerPasswordCredentialTest.java   
@Test
public void accessProtectedResourceByJwtTokenForUser() throws JsonParseException, JsonMappingException, IOException {
    ResponseEntity<String> response = new TestRestTemplate().getForEntity("http://localhost:" + port + "/resources/user", String.class);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());

    response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=user&password=password", null, String.class);
    String responseText = response.getBody();
    assertEquals(HttpStatus.OK, response.getStatusCode());
    HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);
    String accessToken = (String) jwtMap.get("access_token");

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Bearer " + accessToken);

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/user", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/principal", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals("user", response.getBody());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/roles", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals("[{\"authority\":\"ROLE_USER\"}]", response.getBody());
}
项目:demo-spring-boot-security-oauth2    文件:GrantByResourceOwnerPasswordCredentialTest.java   
@Test
public void accessProtectedResourceByJwtTokenForAdmin() throws JsonParseException, JsonMappingException, IOException {
    ResponseEntity<String> response = new TestRestTemplate().getForEntity("http://localhost:" + port + "/resources/admin", String.class);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());

    response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=admin&password=password", null, String.class);
    String responseText = response.getBody();
    assertEquals(HttpStatus.OK, response.getStatusCode());
    HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);
    String accessToken = (String) jwtMap.get("access_token");

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Bearer " + accessToken);

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/admin", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/principal", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals("admin", response.getBody());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/roles", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals("[{\"authority\":\"ROLE_ADMIN\"}]", response.getBody());
}
项目:didi-eureka-server    文件:ApplicationDashboardPathTests.java   
@Test
public void dashboardLoads() {
    ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
            "http://localhost:" + this.port + "/dashboard", String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
    String body = entity.getBody();
    // System.err.println(body);
    assertTrue(body.contains("eureka/js"));
    assertTrue(body.contains("eureka/css"));
    // The "DS Replicas"
    assertTrue(
            body.contains("<a href=\"http://localhost:8761/eureka/\">localhost</a>"));
    // The Home
    assertTrue(body.contains("<a href=\"/dashboard\">Home</a>"));
    // The Lastn
    assertTrue(body.contains("<a href=\"/dashboard/lastn\">Last"));
}
项目:pcf-metrics-trace-example-spring    文件:TraceTest.java   
@Test(timeout = 180000)
public void testTraces() throws Exception {
    waitForAppsToStart();

    String uri = "http://localhost:" + shoppingCart.port() + "/checkout";
    TestRestTemplate restTemplate = new TestRestTemplate();
    ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);

    assertEquals("{\"message\":\"order processed successfully\"}", response.getBody());

    Trace shoppingCartTrace = shoppingCart.getTrace();
    Trace ordersTrace = orders.getTrace();
    Trace paymentsTrace = payments.getTrace();

    assertThat(paymentsTrace.getTraceId()).isEqualTo(shoppingCartTrace.getTraceId());
    assertThat(ordersTrace.getTraceId()).isEqualTo(shoppingCartTrace.getTraceId());

    assertThat(paymentsTrace.getParentSpanId()).isEqualTo(ordersTrace.getSpanId());
    assertThat(ordersTrace.getParentSpanId()).isEqualTo(shoppingCartTrace.getSpanId());

    assertThat(shoppingCartTrace.getSpanId()).isNotEqualTo(ordersTrace.getSpanId());
    assertThat(ordersTrace.getSpanId()).isNotEqualTo(paymentsTrace.getSpanId());
}
项目:metagraph-auth    文件:PasswordTest.java   
@Test
public void testPassword() throws IOException {
    String tokenUrl = authUrlPrefix + "/oauth/token?client_id=" + clientId + "&client_secret=" + clientSecret + "&grant_type=password&username=" + username + "&password=" + password;
    HttpHeaders headers1 = null;
    //headers1   =    AuthorizationUtil.basic("admin","admin");
    ResponseEntity<String> response = new TestRestTemplate().postForEntity(tokenUrl, null, String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    HashMap map = new ObjectMapper().readValue(response.getBody(), HashMap.class);
    String accessToken = (String) map.get("access_token");
    String refreshToken = (String) map.get("refresh_token");
    System.out.println("Token Info:" + map.toString());

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Bearer " + accessToken);
    response = new TestRestTemplate().exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertEquals("secure", new ObjectMapper().readValue(response.getBody(), HashMap.class).get("content"));

    refreshToken(refreshToken);


}
项目:metagraph-auth    文件:ImplicitTest.java   
@Test
public void testImplicit() throws IOException {
    unauthorizedRequest();

    String authUrl = authBasicUrlPrefix + "/oauth/authorize?response_type=token&client_id=" + clientId + "&redirect_uri=" + resourceUrl;
    HttpHeaders headers1 = null;
    headers1 = AuthorizationUtil.basic("admin", "admin");
    ResponseEntity<String> response = new TestRestTemplate().postForEntity(authUrl, new HttpEntity<>(headers1), null, String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());

    String cookieValue = response.getHeaders().get("Set-Cookie").get(0).split(";")[0];
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cookie", cookieValue);
    authUrl = authUrlPrefix + "/oauth/authorize?user_oauth_approval=true&scope.read=true";
    response = new TestRestTemplate().postForEntity(authUrl, new HttpEntity<>(headers), String.class);
    assertEquals(HttpStatus.FOUND, response.getStatusCode());

    String location = response.getHeaders().get("Location").get(0).replace("#", "?");
    System.out.println("Token Info For Location:" + location);

    response = new TestRestTemplate().getForEntity(location, String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertEquals("secure", new ObjectMapper().readValue(response.getBody(), HashMap.class).get("content"));
}
项目:log-sink    文件:LogSinkAppIT.java   
@Test
public void testPushTaupageLogWithRetry() throws Exception {
    final TestRestTemplate restOperations = new TestRestTemplate(CORRECT_USER, CORRECT_PASSWORD);

    stubFor(post(urlPathEqualTo("/api/instance-logs")).willReturn(aResponse().withStatus(201).withFixedDelay(100)));
    stubFor(put(urlEqualTo("/events/" + eventID)).willReturn(aResponse().withStatus(429).withFixedDelay(100)));

    final URI url = URI.create("http://localhost:" + port + "/instance-logs");
    final ResponseEntity<String> response = restOperations.exchange(
            RequestEntity.post(url).contentType(APPLICATION_JSON).body(
                    instanceLogsPayload), String.class);
    assertThat(response.getStatusCode()).isEqualTo(CREATED);

    log.debug("Waiting for async tasks to finish");
    TimeUnit.MILLISECONDS.sleep(7500);

    verify(postRequestedFor(urlPathEqualTo("/api/instance-logs"))
                   .withRequestBody(equalToJson(intanceLogsJsonPayload))
                   .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890")));

    verify(3, putRequestedFor(urlPathEqualTo("/events/" + eventID))
            .withRequestBody(equalToJson(new String(auditTrailJsonPayload)))
            .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890")));
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:SampleActuatorApplicationTests.java   
@Test
public void testMetricsIsSecure() throws Exception {
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = new TestRestTemplate()
            .getForEntity("http://localhost:" + this.port + "/metrics", Map.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
    entity = new TestRestTemplate()
            .getForEntity("http://localhost:" + this.port + "/metrics/", Map.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
    entity = new TestRestTemplate().getForEntity(
            "http://localhost:" + this.port + "/metrics/foo", Map.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
    entity = new TestRestTemplate().getForEntity(
            "http://localhost:" + this.port + "/metrics.json", Map.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:SampleMethodSecurityApplicationTests.java   
@Test
public void testLogin() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.set("username", "admin");
    form.set("password", "admin");
    getCsrf(form, headers);
    ResponseEntity<String> entity = new TestRestTemplate().exchange(
            "http://localhost:" + this.port + "/login", HttpMethod.POST,
            new HttpEntity<MultiValueMap<String, String>>(form, headers),
            String.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND);
    assertThat(entity.getHeaders().getLocation().toString())
            .isEqualTo("http://localhost:" + this.port + "/");
}
项目:sw360rest    文件:AccessTokenPrinter.java   
private void printAccessToken(String authServerURL, String userId, String userPassword) throws IOException {
    String encodedPassword = null;
    try {
        encodedPassword = URLEncoder.encode(userPassword, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return;
    }

    String url = authServerURL + "/oauth/token?grant_type=password&username=" + userId + "&password=" + encodedPassword;

    ResponseEntity<String> responseEntity = new TestRestTemplate(
            "trusted-sw360-client",
            "sw360-secret")
            .postForEntity(url,
                    null,
                    String.class);

    String responseBody = responseEntity.getBody();
    JsonNode responseBodyJsonNode = new ObjectMapper().readTree(responseBody);
    assertThat(responseBodyJsonNode.has("access_token"), is(true));

    String accessToken = responseBodyJsonNode.get("access_token").asText();
    System.out.println("Authorization: Bearer " + accessToken);
}
项目:spring-boot-concourse    文件:SampleActuatorApplicationTests.java   
@Test
public void testMetricsIsSecure() throws Exception {
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = new TestRestTemplate()
            .getForEntity("http://localhost:" + this.port + "/metrics", Map.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
    entity = new TestRestTemplate()
            .getForEntity("http://localhost:" + this.port + "/metrics/", Map.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
    entity = new TestRestTemplate().getForEntity(
            "http://localhost:" + this.port + "/metrics/foo", Map.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
    entity = new TestRestTemplate().getForEntity(
            "http://localhost:" + this.port + "/metrics.json", Map.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:SampleWebSecureCustomApplicationTests.java   
@Test
public void testLogin() throws Exception {
    HttpHeaders headers = getHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.set("username", "user");
    form.set("password", "user");
    ResponseEntity<String> entity = new TestRestTemplate().exchange(
            "http://localhost:" + this.port + "/login", HttpMethod.POST,
            new HttpEntity<MultiValueMap<String, String>>(form, headers),
            String.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND);
    assertThat(entity.getHeaders().getLocation().toString())
            .endsWith(this.port + "/");
    assertThat(entity.getHeaders().get("Set-Cookie")).isNotNull();
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:SampleJetty92ApplicationTests.java   
@Test
public void testCompression() throws Exception {
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Accept-Encoding", "gzip");
    HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
    TestRestTemplate restTemplate = new TestRestTemplate();
    ResponseEntity<byte[]> entity = restTemplate.exchange(
            "http://localhost:" + this.port, HttpMethod.GET, requestEntity,
            byte[].class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
    GZIPInputStream inflater = new GZIPInputStream(
            new ByteArrayInputStream(entity.getBody()));
    try {
        assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8")))
                .isEqualTo("Hello World");
    }
    finally {
        inflater.close();
    }
}
项目:spring-security-oauth2-boot    文件:OAuth2AutoConfigurationTests.java   
private void verifyAuthentication(ClientDetails config, HttpStatus finalStatus) {
    String baseUrl = "http://localhost:" + this.context.getWebServer().getPort();
    TestRestTemplate rest = new TestRestTemplate();
    // First, verify the web endpoint can't be reached
    assertEndpointUnauthorized(baseUrl, rest);
    // Since we can't reach it, need to collect an authorization token
    HttpHeaders headers = getHeaders(config);
    String url = baseUrl + "/oauth/token";
    JsonNode tokenResponse = rest.postForObject(url,
            new HttpEntity<>(getBody(), headers), JsonNode.class);
    String authorizationToken = tokenResponse.findValue("access_token").asText();
    String tokenType = tokenResponse.findValue("token_type").asText();
    String scope = tokenResponse.findValues("scope").get(0).toString();
    assertThat(tokenType).isEqualTo("bearer");
    assertThat(scope).isEqualTo("\"read\"");
    // Now we should be able to see that endpoint.
    headers.set("Authorization", "BEARER " + authorizationToken);
    ResponseEntity<String> securedResponse = rest
            .exchange(new RequestEntity<Void>(headers, HttpMethod.GET,
                    URI.create(baseUrl + "/securedFind")), String.class);
    assertThat(securedResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(securedResponse.getBody()).isEqualTo(
            "You reached an endpoint " + "secured by Spring Security OAuth2");
    ResponseEntity<String> entity = rest.exchange(new RequestEntity<Void>(headers,
            HttpMethod.POST, URI.create(baseUrl + "/securedSave")), String.class);
    assertThat(entity.getStatusCode()).isEqualTo(finalStatus);
}
项目:syndesis    文件:BaseITCase.java   
@Autowired
public void setRestTemplate(TestRestTemplate testRestTemplate) {
    List<HttpMessageConverter<?>> messageConverters = testRestTemplate.getRestTemplate().getMessageConverters();
    messageConverters.add(0, new YamlJackson2HttpMessageConverter());
    messageConverters.add(0, new JsonJackson2HttpMessageConverter());
    messageConverters.add( 0, new ByteArrayHttpMessageConverter());
    this.restTemplate = testRestTemplate;
}
项目:nixmash-blog    文件:GitHubTests.java   
@Before
public void setUp() {
    gitHubRepoUrl = environment.getProperty("github.repo.url");
    gitHubUserUrl = environment.getProperty("github.user.url");
    restTemplate = new TestRestTemplate();
    githubCache = this.cacheManager.getCache("githubStats");
}
项目:demo-spring-boot-security-oauth2    文件:GrantByClientCredentialTest.java   
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void getJwtTokenByTrustedClient() throws JsonParseException, JsonMappingException, IOException {
    ResponseEntity<String> response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?client_id=trusted-app&grant_type=client_credentials", null, String.class);
    String responseText = response.getBody();
    assertEquals(HttpStatus.OK, response.getStatusCode());
    HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);

    assertEquals("bearer", jwtMap.get("token_type"));
    assertEquals("read write", jwtMap.get("scope"));
    assertTrue(jwtMap.containsKey("access_token"));
    assertTrue(jwtMap.containsKey("expires_in"));
    assertTrue(jwtMap.containsKey("jti"));
    String accessToken = (String) jwtMap.get("access_token");

    Jwt jwtToken = JwtHelper.decode(accessToken);

    String claims = jwtToken.getClaims();
    logJson(claims);

    HashMap claimsMap = new ObjectMapper().readValue(claims, HashMap.class);
    assertEquals("spring-boot-application", ((List<String>) claimsMap.get("aud")).get(0));
    assertEquals("trusted-app", claimsMap.get("client_id"));
    assertEquals("read", ((List<String>) claimsMap.get("scope")).get(0));
    assertEquals("write", ((List<String>) claimsMap.get("scope")).get(1));
    List<String> authorities = (List<String>) claimsMap.get("authorities");
    assertEquals(1, authorities.size());
    assertEquals("ROLE_TRUSTED_CLIENT", authorities.get(0));
}
项目:demo-spring-boot-security-oauth2    文件:GrantByClientCredentialTest.java   
@Test
public void accessProtectedResourceByJwtToken() throws JsonParseException, JsonMappingException, IOException, InvalidJwtException {
    ResponseEntity<String> response = new TestRestTemplate().getForEntity("http://localhost:" + port + "/resources/client", String.class);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());

    response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?client_id=trusted-app&grant_type=client_credentials", null, String.class);
    String responseText = response.getBody();
    assertEquals(HttpStatus.OK, response.getStatusCode());
    HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);
    String accessToken = (String) jwtMap.get("access_token");

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Bearer " + accessToken);

    JwtContext jwtContext = jwtConsumer.process(accessToken);
    logJWTClaims(jwtContext);

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/principal", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals("trusted-app", response.getBody());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/trusted_client", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/roles", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals("[{\"authority\":\"ROLE_TRUSTED_CLIENT\"}]", response.getBody());

}
项目:demo-spring-boot-security-oauth2    文件:OtherTest.java   
public static void main(String[] args) {
    try {
        String access_token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsic3ByaW5nLWJvb3QtYXBwbGljYXRpb24iXSwidXNlcl9uYW1lIjoiYXBwX2NsaWVudCIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdLCJleHAiOjE0OTA5NTI5NzcsImF1dGhvcml0aWVzIjpbIlJPTEVfVVNFUiJdLCJqdGkiOiJmOTA4Njk5Mi1mNTc5LTQzZmEtODBjYi00MmViOTEzMjJmMTkiLCJjbGllbnRfaWQiOiJub3JtYWwtYXBwIn0.dTXMB_yDMEQ5n5fS9VXKjvPDOMJQIFJwbpP7WQdw4WU";
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + access_token);
        ResponseEntity<String> response = new TestRestTemplate().exchange("http://localhost:" + 8080 + "/resources/roles", HttpMethod.GET,
                new HttpEntity<>(null, headers), String.class);
        System.out.println(response.getBody());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:lab1-git-race    文件:IntegrationTest.java   
/**
 * This test method checks whether the 'Home' page returns a correct response status and body or not.
 * 
 * @throws Exception if the body returned is not the expected or the connection fails.
 */
@Test
public void testHome() throws Exception {
    ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
            "http://localhost:" + this.port, String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
    assertTrue("Wrong body (title doesn't match):\n" + entity.getBody(), entity
            .getBody().contains("<title>Hello"));
}
项目:lab1-git-race    文件:IntegrationTest.java   
/**
 * This test method checks whether the website's CSS returns a correct response status and body or not,
 * and also if the sheet returned is the expected.
 * 
 * @throws Exception if the connection fails, the body is not valid or the sheet is other than specified.
 */
@Test
public void testCss() throws Exception {
    ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
            "http://localhost:" + this.port
                    + "/webjars/bootstrap/3.3.5/css/bootstrap.min.css", String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
    assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("body"));
    assertEquals("Wrong content type:\n" + entity.getHeaders().getContentType(),
            MediaType.valueOf("text/css"), entity.getHeaders()
                    .getContentType());
}
项目:didi-eureka-server    文件:ApplicationContextTests.java   
@Test
public void catalogLoads() {
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = new TestRestTemplate().getForEntity(
            "http://localhost:" + this.port + "/context/eureka/apps", Map.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
}
项目:didi-eureka-server    文件:ApplicationContextTests.java   
@Test
public void dashboardLoads() {
    ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
            "http://localhost:" + this.port + "/context/", String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
    String body = entity.getBody();
    // System.err.println(body);
    assertTrue(body.contains("eureka/js"));
    assertTrue(body.contains("eureka/css"));
    // The "DS Replicas"
    assertTrue(
            body.contains("<a href=\"http://localhost:8761/eureka/\">localhost</a>"));
}
项目:didi-eureka-server    文件:ApplicationContextTests.java   
@Test
public void cssAvailable() {
    ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
            "http://localhost:" + this.port + "/context/eureka/css/wro.css",
            String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
}
项目:didi-eureka-server    文件:ApplicationContextTests.java   
@Test
public void jsAvailable() {
    ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
            "http://localhost:" + this.port + "/context/eureka/js/wro.js",
            String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
}
项目:didi-eureka-server    文件:ApplicationContextTests.java   
@Test
public void adminLoads() {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = new TestRestTemplate().exchange(
            "http://localhost:" + this.port + "/context/env", HttpMethod.GET,
            new HttpEntity<>("parameters", headers), Map.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
}
项目:didi-eureka-server    文件:ApplicationDashboardDisabledTests.java   
@Test
public void catalogLoads() {
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = new TestRestTemplate().getForEntity(
            "http://localhost:" + this.port + "/eureka/apps", Map.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
}
项目:didi-eureka-server    文件:ApplicationServletPathTests.java   
@Test
public void catalogLoads() {
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = new TestRestTemplate().getForEntity(
            "http://localhost:" + this.port + "/eureka/apps", Map.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
}
项目:didi-eureka-server    文件:ApplicationServletPathTests.java   
@Test
public void dashboardLoads() {
    ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
            "http://localhost:" + this.port + "/servlet/", String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
    String body = entity.getBody();
    // System.err.println(body);
    assertTrue(body.contains("eureka/js"));
    assertTrue(body.contains("eureka/css"));
    // The "DS Replicas"
    assertTrue(
            body.contains("<a href=\"http://localhost:8761/eureka/\">localhost</a>"));
}
项目:didi-eureka-server    文件:ApplicationServletPathTests.java   
@Test
public void cssAvailable() {
    ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
            "http://localhost:" + this.port + "/servlet/eureka/css/wro.css",
            String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
}
项目:didi-eureka-server    文件:ApplicationServletPathTests.java   
@Test
public void jsAvailable() {
    ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
            "http://localhost:" + this.port + "/servlet/eureka/js/wro.js",
            String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
}
项目:didi-eureka-server    文件:ApplicationServletPathTests.java   
@Test
public void adminLoads() {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = new TestRestTemplate().exchange(
            "http://localhost:" + this.port + "/servlet/env", HttpMethod.GET,
            new HttpEntity<>("parameters", headers), Map.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
}
项目:didi-eureka-server    文件:ApplicationTests.java   
@Test
public void catalogLoads() {
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = new TestRestTemplate().getForEntity(
            "http://localhost:" + this.port + "/eureka/apps", Map.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
}
项目:didi-eureka-server    文件:ApplicationTests.java   
@Test
public void adminLoads() {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = new TestRestTemplate().exchange(
            "http://localhost:" + this.port + "/env", HttpMethod.GET,
            new HttpEntity<>("parameters", headers), Map.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
}
项目:didi-eureka-server    文件:ApplicationTests.java   
@Test
public void noDoubleSlashes() {
    String basePath = "http://localhost:" + this.port + "/";
    ResponseEntity<String> entity = new TestRestTemplate().getForEntity(basePath,
            String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
    String body = entity.getBody();
    assertNotNull(body);
    assertFalse("basePath contains double slashes", body.contains(basePath + "/"));
}