org.springframework.test.web.servlet.ResultActions Java Examples

The following examples show how to use org.springframework.test.web.servlet.ResultActions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ResourcesControllerIntegrationTest.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
private ResultActions performGetResourcesFolder(UserDetails user, String folderPath) throws Exception {
    String path = "/plugins/cms/assets/folder";

    if (folderPath != null) {
        path += "?folderPath=" + folderPath;
    }

    if (null == user) {
        return mockMvc.perform(get(path));
    }

    String accessToken = mockOAuthInterceptor(user);
    return mockMvc.perform(
            get(path)
                    .header("Authorization", "Bearer " + accessToken));
}
 
Example #2
Source File: WidgetControllerTest.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testAddWidget() throws Exception {
    UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
    String accessToken = mockOAuthInterceptor(user);
    this.controller.setWidgetValidator(new WidgetValidator());
    // @formatter:off
    ResultActions result = mockMvc.perform(
            post("/widgets")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(convertObjectToJsonBytes(createMockRequest()))
                    .header("Authorization", "Bearer " + accessToken)
    );
    String response = result.andReturn().getResponse().getContentAsString();
    result.andExpect(status().isOk());
    assertNotNull(response);
}
 
Example #3
Source File: JLineupControllerTest.java    From jlineup with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnRun() throws Exception {
    // given
    when(jLineupService.getRun("someId")).thenReturn(Optional.of(runStatusBuilder()
            .withId("someId")
            .withState(State.BEFORE_RUNNING)
            .withJobConfig(exampleConfig())
            .build()));

    // when
    ResultActions result = mvc
            .perform(get("/testContextPath/runs/someId")
                    .contextPath("/testContextPath")
                    .accept(MediaType.APPLICATION_JSON));

    // then
    result.andExpect(status().isOk());
}
 
Example #4
Source File: PageResourceTest.java    From bonita-ui-designer with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void should_save_a_page_renaming_it() throws Exception {
    Page pageToBeUpdated = aPage().withId("my-page").withName("my-page").build();
    pageToBeUpdated.addAsset(AssetBuilder.aFilledAsset(pageToBeUpdated));
    when(pageService.get("my-page")).thenReturn(pageToBeUpdated);
    Page pageToBeSaved = aPage().withName("page-new-name").build();
    pageToBeSaved.addAsset(AssetBuilder.aFilledAsset(pageToBeUpdated));
    when(pageRepository.getNextAvailableId("page-new-name")).thenReturn("page-new-name");


    ResultActions result = mockMvc
            .perform(
                    put("/rest/pages/my-page").contentType(MediaType.APPLICATION_JSON_VALUE).content(
                            convertObjectToJsonBytes(pageToBeSaved)))
            .andExpect(status().isOk())
            .andExpect(header().string(HttpHeaders.LOCATION, "/rest/pages/page-new-name"));

    verify(pageRepository).updateLastUpdateAndSave(aPage().withId("page-new-name").withName("page-new-name").build());
    verify(pageAssetService).duplicateAsset(pageRepository.resolvePath("my-page"), pageRepository.resolvePath("my-page"), "my-page", "page-new-name");
    verify(messagingTemplate).convertAndSend("/previewableRemoval", "my-page");

    Assert.assertEquals(MediaType.APPLICATION_JSON.toString(), result.andReturn().getResponse().getContentType());
}
 
Example #5
Source File: FrontControllerTest.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
@Test
public void testNewFront() throws Exception {
    FrontInfo param = new FrontInfo();
    param.setFrontIp("localhost");
    param.setFrontPort(8081);
    param.setAgency("1fe");

    ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.post( "/front/new").
        content(JsonTools.toJSONString(param)).
        contentType(MediaType.APPLICATION_JSON_UTF8)
    );
    resultActions.
        andExpect(MockMvcResultMatchers.status().isOk()).
        andDo(MockMvcResultHandlers.print());
    System.out.println("response:"+resultActions.andReturn().getResponse().getContentAsString());
}
 
