1
0

Initial application generated by JHipster-5.8.2

This commit is contained in:
Michael Hoennig
2019-04-01 13:14:56 +02:00
commit e0b3d2a36d
404 changed files with 49698 additions and 0 deletions

View File

View File

@@ -0,0 +1,6 @@
Feature: User management
Scenario: Retrieve administrator user
When I search user 'admin'
Then the user is found
And his last name is 'Administrator'

View File

@@ -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));
}
}

View File

@@ -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() {
}
}

View File

@@ -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);
}
}
}

View File

@@ -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.
}
}

View File

@@ -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 {
}

View File

@@ -0,0 +1,9 @@
package org.hostsharing.hsadminng.cucumber.stepdefs;
import org.springframework.test.web.servlet.ResultActions;
public abstract class StepDefs {
protected ResultActions actions;
}

View File

@@ -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));
}
}

View File

@@ -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);
}
}

View File

@@ -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 +
'}';
}
}

View File

@@ -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> {
}

View File

@@ -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);
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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);
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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());
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View 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() {}
}

View File

@@ -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"));
}
}

View File

@@ -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());
}
}

View File

@@ -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"));
}
}

View File

@@ -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 {
}
}

View File

@@ -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));
}
}

View File

@@ -0,0 +1,15 @@
const mock = () => {
let storage = {};
return {
getItem: key => (key in storage ? storage[key] : null),
setItem: (key, value) => (storage[key] = value || ''),
removeItem: key => delete storage[key],
clear: () => (storage = {})
};
};
Object.defineProperty(window, 'localStorage', { value: mock() });
Object.defineProperty(window, 'sessionStorage', { value: mock() });
Object.defineProperty(window, 'getComputedStyle', {
value: () => ['-webkit-appearance']
});

View File

@@ -0,0 +1,26 @@
module.exports = {
preset: 'jest-preset-angular',
setupTestFrameworkScriptFile: '<rootDir>/src/test/javascript/jest.ts',
coverageDirectory: '<rootDir>/build/test-results/',
globals: {
'ts-jest': {
tsConfigFile: 'tsconfig.json'
},
__TRANSFORM_HTML__: true
},
coveragePathIgnorePatterns: [
'<rootDir>/src/test/javascript'
],
moduleNameMapper: {
'app/(.*)': '<rootDir>/src/main/webapp/app/$1'
},
reporters: [
'default',
[ 'jest-junit', { output: './build/test-results/TESTS-results-jest.xml' } ]
],
testResultsProcessor: 'jest-sonar-reporter',
transformIgnorePatterns: ['node_modules/(?!@angular/common/locales)'],
testMatch: ['<rootDir>/src/test/javascript/spec/**/+(*.)+(spec.ts)'],
rootDir: '../../../',
testURL: "http://localhost/"
};

View File

@@ -0,0 +1,2 @@
import 'jest-preset-angular';
import './jest-global-mocks';

View File

@@ -0,0 +1,72 @@
import { TestBed, async, tick, fakeAsync, inject } from '@angular/core/testing';
import { ActivatedRoute } from '@angular/router';
import { Observable, of, throwError } from 'rxjs';
import { HsadminNgTestModule } from '../../../test.module';
import { MockActivatedRoute } from '../../../helpers/mock-route.service';
import { ActivateService } from 'app/account/activate/activate.service';
import { ActivateComponent } from 'app/account/activate/activate.component';
describe('Component Tests', () => {
describe('ActivateComponent', () => {
let comp: ActivateComponent;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HsadminNgTestModule],
declarations: [ActivateComponent],
providers: [
{
provide: ActivatedRoute,
useValue: new MockActivatedRoute({ key: 'ABC123' })
}
]
})
.overrideTemplate(ActivateComponent, '')
.compileComponents();
}));
beforeEach(() => {
const fixture = TestBed.createComponent(ActivateComponent);
comp = fixture.componentInstance;
});
it('calls activate.get with the key from params', inject(
[ActivateService],
fakeAsync((service: ActivateService) => {
spyOn(service, 'get').and.returnValue(of());
comp.ngOnInit();
tick();
expect(service.get).toHaveBeenCalledWith('ABC123');
})
));
it('should set set success to OK upon successful activation', inject(
[ActivateService],
fakeAsync((service: ActivateService) => {
spyOn(service, 'get').and.returnValue(of({}));
comp.ngOnInit();
tick();
expect(comp.error).toBe(null);
expect(comp.success).toEqual('OK');
})
));
it('should set set error to ERROR upon activation failure', inject(
[ActivateService],
fakeAsync((service: ActivateService) => {
spyOn(service, 'get').and.returnValue(throwError('ERROR'));
comp.ngOnInit();
tick();
expect(comp.error).toBe('ERROR');
expect(comp.success).toEqual(null);
})
));
});
});

View File

@@ -0,0 +1,119 @@
import { ComponentFixture, TestBed, inject, tick, fakeAsync } from '@angular/core/testing';
import { Observable, of, throwError } from 'rxjs';
import { Renderer, ElementRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HsadminNgTestModule } from '../../../../test.module';
import { PasswordResetFinishComponent } from 'app/account/password-reset/finish/password-reset-finish.component';
import { PasswordResetFinishService } from 'app/account/password-reset/finish/password-reset-finish.service';
import { MockActivatedRoute } from '../../../../helpers/mock-route.service';
describe('Component Tests', () => {
describe('PasswordResetFinishComponent', () => {
let fixture: ComponentFixture<PasswordResetFinishComponent>;
let comp: PasswordResetFinishComponent;
beforeEach(() => {
fixture = TestBed.configureTestingModule({
imports: [HsadminNgTestModule],
declarations: [PasswordResetFinishComponent],
providers: [
{
provide: ActivatedRoute,
useValue: new MockActivatedRoute({ key: 'XYZPDQ' })
},
{
provide: Renderer,
useValue: {
invokeElementMethod(renderElement: any, methodName: string, args?: any[]) {}
}
},
{
provide: ElementRef,
useValue: new ElementRef(null)
}
]
})
.overrideTemplate(PasswordResetFinishComponent, '')
.createComponent(PasswordResetFinishComponent);
});
beforeEach(() => {
fixture = TestBed.createComponent(PasswordResetFinishComponent);
comp = fixture.componentInstance;
comp.ngOnInit();
});
it('should define its initial state', () => {
comp.ngOnInit();
expect(comp.keyMissing).toBeFalsy();
expect(comp.key).toEqual('XYZPDQ');
expect(comp.resetAccount).toEqual({});
});
it('sets focus after the view has been initialized', inject([ElementRef], (elementRef: ElementRef) => {
const element = fixture.nativeElement;
const node = {
focus() {}
};
elementRef.nativeElement = element;
spyOn(element, 'querySelector').and.returnValue(node);
spyOn(node, 'focus');
comp.ngAfterViewInit();
expect(element.querySelector).toHaveBeenCalledWith('#password');
expect(node.focus).toHaveBeenCalled();
}));
it('should ensure the two passwords entered match', () => {
comp.resetAccount.password = 'password';
comp.confirmPassword = 'non-matching';
comp.finishReset();
expect(comp.doNotMatch).toEqual('ERROR');
});
it('should update success to OK after resetting password', inject(
[PasswordResetFinishService],
fakeAsync((service: PasswordResetFinishService) => {
spyOn(service, 'save').and.returnValue(of({}));
comp.resetAccount.password = 'password';
comp.confirmPassword = 'password';
comp.finishReset();
tick();
expect(service.save).toHaveBeenCalledWith({
key: 'XYZPDQ',
newPassword: 'password'
});
expect(comp.success).toEqual('OK');
})
));
it('should notify of generic error', inject(
[PasswordResetFinishService],
fakeAsync((service: PasswordResetFinishService) => {
spyOn(service, 'save').and.returnValue(throwError('ERROR'));
comp.resetAccount.password = 'password';
comp.confirmPassword = 'password';
comp.finishReset();
tick();
expect(service.save).toHaveBeenCalledWith({
key: 'XYZPDQ',
newPassword: 'password'
});
expect(comp.success).toBeNull();
expect(comp.error).toEqual('ERROR');
})
));
});
});

View File

