1
0

removing JHipster

This commit is contained in:
Michael Hoennig
2022-07-22 13:31:37 +02:00
parent 31cd92f3be
commit f2d0fbe67a
747 changed files with 2225 additions and 92268 deletions

View File

@@ -1,193 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.config;
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;
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 java.util.*;
import javax.servlet.*;
/**
* 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

@@ -1,17 +0,0 @@
// Licensed under Apache-2.0
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

@@ -1,178 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.config.timezone;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
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;
/**
* 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

@@ -1,23 +0,0 @@
// Licensed under Apache-2.0
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

@@ -1,13 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.cucumber;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)
@CucumberOptions(plugin = "pretty", features = "src/test/features")
public class CucumberTest {
}

View File

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

View File

@@ -1,49 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.cucumber.stepdefs;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.hostsharing.hsadminng.web.rest.UserResource;
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;
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

@@ -1,165 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.liquibase;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.ThrowableAssert.catchThrowable;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import liquibase.database.Database;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.CustomChangeException;
import liquibase.exception.DatabaseException;
import liquibase.exception.SetupException;
import com.google.common.base.VerifyException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import java.sql.SQLException;
import java.sql.Statement;
public class ReplaceCustomChangeUnitTest {
private static final String POSTGRES_DATABASE_PRODUCT_NAME = "PostgreSQL";
private static final String H2_DATABASE_PRODUCT_NAME = "H2";
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock
private Database database;
@Mock
private JdbcConnection connection;
@Mock
private Statement statement;
@Before
public void initMocks() throws DatabaseException {
given(database.getConnection()).willReturn(connection);
given(connection.getAutoCommit()).willReturn(false);
given(connection.createStatement()).willReturn(statement);
}
@Test
public void updatesForPostgres() throws Exception {
// given
given(database.getDatabaseProductName()).willReturn(POSTGRES_DATABASE_PRODUCT_NAME);
final ReplaceCustomChange replaceCustomChange = givenReplaceCustomChange("some_table", "address,remark", "|", "\\n");
// when
replaceCustomChange.execute(database);
// then
verify(statement).executeUpdate("UPDATE some_table SET address= replace(address, '|', E'\\n')");
verify(statement).executeUpdate("UPDATE some_table SET remark= replace(remark, '|', E'\\n')");
}
@Test
public void updatesForH2() throws Exception {
// given
given(database.getDatabaseProductName()).willReturn(H2_DATABASE_PRODUCT_NAME);
final ReplaceCustomChange replaceCustomChange = givenReplaceCustomChange("some_table", "address,remark", "|", "\\n");
// when
replaceCustomChange.execute(database);
// then
verify(statement).executeUpdate("UPDATE some_table SET address= replace(address, '|', STRINGDECODE('\\n'))");
verify(statement).executeUpdate("UPDATE some_table SET remark= replace(remark, '|', STRINGDECODE('\\n'))");
}
@Test
public void getConfirmationMessage() throws Exception {
// given
final ReplaceCustomChange replaceCustomChange = givenReplaceCustomChange("some_table", "address,remark", "|", "\\n");
// when
final String actual = replaceCustomChange.getConfirmationMessage();
// then
assertThat(actual).isEqualTo("in table some_table / columns address,remark: replaced all '|' to '\\n'");
}
@Test
public void throwsValidationErrorIfAutoCommitIsOff() throws Exception {
// given
given(database.getDatabaseProductName()).willReturn(POSTGRES_DATABASE_PRODUCT_NAME);
final ReplaceCustomChange replaceCustomChange = givenReplaceCustomChange("some_table", "address,remark", "|", "\\n");
given(connection.getAutoCommit()).willReturn(true);
// when
final Throwable actual = catchThrowable(() -> replaceCustomChange.execute(database));
// then
assertThat(actual).isInstanceOf(VerifyException.class);
}
@Test
public void onDatabaseExceptionThrowsCustomChangeException() throws Exception {
// given
given(database.getDatabaseProductName()).willReturn(POSTGRES_DATABASE_PRODUCT_NAME);
final ReplaceCustomChange replaceCustomChange = givenReplaceCustomChange("some_table", "address,remark", "|", "\\n");
final Exception givenCausingException = new DatabaseException("dummy");
given(connection.createStatement()).willThrow(givenCausingException);
// when
final Throwable actual = catchThrowable(() -> replaceCustomChange.execute(database));
// then
assertThat(actual).isInstanceOfSatisfying(
CustomChangeException.class,
(cce) -> assertThat(cce.getCause()).isSameAs(givenCausingException));
}
@Test
public void onSQLExceptionThrowsCustomChangeException() throws Exception {
// given
given(database.getDatabaseProductName()).willReturn(POSTGRES_DATABASE_PRODUCT_NAME);
final ReplaceCustomChange replaceCustomChange = givenReplaceCustomChange("some_table", "address,remark", "|", "\\n");
final Exception givenCausingException = new SQLException("dummy");
given(statement.executeUpdate(anyString())).willThrow(givenCausingException);
// when
final Throwable actual = catchThrowable(() -> replaceCustomChange.execute(database));
// then
assertThat(actual).isInstanceOfSatisfying(
CustomChangeException.class,
(cce) -> assertThat(cce.getCause()).isSameAs(givenCausingException));
}
@Test
public void setFileOpenerDoesNothing() {
new ReplaceCustomChange().setFileOpener(null);
}
@Test
public void validateDoesNothing() {
new ReplaceCustomChange().validate(null);
}
// --- only test fixture below ---
private ReplaceCustomChange givenReplaceCustomChange(
final String some_table,
final String columns,
final String searchFor,
final String replaceWith) throws SetupException {
final ReplaceCustomChange replaceCustomChange = new ReplaceCustomChange();
replaceCustomChange.setUp();
replaceCustomChange.setTableName(some_table);
replaceCustomChange.setColumnNames(columns);
replaceCustomChange.setSearchFor(searchFor);
replaceCustomChange.setReplaceWith(replaceWith);
return replaceCustomChange;
}
}

View File

@@ -1,76 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.repository;
import static org.assertj.core.api.Assertions.assertThat;
import org.hostsharing.hsadminng.HsadminNgApp;
import org.hostsharing.hsadminng.domain.Asset;
import org.hostsharing.hsadminng.domain.Customer;
import org.hostsharing.hsadminng.domain.Membership;
import org.hostsharing.hsadminng.domain.enumeration.AssetAction;
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 org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.LocalDate;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HsadminNgApp.class)
@Transactional
public class AssetRepositoryIntTest {
@Autowired
private CustomerRepository customerRepository;
@Autowired
private MembershipRepository membershipRepository;
@Autowired
private AssetRepository assetRepository;
@Test
public void sequenceStartsAbove1000000ToSpareIdsForSampleData() {
// given
final Asset givenAsset = createArbitraryAsset();
// when
assetRepository.save(givenAsset);
// then
assertThat(givenAsset.getId()).isGreaterThan(1000000);
}
// --- only test fixture below ---
private Customer createPersistentCustomer() {
return customerRepository.save(CustomerRepositoryIntTest.createCustomer());
}
private Membership createPersistentMembership() {
return membershipRepository
.save(MembershipRepositoryIntTest.createMembership(createPersistentCustomer(), "2019-01-08", null));
}
static Asset createAsset(
final Membership membership,
final AssetAction action,
final String amount,
final String documentDate) {
final Asset asset = new Asset();
asset.setMembership(membership);
asset.setAction(action);
asset.setAmount(new BigDecimal(amount));
asset.setDocumentDate(LocalDate.parse(documentDate));
asset.setValueDate(LocalDate.parse(documentDate).plusDays(1));
return asset;
}
private Asset createArbitraryAsset() {
return createAsset(createPersistentMembership(), AssetAction.PAYMENT, "160.00", "2019-01-08");
}
}

View File

@@ -1,168 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.repository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hostsharing.hsadminng.repository.CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH;
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 java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
/**
* 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

@@ -1,52 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.repository;
import static org.assertj.core.api.Assertions.assertThat;
import org.hostsharing.hsadminng.HsadminNgApp;
import org.hostsharing.hsadminng.domain.Customer;
import org.hostsharing.hsadminng.domain.enumeration.CustomerKind;
import org.hostsharing.hsadminng.domain.enumeration.VatRegion;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
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 org.springframework.transaction.annotation.Transactional;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HsadminNgApp.class)
@Transactional
public class CustomerRepositoryIntTest {
@Autowired
private CustomerRepository customerRepository;
@Test
public void sequenceStartsAbove1000000ToSpareIdsForSampleData() {
// given
final Customer givenCustomer = createCustomer();
// when
customerRepository.save(givenCustomer);
// then
assertThat(givenCustomer.getId()).isGreaterThan(1000000);
}
// --- only test fixture below ---
static Customer createCustomer() {
final Customer customer = new Customer();
customer.setPrefix(RandomStringUtils.randomAlphabetic(3).toLowerCase());
customer.setReference(RandomUtils.nextInt(10001, 19999));
customer.setName(RandomStringUtils.randomAlphabetic(10));
customer.setContractualAddress(RandomStringUtils.randomAlphabetic(10));
customer.setKind(CustomerKind.NATURAL);
customer.setVatRegion(VatRegion.DOMESTIC);
return customer;
}
}

View File

@@ -1,104 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.repository;
import static org.assertj.core.api.Assertions.assertThat;
import org.hostsharing.hsadminng.HsadminNgApp;
import org.hostsharing.hsadminng.domain.Customer;
import org.hostsharing.hsadminng.domain.Membership;
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 org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HsadminNgApp.class)
@Transactional
public class MembershipRepositoryIntTest {
@Autowired
private CustomerRepository customerRepository;
@Autowired
private MembershipRepository membershipRepository;
@Test
public void sequenceStartsAbove1000000ToSpareIdsForSampleData() {
// given
final Membership givenMembership = createMembership(createPersistentCustomer(), "2019-01-01", null);
// when
membershipRepository.save(givenMembership);
// then
assertThat(givenMembership.getId()).isGreaterThan(1000000);
}
@Test
public void hasUncancelledMembershipForCustomerIsTrueForCustomerWithUncancelledMembership() {
// given
final Customer givenCustomerWithUncancelledMembership = createPersistentCustomerWithMembership("2011-08-18", null);
// when
boolean actual = membershipRepository
.hasUncancelledMembershipForCustomer(givenCustomerWithUncancelledMembership.getId());
// then
assertThat(actual).isTrue();
}
@Test
public void hasUncancelledMembershipForCustomerIsFalseForCustomerWithoutMembership() {
// given
final Customer givenCustomerWithoutMembership = createPersistentCustomer();
// when
boolean actual = membershipRepository.hasUncancelledMembershipForCustomer(givenCustomerWithoutMembership.getId());
// then
assertThat(actual).isFalse();
}
@Test
public void hasUncancelledMembershipForCustomerIsFalseForCustomerWithCancelledMembership() {
// given
final Customer givenCustomerWithCancelledMembership = createPersistentCustomerWithMembership(
"2011-08-18",
"2017-12-31");
// when
boolean actual = membershipRepository.hasUncancelledMembershipForCustomer(givenCustomerWithCancelledMembership.getId());
// then
assertThat(actual).isFalse();
}
// --- only test fixture below ---
private Customer createPersistentCustomer() {
return customerRepository.save(CustomerRepositoryIntTest.createCustomer());
}
private Customer createPersistentCustomerWithMembership(final String from, final String to) {
final Customer customer = createPersistentCustomer();
final Membership membership = createMembership(customer, from, to);
membershipRepository.save(membership);
return customer;
}
static Membership createMembership(final Customer customer, final String from, final String to) {
final Membership membership = new Membership();
membership.setCustomer(customer);
membership.setMemberFromDate(LocalDate.parse(from));
if (to != null) {
membership.setMemberUntilDate(LocalDate.parse(to));
}
membership.setAdmissionDocumentDate(membership.getMemberFromDate().minusDays(7));
return membership;
}
}

View File

@@ -1,62 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.repository;
import static org.assertj.core.api.Assertions.assertThat;
import org.hostsharing.hsadminng.HsadminNgApp;
import org.hostsharing.hsadminng.domain.Customer;
import org.hostsharing.hsadminng.domain.SepaMandate;
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 org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HsadminNgApp.class)
@Transactional
public class SepaMandateRepositoryIntTest {
@Autowired
private CustomerRepository customerRepository;
@Autowired
private SepaMandateRepository sepaMandateRepository;
@Test
public void sequenceStartsAbove1000000ToSpareIdsForSampleData() {
// given
final SepaMandate givenSepaMandate = createSepaMandate(createPersistentCustomer(), "DUMMY_REF", "2019-01-08", null);
// when
sepaMandateRepository.save(givenSepaMandate);
// then
assertThat(givenSepaMandate.getId()).isGreaterThan(1000000);
}
// --- only test fixture below ---
private Customer createPersistentCustomer() {
return customerRepository.save(CustomerRepositoryIntTest.createCustomer());
}
static SepaMandate createSepaMandate(final Customer customer, final String reference, final String from, final String to) {
final SepaMandate sepaMandate = new SepaMandate();
sepaMandate.setCustomer(customer);
sepaMandate.setReference(reference);
sepaMandate.setIban("NL57ABNA2228161411");
sepaMandate.setBic("ABNANL2A");
sepaMandate.setGrantingDocumentDate(LocalDate.parse(from));
sepaMandate.setValidFromDate(LocalDate.parse(from).plusDays(1));
if (to != null) {
sepaMandate.setRevokationDocumentDate(LocalDate.parse(to));
sepaMandate.setValidUntilDate(LocalDate.parse(to).plusDays(7));
}
return sepaMandate;
}
}

View File

@@ -1,75 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.repository;
import static org.assertj.core.api.Assertions.assertThat;
import org.hostsharing.hsadminng.HsadminNgApp;
import org.hostsharing.hsadminng.domain.Customer;
import org.hostsharing.hsadminng.domain.Membership;
import org.hostsharing.hsadminng.domain.Share;
import org.hostsharing.hsadminng.domain.enumeration.ShareAction;
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 org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HsadminNgApp.class)
@Transactional
public class ShareRepositoryIntTest {
@Autowired
private CustomerRepository customerRepository;
@Autowired
private MembershipRepository membershipRepository;
@Autowired
private ShareRepository shareRepository;
@Test
public void sequenceStartsAbove1000000ToSpareIdsForSampleData() {
// given
final Share givenShare = createArbitraryShare();
// when
shareRepository.save(givenShare);
// then
assertThat(givenShare.getId()).isGreaterThan(1000000);
}
// --- only test fixture below ---
private Customer createPersistentCustomer() {
return customerRepository.save(CustomerRepositoryIntTest.createCustomer());
}
private Membership createPersistentMembership() {
return membershipRepository
.save(MembershipRepositoryIntTest.createMembership(createPersistentCustomer(), "2019-01-08", null));
}
static Share createShare(
final Membership membership,
final ShareAction action,
final int quantity,
final String documentDate) {
final Share share = new Share();
share.setMembership(membership);
share.setAction(action);
share.setQuantity(quantity);
share.setDocumentDate(LocalDate.parse(documentDate));
share.setValueDate(LocalDate.parse(documentDate).plusDays(1));
return share;
}
private Share createArbitraryShare() {
return createShare(createPersistentMembership(), ShareAction.SUBSCRIPTION, 1, "2019-01-08");
}
}

View File

@@ -1,134 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.repository.timezone;
import java.io.Serializable;
import java.time.*;
import java.util.Objects;
import javax.persistence.*;
@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

@@ -1,13 +0,0 @@
// Licensed under Apache-2.0
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

@@ -1,128 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.security;
import static org.assertj.core.api.Assertions.assertThat;
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;
/**
* 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

@@ -1,74 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.security;
import static org.assertj.core.api.Assertions.assertThat;
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;
/**
* 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

@@ -1,119 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.security.jwt;
import static org.assertj.core.api.Assertions.assertThat;
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;
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

@@ -1,116 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.security.jwt;
import static org.assertj.core.api.Assertions.assertThat;
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
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 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 java.security.Key;
import java.util.*;
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

@@ -1,180 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.*;
import org.hostsharing.hsadminng.domain.Asset;
import org.hostsharing.hsadminng.domain.enumeration.AssetAction;
import org.hostsharing.hsadminng.repository.AssetRepository;
import org.hostsharing.hsadminng.service.dto.AssetDTO;
import org.hostsharing.hsadminng.service.mapper.AssetMapper;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import java.math.BigDecimal;
import javax.persistence.EntityManager;
// HINT: In IntelliJ IDEA such unit test classes can be created with Shift-Ctrl-T.
// Do not forget to amend the class name (.e.g. ...UnitTest / ...IntTest)!
public class AssetServiceUnitTest {
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock
private EntityManager em;
@Mock
private AssetRepository assetRepository;
@Mock
private AssetValidator assetValidator; // needed for @InjectMocks assetService
@Mock
private AssetMapper assetMapper;
@InjectMocks
private AssetService assetService;
// HINT: Click outside of any test method (e.g. here) and use Ctrl-Shift-F10
// to run all tests from this test class. Use Ctrl-F5 to run the last execution again;
// 'execution' here can also apply to running the application, whatever ran last.
// HINT: In IntelliJ IDEA such test methods can be created with Alt-Insert.
@Test
public void deleteIsRejectedForAssetTransactions() {
// when
final Throwable throwException = catchThrowableOfType(
() -> assetService.delete(RandomUtils.nextLong()),
BadRequestAlertException.class);
// then
// HINT: When using auto-import for assertions (e.g. via Alt-Enter in IntelliJ IDEA),
// beware to use the correct candidate from org.assertj.core.api.Assertions.
assertThat(throwException).isEqualToComparingFieldByField(
new BadRequestAlertException("Asset transactions are immutable", "asset", "assetTransactionImmutable"));
}
@Test
public void saveShouldPersistValidTransactions() {
// given
final AssetDTO givenAssetDTO = givenAssetDTO(null, AssetAction.PAYMENT, anyPositiveAmout());
// HINT: given(...)...will...() can't be used for void methods, in that case use Mockito's do...() methods
doNothing().when(assetValidator).validate(givenAssetDTO);
// when
final AssetDTO returnedAssetDto = assetService.save(givenAssetDTO);
// then
verify(em).flush();
verify(em).refresh(any(Asset.class));
assertThat(returnedAssetDto).isEqualToIgnoringGivenFields(givenAssetDTO, "id");
}
@Test
public void saveShouldNotPersistInvalidTransactions() {
// given
final AssetDTO givenAssetDTO = givenAssetDTO(null, AssetAction.PAYMENT, anyNegativeAmount());
doThrow(new BadRequestAlertException("Some Dummy Test Violation", "asset", "assetInvalidTestDummy"))
.when(assetValidator)
.validate(givenAssetDTO);
// when
final Throwable throwException = catchThrowableOfType(
() -> assetService.save(givenAssetDTO),
BadRequestAlertException.class);
// then
assertThat(throwException).isEqualToComparingFieldByField(
new BadRequestAlertException("Some Dummy Test Violation", "asset", "assetInvalidTestDummy"));
}
@Test
public void saveShouldUpdateValidTransactions() {
// given
final AssetDTO givenAssetDTO = givenAssetDTO(anyNonNullId(), AssetAction.PAYMENT, anyPositiveAmout());
doNothing().when(assetValidator).validate(givenAssetDTO);
// when
final AssetDTO returnedAssetDto = assetService.save(givenAssetDTO);
// then
verify(em).flush();
verify(em).refresh(any(Asset.class));
assertThat(returnedAssetDto).isEqualToIgnoringGivenFields(givenAssetDTO, "id");
}
@Test
public void saveShouldNotUpdateInvalidTransactions() {
// given
final AssetDTO givenAssetDTO = givenAssetDTO(anyNonNullId(), AssetAction.PAYMENT, anyNegativeAmount());
// HINT: given(...) can't be used for void methods, in that case use Mockito's do...() methods
doThrow(new BadRequestAlertException("Some Dummy Test Violation", "asset", "assetInvalidTestDummy"))
.when(assetValidator)
.validate(givenAssetDTO);
// when
final Throwable throwException = catchThrowableOfType(
() -> assetService.save(givenAssetDTO),
BadRequestAlertException.class);
// then
assertThat(throwException).isEqualToComparingFieldByField(
new BadRequestAlertException("Some Dummy Test Violation", "asset", "assetInvalidTestDummy"));
}
// --- only test fixture code below ---
private long anyNonNullId() {
return RandomUtils.nextInt();
}
// HINT: This rather complicated setup indicates that the method AssetService::save breaks the single responsibility
// principle.
private AssetDTO givenAssetDTO(final Long id, final AssetAction givenAction, final BigDecimal givenQuantity) {
final AssetDTO givenAssetDTO = createAssetDTO(id, givenAction, givenQuantity);
// dto -> entity
final Asset givenAssetEntity = Mockito.mock(Asset.class);
given(assetMapper.toEntity(same(givenAssetDTO))).willReturn(givenAssetEntity);
// assetRepository.save(entity);
final Asset persistedAssetEntity = Mockito.mock(Asset.class);
given(assetRepository.save(same(givenAssetEntity))).willReturn(persistedAssetEntity);
// entity -> dto
AssetDTO persistedAssetDTO = createAssetDTO(id == null ? RandomUtils.nextLong() : id, givenAction, givenQuantity);
given(assetMapper.toDto(same(persistedAssetEntity))).willReturn(persistedAssetDTO);
return givenAssetDTO;
}
private AssetDTO createAssetDTO(Long id, AssetAction givenAction, BigDecimal givenAmount) {
final AssetDTO givenAssetDTO = new AssetDTO();
givenAssetDTO.setId(id);
givenAssetDTO.setAction(givenAction);
givenAssetDTO.setAmount(givenAmount);
return givenAssetDTO;
}
private BigDecimal anyPositiveAmout() {
return BigDecimal.valueOf(RandomUtils.nextInt()).add(new BigDecimal("0.1"));
}
private BigDecimal anyNegativeAmount() {
return anyPositiveAmout().negate();
}
}

View File

@@ -1,318 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
import org.hostsharing.hsadminng.domain.enumeration.AssetAction;
import org.hostsharing.hsadminng.service.dto.AssetDTO;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import com.google.common.collect.ImmutableList;
import org.apache.commons.lang3.RandomUtils;
import org.assertj.core.api.AbstractThrowableAssert;
import org.junit.Test;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.function.Consumer;
public class AssetValidatorUnitTest {
private AssetValidator assetValidator = new AssetValidator();
@Test
public void shouldAcceptValidIncreasingTransaction() {
for (AssetAction action : ImmutableList.of(AssetAction.PAYMENT, AssetAction.ADOPTION)) {
new GivenAssetValidationTestCase()
.withAnyValidDateValues()
.withAction(action)
.withAmount("64.00")
.when((AssetDTO assetDto) -> assetValidator.validate(assetDto))
.thenActualException()
.isNull();
}
}
@Test
public void shouldAcceptValidDecreasingTransaction() {
for (AssetAction action : ImmutableList
.of(AssetAction.PAYBACK, AssetAction.HANDOVER, AssetAction.CLEARING, AssetAction.LOSS)) {
new GivenAssetValidationTestCase()
.withAnyValidDateValues()
.withAction(action)
.withAmount("-64.00")
.when((AssetDTO assetDto) -> assetValidator.validate(assetDto))
.thenActualException()
.isNull();
}
}
@Test
public void shouldAcceptIfDocumentDateEqualsValueDate() {
new GivenAssetValidationTestCase()
.withDocumentDate("2019-04-11")
.withValueDate("2019-04-11")
.withAction(AssetAction.PAYMENT)
.withAmount("64.00")
.when((AssetDTO assetDto) -> assetValidator.validate(assetDto))
.thenActualException()
.isNull();
}
@Test
public void shouldRejectUpdates() {
new GivenAssetValidationTestCase()
.withId(RandomUtils.nextLong())
.when((AssetDTO assetDto) -> assetValidator.validate(assetDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Asset transactions are immutable",
"asset",
"assetTransactionImmutable"));
}
@Test
public void shouldRejectIfDocumentDateAfterValueDate() {
new GivenAssetValidationTestCase()
.withDocumentDate("2019-04-13")
.withValueDate("2019-04-12")
.withAction(AssetAction.PAYMENT)
.withAmount("64.00")
.when((AssetDTO assetDto) -> assetValidator.validate(assetDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Document date may not be after value date",
"asset",
"documentDateMayNotBeAfterValueDate"));
}
@Test
public void shouldRejectIfPaymentWithNegativeAmount() {
new GivenAssetValidationTestCase()
.withAnyValidDateValues()
.withAction(AssetAction.PAYMENT)
.withAmount("-64.00")
.when((AssetDTO assetDto) -> assetValidator.validate(assetDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Asset payments require a positive amount",
"asset",
"assetPaymentsPositiveAmount"));
}
@Test
public void shouldRejectIfPaymentWithZeroAmount() {
new GivenAssetValidationTestCase()
.withAnyValidDateValues()
.withAction(AssetAction.PAYMENT)
.withAmount("0.00")
.when((AssetDTO assetDto) -> assetValidator.validate(assetDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Asset payments require a positive amount",
"asset",
"assetPaymentsPositiveAmount"));
}
@Test
public void shouldRejectIfAdoptionWithNegativeAmount() {
new GivenAssetValidationTestCase()
.withAnyValidDateValues()
.withAction(AssetAction.ADOPTION)
.withAmount("-64.00")
.when((AssetDTO assetDto) -> assetValidator.validate(assetDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Asset adoptions require a positive amount",
"asset",
"assetAdoptionsPositiveAmount"));
}
@Test
public void shouldRejectIfAdoptionWithZeroAmount() {
new GivenAssetValidationTestCase()
.withAnyValidDateValues()
.withAction(AssetAction.ADOPTION)
.withAmount("0.00")
.when((AssetDTO assetDto) -> assetValidator.validate(assetDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Asset adoptions require a positive amount",
"asset",
"assetAdoptionsPositiveAmount"));
}
@Test
public void shouldRejectIfPaybackWithPositiveAmount() {
new GivenAssetValidationTestCase()
.withAnyValidDateValues()
.withAction(AssetAction.PAYBACK)
.withAmount("64.00")
.when((AssetDTO assetDto) -> assetValidator.validate(assetDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Asset paybacks require a negative amount",
"asset",
"assetPaybacksNegativeAmount"));
}
@Test
public void shouldRejectIfPaybackWithZeroAmount() {
new GivenAssetValidationTestCase()
.withAnyValidDateValues()
.withAction(AssetAction.PAYBACK)
.withAmount("0.00")
.when((AssetDTO assetDto) -> assetValidator.validate(assetDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Asset paybacks require a negative amount",
"asset",
"assetPaybacksNegativeAmount"));
}
@Test
public void shouldRejectIfHandoverWithPositiveAmount() {
new GivenAssetValidationTestCase()
.withAnyValidDateValues()
.withAction(AssetAction.HANDOVER)
.withAmount("64.00")
.when((AssetDTO assetDto) -> assetValidator.validate(assetDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Asset handovers require a negative amount",
"asset",
"assetHandoversNegativeAmount"));
}
@Test
public void shouldRejectIfHandoverWithZeroAmount() {
new GivenAssetValidationTestCase()
.withAnyValidDateValues()
.withAction(AssetAction.HANDOVER)
.withAmount("0.00")
.when((AssetDTO assetDto) -> assetValidator.validate(assetDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Asset handovers require a negative amount",
"asset",
"assetHandoversNegativeAmount"));
}
@Test
public void shouldRejectIfLossWithPositiveAmount() {
new GivenAssetValidationTestCase()
.withAnyValidDateValues()
.withAction(AssetAction.LOSS)
.withAmount("64.00")
.when((AssetDTO assetDto) -> assetValidator.validate(assetDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Asset losses require a negative amount",
"asset",
"assetLossesNegativeAmount"));
}
@Test
public void shouldRejectIfLossWithZeroAmount() {
new GivenAssetValidationTestCase()
.withAnyValidDateValues()
.withAction(AssetAction.LOSS)
.withAmount("0.00")
.when((AssetDTO assetDto) -> assetValidator.validate(assetDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Asset losses require a negative amount",
"asset",
"assetLossesNegativeAmount"));
}
@Test
public void shouldRejectIfClearingWithPositiveAmount() {
new GivenAssetValidationTestCase()
.withAnyValidDateValues()
.withAction(AssetAction.CLEARING)
.withAmount("64.00")
.when((AssetDTO assetDto) -> assetValidator.validate(assetDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Asset clearings require a negative amount",
"asset",
"assetClearingsNegativeAmount"));
}
@Test
public void shouldRejectIfClearingWithZeroAmount() {
new GivenAssetValidationTestCase()
.withAnyValidDateValues()
.withAction(AssetAction.CLEARING)
.withAmount("0.00")
.when((AssetDTO assetDto) -> assetValidator.validate(assetDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Asset clearings require a negative amount",
"asset",
"assetClearingsNegativeAmount"));
}
// -- only test fixture below ---
private class GivenAssetValidationTestCase {
private final AssetDTO assetDto = new AssetDTO();
private BadRequestAlertException actualException;
public GivenAssetValidationTestCase withId(long id) {
assetDto.setId(id);
return this;
}
GivenAssetValidationTestCase withDocumentDate(String documentDate) {
assetDto.setDocumentDate(LocalDate.parse(documentDate));
return this;
}
GivenAssetValidationTestCase withValueDate(String valueDate) {
assetDto.setValueDate(LocalDate.parse(valueDate));
return this;
}
public GivenAssetValidationTestCase withAnyValidDateValues() {
return withDocumentDate("2019-04-11").withValueDate("2019-04-12");
}
GivenAssetValidationTestCase withAction(AssetAction assetAction) {
assetDto.setAction(assetAction);
return this;
}
GivenAssetValidationTestCase withAmount(String amount) {
assetDto.setAmount(new BigDecimal(amount));
return this;
}
GivenAssetValidationTestCase when(final Consumer<AssetDTO> statement) {
actualException = catchThrowableOfType(() -> assetValidator.validate(assetDto), BadRequestAlertException.class);
return this;
}
public AbstractThrowableAssert<?, ? extends Throwable> thenActualException() {
return assertThat(actualException);
}
}
}

View File

@@ -1,192 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import org.hostsharing.hsadminng.HsadminNgApp;
import org.hostsharing.hsadminng.config.Constants;
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 java.io.ByteArrayOutputStream;
import javax.mail.Multipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
@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

@@ -1,68 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import org.hostsharing.hsadminng.domain.Membership;
import org.hostsharing.hsadminng.repository.MembershipRepository;
import org.hostsharing.hsadminng.service.dto.MembershipDTO;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class MembershipServiceUnitTest {
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock
private MembershipRepository membershipRepository;
@Mock
private MembershipValidator membershipValidator;
@InjectMocks
private MembershipService membershipService;
@Test
public void deleteIsRejectedForMembership() {
// when
final Throwable throwException = catchThrowableOfType(
() -> membershipService.delete(RandomUtils.nextLong()),
BadRequestAlertException.class);
// then
assertThat(throwException).isEqualToComparingFieldByField(
new BadRequestAlertException("Membership cannot be deleted", "membership", "membershipNotDeletable"));
}
@Test
public void saveRejectsInvalidMembershipDTO() {
// given
final MembershipDTO givenMembershipDTO = new MembershipDTO();
final BadRequestAlertException givenBadRequestAlertException = new BadRequestAlertException(
"Invalid Membership",
Membership.ENTITY_NAME,
"invalidMembership");
doThrow(givenBadRequestAlertException).when(membershipValidator).validate(givenMembershipDTO);
// when
final Throwable throwException = catchThrowableOfType(
() -> membershipService.save(givenMembershipDTO),
BadRequestAlertException.class);
// then
assertThat(throwException).isSameAs(givenBadRequestAlertException);
verify(membershipRepository, never()).save(any(Membership.class));
}
}

View File

@@ -1,149 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.repository.MembershipRepository;
import org.hostsharing.hsadminng.service.dto.MembershipDTO;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import org.assertj.core.api.AbstractThrowableAssert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import java.time.LocalDate;
import java.util.function.Consumer;
public class MembershipValidatorUnitTest {
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock
private MembershipRepository membershipRepository;
@InjectMocks
private MembershipValidator membershipValidator;
@Before
public void initMocks() {
given(membershipRepository.hasUncancelledMembershipForCustomer(anyLong())).willReturn(false);
}
@Test
public void shouldAcceptNewMembershipIfUntilDateAfterSinceDate() {
new GivenMembershipValidationTestCase()
.withNewMembershipForCustomer(1L)
.since("2019-04-11")
.until("2019-04-12")
.when((MembershipDTO membershipDto) -> membershipValidator.validate(membershipDto))
.thenActualException()
.isNull();
}
@Test
public void shouldRejectNewMembershipIfUntilDateEqualToSinceDate() {
new GivenMembershipValidationTestCase()
.withNewMembershipForCustomer(1L)
.since("2019-04-11")
.until("2019-04-11")
.when((MembershipDTO membershipDto) -> membershipValidator.validate(membershipDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Invalid untilDate",
"membership",
"untilDateMustBeAfterSinceDate"));
}
@Test
public void shouldRejectNewMembershipIfUntilDateAfterSinceDate() {
new GivenMembershipValidationTestCase()
.withNewMembershipForCustomer(1L)
.since("2019-04-12")
.until("2019-04-11")
.when((MembershipDTO membershipDto) -> membershipValidator.validate(membershipDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Invalid untilDate",
"membership",
"untilDateMustBeAfterSinceDate"));
}
@Test
public void shouldAcceptNewUncancelledMembershipIfNoUncancelledMembershipExistsForSameCustomer() {
new GivenMembershipValidationTestCase()
.withUncancelledMembershipForCustomer(1L, false)
.withNewMembershipForCustomer(1L)
.since("2019-04-12")
.when((MembershipDTO membershipDto) -> membershipValidator.validate(membershipDto))
.thenActualException()
.isNull();
}
@Test
public void shouldRejectNewMembershipIfAnyUncancelledMembershipExistsForSameCustomer() {
new GivenMembershipValidationTestCase()
.withUncancelledMembershipForCustomer(1L, true)
.withNewMembershipForCustomer(1L)
.since("2019-04-12")
.when((MembershipDTO membershipDto) -> membershipValidator.validate(membershipDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Another uncancelled membership exists",
"membership",
"anotherUncancelledMembershipExists"));
}
// -- only test fixture below ---
private class GivenMembershipValidationTestCase {
private final MembershipDTO membershipDto = new MembershipDTO();
private BadRequestAlertException actualException;
GivenMembershipValidationTestCase withUncancelledMembershipForCustomer(
final long customerId,
final boolean hasUncancelledMembership) {
given(membershipRepository.hasUncancelledMembershipForCustomer(customerId)).willReturn(hasUncancelledMembership);
return this;
}
GivenMembershipValidationTestCase withNewMembershipForCustomer(long customerId) {
membershipDto.setCustomerId(1L);
return this;
}
GivenMembershipValidationTestCase since(final String sinceDate) {
membershipDto.setMemberFromDate(LocalDate.parse(sinceDate));
return this;
}
public GivenMembershipValidationTestCase until(final String untilDate) {
membershipDto.setMemberUntilDate(LocalDate.parse(untilDate));
return this;
}
GivenMembershipValidationTestCase when(final Consumer<MembershipDTO> statement) {
actualException = catchThrowableOfType(
() -> membershipValidator.validate(membershipDto),
BadRequestAlertException.class);
return this;
}
public AbstractThrowableAssert<?, ? extends Throwable> thenActualException() {
return assertThat(actualException);
}
}
}

View File

@@ -1,178 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.*;
import org.hostsharing.hsadminng.domain.Share;
import org.hostsharing.hsadminng.domain.enumeration.ShareAction;
import org.hostsharing.hsadminng.repository.ShareRepository;
import org.hostsharing.hsadminng.service.dto.ShareDTO;
import org.hostsharing.hsadminng.service.mapper.ShareMapper;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import javax.persistence.EntityManager;
// HINT: In IntelliJ IDEA such unit test classes can be created with Shift-Ctrl-T.
// Do not forget to amend the class name (.e.g. ...UnitTest / ...IntTest)!
public class ShareServiceUnitTest {
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock
private EntityManager em;
@Mock
private ShareRepository shareRepository;
@Mock
private ShareValidator shareValidator; // needed for @InjectMocks shareService
@Mock
private ShareMapper shareMapper;
@InjectMocks
private ShareService shareService;
// HINT: Click outside of any test method (e.g. here) and use Ctrl-Shift-F10
// to run all tests from this test class. Use Ctrl-F5 to run the last execution again;
// 'execution' here can also apply to running the application, whatever ran last.
// HINT: In IntelliJ IDEA such test methods can be created with Alt-Insert.
@Test
public void deleteIsRejectedForShareTransactions() {
// when
final Throwable throwException = catchThrowableOfType(
() -> shareService.delete(RandomUtils.nextLong()),
BadRequestAlertException.class);
// then
// HINT: When using auto-import for assertions (e.g. via Alt-Enter in IntelliJ IDEA),
// beware to use the correct candidate from org.assertj.core.api.Assertions.
assertThat(throwException).isEqualToComparingFieldByField(
new BadRequestAlertException("Share transactions are immutable", "share", "shareTransactionImmutable"));
}
@Test
public void saveShouldPersistValidTransactions() {
// given
final ShareDTO givenShareDTO = givenShareDTO(null, ShareAction.SUBSCRIPTION, anyPositiveNumber());
// HINT: given(...)...will...() can't be used for void methods, in that case use Mockito's do...() methods
doNothing().when(shareValidator).validate(givenShareDTO);
// when
final ShareDTO returnedShareDto = shareService.save(givenShareDTO);
// then
verify(em).flush();
verify(em).refresh(any(Share.class));
assertThat(returnedShareDto).isEqualToIgnoringGivenFields(givenShareDTO, "id");
}
@Test
public void saveShouldNotPersistInvalidTransactions() {
// given
final ShareDTO givenShareDTO = givenShareDTO(null, ShareAction.SUBSCRIPTION, anyNegativeNumber());
doThrow(new BadRequestAlertException("Some Dummy Test Violation", "share", "shareInvalidTestDummy"))
.when(shareValidator)
.validate(givenShareDTO);
// when
final Throwable throwException = catchThrowableOfType(
() -> shareService.save(givenShareDTO),
BadRequestAlertException.class);
// then
assertThat(throwException).isEqualToComparingFieldByField(
new BadRequestAlertException("Some Dummy Test Violation", "share", "shareInvalidTestDummy"));
}
@Test
public void saveShouldUpdateValidTransactions() {
// given
final ShareDTO givenShareDTO = givenShareDTO(anyNonNullId(), ShareAction.SUBSCRIPTION, anyPositiveNumber());
doNothing().when(shareValidator).validate(givenShareDTO);
// when
final ShareDTO returnedShareDto = shareService.save(givenShareDTO);
// then
verify(em).flush();
verify(em).refresh(any(Share.class));
assertThat(returnedShareDto).isEqualToIgnoringGivenFields(givenShareDTO, "id");
}
@Test
public void saveShouldNotUpdateInvalidTransactions() {
// given
final ShareDTO givenShareDTO = givenShareDTO(anyNonNullId(), ShareAction.SUBSCRIPTION, anyNegativeNumber());
// HINT: given(...) can't be used for void methods, in that case use Mockito's do...() methods
doThrow(new BadRequestAlertException("Some Dummy Test Violation", "share", "shareInvalidTestDummy"))
.when(shareValidator)
.validate(givenShareDTO);
// when
final Throwable throwException = catchThrowableOfType(
() -> shareService.save(givenShareDTO),
BadRequestAlertException.class);
// then
assertThat(throwException).isEqualToComparingFieldByField(
new BadRequestAlertException("Some Dummy Test Violation", "share", "shareInvalidTestDummy"));
}
// --- only test fixture code below ---
private long anyNonNullId() {
return RandomUtils.nextInt();
}
// HINT: This rather complicated setup indicates that the method ShareService::save breaks the single responsibility
// principle.
private ShareDTO givenShareDTO(final Long id, final ShareAction givenAction, final int givenQuantity) {
final ShareDTO givenShareDTO = createShareDTO(id, givenAction, givenQuantity);
// dto -> entity
final Share givenShareEntity = Mockito.mock(Share.class);
given(shareMapper.toEntity(same(givenShareDTO))).willReturn(givenShareEntity);
// shareRepository.save(entity);
final Share persistedShareEntity = Mockito.mock(Share.class);
given(shareRepository.save(same(givenShareEntity))).willReturn(persistedShareEntity);
// entity -> dto
ShareDTO persistedShareDTO = createShareDTO(id == null ? RandomUtils.nextLong() : id, givenAction, givenQuantity);
given(shareMapper.toDto(same(persistedShareEntity))).willReturn(persistedShareDTO);
return givenShareDTO;
}
private ShareDTO createShareDTO(Long id, ShareAction givenAction, int givenQuantity) {
final ShareDTO givenShareDTO = new ShareDTO();
givenShareDTO.setId(id);
givenShareDTO.setAction(givenAction);
givenShareDTO.setQuantity(givenQuantity);
return givenShareDTO;
}
private int anyPositiveNumber() {
return RandomUtils.nextInt(1, 1000);
}
private int anyNegativeNumber() {
return -anyPositiveNumber();
}
}

View File

@@ -1,190 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
import org.hostsharing.hsadminng.domain.enumeration.ShareAction;
import org.hostsharing.hsadminng.service.dto.ShareDTO;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import org.apache.commons.lang3.RandomUtils;
import org.assertj.core.api.AbstractThrowableAssert;
import org.junit.Test;
import java.time.LocalDate;
import java.util.function.Consumer;
public class ShareValidatorUnitTest {
private ShareValidator shareValidator = new ShareValidator();
@Test
public void shouldAcceptValidSubscription() {
new GivenShareValidationTestCase()
.withAnyValidDateValues()
.withAction(ShareAction.SUBSCRIPTION)
.withQuantity(1)
.when((ShareDTO shareDto) -> shareValidator.validate(shareDto))
.thenActualException()
.isNull();
}
@Test
public void shouldAcceptValidCancellation() {
new GivenShareValidationTestCase()
.withAnyValidDateValues()
.withAction(ShareAction.CANCELLATION)
.withQuantity(-1)
.when((ShareDTO shareDto) -> shareValidator.validate(shareDto))
.thenActualException()
.isNull();
}
@Test
public void shouldAcceptIfDocumentDateEqualsValueDate() {
new GivenShareValidationTestCase()
.withDocumentDate("2019-04-11")
.withValueDate("2019-04-11")
.withAction(ShareAction.SUBSCRIPTION)
.withQuantity(1)
.when((ShareDTO shareDto) -> shareValidator.validate(shareDto))
.thenActualException()
.isNull();
}
@Test
public void shouldRejectUpdates() {
new GivenShareValidationTestCase()
.withId(RandomUtils.nextLong())
.when((ShareDTO shareDto) -> shareValidator.validate(shareDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Share transactions are immutable",
"share",
"shareTransactionImmutable"));
}
@Test
public void shouldRejectIfDocumentDateAfterValueDate() {
new GivenShareValidationTestCase()
.withDocumentDate("2019-04-13")
.withValueDate("2019-04-12")
.withAction(ShareAction.SUBSCRIPTION)
.withQuantity(1)
.when((ShareDTO shareDto) -> shareValidator.validate(shareDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Document date may not be after value date",
"share",
"documentDateMayNotBeAfterValueDate"));
}
@Test
public void shouldRejectIfSubscriptionWithNegativeQuantity() {
new GivenShareValidationTestCase()
.withAnyValidDateValues()
.withAction(ShareAction.SUBSCRIPTION)
.withQuantity(-1)
.when((ShareDTO shareDto) -> shareValidator.validate(shareDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Share subscriptions require a positive quantity",
"share",
"shareSubscriptionPositiveQuantity"));
}
@Test
public void shouldRejectIfSubscriptionWithZeroQuantity() {
new GivenShareValidationTestCase()
.withAnyValidDateValues()
.withAction(ShareAction.SUBSCRIPTION)
.withQuantity(0)
.when((ShareDTO shareDto) -> shareValidator.validate(shareDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Share subscriptions require a positive quantity",
"share",
"shareSubscriptionPositiveQuantity"));
}
@Test
public void shouldRejectIfCancellationWithPositiveQuantity() {
new GivenShareValidationTestCase()
.withAnyValidDateValues()
.withAction(ShareAction.CANCELLATION)
.withQuantity(1)
.when((ShareDTO shareDto) -> shareValidator.validate(shareDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Share cancellations require a negative quantity",
"share",
"shareCancellationNegativeQuantity"));
}
@Test
public void shouldRejectIfCancellationWithZeroQuantity() {
new GivenShareValidationTestCase()
.withAnyValidDateValues()
.withAction(ShareAction.CANCELLATION)
.withQuantity(0)
.when((ShareDTO shareDto) -> shareValidator.validate(shareDto))
.thenActualException()
.isEqualToComparingFieldByField(
new BadRequestAlertException(
"Share cancellations require a negative quantity",
"share",
"shareCancellationNegativeQuantity"));
}
// -- only test fixture below ---
private class GivenShareValidationTestCase {
private final ShareDTO shareDto = new ShareDTO();
private BadRequestAlertException actualException;
public GivenShareValidationTestCase withId(long id) {
shareDto.setId(id);
return this;
}
GivenShareValidationTestCase withDocumentDate(String documentDate) {
shareDto.setDocumentDate(LocalDate.parse(documentDate));
return this;
}
GivenShareValidationTestCase withValueDate(String valueDate) {
shareDto.setValueDate(LocalDate.parse(valueDate));
return this;
}
public GivenShareValidationTestCase withAnyValidDateValues() {
return withDocumentDate("2019-04-11").withValueDate("2019-04-12");
}
GivenShareValidationTestCase withAction(ShareAction shareAction) {
shareDto.setAction(shareAction);
return this;
}
GivenShareValidationTestCase withQuantity(Integer quantity) {
shareDto.setQuantity(quantity);
return this;
}
GivenShareValidationTestCase when(final Consumer<ShareDTO> statement) {
actualException = catchThrowableOfType(() -> shareValidator.validate(shareDto), BadRequestAlertException.class);
return this;
}
public AbstractThrowableAssert<?, ? extends Throwable> thenActualException() {
return assertThat(actualException);
}
}
}

View File

@@ -1,99 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.domain.UserRoleAssignment;
import org.hostsharing.hsadminng.repository.UserRoleAssignmentRepository;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerFinancialContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerTechnicalContact;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextFake;
import com.google.common.base.VerifyException;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import java.util.Arrays;
import java.util.Set;
public class UserRoleAssignmentServiceUnitTest {
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock
private UserRoleAssignmentRepository userRoleAssignmentRepository;
@InjectMocks
private UserRoleAssignmentService userRoleAssignmentService;
@Test
public void getEffectiveRoleOfCurrentUserReturnsEmptySetIfUserNotAuthenticated() {
// when
final Set<Role> actual = userRoleAssignmentService.getEffectiveRoleOfCurrentUser("test.Something", 1L);
// then
assertThat(actual).isEmpty();
}
@Test
public void getEffectiveRoleOfCurrentUserReturnsEmptySetIfUserAuthenticatedButNoRolesAssigned() {
// given
SecurityContextFake.havingAuthenticatedUser();
// when
final Set<Role> actual = userRoleAssignmentService.getEffectiveRoleOfCurrentUser("test.Something", 1L);
// then
assertThat(actual).isEmpty();
}
@Test
public void getEffectiveRoleOfCurrentUserReturnsExactlyAssignedRoles() {
// given
final String givenUserLogin = "someUser";
SecurityContextFake.havingAuthenticatedUser(givenUserLogin);
final long givenEntityObjectId = 2L;
final String givenEntityTypeId = "test.Something";
given(userRoleAssignmentRepository.findByLogin(givenUserLogin)).willReturn(
Arrays.asList(
new UserRoleAssignment().entityTypeId("test.SomethingElse")
.entityObjectId(givenEntityObjectId)
.assignedRole(CustomerContractualContact.ROLE),
new UserRoleAssignment().entityTypeId(givenEntityTypeId)
.entityObjectId(givenEntityObjectId)
.assignedRole(CustomerFinancialContact.ROLE),
new UserRoleAssignment().entityTypeId(givenEntityTypeId)
.entityObjectId(givenEntityObjectId)
.assignedRole(CustomerTechnicalContact.ROLE),
new UserRoleAssignment().entityTypeId(givenEntityTypeId)
.entityObjectId(3L)
.assignedRole(CustomerContractualContact.ROLE)));
// when
final Set<Role> actual = userRoleAssignmentService
.getEffectiveRoleOfCurrentUser(givenEntityTypeId, givenEntityObjectId);
// then
assertThat(actual)
.containsExactlyInAnyOrder(Role.of(CustomerFinancialContact.class), Role.of(CustomerTechnicalContact.class));
}
@Test
public void getEffectiveRoleOfCurrentUserThrowsExceptionIfEntityTypeIdIsMissing() {
// when
final Throwable actual = catchThrowable(() -> userRoleAssignmentService.getEffectiveRoleOfCurrentUser(null, 1L));
// then
assertThat(actual).isInstanceOf(VerifyException.class);
}
}

View File

@@ -1,194 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
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.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;
/**
* 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

@@ -1,34 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter;
import static org.assertj.core.api.Assertions.assertThat;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.junit.Test;
import org.mockito.Mock;
public class JSonAccessFilterTest {
@Mock
private UserRoleAssignmentService userRoleAssignmentService;
@Test
public void getLoginUserRoles() {
SecurityContextFake.havingUnauthenticatedUser();
new JSonAccessFilter<TestEntity>(null, userRoleAssignmentService, new TestEntity()) {
{
assertThat(this.getLoginUserRoles()).hasSize(0);
}
};
}
private static class TestEntity implements AccessMappings {
@Override
public Long getId() {
return null;
}
}
}

View File

@@ -1,237 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter;
import static org.hostsharing.hsadminng.service.accessfilter.Role.*;
import org.hostsharing.hsadminng.service.IdToDtoResolver;
import org.hostsharing.hsadminng.service.dto.FluentBuilder;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import java.math.BigDecimal;
import java.time.LocalDate;
public class JSonAccessFilterTestFixture {
static GivenDto createSampleDto() {
final GivenDto dto = new GivenDto();
dto.customerId = 888L;
dto.restrictedField = RandomStringUtils.randomAlphabetic(10);
dto.openStringField = RandomStringUtils.randomAlphabetic(10);
dto.openIntegerField = RandomUtils.nextInt();
dto.openPrimitiveIntField = RandomUtils.nextInt();
dto.openLongField = RandomUtils.nextLong();
dto.openPrimitiveLongField = RandomUtils.nextLong();
dto.openBooleanField = true;
dto.openPrimitiveBooleanField = false;
dto.openBigDecimalField = new BigDecimal("987654321234567890987654321234567890.09");
dto.openLocalDateField = LocalDate.parse("2019-04-25");
dto.openLocalDateFieldAsString = "2019-04-25";
dto.openEnumField = TestEnum.GREEN;
dto.openEnumFieldAsString = "GREEN";
return dto;
}
@EntityTypeId("test.GivenCustomer")
static class GivenCustomerDto implements FluentBuilder<GivenCustomerDto> {
@SelfId(resolver = GivenService.class)
@AccessFor(read = Anybody.class)
Long id;
@AccessFor(update = Ignored.class, read = Anybody.class)
String displayLabel;
}
static abstract class GivenCustomerService implements IdToDtoResolver<GivenCustomerDto> {
}
@EntityTypeId("test.Given")
static class GivenDto implements AccessMappings, FluentBuilder<GivenDto> {
@SelfId(resolver = GivenService.class)
@AccessFor(read = Anybody.class)
Long id;
@ParentId(resolver = GivenCustomerService.class)
@AccessFor(init = AnyCustomerUser.class, update = AnyCustomerUser.class, read = AnyCustomerUser.class)
Long customerId;
@AccessFor(
init = { CustomerTechnicalContact.class, CustomerFinancialContact.class },
update = { CustomerTechnicalContact.class, CustomerFinancialContact.class },
read = { CustomerTechnicalContact.class, CustomerFinancialContact.class })
String restrictedField;
@AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
String openStringField;
@AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
Integer openIntegerField;
@AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
int openPrimitiveIntField;
@AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
Long openLongField;
@AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
long openPrimitiveLongField;
@AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
Boolean openBooleanField;
@AccessFor(read = Anybody.class)
boolean openPrimitiveBooleanField;
@AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
LocalDate openLocalDateField;
transient String openLocalDateFieldAsString;
@AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
LocalDate openLocalDateField2;
transient String openLocalDateField2AsString;
@AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
TestEnum openEnumField;
transient String openEnumFieldAsString;
@AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
BigDecimal openBigDecimalField;
@AccessFor(init = Supporter.class, update = Supporter.class, read = Supporter.class)
BigDecimal restrictedBigDecimalField;
@AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
int[] openArrayField;
@AccessFor(init = Ignored.class, update = Ignored.class, read = Anybody.class)
String displayLabel;
@Override
public Long getId() {
return id;
}
}
static abstract class GivenService implements IdToDtoResolver<GivenDto> {
}
enum TestEnum {
BLUE,
GREEN
}
static abstract class GivenChildService implements IdToDtoResolver<GivenChildDto> {
}
public static class GivenChildDto implements AccessMappings, FluentBuilder<GivenChildDto> {
@SelfId(resolver = GivenChildService.class)
@AccessFor(read = AnyCustomerUser.class)
Long id;
@AccessFor(
init = CustomerContractualContact.class,
update = CustomerContractualContact.class,
read = AnyCustomerUser.class)
@ParentId(resolver = GivenService.class)
Long parentId;
@AccessFor(
init = { CustomerTechnicalContact.class, CustomerFinancialContact.class },
update = {
CustomerTechnicalContact.class,
CustomerFinancialContact.class })
String restrictedField;
@Override
public Long getId() {
return id;
}
}
public static class GivenDtoWithMultipleSelfId implements AccessMappings {
@SelfId(resolver = GivenChildService.class)
@AccessFor(read = AnyCustomerUser.class)
Long id;
@SelfId(resolver = GivenChildService.class)
@AccessFor(read = AnyCustomerUser.class)
Long id2;
@Override
public Long getId() {
return id;
}
}
public static class GivenDtoWithUnknownFieldType implements AccessMappings {
@SelfId(resolver = GivenChildService.class)
@AccessFor(read = Anybody.class)
Long id;
@AccessFor(init = Anybody.class, read = Anybody.class)
Arbitrary unknown;
@Override
public Long getId() {
return id;
}
}
static class Arbitrary {
}
@EntityTypeId("givenParent")
public static class GivenParent implements AccessMappings, FluentBuilder<GivenParent> {
@SelfId(resolver = GivenParentService.class)
@AccessFor(read = AnyCustomerUser.class)
Long id;
@Override
public Long getId() {
return id;
}
public GivenParent id(final long id) {
this.id = id;
return this;
}
}
public static class GivenChild implements AccessMappings, FluentBuilder<GivenChild> {
@SelfId(resolver = GivenChildService.class)
@AccessFor(read = AnyCustomerUser.class)
Long id;
@AccessFor(
init = CustomerContractualContact.class,
update = CustomerContractualContact.class,
read = AnyCustomerUser.class)
@ParentId(resolver = GivenParentService.class)
GivenParent parent;
@AccessFor(
init = { CustomerTechnicalContact.class, CustomerFinancialContact.class },
update = {
CustomerTechnicalContact.class,
CustomerFinancialContact.class })
String restrictedField;
@Override
public Long getId() {
return id;
}
}
static abstract class GivenParentService implements IdToDtoResolver<GivenParent> {
}
}

View File

@@ -1,91 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import java.util.List;
public class JSonBuilder {
private StringBuilder json = new StringBuilder();
@SafeVarargs
public static String asJSon(final ImmutablePair<String, Object>... properties) {
final StringBuilder json = new StringBuilder();
for (ImmutablePair<String, Object> prop : properties) {
json.append(inQuotes(prop.left));
json.append(": ");
if (prop.right instanceof Number) {
json.append(prop.right);
} else if (prop.right instanceof List) {
json.append(toJSonArray(prop.right));
} else if (prop.right instanceof String && ((String) prop.right).startsWith("{\n")) {
// TODO mhoennig: find better solution for adding object nodes
json.append(prop.right);
} else {
json.append(inQuotes(prop.right));
}
json.append(",\n");
}
return "{\n" + json.substring(0, json.length() - 2) + "\n}";
}
public JSonBuilder withFieldValue(String name, String value) {
json.append(inQuotes(name)).append(":").append(value != null ? inQuotes(value) : "null").append(",");
return this;
}
public JSonBuilder withFieldValue(String name, Number value) {
json.append(inQuotes(name)).append(":").append(value != null ? value : "null").append(",");
return this;
}
public JSonBuilder toJSonNullFieldDefinition(String name) {
json.append(inQuotes(name)).append(":null,");
return this;
}
public JSonBuilder withFieldValueIfPresent(String name, String value) {
if (value != null) {
json.append(inQuotes(name)).append(":").append(inQuotes(value)).append(",");
}
return this;
}
public JSonBuilder withFieldValueIfPresent(String name, Number value) {
if (value != null) {
json.append(inQuotes(name)).append(":").append(value).append(",");
}
return this;
}
public <E extends Enum<E>> JSonBuilder withFieldValueIfPresent(final String name, final Role value) {
if (value != null) {
json.append(inQuotes(name)).append(":").append(inQuotes(value.name())).append(",");
}
return this;
}
@Override
public String toString() {
return "{" + StringUtils.removeEnd(json.toString(), ",") + "}";
}
@SuppressWarnings("unchecked")
// currently just for the case of date values represented as arrays of integer
private static String toJSonArray(final Object value) {
final StringBuilder jsonArray = new StringBuilder("[");
for (int n = 0; n < ((List<Integer>) value).size(); ++n) {
if (n > 0) {
jsonArray.append(",");
}
jsonArray.append(((List<Integer>) value).get(n));
}
return jsonArray.toString() + "]";
}
private static String inQuotes(Object value) {
return value != null ? "\"" + value.toString() + "\"" : "null";
}
}

View File

@@ -1,579 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.assertj.core.api.Assumptions.assumeThat;
import static org.hostsharing.hsadminng.service.accessfilter.JSonAccessFilterTestFixture.*;
import static org.hostsharing.hsadminng.service.accessfilter.JSonBuilder.asJSon;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.Role.Admin;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Optional;
@SuppressWarnings("ALL")
public class JSonDeserializationWithAccessFilterUnitTest {
public static final String SOME_BIG_DECIMAL_AS_STRING = "5432191234888.1";
public static final BigDecimal SOME_BIG_DECIMAL = new BigDecimal(SOME_BIG_DECIMAL_AS_STRING)
.setScale(2, BigDecimal.ROUND_HALF_UP);
public static final BigDecimal SOME_BIG_DECIMAL_WITH_ANOTHER_SCALE = new BigDecimal(SOME_BIG_DECIMAL_AS_STRING)
.setScale(5, BigDecimal.ROUND_HALF_UP);
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock
private ApplicationContext ctx;
@Mock
private AutowireCapableBeanFactory autowireCapableBeanFactory;
@Mock
private JsonParser jsonParser;
@Mock
private ObjectCodec codec;
@Mock
private TreeNode treeNode;
@Mock
private UserRoleAssignmentService userRoleAssignmentService;
@Mock
private GivenService givenService;
@Mock
private GivenChildService givenChildService;
@Mock
private GivenParentService givenParentService;
@Mock
private GivenCustomerService givenCustomerService;
private SecurityContextMock securityContext;
@Before
public void init() {
securityContext = SecurityContextMock.usingMock(userRoleAssignmentService)
.havingAuthenticatedUser()
.withRole(GivenDto.class, 1234L, Role.AnyCustomerUser.ROLE);
given(ctx.getAutowireCapableBeanFactory()).willReturn(autowireCapableBeanFactory);
given(autowireCapableBeanFactory.createBean(GivenService.class)).willReturn(givenService);
given(givenService.findOne(1234L)).willReturn(
Optional.of(
new GivenDto()
.with(dto -> {
dto.id = 1234L;
dto.customerId = 888L;
dto.openIntegerField = 11111;
dto.openPrimitiveIntField = 2222;
dto.openLongField = 33333333333333L;
dto.openPrimitiveLongField = 44444444L;
dto.openBooleanField = true;
dto.openPrimitiveBooleanField = false;
dto.openBigDecimalField = SOME_BIG_DECIMAL;
dto.openStringField = "3333";
dto.restrictedField = "initial value of restricted field";
dto.restrictedBigDecimalField = SOME_BIG_DECIMAL;
})));
given(autowireCapableBeanFactory.createBean(GivenCustomerService.class)).willReturn(givenCustomerService);
given(givenCustomerService.findOne(888L)).willReturn(
Optional.of(
new GivenCustomerDto()
.with(dto -> dto.id = 888L)));
given(autowireCapableBeanFactory.createBean(GivenChildService.class)).willReturn(givenChildService);
given(autowireCapableBeanFactory.createBean(GivenParentService.class)).willReturn(givenParentService);
given(jsonParser.getCodec()).willReturn(codec);
}
@Test
public void shouldDeserializeNullField() throws IOException {
// given
givenJSonTree(
asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("openStringField", null)));
// when
final GivenDto actualDto = deserializerFor(GivenDto.class).deserialize(jsonParser, null);
// then
assertThat(actualDto.openStringField).isNull();
}
@Test
public void shouldDeserializeStringField() throws IOException {
// given
givenJSonTree(
asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("openStringField", "String Value")));
// when
final GivenDto actualDto = deserializerFor(GivenDto.class).deserialize(jsonParser, null);
// then
assertThat(actualDto.openStringField).isEqualTo("String Value");
}
@Test
public void shouldDeserializeIntegerField() throws IOException {
// given
givenJSonTree(
asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("openIntegerField", 1234)));
// when
// @formatter:off
final GivenDto actualDto = deserializerFor(GivenDto.class).deserialize(jsonParser, null);;
// @formatter:on
// then
assertThat(actualDto.openIntegerField).isEqualTo(1234);
}
@Test
public void shouldDeserializeRestrictedBigDecimalFieldIfUnchangedByCompareTo() throws IOException {
// given
assumeThat(SOME_BIG_DECIMAL_WITH_ANOTHER_SCALE).isNotEqualTo(SOME_BIG_DECIMAL);
givenJSonTree(
asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("restrictedBigDecimalField", SOME_BIG_DECIMAL_WITH_ANOTHER_SCALE)));
// when
final GivenDto actualDto = deserializerFor(GivenDto.class).deserialize(jsonParser, null);
;
// then
assertThat(actualDto.restrictedBigDecimalField).isEqualByComparingTo(SOME_BIG_DECIMAL);
assertThat(actualDto.restrictedBigDecimalField).isEqualByComparingTo(SOME_BIG_DECIMAL_WITH_ANOTHER_SCALE);
}
@Test
// TODO: split in separate tests for each type, you see all errors at once (if any) and it's easier to debug when there are
// problems
public void shouldDeserializeAcessibleFieldOfAnyType() throws IOException {
// given
givenJSonTree(
asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("openIntegerField", 11),
ImmutablePair.of("openPrimitiveIntField", 22),
ImmutablePair.of("openLongField", 333333333333333333L),
ImmutablePair.of("openPrimitiveLongField", 44444L),
ImmutablePair.of("openBooleanField", true),
ImmutablePair.of("openPrimitiveBooleanField", false),
// TODO: ImmutablePair.of("openBigDecimalField", new BigDecimal("99999999999999999999.1")),
// check why DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS is not working!
ImmutablePair.of("openBigDecimalField", new BigDecimal("99999999999999.1")),
ImmutablePair.of("openLocalDateField", LocalDate.parse("2019-04-25")),
ImmutablePair.of("openLocalDateField2", Arrays.asList(2019, 4, 24)),
ImmutablePair.of("openEnumField", TestEnum.GREEN)));
// when
final GivenDto actualDto = deserializerFor(GivenDto.class).deserialize(jsonParser, null);
;
// then
assertThat(actualDto.openIntegerField).isEqualTo(11);
assertThat(actualDto.openPrimitiveIntField).isEqualTo(22);
assertThat(actualDto.openLongField).isEqualTo(333333333333333333L);
assertThat(actualDto.openPrimitiveLongField).isEqualTo(44444L);
assertThat(actualDto.openBooleanField).isEqualTo(true);
assertThat(actualDto.openPrimitiveBooleanField).isEqualTo(false);
assertThat(actualDto.openBigDecimalField).isEqualTo(new BigDecimal("99999999999999.1"));
assertThat(actualDto.openLocalDateField).isEqualTo(LocalDate.parse("2019-04-25"));
assertThat(actualDto.openLocalDateField2).isEqualTo(LocalDate.parse("2019-04-24"));
assertThat(actualDto.openEnumField).isEqualTo(TestEnum.GREEN);
}
@Test
public void shouldNotDeserializeFieldWithUnknownJSonNodeType() throws IOException {
// given
givenJSonTree(
asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("openArrayField", Arrays.asList(11, 22, 33))));
// when
Throwable exception = catchThrowable(() -> deserializerFor(GivenDto.class).deserialize(jsonParser, null));
// then
assertThat(exception).isInstanceOf(NotImplementedException.class);
}
@Test
public void shouldDeserializeStringFieldIfRequiredRoleIsCoveredByUser() throws IOException {
// given
securityContext.havingAuthenticatedUser()
.withRole(GivenCustomerDto.class, 888L, Role.CustomerFinancialContact.ROLE);
givenJSonTree(
asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("restrictedField", "update value of restricted field")));
// when
final GivenDto actualDto = deserializerFor(GivenDto.class).deserialize(jsonParser, null);
// then
assertThat(actualDto.restrictedField).isEqualTo("update value of restricted field");
}
@Test
public void shouldDeserializeUnchangedStringFieldIfRequiredRoleIsNotCoveredByUser() throws IOException {
// given
securityContext.havingAuthenticatedUser()
.withRole(GivenCustomerDto.class, 888L, Role.CustomerFinancialContact.ROLE);
givenJSonTree(
asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("restrictedField", "initial value of restricted field")));
// when
final GivenDto actualDto = deserializerFor(GivenDto.class).deserialize(jsonParser, null);
// then
assertThat(actualDto.restrictedField).isEqualTo("initial value of restricted field");
}
@Test
public void shouldNotDeserializeUpatedStringFieldIfRequiredRoleIsNotCoveredByUser() throws IOException {
// given
securityContext.havingAuthenticatedUser()
.withRole(GivenCustomerDto.class, 888L, Role.ActualCustomerUser.ROLE);
givenJSonTree(
asJSon(
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("restrictedField", "updated value of restricted field")));
// when
final Throwable exception = catchThrowable(() -> deserializerFor(GivenDto.class).deserialize(jsonParser, null));
// then
assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> {
assertThat(badRequestAlertException.getParam()).isEqualTo("GivenDto.restrictedField");
assertThat(badRequestAlertException.getErrorKey()).isEqualTo("initializationProhibited");
});
}
@Test
public void shouldNotInitializeFieldIfRequiredRoleIsNotCoveredByUser() throws IOException {
// given
securityContext.havingAuthenticatedUser()
.withRole(GivenCustomerDto.class, 888L, Role.ActualCustomerUser.ROLE);
givenJSonTree(
asJSon(
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("restrictedField", "another value of restricted field")));
// when
final Throwable exception = catchThrowable(() -> deserializerFor(GivenDto.class).deserialize(jsonParser, null));
// then
assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> {
assertThat(badRequestAlertException.getParam()).isEqualTo("GivenDto.restrictedField");
assertThat(badRequestAlertException.getErrorKey()).isEqualTo("initializationProhibited");
});
}
@Test
public void shouldNotCreateIfRoleRequiredByParentEntityIsNotCoveredByUser() throws IOException {
// given
securityContext.havingAuthenticatedUser()
.withRole(GivenCustomerDto.class, 9999L, Role.CustomerContractualContact.ROLE);
givenJSonTree(
asJSon(
ImmutablePair.of("parentId", 1234L)));
// when
Throwable exception = catchThrowable(
() -> deserializerFor(GivenChildDto.class).deserialize(jsonParser, null));
// then
assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> {
assertThat(badRequestAlertException.getParam()).isEqualTo("GivenChildDto.parentId");
assertThat(badRequestAlertException.getErrorKey()).isEqualTo("referencingProhibited");
});
}
@Test
public void shouldCreateIfRoleRequiredByReferencedEntityIsCoveredByUser() throws IOException {
// given
securityContext.havingAuthenticatedUser()
.withRole(GivenCustomerDto.class, 888L, Role.CustomerContractualContact.ROLE);
givenJSonTree(
asJSon(
ImmutablePair.of("parentId", 1234L)));
// when
final GivenChildDto actualDto = deserializerFor(GivenChildDto.class).deserialize(jsonParser, null);
;
// then
assertThat(actualDto.parentId).isEqualTo(1234L);
}
@Test
public void shouldResolveParentIdFromIdOfSerializedSubEntity() throws IOException {
// given
securityContext.havingAuthenticatedUser()
.withRole(GivenParent.class, 1234L, Role.CustomerContractualContact.ROLE);
givenJSonTree(
asJSon(
ImmutablePair.of(
"parent",
asJSon(
ImmutablePair.of("id", 1234L)))));
given(givenParentService.findOne(1234L)).willReturn(Optional.of(new GivenParent().id(1234)));
// when
final GivenChild actualDto = deserializerFor(GivenChild.class).deserialize(jsonParser, null);
// then
assertThat(actualDto.parent.id).isEqualTo(1234L);
}
@Test
public void shouldNotUpdateFieldIfRequiredRoleIsNotCoveredByUser() throws IOException {
// given
securityContext.havingAuthenticatedUser()
.withRole(GivenCustomerDto.class, 888L, Role.ActualCustomerUser.ROLE);
givenJSonTree(
asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("restrictedField", "Restricted String Value")));
// when
final Throwable exception = catchThrowable(
() -> deserializerFor(GivenDto.class).deserialize(jsonParser, null));
// then
assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> {
assertThat(badRequestAlertException.getParam()).isEqualTo("GivenDto.restrictedField");
assertThat(badRequestAlertException.getErrorKey()).isEqualTo("updateProhibited");
});
}
@Test
public void shouldDetectMultipleSelfIdFields() throws IOException {
// given
givenJSonTree(asJSon(ImmutablePair.of("id", 1111L)));
// when
final Throwable exception = catchThrowable(
() -> deserializerFor(GivenDtoWithMultipleSelfId.class).deserialize(jsonParser, null));
// then
assertThat(exception).isInstanceOf(AssertionError.class)
.hasMessage("multiple @SelfId detected in GivenDtoWithMultipleSelfId");
}
@Test
public void shouldDetectUnknownFieldType() throws IOException {
// given
securityContext.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.ADMIN);
givenJSonTree(asJSon(ImmutablePair.of("unknown", new Arbitrary())));
// when
final Throwable exception = catchThrowable(
() -> deserializerFor(GivenDtoWithUnknownFieldType.class).deserialize(jsonParser, null));
// then
assertThat(exception).isInstanceOf(NotImplementedException.class)
.hasMessageStartingWith("property type not yet implemented: ")
.hasMessageContaining("Arbitrary")
.hasMessageContaining("GivenDtoWithUnknownFieldType.unknown");
}
@Test
public void shouldDetectUnknownPropertyName() throws IOException {
// given
securityContext.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.ADMIN);
givenJSonTree(asJSon(ImmutablePair.of("somePropWhichDoesNotExist", "Some Value")));
// when
final Throwable exception = catchThrowable(
() -> deserializerFor(GivenDto.class).deserialize(jsonParser, null));
// then
assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, (exc) -> {
assertThat(exc).hasMessageStartingWith("Unknown property");
assertThat(exc.getParam()).isEqualTo("somePropWhichDoesNotExist");
assumeThat(exc.getErrorKey()).isEqualTo("unknownProperty");
});
}
@Test
public void shouldNotDeserializeArrayValue() throws IOException {
// given
securityContext.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.ADMIN);
givenJSonTree(asJSon(ImmutablePair.of("openStringField", Arrays.asList(1, 2))));
// when
final Throwable exception = catchThrowable(
() -> deserializerFor(GivenDto.class).deserialize(jsonParser, null));
// then
assertThat(exception).isInstanceOf(NotImplementedException.class);
}
@Test
public void shouldNotDeserializeObjectValue() throws IOException {
// given
securityContext.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.ADMIN);
givenJSonTree("{ \"openStringField\": {\"a\": 1, \"b\": 2 } }");
// when
final Throwable exception = catchThrowable(
() -> deserializerFor(GivenDto.class).deserialize(jsonParser, null));
// then
assertThat(exception).isInstanceOf(NotImplementedException.class);
}
@Test
public void shouldIgnorePropertyToIgnoreForInit() throws IOException {
// given
securityContext.havingAuthenticatedUser().withAuthority(Admin.ROLE.authority());
givenJSonTree(
asJSon(
ImmutablePair.of("displayLabel", "Some Value")));
// when
deserializerFor(GivenDto.class).deserialize(jsonParser, null);
final Throwable exception = catchThrowable(() -> deserializerFor(GivenDto.class).deserialize(jsonParser, null));
// then
assertThat(exception).isNull();
}
@Test
public void shouldIgnorePropertyToIgnoreForUpdate() throws IOException {
// given
securityContext.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.ADMIN);
givenJSonTree(
asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("displayLabel", "Some Value")));
// when
final Throwable exception = catchThrowable(() -> deserializerFor(GivenDto.class).deserialize(jsonParser, null));
// then
assertThat(exception).isNull();
}
// --- only fixture code below ---
private void givenJSonTree(String givenJSon) throws IOException {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
given(codec.readTree(jsonParser)).willReturn(new ObjectMapper().readTree(givenJSon));
}
// We need specialied factories for the deserializer subclasses
// so that the generic type can be accessed via reflection.
// And it's down here to keep the ugly formatting out of the test cases.
// The trick with the unused ...-parameterr might look strange but the reason is
// that I wanted the concrete class to be navigable in the tests and
// multiple deserializer(Class<...Dto>) methods would have the same erasure
// and adding the type the method name, is redundant for the reader.
public JsonDeserializerWithAccessFilter<GivenDto> deserializerFor(
final Class<GivenDto> clazz,
final GivenDto... qualifier) {
return new JsonDeserializerWithAccessFilter<GivenDto>(ctx, userRoleAssignmentService) {
// no need to overload any method here
};
}
public JsonDeserializerWithAccessFilter<GivenChildDto> deserializerFor(
final Class<GivenChildDto> clazz,
final GivenChildDto... qualifier) {
return new JsonDeserializerWithAccessFilter<GivenChildDto>(ctx, userRoleAssignmentService) {
// no need to overload any method here
};
}
private JsonDeserializer<GivenDtoWithMultipleSelfId> deserializerFor(
final Class<GivenDtoWithMultipleSelfId> clazz,
final GivenDtoWithMultipleSelfId... qualifier) {
return new JsonDeserializerWithAccessFilter<GivenDtoWithMultipleSelfId>(ctx, userRoleAssignmentService) {
// no need to overload any method here
};
}
private JsonDeserializer<GivenDtoWithUnknownFieldType> deserializerFor(
final Class<GivenDtoWithUnknownFieldType> clazz,
final GivenDtoWithUnknownFieldType... qualifier) {
return new JsonDeserializerWithAccessFilter<GivenDtoWithUnknownFieldType>(ctx, userRoleAssignmentService) {
// no need to overload any method here
};
}
public JsonDeserializerWithAccessFilter<GivenChild> deserializerFor(
final Class<GivenChild> clazz,
final GivenChild... qualifier) {
return new JsonDeserializerWithAccessFilter<GivenChild>(ctx, userRoleAssignmentService) {
@Override
protected JSonFieldReader<GivenChild> jsonFieldReader(final TreeNode treeNode, final Field field) {
if ("parent".equals(field.getName())) {
return (final GivenChild target) -> {
final long id = getSubNode(treeNode, "id").asLong();
target.parent = givenParentService.findOne(id)
.orElseThrow(
() -> new BadRequestAlertException(
GivenParent.class.getSimpleName() + "#" + id + " not found",
String.valueOf(id),
"idNotFound"));
};
}
return super.jsonFieldReader(treeNode, field);
}
};
}
}

View File

@@ -1,218 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hostsharing.hsadminng.service.accessfilter.JSonAccessFilterTestFixture.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import com.fasterxml.jackson.core.JsonGenerator;
import org.apache.commons.lang3.NotImplementedException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import java.io.IOException;
import java.util.Optional;
public class JSonSerializationWithAccessFilterUnitTest {
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock
private ApplicationContext ctx;
@Mock
private AutowireCapableBeanFactory autowireCapableBeanFactory;
@Mock
private JsonGenerator jsonGenerator;
@Mock
private UserRoleAssignmentService userRoleAssignmentService;
@Mock
private GivenCustomerService givenCustomerService;
private SecurityContextMock securityContext;
private final GivenDto givenDTO = createSampleDto();
@Before
public void init() {
securityContext = SecurityContextMock.usingMock(userRoleAssignmentService)
.havingAuthenticatedUser()
.withRole(GivenCustomerDto.class, 888L, Role.AnyCustomerUser.ROLE);
given(ctx.getAutowireCapableBeanFactory()).willReturn(autowireCapableBeanFactory);
given(autowireCapableBeanFactory.createBean(GivenCustomerService.class)).willReturn(givenCustomerService);
given(givenCustomerService.findOne(888L)).willReturn(
Optional.of(
new GivenCustomerDto()
.with(dto -> dto.id = 888L)));
}
@Test
public void shouldSerializeStringField() throws IOException {
// when
serialize(givenDTO);
// then
verify(jsonGenerator).writeStringField("openStringField", givenDTO.openStringField);
}
@Test
public void shouldSerializeIntegerField() throws IOException {
// when
serialize(givenDTO);
// then
verify(jsonGenerator).writeNumberField("openIntegerField", givenDTO.openIntegerField);
}
@Test
public void shouldSerializePrimitiveIntField() throws IOException {
// when
serialize(givenDTO);
// then
verify(jsonGenerator).writeNumberField("openPrimitiveIntField", givenDTO.openPrimitiveIntField);
}
@Test
public void shouldSerializeLongField() throws IOException {
// when
final Throwable actual = catchThrowable(() -> serialize(givenDTO));
// then
verify(jsonGenerator).writeNumberField("openLongField", givenDTO.openLongField);
}
@Test
public void shouldSerializePrimitiveLongField() throws IOException {
// when
serialize(givenDTO);
// then
verify(jsonGenerator).writeNumberField("openPrimitiveLongField", givenDTO.openPrimitiveLongField);
}
@Test
public void shouldSerializeBooleanField() throws IOException {
// when
serialize(givenDTO);
// then
verify(jsonGenerator).writeBooleanField("openBooleanField", givenDTO.openBooleanField);
}
@Test
public void shouldSerializePrimitiveBooleanField() throws IOException {
// when
serialize(givenDTO);
// then
verify(jsonGenerator).writeBooleanField("openPrimitiveBooleanField", givenDTO.openPrimitiveBooleanField);
}
@Test
public void shouldSerializeBigDecimalField() throws IOException {
// when
final Throwable actual = catchThrowable(() -> serialize(givenDTO));
// then
verify(jsonGenerator).writeNumberField("openBigDecimalField", givenDTO.openBigDecimalField);
}
@Test
public void shouldSerializeLocalDateField() throws IOException {
// when
serialize(givenDTO);
// then
verify(jsonGenerator).writeStringField("openLocalDateField", givenDTO.openLocalDateFieldAsString);
}
@Test
public void shouldSerializeEnumField() throws IOException {
// when
serialize(givenDTO);
// then
verify(jsonGenerator).writeStringField("openEnumField", givenDTO.openEnumFieldAsString);
}
@Test
public void shouldSerializeRestrictedFieldIfRequiredRoleIsCoveredByUser() throws IOException {
// given
securityContext.havingAuthenticatedUser()
.withRole(GivenCustomerDto.class, 888L, Role.of(Role.CustomerFinancialContact.class));
// when
serialize(givenDTO);
// then
verify(jsonGenerator).writeStringField("restrictedField", givenDTO.restrictedField);
}
@Test
public void shouldNotSerializeRestrictedFieldIfRequiredRoleIsNotCoveredByUser() throws IOException {
// given
securityContext.havingAuthenticatedUser().withRole(GivenCustomerDto.class, 888L, Role.AnyCustomerUser.ROLE);
// when
serialize(givenDTO);
// then
verify(jsonGenerator, never()).writeStringField("restrictedField", givenDTO.restrictedField);
}
@Test
public void shouldThrowExceptionForUnimplementedFieldType() {
// given
class Arbitrary {
}
class GivenDtoWithUnimplementedFieldType implements AccessMappings {
@AccessFor(read = Role.Anybody.class)
Arbitrary fieldWithUnimplementedType = new Arbitrary();
@Override
public Long getId() {
return null;
}
}
final GivenDtoWithUnimplementedFieldType givenDtoWithUnimplementedFieldType = new GivenDtoWithUnimplementedFieldType();
SecurityContextFake.havingAuthenticatedUser();
// when
final Throwable actual = catchThrowable(() -> serialize(givenDtoWithUnimplementedFieldType));
// then
assertThat(actual).isInstanceOf(NotImplementedException.class);
}
// --- fixture code below ---
private <T extends AccessMappings> void serialize(final T dto) throws IOException {
// @formatter:off
new JsonSerializerWithAccessFilter<T>(ctx, userRoleAssignmentService) {}
.serialize(dto, jsonGenerator, null);
// @formatter:on
}
}

View File

@@ -1,195 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.ThrowableAssert.catchThrowable;
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
import org.hostsharing.hsadminng.service.accessfilter.Role.*;
import com.google.common.base.VerifyException;
import org.junit.Test;
import java.lang.reflect.Field;
public class RoleUnitTest {
@Test
public void allUserRolesShouldCoverSameRequiredRole() {
assertThat(Hostmaster.ROLE.covers(Hostmaster.class)).isTrue();
assertThat(Admin.ROLE.covers(Admin.class)).isTrue();
assertThat(Supporter.ROLE.covers(Supporter.class)).isTrue();
assertThat(Role.CustomerContractualContact.ROLE.covers(Role.CustomerContractualContact.class)).isTrue();
assertThat(CustomerFinancialContact.ROLE.covers(CustomerFinancialContact.class)).isTrue();
assertThat(CustomerTechnicalContact.ROLE.covers(CustomerTechnicalContact.class)).isTrue();
assertThat(ActualCustomerUser.ROLE.covers((ActualCustomerUser.class))).isTrue();
assertThat(AnyCustomerUser.ROLE.covers((Role.AnyCustomerUser.class))).isTrue();
}
@Test
public void lowerUserRolesShouldNotCoverHigherRequiredRoles() {
assertThat(Hostmaster.ROLE.covers(Nobody.class)).isFalse();
assertThat(Admin.ROLE.covers(Hostmaster.class)).isFalse();
assertThat(Supporter.ROLE.covers(Admin.class)).isFalse();
assertThat(AnyCustomerContact.ROLE.covers(Supporter.class)).isFalse();
assertThat(AnyCustomerContact.ROLE.covers(Role.CustomerContractualContact.class)).isFalse();
assertThat(CustomerFinancialContact.ROLE.covers(Role.CustomerContractualContact.class)).isFalse();
assertThat(CustomerFinancialContact.ROLE.covers(CustomerTechnicalContact.class)).isFalse();
assertThat(CustomerTechnicalContact.ROLE.covers(Role.CustomerContractualContact.class)).isFalse();
assertThat(CustomerTechnicalContact.ROLE.covers(CustomerFinancialContact.class)).isFalse();
assertThat(ActualCustomerUser.ROLE.covers((AnyCustomerContact.class))).isFalse();
assertThat(ActualCustomerUser.ROLE.covers((Role.CustomerContractualContact.class))).isFalse();
assertThat(ActualCustomerUser.ROLE.covers((CustomerTechnicalContact.class))).isFalse();
assertThat(ActualCustomerUser.ROLE.covers((CustomerFinancialContact.class))).isFalse();
assertThat(AnyCustomerUser.ROLE.covers((ActualCustomerUser.class))).isFalse();
assertThat(AnyCustomerUser.ROLE.covers((AnyCustomerContact.class))).isFalse();
assertThat(AnyCustomerUser.ROLE.covers((Role.CustomerContractualContact.class))).isFalse();
assertThat(AnyCustomerUser.ROLE.covers((CustomerTechnicalContact.class))).isFalse();
assertThat(AnyCustomerUser.ROLE.covers((CustomerFinancialContact.class))).isFalse();
assertThat(Anybody.ROLE.covers((Role.AnyCustomerUser.class))).isFalse();
}
@Test
public void higherUserRolesShouldCoverLowerRequiredRoles() {
assertThat(Hostmaster.ROLE.covers(Supporter.class)).isTrue();
assertThat(Admin.ROLE.covers(Supporter.class)).isTrue();
assertThat(Supporter.ROLE.covers(AnyCustomerContact.class)).isTrue();
assertThat(Role.CustomerContractualContact.ROLE.covers(AnyCustomerContact.class)).isTrue();
assertThat(Role.CustomerContractualContact.ROLE.covers(CustomerFinancialContact.class)).isTrue();
assertThat(Role.CustomerContractualContact.ROLE.covers(CustomerTechnicalContact.class)).isTrue();
assertThat(CustomerTechnicalContact.ROLE.covers(Role.AnyCustomerUser.class)).isTrue();
assertThat(ActualCustomerUser.ROLE.covers((Role.AnyCustomerUser.class))).isTrue();
assertThat(AnyCustomerUser.ROLE.covers((Anybody.class))).isTrue();
}
@Test
public void financialContactShouldNotCoverAnyOtherRealRoleRequirement() {
assertThat(CustomerFinancialContact.ROLE.covers(Role.AnyCustomerUser.class)).isFalse();
assertThat(CustomerFinancialContact.ROLE.covers(ActualCustomerUser.class)).isFalse();
assertThat(CustomerFinancialContact.ROLE.covers(Role.AnyCustomerUser.class)).isFalse();
}
@Test
public void ignoredCoversNothingAndIsNotCovered() {
assertThat(Ignored.ROLE.covers(Hostmaster.class)).isFalse();
assertThat(Ignored.ROLE.covers(Anybody.class)).isFalse();
assertThat(Ignored.ROLE.covers(Ignored.class)).isFalse();
assertThat(Hostmaster.ROLE.covers(Ignored.class)).isFalse();
assertThat(Anybody.ROLE.covers(Ignored.class)).isFalse();
}
@Test
public void coversAny() {
assertThat(Hostmaster.ROLE.coversAny(Role.CustomerContractualContact.class, CustomerFinancialContact.class)).isTrue();
assertThat(
Role.CustomerContractualContact.ROLE.coversAny(
Role.CustomerContractualContact.class,
CustomerFinancialContact.class))
.isTrue();
assertThat(
CustomerFinancialContact.ROLE.coversAny(
Role.CustomerContractualContact.class,
CustomerFinancialContact.class))
.isTrue();
assertThat(Role.AnyCustomerUser.ROLE.coversAny(Role.CustomerContractualContact.class, CustomerFinancialContact.class))
.isFalse();
assertThat(catchThrowable(Hostmaster.ROLE::coversAny)).isInstanceOf(VerifyException.class);
assertThat(
catchThrowable(
() -> Hostmaster.ROLE.coversAny(
(Class<Role>[]) null))).isInstanceOf(VerifyException.class);
}
@Test
public void toBeIgnoredForUpdates() {
assertThat(Role.toBeIgnoredForUpdates(someFieldWithoutAccessForAnnotation)).isTrue();
assertThat(Role.toBeIgnoredForUpdates(someFieldWithAccessForAnnotationToBeIgnoredForUpdates)).isTrue();
assertThat(Role.toBeIgnoredForUpdates(someFieldWithAccessForAnnotationToBeIgnoredForUpdatesAmongOthers)).isFalse();
assertThat(Role.toBeIgnoredForUpdates(someFieldWithAccessForAnnotation)).isFalse();
}
@Test
public void getAuthority() {
assertThat(Nobody.ROLE.authority()).isEqualTo(AuthoritiesConstants.USER);
assertThat(Hostmaster.ROLE.authority()).isEqualTo(AuthoritiesConstants.HOSTMASTER);
assertThat(Admin.ROLE.authority()).isEqualTo(AuthoritiesConstants.ADMIN);
assertThat(Supporter.ROLE.authority()).isEqualTo(AuthoritiesConstants.SUPPORTER);
assertThat(Role.CustomerContractualContact.ROLE.authority()).isEqualTo(AuthoritiesConstants.USER);
assertThat(Anybody.ROLE.authority()).isEqualTo(AuthoritiesConstants.ANONYMOUS);
}
@Test
public void isBroadest() {
assertThat(Role.broadest(Hostmaster.ROLE, Role.CustomerContractualContact.ROLE)).isEqualTo(Hostmaster.ROLE);
assertThat(Role.broadest(Role.CustomerContractualContact.ROLE, Hostmaster.ROLE)).isEqualTo(Hostmaster.ROLE);
assertThat(Role.broadest(Role.CustomerContractualContact.ROLE, Role.AnyCustomerUser.ROLE))
.isEqualTo(Role.CustomerContractualContact.ROLE);
}
@Test
public void isAllowedToInit() {
assertThat(Hostmaster.ROLE.isAllowedToInit(someFieldWithoutAccessForAnnotation)).isFalse();
assertThat(Supporter.ROLE.isAllowedToInit(someFieldWithoutAccessForAnnotation)).isFalse();
assertThat(Admin.ROLE.isAllowedToInit(someFieldWithAccessForAnnotation)).isTrue();
}
@Test
public void isAllowedToUpdate() {
assertThat(Hostmaster.ROLE.isAllowedToUpdate(someFieldWithoutAccessForAnnotation)).isFalse();
assertThat(AnyCustomerContact.ROLE.isAllowedToUpdate(someFieldWithAccessForAnnotation)).isFalse();
assertThat(Supporter.ROLE.isAllowedToUpdate(someFieldWithAccessForAnnotation)).isTrue();
}
@Test
public void isAllowedToRead() {
assertThat(Hostmaster.ROLE.isAllowedToRead(someFieldWithoutAccessForAnnotation)).isFalse();
assertThat(Role.AnyCustomerUser.ROLE.isAllowedToRead(someFieldWithAccessForAnnotation)).isFalse();
assertThat(AnyCustomerContact.ROLE.isAllowedToRead(someFieldWithAccessForAnnotation)).isTrue();
}
// --- only test fixture below ---
private static class TestDto {
@AccessFor(init = Admin.class, update = Supporter.class, read = AnyCustomerContact.class)
private Integer someFieldWithAccessForAnnotation;
@AccessFor(update = Ignored.class, read = AnyCustomerContact.class)
private Integer someFieldWithAccessForAnnotationToBeIgnoredForUpdates;
@AccessFor(update = { Ignored.class, Supporter.class }, read = AnyCustomerContact.class)
private Integer someFieldWithAccessForAnnotationToBeIgnoredForUpdatesAmongOthers;
private Integer someFieldWithoutAccessForAnnotation;
}
private static Field someFieldWithoutAccessForAnnotation;
private static Field someFieldWithAccessForAnnotationToBeIgnoredForUpdates;
private static Field someFieldWithAccessForAnnotationToBeIgnoredForUpdatesAmongOthers;
private static Field someFieldWithAccessForAnnotation;
static {
try {
someFieldWithoutAccessForAnnotation = TestDto.class.getDeclaredField("someFieldWithoutAccessForAnnotation");
someFieldWithAccessForAnnotationToBeIgnoredForUpdates = TestDto.class
.getDeclaredField("someFieldWithAccessForAnnotationToBeIgnoredForUpdates");
someFieldWithAccessForAnnotationToBeIgnoredForUpdatesAmongOthers = TestDto.class
.getDeclaredField("someFieldWithAccessForAnnotationToBeIgnoredForUpdatesAmongOthers");
someFieldWithAccessForAnnotation = TestDto.class.getDeclaredField("someFieldWithAccessForAnnotation");
} catch (NoSuchFieldException e) {
throw new AssertionError("precondition failed", e);
}
}
}

View File

@@ -1,57 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter;
import static org.assertj.core.api.Assumptions.assumeThat;
import org.hostsharing.hsadminng.security.SecurityUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.ArrayList;
import java.util.Collection;
abstract class SecurityContextDouble<T extends SecurityContextDouble> {
private final Collection<GrantedAuthority> authorities = new ArrayList<>();
protected SecurityContextDouble() {
}
protected SecurityContextDouble withAuthenticatedUser(final String login) {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken(login, "dummyPassword") {
@Override
public Collection<GrantedAuthority> getAuthorities() {
return authorities;
}
});
SecurityContextHolder.setContext(securityContext);
assumeThat(SecurityUtils.getCurrentUserLogin()).hasValue(login);
return this;
}
public T withAuthority(final String authority) {
authorities.add((GrantedAuthority) () -> authority);
return (T) this;
}
private static class FakePrincipal {
private final String username;
public FakePrincipal(final String username) {
this.username = username;
}
@Override
public String toString() {
return username;
}
}
}

View File

@@ -1,23 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter;
public class SecurityContextFake extends SecurityContextDouble<SecurityContextFake> {
public static SecurityContextFake havingUnauthenticatedUser() {
final SecurityContextFake securityContext = new SecurityContextFake();
return securityContext;
}
public static SecurityContextFake havingAuthenticatedUser() {
return havingAuthenticatedUser("dummyUser");
}
public static SecurityContextFake havingAuthenticatedUser(final String login) {
final SecurityContextFake securityContext = new SecurityContextFake();
securityContext.withAuthenticatedUser(login);
return securityContext;
}
protected SecurityContextFake() {
}
}

View File

@@ -1,47 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter;
import static org.assertj.core.api.Assumptions.assumeThat;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.mockito.Mockito;
import java.util.Arrays;
import java.util.HashSet;
public class SecurityContextMock extends SecurityContextDouble<SecurityContextMock> {
private final UserRoleAssignmentService userRoleAssignmentService;
public static SecurityContextMock usingMock(final UserRoleAssignmentService userRoleAssignmentService) {
return new SecurityContextMock(userRoleAssignmentService);
}
public SecurityContextMock(final UserRoleAssignmentService userRoleAssignmentService) {
this.userRoleAssignmentService = userRoleAssignmentService;
}
public SecurityContextMock havingAuthenticatedUser() {
return havingAuthenticatedUser("dummyUser");
}
public SecurityContextMock havingAuthenticatedUser(final String login) {
super.withAuthenticatedUser(login);
Mockito.reset(userRoleAssignmentService);
return this;
}
public SecurityContextMock withRole(final Class<?> onClass, final long onId, final Role... roles) {
if (userRoleAssignmentService == null) {
throw new IllegalStateException("mock not registered for: " + UserRoleAssignmentService.class.getSimpleName());
}
final EntityTypeId entityTypeId = onClass.getAnnotation(EntityTypeId.class);
assumeThat(entityTypeId).as("@" + EntityTypeId.class.getSimpleName() + " missing on class " + onClass.toString())
.isNotNull();
given(userRoleAssignmentService.getEffectiveRoleOfCurrentUser(entityTypeId.value(), onId))
.willReturn(new HashSet(Arrays.asList(roles)));
return this;
}
}

View File

@@ -1,237 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import static org.apache.commons.lang3.StringUtils.removeEnd;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import org.hostsharing.hsadminng.service.accessfilter.*;
import org.hostsharing.hsadminng.service.util.ReflectionUtil;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Test;
import org.springframework.boot.jackson.JsonComponent;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Usually base classes for unit tests are not a good idea, but because
* DTOs which implement AccessMapping are more like a DSL,
* this base class should be used to enforce its required structure.
*/
public abstract class AccessMappingsUnitTestBase<D> {
private final Class<? extends AccessMappings> dtoClass;
private final BiFunction<Long, Long, D> createSampleDTO;
private final BiFunction<Long, Long, D> createRandomDTO;
public AccessMappingsUnitTestBase(
Class<? extends AccessMappings> dtoClass,
final BiFunction<Long, Long, D> createSampleDTO,
final BiFunction<Long, Long, D> createRandomDTO) {
this.dtoClass = dtoClass;
this.createSampleDTO = createSampleDTO;
this.createRandomDTO = createRandomDTO;
}
@Test
public void shouldConvertToString() {
final D sampleDto = createSampleDTO.apply(1234L, 77L);
final String dtoAsString = dtoToString(sampleDto);
assertThat(sampleDto.toString()).isEqualTo(dtoAsString);
}
@Test
@SuppressWarnings("all")
public void shouldImplementEqualsJustUsingClassAndId() {
final D dto = createSampleDTO.apply(1234L, 77L);
assertThat(dto.equals(dto)).isTrue();
final D dtoWithSameId = createSampleDTO.apply(1234L, 77L);
assertThat(dto.equals(dtoWithSameId)).isTrue();
final D dtoWithAnotherId = createSampleDTO.apply(RandomUtils.nextLong(2000, 9999), 77L);
assertThat(dtoWithAnotherId.equals(dtoWithSameId)).isFalse();
final D dtoWithoutId = createSampleDTO.apply(null, RandomUtils.nextLong());
assertThat(dto.equals(dtoWithoutId)).isFalse();
assertThat(dtoWithoutId.equals(dto)).isFalse();
assertThat(dto.equals(null)).isFalse();
assertThat(dto.equals("")).isFalse();
}
@Test
public void shouldImplementHashCodeJustUsingClassAndId() {
final long randomId = RandomUtils.nextLong();
final D dto = createSampleDTO.apply(randomId, RandomUtils.nextLong());
assertThat(dto.hashCode()).isEqualTo(Objects.hashCode(randomId));
final D dtoWithoutId = createSampleDTO.apply(null, RandomUtils.nextLong());
assertThat(dtoWithoutId.hashCode()).isEqualTo(Objects.hashCode(null));
}
@Test
public void shouldImplementAccessMappings() {
assertThat(dtoClass.getInterfaces()).as("must implement " + AccessMappings.class).contains(AccessMappings.class);
}
@Test
public void shouldImplementSerializer() {
shouldImplementJsonComponent(JsonSerializerWithAccessFilter.class);
}
@Test
public void shouldImplementDeserializer() {
shouldImplementJsonComponent(JsonDeserializerWithAccessFilter.class);
}
// --- only test fixture below ---
protected AccessRightsMatcher initAccessFor(final Class<D> dtoClass, final Role role) {
return new AccessRightsMatcher(dtoClass, role, AccessFor::init);
}
protected AccessRightsMatcher updateAccessFor(final Class<D> dtoClass, final Role role) {
return new AccessRightsMatcher(dtoClass, role, AccessFor::update);
}
protected AccessRightsMatcher readAccessFor(final Class<D> dtoClass, final Role role) {
return new AccessRightsMatcher(dtoClass, role, AccessFor::read);
}
// This class should have the same generics as the outer class, but then the
// method references (AccessFor::*) can't be resolved anymore by the Java compiler.
protected static class AccessRightsMatcher {
private final Object dtoClass;
private final Role role;
private final String[] namesOfFieldsWithAccessForAnnotation;
private final String[] namesOfAccessibleFields;
AccessRightsMatcher(final Class dtoClass, final Role role, final Function<AccessFor, Class<? extends Role>[]> access) {
this.dtoClass = dtoClass;
this.role = role;
final Set<Field> fieldsWithAccessForAnnotation = determineFieldsWithAccessForAnnotation(dtoClass);
this.namesOfFieldsWithAccessForAnnotation = fieldsWithAccessForAnnotation.stream()
.map(Field::getName)
.collect(Collectors.toList())
.toArray(new String[] {});
this.namesOfAccessibleFields = fieldsWithAccessForAnnotation.stream()
.filter(f -> allows(f, access, role))
.map(Field::getName)
.collect(Collectors.toList())
.toArray(new String[] {});
}
public void shouldBeExactlyFor(final String... expectedFields) {
assertThat(namesOfAccessibleFields).containsExactlyInAnyOrder(expectedFields);
}
public void shouldBeForNothing() {
assertThat(namesOfAccessibleFields).isEmpty();
}
public void shouldBeForAllFields() {
assertThat(namesOfAccessibleFields).containsExactlyInAnyOrder(namesOfFieldsWithAccessForAnnotation);
}
private static Set<Field> determineFieldsWithAccessForAnnotation(final Class<?> dtoClass) {
final Set<Field> fieldsWithAccessForAnnotation = new HashSet<>();
for (Field field : dtoClass.getDeclaredFields()) {
if (field.isAnnotationPresent(AccessFor.class)) {
final AccessFor accessFor = field.getAnnotation(AccessFor.class);
fieldsWithAccessForAnnotation.add(field);
}
}
return fieldsWithAccessForAnnotation;
}
private static boolean allows(
final Field field,
final Function<AccessFor, Class<? extends Role>[]> access,
final Role role) {
if (field.isAnnotationPresent(AccessFor.class)) {
final AccessFor accessFor = field.getAnnotation(AccessFor.class);
Class<? extends Role>[] roleClasses = access.apply(accessFor);
return role.coversAny(roleClasses);
}
return false;
}
}
private String dtoToString(final D dto) {
final StringBuilder fieldValues = new StringBuilder();
boolean firstField = true;
for (Field field : dto.getClass().getDeclaredFields()) {
if (field.isAnnotationPresent(AccessFor.class)) {
firstField = appendCommaOptionally(fieldValues, firstField);
appendFieldName(fieldValues, field);
appendFieldValue(dto, fieldValues, field);
}
}
return dto.getClass().getSimpleName() + "{" + fieldValues + "}";
}
private void appendFieldValue(final D dto, final StringBuilder fieldValues, final Field field) {
final Object value = ReflectionUtil.getValue(dto, field);
final boolean inQuotes = isJHipsterToStringUsingQuotes(field);
if (inQuotes) {
fieldValues.append("'");
}
fieldValues.append(value);
if (inQuotes) {
fieldValues.append("'");
}
}
private void appendFieldName(final StringBuilder fieldValues, final Field field) {
fieldValues.append(removeEnd(field.getName(), "Id"));
fieldValues.append("=");
}
private boolean appendCommaOptionally(final StringBuilder fieldValues, boolean firstField) {
if (firstField) {
firstField = false;
} else {
fieldValues.append(", ");
}
return firstField;
}
private boolean isJHipsterToStringUsingQuotes(final Field field) {
return !Number.class.isAssignableFrom(field.getType()) && !Boolean.class.isAssignableFrom(field.getType());
}
private void shouldImplementJsonComponent(final Class<?> expectedSuperclass) {
for (Class<?> declaredClass : dtoClass.getDeclaredClasses()) {
if (expectedSuperclass.isAssignableFrom(declaredClass)) {
assertThat(declaredClass.isAnnotationPresent(JsonComponent.class))
.as(declaredClass + " requires @" + JsonComponent.class.getSimpleName())
.isTrue();
assertThat(ReflectionUtil.determineGenericClassParameter(declaredClass, expectedSuperclass, 0))
.as(declaredClass + " must resolve generic parameter of " + expectedSuperclass + " to type of DTO")
.isEqualTo(dtoClass);
assertThat(Modifier.isPublic(declaredClass.getModifiers())).as(declaredClass + " must be public").isTrue();
assertThat(Modifier.isStatic(declaredClass.getModifiers())).as(declaredClass + " must be static").isTrue();
assertThat(Modifier.isFinal(declaredClass.getModifiers())).as(declaredClass + " must not be final").isFalse();
assertThat(Modifier.isAbstract(declaredClass.getModifiers())).as(declaredClass + " must not be abstract")
.isFalse();
return;
}
}
fail("no " + expectedSuperclass + " defined for " + dtoClass);
}
}