Example #6
Source File: MgmtDistributionSetTagResourceTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Verifies that an updated DS tag is stored in the repository as send to the API.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
        @Expect(type = DistributionSetTagUpdatedEvent.class, count = 1) })
public void updateDistributionSetTag() throws Exception {
    final List<DistributionSetTag> tags = testdataFactory.createDistributionSetTags(1);
    final DistributionSetTag original = tags.get(0);

    final Tag update = entityFactory.tag().create().name("updatedName").colour("updatedCol")
            .description("updatedDesc").build();

    final ResultActions result = mvc
            .perform(put(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + original.getId())
                    .content(JsonBuilder.tag(update)).contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));

    final Tag updated = distributionSetTagManagement.findByRsql(PAGE, "name==updatedName").getContent().get(0);
    assertThat(updated.getName()).isEqualTo(update.getName());
    assertThat(updated.getDescription()).isEqualTo(update.getDescription());
    assertThat(updated.getColour()).isEqualTo(update.getColour());

    result.andExpect(applyTagMatcherOnArrayResult(updated)).andExpect(applyTagMatcherOnArrayResult(updated));
}
 
Example #7
Source File: ResourceVersioningControllerIntegrationTest.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
private String createAndDeleteResource(UserDetails user, String resourceTypeCode, String type, Map<String, String> params) throws Exception {
    String mimeType = type.equals("image") ? "application/jpeg" : "application/pdf";
    ResultActions result = performCreateResource(user, type, "free", mimeType);
    String bodyResult = result.andReturn().getResponse().getContentAsString();
    String resourceId = JsonPath.read(bodyResult, "$.payload.id");

    performDeleteResource(user, resourceTypeCode, resourceId)
            .andExpect(status().isOk());

    result = listTrashedResources(user, params)
            .andExpect(status().isOk());
    bodyResult = result.andReturn().getResponse().getContentAsString();

    Integer payloadSize = JsonPath.read(bodyResult, "$.payload.size()");
    for (int i = 0; i < payloadSize; i++) {
        if (JsonPath.read(bodyResult, "$.payload[" + i + "].description").equals("image_test.jpeg")
                || JsonPath.read(bodyResult, "$.payload[" + i + "].description").equals("file_test.jpeg")) {
            return JsonPath.read(bodyResult, "$.payload[" + i + "].id");
        }
    }
    return null;
}
 