@@ -0,0 +1,110 @@
import { ComponentFixture, TestBed, inject } from '@angular/core/testing';
import { Renderer, ElementRef } from '@angular/core';
import { Observable, of, throwError } from 'rxjs';
import { HsadminNgTestModule } from '../../../../test.module';
import { PasswordResetInitComponent } from 'app/account/password-reset/init/password-reset-init.component';
import { PasswordResetInitService } from 'app/account/password-reset/init/password-reset-init.service';
import { EMAIL_NOT_FOUND_TYPE } from 'app/shared';
describe('Component Tests', () => {
describe('PasswordResetInitComponent', () => {
let fixture: ComponentFixture<PasswordResetInitComponent>;
let comp: PasswordResetInitComponent;
beforeEach(() => {
fixture = TestBed.configureTestingModule({
imports: [HsadminNgTestModule],
declarations: [PasswordResetInitComponent],
providers: [
{
provide: Renderer,
useValue: {
invokeElementMethod(renderElement: any, methodName: string, args?: any[]) {}
}
},
{
provide: ElementRef,
useValue: new ElementRef(null)
}
]
})
.overrideTemplate(PasswordResetInitComponent, '')
.createComponent(PasswordResetInitComponent);
comp = fixture.componentInstance;
comp.ngOnInit();
});
it('should define its initial state', () => {
expect(comp.success).toBeUndefined();
expect(comp.error).toBeUndefined();
expect(comp.errorEmailNotExists).toBeUndefined();
expect(comp.resetAccount).toEqual({});
});
it('sets focus after the view has been initialized', inject([ElementRef], (elementRef: ElementRef) => {
const element = fixture.nativeElement;
const node = {
focus() {}
};
elementRef.nativeElement = element;
spyOn(element, 'querySelector').and.returnValue(node);
spyOn(node, 'focus');
comp.ngAfterViewInit();
expect(element.querySelector).toHaveBeenCalledWith('#email');
expect(node.focus).toHaveBeenCalled();
}));
it('notifies of success upon successful requestReset', inject([PasswordResetInitService], (service: PasswordResetInitService) => {
spyOn(service, 'save').and.returnValue(of({}));
comp.resetAccount.email = 'user@domain.com';
comp.requestReset();
expect(service.save).toHaveBeenCalledWith('user@domain.com');
expect(comp.success).toEqual('OK');
expect(comp.error).toBeNull();
expect(comp.errorEmailNotExists).toBeNull();
}));
it('notifies of unknown email upon email address not registered/400', inject(
[PasswordResetInitService],
(service: PasswordResetInitService) => {
spyOn(service, 'save').and.returnValue(
throwError({
status: 400,
error: { type: EMAIL_NOT_FOUND_TYPE }
})
);
comp.resetAccount.email = 'user@domain.com';
comp.requestReset();
expect(service.save).toHaveBeenCalledWith('user@domain.com');
expect(comp.success).toBeNull();
expect(comp.error).toBeNull();
expect(comp.errorEmailNotExists).toEqual('ERROR');
}
));
it('notifies of error upon error response', inject([PasswordResetInitService], (service: PasswordResetInitService) => {
spyOn(service, 'save').and.returnValue(
throwError({
status: 503,
data: 'something else'
})
);
comp.resetAccount.email = 'user@domain.com';
comp.requestReset();
expect(service.save).toHaveBeenCalledWith('user@domain.com');
expect(comp.success).toBeNull();
expect(comp.errorEmailNotExists).toBeNull();
expect(comp.error).toEqual('ERROR');
}));
});
});

View File

@@ -0,0 +1,48 @@
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { PasswordStrengthBarComponent } from 'app/account/password/password-strength-bar.component';
describe('Component Tests', () => {
describe('PasswordStrengthBarComponent', () => {
let comp: PasswordStrengthBarComponent;
let fixture: ComponentFixture<PasswordStrengthBarComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [PasswordStrengthBarComponent]
})
.overrideTemplate(PasswordStrengthBarComponent, '')
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PasswordStrengthBarComponent);
comp = fixture.componentInstance;
});
describe('PasswordStrengthBarComponents', () => {
it('should initialize with default values', () => {
expect(comp.measureStrength('')).toBe(0);
expect(comp.colors).toEqual(['#F00', '#F90', '#FF0', '#9F0', '#0F0']);
expect(comp.getColor(0).idx).toBe(1);
expect(comp.getColor(0).col).toBe(comp.colors[0]);
});
it('should increase strength upon password value change', () => {
expect(comp.measureStrength('')).toBe(0);
expect(comp.measureStrength('aa')).toBeGreaterThanOrEqual(comp.measureStrength(''));
expect(comp.measureStrength('aa^6')).toBeGreaterThanOrEqual(comp.measureStrength('aa'));
expect(comp.measureStrength('Aa090(**)')).toBeGreaterThanOrEqual(comp.measureStrength('aa^6'));
expect(comp.measureStrength('Aa090(**)+-07365')).toBeGreaterThanOrEqual(comp.measureStrength('Aa090(**)'));
});
it('should change the color based on strength', () => {
expect(comp.getColor(0).col).toBe(comp.colors[0]);
expect(comp.getColor(11).col).toBe(comp.colors[1]);
expect(comp.getColor(22).col).toBe(comp.colors[2]);
expect(comp.getColor(33).col).toBe(comp.colors[3]);
expect(comp.getColor(44).col).toBe(comp.colors[4]);
});
});
});
});

View File

@@ -0,0 +1,89 @@
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { HttpResponse } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { HsadminNgTestModule } from '../../../test.module';
import { PasswordComponent } from 'app/account/password/password.component';
import { PasswordService } from 'app/account/password/password.service';
describe('Component Tests', () => {
describe('PasswordComponent', () => {
let comp: PasswordComponent;
let fixture: ComponentFixture<PasswordComponent>;
let service: PasswordService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HsadminNgTestModule],
declarations: [PasswordComponent],
providers: []
})
.overrideTemplate(PasswordComponent, '')
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PasswordComponent);
comp = fixture.componentInstance;
service = fixture.debugElement.injector.get(PasswordService);
});
it('should show error if passwords do not match', () => {
// GIVEN
comp.newPassword = 'password1';
comp.confirmPassword = 'password2';
// WHEN
comp.changePassword();
// THEN
expect(comp.doNotMatch).toBe('ERROR');
expect(comp.error).toBeNull();
expect(comp.success).toBeNull();
});
it('should call Auth.changePassword when passwords match', () => {
// GIVEN
const passwordValues = {
currentPassword: 'oldPassword',
newPassword: 'myPassword'
};
spyOn(service, 'save').and.returnValue(of(new HttpResponse({ body: true })));
comp.currentPassword = passwordValues.currentPassword;
comp.newPassword = comp.confirmPassword = passwordValues.newPassword;
// WHEN
comp.changePassword();
// THEN
expect(service.save).toHaveBeenCalledWith(passwordValues.newPassword, passwordValues.currentPassword);
});
it('should set success to OK upon success', function() {
// GIVEN
spyOn(service, 'save').and.returnValue(of(new HttpResponse({ body: true })));
comp.newPassword = comp.confirmPassword = 'myPassword';
// WHEN
comp.changePassword();
// THEN
expect(comp.doNotMatch).toBeNull();
expect(comp.error).toBeNull();
expect(comp.success).toBe('OK');
});
it('should notify of error if change password fails', function() {
// GIVEN
spyOn(service, 'save').and.returnValue(throwError('ERROR'));
comp.newPassword = comp.confirmPassword = 'myPassword';
// WHEN
comp.changePassword();
// THEN
expect(comp.doNotMatch).toBeNull();
expect(comp.success).toBeNull();
expect(comp.error).toBe('ERROR');
});
});
});

View File

@@ -0,0 +1,121 @@
import { ComponentFixture, TestBed, async, inject, tick, fakeAsync } from '@angular/core/testing';
import { Observable, of, throwError } from 'rxjs';
import { JhiLanguageService } from 'ng-jhipster';
import { MockLanguageService } from '../../../helpers/mock-language.service';
import { HsadminNgTestModule } from '../../../test.module';
import { EMAIL_ALREADY_USED_TYPE, LOGIN_ALREADY_USED_TYPE } from 'app/shared';
import { Register } from 'app/account/register/register.service';
import { RegisterComponent } from 'app/account/register/register.component';
describe('Component Tests', () => {
describe('RegisterComponent', () => {
let fixture: ComponentFixture<RegisterComponent>;
let comp: RegisterComponent;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HsadminNgTestModule],
declarations: [RegisterComponent]
})
.overrideTemplate(RegisterComponent, '')
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(RegisterComponent);
comp = fixture.componentInstance;
comp.ngOnInit();
});
it('should ensure the two passwords entered match', () => {
comp.registerAccount.password = 'password';
comp.confirmPassword = 'non-matching';
comp.register();
expect(comp.doNotMatch).toEqual('ERROR');
});
it('should update success to OK after creating an account', inject(
[Register, JhiLanguageService],
fakeAsync((service: Register, mockTranslate: MockLanguageService) => {
spyOn(service, 'save').and.returnValue(of({}));
comp.registerAccount.password = comp.confirmPassword = 'password';
comp.register();
tick();
expect(service.save).toHaveBeenCalledWith({
password: 'password',
langKey: 'de'
});
expect(comp.success).toEqual(true);
expect(comp.registerAccount.langKey).toEqual('de');
expect(mockTranslate.getCurrentSpy).toHaveBeenCalled();
expect(comp.errorUserExists).toBeNull();
expect(comp.errorEmailExists).toBeNull();
expect(comp.error).toBeNull();
})
));
it('should notify of user existence upon 400/login already in use', inject(
[Register],
fakeAsync((service: Register) => {
spyOn(service, 'save').and.returnValue(
throwError({
status: 400,
error: { type: LOGIN_ALREADY_USED_TYPE }
})
);
comp.registerAccount.password = comp.confirmPassword = 'password';
comp.register();
tick();
expect(comp.errorUserExists).toEqual('ERROR');
expect(comp.errorEmailExists).toBeNull();
expect(comp.error).toBeNull();
})
));
it('should notify of email existence upon 400/email address already in use', inject(
[Register],
fakeAsync((service: Register) => {
spyOn(service, 'save').and.returnValue(
throwError({
status: 400,
error: { type: EMAIL_ALREADY_USED_TYPE }
})
);
comp.registerAccount.password = comp.confirmPassword = 'password';
comp.register();
tick();
expect(comp.errorEmailExists).toEqual('ERROR');
expect(comp.errorUserExists).toBeNull();
expect(comp.error).toBeNull();
})
));
it('should notify of generic error', inject(
[Register],
fakeAsync((service: Register) => {
spyOn(service, 'save').and.returnValue(
throwError({
status: 503
})
);
comp.registerAccount.password = comp.confirmPassword = 'password';
comp.register();
tick();
expect(comp.errorUserExists).toBeNull();
expect(comp.errorEmailExists).toBeNull();
expect(comp.error).toEqual('ERROR');
})
));
});
});

View File