View File

@@ -1,229 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.domain.Asset;
import org.hostsharing.hsadminng.domain.Customer;
import org.hostsharing.hsadminng.domain.Membership;
import org.hostsharing.hsadminng.domain.enumeration.AssetAction;
import org.hostsharing.hsadminng.repository.AssetRepository;
import org.hostsharing.hsadminng.repository.CustomerRepository;
import org.hostsharing.hsadminng.repository.MembershipRepository;
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
import org.hostsharing.hsadminng.service.AssetService;
import org.hostsharing.hsadminng.service.AssetValidator;
import org.hostsharing.hsadminng.service.MembershipValidator;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerFinancialContact;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock;
import org.hostsharing.hsadminng.service.mapper.AssetMapper;
import org.hostsharing.hsadminng.service.mapper.AssetMapperImpl;
import org.hostsharing.hsadminng.service.mapper.CustomerMapperImpl;
import org.hostsharing.hsadminng.service.mapper.MembershipMapperImpl;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Optional;
import javax.persistence.EntityManager;
@JsonTest
@SpringBootTest(
classes = {
CustomerMapperImpl.class,
MembershipMapperImpl.class,
AssetMapperImpl.class,
AssetDTO.JsonSerializer.class,
AssetDTO.JsonDeserializer.class
})
@RunWith(SpringRunner.class)
public class AssetDTOIntTest {
private static final Long SOME_CUSTOMER_ID = RandomUtils.nextLong(100, 199);
private static final Integer SOME_CUSTOMER_REFERENCE = 10001;
private static final String SOME_CUSTOMER_PREFIX = "abc";
private static final String SOME_CUSTOMER_NAME = "Some Customer Name";
private static final Customer SOME_CUSTOMER = new Customer().id(SOME_CUSTOMER_ID)
.reference(SOME_CUSTOMER_REFERENCE)
.prefix(SOME_CUSTOMER_PREFIX)
.name(SOME_CUSTOMER_NAME);
private static final Long SOME_MEMBERSHIP_ID = RandomUtils.nextLong(200, 299);
private static final LocalDate SOME_MEMBER_FROM_DATE = LocalDate.parse("2000-12-06");
private static final Membership SOME_MEMBERSHIP = new Membership().id(SOME_MEMBERSHIP_ID)
.customer(SOME_CUSTOMER)
.memberFromDate(SOME_MEMBER_FROM_DATE);
private static final String SOME_MEMBERSHIP_DISPLAY_LABEL = "Some Customer Name [10001:abc] 2000-12-06 - ...";
private static final Long SOME_ASSET_ID = RandomUtils.nextLong(300, 399);
private static final Asset SOME_ASSET = new Asset().id(SOME_ASSET_ID).membership(SOME_MEMBERSHIP);
@Rule
public MockitoRule mockito = MockitoJUnit.rule();
@Autowired
private ObjectMapper objectMapper;
@Autowired
private AssetMapper assetMapper;
@MockBean
private AssetRepository assetRepository;
@MockBean
private AssetValidator assetValidator;
@MockBean
private CustomerRepository customerRepository;
@MockBean
private MembershipRepository membershipRepository;
@MockBean
private MembershipValidator membershipValidator;
@MockBean
private AssetService assetService;
@MockBean
private EntityManager em;
@MockBean
private UserRoleAssignmentService userRoleAssignmentService;
private SecurityContextMock securityContext;
@Before
public void init() {
given(customerRepository.findById(SOME_CUSTOMER_ID)).willReturn(Optional.of(SOME_CUSTOMER));
given(membershipRepository.findById(SOME_MEMBERSHIP_ID)).willReturn(Optional.of(SOME_MEMBERSHIP));
given(assetRepository.findById(SOME_ASSET_ID)).willReturn((Optional.of(SOME_ASSET)));
securityContext = SecurityContextMock.usingMock(userRoleAssignmentService);
}
@Test
public void shouldSerializePartiallyForFinancialCustomerContact() throws JsonProcessingException {
// given
securityContext.havingAuthenticatedUser()
.withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.of(CustomerFinancialContact.class));
final AssetDTO given = createSomeAssetDTO(SOME_ASSET_ID);
// when
final String actual = objectMapper.writeValueAsString(given);
// then
given.setRemark(null);
assertEquals(createExpectedJSon(given), actual);
}
@Test
public void shouldSerializeCompletelyForSupporter() throws JsonProcessingException {
// given
securityContext.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.SUPPORTER);
final AssetDTO given = createSomeAssetDTO(SOME_ASSET_ID);
// when
final String actual = objectMapper.writeValueAsString(given);
// then
assertEquals(createExpectedJSon(given), actual);
}
@Test
public void shouldNotDeserializeForContractualCustomerContact() {
// given
securityContext.havingAuthenticatedUser()
.withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.of(CustomerContractualContact.class));
final String json = new JSonBuilder()
.withFieldValue("id", SOME_ASSET_ID)
.withFieldValue("remark", "Updated Remark")
.toString();
// when
final Throwable actual = catchThrowable(() -> objectMapper.readValue(json, AssetDTO.class));
// then
assertThat(actual).isInstanceOfSatisfying(
BadRequestAlertException.class,
bre -> assertThat(bre.getMessage())
.isEqualTo(
"Update of field AssetDTO.remark prohibited for current user role(s): CustomerContractualContact"));
}
@Test
public void shouldDeserializeForAdminIfRemarkIsChanged() throws IOException {
// given
securityContext.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.ADMIN);
final String json = new JSonBuilder()
.withFieldValue("id", SOME_ASSET_ID)
.withFieldValue("remark", "Updated Remark")
.toString();
// when
final AssetDTO actual = objectMapper.readValue(json, AssetDTO.class);
// then
final AssetDTO expected = new AssetDTO();
expected.setId(SOME_ASSET_ID);
expected.setMembershipId(SOME_MEMBERSHIP_ID);
expected.setRemark("Updated Remark");
expected.setMembershipDisplayLabel(SOME_MEMBERSHIP_DISPLAY_LABEL);
assertThat(actual).isEqualToIgnoringGivenFields(expected, "displayLabel");
}
// --- only test fixture below ---
private String createExpectedJSon(AssetDTO dto) {
return new JSonBuilder()
.withFieldValueIfPresent("id", dto.getId())
.withFieldValueIfPresent("documentDate", dto.getDocumentDate().toString())
.withFieldValueIfPresent("valueDate", dto.getValueDate().toString())
.withFieldValueIfPresent("action", dto.getAction().name())
.withFieldValueIfPresent("amount", dto.getAmount().doubleValue())
.withFieldValueIfPresent("remark", dto.getRemark())
.withFieldValueIfPresent("membershipId", dto.getMembershipId())
.withFieldValue("membershipDisplayLabel", dto.getMembershipDisplayLabel())
.toString();
}
private AssetDTO createSomeAssetDTO(final long id) {
final AssetDTO given = new AssetDTO();
given.setId(id);
given.setAction(AssetAction.PAYMENT);
given.setAmount(new BigDecimal("512.01"));
given.setDocumentDate(LocalDate.parse("2019-04-27"));
given.setValueDate(LocalDate.parse("2019-04-28"));
given.setMembershipId(SOME_MEMBERSHIP_ID);
given.setRemark("Some Remark");
given.setMembershipDisplayLabel("Display Label for Membership #" + SOME_MEMBERSHIP_ID);
return given;
}
}