Example #8
Source File: AboutControllerTests.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
@Test
public void testAbout() throws Exception {
	ResultActions result = mockMvc.perform(get("/about").accept(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isOk());
	result.andExpect(jsonPath("$.featureInfo.analyticsEnabled", is(true)))
			.andExpect(jsonPath("$.versionInfo.implementation.name", is("${info.app.name}")))
			.andExpect(jsonPath("$.versionInfo.implementation.version", is("1.2.3.IMPLEMENTATION.TEST")))
			.andExpect(jsonPath("$.versionInfo.core.name", is("Spring Cloud Data Flow Core")))
			.andExpect(jsonPath("$.versionInfo.core.version", is("1.2.3.CORE.TEST")))
			.andExpect(jsonPath("$.versionInfo.dashboard.name", is("Spring Cloud Dataflow UI")))
			.andExpect(jsonPath("$.versionInfo.dashboard.version", is("1.2.3.UI.TEST")))
			.andExpect(jsonPath("$.versionInfo.shell.name", is("Spring Cloud Data Flow Shell Test")))
			.andExpect(jsonPath("$.versionInfo.shell.url", is("https://repo.spring.io/libs-milestone/org/springframework/cloud/spring-cloud-dataflow-shell/1.3.0.BUILD-SNAPSHOT/spring-cloud-dataflow-shell-1.3.0.BUILD-SNAPSHOT.jsdfasdf")))
			.andExpect(jsonPath("$.versionInfo.shell.version", is("1.2.3.SHELL.TEST")))
			.andExpect(jsonPath("$.versionInfo.shell.checksumSha1", is("ABCDEFG")))
			.andExpect(jsonPath("$.versionInfo.shell.checksumSha256").doesNotExist())
			.andExpect(jsonPath("$.securityInfo.authenticationEnabled", is(false)))
			.andExpect(jsonPath("$.securityInfo.authenticated", is(false)))
			.andExpect(jsonPath("$.securityInfo.username", isEmptyOrNullString()))
			.andExpect(jsonPath("$.runtimeEnvironment.appDeployer.deployerName", is("skipper server")))
			.andExpect(jsonPath("$.featureInfo.grafanaEnabled", is(true)))
			.andExpect(jsonPath("$.grafanaInfo.url", is("http://localhost:3001")))
			.andExpect(jsonPath("$.grafanaInfo.refreshInterval", is(30)));
}
 
Example #9
Source File: TestSupportWithMVC.java    From rebuild with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param builder
 * @param user
 * @param expect
 * @return
 * @throws Exception
 */
protected MvcResponse perform(MockHttpServletRequestBuilder builder, ID user, ResultMatcher expect) throws Exception {
    builder.contentType("text/plain; charset=utf-8")
            .accept(MediaType.APPLICATION_JSON_UTF8)
            .header(HttpHeaders.USER_AGENT, UA_WIN10_CHROME);
    if (user != null) {
        builder.sessionAttr(WebUtils.CURRENT_USER, user);
    }

    ResultActions resultActions = springMVC.perform(builder);
    if (expect == null) {
        resultActions.andExpect(MockMvcResultMatchers.status().isOk());
    } else {
        resultActions.andExpect(expect);
    }

    MvcResult result = resultActions.andReturn();

    String content = result.getResponse().getContentAsString();
    if (StringUtils.isNotBlank(content)) {
        return new MvcResponse(content);
    }

    ModelAndView view = result.getModelAndView();
    return new MvcResponse(view);
}
 
Example #10
Source File: UserControllerUnitTest.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void shouldValidateUserPut() throws Exception {
    UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
    String accessToken = mockOAuthInterceptor(user);

    String mockJson = "{\n"
            + "    \"username\": \"username_test\",\n"
            + "    \"status\": \"inactive\",\n"
            + "    \"password\": \"invalid spaces\"\n"
            + " }";

    when(this.userManager.getUser(any(String.class))).thenReturn(this.mockUserDetails("username_test"));
    ResultActions result = mockMvc.perform(
            put("/users/{target}", "mismach")
                    .sessionAttr("user", user)
                    .content(mockJson)
                    .contentType(MediaType.APPLICATION_JSON)
                    .header("Authorization", "Bearer " + accessToken));
    String response = result.andReturn().getResponse().getContentAsString();
    System.out.println("users: " + response);
    result.andExpect(status().isConflict());
}
 
Example #11
Source File: SpringTestAPITest.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void showXMLSourceWorksOnBasicTest() throws Exception {

	// Obtaining response and basic tests
	ResultActions resultActions = this.mvc
			//
			.perform(get("/test?showXMLSource=true"))
			//
			.andDo(print())
			//
			.andExpect(status().isOk())
			.andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_XML))
			//
			;
	// Check the XML
	resultActions.andExpect(xpath("/app/pojos/pojo").exists());
	//
	MvcResult response = resultActions.andReturn();
	// Check the model is still there
	final Object model = response.getModelAndView().getModel().get(XsltConfiguration.XML_SOURCE_TAG);
	assertNotNull("Model object returned is not null", model);
	assertThat("Model object is of the appropriate class", model, instanceOf(App.class));
}
 