@@ -0,0 +1,81 @@
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { Observable, throwError } from 'rxjs';
import { HsadminNgTestModule } from '../../../test.module';
import { AccountService } from 'app/core';
import { SettingsComponent } from 'app/account/settings/settings.component';
describe('Component Tests', () => {
describe('SettingsComponent', () => {
let comp: SettingsComponent;
let fixture: ComponentFixture<SettingsComponent>;
let mockAuth: any;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HsadminNgTestModule],
declarations: [SettingsComponent],
providers: []
})
.overrideTemplate(SettingsComponent, '')
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SettingsComponent);
comp = fixture.componentInstance;
mockAuth = fixture.debugElement.injector.get(AccountService);
});
it('should send the current identity upon save', () => {
// GIVEN
const accountValues = {
firstName: 'John',
lastName: 'Doe',
activated: true,
email: 'john.doe@mail.com',
langKey: 'de',
login: 'john'
};
mockAuth.setIdentityResponse(accountValues);
// WHEN
comp.settingsAccount = accountValues;
comp.save();
// THEN
expect(mockAuth.identitySpy).toHaveBeenCalled();
expect(mockAuth.saveSpy).toHaveBeenCalledWith(accountValues);
expect(comp.settingsAccount).toEqual(accountValues);
});
it('should notify of success upon successful save', () => {
// GIVEN
const accountValues = {
firstName: 'John',
lastName: 'Doe'
};
mockAuth.setIdentityResponse(accountValues);
// WHEN
comp.save();
// THEN
expect(comp.error).toBeNull();
expect(comp.success).toBe('OK');
});
it('should notify of error upon failed save', () => {
// GIVEN
mockAuth.saveSpy.and.returnValue(throwError('ERROR'));
// WHEN
comp.save();
// THEN
expect(comp.error).toEqual('ERROR');
expect(comp.success).toBeNull();
});
});
});

View File

@@ -0,0 +1,133 @@
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { Observable, of } from 'rxjs';
import { HttpHeaders, HttpResponse } from '@angular/common/http';
import { HsadminNgTestModule } from '../../../test.module';
import { AuditsComponent } from 'app/admin/audits/audits.component';
import { AuditsService } from 'app/admin/audits/audits.service';
import { Audit } from 'app/admin/audits/audit.model';
import { ITEMS_PER_PAGE } from 'app/shared';
function build2DigitsDatePart(datePart: number) {
return `0${datePart}`.slice(-2);
}
function getDate(isToday = true) {
let date: Date = new Date();
if (isToday) {
// Today + 1 day - needed if the current day must be included
date.setDate(date.getDate() + 1);
} else {
// get last month
if (date.getMonth() === 0) {
date = new Date(date.getFullYear() - 1, 11, date.getDate());
} else {
date = new Date(date.getFullYear(), date.getMonth() - 1, date.getDate());
}
}
const monthString = build2DigitsDatePart(date.getMonth() + 1);
const dateString = build2DigitsDatePart(date.getDate());
return `${date.getFullYear()}-${monthString}-${dateString}`;
}
describe('Component Tests', () => {
describe('AuditsComponent', () => {
let comp: AuditsComponent;
let fixture: ComponentFixture<AuditsComponent>;
let service: AuditsService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HsadminNgTestModule],
declarations: [AuditsComponent],
providers: [AuditsService]
})
.overrideTemplate(AuditsComponent, '')
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AuditsComponent);
comp = fixture.componentInstance;
service = fixture.debugElement.injector.get(AuditsService);
});
describe('today function ', () => {
it('should set toDate to current date', () => {
comp.today();
expect(comp.toDate).toBe(getDate());
});
});
describe('previousMonth function ', () => {
it('should set fromDate to current date', () => {
comp.previousMonth();
expect(comp.fromDate).toBe(getDate(false));
});
});
describe('By default, on init', () => {
it('should set all default values correctly', () => {
fixture.detectChanges();
expect(comp.toDate).toBe(getDate());
expect(comp.fromDate).toBe(getDate(false));
expect(comp.itemsPerPage).toBe(ITEMS_PER_PAGE);
expect(comp.page).toBe(10);
expect(comp.reverse).toBeFalsy();
expect(comp.predicate).toBe('id');
});
});
describe('OnInit', () => {
it('Should call load all on init', () => {
// GIVEN
const headers = new HttpHeaders().append('link', 'link;link');
const audit = new Audit({ remoteAddress: '127.0.0.1', sessionId: '123' }, 'user', '20140101', 'AUTHENTICATION_SUCCESS');
spyOn(service, 'query').and.returnValue(
of(
new HttpResponse({
body: [audit],
headers
})
)
);
// WHEN
comp.ngOnInit();
// THEN
expect(service.query).toHaveBeenCalled();
expect(comp.audits[0]).toEqual(jasmine.objectContaining(audit));
});
});
describe('Create sort object', () => {
it('Should sort only by id asc', () => {
// GIVEN
comp.predicate = 'id';
comp.reverse = false;
// WHEN
const sort = comp.sort();
// THEN
expect(sort.length).toEqual(1);
expect(sort[0]).toEqual('id,desc');
});
it('Should sort by timestamp asc then by id', () => {
// GIVEN
comp.predicate = 'timestamp';
comp.reverse = true;
// WHEN
const sort = comp.sort();
// THEN
expect(sort.length).toEqual(2);
expect(sort[0]).toEqual('timestamp,asc');
expect(sort[1]).toEqual('id');
});
});
});
});

View File

@@ -0,0 +1,59 @@
import { TestBed } from '@angular/core/testing';
import { AuditsService } from 'app/admin/audits/audits.service';
import { Audit } from 'app/admin/audits/audit.model';
import { SERVER_API_URL } from 'app/app.constants';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
describe('Service Tests', () => {
describe('Audits Service', () => {
let service: AuditsService;
let httpMock;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule]
});
service = TestBed.get(AuditsService);
httpMock = TestBed.get(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
describe('Service methods', () => {
it('should call correct URL', () => {
service.query({}).subscribe(() => {});
const req = httpMock.expectOne({ method: 'GET' });
const resourceUrl = SERVER_API_URL + 'management/audits';
expect(req.request.url).toEqual(resourceUrl);
});
it('should return Audits', () => {
const audit = new Audit({ remoteAddress: '127.0.0.1', sessionId: '123' }, 'user', '20140101', 'AUTHENTICATION_SUCCESS');
service.query({}).subscribe(received => {
expect(received.body[0]).toEqual(audit);
});
const req = httpMock.expectOne({ method: 'GET' });
req.flush([audit]);
});
it('should propagate not found response', () => {
service.query({}).subscribe(null, (_error: any) => {
expect(_error.status).toEqual(404);
});
const req = httpMock.expectOne({ method: 'GET' });
req.flush('Invalid request parameters', {
status: 404,
statusText: 'Bad Request'
});
});
});
});
});

View File

@@ -0,0 +1,71 @@
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { of } from 'rxjs';
import { HttpHeaders, HttpResponse } from '@angular/common/http';
import { HsadminNgTestModule } from '../../../test.module';
import { JhiConfigurationComponent } from 'app/admin/configuration/configuration.component';
import { JhiConfigurationService } from 'app/admin/configuration/configuration.service';
import { ITEMS_PER_PAGE } from 'app/shared';
import { Log } from 'app/admin';
describe('Component Tests', () => {
describe('JhiConfigurationComponent', () => {
let comp: JhiConfigurationComponent;
let fixture: ComponentFixture<JhiConfigurationComponent>;
let service: JhiConfigurationService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HsadminNgTestModule],
declarations: [JhiConfigurationComponent],
providers: [JhiConfigurationService]
})
.overrideTemplate(JhiConfigurationComponent, '')
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(JhiConfigurationComponent);
comp = fixture.componentInstance;
service = fixture.debugElement.injector.get(JhiConfigurationService);
});
describe('OnInit', () => {
it('should set all default values correctly', () => {
expect(comp.configKeys).toEqual([]);
expect(comp.filter).toBe('');
expect(comp.orderProp).toBe('prefix');
expect(comp.reverse).toBe(false);
});
it('Should call load all on init', () => {
// GIVEN
const body = [{ config: 'test', properties: 'test' }, { config: 'test2' }];
const envConfig = { envConfig: 'test' };
spyOn(service, 'get').and.returnValue(of(body));
spyOn(service, 'getEnv').and.returnValue(of(envConfig));
// WHEN
comp.ngOnInit();
// THEN
expect(service.get).toHaveBeenCalled();
expect(service.getEnv).toHaveBeenCalled();
expect(comp.configKeys).toEqual([['0', '1', '2', '3']]);
expect(comp.allConfiguration).toEqual(envConfig);
});
});
describe('keys method', () => {
it('should return the keys of an Object', () => {
// GIVEN
const data = {
key1: 'test',
key2: 'test2'
};
// THEN
expect(comp.keys(data)).toEqual(['key1', 'key2']);
expect(comp.keys(undefined)).toEqual([]);
});
});
});
});

View File

@@ -0,0 +1,64 @@
import { TestBed } from '@angular/core/testing';
import { JhiConfigurationService } from 'app/admin/configuration/configuration.service';
import { SERVER_API_URL } from 'app/app.constants';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpResponse } from '@angular/common/http';
describe('Service Tests', () => {
describe('Logs Service', () => {
let service: JhiConfigurationService;
let httpMock;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule]
});
service = TestBed.get(JhiConfigurationService);
httpMock = TestBed.get(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
describe('Service methods', () => {
it('should call correct URL', () => {
service.get().subscribe(() => {});
const req = httpMock.expectOne({ method: 'GET' });
const resourceUrl = SERVER_API_URL + 'management/configprops';
expect(req.request.url).toEqual(resourceUrl);
});
it('should get the config', () => {
const angularConfig = {
contexts: {
angular: {
beans: ['test2']
}
}
};
service.get().subscribe(received => {
expect(received.body[0]).toEqual(angularConfig);
});
const req = httpMock.expectOne({ method: 'GET' });
req.flush(angularConfig);
});
it('should get the env', () => {
const propertySources = new HttpResponse({
body: [{ name: 'test1', properties: 'test1' }, { name: 'test2', properties: 'test2' }]
});
service.get().subscribe(received => {
expect(received.body[0]).toEqual(propertySources);
});
const req = httpMock.expectOne({ method: 'GET' });
req.flush(propertySources);
});
});
});
});

