@Test public void testList() throws Exception { //创建书架创建的请求 //请求方式为post MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.post("/store/list.do"); //有些参数我注释掉了,你可以自行添加相关参数,得到不同的测试结果 //status为0的记录 //mockHttpServletRequestBuilder.param("status", "0"); //书架编号为dd的记录 //mockHttpServletRequestBuilder.param("number", "dd"); //第一页 mockHttpServletRequestBuilder.param("page", "1"); //每页10条记录 mockHttpServletRequestBuilder.param("rows", "10"); mockMvc.perform(mockHttpServletRequestBuilder).andExpect(status().isOk()) .andDo(print()); //控制台会打印如下结果: //MockHttpServletResponse: //Status = 200 即为后端成功相应 //返回数据 }
@Test @WithMockUser("user123") public void testSocialConnections() throws Exception { LinkedMultiValueMap<String, Connection<?>> connections = new LinkedMultiValueMap<>(); connections.add(connection.getKey().getProviderId(), connection); when(connectionRepository.findAllConnections()).thenReturn(connections); MockHttpServletRequestBuilder request = get("/api/profile/socials") .contentType(MediaType.APPLICATION_JSON); MockHttpServletResponse response = mockMvc.perform(request) .andDo(document("user-profile-socials-list")) .andReturn() .getResponse(); assertThat(response.getStatus()).isEqualTo(200); JsonNode jsonResponse = objectMapper.readTree(response.getContentAsByteArray()); assertThat(jsonResponse.isObject()).isTrue(); assertThat(jsonResponse.has(PROVIDER_ID)).isTrue(); assertThat(jsonResponse.get(PROVIDER_ID).isObject()).isTrue(); assertThat(jsonResponse.get(PROVIDER_ID).get("imageUrl").textValue()).isEqualTo(connection.getImageUrl()); verify(connectionRepository).findAllConnections(); }
@Test @WithMockUser("user123") public void testFindProfileActiveSessions() throws Exception { final UserEntity user = new UserEntity().setUsername("user123"); when(sessionRegistry.getAllPrincipals()).thenReturn(Collections.singletonList(user)); final SessionInformation sessionInformation = new SessionInformation("1", "1", new Date()); when(sessionRegistry.getAllSessions(user, true)) .thenReturn(Collections.singletonList(sessionInformation)); MockHttpServletRequestBuilder request = get("/api/profile/sessions") .contentType(MediaType.APPLICATION_JSON); MockHttpServletResponse response = mockMvc.perform(request) .andDo(document("user-profile-sessions-list")) .andReturn() .getResponse(); assertThat(response.getStatus()).isEqualTo(200); List<SessionInformation> expectedValue = Collections .singletonList(new SessionInformation("user123", "1", sessionInformation.getLastRequest())); assertThat(response.getContentAsByteArray()).isEqualTo(objectMapper.writeValueAsBytes(expectedValue)); verify(sessionRegistry).getAllPrincipals(); verify(sessionRegistry).getAllSessions(user, true); }
@Test public void should_response_4xx_if_flow_name_format_invalid() throws Throwable { String flowName = "hello*gmail"; MockHttpServletRequestBuilder request = get("/flows/" + flowName + "/exist") .contentType(MediaType.APPLICATION_JSON); MvcResult result = this.mockMvc.perform(request) .andExpect(status().is4xxClientError()) .andReturn(); String body = result.getResponse().getContentAsString(); ResponseError error = ResponseError.parse(body, ResponseError.class); Assert.assertNotNull(error); Assert.assertEquals(error.getMessage(), "Illegal node name: hello*gmail"); }
@Test public void createDuplicatedTopic() throws Exception { // Given Topic spring = new Topic("spring"); topicRepository.save(spring); TopicDto topicDto = TopicDto.of(spring.getName()); MockHttpServletRequestBuilder request = post("/api/topic/create") .contentType(MediaType.APPLICATION_JSON_UTF8) .content(objectMapper.writeValueAsString(topicDto)); // When & Then mvc.perform(request) .andDo(print()) .andDo(document("create-topic-duplicated")) .andExpect(status().isConflict()) ; }
@Test @WithMockUser("user123") public void testFindClientById() throws Exception { final OAuth2ClientEntity client = new OAuth2ClientEntity() .setId("client123") .setName("client") .setDescription("description") .setClientSecret("123456secret") .setSecretRequired(true) .setAutoApprove(false) .setAuthorizedGrantTypes(new HashSet<>(Arrays.asList(AUTHORIZATION_CODE, IMPLICIT))); when(oAuth2ClientService.findClientById("client123")).thenReturn(client); MockHttpServletRequestBuilder request = get("/api/clients/client123") .contentType(MediaType.APPLICATION_JSON); MockHttpServletResponse response = mockMvc.perform(request) .andExpect(status().isOk()) .andDo(document("client-read")) .andReturn() .getResponse(); assertThat(response.getContentAsByteArray()) .isEqualTo(objectMapper.writeValueAsBytes(OAuth2ClientRestData.builder() .fromOAuth2ClientEntity(client).build())); verify(oAuth2ClientService).findClientById("client123"); }
@Test @WithMockUser("user123") public void testFindClients() throws Exception { final OAuth2ClientEntity client = new OAuth2ClientEntity() .setId("client123") .setName("client") .setDescription("description") .setClientSecret("123456secret") .setSecretRequired(true) .setAutoApprove(false) .setAuthorizedGrantTypes(new HashSet<>(Arrays.asList(AUTHORIZATION_CODE, IMPLICIT))); Page<OAuth2ClientEntity> clients = new PageImpl<>(Arrays.asList(client)); when(oAuth2ClientService.findClients(anyString(), any())).thenReturn(clients); MockHttpServletRequestBuilder request = get("/api/clients") .contentType(MediaType.APPLICATION_JSON); MockHttpServletResponse response = mockMvc.perform(request) .andExpect(status().isOk()) .andDo(document("client-read-all")) .andReturn() .getResponse(); assertThat(response.getContentAsByteArray()) .isEqualTo(objectMapper.writeValueAsBytes( clients.map(c -> OAuth2ClientRestData.builder().fromOAuth2ClientEntity(c).build()))); verify(oAuth2ClientService).findClients(anyString(), any()); }
@Test @WithMockUser("user123") public void testGenerateClientSecret() throws Exception { final OAuth2ClientEntity client = new OAuth2ClientEntity() .setId("client123"); when(oAuth2ClientService.generateSecret(eq("client123"))).thenReturn(client); MockHttpServletRequestBuilder request = put("/api/clients/client123/generate-secret") .contentType(MediaType.APPLICATION_JSON); MockHttpServletResponse response = mockMvc.perform(request) .andExpect(status().isOk()) .andDo(document("client-generate-secret")) .andReturn() .getResponse(); assertThat(response.getContentAsByteArray()) .isEqualTo(objectMapper.writeValueAsBytes(OAuth2ClientRestData.builder() .fromOAuth2ClientEntity(client).build())); verify(oAuth2ClientService).generateSecret(eq("client123")); }
@Test @WithMockUser("user123") public void testSaveClient() throws Exception { final OAuth2ClientEntity client = new OAuth2ClientEntity() .setId("client123") .setName("client") .setDescription("description") .setSecretRequired(true) .setAutoApprove(false) .setAuthorizedGrantTypes(new HashSet<>(Arrays.asList(AUTHORIZATION_CODE, IMPLICIT))); when(oAuth2ClientService.saveClient(any())).thenReturn(client); MockHttpServletRequestBuilder request = post("/api/clients") .content("{\"name\": \"client\", \"description\": \"description\", " + "\"isSecretRequired\": true, \"isAutoApprove\": false, " + "\"authorizedGrantTypes\": [\"AUTHORIZATION_CODE\",\"IMPLICIT\"]}") .contentType(MediaType.APPLICATION_JSON); MockHttpServletResponse response = mockMvc.perform(request) .andExpect(status().isOk()) .andDo(document("client-create")) .andReturn() .getResponse(); assertThat(response.getContentAsByteArray()) .isEqualTo(objectMapper.writeValueAsBytes(OAuth2ClientRestData.builder() .fromOAuth2ClientEntity(client).build())); verify(oAuth2ClientService).saveClient(any()); }
@Test @WithMockUser("user123") public void testUpdateClient() throws Exception { final OAuth2ClientEntity client = new OAuth2ClientEntity() .setId("client123"); when(oAuth2ClientService.updateClient(eq("client123"), any())).thenReturn(client); MockHttpServletRequestBuilder request = put("/api/clients/client123") .content("{\"name\": \"client\", \"description\": \"description\", \"clientSecret\": \"s3cret\", " + "\"isSecretRequired\": true, \"isAutoApprove\": false, " + "\"authorizedGrantTypes\": [\"AUTHORIZATION_CODE\",\"IMPLICIT\"]}") .contentType(MediaType.APPLICATION_JSON); MockHttpServletResponse response = mockMvc.perform(request) .andExpect(status().isOk()) .andDo(document("client-update")) .andReturn() .getResponse(); assertThat(response.getContentAsByteArray()) .isEqualTo(objectMapper.writeValueAsBytes(OAuth2ClientRestData.builder() .fromOAuth2ClientEntity(client).build())); verify(oAuth2ClientService).updateClient(eq("client123"), any()); }
protected MockHttpServletRequestBuilder createRequestBuilderWithMethodAndUri(Pact.InteractionRequest request) throws Exception { String uri = request.getUri().contains(getServletContextPathWithoutTrailingSlash()) ? StringUtils.substringAfter(request.getUri(), getServletContextPathWithoutTrailingSlash()) : request.getUri(); uri = UriUtils.decode(uri, "UTF-8"); switch (request.getMethod()) { case GET: return get(uri); case POST: return post(uri); case PUT: return put(uri); case DELETE: return delete(uri); default: throw new RuntimeException("Unsupported method " + request.getMethod()); } }
public static MvcResult getHttpResultContent(MockMvc mockMvc, String uri, Method method, Map<String, String> keyvals) throws Exception { MockHttpServletRequestBuilder builder = null; switch (method) { case GET: builder = MockMvcRequestBuilders.get(uri); break; case POST: builder = MockMvcRequestBuilders.post(uri); break; case PUT: builder = MockMvcRequestBuilders.put(uri); break; case DELETE: builder = MockMvcRequestBuilders.delete(uri); break; default: builder = MockMvcRequestBuilders.get(uri); } for (Map.Entry<String, String> entry : keyvals.entrySet()) { builder = builder.param(entry.getKey(), entry.getValue()); } MvcResult result = mockMvc.perform(builder.accept(MediaType.ALL)).andReturn(); // result.getResponse().getHeaderNames(); return result; }
@Test public void testGetUser() throws Exception { final MockHttpServletRequestBuilder getRequest = get(UserController.REQUEST_PATH_API_USERS + "/590f86d92449343841cc2c3f") .accept(MediaType.APPLICATION_JSON); final MvcResult mvcResult = mockMvc .perform(getRequest) .andExpect(MockMvcResultMatchers.request().asyncStarted()) .andReturn(); mockMvc .perform(asyncDispatch(mvcResult)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.lastName").value("One")); }
@Test public void authCode_minimumParams_isSuccess() throws Exception { AuthorizationCode authorizationCode = new AuthorizationCode(); given(this.clientRepository.findById(any(ClientID.class))).willReturn(authCodeClient()); given(this.authorizationCodeService.create(any(AuthorizationCodeContext.class))).willReturn(authorizationCode); given(this.subjectResolver.resolveSubject(any(HttpServletRequest.class))).willReturn(new Subject("user")); given(this.scopeResolver.resolve(any(Subject.class), any(Scope.class), any(OIDCClientMetadata.class))) .will(returnsSecondArg()); MockHttpServletRequestBuilder request = get( "/oauth2/authorize?scope=openid&response_type=code&client_id=test-client&redirect_uri=http://example.com") .session(this.session); this.mvc.perform(request).andExpect(status().isFound()) .andExpect(redirectedUrlTemplate("http://example.com?code={code}", authorizationCode.getValue())); }
@Test public void authCode_withState_isSuccess() throws Exception { AuthorizationCode authorizationCode = new AuthorizationCode(); State state = new State(); given(this.clientRepository.findById(any(ClientID.class))).willReturn(authCodeClient()); given(this.authorizationCodeService.create(any(AuthorizationCodeContext.class))).willReturn(authorizationCode); given(this.subjectResolver.resolveSubject(any(HttpServletRequest.class))).willReturn(new Subject("user")); given(this.scopeResolver.resolve(any(Subject.class), any(Scope.class), any(OIDCClientMetadata.class))) .will(returnsSecondArg()); MockHttpServletRequestBuilder request = get( "/oauth2/authorize?scope=openid&response_type=code&client_id=test-client&redirect_uri=http://example.com&state=" + state.getValue()).session(this.session); this.mvc.perform(request).andExpect(status().isFound()).andExpect(redirectedUrlTemplate( "http://example.com?code={code}&state={state}", authorizationCode.getValue(), state.getValue())); }
@Test public void create() throws Exception { // Given String topic = "spring"; TopicDto topicDto = TopicDto.of(topic); MockHttpServletRequestBuilder request = post("/api/topic/create") .contentType(MediaType.APPLICATION_JSON_UTF8) .content(objectMapper.writeValueAsString(topicDto)); // When & Then mvc.perform(request) .andDo(print()) .andDo(document("create-topic")) .andExpect(jsonPath("$.id").isNotEmpty()) .andExpect(jsonPath("$.name", Matchers.is(topic))) ; }
@Test public void authCode_withPromptNoneAndAuthentication_isSuccess() throws Exception { AuthorizationCode authorizationCode = new AuthorizationCode(); given(this.clientRepository.findById(any(ClientID.class))).willReturn(authCodeClient()); given(this.authorizationCodeService.create(any(AuthorizationCodeContext.class))).willReturn(authorizationCode); given(this.subjectResolver.resolveSubject(any(HttpServletRequest.class))).willReturn(new Subject("user")); given(this.scopeResolver.resolve(any(Subject.class), any(Scope.class), any(OIDCClientMetadata.class))) .will(returnsSecondArg()); MockHttpServletRequestBuilder request = get( "/oauth2/authorize?scope=openid&response_type=code&client_id=test-client&redirect_uri=http://example.com&prompt=none") .session(this.session); this.mvc.perform(request).andExpect(status().isFound()) .andExpect(redirectedUrlTemplate("http://example.com?code={code}", authorizationCode.getValue())); }
@Test public void authCode_withValidMaxAge_isSuccess() throws Exception { AuthorizationCode authorizationCode = new AuthorizationCode(); given(this.clientRepository.findById(any(ClientID.class))).willReturn(authCodeClient()); given(this.authorizationCodeService.create(any(AuthorizationCodeContext.class))).willReturn(authorizationCode); given(this.subjectResolver.resolveSubject(any(HttpServletRequest.class))).willReturn(new Subject("user")); given(this.scopeResolver.resolve(any(Subject.class), any(Scope.class), any(OIDCClientMetadata.class))) .will(returnsSecondArg()); MockHttpServletRequestBuilder request = get( "/oauth2/authorize?scope=openid&response_type=code&client_id=test-client&redirect_uri=http://example.com&max_age=60") .session(this.session); this.mvc.perform(request).andExpect(status().isFound()) .andExpect(redirectedUrlTemplate("http://example.com?code={code}", authorizationCode.getValue())); }
@Test public void implicitWithIdTokenAndToken_minimumParams_isSuccess() throws Exception { BearerAccessToken accessToken = new BearerAccessToken(); JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build()); given(this.clientRepository.findById(any(ClientID.class))).willReturn(implicitWithIdTokenAndTokenClient()); given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken); given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken); given(this.subjectResolver.resolveSubject(any(HttpServletRequest.class))).willReturn(new Subject("user")); given(this.scopeResolver.resolve(any(Subject.class), any(Scope.class), any(OIDCClientMetadata.class))) .will(returnsSecondArg()); MockHttpServletRequestBuilder request = get( "/oauth2/authorize?scope=openid&response_type=id_token token&client_id=test-client&redirect_uri=http://example.com&nonce=test") .session(this.session); this.mvc.perform(request).andExpect(status().isFound()) .andExpect(redirectedUrlTemplate( "http://example.com#access_token={accessToken}&id_token={idToken}&token_type=Bearer", accessToken.getValue(), idToken.serialize())); }
@Test public void implicitWithIdToken_minimumParams_isSuccess() throws Exception { JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build()); given(this.clientRepository.findById(any(ClientID.class))).willReturn(implicitWithIdTokenClient()); given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken); given(this.subjectResolver.resolveSubject(any(HttpServletRequest.class))).willReturn(new Subject("user")); given(this.scopeResolver.resolve(any(Subject.class), any(Scope.class), any(OIDCClientMetadata.class))) .will(returnsSecondArg()); MockHttpServletRequestBuilder request = get( "/oauth2/authorize?scope=openid&response_type=id_token&client_id=test-client&redirect_uri=http://example.com&nonce=test") .session(this.session); this.mvc.perform(request).andExpect(status().isFound()) .andExpect(redirectedUrlTemplate("http://example.com#id_token={idToken}", idToken.serialize())); }
@Test public void hybridWithIdTokenAndToken_minimumParams_isSuccess() throws Exception { BearerAccessToken accessToken = new BearerAccessToken(); JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build()); AuthorizationCode authorizationCode = new AuthorizationCode(); given(this.clientRepository.findById(any(ClientID.class))).willReturn(hybridWithIdTokenAndTokenClient()); given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken); given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken); given(this.authorizationCodeService.create(any(AuthorizationCodeContext.class))).willReturn(authorizationCode); given(this.subjectResolver.resolveSubject(any(HttpServletRequest.class))).willReturn(new Subject("user")); given(this.scopeResolver.resolve(any(Subject.class), any(Scope.class), any(OIDCClientMetadata.class))) .will(returnsSecondArg()); MockHttpServletRequestBuilder request = get( "/oauth2/authorize?scope=openid&response_type=code id_token token&client_id=test-client&redirect_uri=http://example.com&nonce=test") .session(this.session); this.mvc.perform(request).andExpect(status().isFound()).andExpect(redirectedUrlTemplate( "http://example.com#access_token={accessToken}&code={code}&id_token={idToken}&token_type=Bearer", accessToken.getValue(), authorizationCode.getValue(), idToken.serialize())); }
@Test public void hybridWithToken_minimumParams_isSuccess() throws Exception { BearerAccessToken accessToken = new BearerAccessToken(); AuthorizationCode authorizationCode = new AuthorizationCode(); given(this.clientRepository.findById(any(ClientID.class))).willReturn(hybridWithTokenClient()); given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken); given(this.authorizationCodeService.create(any(AuthorizationCodeContext.class))).willReturn(authorizationCode); given(this.subjectResolver.resolveSubject(any(HttpServletRequest.class))).willReturn(new Subject("user")); given(this.scopeResolver.resolve(any(Subject.class), any(Scope.class), any(OIDCClientMetadata.class))) .will(returnsSecondArg()); MockHttpServletRequestBuilder request = get( "/oauth2/authorize?scope=openid&response_type=code token&client_id=test-client&redirect_uri=http://example.com&nonce=test") .session(this.session); this.mvc.perform(request).andExpect(status().isFound()) .andExpect(redirectedUrlTemplate( "http://example.com#access_token={accessToken}&code={code}&token_type=Bearer", accessToken.getValue(), authorizationCode.getValue())); }
@Test public void hybridWithIdTokenAndToken_withState_isSuccess() throws Exception { BearerAccessToken accessToken = new BearerAccessToken(); JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build()); AuthorizationCode authorizationCode = new AuthorizationCode(); State state = new State(); given(this.clientRepository.findById(any(ClientID.class))).willReturn(hybridWithIdTokenAndTokenClient()); given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken); given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken); given(this.authorizationCodeService.create(any(AuthorizationCodeContext.class))).willReturn(authorizationCode); given(this.subjectResolver.resolveSubject(any(HttpServletRequest.class))).willReturn(new Subject("user")); given(this.scopeResolver.resolve(any(Subject.class), any(Scope.class), any(OIDCClientMetadata.class))) .will(returnsSecondArg()); MockHttpServletRequestBuilder request = get( "/oauth2/authorize?scope=openid&response_type=code id_token token&client_id=test-client&redirect_uri=http://example.com&nonce=test&state=" + state.getValue()).session(this.session); this.mvc.perform(request).andExpect(status().isFound()).andExpect(redirectedUrlTemplate( "http://example.com#access_token={accessToken}&code={code}&id_token={idToken}&state={state}&token_type=Bearer", accessToken.getValue(), authorizationCode.getValue(), idToken.serialize(), state.getValue())); }
@Test public void authCode_postAuth_isOk() throws Exception { ClientID clientId = new ClientID("test-client"); URI redirectUri = URI.create("http://rp.example.com"); AuthorizationCode authorizationCode = new AuthorizationCode(); ClientSecretPost clientAuth = new ClientSecretPost(clientId, new Secret("test-secret")); TokenRequest tokenRequest = new TokenRequest(URI.create("http://op.example.com"), clientAuth, new AuthorizationCodeGrant(authorizationCode, redirectUri)); AuthorizationCodeContext context = new AuthorizationCodeContext(new Subject("user"), clientId, redirectUri, new Scope(OIDCScopeValue.OPENID), Instant.now(), new ACR("1"), AMR.PWD, new SessionID("test"), null, null, null); BearerAccessToken accessToken = new BearerAccessToken(); JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build()); given(this.clientRepository.findById(any(ClientID.class))) .willReturn(client(ClientAuthenticationMethod.CLIENT_SECRET_POST)); given(this.authorizationCodeService.consume(eq(authorizationCode))).willReturn(context); given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken); given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken); MockHttpServletRequestBuilder request = post("/oauth2/token").content(tokenRequest.toHTTPRequest().getQuery()) .contentType(MediaType.APPLICATION_FORM_URLENCODED); this.mvc.perform(request).andExpect(status().isOk()); }
@Test public void authCode_pkcePlain_isOk() throws Exception { ClientID clientId = new ClientID("test-client"); URI redirectUri = URI.create("http://rp.example.com"); CodeVerifier codeVerifier = new CodeVerifier(); CodeChallengeMethod codeChallengeMethod = CodeChallengeMethod.PLAIN; AuthorizationCode authorizationCode = new AuthorizationCode(); TokenRequest tokenRequest = new TokenRequest(URI.create("http://op.example.com"), clientId, new AuthorizationCodeGrant(authorizationCode, redirectUri, codeVerifier)); AuthorizationCodeContext context = new AuthorizationCodeContext(new Subject("user"), clientId, redirectUri, new Scope(OIDCScopeValue.OPENID), Instant.now(), new ACR("1"), AMR.PWD, new SessionID("test"), CodeChallenge.compute(codeChallengeMethod, codeVerifier), codeChallengeMethod, null); BearerAccessToken accessToken = new BearerAccessToken(); JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build()); given(this.clientRepository.findById(any(ClientID.class))).willReturn(client(ClientAuthenticationMethod.NONE)); given(this.authorizationCodeService.consume(eq(authorizationCode))).willReturn(context); given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken); given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken); MockHttpServletRequestBuilder request = post("/oauth2/token").content(tokenRequest.toHTTPRequest().getQuery()) .contentType(MediaType.APPLICATION_FORM_URLENCODED); this.mvc.perform(request).andExpect(status().isOk()); }
@Test public void authCode_pkceS256_isOk() throws Exception { ClientID clientId = new ClientID("test-client"); URI redirectUri = URI.create("http://rp.example.com"); CodeVerifier codeVerifier = new CodeVerifier(); CodeChallengeMethod codeChallengeMethod = CodeChallengeMethod.S256; AuthorizationCode authorizationCode = new AuthorizationCode(); TokenRequest tokenRequest = new TokenRequest(URI.create("http://op.example.com"), clientId, new AuthorizationCodeGrant(authorizationCode, URI.create("http://rp.example.com"), codeVerifier)); AuthorizationCodeContext context = new AuthorizationCodeContext(new Subject("user"), clientId, redirectUri, new Scope(OIDCScopeValue.OPENID), Instant.now(), new ACR("1"), AMR.PWD, new SessionID("test"), CodeChallenge.compute(codeChallengeMethod, codeVerifier), codeChallengeMethod, null); BearerAccessToken accessToken = new BearerAccessToken(); JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build()); given(this.clientRepository.findById(any(ClientID.class))).willReturn(client(ClientAuthenticationMethod.NONE)); given(this.authorizationCodeService.consume(eq(authorizationCode))).willReturn(context); given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken); given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken); MockHttpServletRequestBuilder request = post("/oauth2/token").content(tokenRequest.toHTTPRequest().getQuery()) .contentType(MediaType.APPLICATION_FORM_URLENCODED); this.mvc.perform(request).andExpect(status().isOk()); }
@Test public void resourceOwnerPasswordCredentials_basicAuth_isOk() throws Exception { ClientSecretBasic clientAuth = new ClientSecretBasic(new ClientID("test-client"), new Secret("test-secret")); TokenRequest tokenRequest = new TokenRequest(URI.create("http://op.example.com"), clientAuth, new ResourceOwnerPasswordCredentialsGrant("user", new Secret("password")), new Scope(OIDCScopeValue.OPENID)); BearerAccessToken accessToken = new BearerAccessToken(); given(this.clientRepository.findById(any(ClientID.class))) .willReturn(client(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)); given(this.authenticationHandler.authenticate(any(ResourceOwnerPasswordCredentialsGrant.class))) .willReturn(new Subject("user")); given(this.scopeResolver.resolve(any(Subject.class), any(Scope.class), any(OIDCClientMetadata.class))) .willAnswer(returnsSecondArg()); given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken); MockHttpServletRequestBuilder request = post("/oauth2/token").content(tokenRequest.toHTTPRequest().getQuery()) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .header("Authorization", clientAuth.toHTTPAuthorizationHeader()); this.mvc.perform(request).andExpect(status().isOk()); }
@Test public void shouldReturnGameLockerStatus() throws Exception { MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/api/status"); mockMvc.perform(requestBuilder) .andExpect(status().isOk()) .andExpect(jsonPath("$.latencySamples[0].latency").value(LATENCY)) .andExpect(jsonPath("$.errorCount").value(ERROR_COUNT)) .andExpect(jsonPath("$.successCount").value(SUCCESS_COUNT)) .andExpect(jsonPath("$.minLatencyInMillis").value(MIN_LATENCY_IN_MILLIS)) .andExpect(jsonPath("$.maxLatencyInMillis").value(MAX_LATENCY_IN_MILLIS)) .andExpect(jsonPath("$.shards['NA'].errorCount").value(ERROR_COUNT)) .andExpect(jsonPath("$.shards['NA'].successCount").value(SUCCESS_COUNT)) .andExpect(jsonPath("$.shards['NA'].errorCount").value(ERROR_COUNT)) .andExpect(jsonPath("$.shards['NA'].minLatencyInMillis").value(MIN_LATENCY_IN_MILLIS)) .andExpect(jsonPath("$.shards['NA'].maxLatencyInMillis").value(MAX_LATENCY_IN_MILLIS)) .andExpect(jsonPath("$.shards['NA'].meanLatencyInMillis").value(MEAN_LATENCY_IN_MILLIS)) .andExpect(jsonPath("$.shards['NA'].latencyStandardDeviationInMillis").value(STANDARD_DEVIATION_IN_MILLIS)); }
@Test public void clientCredentials_basicAuth_isOk() throws Exception { ClientSecretBasic clientAuth = new ClientSecretBasic(new ClientID("test-client"), new Secret("test-secret")); TokenRequest tokenRequest = new TokenRequest(URI.create("http://op.example.com"), clientAuth, new ClientCredentialsGrant(), new Scope("test")); BearerAccessToken accessToken = new BearerAccessToken(); given(this.clientRepository.findById(any(ClientID.class))) .willReturn(client(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)); given(this.scopeResolver.resolve(any(Subject.class), any(Scope.class), any(OIDCClientMetadata.class))) .willAnswer(returnsSecondArg()); given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken); MockHttpServletRequestBuilder request = post("/oauth2/token").content(tokenRequest.toHTTPRequest().getQuery()) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .header("Authorization", clientAuth.toHTTPAuthorizationHeader()); this.mvc.perform(request).andExpect(status().isOk()); }
@Test public void refreshToken_basicAuth_isOk() throws Exception { ClientID clientId = new ClientID("test-client"); ClientSecretBasic clientAuth = new ClientSecretBasic(clientId, new Secret("test-secret")); TokenRequest tokenRequest = new TokenRequest(URI.create("http://op.example.com"), clientAuth, new RefreshTokenGrant(new RefreshToken())); BearerAccessToken accessToken = new BearerAccessToken(); given(this.clientRepository.findById(any(ClientID.class))) .willReturn(client(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)); given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken); given(this.refreshTokenStore.load(any(RefreshToken.class))).willReturn(new RefreshTokenContext( new RefreshToken(), clientId, new Subject("user"), new Scope(OIDCScopeValue.OPENID), null)); MockHttpServletRequestBuilder request = post("/oauth2/token").content(tokenRequest.toHTTPRequest().getQuery()) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .header("Authorization", clientAuth.toHTTPAuthorizationHeader()); this.mvc.perform(request).andExpect(status().isOk()); }
@Test public void refreshToken_postAuth_isOk() throws Exception { ClientID clientId = new ClientID("test-client"); ClientSecretPost clientAuth = new ClientSecretPost(clientId, new Secret("test-secret")); TokenRequest tokenRequest = new TokenRequest(URI.create("http://op.example.com"), clientAuth, new RefreshTokenGrant(new RefreshToken())); BearerAccessToken accessToken = new BearerAccessToken(); given(this.clientRepository.findById(any(ClientID.class))) .willReturn(client(ClientAuthenticationMethod.CLIENT_SECRET_POST)); given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken); given(this.refreshTokenStore.load(any(RefreshToken.class))).willReturn(new RefreshTokenContext( new RefreshToken(), clientId, new Subject("user"), new Scope(OIDCScopeValue.OPENID), null)); MockHttpServletRequestBuilder request = post("/oauth2/token").content(tokenRequest.toHTTPRequest().getQuery()) .contentType(MediaType.APPLICATION_FORM_URLENCODED); this.mvc.perform(request).andExpect(status().isOk()); }
@Test public void should_response_false_if_flow_name_not_exist() throws Throwable { // given: String flowName = "not-exit"; // when: MockHttpServletRequestBuilder request = get("/flows/" + flowName + "/exist") .contentType(MediaType.APPLICATION_JSON); MvcResult mvcResult = this.mockMvc.perform(request) .andExpect(status().isOk()) .andReturn(); // then: String response = mvcResult.getResponse().getContentAsString(); BooleanValue existed = BooleanValue.parse(response, BooleanValue.class); Assert.assertNotNull(existed); Assert.assertEquals(false, existed.getValue()); }
@Test public void should_raise_exception_if_illegal_parameter_for_queue() throws Exception { // given: CmdInfo cmdBase = new CmdInfo("test-zone-1", "test-agent-1", CmdType.RUN_SHELL, "~/hello.sh"); Assert.assertNotNull(cmdBase.getStatus()); // when: request api of send cmd via queue with illegal priority MockHttpServletRequestBuilder content = post("/cmd/queue/send") .param("priority", "0") .param("retry", "0") .contentType(MediaType.APPLICATION_JSON) .content(cmdBase.toJson()); // then: return 400 for illegal priority range this.mockMvc.perform(content).andExpect(status().isBadRequest()); // when: request api of send cmd via queue with illegal retry content = post("/cmd/queue/send") .param("priority", "1") .param("retry", "101") .contentType(MediaType.APPLICATION_JSON) .content(cmdBase.toJson()); this.mockMvc.perform(content).andExpect(status().isBadRequest()); }