Example #12
Source File: ResultActionsUtils.java    From evernote-rest-webapp with Apache License 2.0 6 votes vote down vote up
public static void verifyNoteAttribute(ResultActions resultActions, String prefix) throws Exception {
	verifyApplicationData(resultActions, prefix + ".applicationData");
	resultActions
			.andExpect(jsonPath(prefix + ".subjectDate").value(30))
			.andExpect(jsonPath(prefix + ".latitude").value(31.0))
			.andExpect(jsonPath(prefix + ".longitude").value(32.0))
			.andExpect(jsonPath(prefix + ".altitude").value(33.0))
			.andExpect(jsonPath(prefix + ".author").value("NOTE_ATTRIBUTE_AUTHOR"))
			.andExpect(jsonPath(prefix + ".source").value("NOTE_ATTRIBUTE_SOURCE"))
			.andExpect(jsonPath(prefix + ".sourceURL").value("NOTE_ATTRIBUTE_URL"))
			.andExpect(jsonPath(prefix + ".sourceApplication").value("NOTE_ATTRIBUTE_SOURCE_APPLICATION"))
			.andExpect(jsonPath(prefix + ".shareDate").value(34))
			.andExpect(jsonPath(prefix + ".reminderOrder").value(35))
			.andExpect(jsonPath(prefix + ".reminderDoneTime").value(36))
			.andExpect(jsonPath(prefix + ".reminderTime").value(37))
			.andExpect(jsonPath(prefix + ".placeName").value("NOTE_ATTRIBUTE_PLACE_NAME"))
			.andExpect(jsonPath(prefix + ".contentClass").value("NOTE_ATTRIBUTE_CONTENT_CLASS"))
			.andExpect(jsonPath(prefix + ".lastEditedBy").value("NOTE_ATTRIBUTE_LAST_EDITED_BY"))
			.andExpect(jsonPath(prefix + ".classifications.CLASSIFICATION_FOO_KEY").value("CLASSIFICATION_FOO_VALUE"))
			.andExpect(jsonPath(prefix + ".classifications.CLASSIFICATION_BAR_KEY").value("CLASSIFICATION_BAR_VALUE"))
			.andExpect(jsonPath(prefix + ".creatorId").value(38))
			.andExpect(jsonPath(prefix + ".lastEditorId").value(39))
	;
}
 
Example #13
Source File: AbstractControllerIntegrationTest.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testCors(String endpoint) throws Exception {
    ResultActions result = mockMvc
            .perform(options(endpoint)
                    .header(HttpHeaders.ORIGIN, "http://www.someurl.com/")
                    .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")
                    .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Content-Type", "Authorization")
            );

    result.andExpect(status().isOk());
    result.andExpect(header().string("Access-Control-Allow-Origin", "*"));
    result.andExpect(header().string("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS,PATCH"));
    result.andExpect(header().string("Access-Control-Allow-Headers", "Content-Type, Authorization"));
    result.andExpect(header().doesNotExist("Access-Control-Allow-Credentials"));
    result.andExpect(header().string("Access-Control-Max-Age", "3600"));

}
 
Example #14
Source File: PageControllerTest.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void shouldValidateDeletePageWithChildren() throws ApsSystemException, Exception {
    UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
    String accessToken = mockOAuthInterceptor(user);

    Page page = new Page();
    page.setCode("page_with_children");
    page.addChildCode("child");
    when(authorizationService.isAuth(any(UserDetails.class), any(String.class))).thenReturn(true);
    when(this.controller.getPageValidator().getPageManager().getDraftPage(any(String.class))).thenReturn(page);
    ResultActions result = mockMvc.perform(
            delete("/pages/{pageCode}", "page_with_children")
            .sessionAttr("user", user)
            .header("Authorization", "Bearer " + accessToken));

    result.andExpect(status().isBadRequest());
    String response = result.andReturn().getResponse().getContentAsString();
    result.andExpect(jsonPath("$.errors", hasSize(1)));
    result.andExpect(jsonPath("$.errors[0].code", is(PageValidator.ERRCODE_PAGE_HAS_CHILDREN)));
}
 