View File

@@ -0,0 +1,321 @@
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { of, throwError } from 'rxjs';
import { HsadminNgTestModule } from '../../../test.module';
import { JhiHealthCheckComponent } from 'app/admin/health/health.component';
import { JhiHealthService } from 'app/admin/health/health.service';
describe('Component Tests', () => {
describe('JhiHealthCheckComponent', () => {
let comp: JhiHealthCheckComponent;
let fixture: ComponentFixture<JhiHealthCheckComponent>;
let service: JhiHealthService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HsadminNgTestModule],
declarations: [JhiHealthCheckComponent]
})
.overrideTemplate(JhiHealthCheckComponent, '')
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(JhiHealthCheckComponent);
comp = fixture.componentInstance;
service = fixture.debugElement.injector.get(JhiHealthService);
});
describe('baseName and subSystemName', () => {
it('should return the basename when it has no sub system', () => {
expect(comp.baseName('base')).toBe('base');
});
it('should return the basename when it has sub systems', () => {
expect(comp.baseName('base.subsystem.system')).toBe('base');
});
it('should return the sub system name', () => {
expect(comp.subSystemName('subsystem')).toBe('');
});
it('should return the subsystem when it has multiple keys', () => {
expect(comp.subSystemName('subsystem.subsystem.system')).toBe(' - subsystem.system');
});
});
describe('transformHealthData', () => {
it('should flatten empty health data', () => {
const data = {};
const expected = [];
expect(service.transformHealthData(data)).toEqual(expected);
});
it('should flatten health data with no subsystems', () => {
const data = {
details: {
status: 'UP',
db: {
status: 'UP',
database: 'H2',
hello: '1'
},
mail: {
status: 'UP',
error: 'mail.a.b.c'
}
}
};
const expected = [
{
name: 'db',
status: 'UP',
details: {
database: 'H2',
hello: '1'
}
},
{
name: 'mail',
error: 'mail.a.b.c',
status: 'UP'
}
];
expect(service.transformHealthData(data)).toEqual(expected);
});
it('should flatten health data with subsystems at level 1, main system has no additional information', () => {
const data = {
details: {
status: 'UP',
db: {
status: 'UP',
database: 'H2',
hello: '1'
},
mail: {
status: 'UP',
error: 'mail.a.b.c'
},
system: {
status: 'DOWN',
subsystem1: {
status: 'UP',
property1: 'system.subsystem1.property1'
},
subsystem2: {
status: 'DOWN',
error: 'system.subsystem1.error',
property2: 'system.subsystem2.property2'
}
}
}
};
const expected = [
{
name: 'db',
status: 'UP',
details: {
database: 'H2',
hello: '1'
}
},
{
name: 'mail',
error: 'mail.a.b.c',
status: 'UP'
},
{
name: 'system.subsystem1',
status: 'UP',
details: {
property1: 'system.subsystem1.property1'
}
},
{
name: 'system.subsystem2',
error: 'system.subsystem1.error',
status: 'DOWN',
details: {
property2: 'system.subsystem2.property2'
}
}
];
expect(service.transformHealthData(data)).toEqual(expected);
});
it('should flatten health data with subsystems at level 1, main system has additional information', () => {
const data = {
details: {
status: 'UP',
db: {
status: 'UP',
database: 'H2',
hello: '1'
},
mail: {
status: 'UP',
error: 'mail.a.b.c'
},
system: {
status: 'DOWN',
property1: 'system.property1',
subsystem1: {
status: 'UP',
property1: 'system.subsystem1.property1'
},
subsystem2: {
status: 'DOWN',
error: 'system.subsystem1.error',
property2: 'system.subsystem2.property2'
}
}
}
};
const expected = [
{
name: 'db',
status: 'UP',
details: {
database: 'H2',
hello: '1'
}
},
{
name: 'mail',
error: 'mail.a.b.c',
status: 'UP'
},
{
name: 'system',
status: 'DOWN',
details: {
property1: 'system.property1'
}
},
{
name: 'system.subsystem1',
status: 'UP',
details: {
property1: 'system.subsystem1.property1'
}
},
{
name: 'system.subsystem2',
error: 'system.subsystem1.error',
status: 'DOWN',
details: {
property2: 'system.subsystem2.property2'
}
}
];
expect(service.transformHealthData(data)).toEqual(expected);
});
it('should flatten health data with subsystems at level 1, main system has additional error', () => {
const data = {
details: {
status: 'UP',
db: {
status: 'UP',
database: 'H2',
hello: '1'
},
mail: {
status: 'UP',
error: 'mail.a.b.c'
},
system: {
status: 'DOWN',
error: 'show me',
subsystem1: {
status: 'UP',
property1: 'system.subsystem1.property1'
},
subsystem2: {
status: 'DOWN',
error: 'system.subsystem1.error',
property2: 'system.subsystem2.property2'
}
}
}
};
const expected = [
{
name: 'db',
status: 'UP',
details: {
database: 'H2',
hello: '1'
}
},
{
name: 'mail',
error: 'mail.a.b.c',
status: 'UP'
},
{
name: 'system',
error: 'show me',
status: 'DOWN'
},
{
name: 'system.subsystem1',
status: 'UP',
details: {
property1: 'system.subsystem1.property1'
}
},
{
name: 'system.subsystem2',
error: 'system.subsystem1.error',
status: 'DOWN',
details: {
property2: 'system.subsystem2.property2'
}
}
];
expect(service.transformHealthData(data)).toEqual(expected);
});
});
describe('getBadgeClass', () => {
it('should get badge class', () => {
const upBadgeClass = comp.getBadgeClass('UP');
const downBadgeClass = comp.getBadgeClass('DOWN');
expect(upBadgeClass).toEqual('badge-success');
expect(downBadgeClass).toEqual('badge-danger');
});
});
describe('refresh', () => {
it('should call refresh on init', () => {
// GIVEN
spyOn(service, 'checkHealth').and.returnValue(of(new HttpResponse()));
spyOn(service, 'transformHealthData').and.returnValue(of({ data: 'test' }));
// WHEN
comp.ngOnInit();
// THEN
expect(service.checkHealth).toHaveBeenCalled();
expect(service.transformHealthData).toHaveBeenCalled();
expect(comp.healthData.value).toEqual({ data: 'test' });
});
it('should handle a 503 on refreshing health data', () => {
// GIVEN
spyOn(service, 'checkHealth').and.returnValue(throwError(new HttpErrorResponse({ status: 503, error: 'Mail down' })));
spyOn(service, 'transformHealthData').and.returnValue(of({ health: 'down' }));
// WHEN
comp.refresh();
// THEN
expect(service.checkHealth).toHaveBeenCalled();
expect(service.transformHealthData).toHaveBeenCalled();
expect(comp.healthData.value).toEqual({ health: 'down' });
});
});
});
});

View File

@@ -0,0 +1,77 @@
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { of } from 'rxjs';
import { HttpHeaders, HttpResponse } from '@angular/common/http';
import { HsadminNgTestModule } from '../../../test.module';
import { LogsComponent } from 'app/admin/logs/logs.component';
import { LogsService } from 'app/admin/logs/logs.service';
import { ITEMS_PER_PAGE } from 'app/shared';
import { Log } from 'app/admin';
describe('Component Tests', () => {
describe('LogsComponent', () => {
let comp: LogsComponent;
let fixture: ComponentFixture<LogsComponent>;
let service: LogsService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HsadminNgTestModule],
declarations: [LogsComponent],
providers: [LogsService]
})
.overrideTemplate(LogsComponent, '')
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LogsComponent);
comp = fixture.componentInstance;
service = fixture.debugElement.injector.get(LogsService);
});
describe('OnInit', () => {
it('should set all default values correctly', () => {
expect(comp.filter).toBe('');
expect(comp.orderProp).toBe('name');
expect(comp.reverse).toBe(false);
});
it('Should call load all on init', () => {
// GIVEN
const headers = new HttpHeaders().append('link', 'link;link');
const log = new Log('main', 'WARN');
spyOn(service, 'findAll').and.returnValue(
of(
new HttpResponse({
body: [log],
headers
})
)
);
// WHEN
comp.ngOnInit();
// THEN
expect(service.findAll).toHaveBeenCalled();
expect(comp.loggers[0]).toEqual(jasmine.objectContaining(log));
});
});
describe('change log level', () => {
it('should change log level correctly', () => {
// GIVEN
const log = new Log('main', 'ERROR');
spyOn(service, 'changeLevel').and.returnValue(of(new HttpResponse()));
spyOn(service, 'findAll').and.returnValue(of(new HttpResponse({ body: [log] })));
// WHEN
comp.changeLevel('main', 'ERROR');
// THEN
expect(service.changeLevel).toHaveBeenCalled();
expect(service.findAll).toHaveBeenCalled();
expect(comp.loggers[0]).toEqual(jasmine.objectContaining(log));
});
});
});
});

View File

