added new test payment, scheduler

This commit is contained in:
psemenkov 2022-12-06 12:31:39 +03:00
parent ab9e2615bd
commit 88a9915448
17 changed files with 539 additions and 34 deletions

View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>backend-api</artifactId>
@ -8,12 +8,12 @@
<description>Clearing backend API module</description>
<packaging>jar</packaging>
<parent>
<artifactId>clearing-parent</artifactId>
<parent>
<artifactId>clearing-parent</artifactId>
<groupId>ru.spcex.clearing</groupId>
<version>SPCEX-1.0.0.0</version>
</parent>
<properties>
<keycloak-spring-boot-starter.version>17.0.1</keycloak-spring-boot-starter.version>
@ -25,9 +25,9 @@
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
@ -92,17 +92,21 @@
<artifactId>spring-boot-test-autoconfigure</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.keycloak.bom</groupId>
<artifactId>keycloak-adapter-bom</artifactId>
<version>${keycloak-spring-boot-starter.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<groupId>org.keycloak.bom</groupId>
<artifactId>keycloak-adapter-bom</artifactId>
<version>${keycloak-spring-boot-starter.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

View file

@ -4,6 +4,8 @@ import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
@ -21,16 +23,13 @@ public class Jackson2HttpConverterTestConfig {
private JacksonObjectMapper() {
//настройки Ильи
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
//настройки какие были на курсе пока не нужны..
// модуль для корректной сериализации LocalDateTime в поля JSON - JavaTimeModule модуль библиотеки jackson-datatype-jsr310
// registerModule(new JavaTimeModule());
// configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
// запрещаем доступ ко всем полям и методам класса и потом разрешаем доступ только к полям, нужны чтобы не было лишних полей из-за методов как: public ActionType getActionType() у BankAccountNewAction
//модуль для корректной сериализации LocalDateTime в поля JSON - JavaTimeModule модуль библиотеки jackson-datatype-jsr310
registerModule(new JavaTimeModule());
configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//запрещаем доступ ко всем полям и методам класса и потом разрешаем доступ только к полям, нужны чтобы не было лишних полей из-за методов как: public ActionType getActionType() у BankAccountNewAction
setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
// не сериализуем null-поля
//не сериализуем null-поля
// setSerializationInclusion(JsonInclude.Include.NON_NULL);
}

View file

@ -0,0 +1,28 @@
package ru.spcex.clearing.backendapi.controller.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import ru.spcex.platform.utils.enumeration.IMessageResolver;
import ru.spcex.platform.utils.enumeration.SpringPropertiesMessageResolver;
import java.util.Locale;
@Configuration
public class MessagesTestConfig {
@Bean("validation-error-messages-test")
public ResourceBundleMessageSource messages() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasenames("messages/error");
source.setUseCodeAsDefaultMessage(true);
source.setDefaultEncoding("utf8");
source.setDefaultLocale(Locale.ROOT);
return source;
}
@Bean("errorTestResolver")
public IMessageResolver errorResolver(@Qualifier("validation-error-messages-test") ResourceBundleMessageSource messageBundle) {
return new SpringPropertiesMessageResolver(messageBundle);
}
}

View file

@ -13,7 +13,7 @@ import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService;
@Configuration
@Import({GetResponseFactoryTestConfiguration.class})
public class StateLoaderImplConfig {
public class StateLoaderImplTestConfig {
@Autowired
@Qualifier("hazelcastServiceTest")
@ -25,7 +25,7 @@ public class StateLoaderImplConfig {
return new GetResponseFactory(meta);
}
@Bean(name = "stateLoaderImpl")
@Bean(name = "stateLoaderImplTest")
public StateLoaderImpl createStateLoaderImpl(@Qualifier("responseFactoryTest") GetResponseFactory responseFactory) {
return new StateLoaderImpl(hazelcastServiceTest, responseFactory);
}

View file

@ -0,0 +1,41 @@
package ru.spcex.clearing.backendapi.controller.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class WebSecurityTestConfigurer {
@Bean
public InMemoryUserDetailsManager userDetailsService(PasswordEncoder passwordEncoder) {
UserDetails user = User.withUsername("spring")
.password(passwordEncoder.encode("secret"))
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/task-runners/**")
.hasRole("USER")
.antMatchers("/**")
.permitAll()
.and()
.httpBasic();
return http.build();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View file

@ -18,6 +18,11 @@ import ru.spcex.clearing.backendapi.controller.queue.account.AccountController;
import ru.spcex.clearing.backendapi.controller.queue.account.BankAccountController;
import ru.spcex.clearing.backendapi.controller.queue.company.*;
import ru.spcex.clearing.backendapi.controller.queue.misc.NotificationController;
import ru.spcex.clearing.backendapi.controller.queue.misc.SessionController;
import ru.spcex.clearing.backendapi.controller.queue.payment.PaymentInstructionController;
import ru.spcex.clearing.backendapi.controller.queue.scheduler.SchedulerAllTodayController;
import ru.spcex.clearing.backendapi.controller.queue.scheduler.SchedulerController;
import ru.spcex.clearing.backendapi.controller.queue.scheduler.TaskRunnerController;
import ru.spcex.clearing.backendapi.meta.GetResponseFactory;
import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService;
@ -38,12 +43,21 @@ import java.util.concurrent.atomic.AtomicLong;
ProfileDocumentController.class,
//misc
NotificationController.class,
//*****************************
SessionController.class,
//payment
PaymentInstructionController.class,
//scheduler
SchedulerAllTodayController.class,
SchedulerController.class,
TaskRunnerController.class,
//******* common configs *******
WebTestConfig.class,
IOperatorTest.class,
KafkaTestConfig.class,
HazelcastServiceTestConfiguration.class,
StateLoaderImplConfig.class,
StateLoaderImplTestConfig.class,
WebSecurityTestConfigurer.class,
MessagesTestConfig.class,
Jackson2HttpConverterTestConfig.class})
@ExtendWith(SpringExtension.class)
@WebMvcTest//(controllers = DeleteCompanyController.class)

View file

@ -124,7 +124,7 @@ class EditClearingMemberCategoryControllerTest extends AbstractControllerTest {
/**
* {@link EditClearingMemberCategoryController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_BankAccount.<br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_ClearingMemberCategory.<br>
* Входной запрос /clearing-member-categories/ <br>
* Ответ CommonGetAllResponse <br>
*/

View file

@ -79,7 +79,7 @@ class EditCompanySymbolControllerTest extends AbstractControllerTest {
/**
* {@link EditCompanySymbolController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_BankAccount.<br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_CompanySymbols.<br>
* Входной запрос /clearing-member-categories/ <br>
* Ответ CommonGetAllResponse <br>
*/

View file

@ -80,7 +80,7 @@ class EditContactControllerTest extends AbstractControllerTest {
/**
* {@link EditContactController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_BankAccount.<br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_Contact.<br>
* Входной запрос /contacts/ <br>
* Ответ CommonGetAllResponse <br>
*/

View file

@ -23,8 +23,8 @@ class ProfileDocumentControllerTest extends AbstractControllerTest {
/**
* {@link ProfileDocumentController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_BankAccount.<br>
* Входной запрос /contacts/ <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_ProfileDocument.<br>
* Входной запрос /profile-documents/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test

View file

@ -24,8 +24,8 @@ class NotificationControllerTest extends AbstractControllerTest {
/**
* {@link NotificationController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_BankAccount.<br>
* Входной запрос /contacts/ <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_Notification.<br>
* Входной запрос /notifications/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test

View file

@ -0,0 +1,54 @@
package ru.spcex.clearing.backendapi.controller.queue.misc;
import com.hazelcast.core.IMap;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import ru.clearing.classes.statics.data.misc.Session;
import ru.spcex.clearing.backendapi.controller.queue.AbstractControllerTest;
import ru.spcex.clearing.backendapi.controller.response.entity.CommonGetAllResponse;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import java.time.LocalDate;
import java.util.Collection;
import java.util.Map;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static ru.spcex.clearing.backendapi.controller.utils.JsonUtil.writeValue;
class SessionControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/sessions/";
/**
* {@link SessionController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_Session.<br>
* Входной запрос /sessions/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test
void getAll() throws Exception {
//ARRANGE
Session session = new Session();
session.setClearingDate(LocalDate.now());
session.setSessionStatus("Ok");
session.setId(currentId.get());
IMap<Long, Session> iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_Session);
iMap.put(session.getId(), session);
Collection<Session> values = iMap.values();
Collection<Map<String, Object>> all = responseFactory.responseFromObjectCollection(values);
CommonGetAllResponse expected = new CommonGetAllResponse();
expected.fromEntity(all);
//ACT
perform(MockMvcRequestBuilders.get(REST_URL)
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())//output to the log request and response
//ASSERT
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(content().json(writeValue(expected)));
}
}

View file

@ -0,0 +1,77 @@
package ru.spcex.clearing.backendapi.controller.queue.payment;
import com.hazelcast.core.IMap;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import ru.clearing.classes.statics.data.payment.PaymentInstruction;
import ru.spcex.clearing.backendapi.controller.queue.AbstractControllerTest;
import ru.spcex.clearing.backendapi.controller.response.entity.CommonGetAllResponse;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import java.time.Instant;
import java.time.LocalDate;
import java.util.Collection;
import java.util.Map;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static ru.spcex.clearing.backendapi.controller.utils.JsonUtil.writeValue;
class PaymentInstructionControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/paymentInstructions/";
/**
* {@link PaymentInstructionController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_PaymentInstruction.<br>
* Входной запрос /paymentInstructions/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test
void getAll() throws Exception {
//ARRANGE
PaymentInstruction paymentInstruction = new PaymentInstruction();
paymentInstruction.setSenderId(1010L);
paymentInstruction.setAddresseeId(1010L);
paymentInstruction.setAdresseeBIC("123456789");
paymentInstruction.setPayeeBankName("BankName");
paymentInstruction.setPayeeBIC("123456789");
paymentInstruction.setAddresseeBankName("BankName");
paymentInstruction.setPaymentDate(Instant.now());
paymentInstruction.setPaymentPurpose("Purpose");
paymentInstruction.setSettlementDate(LocalDate.now());
paymentInstruction.setCreditLegAmount(2020L);
paymentInstruction.setDebitLegAmount(2020L);
paymentInstruction.setCreditLegAccountId(2020L);
paymentInstruction.setCreditCsAccount("Ok");
paymentInstruction.setCreditLegAccount("123456789");
paymentInstruction.setDebitLegAccountId(3030L);
paymentInstruction.setDebitCsAccount("123456789");
paymentInstruction.setDebitLegAccount("123456789");
paymentInstruction.setCreditLegDirection(3030L);
paymentInstruction.setDebitLegDirection(3030L);
paymentInstruction.setCreditLegCurrencyCode("123456789");
paymentInstruction.setDebitLegCurrencyCode("123456789");
paymentInstruction.setClearingDate(LocalDate.now());
paymentInstruction.setTransactionStatus("Status");
paymentInstruction.setDocumentNumber("123456789");
paymentInstruction.setId(currentId.get());
IMap<Long, PaymentInstruction> iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_PaymentInstruction);
iMap.put(paymentInstruction.getId(), paymentInstruction);
Collection<PaymentInstruction> values = iMap.values();
Collection<Map<String, Object>> all = responseFactory.responseFromObjectCollection(values);
CommonGetAllResponse expected = new CommonGetAllResponse();
expected.fromEntity(all);
//ACT
perform(MockMvcRequestBuilders.get(REST_URL)
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())//output to the log request and response
//ASSERT
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(content().json(writeValue(expected)));
}
}

View file

@ -0,0 +1,61 @@
package ru.spcex.clearing.backendapi.controller.queue.scheduler;
import com.hazelcast.core.IMap;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import ru.clearing.classes.statics.data.scheduler.SchedulerAllToday;
import ru.spcex.clearing.backendapi.controller.queue.AbstractControllerTest;
import ru.spcex.clearing.backendapi.controller.response.entity.CommonGetAllResponse;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Collection;
import java.util.Map;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static ru.spcex.clearing.backendapi.controller.utils.JsonUtil.writeValue;
class SchedulerAllTodayControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/schedule/schedulers-all-today/";
/**
* {@link SchedulerAllTodayController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_SchedulerAllToday.<br>
* Входной запрос /schedule/schedulers-all-today/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test
void getAll() throws Exception {
//ARRANGE
SchedulerAllToday schedulerAllToday = new SchedulerAllToday();
schedulerAllToday.setTask("Task");
schedulerAllToday.setTaskTime(LocalTime.now());
schedulerAllToday.setClearingDate(LocalDate.now());
schedulerAllToday.setMarket("Market");
schedulerAllToday.setTaskStatus("Ok");
schedulerAllToday.setSecurityId(10210L);
schedulerAllToday.setSource("Source");
schedulerAllToday.setOrigId(1010L);
schedulerAllToday.setId(currentId.get());
IMap<Long, SchedulerAllToday> iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_SchedulerAllToday);
iMap.put(schedulerAllToday.getId(), schedulerAllToday);
Collection<SchedulerAllToday> values = iMap.values();
Collection<Map<String, Object>> all = responseFactory.responseFromObjectCollection(values);
CommonGetAllResponse expected = new CommonGetAllResponse();
expected.fromEntity(all);
//ACT
perform(MockMvcRequestBuilders.get(REST_URL)
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())//output to the log request and response
//ASSERT
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(content().json(writeValue(expected)));
}
}

View file

@ -0,0 +1,59 @@
package ru.spcex.clearing.backendapi.controller.queue.scheduler;
import com.hazelcast.core.IMap;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import ru.clearing.classes.statics.data.scheduler.Scheduler;
import ru.spcex.clearing.backendapi.controller.queue.AbstractControllerTest;
import ru.spcex.clearing.backendapi.controller.response.entity.CommonGetAllResponse;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Collection;
import java.util.Map;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static ru.spcex.clearing.backendapi.controller.utils.JsonUtil.writeValue;
class SchedulerControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/schedule/schedulers/";
/**
* {@link SchedulerController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_Scheduler.<br>
* Входной запрос /schedule/schedulers/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test
void getAll() throws Exception {
//ARRANGE
Scheduler scheduler = new Scheduler();
scheduler.setTask("Task");
scheduler.setTaskTime(LocalTime.now());
scheduler.setClearingDate(LocalDate.now());
scheduler.setMarket("Market");
scheduler.setTaskStatus("Ok");
scheduler.setSecurityId(10210L);
scheduler.setId(currentId.get());
IMap<Long, Scheduler> iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_Scheduler);
iMap.put(scheduler.getId(), scheduler);
Collection<Scheduler> values = iMap.values();
Collection<Map<String, Object>> all = responseFactory.responseFromObjectCollection(values);
CommonGetAllResponse expected = new CommonGetAllResponse();
expected.fromEntity(all);
//ACT
perform(MockMvcRequestBuilders.get(REST_URL)
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())//output to the log request and response
//ASSERT
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(content().json(writeValue(expected)));
}
}

View file

@ -0,0 +1,169 @@
package ru.spcex.clearing.backendapi.controller.queue.scheduler;
import com.hazelcast.core.IMap;
import org.junit.jupiter.api.Test;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.KeycloakSecurityContext;
import org.keycloak.adapters.spi.KeycloakAccount;
import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken;
import org.keycloak.representations.AccessToken;
import org.springframework.core.NestedExceptionUtils;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import ru.clearing.classes.statics.data.scheduler.TaskRunner;
import ru.clearing.classes.statics.data.user.User;
import ru.clearing.platform.dictionary.TaskDictionary;
import ru.spcex.clearing.backendapi.controller.queue.AbstractControllerTest;
import ru.spcex.clearing.backendapi.controller.queue.account.BankAccountController;
import ru.spcex.clearing.backendapi.controller.request.cud.account.BankAccountNewAction;
import ru.spcex.clearing.backendapi.controller.response.cud.CudResponse;
import ru.spcex.clearing.backendapi.controller.response.cud.QueueSuccessResponse;
import ru.spcex.clearing.backendapi.controller.response.entity.CommonGetAllResponse;
import ru.spcex.clearing.backendapi.domain.actions.IAction;
import ru.spcex.clearing.backendapi.errors.ActionValidationException;
import ru.spcex.clearing.imdg.IMDGDistributedNames;
import ru.spcex.clearing.platform.messaging.domain.ActionType;
import ru.spcex.clearing.platform.messaging.domain.cud.account.BankAccountNewRequest;
import java.util.Collection;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static ru.spcex.clearing.backendapi.controller.utils.JsonUtil.writeValue;
class TaskRunnerControllerTest extends AbstractControllerTest {
private static final String REST_URL = "/task-runners/";
/**
* {@link TaskRunnerController#getAll()} <br>
* Тест проверяет получение запроса по REST API и отправку всех записей из таблицы hazelcast Map_TaskRunner.<br>
* Входной запрос /task-runners/ <br>
* Ответ CommonGetAllResponse <br>
*/
@Test
void getAll() throws Exception {
//ARRANGE
TaskRunner taskRunner = new TaskRunner();
taskRunner.setTask("Task");
taskRunner.setSenderId(10210L);
taskRunner.setId(currentId.get());
IMap<Long, TaskRunner> iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_TaskRunner);
iMap.put(taskRunner.getId(), taskRunner);
Collection<TaskRunner> values = iMap.values();
Collection<Map<String, Object>> all = responseFactory.responseFromObjectCollection(values);
CommonGetAllResponse expected = new CommonGetAllResponse();
expected.fromEntity(all);
//ACT
perform(MockMvcRequestBuilders.get(REST_URL)
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())//output to the log request and response
//ASSERT
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(content().json(writeValue(expected)));
}
// @Test todo пока не работает (
void add() throws Exception {
//ARRANGE
TaskDictionary taskDictionary = new TaskDictionary();
IMap<Long, TaskDictionary> iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_TaskDictionary);
iMap.put(taskDictionary.getId(), taskDictionary);
CudResponse expected = new CudResponse();
expected.setCode(0L);
expected.setMessage("success");
expected.setPayload(new QueueSuccessResponse(ActionType.NEW, currentId.getAndIncrement()));
setUserNameInMockSecurityContextAndMapUser("existUser");
//ACT
perform(MockMvcRequestBuilders.post(REST_URL + "ABLK")
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())//output to the log request and response
//ASSERT
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(content().json(writeValue(expected)));
}
private void setUserNameInMockSecurityContextAndMapUser(String username) {
User user = new User();
user.setIdentifier(username);
user.setId(currentId.get());
IMap<Long, User> iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_User);
iMap.put(user.getId(), user);
AccessToken accessToken = mock(AccessToken.class);
when(accessToken.getPreferredUsername()).thenReturn(username);
KeycloakSecurityContext keycloakSecurityContext = mock(KeycloakSecurityContext.class);
when(keycloakSecurityContext.getToken()).thenReturn(accessToken);
KeycloakPrincipal keycloakPrincipal = mock(KeycloakPrincipal.class);
when(keycloakPrincipal.getKeycloakSecurityContext()).thenReturn(keycloakSecurityContext);
KeycloakAccount details = mock(KeycloakAccount.class);
when(details.getPrincipal()).thenReturn(keycloakPrincipal);
KeycloakAuthenticationToken authentication = mock(KeycloakAuthenticationToken.class);
when(authentication.getDetails()).thenReturn(details);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
// @Test
// void testWithPostProcessor() выдает Exception {
// perform(MockMvcRequestBuilders.get("/greet").with(jwt().jwt(jwt -> {
// jwt.claim("preferred_username", "Tonton Pirate");
// }).authorities(List.of(new SimpleGrantedAuthority("NICE_GUY"), new SimpleGrantedAuthority("AUTHOR")))))
// .andExpect(status().isOk())
// .andExpect(content().string("Hi Tonton Pirate! You are granted with: [NICE_GUY, AUTHOR]."));
// }
/**
* {@link BankAccountController#add(BankAccountNewAction)}<br>
* Тест проверяет работу валидации сущности {@link BankAccountNewAction} принятой по REST API для отправку в Apache Kafka.<br>
* Входной запрос {@link BankAccountNewRequest}:<br>
* {@link BankAccountNewRequest#bankIdentificationCode} - 044525776 или ""<br>
* {@link BankAccountNewRequest#bankName} - Beta Money Bank или ""<br>
* {@link BankAccountNewRequest#correspondentAccount} - 30101111111111111776 или ""<br>
* {@link BankAccountNewRequest#correspondentAccountName} - correspondent или ""<br>
* {@link BankAccountNewRequest#currency} - RUB или ""<br>
* {@link BankAccountNewRequest#destination} - destinatio или ""n<br>
* {@link BankAccountNewRequest#taxpayerIdentificationNumber} - 3664011397 или ""<br>
* {@link BankAccountNewRequest#taxRegistrationReasonCode} - 01 или ""<br>
* {@link BankAccountNewRequest#account} - 11111222223333344444 или ""<br>
*/
@Test
void addWithException() {
// assertThrowsFor(getBankAccountNewAction("", "Beta Money Bank", "30101111111111111776", "correspondent", "RUB", "destination", "3664011397", "01", "11111222223333344444"));
// assertThrowsFor(getBankAccountNewAction("044525776", "", "30101111111111111776", "correspondent", "RUB", "destination", "3664011397", "01", "11111222223333344444"));
// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "", "correspondent", "RUB", "destination", "3664011397", "01", "11111222223333344444"));
// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "30101111111111111776", "", "RUB", "destination", "3664011397", "01", "11111222223333344444"));
// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "30101111111111111776", "correspondent", "", "destination", "3664011397", "01", "11111222223333344444"));
// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "30101111111111111776", "correspondent", "RUB", "", "3664011397", "01", "11111222223333344444"));
// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "30101111111111111776", "correspondent", "RUB", "destination", "", "01", "11111222223333344444"));
// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "30101111111111111776", "correspondent", "RUB", "destination", "3664011397", "", "11111222223333344444"));
// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "30101111111111111776", "correspondent", "RUB", "destination", "3664011397", "01", ""));
}
private void assertThrowsFor(IAction<?> iAction) {
assertThrows(ActionValidationException.class, () -> {
try {
perform(MockMvcRequestBuilders.post(REST_URL).contentType(MediaType.APPLICATION_JSON).content(writeValue(iAction)));
} catch (Exception e) {
Throwable rootCause = NestedExceptionUtils.getRootCause(e);
throw rootCause != null ? rootCause : e;
}
});
}
}

View file

@ -1,7 +1,6 @@
package ru.spcex.clearing.backendapi.meta;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;