Example #15
Source File: RuleControllerTest.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateWhitelisting() throws Exception {
    final RuleDTO ruleDTO = new RuleDTO();
    ruleDTO.setAccountId("4567");
    when(ruleEntityService.update(any(RuleDTO.class), anyLong())).thenReturn(ruleEntity);

    final ObjectMapper objectMapper = new ObjectMapper();
    final String ruleAsJson = objectMapper.writeValueAsString(ruleDTO);

    final ResultActions resultActions = mockMvc.perform(put("/api/whitelisting-rules/1").contentType(APPLICATION_JSON).content(ruleAsJson));
    resultActions.andExpect(status().isOk());

    verify(ruleEntityService).update(any(RuleDTO.class), anyLong());
    verify(teamOperationsMock).getTeamIdsByUser(anyString());
    verify(ruleControllerPropertiesMock).getAllowedTeams();

}
 
Example #16
Source File: GrafanaAuthenticationTest.java    From Insights with Apache License 2.0 6 votes vote down vote up
@Test(priority = 2)
public void loginWithIncorrectCredentials() throws Exception {
	this.mockMvc = getMacMvc();
	Map<String, String> headers = new HashMap();
	headers.put("Cookie", cookiesString);
	headers.put("Authorization", GrafanaAuthenticationTestData.invalid_autharization);
	headers.put(HttpHeaders.ORIGIN, ApplicationConfigProvider.getInstance().getInsightsServiceURL());
	headers.put(HttpHeaders.HOST, AuthenticationUtils.getHost(null));
	headers.put(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "GET, POST, OPTIONS, PUT, DELETE, PATCH");
	headers.put(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "*");
	MockHttpServletRequestBuilder builder = mockHttpServletRequestBuilderPostWithRequestParam("/user/authenticate",
			"", headers);

	ResultActions action = this.mockMvc.perform(builder.with(csrf().asHeader()));
	action.andExpect(status().is(AuthenticationUtils.UNAUTHORISE));
}
 
Example #17
Source File: UpdateExampleApplicationTests.java    From Spring-Boot-Examples with MIT License 6 votes vote down vote up
@Test
public void shouldPartialUpdateTodo() throws Exception {
	// Given
	todoService.addNewTodo(new Todo("title", "description"));

	HashMap<String, Object> updates = new HashMap<>();
	updates.put("title", "new title");
	updates.put("description", "new description");

	// When
	ResultActions result = this.mvc.perform(patch("/todos/1")
			.contentType(MediaType.APPLICATION_JSON_UTF8)
			.content(objectMapper.writeValueAsString(updates)));

	Todo todoResult = todoService.getTodoById(1L);

	// Then
	result.andExpect(status().isNoContent())
			.andExpect(status().reason("Todo partial updated!"));

	assertThat(todoResult).isNotNull();
	assertThat(todoResult.getTitle()).isEqualTo("new title");
	assertThat(todoResult.getDescription()).isEqualTo("new description");
}
 
Example #18
Source File: MetaAlertControllerIntegrationTest.java    From metron with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateMetaAlert() throws Exception {
  ResultActions result = this.mockMvc.perform(
          post(metaalertUrl + "/create")
                  .with(httpBasic(user, password)).with(csrf())
                  .contentType(MediaType.parseMediaType("application/json;charset=UTF-8"))
                  .content(create));
  result.andExpect(status().isOk())
          .andExpect(jsonPath("$.guid", notNullValue()))
          .andExpect(jsonPath("$.timestamp", greaterThan(0L)))
          .andExpect(jsonPath("$.sensorType").value(MetaAlertConstants.METAALERT_TYPE))
          .andExpect(jsonPath("$.document.timestamp", greaterThan(0L)))
          .andExpect(jsonPath("$.document['source.type']").value(MetaAlertConstants.METAALERT_TYPE))
          .andExpect(jsonPath("$.document.status").value("active"))
          .andExpect(jsonPath("$.document.groups[0]").value("group_one"))
          .andExpect(jsonPath("$.document.groups[1]").value("group_two"))
          .andExpect(jsonPath("$.document.metron_alert[0].guid").value("bro_1"))
          .andExpect(jsonPath("$.document.metron_alert[1].guid").value("snort_2"));
}
 