@@ -0,0 +1,58 @@
import { TestBed } from '@angular/core/testing';
import { LogsService } from 'app/admin/logs/logs.service';
import { Log } from 'app/admin/logs/log.model';
import { SERVER_API_URL } from 'app/app.constants';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
describe('Service Tests', () => {
describe('Logs Service', () => {
let service: LogsService;
let httpMock;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule]
});
service = TestBed.get(LogsService);
httpMock = TestBed.get(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
describe('Service methods', () => {
it('should call correct URL', () => {
service.findAll().subscribe(() => {});
const req = httpMock.expectOne({ method: 'GET' });
const resourceUrl = SERVER_API_URL + 'management/logs';
expect(req.request.url).toEqual(resourceUrl);
});
it('should return Logs', () => {
const log = new Log('main', 'ERROR');
service.findAll().subscribe(received => {
expect(received.body[0]).toEqual(log);
});
const req = httpMock.expectOne({ method: 'GET' });
req.flush([log]);
});
it('should change log level', () => {
const log = new Log('main', 'ERROR');
service.changeLevel(log).subscribe(received => {
expect(received.body[0]).toEqual(log);
});
const req = httpMock.expectOne({ method: 'PUT' });
req.flush([log]);
});
});
});
});

View File

@@ -0,0 +1,55 @@
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { of, throwError } from 'rxjs';
import { HsadminNgTestModule } from '../../../test.module';
import { JhiMetricsMonitoringComponent } from 'app/admin/metrics/metrics.component';
import { JhiMetricsService } from 'app/admin/metrics/metrics.service';
describe('Component Tests', () => {
describe('JhiMetricsMonitoringComponent', () => {
let comp: JhiMetricsMonitoringComponent;
let fixture: ComponentFixture<JhiMetricsMonitoringComponent>;
let service: JhiMetricsService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HsadminNgTestModule],
declarations: [JhiMetricsMonitoringComponent]
})
.overrideTemplate(JhiMetricsMonitoringComponent, '')
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(JhiMetricsMonitoringComponent);
comp = fixture.componentInstance;
service = fixture.debugElement.injector.get(JhiMetricsService);
});
describe('refresh', () => {
it('should call refresh on init', () => {
// GIVEN
const response = {
timers: {
service: 'test',
unrelatedKey: 'test'
},
gauges: {
'jcache.statistics': {
value: 2
},
unrelatedKey: 'test'
}
};
spyOn(service, 'getMetrics').and.returnValue(of(response));
// WHEN
comp.ngOnInit();
// THEN
expect(service.getMetrics).toHaveBeenCalled();
});
});
});
});

View File

@@ -0,0 +1,57 @@
import { TestBed } from '@angular/core/testing';
import { JhiMetricsService } from 'app/admin/metrics/metrics.service';
import { SERVER_API_URL } from 'app/app.constants';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
describe('Service Tests', () => {
describe('Logs Service', () => {
let service: JhiMetricsService;
let httpMock;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule]
});
service = TestBed.get(JhiMetricsService);
httpMock = TestBed.get(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
describe('Service methods', () => {
it('should call correct URL', () => {
service.getMetrics().subscribe(() => {});
const req = httpMock.expectOne({ method: 'GET' });
const resourceUrl = SERVER_API_URL + 'management/jhi-metrics';
expect(req.request.url).toEqual(resourceUrl);
});
it('should return Metrics', () => {
const metrics = [];
service.getMetrics().subscribe(received => {
expect(received.body[0]).toEqual(metrics);
});
const req = httpMock.expectOne({ method: 'GET' });
req.flush([metrics]);
});
it('should return Thread Dump', () => {
const dump = [{ name: 'test1', threadState: 'RUNNABLE' }];
service.threadDump().subscribe(received => {
expect(received.body[0]).toEqual(dump);
});
const req = httpMock.expectOne({ method: 'GET' });
req.flush([dump]);
});
});
});
});

View File

@@ -0,0 +1,54 @@
import { ComponentFixture, TestBed, async, inject, fakeAsync, tick } from '@angular/core/testing';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { Observable, of } from 'rxjs';
import { JhiEventManager } from 'ng-jhipster';
import { HsadminNgTestModule } from '../../../test.module';
import { UserMgmtDeleteDialogComponent } from 'app/admin/user-management/user-management-delete-dialog.component';
import { UserService } from 'app/core';
describe('Component Tests', () => {
describe('User Management Delete Component', () => {
let comp: UserMgmtDeleteDialogComponent;
let fixture: ComponentFixture<UserMgmtDeleteDialogComponent>;
let service: UserService;
let mockEventManager: any;
let mockActiveModal: any;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HsadminNgTestModule],
declarations: [UserMgmtDeleteDialogComponent]
})
.overrideTemplate(UserMgmtDeleteDialogComponent, '')
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UserMgmtDeleteDialogComponent);
comp = fixture.componentInstance;
service = fixture.debugElement.injector.get(UserService);
mockEventManager = fixture.debugElement.injector.get(JhiEventManager);
mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal);
});
describe('confirmDelete', () => {
it('Should call delete service on confirmDelete', inject(
[],
fakeAsync(() => {
// GIVEN
spyOn(service, 'delete').and.returnValue(of({}));
// WHEN
comp.confirmDelete('user');
tick();
// THEN
expect(service.delete).toHaveBeenCalledWith('user');
expect(mockActiveModal.dismissSpy).toHaveBeenCalled();
expect(mockEventManager.broadcastSpy).toHaveBeenCalled();
})
));
});
});
});

View File

@@ -0,0 +1,65 @@
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { ActivatedRoute } from '@angular/router';
import { of } from 'rxjs';
import { HsadminNgTestModule } from '../../../test.module';
import { UserMgmtDetailComponent } from 'app/admin/user-management/user-management-detail.component';
import { User } from 'app/core';
describe('Component Tests', () => {
describe('User Management Detail Component', () => {
let comp: UserMgmtDetailComponent;
let fixture: ComponentFixture<UserMgmtDetailComponent>;
const route = ({
data: of({ user: new User(1, 'user', 'first', 'last', 'first@last.com', true, 'en', ['ROLE_USER'], 'admin', null, null, null) })
} as any) as ActivatedRoute;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HsadminNgTestModule],
declarations: [UserMgmtDetailComponent],
providers: [
{
provide: ActivatedRoute,
useValue: route
}
]
})
.overrideTemplate(UserMgmtDetailComponent, '')
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UserMgmtDetailComponent);
comp = fixture.componentInstance;
});
describe('OnInit', () => {
it('Should call load all on init', () => {
// GIVEN
// WHEN
comp.ngOnInit();
// THEN
expect(comp.user).toEqual(
jasmine.objectContaining({
id: 1,
login: 'user',
firstName: 'first',
lastName: 'last',
email: 'first@last.com',
activated: true,
langKey: 'en',
authorities: ['ROLE_USER'],
createdBy: 'admin',
createdDate: null,
lastModifiedBy: null,
lastModifiedDate: null,
password: null
})
);
});
});
});
});

View File

@@ -0,0 +1,102 @@
import { ComponentFixture, TestBed, async, inject, fakeAsync, tick } from '@angular/core/testing';
import { HttpResponse } from '@angular/common/http';
import { ActivatedRoute } from '@angular/router';
import { Observable, of } from 'rxjs';
import { HsadminNgTestModule } from '../../../test.module';
import { UserMgmtUpdateComponent } from 'app/admin/user-management/user-management-update.component';
import { UserService, User, JhiLanguageHelper } from 'app/core';
describe('Component Tests', () => {
describe('User Management Update Component', () => {
let comp: UserMgmtUpdateComponent;
let fixture: ComponentFixture<UserMgmtUpdateComponent>;
let service: UserService;
let mockLanguageHelper: any;
const route = ({
data: of({ user: new User(1, 'user', 'first', 'last', 'first@last.com', true, 'en', ['ROLE_USER'], 'admin', null, null, null) })
} as any) as ActivatedRoute;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HsadminNgTestModule],
declarations: [UserMgmtUpdateComponent],
providers: [
{
provide: ActivatedRoute,
useValue: route
}
]
})
.overrideTemplate(UserMgmtUpdateComponent, '')
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UserMgmtUpdateComponent);
comp = fixture.componentInstance;
service = fixture.debugElement.injector.get(UserService);
mockLanguageHelper = fixture.debugElement.injector.get(JhiLanguageHelper);
});
describe('OnInit', () => {
it('Should load authorities and language on init', inject(
[],
fakeAsync(() => {
// GIVEN
spyOn(service, 'authorities').and.returnValue(of(['USER']));
// WHEN
comp.ngOnInit();
// THEN
expect(service.authorities).toHaveBeenCalled();
expect(comp.authorities).toEqual(['USER']);
expect(mockLanguageHelper.getAllSpy).toHaveBeenCalled();
})
));
});
describe('save', () => {
it('Should call update service on save for existing user', inject(
[],
fakeAsync(() => {
// GIVEN
const entity = new User(123);
spyOn(service, 'update').and.returnValue(
of(
new HttpResponse({
body: entity
})
)
);
comp.user = entity;
// WHEN
comp.save();
tick(); // simulate async
// THEN
expect(service.update).toHaveBeenCalledWith(entity);
expect(comp.isSaving).toEqual(false);
})
));
it('Should call create service on save for new user', inject(
[],
fakeAsync(() => {
// GIVEN
const entity = new User();
spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity })));
comp.user = entity;
// WHEN
comp.save();
tick(); // simulate async
// THEN
expect(service.create).toHaveBeenCalledWith(entity);
expect(comp.isSaving).toEqual(false);
})
));
});
});
});

View File

