Initial application generated by JHipster-5.8.2
This commit is contained in:
@@ -0,0 +1,189 @@
|
||||
package org.hostsharing.hsadminng.config;
|
||||
|
||||
import io.github.jhipster.config.JHipsterConstants;
|
||||
import io.github.jhipster.config.JHipsterProperties;
|
||||
import io.github.jhipster.web.filter.CachingHttpHeadersFilter;
|
||||
import io.undertow.Undertow;
|
||||
import io.undertow.Undertow.Builder;
|
||||
import io.undertow.UndertowOptions;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
|
||||
import org.h2.server.web.WebServlet;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.mock.env.MockEnvironment;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.xnio.OptionMap;
|
||||
|
||||
import javax.servlet.*;
|
||||
import java.util.*;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Unit tests for the WebConfigurer class.
|
||||
*
|
||||
* @see WebConfigurer
|
||||
*/
|
||||
public class WebConfigurerTest {
|
||||
|
||||
private WebConfigurer webConfigurer;
|
||||
|
||||
private MockServletContext servletContext;
|
||||
|
||||
private MockEnvironment env;
|
||||
|
||||
private JHipsterProperties props;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
servletContext = spy(new MockServletContext());
|
||||
doReturn(mock(FilterRegistration.Dynamic.class))
|
||||
.when(servletContext).addFilter(anyString(), any(Filter.class));
|
||||
doReturn(mock(ServletRegistration.Dynamic.class))
|
||||
.when(servletContext).addServlet(anyString(), any(Servlet.class));
|
||||
|
||||
env = new MockEnvironment();
|
||||
props = new JHipsterProperties();
|
||||
|
||||
webConfigurer = new WebConfigurer(env, props);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStartUpProdServletContext() throws ServletException {
|
||||
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
|
||||
webConfigurer.onStartup(servletContext);
|
||||
|
||||
verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.class));
|
||||
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStartUpDevServletContext() throws ServletException {
|
||||
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
|
||||
webConfigurer.onStartup(servletContext);
|
||||
|
||||
verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.class));
|
||||
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomizeServletContainer() {
|
||||
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
|
||||
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
|
||||
webConfigurer.customize(container);
|
||||
assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
|
||||
assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
|
||||
assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
|
||||
if (container.getDocumentRoot() != null) {
|
||||
assertThat(container.getDocumentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("build/www"));
|
||||
}
|
||||
|
||||
Builder builder = Undertow.builder();
|
||||
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
|
||||
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
|
||||
assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUndertowHttp2Enabled() {
|
||||
props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
|
||||
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
|
||||
webConfigurer.customize(container);
|
||||
Builder builder = Undertow.builder();
|
||||
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
|
||||
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
|
||||
assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCorsFilterOnApiPath() throws Exception {
|
||||
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
|
||||
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
|
||||
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
|
||||
props.getCors().setMaxAge(1800L);
|
||||
props.getCors().setAllowCredentials(true);
|
||||
|
||||
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
|
||||
.addFilters(webConfigurer.corsFilter())
|
||||
.build();
|
||||
|
||||
mockMvc.perform(
|
||||
options("/api/test-cors")
|
||||
.header(HttpHeaders.ORIGIN, "other.domain.com")
|
||||
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"))
|
||||
.andExpect(header().string(HttpHeaders.VARY, "Origin"))
|
||||
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE"))
|
||||
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"))
|
||||
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
|
||||
|
||||
mockMvc.perform(
|
||||
get("/api/test-cors")
|
||||
.header(HttpHeaders.ORIGIN, "other.domain.com"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCorsFilterOnOtherPath() throws Exception {
|
||||
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
|
||||
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
|
||||
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
|
||||
props.getCors().setMaxAge(1800L);
|
||||
props.getCors().setAllowCredentials(true);
|
||||
|
||||
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
|
||||
.addFilters(webConfigurer.corsFilter())
|
||||
.build();
|
||||
|
||||
mockMvc.perform(
|
||||
get("/test/test-cors")
|
||||
.header(HttpHeaders.ORIGIN, "other.domain.com"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCorsFilterDeactivated() throws Exception {
|
||||
props.getCors().setAllowedOrigins(null);
|
||||
|
||||
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
|
||||
.addFilters(webConfigurer.corsFilter())
|
||||
.build();
|
||||
|
||||
mockMvc.perform(
|
||||
get("/api/test-cors")
|
||||
.header(HttpHeaders.ORIGIN, "other.domain.com"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCorsFilterDeactivated2() throws Exception {
|
||||
props.getCors().setAllowedOrigins(new ArrayList<>());
|
||||
|
||||
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
|
||||
.addFilters(webConfigurer.corsFilter())
|
||||
.build();
|
||||
|
||||
mockMvc.perform(
|
||||
get("/api/test-cors")
|
||||
.header(HttpHeaders.ORIGIN, "other.domain.com"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
|
||||
}
|
||||
}
|
@@ -0,0 +1,16 @@
|
||||
package org.hostsharing.hsadminng.config;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class WebConfigurerTestController {
|
||||
|
||||
@GetMapping("/api/test-cors")
|
||||
public void testCorsOnApiPath() {
|
||||
}
|
||||
|
||||
@GetMapping("/test/test-cors")
|
||||
public void testCorsOnOtherPath() {
|
||||
}
|
||||
}
|
@@ -0,0 +1,176 @@
|
||||
package org.hostsharing.hsadminng.config.timezone;
|
||||
|
||||
import org.hostsharing.hsadminng.HsadminNgApp;
|
||||
import org.hostsharing.hsadminng.repository.timezone.DateTimeWrapper;
|
||||
import org.hostsharing.hsadminng.repository.timezone.DateTimeWrapperRepository;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.support.rowset.SqlRowSet;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.*;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
import static java.lang.String.format;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Unit tests for the UTC Hibernate configuration.
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = HsadminNgApp.class)
|
||||
public class HibernateTimeZoneTest {
|
||||
|
||||
@Autowired
|
||||
private DateTimeWrapperRepository dateTimeWrapperRepository;
|
||||
@Autowired
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
|
||||
private DateTimeWrapper dateTimeWrapper;
|
||||
private DateTimeFormatter dateTimeFormatter;
|
||||
private DateTimeFormatter timeFormatter;
|
||||
private DateTimeFormatter dateFormatter;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
dateTimeWrapper = new DateTimeWrapper();
|
||||
dateTimeWrapper.setInstant(Instant.parse("2014-11-12T05:50:00.0Z"));
|
||||
dateTimeWrapper.setLocalDateTime(LocalDateTime.parse("2014-11-12T07:50:00.0"));
|
||||
dateTimeWrapper.setOffsetDateTime(OffsetDateTime.parse("2011-12-14T08:30:00.0Z"));
|
||||
dateTimeWrapper.setZonedDateTime(ZonedDateTime.parse("2011-12-14T08:30:00.0Z"));
|
||||
dateTimeWrapper.setLocalTime(LocalTime.parse("14:30:00"));
|
||||
dateTimeWrapper.setOffsetTime(OffsetTime.parse("14:30:00+02:00"));
|
||||
dateTimeWrapper.setLocalDate(LocalDate.parse("2016-09-10"));
|
||||
|
||||
dateTimeFormatter = DateTimeFormatter
|
||||
.ofPattern("yyyy-MM-dd HH:mm:ss.S")
|
||||
.withZone(ZoneId.of("UTC"));
|
||||
|
||||
timeFormatter = DateTimeFormatter
|
||||
.ofPattern("HH:mm:ss")
|
||||
.withZone(ZoneId.of("UTC"));
|
||||
|
||||
dateFormatter = DateTimeFormatter
|
||||
.ofPattern("yyyy-MM-dd");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void storeInstantWithUtcConfigShouldBeStoredOnGMTTimeZone() {
|
||||
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
|
||||
|
||||
String request = generateSqlRequest("instant", dateTimeWrapper.getId());
|
||||
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
|
||||
String expectedValue = dateTimeFormatter.format(dateTimeWrapper.getInstant());
|
||||
|
||||
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void storeLocalDateTimeWithUtcConfigShouldBeStoredOnGMTTimeZone() {
|
||||
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
|
||||
|
||||
String request = generateSqlRequest("local_date_time", dateTimeWrapper.getId());
|
||||
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
|
||||
String expectedValue = dateTimeWrapper
|
||||
.getLocalDateTime()
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.format(dateTimeFormatter);
|
||||
|
||||
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void storeOffsetDateTimeWithUtcConfigShouldBeStoredOnGMTTimeZone() {
|
||||
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
|
||||
|
||||
String request = generateSqlRequest("offset_date_time", dateTimeWrapper.getId());
|
||||
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
|
||||
String expectedValue = dateTimeWrapper
|
||||
.getOffsetDateTime()
|
||||
.format(dateTimeFormatter);
|
||||
|
||||
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void storeZoneDateTimeWithUtcConfigShouldBeStoredOnGMTTimeZone() {
|
||||
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
|
||||
|
||||
String request = generateSqlRequest("zoned_date_time", dateTimeWrapper.getId());
|
||||
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
|
||||
String expectedValue = dateTimeWrapper
|
||||
.getZonedDateTime()
|
||||
.format(dateTimeFormatter);
|
||||
|
||||
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void storeLocalTimeWithUtcConfigShouldBeStoredOnGMTTimeZoneAccordingToHis1stJan1970Value() {
|
||||
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
|
||||
|
||||
String request = generateSqlRequest("local_time", dateTimeWrapper.getId());
|
||||
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
|
||||
String expectedValue = dateTimeWrapper
|
||||
.getLocalTime()
|
||||
.atDate(LocalDate.of(1970, Month.JANUARY, 1))
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.format(timeFormatter);
|
||||
|
||||
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void storeOffsetTimeWithUtcConfigShouldBeStoredOnGMTTimeZoneAccordingToHis1stJan1970Value() {
|
||||
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
|
||||
|
||||
String request = generateSqlRequest("offset_time", dateTimeWrapper.getId());
|
||||
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
|
||||
String expectedValue = dateTimeWrapper
|
||||
.getOffsetTime()
|
||||
.toLocalTime()
|
||||
.atDate(LocalDate.of(1970, Month.JANUARY, 1))
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.format(timeFormatter);
|
||||
|
||||
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void storeLocalDateWithUtcConfigShouldBeStoredWithoutTransformation() {
|
||||
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
|
||||
|
||||
String request = generateSqlRequest("local_date", dateTimeWrapper.getId());
|
||||
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
|
||||
String expectedValue = dateTimeWrapper
|
||||
.getLocalDate()
|
||||
.format(dateFormatter);
|
||||
|
||||
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
|
||||
}
|
||||
|
||||
private String generateSqlRequest(String fieldName, long id) {
|
||||
return format("SELECT %s FROM jhi_date_time_wrapper where id=%d", fieldName, id);
|
||||
}
|
||||
|
||||
private void assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(SqlRowSet sqlRowSet, String expectedValue) {
|
||||
while (sqlRowSet.next()) {
|
||||
String dbValue = sqlRowSet.getString(1);
|
||||
|
||||
assertThat(dbValue).isNotNull();
|
||||
assertThat(dbValue).isEqualTo(expectedValue);
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,20 @@
|
||||
package org.hostsharing.hsadminng.cucumber;
|
||||
|
||||
import org.hostsharing.hsadminng.HsadminNgApp;
|
||||
import cucumber.api.java.Before;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
|
||||
@SpringBootTest
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = HsadminNgApp.class)
|
||||
public class CucumberContextConfiguration {
|
||||
|
||||
@Before
|
||||
public void setup_cucumber_spring_context(){
|
||||
// Dummy method so cucumber will recognize this class as glue
|
||||
// and use its context configuration.
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,13 @@
|
||||
package org.hostsharing.hsadminng.cucumber;
|
||||
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
|
||||
import cucumber.api.CucumberOptions;
|
||||
import cucumber.api.junit.Cucumber;
|
||||
|
||||
@RunWith(Cucumber.class)
|
||||
@CucumberOptions(plugin = "pretty", features = "src/test/features")
|
||||
public class CucumberTest {
|
||||
|
||||
}
|
@@ -0,0 +1,9 @@
|
||||
package org.hostsharing.hsadminng.cucumber.stepdefs;
|
||||
|
||||
import org.springframework.test.web.servlet.ResultActions;
|
||||
|
||||
public abstract class StepDefs {
|
||||
|
||||
protected ResultActions actions;
|
||||
|
||||
}
|
@@ -0,0 +1,47 @@
|
||||
package org.hostsharing.hsadminng.cucumber.stepdefs;
|
||||
|
||||
import cucumber.api.java.Before;
|
||||
import cucumber.api.java.en.Then;
|
||||
import cucumber.api.java.en.When;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import org.hostsharing.hsadminng.web.rest.UserResource;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
public class UserStepDefs extends StepDefs {
|
||||
|
||||
@Autowired
|
||||
private UserResource userResource;
|
||||
|
||||
private MockMvc restUserMockMvc;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource).build();
|
||||
}
|
||||
|
||||
@When("I search user {string}")
|
||||
public void i_search_user(String userId) throws Throwable {
|
||||
actions = restUserMockMvc.perform(get("/api/users/" + userId)
|
||||
.accept(MediaType.APPLICATION_JSON));
|
||||
}
|
||||
|
||||
@Then("the user is found")
|
||||
public void the_user_is_found() throws Throwable {
|
||||
actions
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
|
||||
}
|
||||
|
||||
@Then("his last name is {string}")
|
||||
public void his_last_name_is(String lastName) throws Throwable {
|
||||
actions.andExpect(jsonPath("$.lastName").value(lastName));
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,165 @@
|
||||
package org.hostsharing.hsadminng.repository;
|
||||
|
||||
import org.hostsharing.hsadminng.HsadminNgApp;
|
||||
import org.hostsharing.hsadminng.config.Constants;
|
||||
import org.hostsharing.hsadminng.config.audit.AuditEventConverter;
|
||||
import org.hostsharing.hsadminng.domain.PersistentAuditEvent;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.actuate.audit.AuditEvent;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpSession;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetails;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.hostsharing.hsadminng.repository.CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH;
|
||||
|
||||
/**
|
||||
* Test class for the CustomAuditEventRepository class.
|
||||
*
|
||||
* @see CustomAuditEventRepository
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = HsadminNgApp.class)
|
||||
@Transactional
|
||||
public class CustomAuditEventRepositoryIntTest {
|
||||
|
||||
@Autowired
|
||||
private PersistenceAuditEventRepository persistenceAuditEventRepository;
|
||||
|
||||
@Autowired
|
||||
private AuditEventConverter auditEventConverter;
|
||||
|
||||
private CustomAuditEventRepository customAuditEventRepository;
|
||||
|
||||
private PersistentAuditEvent testUserEvent;
|
||||
|
||||
private PersistentAuditEvent testOtherUserEvent;
|
||||
|
||||
private PersistentAuditEvent testOldUserEvent;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
customAuditEventRepository = new CustomAuditEventRepository(persistenceAuditEventRepository, auditEventConverter);
|
||||
persistenceAuditEventRepository.deleteAll();
|
||||
Instant oneHourAgo = Instant.now().minusSeconds(3600);
|
||||
|
||||
testUserEvent = new PersistentAuditEvent();
|
||||
testUserEvent.setPrincipal("test-user");
|
||||
testUserEvent.setAuditEventType("test-type");
|
||||
testUserEvent.setAuditEventDate(oneHourAgo);
|
||||
Map<String, String> data = new HashMap<>();
|
||||
data.put("test-key", "test-value");
|
||||
testUserEvent.setData(data);
|
||||
|
||||
testOldUserEvent = new PersistentAuditEvent();
|
||||
testOldUserEvent.setPrincipal("test-user");
|
||||
testOldUserEvent.setAuditEventType("test-type");
|
||||
testOldUserEvent.setAuditEventDate(oneHourAgo.minusSeconds(10000));
|
||||
|
||||
testOtherUserEvent = new PersistentAuditEvent();
|
||||
testOtherUserEvent.setPrincipal("other-test-user");
|
||||
testOtherUserEvent.setAuditEventType("test-type");
|
||||
testOtherUserEvent.setAuditEventDate(oneHourAgo);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addAuditEvent() {
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("test-key", "test-value");
|
||||
AuditEvent event = new AuditEvent("test-user", "test-type", data);
|
||||
customAuditEventRepository.add(event);
|
||||
List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll();
|
||||
assertThat(persistentAuditEvents).hasSize(1);
|
||||
PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0);
|
||||
assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal());
|
||||
assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType());
|
||||
assertThat(persistentAuditEvent.getData()).containsKey("test-key");
|
||||
assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("test-value");
|
||||
assertThat(persistentAuditEvent.getAuditEventDate()).isEqualTo(event.getTimestamp());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addAuditEventTruncateLargeData() {
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
StringBuilder largeData = new StringBuilder();
|
||||
for (int i = 0; i < EVENT_DATA_COLUMN_MAX_LENGTH + 10; i++) {
|
||||
largeData.append("a");
|
||||
}
|
||||
data.put("test-key", largeData);
|
||||
AuditEvent event = new AuditEvent("test-user", "test-type", data);
|
||||
customAuditEventRepository.add(event);
|
||||
List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll();
|
||||
assertThat(persistentAuditEvents).hasSize(1);
|
||||
PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0);
|
||||
assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal());
|
||||
assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType());
|
||||
assertThat(persistentAuditEvent.getData()).containsKey("test-key");
|
||||
String actualData = persistentAuditEvent.getData().get("test-key");
|
||||
assertThat(actualData.length()).isEqualTo(EVENT_DATA_COLUMN_MAX_LENGTH);
|
||||
assertThat(actualData).isSubstringOf(largeData);
|
||||
assertThat(persistentAuditEvent.getAuditEventDate()).isEqualTo(event.getTimestamp());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddEventWithWebAuthenticationDetails() {
|
||||
HttpSession session = new MockHttpSession(null, "test-session-id");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setSession(session);
|
||||
request.setRemoteAddr("1.2.3.4");
|
||||
WebAuthenticationDetails details = new WebAuthenticationDetails(request);
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("test-key", details);
|
||||
AuditEvent event = new AuditEvent("test-user", "test-type", data);
|
||||
customAuditEventRepository.add(event);
|
||||
List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll();
|
||||
assertThat(persistentAuditEvents).hasSize(1);
|
||||
PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0);
|
||||
assertThat(persistentAuditEvent.getData().get("remoteAddress")).isEqualTo("1.2.3.4");
|
||||
assertThat(persistentAuditEvent.getData().get("sessionId")).isEqualTo("test-session-id");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddEventWithNullData() {
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("test-key", null);
|
||||
AuditEvent event = new AuditEvent("test-user", "test-type", data);
|
||||
customAuditEventRepository.add(event);
|
||||
List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll();
|
||||
assertThat(persistentAuditEvents).hasSize(1);
|
||||
PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0);
|
||||
assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addAuditEventWithAnonymousUser() {
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("test-key", "test-value");
|
||||
AuditEvent event = new AuditEvent(Constants.ANONYMOUS_USER, "test-type", data);
|
||||
customAuditEventRepository.add(event);
|
||||
List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll();
|
||||
assertThat(persistentAuditEvents).hasSize(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addAuditEventWithAuthorizationFailureType() {
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("test-key", "test-value");
|
||||
AuditEvent event = new AuditEvent("test-user", "AUTHORIZATION_FAILURE", data);
|
||||
customAuditEventRepository.add(event);
|
||||
List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll();
|
||||
assertThat(persistentAuditEvents).hasSize(0);
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,132 @@
|
||||
package org.hostsharing.hsadminng.repository.timezone;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
import java.time.*;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
@Table(name = "jhi_date_time_wrapper")
|
||||
public class DateTimeWrapper implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
|
||||
@SequenceGenerator(name = "sequenceGenerator")
|
||||
private Long id;
|
||||
|
||||
@Column(name = "instant")
|
||||
private Instant instant;
|
||||
|
||||
@Column(name = "local_date_time")
|
||||
private LocalDateTime localDateTime;
|
||||
|
||||
@Column(name = "offset_date_time")
|
||||
private OffsetDateTime offsetDateTime;
|
||||
|
||||
@Column(name = "zoned_date_time")
|
||||
private ZonedDateTime zonedDateTime;
|
||||
|
||||
@Column(name = "local_time")
|
||||
private LocalTime localTime;
|
||||
|
||||
@Column(name = "offset_time")
|
||||
private OffsetTime offsetTime;
|
||||
|
||||
@Column(name = "local_date")
|
||||
private LocalDate localDate;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Instant getInstant() {
|
||||
return instant;
|
||||
}
|
||||
|
||||
public void setInstant(Instant instant) {
|
||||
this.instant = instant;
|
||||
}
|
||||
|
||||
public LocalDateTime getLocalDateTime() {
|
||||
return localDateTime;
|
||||
}
|
||||
|
||||
public void setLocalDateTime(LocalDateTime localDateTime) {
|
||||
this.localDateTime = localDateTime;
|
||||
}
|
||||
|
||||
public OffsetDateTime getOffsetDateTime() {
|
||||
return offsetDateTime;
|
||||
}
|
||||
|
||||
public void setOffsetDateTime(OffsetDateTime offsetDateTime) {
|
||||
this.offsetDateTime = offsetDateTime;
|
||||
}
|
||||
|
||||
public ZonedDateTime getZonedDateTime() {
|
||||
return zonedDateTime;
|
||||
}
|
||||
|
||||
public void setZonedDateTime(ZonedDateTime zonedDateTime) {
|
||||
this.zonedDateTime = zonedDateTime;
|
||||
}
|
||||
|
||||
public LocalTime getLocalTime() {
|
||||
return localTime;
|
||||
}
|
||||
|
||||
public void setLocalTime(LocalTime localTime) {
|
||||
this.localTime = localTime;
|
||||
}
|
||||
|
||||
public OffsetTime getOffsetTime() {
|
||||
return offsetTime;
|
||||
}
|
||||
|
||||
public void setOffsetTime(OffsetTime offsetTime) {
|
||||
this.offsetTime = offsetTime;
|
||||
}
|
||||
|
||||
public LocalDate getLocalDate() {
|
||||
return localDate;
|
||||
}
|
||||
|
||||
public void setLocalDate(LocalDate localDate) {
|
||||
this.localDate = localDate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
DateTimeWrapper dateTimeWrapper = (DateTimeWrapper) o;
|
||||
return !(dateTimeWrapper.getId() == null || getId() == null) && Objects.equals(getId(), dateTimeWrapper.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "TimeZoneTest{" +
|
||||
"id=" + id +
|
||||
", instant=" + instant +
|
||||
", localDateTime=" + localDateTime +
|
||||
", offsetDateTime=" + offsetDateTime +
|
||||
", zonedDateTime=" + zonedDateTime +
|
||||
'}';
|
||||
}
|
||||
}
|
@@ -0,0 +1,12 @@
|
||||
package org.hostsharing.hsadminng.repository.timezone;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
/**
|
||||
* Spring Data JPA repository for the DateTimeWrapper entity.
|
||||
*/
|
||||
@Repository
|
||||
public interface DateTimeWrapperRepository extends JpaRepository<DateTimeWrapper, Long> {
|
||||
|
||||
}
|
@@ -0,0 +1,127 @@
|
||||
package org.hostsharing.hsadminng.security;
|
||||
|
||||
import org.hostsharing.hsadminng.HsadminNgApp;
|
||||
import org.hostsharing.hsadminng.domain.User;
|
||||
import org.hostsharing.hsadminng.repository.UserRepository;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Test class for DomainUserDetailsService.
|
||||
*
|
||||
* @see DomainUserDetailsService
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = HsadminNgApp.class)
|
||||
@Transactional
|
||||
public class DomainUserDetailsServiceIntTest {
|
||||
|
||||
private static final String USER_ONE_LOGIN = "test-user-one";
|
||||
private static final String USER_ONE_EMAIL = "test-user-one@localhost";
|
||||
private static final String USER_TWO_LOGIN = "test-user-two";
|
||||
private static final String USER_TWO_EMAIL = "test-user-two@localhost";
|
||||
private static final String USER_THREE_LOGIN = "test-user-three";
|
||||
private static final String USER_THREE_EMAIL = "test-user-three@localhost";
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private UserDetailsService domainUserDetailsService;
|
||||
|
||||
private User userOne;
|
||||
private User userTwo;
|
||||
private User userThree;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
userOne = new User();
|
||||
userOne.setLogin(USER_ONE_LOGIN);
|
||||
userOne.setPassword(RandomStringUtils.random(60));
|
||||
userOne.setActivated(true);
|
||||
userOne.setEmail(USER_ONE_EMAIL);
|
||||
userOne.setFirstName("userOne");
|
||||
userOne.setLastName("doe");
|
||||
userOne.setLangKey("en");
|
||||
userRepository.save(userOne);
|
||||
|
||||
userTwo = new User();
|
||||
userTwo.setLogin(USER_TWO_LOGIN);
|
||||
userTwo.setPassword(RandomStringUtils.random(60));
|
||||
userTwo.setActivated(true);
|
||||
userTwo.setEmail(USER_TWO_EMAIL);
|
||||
userTwo.setFirstName("userTwo");
|
||||
userTwo.setLastName("doe");
|
||||
userTwo.setLangKey("en");
|
||||
userRepository.save(userTwo);
|
||||
|
||||
userThree = new User();
|
||||
userThree.setLogin(USER_THREE_LOGIN);
|
||||
userThree.setPassword(RandomStringUtils.random(60));
|
||||
userThree.setActivated(false);
|
||||
userThree.setEmail(USER_THREE_EMAIL);
|
||||
userThree.setFirstName("userThree");
|
||||
userThree.setLastName("doe");
|
||||
userThree.setLangKey("en");
|
||||
userRepository.save(userThree);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void assertThatUserCanBeFoundByLogin() {
|
||||
UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN);
|
||||
assertThat(userDetails).isNotNull();
|
||||
assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void assertThatUserCanBeFoundByLoginIgnoreCase() {
|
||||
UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN.toUpperCase(Locale.ENGLISH));
|
||||
assertThat(userDetails).isNotNull();
|
||||
assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void assertThatUserCanBeFoundByEmail() {
|
||||
UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL);
|
||||
assertThat(userDetails).isNotNull();
|
||||
assertThat(userDetails.getUsername()).isEqualTo(USER_TWO_LOGIN);
|
||||
}
|
||||
|
||||
@Test(expected = UsernameNotFoundException.class)
|
||||
@Transactional
|
||||
public void assertThatUserCanNotBeFoundByEmailIgnoreCase() {
|
||||
domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL.toUpperCase(Locale.ENGLISH));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void assertThatEmailIsPrioritizedOverLogin() {
|
||||
UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_EMAIL);
|
||||
assertThat(userDetails).isNotNull();
|
||||
assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN);
|
||||
}
|
||||
|
||||
@Test(expected = UserNotActivatedException.class)
|
||||
@Transactional
|
||||
public void assertThatUserNotActivatedExceptionIsThrownForNotActivatedUsers() {
|
||||
domainUserDetailsService.loadUserByUsername(USER_THREE_LOGIN);
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,73 @@
|
||||
package org.hostsharing.hsadminng.security;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Test class for the SecurityUtils utility class.
|
||||
*
|
||||
* @see SecurityUtils
|
||||
*/
|
||||
public class SecurityUtilsUnitTest {
|
||||
|
||||
@Test
|
||||
public void testgetCurrentUserLogin() {
|
||||
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
|
||||
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
Optional<String> login = SecurityUtils.getCurrentUserLogin();
|
||||
assertThat(login).contains("admin");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testgetCurrentUserJWT() {
|
||||
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
|
||||
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "token"));
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
Optional<String> jwt = SecurityUtils.getCurrentUserJWT();
|
||||
assertThat(jwt).contains("token");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsAuthenticated() {
|
||||
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
|
||||
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
boolean isAuthenticated = SecurityUtils.isAuthenticated();
|
||||
assertThat(isAuthenticated).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAnonymousIsNotAuthenticated() {
|
||||
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
|
||||
Collection<GrantedAuthority> authorities = new ArrayList<>();
|
||||
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
|
||||
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities));
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
boolean isAuthenticated = SecurityUtils.isAuthenticated();
|
||||
assertThat(isAuthenticated).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsCurrentUserInRole() {
|
||||
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
|
||||
Collection<GrantedAuthority> authorities = new ArrayList<>();
|
||||
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
|
||||
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("user", "user", authorities));
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
|
||||
assertThat(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.USER)).isTrue();
|
||||
assertThat(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN)).isFalse();
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,115 @@
|
||||
package org.hostsharing.hsadminng.security.jwt;
|
||||
|
||||
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
|
||||
import io.github.jhipster.config.JHipsterProperties;
|
||||
import io.jsonwebtoken.io.Decoders;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class JWTFilterTest {
|
||||
|
||||
private TokenProvider tokenProvider;
|
||||
|
||||
private JWTFilter jwtFilter;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
JHipsterProperties jHipsterProperties = new JHipsterProperties();
|
||||
tokenProvider = new TokenProvider(jHipsterProperties);
|
||||
ReflectionTestUtils.setField(tokenProvider, "key",
|
||||
Keys.hmacShaKeyFor(Decoders.BASE64
|
||||
.decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")));
|
||||
|
||||
ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", 60000);
|
||||
jwtFilter = new JWTFilter(tokenProvider);
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJWTFilter() throws Exception {
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
|
||||
"test-user",
|
||||
"test-password",
|
||||
Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
|
||||
);
|
||||
String jwt = tokenProvider.createToken(authentication, false);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
|
||||
request.setRequestURI("/api/test");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain filterChain = new MockFilterChain();
|
||||
jwtFilter.doFilter(request, response, filterChain);
|
||||
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user");
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJWTFilterInvalidToken() throws Exception {
|
||||
String jwt = "wrong_jwt";
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
|
||||
request.setRequestURI("/api/test");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain filterChain = new MockFilterChain();
|
||||
jwtFilter.doFilter(request, response, filterChain);
|
||||
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJWTFilterMissingAuthorization() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/api/test");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain filterChain = new MockFilterChain();
|
||||
jwtFilter.doFilter(request, response, filterChain);
|
||||
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJWTFilterMissingToken() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer ");
|
||||
request.setRequestURI("/api/test");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain filterChain = new MockFilterChain();
|
||||
jwtFilter.doFilter(request, response, filterChain);
|
||||
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJWTFilterWrongScheme() throws Exception {
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
|
||||
"test-user",
|
||||
"test-password",
|
||||
Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
|
||||
);
|
||||
String jwt = tokenProvider.createToken(authentication, false);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt);
|
||||
request.setRequestURI("/api/test");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain filterChain = new MockFilterChain();
|
||||
jwtFilter.doFilter(request, response, filterChain);
|
||||
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,111 @@
|
||||
package org.hostsharing.hsadminng.security.jwt;
|
||||
|
||||
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
|
||||
|
||||
import java.security.Key;
|
||||
import java.util.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import io.github.jhipster.config.JHipsterProperties;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import io.jsonwebtoken.io.Decoders;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TokenProviderTest {
|
||||
|
||||
private final long ONE_MINUTE = 60000;
|
||||
private Key key;
|
||||
private JHipsterProperties jHipsterProperties;
|
||||
private TokenProvider tokenProvider;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
jHipsterProperties = Mockito.mock(JHipsterProperties.class);
|
||||
tokenProvider = new TokenProvider(jHipsterProperties);
|
||||
key = Keys.hmacShaKeyFor(Decoders.BASE64
|
||||
.decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));
|
||||
|
||||
ReflectionTestUtils.setField(tokenProvider, "key", key);
|
||||
ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", ONE_MINUTE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReturnFalseWhenJWThasInvalidSignature() {
|
||||
boolean isTokenValid = tokenProvider.validateToken(createTokenWithDifferentSignature());
|
||||
|
||||
assertThat(isTokenValid).isEqualTo(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReturnFalseWhenJWTisMalformed() {
|
||||
Authentication authentication = createAuthentication();
|
||||
String token = tokenProvider.createToken(authentication, false);
|
||||
String invalidToken = token.substring(1);
|
||||
boolean isTokenValid = tokenProvider.validateToken(invalidToken);
|
||||
|
||||
assertThat(isTokenValid).isEqualTo(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReturnFalseWhenJWTisExpired() {
|
||||
ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", -ONE_MINUTE);
|
||||
|
||||
Authentication authentication = createAuthentication();
|
||||
String token = tokenProvider.createToken(authentication, false);
|
||||
|
||||
boolean isTokenValid = tokenProvider.validateToken(token);
|
||||
|
||||
assertThat(isTokenValid).isEqualTo(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReturnFalseWhenJWTisUnsupported() {
|
||||
String unsupportedToken = createUnsupportedToken();
|
||||
|
||||
boolean isTokenValid = tokenProvider.validateToken(unsupportedToken);
|
||||
|
||||
assertThat(isTokenValid).isEqualTo(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReturnFalseWhenJWTisInvalid() {
|
||||
boolean isTokenValid = tokenProvider.validateToken("");
|
||||
|
||||
assertThat(isTokenValid).isEqualTo(false);
|
||||
}
|
||||
|
||||
private Authentication createAuthentication() {
|
||||
Collection<GrantedAuthority> authorities = new ArrayList<>();
|
||||
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
|
||||
return new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities);
|
||||
}
|
||||
|
||||
private String createUnsupportedToken() {
|
||||
return Jwts.builder()
|
||||
.setPayload("payload")
|
||||
.signWith(key, SignatureAlgorithm.HS512)
|
||||
.compact();
|
||||
}
|
||||
|
||||
private String createTokenWithDifferentSignature() {
|
||||
Key otherKey = Keys.hmacShaKeyFor(Decoders.BASE64
|
||||
.decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));
|
||||
|
||||
return Jwts.builder()
|
||||
.setSubject("anonymous")
|
||||
.signWith(otherKey, SignatureAlgorithm.HS512)
|
||||
.setExpiration(new Date(new Date().getTime() + ONE_MINUTE))
|
||||
.compact();
|
||||
}
|
||||
}
|
@@ -0,0 +1,187 @@
|
||||
package org.hostsharing.hsadminng.service;
|
||||
import org.hostsharing.hsadminng.config.Constants;
|
||||
|
||||
import org.hostsharing.hsadminng.HsadminNgApp;
|
||||
import org.hostsharing.hsadminng.domain.User;
|
||||
import io.github.jhipster.config.JHipsterProperties;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Captor;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.mockito.Spy;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.mail.MailSendException;
|
||||
import org.springframework.mail.javamail.JavaMailSenderImpl;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.thymeleaf.spring5.SpringTemplateEngine;
|
||||
|
||||
import javax.mail.Multipart;
|
||||
import javax.mail.internet.MimeBodyPart;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import javax.mail.internet.MimeMultipart;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = HsadminNgApp.class)
|
||||
public class MailServiceIntTest {
|
||||
|
||||
@Autowired
|
||||
private JHipsterProperties jHipsterProperties;
|
||||
|
||||
@Autowired
|
||||
private MessageSource messageSource;
|
||||
|
||||
@Autowired
|
||||
private SpringTemplateEngine templateEngine;
|
||||
|
||||
@Spy
|
||||
private JavaMailSenderImpl javaMailSender;
|
||||
|
||||
@Captor
|
||||
private ArgumentCaptor<MimeMessage> messageCaptor;
|
||||
|
||||
private MailService mailService;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
doNothing().when(javaMailSender).send(any(MimeMessage.class));
|
||||
mailService = new MailService(jHipsterProperties, javaMailSender, messageSource, templateEngine);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendEmail() throws Exception {
|
||||
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false);
|
||||
verify(javaMailSender).send(messageCaptor.capture());
|
||||
MimeMessage message = messageCaptor.getValue();
|
||||
assertThat(message.getSubject()).isEqualTo("testSubject");
|
||||
assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com");
|
||||
assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
|
||||
assertThat(message.getContent()).isInstanceOf(String.class);
|
||||
assertThat(message.getContent().toString()).isEqualTo("testContent");
|
||||
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendHtmlEmail() throws Exception {
|
||||
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, true);
|
||||
verify(javaMailSender).send(messageCaptor.capture());
|
||||
MimeMessage message = messageCaptor.getValue();
|
||||
assertThat(message.getSubject()).isEqualTo("testSubject");
|
||||
assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com");
|
||||
assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
|
||||
assertThat(message.getContent()).isInstanceOf(String.class);
|
||||
assertThat(message.getContent().toString()).isEqualTo("testContent");
|
||||
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendMultipartEmail() throws Exception {
|
||||
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, false);
|
||||
verify(javaMailSender).send(messageCaptor.capture());
|
||||
MimeMessage message = messageCaptor.getValue();
|
||||
MimeMultipart mp = (MimeMultipart) message.getContent();
|
||||
MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
|
||||
ByteArrayOutputStream aos = new ByteArrayOutputStream();
|
||||
part.writeTo(aos);
|
||||
assertThat(message.getSubject()).isEqualTo("testSubject");
|
||||
assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com");
|
||||
assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
|
||||
assertThat(message.getContent()).isInstanceOf(Multipart.class);
|
||||
assertThat(aos.toString()).isEqualTo("\r\ntestContent");
|
||||
assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendMultipartHtmlEmail() throws Exception {
|
||||
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, true);
|
||||
verify(javaMailSender).send(messageCaptor.capture());
|
||||
MimeMessage message = messageCaptor.getValue();
|
||||
MimeMultipart mp = (MimeMultipart) message.getContent();
|
||||
MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
|
||||
ByteArrayOutputStream aos = new ByteArrayOutputStream();
|
||||
part.writeTo(aos);
|
||||
assertThat(message.getSubject()).isEqualTo("testSubject");
|
||||
assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com");
|
||||
assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
|
||||
assertThat(message.getContent()).isInstanceOf(Multipart.class);
|
||||
assertThat(aos.toString()).isEqualTo("\r\ntestContent");
|
||||
assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendEmailFromTemplate() throws Exception {
|
||||
User user = new User();
|
||||
user.setLogin("john");
|
||||
user.setEmail("john.doe@example.com");
|
||||
user.setLangKey("en");
|
||||
mailService.sendEmailFromTemplate(user, "mail/testEmail", "email.test.title");
|
||||
verify(javaMailSender).send(messageCaptor.capture());
|
||||
MimeMessage message = messageCaptor.getValue();
|
||||
assertThat(message.getSubject()).isEqualTo("test title");
|
||||
assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail());
|
||||
assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
|
||||
assertThat(message.getContent().toString()).isEqualToNormalizingNewlines("<html>test title, http://127.0.0.1:8080, john</html>\n");
|
||||
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendActivationEmail() throws Exception {
|
||||
User user = new User();
|
||||
user.setLangKey(Constants.DEFAULT_LANGUAGE);
|
||||
user.setLogin("john");
|
||||
user.setEmail("john.doe@example.com");
|
||||
mailService.sendActivationEmail(user);
|
||||
verify(javaMailSender).send(messageCaptor.capture());
|
||||
MimeMessage message = messageCaptor.getValue();
|
||||
assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail());
|
||||
assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
|
||||
assertThat(message.getContent().toString()).isNotEmpty();
|
||||
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreationEmail() throws Exception {
|
||||
User user = new User();
|
||||
user.setLangKey(Constants.DEFAULT_LANGUAGE);
|
||||
user.setLogin("john");
|
||||
user.setEmail("john.doe@example.com");
|
||||
mailService.sendCreationEmail(user);
|
||||
verify(javaMailSender).send(messageCaptor.capture());
|
||||
MimeMessage message = messageCaptor.getValue();
|
||||
assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail());
|
||||
assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
|
||||
assertThat(message.getContent().toString()).isNotEmpty();
|
||||
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendPasswordResetMail() throws Exception {
|
||||
User user = new User();
|
||||
user.setLangKey(Constants.DEFAULT_LANGUAGE);
|
||||
user.setLogin("john");
|
||||
user.setEmail("john.doe@example.com");
|
||||
mailService.sendPasswordResetMail(user);
|
||||
verify(javaMailSender).send(messageCaptor.capture());
|
||||
MimeMessage message = messageCaptor.getValue();
|
||||
assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail());
|
||||
assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
|
||||
assertThat(message.getContent().toString()).isNotEmpty();
|
||||
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendEmailWithException() throws Exception {
|
||||
doThrow(MailSendException.class).when(javaMailSender).send(any(MimeMessage.class));
|
||||
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false);
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,192 @@
|
||||
package org.hostsharing.hsadminng.service;
|
||||
|
||||
import org.hostsharing.hsadminng.HsadminNgApp;
|
||||
import org.hostsharing.hsadminng.config.Constants;
|
||||
import org.hostsharing.hsadminng.domain.User;
|
||||
import org.hostsharing.hsadminng.repository.UserRepository;
|
||||
import org.hostsharing.hsadminng.service.dto.UserDTO;
|
||||
import org.hostsharing.hsadminng.service.util.RandomUtil;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.data.auditing.AuditingHandler;
|
||||
import org.springframework.data.auditing.DateTimeProvider;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Optional;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Test class for the UserResource REST controller.
|
||||
*
|
||||
* @see UserService
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = HsadminNgApp.class)
|
||||
@Transactional
|
||||
public class UserServiceIntTest {
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Autowired
|
||||
private AuditingHandler auditingHandler;
|
||||
|
||||
@Mock
|
||||
DateTimeProvider dateTimeProvider;
|
||||
|
||||
private User user;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
user = new User();
|
||||
user.setLogin("johndoe");
|
||||
user.setPassword(RandomStringUtils.random(60));
|
||||
user.setActivated(true);
|
||||
user.setEmail("johndoe@localhost");
|
||||
user.setFirstName("john");
|
||||
user.setLastName("doe");
|
||||
user.setImageUrl("http://placehold.it/50x50");
|
||||
user.setLangKey("en");
|
||||
|
||||
when(dateTimeProvider.getNow()).thenReturn(Optional.of(LocalDateTime.now()));
|
||||
auditingHandler.setDateTimeProvider(dateTimeProvider);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void assertThatUserMustExistToResetPassword() {
|
||||
userRepository.saveAndFlush(user);
|
||||
Optional<User> maybeUser = userService.requestPasswordReset("invalid.login@localhost");
|
||||
assertThat(maybeUser).isNotPresent();
|
||||
|
||||
maybeUser = userService.requestPasswordReset(user.getEmail());
|
||||
assertThat(maybeUser).isPresent();
|
||||
assertThat(maybeUser.orElse(null).getEmail()).isEqualTo(user.getEmail());
|
||||
assertThat(maybeUser.orElse(null).getResetDate()).isNotNull();
|
||||
assertThat(maybeUser.orElse(null).getResetKey()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void assertThatOnlyActivatedUserCanRequestPasswordReset() {
|
||||
user.setActivated(false);
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
Optional<User> maybeUser = userService.requestPasswordReset(user.getLogin());
|
||||
assertThat(maybeUser).isNotPresent();
|
||||
userRepository.delete(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void assertThatResetKeyMustNotBeOlderThan24Hours() {
|
||||
Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
|
||||
String resetKey = RandomUtil.generateResetKey();
|
||||
user.setActivated(true);
|
||||
user.setResetDate(daysAgo);
|
||||
user.setResetKey(resetKey);
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
|
||||
assertThat(maybeUser).isNotPresent();
|
||||
userRepository.delete(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void assertThatResetKeyMustBeValid() {
|
||||
Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
|
||||
user.setActivated(true);
|
||||
user.setResetDate(daysAgo);
|
||||
user.setResetKey("1234");
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
|
||||
assertThat(maybeUser).isNotPresent();
|
||||
userRepository.delete(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void assertThatUserCanResetPassword() {
|
||||
String oldPassword = user.getPassword();
|
||||
Instant daysAgo = Instant.now().minus(2, ChronoUnit.HOURS);
|
||||
String resetKey = RandomUtil.generateResetKey();
|
||||
user.setActivated(true);
|
||||
user.setResetDate(daysAgo);
|
||||
user.setResetKey(resetKey);
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
|
||||
assertThat(maybeUser).isPresent();
|
||||
assertThat(maybeUser.orElse(null).getResetDate()).isNull();
|
||||
assertThat(maybeUser.orElse(null).getResetKey()).isNull();
|
||||
assertThat(maybeUser.orElse(null).getPassword()).isNotEqualTo(oldPassword);
|
||||
|
||||
userRepository.delete(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testFindNotActivatedUsersByCreationDateBefore() {
|
||||
Instant now = Instant.now();
|
||||
when(dateTimeProvider.getNow()).thenReturn(Optional.of(now.minus(4, ChronoUnit.DAYS)));
|
||||
user.setActivated(false);
|
||||
User dbUser = userRepository.saveAndFlush(user);
|
||||
dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS));
|
||||
userRepository.saveAndFlush(user);
|
||||
List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS));
|
||||
assertThat(users).isNotEmpty();
|
||||
userService.removeNotActivatedUsers();
|
||||
users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS));
|
||||
assertThat(users).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void assertThatAnonymousUserIsNotGet() {
|
||||
user.setLogin(Constants.ANONYMOUS_USER);
|
||||
if (!userRepository.findOneByLogin(Constants.ANONYMOUS_USER).isPresent()) {
|
||||
userRepository.saveAndFlush(user);
|
||||
}
|
||||
final PageRequest pageable = PageRequest.of(0, (int) userRepository.count());
|
||||
final Page<UserDTO> allManagedUsers = userService.getAllManagedUsers(pageable);
|
||||
assertThat(allManagedUsers.getContent().stream()
|
||||
.noneMatch(user -> Constants.ANONYMOUS_USER.equals(user.getLogin())))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testRemoveNotActivatedUsers() {
|
||||
// custom "now" for audit to use as creation date
|
||||
when(dateTimeProvider.getNow()).thenReturn(Optional.of(Instant.now().minus(30, ChronoUnit.DAYS)));
|
||||
|
||||
user.setActivated(false);
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
assertThat(userRepository.findOneByLogin("johndoe")).isPresent();
|
||||
userService.removeNotActivatedUsers();
|
||||
assertThat(userRepository.findOneByLogin("johndoe")).isNotPresent();
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,150 @@
|
||||
package org.hostsharing.hsadminng.service.mapper;
|
||||
|
||||
|
||||
import org.hostsharing.hsadminng.HsadminNgApp;
|
||||
import org.hostsharing.hsadminng.domain.User;
|
||||
import org.hostsharing.hsadminng.service.dto.UserDTO;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Test class for the UserMapper.
|
||||
*
|
||||
* @see UserMapper
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = HsadminNgApp.class)
|
||||
public class UserMapperTest {
|
||||
|
||||
private static final String DEFAULT_LOGIN = "johndoe";
|
||||
|
||||
@Autowired
|
||||
private UserMapper userMapper;
|
||||
|
||||
private User user;
|
||||
private UserDTO userDto;
|
||||
|
||||
private static final Long DEFAULT_ID = 1L;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
user = new User();
|
||||
user.setLogin(DEFAULT_LOGIN);
|
||||
user.setPassword(RandomStringUtils.random(60));
|
||||
user.setActivated(true);
|
||||
user.setEmail("johndoe@localhost");
|
||||
user.setFirstName("john");
|
||||
user.setLastName("doe");
|
||||
user.setImageUrl("image_url");
|
||||
user.setLangKey("en");
|
||||
|
||||
userDto = new UserDTO(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usersToUserDTOsShouldMapOnlyNonNullUsers(){
|
||||
List<User> users = new ArrayList<>();
|
||||
users.add(user);
|
||||
users.add(null);
|
||||
|
||||
List<UserDTO> userDTOS = userMapper.usersToUserDTOs(users);
|
||||
|
||||
assertThat(userDTOS).isNotEmpty();
|
||||
assertThat(userDTOS).size().isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void userDTOsToUsersShouldMapOnlyNonNullUsers(){
|
||||
List<UserDTO> usersDto = new ArrayList<>();
|
||||
usersDto.add(userDto);
|
||||
usersDto.add(null);
|
||||
|
||||
List<User> users = userMapper.userDTOsToUsers(usersDto);
|
||||
|
||||
assertThat(users).isNotEmpty();
|
||||
assertThat(users).size().isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void userDTOsToUsersWithAuthoritiesStringShouldMapToUsersWithAuthoritiesDomain(){
|
||||
Set<String> authoritiesAsString = new HashSet<>();
|
||||
authoritiesAsString.add("ADMIN");
|
||||
userDto.setAuthorities(authoritiesAsString);
|
||||
|
||||
List<UserDTO> usersDto = new ArrayList<>();
|
||||
usersDto.add(userDto);
|
||||
|
||||
List<User> users = userMapper.userDTOsToUsers(usersDto);
|
||||
|
||||
assertThat(users).isNotEmpty();
|
||||
assertThat(users).size().isEqualTo(1);
|
||||
assertThat(users.get(0).getAuthorities()).isNotNull();
|
||||
assertThat(users.get(0).getAuthorities()).isNotEmpty();
|
||||
assertThat(users.get(0).getAuthorities().iterator().next().getName()).isEqualTo("ADMIN");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void userDTOsToUsersMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities(){
|
||||
userDto.setAuthorities(null);
|
||||
|
||||
List<UserDTO> usersDto = new ArrayList<>();
|
||||
usersDto.add(userDto);
|
||||
|
||||
List<User> users = userMapper.userDTOsToUsers(usersDto);
|
||||
|
||||
assertThat(users).isNotEmpty();
|
||||
assertThat(users).size().isEqualTo(1);
|
||||
assertThat(users.get(0).getAuthorities()).isNotNull();
|
||||
assertThat(users.get(0).getAuthorities()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void userDTOToUserMapWithAuthoritiesStringShouldReturnUserWithAuthorities(){
|
||||
Set<String> authoritiesAsString = new HashSet<>();
|
||||
authoritiesAsString.add("ADMIN");
|
||||
userDto.setAuthorities(authoritiesAsString);
|
||||
|
||||
userDto.setAuthorities(authoritiesAsString);
|
||||
|
||||
User user = userMapper.userDTOToUser(userDto);
|
||||
|
||||
assertThat(user).isNotNull();
|
||||
assertThat(user.getAuthorities()).isNotNull();
|
||||
assertThat(user.getAuthorities()).isNotEmpty();
|
||||
assertThat(user.getAuthorities().iterator().next().getName()).isEqualTo("ADMIN");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void userDTOToUserMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities(){
|
||||
userDto.setAuthorities(null);
|
||||
|
||||
User user = userMapper.userDTOToUser(userDto);
|
||||
|
||||
assertThat(user).isNotNull();
|
||||
assertThat(user.getAuthorities()).isNotNull();
|
||||
assertThat(user.getAuthorities()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void userDTOToUserMapWithNullUserShouldReturnNull(){
|
||||
assertThat(userMapper.userDTOToUser(null)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUserFromId() {
|
||||
assertThat(userMapper.userFromId(DEFAULT_ID).getId()).isEqualTo(DEFAULT_ID);
|
||||
assertThat(userMapper.userFromId(null)).isNull();
|
||||
}
|
||||
}
|
@@ -0,0 +1,818 @@
|
||||
package org.hostsharing.hsadminng.web.rest;
|
||||
|
||||
import org.hostsharing.hsadminng.HsadminNgApp;
|
||||
import org.hostsharing.hsadminng.config.Constants;
|
||||
import org.hostsharing.hsadminng.domain.Authority;
|
||||
import org.hostsharing.hsadminng.domain.User;
|
||||
import org.hostsharing.hsadminng.repository.AuthorityRepository;
|
||||
import org.hostsharing.hsadminng.repository.UserRepository;
|
||||
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
|
||||
import org.hostsharing.hsadminng.service.MailService;
|
||||
import org.hostsharing.hsadminng.service.UserService;
|
||||
import org.hostsharing.hsadminng.service.dto.PasswordChangeDTO;
|
||||
import org.hostsharing.hsadminng.service.dto.UserDTO;
|
||||
import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator;
|
||||
import org.hostsharing.hsadminng.web.rest.vm.KeyAndPasswordVM;
|
||||
import org.hostsharing.hsadminng.web.rest.vm.ManagedUserVM;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doNothing;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
/**
|
||||
* Test class for the AccountResource REST controller.
|
||||
*
|
||||
* @see AccountResource
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = HsadminNgApp.class)
|
||||
public class AccountResourceIntTest {
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private AuthorityRepository authorityRepository;
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
@Autowired
|
||||
private HttpMessageConverter<?>[] httpMessageConverters;
|
||||
|
||||
@Autowired
|
||||
private ExceptionTranslator exceptionTranslator;
|
||||
|
||||
@Mock
|
||||
private UserService mockUserService;
|
||||
|
||||
@Mock
|
||||
private MailService mockMailService;
|
||||
|
||||
private MockMvc restMvc;
|
||||
|
||||
private MockMvc restUserMockMvc;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
doNothing().when(mockMailService).sendActivationEmail(any());
|
||||
AccountResource accountResource =
|
||||
new AccountResource(userRepository, userService, mockMailService);
|
||||
|
||||
AccountResource accountUserMockResource =
|
||||
new AccountResource(userRepository, mockUserService, mockMailService);
|
||||
this.restMvc = MockMvcBuilders.standaloneSetup(accountResource)
|
||||
.setMessageConverters(httpMessageConverters)
|
||||
.setControllerAdvice(exceptionTranslator)
|
||||
.build();
|
||||
this.restUserMockMvc = MockMvcBuilders.standaloneSetup(accountUserMockResource)
|
||||
.setControllerAdvice(exceptionTranslator)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNonAuthenticatedUser() throws Exception {
|
||||
restUserMockMvc.perform(get("/api/authenticate")
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAuthenticatedUser() throws Exception {
|
||||
restUserMockMvc.perform(get("/api/authenticate")
|
||||
.with(request -> {
|
||||
request.setRemoteUser("test");
|
||||
return request;
|
||||
})
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("test"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetExistingAccount() throws Exception {
|
||||
Set<Authority> authorities = new HashSet<>();
|
||||
Authority authority = new Authority();
|
||||
authority.setName(AuthoritiesConstants.ADMIN);
|
||||
authorities.add(authority);
|
||||
|
||||
User user = new User();
|
||||
user.setLogin("test");
|
||||
user.setFirstName("john");
|
||||
user.setLastName("doe");
|
||||
user.setEmail("john.doe@jhipster.com");
|
||||
user.setImageUrl("http://placehold.it/50x50");
|
||||
user.setLangKey("en");
|
||||
user.setAuthorities(authorities);
|
||||
when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.of(user));
|
||||
|
||||
restUserMockMvc.perform(get("/api/account")
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
|
||||
.andExpect(jsonPath("$.login").value("test"))
|
||||
.andExpect(jsonPath("$.firstName").value("john"))
|
||||
.andExpect(jsonPath("$.lastName").value("doe"))
|
||||
.andExpect(jsonPath("$.email").value("john.doe@jhipster.com"))
|
||||
.andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50"))
|
||||
.andExpect(jsonPath("$.langKey").value("en"))
|
||||
.andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetUnknownAccount() throws Exception {
|
||||
when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.empty());
|
||||
|
||||
restUserMockMvc.perform(get("/api/account")
|
||||
.accept(MediaType.APPLICATION_PROBLEM_JSON))
|
||||
.andExpect(status().isInternalServerError());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testRegisterValid() throws Exception {
|
||||
ManagedUserVM validUser = new ManagedUserVM();
|
||||
validUser.setLogin("test-register-valid");
|
||||
validUser.setPassword("password");
|
||||
validUser.setFirstName("Alice");
|
||||
validUser.setLastName("Test");
|
||||
validUser.setEmail("test-register-valid@example.com");
|
||||
validUser.setImageUrl("http://placehold.it/50x50");
|
||||
validUser.setLangKey(Constants.DEFAULT_LANGUAGE);
|
||||
validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
|
||||
assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isFalse();
|
||||
|
||||
restMvc.perform(
|
||||
post("/api/register")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(validUser)))
|
||||
.andExpect(status().isCreated());
|
||||
|
||||
assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testRegisterInvalidLogin() throws Exception {
|
||||
ManagedUserVM invalidUser = new ManagedUserVM();
|
||||
invalidUser.setLogin("funky-log!n");// <-- invalid
|
||||
invalidUser.setPassword("password");
|
||||
invalidUser.setFirstName("Funky");
|
||||
invalidUser.setLastName("One");
|
||||
invalidUser.setEmail("funky@example.com");
|
||||
invalidUser.setActivated(true);
|
||||
invalidUser.setImageUrl("http://placehold.it/50x50");
|
||||
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
|
||||
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
|
||||
|
||||
restUserMockMvc.perform(
|
||||
post("/api/register")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
Optional<User> user = userRepository.findOneByEmailIgnoreCase("funky@example.com");
|
||||
assertThat(user.isPresent()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testRegisterInvalidEmail() throws Exception {
|
||||
ManagedUserVM invalidUser = new ManagedUserVM();
|
||||
invalidUser.setLogin("bob");
|
||||
invalidUser.setPassword("password");
|
||||
invalidUser.setFirstName("Bob");
|
||||
invalidUser.setLastName("Green");
|
||||
invalidUser.setEmail("invalid");// <-- invalid
|
||||
invalidUser.setActivated(true);
|
||||
invalidUser.setImageUrl("http://placehold.it/50x50");
|
||||
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
|
||||
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
|
||||
|
||||
restUserMockMvc.perform(
|
||||
post("/api/register")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
Optional<User> user = userRepository.findOneByLogin("bob");
|
||||
assertThat(user.isPresent()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testRegisterInvalidPassword() throws Exception {
|
||||
ManagedUserVM invalidUser = new ManagedUserVM();
|
||||
invalidUser.setLogin("bob");
|
||||
invalidUser.setPassword("123");// password with only 3 digits
|
||||
invalidUser.setFirstName("Bob");
|
||||
invalidUser.setLastName("Green");
|
||||
invalidUser.setEmail("bob@example.com");
|
||||
invalidUser.setActivated(true);
|
||||
invalidUser.setImageUrl("http://placehold.it/50x50");
|
||||
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
|
||||
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
|
||||
|
||||
restUserMockMvc.perform(
|
||||
post("/api/register")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
Optional<User> user = userRepository.findOneByLogin("bob");
|
||||
assertThat(user.isPresent()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testRegisterNullPassword() throws Exception {
|
||||
ManagedUserVM invalidUser = new ManagedUserVM();
|
||||
invalidUser.setLogin("bob");
|
||||
invalidUser.setPassword(null);// invalid null password
|
||||
invalidUser.setFirstName("Bob");
|
||||
invalidUser.setLastName("Green");
|
||||
invalidUser.setEmail("bob@example.com");
|
||||
invalidUser.setActivated(true);
|
||||
invalidUser.setImageUrl("http://placehold.it/50x50");
|
||||
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
|
||||
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
|
||||
|
||||
restUserMockMvc.perform(
|
||||
post("/api/register")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
Optional<User> user = userRepository.findOneByLogin("bob");
|
||||
assertThat(user.isPresent()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testRegisterDuplicateLogin() throws Exception {
|
||||
// First registration
|
||||
ManagedUserVM firstUser = new ManagedUserVM();
|
||||
firstUser.setLogin("alice");
|
||||
firstUser.setPassword("password");
|
||||
firstUser.setFirstName("Alice");
|
||||
firstUser.setLastName("Something");
|
||||
firstUser.setEmail("alice@example.com");
|
||||
firstUser.setImageUrl("http://placehold.it/50x50");
|
||||
firstUser.setLangKey(Constants.DEFAULT_LANGUAGE);
|
||||
firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
|
||||
|
||||
// Duplicate login, different email
|
||||
ManagedUserVM secondUser = new ManagedUserVM();
|
||||
secondUser.setLogin(firstUser.getLogin());
|
||||
secondUser.setPassword(firstUser.getPassword());
|
||||
secondUser.setFirstName(firstUser.getFirstName());
|
||||
secondUser.setLastName(firstUser.getLastName());
|
||||
secondUser.setEmail("alice2@example.com");
|
||||
secondUser.setImageUrl(firstUser.getImageUrl());
|
||||
secondUser.setLangKey(firstUser.getLangKey());
|
||||
secondUser.setCreatedBy(firstUser.getCreatedBy());
|
||||
secondUser.setCreatedDate(firstUser.getCreatedDate());
|
||||
secondUser.setLastModifiedBy(firstUser.getLastModifiedBy());
|
||||
secondUser.setLastModifiedDate(firstUser.getLastModifiedDate());
|
||||
secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities()));
|
||||
|
||||
// First user
|
||||
restMvc.perform(
|
||||
post("/api/register")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(firstUser)))
|
||||
.andExpect(status().isCreated());
|
||||
|
||||
// Second (non activated) user
|
||||
restMvc.perform(
|
||||
post("/api/register")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
|
||||
.andExpect(status().isCreated());
|
||||
|
||||
Optional<User> testUser = userRepository.findOneByEmailIgnoreCase("alice2@example.com");
|
||||
assertThat(testUser.isPresent()).isTrue();
|
||||
testUser.get().setActivated(true);
|
||||
userRepository.save(testUser.get());
|
||||
|
||||
// Second (already activated) user
|
||||
restMvc.perform(
|
||||
post("/api/register")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
|
||||
.andExpect(status().is4xxClientError());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testRegisterDuplicateEmail() throws Exception {
|
||||
// First user
|
||||
ManagedUserVM firstUser = new ManagedUserVM();
|
||||
firstUser.setLogin("test-register-duplicate-email");
|
||||
firstUser.setPassword("password");
|
||||
firstUser.setFirstName("Alice");
|
||||
firstUser.setLastName("Test");
|
||||
firstUser.setEmail("test-register-duplicate-email@example.com");
|
||||
firstUser.setImageUrl("http://placehold.it/50x50");
|
||||
firstUser.setLangKey(Constants.DEFAULT_LANGUAGE);
|
||||
firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
|
||||
|
||||
// Register first user
|
||||
restMvc.perform(
|
||||
post("/api/register")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(firstUser)))
|
||||
.andExpect(status().isCreated());
|
||||
|
||||
Optional<User> testUser1 = userRepository.findOneByLogin("test-register-duplicate-email");
|
||||
assertThat(testUser1.isPresent()).isTrue();
|
||||
|
||||
// Duplicate email, different login
|
||||
ManagedUserVM secondUser = new ManagedUserVM();
|
||||
secondUser.setLogin("test-register-duplicate-email-2");
|
||||
secondUser.setPassword(firstUser.getPassword());
|
||||
secondUser.setFirstName(firstUser.getFirstName());
|
||||
secondUser.setLastName(firstUser.getLastName());
|
||||
secondUser.setEmail(firstUser.getEmail());
|
||||
secondUser.setImageUrl(firstUser.getImageUrl());
|
||||
secondUser.setLangKey(firstUser.getLangKey());
|
||||
secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities()));
|
||||
|
||||
// Register second (non activated) user
|
||||
restMvc.perform(
|
||||
post("/api/register")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
|
||||
.andExpect(status().isCreated());
|
||||
|
||||
Optional<User> testUser2 = userRepository.findOneByLogin("test-register-duplicate-email");
|
||||
assertThat(testUser2.isPresent()).isFalse();
|
||||
|
||||
Optional<User> testUser3 = userRepository.findOneByLogin("test-register-duplicate-email-2");
|
||||
assertThat(testUser3.isPresent()).isTrue();
|
||||
|
||||
// Duplicate email - with uppercase email address
|
||||
ManagedUserVM userWithUpperCaseEmail = new ManagedUserVM();
|
||||
userWithUpperCaseEmail.setId(firstUser.getId());
|
||||
userWithUpperCaseEmail.setLogin("test-register-duplicate-email-3");
|
||||
userWithUpperCaseEmail.setPassword(firstUser.getPassword());
|
||||
userWithUpperCaseEmail.setFirstName(firstUser.getFirstName());
|
||||
userWithUpperCaseEmail.setLastName(firstUser.getLastName());
|
||||
userWithUpperCaseEmail.setEmail("TEST-register-duplicate-email@example.com");
|
||||
userWithUpperCaseEmail.setImageUrl(firstUser.getImageUrl());
|
||||
userWithUpperCaseEmail.setLangKey(firstUser.getLangKey());
|
||||
userWithUpperCaseEmail.setAuthorities(new HashSet<>(firstUser.getAuthorities()));
|
||||
|
||||
// Register third (not activated) user
|
||||
restMvc.perform(
|
||||
post("/api/register")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail)))
|
||||
.andExpect(status().isCreated());
|
||||
|
||||
Optional<User> testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3");
|
||||
assertThat(testUser4.isPresent()).isTrue();
|
||||
assertThat(testUser4.get().getEmail()).isEqualTo("test-register-duplicate-email@example.com");
|
||||
|
||||
testUser4.get().setActivated(true);
|
||||
userService.updateUser((new UserDTO(testUser4.get())));
|
||||
|
||||
// Register 4th (already activated) user
|
||||
restMvc.perform(
|
||||
post("/api/register")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
|
||||
.andExpect(status().is4xxClientError());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testRegisterAdminIsIgnored() throws Exception {
|
||||
ManagedUserVM validUser = new ManagedUserVM();
|
||||
validUser.setLogin("badguy");
|
||||
validUser.setPassword("password");
|
||||
validUser.setFirstName("Bad");
|
||||
validUser.setLastName("Guy");
|
||||
validUser.setEmail("badguy@example.com");
|
||||
validUser.setActivated(true);
|
||||
validUser.setImageUrl("http://placehold.it/50x50");
|
||||
validUser.setLangKey(Constants.DEFAULT_LANGUAGE);
|
||||
validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
|
||||
|
||||
restMvc.perform(
|
||||
post("/api/register")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(validUser)))
|
||||
.andExpect(status().isCreated());
|
||||
|
||||
Optional<User> userDup = userRepository.findOneByLogin("badguy");
|
||||
assertThat(userDup.isPresent()).isTrue();
|
||||
assertThat(userDup.get().getAuthorities()).hasSize(1)
|
||||
.containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).get());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testActivateAccount() throws Exception {
|
||||
final String activationKey = "some activation key";
|
||||
User user = new User();
|
||||
user.setLogin("activate-account");
|
||||
user.setEmail("activate-account@example.com");
|
||||
user.setPassword(RandomStringUtils.random(60));
|
||||
user.setActivated(false);
|
||||
user.setActivationKey(activationKey);
|
||||
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
restMvc.perform(get("/api/activate?key={activationKey}", activationKey))
|
||||
.andExpect(status().isOk());
|
||||
|
||||
user = userRepository.findOneByLogin(user.getLogin()).orElse(null);
|
||||
assertThat(user.getActivated()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testActivateAccountWithWrongKey() throws Exception {
|
||||
restMvc.perform(get("/api/activate?key=wrongActivationKey"))
|
||||
.andExpect(status().isInternalServerError());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
@WithMockUser("save-account")
|
||||
public void testSaveAccount() throws Exception {
|
||||
User user = new User();
|
||||
user.setLogin("save-account");
|
||||
user.setEmail("save-account@example.com");
|
||||
user.setPassword(RandomStringUtils.random(60));
|
||||
user.setActivated(true);
|
||||
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
UserDTO userDTO = new UserDTO();
|
||||
userDTO.setLogin("not-used");
|
||||
userDTO.setFirstName("firstname");
|
||||
userDTO.setLastName("lastname");
|
||||
userDTO.setEmail("save-account@example.com");
|
||||
userDTO.setActivated(false);
|
||||
userDTO.setImageUrl("http://placehold.it/50x50");
|
||||
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
|
||||
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
|
||||
|
||||
restMvc.perform(
|
||||
post("/api/account")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
|
||||
.andExpect(status().isOk());
|
||||
|
||||
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
|
||||
assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName());
|
||||
assertThat(updatedUser.getLastName()).isEqualTo(userDTO.getLastName());
|
||||
assertThat(updatedUser.getEmail()).isEqualTo(userDTO.getEmail());
|
||||
assertThat(updatedUser.getLangKey()).isEqualTo(userDTO.getLangKey());
|
||||
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
|
||||
assertThat(updatedUser.getImageUrl()).isEqualTo(userDTO.getImageUrl());
|
||||
assertThat(updatedUser.getActivated()).isEqualTo(true);
|
||||
assertThat(updatedUser.getAuthorities()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
@WithMockUser("save-invalid-email")
|
||||
public void testSaveInvalidEmail() throws Exception {
|
||||
User user = new User();
|
||||
user.setLogin("save-invalid-email");
|
||||
user.setEmail("save-invalid-email@example.com");
|
||||
user.setPassword(RandomStringUtils.random(60));
|
||||
user.setActivated(true);
|
||||
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
UserDTO userDTO = new UserDTO();
|
||||
userDTO.setLogin("not-used");
|
||||
userDTO.setFirstName("firstname");
|
||||
userDTO.setLastName("lastname");
|
||||
userDTO.setEmail("invalid email");
|
||||
userDTO.setActivated(false);
|
||||
userDTO.setImageUrl("http://placehold.it/50x50");
|
||||
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
|
||||
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
|
||||
|
||||
restMvc.perform(
|
||||
post("/api/account")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
@WithMockUser("save-existing-email")
|
||||
public void testSaveExistingEmail() throws Exception {
|
||||
User user = new User();
|
||||
user.setLogin("save-existing-email");
|
||||
user.setEmail("save-existing-email@example.com");
|
||||
user.setPassword(RandomStringUtils.random(60));
|
||||
user.setActivated(true);
|
||||
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
User anotherUser = new User();
|
||||
anotherUser.setLogin("save-existing-email2");
|
||||
anotherUser.setEmail("save-existing-email2@example.com");
|
||||
anotherUser.setPassword(RandomStringUtils.random(60));
|
||||
anotherUser.setActivated(true);
|
||||
|
||||
userRepository.saveAndFlush(anotherUser);
|
||||
|
||||
UserDTO userDTO = new UserDTO();
|
||||
userDTO.setLogin("not-used");
|
||||
userDTO.setFirstName("firstname");
|
||||
userDTO.setLastName("lastname");
|
||||
userDTO.setEmail("save-existing-email2@example.com");
|
||||
userDTO.setActivated(false);
|
||||
userDTO.setImageUrl("http://placehold.it/50x50");
|
||||
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
|
||||
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
|
||||
|
||||
restMvc.perform(
|
||||
post("/api/account")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null);
|
||||
assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email@example.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
@WithMockUser("save-existing-email-and-login")
|
||||
public void testSaveExistingEmailAndLogin() throws Exception {
|
||||
User user = new User();
|
||||
user.setLogin("save-existing-email-and-login");
|
||||
user.setEmail("save-existing-email-and-login@example.com");
|
||||
user.setPassword(RandomStringUtils.random(60));
|
||||
user.setActivated(true);
|
||||
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
UserDTO userDTO = new UserDTO();
|
||||
userDTO.setLogin("not-used");
|
||||
userDTO.setFirstName("firstname");
|
||||
userDTO.setLastName("lastname");
|
||||
userDTO.setEmail("save-existing-email-and-login@example.com");
|
||||
userDTO.setActivated(false);
|
||||
userDTO.setImageUrl("http://placehold.it/50x50");
|
||||
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
|
||||
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
|
||||
|
||||
restMvc.perform(
|
||||
post("/api/account")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
|
||||
.andExpect(status().isOk());
|
||||
|
||||
User updatedUser = userRepository.findOneByLogin("save-existing-email-and-login").orElse(null);
|
||||
assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email-and-login@example.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
@WithMockUser("change-password-wrong-existing-password")
|
||||
public void testChangePasswordWrongExistingPassword() throws Exception {
|
||||
User user = new User();
|
||||
String currentPassword = RandomStringUtils.random(60);
|
||||
user.setPassword(passwordEncoder.encode(currentPassword));
|
||||
user.setLogin("change-password-wrong-existing-password");
|
||||
user.setEmail("change-password-wrong-existing-password@example.com");
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
restMvc.perform(post("/api/account/change-password")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1"+currentPassword, "new password"))))
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
User updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password").orElse(null);
|
||||
assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isFalse();
|
||||
assertThat(passwordEncoder.matches(currentPassword, updatedUser.getPassword())).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
@WithMockUser("change-password")
|
||||
public void testChangePassword() throws Exception {
|
||||
User user = new User();
|
||||
String currentPassword = RandomStringUtils.random(60);
|
||||
user.setPassword(passwordEncoder.encode(currentPassword));
|
||||
user.setLogin("change-password");
|
||||
user.setEmail("change-password@example.com");
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
restMvc.perform(post("/api/account/change-password")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password"))))
|
||||
.andExpect(status().isOk());
|
||||
|
||||
User updatedUser = userRepository.findOneByLogin("change-password").orElse(null);
|
||||
assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
@WithMockUser("change-password-too-small")
|
||||
public void testChangePasswordTooSmall() throws Exception {
|
||||
User user = new User();
|
||||
String currentPassword = RandomStringUtils.random(60);
|
||||
user.setPassword(passwordEncoder.encode(currentPassword));
|
||||
user.setLogin("change-password-too-small");
|
||||
user.setEmail("change-password-too-small@example.com");
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MIN_LENGTH - 1);
|
||||
|
||||
restMvc.perform(post("/api/account/change-password")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))))
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null);
|
||||
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
@WithMockUser("change-password-too-long")
|
||||
public void testChangePasswordTooLong() throws Exception {
|
||||
User user = new User();
|
||||
String currentPassword = RandomStringUtils.random(60);
|
||||
user.setPassword(passwordEncoder.encode(currentPassword));
|
||||
user.setLogin("change-password-too-long");
|
||||
user.setEmail("change-password-too-long@example.com");
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1);
|
||||
|
||||
restMvc.perform(post("/api/account/change-password")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))))
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null);
|
||||
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
@WithMockUser("change-password-empty")
|
||||
public void testChangePasswordEmpty() throws Exception {
|
||||
User user = new User();
|
||||
String currentPassword = RandomStringUtils.random(60);
|
||||
user.setPassword(passwordEncoder.encode(currentPassword));
|
||||
user.setLogin("change-password-empty");
|
||||
user.setEmail("change-password-empty@example.com");
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
restMvc.perform(post("/api/account/change-password")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, ""))))
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null);
|
||||
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testRequestPasswordReset() throws Exception {
|
||||
User user = new User();
|
||||
user.setPassword(RandomStringUtils.random(60));
|
||||
user.setActivated(true);
|
||||
user.setLogin("password-reset");
|
||||
user.setEmail("password-reset@example.com");
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
restMvc.perform(post("/api/account/reset-password/init")
|
||||
.content("password-reset@example.com"))
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testRequestPasswordResetUpperCaseEmail() throws Exception {
|
||||
User user = new User();
|
||||
user.setPassword(RandomStringUtils.random(60));
|
||||
user.setActivated(true);
|
||||
user.setLogin("password-reset");
|
||||
user.setEmail("password-reset@example.com");
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
restMvc.perform(post("/api/account/reset-password/init")
|
||||
.content("password-reset@EXAMPLE.COM"))
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequestPasswordResetWrongEmail() throws Exception {
|
||||
restMvc.perform(
|
||||
post("/api/account/reset-password/init")
|
||||
.content("password-reset-wrong-email@example.com"))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testFinishPasswordReset() throws Exception {
|
||||
User user = new User();
|
||||
user.setPassword(RandomStringUtils.random(60));
|
||||
user.setLogin("finish-password-reset");
|
||||
user.setEmail("finish-password-reset@example.com");
|
||||
user.setResetDate(Instant.now().plusSeconds(60));
|
||||
user.setResetKey("reset key");
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
|
||||
keyAndPassword.setKey(user.getResetKey());
|
||||
keyAndPassword.setNewPassword("new password");
|
||||
|
||||
restMvc.perform(
|
||||
post("/api/account/reset-password/finish")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
|
||||
.andExpect(status().isOk());
|
||||
|
||||
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
|
||||
assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testFinishPasswordResetTooSmall() throws Exception {
|
||||
User user = new User();
|
||||
user.setPassword(RandomStringUtils.random(60));
|
||||
user.setLogin("finish-password-reset-too-small");
|
||||
user.setEmail("finish-password-reset-too-small@example.com");
|
||||
user.setResetDate(Instant.now().plusSeconds(60));
|
||||
user.setResetKey("reset key too small");
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
|
||||
keyAndPassword.setKey(user.getResetKey());
|
||||
keyAndPassword.setNewPassword("foo");
|
||||
|
||||
restMvc.perform(
|
||||
post("/api/account/reset-password/finish")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
|
||||
assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testFinishPasswordResetWrongKey() throws Exception {
|
||||
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
|
||||
keyAndPassword.setKey("wrong reset key");
|
||||
keyAndPassword.setNewPassword("new password");
|
||||
|
||||
restMvc.perform(
|
||||
post("/api/account/reset-password/finish")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
|
||||
.andExpect(status().isInternalServerError());
|
||||
}
|
||||
}
|
@@ -0,0 +1,162 @@
|
||||
package org.hostsharing.hsadminng.web.rest;
|
||||
|
||||
import org.hostsharing.hsadminng.HsadminNgApp;
|
||||
import org.hostsharing.hsadminng.config.audit.AuditEventConverter;
|
||||
import org.hostsharing.hsadminng.domain.PersistentAuditEvent;
|
||||
import org.hostsharing.hsadminng.repository.PersistenceAuditEventRepository;
|
||||
import org.hostsharing.hsadminng.service.AuditEventService;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
|
||||
import org.springframework.format.support.FormattingConversionService;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
/**
|
||||
* Test class for the AuditResource REST controller.
|
||||
*
|
||||
* @see AuditResource
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = HsadminNgApp.class)
|
||||
@Transactional
|
||||
public class AuditResourceIntTest {
|
||||
|
||||
private static final String SAMPLE_PRINCIPAL = "SAMPLE_PRINCIPAL";
|
||||
private static final String SAMPLE_TYPE = "SAMPLE_TYPE";
|
||||
private static final Instant SAMPLE_TIMESTAMP = Instant.parse("2015-08-04T10:11:30Z");
|
||||
private static final long SECONDS_PER_DAY = 60 * 60 * 24;
|
||||
|
||||
@Autowired
|
||||
private PersistenceAuditEventRepository auditEventRepository;
|
||||
|
||||
@Autowired
|
||||
private AuditEventConverter auditEventConverter;
|
||||
|
||||
@Autowired
|
||||
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
|
||||
|
||||
@Autowired
|
||||
private FormattingConversionService formattingConversionService;
|
||||
|
||||
@Autowired
|
||||
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
|
||||
|
||||
private PersistentAuditEvent auditEvent;
|
||||
|
||||
private MockMvc restAuditMockMvc;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
AuditEventService auditEventService =
|
||||
new AuditEventService(auditEventRepository, auditEventConverter);
|
||||
AuditResource auditResource = new AuditResource(auditEventService);
|
||||
this.restAuditMockMvc = MockMvcBuilders.standaloneSetup(auditResource)
|
||||
.setCustomArgumentResolvers(pageableArgumentResolver)
|
||||
.setConversionService(formattingConversionService)
|
||||
.setMessageConverters(jacksonMessageConverter).build();
|
||||
}
|
||||
|
||||
@Before
|
||||
public void initTest() {
|
||||
auditEventRepository.deleteAll();
|
||||
auditEvent = new PersistentAuditEvent();
|
||||
auditEvent.setAuditEventType(SAMPLE_TYPE);
|
||||
auditEvent.setPrincipal(SAMPLE_PRINCIPAL);
|
||||
auditEvent.setAuditEventDate(SAMPLE_TIMESTAMP);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getAllAudits() throws Exception {
|
||||
// Initialize the database
|
||||
auditEventRepository.save(auditEvent);
|
||||
|
||||
// Get all the audits
|
||||
restAuditMockMvc.perform(get("/management/audits"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
|
||||
.andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getAudit() throws Exception {
|
||||
// Initialize the database
|
||||
auditEventRepository.save(auditEvent);
|
||||
|
||||
// Get the audit
|
||||
restAuditMockMvc.perform(get("/management/audits/{id}", auditEvent.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
|
||||
.andExpect(jsonPath("$.principal").value(SAMPLE_PRINCIPAL));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getAuditsByDate() throws Exception {
|
||||
// Initialize the database
|
||||
auditEventRepository.save(auditEvent);
|
||||
|
||||
// Generate dates for selecting audits by date, making sure the period will contain the audit
|
||||
String fromDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10);
|
||||
String toDate = SAMPLE_TIMESTAMP.plusSeconds(SECONDS_PER_DAY).toString().substring(0, 10);
|
||||
|
||||
// Get the audit
|
||||
restAuditMockMvc.perform(get("/management/audits?fromDate="+fromDate+"&toDate="+toDate))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
|
||||
.andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getNonExistingAuditsByDate() throws Exception {
|
||||
// Initialize the database
|
||||
auditEventRepository.save(auditEvent);
|
||||
|
||||
// Generate dates for selecting audits by date, making sure the period will not contain the sample audit
|
||||
String fromDate = SAMPLE_TIMESTAMP.minusSeconds(2*SECONDS_PER_DAY).toString().substring(0, 10);
|
||||
String toDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10);
|
||||
|
||||
// Query audits but expect no results
|
||||
restAuditMockMvc.perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
|
||||
.andExpect(header().string("X-Total-Count", "0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getNonExistingAudit() throws Exception {
|
||||
// Get the audit
|
||||
restAuditMockMvc.perform(get("/management/audits/{id}", Long.MAX_VALUE))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testPersistentAuditEventEquals() throws Exception {
|
||||
TestUtil.equalsVerifier(PersistentAuditEvent.class);
|
||||
PersistentAuditEvent auditEvent1 = new PersistentAuditEvent();
|
||||
auditEvent1.setId(1L);
|
||||
PersistentAuditEvent auditEvent2 = new PersistentAuditEvent();
|
||||
auditEvent2.setId(auditEvent1.getId());
|
||||
assertThat(auditEvent1).isEqualTo(auditEvent2);
|
||||
auditEvent2.setId(2L);
|
||||
assertThat(auditEvent1).isNotEqualTo(auditEvent2);
|
||||
auditEvent1.setId(null);
|
||||
assertThat(auditEvent1).isNotEqualTo(auditEvent2);
|
||||
}
|
||||
}
|
@@ -0,0 +1,66 @@
|
||||
package org.hostsharing.hsadminng.web.rest;
|
||||
|
||||
import org.hostsharing.hsadminng.HsadminNgApp;
|
||||
import org.hostsharing.hsadminng.web.rest.vm.LoggerVM;
|
||||
import ch.qos.logback.classic.AsyncAppender;
|
||||
import ch.qos.logback.classic.LoggerContext;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Test class for the LogsResource REST controller.
|
||||
*
|
||||
* @see LogsResource
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = HsadminNgApp.class)
|
||||
public class LogsResourceIntTest {
|
||||
|
||||
private MockMvc restLogsMockMvc;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
LogsResource logsResource = new LogsResource();
|
||||
this.restLogsMockMvc = MockMvcBuilders
|
||||
.standaloneSetup(logsResource)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getAllLogs() throws Exception {
|
||||
restLogsMockMvc.perform(get("/management/logs"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void changeLogs() throws Exception {
|
||||
LoggerVM logger = new LoggerVM();
|
||||
logger.setLevel("INFO");
|
||||
logger.setName("ROOT");
|
||||
|
||||
restLogsMockMvc.perform(put("/management/logs")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(logger)))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLogstashAppender() {
|
||||
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
|
||||
assertThat(context.getLogger("ROOT").getAppender("ASYNC_LOGSTASH")).isInstanceOf(AsyncAppender.class);
|
||||
}
|
||||
}
|
141
src/test/java/org/hostsharing/hsadminng/web/rest/TestUtil.java
Normal file
141
src/test/java/org/hostsharing/hsadminng/web/rest/TestUtil.java
Normal file
@@ -0,0 +1,141 @@
|
||||
package org.hostsharing.hsadminng.web.rest;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import org.hamcrest.Description;
|
||||
import org.hamcrest.TypeSafeDiagnosingMatcher;
|
||||
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
|
||||
import org.springframework.format.support.DefaultFormattingConversionService;
|
||||
import org.springframework.format.support.FormattingConversionService;
|
||||
import org.springframework.http.MediaType;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeParseException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Utility class for testing REST controllers.
|
||||
*/
|
||||
public final class TestUtil {
|
||||
|
||||
private static final ObjectMapper mapper = createObjectMapper();
|
||||
|
||||
/** MediaType for JSON UTF8 */
|
||||
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(
|
||||
MediaType.APPLICATION_JSON.getType(),
|
||||
MediaType.APPLICATION_JSON.getSubtype(), StandardCharsets.UTF_8);
|
||||
|
||||
|
||||
private static ObjectMapper createObjectMapper() {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
|
||||
mapper.registerModule(new JavaTimeModule());
|
||||
return mapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an object to JSON byte array.
|
||||
*
|
||||
* @param object
|
||||
* the object to convert
|
||||
* @return the JSON byte array
|
||||
* @throws IOException
|
||||
*/
|
||||
public static byte[] convertObjectToJsonBytes(Object object)
|
||||
throws IOException {
|
||||
return mapper.writeValueAsBytes(object);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a byte array with a specific size filled with specified data.
|
||||
*
|
||||
* @param size the size of the byte array
|
||||
* @param data the data to put in the byte array
|
||||
* @return the JSON byte array
|
||||
*/
|
||||
public static byte[] createByteArray(int size, String data) {
|
||||
byte[] byteArray = new byte[size];
|
||||
for (int i = 0; i < size; i++) {
|
||||
byteArray[i] = Byte.parseByte(data, 2);
|
||||
}
|
||||
return byteArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* A matcher that tests that the examined string represents the same instant as the reference datetime.
|
||||
*/
|
||||
public static class ZonedDateTimeMatcher extends TypeSafeDiagnosingMatcher<String> {
|
||||
|
||||
private final ZonedDateTime date;
|
||||
|
||||
public ZonedDateTimeMatcher(ZonedDateTime date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean matchesSafely(String item, Description mismatchDescription) {
|
||||
try {
|
||||
if (!date.isEqual(ZonedDateTime.parse(item))) {
|
||||
mismatchDescription.appendText("was ").appendValue(item);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (DateTimeParseException e) {
|
||||
mismatchDescription.appendText("was ").appendValue(item)
|
||||
.appendText(", which could not be parsed as a ZonedDateTime");
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void describeTo(Description description) {
|
||||
description.appendText("a String representing the same Instant as ").appendValue(date);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a matcher that matches when the examined string reprensents the same instant as the reference datetime
|
||||
* @param date the reference datetime against which the examined string is checked
|
||||
*/
|
||||
public static ZonedDateTimeMatcher sameInstant(ZonedDateTime date) {
|
||||
return new ZonedDateTimeMatcher(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies the equals/hashcode contract on the domain object.
|
||||
*/
|
||||
public static <T> void equalsVerifier(Class<T> clazz) throws Exception {
|
||||
T domainObject1 = clazz.getConstructor().newInstance();
|
||||
assertThat(domainObject1.toString()).isNotNull();
|
||||
assertThat(domainObject1).isEqualTo(domainObject1);
|
||||
assertThat(domainObject1.hashCode()).isEqualTo(domainObject1.hashCode());
|
||||
// Test with an instance of another class
|
||||
Object testOtherObject = new Object();
|
||||
assertThat(domainObject1).isNotEqualTo(testOtherObject);
|
||||
assertThat(domainObject1).isNotEqualTo(null);
|
||||
// Test with an instance of the same class
|
||||
T domainObject2 = clazz.getConstructor().newInstance();
|
||||
assertThat(domainObject1).isNotEqualTo(domainObject2);
|
||||
// HashCodes are equals because the objects are not persisted yet
|
||||
assertThat(domainObject1.hashCode()).isEqualTo(domainObject2.hashCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a FormattingConversionService which use ISO date format, instead of the localized one.
|
||||
* @return the FormattingConversionService
|
||||
*/
|
||||
public static FormattingConversionService createFormattingConversionService() {
|
||||
DefaultFormattingConversionService dfcs = new DefaultFormattingConversionService ();
|
||||
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
|
||||
registrar.setUseIsoFormat(true);
|
||||
registrar.registerFormatters(dfcs);
|
||||
return dfcs;
|
||||
}
|
||||
|
||||
private TestUtil() {}
|
||||
}
|
@@ -0,0 +1,125 @@
|
||||
package org.hostsharing.hsadminng.web.rest;
|
||||
|
||||
import org.hostsharing.hsadminng.HsadminNgApp;
|
||||
import org.hostsharing.hsadminng.domain.User;
|
||||
import org.hostsharing.hsadminng.repository.UserRepository;
|
||||
import org.hostsharing.hsadminng.security.jwt.TokenProvider;
|
||||
import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator;
|
||||
import org.hostsharing.hsadminng.web.rest.vm.LoginVM;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.hamcrest.Matchers.isEmptyString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
/**
|
||||
* Test class for the UserJWTController REST controller.
|
||||
*
|
||||
* @see UserJWTController
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = HsadminNgApp.class)
|
||||
public class UserJWTControllerIntTest {
|
||||
|
||||
@Autowired
|
||||
private TokenProvider tokenProvider;
|
||||
|
||||
@Autowired
|
||||
private AuthenticationManager authenticationManager;
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
@Autowired
|
||||
private ExceptionTranslator exceptionTranslator;
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
UserJWTController userJWTController = new UserJWTController(tokenProvider, authenticationManager);
|
||||
this.mockMvc = MockMvcBuilders.standaloneSetup(userJWTController)
|
||||
.setControllerAdvice(exceptionTranslator)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testAuthorize() throws Exception {
|
||||
User user = new User();
|
||||
user.setLogin("user-jwt-controller");
|
||||
user.setEmail("user-jwt-controller@example.com");
|
||||
user.setActivated(true);
|
||||
user.setPassword(passwordEncoder.encode("test"));
|
||||
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
LoginVM login = new LoginVM();
|
||||
login.setUsername("user-jwt-controller");
|
||||
login.setPassword("test");
|
||||
mockMvc.perform(post("/api/authenticate")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(login)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id_token").isString())
|
||||
.andExpect(jsonPath("$.id_token").isNotEmpty())
|
||||
.andExpect(header().string("Authorization", not(nullValue())))
|
||||
.andExpect(header().string("Authorization", not(isEmptyString())));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testAuthorizeWithRememberMe() throws Exception {
|
||||
User user = new User();
|
||||
user.setLogin("user-jwt-controller-remember-me");
|
||||
user.setEmail("user-jwt-controller-remember-me@example.com");
|
||||
user.setActivated(true);
|
||||
user.setPassword(passwordEncoder.encode("test"));
|
||||
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
LoginVM login = new LoginVM();
|
||||
login.setUsername("user-jwt-controller-remember-me");
|
||||
login.setPassword("test");
|
||||
login.setRememberMe(true);
|
||||
mockMvc.perform(post("/api/authenticate")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(login)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id_token").isString())
|
||||
.andExpect(jsonPath("$.id_token").isNotEmpty())
|
||||
.andExpect(header().string("Authorization", not(nullValue())))
|
||||
.andExpect(header().string("Authorization", not(isEmptyString())));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testAuthorizeFails() throws Exception {
|
||||
LoginVM login = new LoginVM();
|
||||
login.setUsername("wrong-user");
|
||||
login.setPassword("wrong password");
|
||||
mockMvc.perform(post("/api/authenticate")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(login)))
|
||||
.andExpect(status().isUnauthorized())
|
||||
.andExpect(jsonPath("$.id_token").doesNotExist())
|
||||
.andExpect(header().doesNotExist("Authorization"));
|
||||
}
|
||||
}
|
@@ -0,0 +1,608 @@
|
||||
package org.hostsharing.hsadminng.web.rest;
|
||||
|
||||
import org.hostsharing.hsadminng.HsadminNgApp;
|
||||
import org.hostsharing.hsadminng.domain.Authority;
|
||||
import org.hostsharing.hsadminng.domain.User;
|
||||
import org.hostsharing.hsadminng.repository.UserRepository;
|
||||
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
|
||||
import org.hostsharing.hsadminng.service.MailService;
|
||||
import org.hostsharing.hsadminng.service.UserService;
|
||||
import org.hostsharing.hsadminng.service.dto.UserDTO;
|
||||
import org.hostsharing.hsadminng.service.mapper.UserMapper;
|
||||
import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator;
|
||||
import org.hostsharing.hsadminng.web.rest.vm.ManagedUserVM;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.hamcrest.Matchers.hasItems;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
/**
|
||||
* Test class for the UserResource REST controller.
|
||||
*
|
||||
* @see UserResource
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = HsadminNgApp.class)
|
||||
public class UserResourceIntTest {
|
||||
|
||||
private static final String DEFAULT_LOGIN = "johndoe";
|
||||
private static final String UPDATED_LOGIN = "jhipster";
|
||||
|
||||
private static final Long DEFAULT_ID = 1L;
|
||||
|
||||
private static final String DEFAULT_PASSWORD = "passjohndoe";
|
||||
private static final String UPDATED_PASSWORD = "passjhipster";
|
||||
|
||||
private static final String DEFAULT_EMAIL = "johndoe@localhost";
|
||||
private static final String UPDATED_EMAIL = "jhipster@localhost";
|
||||
|
||||
private static final String DEFAULT_FIRSTNAME = "john";
|
||||
private static final String UPDATED_FIRSTNAME = "jhipsterFirstName";
|
||||
|
||||
private static final String DEFAULT_LASTNAME = "doe";
|
||||
private static final String UPDATED_LASTNAME = "jhipsterLastName";
|
||||
|
||||
private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50";
|
||||
private static final String UPDATED_IMAGEURL = "http://placehold.it/40x40";
|
||||
|
||||
private static final String DEFAULT_LANGKEY = "en";
|
||||
private static final String UPDATED_LANGKEY = "fr";
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private MailService mailService;
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Autowired
|
||||
private UserMapper userMapper;
|
||||
|
||||
@Autowired
|
||||
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
|
||||
|
||||
@Autowired
|
||||
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
|
||||
|
||||
@Autowired
|
||||
private ExceptionTranslator exceptionTranslator;
|
||||
|
||||
@Autowired
|
||||
private EntityManager em;
|
||||
|
||||
@Autowired
|
||||
private CacheManager cacheManager;
|
||||
|
||||
private MockMvc restUserMockMvc;
|
||||
|
||||
private User user;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).clear();
|
||||
cacheManager.getCache(UserRepository.USERS_BY_EMAIL_CACHE).clear();
|
||||
UserResource userResource = new UserResource(userService, userRepository, mailService);
|
||||
|
||||
this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource)
|
||||
.setCustomArgumentResolvers(pageableArgumentResolver)
|
||||
.setControllerAdvice(exceptionTranslator)
|
||||
.setMessageConverters(jacksonMessageConverter)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a User.
|
||||
*
|
||||
* This is a static method, as tests for other entities might also need it,
|
||||
* if they test an entity which has a required relationship to the User entity.
|
||||
*/
|
||||
public static User createEntity(EntityManager em) {
|
||||
User user = new User();
|
||||
user.setLogin(DEFAULT_LOGIN + RandomStringUtils.randomAlphabetic(5));
|
||||
user.setPassword(RandomStringUtils.random(60));
|
||||
user.setActivated(true);
|
||||
user.setEmail(RandomStringUtils.randomAlphabetic(5) + DEFAULT_EMAIL);
|
||||
user.setFirstName(DEFAULT_FIRSTNAME);
|
||||
user.setLastName(DEFAULT_LASTNAME);
|
||||
user.setImageUrl(DEFAULT_IMAGEURL);
|
||||
user.setLangKey(DEFAULT_LANGKEY);
|
||||
return user;
|
||||
}
|
||||
|
||||
@Before
|
||||
public void initTest() {
|
||||
user = createEntity(em);
|
||||
user.setLogin(DEFAULT_LOGIN);
|
||||
user.setEmail(DEFAULT_EMAIL);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void createUser() throws Exception {
|
||||
int databaseSizeBeforeCreate = userRepository.findAll().size();
|
||||
|
||||
// Create the User
|
||||
ManagedUserVM managedUserVM = new ManagedUserVM();
|
||||
managedUserVM.setLogin(DEFAULT_LOGIN);
|
||||
managedUserVM.setPassword(DEFAULT_PASSWORD);
|
||||
managedUserVM.setFirstName(DEFAULT_FIRSTNAME);
|
||||
managedUserVM.setLastName(DEFAULT_LASTNAME);
|
||||
managedUserVM.setEmail(DEFAULT_EMAIL);
|
||||
managedUserVM.setActivated(true);
|
||||
managedUserVM.setImageUrl(DEFAULT_IMAGEURL);
|
||||
managedUserVM.setLangKey(DEFAULT_LANGKEY);
|
||||
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
|
||||
|
||||
restUserMockMvc.perform(post("/api/users")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
|
||||
.andExpect(status().isCreated());
|
||||
|
||||
// Validate the User in the database
|
||||
List<User> userList = userRepository.findAll();
|
||||
assertThat(userList).hasSize(databaseSizeBeforeCreate + 1);
|
||||
User testUser = userList.get(userList.size() - 1);
|
||||
assertThat(testUser.getLogin()).isEqualTo(DEFAULT_LOGIN);
|
||||
assertThat(testUser.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
|
||||
assertThat(testUser.getLastName()).isEqualTo(DEFAULT_LASTNAME);
|
||||
assertThat(testUser.getEmail()).isEqualTo(DEFAULT_EMAIL);
|
||||
assertThat(testUser.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
|
||||
assertThat(testUser.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void createUserWithExistingId() throws Exception {
|
||||
int databaseSizeBeforeCreate = userRepository.findAll().size();
|
||||
|
||||
ManagedUserVM managedUserVM = new ManagedUserVM();
|
||||
managedUserVM.setId(1L);
|
||||
managedUserVM.setLogin(DEFAULT_LOGIN);
|
||||
managedUserVM.setPassword(DEFAULT_PASSWORD);
|
||||
managedUserVM.setFirstName(DEFAULT_FIRSTNAME);
|
||||
managedUserVM.setLastName(DEFAULT_LASTNAME);
|
||||
managedUserVM.setEmail(DEFAULT_EMAIL);
|
||||
managedUserVM.setActivated(true);
|
||||
managedUserVM.setImageUrl(DEFAULT_IMAGEURL);
|
||||
managedUserVM.setLangKey(DEFAULT_LANGKEY);
|
||||
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
|
||||
|
||||
// An entity with an existing ID cannot be created, so this API call must fail
|
||||
restUserMockMvc.perform(post("/api/users")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
// Validate the User in the database
|
||||
List<User> userList = userRepository.findAll();
|
||||
assertThat(userList).hasSize(databaseSizeBeforeCreate);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void createUserWithExistingLogin() throws Exception {
|
||||
// Initialize the database
|
||||
userRepository.saveAndFlush(user);
|
||||
int databaseSizeBeforeCreate = userRepository.findAll().size();
|
||||
|
||||
ManagedUserVM managedUserVM = new ManagedUserVM();
|
||||
managedUserVM.setLogin(DEFAULT_LOGIN);// this login should already be used
|
||||
managedUserVM.setPassword(DEFAULT_PASSWORD);
|
||||
managedUserVM.setFirstName(DEFAULT_FIRSTNAME);
|
||||
managedUserVM.setLastName(DEFAULT_LASTNAME);
|
||||
managedUserVM.setEmail("anothermail@localhost");
|
||||
managedUserVM.setActivated(true);
|
||||
managedUserVM.setImageUrl(DEFAULT_IMAGEURL);
|
||||
managedUserVM.setLangKey(DEFAULT_LANGKEY);
|
||||
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
|
||||
|
||||
// Create the User
|
||||
restUserMockMvc.perform(post("/api/users")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
// Validate the User in the database
|
||||
List<User> userList = userRepository.findAll();
|
||||
assertThat(userList).hasSize(databaseSizeBeforeCreate);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void createUserWithExistingEmail() throws Exception {
|
||||
// Initialize the database
|
||||
userRepository.saveAndFlush(user);
|
||||
int databaseSizeBeforeCreate = userRepository.findAll().size();
|
||||
|
||||
ManagedUserVM managedUserVM = new ManagedUserVM();
|
||||
managedUserVM.setLogin("anotherlogin");
|
||||
managedUserVM.setPassword(DEFAULT_PASSWORD);
|
||||
managedUserVM.setFirstName(DEFAULT_FIRSTNAME);
|
||||
managedUserVM.setLastName(DEFAULT_LASTNAME);
|
||||
managedUserVM.setEmail(DEFAULT_EMAIL);// this email should already be used
|
||||
managedUserVM.setActivated(true);
|
||||
managedUserVM.setImageUrl(DEFAULT_IMAGEURL);
|
||||
managedUserVM.setLangKey(DEFAULT_LANGKEY);
|
||||
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
|
||||
|
||||
// Create the User
|
||||
restUserMockMvc.perform(post("/api/users")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
// Validate the User in the database
|
||||
List<User> userList = userRepository.findAll();
|
||||
assertThat(userList).hasSize(databaseSizeBeforeCreate);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void getAllUsers() throws Exception {
|
||||
// Initialize the database
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
// Get all the users
|
||||
restUserMockMvc.perform(get("/api/users?sort=id,desc")
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
|
||||
.andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN)))
|
||||
.andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRSTNAME)))
|
||||
.andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LASTNAME)))
|
||||
.andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL)))
|
||||
.andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGEURL)))
|
||||
.andExpect(jsonPath("$.[*].langKey").value(hasItem(DEFAULT_LANGKEY)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void getUser() throws Exception {
|
||||
// Initialize the database
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNull();
|
||||
|
||||
// Get the user
|
||||
restUserMockMvc.perform(get("/api/users/{login}", user.getLogin()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
|
||||
.andExpect(jsonPath("$.login").value(user.getLogin()))
|
||||
.andExpect(jsonPath("$.firstName").value(DEFAULT_FIRSTNAME))
|
||||
.andExpect(jsonPath("$.lastName").value(DEFAULT_LASTNAME))
|
||||
.andExpect(jsonPath("$.email").value(DEFAULT_EMAIL))
|
||||
.andExpect(jsonPath("$.imageUrl").value(DEFAULT_IMAGEURL))
|
||||
.andExpect(jsonPath("$.langKey").value(DEFAULT_LANGKEY));
|
||||
|
||||
assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void getNonExistingUser() throws Exception {
|
||||
restUserMockMvc.perform(get("/api/users/unknown"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void updateUser() throws Exception {
|
||||
// Initialize the database
|
||||
userRepository.saveAndFlush(user);
|
||||
int databaseSizeBeforeUpdate = userRepository.findAll().size();
|
||||
|
||||
// Update the user
|
||||
User updatedUser = userRepository.findById(user.getId()).get();
|
||||
|
||||
ManagedUserVM managedUserVM = new ManagedUserVM();
|
||||
managedUserVM.setId(updatedUser.getId());
|
||||
managedUserVM.setLogin(updatedUser.getLogin());
|
||||
managedUserVM.setPassword(UPDATED_PASSWORD);
|
||||
managedUserVM.setFirstName(UPDATED_FIRSTNAME);
|
||||
managedUserVM.setLastName(UPDATED_LASTNAME);
|
||||
managedUserVM.setEmail(UPDATED_EMAIL);
|
||||
managedUserVM.setActivated(updatedUser.getActivated());
|
||||
managedUserVM.setImageUrl(UPDATED_IMAGEURL);
|
||||
managedUserVM.setLangKey(UPDATED_LANGKEY);
|
||||
managedUserVM.setCreatedBy(updatedUser.getCreatedBy());
|
||||
managedUserVM.setCreatedDate(updatedUser.getCreatedDate());
|
||||
managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy());
|
||||
managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate());
|
||||
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
|
||||
|
||||
restUserMockMvc.perform(put("/api/users")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// Validate the User in the database
|
||||
List<User> userList = userRepository.findAll();
|
||||
assertThat(userList).hasSize(databaseSizeBeforeUpdate);
|
||||
User testUser = userList.get(userList.size() - 1);
|
||||
assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME);
|
||||
assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME);
|
||||
assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL);
|
||||
assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL);
|
||||
assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void updateUserLogin() throws Exception {
|
||||
// Initialize the database
|
||||
userRepository.saveAndFlush(user);
|
||||
int databaseSizeBeforeUpdate = userRepository.findAll().size();
|
||||
|
||||
// Update the user
|
||||
User updatedUser = userRepository.findById(user.getId()).get();
|
||||
|
||||
ManagedUserVM managedUserVM = new ManagedUserVM();
|
||||
managedUserVM.setId(updatedUser.getId());
|
||||
managedUserVM.setLogin(UPDATED_LOGIN);
|
||||
managedUserVM.setPassword(UPDATED_PASSWORD);
|
||||
managedUserVM.setFirstName(UPDATED_FIRSTNAME);
|
||||
managedUserVM.setLastName(UPDATED_LASTNAME);
|
||||
managedUserVM.setEmail(UPDATED_EMAIL);
|
||||
managedUserVM.setActivated(updatedUser.getActivated());
|
||||
managedUserVM.setImageUrl(UPDATED_IMAGEURL);
|
||||
managedUserVM.setLangKey(UPDATED_LANGKEY);
|
||||
managedUserVM.setCreatedBy(updatedUser.getCreatedBy());
|
||||
managedUserVM.setCreatedDate(updatedUser.getCreatedDate());
|
||||
managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy());
|
||||
managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate());
|
||||
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
|
||||
|
||||
restUserMockMvc.perform(put("/api/users")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// Validate the User in the database
|
||||
List<User> userList = userRepository.findAll();
|
||||
assertThat(userList).hasSize(databaseSizeBeforeUpdate);
|
||||
User testUser = userList.get(userList.size() - 1);
|
||||
assertThat(testUser.getLogin()).isEqualTo(UPDATED_LOGIN);
|
||||
assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME);
|
||||
assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME);
|
||||
assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL);
|
||||
assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL);
|
||||
assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void updateUserExistingEmail() throws Exception {
|
||||
// Initialize the database with 2 users
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
User anotherUser = new User();
|
||||
anotherUser.setLogin("jhipster");
|
||||
anotherUser.setPassword(RandomStringUtils.random(60));
|
||||
anotherUser.setActivated(true);
|
||||
anotherUser.setEmail("jhipster@localhost");
|
||||
anotherUser.setFirstName("java");
|
||||
anotherUser.setLastName("hipster");
|
||||
anotherUser.setImageUrl("");
|
||||
anotherUser.setLangKey("en");
|
||||
userRepository.saveAndFlush(anotherUser);
|
||||
|
||||
// Update the user
|
||||
User updatedUser = userRepository.findById(user.getId()).get();
|
||||
|
||||
ManagedUserVM managedUserVM = new ManagedUserVM();
|
||||
managedUserVM.setId(updatedUser.getId());
|
||||
managedUserVM.setLogin(updatedUser.getLogin());
|
||||
managedUserVM.setPassword(updatedUser.getPassword());
|
||||
managedUserVM.setFirstName(updatedUser.getFirstName());
|
||||
managedUserVM.setLastName(updatedUser.getLastName());
|
||||
managedUserVM.setEmail("jhipster@localhost");// this email should already be used by anotherUser
|
||||
managedUserVM.setActivated(updatedUser.getActivated());
|
||||
managedUserVM.setImageUrl(updatedUser.getImageUrl());
|
||||
managedUserVM.setLangKey(updatedUser.getLangKey());
|
||||
managedUserVM.setCreatedBy(updatedUser.getCreatedBy());
|
||||
managedUserVM.setCreatedDate(updatedUser.getCreatedDate());
|
||||
managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy());
|
||||
managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate());
|
||||
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
|
||||
|
||||
restUserMockMvc.perform(put("/api/users")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void updateUserExistingLogin() throws Exception {
|
||||
// Initialize the database
|
||||
userRepository.saveAndFlush(user);
|
||||
|
||||
User anotherUser = new User();
|
||||
anotherUser.setLogin("jhipster");
|
||||
anotherUser.setPassword(RandomStringUtils.random(60));
|
||||
anotherUser.setActivated(true);
|
||||
anotherUser.setEmail("jhipster@localhost");
|
||||
anotherUser.setFirstName("java");
|
||||
anotherUser.setLastName("hipster");
|
||||
anotherUser.setImageUrl("");
|
||||
anotherUser.setLangKey("en");
|
||||
userRepository.saveAndFlush(anotherUser);
|
||||
|
||||
// Update the user
|
||||
User updatedUser = userRepository.findById(user.getId()).get();
|
||||
|
||||
ManagedUserVM managedUserVM = new ManagedUserVM();
|
||||
managedUserVM.setId(updatedUser.getId());
|
||||
managedUserVM.setLogin("jhipster");// this login should already be used by anotherUser
|
||||
managedUserVM.setPassword(updatedUser.getPassword());
|
||||
managedUserVM.setFirstName(updatedUser.getFirstName());
|
||||
managedUserVM.setLastName(updatedUser.getLastName());
|
||||
managedUserVM.setEmail(updatedUser.getEmail());
|
||||
managedUserVM.setActivated(updatedUser.getActivated());
|
||||
managedUserVM.setImageUrl(updatedUser.getImageUrl());
|
||||
managedUserVM.setLangKey(updatedUser.getLangKey());
|
||||
managedUserVM.setCreatedBy(updatedUser.getCreatedBy());
|
||||
managedUserVM.setCreatedDate(updatedUser.getCreatedDate());
|
||||
managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy());
|
||||
managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate());
|
||||
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
|
||||
|
||||
restUserMockMvc.perform(put("/api/users")
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void deleteUser() throws Exception {
|
||||
// Initialize the database
|
||||
userRepository.saveAndFlush(user);
|
||||
int databaseSizeBeforeDelete = userRepository.findAll().size();
|
||||
|
||||
// Delete the user
|
||||
restUserMockMvc.perform(delete("/api/users/{login}", user.getLogin())
|
||||
.accept(TestUtil.APPLICATION_JSON_UTF8))
|
||||
.andExpect(status().isOk());
|
||||
|
||||
assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNull();
|
||||
|
||||
// Validate the database is empty
|
||||
List<User> userList = userRepository.findAll();
|
||||
assertThat(userList).hasSize(databaseSizeBeforeDelete - 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void getAllAuthorities() throws Exception {
|
||||
restUserMockMvc.perform(get("/api/users/authorities")
|
||||
.accept(TestUtil.APPLICATION_JSON_UTF8)
|
||||
.contentType(TestUtil.APPLICATION_JSON_UTF8))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
|
||||
.andExpect(jsonPath("$").isArray())
|
||||
.andExpect(jsonPath("$").value(hasItems(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testUserEquals() throws Exception {
|
||||
TestUtil.equalsVerifier(User.class);
|
||||
User user1 = new User();
|
||||
user1.setId(1L);
|
||||
User user2 = new User();
|
||||
user2.setId(user1.getId());
|
||||
assertThat(user1).isEqualTo(user2);
|
||||
user2.setId(2L);
|
||||
assertThat(user1).isNotEqualTo(user2);
|
||||
user1.setId(null);
|
||||
assertThat(user1).isNotEqualTo(user2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUserDTOtoUser() {
|
||||
UserDTO userDTO = new UserDTO();
|
||||
userDTO.setId(DEFAULT_ID);
|
||||
userDTO.setLogin(DEFAULT_LOGIN);
|
||||
userDTO.setFirstName(DEFAULT_FIRSTNAME);
|
||||
userDTO.setLastName(DEFAULT_LASTNAME);
|
||||
userDTO.setEmail(DEFAULT_EMAIL);
|
||||
userDTO.setActivated(true);
|
||||
userDTO.setImageUrl(DEFAULT_IMAGEURL);
|
||||
userDTO.setLangKey(DEFAULT_LANGKEY);
|
||||
userDTO.setCreatedBy(DEFAULT_LOGIN);
|
||||
userDTO.setLastModifiedBy(DEFAULT_LOGIN);
|
||||
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
|
||||
|
||||
User user = userMapper.userDTOToUser(userDTO);
|
||||
assertThat(user.getId()).isEqualTo(DEFAULT_ID);
|
||||
assertThat(user.getLogin()).isEqualTo(DEFAULT_LOGIN);
|
||||
assertThat(user.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
|
||||
assertThat(user.getLastName()).isEqualTo(DEFAULT_LASTNAME);
|
||||
assertThat(user.getEmail()).isEqualTo(DEFAULT_EMAIL);
|
||||
assertThat(user.getActivated()).isEqualTo(true);
|
||||
assertThat(user.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
|
||||
assertThat(user.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
|
||||
assertThat(user.getCreatedBy()).isNull();
|
||||
assertThat(user.getCreatedDate()).isNotNull();
|
||||
assertThat(user.getLastModifiedBy()).isNull();
|
||||
assertThat(user.getLastModifiedDate()).isNotNull();
|
||||
assertThat(user.getAuthorities()).extracting("name").containsExactly(AuthoritiesConstants.USER);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUserToUserDTO() {
|
||||
user.setId(DEFAULT_ID);
|
||||
user.setCreatedBy(DEFAULT_LOGIN);
|
||||
user.setCreatedDate(Instant.now());
|
||||
user.setLastModifiedBy(DEFAULT_LOGIN);
|
||||
user.setLastModifiedDate(Instant.now());
|
||||
Set<Authority> authorities = new HashSet<>();
|
||||
Authority authority = new Authority();
|
||||
authority.setName(AuthoritiesConstants.USER);
|
||||
authorities.add(authority);
|
||||
user.setAuthorities(authorities);
|
||||
|
||||
UserDTO userDTO = userMapper.userToUserDTO(user);
|
||||
|
||||
assertThat(userDTO.getId()).isEqualTo(DEFAULT_ID);
|
||||
assertThat(userDTO.getLogin()).isEqualTo(DEFAULT_LOGIN);
|
||||
assertThat(userDTO.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
|
||||
assertThat(userDTO.getLastName()).isEqualTo(DEFAULT_LASTNAME);
|
||||
assertThat(userDTO.getEmail()).isEqualTo(DEFAULT_EMAIL);
|
||||
assertThat(userDTO.isActivated()).isEqualTo(true);
|
||||
assertThat(userDTO.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
|
||||
assertThat(userDTO.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
|
||||
assertThat(userDTO.getCreatedBy()).isEqualTo(DEFAULT_LOGIN);
|
||||
assertThat(userDTO.getCreatedDate()).isEqualTo(user.getCreatedDate());
|
||||
assertThat(userDTO.getLastModifiedBy()).isEqualTo(DEFAULT_LOGIN);
|
||||
assertThat(userDTO.getLastModifiedDate()).isEqualTo(user.getLastModifiedDate());
|
||||
assertThat(userDTO.getAuthorities()).containsExactly(AuthoritiesConstants.USER);
|
||||
assertThat(userDTO.toString()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAuthorityEquals() {
|
||||
Authority authorityA = new Authority();
|
||||
assertThat(authorityA).isEqualTo(authorityA);
|
||||
assertThat(authorityA).isNotEqualTo(null);
|
||||
assertThat(authorityA).isNotEqualTo(new Object());
|
||||
assertThat(authorityA.hashCode()).isEqualTo(0);
|
||||
assertThat(authorityA.toString()).isNotNull();
|
||||
|
||||
Authority authorityB = new Authority();
|
||||
assertThat(authorityA).isEqualTo(authorityB);
|
||||
|
||||
authorityB.setName(AuthoritiesConstants.ADMIN);
|
||||
assertThat(authorityA).isNotEqualTo(authorityB);
|
||||
|
||||
authorityA.setName(AuthoritiesConstants.USER);
|
||||
assertThat(authorityA).isNotEqualTo(authorityB);
|
||||
|
||||
authorityB.setName(AuthoritiesConstants.USER);
|
||||
assertThat(authorityA).isEqualTo(authorityB);
|
||||
assertThat(authorityA.hashCode()).isEqualTo(authorityB.hashCode());
|
||||
}
|
||||
}
|
@@ -0,0 +1,150 @@
|
||||
package org.hostsharing.hsadminng.web.rest.errors;
|
||||
|
||||
import org.hostsharing.hsadminng.HsadminNgApp;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Test class for the ExceptionTranslator controller advice.
|
||||
*
|
||||
* @see ExceptionTranslator
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = HsadminNgApp.class)
|
||||
public class ExceptionTranslatorIntTest {
|
||||
|
||||
@Autowired
|
||||
private ExceptionTranslatorTestController controller;
|
||||
|
||||
@Autowired
|
||||
private ExceptionTranslator exceptionTranslator;
|
||||
|
||||
@Autowired
|
||||
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
mockMvc = MockMvcBuilders.standaloneSetup(controller)
|
||||
.setControllerAdvice(exceptionTranslator)
|
||||
.setMessageConverters(jacksonMessageConverter)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConcurrencyFailure() throws Exception {
|
||||
mockMvc.perform(get("/test/concurrency-failure"))
|
||||
.andExpect(status().isConflict())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
|
||||
.andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMethodArgumentNotValid() throws Exception {
|
||||
mockMvc.perform(post("/test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
|
||||
.andExpect(jsonPath("$.message").value(ErrorConstants.ERR_VALIDATION))
|
||||
.andExpect(jsonPath("$.fieldErrors.[0].objectName").value("testDTO"))
|
||||
.andExpect(jsonPath("$.fieldErrors.[0].field").value("test"))
|
||||
.andExpect(jsonPath("$.fieldErrors.[0].message").value("NotNull"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParameterizedError() throws Exception {
|
||||
mockMvc.perform(get("/test/parameterized-error"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
|
||||
.andExpect(jsonPath("$.message").value("test parameterized error"))
|
||||
.andExpect(jsonPath("$.params.param0").value("param0_value"))
|
||||
.andExpect(jsonPath("$.params.param1").value("param1_value"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParameterizedError2() throws Exception {
|
||||
mockMvc.perform(get("/test/parameterized-error2"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
|
||||
.andExpect(jsonPath("$.message").value("test parameterized error"))
|
||||
.andExpect(jsonPath("$.params.foo").value("foo_value"))
|
||||
.andExpect(jsonPath("$.params.bar").value("bar_value"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMissingServletRequestPartException() throws Exception {
|
||||
mockMvc.perform(get("/test/missing-servlet-request-part"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
|
||||
.andExpect(jsonPath("$.message").value("error.http.400"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMissingServletRequestParameterException() throws Exception {
|
||||
mockMvc.perform(get("/test/missing-servlet-request-parameter"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
|
||||
.andExpect(jsonPath("$.message").value("error.http.400"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAccessDenied() throws Exception {
|
||||
mockMvc.perform(get("/test/access-denied"))
|
||||
.andExpect(status().isForbidden())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
|
||||
.andExpect(jsonPath("$.message").value("error.http.403"))
|
||||
.andExpect(jsonPath("$.detail").value("test access denied!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUnauthorized() throws Exception {
|
||||
mockMvc.perform(get("/test/unauthorized"))
|
||||
.andExpect(status().isUnauthorized())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
|
||||
.andExpect(jsonPath("$.message").value("error.http.401"))
|
||||
.andExpect(jsonPath("$.path").value("/test/unauthorized"))
|
||||
.andExpect(jsonPath("$.detail").value("test authentication failed!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMethodNotSupported() throws Exception {
|
||||
mockMvc.perform(post("/test/access-denied"))
|
||||
.andExpect(status().isMethodNotAllowed())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
|
||||
.andExpect(jsonPath("$.message").value("error.http.405"))
|
||||
.andExpect(jsonPath("$.detail").value("Request method 'POST' not supported"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExceptionWithResponseStatus() throws Exception {
|
||||
mockMvc.perform(get("/test/response-status"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
|
||||
.andExpect(jsonPath("$.message").value("error.http.400"))
|
||||
.andExpect(jsonPath("$.title").value("test response status"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInternalServerError() throws Exception {
|
||||
mockMvc.perform(get("/test/internal-server-error"))
|
||||
.andExpect(status().isInternalServerError())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
|
||||
.andExpect(jsonPath("$.message").value("error.http.500"))
|
||||
.andExpect(jsonPath("$.title").value("Internal Server Error"));
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,86 @@
|
||||
package org.hostsharing.hsadminng.web.rest.errors;
|
||||
|
||||
import org.springframework.dao.ConcurrencyFailureException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
public class ExceptionTranslatorTestController {
|
||||
|
||||
@GetMapping("/test/concurrency-failure")
|
||||
public void concurrencyFailure() {
|
||||
throw new ConcurrencyFailureException("test concurrency failure");
|
||||
}
|
||||
|
||||
@PostMapping("/test/method-argument")
|
||||
public void methodArgument(@Valid @RequestBody TestDTO testDTO) {
|
||||
}
|
||||
|
||||
@GetMapping("/test/parameterized-error")
|
||||
public void parameterizedError() {
|
||||
throw new CustomParameterizedException("test parameterized error", "param0_value", "param1_value");
|
||||
}
|
||||
|
||||
@GetMapping("/test/parameterized-error2")
|
||||
public void parameterizedError2() {
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("foo", "foo_value");
|
||||
params.put("bar", "bar_value");
|
||||
throw new CustomParameterizedException("test parameterized error", params);
|
||||
}
|
||||
|
||||
@GetMapping("/test/missing-servlet-request-part")
|
||||
public void missingServletRequestPartException(@RequestPart String part) {
|
||||
}
|
||||
|
||||
@GetMapping("/test/missing-servlet-request-parameter")
|
||||
public void missingServletRequestParameterException(@RequestParam String param) {
|
||||
}
|
||||
|
||||
@GetMapping("/test/access-denied")
|
||||
public void accessdenied() {
|
||||
throw new AccessDeniedException("test access denied!");
|
||||
}
|
||||
|
||||
@GetMapping("/test/unauthorized")
|
||||
public void unauthorized() {
|
||||
throw new BadCredentialsException("test authentication failed!");
|
||||
}
|
||||
|
||||
@GetMapping("/test/response-status")
|
||||
public void exceptionWithReponseStatus() {
|
||||
throw new TestResponseStatusException();
|
||||
}
|
||||
|
||||
@GetMapping("/test/internal-server-error")
|
||||
public void internalServerError() {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
|
||||
public static class TestDTO {
|
||||
|
||||
@NotNull
|
||||
private String test;
|
||||
|
||||
public String getTest() {
|
||||
return test;
|
||||
}
|
||||
|
||||
public void setTest(String test) {
|
||||
this.test = test;
|
||||
}
|
||||
}
|
||||
|
||||
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "test response status")
|
||||
@SuppressWarnings("serial")
|
||||
public static class TestResponseStatusException extends RuntimeException {
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,44 @@
|
||||
package org.hostsharing.hsadminng.web.rest.util;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
|
||||
/**
|
||||
* Tests based on parsing algorithm in app/components/util/pagination-util.service.js
|
||||
*
|
||||
* @see PaginationUtil
|
||||
*/
|
||||
public class PaginationUtilUnitTest {
|
||||
|
||||
@Test
|
||||
public void generatePaginationHttpHeadersTest() {
|
||||
String baseUrl = "/api/_search/example";
|
||||
List<String> content = new ArrayList<>();
|
||||
Page<String> page = new PageImpl<>(content, PageRequest.of(6, 50), 400L);
|
||||
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl);
|
||||
List<String> strHeaders = headers.get(HttpHeaders.LINK);
|
||||
assertNotNull(strHeaders);
|
||||
assertTrue(strHeaders.size() == 1);
|
||||
String headerData = strHeaders.get(0);
|
||||
assertTrue(headerData.split(",").length == 4);
|
||||
String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\","
|
||||
+ "</api/_search/example?page=5&size=50>; rel=\"prev\","
|
||||
+ "</api/_search/example?page=7&size=50>; rel=\"last\","
|
||||
+ "</api/_search/example?page=0&size=50>; rel=\"first\"";
|
||||
assertEquals(expectedData, headerData);
|
||||
List<String> xTotalCountHeaders = headers.get("X-Total-Count");
|
||||
assertTrue(xTotalCountHeaders.size() == 1);
|
||||
assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L));
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user