Example #19
Source File: PageControllerTest.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void shouldValidateMovePageNameMismatch() throws ApsSystemException, Exception {
    UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
    String accessToken = mockOAuthInterceptor(user);

    PagePositionRequest request = new PagePositionRequest();
    request.setCode("WRONG");
    request.setParentCode("new_parent_page");
    request.setPosition(1);
    
    when(authorizationService.isAuth(any(UserDetails.class), any(String.class))).thenReturn(true);
    when(this.controller.getPageValidator().getPageManager().getDraftPage("new_parent_page")).thenReturn(new Page());
    
    ResultActions result = mockMvc.perform(
            put("/pages/{pageCode}/position", "page_to_move")
                    .sessionAttr("user", user)
                    .content(convertObjectToJsonBytes(request))
                    .contentType(MediaType.APPLICATION_JSON)
                    .header("Authorization", "Bearer " + accessToken));

    result.andExpect(status().isBadRequest())
            .andExpect(jsonPath("$.errors", hasSize(1)))
            .andExpect(jsonPath("$.errors[0].code", is(PageValidator.ERRCODE_URINAME_MISMATCH)));
}
 
Example #20
Source File: TodoControllerTest.java    From Spring-Boot-Examples with MIT License 5 votes vote down vote up
@Test
public void shouldReturn404WhenTryPartialUpdateTodoWhichNotExists() throws Exception {
    // Given
    given(todoService.getTodoById(anyLong())).willReturn(null);
    HashMap<String, Object> updates = new HashMap<>();
    updates.put("description", "new description");
    // When
    ResultActions result = this.mvc.perform(patch("/todos/10")
            .contentType(MediaType.APPLICATION_JSON_VALUE)
            .content(objectMapper.writeValueAsString(updates)));
    // Then
    result.andExpect(status().isNotFound());
}
 
Example #21
Source File: ProfileTypeControllerTest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testPayloadOk() throws Exception {
    UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
    String accessToken = mockOAuthInterceptor(user);
    InputStream isJsonPost = this.getClass().getResourceAsStream("1_POST_valid.json");
    String jsonPost = FileTextReader.getText(isJsonPost);
    ResultActions result = mockMvc
            .perform(post("/profileTypes")
                    .content(jsonPost)
                    .contentType(MediaType.APPLICATION_JSON_VALUE)
                    .header("Authorization", "Bearer " + accessToken));
    Mockito.verify(userProfileTypeService, Mockito.times(1)).addUserProfileType(any(ProfileTypeDtoRequest.class), any(BindingResult.class));
    result.andExpect(status().isOk());
}
 
Example #22
Source File: GuiFragmentSettingsControllerTest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void getSetting_2() throws Exception {
    UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
    String accessToken = mockOAuthInterceptor(user);
    when(this.configManager.getParam(SystemConstants.CONFIG_PARAM_EDIT_EMPTY_FRAGMENT_ENABLED)).thenReturn("invalid");
    ResultActions result = mockMvc.perform(
            get("/fragmentsSettings").header("Authorization", "Bearer " + accessToken));
    result.andExpect(status().isOk());
    result.andExpect(jsonPath("$.errors", Matchers.hasSize(0)));
    result.andExpect(jsonPath("$.payload." + GuiFragmentSettingsController.RESULT_PARAM_NAME, is(false)));
}
 
Example #23
Source File: MockMvcWebConnection.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private MockHttpServletResponse getResponse(RequestBuilder requestBuilder) throws IOException {
	ResultActions resultActions;
	try {
		resultActions = this.mockMvc.perform(requestBuilder);
	}
	catch (Exception ex) {
		throw new IOException(ex);
	}

	return resultActions.andReturn().getResponse();
}
 