@@ -0,0 +1,85 @@
import { ComponentFixture, TestBed, async, inject, fakeAsync, tick } from '@angular/core/testing';
import { Observable, of } from 'rxjs';
import { HttpHeaders, HttpResponse } from '@angular/common/http';
import { HsadminNgTestModule } from '../../../test.module';
import { UserMgmtComponent } from 'app/admin/user-management/user-management.component';
import { UserService, User } from 'app/core';
describe('Component Tests', () => {
describe('User Management Component', () => {
let comp: UserMgmtComponent;
let fixture: ComponentFixture<UserMgmtComponent>;
let service: UserService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HsadminNgTestModule],
declarations: [UserMgmtComponent]
})
.overrideTemplate(UserMgmtComponent, '')
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UserMgmtComponent);
comp = fixture.componentInstance;
service = fixture.debugElement.injector.get(UserService);
});
describe('OnInit', () => {
it('Should call load all on init', inject(
[],
fakeAsync(() => {
// GIVEN
const headers = new HttpHeaders().append('link', 'link;link');
spyOn(service, 'query').and.returnValue(
of(
new HttpResponse({
body: [new User(123)],
headers
})
)
);
// WHEN
comp.ngOnInit();
tick(); // simulate async
// THEN
expect(service.query).toHaveBeenCalled();
expect(comp.users[0]).toEqual(jasmine.objectContaining({ id: 123 }));
})
));
});
describe('setActive', () => {
it('Should update user and call load all', inject(
[],
fakeAsync(() => {
// GIVEN
const headers = new HttpHeaders().append('link', 'link;link');
const user = new User(123);
spyOn(service, 'query').and.returnValue(
of(
new HttpResponse({
body: [user],
headers
})
)
);
spyOn(service, 'update').and.returnValue(of(new HttpResponse({ status: 200 })));
// WHEN
comp.setActive(user, true);
tick(); // simulate async
// THEN
expect(service.update).toHaveBeenCalledWith(user);
expect(service.query).toHaveBeenCalled();
expect(comp.users[0]).toEqual(jasmine.objectContaining({ id: 123 }));
})
));
});
});
});

View File

@@ -0,0 +1,110 @@
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { SERVER_API_URL } from 'app/app.constants';
import { AccountService } from 'app/core';
import { JhiDateUtils, JhiLanguageService } from 'ng-jhipster';
import { SessionStorageService } from 'ngx-webstorage';
import { MockLanguageService } from '../../../helpers/mock-language.service';
describe('Service Tests', () => {
describe('Account Service', () => {
let service: AccountService;
let httpMock;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
JhiDateUtils,
SessionStorageService,
{
provide: JhiLanguageService,
useClass: MockLanguageService
}
]
});
service = TestBed.get(AccountService);
httpMock = TestBed.get(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
describe('Service methods', () => {
it('should call /account if user is undefined', () => {
service.identity().then(() => {});
const req = httpMock.expectOne({ method: 'GET' });
const resourceUrl = SERVER_API_URL + 'api/account';
expect(req.request.url).toEqual(`${resourceUrl}`);
});
it('should call /account only once', () => {
service.identity().then(() => service.identity().then(() => {}));
const req = httpMock.expectOne({ method: 'GET' });
const resourceUrl = SERVER_API_URL + 'api/account';
expect(req.request.url).toEqual(`${resourceUrl}`);
req.flush({
firstName: 'John'
});
});
describe('hasAuthority', () => {
it('should return false if user is not logged', async () => {
const hasAuthority = await service.hasAuthority('ROLE_USER');
expect(hasAuthority).toBeFalsy();
});
it('should return false if user is logged and has not authority', async () => {
service.authenticate({
authorities: ['ROLE_USER']
});
const hasAuthority = await service.hasAuthority('ROLE_ADMIN');
expect(hasAuthority).toBeFalsy();
});
it('should return true if user is logged and has authority', async () => {
service.authenticate({
authorities: ['ROLE_USER']
});
const hasAuthority = await service.hasAuthority('ROLE_USER');
expect(hasAuthority).toBeTruthy();
});
});
describe('hasAnyAuthority', () => {
it('should return false if user is not logged', async () => {
const hasAuthority = await service.hasAnyAuthority(['ROLE_USER']);
expect(hasAuthority).toBeFalsy();
});
it('should return false if user is logged and has not authority', async () => {
service.authenticate({
authorities: ['ROLE_USER']
});
const hasAuthority = await service.hasAnyAuthority(['ROLE_ADMIN']);
expect(hasAuthority).toBeFalsy();
});
it('should return true if user is logged and has authority', async () => {
service.authenticate({
authorities: ['ROLE_USER']
});
const hasAuthority = await service.hasAnyAuthority(['ROLE_USER', 'ROLE_ADMIN']);
expect(hasAuthority).toBeTruthy();
});
});
});
});
});

View File

@@ -0,0 +1,66 @@
import { TestBed } from '@angular/core/testing';
import { JhiDateUtils } from 'ng-jhipster';
import { UserService, User } from 'app/core';
import { SERVER_API_URL } from 'app/app.constants';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
describe('Service Tests', () => {
describe('User Service', () => {
let service: UserService;
let httpMock;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [JhiDateUtils]
});
service = TestBed.get(UserService);
httpMock = TestBed.get(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
describe('Service methods', () => {
it('should call correct URL', () => {
service.find('user').subscribe(() => {});
const req = httpMock.expectOne({ method: 'GET' });
const resourceUrl = SERVER_API_URL + 'api/users';
expect(req.request.url).toEqual(`${resourceUrl}/user`);
});
it('should return User', () => {
service.find('user').subscribe(received => {
expect(received.body.login).toEqual('user');
});
const req = httpMock.expectOne({ method: 'GET' });
req.flush(new User(1, 'user'));
});
it('should return Authorities', () => {
service.authorities().subscribe(_authorities => {
expect(_authorities).toEqual(['ROLE_USER', 'ROLE_ADMIN']);
});
const req = httpMock.expectOne({ method: 'GET' });
req.flush(['ROLE_USER', 'ROLE_ADMIN']);
});
it('should propagate not found response', () => {
service.find('user').subscribe(null, (_error: any) => {
expect(_error.status).toEqual(404);
});
const req = httpMock.expectOne({ method: 'GET' });
req.flush('Invalid request parameters', {
status: 404,
statusText: 'Bad Request'
});
});
});
});
});

View File

@@ -0,0 +1,135 @@
import { ComponentFixture, TestBed, async, inject, fakeAsync, tick } from '@angular/core/testing';
import { HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { JhiAlertService, JhiEventManager } from 'ng-jhipster';
import { TranslateModule } from '@ngx-translate/core';
import { HsadminNgTestModule } from '../../../test.module';
import { JhiAlertErrorComponent } from 'app/shared/alert/alert-error.component';
import { MockAlertService } from '../../../helpers/mock-alert.service';
describe('Component Tests', () => {
describe('Alert Error Component', () => {
let comp: JhiAlertErrorComponent;
let fixture: ComponentFixture<JhiAlertErrorComponent>;
let eventManager: JhiEventManager;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HsadminNgTestModule, TranslateModule.forRoot()],
declarations: [JhiAlertErrorComponent],
providers: [
JhiEventManager,
{
provide: JhiAlertService,
useClass: MockAlertService
}
]
})
.overrideTemplate(JhiAlertErrorComponent, '')
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(JhiAlertErrorComponent);
comp = fixture.componentInstance;
eventManager = fixture.debugElement.injector.get(JhiEventManager);
});
describe('Error Handling', () => {
it('Should display an alert on status 0', () => {
// GIVEN
eventManager.broadcast({ name: 'hsadminNgApp.httpError', content: { status: 0 } });
// THEN
expect(comp.alerts.length).toBe(1);
expect(comp.alerts[0].msg).toBe('error.server.not.reachable');
});
it('Should display an alert on status 404', () => {
// GIVEN
eventManager.broadcast({ name: 'hsadminNgApp.httpError', content: { status: 404 } });
// THEN
expect(comp.alerts.length).toBe(1);
expect(comp.alerts[0].msg).toBe('error.url.not.found');
});
it('Should display an alert on generic error', () => {
// GIVEN
eventManager.broadcast({ name: 'hsadminNgApp.httpError', content: { error: { message: 'Error Message' } } });
eventManager.broadcast({ name: 'hsadminNgApp.httpError', content: { error: 'Second Error Message' } });
// THEN
expect(comp.alerts.length).toBe(2);
expect(comp.alerts[0].msg).toBe('Error Message');
expect(comp.alerts[1].msg).toBe('Second Error Message');
});
it('Should display an alert on status 400 for generic error', () => {
// GIVEN
const response = new HttpErrorResponse({
url: 'http://localhost:8080/api/foos',
headers: new HttpHeaders(),
status: 400,
statusText: 'Bad Request',
error: {
type: 'https://www.jhipster.tech/problem/constraint-violation',
title: 'Bad Request',
status: 400,
path: '/api/foos',
message: 'error.validation'
}
});
eventManager.broadcast({ name: 'hsadminNgApp.httpError', content: response });
// THEN
expect(comp.alerts.length).toBe(1);
expect(comp.alerts[0].msg).toBe('error.validation');
});
it('Should display an alert on status 400 for generic error without message', () => {
// GIVEN
const response = new HttpErrorResponse({
url: 'http://localhost:8080/api/foos',
headers: new HttpHeaders(),
status: 400,
error: 'Bad Request'
});
eventManager.broadcast({ name: 'hsadminNgApp.httpError', content: response });
// THEN
expect(comp.alerts.length).toBe(1);
expect(comp.alerts[0].msg).toBe('Bad Request');
});
it('Should display an alert on status 400 for invalid parameters', () => {
// GIVEN
const response = new HttpErrorResponse({
url: 'http://localhost:8080/api/foos',
headers: new HttpHeaders(),
status: 400,
statusText: 'Bad Request',
error: {
type: 'https://www.jhipster.tech/problem/constraint-violation',
title: 'Method argument not valid',
status: 400,
path: '/api/foos',
message: 'error.validation',
fieldErrors: [{ objectName: 'foo', field: 'minField', message: 'Min' }]
}
});
eventManager.broadcast({ name: 'hsadminNgApp.httpError', content: response });
// THEN
expect(comp.alerts.length).toBe(1);
expect(comp.alerts[0].msg).toBe('error.Size');
});
it('Should display an alert on status 400 for error headers', () => {
// GIVEN
const response = new HttpErrorResponse({
url: 'http://localhost:8080/api/foos',
headers: new HttpHeaders().append('app-error', 'Error Message').append('app-params', 'foo'),
status: 400,
statusText: 'Bad Request',
error: {
status: 400,
message: 'error.validation'
}
});
eventManager.broadcast({ name: 'hsadminNgApp.httpError', content: response });
// THEN
expect(comp.alerts.length).toBe(1);
expect(comp.alerts[0].msg).toBe('Error Message');
});
});
});
});

