1
0

gw spotlessApply to latest revision, preparation for re-merging generated

This commit is contained in:
Michael Hoennig
2019-04-30 12:21:33 +02:00
parent a5f69a8cad
commit b5d50acfbd
180 changed files with 3756 additions and 2772 deletions
src
main
java
org
hostsharing
hsadminng
ApplicationWebXml.javaHsadminNgApp.java
aop
config
domain
repository
security
service
web
test
java
org
hostsharing
hsadminng
config
cucumber
repository
security
service
web

@@ -1,13 +1,23 @@
// 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.apache.commons.io.FilenameUtils;
import org.h2.server.web.WebServlet;
import org.junit.Before;
import org.junit.Test;
@@ -20,17 +30,9 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.xnio.OptionMap;
import javax.servlet.*;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import javax.servlet.*;
/**
* Unit tests for the WebConfigurer class.
@@ -51,9 +53,11 @@ public class WebConfigurerTest {
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.class))
.when(servletContext).addFilter(anyString(), any(Filter.class));
.when(servletContext)
.addFilter(anyString(), any(Filter.class));
doReturn(mock(ServletRegistration.Dynamic.class))
.when(servletContext).addServlet(anyString(), any(Servlet.class));
.when(servletContext)
.addServlet(anyString(), any(Servlet.class));
env = new MockEnvironment();
props = new JHipsterProperties();
@@ -117,25 +121,25 @@ public class WebConfigurerTest {
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
.addFilters(webConfigurer.corsFilter())
.build();
.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"));
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"));
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
@@ -147,14 +151,14 @@ public class WebConfigurerTest {
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
.addFilters(webConfigurer.corsFilter())
.build();
.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));
get("/test/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
@@ -162,14 +166,14 @@ public class WebConfigurerTest {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
.addFilters(webConfigurer.corsFilter())
.build();
.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));
get("/api/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
@@ -177,13 +181,13 @@ public class WebConfigurerTest {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
.addFilters(webConfigurer.corsFilter())
.build();
.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));
get("/api/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}

@@ -1,3 +1,4 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.config;
import org.springframework.web.bind.annotation.GetMapping;

@@ -1,8 +1,13 @@
// 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;
@@ -16,9 +21,6 @@ import org.springframework.transaction.annotation.Transactional;
import java.time.*;
import java.time.format.DateTimeFormatter;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for the UTC Hibernate configuration.
*/
@@ -48,15 +50,15 @@ public class HibernateTimeZoneTest {
dateTimeWrapper.setLocalDate(LocalDate.parse("2016-09-10"));
dateTimeFormatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss.S")
.withZone(ZoneId.of("UTC"));
.ofPattern("yyyy-MM-dd HH:mm:ss.S")
.withZone(ZoneId.of("UTC"));
timeFormatter = DateTimeFormatter
.ofPattern("HH:mm:ss")
.withZone(ZoneId.of("UTC"));
.ofPattern("HH:mm:ss")
.withZone(ZoneId.of("UTC"));
dateFormatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd");
.ofPattern("yyyy-MM-dd");
}
@Test
@@ -79,9 +81,9 @@ public class HibernateTimeZoneTest {
String request = generateSqlRequest("local_date_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper
.getLocalDateTime()
.atZone(ZoneId.systemDefault())
.format(dateTimeFormatter);
.getLocalDateTime()
.atZone(ZoneId.systemDefault())
.format(dateTimeFormatter);
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}
@@ -94,8 +96,8 @@ public class HibernateTimeZoneTest {
String request = generateSqlRequest("offset_date_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper
.getOffsetDateTime()
.format(dateTimeFormatter);
.getOffsetDateTime()
.format(dateTimeFormatter);
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}
@@ -108,8 +110,8 @@ public class HibernateTimeZoneTest {
String request = generateSqlRequest("zoned_date_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper
.getZonedDateTime()
.format(dateTimeFormatter);
.getZonedDateTime()
.format(dateTimeFormatter);
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}
@@ -122,10 +124,10 @@ public class HibernateTimeZoneTest {
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);
.getLocalTime()
.atDate(LocalDate.of(1970, Month.JANUARY, 1))
.atZone(ZoneId.systemDefault())
.format(timeFormatter);
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}
@@ -138,11 +140,11 @@ public class HibernateTimeZoneTest {
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);
.getOffsetTime()
.toLocalTime()
.atDate(LocalDate.of(1970, Month.JANUARY, 1))
.atZone(ZoneId.systemDefault())
.format(timeFormatter);
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}
@@ -155,8 +157,8 @@ public class HibernateTimeZoneTest {
String request = generateSqlRequest("local_date", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper
.getLocalDate()
.format(dateFormatter);
.getLocalDate()
.format(dateFormatter);
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}

@@ -1,7 +1,10 @@
// 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;
@@ -12,7 +15,7 @@ import org.springframework.test.context.web.WebAppConfiguration;
public class CucumberContextConfiguration {
@Before
public void setup_cucumber_spring_context(){
public void setup_cucumber_spring_context() {
// Dummy method so cucumber will recognize this class as glue
// and use its context configuration.
}

@@ -1,13 +1,13 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.cucumber;
import org.junit.runner.RunWith;
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 {
public class CucumberTest {
}

@@ -1,3 +1,4 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.cucumber.stepdefs;
import org.springframework.test.web.servlet.ResultActions;

@@ -1,5 +1,11 @@
// 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;
@@ -9,11 +15,6 @@ import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.hostsharing.hsadminng.web.rest.UserResource;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
public class UserStepDefs extends StepDefs {
@Autowired
@@ -28,15 +29,16 @@ public class UserStepDefs extends StepDefs {
@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));
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));
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
}
@Then("his last name is {string}")

@@ -1,9 +1,14 @@
// 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;
@@ -16,14 +21,12 @@ import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpSession;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hostsharing.hsadminng.repository.CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH;
import javax.servlet.http.HttpSession;
/**
* Test class for the CustomAuditEventRepository class.

@@ -1,12 +1,16 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.repository;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
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.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;
@@ -16,13 +20,10 @@ import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HsadminNgApp.class)
@Transactional
public class MembershipRepositoryIntTest {
public class MembershipRepositoryIntTest {
@Autowired
private CustomerRepository customerRepository;
@@ -36,7 +37,8 @@ public class MembershipRepositoryIntTest {
final Customer givenCustomerWithUncancelledMembership = createCustomerWithMembership("2011-08-18", null);
// when
boolean actual = membershipRepository.hasUncancelledMembershipForCustomer(givenCustomerWithUncancelledMembership.getId());
boolean actual = membershipRepository
.hasUncancelledMembershipForCustomer(givenCustomerWithUncancelledMembership.getId());
// then
assertThat(actual).isTrue();

@@ -1,10 +1,12 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.repository.timezone;
import javax.persistence.*;
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 {
@@ -122,11 +124,11 @@ public class DateTimeWrapper implements Serializable {
@Override
public String toString() {
return "TimeZoneTest{" +
"id=" + id +
", instant=" + instant +
", localDateTime=" + localDateTime +
", offsetDateTime=" + offsetDateTime +
", zonedDateTime=" + zonedDateTime +
'}';
"id=" + id +
", instant=" + instant +
", localDateTime=" + localDateTime +
", offsetDateTime=" + offsetDateTime +
", zonedDateTime=" + zonedDateTime +
'}';
}
}

@@ -1,3 +1,4 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.repository.timezone;
import org.springframework.data.jpa.repository.JpaRepository;

@@ -1,5 +1,8 @@
// 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;
@@ -18,8 +21,6 @@ import org.springframework.transaction.annotation.Transactional;
import java.util.Locale;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test class for DomainUserDetailsService.
*
@@ -107,7 +108,7 @@ public class DomainUserDetailsServiceIntTest {
@Test(expected = UsernameNotFoundException.class)
@Transactional
public void assertThatUserCanNotBeFoundByEmailIgnoreCase() {
domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL.toUpperCase(Locale.ENGLISH));
domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL.toUpperCase(Locale.ENGLISH));
}
@Test

@@ -1,5 +1,8 @@
// 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;
@@ -11,8 +14,6 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test class for the SecurityUtils utility class.
*

@@ -1,6 +1,10 @@
// 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;
@@ -18,8 +22,6 @@ import org.springframework.test.util.ReflectionTestUtils;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
public class JWTFilterTest {
private TokenProvider tokenProvider;
@@ -30,9 +32,13 @@ public class JWTFilterTest {
public void setup() {
JHipsterProperties jHipsterProperties = new JHipsterProperties();
tokenProvider = new TokenProvider(jHipsterProperties);
ReflectionTestUtils.setField(tokenProvider, "key",
Keys.hmacShaKeyFor(Decoders.BASE64
.decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")));
ReflectionTestUtils.setField(
tokenProvider,
"key",
Keys.hmacShaKeyFor(
Decoders.BASE64
.decode(
"fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")));
ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", 60000);
jwtFilter = new JWTFilter(tokenProvider);
@@ -42,10 +48,9 @@ public class JWTFilterTest {
@Test
public void testJWTFilter() throws Exception {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
"test-user",
"test-password",
Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
);
"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);
@@ -97,10 +102,9 @@ public class JWTFilterTest {
@Test
public void testJWTFilterWrongScheme() throws Exception {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
"test-user",
"test-password",
Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
);
"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);

@@ -1,9 +1,15 @@
// 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 java.security.Key;
import java.util.*;
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;
@@ -14,13 +20,8 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.test.util.ReflectionTestUtils;
import io.github.jhipster.config.JHipsterProperties;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import static org.assertj.core.api.Assertions.assertThat;
import java.security.Key;
import java.util.*;
public class TokenProviderTest {
@@ -33,8 +34,10 @@ public class TokenProviderTest {
public void setup() {
jHipsterProperties = Mockito.mock(JHipsterProperties.class);
tokenProvider = new TokenProvider(jHipsterProperties);
key = Keys.hmacShaKeyFor(Decoders.BASE64
.decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));
key = Keys.hmacShaKeyFor(
Decoders.BASE64
.decode(
"fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));
ReflectionTestUtils.setField(tokenProvider, "key", key);
ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", ONE_MINUTE);
@@ -93,19 +96,21 @@ public class TokenProviderTest {
private String createUnsupportedToken() {
return Jwts.builder()
.setPayload("payload")
.signWith(key, SignatureAlgorithm.HS512)
.compact();
.setPayload("payload")
.signWith(key, SignatureAlgorithm.HS512)
.compact();
}
private String createTokenWithDifferentSignature() {
Key otherKey = Keys.hmacShaKeyFor(Decoders.BASE64
.decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));
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();
.setSubject("anonymous")
.signWith(otherKey, SignatureAlgorithm.HS512)
.setExpiration(new Date(new Date().getTime() + ONE_MINUTE))
.compact();
}
}

@@ -1,12 +1,20 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service;
import org.apache.commons.lang3.RandomUtils;
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;
@@ -15,15 +23,9 @@ import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import javax.persistence.EntityManager;
import java.math.BigDecimal;
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 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)!
@@ -55,13 +57,15 @@ public class AssetServiceUnitTest {
@Test
public void deleteIsRejectedForAssetTransactions() {
// when
final Throwable throwException = catchThrowableOfType(() -> assetService.delete(RandomUtils.nextLong()), BadRequestAlertException.class);
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"));
new BadRequestAlertException("Asset transactions are immutable", "asset", "assetTransactionImmutable"));
}
@Test
@@ -84,14 +88,18 @@ public class AssetServiceUnitTest {
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);
doThrow(new BadRequestAlertException("Some Dummy Test Violation", "asset", "assetInvalidTestDummy"))
.when(assetValidator)
.validate(givenAssetDTO);
// when
final Throwable throwException = catchThrowableOfType(() -> assetService.save(givenAssetDTO), BadRequestAlertException.class);
final Throwable throwException = catchThrowableOfType(
() -> assetService.save(givenAssetDTO),
BadRequestAlertException.class);
// then
assertThat(throwException).isEqualToComparingFieldByField(
new BadRequestAlertException("Some Dummy Test Violation", "asset", "assetInvalidTestDummy"));
new BadRequestAlertException("Some Dummy Test Violation", "asset", "assetInvalidTestDummy"));
}
@Test
@@ -114,14 +122,18 @@ public class AssetServiceUnitTest {
// 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);
doThrow(new BadRequestAlertException("Some Dummy Test Violation", "asset", "assetInvalidTestDummy"))
.when(assetValidator)
.validate(givenAssetDTO);
// when
final Throwable throwException = catchThrowableOfType(() -> assetService.save(givenAssetDTO), BadRequestAlertException.class);
final Throwable throwException = catchThrowableOfType(
() -> assetService.save(givenAssetDTO),
BadRequestAlertException.class);
// then
assertThat(throwException).isEqualToComparingFieldByField(
new BadRequestAlertException("Some Dummy Test Violation", "asset", "assetInvalidTestDummy"));
new BadRequestAlertException("Some Dummy Test Violation", "asset", "assetInvalidTestDummy"));
}
// --- only test fixture code below ---
@@ -130,7 +142,8 @@ public class AssetServiceUnitTest {
return RandomUtils.nextInt();
}
// HINT: This rather complicated setup indicates that the method AssetService::save breaks the single responsibility principle.
// 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);

@@ -1,20 +1,23 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service;
import com.google.common.collect.ImmutableList;
import org.apache.commons.lang3.RandomUtils;
import org.assertj.core.api.AbstractThrowableAssert;
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;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
public class AssetValidatorUnitTest {
private AssetValidator assetValidator = new AssetValidator();
@@ -23,173 +26,250 @@ public class AssetValidatorUnitTest {
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();
.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)) {
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();
.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();
.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"));
.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"));
.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"));
.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"));
.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"));
.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"));
.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"));
.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"));
.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"));
.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"));
.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"));
.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"));
.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"));
.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"));
.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 {
@@ -226,7 +306,7 @@ public class AssetValidatorUnitTest {
return this;
}
GivenAssetValidationTestCase when(final Consumer<AssetDTO> statement) {
GivenAssetValidationTestCase when(final Consumer<AssetDTO> statement) {
actualException = catchThrowableOfType(() -> assetValidator.validate(assetDto), BadRequestAlertException.class);
return this;
}

@@ -1,9 +1,16 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service;
import org.hostsharing.hsadminng.config.Constants;
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;
@@ -19,15 +26,12 @@ 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;
import java.io.ByteArrayOutputStream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HsadminNgApp.class)
@@ -129,7 +133,8 @@ public class MailServiceIntTest {
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.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");
}

@@ -1,10 +1,17 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service;
import org.apache.commons.lang3.RandomUtils;
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;
@@ -12,11 +19,6 @@ import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
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.*;
public class MembershipServiceUnitTest {
@Rule
@@ -34,22 +36,29 @@ public class MembershipServiceUnitTest {
@Test
public void deleteIsRejectedForMembership() {
// when
final Throwable throwException = catchThrowableOfType(() -> membershipService.delete(RandomUtils.nextLong()), BadRequestAlertException.class);
final Throwable throwException = catchThrowableOfType(
() -> membershipService.delete(RandomUtils.nextLong()),
BadRequestAlertException.class);
// then
assertThat(throwException).isEqualToComparingFieldByField(
new BadRequestAlertException("Membership cannot be deleted", "membership", "membershipNotDeletable"));
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");
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);
final Throwable throwException = catchThrowableOfType(
() -> membershipService.save(givenMembershipDTO),
BadRequestAlertException.class);
// then
assertThat(throwException).isSameAs(givenBadRequestAlertException);

@@ -1,9 +1,16 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service;
import org.assertj.core.api.AbstractThrowableAssert;
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;
@@ -15,11 +22,6 @@ import org.mockito.junit.MockitoRule;
import java.time.LocalDate;
import java.util.function.Consumer;
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;
public class MembershipValidatorUnitTest {
@Rule
@@ -39,47 +41,69 @@ public class MembershipValidatorUnitTest {
@Test
public void shouldAcceptNewMembershipIfUntilDateAfterSinceDate() {
new GivenMembershipValidationTestCase()
.withNewMembershipForCustomer(1L).since("2019-04-11").until("2019-04-12")
.when((MembershipDTO membershipDto) -> membershipValidator.validate(membershipDto))
.thenActualException().isNull();
.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"));
.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"));
.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();
.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"));
.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 ---
@@ -89,7 +113,9 @@ public class MembershipValidatorUnitTest {
private final MembershipDTO membershipDto = new MembershipDTO();
private BadRequestAlertException actualException;
GivenMembershipValidationTestCase withUncancelledMembershipForCustomer(final long customerId, final boolean hasUncancelledMembership) {
GivenMembershipValidationTestCase withUncancelledMembershipForCustomer(
final long customerId,
final boolean hasUncancelledMembership) {
given(membershipRepository.hasUncancelledMembershipForCustomer(customerId)).willReturn(hasUncancelledMembership);
return this;
}
@@ -99,7 +125,6 @@ public class MembershipValidatorUnitTest {
return this;
}
GivenMembershipValidationTestCase since(final String sinceDate) {
membershipDto.setMemberFromDate(LocalDate.parse(sinceDate));
return this;
@@ -111,7 +136,9 @@ public class MembershipValidatorUnitTest {
}
GivenMembershipValidationTestCase when(final Consumer<MembershipDTO> statement) {
actualException = catchThrowableOfType(() -> membershipValidator.validate(membershipDto), BadRequestAlertException.class);
actualException = catchThrowableOfType(
() -> membershipValidator.validate(membershipDto),
BadRequestAlertException.class);
return this;
}

@@ -1,12 +1,20 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service;
import org.apache.commons.lang3.RandomUtils;
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;
@@ -17,13 +25,6 @@ import org.mockito.junit.MockitoRule;
import javax.persistence.EntityManager;
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.*;
// 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 {
@@ -54,13 +55,15 @@ public class ShareServiceUnitTest {
@Test
public void deleteIsRejectedForShareTransactions() {
// when
final Throwable throwException = catchThrowableOfType(() -> shareService.delete(RandomUtils.nextLong()), BadRequestAlertException.class);
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"));
new BadRequestAlertException("Share transactions are immutable", "share", "shareTransactionImmutable"));
}
@Test
@@ -83,14 +86,18 @@ public class ShareServiceUnitTest {
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);
doThrow(new BadRequestAlertException("Some Dummy Test Violation", "share", "shareInvalidTestDummy"))
.when(shareValidator)
.validate(givenShareDTO);
// when
final Throwable throwException = catchThrowableOfType(() -> shareService.save(givenShareDTO), BadRequestAlertException.class);
final Throwable throwException = catchThrowableOfType(
() -> shareService.save(givenShareDTO),
BadRequestAlertException.class);
// then
assertThat(throwException).isEqualToComparingFieldByField(
new BadRequestAlertException("Some Dummy Test Violation", "share", "shareInvalidTestDummy"));
new BadRequestAlertException("Some Dummy Test Violation", "share", "shareInvalidTestDummy"));
}
@Test
@@ -113,14 +120,18 @@ public class ShareServiceUnitTest {
// 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);
doThrow(new BadRequestAlertException("Some Dummy Test Violation", "share", "shareInvalidTestDummy"))
.when(shareValidator)
.validate(givenShareDTO);
// when
final Throwable throwException = catchThrowableOfType(() -> shareService.save(givenShareDTO), BadRequestAlertException.class);
final Throwable throwException = catchThrowableOfType(
() -> shareService.save(givenShareDTO),
BadRequestAlertException.class);
// then
assertThat(throwException).isEqualToComparingFieldByField(
new BadRequestAlertException("Some Dummy Test Violation", "share", "shareInvalidTestDummy"));
new BadRequestAlertException("Some Dummy Test Violation", "share", "shareInvalidTestDummy"));
}
// --- only test fixture code below ---
@@ -129,7 +140,8 @@ public class ShareServiceUnitTest {
return RandomUtils.nextInt();
}
// HINT: This rather complicated setup indicates that the method ShareService::save breaks the single responsibility principle.
// 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);

@@ -1,18 +1,20 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service;
import org.apache.commons.lang3.RandomUtils;
import org.assertj.core.api.AbstractThrowableAssert;
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;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
public class ShareValidatorUnitTest {
private ShareValidator shareValidator = new ShareValidator();
@@ -20,90 +22,126 @@ public class ShareValidatorUnitTest {
@Test
public void shouldAcceptValidSubscription() {
new GivenShareValidationTestCase()
.withAnyValidDateValues()
.withAction(ShareAction.SUBSCRIPTION).withQuantity(1)
.when((ShareDTO shareDto) -> shareValidator.validate(shareDto))
.thenActualException().isNull();
.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();
.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();
.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"));
.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"));
.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"));
.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"));
.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"));
.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"));
.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 {
@@ -140,7 +178,7 @@ public class ShareValidatorUnitTest {
return this;
}
GivenShareValidationTestCase when(final Consumer<ShareDTO> statement) {
GivenShareValidationTestCase when(final Consumer<ShareDTO> statement) {
actualException = catchThrowableOfType(() -> shareValidator.validate(shareDto), BadRequestAlertException.class);
return this;
}
@@ -150,5 +188,3 @@ public class ShareValidatorUnitTest {
}
}
}

@@ -1,5 +1,9 @@
// 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;
@@ -22,13 +26,10 @@ import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.time.LocalDateTime;
import java.util.Optional;
import java.time.temporal.ChronoUnit;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import java.util.Optional;
/**
* Test class for the UserResource REST controller.
@@ -169,12 +170,13 @@ public class UserServiceIntTest {
}
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();
assertThat(
allManagedUsers.getContent()
.stream()
.noneMatch(user -> Constants.ANONYMOUS_USER.equals(user.getLogin())))
.isTrue();
}
@Test
@Transactional
public void testRemoveNotActivatedUsers() {

@@ -1,15 +1,17 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
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;
import static org.hostsharing.hsadminng.service.accessfilter.Role.*;
public class JSonAccessFilterTestFixture {
static GivenDto createSampleDto() {
@@ -32,6 +34,7 @@ public class JSonAccessFilterTestFixture {
}
static class GivenCustomerDto implements FluentBuilder<GivenCustomerDto> {
@SelfId(resolver = GivenService.class)
@AccessFor(read = ANYBODY)
Long id;
@@ -45,6 +48,7 @@ public class JSonAccessFilterTestFixture {
}
static class GivenDto implements FluentBuilder<GivenDto> {
@SelfId(resolver = GivenService.class)
@AccessFor(read = ANYBODY)
Long id;
@@ -53,7 +57,10 @@ public class JSonAccessFilterTestFixture {
@AccessFor(init = ACTUAL_CUSTOMER_USER, update = ACTUAL_CUSTOMER_USER, read = ACTUAL_CUSTOMER_USER)
Long customerId;
@AccessFor(init = {TECHNICAL_CONTACT, FINANCIAL_CONTACT}, update = {TECHNICAL_CONTACT, FINANCIAL_CONTACT}, read = {TECHNICAL_CONTACT, FINANCIAL_CONTACT})
@AccessFor(
init = { TECHNICAL_CONTACT, FINANCIAL_CONTACT },
update = { TECHNICAL_CONTACT, FINANCIAL_CONTACT },
read = { TECHNICAL_CONTACT, FINANCIAL_CONTACT })
String restrictedField;
@AccessFor(init = ANYBODY, update = ANYBODY, read = ANYBODY)
@@ -103,7 +110,8 @@ public class JSonAccessFilterTestFixture {
}
enum TestEnum {
BLUE, GREEN
BLUE,
GREEN
}
static abstract class GivenChildService implements IdToDtoResolver<GivenChildDto> {
@@ -119,7 +127,7 @@ public class JSonAccessFilterTestFixture {
@ParentId(resolver = GivenService.class)
Long parentId;
@AccessFor(init = {TECHNICAL_CONTACT, FINANCIAL_CONTACT}, update = {TECHNICAL_CONTACT, FINANCIAL_CONTACT})
@AccessFor(init = { TECHNICAL_CONTACT, FINANCIAL_CONTACT }, update = { TECHNICAL_CONTACT, FINANCIAL_CONTACT })
String restrictedField;
}

@@ -1,3 +1,4 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter;
import org.apache.commons.lang3.StringUtils;
@@ -70,7 +71,6 @@ public class JSonBuilder {
return jsonArray.toString() + "]";
}
private static String inQuotes(Object value) {
return value != null ? "\"" + value.toString() + "\"" : "null";
}

@@ -1,13 +1,25 @@
// 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.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
import static org.mockito.BDDMockito.given;
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.ObjectMapper;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -23,21 +35,14 @@ import java.time.LocalDate;
import java.util.Arrays;
import java.util.Optional;
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.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
import static org.mockito.BDDMockito.given;
@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);
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();
@@ -72,26 +77,28 @@ public class JSonDeserializationWithAccessFilterUnitTest {
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(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(givenCustomerService.findOne(888L)).willReturn(
Optional.of(
new GivenCustomerDto()
.with(dto -> dto.id = 888L)));
given(jsonParser.getCodec()).willReturn(codec);
}
@@ -99,10 +106,11 @@ public class JSonDeserializationWithAccessFilterUnitTest {
@Test
public void shouldDeserializeNullField() throws IOException {
// given
givenJSonTree(asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("openStringField", null)));
givenJSonTree(
asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("openStringField", null)));
// when
GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize();
@@ -114,10 +122,11 @@ public class JSonDeserializationWithAccessFilterUnitTest {
@Test
public void shouldDeserializeStringField() throws IOException {
// given
givenJSonTree(asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("openStringField", "String Value")));
givenJSonTree(
asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("openStringField", "String Value")));
// when
GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize();
@@ -129,10 +138,11 @@ public class JSonDeserializationWithAccessFilterUnitTest {
@Test
public void shouldDeserializeIntegerField() throws IOException {
// given
givenJSonTree(asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("openIntegerField", 1234)));
givenJSonTree(
asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("openIntegerField", 1234)));
// when
GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize();
@@ -141,15 +151,15 @@ public class JSonDeserializationWithAccessFilterUnitTest {
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)));
givenJSonTree(
asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("restrictedBigDecimalField", SOME_BIG_DECIMAL_WITH_ANOTHER_SCALE)));
// when
GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize();
@@ -160,26 +170,26 @@ public class JSonDeserializationWithAccessFilterUnitTest {
}
@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
// 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)
)
);
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
GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize();
@@ -200,15 +210,15 @@ public class JSonDeserializationWithAccessFilterUnitTest {
@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))
)
);
givenJSonTree(
asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("openArrayField", Arrays.asList(11, 22, 33))));
// when
Throwable exception = catchThrowable(() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize());
Throwable exception = catchThrowable(
() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize());
// then
assertThat(exception).isInstanceOf(NotImplementedException.class);
@@ -219,10 +229,11 @@ public class JSonDeserializationWithAccessFilterUnitTest {
// given
givenAuthenticatedUser();
givenUserHavingRole(GivenCustomerDto.class, 888L, Role.FINANCIAL_CONTACT);
givenJSonTree(asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("restrictedField", "update value of restricted field")));
givenJSonTree(
asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("restrictedField", "update value of restricted field")));
// when
GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize();
@@ -236,10 +247,11 @@ public class JSonDeserializationWithAccessFilterUnitTest {
// given
givenAuthenticatedUser();
givenUserHavingRole(GivenCustomerDto.class, 888L, Role.ACTUAL_CUSTOMER_USER);
givenJSonTree(asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("restrictedField", "initial value of restricted field")));
givenJSonTree(
asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("restrictedField", "initial value of restricted field")));
// when
GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize();
@@ -253,13 +265,14 @@ public class JSonDeserializationWithAccessFilterUnitTest {
// given
givenAuthenticatedUser();
givenUserHavingRole(GivenCustomerDto.class, 888L, Role.ACTUAL_CUSTOMER_USER);
givenJSonTree(asJSon(
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("restrictedField", "updated value of restricted field"))
);
givenJSonTree(
asJSon(
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("restrictedField", "updated value of restricted field")));
// when
Throwable exception = catchThrowable(() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize());
Throwable exception = catchThrowable(
() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize());
// then
assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> {
@@ -273,13 +286,14 @@ public class JSonDeserializationWithAccessFilterUnitTest {
// given
givenAuthenticatedUser();
givenUserHavingRole(GivenCustomerDto.class, 888L, Role.ACTUAL_CUSTOMER_USER);
givenJSonTree(asJSon(
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("restrictedField", "another value of restricted field"))
);
givenJSonTree(
asJSon(
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("restrictedField", "another value of restricted field")));
// when
Throwable exception = catchThrowable(() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize());
Throwable exception = catchThrowable(
() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize());
// then
assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> {
@@ -293,12 +307,13 @@ public class JSonDeserializationWithAccessFilterUnitTest {
// given
givenAuthenticatedUser();
givenUserHavingRole(GivenDto.class, 9999L, Role.CONTRACTUAL_CONTACT);
givenJSonTree(asJSon(
ImmutablePair.of("parentId", 1234L))
);
givenJSonTree(
asJSon(
ImmutablePair.of("parentId", 1234L)));
// when
Throwable exception = catchThrowable(() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenChildDto.class).deserialize());
Throwable exception = catchThrowable(
() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenChildDto.class).deserialize());
// then
assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> {
@@ -312,12 +327,13 @@ public class JSonDeserializationWithAccessFilterUnitTest {
// given
givenAuthenticatedUser();
givenUserHavingRole(GivenDto.class, 1234L, Role.CONTRACTUAL_CONTACT);
givenJSonTree(asJSon(
ImmutablePair.of("parentId", 1234L))
);
givenJSonTree(
asJSon(
ImmutablePair.of("parentId", 1234L)));
// when
final GivenChildDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenChildDto.class).deserialize();
final GivenChildDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenChildDto.class)
.deserialize();
// then
assertThat(actualDto.parentId).isEqualTo(1234L);
@@ -328,13 +344,15 @@ public class JSonDeserializationWithAccessFilterUnitTest {
// given
givenAuthenticatedUser();
givenUserHavingRole(GivenCustomerDto.class, 888L, Role.ACTUAL_CUSTOMER_USER);
givenJSonTree(asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("restrictedField", "Restricted String Value")));
givenJSonTree(
asJSon(
ImmutablePair.of("id", 1234L),
ImmutablePair.of("customerId", 888L),
ImmutablePair.of("restrictedField", "Restricted String Value")));
// when
Throwable exception = catchThrowable(() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize());
Throwable exception = catchThrowable(
() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize());
// then
assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> {
@@ -349,10 +367,13 @@ public class JSonDeserializationWithAccessFilterUnitTest {
givenJSonTree(asJSon(ImmutablePair.of("id", 1111L)));
// when
Throwable exception = catchThrowable(() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDtoWithMultipleSelfId.class).deserialize());
Throwable exception = catchThrowable(
() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDtoWithMultipleSelfId.class)
.deserialize());
// then
assertThat(exception).isInstanceOf(AssertionError.class).hasMessage("multiple @SelfId detected in GivenDtoWithMultipleSelfId");
assertThat(exception).isInstanceOf(AssertionError.class)
.hasMessage("multiple @SelfId detected in GivenDtoWithMultipleSelfId");
}
@Test
@@ -363,13 +384,15 @@ public class JSonDeserializationWithAccessFilterUnitTest {
givenJSonTree(asJSon(ImmutablePair.of("unknown", new Arbitrary())));
// when
Throwable exception = catchThrowable(() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDtoWithUnknownFieldType.class).deserialize());
Throwable exception = catchThrowable(
() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDtoWithUnknownFieldType.class)
.deserialize());
// then
assertThat(exception).isInstanceOf(NotImplementedException.class)
.hasMessageStartingWith("property type not yet implemented: ")
.hasMessageContaining("Arbitrary")
.hasMessageContaining("GivenDtoWithUnknownFieldType.unknown");
.hasMessageStartingWith("property type not yet implemented: ")
.hasMessageContaining("Arbitrary")
.hasMessageContaining("GivenDtoWithUnknownFieldType.unknown");
}
// --- only fixture code below ---

@@ -1,6 +1,15 @@
// 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 com.fasterxml.jackson.core.JsonGenerator;
import org.apache.commons.lang3.NotImplementedException;
import org.junit.Before;
import org.junit.Rule;
@@ -14,13 +23,6 @@ import org.springframework.context.ApplicationContext;
import java.io.IOException;
import java.util.Optional;
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;
public class JSonSerializationWithAccessFilterUnitTest {
@Rule
@@ -47,9 +49,10 @@ public class JSonSerializationWithAccessFilterUnitTest {
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)
));
given(givenCustomerService.findOne(888L)).willReturn(
Optional.of(
new GivenCustomerDto()
.with(dto -> dto.id = 888L)));
}
@Test
@@ -177,13 +180,16 @@ public class JSonSerializationWithAccessFilterUnitTest {
class Arbitrary {
}
class GivenDtoWithUnimplementedFieldType {
@AccessFor(read = Role.ANYBODY)
Arbitrary fieldWithUnimplementedType = new Arbitrary();
}
final GivenDtoWithUnimplementedFieldType givenDtoWithUnimplementedFieldType = new GivenDtoWithUnimplementedFieldType();
// when
final Throwable actual = catchThrowable(() -> new JSonSerializationWithAccessFilter<>(ctx, jsonGenerator, null, givenDtoWithUnimplementedFieldType).serialize());
final Throwable actual = catchThrowable(
() -> new JSonSerializationWithAccessFilter<>(ctx, jsonGenerator, null, givenDtoWithUnimplementedFieldType)
.serialize());
// then
assertThat(actual).isInstanceOf(NotImplementedException.class);

@@ -1,12 +1,14 @@
// 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.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assumptions.assumeThat;
public class MockSecurityContext {
public static void givenAuthenticatedUser() {

@@ -1,13 +1,15 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter;
import com.google.common.base.VerifyException;
import org.junit.Test;
import java.lang.reflect.Field;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.ThrowableAssert.catchThrowable;
import com.google.common.base.VerifyException;
import org.junit.Test;
import java.lang.reflect.Field;
public class RoleUnitTest {
@Test
@@ -20,7 +22,6 @@ public class RoleUnitTest {
assertThat(Role.FINANCIAL_CONTACT.covers(Role.FINANCIAL_CONTACT)).isTrue();
assertThat(Role.TECHNICAL_CONTACT.covers(Role.TECHNICAL_CONTACT)).isTrue();
assertThat(Role.ACTUAL_CUSTOMER_USER.covers((Role.ACTUAL_CUSTOMER_USER))).isTrue();
assertThat(Role.ANY_CUSTOMER_USER.covers((Role.ANY_CUSTOMER_USER))).isTrue();
}
@@ -153,13 +154,14 @@ public class RoleUnitTest {
// --- only test fixture below ---
static class TestDto {
@AccessFor(init = Role.ADMIN, update = Role.SUPPORTER, read = Role.ANY_CUSTOMER_CONTACT)
private Integer someFieldWithAccessForAnnotation;
@AccessFor(update = Role.IGNORED, read = Role.ANY_CUSTOMER_CONTACT)
private Integer someFieldWithAccessForAnnotationToBeIgnoredForUpdates;
@AccessFor(update = {Role.IGNORED, Role.SUPPORTER}, read = Role.ANY_CUSTOMER_CONTACT)
@AccessFor(update = { Role.IGNORED, Role.SUPPORTER }, read = Role.ANY_CUSTOMER_CONTACT)
private Integer someFieldWithAccessForAnnotationToBeIgnoredForUpdatesAmongOthers;
private Integer someFieldWithoutAccessForAnnotation;
@@ -173,8 +175,10 @@ public class RoleUnitTest {
static {
try {
someFieldWithoutAccessForAnnotation = TestDto.class.getDeclaredField("someFieldWithoutAccessForAnnotation");
someFieldWithAccessForAnnotationToBeIgnoredForUpdates = TestDto.class.getDeclaredField("someFieldWithAccessForAnnotationToBeIgnoredForUpdates");
someFieldWithAccessForAnnotationToBeIgnoredForUpdatesAmongOthers = TestDto.class.getDeclaredField("someFieldWithAccessForAnnotationToBeIgnoredForUpdatesAmongOthers");
someFieldWithAccessForAnnotationToBeIgnoredForUpdates = TestDto.class
.getDeclaredField("someFieldWithAccessForAnnotationToBeIgnoredForUpdates");
someFieldWithAccessForAnnotationToBeIgnoredForUpdatesAmongOthers = TestDto.class
.getDeclaredField("someFieldWithAccessForAnnotationToBeIgnoredForUpdatesAmongOthers");
someFieldWithAccessForAnnotation = TestDto.class.getDeclaredField("someFieldWithAccessForAnnotation");
} catch (NoSuchFieldException e) {
throw new AssertionError("precondition failed", e);

@@ -1,8 +1,14 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import org.apache.commons.lang3.RandomUtils;
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;
@@ -15,10 +21,6 @@ import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.apache.commons.lang3.StringUtils.removeEnd;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
/**
* Usually base classes for unit tests are not a good idea, but because
* DTOs which implement AccessMapping are more like a DSL,
@@ -30,7 +32,10 @@ public abstract class AccessMappingsUnitTestBase<D> {
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) {
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;
@@ -105,6 +110,7 @@ public abstract class AccessMappingsUnitTestBase<D> {
// 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;
@@ -117,9 +123,14 @@ public abstract class AccessMappingsUnitTestBase<D> {
final Set<Field> fieldsWithAccessForAnnotation = determineFieldsWithAccessForAnnotation(dtoClass);
this.namesOfFieldsWithAccessForAnnotation = fieldsWithAccessForAnnotation.stream()
.map(Field::getName).collect(Collectors.toList()).toArray(new String[]{});
.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[]{});
.filter(f -> allows(f, access, role))
.map(Field::getName)
.collect(Collectors.toList())
.toArray(new String[] {});
}
public void shouldBeExactlyFor(final String... expectedFields) {
@@ -134,7 +145,6 @@ public abstract class AccessMappingsUnitTestBase<D> {
assertThat(namesOfAccessibleFields).containsExactlyInAnyOrder(namesOfFieldsWithAccessForAnnotation);
}
private static Set<Field> determineFieldsWithAccessForAnnotation(final Class<?> dtoClass) {
final Set<Field> fieldsWithAccessForAnnotation = new HashSet<>();
@@ -205,13 +215,16 @@ public abstract class AccessMappingsUnitTestBase<D> {
for (Class<?> declaredClass : dtoClass.getDeclaredClasses()) {
if (expectedSuperclass.isAssignableFrom(declaredClass)) {
assertThat(declaredClass.isAnnotationPresent(JsonComponent.class))
.as(declaredClass + " requires @" + JsonComponent.class.getSimpleName()).isTrue();
.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);
.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();
assertThat(Modifier.isAbstract(declaredClass.getModifiers())).as(declaredClass + " must not be abstract")
.isFalse();
return;
}
}

@@ -1,8 +1,13 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.RandomUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
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;
@@ -20,6 +25,11 @@ 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;
@@ -32,27 +42,22 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import javax.persistence.EntityManager;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import javax.persistence.EntityManager;
@JsonTest
@SpringBootTest(classes = {
CustomerMapperImpl.class,
MembershipMapperImpl.class,
AssetMapperImpl.class,
AssetDTO.JsonSerializer.class,
AssetDTO.JsonDeserializer.class
})
@SpringBootTest(
classes = {
CustomerMapperImpl.class,
MembershipMapperImpl.class,
AssetMapperImpl.class,
AssetDTO.JsonSerializer.class,
AssetDTO.JsonDeserializer.class
})
@RunWith(SpringRunner.class)
public class AssetDTOIntTest {
@@ -61,12 +66,15 @@ public class AssetDTOIntTest {
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);
.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);
.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);
@@ -146,17 +154,18 @@ public class AssetDTOIntTest {
givenAuthenticatedUser();
givenUserHavingRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CONTRACTUAL_CONTACT);
final String json = new JSonBuilder()
.withFieldValue("id", SOME_ASSET_ID)
.withFieldValue("remark", "Updated Remark")
.toString();
.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 CONTRACTUAL_CONTACT")
);
assertThat(actual).isInstanceOfSatisfying(
BadRequestAlertException.class,
bre -> assertThat(bre.getMessage())
.isEqualTo("Update of field AssetDTO.remark prohibited for current user role CONTRACTUAL_CONTACT"));
}
@Test
@@ -165,9 +174,9 @@ public class AssetDTOIntTest {
givenAuthenticatedUser();
givenUserHavingRole(Role.ADMIN);
final String json = new JSonBuilder()
.withFieldValue("id", SOME_ASSET_ID)
.withFieldValue("remark", "Updated Remark")
.toString();
.withFieldValue("id", SOME_ASSET_ID)
.withFieldValue("remark", "Updated Remark")
.toString();
// when
final AssetDTO actual = objectMapper.readValue(json, AssetDTO.class);
@@ -185,18 +194,17 @@ public class AssetDTOIntTest {
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();
.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);

@@ -1,10 +1,12 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.hostsharing.hsadminng.domain.enumeration.AssetAction;
import org.hostsharing.hsadminng.service.accessfilter.Role;
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;
@@ -19,7 +21,12 @@ public class AssetDTOUnitTest extends AccessMappingsUnitTestBase<AssetDTO> {
@Test
public void shouldHaveProperAccessForAdmin() {
initAccessFor(AssetDTO.class, Role.ADMIN).shouldBeExactlyFor(
"membershipId", "documentDate", "amount", "action", "valueDate", "remark");
"membershipId",
"documentDate",
"amount",
"action",
"valueDate",
"remark");
updateAccessFor(AssetDTO.class, Role.ADMIN).shouldBeExactlyFor("remark");
readAccessFor(AssetDTO.class, Role.ADMIN).shouldBeForAllFields();
}
@@ -29,7 +36,13 @@ public class AssetDTOUnitTest extends AccessMappingsUnitTestBase<AssetDTO> {
initAccessFor(AssetDTO.class, Role.CONTRACTUAL_CONTACT).shouldBeForNothing();
updateAccessFor(AssetDTO.class, Role.CONTRACTUAL_CONTACT).shouldBeForNothing();
readAccessFor(AssetDTO.class, Role.CONTRACTUAL_CONTACT).shouldBeExactlyFor(
"id", "membershipId", "documentDate", "amount", "action", "valueDate", "membershipDisplayLabel");
"id",
"membershipId",
"documentDate",
"amount",
"action",
"valueDate",
"membershipDisplayLabel");
}
@Test

@@ -1,7 +1,12 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
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;
@@ -11,6 +16,10 @@ import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder;
import org.hostsharing.hsadminng.service.accessfilter.Role;
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.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -25,14 +34,14 @@ import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
@JsonTest
@SpringBootTest(classes = {CustomerMapperImpl.class, CustomerRepository.class, CustomerService.class, CustomerDTO.CustomerJsonSerializer.class, CustomerDTO.CustomerJsonDeserializer.class})
@SpringBootTest(
classes = {
CustomerMapperImpl.class,
CustomerRepository.class,
CustomerService.class,
CustomerDTO.CustomerJsonSerializer.class,
CustomerDTO.CustomerJsonDeserializer.class })
@RunWith(SpringRunner.class)
public class CustomerDTOUnitTest {
@@ -80,11 +89,12 @@ public class CustomerDTOUnitTest {
// 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();
.withFieldValue("id", given.getId())
.withFieldValue("reference", given.getReference())
.withFieldValue("prefix", given.getPrefix())
.withFieldValue("name", given.getName())
.withFieldValue("displayLabel", given.getDisplayLabel())
.toString();
assertEquals(expectedJSon, actual);
}
@@ -126,23 +136,24 @@ public class CustomerDTOUnitTest {
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();
.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) {

@@ -1,9 +1,10 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class MembershipDTOTest {
@Test

@@ -1,15 +1,25 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.tuple.ImmutablePair;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hostsharing.hsadminng.service.accessfilter.JSonBuilder.asJSon;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.service.CustomerService;
import org.hostsharing.hsadminng.service.MembershipService;
import org.hostsharing.hsadminng.service.accessfilter.JSonDeserializationWithAccessFilter;
import org.hostsharing.hsadminng.service.accessfilter.Role;
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.ObjectMapper;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -22,13 +32,6 @@ import org.springframework.context.ApplicationContext;
import java.io.IOException;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hostsharing.hsadminng.service.accessfilter.JSonBuilder.asJSon;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
import static org.mockito.BDDMockito.given;
public class MembershipDTOUnitTest {
@Rule
@@ -59,12 +62,13 @@ public class MembershipDTOUnitTest {
public void init() {
given(jsonParser.getCodec()).willReturn(codec);
given (ctx.getAutowireCapableBeanFactory()).willReturn(autowireCapableBeanFactory);
given(ctx.getAutowireCapableBeanFactory()).willReturn(autowireCapableBeanFactory);
given(autowireCapableBeanFactory.createBean(MembershipService.class)).willReturn(membershipService);
given(autowireCapableBeanFactory.createBean(CustomerService.class)).willReturn(customerService);
given(customerService.findOne(1234L)).willReturn(Optional.of(new CustomerDTO()
.with(dto -> dto.setId(1234L))
));
given(customerService.findOne(1234L)).willReturn(
Optional.of(
new CustomerDTO()
.with(dto -> dto.setId(1234L))));
}
@Test
@@ -74,7 +78,8 @@ public class MembershipDTOUnitTest {
givenJSonTree(asJSon(ImmutablePair.of("customerId", 1234L)));
// when
final MembershipDTO actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, MembershipDTO.class).deserialize();
final MembershipDTO actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, MembershipDTO.class)
.deserialize();
// then
assertThat(actualDto.getCustomerId()).isEqualTo(1234L);
@@ -87,7 +92,8 @@ public class MembershipDTOUnitTest {
givenJSonTree(asJSon(ImmutablePair.of("customerId", 1234L)));
// when
Throwable exception = catchThrowable(() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, MembershipDTO.class).deserialize());
Throwable exception = catchThrowable(
() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, MembershipDTO.class).deserialize());
// then
assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> {

@@ -1,8 +1,14 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.RandomUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
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;
@@ -17,6 +23,11 @@ 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;
@@ -29,27 +40,21 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import javax.persistence.EntityManager;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
import static org.hostsharing.hsadminng.service.dto.SepaMandateDTOUnitTest.createSampleDTO;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import javax.persistence.EntityManager;
@JsonTest
@SpringBootTest(classes = {
CustomerMapperImpl.class,
MembershipMapperImpl.class,
SepaMandateMapperImpl.class,
SepaMandateDTO.JsonSerializer.class,
SepaMandateDTO.JsonDeserializer.class
})
@SpringBootTest(
classes = {
CustomerMapperImpl.class,
MembershipMapperImpl.class,
SepaMandateMapperImpl.class,
SepaMandateDTO.JsonSerializer.class,
SepaMandateDTO.JsonDeserializer.class
})
@RunWith(SpringRunner.class)
public class SepaMandateDTOIntTest {
@@ -59,7 +64,9 @@ public class SepaMandateDTOIntTest {
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);
.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);
@@ -134,17 +141,18 @@ public class SepaMandateDTOIntTest {
givenAuthenticatedUser();
givenUserHavingRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CONTRACTUAL_CONTACT);
final String json = new JSonBuilder()
.withFieldValue("id", SOME_SEPA_MANDATE_ID)
.withFieldValue("remark", "Updated Remark")
.toString();
.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 CONTRACTUAL_CONTACT")
);
assertThat(actual).isInstanceOfSatisfying(
BadRequestAlertException.class,
bre -> assertThat(bre.getMessage()).isEqualTo(
"Update of field SepaMandateDTO.remark prohibited for current user role CONTRACTUAL_CONTACT"));
}
@Test
@@ -153,9 +161,9 @@ public class SepaMandateDTOIntTest {
givenAuthenticatedUser();
givenUserHavingRole(Role.ADMIN);
final String json = new JSonBuilder()
.withFieldValue("id", SOME_SEPA_MANDATE_ID)
.withFieldValue("remark", "Updated Remark")
.toString();
.withFieldValue("id", SOME_SEPA_MANDATE_ID)
.withFieldValue("remark", "Updated Remark")
.toString();
// when
final SepaMandateDTO actual = objectMapper.readValue(json, SepaMandateDTO.class);
@@ -173,18 +181,18 @@ public class SepaMandateDTOIntTest {
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();
.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();
}
}

@@ -1,8 +1,10 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.junit.Test;
import java.time.LocalDate;
@@ -16,31 +18,66 @@ public class SepaMandateDTOUnitTest extends AccessMappingsUnitTestBase<SepaManda
@Test
public void shouldHaveProperAccessForAdmin() {
initAccessFor(SepaMandateDTO.class, Role.ADMIN).shouldBeExactlyFor(
"grantingDocumentDate", "bic", "remark", "validUntilDate", "customerId", "validFromDate",
"iban", "revokationDocumentDate", "lastUsedDate", "reference");
"grantingDocumentDate",
"bic",
"remark",
"validUntilDate",
"customerId",
"validFromDate",
"iban",
"revokationDocumentDate",
"lastUsedDate",
"reference");
updateAccessFor(SepaMandateDTO.class, Role.ADMIN).shouldBeExactlyFor(
"remark", "validUntilDate", "revokationDocumentDate", "lastUsedDate");
"remark",
"validUntilDate",
"revokationDocumentDate",
"lastUsedDate");
readAccessFor(SepaMandateDTO.class, Role.ADMIN).shouldBeForAllFields();
}
@Test
public void shouldHaveProperAccessForSupporter() {
initAccessFor(SepaMandateDTO.class, Role.SUPPORTER).shouldBeExactlyFor(
"grantingDocumentDate", "bic", "validUntilDate", "customerId", "validFromDate", "iban", "reference");
"grantingDocumentDate",
"bic",
"validUntilDate",
"customerId",
"validFromDate",
"iban",
"reference");
updateAccessFor(SepaMandateDTO.class, Role.SUPPORTER).shouldBeExactlyFor(
"remark", "validUntilDate", "revokationDocumentDate");
"remark",
"validUntilDate",
"revokationDocumentDate");
readAccessFor(SepaMandateDTO.class, Role.SUPPORTER).shouldBeForAllFields();
}
@Test
public void shouldHaveProperAccessForContractualContact() {
initAccessFor(SepaMandateDTO.class, Role.CONTRACTUAL_CONTACT).shouldBeExactlyFor(
"grantingDocumentDate", "bic", "validUntilDate", "customerId", "validFromDate", "iban", "reference");
"grantingDocumentDate",
"bic",
"validUntilDate",
"customerId",
"validFromDate",
"iban",
"reference");
updateAccessFor(SepaMandateDTO.class, Role.CONTRACTUAL_CONTACT).shouldBeExactlyFor(
"validUntilDate", "revokationDocumentDate");
"validUntilDate",
"revokationDocumentDate");
readAccessFor(SepaMandateDTO.class, Role.CONTRACTUAL_CONTACT).shouldBeExactlyFor(
"grantingDocumentDate", "bic", "id", "validUntilDate", "customerId", "validFromDate", "iban",
"revokationDocumentDate", "customerDisplayLabel", "lastUsedDate", "reference");
"grantingDocumentDate",
"bic",
"id",
"validUntilDate",
"customerId",
"validFromDate",
"iban",
"revokationDocumentDate",
"customerDisplayLabel",
"lastUsedDate",
"reference");
}
@Test

@@ -1,8 +1,13 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.RandomUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
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;
@@ -20,6 +25,11 @@ 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;
@@ -32,26 +42,21 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import javax.persistence.EntityManager;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import javax.persistence.EntityManager;
@JsonTest
@SpringBootTest(classes = {
CustomerMapperImpl.class,
MembershipMapperImpl.class,
ShareMapperImpl.class,
ShareDTO.JsonSerializer.class,
ShareDTO.JsonDeserializer.class
})
@SpringBootTest(
classes = {
CustomerMapperImpl.class,
MembershipMapperImpl.class,
ShareMapperImpl.class,
ShareDTO.JsonSerializer.class,
ShareDTO.JsonDeserializer.class
})
@RunWith(SpringRunner.class)
public class ShareDTOIntTest {
@@ -60,12 +65,15 @@ public class ShareDTOIntTest {
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);
.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);
.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);
@@ -145,17 +153,18 @@ public class ShareDTOIntTest {
givenAuthenticatedUser();
givenUserHavingRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CONTRACTUAL_CONTACT);
final String json = new JSonBuilder()
.withFieldValue("id", SOME_SHARE_ID)
.withFieldValue("remark", "Updated Remark")
.toString();
.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 CONTRACTUAL_CONTACT")
);
assertThat(actual).isInstanceOfSatisfying(
BadRequestAlertException.class,
bre -> assertThat(bre.getMessage())
.isEqualTo("Update of field ShareDTO.remark prohibited for current user role CONTRACTUAL_CONTACT"));
}
@Test
@@ -164,9 +173,9 @@ public class ShareDTOIntTest {
givenAuthenticatedUser();
givenUserHavingRole(Role.ADMIN);
final String json = new JSonBuilder()
.withFieldValue("id", SOME_SHARE_ID)
.withFieldValue("remark", "Updated Remark")
.toString();
.withFieldValue("id", SOME_SHARE_ID)
.withFieldValue("remark", "Updated Remark")
.toString();
// when
final ShareDTO actual = objectMapper.readValue(json, ShareDTO.class);
@@ -184,15 +193,15 @@ public class ShareDTOIntTest {
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();
.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) {

@@ -1,10 +1,12 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.hostsharing.hsadminng.domain.enumeration.ShareAction;
import org.hostsharing.hsadminng.service.accessfilter.Role;
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;
@@ -18,7 +20,12 @@ public class ShareDTOUnitTest extends AccessMappingsUnitTestBase<ShareDTO> {
@Test
public void shouldHaveProperAccessForAdmin() {
initAccessFor(ShareDTO.class, Role.ADMIN).shouldBeExactlyFor(
"membershipId", "documentDate", "quantity", "action", "valueDate", "remark");
"membershipId",
"documentDate",
"quantity",
"action",
"valueDate",
"remark");
updateAccessFor(ShareDTO.class, Role.ADMIN).shouldBeExactlyFor("remark");
readAccessFor(ShareDTO.class, Role.ADMIN).shouldBeForAllFields();
}
@@ -28,7 +35,13 @@ public class ShareDTOUnitTest extends AccessMappingsUnitTestBase<ShareDTO> {
initAccessFor(ShareDTO.class, Role.CONTRACTUAL_CONTACT).shouldBeForNothing();
updateAccessFor(ShareDTO.class, Role.CONTRACTUAL_CONTACT).shouldBeForNothing();
readAccessFor(ShareDTO.class, Role.CONTRACTUAL_CONTACT).shouldBeExactlyFor(
"id", "membershipId", "documentDate", "quantity", "action", "valueDate", "membershipDisplayLabel");
"id",
"membershipId",
"documentDate",
"quantity",
"action",
"valueDate",
"membershipDisplayLabel");
}
@Test
@@ -74,4 +87,3 @@ public class ShareDTOUnitTest extends AccessMappingsUnitTestBase<ShareDTO> {
return dto;
}
}

@@ -1,9 +1,12 @@
// 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;
@@ -17,8 +20,6 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test class for the UserMapper.
*
@@ -54,7 +55,7 @@ public class UserMapperTest {
}
@Test
public void usersToUserDTOsShouldMapOnlyNonNullUsers(){
public void usersToUserDTOsShouldMapOnlyNonNullUsers() {
List<User> users = new ArrayList<>();
users.add(user);
users.add(null);
@@ -66,7 +67,7 @@ public class UserMapperTest {
}
@Test
public void userDTOsToUsersShouldMapOnlyNonNullUsers(){
public void userDTOsToUsersShouldMapOnlyNonNullUsers() {
List<UserDTO> usersDto = new ArrayList<>();
usersDto.add(userDto);
usersDto.add(null);
@@ -78,7 +79,7 @@ public class UserMapperTest {
}
@Test
public void userDTOsToUsersWithAuthoritiesStringShouldMapToUsersWithAuthoritiesDomain(){
public void userDTOsToUsersWithAuthoritiesStringShouldMapToUsersWithAuthoritiesDomain() {
Set<String> authoritiesAsString = new HashSet<>();
authoritiesAsString.add("ADMIN");
userDto.setAuthorities(authoritiesAsString);
@@ -96,7 +97,7 @@ public class UserMapperTest {
}
@Test
public void userDTOsToUsersMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities(){
public void userDTOsToUsersMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities() {
userDto.setAuthorities(null);
List<UserDTO> usersDto = new ArrayList<>();
@@ -111,7 +112,7 @@ public class UserMapperTest {
}
@Test
public void userDTOToUserMapWithAuthoritiesStringShouldReturnUserWithAuthorities(){
public void userDTOToUserMapWithAuthoritiesStringShouldReturnUserWithAuthorities() {
Set<String> authoritiesAsString = new HashSet<>();
authoritiesAsString.add("ADMIN");
userDto.setAuthorities(authoritiesAsString);
@@ -127,7 +128,7 @@ public class UserMapperTest {
}
@Test
public void userDTOToUserMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities(){
public void userDTOToUserMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities() {
userDto.setAuthorities(null);
User user = userMapper.userDTOToUser(userDto);
@@ -138,7 +139,7 @@ public class UserMapperTest {
}
@Test
public void userDTOToUserMapWithNullUserShouldReturnNull(){
public void userDTOToUserMapWithNullUserShouldReturnNull() {
assertThat(userMapper.userDTOToUser(null)).isNull();
}

@@ -1,18 +1,19 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.util;
import org.junit.Test;
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");
assertThat(actual).isInstanceOf(IllegalArgumentException.class)
.hasMessage("java.lang.NoSuchFieldException: unknownField");
}
@Test
@@ -57,8 +58,10 @@ public class ReflectionUtilUnitTest {
@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<...>");
final Throwable actual = catchThrowable(
() -> ReflectionUtil.determineGenericInterfaceParameter(SomeClass.class, UnusedGenericInterface.class, 1));
assertThat(actual).isInstanceOf(AssertionError.class)
.hasMessageContaining("SomeClass expected to implement UnusedGenericInterface<...>");
}
@Test
@@ -75,8 +78,10 @@ public class ReflectionUtilUnitTest {
@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<...>");
final Throwable actual = catchThrowable(
() -> ReflectionUtil.determineGenericClassParameter(SomeClass.class, UnusedSuperClass.class, 1));
assertThat(actual).isInstanceOf(AssertionError.class)
.hasMessageContaining("GenericClass expected to extend UnusedSuperClass<...>");
}
@Test
@@ -85,9 +90,8 @@ public class ReflectionUtilUnitTest {
final Throwable actual = catchThrowable(() -> unchecked(() -> {
throw givenException;
}));
assertThat(actual).isInstanceOfSatisfying(RuntimeException.class, rte ->
assertThat(rte.getCause()).isSameAs(givenException)
);
assertThat(actual)
.isInstanceOfSatisfying(RuntimeException.class, rte -> assertThat(rte.getCause()).isSameAs(givenException));
}
@Test
@@ -98,6 +102,7 @@ public class ReflectionUtilUnitTest {
// --- only test fixture below ---
private static class TestDto {
int intVal;
TestDto(final int intval) {
@@ -118,7 +123,8 @@ public class ReflectionUtilUnitTest {
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 UnusedSuperClass extends GenericClass<String, Boolean>
implements IntermediateInterfaces<Integer, Long> {
}
private static class GenericClass<T, V> {
@@ -134,6 +140,8 @@ public class ReflectionUtilUnitTest {
}
enum SomeEnum {
RED, BLUE, GREEN
RED,
BLUE,
GREEN
}
}

@@ -1,5 +1,13 @@
// 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;
@@ -14,8 +22,8 @@ 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.apache.commons.lang3.RandomStringUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -35,13 +43,6 @@ import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the AccountResource REST controller.
*
@@ -83,38 +84,38 @@ public class AccountResourceIntTest {
public void setup() {
MockitoAnnotations.initMocks(this);
doNothing().when(mockMailService).sendActivationEmail(any());
AccountResource accountResource =
new AccountResource(userRepository, userService, mockMailService);
AccountResource accountResource = new AccountResource(userRepository, userService, mockMailService);
AccountResource accountUserMockResource =
new AccountResource(userRepository, mockUserService, mockMailService);
AccountResource accountUserMockResource = new AccountResource(userRepository, mockUserService, mockMailService);
this.restMvc = MockMvcBuilders.standaloneSetup(accountResource)
.setMessageConverters(httpMessageConverters)
.setControllerAdvice(exceptionTranslator)
.build();
.setMessageConverters(httpMessageConverters)
.setControllerAdvice(exceptionTranslator)
.build();
this.restUserMockMvc = MockMvcBuilders.standaloneSetup(accountUserMockResource)
.setControllerAdvice(exceptionTranslator)
.build();
.setControllerAdvice(exceptionTranslator)
.build();
}
@Test
public void testNonAuthenticatedUser() throws Exception {
restUserMockMvc.perform(get("/api/authenticate")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(""));
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"));
restUserMockMvc.perform(
get("/api/authenticate")
.with(request -> {
request.setRemoteUser("test");
return request;
})
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string("test"));
}
@Test
@@ -134,26 +135,28 @@ public class AccountResourceIntTest {
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));
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());
restUserMockMvc.perform(
get("/api/account")
.accept(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(status().isInternalServerError());
}
@Test
@@ -171,10 +174,10 @@ public class AccountResourceIntTest {
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());
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(validUser)))
.andExpect(status().isCreated());
assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isTrue();
}
@@ -194,10 +197,10 @@ public class AccountResourceIntTest {
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
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();
@@ -218,10 +221,10 @@ public class AccountResourceIntTest {
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
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();
@@ -242,10 +245,10 @@ public class AccountResourceIntTest {
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
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();
@@ -266,10 +269,10 @@ public class AccountResourceIntTest {
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
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();
@@ -306,17 +309,17 @@ public class AccountResourceIntTest {
// First user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(firstUser)))
.andExpect(status().isCreated());
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());
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();
@@ -325,10 +328,10 @@ public class AccountResourceIntTest {
// Second (already activated) user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
.andExpect(status().is4xxClientError());
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
.andExpect(status().is4xxClientError());
}
@Test
@@ -347,10 +350,10 @@ public class AccountResourceIntTest {
// Register first user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(firstUser)))
.andExpect(status().isCreated());
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();
@@ -368,10 +371,10 @@ public class AccountResourceIntTest {
// Register second (non activated) user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
.andExpect(status().isCreated());
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();
@@ -393,10 +396,10 @@ public class AccountResourceIntTest {
// Register third (not activated) user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail)))
.andExpect(status().isCreated());
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();
@@ -407,10 +410,10 @@ public class AccountResourceIntTest {
// Register 4th (already activated) user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
.andExpect(status().is4xxClientError());
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
.andExpect(status().is4xxClientError());
}
@Test
@@ -428,15 +431,15 @@ public class AccountResourceIntTest {
validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(validUser)))
.andExpect(status().isCreated());
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());
.containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).get());
}
@Test
@@ -453,7 +456,7 @@ public class AccountResourceIntTest {
userRepository.saveAndFlush(user);
restMvc.perform(get("/api/activate?key={activationKey}", activationKey))
.andExpect(status().isOk());
.andExpect(status().isOk());
user = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(user.getActivated()).isTrue();
@@ -463,7 +466,7 @@ public class AccountResourceIntTest {
@Transactional
public void testActivateAccountWithWrongKey() throws Exception {
restMvc.perform(get("/api/activate?key=wrongActivationKey"))
.andExpect(status().isInternalServerError());
.andExpect(status().isInternalServerError());
}
@Test
@@ -489,10 +492,10 @@ public class AccountResourceIntTest {
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isOk());
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());
@@ -528,10 +531,10 @@ public class AccountResourceIntTest {
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isBadRequest());
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isBadRequest());
assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent();
}
@@ -567,10 +570,10 @@ public class AccountResourceIntTest {
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isBadRequest());
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");
@@ -599,10 +602,10 @@ public class AccountResourceIntTest {
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isOk());
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");
@@ -619,10 +622,13 @@ public class AccountResourceIntTest {
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());
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();
@@ -640,10 +646,11 @@ public class AccountResourceIntTest {
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());
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();
@@ -662,10 +669,11 @@ public class AccountResourceIntTest {
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());
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());
@@ -684,10 +692,11 @@ public class AccountResourceIntTest {
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());
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());
@@ -704,10 +713,11 @@ public class AccountResourceIntTest {
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());
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());
@@ -723,9 +733,10 @@ public class AccountResourceIntTest {
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());
restMvc.perform(
post("/api/account/reset-password/init")
.content("password-reset@example.com"))
.andExpect(status().isOk());
}
@Test
@@ -738,17 +749,18 @@ public class AccountResourceIntTest {
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());
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());
post("/api/account/reset-password/init")
.content("password-reset-wrong-email@example.com"))
.andExpect(status().isBadRequest());
}
@Test
@@ -767,10 +779,10 @@ public class AccountResourceIntTest {
keyAndPassword.setNewPassword("new password");
restMvc.perform(
post("/api/account/reset-password/finish")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isOk());
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();
@@ -792,16 +804,15 @@ public class AccountResourceIntTest {
keyAndPassword.setNewPassword("foo");
restMvc.perform(
post("/api/account/reset-password/finish")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isBadRequest());
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 {
@@ -810,9 +821,9 @@ public class AccountResourceIntTest {
keyAndPassword.setNewPassword("new password");
restMvc.perform(
post("/api/account/reset-password/finish")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isInternalServerError());
post("/api/account/reset-password/finish")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isInternalServerError());
}
}

@@ -1,5 +1,12 @@
// 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;
@@ -12,6 +19,7 @@ import org.hostsharing.hsadminng.service.accessfilter.Role;
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;
@@ -27,18 +35,14 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Validator;
import javax.persistence.EntityManager;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
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 javax.persistence.EntityManager;
/**
* Test class for the AssetResource REST controller.
*
@@ -102,11 +106,12 @@ public class AssetResourceIntTest {
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();
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator)
.build();
}
/**
@@ -117,11 +122,11 @@ public class AssetResourceIntTest {
*/
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);
.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);
@@ -138,11 +143,11 @@ public class AssetResourceIntTest {
*/
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);
.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);
@@ -150,6 +155,7 @@ public class AssetResourceIntTest {
em.flush();
return asset;
}
@Before
public void initTest() {
asset = createEntity(em);
@@ -163,10 +169,11 @@ public class AssetResourceIntTest {
// 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());
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();
@@ -189,10 +196,11 @@ public class AssetResourceIntTest {
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());
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();
@@ -210,10 +218,11 @@ public class AssetResourceIntTest {
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());
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();
@@ -230,10 +239,11 @@ public class AssetResourceIntTest {
// 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());
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);
@@ -249,10 +259,11 @@ public class AssetResourceIntTest {
// 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());
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);
@@ -268,10 +279,11 @@ public class AssetResourceIntTest {
// 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());
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);
@@ -287,10 +299,11 @@ public class AssetResourceIntTest {
// 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());
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);
@@ -304,16 +317,16 @@ public class AssetResourceIntTest {
// 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)));
.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 {
@@ -322,14 +335,14 @@ public class AssetResourceIntTest {
// 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));
.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
@@ -397,7 +410,6 @@ public class AssetResourceIntTest {
defaultAssetShouldBeFound("documentDate.lessThan=" + UPDATED_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllAssetsByValueDateIsEqualToSomething() throws Exception {
@@ -463,7 +475,6 @@ public class AssetResourceIntTest {
defaultAssetShouldBeFound("valueDate.lessThan=" + UPDATED_VALUE_DATE);
}
@Test
@Transactional
public void getAllAssetsByActionIsEqualToSomething() throws Exception {
@@ -585,7 +596,8 @@ public class AssetResourceIntTest {
@Transactional
public void getAllAssetsByMembershipIsEqualToSomething() throws Exception {
// Initialize the database
Membership membership = MembershipResourceIntTest.createPersistentEntity(em, CustomerResourceIntTest.createPersistentEntity(em));
Membership membership = MembershipResourceIntTest
.createPersistentEntity(em, CustomerResourceIntTest.createPersistentEntity(em));
asset.setMembership(membership);
assetRepository.saveAndFlush(asset);
Long membershipId = membership.getId();
@@ -602,20 +614,20 @@ public class AssetResourceIntTest {
*/
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)));
.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"));
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("1"));
}
/**
@@ -623,25 +635,24 @@ public class AssetResourceIntTest {
*/
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());
.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"));
.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());
.andExpect(status().isNotFound());
}
@Test
@@ -657,17 +668,18 @@ public class AssetResourceIntTest {
// 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);
.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());
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();
@@ -689,10 +701,11 @@ public class AssetResourceIntTest {
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());
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();
@@ -708,9 +721,10 @@ public class AssetResourceIntTest {
int databaseSizeBeforeDelete = assetRepository.findAll().size();
// Delete the asset
restAssetMockMvc.perform(delete("/api/assets/{id}", asset.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest());
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();

@@ -1,10 +1,17 @@
// 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;
@@ -22,11 +29,6 @@ import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the AuditResource REST controller.
*
@@ -64,13 +66,13 @@ public class AuditResourceIntTest {
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
AuditEventService auditEventService =
new AuditEventService(auditEventRepository, auditEventConverter);
AuditEventService auditEventService = new AuditEventService(auditEventRepository, auditEventConverter);
AuditResource auditResource = new AuditResource(auditEventService);
this.restAuditMockMvc = MockMvcBuilders.standaloneSetup(auditResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setConversionService(formattingConversionService)
.setMessageConverters(jacksonMessageConverter).build();
.setCustomArgumentResolvers(pageableArgumentResolver)
.setConversionService(formattingConversionService)
.setMessageConverters(jacksonMessageConverter)
.build();
}
@Before
@@ -89,9 +91,9 @@ public class AuditResourceIntTest {
// 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)));
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL)));
}
@Test
@@ -101,9 +103,9 @@ public class AuditResourceIntTest {
// 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));
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.principal").value(SAMPLE_PRINCIPAL));
}
@Test
@@ -112,14 +114,14 @@ public class AuditResourceIntTest {
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 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)));
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
@@ -128,21 +130,21 @@ public class AuditResourceIntTest {
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 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"));
.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());
.andExpect(status().isNotFound());
}
@Test

@@ -1,5 +1,14 @@
// 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.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
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.Customer;
import org.hostsharing.hsadminng.domain.Membership;
@@ -14,6 +23,7 @@ import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.dto.CustomerDTO;
import org.hostsharing.hsadminng.service.mapper.CustomerMapper;
import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -29,18 +39,11 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Validator;
import javax.persistence.EntityManager;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
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 javax.persistence.EntityManager;
/**
* Test class for the CustomerResource REST controller.
@@ -147,11 +150,12 @@ public class CustomerResourceIntTest {
final CustomerResource customerResource = new CustomerResource(customerService, customerQueryService);
this.restCustomerMockMvc = MockMvcBuilders.standaloneSetup(customerResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator).build();
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator)
.build();
}
/**
@@ -162,21 +166,21 @@ public class CustomerResourceIntTest {
*/
public static Customer createEntity(EntityManager em) {
Customer customer = new Customer()
.reference(DEFAULT_REFERENCE)
.prefix(DEFAULT_PREFIX)
.name(DEFAULT_NAME)
.kind(DEFAULT_KIND)
.birthDate(DEFAULT_BIRTH_DATE)
.birthPlace(DEFAULT_BIRTH_PLACE)
.registrationCourt(DEFAULT_REGISTRATION_COURT)
.registrationNumber(DEFAULT_REGISTRATION_NUMBER)
.vatRegion(DEFAULT_VAT_REGION)
.vatNumber(DEFAULT_VAT_NUMBER)
.contractualSalutation(DEFAULT_CONTRACTUAL_SALUTATION)
.contractualAddress(DEFAULT_CONTRACTUAL_ADDRESS)
.billingSalutation(DEFAULT_BILLING_SALUTATION)
.billingAddress(DEFAULT_BILLING_ADDRESS)
.remark(DEFAULT_REMARK);
.reference(DEFAULT_REFERENCE)
.prefix(DEFAULT_PREFIX)
.name(DEFAULT_NAME)
.kind(DEFAULT_KIND)
.birthDate(DEFAULT_BIRTH_DATE)
.birthPlace(DEFAULT_BIRTH_PLACE)
.registrationCourt(DEFAULT_REGISTRATION_COURT)
.registrationNumber(DEFAULT_REGISTRATION_NUMBER)
.vatRegion(DEFAULT_VAT_REGION)
.vatNumber(DEFAULT_VAT_NUMBER)
.contractualSalutation(DEFAULT_CONTRACTUAL_SALUTATION)
.contractualAddress(DEFAULT_CONTRACTUAL_ADDRESS)
.billingSalutation(DEFAULT_BILLING_SALUTATION)
.billingAddress(DEFAULT_BILLING_ADDRESS)
.remark(DEFAULT_REMARK);
return customer;
}
@@ -188,12 +192,12 @@ public class CustomerResourceIntTest {
*/
public static Customer createPersistentEntity(EntityManager em) {
Customer customer = new Customer()
.reference(OTHER_REFERENCE_BASE + otherCounter)
.prefix(OTHER_PREFIX_BASE + String.format("%02d", otherCounter))
.name(OTHER_NAME_BASE + otherCounter)
.kind(OTHER_KIND)
.vatRegion(OTHER_VAT_REGION)
.contractualAddress(OTHER_CONTRACTUAL_ADDRESS_BASE + otherCounter);
.reference(OTHER_REFERENCE_BASE + otherCounter)
.prefix(OTHER_PREFIX_BASE + String.format("%02d", otherCounter))
.name(OTHER_NAME_BASE + otherCounter)
.kind(OTHER_KIND)
.vatRegion(OTHER_VAT_REGION)
.contractualAddress(OTHER_CONTRACTUAL_ADDRESS_BASE + otherCounter);
em.persist(customer);
em.flush();
++otherCounter;
@@ -212,10 +216,11 @@ public class CustomerResourceIntTest {
// Create the Customer
CustomerDTO customerDTO = customerMapper.toDto(customer);
restCustomerMockMvc.perform(post("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isCreated());
restCustomerMockMvc.perform(
post("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isCreated());
// Validate the Customer in the database
List<Customer> customerList = customerRepository.findAll();
@@ -250,10 +255,11 @@ public class CustomerResourceIntTest {
CustomerDTO customerDTO = customerMapper.toDto(customer);
// An entity with an existing ID cannot be created, so this API call must fail
restCustomerMockMvc.perform(post("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isBadRequest());
restCustomerMockMvc.perform(
post("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isBadRequest());
// Validate the Customer in the database
List<Customer> customerList = customerRepository.findAll();
@@ -270,10 +276,11 @@ public class CustomerResourceIntTest {
CustomerDTO customerDTO = customerMapper.toDto(customer);
// An entity with an existing ID cannot be created, so this API call must fail
restCustomerMockMvc.perform(post("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isBadRequest());
restCustomerMockMvc.perform(
post("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isBadRequest());
// Validate the Customer in the database
List<Customer> customerList = customerRepository.findAll();
@@ -290,10 +297,11 @@ public class CustomerResourceIntTest {
// Create the Customer, which fails.
CustomerDTO customerDTO = customerMapper.toDto(customer);
restCustomerMockMvc.perform(post("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isBadRequest());
restCustomerMockMvc.perform(
post("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isBadRequest());
List<Customer> customerList = customerRepository.findAll();
assertThat(customerList).hasSize(databaseSizeBeforeTest);
@@ -309,10 +317,11 @@ public class CustomerResourceIntTest {
// Create the Customer, which fails.
CustomerDTO customerDTO = customerMapper.toDto(customer);
restCustomerMockMvc.perform(post("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isBadRequest());
restCustomerMockMvc.perform(
post("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isBadRequest());
List<Customer> customerList = customerRepository.findAll();
assertThat(customerList).hasSize(databaseSizeBeforeTest);
@@ -328,10 +337,11 @@ public class CustomerResourceIntTest {
// Create the Customer, which fails.
CustomerDTO customerDTO = customerMapper.toDto(customer);
restCustomerMockMvc.perform(post("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isBadRequest());
restCustomerMockMvc.perform(
post("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isBadRequest());
List<Customer> customerList = customerRepository.findAll();
assertThat(customerList).hasSize(databaseSizeBeforeTest);
@@ -347,10 +357,11 @@ public class CustomerResourceIntTest {
// Create the Customer, which fails.
CustomerDTO customerDTO = customerMapper.toDto(customer);
restCustomerMockMvc.perform(post("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isBadRequest());
restCustomerMockMvc.perform(
post("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isBadRequest());
List<Customer> customerList = customerRepository.findAll();
assertThat(customerList).hasSize(databaseSizeBeforeTest);
@@ -366,10 +377,11 @@ public class CustomerResourceIntTest {
// Create the Customer, which fails.
CustomerDTO customerDTO = customerMapper.toDto(customer);
restCustomerMockMvc.perform(post("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isBadRequest());
restCustomerMockMvc.perform(
post("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isBadRequest());
List<Customer> customerList = customerRepository.findAll();
assertThat(customerList).hasSize(databaseSizeBeforeTest);
@@ -385,10 +397,11 @@ public class CustomerResourceIntTest {
// Create the Customer, which fails.
CustomerDTO customerDTO = customerMapper.toDto(customer);
restCustomerMockMvc.perform(post("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isBadRequest());
restCustomerMockMvc.perform(
post("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isBadRequest());
List<Customer> customerList = customerRepository.findAll();
assertThat(customerList).hasSize(databaseSizeBeforeTest);
@@ -402,24 +415,24 @@ public class CustomerResourceIntTest {
// Get all the customerList
restCustomerMockMvc.perform(get("/api/customers?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(customer.getId().intValue())))
.andExpect(jsonPath("$.[*].reference").value(hasItem(DEFAULT_REFERENCE)))
.andExpect(jsonPath("$.[*].prefix").value(hasItem(DEFAULT_PREFIX)))
.andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
.andExpect(jsonPath("$.[*].kind").value(hasItem(DEFAULT_KIND.toString())))
.andExpect(jsonPath("$.[*].birthDate").value(hasItem(DEFAULT_BIRTH_DATE.toString())))
.andExpect(jsonPath("$.[*].birthPlace").value(hasItem(DEFAULT_BIRTH_PLACE)))
.andExpect(jsonPath("$.[*].registrationCourt").value(hasItem(DEFAULT_REGISTRATION_COURT)))
.andExpect(jsonPath("$.[*].registrationNumber").value(hasItem(DEFAULT_REGISTRATION_NUMBER)))
.andExpect(jsonPath("$.[*].vatRegion").value(hasItem(DEFAULT_VAT_REGION.toString())))
.andExpect(jsonPath("$.[*].vatNumber").value(hasItem(DEFAULT_VAT_NUMBER)))
.andExpect(jsonPath("$.[*].contractualSalutation").value(hasItem(DEFAULT_CONTRACTUAL_SALUTATION)))
.andExpect(jsonPath("$.[*].contractualAddress").value(hasItem(DEFAULT_CONTRACTUAL_ADDRESS)))
.andExpect(jsonPath("$.[*].billingSalutation").value(hasItem(DEFAULT_BILLING_SALUTATION)))
.andExpect(jsonPath("$.[*].billingAddress").value(hasItem(DEFAULT_BILLING_ADDRESS)))
.andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK)));
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(customer.getId().intValue())))
.andExpect(jsonPath("$.[*].reference").value(hasItem(DEFAULT_REFERENCE)))
.andExpect(jsonPath("$.[*].prefix").value(hasItem(DEFAULT_PREFIX)))
.andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
.andExpect(jsonPath("$.[*].kind").value(hasItem(DEFAULT_KIND.toString())))
.andExpect(jsonPath("$.[*].birthDate").value(hasItem(DEFAULT_BIRTH_DATE.toString())))
.andExpect(jsonPath("$.[*].birthPlace").value(hasItem(DEFAULT_BIRTH_PLACE)))
.andExpect(jsonPath("$.[*].registrationCourt").value(hasItem(DEFAULT_REGISTRATION_COURT)))
.andExpect(jsonPath("$.[*].registrationNumber").value(hasItem(DEFAULT_REGISTRATION_NUMBER)))
.andExpect(jsonPath("$.[*].vatRegion").value(hasItem(DEFAULT_VAT_REGION.toString())))
.andExpect(jsonPath("$.[*].vatNumber").value(hasItem(DEFAULT_VAT_NUMBER)))
.andExpect(jsonPath("$.[*].contractualSalutation").value(hasItem(DEFAULT_CONTRACTUAL_SALUTATION)))
.andExpect(jsonPath("$.[*].contractualAddress").value(hasItem(DEFAULT_CONTRACTUAL_ADDRESS)))
.andExpect(jsonPath("$.[*].billingSalutation").value(hasItem(DEFAULT_BILLING_SALUTATION)))
.andExpect(jsonPath("$.[*].billingAddress").value(hasItem(DEFAULT_BILLING_ADDRESS)))
.andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK)));
}
@Test
@@ -430,24 +443,24 @@ public class CustomerResourceIntTest {
// Get the customer
restCustomerMockMvc.perform(get("/api/customers/{id}", customer.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(customer.getId().intValue()))
.andExpect(jsonPath("$.reference").value(DEFAULT_REFERENCE))
.andExpect(jsonPath("$.prefix").value(DEFAULT_PREFIX))
.andExpect(jsonPath("$.name").value(DEFAULT_NAME))
.andExpect(jsonPath("$.kind").value(DEFAULT_KIND.toString()))
.andExpect(jsonPath("$.birthDate").value(DEFAULT_BIRTH_DATE.toString()))
.andExpect(jsonPath("$.birthPlace").value(DEFAULT_BIRTH_PLACE))
.andExpect(jsonPath("$.registrationCourt").value(DEFAULT_REGISTRATION_COURT))
.andExpect(jsonPath("$.registrationNumber").value(DEFAULT_REGISTRATION_NUMBER))
.andExpect(jsonPath("$.vatRegion").value(DEFAULT_VAT_REGION.toString()))
.andExpect(jsonPath("$.vatNumber").value(DEFAULT_VAT_NUMBER))
.andExpect(jsonPath("$.contractualSalutation").value(DEFAULT_CONTRACTUAL_SALUTATION))
.andExpect(jsonPath("$.contractualAddress").value(DEFAULT_CONTRACTUAL_ADDRESS))
.andExpect(jsonPath("$.billingSalutation").value(DEFAULT_BILLING_SALUTATION))
.andExpect(jsonPath("$.billingAddress").value(DEFAULT_BILLING_ADDRESS))
.andExpect(jsonPath("$.remark").value(DEFAULT_REMARK));
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(customer.getId().intValue()))
.andExpect(jsonPath("$.reference").value(DEFAULT_REFERENCE))
.andExpect(jsonPath("$.prefix").value(DEFAULT_PREFIX))
.andExpect(jsonPath("$.name").value(DEFAULT_NAME))
.andExpect(jsonPath("$.kind").value(DEFAULT_KIND.toString()))
.andExpect(jsonPath("$.birthDate").value(DEFAULT_BIRTH_DATE.toString()))
.andExpect(jsonPath("$.birthPlace").value(DEFAULT_BIRTH_PLACE))
.andExpect(jsonPath("$.registrationCourt").value(DEFAULT_REGISTRATION_COURT))
.andExpect(jsonPath("$.registrationNumber").value(DEFAULT_REGISTRATION_NUMBER))
.andExpect(jsonPath("$.vatRegion").value(DEFAULT_VAT_REGION.toString()))
.andExpect(jsonPath("$.vatNumber").value(DEFAULT_VAT_NUMBER))
.andExpect(jsonPath("$.contractualSalutation").value(DEFAULT_CONTRACTUAL_SALUTATION))
.andExpect(jsonPath("$.contractualAddress").value(DEFAULT_CONTRACTUAL_ADDRESS))
.andExpect(jsonPath("$.billingSalutation").value(DEFAULT_BILLING_SALUTATION))
.andExpect(jsonPath("$.billingAddress").value(DEFAULT_BILLING_ADDRESS))
.andExpect(jsonPath("$.remark").value(DEFAULT_REMARK));
}
@Test
@@ -515,7 +528,6 @@ public class CustomerResourceIntTest {
defaultCustomerShouldBeFound("reference.lessThan=" + (DEFAULT_REFERENCE + 1));
}
@Test
@Transactional
public void getAllCustomersByPrefixIsEqualToSomething() throws Exception {
@@ -698,7 +710,6 @@ public class CustomerResourceIntTest {
defaultCustomerShouldBeFound("birthDate.lessThan=" + UPDATED_BIRTH_DATE);
}
@Test
@Transactional
public void getAllCustomersByBirthPlaceIsEqualToSomething() throws Exception {
@@ -797,7 +808,8 @@ public class CustomerResourceIntTest {
customerRepository.saveAndFlush(customer);
// Get all the customerList where registrationNumber in DEFAULT_REGISTRATION_NUMBER or UPDATED_REGISTRATION_NUMBER
defaultCustomerShouldBeFound("registrationNumber.in=" + DEFAULT_REGISTRATION_NUMBER + "," + UPDATED_REGISTRATION_NUMBER);
defaultCustomerShouldBeFound(
"registrationNumber.in=" + DEFAULT_REGISTRATION_NUMBER + "," + UPDATED_REGISTRATION_NUMBER);
// Get all the customerList where registrationNumber equals to UPDATED_REGISTRATION_NUMBER
defaultCustomerShouldNotBeFound("registrationNumber.in=" + UPDATED_REGISTRATION_NUMBER);
@@ -913,8 +925,10 @@ public class CustomerResourceIntTest {
// Initialize the database
customerRepository.saveAndFlush(customer);
// Get all the customerList where contractualSalutation in DEFAULT_CONTRACTUAL_SALUTATION or UPDATED_CONTRACTUAL_SALUTATION
defaultCustomerShouldBeFound("contractualSalutation.in=" + DEFAULT_CONTRACTUAL_SALUTATION + "," + UPDATED_CONTRACTUAL_SALUTATION);
// Get all the customerList where contractualSalutation in DEFAULT_CONTRACTUAL_SALUTATION or
// UPDATED_CONTRACTUAL_SALUTATION
defaultCustomerShouldBeFound(
"contractualSalutation.in=" + DEFAULT_CONTRACTUAL_SALUTATION + "," + UPDATED_CONTRACTUAL_SALUTATION);
// Get all the customerList where contractualSalutation equals to UPDATED_CONTRACTUAL_SALUTATION
defaultCustomerShouldNotBeFound("contractualSalutation.in=" + UPDATED_CONTRACTUAL_SALUTATION);
@@ -953,7 +967,8 @@ public class CustomerResourceIntTest {
customerRepository.saveAndFlush(customer);
// Get all the customerList where contractualAddress in DEFAULT_CONTRACTUAL_ADDRESS or UPDATED_CONTRACTUAL_ADDRESS
defaultCustomerShouldBeFound("contractualAddress.in=" + DEFAULT_CONTRACTUAL_ADDRESS + "," + UPDATED_CONTRACTUAL_ADDRESS);
defaultCustomerShouldBeFound(
"contractualAddress.in=" + DEFAULT_CONTRACTUAL_ADDRESS + "," + UPDATED_CONTRACTUAL_ADDRESS);
// Get all the customerList where contractualAddress equals to UPDATED_CONTRACTUAL_ADDRESS
defaultCustomerShouldNotBeFound("contractualAddress.in=" + UPDATED_CONTRACTUAL_ADDRESS);
@@ -1107,7 +1122,6 @@ public class CustomerResourceIntTest {
defaultCustomerShouldNotBeFound("membershipId.equals=" + (membershipId + 1));
}
@Test
@Transactional
public void getAllCustomersBySepamandateIsEqualToSomething() throws Exception {
@@ -1131,30 +1145,30 @@ public class CustomerResourceIntTest {
*/
private void defaultCustomerShouldBeFound(String filter) throws Exception {
restCustomerMockMvc.perform(get("/api/customers?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(customer.getId().intValue())))
.andExpect(jsonPath("$.[*].reference").value(hasItem(DEFAULT_REFERENCE)))
.andExpect(jsonPath("$.[*].prefix").value(hasItem(DEFAULT_PREFIX)))
.andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
.andExpect(jsonPath("$.[*].kind").value(hasItem(DEFAULT_KIND.toString())))
.andExpect(jsonPath("$.[*].birthDate").value(hasItem(DEFAULT_BIRTH_DATE.toString())))
.andExpect(jsonPath("$.[*].birthPlace").value(hasItem(DEFAULT_BIRTH_PLACE)))
.andExpect(jsonPath("$.[*].registrationCourt").value(hasItem(DEFAULT_REGISTRATION_COURT)))
.andExpect(jsonPath("$.[*].registrationNumber").value(hasItem(DEFAULT_REGISTRATION_NUMBER)))
.andExpect(jsonPath("$.[*].vatRegion").value(hasItem(DEFAULT_VAT_REGION.toString())))
.andExpect(jsonPath("$.[*].vatNumber").value(hasItem(DEFAULT_VAT_NUMBER)))
.andExpect(jsonPath("$.[*].contractualSalutation").value(hasItem(DEFAULT_CONTRACTUAL_SALUTATION)))
.andExpect(jsonPath("$.[*].contractualAddress").value(hasItem(DEFAULT_CONTRACTUAL_ADDRESS)))
.andExpect(jsonPath("$.[*].billingSalutation").value(hasItem(DEFAULT_BILLING_SALUTATION)))
.andExpect(jsonPath("$.[*].billingAddress").value(hasItem(DEFAULT_BILLING_ADDRESS)))
.andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK)));
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(customer.getId().intValue())))
.andExpect(jsonPath("$.[*].reference").value(hasItem(DEFAULT_REFERENCE)))
.andExpect(jsonPath("$.[*].prefix").value(hasItem(DEFAULT_PREFIX)))
.andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
.andExpect(jsonPath("$.[*].kind").value(hasItem(DEFAULT_KIND.toString())))
.andExpect(jsonPath("$.[*].birthDate").value(hasItem(DEFAULT_BIRTH_DATE.toString())))
.andExpect(jsonPath("$.[*].birthPlace").value(hasItem(DEFAULT_BIRTH_PLACE)))
.andExpect(jsonPath("$.[*].registrationCourt").value(hasItem(DEFAULT_REGISTRATION_COURT)))
.andExpect(jsonPath("$.[*].registrationNumber").value(hasItem(DEFAULT_REGISTRATION_NUMBER)))
.andExpect(jsonPath("$.[*].vatRegion").value(hasItem(DEFAULT_VAT_REGION.toString())))
.andExpect(jsonPath("$.[*].vatNumber").value(hasItem(DEFAULT_VAT_NUMBER)))
.andExpect(jsonPath("$.[*].contractualSalutation").value(hasItem(DEFAULT_CONTRACTUAL_SALUTATION)))
.andExpect(jsonPath("$.[*].contractualAddress").value(hasItem(DEFAULT_CONTRACTUAL_ADDRESS)))
.andExpect(jsonPath("$.[*].billingSalutation").value(hasItem(DEFAULT_BILLING_SALUTATION)))
.andExpect(jsonPath("$.[*].billingAddress").value(hasItem(DEFAULT_BILLING_ADDRESS)))
.andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK)));
// Check, that the count call also returns 1
restCustomerMockMvc.perform(get("/api/customers/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("1"));
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("1"));
}
/**
@@ -1162,25 +1176,24 @@ public class CustomerResourceIntTest {
*/
private void defaultCustomerShouldNotBeFound(String filter) throws Exception {
restCustomerMockMvc.perform(get("/api/customers?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
.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
restCustomerMockMvc.perform(get("/api/customers/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("0"));
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("0"));
}
@Test
@Transactional
public void getNonExistingCustomer() throws Exception {
// Get the customer
restCustomerMockMvc.perform(get("/api/customers/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
.andExpect(status().isNotFound());
}
@Test
@@ -1196,27 +1209,28 @@ public class CustomerResourceIntTest {
// Disconnect from session so that the updates on updatedCustomer are not directly saved in db
em.detach(updatedCustomer);
updatedCustomer
.reference(null)
.prefix(null)
.name(UPDATED_NAME)
.kind(UPDATED_KIND)
.birthDate(UPDATED_BIRTH_DATE)
.birthPlace(UPDATED_BIRTH_PLACE)
.registrationCourt(UPDATED_REGISTRATION_COURT)
.registrationNumber(UPDATED_REGISTRATION_NUMBER)
.vatRegion(UPDATED_VAT_REGION)
.vatNumber(UPDATED_VAT_NUMBER)
.contractualSalutation(UPDATED_CONTRACTUAL_SALUTATION)
.contractualAddress(UPDATED_CONTRACTUAL_ADDRESS)
.billingSalutation(UPDATED_BILLING_SALUTATION)
.billingAddress(UPDATED_BILLING_ADDRESS)
.remark(UPDATED_REMARK);
.reference(null)
.prefix(null)
.name(UPDATED_NAME)
.kind(UPDATED_KIND)
.birthDate(UPDATED_BIRTH_DATE)
.birthPlace(UPDATED_BIRTH_PLACE)
.registrationCourt(UPDATED_REGISTRATION_COURT)
.registrationNumber(UPDATED_REGISTRATION_NUMBER)
.vatRegion(UPDATED_VAT_REGION)
.vatNumber(UPDATED_VAT_NUMBER)
.contractualSalutation(UPDATED_CONTRACTUAL_SALUTATION)
.contractualAddress(UPDATED_CONTRACTUAL_ADDRESS)
.billingSalutation(UPDATED_BILLING_SALUTATION)
.billingAddress(UPDATED_BILLING_ADDRESS)
.remark(UPDATED_REMARK);
CustomerDTO customerDTO = customerMapper.toDto(updatedCustomer);
restCustomerMockMvc.perform(put("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isOk());
restCustomerMockMvc.perform(
put("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isOk());
// Validate the Customer in the database
List<Customer> customerList = customerRepository.findAll();
@@ -1248,10 +1262,11 @@ public class CustomerResourceIntTest {
CustomerDTO customerDTO = customerMapper.toDto(customer);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restCustomerMockMvc.perform(put("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isBadRequest());
restCustomerMockMvc.perform(
put("/api/customers")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(customerDTO)))
.andExpect(status().isBadRequest());
// Validate the Customer in the database
List<Customer> customerList = customerRepository.findAll();
@@ -1267,9 +1282,10 @@ public class CustomerResourceIntTest {
int databaseSizeBeforeDelete = customerRepository.findAll().size();
// Delete the customer
restCustomerMockMvc.perform(delete("/api/customers/{id}", customer.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest());
restCustomerMockMvc.perform(
delete("/api/customers/{id}", customer.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest());
// Validate the database is unchanged
List<Customer> customerList = customerRepository.findAll();

@@ -1,9 +1,18 @@
// 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;
@@ -14,12 +23,6 @@ import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Test class for the LogsResource REST controller.
*
@@ -35,15 +38,15 @@ public class LogsResourceIntTest {
public void setup() {
LogsResource logsResource = new LogsResource();
this.restLogsMockMvc = MockMvcBuilders
.standaloneSetup(logsResource)
.build();
.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));
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
}
@Test
@@ -52,10 +55,11 @@ public class LogsResourceIntTest {
logger.setLevel("INFO");
logger.setName("ROOT");
restLogsMockMvc.perform(put("/management/logs")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(logger)))
.andExpect(status().isNoContent());
restLogsMockMvc.perform(
put("/management/logs")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(logger)))
.andExpect(status().isNoContent());
}
@Test

@@ -1,5 +1,12 @@
// 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;
@@ -13,6 +20,7 @@ import org.hostsharing.hsadminng.service.accessfilter.Role;
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;
@@ -28,16 +36,11 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Validator;
import javax.persistence.EntityManager;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
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 javax.persistence.EntityManager;
/**
* Test class for the MembershipResource REST controller.
@@ -54,8 +57,12 @@ public class MembershipResourceIntTest {
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_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());
@@ -105,11 +112,12 @@ public class MembershipResourceIntTest {
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();
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator)
.build();
}
/**
@@ -120,11 +128,11 @@ public class MembershipResourceIntTest {
*/
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);
.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);
@@ -141,10 +149,10 @@ public class MembershipResourceIntTest {
*/
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);
.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);
@@ -164,10 +172,11 @@ public class MembershipResourceIntTest {
// Create the Membership
MembershipDTO membershipDTO = membershipMapper.toDto(membership);
restMembershipMockMvc.perform(post("/api/memberships")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(membershipDTO)))
.andExpect(status().isCreated());
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();
@@ -192,10 +201,11 @@ public class MembershipResourceIntTest {
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());
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();
@@ -212,10 +222,11 @@ public class MembershipResourceIntTest {
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());
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();
@@ -232,10 +243,11 @@ public class MembershipResourceIntTest {
// 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());
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);
@@ -251,10 +263,11 @@ public class MembershipResourceIntTest {
// 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());
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);
@@ -268,14 +281,16 @@ public class MembershipResourceIntTest {
// 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)));
.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
@@ -286,14 +301,14 @@ public class MembershipResourceIntTest {
// 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));
.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
@@ -315,8 +330,10 @@ public class MembershipResourceIntTest {
// 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 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);
@@ -361,7 +378,6 @@ public class MembershipResourceIntTest {
defaultMembershipShouldBeFound("admissionDocumentDate.lessThan=" + UPDATED_ADMISSION_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllMembershipsByCancellationDocumentDateIsEqualToSomething() throws Exception {
@@ -381,8 +397,10 @@ public class MembershipResourceIntTest {
// 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 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);
@@ -407,10 +425,12 @@ public class MembershipResourceIntTest {
// Initialize the database
membershipRepository.saveAndFlush(membership);
// Get all the membershipList where cancellationDocumentDate greater than or equals to DEFAULT_CANCELLATION_DOCUMENT_DATE
// 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
// Get all the membershipList where cancellationDocumentDate greater than or equals to
// UPDATED_CANCELLATION_DOCUMENT_DATE
defaultMembershipShouldNotBeFound("cancellationDocumentDate.greaterOrEqualThan=" + UPDATED_CANCELLATION_DOCUMENT_DATE);
}
@@ -427,7 +447,6 @@ public class MembershipResourceIntTest {
defaultMembershipShouldBeFound("cancellationDocumentDate.lessThan=" + UPDATED_CANCELLATION_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllMembershipsByMemberFromDateIsEqualToSomething() throws Exception {
@@ -493,7 +512,6 @@ public class MembershipResourceIntTest {
defaultMembershipShouldBeFound("memberFromDate.lessThan=" + UPDATED_MEMBER_FROM_DATE);
}
@Test
@Transactional
public void getAllMembershipsByMemberUntilDateIsEqualToSomething() throws Exception {
@@ -559,7 +577,6 @@ public class MembershipResourceIntTest {
defaultMembershipShouldBeFound("memberUntilDate.lessThan=" + UPDATED_MEMBER_UNTIL_DATE);
}
@Test
@Transactional
public void getAllMembershipsByRemarkIsEqualToSomething() throws Exception {
@@ -615,7 +632,6 @@ public class MembershipResourceIntTest {
defaultMembershipShouldNotBeFound("shareId.equals=" + (shareId + 1));
}
@Test
@Transactional
public void getAllMembershipsByAssetIsEqualToSomething() throws Exception {
@@ -632,7 +648,6 @@ public class MembershipResourceIntTest {
defaultMembershipShouldNotBeFound("assetId.equals=" + (assetId + 1));
}
@Test
@Transactional
public void getAllMembershipsByCustomerIsEqualToSomething() throws Exception {
@@ -654,20 +669,22 @@ public class MembershipResourceIntTest {
*/
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)));
.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"));
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("1"));
}
/**
@@ -675,25 +692,24 @@ public class MembershipResourceIntTest {
*/
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());
.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"));
.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());
.andExpect(status().isNotFound());
}
@Test
@@ -709,15 +725,16 @@ public class MembershipResourceIntTest {
// 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);
.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());
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();
@@ -739,10 +756,11 @@ public class MembershipResourceIntTest {
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());
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();
@@ -758,9 +776,10 @@ public class MembershipResourceIntTest {
int databaseSizeBeforeDelete = membershipRepository.findAll().size();
// Delete the membership
restMembershipMockMvc.perform(delete("/api/memberships/{id}", membership.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest());
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();

@@ -1,5 +1,12 @@
// 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.Customer;
import org.hostsharing.hsadminng.domain.SepaMandate;
@@ -12,6 +19,7 @@ import org.hostsharing.hsadminng.service.dto.CustomerDTO;
import org.hostsharing.hsadminng.service.dto.SepaMandateDTO;
import org.hostsharing.hsadminng.service.mapper.SepaMandateMapper;
import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -27,16 +35,11 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Validator;
import javax.persistence.EntityManager;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
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 javax.persistence.EntityManager;
/**
* Test class for the SepaMandateResource REST controller.
@@ -113,11 +116,12 @@ public class SepaMandateResourceIntTest {
MockitoAnnotations.initMocks(this);
final SepaMandateResource sepaMandateResource = new SepaMandateResource(sepaMandateService, sepaMandateQueryService);
this.restSepaMandateMockMvc = MockMvcBuilders.standaloneSetup(sepaMandateResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator).build();
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator)
.build();
}
/**
@@ -128,15 +132,15 @@ public class SepaMandateResourceIntTest {
*/
public static SepaMandate createEntity(EntityManager em) {
SepaMandate sepaMandate = new SepaMandate()
.reference(DEFAULT_REFERENCE)
.iban(DEFAULT_IBAN)
.bic(DEFAULT_BIC)
.grantingDocumentDate(DEFAULT_GRANTING_DOCUMENT_DATE)
.revokationDocumentDate(DEFAULT_REVOKATION_DOCUMENT_DATE)
.validFromDate(DEFAULT_VALID_FROM_DATE)
.validUntilDate(DEFAULT_VALID_UNTIL_DATE)
.lastUsedDate(DEFAULT_LAST_USED_DATE)
.remark(DEFAULT_REMARK);
.reference(DEFAULT_REFERENCE)
.iban(DEFAULT_IBAN)
.bic(DEFAULT_BIC)
.grantingDocumentDate(DEFAULT_GRANTING_DOCUMENT_DATE)
.revokationDocumentDate(DEFAULT_REVOKATION_DOCUMENT_DATE)
.validFromDate(DEFAULT_VALID_FROM_DATE)
.validUntilDate(DEFAULT_VALID_UNTIL_DATE)
.lastUsedDate(DEFAULT_LAST_USED_DATE)
.remark(DEFAULT_REMARK);
// Add required entity
Customer customer = CustomerResourceIntTest.createEntity(em);
em.persist(customer);
@@ -153,15 +157,15 @@ public class SepaMandateResourceIntTest {
*/
public static SepaMandate createEntity(EntityManager em, final Customer customer) {
SepaMandate sepaMandate = new SepaMandate()
.reference(DEFAULT_REFERENCE)
.iban(DEFAULT_IBAN)
.bic(DEFAULT_BIC)
.grantingDocumentDate(DEFAULT_GRANTING_DOCUMENT_DATE)
.validFromDate(DEFAULT_VALID_FROM_DATE)
.validUntilDate(DEFAULT_VALID_UNTIL_DATE)
.lastUsedDate(DEFAULT_LAST_USED_DATE)
.revokationDocumentDate(DEFAULT_REVOKATION_DOCUMENT_DATE)
.remark(DEFAULT_REMARK);
.reference(DEFAULT_REFERENCE)
.iban(DEFAULT_IBAN)
.bic(DEFAULT_BIC)
.grantingDocumentDate(DEFAULT_GRANTING_DOCUMENT_DATE)
.validFromDate(DEFAULT_VALID_FROM_DATE)
.validUntilDate(DEFAULT_VALID_UNTIL_DATE)
.lastUsedDate(DEFAULT_LAST_USED_DATE)
.revokationDocumentDate(DEFAULT_REVOKATION_DOCUMENT_DATE)
.remark(DEFAULT_REMARK);
// Add required entity
sepaMandate.setCustomer(customer);
return sepaMandate;
@@ -186,10 +190,11 @@ public class SepaMandateResourceIntTest {
MockSecurityContext.givenAuthenticatedUser();
MockSecurityContext.givenUserHavingRole(CustomerDTO.class, sepaMandateDTO.getCustomerId(), Role.FINANCIAL_CONTACT);
restSepaMandateMockMvc.perform(post("/api/sepa-mandates")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO)))
.andExpect(status().isCreated());
restSepaMandateMockMvc.perform(
post("/api/sepa-mandates")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO)))
.andExpect(status().isCreated());
// Validate the SepaMandate in the database
List<SepaMandate> sepaMandateList = sepaMandateRepository.findAll();
@@ -216,10 +221,11 @@ public class SepaMandateResourceIntTest {
SepaMandateDTO sepaMandateDTO = sepaMandateMapper.toDto(sepaMandate);
// An entity with an existing ID cannot be created, so this API call must fail
restSepaMandateMockMvc.perform(post("/api/sepa-mandates")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO)))
.andExpect(status().isBadRequest());
restSepaMandateMockMvc.perform(
post("/api/sepa-mandates")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO)))
.andExpect(status().isBadRequest());
// Validate the SepaMandate in the database
List<SepaMandate> sepaMandateList = sepaMandateRepository.findAll();
@@ -236,10 +242,11 @@ public class SepaMandateResourceIntTest {
// Create the SepaMandate, which fails.
SepaMandateDTO sepaMandateDTO = sepaMandateMapper.toDto(sepaMandate);
restSepaMandateMockMvc.perform(post("/api/sepa-mandates")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO)))
.andExpect(status().isBadRequest());
restSepaMandateMockMvc.perform(
post("/api/sepa-mandates")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO)))
.andExpect(status().isBadRequest());
List<SepaMandate> sepaMandateList = sepaMandateRepository.findAll();
assertThat(sepaMandateList).hasSize(databaseSizeBeforeTest);
@@ -255,10 +262,11 @@ public class SepaMandateResourceIntTest {
// Create the SepaMandate, which fails.
SepaMandateDTO sepaMandateDTO = sepaMandateMapper.toDto(sepaMandate);
restSepaMandateMockMvc.perform(post("/api/sepa-mandates")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO)))
.andExpect(status().isBadRequest());
restSepaMandateMockMvc.perform(
post("/api/sepa-mandates")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO)))
.andExpect(status().isBadRequest());
List<SepaMandate> sepaMandateList = sepaMandateRepository.findAll();
assertThat(sepaMandateList).hasSize(databaseSizeBeforeTest);
@@ -274,10 +282,11 @@ public class SepaMandateResourceIntTest {
// Create the SepaMandate, which fails.
SepaMandateDTO sepaMandateDTO = sepaMandateMapper.toDto(sepaMandate);
restSepaMandateMockMvc.perform(post("/api/sepa-mandates")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO)))
.andExpect(status().isBadRequest());
restSepaMandateMockMvc.perform(
post("/api/sepa-mandates")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO)))
.andExpect(status().isBadRequest());
List<SepaMandate> sepaMandateList = sepaMandateRepository.findAll();
assertThat(sepaMandateList).hasSize(databaseSizeBeforeTest);
@@ -291,20 +300,20 @@ public class SepaMandateResourceIntTest {
// Get all the sepaMandateList
restSepaMandateMockMvc.perform(get("/api/sepa-mandates?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(sepaMandate.getId().intValue())))
.andExpect(jsonPath("$.[*].reference").value(hasItem(DEFAULT_REFERENCE)))
.andExpect(jsonPath("$.[*].iban").value(hasItem(DEFAULT_IBAN)))
.andExpect(jsonPath("$.[*].bic").value(hasItem(DEFAULT_BIC)))
.andExpect(jsonPath("$.[*].grantingDocumentDate").value(hasItem(DEFAULT_GRANTING_DOCUMENT_DATE.toString())))
.andExpect(jsonPath("$.[*].revokationDocumentDate").value(hasItem(DEFAULT_REVOKATION_DOCUMENT_DATE.toString())))
.andExpect(jsonPath("$.[*].validFromDate").value(hasItem(DEFAULT_VALID_FROM_DATE.toString())))
.andExpect(jsonPath("$.[*].validUntilDate").value(hasItem(DEFAULT_VALID_UNTIL_DATE.toString())))
.andExpect(jsonPath("$.[*].lastUsedDate").value(hasItem(DEFAULT_LAST_USED_DATE.toString())))
.andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK)));
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(sepaMandate.getId().intValue())))
.andExpect(jsonPath("$.[*].reference").value(hasItem(DEFAULT_REFERENCE)))
.andExpect(jsonPath("$.[*].iban").value(hasItem(DEFAULT_IBAN)))
.andExpect(jsonPath("$.[*].bic").value(hasItem(DEFAULT_BIC)))
.andExpect(jsonPath("$.[*].grantingDocumentDate").value(hasItem(DEFAULT_GRANTING_DOCUMENT_DATE.toString())))
.andExpect(jsonPath("$.[*].revokationDocumentDate").value(hasItem(DEFAULT_REVOKATION_DOCUMENT_DATE.toString())))
.andExpect(jsonPath("$.[*].validFromDate").value(hasItem(DEFAULT_VALID_FROM_DATE.toString())))
.andExpect(jsonPath("$.[*].validUntilDate").value(hasItem(DEFAULT_VALID_UNTIL_DATE.toString())))
.andExpect(jsonPath("$.[*].lastUsedDate").value(hasItem(DEFAULT_LAST_USED_DATE.toString())))
.andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK)));
}
@Test
@Transactional
public void getSepaMandate() throws Exception {
@@ -313,18 +322,18 @@ public class SepaMandateResourceIntTest {
// Get the sepaMandate
restSepaMandateMockMvc.perform(get("/api/sepa-mandates/{id}", sepaMandate.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(sepaMandate.getId().intValue()))
.andExpect(jsonPath("$.reference").value(DEFAULT_REFERENCE))
.andExpect(jsonPath("$.iban").value(DEFAULT_IBAN))
.andExpect(jsonPath("$.bic").value(DEFAULT_BIC))
.andExpect(jsonPath("$.grantingDocumentDate").value(DEFAULT_GRANTING_DOCUMENT_DATE.toString()))
.andExpect(jsonPath("$.revokationDocumentDate").value(DEFAULT_REVOKATION_DOCUMENT_DATE.toString()))
.andExpect(jsonPath("$.validFromDate").value(DEFAULT_VALID_FROM_DATE.toString()))
.andExpect(jsonPath("$.validUntilDate").value(DEFAULT_VALID_UNTIL_DATE.toString()))
.andExpect(jsonPath("$.lastUsedDate").value(DEFAULT_LAST_USED_DATE.toString()))
.andExpect(jsonPath("$.remark").value(DEFAULT_REMARK));
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(sepaMandate.getId().intValue()))
.andExpect(jsonPath("$.reference").value(DEFAULT_REFERENCE))
.andExpect(jsonPath("$.iban").value(DEFAULT_IBAN))
.andExpect(jsonPath("$.bic").value(DEFAULT_BIC))
.andExpect(jsonPath("$.grantingDocumentDate").value(DEFAULT_GRANTING_DOCUMENT_DATE.toString()))
.andExpect(jsonPath("$.revokationDocumentDate").value(DEFAULT_REVOKATION_DOCUMENT_DATE.toString()))
.andExpect(jsonPath("$.validFromDate").value(DEFAULT_VALID_FROM_DATE.toString()))
.andExpect(jsonPath("$.validUntilDate").value(DEFAULT_VALID_UNTIL_DATE.toString()))
.andExpect(jsonPath("$.lastUsedDate").value(DEFAULT_LAST_USED_DATE.toString()))
.andExpect(jsonPath("$.remark").value(DEFAULT_REMARK));
}
@Test
@@ -463,8 +472,10 @@ public class SepaMandateResourceIntTest {
// Initialize the database
sepaMandateRepository.saveAndFlush(sepaMandate);
// Get all the sepaMandateList where grantingDocumentDate in DEFAULT_GRANTING_DOCUMENT_DATE or UPDATED_GRANTING_DOCUMENT_DATE
defaultSepaMandateShouldBeFound("grantingDocumentDate.in=" + DEFAULT_GRANTING_DOCUMENT_DATE + "," + UPDATED_GRANTING_DOCUMENT_DATE);
// Get all the sepaMandateList where grantingDocumentDate in DEFAULT_GRANTING_DOCUMENT_DATE or
// UPDATED_GRANTING_DOCUMENT_DATE
defaultSepaMandateShouldBeFound(
"grantingDocumentDate.in=" + DEFAULT_GRANTING_DOCUMENT_DATE + "," + UPDATED_GRANTING_DOCUMENT_DATE);
// Get all the sepaMandateList where grantingDocumentDate equals to UPDATED_GRANTING_DOCUMENT_DATE
defaultSepaMandateShouldNotBeFound("grantingDocumentDate.in=" + UPDATED_GRANTING_DOCUMENT_DATE);
@@ -509,7 +520,6 @@ public class SepaMandateResourceIntTest {
defaultSepaMandateShouldBeFound("grantingDocumentDate.lessThan=" + UPDATED_GRANTING_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllSepaMandatesByRevokationDocumentDateIsEqualToSomething() throws Exception {
@@ -529,8 +539,10 @@ public class SepaMandateResourceIntTest {
// Initialize the database
sepaMandateRepository.saveAndFlush(sepaMandate);
// Get all the sepaMandateList where revokationDocumentDate in DEFAULT_REVOKATION_DOCUMENT_DATE or UPDATED_REVOKATION_DOCUMENT_DATE
defaultSepaMandateShouldBeFound("revokationDocumentDate.in=" + DEFAULT_REVOKATION_DOCUMENT_DATE + "," + UPDATED_REVOKATION_DOCUMENT_DATE);
// Get all the sepaMandateList where revokationDocumentDate in DEFAULT_REVOKATION_DOCUMENT_DATE or
// UPDATED_REVOKATION_DOCUMENT_DATE
defaultSepaMandateShouldBeFound(
"revokationDocumentDate.in=" + DEFAULT_REVOKATION_DOCUMENT_DATE + "," + UPDATED_REVOKATION_DOCUMENT_DATE);
// Get all the sepaMandateList where revokationDocumentDate equals to UPDATED_REVOKATION_DOCUMENT_DATE
defaultSepaMandateShouldNotBeFound("revokationDocumentDate.in=" + UPDATED_REVOKATION_DOCUMENT_DATE);
@@ -575,7 +587,6 @@ public class SepaMandateResourceIntTest {
defaultSepaMandateShouldBeFound("revokationDocumentDate.lessThan=" + UPDATED_REVOKATION_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllSepaMandatesByValidFromDateIsEqualToSomething() throws Exception {
@@ -641,7 +652,6 @@ public class SepaMandateResourceIntTest {
defaultSepaMandateShouldBeFound("validFromDate.lessThan=" + UPDATED_VALID_FROM_DATE);
}
@Test
@Transactional
public void getAllSepaMandatesByValidUntilDateIsEqualToSomething() throws Exception {
@@ -707,7 +717,6 @@ public class SepaMandateResourceIntTest {
defaultSepaMandateShouldBeFound("validUntilDate.lessThan=" + UPDATED_VALID_UNTIL_DATE);
}
@Test
@Transactional
public void getAllSepaMandatesByLastUsedDateIsEqualToSomething() throws Exception {
@@ -773,7 +782,6 @@ public class SepaMandateResourceIntTest {
defaultSepaMandateShouldBeFound("lastUsedDate.lessThan=" + UPDATED_LAST_USED_DATE);
}
@Test
@Transactional
public void getAllSepaMandatesByRemarkIsEqualToSomething() throws Exception {
@@ -834,24 +842,24 @@ public class SepaMandateResourceIntTest {
*/
private void defaultSepaMandateShouldBeFound(String filter) throws Exception {
restSepaMandateMockMvc.perform(get("/api/sepa-mandates?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(sepaMandate.getId().intValue())))
.andExpect(jsonPath("$.[*].reference").value(hasItem(DEFAULT_REFERENCE)))
.andExpect(jsonPath("$.[*].iban").value(hasItem(DEFAULT_IBAN)))
.andExpect(jsonPath("$.[*].bic").value(hasItem(DEFAULT_BIC)))
.andExpect(jsonPath("$.[*].grantingDocumentDate").value(hasItem(DEFAULT_GRANTING_DOCUMENT_DATE.toString())))
.andExpect(jsonPath("$.[*].revokationDocumentDate").value(hasItem(DEFAULT_REVOKATION_DOCUMENT_DATE.toString())))
.andExpect(jsonPath("$.[*].validFromDate").value(hasItem(DEFAULT_VALID_FROM_DATE.toString())))
.andExpect(jsonPath("$.[*].validUntilDate").value(hasItem(DEFAULT_VALID_UNTIL_DATE.toString())))
.andExpect(jsonPath("$.[*].lastUsedDate").value(hasItem(DEFAULT_LAST_USED_DATE.toString())))
.andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK)));
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(sepaMandate.getId().intValue())))
.andExpect(jsonPath("$.[*].reference").value(hasItem(DEFAULT_REFERENCE)))
.andExpect(jsonPath("$.[*].iban").value(hasItem(DEFAULT_IBAN)))
.andExpect(jsonPath("$.[*].bic").value(hasItem(DEFAULT_BIC)))
.andExpect(jsonPath("$.[*].grantingDocumentDate").value(hasItem(DEFAULT_GRANTING_DOCUMENT_DATE.toString())))
.andExpect(jsonPath("$.[*].revokationDocumentDate").value(hasItem(DEFAULT_REVOKATION_DOCUMENT_DATE.toString())))
.andExpect(jsonPath("$.[*].validFromDate").value(hasItem(DEFAULT_VALID_FROM_DATE.toString())))
.andExpect(jsonPath("$.[*].validUntilDate").value(hasItem(DEFAULT_VALID_UNTIL_DATE.toString())))
.andExpect(jsonPath("$.[*].lastUsedDate").value(hasItem(DEFAULT_LAST_USED_DATE.toString())))
.andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK)));
// Check, that the count call also returns 1
restSepaMandateMockMvc.perform(get("/api/sepa-mandates/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("1"));
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("1"));
}
/**
@@ -859,25 +867,24 @@ public class SepaMandateResourceIntTest {
*/
private void defaultSepaMandateShouldNotBeFound(String filter) throws Exception {
restSepaMandateMockMvc.perform(get("/api/sepa-mandates?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
.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
restSepaMandateMockMvc.perform(get("/api/sepa-mandates/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("0"));
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("0"));
}
@Test
@Transactional
public void getNonExistingSepaMandate() throws Exception {
// Get the sepaMandate
restSepaMandateMockMvc.perform(get("/api/sepa-mandates/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
.andExpect(status().isNotFound());
}
@Test
@@ -893,16 +900,17 @@ public class SepaMandateResourceIntTest {
// Disconnect from session so that the updates on updatedSepaMandate are not directly saved in db
em.detach(updatedSepaMandate);
updatedSepaMandate
.revokationDocumentDate(UPDATED_REVOKATION_DOCUMENT_DATE)
.validUntilDate(UPDATED_VALID_UNTIL_DATE)
.lastUsedDate(UPDATED_LAST_USED_DATE)
.remark(UPDATED_REMARK);
.revokationDocumentDate(UPDATED_REVOKATION_DOCUMENT_DATE)
.validUntilDate(UPDATED_VALID_UNTIL_DATE)
.lastUsedDate(UPDATED_LAST_USED_DATE)
.remark(UPDATED_REMARK);
SepaMandateDTO sepaMandateDTO = sepaMandateMapper.toDto(updatedSepaMandate);
restSepaMandateMockMvc.perform(put("/api/sepa-mandates")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO)))
.andExpect(status().isOk());
restSepaMandateMockMvc.perform(
put("/api/sepa-mandates")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO)))
.andExpect(status().isOk());
// Validate the SepaMandate in the database
List<SepaMandate> sepaMandateList = sepaMandateRepository.findAll();
@@ -928,10 +936,11 @@ public class SepaMandateResourceIntTest {
SepaMandateDTO sepaMandateDTO = sepaMandateMapper.toDto(sepaMandate);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restSepaMandateMockMvc.perform(put("/api/sepa-mandates")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO)))
.andExpect(status().isBadRequest());
restSepaMandateMockMvc.perform(
put("/api/sepa-mandates")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO)))
.andExpect(status().isBadRequest());
// Validate the SepaMandate in the database
List<SepaMandate> sepaMandateList = sepaMandateRepository.findAll();
@@ -947,9 +956,10 @@ public class SepaMandateResourceIntTest {
int databaseSizeBeforeDelete = sepaMandateRepository.findAll().size();
// Delete the sepaMandate
restSepaMandateMockMvc.perform(delete("/api/sepa-mandates/{id}", sepaMandate.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
restSepaMandateMockMvc.perform(
delete("/api/sepa-mandates/{id}", sepaMandate.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<SepaMandate> sepaMandateList = sepaMandateRepository.findAll();

@@ -1,17 +1,19 @@
// 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;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.assertj.core.api.ThrowableAssert.catchThrowable;
// Currently this class tests mostly special 'bad paths'
// which make little sense to test in *ResourceIntTest.
public class SepaMandateResourceUnitTest {

@@ -1,5 +1,12 @@
// 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;
@@ -12,6 +19,7 @@ import org.hostsharing.hsadminng.service.accessfilter.Role;
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;
@@ -27,16 +35,11 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Validator;
import javax.persistence.EntityManager;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
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 javax.persistence.EntityManager;
/**
* Test class for the ShareResource REST controller.
@@ -101,11 +104,12 @@ public class ShareResourceIntTest {
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();
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator)
.build();
}
/**
@@ -116,11 +120,11 @@ public class ShareResourceIntTest {
*/
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);
.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);
@@ -137,11 +141,11 @@ public class ShareResourceIntTest {
*/
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);
.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);
@@ -163,10 +167,11 @@ public class ShareResourceIntTest {
// 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());
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();
@@ -189,10 +194,11 @@ public class ShareResourceIntTest {
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());
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();
@@ -210,10 +216,11 @@ public class ShareResourceIntTest {
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());
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();
@@ -230,10 +237,11 @@ public class ShareResourceIntTest {
// 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());
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);
@@ -249,10 +257,11 @@ public class ShareResourceIntTest {
// 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());
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);
@@ -268,10 +277,11 @@ public class ShareResourceIntTest {
// 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());
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);
@@ -287,10 +297,11 @@ public class ShareResourceIntTest {
// 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());
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);
@@ -304,14 +315,14 @@ public class ShareResourceIntTest {
// 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())));
.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
@@ -322,14 +333,14 @@ public class ShareResourceIntTest {
// 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()));
.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
@@ -397,7 +408,6 @@ public class ShareResourceIntTest {
defaultShareShouldBeFound("documentDate.lessThan=" + UPDATED_DOCUMENT_DATE);
}
@Test
@Transactional
public void getAllSharesByValueDateIsEqualToSomething() throws Exception {
@@ -463,7 +473,6 @@ public class ShareResourceIntTest {
defaultShareShouldBeFound("valueDate.lessThan=" + UPDATED_VALUE_DATE);
}
@Test
@Transactional
public void getAllSharesByActionIsEqualToSomething() throws Exception {
@@ -568,7 +577,6 @@ public class ShareResourceIntTest {
defaultShareShouldBeFound("quantity.lessThan=" + UPDATED_QUANTITY);
}
@Test
@Transactional
public void getAllSharesByRemarkIsEqualToSomething() throws Exception {
@@ -612,7 +620,8 @@ public class ShareResourceIntTest {
@Transactional
public void getAllSharesByMembershipIsEqualToSomething() throws Exception {
// Initialize the database
Membership membership = MembershipResourceIntTest.createPersistentEntity(em, CustomerResourceIntTest.createPersistentEntity(em));
Membership membership = MembershipResourceIntTest
.createPersistentEntity(em, CustomerResourceIntTest.createPersistentEntity(em));
share.setMembership(membership);
shareRepository.saveAndFlush(share);
Long membershipId = membership.getId();
@@ -629,20 +638,20 @@ public class ShareResourceIntTest {
*/
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)));
.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"));
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("1"));
}
/**
@@ -650,25 +659,24 @@ public class ShareResourceIntTest {
*/
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());
.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"));
.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());
.andExpect(status().isNotFound());
}
@Test
@@ -684,17 +692,18 @@ public class ShareResourceIntTest {
// 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);
.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());
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();
@@ -717,10 +726,11 @@ public class ShareResourceIntTest {
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());
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();
@@ -736,9 +746,10 @@ public class ShareResourceIntTest {
int databaseSizeBeforeDelete = shareRepository.findAll().size();
// Delete the share
restShareMockMvc.perform(delete("/api/shares/{id}", share.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest());
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();

@@ -1,8 +1,12 @@
// 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;
@@ -15,8 +19,6 @@ import java.nio.charset.StandardCharsets;
import java.time.ZonedDateTime;
import java.time.format.DateTimeParseException;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Utility class for testing REST controllers.
*/
@@ -27,8 +29,8 @@ public final class TestUtil {
/** MediaType for JSON UTF8 */
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(
MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(), StandardCharsets.UTF_8);
MediaType.APPLICATION_JSON.getSubtype(),
StandardCharsets.UTF_8);
private static ObjectMapper createObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
@@ -85,8 +87,9 @@ public final class TestUtil {
}
return true;
} catch (DateTimeParseException e) {
mismatchDescription.appendText("was ").appendValue(item)
.appendText(", which could not be parsed as a ZonedDateTime");
mismatchDescription.appendText("was ")
.appendValue(item)
.appendText(", which could not be parsed as a ZonedDateTime");
return false;
}
@@ -100,6 +103,7 @@ public final class TestUtil {
/**
* 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) {
@@ -127,15 +131,17 @@ public final class TestUtil {
/**
* Create a FormattingConversionService which use ISO date format, instead of the localized one.
*
* @return the FormattingConversionService
*/
public static FormattingConversionService createFormattingConversionService() {
DefaultFormattingConversionService dfcs = new DefaultFormattingConversionService ();
DefaultFormattingConversionService dfcs = new DefaultFormattingConversionService();
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setUseIsoFormat(true);
registrar.registerFormatters(dfcs);
return dfcs;
}
private TestUtil() {}
private TestUtil() {
}
}

@@ -1,11 +1,21 @@
// 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;
@@ -18,14 +28,6 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.isEmptyString;
import static org.hamcrest.Matchers.not;
/**
* Test class for the UserJWTController REST controller.
*
@@ -56,8 +58,8 @@ public class UserJWTControllerIntTest {
public void setup() {
UserJWTController userJWTController = new UserJWTController(tokenProvider, authenticationManager);
this.mockMvc = MockMvcBuilders.standaloneSetup(userJWTController)
.setControllerAdvice(exceptionTranslator)
.build();
.setControllerAdvice(exceptionTranslator)
.build();
}
@Test
@@ -74,14 +76,15 @@ public class UserJWTControllerIntTest {
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())));
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
@@ -99,14 +102,15 @@ public class UserJWTControllerIntTest {
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())));
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
@@ -115,11 +119,12 @@ public class UserJWTControllerIntTest {
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"));
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"));
}
}

@@ -1,5 +1,12 @@
// 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;
@@ -11,6 +18,7 @@ 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;
@@ -26,15 +34,10 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.time.Instant;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import javax.persistence.EntityManager;
/**
* Test class for the UserResource REST controller.
@@ -106,10 +109,10 @@ public class UserResourceIntTest {
UserResource userResource = new UserResource(userService, userRepository, mailService);
this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter)
.build();
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter)
.build();
}
/**
@@ -155,10 +158,11 @@ public class UserResourceIntTest {
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());
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();
@@ -190,10 +194,11 @@ public class UserResourceIntTest {
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());
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();
@@ -219,10 +224,11 @@ public class UserResourceIntTest {
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());
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();
@@ -248,10 +254,11 @@ public class UserResourceIntTest {
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());
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();
@@ -265,16 +272,17 @@ public class UserResourceIntTest {
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)));
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
@@ -287,14 +295,14 @@ public class UserResourceIntTest {
// 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));
.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();
}
@@ -303,7 +311,7 @@ public class UserResourceIntTest {
@Transactional
public void getNonExistingUser() throws Exception {
restUserMockMvc.perform(get("/api/users/unknown"))
.andExpect(status().isNotFound());
.andExpect(status().isNotFound());
}
@Test
@@ -332,10 +340,11 @@ public class UserResourceIntTest {
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());
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();
@@ -374,10 +383,11 @@ public class UserResourceIntTest {
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());
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();
@@ -427,10 +437,11 @@ public class UserResourceIntTest {
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());
restUserMockMvc.perform(
put("/api/users")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isBadRequest());
}
@Test
@@ -469,10 +480,11 @@ public class UserResourceIntTest {
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());
restUserMockMvc.perform(
put("/api/users")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isBadRequest());
}
@Test
@@ -483,9 +495,10 @@ public class UserResourceIntTest {
int databaseSizeBeforeDelete = userRepository.findAll().size();
// Delete the user
restUserMockMvc.perform(delete("/api/users/{login}", user.getLogin())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
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();
@@ -497,13 +510,14 @@ public class UserResourceIntTest {
@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)));
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

@@ -1,6 +1,14 @@
// 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;
@@ -12,12 +20,6 @@ import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Test class for the ExceptionTranslator controller advice.
*
@@ -41,110 +43,110 @@ public class ExceptionTranslatorIntTest {
@Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter)
.build();
.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));
.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"));
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"));
.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"));
.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"));
.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"));
.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!"));
.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!"));
.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"));
.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"));
.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"));
.andExpect(status().isInternalServerError())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.500"))
.andExpect(jsonPath("$.title").value("Internal Server Error"));
}
}

@@ -1,3 +1,4 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.web.rest.errors;
import org.springframework.dao.ConcurrencyFailureException;
@@ -6,11 +7,12 @@ import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
@RestController
public class ExceptionTranslatorTestController {

@@ -1,18 +1,19 @@
// 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 java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import java.util.ArrayList;
import java.util.List;
/**
* Tests based on parsing algorithm in app/components/util/pagination-util.service.js
*