View File

@@ -1,92 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import org.hostsharing.hsadminng.domain.enumeration.AssetAction;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.Admin;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.util.RandomUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Test;
import java.math.BigDecimal;
import java.time.LocalDate;
public class AssetDTOUnitTest extends AccessMappingsUnitTestBase<AssetDTO> {
public AssetDTOUnitTest() {
super(AssetDTO.class, AssetDTOUnitTest::createSampleDTO, AssetDTOUnitTest::createRandomDTO);
}
@Test
public void shouldHaveProperAccessForAdmin() {
initAccessFor(AssetDTO.class, Admin.ROLE).shouldBeExactlyFor(
"membershipId",
"documentDate",
"amount",
"action",
"valueDate",
"remark");
updateAccessFor(AssetDTO.class, Admin.ROLE).shouldBeExactlyFor("remark");
readAccessFor(AssetDTO.class, Admin.ROLE).shouldBeForAllFields();
}
@Test
public void shouldHaveProperAccessForContractualContact() {
initAccessFor(AssetDTO.class, CustomerContractualContact.ROLE).shouldBeForNothing();
updateAccessFor(AssetDTO.class, CustomerContractualContact.ROLE).shouldBeForNothing();
readAccessFor(AssetDTO.class, CustomerContractualContact.ROLE).shouldBeExactlyFor(
"id",
"membershipId",
"documentDate",
"amount",
"action",
"valueDate",
"membershipDisplayLabel");
}
@Test
public void shouldHaveNoAccessForTechnicalContact() {
initAccessFor(AssetDTO.class, Role.CustomerTechnicalContact.ROLE).shouldBeForNothing();
updateAccessFor(AssetDTO.class, Role.CustomerTechnicalContact.ROLE).shouldBeForNothing();
readAccessFor(AssetDTO.class, Role.CustomerTechnicalContact.ROLE).shouldBeForNothing();
}
@Test
public void shouldHaveNoAccessForNormalUsersWithinCustomerRealm() {
initAccessFor(AssetDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
updateAccessFor(AssetDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
readAccessFor(AssetDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
}
// --- only test fixture below ---
private static AssetDTO createSampleDTO(final Long id, final Long parentId) {
final AssetDTO dto = new AssetDTO();
dto.setId(id);
dto.setDocumentDate(LocalDate.parse("2000-12-07"));
dto.setAmount(new BigDecimal("512.01"));
dto.setAction(AssetAction.PAYMENT);
dto.setRemark("Some Remark");
dto.setValueDate(LocalDate.parse("2000-12-18"));
dto.setMembershipId(parentId);
dto.setMembershipDisplayLabel("Some Membership");
return dto;
}
private static AssetDTO createRandomDTO(final Long id, final Long parentId) {
final AssetDTO dto = new AssetDTO();
dto.setId(id);
final LocalDate randomDate = LocalDate.parse("2000-12-07").plusDays(RandomUtils.nextInt(1, 999));
dto.setDocumentDate(randomDate);
dto.setAmount(new BigDecimal(RandomUtils.nextDouble()));
dto.setAction(RandomUtil.generateEnumValue(AssetAction.class));
dto.setRemark(RandomStringUtils.randomAlphanumeric(20));
dto.setValueDate(randomDate.plusDays(RandomUtils.nextInt(1, 99)));
dto.setMembershipId(parentId);
dto.setMembershipDisplayLabel("The Membership #" + dto.getMembershipId());
return dto;
}
}

View File

@@ -1,188 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.domain.Customer;
import org.hostsharing.hsadminng.domain.enumeration.CustomerKind;
import org.hostsharing.hsadminng.domain.enumeration.VatRegion;
import org.hostsharing.hsadminng.repository.CustomerRepository;
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
import org.hostsharing.hsadminng.service.CustomerService;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerTechnicalContact;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock;
import org.hostsharing.hsadminng.service.mapper.CustomerMapper;
import org.hostsharing.hsadminng.service.mapper.CustomerMapperImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.util.Optional;
@JsonTest
@SpringBootTest(
classes = {
CustomerMapperImpl.class,
CustomerRepository.class,
CustomerService.class,
CustomerDTO.CustomerJsonSerializer.class,
CustomerDTO.CustomerJsonDeserializer.class })
@RunWith(SpringRunner.class)
public class CustomerDTOUnitTest {
@Rule
public MockitoRule mockito = MockitoJUnit.rule();
@Autowired
private ObjectMapper objectMapper;
@Autowired
private CustomerMapper customerMapper;
@MockBean
private CustomerRepository customerRepository;
@MockBean
private CustomerService customerService;
@MockBean
private UserRoleAssignmentService userRoleAssignmentService;
private SecurityContextMock securityContext;
@Before
public void init() {
securityContext = SecurityContextMock.usingMock(userRoleAssignmentService);
}
@Test
public void testSerializationAsContractualCustomerContact() throws JsonProcessingException {
// given
securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, 1234L, Role.of(CustomerContractualContact.class));
CustomerDTO given = createSomeCustomerDTO(1234L);
// when
String actual = objectMapper.writeValueAsString(given);
// then
given.setRemark(null);
assertEquals(createExpectedJSon(given), actual);
}
@Test
public void testSerializationAsTechnicalCustomerUser() throws JsonProcessingException {
// given
securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, 1234L, Role.of(CustomerTechnicalContact.class));
CustomerDTO given = createSomeCustomerDTO(1234L);
// when
String actual = objectMapper.writeValueAsString(given);
// then
final String expectedJSon = new JSonBuilder()
.withFieldValue("id", given.getId())
.withFieldValue("reference", given.getReference())
.withFieldValue("prefix", given.getPrefix())
.withFieldValue("name", given.getName())
.withFieldValue("displayLabel", given.getDisplayLabel())
.toString();
assertEquals(expectedJSon, actual);
}
@Test
public void testSerializationAsSupporter() throws JsonProcessingException {
// given
securityContext.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.SUPPORTER);
CustomerDTO given = createSomeCustomerDTO(1234L);
// when
String actual = objectMapper.writeValueAsString(given);
// then
assertThat(actual).isEqualTo(createExpectedJSon(given));
}
@Test
public void testDeserializeAsContractualCustomerContact() throws IOException {
// given
securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, 1234L, Role.of(CustomerContractualContact.class));
given(customerRepository.findById(1234L)).willReturn(Optional.of(new Customer().id(1234L)));
String json = "{\"id\":1234,\"contractualSalutation\":\"Hallo Updated\",\"billingSalutation\":\"Moin Updated\"}";
// when
CustomerDTO actual = objectMapper.readValue(json, CustomerDTO.class);
// then
CustomerDTO expected = new CustomerDTO();
expected.setId(1234L);
expected.setContractualSalutation("Hallo Updated");
expected.setBillingSalutation("Moin Updated");
assertThat(actual).isEqualToIgnoringGivenFields(expected, "displayLabel");
}
// --- only test fixture below ---
private String createExpectedJSon(CustomerDTO dto) {
return new JSonBuilder()
.withFieldValueIfPresent("id", dto.getId())
.withFieldValueIfPresent("reference", dto.getReference())
.withFieldValueIfPresent("prefix", dto.getPrefix())
.withFieldValueIfPresent("name", dto.getName())
.withFieldValueIfPresent("kind", "LEGAL")
.toJSonNullFieldDefinition("birthDate")
.toJSonNullFieldDefinition("birthPlace")
.withFieldValueIfPresent("registrationCourt", "Registergericht")
.withFieldValueIfPresent("registrationNumber", "Registernummer")
.withFieldValueIfPresent("vatRegion", "DOMESTIC")
.withFieldValueIfPresent("vatNumber", "DE1234")
.withFieldValueIfPresent("contractualSalutation", dto.getContractualSalutation())
.withFieldValueIfPresent("contractualAddress", dto.getContractualAddress())
.withFieldValueIfPresent("billingSalutation", dto.getBillingSalutation())
.withFieldValueIfPresent("billingAddress", dto.getBillingAddress())
.withFieldValueIfPresent("remark", dto.getRemark())
.withFieldValueIfPresent("displayLabel", dto.getDisplayLabel())
.toString();
}
private CustomerDTO createSomeCustomerDTO(final long id) {
final CustomerDTO given = new CustomerDTO();
given.setId(id);
given.setReference(10001);
given.setPrefix("abc");
given.setName("Mein Name");
given.setKind(CustomerKind.LEGAL);
given.setRegistrationCourt("Registergericht");
given.setRegistrationNumber("Registernummer");
given.setVatRegion(VatRegion.DOMESTIC);
given.setVatNumber("DE1234");
given.setContractualAddress("Eine Adresse");
given.setContractualSalutation("Hallo");
given.setBillingAddress("Noch eine Adresse");
given.setBillingSalutation("Moin");
given.setRemark("Eine Bemerkung");
given.setDisplayLabel("Display Label");
return given;
}
}