Example #24
Source File: RoleControllerIntegrationTest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testGetRoleUserReferences() throws Exception {
    String code = "editor";
    UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
    String accessToken = mockOAuthInterceptor(user);
    ResultActions result = mockMvc
            .perform(get("/roles/{rolecode}/userreferences", code)
                    .header("Authorization", "Bearer " + accessToken));
    result.andExpect(status().isOk());

}
 
Example #25
Source File: VersioningConfigurationControllerTest.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testNotAuthorizedGetExistingContentVersioning() throws Exception {
    VersioningConfigurationDTO configuration = new VersioningConfigurationDTO();
    UserDetails user = this.createUser(false);
    when(this.httpSession.getAttribute("user")).thenReturn(user);
    when(this.service.getVersioningConfiguration())
            .thenReturn(configuration);
    ResultActions result = getVersioningConfiguration(user);
    result.andExpect(status().isForbidden());
}
 
Example #26
Source File: DatabaseControllerIntegrationTest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testGetReport() throws Exception {
    UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
    String accessToken = mockOAuthInterceptor(user);
    ResultActions result = mockMvc
            .perform(get("/database/report/{dumpCode}", new Object[]{"develop"})
                    .header("Authorization", "Bearer " + accessToken));
    result.andExpect(status().isNotFound());
    result.andExpect(jsonPath("$.errors.length()", is(1)));
}
 
Example #27
Source File: AppTests.java    From tutorial with MIT License 5 votes vote down vote up
@Test
public void testFileUpload() throws Exception{
    String fileFolder = "target/files/";
    File folder = new File(fileFolder);
    if(!folder.exists()) {
        folder.mkdirs();
    }
    // 下面这句可以设置bean里面通过@Value获得的数据
    ReflectionTestUtils.setField(tvSeriesController, "uploadFolder", folder.getAbsolutePath());
    
    InputStream is = getClass().getResourceAsStream("/testfileupload.jpg");
    if(is == null) {
        throw new RuntimeException("需要先在src/test/resources目录下放置一张jpg文件,名为testfileupload.jpg然后运行测试");
    }
    
    //模拟一个文件上传的请求
    MockMultipartFile imgFile = new MockMultipartFile("photo", "testfileupload.jpg", "image/jpeg", IOUtils.toByteArray(is));
    
    ResultActions result = mockMvc.perform(MockMvcRequestBuilders.multipart("/tvseries/1/photos")
                    .file(imgFile))
                    .andExpect(MockMvcResultMatchers.status().isOk());
    
    //解析返回的JSON
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(result.andReturn().getResponse().getContentAsString(), new TypeReference<Map<String, Object>>(){});
   
    String fileName = (String) map.get("photo");
    File f2 = new File(folder, fileName);
    //返回的文件名,应该已经保存在filFolder文件夹下
    Assert.assertTrue(f2.exists());
}
 
Example #28
Source File: StreamInterceptorIntegrationTest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testAddPublishUnpublishDelete() throws Exception {
    UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
    String accessToken = mockOAuthInterceptor(user);
    String code = "testAddDelete";
    try {
        IActionLogRecordSearchBean searchBean = null;
        List<Integer> logs1 = actionLogManager.getActionRecords(searchBean);
        int size1 = logs1.size();
        pageManager.addPage(createPage(code, null, null));
        //status
        PageStatusRequest pageStatusRequest = new PageStatusRequest();
        pageStatusRequest.setStatus("published");
        IPage page = this.pageManager.getDraftPage(code);
        assertThat(page, is(not(nullValue())));
        ResultActions result = mockMvc
                .perform(put("/pages/{code}/status", code)
                        .content(mapper.writeValueAsString(pageStatusRequest))
                        .contentType(MediaType.APPLICATION_JSON)
                        .header("Authorization", "Bearer " + accessToken));
        result.andExpect(status().isOk());
        this.waitActionLoggerThread();
        List<Integer> logs2 = actionLogManager.getActionRecords(searchBean);
        int size2 = logs2.size();
        Assert.assertEquals(1, (size2 - size1));
        page = this.pageManager.getDraftPage(code);
        assertThat(page, is(not(nullValue())));
        IPage onlinePage = this.pageManager.getOnlinePage(code);
        assertThat(onlinePage, is(not(nullValue())));
    } finally {
        this.pageManager.deletePage(code);
    }
}
 
