@Test public void should_download_success() throws Exception { String response = performRequestWith200Status(get("/credentials")); Credential[] credentials = Jsonable.parseArray(response, Credential[].class); Assert.assertEquals(4, credentials.length); response = performRequestWith200Status(get("/credentials/rsa-credential")); Assert.assertNotNull(response); // when: get download file MvcResult result = mockMvc.perform(get("/credentials/rsa-credential/download")).andExpect(status().isOk()) .andReturn(); File file = new File(String.valueOf(Paths.get(workspace.toString(), "test.zip"))); FileUtils.writeByteArrayToFile(file, result.getResponse().getContentAsByteArray()); // then: response is not null Assert.assertNotNull(response); // then: file is exists Assert.assertEquals(true, file.exists()); ZipFile zipFile = new ZipFile(file); // them: zipfile has two files Assert.assertEquals(2, zipFile.size()); }
@Test public void test8_2() throws Exception { // ResultActions actions = mockMvc.perform((post("/jsonp-fastjsonview/test8?callback=fnUpdateSome").characterEncoding( // "UTF-8"))); // actions.andDo(print()); // actions.andExpect(status().isOk()).andExpect(content().contentType(APPLICATION_JAVASCRIPT)) // .andExpect(content().string("fnUpdateSome({\"id\":100,\"name\":\"测试\"})")); MvcResult mvcResult = mockMvc.perform(post("/jsonp-fastjsonview/test8?callback=fnUpdateSome").characterEncoding("UTF-8")) .andExpect(request().asyncStarted()) .andReturn(); mockMvc.perform(asyncDispatch(mvcResult)) .andExpect(status().isOk()) .andExpect(content().contentType(FastJsonHttpMessageConverter.APPLICATION_JAVASCRIPT)) .andExpect(content().string("/**/fnUpdateSome({})")); }
@Test public void changeLevelTest() throws Exception { LoggerVM logger = new LoggerVM(); logger.setLevel("ERROR"); logger.setName("ROOT"); mock.perform(put("/management/logs") .contentType(MediaType.APPLICATION_JSON_UTF8) .content(new ObjectMapper().writeValueAsString(logger))) .andExpect(status().isNoContent()); MvcResult res = mock.perform(get("/management/logs") .accept(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andReturn(); assertTrue(res.getResponse().getContentAsString().contains("\"name\":\""+logger.getName() +"\",\"level\":\""+logger.getLevel()+"\"")); }
@Test public void should_load_database_info() throws Throwable { // when: load db info MvcResult result = this.mockMvc.perform(get("/sys/info/db")) .andExpect(status().isOk()) .andReturn(); // then: String content = result.getResponse().getContentAsString(); GroupSystemInfo dbInfo = SystemInfo.parse(content, GroupSystemInfo.class); Assert.assertEquals(Type.DB, dbInfo.getType()); Map<String, String> mysqlInfo = dbInfo.get(DBGroupName.MYSQL); Assert.assertNotNull(mysqlInfo); Assert.assertEquals(5, mysqlInfo.size()); }
@Test public void testPredict_11dim() throws Exception { final String predictJson = "{" + "\"request\": {" + "\"ndarray\": [[1.0]]}" + "}"; MvcResult res = mvc.perform(MockMvcRequestBuilders.post("/api/v0.1/predictions") .accept(MediaType.APPLICATION_JSON_UTF8) .content(predictJson) .contentType(MediaType.APPLICATION_JSON_UTF8)).andReturn(); String response = res.getResponse().getContentAsString(); System.out.println(response); Assert.assertEquals(200, res.getResponse().getStatus()); }
@Test public void should_list_all_online_agent() throws Throwable { // given: String zoneName = "test-zone-01"; zoneService.createZone(new Zone(zoneName, MOCK_CLOUD_PROVIDER_NAME)); Thread.sleep(1000); String agentName = "act-001"; String path = ZKHelper.buildPath(zoneName, agentName); zkClient.createEphemeral(path, null); Thread.sleep(1000); // when: send get request MvcResult result = this.mockMvc.perform(get("/agents/list").param("zone", zoneName)) .andDo(print()) .andExpect(status().isOk()) .andReturn(); // then: String json = result.getResponse().getContentAsString(); Assert.assertNotNull(json); Agent[] agentList = gsonConfig.fromJson(json, Agent[].class); Assert.assertEquals(1, agentList.length); Assert.assertEquals(agentName, agentList[0].getName()); }
@Test public void shouldFailForEmptyDefence() throws Exception { long anyClaimId = 500; String anyDefendantId = "500"; Response response = SampleResponse.FullDefence.builder() .withDefence("") .build(); MvcResult result = makeRequest(anyClaimId, anyDefendantId, response) .andExpect(status().isBadRequest()) .andReturn(); assertThat(extractErrors(result)) .hasSize(1) .contains("defence : may not be empty"); }
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 testController () throws Exception { MvcResult result = mockMvc.perform(get("/callSelectDept/359.json")) .andExpect(request().asyncStarted()) .andReturn(); result.getRequest().getAsyncContext().setTimeout(5000); result.getAsyncResult(); result= mockMvc.perform(asyncDispatch(result)) .andExpect(status().isOk()) .andExpect(header().string("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE)) .andReturn(); System.out.println(result.getResponse().getContentAsString()); }
@Test public void should_update_status() throws Exception { String petName = "pet1"; PetStatusRequest request = new PetStatusRequest(pet.getId(), PetStatus.Locked); this.mockMvc.perform(put(format("/api/pets/%s/status", pet.getId())). contentType(APPLICATION_JSON_UTF8). content(this.objectMapper.writeValueAsString(request))). andExpect(status().isOk()); MvcResult queryResult = this.mockMvc.perform(get(format("/api/pets/shops/%s", shop.getId()))). andExpect(status().isOk()). andReturn(); List<ShopPetResponse> shopPets = this.objectMapper.readValue( queryResult.getResponse().getContentAsByteArray(), new TypeReference<List<ShopPetResponse>>(){}); Assert.assertEquals(1, shopPets.size()); ShopPetResponse shopPet = shopPets.get(0); Assert.assertEquals(pet.getId(), pet.getId()); Assert.assertEquals(PetStatus.Locked, shopPet.getPetStatus()); }
@Test public void should_get_the_preset_shop_list() throws Exception { MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/api/shops") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andReturn(); List<ShopResponse> shops = this.objectMapper.readValue( mvcResult.getResponse().getContentAsByteArray(), new TypeReference<List<ShopResponse>>(){}); assertEquals(1, shops.size()); ShopResponse shop = shops.get(0); assertEquals(shopName, shop.getName()); }
@Test public void should_audit_retrieval() throws Exception { final String url = uploadFileAndReturnSelfUrl(); mvc.perform(get(url) .headers(headers)); final MvcResult auditResponse = mvc.perform(get(url + "/auditEntries") .headers(headers)) .andExpect(status().isOk()) .andReturn(); final JsonNode auditEntries = getAuditEntriesFromResponse(auditResponse); assertThat(auditEntries.size(), is(3)); assertThat(auditEntries.get(2).get("action").asText(), equalTo("READ")); }
@Test public void should_audit_delete() throws Exception { final String url = uploadFileAndReturnSelfUrl(); mvc.perform(delete(url) .headers(headers)); final MvcResult auditResponse = mvc.perform(get(url + "/auditEntries") .headers(headers)) .andExpect(status().isOk()) .andReturn(); final JsonNode auditEntries = getAuditEntriesFromResponse(auditResponse); assertThat(auditEntries.size(), is(3)); assertThat(auditEntries.get(2).get("action").asText(), equalTo("DELETED")); }
@Test public void createJsonFileFromSwaggerEndpoint() throws Exception { String outputDir = Optional.ofNullable(System.getProperty("io.springfox.staticdocs.outputDir")) .orElse("build/swagger"); System.err.println(outputDir); MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); String swaggerJson = response.getContentAsString(); Files.createDirectories(Paths.get(outputDir)); try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)) { writer.write(swaggerJson); } }
@Test public void createPostWithoutAuthentication() throws Exception { Post _data = Post.builder().title("my first post").content("my content of my post").build(); given(this.postService.createPost(any(PostForm.class))) .willReturn(_data); MvcResult result = this.mockMvc .perform( post("/posts") .content(objectMapper.writeValueAsString(PostForm.builder().title("my first post").content("my content of my post").build())) .contentType(MediaType.APPLICATION_JSON) ) .andExpect(status().isUnauthorized()) .andReturn(); log.debug("mvc result::" + result.getResponse().getContentAsString()); verify(this.postService, times(0)).createPost(any(PostForm.class)); verifyNoMoreInteractions(this.postService); }
@Override public void match(MvcResult result) throws Exception { String content = result.getResponse().getContentAsString(); final JsonParser parser = new JsonParser(); final JsonElement actual = parser.parse(content); if (actual.isJsonPrimitive()) { final JsonElement expected = parser.parse(expectedJsonResponse); assertThat(actual, is(expected)); } else { try { JSONAssert.assertEquals(expectedJsonResponse, content, false); } catch (AssertionError e) { throw new ComparisonFailure(e.getMessage(), expectedJsonResponse, content); } } }
@Test public void availableSubjectsForStudyPlanJsonTest() throws Exception { // given 3 subjects, where all of them contain the string "Engineering", but one is already part of studyPlan2 studyPlan1.addSubjects(new SubjectForStudyPlan(subjects.get(1), studyPlan2, true)); studyPlanRepository.save(studyPlan2); // when searching for "Engineering MvcResult result = mockMvc.perform( get("/admin/studyplans/json/availableSubjects").with(user("admin").roles("ADMIN")) .param("id", studyPlan2.getId().toString()) .param("query", "Engineering") ).andExpect((status().isOk()) ).andReturn(); // the other 2 subjects should be available for studyPlan2 assertTrue(result.getResponse().getContentAsString().contains("Advanced Software Engineering")); assertTrue(result.getResponse().getContentAsString().contains("Model Engineering")); assertFalse(result.getResponse().getContentAsString().contains("Software Engineering and Project Management")); }
@Test public void testSubjectWithParentsFailWhenNotUsingTitan() throws Exception { BaseSubject subject = SubjectPrivilegeManagementControllerIT.JSON_UTILS.deserializeFromFile( "controller-test/a-subject-with-parents.json", BaseSubject.class); Assert.assertNotNull(subject); MockMvcContext putContext = SubjectPrivilegeManagementControllerIT.TEST_UTILS.createWACWithCustomPUTRequestBuilder( this.wac, TEST_ZONE.getSubdomain(), SubjectPrivilegeManagementControllerIT.SUBJECT_BASE_URL + "/dave-with-parents"); final MvcResult result = putContext.getMockMvc() .perform(putContext.getBuilder().contentType(MediaType.APPLICATION_JSON) .content(ResourcePrivilegeManagementControllerIT .OBJECT_MAPPER.writeValueAsString(subject))) .andExpect(status().isNotImplemented()) .andReturn(); Assert.assertEquals(result.getResponse().getContentAsString(), "{\"ErrorDetails\":{\"errorCode\":\"FAILURE\"," + "\"errorMessage\":\"" + BaseRestApi.PARENTS_ATTR_NOT_SUPPORTED_MSG + "\"}}"); }
@Test public void testPredict_21dim() throws Exception { final String predictJson = "{" + "\"request\": {" + "\"ndarray\": [[1.0],[2.0]]}" + "}"; MvcResult res = mvc.perform(MockMvcRequestBuilders.post("/api/v0.1/predictions") .accept(MediaType.APPLICATION_JSON_UTF8) .content(predictJson) .contentType(MediaType.APPLICATION_JSON_UTF8)).andReturn(); String response = res.getResponse().getContentAsString(); System.out.println(response); Assert.assertEquals(200, res.getResponse().getStatus()); }
@Test public void logout() throws Exception { String url = "/tokens"; HashMap<String, String> keyvals = new HashMap<>(); // keyvals.put("phone", "18217699800"); // keyvals.put("password", "123456"); keyvals.put("token",token); TestUtil.Method method = TestUtil.Method.DELETE; MvcResult result = TestUtil.getHttpResultContent(mockMvc, url, method, keyvals); System.out.println("----------------"); System.out.println(url+" "+method); for (String s : result.getResponse().getHeaderNames()) { System.out.println(s + ": " + result.getResponse().getHeaders(s)); } System.out.println(result.getResponse().getStatus()); System.out.println(result.getResponse().getContentAsString()); System.out.println("----------------"); //{"code":200,"message":"ok","content":{"uid":"213124128","token":"213124128_9ffabcb2-43ad-426a-bd63-f209de6d7f1e"}} //{"code":90004,"message":"用户名或者密码不正确","content":null} }
@Test public void testResourceWithParentsFailWhenNotUsingTitan() throws Exception { BaseResource resource = ResourcePrivilegeManagementControllerIT.JSON_UTILS.deserializeFromFile( "controller-test/a-resource-with-parents.json", BaseResource.class); Assert.assertNotNull(resource); MockMvcContext putContext = ResourcePrivilegeManagementControllerIT.TEST_UTILS.createWACWithCustomPUTRequestBuilder( this.wac, TEST_ZONE.getSubdomain(), ResourcePrivilegeManagementControllerIT.RESOURCE_BASE_URL + "/%2Fservices%2Fsecured-api-with-parents"); final MvcResult result = putContext.getMockMvc() .perform(putContext.getBuilder().contentType(MediaType.APPLICATION_JSON) .content(ResourcePrivilegeManagementControllerIT .OBJECT_MAPPER.writeValueAsString(resource))) .andExpect(status().isNotImplemented()) .andReturn(); Assert.assertEquals(result.getResponse().getContentAsString(), "{\"ErrorDetails\":{\"errorCode\":\"FAILURE\"," + "\"errorMessage\":\"" + BaseRestApi.PARENTS_ATTR_NOT_SUPPORTED_MSG + "\"}}"); }
@Test public void testChangeValidFrom() throws Exception { for (String graphName : this.graphVersions.keySet()) { for (String version : this.graphVersions.get(graphName)) { MvcResult graphVersionResult = mockMvc.perform(put("/metadata/graphs/" + graphName + "/versions/" + version + "/validFrom/" + "10") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andReturn(); String result = graphVersionResult.getResponse().getContentAsString(); log.info(result); ObjectMapper mapper = new ObjectMapper(); Map resultMap = mapper.readValue(result,HashMap.class); Assert.assertEquals(resultMap.get("validFrom"),10); mockMvc.perform(put("/metadata/graphs/" + graphName + "/versions/" + version + "/validTo/" + "0") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isUnprocessableEntity()) .andReturn(); mockMvc.perform(delete("/metadata/graphs/" + graphName + "/versions/" + version + "/validTo/") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andReturn(); } } }
@Test public void autoCompleteShouldReturnJson() throws Exception { integrationMvc = standaloneSetup(new SolrController(productService)) .setSingleView(new InternalResourceView("/products/search.html")).build(); MvcResult result = integrationMvc .perform(get(String.format("/products/autocomplete?term=%s", AUTOCOMPLETE_FRAGMENT)) .accept(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)).andReturn(); // Using Jackson ObjectMapper on JSON // // ObjectMapper mapper = new ObjectMapper(); // List<String> fragments = Arrays.asList(mapper.readValue(body, String[].class)); String body = result.getResponse().getContentAsString(); String[] fragments = body.replaceAll("[\\p{Ps}\\p{Pe}\\\"]", "").split(","); for (String string : fragments) { assert(string.contains(AUTOCOMPLETE_FRAGMENT)); } }
@Test public void allTagsJsonTest() throws Exception { // given 5 tags MvcResult result = mockMvc.perform( get("/lecturer/courses/json/tags") .with(user(user1)) ).andExpect((status().isOk()) ).andReturn(); // the response should contain all these tags assertTrue(result.getResponse().getContentAsString().contains(tag1.getName())); assertTrue(result.getResponse().getContentAsString().contains(tag2.getName())); assertTrue(result.getResponse().getContentAsString().contains(tag3.getName())); assertTrue(result.getResponse().getContentAsString().contains(tag4.getName())); assertTrue(result.getResponse().getContentAsString().contains(tag5.getName())); }
@Test public void updateBlog() throws Exception { log.debug("================== update a blog ========================="); BlogForm form = new BlogForm(); form.setSubject("测试xxx"); form.setContent("内容内容内容内容xxx"); MvcResult response = mvc.perform( put(Constants.URI_API + "/blogs/" + this.post.getId()).contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(form)) ) .andExpect(status().isOk()) .andReturn(); log.debug(""); log.debug("result ==>" + response.getResponse().getContentAsString()); log.debug(""); }
@Test public void checkDeleteReleaseWithPackage() throws Exception { // Make the test repo Local Repository repo = this.repositoryRepository.findByName("test"); repo.setLocal(true); this.repositoryRepository.save(repo); // Deploy String releaseNameOne = "test1"; Release release = install("log", "1.0.0", releaseNameOne); assertThat(release.getVersion()).isEqualTo(1); String releaseNameTwo = "test2"; Release release2 = install("log", "1.0.0", releaseNameTwo); assertThat(release2.getVersion()).isEqualTo(1); // Undeploy boolean deletePackage = true; MvcResult result = mockMvc.perform(delete("/api/release/" + releaseNameOne + "/" + deletePackage)) .andDo(print()).andExpect(status().isConflict()).andReturn(); assertThat(result.getResponse().getContentAsString()) .contains("Can not delete Package Metadata [log:1.0.0] in Repository [test]. Not all releases of " + "this package have the status DELETED. Active Releases [test2]"); assertThat(this.packageMetadataRepository.findByName("log").size()).isEqualTo(3); // Delete the 'release2' only not the package. mockMvc.perform(delete("/api/release/" + releaseNameTwo + "/" + false)) .andDo(print()).andExpect(status().isOk()).andReturn(); assertThat(this.packageMetadataRepository.findByName("log").size()).isEqualTo(3); // Second attempt to delete 'release1' along with its package 'log'. mockMvc.perform(delete("/api/release/" + releaseNameOne + "/" + deletePackage)) .andDo(print()).andExpect(status().isOk()).andReturn(); assertThat(this.packageMetadataRepository.findByName("log").size()).isEqualTo(0); }
@Test public void testReadGraphCurrentId() throws Exception { for (String graphName : this.graphVersions.keySet()) { MvcResult graphVersionResult = mockMvc.perform(get("/metadata/graphs/" + graphName + "/versions/current/id")).andExpect(status().isOk()).andExpect(content().contentType(MediaType.parseMediaType("application/json;charset=UTF-8"))) .andReturn(); String graphIdResult = graphVersionResult.getResponse().getContentAsString(); ObjectMapper mapper = new ObjectMapper(); HashMap versionResult = mapper.readValue(graphIdResult, HashMap.class); Assert.assertTrue(versionResult.containsKey("id")); log.info(versionResult.toString()); } }
protected Release installPackage(InstallRequest installRequest) throws Exception { MvcResult result = mockMvc.perform(post("/api/package/install") .content(convertObjectToJson(installRequest))).andDo(print()) .andExpect(status().isCreated()).andReturn(); Release release = convertContentToRelease(result.getResponse().getContentAsString()); assertReleaseIsDeployedSuccessfully(release.getName(), release.getVersion()); String releaseName = installRequest.getInstallProperties().getReleaseName(); Release deployedRelease = this.releaseRepository.findByNameAndVersion(releaseName, release.getVersion()); PackageMetadata packageMetadata = this.packageMetadataRepository.findByNameAndVersionByMaxRepoOrder( installRequest.getPackageIdentifier().getPackageName(), installRequest.getPackageIdentifier().getPackageVersion()); commonReleaseAssertions(releaseName, packageMetadata, deployedRelease); return deployedRelease; }
private void activationEntityCreated(MvcResult result) throws IOException, MessagingException { String activationId = getActivationIdFromMail(); PendingAccountActivation activation = pendingAccountActivationRepository.findOne(activationId); assertNotNull(activation); assertEquals(form.getName(), activation.getForUser().getName()); }
private void userCanLogin(MvcResult result) throws Exception { mockMvc.perform( formLogin().user("s1234567").password("pass") ).andExpect( authenticated().withRoles(Role.STUDENT.name()) ); }
@Test public void processParameterizedValidationErrorTest() throws Exception { // These lines will throw the wanted exception SecurityContext securityContext = Mockito.mock(SecurityContext.class); Mockito.when(securityContext.getAuthentication()).thenThrow(new CustomParameterizedException(null)); SecurityContextHolder.setContext(securityContext); MvcResult res = mock.perform(get("/api/account")) .andExpect(status().isBadRequest()) .andReturn(); assertThat(res.getResolvedException(), instanceOf(CustomParameterizedException.class)); }