View File

@@ -1,197 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hostsharing.hsadminng.service.dto.MembershipDTOUnitTest.createSampleDTO;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.domain.Customer;
import org.hostsharing.hsadminng.domain.Membership;
import org.hostsharing.hsadminng.repository.CustomerRepository;
import org.hostsharing.hsadminng.repository.MembershipRepository;
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
import org.hostsharing.hsadminng.service.MembershipService;
import org.hostsharing.hsadminng.service.MembershipValidator;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerFinancialContact;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock;
import org.hostsharing.hsadminng.service.mapper.CustomerMapperImpl;
import org.hostsharing.hsadminng.service.mapper.MembershipMapper;
import org.hostsharing.hsadminng.service.mapper.MembershipMapperImpl;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;
import javax.persistence.EntityManager;
@JsonTest
@SpringBootTest(
classes = {
CustomerMapperImpl.class,
MembershipMapperImpl.class,
MembershipMapperImpl.class,
MembershipDTO.JsonSerializer.class,
MembershipDTO.JsonDeserializer.class
})
@RunWith(SpringRunner.class)
public class MembershipDTOIntTest {
private static final Long SOME_CUSTOMER_ID = RandomUtils.nextLong(100, 199);
private static final Integer SOME_CUSTOMER_REFERENCE = 10001;
private static final String SOME_CUSTOMER_PREFIX = "abc";
private static final String SOME_CUSTOMER_NAME = "Some Customer Name";
private static final String SOME_CUSTOMER_DISPLAY_LABEL = "Some Customer Name [10001:abc]";
private static final Customer SOME_CUSTOMER = new Customer().id(SOME_CUSTOMER_ID)
.reference(SOME_CUSTOMER_REFERENCE)
.prefix(SOME_CUSTOMER_PREFIX)
.name(SOME_CUSTOMER_NAME);
private static final Long SOME_SEPA_MANDATE_ID = RandomUtils.nextLong(300, 399);
private static final Membership SOME_SEPA_MANDATE = new Membership().id(SOME_SEPA_MANDATE_ID).customer(SOME_CUSTOMER);
@Rule
public MockitoRule mockito = MockitoJUnit.rule();
@Autowired
private ObjectMapper objectMapper;
@Autowired
private MembershipMapper membershipMapper;
@MockBean
private CustomerRepository customerRepository;
@MockBean
private MembershipRepository membershipRepository;
@MockBean
private MembershipValidator membershipValidator;
@MockBean
private MembershipService MembershipService;
@MockBean
private EntityManager em;
@MockBean
public UserRoleAssignmentService userRoleAssignmentService;
private SecurityContextMock securityContext;
@Before
public void init() {
given(customerRepository.findById(SOME_CUSTOMER_ID)).willReturn(Optional.of(SOME_CUSTOMER));
given(membershipRepository.findById(SOME_SEPA_MANDATE_ID)).willReturn((Optional.of(SOME_SEPA_MANDATE)));
securityContext = SecurityContextMock.usingMock(userRoleAssignmentService);
}
@Test
public void shouldSerializePartiallyForFinancialCustomerContact() throws JsonProcessingException {
// given
securityContext.havingAuthenticatedUser()
.withRole(CustomerDTO.class, SOME_CUSTOMER_ID, CustomerFinancialContact.ROLE);
final MembershipDTO given = createSampleDTO(SOME_SEPA_MANDATE_ID, SOME_CUSTOMER_ID);
// when
final String actual = objectMapper.writeValueAsString(given);
// then
given.setRemark(null);
assertEquals(createExpectedJSon(given), actual);
}
@Test
public void shouldSerializeCompletelyForSupporter() throws JsonProcessingException {
// given
securityContext.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.SUPPORTER);
final MembershipDTO given = createSampleDTO(SOME_SEPA_MANDATE_ID, SOME_CUSTOMER_ID);
// when
final String actual = objectMapper.writeValueAsString(given);
// then
assertEquals(createExpectedJSon(given), actual);
}
@Test
public void shouldNotDeserializeForContractualCustomerContact() {
// given
securityContext.havingAuthenticatedUser()
.withRole(CustomerDTO.class, SOME_CUSTOMER_ID, CustomerContractualContact.ROLE);
final String json = new JSonBuilder()
.withFieldValue("id", SOME_SEPA_MANDATE_ID)
.withFieldValue("remark", "Updated Remark")
.toString();
// when
final Throwable actual = catchThrowable(() -> objectMapper.readValue(json, MembershipDTO.class));
// then
assertThat(actual).isInstanceOfSatisfying(
BadRequestAlertException.class,
bre -> assertThat(bre.getMessage()).isEqualTo(
"Update of field MembershipDTO.remark prohibited for current user role(s): CustomerContractualContact"));
}
@Test
public void shouldDeserializeForAdminIfRemarkIsChanged() throws IOException {
// given
securityContext.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.ADMIN);
final String json = new JSonBuilder()
.withFieldValue("id", SOME_SEPA_MANDATE_ID)
.withFieldValue("remark", "Updated Remark")
.toString();
// when
final MembershipDTO actual = objectMapper.readValue(json, MembershipDTO.class);
// then
final MembershipDTO expected = new MembershipDTO();
expected.setId(SOME_SEPA_MANDATE_ID);
expected.setCustomerId(SOME_CUSTOMER_ID);
expected.setRemark("Updated Remark");
assertThat(actual).isEqualToIgnoringGivenFields(expected, "customerPrefix", "customerDisplayLabel", "displayLabel");
}
// --- only test fixture below ---
private String createExpectedJSon(MembershipDTO dto) {
return new JSonBuilder()
.withFieldValueIfPresent("id", dto.getId())
.withFieldValueIfPresent("admissionDocumentDate", Objects.toString(dto.getAdmissionDocumentDate()))
.withFieldValueIfPresent("cancellationDocumentDate", Objects.toString(dto.getCancellationDocumentDate()))
.withFieldValueIfPresent("memberFromDate", Objects.toString(dto.getMemberFromDate()))
.withFieldValueIfPresent("memberUntilDate", Objects.toString(dto.getMemberUntilDate()))
.withFieldValueIfPresent("remark", dto.getRemark())
.withFieldValueIfPresent("customerId", dto.getCustomerId())
.withFieldValue("customerPrefix", dto.getCustomerPrefix())
.withFieldValue("customerDisplayLabel", dto.getCustomerDisplayLabel())
.withFieldValue("displayLabel", dto.getDisplayLabel())
.toString();
}
}

View File