View File

@@ -0,0 +1,157 @@
import { ComponentFixture, TestBed, async, inject, fakeAsync, tick } from '@angular/core/testing';
import { Router } from '@angular/router';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { JhiEventManager } from 'ng-jhipster';
import { LoginService } from 'app/core/login/login.service';
import { JhiLoginModalComponent } from 'app/shared/login/login.component';
import { StateStorageService } from 'app/core/auth/state-storage.service';
import { HsadminNgTestModule } from '../../../test.module';
import { MockLoginService } from '../../../helpers/mock-login.service';
import { MockStateStorageService } from '../../../helpers/mock-state-storage.service';
describe('Component Tests', () => {
describe('LoginComponent', () => {
let comp: JhiLoginModalComponent;
let fixture: ComponentFixture<JhiLoginModalComponent>;
let mockLoginService: any;
let mockStateStorageService: any;
let mockRouter: any;
let mockEventManager: any;
let mockActiveModal: any;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HsadminNgTestModule],
declarations: [JhiLoginModalComponent],
providers: [
{
provide: LoginService,
useClass: MockLoginService
},
{
provide: StateStorageService,
useClass: MockStateStorageService
}
]
})
.overrideTemplate(JhiLoginModalComponent, '')
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(JhiLoginModalComponent);
comp = fixture.componentInstance;
mockLoginService = fixture.debugElement.injector.get(LoginService);
mockStateStorageService = fixture.debugElement.injector.get(StateStorageService);
mockRouter = fixture.debugElement.injector.get(Router);
mockEventManager = fixture.debugElement.injector.get(JhiEventManager);
mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal);
});
it('should authenticate the user upon login when previous state was set', inject(
[],
fakeAsync(() => {
// GIVEN
const credentials = {
username: 'admin',
password: 'admin',
rememberMe: true
};
comp.username = 'admin';
comp.password = 'admin';
comp.rememberMe = true;
comp.credentials = credentials;
mockLoginService.setResponse({});
mockStateStorageService.setResponse({ redirect: 'dummy' });
// WHEN/
comp.login();
tick(); // simulate async
// THEN
expect(comp.authenticationError).toEqual(false);
expect(mockActiveModal.dismissSpy).toHaveBeenCalledWith('login success');
expect(mockEventManager.broadcastSpy).toHaveBeenCalledTimes(1);
expect(mockLoginService.loginSpy).toHaveBeenCalledWith(credentials);
expect(mockStateStorageService.getUrlSpy).toHaveBeenCalledTimes(1);
expect(mockStateStorageService.storeUrlSpy).toHaveBeenCalledWith(null);
expect(mockRouter.navigateSpy).toHaveBeenCalledWith([{ redirect: 'dummy' }]);
})
));
it('should authenticate the user upon login when previous state was not set', inject(
[],
fakeAsync(() => {
// GIVEN
const credentials = {
username: 'admin',
password: 'admin',
rememberMe: true
};
comp.username = 'admin';
comp.password = 'admin';
comp.rememberMe = true;
comp.credentials = credentials;
mockLoginService.setResponse({});
mockStateStorageService.setResponse(null);
// WHEN
comp.login();
tick(); // simulate async
// THEN
expect(comp.authenticationError).toEqual(false);
expect(mockActiveModal.dismissSpy).toHaveBeenCalledWith('login success');
expect(mockEventManager.broadcastSpy).toHaveBeenCalledTimes(1);
expect(mockLoginService.loginSpy).toHaveBeenCalledWith(credentials);
expect(mockStateStorageService.getUrlSpy).toHaveBeenCalledTimes(1);
expect(mockStateStorageService.storeUrlSpy).not.toHaveBeenCalled();
expect(mockRouter.navigateSpy).not.toHaveBeenCalled();
})
));
it('should empty the credentials upon cancel', () => {
// GIVEN
const credentials = {
username: 'admin',
password: 'admin',
rememberMe: true
};
const expected = {
username: null,
password: null,
rememberMe: true
};
comp.credentials = credentials;
// WHEN
comp.cancel();
// THEN
expect(comp.authenticationError).toEqual(false);
expect(comp.credentials).toEqual(expected);
expect(mockActiveModal.dismissSpy).toHaveBeenCalledWith('cancel');
});
it('should redirect user when register', () => {
// WHEN
comp.register();
// THEN
expect(mockActiveModal.dismissSpy).toHaveBeenCalledWith('to state register');
expect(mockRouter.navigateSpy).toHaveBeenCalledWith(['/register']);
});
it('should redirect user when request password', () => {
// WHEN
comp.requestResetPassword();
// THEN
expect(mockActiveModal.dismissSpy).toHaveBeenCalledWith('to state requestReset');
expect(mockRouter.navigateSpy).toHaveBeenCalledWith(['/reset', 'request']);
});
});
});

View File

@@ -0,0 +1,35 @@
import { SpyObject } from './spyobject';
import { AccountService } from 'app/core/auth/account.service';
import Spy = jasmine.Spy;
export class MockAccountService extends SpyObject {
getSpy: Spy;
saveSpy: Spy;
fakeResponse: any;
identitySpy: Spy;
constructor() {
super(AccountService);
this.fakeResponse = null;
this.getSpy = this.spy('get').andReturn(this);
this.saveSpy = this.spy('save').andReturn(this);
this.setIdentitySpy({});
}
subscribe(callback: any) {
callback(this.fakeResponse);
}
setResponse(json: any): void {
this.fakeResponse = json;
}
setIdentitySpy(json: any): any {
this.identitySpy = this.spy('identity').andReturn(Promise.resolve(json));
}
setIdentityResponse(json: any): void {
this.setIdentitySpy(json);
}
}

View File

@@ -0,0 +1,12 @@
import { SpyObject } from './spyobject';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import Spy = jasmine.Spy;
export class MockActiveModal extends SpyObject {
dismissSpy: Spy;
constructor() {
super(NgbActiveModal);
this.dismissSpy = this.spy('dismiss').andReturn(this);
}
}

View File

@@ -0,0 +1,11 @@
import { SpyObject } from './spyobject';
import { JhiAlertService, JhiAlert } from 'ng-jhipster';
export class MockAlertService extends SpyObject {
constructor() {
super(JhiAlertService);
}
addAlert(alertOptions: JhiAlert) {
return alertOptions;
}
}

View File

@@ -0,0 +1,12 @@
import { SpyObject } from './spyobject';
import { JhiEventManager } from 'ng-jhipster';
import Spy = jasmine.Spy;
export class MockEventManager extends SpyObject {
broadcastSpy: Spy;
constructor() {
super(JhiEventManager);
this.broadcastSpy = this.spy('broadcast').andReturn(this);
}
}

View File

@@ -0,0 +1,36 @@
import { SpyObject } from './spyobject';
import { JhiLanguageService } from 'ng-jhipster';
import { JhiLanguageHelper } from 'app/core/language/language.helper';
import Spy = jasmine.Spy;
export class MockLanguageService extends SpyObject {
getCurrentSpy: Spy;
fakeResponse: any;
constructor() {
super(JhiLanguageService);
this.fakeResponse = 'de';
this.getCurrentSpy = this.spy('getCurrent').andReturn(Promise.resolve(this.fakeResponse));
}
init() {}
changeLanguage(languageKey: string) {}
setLocations(locations: string[]) {}
addLocation(location: string) {}
reload() {}
}
export class MockLanguageHelper extends SpyObject {
getAllSpy: Spy;
constructor() {
super(JhiLanguageHelper);
this.getAllSpy = this.spy('getAll').andReturn(Promise.resolve(['en', 'fr']));
}
}

View File

@@ -0,0 +1,29 @@
import { SpyObject } from './spyobject';
import { LoginService } from 'app/core/login/login.service';
import Spy = jasmine.Spy;
export class MockLoginService extends SpyObject {
loginSpy: Spy;
logoutSpy: Spy;
registerSpy: Spy;
requestResetPasswordSpy: Spy;
cancelSpy: Spy;
constructor() {
super(LoginService);
this.setLoginSpy({});
this.logoutSpy = this.spy('logout').andReturn(this);
this.registerSpy = this.spy('register').andReturn(this);
this.requestResetPasswordSpy = this.spy('requestResetPassword').andReturn(this);
this.cancelSpy = this.spy('cancel').andReturn(this);
}
setLoginSpy(json: any) {
this.loginSpy = this.spy('login').andReturn(Promise.resolve(json));
}
setResponse(json: any): void {
this.setLoginSpy(json);
}
}

