Here are the examples of the java api org.springframework.mock.web.MockHttpSession taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
168 Examples
19
View Source File : StaticContentControllerTest.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
/**
* @author Luciano Fiandesio
*/
public clreplaced StaticContentControllerTest extends DhisWebSpringTest {
private final static String URL = "/staticContent/";
private final static String MIME_PNG = IMAGE_PNG.toString();
private MockHttpSession session;
private MockMultipartFile mockMultipartFile;
@Autowired
private SystemSettingManager systemSettingManager;
@Autowired
private JCloudsFileResourceContentStore fileResourceContentStore;
@Before
public void setUp() {
this.session = getSession("ALL");
this.mockMultipartFile = new MockMultipartFile("file", "testlogo.png", MIME_PNG, "image".getBytes());
systemSettingManager.saveSystemSetting(USE_CUSTOM_LOGO_BANNER, FALSE);
}
@Test
public void verifyFetchWithInvalidKey() throws Exception {
mvc.perform(get(URL + "idontexist").session(session).contentType(APPLICATION_JSON_UTF8)).andExpect(status().is(SC_NOT_FOUND));
}
@Test
public void verifyFetchWithDefaultKey() throws Exception {
mvc.perform(get(URL + LOGO_BANNER).accept(TEXT_HTML_VALUE).session(session)).andExpect(redirectedUrlPattern("**/dhis-web-commons/css/light_blue/logo_banner.png")).andExpect(status().is(SC_MOVED_TEMPORARILY));
}
@Test
public void verifyFetchCustom() throws Exception {
// store a mock file to the content store, before fetching it
fileResourceContentStore.saveFileResourceContent(build(LOGO_BANNER, mockMultipartFile, DOreplacedENT), "image".getBytes());
systemSettingManager.saveSystemSetting(USE_CUSTOM_LOGO_BANNER, TRUE);
mvc.perform(get(URL + LOGO_BANNER).accept(TEXT_HTML_VALUE).session(session)).andExpect(content().contentType(MIME_PNG)).andExpect(content().bytes(mockMultipartFile.getBytes())).andExpect(status().is(SC_OK));
}
@Test
public void testGetStaticImagesCustomKey() throws Exception {
// Given
final String theExpectedType = "png";
final String theExpectedApiUrl = "/api" + RESOURCE_PATH;
// a mock file in the content store used during the fetch
fileResourceContentStore.saveFileResourceContent(build(LOGO_BANNER, mockMultipartFile, DOreplacedENT), "image".getBytes());
// a positive flag indicating the usage of a custom logo
systemSettingManager.saveSystemSetting(USE_CUSTOM_LOGO_BANNER, TRUE);
// When
final ResultActions result = mvc.perform(get(URL + LOGO_BANNER).accept(APPLICATION_JSON).session(session));
// Then
result.andExpect(content().contentType(APPLICATION_JSON)).andExpect(content().string(containsString(theExpectedType))).andExpect(content().string(containsString(theExpectedApiUrl))).andExpect(status().isFound());
}
@Test
public void testGetStaticImagesUsingNonExistingKey() throws Exception {
// Given
final String theExpectedStatusMessage = "Not Found";
final String theExpectedStatusCode = "404";
final String theExpectedStatus = "ERROR";
final String theExpectedMessage = "Key does not exist.";
final String aNonExistingLogoBanner = "nonExistingLogo";
// a mock file in the content store used during the fetch
fileResourceContentStore.saveFileResourceContent(build(LOGO_BANNER, mockMultipartFile, DOreplacedENT), "image".getBytes());
// When
final ResultActions result = mvc.perform(get(URL + aNonExistingLogoBanner).accept(APPLICATION_JSON).session(session));
// Then
result.andExpect(content().contentType(APPLICATION_JSON)).andExpect(content().string(not(containsString("png")))).andExpect(content().string(containsString(theExpectedStatusMessage))).andExpect(content().string(containsString(theExpectedStatus))).andExpect(content().string(containsString(theExpectedMessage))).andExpect(content().string(containsString(theExpectedStatusCode))).andExpect(status().isNotFound());
}
@Test
public void testGetStaticImagesUsingNonExistingLogo() throws Exception {
// Given
final String theExpectedStatusMessage = "Not Found";
final String theExpectedStatusCode = "404";
final String theExpectedStatus = "ERROR";
final String theExpectedMessage = "No custom file found.";
// a non existing logo in the content store used during the fetch
fileResourceContentStore.deleteFileResourceContent(makeKey(DOreplacedENT, Optional.of(LOGO_BANNER)));
// When
final ResultActions result = mvc.perform(get(URL + LOGO_BANNER).accept(APPLICATION_JSON).session(session));
// Then
result.andExpect(content().contentType(APPLICATION_JSON)).andExpect(content().string(not(containsString("png")))).andExpect(content().string(containsString(theExpectedStatusMessage))).andExpect(content().string(containsString(theExpectedStatus))).andExpect(content().string(containsString(theExpectedMessage))).andExpect(content().string(containsString(theExpectedStatusCode))).andExpect(status().isNotFound());
}
@Test
public void verifyStoreImage() throws Exception {
mvc.perform(multipart(URL + LOGO_BANNER).file(mockMultipartFile).session(session)).andExpect(status().is(SC_NO_CONTENT));
}
@Test
public void verifyErrorWhenStoringInvalidMimeType() throws Exception {
final String error = buildResponse("Unsupported Media Type", 415, "WARNING", null);
mvc.perform(multipart(URL + LOGO_BANNER).file(new MockMultipartFile("file", "testlogo.png", IMAGE_JPEG.toString(), "image".getBytes())).session(session)).andExpect(content().json(error)).andExpect(status().is(SC_UNSUPPORTED_MEDIA_TYPE));
}
@Test
public void verifyErrorWhenStoringInvalidKey() throws Exception {
final String error = buildResponse("Bad Request", 400, "ERROR", "This key is not supported.");
mvc.perform(multipart(URL + "idontexist").file(mockMultipartFile).session(session)).andExpect(content().json(error)).andExpect(status().is(SC_BAD_REQUEST));
}
private String buildResponse(String httpStatus, int code, String status, String message) throws Exception {
return new JSONObject().put("httpStatus", httpStatus).put("httpStatusCode", code).put("status", status).putOpt("message", message).toString();
}
}
19
View Source File : WithOAuth2MockAccessTokenSecurityContextFactory.java
License : Apache License 2.0
Project Creator : anilallewar
License : Apache License 2.0
Project Creator : anilallewar
/**
* Security context factory that will help us in mocking up the OAuth2 workflow
* so that we can embed an mock access token in the security context.<br>
* <br>
*
* @author anilallewar
*/
public clreplaced WithOAuth2MockAccessTokenSecurityContextFactory implements WithSecurityContextFactory<WithMockOAuth2Token> {
// Default OAuth2 access token
private static final String TEST_ACCESS_TOKEN = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0OTgwMDA0MDEsInVzZXJfbmFtZSI6ImFuaWwiLCJhdXRob3JpdGllcyI6WyJST0xFX0FETUlOIiwiUk9MRV9VU0VSIl0sImp0aSI6IjkzY2Y3Y2U0LWY2ZDgtNGJkNi04NGE5LWQ4NDViYmEwZGY2ZCIsImNsaWVudF9pZCI6ImFjbWUiLCJzY29wZSI6WyJvcGVuaWQiXX0.NdAHIna-8GCRGmvaDqO5iOGy3gkjaVaAZqXkDvpjKiQqSVrM_1j1xvPBwuy2iWjyD_crkw_zehE_jKfLpcLxw2JLJZPOtLaUeCYs6euUvboOAVKpmg62mi81PgV3tpEBaqSi5MmATtVcerXFf64LgS1ZPnsw8WIogGlqkhziSzOR4yH2tAzY0aIheL7AWxAgxfBe6I7Lej9ld1Fx6xHodIz8TzmSD-wlZ18e40WBpd_0wc7M8VE_uK18f39btM2VS02FxVm9fdxxwwDXzDT-ODJOs0L_NoKHmZx-JF72bjNUmac81ZcH4fU-fVdme5b-oJowFPgfhZZZ4_nKFv71Ww";
@Autowired
MockHttpSession session;
@Override
public SecurityContext createSecurityContext(WithMockOAuth2Token withMockOAuth2Token) {
SecurityContext context = SecurityContextHolder.createEmptyContext();
Authentication authentication = this.getOauthTestAuthentication(withMockOAuth2Token);
context.setAuthentication(authentication);
this.session.setAttribute("scopedTarget.oauth2ClientContext", this.getOauth2ClientContext());
return context;
}
/**
* Create the authentication object that we need to setup in context
*
* @param withMockOAuth2Token
* @return
*/
private Authentication getOauthTestAuthentication(WithMockOAuth2Token withMockOAuth2Token) {
return new OAuth2Authentication(getOauth2Request(withMockOAuth2Token), getAuthentication(withMockOAuth2Token));
}
/**
* Mock OAuth2Request
*
* @param withMockOAuth2Token
* @return
*/
private OAuth2Request getOauth2Request(WithMockOAuth2Token withMockOAuth2Token) {
String clientId = withMockOAuth2Token.clientId();
Map<String, String> requestParameters = Collections.emptyMap();
boolean approved = true;
String redirectUrl = withMockOAuth2Token.redirectUrl();
Set<String> responseTypes = Collections.emptySet();
Set<String> scopes = new HashSet<>(Arrays.asList(withMockOAuth2Token.scopes()));
Set<String> resourceIds = Collections.emptySet();
Map<String, Serializable> extensionProperties = Collections.emptyMap();
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(withMockOAuth2Token.authorities());
OAuth2Request oAuth2Request = new OAuth2Request(requestParameters, clientId, authorities, approved, scopes, resourceIds, redirectUrl, responseTypes, extensionProperties);
return oAuth2Request;
}
/**
* Provide the mock user information to be used
*
* @param withMockOAuth2Token
* @return
*/
private Authentication getAuthentication(WithMockOAuth2Token withMockOAuth2Token) {
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(withMockOAuth2Token.authorities());
User userPrincipal = new User(withMockOAuth2Token.userName(), withMockOAuth2Token.preplacedword(), true, true, true, true, authorities);
HashMap<String, String> details = new HashMap<String, String>();
details.put("user_name", withMockOAuth2Token.userName());
details.put("email", "[email protected]");
details.put("name", "Anil Allewar");
TestingAuthenticationToken token = new TestingAuthenticationToken(userPrincipal, null, authorities);
token.setAuthenticated(true);
token.setDetails(details);
return token;
}
/**
* Create the mock {@link OAuth2ClientContext} object that will be injected
* into the session replacedociated with the request.<br>
* <br>
*
* Without this object in the session, Spring security will attempt to make
* a request to obtain the token if the controller object attempts to use it
* (as in our case)
*
* @return
*/
private OAuth2ClientContext getOauth2ClientContext() {
OAuth2ClientContext mockClient = mock(OAuth2ClientContext.clreplaced);
when(mockClient.getAccessToken()).thenReturn(new DefaultOAuth2AccessToken(TEST_ACCESS_TOKEN));
return mockClient;
}
}
18
View Source File : MockHttpServletRequestBuilderTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void session() {
MockHttpSession session = new MockHttpSession(this.servletContext);
session.setAttribute("foo", "bar");
this.builder.session(session);
this.builder.sessionAttr("baz", "qux");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
replacedertEquals(session, request.getSession());
replacedertEquals("bar", request.getSession().getAttribute("foo"));
replacedertEquals("qux", request.getSession().getAttribute("baz"));
}
18
View Source File : MockHttpServletRequestBuilder.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Set the HTTP session to use, possibly re-used across requests.
* <p>Individual attributes provided via {@link #sessionAttr(String, Object)}
* override the content of the session provided here.
* @param session the HTTP session
*/
public MockHttpServletRequestBuilder session(MockHttpSession session) {
replacedert.notNull(session, "'session' must not be null");
this.session = session;
return this;
}
18
View Source File : AbstractLoginTest.java
License : MIT License
Project Creator : SourceLabOrg
License : MIT License
Project Creator : SourceLabOrg
protected void validateAuthenticated(final MvcResult result, final String expectedUsername, final long expectedUserId, final Collection<String> expectedRoles) {
// Validate session is valid
final MockHttpSession session = (MockHttpSession) result.getRequest().getSession();
replacedertNotNull("Session should not be null", session);
replacedertTrue("Session should be new", session.isNew());
replacedertFalse("sesison should be valid", session.isInvalid());
// Pull out context
final SecurityContext securityContext = (SecurityContext) session.getValue("SPRING_SECURITY_CONTEXT");
replacedertNotNull("Should be authenticated", securityContext);
final UsernamePreplacedwordAuthenticationToken authenticationToken = (UsernamePreplacedwordAuthenticationToken) securityContext.getAuthentication();
replacedertNotNull("Should be authenticated", authenticationToken);
// Verify we have the correct roles
expectedRoles.forEach((expectedRole) -> {
replacedertTrue("Should have user role", authenticationToken.getAuthorities().contains(new SimpleGrantedAuthority(expectedRole)));
});
replacedertEquals("Should have no extra roles", expectedRoles.size(), authenticationToken.getAuthorities().size());
final CustomUserDetails customUserDetails = (CustomUserDetails) authenticationToken.getPrincipal();
expectedRoles.forEach((expectedRole) -> {
replacedertTrue("Should have user role", customUserDetails.getAuthorities().contains(new SimpleGrantedAuthority(expectedRole)));
});
replacedertEquals("Should have no extra roles", expectedRoles.size(), customUserDetails.getAuthorities().size());
replacedertEquals("LDAP Users should have userId", expectedUserId, customUserDetails.getUserId());
replacedertEquals("Should have username", expectedUsername, customUserDetails.getUsername());
}
18
View Source File : MockHttpServletRequestBuilderTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
@Test
public void session() {
MockHttpSession session = new MockHttpSession(this.servletContext);
session.setAttribute("foo", "bar");
this.builder.session(session);
this.builder.sessionAttr("baz", "qux");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
replacedertThat(request.getSession()).isEqualTo(session);
replacedertThat(request.getSession().getAttribute("foo")).isEqualTo("bar");
replacedertThat(request.getSession().getAttribute("baz")).isEqualTo("qux");
}
18
View Source File : AbstractDiscoverTest.java
License : MIT License
Project Creator : freeacs
License : MIT License
Project Creator : freeacs
public void discoverUnit() throws Exception {
MockHttpSession session = new MockHttpSession();
mvc.perform(post("/tr069").session(session).content(getFilereplacedtring("/provision/cpe/Inform.xml"))).andExpect(status().isOk()).andExpect(content().contentType("text/xml")).andExpect(header().string("SOAPAction", "")).andExpect(xpath("/*[local-name() = 'Envelope']" + "/*[local-name() = 'Body']" + "/*[local-name() = 'InformResponse']" + "/MaxEnvelopes").string("1"));
mvc.perform(post("/tr069").session(session)).andExpect(status().isOk()).andExpect(content().contentType("text/xml")).andExpect(header().string("SOAPAction", "")).andExpect(xpath("/*[local-name() = 'Envelope']" + "/*[local-name() = 'Body']" + "/*[local-name() = 'GetParameterNames']" + "/ParameterPath").string("InternetGatewayDevice.")).andExpect(xpath("/*[local-name() = 'Envelope']" + "/*[local-name() = 'Body']" + "/*[local-name() = 'GetParameterNames']" + "/NextLevel").string("false"));
mvc.perform(post("/tr069").session(session).content(getFilereplacedtring("/provision/cpe/GetParameterNamesResponse.xml"))).andExpect(status().isOk()).andExpect(content().contentType("text/xml")).andExpect(header().string("SOAPAction", "")).andExpect(xpath("/*[local-name() = 'Envelope']" + "/*[local-name() = 'Body']" + "/*[local-name() = 'GetParameterValues']" + "/ParameterNames" + "/string[1]").string("InternetGatewayDevice.DeviceInfo.SoftwareVersion")).andExpect(xpath("/*[local-name() = 'Envelope']" + "/*[local-name() = 'Body']" + "/*[local-name() = 'GetParameterValues']" + "/ParameterNames" + "/string[2]").string("InternetGatewayDevice.DeviceInfo.VendorConfigFile."));
mvc.perform(post("/tr069").session(session).content(getFilereplacedtring("/provision/cpe/GetParameterValuesResponse.xml"))).andExpect(status().isOk()).andExpect(content().contentType("text/xml")).andExpect(header().string("SOAPAction", "")).andExpect(xpath("/*[local-name() = 'Envelope']" + "/*[local-name() = 'Body']" + "/*[local-name() = 'SetParameterValues']" + "/ParameterList" + "/ParameterValueStruct" + "/Name").string("InternetGatewayDevice.ManagementServer.PeriodicInformInterval")).andExpect(xpath("/*[local-name() = 'Envelope']" + "/*[local-name() = 'Body']" + "/*[local-name() = 'SetParameterValues']" + "/ParameterList" + "/ParameterValueStruct" + "/Value").string(hasNoSpace()));
mvc.perform(post("/tr069").session(session).content(getFilereplacedtring("/provision/cpe/SetParameterValuesResponse.xml"))).andExpect(status().isNoContent()).andExpect(content().contentType("text/html")).andExpect(header().doesNotExist("SOAPAction"));
}
18
View Source File : DataElementControllerDocumentation.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testGetById404() throws Exception {
MockHttpSession session = getSession("ALL");
mvc.perform(get("/dataElements/{id}", "deabcdefghA").session(session).accept(MediaType.APPLICATION_JSON)).andExpect(status().isNotFound());
}
18
View Source File : DataElementControllerDocumentation.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testFilterEqualOk() throws Exception {
MockHttpSession session = getSession("F_DATAELEMENT_PUBLIC_ADD");
DataElement de = createDataElement('A');
manager.save(de);
mvc.perform(get("/dataElements?filter=name:eq:DataElementA").session(session).contentType(TestUtils.APPLICATION_JSON_UTF8)).andExpect(jsonPath("$.pager.total", org.hamcrest.Matchers.greaterThan(0)));
}
18
View Source File : DataElementControllerDocumentation.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testFilteriLikeOk() throws Exception {
MockHttpSession session = getSession("F_DATAELEMENT_PUBLIC_ADD");
DataElement de = createDataElement('A');
manager.save(de);
mvc.perform(get("/dataElements?filter=name:ilike:DataElementA").session(session).contentType(TestUtils.APPLICATION_JSON_UTF8)).andExpect(jsonPath("$.pager.total", org.hamcrest.Matchers.greaterThan(0)));
}
18
View Source File : AbstractWebApiTest.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testDeleteByIdOk() throws Exception {
MockHttpSession session = getSession("ALL");
T object = createTestObject(testClreplaced, 'A');
manager.save(object);
mvc.perform(delete(schema.getRelativeApiEndpoint() + "/{id}", object.getUid()).session(session).accept(MediaType.APPLICATION_JSON)).andExpect(status().is(deleteStatus)).andDo(doreplacedentPrettyPrint(schema.getPlural() + "/delete"));
}
18
View Source File : AbstractWebApiTest.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testDeleteById404() throws Exception {
MockHttpSession session = getSession("ALL");
mvc.perform(delete(schema.getRelativeApiEndpoint() + "/{id}", "deabcdefghA").session(session).accept(MediaType.APPLICATION_JSON)).andExpect(status().isNotFound());
}
18
View Source File : PrePostSecurityAnnotationsTest.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void authorityAllCanAccessApps() throws Exception {
MockHttpSession session = getSession("ALL");
mvc.perform(put("/apps").session(session)).andExpect(status().isNoContent());
}
18
View Source File : PrePostSecurityAnnotationsTest.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void authorityNoAuthorityCantAccessApps() throws Exception {
MockHttpSession session = getSession("NO_AUTHORITY");
mvc.perform(put("/apps").session(session)).andExpect(status().isForbidden());
}
18
View Source File : ApiVersionTypeTest.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testTypeAnnotationV31V32() throws Exception {
MockHttpSession session = getSession("ALL");
String endpoint = "/type/testV31V32";
mvc.perform(get(endpoint).session(session)).andExpect(status().isNotFound());
mvc.perform(get("/31" + endpoint).session(session)).andExpect(status().isOk());
mvc.perform(get("/32" + endpoint).session(session)).andExpect(status().isOk());
}
18
View Source File : ApiVersionTypeTest.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testTypeAnnotationDefaultAll() throws Exception {
MockHttpSession session = getSession("ALL");
String endpoint = "/type/testDefaultAll";
mvc.perform(get(endpoint).session(session)).andExpect(status().isOk());
mvc.perform(get("/31" + endpoint).session(session)).andExpect(status().isOk());
mvc.perform(get("/32" + endpoint).session(session)).andExpect(status().isOk());
}
18
View Source File : ApiVersionTypeTest.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testTypeAnnotationAllExcludeV32() throws Exception {
MockHttpSession session = getSession("ALL");
String endpoint = "/type/testAllExcludeV32";
mvc.perform(get(endpoint).session(session)).andExpect(status().isNotFound());
mvc.perform(get("/31" + endpoint).session(session)).andExpect(status().isOk());
mvc.perform(get("/32" + endpoint).session(session)).andExpect(status().isNotFound());
}
18
View Source File : ApiVersionTypeTest.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testTypeAnnotationDefault() throws Exception {
MockHttpSession session = getSession("ALL");
String endpoint = "/type/testDefault";
mvc.perform(get(endpoint).session(session)).andExpect(status().isOk());
mvc.perform(get("/31" + endpoint).session(session)).andExpect(status().isNotFound());
mvc.perform(get("/32" + endpoint).session(session)).andExpect(status().isNotFound());
}
18
View Source File : ApiVersionTypeTest.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testTypeAnnotationDefaultV31() throws Exception {
MockHttpSession session = getSession("ALL");
String endpoint = "/type/testDefaultV31";
mvc.perform(get(endpoint).session(session)).andExpect(status().isOk());
mvc.perform(get("/31" + endpoint).session(session)).andExpect(status().isOk());
mvc.perform(get("/32" + endpoint).session(session)).andExpect(status().isNotFound());
}
18
View Source File : ApiVersionTypeTest.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testTypeAnnotationAll() throws Exception {
MockHttpSession session = getSession("ALL");
String endpoint = "/type/testAll";
mvc.perform(get(endpoint).session(session)).andExpect(status().isNotFound());
mvc.perform(get("/31" + endpoint).session(session)).andExpect(status().isOk());
mvc.perform(get("/32" + endpoint).session(session)).andExpect(status().isOk());
}
18
View Source File : ApiVersionMethodTest.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testMethodV31V32() throws Exception {
MockHttpSession session = getSession("ALL");
String endpoint = "/method/testV31V32";
mvc.perform(get(endpoint).session(session)).andExpect(status().isNotFound());
mvc.perform(get("/31" + endpoint).session(session)).andExpect(status().isNotFound());
mvc.perform(get("/32" + endpoint).session(session)).andExpect(status().isNotFound());
mvc.perform(get("/31" + endpoint + "/a").session(session)).andExpect(status().isOk());
mvc.perform(post("/31" + endpoint + "/a").session(session)).andExpect(status().isOk());
mvc.perform(put("/31" + endpoint + "/a").session(session)).andExpect(status().isMethodNotAllowed());
mvc.perform(get("/32" + endpoint + "/b").session(session)).andExpect(status().isOk());
mvc.perform(post("/32" + endpoint + "/b").session(session)).andExpect(status().isMethodNotAllowed());
mvc.perform(put("/32" + endpoint + "/b").session(session)).andExpect(status().isOk());
}
18
View Source File : ApiVersionMethodTest.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testMethodDefault() throws Exception {
MockHttpSession session = getSession("ALL");
String endpoint = "/method/testDefault";
mvc.perform(get(endpoint).session(session)).andExpect(status().isNotFound());
mvc.perform(get("/31" + endpoint).session(session)).andExpect(status().isNotFound());
mvc.perform(get("/32" + endpoint).session(session)).andExpect(status().isNotFound());
mvc.perform(get("/31" + endpoint + "/a").session(session)).andExpect(status().isNotFound());
mvc.perform(get("/32" + endpoint + "/b").session(session)).andExpect(status().isNotFound());
mvc.perform(get(endpoint + "/a").session(session)).andExpect(status().isOk());
mvc.perform(get(endpoint + "/b").session(session)).andExpect(status().isOk());
}
18
View Source File : ApiVersionMethodTest.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testMethodAll() throws Exception {
MockHttpSession session = getSession("ALL");
String endpoint = "/method/testAll";
mvc.perform(get(endpoint).session(session)).andExpect(status().isNotFound());
mvc.perform(get("/31" + endpoint).session(session)).andExpect(status().isNotFound());
mvc.perform(get("/32" + endpoint).session(session)).andExpect(status().isNotFound());
mvc.perform(get("/31" + endpoint + "/a").session(session)).andExpect(status().isOk());
mvc.perform(get("/32" + endpoint + "/b").session(session)).andExpect(status().isOk());
}
18
View Source File : ApiVersionMethodTest.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testMethodAllExcludeV32() throws Exception {
MockHttpSession session = getSession("ALL");
String endpoint = "/method/testAllExcludeV32";
mvc.perform(get(endpoint).session(session)).andExpect(status().isNotFound());
mvc.perform(get("/32" + endpoint).session(session)).andExpect(status().isNotFound());
mvc.perform(get("/32" + endpoint + "/a").session(session)).andExpect(status().isNotFound());
mvc.perform(get("/32" + endpoint + "/b").session(session)).andExpect(status().isNotFound());
mvc.perform(get("/31" + endpoint + "/a").session(session)).andExpect(status().isOk());
mvc.perform(get("/31" + endpoint + "/b").session(session)).andExpect(status().isOk());
}
18
View Source File : ApiVersionInheritTypeTest.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testGetInherited() throws Exception {
MockHttpSession session = getSession("ALL");
String endpoint = "/type/testInheritedFromBase";
mvc.perform(get(endpoint).session(session)).andExpect(status().isNotFound());
mvc.perform(post(endpoint + "/abc").session(session)).andExpect(status().isNotFound());
mvc.perform(get("/31" + endpoint).session(session)).andExpect(status().isNotFound());
mvc.perform(post("/31" + endpoint + "/abc").session(session)).andExpect(status().isNotFound());
mvc.perform(get("/32" + endpoint).session(session)).andExpect(status().isOk());
mvc.perform(get("/32" + endpoint + "/abc").session(session)).andExpect(status().isMethodNotAllowed());
mvc.perform(put("/32" + endpoint + "/abc").session(session)).andExpect(status().isMethodNotAllowed());
mvc.perform(delete("/32" + endpoint + "/abc").session(session)).andExpect(status().isMethodNotAllowed());
mvc.perform(post("/32" + endpoint + "/abc").session(session)).andExpect(status().isOk());
}
17
View Source File : AopNamespaceHandlerScopeIntegrationTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void testSessionScoping() throws Exception {
MockHttpSession oldSession = new MockHttpSession();
MockHttpSession newSession = new MockHttpSession();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(oldSession);
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
ITestBean scoped = (ITestBean) this.context.getBean("sessionScoped");
replacedertTrue("Should be AOP proxy", AopUtils.isAopProxy(scoped));
replacedertFalse("Should not be target clreplaced proxy", scoped instanceof TestBean);
ITestBean scopedAlias = (ITestBean) this.context.getBean("sessionScopedAlias");
replacedertSame(scoped, scopedAlias);
ITestBean testBean = (ITestBean) this.context.getBean("testBean");
replacedertTrue("Should be AOP proxy", AopUtils.isAopProxy(testBean));
replacedertFalse("Regular bean should be JDK proxy", testBean instanceof TestBean);
String rob = "Rob Harrop";
String bram = "Bram Smeets";
replacedertEquals(rob, scoped.getName());
scoped.setName(bram);
request.setSession(newSession);
replacedertEquals(rob, scoped.getName());
request.setSession(oldSession);
replacedertEquals(bram, scoped.getName());
replacedertTrue("Should have advisors", ((Advised) scoped).getAdvisors().length > 0);
}
17
View Source File : HtmlUnitRequestBuilder.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
private MockHttpSession httpSession(MockHttpServletRequest request, final String sessionid) {
MockHttpSession session;
synchronized (this.sessions) {
session = this.sessions.get(sessionid);
if (session == null) {
session = new HtmlUnitMockHttpSession(request, sessionid);
session.setNew(true);
synchronized (this.sessions) {
this.sessions.put(sessionid, session);
}
addSessionCookie(request, sessionid);
} else {
session.setNew(false);
}
}
return session;
}
17
View Source File : SessionScopeControllerTest.java
License : GNU General Public License v3.0
Project Creator : spring-framework-guru
License : GNU General Public License v3.0
Project Creator : spring-framework-guru
@Test
void getMessage() throws Exception {
MockHttpSession session1 = new MockHttpSession();
MockHttpSession session2 = new MockHttpSession();
MockHttpServletResponse response1 = mockMvc.perform(get("/session/message").session(session1)).andReturn().getResponse();
MockHttpServletResponse response2 = mockMvc.perform(get("/session/message").session(session1)).andReturn().getResponse();
replacedertThat(response1.equals(to(response2)));
MockHttpServletResponse response3 = mockMvc.perform(get("/session/message").session(session2)).andReturn().getResponse();
replacedertThat(response3).isNotEqualTo(response1);
replacedertThat(response3).isNotEqualTo(response2);
}
17
View Source File : AbstractLoginTest.java
License : MIT License
Project Creator : SourceLabOrg
License : MIT License
Project Creator : SourceLabOrg
protected void validateMustLogin() throws Exception {
// Hit the home page and we should get redirected to login page.
final MvcResult result = mockMvc.perform(get("/").with(anonymous())).andExpect(status().is3xxRedirection()).andExpect(redirectedUrl("http://localhost/login")).andReturn();
final MockHttpSession session = (MockHttpSession) result.getRequest().getSession(false);
replacedertNotNull(session);
replacedertNull("Should have no security context", session.getValue("SPRING_SECURITY_CONTEXT"));
}
17
View Source File : LoginMvcTest.java
License : Apache License 2.0
Project Creator : f0rb
License : Apache License 2.0
Project Creator : f0rb
/*=============== login ==================*/
@Test
void login() throws Exception {
String content = "{\"account\":\"f0rb\",\"preplacedword\":\"123456\"}";
MvcResult mvcResult = requestJson(post("/login"), content).andExpect(statusIs200()).andReturn();
MockHttpSession session = (MockHttpSession) mvcResult.getRequest().getSession();
mockMvc.perform(get("/account").session(session)).andExpect(jsonPath("$.id").value("1")).andExpect(jsonPath("$.nickname").value("测试1"));
}
17
View Source File : DataElementControllerDocumentation.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testFilterLike() throws Exception {
MockHttpSession session = getSession("F_DATAELEMENT_PUBLIC_ADD");
DataElement de = createDataElement('A');
manager.save(de);
List<FieldDescriptor> fieldDescriptors = new ArrayList<>(ResponseDoreplacedentation.pager());
fieldDescriptors.add(fieldWithPath("dataElements").description("Data elements"));
mvc.perform(get("/dataElements?filter=name:like:DataElementA").session(session).contentType(TestUtils.APPLICATION_JSON_UTF8)).andExpect(jsonPath("$.pager.total", org.hamcrest.Matchers.greaterThan(0))).andDo(doreplacedentPrettyPrint("data-elements/filter", responseFields(fieldDescriptors.toArray(new FieldDescriptor[fieldDescriptors.size()]))));
}
17
View Source File : DataElementControllerDocumentation.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testFieldsFilterOk() throws Exception {
MockHttpSession session = getSession("F_DATAELEMENT_PUBLIC_ADD");
DataElement de = createDataElement('A');
manager.save(de);
List<FieldDescriptor> fieldDescriptors = new ArrayList<>(ResponseDoreplacedentation.pager());
fieldDescriptors.add(fieldWithPath("dataElements").description("Data elements"));
mvc.perform(get("/dataElements?filter=name:eq:DataElementA&fields=id,name,valueType").session(session).contentType(TestUtils.APPLICATION_JSON_UTF8)).andExpect(jsonPath("$.dataElements[*].id").exists()).andExpect(jsonPath("$.dataElements[*].name").exists()).andExpect(jsonPath("$.dataElements[*].valueType").exists()).andExpect(jsonPath("$.dataElements[*].categoryCombo").doesNotExist()).andDo(doreplacedentPrettyPrint("data-elements/fields", responseFields(fieldDescriptors.toArray(new FieldDescriptor[fieldDescriptors.size()]))));
}
17
View Source File : DataElementControllerDocumentation.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testCreateValidation() throws Exception {
MockHttpSession session = getSession("F_DATAELEMENT_PUBLIC_ADD");
DataElement de = createDataElement('A');
de.setName(null);
mvc.perform(post("/dataElements").session(session).contentType(TestUtils.APPLICATION_JSON_UTF8).content(TestUtils.convertObjectToJsonBytes(de)));
de = manager.getByName(DataElement.clreplaced, "DataElementA");
replacedertNull(de);
}
17
View Source File : AttributeControllerDocumentation.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testCreateSectionAttribute() throws Exception {
InputStream input = new ClreplacedPathResource("attribute/SectionAttribute.json").getInputStream();
MockHttpSession session = getSession("ALL");
mvc.perform(post(schema.getRelativeApiEndpoint()).session(session).contentType(TestUtils.APPLICATION_JSON_UTF8).content(ByteStreams.toByteArray(input))).andExpect(status().is(createdStatus));
}
17
View Source File : AttributeControllerDocumentation.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Override
public void testCreate() throws Exception {
InputStream input = new ClreplacedPathResource("attribute/SQLViewAttribute.json").getInputStream();
MockHttpSession session = getSession("ALL");
Set<FieldDescriptor> fieldDescriptors = TestUtils.getFieldDescriptors(schema);
mvc.perform(post(schema.getRelativeApiEndpoint()).session(session).contentType(TestUtils.APPLICATION_JSON_UTF8).content(ByteStreams.toByteArray(input))).andExpect(status().is(createdStatus)).andDo(doreplacedentPrettyPrint(schema.getPlural() + "/create", requestFields(fieldDescriptors.toArray(new FieldDescriptor[fieldDescriptors.size()]))));
}
17
View Source File : AttributeControllerDocumentation.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Override
public void testGetAll() throws Exception {
InputStream input = new ClreplacedPathResource("attribute/SQLViewAttribute.json").getInputStream();
MockHttpSession session = getSession("ALL");
mvc.perform(post(schema.getRelativeApiEndpoint()).session(session).contentType(TestUtils.APPLICATION_JSON_UTF8).content(ByteStreams.toByteArray(input))).andExpect(status().is(createdStatus)).andReturn();
List<FieldDescriptor> fieldDescriptors = new ArrayList<>();
fieldDescriptors.addAll(ResponseDoreplacedentation.pager());
fieldDescriptors.add(fieldWithPath(schema.getPlural()).description(schema.getPlural()));
mvc.perform(get(schema.getRelativeApiEndpoint()).session(session).accept(TestUtils.APPLICATION_JSON_UTF8)).andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith(TestUtils.APPLICATION_JSON_UTF8)).andExpect(jsonPath("$." + schema.getPlural()).isArray()).andExpect(jsonPath("$." + schema.getPlural() + ".length()").value(1)).andDo(doreplacedentPrettyPrint(schema.getPlural() + "/all", responseFields(fieldDescriptors.toArray(new FieldDescriptor[fieldDescriptors.size()]))));
}
17
View Source File : AttributeControllerDocumentation.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Override
public void testUpdate() throws Exception {
InputStream input = new ClreplacedPathResource("attribute/SQLViewAttribute.json").getInputStream();
MockHttpSession session = getSession("ALL");
MvcResult postResult = mvc.perform(post(schema.getRelativeApiEndpoint()).session(session).contentType(TestUtils.APPLICATION_JSON_UTF8).content(ByteStreams.toByteArray(input))).andExpect(status().is(createdStatus)).andReturn();
String uid = TestUtils.getCreatedUid(postResult.getResponse().getContentreplacedtring());
InputStream inputUpdate = new ClreplacedPathResource("attribute/SQLViewAttribute.json").getInputStream();
mvc.perform(put(schema.getRelativeApiEndpoint() + "/" + uid).session(session).contentType(TestUtils.APPLICATION_JSON_UTF8).content(ByteStreams.toByteArray(inputUpdate))).andExpect(status().is(updateStatus)).andDo(doreplacedentPrettyPrint(schema.getPlural() + "/update"));
}
17
View Source File : AttributeControllerDocumentation.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Override
public void testDeleteByIdOk() throws Exception {
InputStream input = new ClreplacedPathResource("attribute/SQLViewAttribute.json").getInputStream();
MockHttpSession session = getSession("ALL");
MvcResult postResult = mvc.perform(post(schema.getRelativeApiEndpoint()).session(session).contentType(TestUtils.APPLICATION_JSON_UTF8).content(ByteStreams.toByteArray(input))).andExpect(status().is(createdStatus)).andReturn();
String uid = TestUtils.getCreatedUid(postResult.getResponse().getContentreplacedtring());
mvc.perform(delete(schema.getRelativeApiEndpoint() + "/{id}", uid).session(session).accept(MediaType.APPLICATION_JSON)).andExpect(status().is(deleteStatus)).andDo(doreplacedentPrettyPrint(schema.getPlural() + "/delete"));
}
17
View Source File : AbstractWebApiTest.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testUpdate() throws Exception {
MockHttpSession session = getSession("ALL");
T object = createTestObject(testClreplaced, 'A');
manager.save(object);
object.setHref("updatedHref");
mvc.perform(put(schema.getRelativeApiEndpoint() + "/" + object.getUid()).session(session).contentType(TestUtils.APPLICATION_JSON_UTF8).content(TestUtils.convertObjectToJsonBytes(object))).andExpect(status().is(updateStatus)).andDo(doreplacedentPrettyPrint(schema.getPlural() + "/update"));
}
17
View Source File : AbstractWebApiTest.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testGetByIdOk() throws Exception {
MockHttpSession session = getSession("ALL");
T object = createTestObject(testClreplaced, 'A');
manager.save(object);
Set<FieldDescriptor> fieldDescriptors = TestUtils.getFieldDescriptors(schema);
mvc.perform(get(schema.getRelativeApiEndpoint() + "/{id}", object.getUid()).session(session).accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$.name").value(object.getName())).andDo(doreplacedentPrettyPrint(schema.getPlural() + "/id", responseFields(fieldDescriptors.toArray(new FieldDescriptor[fieldDescriptors.size()]))));
}
17
View Source File : DhisWebSpringTest.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
// -------------------------------------------------------------------------
// Supportive methods
// -------------------------------------------------------------------------
public MockHttpSession getSession(String... authorities) {
createAndInjectAdminUser(authorities);
MockHttpSession session = new MockHttpSession();
session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
return session;
}
17
View Source File : SetUserPreferredWidgetsPerModuleTest.java
License : GNU Lesser General Public License v3.0
Project Creator : ArkCase
License : GNU Lesser General Public License v3.0
Project Creator : ArkCase
/**
* Created by marjan.stefanoski on 19.01.2016.
*/
@RunWith(SpringJUnit4ClreplacedRunner.clreplaced)
@ContextConfiguration(locations = { "clreplacedpath:/spring/spring-web-acm-web.xml", "clreplacedpath:/spring/spring-library-dashboard-plugin-test.xml" })
public clreplaced SetUserPreferredWidgetsPerModuleTest extends EasyMockSupport {
private MockMvc mockMvc;
private MockHttpSession mockHttpSession;
private SetUserPreferredWidgetsPerModule unit;
private UserPreferenceService mockUserPreferenceService;
private Authentication mockAuthentication;
@Autowired
private ExceptionHandlerExceptionResolver exceptionResolver;
private Logger log = LoggerFactory.getLogger(getClreplaced());
@Before
public void setUp() throws Exception {
mockUserPreferenceService = createMock(UserPreferenceService.clreplaced);
mockHttpSession = new MockHttpSession();
mockAuthentication = createMock(Authentication.clreplaced);
unit = new SetUserPreferredWidgetsPerModule();
unit.setUserPreferenceService(mockUserPreferenceService);
mockMvc = MockMvcBuilders.standaloneSetup(unit).setHandlerExceptionResolvers(exceptionResolver).build();
}
@Test
public void setPreferredWidgets() throws Exception {
String userId = "user";
String moduleName = "newModule";
String ipAddr = "127.0.0.1";
List<String> widgetList = new ArrayList<>();
widgetList.add("newWidget");
PreferredWidgetsDto preferredWidgetsDto = new PreferredWidgetsDto();
preferredWidgetsDto.setPreferredWidgets(widgetList);
preferredWidgetsDto.setModuleName(moduleName);
ObjectMapper objectMapper = new ObjectMapper();
String in = objectMapper.writeValuereplacedtring(preferredWidgetsDto);
log.debug("Input JSON: " + in);
// MVC test clreplacedes must call getName() somehow
expect(mockAuthentication.getName()).andReturn("user").atLeastOnce();
Capture<PreferredWidgetsDto> savedPreferredWidgetsDto = new Capture<>();
mockHttpSession.setAttribute("acm_ip_address", "127.0.0.1");
expect(mockUserPreferenceService.updateUserPreferenceWidgets(eq(userId), capture(savedPreferredWidgetsDto), eq(ipAddr))).andReturn(preferredWidgetsDto);
replayAll();
MvcResult result = mockMvc.perform(put("/api/v1/plugin/dashboard/widgets/preferred").contentType(MediaType.APPLICATION_JSON).accept(MediaType.parseMediaType("application/json;charset=UTF-8")).session(mockHttpSession).principal(mockAuthentication).content(in)).andReturn();
verifyAll();
replacedertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
replacedertTrue(result.getResponse().getContentType().startsWith(MediaType.APPLICATION_JSON_VALUE));
String json = result.getResponse().getContentreplacedtring();
log.info("results: " + json);
PreferredWidgetsDto fromJson = new ObjectMapper().readValue(json, PreferredWidgetsDto.clreplaced);
replacedertNotNull(fromJson);
replacedertEquals(preferredWidgetsDto.getModuleName(), fromJson.getModuleName());
replacedertEquals(preferredWidgetsDto.getPreferredWidgets().get(0), fromJson.getPreferredWidgets().get(0));
}
}
17
View Source File : GetUserPreferredWidgetsByModuleTest.java
License : GNU Lesser General Public License v3.0
Project Creator : ArkCase
License : GNU Lesser General Public License v3.0
Project Creator : ArkCase
/**
* Created by marjan.stefanoski on 19.01.2016.
*/
@RunWith(SpringJUnit4ClreplacedRunner.clreplaced)
@ContextConfiguration(locations = { "clreplacedpath:/spring/spring-web-acm-web.xml", "clreplacedpath:/spring/spring-library-dashboard-plugin-test.xml" })
public clreplaced GetUserPreferredWidgetsByModuleTest extends EasyMockSupport {
private MockMvc mockMvc;
private MockHttpSession mockHttpSession;
private GetUserPreferredWidgetsByModule unit;
private UserPreferenceService mockUserPreferenceService;
private Authentication mockAuthentication;
@Autowired
private ExceptionHandlerExceptionResolver exceptionResolver;
private Logger log = LoggerFactory.getLogger(getClreplaced());
@Before
public void setUp() throws Exception {
mockUserPreferenceService = createMock(UserPreferenceService.clreplaced);
mockHttpSession = new MockHttpSession();
mockAuthentication = createMock(Authentication.clreplaced);
unit = new GetUserPreferredWidgetsByModule();
unit.setUserPreferenceService(mockUserPreferenceService);
mockMvc = MockMvcBuilders.standaloneSetup(unit).setHandlerExceptionResolvers(exceptionResolver).build();
}
@Test
public void getPreferredWidgets() throws Exception {
String userId = "marjan";
String moduleName = "moduleName";
List<String> widgetList = new ArrayList<>();
widgetList.add("newWidget");
PreferredWidgetsDto preferredWidgetsDto = new PreferredWidgetsDto();
preferredWidgetsDto.setPreferredWidgets(widgetList);
preferredWidgetsDto.setModuleName(moduleName);
expect(mockUserPreferenceService.getPreferredWidgetsByUserAndModule(userId, moduleName)).andReturn(preferredWidgetsDto);
// MVC test clreplacedes must call getName() somehow
expect(mockAuthentication.getName()).andReturn("marjan").atLeastOnce();
replayAll();
MvcResult result = mockMvc.perform(get("/api/v1/plugin/dashboard/widgets/preferred/moduleName").accept(MediaType.parseMediaType("application/json;charset=UTF-8")).session(mockHttpSession).principal(mockAuthentication)).andReturn();
verifyAll();
replacedertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
replacedertTrue(result.getResponse().getContentType().startsWith(MediaType.APPLICATION_JSON_VALUE));
String json = result.getResponse().getContentreplacedtring();
log.info("results: " + json);
PreferredWidgetsDto fromJson = new ObjectMapper().readValue(json, PreferredWidgetsDto.clreplaced);
replacedertNotNull(fromJson);
replacedertEquals(preferredWidgetsDto.getModuleName(), fromJson.getModuleName());
replacedertEquals(preferredWidgetsDto.getPreferredWidgets().get(0), fromJson.getPreferredWidgets().get(0));
}
}
16
View Source File : HttpSessionChallengeRepositoryTest.java
License : Apache License 2.0
Project Creator : webauthn4j
License : Apache License 2.0
Project Creator : webauthn4j
@Test
public void loadChallenge_test() {
MockHttpSession session = new MockHttpSession();
MockHttpServletRequest prevRequest = new MockHttpServletRequest();
prevRequest.setSession(session);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(session);
String attrName = ".test-challenge";
target.setSessionAttributeName(attrName);
Challenge challenge = target.generateChallenge();
target.saveChallenge(challenge, prevRequest);
Challenge loadedChallenge = target.loadChallenge(request);
replacedertThat(loadedChallenge).isEqualTo(challenge);
}
16
View Source File : HttpSessionChallengeRepositoryTest.java
License : Apache License 2.0
Project Creator : webauthn4j
License : Apache License 2.0
Project Creator : webauthn4j
@Test
public void saveChallenge_test_with_null() {
MockHttpSession session = new MockHttpSession();
MockHttpServletRequest prevRequest = new MockHttpServletRequest();
prevRequest.setSession(session);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(session);
Challenge challenge = target.generateChallenge();
target.saveChallenge(challenge, prevRequest);
target.saveChallenge(null, request);
Challenge loadedChallenge = target.loadChallenge(request);
replacedertThat(loadedChallenge).isNull();
}
16
View Source File : RequestAndSessionScopedBeansWacTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Integration tests that verify support for request and session scoped beans
* in conjunction with the TestContext Framework.
*
* @author Sam Brannen
* @since 3.2
*/
@RunWith(SpringJUnit4ClreplacedRunner.clreplaced)
@ContextConfiguration
@WebAppConfiguration
public clreplaced RequestAndSessionScopedBeansWacTests {
@Autowired
private WebApplicationContext wac;
@Autowired
private MockHttpServletRequest request;
@Autowired
private MockHttpSession session;
@Test
public void requestScope() throws Exception {
final String beanName = "requestScopedTestBean";
final String contextPath = "/path";
replacedertNull(request.getAttribute(beanName));
request.setContextPath(contextPath);
TestBean testBean = wac.getBean(beanName, TestBean.clreplaced);
replacedertEquals(contextPath, testBean.getName());
replacedertSame(testBean, request.getAttribute(beanName));
replacedertSame(testBean, wac.getBean(beanName, TestBean.clreplaced));
}
@Test
public void sessionScope() throws Exception {
final String beanName = "sessionScopedTestBean";
replacedertNull(session.getAttribute(beanName));
TestBean testBean = wac.getBean(beanName, TestBean.clreplaced);
replacedertSame(testBean, session.getAttribute(beanName));
replacedertSame(testBean, wac.getBean(beanName, TestBean.clreplaced));
}
}
16
View Source File : AbstractLoginTest.java
License : MIT License
Project Creator : SourceLabOrg
License : MIT License
Project Creator : SourceLabOrg
/**
* Attempt to login with invalid credentials.
*/
@Test
public void test_invalidLoginAuthentication() throws Exception {
for (final InvalidCredentialsTestCase testCase : getInvalidCredentials()) {
// Attempt to login now
final MvcResult result = mockMvc.perform(post("/login").with(anonymous()).with(csrf()).param("email", testCase.getUsername()).param("preplacedword", testCase.getPreplacedword())).andExpect(status().is3xxRedirection()).andExpect(redirectedUrl("/login?error=true")).andReturn();
final MockHttpSession session = (MockHttpSession) result.getRequest().getSession(false);
replacedertNotNull(session);
replacedertNull("Should have no security context", session.getValue("SPRING_SECURITY_CONTEXT"));
}
}
16
View Source File : RequestAndSessionScopedBeansWacTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
/**
* Integration tests that verify support for request and session scoped beans
* in conjunction with the TestContext Framework.
*
* @author Sam Brannen
* @since 3.2
*/
@SpringJUnitWebConfig
clreplaced RequestAndSessionScopedBeansWacTests {
@Autowired
WebApplicationContext wac;
@Autowired
MockHttpServletRequest request;
@Autowired
MockHttpSession session;
@Test
void requestScope() throws Exception {
String beanName = "requestScopedTestBean";
String contextPath = "/path";
replacedertThat(request.getAttribute(beanName)).isNull();
request.setContextPath(contextPath);
TestBean testBean = wac.getBean(beanName, TestBean.clreplaced);
replacedertThat(testBean.getName()).isEqualTo(contextPath);
replacedertThat(request.getAttribute(beanName)).isSameAs(testBean);
replacedertThat(wac.getBean(beanName, TestBean.clreplaced)).isSameAs(testBean);
}
@Test
void sessionScope() throws Exception {
String beanName = "sessionScopedTestBean";
replacedertThat(session.getAttribute(beanName)).isNull();
TestBean testBean = wac.getBean(beanName, TestBean.clreplaced);
replacedertThat(session.getAttribute(beanName)).isSameAs(testBean);
replacedertThat(wac.getBean(beanName, TestBean.clreplaced)).isSameAs(testBean);
}
}
16
View Source File : DemoApplicationTest.java
License : Apache License 2.0
Project Creator : f0rb
License : Apache License 2.0
Project Creator : f0rb
protected ResultActions requestJson(MockHttpServletRequestBuilder builder, String content, MockHttpSession session) throws Exception {
return mockMvc.perform(builder.content(content).contentType(MediaType.APPLICATION_JSON_UTF8).session(session));
}
16
View Source File : DataElementControllerDocumentation.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
@Test
public void testAddDeleteCollectionItem() throws Exception {
MockHttpSession session = getSession("ALL");
DataElement de = createDataElement('A');
manager.save(de);
Schema schema = schemaService.getSchema(DataElement.clreplaced);
List<Property> properties = schema.getProperties();
for (Property property : properties) {
if (property.isCollection()) {
String collectionName = property.getCollectionName();
IdentifiableObject item = createTestObject(property.gereplacedemKlreplaced(), 'A');
if (item == null) {
continue;
} else {
manager.save(item);
}
mvc.perform(post("/dataElements/" + de.getUid() + "/" + collectionName + "/" + item.getUid()).session(session).contentType(TestUtils.APPLICATION_JSON_UTF8)).andDo(doreplacedentPrettyPrint("data-elements/add" + collectionName)).andExpect(status().isNoContent());
mvc.perform(delete("/dataElements/" + de.getUid() + "/" + collectionName + "/" + item.getUid()).session(session).contentType(TestUtils.APPLICATION_JSON_UTF8)).andDo(doreplacedentPrettyPrint("data-elements/delete" + collectionName)).andExpect(status().isNoContent());
}
}
}
See More Examples