@@ -1,108 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.Admin;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerTechnicalContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.Supporter;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Test;
import java.time.LocalDate;
public class MembershipDTOUnitTest extends AccessMappingsUnitTestBase<MembershipDTO> {
public MembershipDTOUnitTest() {
super(MembershipDTO.class, MembershipDTOUnitTest::createSampleDTO, MembershipDTOUnitTest::createRandomDTO);
}
@Test
public void shouldHaveProperAccessForAdmin() {
initAccessFor(MembershipDTO.class, Admin.ROLE).shouldBeExactlyFor(
"admissionDocumentDate",
"cancellationDocumentDate",
"memberFromDate",
"memberUntilDate",
"customerId",
"remark");
updateAccessFor(MembershipDTO.class, Admin.ROLE).shouldBeExactlyFor(
"cancellationDocumentDate",
"memberUntilDate",
"remark");
readAccessFor(MembershipDTO.class, Admin.ROLE).shouldBeForAllFields();
}
@Test
public void shouldHaveProperAccessForSupporter() {
initAccessFor(MembershipDTO.class, Supporter.ROLE).shouldBeForNothing();
updateAccessFor(MembershipDTO.class, Supporter.ROLE).shouldBeForNothing();
readAccessFor(MembershipDTO.class, Supporter.ROLE).shouldBeForAllFields();
}
@Test
public void shouldHaveProperAccessForContractualContact() {
initAccessFor(MembershipDTO.class, CustomerContractualContact.ROLE).shouldBeForNothing();
updateAccessFor(MembershipDTO.class, CustomerContractualContact.ROLE).shouldBeForNothing();
readAccessFor(MembershipDTO.class, CustomerContractualContact.ROLE).shouldBeExactlyFor(
"id",
"admissionDocumentDate",
"cancellationDocumentDate",
"memberFromDate",
"memberUntilDate",
"customerId",
"customerPrefix",
"customerDisplayLabel",
"displayLabel");
}
@Test
public void shouldHaveNoAccessForTechnicalContact() {
initAccessFor(MembershipDTO.class, CustomerTechnicalContact.ROLE).shouldBeForNothing();
updateAccessFor(MembershipDTO.class, CustomerTechnicalContact.ROLE).shouldBeForNothing();
readAccessFor(MembershipDTO.class, CustomerTechnicalContact.ROLE).shouldBeForNothing();
}
@Test
public void shouldHaveNoAccessForNormalUsersWithinCustomerRealm() {
initAccessFor(MembershipDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
updateAccessFor(MembershipDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
readAccessFor(MembershipDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
}
// --- only test fixture below ---
static MembershipDTO createSampleDTO(final Long id, final Long parentId) {
final MembershipDTO dto = new MembershipDTO();
dto.setId(id);
final LocalDate referenceDate = LocalDate.parse("2000-12-07");
dto.setAdmissionDocumentDate(referenceDate);
dto.setCancellationDocumentDate(referenceDate.plusDays(3500));
dto.setMemberFromDate(referenceDate.plusDays(4));
dto.setMemberUntilDate(referenceDate.plusDays(3500).plusDays(400).withDayOfYear(1).minusDays(1));
dto.setRemark("Some Remark");
dto.setCustomerId(parentId);
dto.setCustomerPrefix("abc");
dto.setCustomerDisplayLabel("ABC GmbH [abc:10001]");
dto.setDisplayLabel("ABC GmbH [abc:10001] 2000-12-11 - 2011-12-31");
return dto;
}
public static MembershipDTO createRandomDTO(final Long id, final Long parentId) {
final MembershipDTO dto = new MembershipDTO();
dto.setId(id);
final LocalDate randomDate = LocalDate.parse("2000-12-07").plusDays(RandomUtils.nextInt(1, 999));
dto.setAdmissionDocumentDate(randomDate);
dto.setCancellationDocumentDate(randomDate.plusDays(3500));
dto.setMemberFromDate(randomDate.plusDays(4));
dto.setMemberUntilDate(randomDate.plusDays(3500).plusDays(400).withDayOfYear(1).minusDays(1));
dto.setRemark(RandomStringUtils.randomAlphanumeric(20).toUpperCase());
dto.setCustomerId(parentId);
dto.setCustomerPrefix(RandomStringUtils.randomAlphabetic(3).toLowerCase());
dto.setCustomerDisplayLabel(RandomStringUtils.randomAlphabetic(13));
dto.setDisplayLabel(dto.getCustomerDisplayLabel() + dto.getMemberFromDate() + " - " + dto.getMemberUntilDate());
return dto;
}
}

View File

@@ -1,206 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hostsharing.hsadminng.service.dto.SepaMandateDTOUnitTest.createSampleDTO;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.domain.Customer;
import org.hostsharing.hsadminng.domain.SepaMandate;
import org.hostsharing.hsadminng.repository.CustomerRepository;
import org.hostsharing.hsadminng.repository.MembershipRepository;
import org.hostsharing.hsadminng.repository.SepaMandateRepository;
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
import org.hostsharing.hsadminng.service.MembershipValidator;
import org.hostsharing.hsadminng.service.SepaMandateService;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerFinancialContact;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock;
import org.hostsharing.hsadminng.service.mapper.CustomerMapperImpl;
import org.hostsharing.hsadminng.service.mapper.MembershipMapperImpl;
import org.hostsharing.hsadminng.service.mapper.SepaMandateMapper;
import org.hostsharing.hsadminng.service.mapper.SepaMandateMapperImpl;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;
import javax.persistence.EntityManager;
@JsonTest
@SpringBootTest(
classes = {
CustomerMapperImpl.class,
MembershipMapperImpl.class,
SepaMandateMapperImpl.class,
SepaMandateDTO.JsonSerializer.class,
SepaMandateDTO.JsonDeserializer.class
})
@RunWith(SpringRunner.class)
public class SepaMandateDTOIntTest {
private static final Long SOME_CUSTOMER_ID = RandomUtils.nextLong(100, 199);
private static final Integer SOME_CUSTOMER_REFERENCE = 10001;
private static final String SOME_CUSTOMER_PREFIX = "abc";
private static final String SOME_CUSTOMER_NAME = "Some Customer Name";
private static final String SOME_CUSTOMER_DISPLAY_LABEL = "Some Customer Name [10001:abc]";
private static final Customer SOME_CUSTOMER = new Customer().id(SOME_CUSTOMER_ID)
.reference(SOME_CUSTOMER_REFERENCE)
.prefix(SOME_CUSTOMER_PREFIX)
.name(SOME_CUSTOMER_NAME);
private static final Long SOME_SEPA_MANDATE_ID = RandomUtils.nextLong(300, 399);
private static final SepaMandate SOME_SEPA_MANDATE = new SepaMandate().id(SOME_SEPA_MANDATE_ID).customer(SOME_CUSTOMER);
@Rule
public MockitoRule mockito = MockitoJUnit.rule();
@Autowired
private ObjectMapper objectMapper;
@Autowired
private SepaMandateMapper sepaMandateMapper;
@MockBean
private SepaMandateRepository sepaMandateRepository;
@MockBean
private CustomerRepository customerRepository;
@MockBean
private MembershipRepository membershipRepository;
@MockBean
private MembershipValidator membershipValidator;
@MockBean
private SepaMandateService sepaMandateService;
@MockBean
private EntityManager em;
@MockBean
public UserRoleAssignmentService userRoleAssignmentService;
private SecurityContextMock securityContext;
@Before
public void init() {
given(customerRepository.findById(SOME_CUSTOMER_ID)).willReturn(Optional.of(SOME_CUSTOMER));
given(sepaMandateRepository.findById(SOME_SEPA_MANDATE_ID)).willReturn((Optional.of(SOME_SEPA_MANDATE)));
securityContext = SecurityContextMock.usingMock(userRoleAssignmentService);
}
@Test
public void shouldSerializePartiallyForFinancialCustomerContact() throws JsonProcessingException {
// given
securityContext.havingAuthenticatedUser()
.withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.of(CustomerFinancialContact.class));
final SepaMandateDTO given = createSampleDTO(SOME_SEPA_MANDATE_ID, SOME_CUSTOMER_ID);
// when
final String actual = objectMapper.writeValueAsString(given);
// then
given.setRemark(null);
assertEquals(createExpectedJSon(given), actual);
}
@Test
public void shouldSerializeCompletelyForSupporter() throws JsonProcessingException {
// given
securityContext.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.SUPPORTER);
final SepaMandateDTO given = createSampleDTO(SOME_SEPA_MANDATE_ID, SOME_CUSTOMER_ID);
// when
final String actual = objectMapper.writeValueAsString(given);
// then
assertEquals(createExpectedJSon(given), actual);
}
@Test
public void shouldNotDeserializeForContractualCustomerContact() {
// given
securityContext.havingAuthenticatedUser()
.withRole(CustomerDTO.class, SOME_CUSTOMER_ID, CustomerContractualContact.ROLE);
final String json = new JSonBuilder()
.withFieldValue("id", SOME_SEPA_MANDATE_ID)
.withFieldValue("remark", "Updated Remark")
.toString();
// when
final Throwable actual = catchThrowable(() -> objectMapper.readValue(json, SepaMandateDTO.class));
// then
assertThat(actual).isInstanceOfSatisfying(
BadRequestAlertException.class,
bre -> assertThat(bre.getMessage()).isEqualTo(
"Update of field SepaMandateDTO.remark prohibited for current user role(s): CustomerContractualContact"));
}
@Test
public void shouldDeserializeForAdminIfRemarkIsChanged() throws IOException {
// given
securityContext.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.ADMIN);
final String json = new JSonBuilder()
.withFieldValue("id", SOME_SEPA_MANDATE_ID)
.withFieldValue("remark", "Updated Remark")
.toString();
// when
final SepaMandateDTO actual = objectMapper.readValue(json, SepaMandateDTO.class);
// then
final SepaMandateDTO expected = new SepaMandateDTO();
expected.setId(SOME_SEPA_MANDATE_ID);
expected.setCustomerId(SOME_CUSTOMER_ID);
expected.setRemark("Updated Remark");
expected.setCustomerDisplayLabel(SOME_CUSTOMER_DISPLAY_LABEL);
assertThat(actual).isEqualToIgnoringGivenFields(expected, "displayLabel");
}
// --- only test fixture below ---
private String createExpectedJSon(SepaMandateDTO dto) {
return new JSonBuilder()
.withFieldValueIfPresent("id", dto.getId())
.withFieldValueIfPresent("reference", dto.getReference())
.withFieldValueIfPresent("iban", dto.getIban())
.withFieldValueIfPresent("bic", dto.getBic())
.withFieldValueIfPresent("grantingDocumentDate", Objects.toString(dto.getGrantingDocumentDate()))
.withFieldValueIfPresent("revokationDocumentDate", Objects.toString(dto.getRevokationDocumentDate()))
.withFieldValueIfPresent("validFromDate", Objects.toString(dto.getValidFromDate()))
.withFieldValueIfPresent("validUntilDate", Objects.toString(dto.getValidUntilDate()))
.withFieldValueIfPresent("lastUsedDate", Objects.toString(dto.getLastUsedDate()))
.withFieldValueIfPresent("remark", dto.getRemark())
.withFieldValueIfPresent("customerId", dto.getCustomerId())
.withFieldValue("customerDisplayLabel", dto.getCustomerDisplayLabel())
.toString();
}
}

View File