Example #29
Source File: UserControllerIntegrationTest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testUpdatePassword_2() throws Exception {
    String validUsername = "valid_ok.2";
    String validPassword = "valid.123_ok";
    String newValidPassword = "valid.1234_ok";
    try {
        UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
        String accessToken = mockOAuthInterceptor(user);

        String mockJson = "{\"username\": \"" + validUsername + "\",\"status\": \"active\",\"password\": \"" + validPassword + "\"}";
        this.executeUserPost(mockJson, accessToken, status().isOk());

        String invalidBody1 = "{\"username\": \"" + validUsername + "\",\"oldPassword\": \"" + validPassword + "\",\"newPassword\": \"" + newValidPassword + "\"}";
        ResultActions resultInvalid1 = this.executeUpdatePassword(invalidBody1, "no_same_username", accessToken, status().isConflict());
        resultInvalid1.andExpect(jsonPath("$.payload", Matchers.hasSize(0)));
        resultInvalid1.andExpect(jsonPath("$.errors", Matchers.hasSize(1)));
        resultInvalid1.andExpect(jsonPath("$.errors[0].code", is("2")));
        resultInvalid1.andExpect(jsonPath("$.metaData.size()", is(0)));

        String noExistingUser = "test12345";
        String invalidBody2 = "{\"username\": \"" + noExistingUser + "\",\"oldPassword\": \"" + validPassword + "\",\"newPassword\": \"" + newValidPassword + "\"}";
        ResultActions resultInvalid2 = this.executeUpdatePassword(invalidBody2, noExistingUser, accessToken, status().isNotFound());
        resultInvalid2.andExpect(jsonPath("$.payload", Matchers.hasSize(0)));
        resultInvalid2.andExpect(jsonPath("$.errors", Matchers.hasSize(1)));
        resultInvalid2.andExpect(jsonPath("$.errors[0].code", is("1")));
        resultInvalid2.andExpect(jsonPath("$.metaData.size()", is(0)));

        String validBody = "{\"username\": \"" + validUsername + "\",\"oldPassword\": \"" + validPassword + "\",\"newPassword\": \"" + newValidPassword + "\"}";
        ResultActions resultValid = this.executeUpdatePassword(validBody, validUsername, accessToken, status().isOk());
        resultValid.andExpect(jsonPath("$.payload.username", is(validUsername)));
        resultValid.andExpect(jsonPath("$.errors", Matchers.hasSize(0)));
        resultValid.andExpect(jsonPath("$.metaData.size()", is(0)));

    } catch (Throwable e) {
        throw e;
    } finally {
        this.userManager.removeUser(validUsername);
    }
}
 
Example #30
Source File: FileBrowserControllerIntegrationTest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testBrowseFolder_3() throws Exception {
    UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
    String accessToken = mockOAuthInterceptor(user);
    ResultActions result = mockMvc
            .perform(get("/fileBrowser").param("currentPath", "conf/unexisting").param("protectedFolder", "false")
                    .header("Authorization", "Bearer " + accessToken));
    result.andExpect(status().isNotFound());
    result.andExpect(jsonPath("$.payload", Matchers.hasSize(0)));
    result.andExpect(jsonPath("$.errors", Matchers.hasSize(1)));
    result.andExpect(jsonPath("$.metaData.size()", is(0)));
}