View File

@@ -0,0 +1,29 @@
import { ActivatedRoute, Router } from '@angular/router';
import { SpyObject } from './spyobject';
import { Observable, of } from 'rxjs';
import Spy = jasmine.Spy;
export class MockActivatedRoute extends ActivatedRoute {
constructor(parameters?: any) {
super();
this.queryParams = of(parameters);
this.params = of(parameters);
this.data = of({
...parameters,
pagingParams: {
page: 10,
ascending: false,
predicate: 'id'
}
});
}
}
export class MockRouter extends SpyObject {
navigateSpy: Spy;
constructor() {
super(Router);
this.navigateSpy = this.spy('navigate');
}
}

View File

@@ -0,0 +1,22 @@
import { SpyObject } from './spyobject';
import { StateStorageService } from 'app/core/auth/state-storage.service';
import Spy = jasmine.Spy;
export class MockStateStorageService extends SpyObject {
getUrlSpy: Spy;
storeUrlSpy: Spy;
constructor() {
super(StateStorageService);
this.setUrlSpy({});
this.storeUrlSpy = this.spy('storeUrl').andReturn(this);
}
setUrlSpy(json) {
this.getUrlSpy = this.spy('getUrl').andReturn(json);
}
setResponse(json: any): void {
this.setUrlSpy(json);
}
}

View File

@@ -0,0 +1,69 @@
export interface GuinessCompatibleSpy extends jasmine.Spy {
/** By chaining the spy with and.returnValue, all calls to the function will return a specific
* value. */
andReturn(val: any): void;
/** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied
* function. */
andCallFake(fn: Function): GuinessCompatibleSpy;
/** removes all recorded calls */
reset();
}
export class SpyObject {
static stub(object = null, config = null, overrides = null) {
if (!(object instanceof SpyObject)) {
overrides = config;
config = object;
object = new SpyObject();
}
const m = {};
Object.keys(config).forEach(key => (m[key] = config[key]));
Object.keys(overrides).forEach(key => (m[key] = overrides[key]));
Object.keys(m).forEach(key => {
object.spy(key).andReturn(m[key]);
});
return object;
}
constructor(type = null) {
if (type) {
Object.keys(type.prototype).forEach(prop => {
let m = null;
try {
m = type.prototype[prop];
} catch (e) {
// As we are creating spys for abstract classes,
// these classes might have getters that throw when they are accessed.
// As we are only auto creating spys for methods, this
// should not matter.
}
if (typeof m === 'function') {
this.spy(prop);
}
});
}
}
spy(name) {
if (!this[name]) {
this[name] = this._createGuinnessCompatibleSpy(name);
}
return this[name];
}
prop(name, value) {
this[name] = value;
}
/** @internal */
_createGuinnessCompatibleSpy(name): GuinessCompatibleSpy {
const newSpy: GuinessCompatibleSpy = <any>jasmine.createSpy(name);
newSpy.andCallFake = <any>newSpy.and.callFake;
newSpy.andReturn = <any>newSpy.and.returnValue;
newSpy.reset = <any>newSpy.calls.reset;
// revisit return null here (previously needed for rtts_assert).
newSpy.and.returnValue(null);
return newSpy;
}
}

View File

@@ -0,0 +1,72 @@
import { DatePipe } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { NgModule, ElementRef, Renderer } from '@angular/core';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { JhiLanguageService, JhiDataUtils, JhiDateUtils, JhiEventManager, JhiAlertService, JhiParseLinks } from 'ng-jhipster';
import { MockLanguageService, MockLanguageHelper } from './helpers/mock-language.service';
import { JhiLanguageHelper, AccountService, LoginModalService } from 'app/core';
import { MockAccountService } from './helpers/mock-account.service';
import { MockActivatedRoute, MockRouter } from './helpers/mock-route.service';
import { MockActiveModal } from './helpers/mock-active-modal.service';
import { MockEventManager } from './helpers/mock-event-manager.service';
@NgModule({
providers: [
DatePipe,
JhiDataUtils,
JhiDateUtils,
JhiParseLinks,
{
provide: JhiLanguageService,
useClass: MockLanguageService
},
{
provide: JhiLanguageHelper,
useClass: MockLanguageHelper
},
{
provide: JhiEventManager,
useClass: MockEventManager
},
{
provide: NgbActiveModal,
useClass: MockActiveModal
},
{
provide: ActivatedRoute,
useValue: new MockActivatedRoute({ id: 123 })
},
{
provide: Router,
useClass: MockRouter
},
{
provide: AccountService,
useClass: MockAccountService
},
{
provide: LoginModalService,
useValue: null
},
{
provide: ElementRef,
useValue: null
},
{
provide: Renderer,
useValue: null
},
{
provide: JhiAlertService,
useValue: null
},
{
provide: NgbModal,
useValue: null
}
],
imports: [HttpClientTestingModule]
})
export class HsadminNgTestModule {}

View File

@@ -0,0 +1,107 @@
# ===================================================================
# Spring Boot configuration.
#
# This configuration is used for unit/integration tests.
#
# More information on profiles: https://www.jhipster.tech/profiles/
# More information on configuration properties: https://www.jhipster.tech/common-application-properties/
# ===================================================================
# ===================================================================
# Standard Spring Boot properties.
# Full reference is available at:
# http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
# ===================================================================
spring:
application:
name: hsadminNg
cache:
type: simple
datasource:
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:h2:mem:hsadminNg;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
name:
username:
password:
hikari:
auto-commit: false
jpa:
database-platform: io.github.jhipster.domain.util.FixedH2Dialect
database: H2
open-in-view: false
show-sql: false
hibernate:
ddl-auto: none
naming:
physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
implicit-strategy: org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy
properties:
hibernate.id.new_generator_mappings: true
hibernate.connection.provider_disables_autocommit: true
hibernate.cache.use_second_level_cache: false
hibernate.cache.use_query_cache: false
hibernate.generate_statistics: false
hibernate.hbm2ddl.auto: validate
hibernate.jdbc.time_zone: UTC
liquibase:
contexts: test
mail:
host: localhost
messages:
basename: i18n/messages
mvc:
favicon:
enabled: false
thymeleaf:
mode: HTML
server:
port: 10344
address: localhost
# ===================================================================
# JHipster specific properties
#
# Full reference is available at: https://www.jhipster.tech/common-application-properties/
# ===================================================================
jhipster:
async:
core-pool-size: 1
max-pool-size: 50
queue-capacity: 10000
# To test logstash appender
logging:
logstash:
enabled: true
host: localhost
port: 5000
queue-size: 512
mail:
from: test@localhost
base-url: http://127.0.0.1:8080
security:
authentication:
jwt:
# This token must be encoded using Base64 (you can type `echo 'secret-key'|base64` on your command line)
base64-secret: ZDFlMDUzODIzMTUzZDEwZjExN2E5ZjAzY2VhZmYzNDE1YjhlYWUxZGRhMGU3ODZiNjRkNjVlNzEwZjExYWY4YzczM2NlYzI5YWE1OTRkNWM0YThlYjZjZjA5Zjc5YWJkOTgzYjdhZjQxZWQyZGUyYjFlYjI5ZDE3NmE4M2UzYjQ=
# Token is valid 24 hours
token-validity-in-seconds: 86400
metrics:
logs: # Reports metrics in the logs
enabled: true
report-frequency: 60 # in seconds
# ===================================================================
# Application specific properties
# Add your own application properties here, see the ApplicationProperties class
# to have type-safe configuration, like in the JHipsterProperties above
#
# More documentation is available at:
# https://www.jhipster.tech/common-application-properties/
# ===================================================================
# application:

View File

@@ -0,0 +1 @@
email.test.title=test title

View File

@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration>
<configuration scan="true">
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<logger name="org.hostsharing.hsadminng" level="INFO"/>
<logger name="io.github.jhipster" level="WARN"/>
<logger name="javax.activation" level="WARN"/>
<logger name="javax.mail" level="WARN"/>
<logger name="javax.xml.bind" level="WARN"/>
<logger name="ch.qos.logback" level="WARN"/>
<logger name="com.ryantenney" level="WARN"/>
<logger name="com.sun" level="WARN"/>
<logger name="com.zaxxer" level="WARN"/>
<logger name="io.undertow" level="WARN"/>
<logger name="io.undertow.websockets.jsr" level="ERROR"/>
<logger name="org.ehcache" level="WARN"/>
<logger name="org.apache" level="WARN"/>
<logger name="org.apache.catalina.startup.DigesterFactory" level="OFF"/>
<logger name="org.bson" level="WARN"/>
<logger name="org.hibernate.validator" level="WARN"/>
<logger name="org.hibernate" level="WARN"/>
<logger name="org.hibernate.ejb.HibernatePersistence" level="OFF"/>
<logger name="org.postgresql.jdbc" level="WARN"/>
<logger name="org.springframework" level="WARN"/>
<logger name="org.springframework.web" level="WARN"/>
<logger name="org.springframework.security" level="WARN"/>
<logger name="org.springframework.cache" level="WARN"/>
<logger name="org.thymeleaf" level="WARN"/>
<logger name="org.xnio" level="WARN"/>
<logger name="springfox" level="WARN"/>
<logger name="sun.rmi" level="WARN"/>
<logger name="liquibase" level="WARN"/>
<logger name="LiquibaseSchemaResolver" level="INFO"/>
<logger name="sun.rmi.transport" level="WARN"/>
<root level="WARN">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>

View File

@@ -0,0 +1 @@
<html xmlns:th="http://www.thymeleaf.org" th:text="|#{email.test.title}, ${baseUrl}, ${user.login}|"></html>