@@ -1,137 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.Admin;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerTechnicalContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.Supporter;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Test;
import java.time.LocalDate;
public class SepaMandateDTOUnitTest extends AccessMappingsUnitTestBase<SepaMandateDTO> {
public SepaMandateDTOUnitTest() {
super(SepaMandateDTO.class, SepaMandateDTOUnitTest::createSampleDTO, SepaMandateDTOUnitTest::createRandomDTO);
}
@Test
public void shouldHaveProperAccessForAdmin() {
initAccessFor(SepaMandateDTO.class, Role.of(Admin.class)).shouldBeExactlyFor(
"grantingDocumentDate",
"bic",
"remark",
"validUntilDate",
"customerId",
"validFromDate",
"iban",
"revokationDocumentDate",
"lastUsedDate",
"reference");
updateAccessFor(SepaMandateDTO.class, Role.of(Admin.class)).shouldBeExactlyFor(
"remark",
"validUntilDate",
"revokationDocumentDate",
"lastUsedDate");
readAccessFor(SepaMandateDTO.class, Role.of(Admin.class)).shouldBeForAllFields();
}
@Test
public void shouldHaveProperAccessForSupporter() {
initAccessFor(SepaMandateDTO.class, Role.of(Supporter.class)).shouldBeExactlyFor(
"grantingDocumentDate",
"bic",
"validUntilDate",
"customerId",
"validFromDate",
"iban",
"reference");
updateAccessFor(SepaMandateDTO.class, Role.of(Supporter.class)).shouldBeExactlyFor(
"remark",
"validUntilDate",
"revokationDocumentDate");
readAccessFor(SepaMandateDTO.class, Role.of(Supporter.class)).shouldBeForAllFields();
}
@Test
public void shouldHaveProperAccessForContractualContact() {
initAccessFor(SepaMandateDTO.class, Role.of(CustomerContractualContact.class)).shouldBeExactlyFor(
"grantingDocumentDate",
"bic",
"validUntilDate",
"customerId",
"validFromDate",
"iban",
"reference");
updateAccessFor(SepaMandateDTO.class, Role.of(CustomerContractualContact.class)).shouldBeExactlyFor(
"validUntilDate",
"revokationDocumentDate");
readAccessFor(SepaMandateDTO.class, Role.of(CustomerContractualContact.class)).shouldBeExactlyFor(
"grantingDocumentDate",
"bic",
"id",
"validUntilDate",
"customerId",
"validFromDate",
"iban",
"revokationDocumentDate",
"customerDisplayLabel",
"lastUsedDate",
"reference");
}
@Test
public void shouldHaveNoAccessForTechnicalContact() {
initAccessFor(SepaMandateDTO.class, Role.of(CustomerTechnicalContact.class)).shouldBeForNothing();
updateAccessFor(SepaMandateDTO.class, Role.of(CustomerTechnicalContact.class)).shouldBeForNothing();
readAccessFor(SepaMandateDTO.class, Role.of(CustomerTechnicalContact.class)).shouldBeForNothing();
}
@Test
public void shouldHaveNoAccessForNormalUsersWithinCustomerRealm() {
initAccessFor(SepaMandateDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
updateAccessFor(SepaMandateDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
readAccessFor(SepaMandateDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
}
// --- only test fixture below ---
public static SepaMandateDTO createSampleDTO(final Long id, final Long parentId) {
final SepaMandateDTO dto = new SepaMandateDTO();
dto.setId(id);
dto.setReference("Some Reference");
dto.setGrantingDocumentDate(LocalDate.parse("2000-12-07"));
dto.setRevokationDocumentDate(LocalDate.parse("2019-04-27"));
dto.setValidFromDate(LocalDate.parse("2000-12-18"));
dto.setValidUntilDate(LocalDate.parse("2019-05-31"));
dto.setLastUsedDate(LocalDate.parse("2019-04-04"));
dto.setIban("DE1234IBAN");
dto.setBic("BIC1234");
dto.setRemark("Some Remark");
dto.setCustomerId(parentId);
dto.setCustomerDisplayLabel("abc");
return dto;
}
public static SepaMandateDTO createRandomDTO(final Long id, final Long parentId) {
final SepaMandateDTO dto = new SepaMandateDTO();
dto.setId(id);
dto.setReference(RandomStringUtils.randomAlphanumeric(10));
final LocalDate randomDate = LocalDate.parse("2000-12-07").plusDays(RandomUtils.nextInt(1, 999));
dto.setGrantingDocumentDate(randomDate);
dto.setRevokationDocumentDate(randomDate.plusDays(RandomUtils.nextInt(1100, 2999)));
dto.setValidFromDate(randomDate.plusDays(RandomUtils.nextInt(0, 7)));
dto.setValidUntilDate(dto.getRevokationDocumentDate().plusDays(7));
dto.setLastUsedDate(dto.getRevokationDocumentDate().minusDays(20));
dto.setIban(RandomStringUtils.randomAlphanumeric(20).toUpperCase());
dto.setBic(RandomStringUtils.randomAlphanumeric(10).toUpperCase());
dto.setRemark(RandomStringUtils.randomAlphanumeric(20).toUpperCase());
dto.setCustomerId(parentId);
dto.setCustomerDisplayLabel(RandomStringUtils.randomAlphabetic(3).toLowerCase());
return dto;
}
}

View File

@@ -1,227 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.domain.Customer;
import org.hostsharing.hsadminng.domain.Membership;
import org.hostsharing.hsadminng.domain.Share;
import org.hostsharing.hsadminng.domain.enumeration.ShareAction;
import org.hostsharing.hsadminng.repository.CustomerRepository;
import org.hostsharing.hsadminng.repository.MembershipRepository;
import org.hostsharing.hsadminng.repository.ShareRepository;
import org.hostsharing.hsadminng.service.MembershipValidator;
import org.hostsharing.hsadminng.service.ShareService;
import org.hostsharing.hsadminng.service.ShareValidator;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerFinancialContact;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock;
import org.hostsharing.hsadminng.service.mapper.CustomerMapperImpl;
import org.hostsharing.hsadminng.service.mapper.MembershipMapperImpl;
import org.hostsharing.hsadminng.service.mapper.ShareMapper;
import org.hostsharing.hsadminng.service.mapper.ShareMapperImpl;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Optional;
import javax.persistence.EntityManager;
@JsonTest
@SpringBootTest(
classes = {
CustomerMapperImpl.class,
MembershipMapperImpl.class,
ShareMapperImpl.class,
ShareDTO.JsonSerializer.class,
ShareDTO.JsonDeserializer.class
})
@RunWith(SpringRunner.class)
public class ShareDTOIntTest {
private static final Long SOME_CUSTOMER_ID = RandomUtils.nextLong(100, 199);
private static final Integer SOME_CUSTOMER_REFERENCE = 10001;
private static final String SOME_CUSTOMER_PREFIX = "abc";
private static final String SOME_CUSTOMER_NAME = "Some Customer Name";
private static final Customer SOME_CUSTOMER = new Customer().id(SOME_CUSTOMER_ID)
.reference(SOME_CUSTOMER_REFERENCE)
.prefix(SOME_CUSTOMER_PREFIX)
.name(SOME_CUSTOMER_NAME);
private static final Long SOME_MEMBERSHIP_ID = RandomUtils.nextLong(200, 299);
private static final LocalDate SOME_MEMBER_FROM_DATE = LocalDate.parse("2000-12-06");
private static final Membership SOME_MEMBERSHIP = new Membership().id(SOME_MEMBERSHIP_ID)
.customer(SOME_CUSTOMER)
.memberFromDate(SOME_MEMBER_FROM_DATE);
private static final String SOME_MEMBERSHIP_DISPLAY_LABEL = "Some Customer Name [10001:abc] 2000-12-06 - ...";
private static final Long SOME_SHARE_ID = RandomUtils.nextLong(300, 399);
private static final Share SOME_SHARE = new Share().id(SOME_SHARE_ID).membership(SOME_MEMBERSHIP);
@Rule
public MockitoRule mockito = MockitoJUnit.rule();
@Autowired
private ObjectMapper objectMapper;
@Autowired
private ShareMapper shareMapper;
@MockBean
private ShareRepository shareRepository;
@MockBean
private ShareValidator shareValidator;
@MockBean
private CustomerRepository customerRepository;
@MockBean
private MembershipRepository membershipRepository;
@MockBean
private MembershipValidator membershipValidator;
@MockBean
private ShareService shareService;
@MockBean
private EntityManager em;
@MockBean
private UserRoleAssignmentService userRoleAssignmentService;
private SecurityContextMock securityContext;
@Before
public void init() {
given(customerRepository.findById(SOME_CUSTOMER_ID)).willReturn(Optional.of(SOME_CUSTOMER));
given(membershipRepository.findById(SOME_MEMBERSHIP_ID)).willReturn(Optional.of(SOME_MEMBERSHIP));
given(shareRepository.findById(SOME_SHARE_ID)).willReturn((Optional.of(SOME_SHARE)));
securityContext = SecurityContextMock.usingMock(userRoleAssignmentService);
}
@Test
public void shouldSerializePartiallyForFinancialCustomerContact() throws JsonProcessingException {
// given
securityContext.havingAuthenticatedUser()
.withRole(CustomerDTO.class, SOME_CUSTOMER_ID, CustomerFinancialContact.ROLE);
final ShareDTO given = createSomeShareDTO(SOME_SHARE_ID);
// when
final String actual = objectMapper.writeValueAsString(given);
// then
given.setRemark(null);
assertEquals(createExpectedJSon(given), actual);
}
@Test
public void shouldSerializeCompletelyForSupporter() throws JsonProcessingException {
// given
securityContext.havingAuthenticatedUser().withAuthority(Role.Supporter.ROLE.authority());
final ShareDTO given = createSomeShareDTO(SOME_SHARE_ID);
// when
final String actual = objectMapper.writeValueAsString(given);
// then
assertEquals(createExpectedJSon(given), actual);
}
@Test
public void shouldNotDeserializeForContractualCustomerContact() {
// given
securityContext.havingAuthenticatedUser()
.withRole(CustomerDTO.class, SOME_CUSTOMER_ID, CustomerContractualContact.ROLE);
final String json = new JSonBuilder()
.withFieldValue("id", SOME_SHARE_ID)
.withFieldValue("remark", "Updated Remark")
.toString();
// when
final Throwable actual = catchThrowable(() -> objectMapper.readValue(json, ShareDTO.class));
// then
assertThat(actual).isInstanceOfSatisfying(
BadRequestAlertException.class,
bre -> assertThat(bre.getMessage())
.isEqualTo(
"Update of field ShareDTO.remark prohibited for current user role(s): CustomerContractualContact"));
}
@Test
public void shouldDeserializeForAdminIfRemarkIsChanged() throws IOException {
// given
securityContext.havingAuthenticatedUser().withAuthority(Role.Admin.ROLE.authority());
final String json = new JSonBuilder()
.withFieldValue("id", SOME_SHARE_ID)
.withFieldValue("remark", "Updated Remark")
.toString();
// when
final ShareDTO actual = objectMapper.readValue(json, ShareDTO.class);
// then
final ShareDTO expected = new ShareDTO();
expected.setId(SOME_SHARE_ID);
expected.setMembershipId(SOME_MEMBERSHIP_ID);
expected.setRemark("Updated Remark");
expected.setMembershipDisplayLabel(SOME_MEMBERSHIP_DISPLAY_LABEL);
assertThat(actual).isEqualToIgnoringGivenFields(expected, "displayLabel");
}
// --- only test fixture below ---
private String createExpectedJSon(ShareDTO dto) {
return new JSonBuilder()
.withFieldValueIfPresent("id", dto.getId())
.withFieldValueIfPresent("documentDate", dto.getDocumentDate().toString())
.withFieldValueIfPresent("valueDate", dto.getValueDate().toString())
.withFieldValueIfPresent("action", dto.getAction().name())
.withFieldValueIfPresent("quantity", dto.getQuantity())
.withFieldValueIfPresent("remark", dto.getRemark())
.withFieldValueIfPresent("membershipId", dto.getMembershipId())
.withFieldValue("membershipDisplayLabel", dto.getMembershipDisplayLabel())
.toString();
}
private ShareDTO createSomeShareDTO(final long id) {
final ShareDTO given = new ShareDTO();
given.setId(id);
given.setAction(ShareAction.SUBSCRIPTION);
given.setQuantity(16);
given.setDocumentDate(LocalDate.parse("2019-04-27"));
given.setValueDate(LocalDate.parse("2019-04-28"));
given.setMembershipId(SOME_MEMBERSHIP_ID);
given.setRemark("Some Remark");
given.setMembershipDisplayLabel("Display Label for Membership #" + SOME_MEMBERSHIP_ID);
return given;
}
}

View File

@@ -1,92 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import org.hostsharing.hsadminng.domain.enumeration.ShareAction;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.Admin;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerTechnicalContact;
import org.hostsharing.hsadminng.service.util.RandomUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Test;
import java.time.LocalDate;
public class ShareDTOUnitTest extends AccessMappingsUnitTestBase<ShareDTO> {
public ShareDTOUnitTest() {
super(ShareDTO.class, ShareDTOUnitTest::createSampleDTO, ShareDTOUnitTest::createRandomDTO);
}
@Test
public void shouldHaveProperAccessForAdmin() {
initAccessFor(ShareDTO.class, Admin.ROLE).shouldBeExactlyFor(
"membershipId",
"documentDate",
"quantity",
"action",
"valueDate",
"remark");
updateAccessFor(ShareDTO.class, Admin.ROLE).shouldBeExactlyFor("remark");
readAccessFor(ShareDTO.class, Admin.ROLE).shouldBeForAllFields();
}
@Test
public void shouldHaveProperAccessForContractualContact() {
initAccessFor(ShareDTO.class, CustomerContractualContact.ROLE).shouldBeForNothing();
updateAccessFor(ShareDTO.class, CustomerContractualContact.ROLE).shouldBeForNothing();
readAccessFor(ShareDTO.class, CustomerContractualContact.ROLE).shouldBeExactlyFor(
"id",
"membershipId",
"documentDate",
"quantity",
"action",
"valueDate",
"membershipDisplayLabel");
}
@Test
public void shouldHaveNoAccessForTechnicalContact() {
initAccessFor(ShareDTO.class, CustomerTechnicalContact.ROLE).shouldBeForNothing();
updateAccessFor(ShareDTO.class, CustomerTechnicalContact.ROLE).shouldBeForNothing();
readAccessFor(ShareDTO.class, CustomerTechnicalContact.ROLE).shouldBeForNothing();
}
@Test
public void shouldHaveNoAccessForNormalUsersWithinCustomerRealm() {
initAccessFor(ShareDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
updateAccessFor(ShareDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
readAccessFor(ShareDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
}
// --- only test fixture below ---
private static ShareDTO createSampleDTO(final Long id, final Long parentId) {
final ShareDTO dto = new ShareDTO();
dto.setId(id);
dto.setMembershipId(parentId);
dto.setAction(ShareAction.SUBSCRIPTION);
dto.setQuantity(3);
dto.setDocumentDate(LocalDate.parse("2019-04-22"));
dto.setValueDate(LocalDate.parse("2019-04-30"));
dto.setRemark("Some Remark");
dto.setMembershipDisplayLabel("The Membership #888");
return dto;
}
private static ShareDTO createRandomDTO(final Long id, final Long parentId) {
final ShareDTO dto = new ShareDTO();
dto.setId(id);
dto.setMembershipId(parentId);
dto.setAction(RandomUtil.generateEnumValue(ShareAction.class));
dto.setQuantity(RandomUtils.nextInt());
final LocalDate randomDate = LocalDate.parse("2000-12-07").plusDays(RandomUtils.nextInt(1, 999));
dto.setDocumentDate(randomDate);
dto.setValueDate(randomDate.plusDays(RandomUtils.nextInt(1, 99)));
dto.setRemark(RandomStringUtils.randomAlphanumeric(20));
dto.setMembershipDisplayLabel("The Membership #" + dto.getMembershipId());
return dto;
}
}

View File

@@ -1,163 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import static org.apache.commons.lang3.tuple.ImmutablePair.of;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.domain.Customer;
import org.hostsharing.hsadminng.domain.User;
import org.hostsharing.hsadminng.domain.UserRoleAssignment;
import org.hostsharing.hsadminng.repository.UserRepository;
import org.hostsharing.hsadminng.repository.UserRoleAssignmentRepository;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.util.Optional;
@JsonTest
@SpringBootTest(
classes = {
UserRoleAssignmentRepository.class,
UserRoleAssignmentService.class,
UserRoleAssignment.UserRoleAssignmentJsonSerializer.class,
UserRoleAssignment.UserRoleAssignmentJsonDeserializer.class })
@RunWith(SpringRunner.class)
public class UserRoleAssignmentUnitTest {
private static final long USER_ROLE_ASSIGNMENT_ID = 1234L;
private static final long CUSTOMER_ID = 888L;
private static final long USER_ID = 42L;
@Rule
public MockitoRule mockito = MockitoJUnit.rule();
@Autowired
private ObjectMapper objectMapper;
@MockBean
private UserRepository userRepository;
@MockBean
private UserRoleAssignmentRepository userRoleAssignmentRepository;
@MockBean
private UserRoleAssignmentService userRoleAssignmentService;
private SecurityContextMock securityContext;
@Before
public void init() {
securityContext = SecurityContextMock.usingMock(userRoleAssignmentService);
}
@Test
public void testSerializationAsContractualCustomerContact() throws JsonProcessingException {
// given
securityContext.havingAuthenticatedUser()
.withRole(
CustomerDTO.class,
CUSTOMER_ID,
Role.CustomerContractualContact.ROLE);
UserRoleAssignment given = createSomeUserRoleAssignment(USER_ROLE_ASSIGNMENT_ID);
// when
String actual = objectMapper.writeValueAsString(given);
// then
assertEquals("{}", actual); // dependent rights not yet implemented for UserRoleAssignments
}
@Test
public void testSerializationAsSupporter() throws JsonProcessingException {
// given
securityContext.havingAuthenticatedUser().withAuthority(Role.Supporter.ROLE.authority());
UserRoleAssignment given = createSomeUserRoleAssignment(USER_ROLE_ASSIGNMENT_ID);
// when
String actual = objectMapper.writeValueAsString(given);
// then
assertThat(actual).isEqualTo(createExpectedJSon(given));
}
@Test
public void testDeserializeAsAdmin() throws IOException {
// given
securityContext.havingAuthenticatedUser().withAuthority(Role.Admin.ROLE.authority());
given(userRoleAssignmentRepository.findById(USER_ROLE_ASSIGNMENT_ID))
.willReturn(Optional.of(new UserRoleAssignment().id(USER_ROLE_ASSIGNMENT_ID)));
final User expectedUser = new User().id(USER_ID);
given(userRepository.getOne(USER_ID)).willReturn(expectedUser);
String json = JSonBuilder.asJSon(
of("id", USER_ROLE_ASSIGNMENT_ID),
of("entityTypeId", Customer.ENTITY_TYPE_ID),
of("entityObjectId", CUSTOMER_ID),
of(
"user",
JSonBuilder.asJSon(
of("id", USER_ID))),
of("assignedRole", Role.CustomerTechnicalContact.ROLE.name()));
// when
UserRoleAssignment actual = objectMapper.readValue(json, UserRoleAssignment.class);
// then
UserRoleAssignment expected = new UserRoleAssignment();
expected.setId(USER_ROLE_ASSIGNMENT_ID);
expected.setEntityTypeId(Customer.ENTITY_TYPE_ID);
expected.setEntityObjectId(CUSTOMER_ID);
expected.setAssignedRole(Role.CustomerTechnicalContact.ROLE);
expected.setUser(expectedUser);
assertThat(actual).isEqualToComparingFieldByField(expected);
}
@Test
public void getAssignedRoleHandlesNullValue() {
assertThat(new UserRoleAssignment().assignedRole(null).getAssignedRole()).isNull();
assertThat(new UserRoleAssignment().assignedRole(Role.Admin.ROLE).getAssignedRole()).isEqualTo(Role.Admin.ROLE);
}
// --- only test fixture below ---
public static String createExpectedJSon(UserRoleAssignment dto) {
return new JSonBuilder()
.withFieldValueIfPresent("id", dto.getId())
.withFieldValueIfPresent("entityTypeId", dto.getEntityTypeId())
.withFieldValueIfPresent("entityObjectId", dto.getEntityObjectId())
.withFieldValueIfPresent("assignedRole", dto.getAssignedRole())
.withFieldValueIfPresent("user", dto.getUser().getId())
.toString();
}
public static UserRoleAssignment createSomeUserRoleAssignment(final Long id) {
final UserRoleAssignment given = new UserRoleAssignment();
given.setId(id);
given.setEntityTypeId(Customer.ENTITY_TYPE_ID);
given.setEntityObjectId(CUSTOMER_ID);
given.setUser(new User().id(USER_ID));
given.setAssignedRole(Role.CustomerTechnicalContact.ROLE);
return given;
}
}

View File

@@ -1,151 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.mapper;
import static org.assertj.core.api.Assertions.assertThat;
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;
/**
* 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

@@ -1,147 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.util;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.ThrowableAssert.catchThrowable;
import static org.hostsharing.hsadminng.service.util.ReflectionUtil.unchecked;
import org.junit.Test;
public class ReflectionUtilUnitTest {
@Test
public void getUknownFieldThrowsIllegalArgumentException() {
final Throwable actual = catchThrowable(() -> ReflectionUtil.getField(SomeClass.class, "unknownField"));
assertThat(actual).isInstanceOf(IllegalArgumentException.class)
.hasMessage("java.lang.NoSuchFieldException: unknownField");
}
@Test
public void setValue() {
final TestDto dto = new TestDto(5);
ReflectionUtil.setValue(dto, ReflectionUtil.getField(dto.getClass(), "intVal"), 77);
assertThat(dto.intVal).isEqualTo(77);
}
@Test
public void setValueViaSuperclass() {
final SubTestDto dto = new SubTestDto(5);
ReflectionUtil.setValue(dto, ReflectionUtil.getField(dto.getClass(), "intVal"), 77);
assertThat(dto.intVal).isEqualTo(77);
}
@Test
public void getValue() {
final TestDto dto = new TestDto(5);
final int actual = ReflectionUtil.getValue(dto, ReflectionUtil.getField(dto.getClass(), "intVal"));
assertThat(actual).isEqualTo(5);
}
@Test
public void getValueViaSuperclass() {
final SubTestDto dto = new SubTestDto(5);
final int actual = ReflectionUtil.getValue(dto, ReflectionUtil.getField(dto.getClass(), "intVal"));
assertThat(actual).isEqualTo(5);
}
@Test
public void determineGenericInterfaceParameteDirect() {
Class<?> actual = ReflectionUtil.determineGenericInterfaceParameter(SuperClass.class, GenericInterface.class, 1);
assertThat(actual).isEqualTo(Long.class);
}
@Test
public void determineGenericInterfaceParameterViaSuperclass() {
Class<?> actual = ReflectionUtil.determineGenericInterfaceParameter(SomeClass.class, GenericInterface.class, 1);
assertThat(actual).isEqualTo(Long.class);
}
@Test
public void throwsExceptionIfGenericInterfaceNotImplemented() {
final Throwable actual = catchThrowable(
() -> ReflectionUtil.determineGenericInterfaceParameter(SomeClass.class, UnusedGenericInterface.class, 1));
assertThat(actual).isInstanceOf(AssertionError.class)
.hasMessageContaining("SomeClass expected to implement UnusedGenericInterface<...>");
}
@Test
public void determineGenericClassParameterDirect() {
Class<?> actual = ReflectionUtil.determineGenericClassParameter(SuperClass.class, GenericClass.class, 1);
assertThat(actual).isEqualTo(Boolean.class);
}
@Test
public void determineGenericClassParameterViaSuperclss() {
Class<?> actual = ReflectionUtil.determineGenericClassParameter(SomeClass.class, GenericClass.class, 1);
assertThat(actual).isEqualTo(Boolean.class);
}
@Test
public void throwsExceptionIfGenericClassNotExended() {
final Throwable actual = catchThrowable(
() -> ReflectionUtil.determineGenericClassParameter(SomeClass.class, UnusedSuperClass.class, 1));
assertThat(actual).isInstanceOf(AssertionError.class)
.hasMessageContaining("GenericClass expected to extend UnusedSuperClass<...>");
}
@Test
public void uncheckedRethrowsCheckedException() {
final Exception givenException = new Exception("Checked Test Exception");
final Throwable actual = catchThrowable(() -> unchecked(() -> {
throw givenException;
}));
assertThat(actual)
.isInstanceOfSatisfying(RuntimeException.class, rte -> assertThat(rte.getCause()).isSameAs(givenException));
}
@Test
public void asEnumValue() {
assertThat(ReflectionUtil.asEnumValue(SomeEnum.class, "GREEN")).isEqualTo(SomeEnum.GREEN);
}
// --- only test fixture below ---
private static class TestDto {
int intVal;
TestDto(final int intval) {
this.intVal = intval;
}
}
private static class SubTestDto extends TestDto {
SubTestDto(final int intval) {
super(intval);
}
}
private static class SomeClass extends SuperClass {
}
private static class SuperClass extends GenericClass<String, Boolean> implements IntermediateInterfaces<Integer, Long> {
}
private static class UnusedSuperClass extends GenericClass<String, Boolean>
implements IntermediateInterfaces<Integer, Long> {
}
private static class GenericClass<T, V> {
}
private interface IntermediateInterfaces<T, V> extends GenericInterface<Integer, Long> {
}
private interface GenericInterface<T, V> {
}
private interface UnusedGenericInterface<T, V> {
}
enum SomeEnum {
RED,
BLUE,
GREEN
}
}

View File

@@ -1,829 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.web.rest;
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.*;
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.*;
/**
* 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

@@ -1,777 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.web.rest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.hostsharing.hsadminng.HsadminNgApp;
import org.hostsharing.hsadminng.domain.Asset;
import org.hostsharing.hsadminng.domain.Membership;
import org.hostsharing.hsadminng.domain.enumeration.AssetAction;
import org.hostsharing.hsadminng.repository.AssetRepository;
import org.hostsharing.hsadminng.service.AssetQueryService;
import org.hostsharing.hsadminng.service.AssetService;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock;
import org.hostsharing.hsadminng.service.dto.AssetDTO;
import org.hostsharing.hsadminng.service.mapper.AssetMapper;
import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator;
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.boot.test.mock.mockito.MockBean;
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 org.springframework.validation.Validator;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
import javax.persistence.EntityManager;
/**
* Test class for the AssetResource REST controller.
*
* @see AssetResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HsadminNgApp.class)
public class AssetResourceIntTest {
private static final LocalDate DEFAULT_DOCUMENT_DATE = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_DOCUMENT_DATE = LocalDate.now(ZoneId.systemDefault());
private static final LocalDate DEFAULT_VALUE_DATE = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_VALUE_DATE = LocalDate.now(ZoneId.systemDefault());
private static final AssetAction DEFAULT_ACTION = AssetAction.PAYMENT;
private static final AssetAction UPDATED_ACTION = AssetAction.HANDOVER;
private static final BigDecimal DEFAULT_AMOUNT = new BigDecimal("1");
private static final BigDecimal UPDATED_AMOUNT = new BigDecimal("2");
private static final String DEFAULT_REMARK = "AAAAAAAAAA";
private static final String UPDATED_REMARK = "BBBBBBBBBB";
@Autowired
private AssetRepository assetRepository;
@Autowired
private AssetMapper assetMapper;
@Autowired
private AssetService assetService;
@Autowired
private AssetQueryService assetQueryService;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
@Autowired
private Validator validator;
@MockBean
private UserRoleAssignmentService userRoleAssignmentService;
private MockMvc restAssetMockMvc;
private Asset asset;
@Before
public void setup() {
SecurityContextMock.usingMock(userRoleAssignmentService)
.havingAuthenticatedUser()
.withAuthority(Role.Admin.ROLE.authority());
MockitoAnnotations.initMocks(this);
final AssetResource assetResource = new AssetResource(assetService, assetQueryService);
this.restAssetMockMvc = MockMvcBuilders.standaloneSetup(assetResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator)
.build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Asset createEntity(EntityManager em) {
Asset asset = new Asset()
.documentDate(DEFAULT_DOCUMENT_DATE)
.valueDate(DEFAULT_VALUE_DATE)
.action(DEFAULT_ACTION)
.amount(DEFAULT_AMOUNT)
.remark(DEFAULT_REMARK);
// Add required entity
Membership membership = MembershipResourceIntTest.createEntity(em);
em.persist(membership);
em.flush();
asset.setMembership(membership);
return asset;
}
/**
* Create a persistent entity related to the given persistent membership for testing purposes.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Asset createPersistentEntity(EntityManager em, final Membership membership) {
Asset asset = new Asset()
.documentDate(DEFAULT_DOCUMENT_DATE)
.valueDate(DEFAULT_VALUE_DATE)
.action(DEFAULT_ACTION)
.amount(DEFAULT_AMOUNT)
.remark(DEFAULT_REMARK);
// Add required entity
asset.setMembership(membership);
membership.addAsset(asset);
em.persist(asset);
em.flush();
return asset;
}
@Before
public void initTest() {
asset = createEntity(em);
}
@Test
@Transactional
public void createAsset() throws Exception {
int databaseSizeBeforeCreate = assetRepository.findAll().size();
// Create the Asset
AssetDTO assetDTO = assetMapper.toDto(asset);
assetDTO.setMembershipDisplayLabel(null);
restAssetMockMvc.perform(
post("/api/assets")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(assetDTO)))
.andExpect(status().isCreated());
// Validate the Asset in the database
List<Asset> assetList = assetRepository.findAll();
assertThat(assetList).hasSize(databaseSizeBeforeCreate + 1);
Asset testAsset = assetList.get(assetList.size() - 1);
assertThat(testAsset.getDocumentDate()).isEqualTo(DEFAULT_DOCUMENT_DATE);
assertThat(testAsset.getValueDate()).isEqualTo(DEFAULT_VALUE_DATE);
assertThat(testAsset.getAction()).isEqualTo(DEFAULT_ACTION);
assertThat(testAsset.getAmount()).isEqualTo(DEFAULT_AMOUNT.setScale(2, RoundingMode.HALF_DOWN));
assertThat(testAsset.getRemark()).isEqualTo(DEFAULT_REMARK);
}
@Test
@Transactional
public void createAssetWithIdForNonExistingEntity() throws Exception {
int databaseSizeBeforeCreate = assetRepository.findAll().size();
// Create the Asset with an ID
asset.setId(1L);
AssetDTO assetDTO = assetMapper.toDto(asset);
// An entity with an existing ID cannot be created, so this API call must fail
restAssetMockMvc.perform(
post("/api/assets")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(assetDTO)))
.andExpect(status().isBadRequest());
// Validate the Asset in the database
List<Asset> assetList = assetRepository.findAll();
assertThat(assetList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void createAssetWithExistingExistingEntity() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
int databaseSizeBeforeCreate = assetRepository.findAll().size();
// Create the Asset with the ID of an existing ID
AssetDTO assetDTO = assetMapper.toDto(asset);
// An entity with an existing ID cannot be created, so this API call must fail
restAssetMockMvc.perform(
post("/api/assets")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(assetDTO)))
.andExpect(status().isBadRequest());
// Validate the Asset in the database
List<Asset> assetList = assetRepository.findAll();
assertThat(assetList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void checkDocumentDateIsRequired() throws Exception {
int databaseSizeBeforeTest = assetRepository.findAll().size();
// set the field null
asset.setDocumentDate(null);
// Create the Asset, which fails.
AssetDTO assetDTO = assetMapper.toDto(asset);
restAssetMockMvc.perform(
post("/api/assets")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(assetDTO)))
.andExpect(status().isBadRequest());
List<Asset> assetList = assetRepository.findAll();
assertThat(assetList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkValueDateIsRequired() throws Exception {
int databaseSizeBeforeTest = assetRepository.findAll().size();
// set the field null
asset.setValueDate(null);
// Create the Asset, which fails.
AssetDTO assetDTO = assetMapper.toDto(asset);
restAssetMockMvc.perform(
post("/api/assets")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(assetDTO)))
.andExpect(status().isBadRequest());
List<Asset> assetList = assetRepository.findAll();
assertThat(assetList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkActionIsRequired() throws Exception {
int databaseSizeBeforeTest = assetRepository.findAll().size();
// set the field null
asset.setAction(null);
// Create the Asset, which fails.
AssetDTO assetDTO = assetMapper.toDto(asset);
restAssetMockMvc.perform(
post("/api/assets")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(assetDTO)))
.andExpect(status().isBadRequest());
List<Asset> assetList = assetRepository.findAll();
assertThat(assetList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkAmountIsRequired() throws Exception {
int databaseSizeBeforeTest = assetRepository.findAll().size();
// set the field null
asset.setAmount(null);
// Create the Asset, which fails.
AssetDTO assetDTO = assetMapper.toDto(asset);
restAssetMockMvc.perform(
post("/api/assets")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(assetDTO)))
.andExpect(status().isBadRequest());
List<Asset> assetList = assetRepository.findAll();
assertThat(assetList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void getAllAssets() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList
restAssetMockMvc.perform(get("/api/assets?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(asset.getId().intValue())))
.andExpect(jsonPath("$.[*].documentDate").value(hasItem(DEFAULT_DOCUMENT_DATE.toString())))
.andExpect(jsonPath("$.[*].valueDate").value(hasItem(DEFAULT_VALUE_DATE.toString())))
.andExpect(jsonPath("$.[*].action").value(hasItem(DEFAULT_ACTION.toString())))
.andExpect(jsonPath("$.[*].amount").value(hasItem(DEFAULT_AMOUNT.intValue())))
.andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK)));
}
@Test
@Transactional
public void getAsset() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get the asset
restAssetMockMvc.perform(get("/api/assets/{id}", asset.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(asset.getId().intValue()))
.andExpect(jsonPath("$.documentDate").value(DEFAULT_DOCUMENT_DATE.toString()))
.andExpect(jsonPath("$.valueDate").value(DEFAULT_VALUE_DATE.toString()))
.andExpect(jsonPath("$.action").value(DEFAULT_ACTION.toString()))
.andExpect(jsonPath("$.amount").value(DEFAULT_AMOUNT.intValue()))
.andExpect(jsonPath("$.remark").value(DEFAULT_REMARK));
}
@Test
@Transactional
public void getAllAssetsByDocumentDateIsEqualToSomething() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList where documentDate equals to DEFAULT_DOCUMENT_DATE
defaultAssetShouldBeFound("documentDate.equals=" + DEFAULT_DOCUMENT_DATE);
// Get all the assetList where documentDate equals to UPDATED_DOCUMENT_DATE
defaultAssetShouldNotBeFound("documentDate.equals=" + UPDATED_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllAssetsByDocumentDateIsInShouldWork() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList where documentDate in DEFAULT_DOCUMENT_DATE or UPDATED_DOCUMENT_DATE
defaultAssetShouldBeFound("documentDate.in=" + DEFAULT_DOCUMENT_DATE + "," + UPDATED_DOCUMENT_DATE);
// Get all the assetList where documentDate equals to UPDATED_DOCUMENT_DATE
defaultAssetShouldNotBeFound("documentDate.in=" + UPDATED_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllAssetsByDocumentDateIsNullOrNotNull() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList where documentDate is not null
defaultAssetShouldBeFound("documentDate.specified=true");
// Get all the assetList where documentDate is null
defaultAssetShouldNotBeFound("documentDate.specified=false");
}
@Test
@Transactional
public void getAllAssetsByDocumentDateIsGreaterThanOrEqualToSomething() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList where documentDate greater than or equals to DEFAULT_DOCUMENT_DATE
defaultAssetShouldBeFound("documentDate.greaterOrEqualThan=" + DEFAULT_DOCUMENT_DATE);
// Get all the assetList where documentDate greater than or equals to UPDATED_DOCUMENT_DATE
defaultAssetShouldNotBeFound("documentDate.greaterOrEqualThan=" + UPDATED_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllAssetsByDocumentDateIsLessThanSomething() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList where documentDate less than or equals to DEFAULT_DOCUMENT_DATE
defaultAssetShouldNotBeFound("documentDate.lessThan=" + DEFAULT_DOCUMENT_DATE);
// Get all the assetList where documentDate less than or equals to UPDATED_DOCUMENT_DATE
defaultAssetShouldBeFound("documentDate.lessThan=" + UPDATED_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllAssetsByValueDateIsEqualToSomething() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList where valueDate equals to DEFAULT_VALUE_DATE
defaultAssetShouldBeFound("valueDate.equals=" + DEFAULT_VALUE_DATE);
// Get all the assetList where valueDate equals to UPDATED_VALUE_DATE
defaultAssetShouldNotBeFound("valueDate.equals=" + UPDATED_VALUE_DATE);
}
@Test
@Transactional
public void getAllAssetsByValueDateIsInShouldWork() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList where valueDate in DEFAULT_VALUE_DATE or UPDATED_VALUE_DATE
defaultAssetShouldBeFound("valueDate.in=" + DEFAULT_VALUE_DATE + "," + UPDATED_VALUE_DATE);
// Get all the assetList where valueDate equals to UPDATED_VALUE_DATE
defaultAssetShouldNotBeFound("valueDate.in=" + UPDATED_VALUE_DATE);
}
@Test
@Transactional
public void getAllAssetsByValueDateIsNullOrNotNull() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList where valueDate is not null
defaultAssetShouldBeFound("valueDate.specified=true");
// Get all the assetList where valueDate is null
defaultAssetShouldNotBeFound("valueDate.specified=false");
}
@Test
@Transactional
public void getAllAssetsByValueDateIsGreaterThanOrEqualToSomething() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList where valueDate greater than or equals to DEFAULT_VALUE_DATE
defaultAssetShouldBeFound("valueDate.greaterOrEqualThan=" + DEFAULT_VALUE_DATE);
// Get all the assetList where valueDate greater than or equals to UPDATED_VALUE_DATE
defaultAssetShouldNotBeFound("valueDate.greaterOrEqualThan=" + UPDATED_VALUE_DATE);
}
@Test
@Transactional
public void getAllAssetsByValueDateIsLessThanSomething() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList where valueDate less than or equals to DEFAULT_VALUE_DATE
defaultAssetShouldNotBeFound("valueDate.lessThan=" + DEFAULT_VALUE_DATE);
// Get all the assetList where valueDate less than or equals to UPDATED_VALUE_DATE
defaultAssetShouldBeFound("valueDate.lessThan=" + UPDATED_VALUE_DATE);
}
@Test
@Transactional
public void getAllAssetsByActionIsEqualToSomething() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList where action equals to DEFAULT_ACTION
defaultAssetShouldBeFound("action.equals=" + DEFAULT_ACTION);
// Get all the assetList where action equals to UPDATED_ACTION
defaultAssetShouldNotBeFound("action.equals=" + UPDATED_ACTION);
}
@Test
@Transactional
public void getAllAssetsByActionIsInShouldWork() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList where action in DEFAULT_ACTION or UPDATED_ACTION
defaultAssetShouldBeFound("action.in=" + DEFAULT_ACTION + "," + UPDATED_ACTION);
// Get all the assetList where action equals to UPDATED_ACTION
defaultAssetShouldNotBeFound("action.in=" + UPDATED_ACTION);
}
@Test
@Transactional
public void getAllAssetsByActionIsNullOrNotNull() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList where action is not null
defaultAssetShouldBeFound("action.specified=true");
// Get all the assetList where action is null
defaultAssetShouldNotBeFound("action.specified=false");
}
@Test
@Transactional
public void getAllAssetsByAmountIsEqualToSomething() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList where amount equals to DEFAULT_AMOUNT
defaultAssetShouldBeFound("amount.equals=" + DEFAULT_AMOUNT);
// Get all the assetList where amount equals to UPDATED_AMOUNT
defaultAssetShouldNotBeFound("amount.equals=" + UPDATED_AMOUNT);
}
@Test
@Transactional
public void getAllAssetsByAmountIsInShouldWork() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList where amount in DEFAULT_AMOUNT or UPDATED_AMOUNT
defaultAssetShouldBeFound("amount.in=" + DEFAULT_AMOUNT + "," + UPDATED_AMOUNT);
// Get all the assetList where amount equals to UPDATED_AMOUNT
defaultAssetShouldNotBeFound("amount.in=" + UPDATED_AMOUNT);
}
@Test
@Transactional
public void getAllAssetsByAmountIsNullOrNotNull() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList where amount is not null
defaultAssetShouldBeFound("amount.specified=true");
// Get all the assetList where amount is null
defaultAssetShouldNotBeFound("amount.specified=false");
}
@Test
@Transactional
public void getAllAssetsByRemarkIsEqualToSomething() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList where remark equals to DEFAULT_REMARK
defaultAssetShouldBeFound("remark.equals=" + DEFAULT_REMARK);
// Get all the assetList where remark equals to UPDATED_REMARK
defaultAssetShouldNotBeFound("remark.equals=" + UPDATED_REMARK);
}
@Test
@Transactional
public void getAllAssetsByRemarkIsInShouldWork() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList where remark in DEFAULT_REMARK or UPDATED_REMARK
defaultAssetShouldBeFound("remark.in=" + DEFAULT_REMARK + "," + UPDATED_REMARK);
// Get all the assetList where remark equals to UPDATED_REMARK
defaultAssetShouldNotBeFound("remark.in=" + UPDATED_REMARK);
}
@Test
@Transactional
public void getAllAssetsByRemarkIsNullOrNotNull() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
// Get all the assetList where remark is not null
defaultAssetShouldBeFound("remark.specified=true");
// Get all the assetList where remark is null
defaultAssetShouldNotBeFound("remark.specified=false");
}
@Test
@Transactional
public void getAllAssetsByMembershipIsEqualToSomething() throws Exception {
// Initialize the database
Membership membership = MembershipResourceIntTest
.createPersistentEntity(em, CustomerResourceIntTest.createPersistentEntity(em));
asset.setMembership(membership);
assetRepository.saveAndFlush(asset);
Long membershipId = membership.getId();
// Get all the assetList where membership equals to membershipId
defaultAssetShouldBeFound("membershipId.equals=" + membershipId);
// Get all the assetList where membership equals to membershipId + 1
defaultAssetShouldNotBeFound("membershipId.equals=" + (membershipId + 1));
}
/**
* Executes the search, and checks that the default entity is returned
*/
private void defaultAssetShouldBeFound(String filter) throws Exception {
restAssetMockMvc.perform(get("/api/assets?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(asset.getId().intValue())))
.andExpect(jsonPath("$.[*].documentDate").value(hasItem(DEFAULT_DOCUMENT_DATE.toString())))
.andExpect(jsonPath("$.[*].valueDate").value(hasItem(DEFAULT_VALUE_DATE.toString())))
.andExpect(jsonPath("$.[*].action").value(hasItem(DEFAULT_ACTION.toString())))
.andExpect(jsonPath("$.[*].amount").value(hasItem(DEFAULT_AMOUNT.intValue())))
.andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK)));
// Check, that the count call also returns 1
restAssetMockMvc.perform(get("/api/assets/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("1"));
}
/**
* Executes the search, and checks that the default entity is not returned
*/
private void defaultAssetShouldNotBeFound(String filter) throws Exception {
restAssetMockMvc.perform(get("/api/assets?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
// Check, that the count call also returns 0
restAssetMockMvc.perform(get("/api/assets/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("0"));
}
@Test
@Transactional
public void getNonExistingAsset() throws Exception {
// Get the asset
restAssetMockMvc.perform(get("/api/assets/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateAsset() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
int databaseSizeBeforeUpdate = assetRepository.findAll().size();
// Update the asset
Asset updatedAsset = assetRepository.findById(asset.getId()).get();
// Disconnect from session so that the updates on updatedAsset are not directly saved in db
em.detach(updatedAsset);
updatedAsset
.documentDate(UPDATED_DOCUMENT_DATE)
.valueDate(UPDATED_VALUE_DATE)
.action(UPDATED_ACTION)
.amount(UPDATED_AMOUNT)
.remark(UPDATED_REMARK);
AssetDTO assetDTO = assetMapper.toDto(updatedAsset);
restAssetMockMvc.perform(
put("/api/assets")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(assetDTO)))
.andExpect(status().isBadRequest());
// Validate the Asset in the database
List<Asset> assetList = assetRepository.findAll();
assertThat(assetList).hasSize(databaseSizeBeforeUpdate);
Asset testAsset = assetList.get(assetList.size() - 1);
assertThat(testAsset.getDocumentDate()).isEqualTo(DEFAULT_DOCUMENT_DATE);
assertThat(testAsset.getValueDate()).isEqualTo(DEFAULT_VALUE_DATE);
assertThat(testAsset.getAction()).isEqualByComparingTo(DEFAULT_ACTION);
assertThat(testAsset.getAmount()).isEqualByComparingTo(DEFAULT_AMOUNT);
assertThat(testAsset.getRemark()).isEqualTo(DEFAULT_REMARK);
}
@Test
@Transactional
public void updateNonExistingAsset() throws Exception {
int databaseSizeBeforeUpdate = assetRepository.findAll().size();
// Create the Asset
AssetDTO assetDTO = assetMapper.toDto(asset);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restAssetMockMvc.perform(
put("/api/assets")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(assetDTO)))
.andExpect(status().isBadRequest());
// Validate the Asset in the database
List<Asset> assetList = assetRepository.findAll();
assertThat(assetList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
public void deleteAsset() throws Exception {
// Initialize the database
assetRepository.saveAndFlush(asset);
int databaseSizeBeforeDelete = assetRepository.findAll().size();
// Delete the asset
restAssetMockMvc.perform(
delete("/api/assets/{id}", asset.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest());
// Validate the database still contains the same number of assets
List<Asset> assetList = assetRepository.findAll();
assertThat(assetList).hasSize(databaseSizeBeforeDelete);
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Asset.class);
Asset asset1 = new Asset();
asset1.setId(1L);
Asset asset2 = new Asset();
asset2.setId(asset1.getId());
assertThat(asset1).isEqualTo(asset2);
asset2.setId(2L);
assertThat(asset1).isNotEqualTo(asset2);
asset1.setId(null);
assertThat(asset1).isNotEqualTo(asset2);
}
@Test
@Transactional
public void dtoEqualsVerifier() throws Exception {
TestUtil.equalsVerifier(AssetDTO.class);
AssetDTO assetDTO1 = new AssetDTO();
assetDTO1.setId(1L);
AssetDTO assetDTO2 = new AssetDTO();
assertThat(assetDTO1).isNotEqualTo(assetDTO2);
assetDTO2.setId(assetDTO1.getId());
assertThat(assetDTO1).isEqualTo(assetDTO2);
assetDTO2.setId(2L);
assertThat(assetDTO1).isNotEqualTo(assetDTO2);
assetDTO1.setId(null);
assertThat(assetDTO1).isNotEqualTo(assetDTO2);
}
@Test
@Transactional
public void testEntityFromId() {
assertThat(assetMapper.fromId(42L).getId()).isEqualTo(42);
assertThat(assetMapper.fromId(null)).isNull();
}
}

View File

@@ -1,164 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.web.rest;
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.*;
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;
/**
* 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

@@ -1,70 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.web.rest;
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;
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;
/**
* 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

@@ -1,837 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.web.rest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.hostsharing.hsadminng.HsadminNgApp;
import org.hostsharing.hsadminng.domain.Asset;
import org.hostsharing.hsadminng.domain.Customer;
import org.hostsharing.hsadminng.domain.Membership;
import org.hostsharing.hsadminng.domain.Share;
import org.hostsharing.hsadminng.repository.MembershipRepository;
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
import org.hostsharing.hsadminng.service.MembershipQueryService;
import org.hostsharing.hsadminng.service.MembershipService;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock;
import org.hostsharing.hsadminng.service.dto.MembershipDTO;
import org.hostsharing.hsadminng.service.mapper.MembershipMapper;
import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator;
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.boot.test.mock.mockito.MockBean;
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 org.springframework.validation.Validator;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
import javax.persistence.EntityManager;
/**
* Test class for the MembershipResource REST controller.
*
* @see MembershipResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HsadminNgApp.class)
public class MembershipResourceIntTest {
private static final LocalDate DEFAULT_DOCUMENT_DATE = LocalDate.now(ZoneId.systemDefault());
private static final LocalDate UPDATED_DOCUMENT_DATE = DEFAULT_DOCUMENT_DATE.plusDays(1);
private static final LocalDate DEFAULT_MEMBER_FROM_DATE = DEFAULT_DOCUMENT_DATE.plusDays(2);
private static final LocalDate UPDATED_MEMBER_FROM_DATE = UPDATED_DOCUMENT_DATE.plusDays(8);
private static final LocalDate DEFAULT_MEMBER_UNTIL_DATE = DEFAULT_MEMBER_FROM_DATE.plusYears(1)
.withMonth(12)
.withDayOfMonth(31);
private static final LocalDate UPDATED_MEMBER_UNTIL_DATE = UPDATED_MEMBER_FROM_DATE.plusYears(7)
.withMonth(12)
.withDayOfMonth(31);
private static final LocalDate DEFAULT_ADMISSION_DOCUMENT_DATE = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_ADMISSION_DOCUMENT_DATE = LocalDate.now(ZoneId.systemDefault());
private static final LocalDate DEFAULT_CANCELLATION_DOCUMENT_DATE = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_CANCELLATION_DOCUMENT_DATE = LocalDate.now(ZoneId.systemDefault());
private static final String DEFAULT_REMARK = "AAAAAAAAAA";
private static final String UPDATED_REMARK = "BBBBBBBBBB";
@Autowired
private MembershipRepository membershipRepository;
@Autowired
private MembershipMapper membershipMapper;
@Autowired
private MembershipService membershipService;
@Autowired
private MembershipQueryService membershipQueryService;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
@Autowired
private Validator validator;
@MockBean
private UserRoleAssignmentService userRoleAssignmentService;
private SecurityContextMock securityContext;
private MockMvc restMembershipMockMvc;
private Membership membership;
@Before
public void setup() {
securityContext = SecurityContextMock.usingMock(userRoleAssignmentService)
.havingAuthenticatedUser()
.withAuthority(AuthoritiesConstants.ADMIN);
MockitoAnnotations.initMocks(this);
final MembershipResource membershipResource = new MembershipResource(membershipService, membershipQueryService);
this.restMembershipMockMvc = MockMvcBuilders.standaloneSetup(membershipResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator)
.build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Membership createEntity(EntityManager em) {
Membership membership = new Membership()
.admissionDocumentDate(DEFAULT_ADMISSION_DOCUMENT_DATE)
.cancellationDocumentDate(DEFAULT_CANCELLATION_DOCUMENT_DATE)
.memberFromDate(DEFAULT_MEMBER_FROM_DATE)
.memberUntilDate(DEFAULT_MEMBER_UNTIL_DATE)
.remark(DEFAULT_REMARK);
// Add required entity
Customer customer = CustomerResourceIntTest.createEntity(em);
em.persist(customer);
em.flush();
membership.setCustomer(customer);
return membership;
}
/**
* Create an entity for tests for a specific customer.
* <p>
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Membership createPersistentEntity(EntityManager em, final Customer customer) {
Membership membership = new Membership()
.admissionDocumentDate(DEFAULT_ADMISSION_DOCUMENT_DATE)
.memberFromDate(DEFAULT_MEMBER_FROM_DATE)
.memberUntilDate(DEFAULT_MEMBER_UNTIL_DATE)
.remark(DEFAULT_REMARK);
// Add required entity
membership.setCustomer(customer);
em.persist(membership);
em.flush();
return membership;
}
@Before
public void initTest() {
membership = createEntity(em);
}
@Test
@Transactional
public void createMembership() throws Exception {
int databaseSizeBeforeCreate = membershipRepository.findAll().size();
// Create the Membership
MembershipDTO membershipDTO = membershipMapper.toDto(membership);
membershipDTO.setCustomerPrefix(null);
membershipDTO.setCustomerDisplayLabel(null);
membershipDTO.setDisplayLabel(null);
restMembershipMockMvc.perform(
post("/api/memberships")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(membershipDTO)))
.andExpect(status().isCreated());
// Validate the Membership in the database
List<Membership> membershipList = membershipRepository.findAll();
assertThat(membershipList).hasSize(databaseSizeBeforeCreate + 1);
Membership testMembership = membershipList.get(membershipList.size() - 1);
assertThat(testMembership.getAdmissionDocumentDate()).isEqualTo(DEFAULT_ADMISSION_DOCUMENT_DATE);
assertThat(testMembership.getCancellationDocumentDate()).isEqualTo(DEFAULT_CANCELLATION_DOCUMENT_DATE);
assertThat(testMembership.getMemberFromDate()).isEqualTo(DEFAULT_MEMBER_FROM_DATE);
assertThat(testMembership.getMemberUntilDate()).isEqualTo(DEFAULT_MEMBER_UNTIL_DATE);
assertThat(testMembership.getRemark()).isEqualTo(DEFAULT_REMARK);
}
@Test
@Transactional
public void createCustomerWithExistingIdIsRejected() throws Exception {
// Initialize the database
final long existingCustomerId = membershipRepository.saveAndFlush(membership).getId();
int databaseSizeBeforeCreate = membershipRepository.findAll().size();
// Create the Customer with an existing ID
membership.setId(existingCustomerId);
MembershipDTO membershipDTO = membershipMapper.toDto(membership);
// An entity with an existing ID cannot be created, so this API call must fail
restMembershipMockMvc.perform(
post("/api/memberships")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(membershipDTO)))
.andExpect(status().isBadRequest());
// Validate the Customer in the database
List<Membership> membershipList = membershipRepository.findAll();
assertThat(membershipList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void createCustomerWithNonExistingIdIsRejected() throws Exception {
int databaseSizeBeforeCreate = membershipRepository.findAll().size();
// Create the Membership with an ID for which no entity exists
membership.setId(1L);
MembershipDTO membershipDTO = membershipMapper.toDto(membership);
// An entity with an existing ID cannot be created, so this API call must fail
restMembershipMockMvc.perform(
post("/api/memberships")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(membershipDTO)))
.andExpect(status().isBadRequest());
// Validate the Membership in the database
List<Membership> membershipList = membershipRepository.findAll();
assertThat(membershipList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void checkAdmissionDocumentDateIsRequired() throws Exception {
int databaseSizeBeforeTest = membershipRepository.findAll().size();
// set the field null
membership.setAdmissionDocumentDate(null);
// Create the Membership, which fails.
MembershipDTO membershipDTO = membershipMapper.toDto(membership);
restMembershipMockMvc.perform(
post("/api/memberships")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(membershipDTO)))
.andExpect(status().isBadRequest());
List<Membership> membershipList = membershipRepository.findAll();
assertThat(membershipList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkMemberFromDateIsRequired() throws Exception {
int databaseSizeBeforeTest = membershipRepository.findAll().size();
// set the field null
membership.setMemberFromDate(null);
// Create the Membership, which fails.
MembershipDTO membershipDTO = membershipMapper.toDto(membership);
restMembershipMockMvc.perform(
post("/api/memberships")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(membershipDTO)))
.andExpect(status().isBadRequest());
List<Membership> membershipList = membershipRepository.findAll();
assertThat(membershipList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void getAllMemberships() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList
restMembershipMockMvc.perform(get("/api/memberships?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(membership.getId().intValue())))
.andExpect(jsonPath("$.[*].admissionDocumentDate").value(hasItem(DEFAULT_ADMISSION_DOCUMENT_DATE.toString())))
.andExpect(
jsonPath("$.[*].cancellationDocumentDate")
.value(hasItem(DEFAULT_CANCELLATION_DOCUMENT_DATE.toString())))
.andExpect(jsonPath("$.[*].memberFromDate").value(hasItem(DEFAULT_MEMBER_FROM_DATE.toString())))
.andExpect(jsonPath("$.[*].memberUntilDate").value(hasItem(DEFAULT_MEMBER_UNTIL_DATE.toString())))
.andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK)));
}
@Test
@Transactional
public void getMembership() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get the membership
restMembershipMockMvc.perform(get("/api/memberships/{id}", membership.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(membership.getId().intValue()))
.andExpect(jsonPath("$.admissionDocumentDate").value(DEFAULT_ADMISSION_DOCUMENT_DATE.toString()))
.andExpect(jsonPath("$.cancellationDocumentDate").value(DEFAULT_CANCELLATION_DOCUMENT_DATE.toString()))
.andExpect(jsonPath("$.memberFromDate").value(DEFAULT_MEMBER_FROM_DATE.toString()))
.andExpect(jsonPath("$.memberUntilDate").value(DEFAULT_MEMBER_UNTIL_DATE.toString()))
.andExpect(jsonPath("$.remark").value(DEFAULT_REMARK));
}
@Test
@Transactional
public void getAllMembershipsByAdmissionDocumentDateIsEqualToSomething() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where admissionDocumentDate equals to DEFAULT_ADMISSION_DOCUMENT_DATE
defaultMembershipShouldBeFound("admissionDocumentDate.equals=" + DEFAULT_ADMISSION_DOCUMENT_DATE);
// Get all the membershipList where admissionDocumentDate equals to UPDATED_ADMISSION_DOCUMENT_DATE
defaultMembershipShouldNotBeFound("admissionDocumentDate.equals=" + UPDATED_ADMISSION_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllMembershipsByAdmissionDocumentDateIsInShouldWork() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where admissionDocumentDate in DEFAULT_ADMISSION_DOCUMENT_DATE or
// UPDATED_ADMISSION_DOCUMENT_DATE
defaultMembershipShouldBeFound(
"admissionDocumentDate.in=" + DEFAULT_ADMISSION_DOCUMENT_DATE + "," + UPDATED_ADMISSION_DOCUMENT_DATE);
// Get all the membershipList where admissionDocumentDate equals to UPDATED_ADMISSION_DOCUMENT_DATE
defaultMembershipShouldNotBeFound("admissionDocumentDate.in=" + UPDATED_ADMISSION_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllMembershipsByAdmissionDocumentDateIsNullOrNotNull() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where admissionDocumentDate is not null
defaultMembershipShouldBeFound("admissionDocumentDate.specified=true");
// Get all the membershipList where admissionDocumentDate is null
defaultMembershipShouldNotBeFound("admissionDocumentDate.specified=false");
}
@Test
@Transactional
public void getAllMembershipsByAdmissionDocumentDateIsGreaterThanOrEqualToSomething() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where admissionDocumentDate greater than or equals to DEFAULT_ADMISSION_DOCUMENT_DATE
defaultMembershipShouldBeFound("admissionDocumentDate.greaterOrEqualThan=" + DEFAULT_ADMISSION_DOCUMENT_DATE);
// Get all the membershipList where admissionDocumentDate greater than or equals to UPDATED_ADMISSION_DOCUMENT_DATE
defaultMembershipShouldNotBeFound("admissionDocumentDate.greaterOrEqualThan=" + UPDATED_ADMISSION_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllMembershipsByAdmissionDocumentDateIsLessThanSomething() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where admissionDocumentDate less than or equals to DEFAULT_ADMISSION_DOCUMENT_DATE
defaultMembershipShouldNotBeFound("admissionDocumentDate.lessThan=" + DEFAULT_ADMISSION_DOCUMENT_DATE);
// Get all the membershipList where admissionDocumentDate less than or equals to UPDATED_ADMISSION_DOCUMENT_DATE
defaultMembershipShouldBeFound("admissionDocumentDate.lessThan=" + UPDATED_ADMISSION_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllMembershipsByCancellationDocumentDateIsEqualToSomething() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where cancellationDocumentDate equals to DEFAULT_CANCELLATION_DOCUMENT_DATE
defaultMembershipShouldBeFound("cancellationDocumentDate.equals=" + DEFAULT_CANCELLATION_DOCUMENT_DATE);
// Get all the membershipList where cancellationDocumentDate equals to UPDATED_CANCELLATION_DOCUMENT_DATE
defaultMembershipShouldNotBeFound("cancellationDocumentDate.equals=" + UPDATED_CANCELLATION_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllMembershipsByCancellationDocumentDateIsInShouldWork() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where cancellationDocumentDate in DEFAULT_CANCELLATION_DOCUMENT_DATE or
// UPDATED_CANCELLATION_DOCUMENT_DATE
defaultMembershipShouldBeFound(
"cancellationDocumentDate.in=" + DEFAULT_CANCELLATION_DOCUMENT_DATE + "," + UPDATED_CANCELLATION_DOCUMENT_DATE);
// Get all the membershipList where cancellationDocumentDate equals to UPDATED_CANCELLATION_DOCUMENT_DATE
defaultMembershipShouldNotBeFound("cancellationDocumentDate.in=" + UPDATED_CANCELLATION_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllMembershipsByCancellationDocumentDateIsNullOrNotNull() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where cancellationDocumentDate is not null
defaultMembershipShouldBeFound("cancellationDocumentDate.specified=true");
// Get all the membershipList where cancellationDocumentDate is null
defaultMembershipShouldNotBeFound("cancellationDocumentDate.specified=false");
}
@Test
@Transactional
public void getAllMembershipsByCancellationDocumentDateIsGreaterThanOrEqualToSomething() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where cancellationDocumentDate greater than or equals to
// DEFAULT_CANCELLATION_DOCUMENT_DATE
defaultMembershipShouldBeFound("cancellationDocumentDate.greaterOrEqualThan=" + DEFAULT_CANCELLATION_DOCUMENT_DATE);
// Get all the membershipList where cancellationDocumentDate greater than or equals to
// UPDATED_CANCELLATION_DOCUMENT_DATE
defaultMembershipShouldNotBeFound("cancellationDocumentDate.greaterOrEqualThan=" + UPDATED_CANCELLATION_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllMembershipsByCancellationDocumentDateIsLessThanSomething() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where cancellationDocumentDate less than or equals to DEFAULT_CANCELLATION_DOCUMENT_DATE
defaultMembershipShouldNotBeFound("cancellationDocumentDate.lessThan=" + DEFAULT_CANCELLATION_DOCUMENT_DATE);
// Get all the membershipList where cancellationDocumentDate less than or equals to UPDATED_CANCELLATION_DOCUMENT_DATE
defaultMembershipShouldBeFound("cancellationDocumentDate.lessThan=" + UPDATED_CANCELLATION_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllMembershipsByMemberFromDateIsEqualToSomething() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where memberFromDate equals to DEFAULT_MEMBER_FROM_DATE
defaultMembershipShouldBeFound("memberFromDate.equals=" + DEFAULT_MEMBER_FROM_DATE);
// Get all the membershipList where memberFromDate equals to UPDATED_MEMBER_FROM_DATE
defaultMembershipShouldNotBeFound("memberFromDate.equals=" + UPDATED_MEMBER_FROM_DATE);
}
@Test
@Transactional
public void getAllMembershipsByMemberFromDateIsInShouldWork() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where memberFromDate in DEFAULT_MEMBER_FROM_DATE or UPDATED_MEMBER_FROM_DATE
defaultMembershipShouldBeFound("memberFromDate.in=" + DEFAULT_MEMBER_FROM_DATE + "," + UPDATED_MEMBER_FROM_DATE);
// Get all the membershipList where memberFromDate equals to UPDATED_MEMBER_FROM_DATE
defaultMembershipShouldNotBeFound("memberFromDate.in=" + UPDATED_MEMBER_FROM_DATE);
}
@Test
@Transactional
public void getAllMembershipsByMemberFromDateIsNullOrNotNull() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where memberFromDate is not null
defaultMembershipShouldBeFound("memberFromDate.specified=true");
// Get all the membershipList where memberFromDate is null
defaultMembershipShouldNotBeFound("memberFromDate.specified=false");
}
@Test
@Transactional
public void getAllMembershipsByMemberFromDateIsGreaterThanOrEqualToSomething() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where memberFromDate greater than or equals to DEFAULT_MEMBER_FROM_DATE
defaultMembershipShouldBeFound("memberFromDate.greaterOrEqualThan=" + DEFAULT_MEMBER_FROM_DATE);
// Get all the membershipList where memberFromDate greater than or equals to UPDATED_MEMBER_FROM_DATE
defaultMembershipShouldNotBeFound("memberFromDate.greaterOrEqualThan=" + UPDATED_MEMBER_FROM_DATE);
}
@Test
@Transactional
public void getAllMembershipsByMemberFromDateIsLessThanSomething() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where memberFromDate less than or equals to DEFAULT_MEMBER_FROM_DATE
defaultMembershipShouldNotBeFound("memberFromDate.lessThan=" + DEFAULT_MEMBER_FROM_DATE);
// Get all the membershipList where memberFromDate less than or equals to UPDATED_MEMBER_FROM_DATE
defaultMembershipShouldBeFound("memberFromDate.lessThan=" + UPDATED_MEMBER_FROM_DATE);
}
@Test
@Transactional
public void getAllMembershipsByMemberUntilDateIsEqualToSomething() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where memberUntilDate equals to DEFAULT_MEMBER_UNTIL_DATE
defaultMembershipShouldBeFound("memberUntilDate.equals=" + DEFAULT_MEMBER_UNTIL_DATE);
// Get all the membershipList where memberUntilDate equals to UPDATED_MEMBER_UNTIL_DATE
defaultMembershipShouldNotBeFound("memberUntilDate.equals=" + UPDATED_MEMBER_UNTIL_DATE);
}
@Test
@Transactional
public void getAllMembershipsByMemberUntilDateIsInShouldWork() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where memberUntilDate in DEFAULT_MEMBER_UNTIL_DATE or UPDATED_MEMBER_UNTIL_DATE
defaultMembershipShouldBeFound("memberUntilDate.in=" + DEFAULT_MEMBER_UNTIL_DATE + "," + UPDATED_MEMBER_UNTIL_DATE);
// Get all the membershipList where memberUntilDate equals to UPDATED_MEMBER_UNTIL_DATE
defaultMembershipShouldNotBeFound("memberUntilDate.in=" + UPDATED_MEMBER_UNTIL_DATE);
}
@Test
@Transactional
public void getAllMembershipsByMemberUntilDateIsNullOrNotNull() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where memberUntilDate is not null
defaultMembershipShouldBeFound("memberUntilDate.specified=true");
// Get all the membershipList where memberUntilDate is null
defaultMembershipShouldNotBeFound("memberUntilDate.specified=false");
}
@Test
@Transactional
public void getAllMembershipsByMemberUntilDateIsGreaterThanOrEqualToSomething() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where memberUntilDate greater than or equals to DEFAULT_MEMBER_UNTIL_DATE
defaultMembershipShouldBeFound("memberUntilDate.greaterOrEqualThan=" + DEFAULT_MEMBER_UNTIL_DATE);
// Get all the membershipList where memberUntilDate greater than or equals to UPDATED_MEMBER_UNTIL_DATE
defaultMembershipShouldNotBeFound("memberUntilDate.greaterOrEqualThan=" + UPDATED_MEMBER_UNTIL_DATE);
}
@Test
@Transactional
public void getAllMembershipsByMemberUntilDateIsLessThanSomething() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where memberUntilDate less than or equals to DEFAULT_MEMBER_UNTIL_DATE
defaultMembershipShouldNotBeFound("memberUntilDate.lessThan=" + DEFAULT_MEMBER_UNTIL_DATE);
// Get all the membershipList where memberUntilDate less than or equals to UPDATED_MEMBER_UNTIL_DATE
defaultMembershipShouldBeFound("memberUntilDate.lessThan=" + UPDATED_MEMBER_UNTIL_DATE);
}
@Test
@Transactional
public void getAllMembershipsByRemarkIsEqualToSomething() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where remark equals to DEFAULT_REMARK
defaultMembershipShouldBeFound("remark.equals=" + DEFAULT_REMARK);
// Get all the membershipList where remark equals to UPDATED_REMARK
defaultMembershipShouldNotBeFound("remark.equals=" + UPDATED_REMARK);
}
@Test
@Transactional
public void getAllMembershipsByRemarkIsInShouldWork() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where remark in DEFAULT_REMARK or UPDATED_REMARK
defaultMembershipShouldBeFound("remark.in=" + DEFAULT_REMARK + "," + UPDATED_REMARK);
// Get all the membershipList where remark equals to UPDATED_REMARK
defaultMembershipShouldNotBeFound("remark.in=" + UPDATED_REMARK);
}
@Test
@Transactional
public void getAllMembershipsByRemarkIsNullOrNotNull() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where remark is not null
defaultMembershipShouldBeFound("remark.specified=true");
// Get all the membershipList where remark is null
defaultMembershipShouldNotBeFound("remark.specified=false");
}
@Test
@Transactional
public void getAllMembershipsByShareIsEqualToSomething() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
Share share = ShareResourceIntTest.createPersistentEntity(em, membership);
Long shareId = share.getId();
// Get all the membershipList where share equals to shareId
defaultMembershipShouldBeFound("shareId.equals=" + shareId);
// Get all the membershipList where share equals to shareId + 1
defaultMembershipShouldNotBeFound("shareId.equals=" + (shareId + 1));
}
@Test
@Transactional
public void getAllMembershipsByAssetIsEqualToSomething() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
Asset asset = AssetResourceIntTest.createPersistentEntity(em, membership);
Long assetId = asset.getId();
// Get all the membershipList where asset equals to assetId
defaultMembershipShouldBeFound("assetId.equals=" + assetId);
// Get all the membershipList where asset equals to assetId + 1
defaultMembershipShouldNotBeFound("assetId.equals=" + (assetId + 1));
}
@Test
@Transactional
public void getAllMembershipsByCustomerIsEqualToSomething() throws Exception {
// Initialize the database
Customer customer = CustomerResourceIntTest.createPersistentEntity(em);
membership.setCustomer(customer);
membershipRepository.saveAndFlush(membership);
Long customerId = customer.getId();
// Get all the membershipList where customer equals to customerId
defaultMembershipShouldBeFound("customerId.equals=" + customerId);
// Get all the membershipList where customer equals to customerId + 1
defaultMembershipShouldNotBeFound("customerId.equals=" + (customerId + 1));
}
/**
* Executes the search, and checks that the default entity is returned
*/
private void defaultMembershipShouldBeFound(String filter) throws Exception {
restMembershipMockMvc.perform(get("/api/memberships?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(membership.getId().intValue())))
.andExpect(jsonPath("$.[*].admissionDocumentDate").value(hasItem(DEFAULT_ADMISSION_DOCUMENT_DATE.toString())))
.andExpect(
jsonPath("$.[*].cancellationDocumentDate")
.value(hasItem(DEFAULT_CANCELLATION_DOCUMENT_DATE.toString())))
.andExpect(jsonPath("$.[*].memberFromDate").value(hasItem(DEFAULT_MEMBER_FROM_DATE.toString())))
.andExpect(jsonPath("$.[*].memberUntilDate").value(hasItem(DEFAULT_MEMBER_UNTIL_DATE.toString())))
.andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK)));
// Check, that the count call also returns 1
restMembershipMockMvc.perform(get("/api/memberships/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("1"));
}
/**
* Executes the search, and checks that the default entity is not returned
*/
private void defaultMembershipShouldNotBeFound(String filter) throws Exception {
restMembershipMockMvc.perform(get("/api/memberships?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
// Check, that the count call also returns 0
restMembershipMockMvc.perform(get("/api/memberships/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("0"));
}
@Test
@Transactional
public void getNonExistingMembership() throws Exception {
// Get the membership
restMembershipMockMvc.perform(get("/api/memberships/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateMembership() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
int databaseSizeBeforeUpdate = membershipRepository.findAll().size();
// Update the membership
Membership updatedMembership = membershipRepository.findById(membership.getId()).get();
// Disconnect from session so that the updates on updatedMembership are not directly saved in db
em.detach(updatedMembership);
updatedMembership
.cancellationDocumentDate(UPDATED_CANCELLATION_DOCUMENT_DATE)
.memberUntilDate(UPDATED_MEMBER_UNTIL_DATE)
.remark(UPDATED_REMARK);
MembershipDTO membershipDTO = membershipMapper.toDto(updatedMembership);
restMembershipMockMvc.perform(
put("/api/memberships")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(membershipDTO)))
.andExpect(status().isOk());
// Validate the Membership in the database
List<Membership> membershipList = membershipRepository.findAll();
assertThat(membershipList).hasSize(databaseSizeBeforeUpdate);
Membership testMembership = membershipList.get(membershipList.size() - 1);
assertThat(testMembership.getAdmissionDocumentDate()).isEqualTo(DEFAULT_ADMISSION_DOCUMENT_DATE);
assertThat(testMembership.getCancellationDocumentDate()).isEqualTo(UPDATED_CANCELLATION_DOCUMENT_DATE);
assertThat(testMembership.getMemberFromDate()).isEqualTo(DEFAULT_MEMBER_FROM_DATE);
assertThat(testMembership.getMemberUntilDate()).isEqualTo(UPDATED_MEMBER_UNTIL_DATE);
assertThat(testMembership.getRemark()).isEqualTo(UPDATED_REMARK);
}
@Test
@Transactional
public void updateNonExistingMembership() throws Exception {
int databaseSizeBeforeUpdate = membershipRepository.findAll().size();
// Create the Membership
MembershipDTO membershipDTO = membershipMapper.toDto(membership);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restMembershipMockMvc.perform(
put("/api/memberships")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(membershipDTO)))
.andExpect(status().isBadRequest());
// Validate the Membership in the database
List<Membership> membershipList = membershipRepository.findAll();
assertThat(membershipList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
public void deleteMembership() throws Exception {
// Initialize the database
membershipRepository.saveAndFlush(membership);
int databaseSizeBeforeDelete = membershipRepository.findAll().size();
// Delete the membership
restMembershipMockMvc.perform(
delete("/api/memberships/{id}", membership.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest());
// Validate the database is unchanged
List<Membership> membershipList = membershipRepository.findAll();
assertThat(membershipList).hasSize(databaseSizeBeforeDelete);
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Membership.class);
Membership membership1 = new Membership();
membership1.setId(1L);
Membership membership2 = new Membership();
membership2.setId(membership1.getId());
assertThat(membership1).isEqualTo(membership2);
membership2.setId(2L);
assertThat(membership1).isNotEqualTo(membership2);
membership1.setId(null);
assertThat(membership1).isNotEqualTo(membership2);
}
@Test
@Transactional
public void dtoEqualsVerifier() throws Exception {
TestUtil.equalsVerifier(MembershipDTO.class);
MembershipDTO membershipDTO1 = new MembershipDTO();
membershipDTO1.setId(1L);
MembershipDTO membershipDTO2 = new MembershipDTO();
assertThat(membershipDTO1).isNotEqualTo(membershipDTO2);
membershipDTO2.setId(membershipDTO1.getId());
assertThat(membershipDTO1).isEqualTo(membershipDTO2);
membershipDTO2.setId(2L);
assertThat(membershipDTO1).isNotEqualTo(membershipDTO2);
membershipDTO1.setId(null);
assertThat(membershipDTO1).isNotEqualTo(membershipDTO2);
}
@Test
@Transactional
public void testEntityFromId() {
assertThat(membershipMapper.fromId(42L).getId()).isEqualTo(42);
assertThat(membershipMapper.fromId(null)).isNull();
}
}

View File

@@ -1,58 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.web.rest;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.assertj.core.api.ThrowableAssert.catchThrowable;
import org.hostsharing.hsadminng.service.dto.MembershipDTO;
import org.hostsharing.hsadminng.service.dto.MembershipDTOUnitTest;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
// Currently this class tests mostly special 'bad paths'
// which make little sense to test in *ResourceIntTest.
public class MembershipResourceUnitTest {
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@InjectMocks
private MembershipResource membershipResource;
@Test
public void createSepaMandateWithoutIdThrowsBadRequestException() {
// given
final MembershipDTO givenDto = MembershipDTOUnitTest.createRandomDTO(null, 1L);
// when
final Throwable actual = catchThrowable(() -> membershipResource.updateMembership(givenDto));
// then
assertThat(actual).isInstanceOfSatisfying(BadRequestAlertException.class, bre -> {
assertThat(bre.getErrorKey()).isEqualTo("idnull");
assertThat(bre.getParam()).isEqualTo("membership");
});
}
@Test
public void createSepaMandateWithIdThrowsBadRequestException() {
// given
final MembershipDTO givenDto = MembershipDTOUnitTest.createRandomDTO(2L, 1L);
// when
final Throwable actual = catchThrowable(() -> membershipResource.createMembership(givenDto));
// then
assertThat(actual).isInstanceOfSatisfying(BadRequestAlertException.class, bre -> {
assertThat(bre.getErrorKey()).isEqualTo("idexists");
assertThat(bre.getParam()).isEqualTo("membership");
});
}
}

View File

@@ -1,58 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.web.rest;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.assertj.core.api.ThrowableAssert.catchThrowable;
import org.hostsharing.hsadminng.service.dto.SepaMandateDTO;
import org.hostsharing.hsadminng.service.dto.SepaMandateDTOUnitTest;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
// Currently this class tests mostly special 'bad paths'
// which make little sense to test in *ResourceIntTest.
public class SepaMandateResourceUnitTest {
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@InjectMocks
private SepaMandateResource sepaMandateResource;
@Test
public void createSepaMandateWithoutIdThrowsBadRequestException() {
// given
final SepaMandateDTO givenDto = SepaMandateDTOUnitTest.createRandomDTO(null, 1L);
// when
final Throwable actual = catchThrowable(() -> sepaMandateResource.updateSepaMandate(givenDto));
// then
assertThat(actual).isInstanceOfSatisfying(BadRequestAlertException.class, bre -> {
assertThat(bre.getErrorKey()).isEqualTo("idnull");
assertThat(bre.getParam()).isEqualTo("sepaMandate");
});
}
@Test
public void createSepaMandateWithIdThrowsBadRequestException() {
// given
final SepaMandateDTO givenDto = SepaMandateDTOUnitTest.createRandomDTO(2L, 1L);
// when
final Throwable actual = catchThrowable(() -> sepaMandateResource.createSepaMandate(givenDto));
// then
assertThat(actual).isInstanceOfSatisfying(BadRequestAlertException.class, bre -> {
assertThat(bre.getErrorKey()).isEqualTo("idexists");
assertThat(bre.getParam()).isEqualTo("sepaMandate");
});
}
}

View File

@@ -1,802 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.web.rest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.hostsharing.hsadminng.HsadminNgApp;
import org.hostsharing.hsadminng.domain.Membership;
import org.hostsharing.hsadminng.domain.Share;
import org.hostsharing.hsadminng.domain.enumeration.ShareAction;
import org.hostsharing.hsadminng.repository.ShareRepository;
import org.hostsharing.hsadminng.service.ShareQueryService;
import org.hostsharing.hsadminng.service.ShareService;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock;
import org.hostsharing.hsadminng.service.dto.ShareDTO;
import org.hostsharing.hsadminng.service.mapper.ShareMapper;
import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator;
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.boot.test.mock.mockito.MockBean;
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 org.springframework.validation.Validator;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
import javax.persistence.EntityManager;
/**
* Test class for the ShareResource REST controller.
*
* @see ShareResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HsadminNgApp.class)
public class ShareResourceIntTest {
private static final LocalDate DEFAULT_DOCUMENT_DATE = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_DOCUMENT_DATE = LocalDate.now(ZoneId.systemDefault());
private static final LocalDate DEFAULT_VALUE_DATE = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_VALUE_DATE = LocalDate.now(ZoneId.systemDefault());
private static final ShareAction DEFAULT_ACTION = ShareAction.SUBSCRIPTION;
private static final ShareAction UPDATED_ACTION = ShareAction.CANCELLATION;
private static final Integer DEFAULT_QUANTITY = 1;
private static final Integer UPDATED_QUANTITY = 2;
private static final String DEFAULT_REMARK = "AAAAAAAAAA";
private static final String UPDATED_REMARK = "BBBBBBBBBB";
@Autowired
private ShareRepository shareRepository;
@Autowired
private ShareMapper shareMapper;
@Autowired
private ShareService shareService;
@Autowired
private ShareQueryService shareQueryService;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
@Autowired
private Validator validator;
@MockBean
private UserRoleAssignmentService userRoleAssignmentService;
private MockMvc restShareMockMvc;
private Share share;
@Before
public void setup() {
SecurityContextMock.usingMock(userRoleAssignmentService)
.havingAuthenticatedUser()
.withAuthority(Role.Admin.ROLE.authority());
MockitoAnnotations.initMocks(this);
final ShareResource shareResource = new ShareResource(shareService, shareQueryService);
this.restShareMockMvc = MockMvcBuilders.standaloneSetup(shareResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator)
.build();
}
/**
* Create an entity for this test.
* <p>
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Share createEntity(EntityManager em) {
Share share = new Share()
.documentDate(DEFAULT_DOCUMENT_DATE)
.valueDate(DEFAULT_VALUE_DATE)
.action(DEFAULT_ACTION)
.quantity(DEFAULT_QUANTITY)
.remark(DEFAULT_REMARK);
// Add required entity
Membership membership = MembershipResourceIntTest.createEntity(em);
em.persist(membership);
em.flush();
share.setMembership(membership);
return share;
}
/**
* Create a persistent entity related to the given persistent membership for testing purposes.
* <p>
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Share createPersistentEntity(EntityManager em, final Membership membership) {
Share share = new Share()
.documentDate(DEFAULT_DOCUMENT_DATE)
.valueDate(DEFAULT_VALUE_DATE)
.action(DEFAULT_ACTION)
.quantity(DEFAULT_QUANTITY)
.remark(DEFAULT_REMARK);
// Add required entity
share.setMembership(membership);
membership.addShare(share);
em.persist(share);
em.flush();
return share;
}
@Before
public void initTest() {
share = createEntity(em);
}
@Test
@Transactional
public void createShare() throws Exception {
int databaseSizeBeforeCreate = shareRepository.findAll().size();
// Create the Share
ShareDTO shareDTO = shareMapper.toDto(share);
shareDTO.setMembershipDisplayLabel(null);
restShareMockMvc.perform(
post("/api/shares")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(shareDTO)))
.andExpect(status().isCreated());
// Validate the Share in the database
List<Share> shareList = shareRepository.findAll();
assertThat(shareList).hasSize(databaseSizeBeforeCreate + 1);
Share testShare = shareList.get(shareList.size() - 1);
assertThat(testShare.getDocumentDate()).isEqualTo(DEFAULT_DOCUMENT_DATE);
assertThat(testShare.getValueDate()).isEqualTo(DEFAULT_VALUE_DATE);
assertThat(testShare.getAction()).isEqualTo(DEFAULT_ACTION);
assertThat(testShare.getQuantity()).isEqualTo(DEFAULT_QUANTITY);
assertThat(testShare.getRemark()).isEqualTo(DEFAULT_REMARK);
}
@Test
@Transactional
public void createShareWithIdForNonExistingEntity() throws Exception {
int databaseSizeBeforeCreate = shareRepository.findAll().size();
// Create the Share with an ID
share.setId(1L);
ShareDTO shareDTO = shareMapper.toDto(share);
// An entity with an existing ID cannot be created, so this API call must fail
restShareMockMvc.perform(
post("/api/shares")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(shareDTO)))
.andExpect(status().isBadRequest());
// Validate the Share in the database
List<Share> shareList = shareRepository.findAll();
assertThat(shareList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void createShareWithExistingExistingEntity() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
int databaseSizeBeforeCreate = shareRepository.findAll().size();
// Create the Share with the ID of an existing ID
ShareDTO shareDTO = shareMapper.toDto(share);
// An entity with an existing ID cannot be created, so this API call must fail
restShareMockMvc.perform(
post("/api/shares")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(shareDTO)))
.andExpect(status().isBadRequest());
// Validate the Share in the database
List<Share> assetList = shareRepository.findAll();
assertThat(assetList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void checkDocumentDateIsRequired() throws Exception {
int databaseSizeBeforeTest = shareRepository.findAll().size();
// set the field null
share.setDocumentDate(null);
// Create the Share, which fails.
ShareDTO shareDTO = shareMapper.toDto(share);
restShareMockMvc.perform(
post("/api/shares")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(shareDTO)))
.andExpect(status().isBadRequest());
List<Share> shareList = shareRepository.findAll();
assertThat(shareList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkValueDateIsRequired() throws Exception {
int databaseSizeBeforeTest = shareRepository.findAll().size();
// set the field null
share.setValueDate(null);
// Create the Share, which fails.
ShareDTO shareDTO = shareMapper.toDto(share);
restShareMockMvc.perform(
post("/api/shares")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(shareDTO)))
.andExpect(status().isBadRequest());
List<Share> shareList = shareRepository.findAll();
assertThat(shareList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkActionIsRequired() throws Exception {
int databaseSizeBeforeTest = shareRepository.findAll().size();
// set the field null
share.setAction(null);
// Create the Share, which fails.
ShareDTO shareDTO = shareMapper.toDto(share);
restShareMockMvc.perform(
post("/api/shares")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(shareDTO)))
.andExpect(status().isBadRequest());
List<Share> shareList = shareRepository.findAll();
assertThat(shareList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkQuantityIsRequired() throws Exception {
int databaseSizeBeforeTest = shareRepository.findAll().size();
// set the field null
share.setQuantity(null);
// Create the Share, which fails.
ShareDTO shareDTO = shareMapper.toDto(share);
restShareMockMvc.perform(
post("/api/shares")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(shareDTO)))
.andExpect(status().isBadRequest());
List<Share> shareList = shareRepository.findAll();
assertThat(shareList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void getAllShares() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList
restShareMockMvc.perform(get("/api/shares?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(share.getId().intValue())))
.andExpect(jsonPath("$.[*].documentDate").value(hasItem(DEFAULT_DOCUMENT_DATE.toString())))
.andExpect(jsonPath("$.[*].valueDate").value(hasItem(DEFAULT_VALUE_DATE.toString())))
.andExpect(jsonPath("$.[*].action").value(hasItem(DEFAULT_ACTION.toString())))
.andExpect(jsonPath("$.[*].quantity").value(hasItem(DEFAULT_QUANTITY)))
.andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK.toString())));
}
@Test
@Transactional
public void getShare() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get the share
restShareMockMvc.perform(get("/api/shares/{id}", share.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(share.getId().intValue()))
.andExpect(jsonPath("$.documentDate").value(DEFAULT_DOCUMENT_DATE.toString()))
.andExpect(jsonPath("$.valueDate").value(DEFAULT_VALUE_DATE.toString()))
.andExpect(jsonPath("$.action").value(DEFAULT_ACTION.toString()))
.andExpect(jsonPath("$.quantity").value(DEFAULT_QUANTITY))
.andExpect(jsonPath("$.remark").value(DEFAULT_REMARK.toString()));
}
@Test
@Transactional
public void getAllSharesByDocumentDateIsEqualToSomething() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where documentDate equals to DEFAULT_DOCUMENT_DATE
defaultShareShouldBeFound("documentDate.equals=" + DEFAULT_DOCUMENT_DATE);
// Get all the shareList where documentDate equals to UPDATED_DOCUMENT_DATE
defaultShareShouldNotBeFound("documentDate.equals=" + UPDATED_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllSharesByDocumentDateIsInShouldWork() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where documentDate in DEFAULT_DOCUMENT_DATE or UPDATED_DOCUMENT_DATE
defaultShareShouldBeFound("documentDate.in=" + DEFAULT_DOCUMENT_DATE + "," + UPDATED_DOCUMENT_DATE);
// Get all the shareList where documentDate equals to UPDATED_DOCUMENT_DATE
defaultShareShouldNotBeFound("documentDate.in=" + UPDATED_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllSharesByDocumentDateIsNullOrNotNull() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where documentDate is not null
defaultShareShouldBeFound("documentDate.specified=true");
// Get all the shareList where documentDate is null
defaultShareShouldNotBeFound("documentDate.specified=false");
}
@Test
@Transactional
public void getAllSharesByDocumentDateIsGreaterThanOrEqualToSomething() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where documentDate greater than or equals to DEFAULT_DOCUMENT_DATE
defaultShareShouldBeFound("documentDate.greaterOrEqualThan=" + DEFAULT_DOCUMENT_DATE);
// Get all the shareList where documentDate greater than or equals to UPDATED_DOCUMENT_DATE
defaultShareShouldNotBeFound("documentDate.greaterOrEqualThan=" + UPDATED_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllSharesByDocumentDateIsLessThanSomething() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where documentDate less than or equals to DEFAULT_DOCUMENT_DATE
defaultShareShouldNotBeFound("documentDate.lessThan=" + DEFAULT_DOCUMENT_DATE);
// Get all the shareList where documentDate less than or equals to UPDATED_DOCUMENT_DATE
defaultShareShouldBeFound("documentDate.lessThan=" + UPDATED_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllSharesByValueDateIsEqualToSomething() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where valueDate equals to DEFAULT_VALUE_DATE
defaultShareShouldBeFound("valueDate.equals=" + DEFAULT_VALUE_DATE);
// Get all the shareList where valueDate equals to UPDATED_VALUE_DATE
defaultShareShouldNotBeFound("valueDate.equals=" + UPDATED_VALUE_DATE);
}
@Test
@Transactional
public void getAllSharesByValueDateIsInShouldWork() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where valueDate in DEFAULT_VALUE_DATE or UPDATED_VALUE_DATE
defaultShareShouldBeFound("valueDate.in=" + DEFAULT_VALUE_DATE + "," + UPDATED_VALUE_DATE);
// Get all the shareList where valueDate equals to UPDATED_VALUE_DATE
defaultShareShouldNotBeFound("valueDate.in=" + UPDATED_VALUE_DATE);
}
@Test
@Transactional
public void getAllSharesByValueDateIsNullOrNotNull() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where valueDate is not null
defaultShareShouldBeFound("valueDate.specified=true");
// Get all the shareList where valueDate is null
defaultShareShouldNotBeFound("valueDate.specified=false");
}
@Test
@Transactional
public void getAllSharesByValueDateIsGreaterThanOrEqualToSomething() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where valueDate greater than or equals to DEFAULT_VALUE_DATE
defaultShareShouldBeFound("valueDate.greaterOrEqualThan=" + DEFAULT_VALUE_DATE);
// Get all the shareList where valueDate greater than or equals to UPDATED_VALUE_DATE
defaultShareShouldNotBeFound("valueDate.greaterOrEqualThan=" + UPDATED_VALUE_DATE);
}
@Test
@Transactional
public void getAllSharesByValueDateIsLessThanSomething() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where valueDate less than or equals to DEFAULT_VALUE_DATE
defaultShareShouldNotBeFound("valueDate.lessThan=" + DEFAULT_VALUE_DATE);
// Get all the shareList where valueDate less than or equals to UPDATED_VALUE_DATE
defaultShareShouldBeFound("valueDate.lessThan=" + UPDATED_VALUE_DATE);
}
@Test
@Transactional
public void getAllSharesByActionIsEqualToSomething() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where action equals to DEFAULT_ACTION
defaultShareShouldBeFound("action.equals=" + DEFAULT_ACTION);
// Get all the shareList where action equals to UPDATED_ACTION
defaultShareShouldNotBeFound("action.equals=" + UPDATED_ACTION);
}
@Test
@Transactional
public void getAllSharesByActionIsInShouldWork() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where action in DEFAULT_ACTION or UPDATED_ACTION
defaultShareShouldBeFound("action.in=" + DEFAULT_ACTION + "," + UPDATED_ACTION);
// Get all the shareList where action equals to UPDATED_ACTION
defaultShareShouldNotBeFound("action.in=" + UPDATED_ACTION);
}
@Test
@Transactional
public void getAllSharesByActionIsNullOrNotNull() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where action is not null
defaultShareShouldBeFound("action.specified=true");
// Get all the shareList where action is null
defaultShareShouldNotBeFound("action.specified=false");
}
@Test
@Transactional
public void getAllSharesByQuantityIsEqualToSomething() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where quantity equals to DEFAULT_QUANTITY
defaultShareShouldBeFound("quantity.equals=" + DEFAULT_QUANTITY);
// Get all the shareList where quantity equals to UPDATED_QUANTITY
defaultShareShouldNotBeFound("quantity.equals=" + UPDATED_QUANTITY);
}
@Test
@Transactional
public void getAllSharesByQuantityIsInShouldWork() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where quantity in DEFAULT_QUANTITY or UPDATED_QUANTITY
defaultShareShouldBeFound("quantity.in=" + DEFAULT_QUANTITY + "," + UPDATED_QUANTITY);
// Get all the shareList where quantity equals to UPDATED_QUANTITY
defaultShareShouldNotBeFound("quantity.in=" + UPDATED_QUANTITY);
}
@Test
@Transactional
public void getAllSharesByQuantityIsNullOrNotNull() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where quantity is not null
defaultShareShouldBeFound("quantity.specified=true");
// Get all the shareList where quantity is null
defaultShareShouldNotBeFound("quantity.specified=false");
}
@Test
@Transactional
public void getAllSharesByQuantityIsGreaterThanOrEqualToSomething() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where quantity greater than or equals to DEFAULT_QUANTITY
defaultShareShouldBeFound("quantity.greaterOrEqualThan=" + DEFAULT_QUANTITY);
// Get all the shareList where quantity greater than or equals to UPDATED_QUANTITY
defaultShareShouldNotBeFound("quantity.greaterOrEqualThan=" + UPDATED_QUANTITY);
}
@Test
@Transactional
public void getAllSharesByQuantityIsLessThanSomething() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where quantity less than or equals to DEFAULT_QUANTITY
defaultShareShouldNotBeFound("quantity.lessThan=" + DEFAULT_QUANTITY);
// Get all the shareList where quantity less than or equals to UPDATED_QUANTITY
defaultShareShouldBeFound("quantity.lessThan=" + UPDATED_QUANTITY);
}
@Test
@Transactional
public void getAllSharesByRemarkIsEqualToSomething() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where remark equals to DEFAULT_REMARK
defaultShareShouldBeFound("remark.equals=" + DEFAULT_REMARK);
// Get all the shareList where remark equals to UPDATED_REMARK
defaultShareShouldNotBeFound("remark.equals=" + UPDATED_REMARK);
}
@Test
@Transactional
public void getAllSharesByRemarkIsInShouldWork() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where remark in DEFAULT_REMARK or UPDATED_REMARK
defaultShareShouldBeFound("remark.in=" + DEFAULT_REMARK + "," + UPDATED_REMARK);
// Get all the shareList where remark equals to UPDATED_REMARK
defaultShareShouldNotBeFound("remark.in=" + UPDATED_REMARK);
}
@Test
@Transactional
public void getAllSharesByRemarkIsNullOrNotNull() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
// Get all the shareList where remark is not null
defaultShareShouldBeFound("remark.specified=true");
// Get all the shareList where remark is null
defaultShareShouldNotBeFound("remark.specified=false");
}
@Test
@Transactional
public void getAllSharesByMembershipIsEqualToSomething() throws Exception {
// Initialize the database
Membership membership = MembershipResourceIntTest
.createPersistentEntity(em, CustomerResourceIntTest.createPersistentEntity(em));
share.setMembership(membership);
shareRepository.saveAndFlush(share);
Long membershipId = membership.getId();
// Get all the shareList where membership equals to membershipId
defaultShareShouldBeFound("membershipId.equals=" + membershipId);
// Get all the shareList where membership equals to membershipId + 1
defaultShareShouldNotBeFound("membershipId.equals=" + (membershipId + 1));
}
/**
* Executes the search, and checks that the default entity is returned
*/
private void defaultShareShouldBeFound(String filter) throws Exception {
restShareMockMvc.perform(get("/api/shares?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(share.getId().intValue())))
.andExpect(jsonPath("$.[*].documentDate").value(hasItem(DEFAULT_DOCUMENT_DATE.toString())))
.andExpect(jsonPath("$.[*].valueDate").value(hasItem(DEFAULT_VALUE_DATE.toString())))
.andExpect(jsonPath("$.[*].action").value(hasItem(DEFAULT_ACTION.toString())))
.andExpect(jsonPath("$.[*].quantity").value(hasItem(DEFAULT_QUANTITY)))
.andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK)));
// Check, that the count call also returns 1
restShareMockMvc.perform(get("/api/shares/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("1"));
}
/**
* Executes the search, and checks that the default entity is not returned
*/
private void defaultShareShouldNotBeFound(String filter) throws Exception {
restShareMockMvc.perform(get("/api/shares?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
// Check, that the count call also returns 0
restShareMockMvc.perform(get("/api/shares/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("0"));
}
@Test
@Transactional
public void getNonExistingShare() throws Exception {
// Get the share
restShareMockMvc.perform(get("/api/shares/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateShare() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
int databaseSizeBeforeUpdate = shareRepository.findAll().size();
// Update the share
Share updatedShare = shareRepository.findById(share.getId()).get();
// Disconnect from session so that the updates on updatedShare are not directly saved in db
em.detach(updatedShare);
updatedShare
.documentDate(UPDATED_DOCUMENT_DATE)
.valueDate(UPDATED_VALUE_DATE)
.action(UPDATED_ACTION)
.quantity(UPDATED_QUANTITY)
.remark(UPDATED_REMARK);
ShareDTO shareDTO = shareMapper.toDto(updatedShare);
restShareMockMvc.perform(
put("/api/shares")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(shareDTO)))
.andExpect(status().isBadRequest());
// Validate the database is unchanged
List<Share> shareList = shareRepository.findAll();
assertThat(shareList).hasSize(databaseSizeBeforeUpdate);
Share testShare = shareList.get(shareList.size() - 1);
assertThat(testShare.getDocumentDate()).isEqualTo(DEFAULT_DOCUMENT_DATE);
assertThat(testShare.getValueDate()).isEqualTo(DEFAULT_VALUE_DATE);
assertThat(testShare.getAction()).isEqualTo(DEFAULT_ACTION);
assertThat(testShare.getQuantity()).isEqualTo(DEFAULT_QUANTITY);
assertThat(testShare.getRemark()).isEqualTo(DEFAULT_REMARK);
}
@Test
@Transactional
public void updateNonExistingShare() throws Exception {
int databaseSizeBeforeUpdate = shareRepository.findAll().size();
// Create the Share
ShareDTO shareDTO = shareMapper.toDto(share);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restShareMockMvc.perform(
put("/api/shares")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(shareDTO)))
.andExpect(status().isBadRequest());
// Validate the Share in the database
List<Share> shareList = shareRepository.findAll();
assertThat(shareList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
public void deleteShare() throws Exception {
// Initialize the database
shareRepository.saveAndFlush(share);
int databaseSizeBeforeDelete = shareRepository.findAll().size();
// Delete the share
restShareMockMvc.perform(
delete("/api/shares/{id}", share.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest());
// Validate the database is unchanged
List<Share> shareList = shareRepository.findAll();
assertThat(shareList).hasSize(databaseSizeBeforeDelete);
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Share.class);
Share share1 = new Share();
share1.setId(1L);
Share share2 = new Share();
share2.setId(share1.getId());
assertThat(share1).isEqualTo(share2);
share2.setId(2L);
assertThat(share1).isNotEqualTo(share2);
share1.setId(null);
assertThat(share1).isNotEqualTo(share2);
}
@Test
@Transactional
public void dtoEqualsVerifier() throws Exception {
TestUtil.equalsVerifier(ShareDTO.class);
ShareDTO shareDTO1 = new ShareDTO();
shareDTO1.setId(1L);
ShareDTO shareDTO2 = new ShareDTO();
assertThat(shareDTO1).isNotEqualTo(shareDTO2);
shareDTO2.setId(shareDTO1.getId());
assertThat(shareDTO1).isEqualTo(shareDTO2);
shareDTO2.setId(2L);
assertThat(shareDTO1).isNotEqualTo(shareDTO2);
shareDTO1.setId(null);
assertThat(shareDTO1).isNotEqualTo(shareDTO2);
}
@Test
@Transactional
public void testEntityFromId() {
assertThat(shareMapper.fromId(42L).getId()).isEqualTo(42);
assertThat(shareMapper.fromId(null)).isNull();
}
}

View File

@@ -1,147 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.web.rest;
import static org.assertj.core.api.Assertions.assertThat;
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;
/**
* 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

@@ -1,130 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.web.rest;
import static org.hamcrest.Matchers.isEmptyString;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
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;
/**
* 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

@@ -1,622 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.web.rest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
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 java.time.Instant;
import java.util.*;
import javax.persistence.EntityManager;
/**
* 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

@@ -1,552 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.web.rest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.hostsharing.hsadminng.HsadminNgApp;
import org.hostsharing.hsadminng.domain.User;
import org.hostsharing.hsadminng.domain.UserRoleAssignment;
import org.hostsharing.hsadminng.repository.UserRoleAssignmentRepository;
import org.hostsharing.hsadminng.service.UserRoleAssignmentQueryService;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.Admin;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerTechnicalContact;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextFake;
import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator;
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.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 org.springframework.validation.Validator;
import java.util.List;
import javax.persistence.EntityManager;
/**
* Test class for the UserRoleAssignmentResource REST controller.
*
* @see UserRoleAssignmentResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { HsadminNgApp.class })
public class UserRoleAssignmentResourceIntTest {
private static final String DEFAULT_ENTITY_TYPE_ID = "AAAAAAAAAA";
private static final String UPDATED_ENTITY_TYPE_ID = "BBBBBBBBBB";
private static final Long DEFAULT_ENTITY_OBJECT_ID = 1L;
private static final Long UPDATED_ENTITY_OBJECT_ID = 2L;
private static final Role DEFAULT_ASSIGNED_ROLE = CustomerTechnicalContact.ROLE;
private static final Role UPDATED_ASSIGNED_ROLE = CustomerContractualContact.ROLE;
@Autowired
private UserRoleAssignmentRepository userRoleAssignmentRepository;
@Autowired
private UserRoleAssignmentService userRoleAssignmentService;
@Autowired
private UserRoleAssignmentQueryService userRoleAssignmentQueryService;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
@Autowired
private Validator validator;
private MockMvc restUserRoleAssignmentMockMvc;
private UserRoleAssignment userRoleAssignment;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final UserRoleAssignmentResource userRoleAssignmentResource = new UserRoleAssignmentResource(
userRoleAssignmentService,
userRoleAssignmentQueryService);
this.restUserRoleAssignmentMockMvc = MockMvcBuilders.standaloneSetup(userRoleAssignmentResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator)
.build();
SecurityContextFake.havingAuthenticatedUser().withAuthority(Role.Supporter.ROLE.authority());
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static UserRoleAssignment createEntity(EntityManager em) {
User user = UserResourceIntTest.createEntity(em);
em.persist(user);
em.flush();
return new UserRoleAssignment()
.entityTypeId(DEFAULT_ENTITY_TYPE_ID)
.entityObjectId(DEFAULT_ENTITY_OBJECT_ID)
.user(user)
.assignedRole(DEFAULT_ASSIGNED_ROLE);
}
@Before
public void initTest() {
userRoleAssignment = createEntity(em);
}
@Test
@Transactional
public void createUserRoleAssignment() throws Exception {
int databaseSizeBeforeCreate = userRoleAssignmentRepository.findAll().size();
// Create the UserRoleAssignment
SecurityContextFake.havingAuthenticatedUser().withAuthority(Admin.ROLE.authority());
restUserRoleAssignmentMockMvc.perform(
post("/api/user-role-assignments")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userRoleAssignment)))
.andExpect(status().isCreated());
// Validate the UserRoleAssignment in the database
List<UserRoleAssignment> userRoleAssignmentList = userRoleAssignmentRepository.findAll();
assertThat(userRoleAssignmentList).hasSize(databaseSizeBeforeCreate + 1);
UserRoleAssignment testUserRoleAssignment = userRoleAssignmentList.get(userRoleAssignmentList.size() - 1);
assertThat(testUserRoleAssignment.getEntityTypeId()).isEqualTo(DEFAULT_ENTITY_TYPE_ID);
assertThat(testUserRoleAssignment.getEntityObjectId()).isEqualTo(DEFAULT_ENTITY_OBJECT_ID);
assertThat(testUserRoleAssignment.getAssignedRole().name()).isEqualTo(DEFAULT_ASSIGNED_ROLE.name());
assertThat(testUserRoleAssignment.getAssignedRole()).isEqualTo(DEFAULT_ASSIGNED_ROLE);
}
@Test
@Transactional
public void createUserRoleAssignmentWithExistingId() throws Exception {
int databaseSizeBeforeCreate = userRoleAssignmentRepository.findAll().size();
// Create the UserRoleAssignment with an existing ID
userRoleAssignment.setId(1L);
// An entity with an existing ID cannot be created, so this API call must fail
restUserRoleAssignmentMockMvc.perform(
post("/api/user-role-assignments")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userRoleAssignment)))
.andExpect(status().isBadRequest());
// Validate the UserRoleAssignment in the database
List<UserRoleAssignment> userRoleAssignmentList = userRoleAssignmentRepository.findAll();
assertThat(userRoleAssignmentList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void checkEntityTypeIdIsRequired() throws Exception {
int databaseSizeBeforeTest = userRoleAssignmentRepository.findAll().size();
// set the field null
userRoleAssignment.setEntityTypeId(null);
// Create the UserRoleAssignment, which fails.
restUserRoleAssignmentMockMvc.perform(
post("/api/user-role-assignments")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userRoleAssignment)))
.andExpect(status().isBadRequest());
List<UserRoleAssignment> userRoleAssignmentList = userRoleAssignmentRepository.findAll();
assertThat(userRoleAssignmentList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkEntityObjectIdIsRequired() throws Exception {
int databaseSizeBeforeTest = userRoleAssignmentRepository.findAll().size();
// set the field null
userRoleAssignment.setEntityObjectId(null);
// Create the UserRoleAssignment, which fails.
restUserRoleAssignmentMockMvc.perform(
post("/api/user-role-assignments")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userRoleAssignment)))
.andExpect(status().isBadRequest());
List<UserRoleAssignment> userRoleAssignmentList = userRoleAssignmentRepository.findAll();
assertThat(userRoleAssignmentList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkAssignedRoleIsRequired() throws Exception {
int databaseSizeBeforeTest = userRoleAssignmentRepository.findAll().size();
// set the field null
userRoleAssignment.setAssignedRole(null);
// Create the UserRoleAssignment, which fails.
restUserRoleAssignmentMockMvc.perform(
post("/api/user-role-assignments")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userRoleAssignment)))
.andExpect(status().isBadRequest());
List<UserRoleAssignment> userRoleAssignmentList = userRoleAssignmentRepository.findAll();
assertThat(userRoleAssignmentList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void getAllUserRoleAssignments() throws Exception {
// Initialize the database
userRoleAssignmentRepository.saveAndFlush(userRoleAssignment);
// Get all the userRoleAssignmentList
restUserRoleAssignmentMockMvc.perform(get("/api/user-role-assignments?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(userRoleAssignment.getId().intValue())))
.andExpect(jsonPath("$.[*].entityTypeId").value(hasItem(DEFAULT_ENTITY_TYPE_ID)))
.andExpect(jsonPath("$.[*].entityObjectId").value(hasItem(DEFAULT_ENTITY_OBJECT_ID.intValue())))
.andExpect(jsonPath("$.[*].assignedRole").value(hasItem(DEFAULT_ASSIGNED_ROLE.name())));
}
@Test
@Transactional
public void getUserRoleAssignment() throws Exception {
// Initialize the database
userRoleAssignmentRepository.saveAndFlush(userRoleAssignment);
// Get the userRoleAssignment
restUserRoleAssignmentMockMvc.perform(get("/api/user-role-assignments/{id}", userRoleAssignment.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(userRoleAssignment.getId().intValue()))
.andExpect(jsonPath("$.entityTypeId").value(DEFAULT_ENTITY_TYPE_ID))
.andExpect(jsonPath("$.entityObjectId").value(DEFAULT_ENTITY_OBJECT_ID.intValue()))
.andExpect(jsonPath("$.assignedRole").value(DEFAULT_ASSIGNED_ROLE.name()));
}
@Test
@Transactional
public void getAllUserRoleAssignmentsByEntityTypeIdIsEqualToSomething() throws Exception {
// Initialize the database
userRoleAssignmentRepository.saveAndFlush(userRoleAssignment);
// Get all the userRoleAssignmentList where entityTypeId equals to DEFAULT_ENTITY_TYPE_ID
defaultUserRoleAssignmentShouldBeFound("entityTypeId.equals=" + DEFAULT_ENTITY_TYPE_ID);
// Get all the userRoleAssignmentList where entityTypeId equals to UPDATED_ENTITY_TYPE_ID
defaultUserRoleAssignmentShouldNotBeFound("entityTypeId.equals=" + UPDATED_ENTITY_TYPE_ID);
}
@Test
@Transactional
public void getAllUserRoleAssignmentsByEntityTypeIdIsInShouldWork() throws Exception {
// Initialize the database
userRoleAssignmentRepository.saveAndFlush(userRoleAssignment);
// Get all the userRoleAssignmentList where entityTypeId in DEFAULT_ENTITY_TYPE_ID or UPDATED_ENTITY_TYPE_ID
defaultUserRoleAssignmentShouldBeFound("entityTypeId.in=" + DEFAULT_ENTITY_TYPE_ID + "," + UPDATED_ENTITY_TYPE_ID);
// Get all the userRoleAssignmentList where entityTypeId equals to UPDATED_ENTITY_TYPE_ID
defaultUserRoleAssignmentShouldNotBeFound("entityTypeId.in=" + UPDATED_ENTITY_TYPE_ID);
}
@Test
@Transactional
public void getAllUserRoleAssignmentsByEntityTypeIdIsNullOrNotNull() throws Exception {
// Initialize the database
userRoleAssignmentRepository.saveAndFlush(userRoleAssignment);
// Get all the userRoleAssignmentList where entityTypeId is not null
defaultUserRoleAssignmentShouldBeFound("entityTypeId.specified=true");
// Get all the userRoleAssignmentList where entityTypeId is null
defaultUserRoleAssignmentShouldNotBeFound("entityTypeId.specified=false");
}
@Test
@Transactional
public void getAllUserRoleAssignmentsByEntityObjectIdIsEqualToSomething() throws Exception {
// Initialize the database
userRoleAssignmentRepository.saveAndFlush(userRoleAssignment);
// Get all the userRoleAssignmentList where entityObjectId equals to DEFAULT_ENTITY_OBJECT_ID
defaultUserRoleAssignmentShouldBeFound("entityObjectId.equals=" + DEFAULT_ENTITY_OBJECT_ID);
// Get all the userRoleAssignmentList where entityObjectId equals to UPDATED_ENTITY_OBJECT_ID
defaultUserRoleAssignmentShouldNotBeFound("entityObjectId.equals=" + UPDATED_ENTITY_OBJECT_ID);
}
@Test
@Transactional
public void getAllUserRoleAssignmentsByEntityObjectIdIsInShouldWork() throws Exception {
// Initialize the database
userRoleAssignmentRepository.saveAndFlush(userRoleAssignment);
// Get all the userRoleAssignmentList where entityObjectId in DEFAULT_ENTITY_OBJECT_ID or UPDATED_ENTITY_OBJECT_ID
defaultUserRoleAssignmentShouldBeFound(
"entityObjectId.in=" + DEFAULT_ENTITY_OBJECT_ID + "," + UPDATED_ENTITY_OBJECT_ID);
// Get all the userRoleAssignmentList where entityObjectId equals to UPDATED_ENTITY_OBJECT_ID
defaultUserRoleAssignmentShouldNotBeFound("entityObjectId.in=" + UPDATED_ENTITY_OBJECT_ID);
}
@Test
@Transactional
public void getAllUserRoleAssignmentsByEntityObjectIdIsNullOrNotNull() throws Exception {
// Initialize the database
userRoleAssignmentRepository.saveAndFlush(userRoleAssignment);
// Get all the userRoleAssignmentList where entityObjectId is not null
defaultUserRoleAssignmentShouldBeFound("entityObjectId.specified=true");
// Get all the userRoleAssignmentList where entityObjectId is null
defaultUserRoleAssignmentShouldNotBeFound("entityObjectId.specified=false");
}
@Test
@Transactional
public void getAllUserRoleAssignmentsByEntityObjectIdIsGreaterThanOrEqualToSomething() throws Exception {
// Initialize the database
userRoleAssignmentRepository.saveAndFlush(userRoleAssignment);
// Get all the userRoleAssignmentList where entityObjectId greater than or equals to DEFAULT_ENTITY_OBJECT_ID
defaultUserRoleAssignmentShouldBeFound("entityObjectId.greaterOrEqualThan=" + DEFAULT_ENTITY_OBJECT_ID);
// Get all the userRoleAssignmentList where entityObjectId greater than or equals to UPDATED_ENTITY_OBJECT_ID
defaultUserRoleAssignmentShouldNotBeFound("entityObjectId.greaterOrEqualThan=" + UPDATED_ENTITY_OBJECT_ID);
}
@Test
@Transactional
public void getAllUserRoleAssignmentsByEntityObjectIdIsLessThanSomething() throws Exception {
// Initialize the database
userRoleAssignmentRepository.saveAndFlush(userRoleAssignment);
// Get all the userRoleAssignmentList where entityObjectId less than or equals to DEFAULT_ENTITY_OBJECT_ID
defaultUserRoleAssignmentShouldNotBeFound("entityObjectId.lessThan=" + DEFAULT_ENTITY_OBJECT_ID);
// Get all the userRoleAssignmentList where entityObjectId less than or equals to UPDATED_ENTITY_OBJECT_ID
defaultUserRoleAssignmentShouldBeFound("entityObjectId.lessThan=" + UPDATED_ENTITY_OBJECT_ID);
}
@Test
@Transactional
public void getAllUserRoleAssignmentsByAssignedRoleIsEqualToSomething() throws Exception {
// Initialize the database
userRoleAssignmentRepository.saveAndFlush(userRoleAssignment);
// Get all the userRoleAssignmentList where assignedRole equals to DEFAULT_ASSIGNED_ROLE
defaultUserRoleAssignmentShouldBeFound("assignedRole.equals=" + DEFAULT_ASSIGNED_ROLE.name());
// Get all the userRoleAssignmentList where assignedRole equals to UPDATED_ASSIGNED_ROLE
defaultUserRoleAssignmentShouldNotBeFound("assignedRole.equals=" + UPDATED_ASSIGNED_ROLE.name());
}
@Test
@Transactional
public void getAllUserRoleAssignmentsByAssignedRoleIsInShouldWork() throws Exception {
// Initialize the database
userRoleAssignmentRepository.saveAndFlush(userRoleAssignment);
// Get all the userRoleAssignmentList where assignedRole in DEFAULT_ASSIGNED_ROLE or UPDATED_ASSIGNED_ROLE
defaultUserRoleAssignmentShouldBeFound(
"assignedRole.in=" + DEFAULT_ASSIGNED_ROLE.name() + "," + UPDATED_ASSIGNED_ROLE.name());
// Get all the userRoleAssignmentList where assignedRole equals to UPDATED_ASSIGNED_ROLE
defaultUserRoleAssignmentShouldNotBeFound("assignedRole.in=" + UPDATED_ASSIGNED_ROLE.name());
}
@Test
@Transactional
public void getAllUserRoleAssignmentsByAssignedRoleIsNullOrNotNull() throws Exception {
// Initialize the database
userRoleAssignmentRepository.saveAndFlush(userRoleAssignment);
// Get all the userRoleAssignmentList where assignedRole is not null
defaultUserRoleAssignmentShouldBeFound("assignedRole.specified=true");
// Get all the userRoleAssignmentList where assignedRole is null
defaultUserRoleAssignmentShouldNotBeFound("assignedRole.specified=false");
}
@Test
@Transactional
public void getAllUserRoleAssignmentsByUserIsEqualToSomething() throws Exception {
// Initialize the database
User user = UserResourceIntTest.createEntity(em);
em.persist(user);
em.flush();
userRoleAssignment.setUser(user);
userRoleAssignmentRepository.saveAndFlush(userRoleAssignment);
Long userId = user.getId();
// Get all the userRoleAssignmentList where user equals to userId
defaultUserRoleAssignmentShouldBeFound("userId.equals=" + userId);
// Get all the userRoleAssignmentList where user equals to userId + 1
defaultUserRoleAssignmentShouldNotBeFound("userId.equals=" + (userId + 1));
}
/**
* Executes the search, and checks that the default entity is returned
*/
private void defaultUserRoleAssignmentShouldBeFound(String filter) throws Exception {
restUserRoleAssignmentMockMvc.perform(get("/api/user-role-assignments?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(userRoleAssignment.getId().intValue())))
.andExpect(jsonPath("$.[*].entityTypeId").value(hasItem(DEFAULT_ENTITY_TYPE_ID)))
.andExpect(jsonPath("$.[*].entityObjectId").value(hasItem(DEFAULT_ENTITY_OBJECT_ID.intValue())))
.andExpect(jsonPath("$.[*].assignedRole").value(hasItem(DEFAULT_ASSIGNED_ROLE.name())));
// Check, that the count call also returns 1
restUserRoleAssignmentMockMvc.perform(get("/api/user-role-assignments/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("1"));
}
/**
* Executes the search, and checks that the default entity is not returned
*/
private void defaultUserRoleAssignmentShouldNotBeFound(String filter) throws Exception {
restUserRoleAssignmentMockMvc.perform(get("/api/user-role-assignments?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
// Check, that the count call also returns 0
restUserRoleAssignmentMockMvc.perform(get("/api/user-role-assignments/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("0"));
}
@Test
@Transactional
public void getNonExistingUserRoleAssignment() throws Exception {
// Get the userRoleAssignment
restUserRoleAssignmentMockMvc.perform(get("/api/user-role-assignments/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateUserRoleAssignment() throws Exception {
// Initialize the database
userRoleAssignmentService.save(userRoleAssignment);
int databaseSizeBeforeUpdate = userRoleAssignmentRepository.findAll().size();
// Update the userRoleAssignment
SecurityContextFake.havingAuthenticatedUser().withAuthority(Admin.ROLE.authority());
UserRoleAssignment updatedUserRoleAssignment = userRoleAssignmentRepository.findById(userRoleAssignment.getId()).get();
// Disconnect from session so that the updates on updatedUserRoleAssignment are not directly saved in db
em.detach(updatedUserRoleAssignment);
updatedUserRoleAssignment
.entityTypeId(UPDATED_ENTITY_TYPE_ID)
.entityObjectId(UPDATED_ENTITY_OBJECT_ID)
.assignedRole(UPDATED_ASSIGNED_ROLE);
restUserRoleAssignmentMockMvc.perform(
put("/api/user-role-assignments")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(updatedUserRoleAssignment)))
.andExpect(status().isOk());
// Validate the UserRoleAssignment in the database
List<UserRoleAssignment> userRoleAssignmentList = userRoleAssignmentRepository.findAll();
assertThat(userRoleAssignmentList).hasSize(databaseSizeBeforeUpdate);
UserRoleAssignment testUserRoleAssignment = userRoleAssignmentList.get(userRoleAssignmentList.size() - 1);
assertThat(testUserRoleAssignment.getEntityTypeId()).isEqualTo(UPDATED_ENTITY_TYPE_ID);
assertThat(testUserRoleAssignment.getEntityObjectId()).isEqualTo(UPDATED_ENTITY_OBJECT_ID);
assertThat(testUserRoleAssignment.getAssignedRole().name()).isEqualTo(UPDATED_ASSIGNED_ROLE.name());
assertThat(testUserRoleAssignment.getAssignedRole()).isEqualTo(UPDATED_ASSIGNED_ROLE);
}
@Test
@Transactional
public void updateNonExistingUserRoleAssignment() throws Exception {
int databaseSizeBeforeUpdate = userRoleAssignmentRepository.findAll().size();
// Create the UserRoleAssignment
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restUserRoleAssignmentMockMvc.perform(
put("/api/user-role-assignments")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userRoleAssignment)))
.andExpect(status().isBadRequest());
// Validate the UserRoleAssignment in the database
List<UserRoleAssignment> userRoleAssignmentList = userRoleAssignmentRepository.findAll();
assertThat(userRoleAssignmentList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
public void deleteUserRoleAssignment() throws Exception {
// Initialize the database
userRoleAssignmentService.save(userRoleAssignment);
int databaseSizeBeforeDelete = userRoleAssignmentRepository.findAll().size();
// Delete the userRoleAssignment
restUserRoleAssignmentMockMvc.perform(
delete("/api/user-role-assignments/{id}", userRoleAssignment.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<UserRoleAssignment> userRoleAssignmentList = userRoleAssignmentRepository.findAll();
assertThat(userRoleAssignmentList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(UserRoleAssignment.class);
UserRoleAssignment userRoleAssignment1 = new UserRoleAssignment();
userRoleAssignment1.setId(1L);
UserRoleAssignment userRoleAssignment2 = new UserRoleAssignment();
userRoleAssignment2.setId(userRoleAssignment1.getId());
assertThat(userRoleAssignment1).isEqualTo(userRoleAssignment2);
userRoleAssignment2.setId(2L);
assertThat(userRoleAssignment1).isNotEqualTo(userRoleAssignment2);
userRoleAssignment1.setId(null);
assertThat(userRoleAssignment1).isNotEqualTo(userRoleAssignment2);
}
}

View File

@@ -1,58 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.web.rest;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.assertj.core.api.ThrowableAssert.catchThrowable;
import org.hostsharing.hsadminng.domain.UserRoleAssignment;
import org.hostsharing.hsadminng.service.dto.UserRoleAssignmentUnitTest;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
// Currently this class tests mostly special 'bad paths'
// which make little sense to test in *ResourceIntTest.
public class UserRoleAssignmentResourceUnitTest {
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@InjectMocks
private UserRoleAssignmentResource userRoleAssignmentResource;
@Test
public void createUserRoleAssignmentWithoutIdThrowsBadRequestException() {
// given
final UserRoleAssignment givenEntity = UserRoleAssignmentUnitTest.createSomeUserRoleAssignment(null);
// when
final Throwable actual = catchThrowable(() -> userRoleAssignmentResource.updateUserRoleAssignment(givenEntity));
// then
assertThat(actual).isInstanceOfSatisfying(BadRequestAlertException.class, bre -> {
assertThat(bre.getErrorKey()).isEqualTo("idnull");
assertThat(bre.getParam()).isEqualTo("userRoleAssignment");
});
}
@Test
public void createUserRoleAssignmentWithIdThrowsBadRequestException() {
// given
final UserRoleAssignment givenEntity = UserRoleAssignmentUnitTest.createSomeUserRoleAssignment(1L);
// when
final Throwable actual = catchThrowable(() -> userRoleAssignmentResource.createUserRoleAssignment(givenEntity));
// then
assertThat(actual).isInstanceOfSatisfying(BadRequestAlertException.class, bre -> {
assertThat(bre.getErrorKey()).isEqualTo("idexists");
assertThat(bre.getParam()).isEqualTo("userRoleAssignment");
});
}
}

View File

@@ -1,152 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.web.rest.errors;
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;
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;
/**
* 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

@@ -1,88 +0,0 @@
// Licensed under Apache-2.0
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 java.util.HashMap;
import java.util.Map;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
@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

@@ -1,45 +0,0 @@
// Licensed under Apache-2.0
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 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;
import java.util.ArrayList;
import java.util.List;
/**
* 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));
}
}