From 0d47c239b96bcc3b2b0f61d9c31154fa93fa98ba Mon Sep 17 00:00:00 2001 From: psemenkov Date: Wed, 21 Sep 2022 15:33:05 +0300 Subject: [PATCH 01/33] http://git.mfd.msk/mfd/clearing/issues/6 --- fixing generate java doc for app --- .../clearing/imdg/base/TemplateMapStore.java | 5 +++-- .../platform/utils/enumeration/IEnumId.java | 14 +++++++------- pom.xml | 19 +++++++++++++++---- 3 files changed, 25 insertions(+), 13 deletions(-) diff --git a/clearing-parent/imdg/src/main/java/ru/spcex/clearing/imdg/base/TemplateMapStore.java b/clearing-parent/imdg/src/main/java/ru/spcex/clearing/imdg/base/TemplateMapStore.java index b211c13d0..e719f23c8 100644 --- a/clearing-parent/imdg/src/main/java/ru/spcex/clearing/imdg/base/TemplateMapStore.java +++ b/clearing-parent/imdg/src/main/java/ru/spcex/clearing/imdg/base/TemplateMapStore.java @@ -10,7 +10,6 @@ import java.util.*; /** * MapStore для шаблонных бизнес-объектов - * @Component */ public abstract class TemplateMapStore extends ObjectBaseMapStore implements AutoconfiguredMap { @@ -38,13 +37,13 @@ public abstract class TemplateMapStore extends Object // } /** - * * @return IMDGDistributedNames.* */ public abstract String getMapName(); /** * Список индексируемых полей, для быстрого поиска + * * @return */ public String[] getIndexingField() { @@ -53,6 +52,7 @@ public abstract class TemplateMapStore extends Object /** * Десериализатор + * * @param resultSet * @return */ @@ -67,6 +67,7 @@ public abstract class TemplateMapStore extends Object /** * Сериализатор + * * @param resultSet * @return Object[] args */ diff --git a/platform-parent/platform-utils/src/main/java/ru/spcex/platform/utils/enumeration/IEnumId.java b/platform-parent/platform-utils/src/main/java/ru/spcex/platform/utils/enumeration/IEnumId.java index a45b3c628..10859b6a4 100644 --- a/platform-parent/platform-utils/src/main/java/ru/spcex/platform/utils/enumeration/IEnumId.java +++ b/platform-parent/platform-utils/src/main/java/ru/spcex/platform/utils/enumeration/IEnumId.java @@ -4,11 +4,7 @@ import java.io.Serializable; import java.util.Objects; public interface IEnumId extends Serializable { - Long getId(); - - default boolean equalsById(Long id) { - return id != null && getId().equals(id); - } + Long UNDEFINED_VALUE = Long.MIN_VALUE; /** * Проверяет что среди данного набора Enum, присутствует элемент с данным id @@ -46,7 +42,7 @@ public interface IEnumId extends Serializable { * Возвращает Enum по id, если в заданном классе такой определен * id может быть null * - * @return Enum если нашел, иначе null + * @return Enum если нашел, иначе null */ static & IEnumId> T getEnumById(Class enumClass, Long id) { for (T e : enumClass.getEnumConstants()) { @@ -60,5 +56,9 @@ public interface IEnumId extends Serializable { return enumVal == null ? null : enumVal.getId(); } - Long UNDEFINED_VALUE = Long.MIN_VALUE; + Long getId(); + + default boolean equalsById(Long id) { + return id != null && getId().equals(id); + } } diff --git a/pom.xml b/pom.xml index a2946836b..7e1358770 100644 --- a/pom.xml +++ b/pom.xml @@ -1,6 +1,6 @@ - 4.0.0 @@ -30,8 +30,10 @@ ${folder_root_clearing_temp} - ${folder_root_clearing}/clearing-parent/backend-api - ${folder_root_clearing}/clearing-parent/securities-service + ${folder_root_clearing}/clearing-parent/backend-api + + ${folder_root_clearing}/clearing-parent/securities-service + ${folder_root_clearing}/clearing-parent/imdg ${folder_root_clearing}/clearing-parent/dbf-exporter ${folder_root_clearing}/clearing-parent/dbf-importer @@ -279,6 +281,15 @@ + + org.apache.maven.plugins + maven-javadoc-plugin + + private + true + + + \ No newline at end of file From 48036a9a911d4f474dfaf58dafc814b6b0b4f9a8 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Wed, 21 Sep 2022 15:39:41 +0300 Subject: [PATCH 02/33] http://git.mfd.msk/mfd/clearing/issues/6 --- fixing bug --- pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7e1358770..3eb9a2b0a 100644 --- a/pom.xml +++ b/pom.xml @@ -287,7 +287,6 @@ private true - From da2f2c12dbfc993fceb44b06ef70405fc575e859 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Thu, 22 Sep 2022 19:30:11 +0300 Subject: [PATCH 03/33] --- added test class --- .../service/BankAccountServiceTest.java | 2 +- clearing-parent/backend-api/pom.xml | 49 +++++++---- .../account/BankAccountControllerTest.java | 72 ++++++++++++++++ .../config/Jackson2HttpConverterConfig.java | 39 +++++++++ .../controller/queue/utils/JsonUtil.java | 38 +++++++++ .../queue/utils/MatcherFactory.java | 82 +++++++++++++++++++ .../services/AbstractUpdateMapService.java | 10 +-- 7 files changed, 271 insertions(+), 21 deletions(-) create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/Jackson2HttpConverterConfig.java create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/JsonUtil.java create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/MatcherFactory.java diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java index cbc7952d1..027c1d3e6 100644 --- a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java +++ b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java @@ -36,7 +36,7 @@ import static ru.spcex.clearing.account.utils.MatcherFactory.usingIgnoringFields @ContextConfiguration(classes = { HazelcastServiceTestConfiguration.class}) public class BankAccountServiceTest { - public static final Matcher BANK_ACCOUNT_MATCHER = usingIgnoringFieldsComparator("id"); + public static final Matcher BANK_ACCOUNT_MATCHER = usingIgnoringFieldsComparator(); private static final int PARTITION = 0; private static final String TOPIC_ACCOUNT_NEW = Consts.DESTINATION_BANK_ACCOUNT_NEW; private static final String TOPIC_ACCOUNT_UPDATE = Consts.DESTINATION_BANK_ACCOUNT_UPDATE; diff --git a/clearing-parent/backend-api/pom.xml b/clearing-parent/backend-api/pom.xml index 18b29f7d1..96503e90f 100644 --- a/clearing-parent/backend-api/pom.xml +++ b/clearing-parent/backend-api/pom.xml @@ -1,6 +1,6 @@ - 4.0.0 backend-api @@ -8,12 +8,12 @@ Clearing backend API module jar - - clearing-parent + + clearing-parent ru.spcex.clearing SPCEX-1.0.0.0 - + 17.0.1 @@ -25,9 +25,9 @@ spring-boot-starter-web - org.springframework.boot - spring-boot-starter-security - + org.springframework.boot + spring-boot-starter-security + org.keycloak keycloak-spring-boot-starter @@ -53,17 +53,38 @@ ru.spcex.clearing classes + + + org.springframework + spring-test + test + + + org.mockito + mockito-core + + + org.junit.jupiter + junit-jupiter + test + + + org.assertj + assertj-core + test + + - org.keycloak.bom - keycloak-adapter-bom - ${keycloak-spring-boot-starter.version} - pom - import - + org.keycloak.bom + keycloak-adapter-bom + ${keycloak-spring-boot-starter.version} + pom + import + diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java new file mode 100644 index 000000000..4c4e2cc34 --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java @@ -0,0 +1,72 @@ +package ru.spcex.clearing.backendapi.controller.queue.account; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.filter.CharacterEncodingFilter; +import ru.spcex.clearing.backendapi.controller.queue.config.Jackson2HttpConverterConfig; +import ru.spcex.clearing.backendapi.controller.queue.utils.JsonUtil; +import ru.spcex.clearing.backendapi.controller.queue.utils.MatcherFactory; +import ru.spcex.clearing.backendapi.controller.request.cud.account.BankAccountNewAction; +import ru.spcex.clearing.backendapi.controller.response.cud.CudResponse; + +import javax.annotation.PostConstruct; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringJUnitWebConfig(classes = { + Jackson2HttpConverterConfig.class}) +class BankAccountControllerTest { + + public static final MatcherFactory.Matcher CUD_RESPONSE_MATCHER = MatcherFactory.usingIgnoringFieldsComparator(CudResponse.class); + private static final String REST_URL = "/securities/bank-accounts/"; + private static final CharacterEncodingFilter CHARACTER_ENCODING_FILTER = new CharacterEncodingFilter(); + + static { + CHARACTER_ENCODING_FILTER.setEncoding("UTF-8"); + CHARACTER_ENCODING_FILTER.setForceEncoding(true); + } + + @Autowired + public Environment env; + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext webApplicationContext; + + @PostConstruct + private void postConstruct() { + mockMvc = MockMvcBuilders + .webAppContextSetup(webApplicationContext) + .addFilter(CHARACTER_ENCODING_FILTER) +// .apply(springSecurity()) + .build(); + } + + @Test + void add() throws Exception { + BankAccountNewAction bankAccountNewAction = new BankAccountNewAction(); + ResultActions action = mockMvc.perform(MockMvcRequestBuilders.post(REST_URL) + .contentType(MediaType.APPLICATION_JSON) +// .with(userHttpBasic(admin)) + .content(JsonUtil.writeValue(bankAccountNewAction))) + .andExpect(status().isCreated()); + + CudResponse created = CUD_RESPONSE_MATCHER.readFromJson(action); + } + + @Test + void update() { + } + + @Test + void delete() { + } +} \ No newline at end of file diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/Jackson2HttpConverterConfig.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/Jackson2HttpConverterConfig.java new file mode 100644 index 000000000..c6d557d21 --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/Jackson2HttpConverterConfig.java @@ -0,0 +1,39 @@ +package ru.spcex.clearing.backendapi.controller.queue.config; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; + +@Configuration +public class Jackson2HttpConverterConfig { + @Bean("customJsonHttpConverter") + public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { + return new MappingJackson2HttpMessageConverter(JacksonObjectMapper.getMapper()); + } + + public static class JacksonObjectMapper extends ObjectMapper { + private static final ObjectMapper MAPPER = new JacksonObjectMapper(); + + 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 boolean isExcess() +// setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE); +// setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); +// не сериализуем null-поля +// setSerializationInclusion(JsonInclude.Include.NON_NULL); + } + + public static ObjectMapper getMapper() { + return MAPPER; + } + } +} \ No newline at end of file diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/JsonUtil.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/JsonUtil.java new file mode 100644 index 000000000..fb20fe457 --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/JsonUtil.java @@ -0,0 +1,38 @@ +package ru.spcex.clearing.backendapi.controller.queue.utils; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectReader; + +import java.io.IOException; +import java.util.List; + +import static ru.spcex.clearing.backendapi.controller.queue.config.Jackson2HttpConverterConfig.JacksonObjectMapper.getMapper; + +public class JsonUtil { + + public static List readValues(String json, Class clazz) { + ObjectReader reader = getMapper().readerFor(clazz); + try { + return reader.readValues(json).readAll(); + } catch (IOException e) { + throw new IllegalArgumentException("Invalid read array from JSON:\n'" + json + "'", e); + } + } + + public static T readValue(String json, Class clazz) { + try { + return getMapper().readValue(json, clazz); + } catch (IOException e) { + throw new IllegalArgumentException("Invalid read from JSON:\n'" + json + "'", e); + } + } + + public static String writeValue(T obj) { + try { + return getMapper().writeValueAsString(obj); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Invalid write to JSON:\n'" + obj + "'", e); + } + } + +} \ No newline at end of file diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/MatcherFactory.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/MatcherFactory.java new file mode 100644 index 000000000..1143b031a --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/MatcherFactory.java @@ -0,0 +1,82 @@ +package ru.spcex.clearing.backendapi.controller.queue.utils; + +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.ResultMatcher; + +import java.io.UnsupportedEncodingException; +import java.util.List; +import java.util.function.BiConsumer; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Factory for creating test matchers. + *

+ * Comparing actual and expected objects via AssertJ + * Support converting json MvcResult to objects for comparation. + */ +public class MatcherFactory { + + public static Matcher usingAssertions(Class clazz, BiConsumer assertion, BiConsumer, Iterable> iterableAssertion) { + return new Matcher<>(clazz, assertion, iterableAssertion); + } + + public static Matcher usingEqualsComparator(Class clazz) { + return usingAssertions(clazz, + (a, e) -> assertThat(a).isEqualTo(e), + (a, e) -> assertThat(a).isEqualTo(e)); + } + + public static Matcher usingIgnoringFieldsComparator(Class clazz, String... fieldsToIgnore) { + return usingAssertions(clazz, + (a, e) -> assertThat(a).usingRecursiveComparison().ignoringFields(fieldsToIgnore).isEqualTo(e), + (a, e) -> assertThat(a).usingRecursiveFieldByFieldElementComparatorIgnoringFields(fieldsToIgnore).isEqualTo(e)); + } + + public static class Matcher { + private final Class clazz; + private final BiConsumer assertion; + private final BiConsumer, Iterable> iterableAssertion; + + private Matcher(Class clazz, BiConsumer assertion, BiConsumer, Iterable> iterableAssertion) { + this.clazz = clazz; + this.assertion = assertion; + this.iterableAssertion = iterableAssertion; + } + + private static String getContent(MvcResult result) throws UnsupportedEncodingException { + return result.getResponse().getContentAsString(); + } + + public void assertMatch(T actual, T expected) { + assertion.accept(actual, expected); + } + + @SafeVarargs + public final void assertMatch(Iterable actual, T... expected) { + assertMatch(actual, List.of(expected)); + } + + public void assertMatch(Iterable actual, Iterable expected) { + iterableAssertion.accept(actual, expected); + } + + public ResultMatcher contentJson(T expected) { + return result -> assertMatch(JsonUtil.readValue(getContent(result), clazz), expected); + } + + @SafeVarargs + public final ResultMatcher contentJson(T... expected) { + return contentJson(List.of(expected)); + } + + public ResultMatcher contentJson(Iterable expected) { + return result -> assertMatch(JsonUtil.readValues(getContent(result), clazz), expected); + } + + public T readFromJson(ResultActions action) throws UnsupportedEncodingException { + return JsonUtil.readValue(getContent(action.andReturn()), clazz); + } + } +} diff --git a/clearing-parent/imdg/src/main/java/ru/spcex/clearing/imdg/services/AbstractUpdateMapService.java b/clearing-parent/imdg/src/main/java/ru/spcex/clearing/imdg/services/AbstractUpdateMapService.java index 24a5bc55b..f90e5ee06 100644 --- a/clearing-parent/imdg/src/main/java/ru/spcex/clearing/imdg/services/AbstractUpdateMapService.java +++ b/clearing-parent/imdg/src/main/java/ru/spcex/clearing/imdg/services/AbstractUpdateMapService.java @@ -15,13 +15,11 @@ import java.time.Instant; public abstract class AbstractUpdateMapService implements InitializingBean, EntryAddedListener, EntryUpdatedListener, EntryRemovedListener { - private final Logger log = LoggerFactory.getLogger(this.getClass()); - - protected final String EVENT_CREATE="CREATE"; - protected final String EVENT_UPDATE="UPDATE"; - protected final String EVENT_DELETE="DELETE"; - + protected final String EVENT_CREATE = "CREATE"; + protected final String EVENT_UPDATE = "UPDATE"; + protected final String EVENT_DELETE = "DELETE"; protected final HazelcastInstance hazelcastServerInstance; + private final Logger log = LoggerFactory.getLogger(this.getClass()); public AbstractUpdateMapService(HazelcastInstance hazelcastServerInstance) { this.hazelcastServerInstance = hazelcastServerInstance; From 2ac22ddbdd2f28b8a327af5306c82ef84608ba85 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Fri, 23 Sep 2022 18:25:01 +0300 Subject: [PATCH 04/33] --- added test for method add --- clearing-parent/backend-api/pom.xml | 5 +- .../account/BankAccountControllerTest.java | 63 +++++++++++++---- .../config/BankAccountControllerConfig.java | 18 +++++ .../HazelcastServiceTestConfiguration.java | 68 +++++++++++++++++++ .../controller/queue/config/IOperator.java | 24 +++++++ .../config/Jackson2HttpConverterConfig.java | 8 ++- .../controller/queue/config/KafkaConfig.java | 18 +++++ .../controller/queue/utils/JsonUtil.java | 9 +++ 8 files changed, 196 insertions(+), 17 deletions(-) create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/HazelcastServiceTestConfiguration.java create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/IOperator.java create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/KafkaConfig.java diff --git a/clearing-parent/backend-api/pom.xml b/clearing-parent/backend-api/pom.xml index 96503e90f..0f9f3f647 100644 --- a/clearing-parent/backend-api/pom.xml +++ b/clearing-parent/backend-api/pom.xml @@ -60,8 +60,9 @@ test - org.mockito - mockito-core + org.skyscreamer + jsonassert + test org.junit.jupiter diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java index 4c4e2cc34..d89b18d34 100644 --- a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java @@ -2,26 +2,35 @@ package ru.spcex.clearing.backendapi.controller.queue.account; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.filter.CharacterEncodingFilter; -import ru.spcex.clearing.backendapi.controller.queue.config.Jackson2HttpConverterConfig; -import ru.spcex.clearing.backendapi.controller.queue.utils.JsonUtil; +import ru.spcex.clearing.backendapi.config.WebConfig; +import ru.spcex.clearing.backendapi.controller.queue.config.*; import ru.spcex.clearing.backendapi.controller.queue.utils.MatcherFactory; 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.platform.messaging.domain.ActionType; +import ru.spcex.clearing.platform.messaging.domain.cud.account.BankAccountNewRequest; import javax.annotation.PostConstruct; +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.queue.utils.JsonUtil.writeValue; @SpringJUnitWebConfig(classes = { + WebConfig.class, + IOperator.class, + BankAccountControllerConfig.class, + KafkaConfig.class, + HazelcastServiceTestConfiguration.class, Jackson2HttpConverterConfig.class}) class BankAccountControllerTest { @@ -34,8 +43,6 @@ class BankAccountControllerTest { CHARACTER_ENCODING_FILTER.setForceEncoding(true); } - @Autowired - public Environment env; private MockMvc mockMvc; @Autowired @@ -50,16 +57,48 @@ class BankAccountControllerTest { .build(); } + /** + * {@link BankAccountController#add(BankAccountNewAction)}
+ * Тест проверяет получение сущности {@link BankAccountNewAction} по REST API и отправку в Apache Kafka.
+ * Входной запрос {@link BankAccountNewRequest}:
+ * {@link BankAccountNewRequest#bankIdentificationCode} - 044525776
+ * {@link BankAccountNewRequest#bankName} - Beta Money Bank
+ * {@link BankAccountNewRequest#correspondentAccount} - 30101111111111111776
+ * {@link BankAccountNewRequest#correspondentAccountName} - correspondent
+ * {@link BankAccountNewRequest#currency} - RUB
+ * {@link BankAccountNewRequest#destination} - destination
+ * {@link BankAccountNewRequest#taxpayerIdentificationNumber} - 3664011397
+ * {@link BankAccountNewRequest#taxRegistrationReasonCode} - 01
+ * {@link BankAccountNewRequest#account} - 11111222223333344444
+ */ @Test void add() throws Exception { + //ARRANGE BankAccountNewAction bankAccountNewAction = new BankAccountNewAction(); - ResultActions action = mockMvc.perform(MockMvcRequestBuilders.post(REST_URL) - .contentType(MediaType.APPLICATION_JSON) -// .with(userHttpBasic(admin)) - .content(JsonUtil.writeValue(bankAccountNewAction))) - .andExpect(status().isCreated()); + bankAccountNewAction.setBankIdentificationCode("044525776"); + bankAccountNewAction.setBankName("Beta Money Bank"); + bankAccountNewAction.setCorrespondentAccount("30101111111111111776"); + bankAccountNewAction.setCorrespondentAccountName("correspondent"); + bankAccountNewAction.setCurrency("RUB"); + bankAccountNewAction.setDestination("destination"); + bankAccountNewAction.setTaxpayerIdentificationNumber("3664011397"); + bankAccountNewAction.setTaxRegistrationReasonCode("01"); + bankAccountNewAction.setAccount("11111222223333344444"); - CudResponse created = CUD_RESPONSE_MATCHER.readFromJson(action); + CudResponse extended = new CudResponse(); + extended.setCode(0L); + extended.setMessage("success"); + extended.setPayload(new QueueSuccessResponse(ActionType.NEW, 0L)); + + //ACT + mockMvc.perform(MockMvcRequestBuilders.post(REST_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(writeValue(bankAccountNewAction))) + .andDo(print())//output to the log request and response +// ASSERT + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(content().json(writeValue(extended))); } @Test diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java new file mode 100644 index 000000000..2f832f51b --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java @@ -0,0 +1,18 @@ +package ru.spcex.clearing.backendapi.controller.queue.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import ru.spcex.clearing.backendapi.controller.queue.account.BankAccountController; +import ru.spcex.clearing.backendapi.service.IOperator; + +@Configuration +public class BankAccountControllerConfig { + + @Autowired + @Bean + public BankAccountController createBankAccountController(IOperator operator) { + return new BankAccountController(operator); + } + +} diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/HazelcastServiceTestConfiguration.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/HazelcastServiceTestConfiguration.java new file mode 100644 index 000000000..04e64990d --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/HazelcastServiceTestConfiguration.java @@ -0,0 +1,68 @@ +package ru.spcex.clearing.backendapi.controller.queue.config; + +import com.hazelcast.config.*; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import ru.spcex.platform.imdg.iml.hazelcast.config.HazelcastClientParams; +import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService; +import ru.spcex.platform.imdg.iml.hazelcast.util.HazelcastHelper; + +import java.util.List; +import java.util.Random; + +@Configuration +public class HazelcastServiceTestConfiguration { + private HazelcastInstance hazelcastInstance; + + private static ThreadPoolTaskExecutor createThreadPoolTaskExecutor(int maxPoolSz, boolean waitForCompletion) { + ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor(); + if (maxPoolSz > 2) { + pool.setKeepAliveSeconds(60); + pool.setAllowCoreThreadTimeOut(true); + } + pool.setCorePoolSize(maxPoolSz); + pool.setWaitForTasksToCompleteOnShutdown(waitForCompletion); + return pool; + } + + @Bean(name = "hazelcastServiceTest") + public HazelcastService hazelcastService(@Qualifier("taskExecutorHazelcastClientInitializer") ThreadPoolTaskExecutor taskExecutorHazelcastClientInitializer, @Qualifier("taskExecutorIdGeneratorAwaiter") ThreadPoolTaskExecutor taskExecutorIdGeneratorAwaiter, HazelcastClientParams params) { + Config cfg = new Config(); + cfg.setInstanceName("localhost"); + + NetworkConfig networkConfig = new NetworkConfig(); + JoinConfig joinConfig = new JoinConfig(); + joinConfig.setMulticastConfig(new MulticastConfig().setEnabled(false)); + joinConfig.setTcpIpConfig(new TcpIpConfig().setEnabled(true).setMembers(List.of("127.0.0.1"))); + networkConfig.setJoin(joinConfig); + cfg.setNetworkConfig(networkConfig); + hazelcastInstance = Hazelcast.newHazelcastInstance(cfg); + HazelcastHelper.otcSystem_setStorageState(true, hazelcastInstance); + return new HazelcastService(taskExecutorHazelcastClientInitializer, taskExecutorIdGeneratorAwaiter, params); + } + + @Bean(name = "taskExecutorHazelcastClientInitializer") + public ThreadPoolTaskExecutor taskExecutorHazelcastClientInitializer() { + return createThreadPoolTaskExecutor(1, true); + } + + @Bean(name = "taskExecutorIdGeneratorAwaiter") + public ThreadPoolTaskExecutor taskExecutorIdGeneratorAwaiter() { + return createThreadPoolTaskExecutor(1, false); + } + + @Bean(name = "hazelcastClientParams") + public HazelcastClientParams getHazelcastClientParams() { + HazelcastClientParams params = new HazelcastClientParams(); + params.setLogin("dev"); + params.setPassword("dev-pass"); + params.setClusterMembers("127.0.0.1"); + params.setInstanceName("hzTestClient" + new Random().nextInt()); + params.setNearCacheConfig(new NearCacheConfig()); + return params; + } +} diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/IOperator.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/IOperator.java new file mode 100644 index 000000000..065785269 --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/IOperator.java @@ -0,0 +1,24 @@ +package ru.spcex.clearing.backendapi.controller.queue.config; + +import org.apache.kafka.clients.producer.Producer; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import ru.spcex.clearing.backendapi.service.impl.OperatorImpl; +import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService; + +@Configuration +public class IOperator { + + @Autowired + @Qualifier("hazelcastServiceTest") + private HazelcastService hazelcastServiceTest; + + @Autowired + @Bean + public OperatorImpl createIOperator(Producer kafka) { + return new OperatorImpl(kafka, hazelcastServiceTest); + } + +} diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/Jackson2HttpConverterConfig.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/Jackson2HttpConverterConfig.java index c6d557d21..a1f8c5bea 100644 --- a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/Jackson2HttpConverterConfig.java +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/Jackson2HttpConverterConfig.java @@ -1,5 +1,7 @@ package ru.spcex.clearing.backendapi.controller.queue.config; +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 org.springframework.context.annotation.Bean; @@ -25,9 +27,9 @@ public class Jackson2HttpConverterConfig { // registerModule(new JavaTimeModule()); // configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); -// запрещаем доступ ко всем полям и методам класса и потом разрешаем доступ только к полям, нужны чтобы не было лишних полей из-за методов как: public boolean isExcess() -// setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE); -// setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); +// запрещаем доступ ко всем полям и методам класса и потом разрешаем доступ только к полям, нужны чтобы не было лишних полей из-за методов как: public ActionType getActionType() у BankAccountNewAction + setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE); + setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); // не сериализуем null-поля // setSerializationInclusion(JsonInclude.Include.NON_NULL); } diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/KafkaConfig.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/KafkaConfig.java new file mode 100644 index 000000000..e8c020252 --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/KafkaConfig.java @@ -0,0 +1,18 @@ +package ru.spcex.clearing.backendapi.controller.queue.config; + +import org.apache.kafka.clients.producer.MockProducer; +import org.apache.kafka.clients.producer.Producer; +import org.apache.kafka.common.serialization.StringSerializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import ru.spcex.clearing.platform.messaging.serialization.JsonSerializer; + +@Configuration +public class KafkaConfig { + + @Bean + public Producer createProducer() { + return new MockProducer<>(true, new StringSerializer(), new JsonSerializer()); + } + +} diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/JsonUtil.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/JsonUtil.java index fb20fe457..2780f9465 100644 --- a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/JsonUtil.java +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/JsonUtil.java @@ -1,10 +1,13 @@ package ru.spcex.clearing.backendapi.controller.queue.utils; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectReader; import java.io.IOException; import java.util.List; +import java.util.Map; +import java.util.Set; import static ru.spcex.clearing.backendapi.controller.queue.config.Jackson2HttpConverterConfig.JacksonObjectMapper.getMapper; @@ -35,4 +38,10 @@ public class JsonUtil { } } + public static String writeIgnoreProps(T obj, String... ignoreProps) { + Map map = getMapper().convertValue(obj, new TypeReference<>() { + }); + map.keySet().removeAll(Set.of(ignoreProps)); + return writeValue(map); + } } \ No newline at end of file From 11eb548d79cab177712ac53945ad69ab16c5f215 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Mon, 26 Sep 2022 14:00:34 +0300 Subject: [PATCH 05/33] http://git.mfd.msk/mfd/clearing/issues/7 --- added test for BankAccountController with validation test for add method. For methods update and delete didn't do the check validation empty id because without id REST request for path "/securities/bank-accounts/" not work. --- .../account/BankAccountControllerTest.java | 162 ++++++++++++++++-- 1 file changed, 148 insertions(+), 14 deletions(-) diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java index d89b18d34..e0705f548 100644 --- a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java @@ -2,6 +2,7 @@ package ru.spcex.clearing.backendapi.controller.queue.account; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.NestedExceptionUtils; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; import org.springframework.test.web.servlet.MockMvc; @@ -13,13 +14,18 @@ import ru.spcex.clearing.backendapi.config.WebConfig; import ru.spcex.clearing.backendapi.controller.queue.config.*; import ru.spcex.clearing.backendapi.controller.queue.utils.MatcherFactory; import ru.spcex.clearing.backendapi.controller.request.cud.account.BankAccountNewAction; +import ru.spcex.clearing.backendapi.controller.request.cud.account.BankAccountUpdateAction; import ru.spcex.clearing.backendapi.controller.response.cud.CudResponse; import ru.spcex.clearing.backendapi.controller.response.cud.QueueSuccessResponse; +import ru.spcex.clearing.backendapi.domain.actions.IAction; +import ru.spcex.clearing.backendapi.errors.ActionValidationException; import ru.spcex.clearing.platform.messaging.domain.ActionType; import ru.spcex.clearing.platform.messaging.domain.cud.account.BankAccountNewRequest; import javax.annotation.PostConstruct; +import java.util.concurrent.atomic.AtomicLong; +import static org.junit.jupiter.api.Assertions.assertThrows; 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; @@ -37,6 +43,7 @@ class BankAccountControllerTest { public static final MatcherFactory.Matcher CUD_RESPONSE_MATCHER = MatcherFactory.usingIgnoringFieldsComparator(CudResponse.class); private static final String REST_URL = "/securities/bank-accounts/"; private static final CharacterEncodingFilter CHARACTER_ENCODING_FILTER = new CharacterEncodingFilter(); + private static final AtomicLong currentId = new AtomicLong(); static { CHARACTER_ENCODING_FILTER.setEncoding("UTF-8"); @@ -74,22 +81,21 @@ class BankAccountControllerTest { @Test void add() throws Exception { //ARRANGE - BankAccountNewAction bankAccountNewAction = new BankAccountNewAction(); - bankAccountNewAction.setBankIdentificationCode("044525776"); - bankAccountNewAction.setBankName("Beta Money Bank"); - bankAccountNewAction.setCorrespondentAccount("30101111111111111776"); - bankAccountNewAction.setCorrespondentAccountName("correspondent"); - bankAccountNewAction.setCurrency("RUB"); - bankAccountNewAction.setDestination("destination"); - bankAccountNewAction.setTaxpayerIdentificationNumber("3664011397"); - bankAccountNewAction.setTaxRegistrationReasonCode("01"); - bankAccountNewAction.setAccount("11111222223333344444"); + BankAccountNewAction bankAccountNewAction = getBankAccountNewAction( + "044525776", + "Beta Money Bank", + "30101111111111111776", + "correspondent", + "RUB", + "destination", + "3664011397", + "01", + "11111222223333344444"); CudResponse extended = new CudResponse(); extended.setCode(0L); extended.setMessage("success"); - extended.setPayload(new QueueSuccessResponse(ActionType.NEW, 0L)); - + extended.setPayload(new QueueSuccessResponse(ActionType.NEW, currentId.getAndIncrement())); //ACT mockMvc.perform(MockMvcRequestBuilders.post(REST_URL) .contentType(MediaType.APPLICATION_JSON) @@ -101,11 +107,139 @@ class BankAccountControllerTest { .andExpect(content().json(writeValue(extended))); } + /** + * {@link BankAccountController#add(BankAccountNewAction)}
+ * Тест проверяет работу валидации сущности {@link BankAccountNewAction} принятой по REST API для отправку в Apache Kafka.
+ * Входной запрос {@link BankAccountNewRequest}:
+ * {@link BankAccountNewRequest#bankIdentificationCode} - 044525776 или ""
+ * {@link BankAccountNewRequest#bankName} - Beta Money Bank или ""
+ * {@link BankAccountNewRequest#correspondentAccount} - 30101111111111111776 или ""
+ * {@link BankAccountNewRequest#correspondentAccountName} - correspondent или ""
+ * {@link BankAccountNewRequest#currency} - RUB или ""
+ * {@link BankAccountNewRequest#destination} - destinatio или ""n
+ * {@link BankAccountNewRequest#taxpayerIdentificationNumber} - 3664011397 или ""
+ * {@link BankAccountNewRequest#taxRegistrationReasonCode} - 01 или ""
+ * {@link BankAccountNewRequest#account} - 11111222223333344444 или ""
+ */ @Test - void update() { + 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", "")); } + /** + * {@link BankAccountController#update(Long, BankAccountUpdateAction)}
+ * Тест проверяет получение сущности {@link BankAccountUpdateAction} по REST API и отправку в Apache Kafka.
+ * Входной запрос {@link BankAccountUpdateAction}:
+ * {@link BankAccountUpdateAction#bankIdentificationCode} - 044525776
+ * {@link BankAccountUpdateAction#bankName} - Beta Money Bank
+ * {@link BankAccountUpdateAction#correspondentAccount} - 30101111111111111776
+ * {@link BankAccountUpdateAction#correspondentAccountName} - correspondent
+ * {@link BankAccountUpdateAction#currency} - RUB
+ * {@link BankAccountUpdateAction#destination} - destination
+ * {@link BankAccountUpdateAction#taxpayerIdentificationNumber} - 3664011397
+ * {@link BankAccountUpdateAction#taxRegistrationReasonCode} - 01
+ * {@link BankAccountUpdateAction#account} - 11111222223333344444
+ */ @Test - void delete() { + void update() throws Exception { + //ARRANGE + BankAccountUpdateAction bankAccountNewAction = getBankAccountUpdateAction( + "044525776", + "Beta Money Bank", + "30101111111111111776", + "correspondent", + "RUB", + "destination", + "3664011397", + "01", + "11111222223333344444"); + + CudResponse extended = new CudResponse(); + extended.setCode(0L); + extended.setMessage("success"); + extended.setPayload(new QueueSuccessResponse(ActionType.UPDATE, currentId.getAndIncrement())); + //ACT + mockMvc.perform(MockMvcRequestBuilders.put(REST_URL + "0") + .contentType(MediaType.APPLICATION_JSON) + .content(writeValue(bankAccountNewAction))) + .andDo(print())//output to the log request and response +// ASSERT + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(content().json(writeValue(extended))); + } + + + /** + * {@link BankAccountController#delete(Long)}
+ * Тест проверяет получение id сущности {@link Long} по REST API и отправку в Apache Kafka.
+ * Входной запрос {@link Long}: - 0L
+ */ + @Test + void delete() throws Exception { + //ARRANGE + CudResponse extended = new CudResponse(); + extended.setCode(0L); + extended.setMessage("success"); + extended.setPayload(new QueueSuccessResponse(ActionType.DELETE, currentId.getAndIncrement())); + //ACT + mockMvc.perform(MockMvcRequestBuilders.delete(REST_URL + "0") + .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(extended))); + } + + private void assertThrowsFor(IAction iAction) { + assertThrows(ActionValidationException.class, () -> { + try { + mockMvc.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; + } + }); + } + + private BankAccountNewAction getBankAccountNewAction(String BankIdentificationCode, String BankName, String CorrespondentAccount, String CorrespondentAccountName, + String Currency, String Destination, String TaxpayerIdentificationNumber, String TaxRegistrationReasonCode, + String Account) { + BankAccountNewAction bankAccountNewAction = new BankAccountNewAction(); + bankAccountNewAction.setBankIdentificationCode(BankIdentificationCode); + bankAccountNewAction.setBankName(BankName); + bankAccountNewAction.setCorrespondentAccount(CorrespondentAccount); + bankAccountNewAction.setCorrespondentAccountName(CorrespondentAccountName); + bankAccountNewAction.setCurrency(Currency); + bankAccountNewAction.setDestination(Destination); + bankAccountNewAction.setTaxpayerIdentificationNumber(TaxpayerIdentificationNumber); + bankAccountNewAction.setTaxRegistrationReasonCode(TaxRegistrationReasonCode); + bankAccountNewAction.setAccount(Account); + return bankAccountNewAction; + } + + private BankAccountUpdateAction getBankAccountUpdateAction(String BankIdentificationCode, String BankName, String CorrespondentAccount, String CorrespondentAccountName, + String Currency, String Destination, String TaxpayerIdentificationNumber, String TaxRegistrationReasonCode, + String Account) { + BankAccountUpdateAction bankAccountUpdateAction = new BankAccountUpdateAction(); + bankAccountUpdateAction.setBankIdentificationCode(BankIdentificationCode); + bankAccountUpdateAction.setBankName(BankName); + bankAccountUpdateAction.setCorrespondentAccount(CorrespondentAccount); + bankAccountUpdateAction.setCorrespondentAccountName(CorrespondentAccountName); + bankAccountUpdateAction.setCurrency(Currency); + bankAccountUpdateAction.setDestination(Destination); + bankAccountUpdateAction.setTaxpayerIdentificationNumber(TaxpayerIdentificationNumber); + bankAccountUpdateAction.setTaxRegistrationReasonCode(TaxRegistrationReasonCode); + bankAccountUpdateAction.setAccount(Account); + return bankAccountUpdateAction; } } \ No newline at end of file From 1bceabef85dc69aa741199e6266c43335edd9e7d Mon Sep 17 00:00:00 2001 From: psemenkov Date: Mon, 12 Sep 2022 13:11:12 +0300 Subject: [PATCH 06/33] http://git.mfd.msk/dashboard/issues?assignee_id=30 --- primary testing --- clearing-parent/account-service/pom.xml | 16 ++ .../service/BankAccountServiceTest.java | 203 ++++++++++++++++++ 2 files changed, 219 insertions(+) create mode 100644 clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java diff --git a/clearing-parent/account-service/pom.xml b/clearing-parent/account-service/pom.xml index 7585732cf..01f40da8d 100644 --- a/clearing-parent/account-service/pom.xml +++ b/clearing-parent/account-service/pom.xml @@ -36,6 +36,22 @@ com.fasterxml.jackson.core jackson-databind
+ + + org.mockito + mockito-core + + + org.junit.jupiter + junit-jupiter + test + + + org.assertj + assertj-core + test + + diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java new file mode 100644 index 000000000..907a76f6e --- /dev/null +++ b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java @@ -0,0 +1,203 @@ +package ru.spcex.clearing.account.service; + +import org.apache.kafka.clients.consumer.*; +import org.apache.kafka.common.TopicPartition; +import org.apache.kafka.common.errors.WakeupException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import ru.clearing.classes.statics.data.account.BankAccount; +import ru.spcex.clearing.imdg.IMDGDistributedNames; +import ru.spcex.clearing.platform.messaging.domain.Consts; +import ru.spcex.platform.imdg.api.Imdg; +import ru.spcex.platform.imdg.api.ImdgProvider; +import ru.spcex.platform.imdg.iml.hazelcast.adapter.ImdgHazelcast; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.stream.StreamSupport; + +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +import static org.mockito.Mockito.doReturn; + +class BankAccountServiceTest { + + private static final int PARTITION = 0; + private static final String TOPIC = Consts.DESTINATION_BANK_ACCOUNT_NEW; + private MockConsumer consumer; + private MockConsumer mockConsumer; + private List updates; + private CountryPopulationConsumer countryPopulationConsumer; + private Throwable pollException; + + @BeforeEach + void setUp() { + mockConsumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); + + consumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); + updates = new ArrayList<>(); + countryPopulationConsumer = new CountryPopulationConsumer(consumer, + ex -> this.pollException = ex, updates::add); + } + + @Test + public void bankAccountNew() { + //arrange + mockConsumer.schedulePollTask(() -> { + mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC, PARTITION))); + mockConsumer.addRecord(new ConsumerRecord<>(TOPIC, PARTITION, 0, "key", "value")); + }); + mockConsumer.schedulePollTask(() -> mockConsumer.wakeup()); + + HashMap startOffsets = new HashMap<>(); + TopicPartition tp = new TopicPartition(TOPIC, PARTITION); + startOffsets.put(tp, 0L); + mockConsumer.updateBeginningOffsets(startOffsets); + + ImdgProvider imdgProvider = Mockito.mock(ImdgProvider.class); + Imdg bankAccountMap = new ImdgHazelcast(); + doReturn(bankAccountMap).when(imdgProvider).getImdg(IMDGDistributedNames.Map_BankAccount, BankAccount.class); + + BankAccountService bankAccountService = new BankAccountService(mockConsumer, imdgProvider); +// Map>> records = new LinkedHashMap<>(); +// +// String topic = Consts.DESTINATION_BANK_ACCOUNT_NEW; +// ConsumerRecord record1 = new ConsumerRecord<>(topic, 1, 0, 0L, TimestampType.CREATE_TIME, 0L, 0, 0, 1, "value1"); +// records.put(new TopicPartition(topic, 0), Arrays.asList(record1)); + + //doReturn(records).when(kafkaQueue).poll(Duration.of(10, ChronoUnit.SECONDS)); + + + //act + bankAccountService.afterPropertiesSet(); + + //assert + + } + + @Test + void whenStartingByAssigningTopicPartition_thenExpectUpdatesAreConsumedCorrectly() { + // GIVEN + consumer.schedulePollTask(() -> consumer.addRecord(record(TOPIC, PARTITION, "Romania", 19_410_000))); + consumer.schedulePollTask(() -> countryPopulationConsumer.stop()); + + HashMap startOffsets = new HashMap<>(); + TopicPartition tp = new TopicPartition(TOPIC, PARTITION); + startOffsets.put(tp, 0L); + consumer.updateBeginningOffsets(startOffsets); + + // WHEN + countryPopulationConsumer.startByAssigning(TOPIC, PARTITION); + + // THEN + assertThat(updates).hasSize(1); + assertThat(consumer.closed()).isTrue(); + } + + @Test + void whenStartingBySubscribingToTopic_thenExpectUpdatesAreConsumedCorrectly() { + // GIVEN + consumer.schedulePollTask(() -> { + consumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC, PARTITION))); + consumer.addRecord(record(TOPIC, PARTITION, "Romania", 20)); + }); + consumer.schedulePollTask(() -> countryPopulationConsumer.stop()); + + HashMap startOffsets = new HashMap<>(); + TopicPartition tp = new TopicPartition(TOPIC, 0); + startOffsets.put(tp, 0L); + consumer.updateBeginningOffsets(startOffsets); + + // WHEN + countryPopulationConsumer.startBySubscribing(TOPIC); + + // THEN + assertThat(updates).hasSize(1); + assertThat(consumer.closed()).isTrue(); + } + + class CountryPopulation { + + private String country; + private Integer population; + + // standard constructor, getters and setters + + + public CountryPopulation(String country, Integer population) { + this.country = country; + this.population = population; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public Integer getPopulation() { + return population; + } + + public void setPopulation(Integer population) { + this.population = population; + } + } + + public class CountryPopulationConsumer { + + private Consumer consumer; + private java.util.function.Consumer exceptionConsumer; + private java.util.function.Consumer countryPopulationConsumer; + + // standard constructor + + + public CountryPopulationConsumer(Consumer consumer, java.util.function.Consumer exceptionConsumer, java.util.function.Consumer countryPopulationConsumer) { + this.consumer = consumer; + this.exceptionConsumer = exceptionConsumer; + this.countryPopulationConsumer = countryPopulationConsumer; + } + + void startBySubscribing(String topic) { + consume(() -> consumer.subscribe(Collections.singleton(topic))); + } + + void startByAssigning(String topic, int partition) { + consume(() -> consumer.assign(Collections.singleton(new TopicPartition(topic, partition)))); + } + + private void consume(Runnable beforePollingTask) { + try { + beforePollingTask.run(); + while (true) { + ConsumerRecords records = consumer.poll(Duration.of(10, ChronoUnit.SECONDS)); + StreamSupport.stream(records.spliterator(), false) + .map(record -> new CountryPopulation(record.key(), record.value())) + .forEach(countryPopulationConsumer); + consumer.commitSync(); + } + } catch (WakeupException e) { + System.out.println("Shutting down..."); + } catch (RuntimeException ex) { + exceptionConsumer.accept(ex); + } finally { + consumer.close(); + } + } + + public void stop() { + consumer.wakeup(); + } + } + + private ConsumerRecord record(String topic, int partition, String country, int population) { + return new ConsumerRecord<>(topic, partition, 0, country, population); + } +} \ No newline at end of file From cac7d654082dad21c90e3e9ec2b6cfefa4961076 Mon Sep 17 00:00:00 2001 From: aalehin Date: Mon, 12 Sep 2022 13:37:54 +0300 Subject: [PATCH 07/33] http://git.mfd.msk/dashboard/issues?assignee_id=30 --- small refactor --- .../service/BankAccountServiceTest.java | 144 +----------------- 1 file changed, 4 insertions(+), 140 deletions(-) diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java index 907a76f6e..621c5e9e4 100644 --- a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java +++ b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java @@ -1,8 +1,9 @@ package ru.spcex.clearing.account.service; -import org.apache.kafka.clients.consumer.*; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.MockConsumer; +import org.apache.kafka.clients.consumer.OffsetResetStrategy; import org.apache.kafka.common.TopicPartition; -import org.apache.kafka.common.errors.WakeupException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -13,35 +14,20 @@ import ru.spcex.platform.imdg.api.Imdg; import ru.spcex.platform.imdg.api.ImdgProvider; import ru.spcex.platform.imdg.iml.hazelcast.adapter.ImdgHazelcast; -import java.time.Duration; -import java.time.temporal.ChronoUnit; -import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; -import java.util.List; -import java.util.stream.StreamSupport; -import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import static org.mockito.Mockito.doReturn; class BankAccountServiceTest { private static final int PARTITION = 0; private static final String TOPIC = Consts.DESTINATION_BANK_ACCOUNT_NEW; - private MockConsumer consumer; private MockConsumer mockConsumer; - private List updates; - private CountryPopulationConsumer countryPopulationConsumer; - private Throwable pollException; @BeforeEach void setUp() { mockConsumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); - - consumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); - updates = new ArrayList<>(); - countryPopulationConsumer = new CountryPopulationConsumer(consumer, - ex -> this.pollException = ex, updates::add); } @Test @@ -49,7 +35,7 @@ class BankAccountServiceTest { //arrange mockConsumer.schedulePollTask(() -> { mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC, PARTITION))); - mockConsumer.addRecord(new ConsumerRecord<>(TOPIC, PARTITION, 0, "key", "value")); + mockConsumer.addRecord(new ConsumerRecord<>(TOPIC, PARTITION, 0, "key", "test-value")); }); mockConsumer.schedulePollTask(() -> mockConsumer.wakeup()); @@ -78,126 +64,4 @@ class BankAccountServiceTest { //assert } - - @Test - void whenStartingByAssigningTopicPartition_thenExpectUpdatesAreConsumedCorrectly() { - // GIVEN - consumer.schedulePollTask(() -> consumer.addRecord(record(TOPIC, PARTITION, "Romania", 19_410_000))); - consumer.schedulePollTask(() -> countryPopulationConsumer.stop()); - - HashMap startOffsets = new HashMap<>(); - TopicPartition tp = new TopicPartition(TOPIC, PARTITION); - startOffsets.put(tp, 0L); - consumer.updateBeginningOffsets(startOffsets); - - // WHEN - countryPopulationConsumer.startByAssigning(TOPIC, PARTITION); - - // THEN - assertThat(updates).hasSize(1); - assertThat(consumer.closed()).isTrue(); - } - - @Test - void whenStartingBySubscribingToTopic_thenExpectUpdatesAreConsumedCorrectly() { - // GIVEN - consumer.schedulePollTask(() -> { - consumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC, PARTITION))); - consumer.addRecord(record(TOPIC, PARTITION, "Romania", 20)); - }); - consumer.schedulePollTask(() -> countryPopulationConsumer.stop()); - - HashMap startOffsets = new HashMap<>(); - TopicPartition tp = new TopicPartition(TOPIC, 0); - startOffsets.put(tp, 0L); - consumer.updateBeginningOffsets(startOffsets); - - // WHEN - countryPopulationConsumer.startBySubscribing(TOPIC); - - // THEN - assertThat(updates).hasSize(1); - assertThat(consumer.closed()).isTrue(); - } - - class CountryPopulation { - - private String country; - private Integer population; - - // standard constructor, getters and setters - - - public CountryPopulation(String country, Integer population) { - this.country = country; - this.population = population; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - public Integer getPopulation() { - return population; - } - - public void setPopulation(Integer population) { - this.population = population; - } - } - - public class CountryPopulationConsumer { - - private Consumer consumer; - private java.util.function.Consumer exceptionConsumer; - private java.util.function.Consumer countryPopulationConsumer; - - // standard constructor - - - public CountryPopulationConsumer(Consumer consumer, java.util.function.Consumer exceptionConsumer, java.util.function.Consumer countryPopulationConsumer) { - this.consumer = consumer; - this.exceptionConsumer = exceptionConsumer; - this.countryPopulationConsumer = countryPopulationConsumer; - } - - void startBySubscribing(String topic) { - consume(() -> consumer.subscribe(Collections.singleton(topic))); - } - - void startByAssigning(String topic, int partition) { - consume(() -> consumer.assign(Collections.singleton(new TopicPartition(topic, partition)))); - } - - private void consume(Runnable beforePollingTask) { - try { - beforePollingTask.run(); - while (true) { - ConsumerRecords records = consumer.poll(Duration.of(10, ChronoUnit.SECONDS)); - StreamSupport.stream(records.spliterator(), false) - .map(record -> new CountryPopulation(record.key(), record.value())) - .forEach(countryPopulationConsumer); - consumer.commitSync(); - } - } catch (WakeupException e) { - System.out.println("Shutting down..."); - } catch (RuntimeException ex) { - exceptionConsumer.accept(ex); - } finally { - consumer.close(); - } - } - - public void stop() { - consumer.wakeup(); - } - } - - private ConsumerRecord record(String topic, int partition, String country, int population) { - return new ConsumerRecord<>(topic, partition, 0, country, population); - } } \ No newline at end of file From 7c17cf4e46eb61a19b9ef2275ab87fb87b0754f2 Mon Sep 17 00:00:00 2001 From: aalehin Date: Mon, 12 Sep 2022 13:42:43 +0300 Subject: [PATCH 08/33] http://git.mfd.msk/dashboard/issues?assignee_id=30 --- small refactor --- .../spcex/clearing/account/service/BankAccountServiceTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java index 621c5e9e4..a3572d8db 100644 --- a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java +++ b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java @@ -43,7 +43,6 @@ class BankAccountServiceTest { TopicPartition tp = new TopicPartition(TOPIC, PARTITION); startOffsets.put(tp, 0L); mockConsumer.updateBeginningOffsets(startOffsets); - ImdgProvider imdgProvider = Mockito.mock(ImdgProvider.class); Imdg bankAccountMap = new ImdgHazelcast(); doReturn(bankAccountMap).when(imdgProvider).getImdg(IMDGDistributedNames.Map_BankAccount, BankAccount.class); From c9a0994fbad4e5c4de45de76636960754571fb25 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Wed, 14 Sep 2022 15:20:28 +0300 Subject: [PATCH 09/33] http://git.mfd.msk/dashboard/issues?assignee_id=30 --- adding hazelcast client --- clearing-parent/account-service/pom.xml | 5 + .../HazelcastInstanceTestConfiguration.java | 29 +++++ .../HazelcastServiceTestConfiguration.java | 73 ++++++++++++ .../service/BankAccountServiceTest.java | 106 ++++++++++++++---- 4 files changed, 194 insertions(+), 19 deletions(-) create mode 100644 clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastInstanceTestConfiguration.java create mode 100644 clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastServiceTestConfiguration.java diff --git a/clearing-parent/account-service/pom.xml b/clearing-parent/account-service/pom.xml index 01f40da8d..683aff67d 100644 --- a/clearing-parent/account-service/pom.xml +++ b/clearing-parent/account-service/pom.xml @@ -37,6 +37,11 @@ jackson-databind + + org.springframework + spring-test + test + org.mockito mockito-core diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastInstanceTestConfiguration.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastInstanceTestConfiguration.java new file mode 100644 index 000000000..410d8392d --- /dev/null +++ b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastInstanceTestConfiguration.java @@ -0,0 +1,29 @@ +package ru.spcex.clearing.account.config; + +import com.hazelcast.config.Config; +import com.hazelcast.config.JoinConfig; +import com.hazelcast.config.MulticastConfig; +import com.hazelcast.config.NetworkConfig; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.Random; + +@Configuration +public class HazelcastInstanceTestConfiguration { + + @Bean(name = "hazelcastInstance") + public HazelcastInstance hazelcastInstance() { + Config cfg = new Config(); + cfg.setInstanceName("unittest_test_" + new Random().nextInt()); + NetworkConfig networkConfig = new NetworkConfig(); + JoinConfig joinConfig = new JoinConfig(); + joinConfig.setMulticastConfig(new MulticastConfig().setEnabled(false)); + networkConfig.setJoin(joinConfig); + cfg.setNetworkConfig(networkConfig); + return Hazelcast.newHazelcastInstance(cfg); + } + +} diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastServiceTestConfiguration.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastServiceTestConfiguration.java new file mode 100644 index 000000000..2dbc81965 --- /dev/null +++ b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastServiceTestConfiguration.java @@ -0,0 +1,73 @@ +package ru.spcex.clearing.account.config; + +import com.hazelcast.config.*; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import ru.spcex.platform.imdg.iml.hazelcast.config.HazelcastClientParams; +import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService; + +import java.util.List; + +@Configuration +public class HazelcastServiceTestConfiguration { + private HazelcastInstance hazelcastInstance; + + private static ThreadPoolTaskExecutor createThreadPoolTaskExecutor(int maxPoolSz, boolean waitForCompletion) { + ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor(); + if (maxPoolSz > 2) { + pool.setKeepAliveSeconds(60); + pool.setAllowCoreThreadTimeOut(true); + } + pool.setCorePoolSize(maxPoolSz); + pool.setWaitForTasksToCompleteOnShutdown(waitForCompletion); + return pool; + } + + @Bean(name = "hazelcastServiceTest") + public HazelcastService hazelcastService(@Qualifier("taskExecutorHazelcastClientInitializer") ThreadPoolTaskExecutor taskExecutorHazelcastClientInitializer, @Qualifier("taskExecutorIdGeneratorAwaiter") ThreadPoolTaskExecutor taskExecutorIdGeneratorAwaiter, HazelcastClientParams params) { + Config cfg = new Config(); + cfg.setInstanceName("localhost"); + + NetworkConfig networkConfig = new NetworkConfig(); + JoinConfig joinConfig = new JoinConfig(); + joinConfig.setMulticastConfig(new MulticastConfig().setEnabled(false)); + joinConfig.setTcpIpConfig(new TcpIpConfig().setEnabled(true).setMembers(List.of("127.0.0.1"))); + networkConfig.setJoin(joinConfig); +// .setPort(configRoot.getHazelcast().getListenPort()) +// .setJoin(new JoinConfig() +// .setMulticastConfig(new MulticastConfig() +// .setEnabled(false)) +// .setTcpIpConfig(new TcpIpConfig() +// .setEnabled(true).setMembers(hzSettings.getClusterMembers()) +// ) + cfg.setNetworkConfig(networkConfig); + hazelcastInstance = Hazelcast.newHazelcastInstance(cfg); + return new HazelcastService(taskExecutorHazelcastClientInitializer, taskExecutorIdGeneratorAwaiter, params); + } + + @Bean(name = "taskExecutorHazelcastClientInitializer") + public ThreadPoolTaskExecutor taskExecutorHazelcastClientInitializer() { + return createThreadPoolTaskExecutor(1, true); + } + + @Bean(name = "taskExecutorIdGeneratorAwaiter") + public ThreadPoolTaskExecutor taskExecutorIdGeneratorAwaiter() { + return createThreadPoolTaskExecutor(1, false); + } + + @Bean(name = "hazelcastClientParams") + public HazelcastClientParams getHazelcastClientParams() { + HazelcastClientParams params = new HazelcastClientParams(); + params.setLogin("dev"); + params.setPassword("dev-pass"); + params.setClusterMembers("127.0.0.1"); + params.setInstanceName("localhost"); + params.setNearCacheConfig(new NearCacheConfig()); + + return params; + } +} diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java index a3572d8db..d7c11a50c 100644 --- a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java +++ b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java @@ -1,41 +1,81 @@ package ru.spcex.clearing.account.service; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.hazelcast.core.IMap; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.MockConsumer; import org.apache.kafka.clients.consumer.OffsetResetStrategy; import org.apache.kafka.common.TopicPartition; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.Mockito; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; import ru.clearing.classes.statics.data.account.BankAccount; +import ru.spcex.clearing.account.config.HazelcastServiceTestConfiguration; import ru.spcex.clearing.imdg.IMDGDistributedNames; +import ru.spcex.clearing.platform.messaging.domain.ActionType; +import ru.spcex.clearing.platform.messaging.domain.BaseRequest; import ru.spcex.clearing.platform.messaging.domain.Consts; +import ru.spcex.clearing.platform.messaging.domain.cud.account.BankAccountNewRequest; import ru.spcex.platform.imdg.api.Imdg; -import ru.spcex.platform.imdg.api.ImdgProvider; -import ru.spcex.platform.imdg.iml.hazelcast.adapter.ImdgHazelcast; +import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService; import java.util.Collections; import java.util.HashMap; -import static org.mockito.Mockito.doReturn; - -class BankAccountServiceTest { +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { + HazelcastServiceTestConfiguration.class}) +public class BankAccountServiceTest { private static final int PARTITION = 0; private static final String TOPIC = Consts.DESTINATION_BANK_ACCOUNT_NEW; + private final String jsonBaseRequest; + private final ObjectMapper objectMapper = new ObjectMapper(); + private final BankAccountNewRequest bankAccountNewRequest = new BankAccountNewRequest(); + private final BaseRequest baseRequest = new BaseRequest<>(); + + @Autowired + @Qualifier("hazelcastServiceTest") + private HazelcastService hazelcastServiceTest; private MockConsumer mockConsumer; + { + bankAccountNewRequest.setBankName("ooo tinkoff"); + bankAccountNewRequest.setBankIdentificationCode("99999"); + bankAccountNewRequest.setCorrespondentAccount("9294189285498598598"); + bankAccountNewRequest.setCorrespondentAccountName("BIK OF TINKOFF"); + bankAccountNewRequest.setCurrency("RUB"); + bankAccountNewRequest.setDestination("OOO ROGA I KOPITA"); + bankAccountNewRequest.setTaxpayerIdentificationNumber("848484848484"); + bankAccountNewRequest.setTaxRegistrationReasonCode("886886"); + bankAccountNewRequest.setAccount("123456789123"); + + baseRequest.setRequestPayload(bankAccountNewRequest); + baseRequest.setId(0L); + baseRequest.setActionType(ActionType.NEW); + try { + jsonBaseRequest = objectMapper.writeValueAsString(baseRequest); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + } + @BeforeEach void setUp() { mockConsumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); } @Test - public void bankAccountNew() { + public void bankAccountNew() throws InterruptedException { //arrange mockConsumer.schedulePollTask(() -> { mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC, PARTITION))); - mockConsumer.addRecord(new ConsumerRecord<>(TOPIC, PARTITION, 0, "key", "test-value")); + mockConsumer.addRecord(new ConsumerRecord<>(TOPIC, PARTITION, 0, "key", jsonBaseRequest)); }); mockConsumer.schedulePollTask(() -> mockConsumer.wakeup()); @@ -43,24 +83,52 @@ class BankAccountServiceTest { TopicPartition tp = new TopicPartition(TOPIC, PARTITION); startOffsets.put(tp, 0L); mockConsumer.updateBeginningOffsets(startOffsets); - ImdgProvider imdgProvider = Mockito.mock(ImdgProvider.class); - Imdg bankAccountMap = new ImdgHazelcast(); - doReturn(bankAccountMap).when(imdgProvider).getImdg(IMDGDistributedNames.Map_BankAccount, BankAccount.class); - BankAccountService bankAccountService = new BankAccountService(mockConsumer, imdgProvider); -// Map>> records = new LinkedHashMap<>(); + +// ImdgProvider imdgProvider = Mockito.mock(ImdgProvider.class); // -// String topic = Consts.DESTINATION_BANK_ACCOUNT_NEW; -// ConsumerRecord record1 = new ConsumerRecord<>(topic, 1, 0, 0L, TimestampType.CREATE_TIME, 0L, 0, 0, 1, "value1"); -// records.put(new TopicPartition(topic, 0), Arrays.asList(record1)); - - //doReturn(records).when(kafkaQueue).poll(Duration.of(10, ChronoUnit.SECONDS)); +// ImdgHazelcast bankAccountMap = Mockito.mock(ImdgHazelcast.class); +// +// ArgumentCaptor bankAccountCaptor = ArgumentCaptor.forClass(BankAccount.class); +// +// doReturn(bankAccountMap).when(imdgProvider).getImdg(IMDGDistributedNames.Map_BankAccount, BankAccount.class); - //act + try { + hazelcastServiceTest.init(); + Thread.sleep(10000); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + //мапа которую проверял Илья + IMap map = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_KeyRate); + Imdg imdg = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_BankAccount, BankAccount.class); +// IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_BankAccount); + BankAccountService bankAccountService = new BankAccountService(mockConsumer, hazelcastServiceTest); bankAccountService.afterPropertiesSet(); + + Thread.sleep(10000); + IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_BankAccount); + + BankAccount predictableResult = new BankAccount(); + predictableResult.setBankName("ooo tinkoff"); + predictableResult.setBankIdentificationCode("99999"); + predictableResult.setCorrespondentAccount("9294189285498598598"); + predictableResult.setCorrespondentAccountName("BIK OF TINKOFF"); + predictableResult.setCurrency("RUB"); + predictableResult.setDestination("OOO ROGA I KOPITA"); + predictableResult.setTaxpayerIdentificationNumber("848484848484"); + predictableResult.setTaxRegistrationReasonCode("886886"); + predictableResult.setAccount("123456789123"); + + +// Mockito.verify(bankAccountMap).insert(bankAccountCaptor.capture()); + +// BankAccount bankAccount = bankAccountCaptor.getValue(); //assert + +// assertThat(bankAccount).isEqualTo(predictableResult); } } \ No newline at end of file From 49fe74ea60e3aabb25ae7b35e0bb8620b246b894 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Thu, 15 Sep 2022 11:56:24 +0300 Subject: [PATCH 10/33] http://git.mfd.msk/dashboard/issues?assignee_id=30 --- hz and kafka working --- .../config/HazelcastServiceTestConfiguration.java | 5 ++++- .../account/service/BankAccountServiceTest.java | 13 +++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastServiceTestConfiguration.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastServiceTestConfiguration.java index 2dbc81965..7e92690b0 100644 --- a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastServiceTestConfiguration.java +++ b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastServiceTestConfiguration.java @@ -9,8 +9,10 @@ import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import ru.spcex.platform.imdg.iml.hazelcast.config.HazelcastClientParams; import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService; +import ru.spcex.platform.imdg.iml.hazelcast.util.HazelcastHelper; import java.util.List; +import java.util.Random; @Configuration public class HazelcastServiceTestConfiguration { @@ -46,6 +48,7 @@ public class HazelcastServiceTestConfiguration { // ) cfg.setNetworkConfig(networkConfig); hazelcastInstance = Hazelcast.newHazelcastInstance(cfg); + HazelcastHelper.otcSystem_setStorageState(true, hazelcastInstance); return new HazelcastService(taskExecutorHazelcastClientInitializer, taskExecutorIdGeneratorAwaiter, params); } @@ -65,7 +68,7 @@ public class HazelcastServiceTestConfiguration { params.setLogin("dev"); params.setPassword("dev-pass"); params.setClusterMembers("127.0.0.1"); - params.setInstanceName("localhost"); + params.setInstanceName("hzTestClient" + new Random().nextInt()); params.setNearCacheConfig(new NearCacheConfig()); return params; diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java index d7c11a50c..ff35a61f7 100644 --- a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java +++ b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java @@ -92,19 +92,16 @@ public class BankAccountServiceTest { // ArgumentCaptor bankAccountCaptor = ArgumentCaptor.forClass(BankAccount.class); // // doReturn(bankAccountMap).when(imdgProvider).getImdg(IMDGDistributedNames.Map_BankAccount, BankAccount.class); - - + //мапа которую проверял Илья + Imdg imdg = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_BankAccount, BankAccount.class); +// IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_BankAccount); + BankAccountService bankAccountService = new BankAccountService(mockConsumer, hazelcastServiceTest); try { - hazelcastServiceTest.init(); +// hazelcastServiceTest.init(); Thread.sleep(10000); } catch (InterruptedException e) { throw new RuntimeException(e); } - //мапа которую проверял Илья - IMap map = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_KeyRate); - Imdg imdg = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_BankAccount, BankAccount.class); -// IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_BankAccount); - BankAccountService bankAccountService = new BankAccountService(mockConsumer, hazelcastServiceTest); bankAccountService.afterPropertiesSet(); From bb49709287d4f6fcd52c3c562d63dad3be7e7d84 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Thu, 15 Sep 2022 12:17:28 +0300 Subject: [PATCH 11/33] http://git.mfd.msk/dashboard/issues?assignee_id=30 --- first test done --- .../account/service/BankAccountService.java | 1 + .../service/BankAccountServiceTest.java | 67 +++++++------------ .../account/utils/MatcherFactory.java | 38 +++++++++++ 3 files changed, 65 insertions(+), 41 deletions(-) create mode 100644 clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/utils/MatcherFactory.java diff --git a/clearing-parent/account-service/src/main/java/ru/spcex/clearing/account/service/BankAccountService.java b/clearing-parent/account-service/src/main/java/ru/spcex/clearing/account/service/BankAccountService.java index b95313fd0..176a6a35a 100644 --- a/clearing-parent/account-service/src/main/java/ru/spcex/clearing/account/service/BankAccountService.java +++ b/clearing-parent/account-service/src/main/java/ru/spcex/clearing/account/service/BankAccountService.java @@ -54,6 +54,7 @@ public class BankAccountService extends QueueConsumer implements InitializingBea bankAccount.setDestination(req.getDestination()); bankAccount.setTaxpayerIdentificationNumber(req.getTaxpayerIdentificationNumber()); bankAccount.setTaxRegistrationReasonCode(req.getTaxRegistrationReasonCode()); + bankAccount.setAccount(req.getAccount()); bankAccountMap.insert(bankAccount); log.debug("successfully processed, new id {}", bankAccount.getId()); diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java index ff35a61f7..b0864cef4 100644 --- a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java +++ b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java @@ -16,22 +16,24 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import ru.clearing.classes.statics.data.account.BankAccount; import ru.spcex.clearing.account.config.HazelcastServiceTestConfiguration; +import ru.spcex.clearing.account.utils.MatcherFactory.Matcher; import ru.spcex.clearing.imdg.IMDGDistributedNames; import ru.spcex.clearing.platform.messaging.domain.ActionType; import ru.spcex.clearing.platform.messaging.domain.BaseRequest; import ru.spcex.clearing.platform.messaging.domain.Consts; import ru.spcex.clearing.platform.messaging.domain.cud.account.BankAccountNewRequest; -import ru.spcex.platform.imdg.api.Imdg; import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService; import java.util.Collections; import java.util.HashMap; +import static ru.spcex.clearing.account.utils.MatcherFactory.usingIgnoringFieldsComparator; + @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = { HazelcastServiceTestConfiguration.class}) public class BankAccountServiceTest { - + public static final Matcher BANK_ACCOUNT_MATCHER = usingIgnoringFieldsComparator("id"); private static final int PARTITION = 0; private static final String TOPIC = Consts.DESTINATION_BANK_ACCOUNT_NEW; private final String jsonBaseRequest; @@ -73,41 +75,6 @@ public class BankAccountServiceTest { @Test public void bankAccountNew() throws InterruptedException { //arrange - mockConsumer.schedulePollTask(() -> { - mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC, PARTITION))); - mockConsumer.addRecord(new ConsumerRecord<>(TOPIC, PARTITION, 0, "key", jsonBaseRequest)); - }); - mockConsumer.schedulePollTask(() -> mockConsumer.wakeup()); - - HashMap startOffsets = new HashMap<>(); - TopicPartition tp = new TopicPartition(TOPIC, PARTITION); - startOffsets.put(tp, 0L); - mockConsumer.updateBeginningOffsets(startOffsets); - - -// ImdgProvider imdgProvider = Mockito.mock(ImdgProvider.class); -// -// ImdgHazelcast bankAccountMap = Mockito.mock(ImdgHazelcast.class); -// -// ArgumentCaptor bankAccountCaptor = ArgumentCaptor.forClass(BankAccount.class); -// -// doReturn(bankAccountMap).when(imdgProvider).getImdg(IMDGDistributedNames.Map_BankAccount, BankAccount.class); - //мапа которую проверял Илья - Imdg imdg = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_BankAccount, BankAccount.class); -// IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_BankAccount); - BankAccountService bankAccountService = new BankAccountService(mockConsumer, hazelcastServiceTest); - try { -// hazelcastServiceTest.init(); - Thread.sleep(10000); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - bankAccountService.afterPropertiesSet(); - - - Thread.sleep(10000); - IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_BankAccount); - BankAccount predictableResult = new BankAccount(); predictableResult.setBankName("ooo tinkoff"); predictableResult.setBankIdentificationCode("99999"); @@ -118,14 +85,32 @@ public class BankAccountServiceTest { predictableResult.setTaxpayerIdentificationNumber("848484848484"); predictableResult.setTaxRegistrationReasonCode("886886"); predictableResult.setAccount("123456789123"); + predictableResult.setId(0L); + //KAFKA + mockConsumer.schedulePollTask(() -> { + mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC, PARTITION))); + mockConsumer.addRecord(new ConsumerRecord<>(TOPIC, PARTITION, 0, "key", jsonBaseRequest)); + }); + + HashMap startOffsets = new HashMap<>(); + TopicPartition tp = new TopicPartition(TOPIC, PARTITION); + startOffsets.put(tp, 0L); + mockConsumer.updateBeginningOffsets(startOffsets); -// Mockito.verify(bankAccountMap).insert(bankAccountCaptor.capture()); + //ACT -// BankAccount bankAccount = bankAccountCaptor.getValue(); - //assert + //service set up + BankAccountService bankAccountService = new BankAccountService(mockConsumer, hazelcastServiceTest); + Thread.sleep(10000); + //callbacks set up + bankAccountService.afterPropertiesSet(); + Thread.sleep(10000); + //ASSERT + IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_BankAccount); + BankAccount result = iMap.get(0L); -// assertThat(bankAccount).isEqualTo(predictableResult); + BANK_ACCOUNT_MATCHER.assertMatch(result, predictableResult); } } \ No newline at end of file diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/utils/MatcherFactory.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/utils/MatcherFactory.java new file mode 100644 index 000000000..b2d1a4fdc --- /dev/null +++ b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/utils/MatcherFactory.java @@ -0,0 +1,38 @@ +package ru.spcex.clearing.account.utils; + +import java.util.Arrays; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Factory for creating test matchers. + *

+ * Comparing actual and expected objects via AssertJ + */ +public class MatcherFactory { + + public static Matcher usingIgnoringFieldsComparator(String... fieldsToIgnore) { + return new Matcher<>(fieldsToIgnore); + } + + public static class Matcher { + private final String[] fieldsToIgnore; + + private Matcher(String... fieldsToIgnore) { + this.fieldsToIgnore = fieldsToIgnore; + } + + public void assertMatch(T actual, T expected) { + assertThat(actual).usingRecursiveComparison().ignoringFields(fieldsToIgnore).isEqualTo(expected); + } + + @SafeVarargs + public final void assertMatch(Iterable actual, T... expected) { + assertMatch(actual, Arrays.asList(expected)); + } + + public void assertMatch(Iterable actual, Iterable expected) { + assertThat(actual).usingRecursiveFieldByFieldElementComparatorIgnoringFields(fieldsToIgnore).isEqualTo(expected); + } + } +} From 1cbb7fbf234d5460475cf90b723e7c188f472c50 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Thu, 15 Sep 2022 16:45:02 +0300 Subject: [PATCH 12/33] http://git.mfd.msk/dashboard/issues?assignee_id=30 --- tree test done, but dot work together --- .../account/service/BankAccountService.java | 3 + .../HazelcastServiceTestConfiguration.java | 7 - .../service/BankAccountServiceTest.java | 220 ++++++++++++++++-- 3 files changed, 199 insertions(+), 31 deletions(-) diff --git a/clearing-parent/account-service/src/main/java/ru/spcex/clearing/account/service/BankAccountService.java b/clearing-parent/account-service/src/main/java/ru/spcex/clearing/account/service/BankAccountService.java index 176a6a35a..11e168726 100644 --- a/clearing-parent/account-service/src/main/java/ru/spcex/clearing/account/service/BankAccountService.java +++ b/clearing-parent/account-service/src/main/java/ru/spcex/clearing/account/service/BankAccountService.java @@ -72,7 +72,10 @@ public class BankAccountService extends QueueConsumer implements InitializingBea bankAccount.setDestination(req.getDestination()); bankAccount.setTaxpayerIdentificationNumber(req.getTaxpayerIdentificationNumber()); bankAccount.setTaxRegistrationReasonCode(req.getTaxRegistrationReasonCode()); + bankAccount.setAccount(req.getAccount()); + bankAccountMap.update(bankAccount); + log.debug("successfully update, existing bankAccount with id {}", bankAccount.getId()); } private void bankAccountDelete(BaseRequest userRequest) { diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastServiceTestConfiguration.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastServiceTestConfiguration.java index 7e92690b0..3a64d5190 100644 --- a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastServiceTestConfiguration.java +++ b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastServiceTestConfiguration.java @@ -39,13 +39,6 @@ public class HazelcastServiceTestConfiguration { joinConfig.setMulticastConfig(new MulticastConfig().setEnabled(false)); joinConfig.setTcpIpConfig(new TcpIpConfig().setEnabled(true).setMembers(List.of("127.0.0.1"))); networkConfig.setJoin(joinConfig); -// .setPort(configRoot.getHazelcast().getListenPort()) -// .setJoin(new JoinConfig() -// .setMulticastConfig(new MulticastConfig() -// .setEnabled(false)) -// .setTcpIpConfig(new TcpIpConfig() -// .setEnabled(true).setMembers(hzSettings.getClusterMembers()) -// ) cfg.setNetworkConfig(networkConfig); hazelcastInstance = Hazelcast.newHazelcastInstance(cfg); HazelcastHelper.otcSystem_setStorageState(true, hazelcastInstance); diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java index b0864cef4..3763ec977 100644 --- a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java +++ b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java @@ -7,6 +7,7 @@ import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.MockConsumer; import org.apache.kafka.clients.consumer.OffsetResetStrategy; import org.apache.kafka.common.TopicPartition; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -22,6 +23,8 @@ import ru.spcex.clearing.platform.messaging.domain.ActionType; import ru.spcex.clearing.platform.messaging.domain.BaseRequest; import ru.spcex.clearing.platform.messaging.domain.Consts; import ru.spcex.clearing.platform.messaging.domain.cud.account.BankAccountNewRequest; +import ru.spcex.clearing.platform.messaging.domain.cud.account.BankAccountUpdateRequest; +import ru.spcex.clearing.platform.messaging.domain.cud.common.CommonDeleteRequest; import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService; import java.util.Collections; @@ -35,18 +38,24 @@ import static ru.spcex.clearing.account.utils.MatcherFactory.usingIgnoringFields public class BankAccountServiceTest { public static final Matcher BANK_ACCOUNT_MATCHER = usingIgnoringFieldsComparator("id"); private static final int PARTITION = 0; - private static final String TOPIC = Consts.DESTINATION_BANK_ACCOUNT_NEW; - private final String jsonBaseRequest; - private final ObjectMapper objectMapper = new ObjectMapper(); - private final BankAccountNewRequest bankAccountNewRequest = new BankAccountNewRequest(); - private final BaseRequest baseRequest = new BaseRequest<>(); + private static final String TOPIC_ACCOUNT_NEW = Consts.DESTINATION_BANK_ACCOUNT_NEW; + private static final String TOPIC_ACCOUNT_UPDATE = Consts.DESTINATION_BANK_ACCOUNT_UPDATE; + private static final String TOPIC_ACCOUNT_DELETE = Consts.DESTINATION_BANK_ACCOUNT_DELETE; @Autowired @Qualifier("hazelcastServiceTest") private HazelcastService hazelcastServiceTest; private MockConsumer mockConsumer; - { + @BeforeEach + void setUp() { + mockConsumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); + } + + @Test + public void bankAccountNew() throws InterruptedException { + //arrange + BankAccountNewRequest bankAccountNewRequest = new BankAccountNewRequest(); bankAccountNewRequest.setBankName("ooo tinkoff"); bankAccountNewRequest.setBankIdentificationCode("99999"); bankAccountNewRequest.setCorrespondentAccount("9294189285498598598"); @@ -57,24 +66,17 @@ public class BankAccountServiceTest { bankAccountNewRequest.setTaxRegistrationReasonCode("886886"); bankAccountNewRequest.setAccount("123456789123"); - baseRequest.setRequestPayload(bankAccountNewRequest); - baseRequest.setId(0L); - baseRequest.setActionType(ActionType.NEW); + BaseRequest baseNewRequest = new BaseRequest<>(); + baseNewRequest.setRequestPayload(bankAccountNewRequest); + baseNewRequest.setId(0L); + baseNewRequest.setActionType(ActionType.NEW); + String jsonBaseNewRequest; + ObjectMapper objectMapper = new ObjectMapper(); try { - jsonBaseRequest = objectMapper.writeValueAsString(baseRequest); + jsonBaseNewRequest = objectMapper.writeValueAsString(baseNewRequest); } catch (JsonProcessingException e) { throw new RuntimeException(e); } - } - - @BeforeEach - void setUp() { - mockConsumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); - } - - @Test - public void bankAccountNew() throws InterruptedException { - //arrange BankAccount predictableResult = new BankAccount(); predictableResult.setBankName("ooo tinkoff"); predictableResult.setBankIdentificationCode("99999"); @@ -88,13 +90,13 @@ public class BankAccountServiceTest { predictableResult.setId(0L); //KAFKA mockConsumer.schedulePollTask(() -> { - mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC, PARTITION))); - mockConsumer.addRecord(new ConsumerRecord<>(TOPIC, PARTITION, 0, "key", jsonBaseRequest)); + mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC_ACCOUNT_NEW, PARTITION))); + mockConsumer.addRecord(new ConsumerRecord<>(TOPIC_ACCOUNT_NEW, PARTITION, 0, "key", jsonBaseNewRequest)); }); - + HashMap startOffsets = new HashMap<>(); - TopicPartition tp = new TopicPartition(TOPIC, PARTITION); + TopicPartition tp = new TopicPartition(TOPIC_ACCOUNT_NEW, PARTITION); startOffsets.put(tp, 0L); mockConsumer.updateBeginningOffsets(startOffsets); @@ -110,7 +112,177 @@ public class BankAccountServiceTest { //ASSERT IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_BankAccount); BankAccount result = iMap.get(0L); + iMap.clear(); BANK_ACCOUNT_MATCHER.assertMatch(result, predictableResult); } + + @Test + void bankAccountUpdate() throws InterruptedException { + //arrange + BankAccountNewRequest bankAccountNewRequest = new BankAccountNewRequest(); + bankAccountNewRequest.setBankName("ooo tinkoff"); + bankAccountNewRequest.setBankIdentificationCode("99999"); + bankAccountNewRequest.setCorrespondentAccount("9294189285498598598"); + bankAccountNewRequest.setCorrespondentAccountName("BIK OF TINKOFF"); + bankAccountNewRequest.setCurrency("RUB"); + bankAccountNewRequest.setDestination("OOO ROGA I KOPITA"); + bankAccountNewRequest.setTaxpayerIdentificationNumber("848484848484"); + bankAccountNewRequest.setTaxRegistrationReasonCode("886886"); + bankAccountNewRequest.setAccount("123456789123"); + + BaseRequest baseNewRequest = new BaseRequest<>(); + baseNewRequest.setRequestPayload(bankAccountNewRequest); + baseNewRequest.setId(0L); + baseNewRequest.setActionType(ActionType.NEW); + String jsonBaseNewRequest; + ObjectMapper objectMapper = new ObjectMapper(); + try { + jsonBaseNewRequest = objectMapper.writeValueAsString(baseNewRequest); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + BankAccountUpdateRequest bankAccountUpdateRequest = new BankAccountUpdateRequest(); + bankAccountUpdateRequest.setId(0L); + bankAccountUpdateRequest.setBankName("NEW BUNK NAME"); + bankAccountUpdateRequest.setBankIdentificationCode("88888"); + bankAccountUpdateRequest.setCorrespondentAccount("894984646541316"); + bankAccountUpdateRequest.setCorrespondentAccountName("BIK OF NEW BUNK"); + bankAccountUpdateRequest.setCurrency("EU"); + bankAccountUpdateRequest.setDestination("OOO NEW BUNK"); + bankAccountUpdateRequest.setTaxpayerIdentificationNumber("65468461321"); + bankAccountUpdateRequest.setTaxRegistrationReasonCode("532137"); + bankAccountUpdateRequest.setAccount("326984656514"); + + BaseRequest baseUpdateRequest = new BaseRequest<>(); + baseUpdateRequest.setRequestPayload(bankAccountUpdateRequest); + baseUpdateRequest.setId(0L); + baseUpdateRequest.setActionType(ActionType.UPDATE); + String jsonBaseUpdateRequest; + try { + jsonBaseUpdateRequest = objectMapper.writeValueAsString(baseUpdateRequest); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + BankAccount predictableUpdateResult = new BankAccount(); + predictableUpdateResult.setBankName("NEW BUNK NAME"); + predictableUpdateResult.setBankIdentificationCode("88888"); + predictableUpdateResult.setCorrespondentAccount("894984646541316"); + predictableUpdateResult.setCorrespondentAccountName("BIK OF NEW BUNK"); + predictableUpdateResult.setCurrency("EU"); + predictableUpdateResult.setDestination("OOO NEW BUNK"); + predictableUpdateResult.setTaxpayerIdentificationNumber("65468461321"); + predictableUpdateResult.setTaxRegistrationReasonCode("532137"); + predictableUpdateResult.setAccount("326984656514"); + predictableUpdateResult.setId(0L); + + //KAFKA + mockConsumer.schedulePollTask(() -> { + mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC_ACCOUNT_NEW, PARTITION))); + mockConsumer.addRecord(new ConsumerRecord<>(TOPIC_ACCOUNT_NEW, PARTITION, 0, "key", jsonBaseNewRequest)); + }); + HashMap startOffsets = new HashMap<>(); + TopicPartition tp = new TopicPartition(TOPIC_ACCOUNT_NEW, PARTITION); + startOffsets.put(tp, 0L); + mockConsumer.updateBeginningOffsets(startOffsets); + + //ACT + //service set up + BankAccountService bankAccountService = new BankAccountService(mockConsumer, hazelcastServiceTest); + Thread.sleep(10000); + //callbacks set up + bankAccountService.afterPropertiesSet(); + Thread.sleep(10000); + + //KAFKA + mockConsumer.schedulePollTask(() -> { + mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC_ACCOUNT_UPDATE, PARTITION))); + mockConsumer.addRecord(new ConsumerRecord<>(TOPIC_ACCOUNT_UPDATE, PARTITION, 0, "key", jsonBaseUpdateRequest)); + }); + HashMap startOffsetsUpdating = new HashMap<>(); + TopicPartition tpUpdating = new TopicPartition(TOPIC_ACCOUNT_UPDATE, PARTITION); + startOffsetsUpdating.put(tpUpdating, 0L); + mockConsumer.updateBeginningOffsets(startOffsetsUpdating); + + //ASSERT + Thread.sleep(10000); + IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_BankAccount); + BankAccount resultUpdating = iMap.get(0L); + iMap.clear(); + BANK_ACCOUNT_MATCHER.assertMatch(resultUpdating, predictableUpdateResult); + } + + @Test + void bankAccountDelete() throws InterruptedException { + //arrange + BankAccountNewRequest bankAccountNewRequest = new BankAccountNewRequest(); + bankAccountNewRequest.setBankName("ooo tinkoff"); + bankAccountNewRequest.setBankIdentificationCode("99999"); + bankAccountNewRequest.setCorrespondentAccount("9294189285498598598"); + bankAccountNewRequest.setCorrespondentAccountName("BIK OF TINKOFF"); + bankAccountNewRequest.setCurrency("RUB"); + bankAccountNewRequest.setDestination("OOO ROGA I KOPITA"); + bankAccountNewRequest.setTaxpayerIdentificationNumber("848484848484"); + bankAccountNewRequest.setTaxRegistrationReasonCode("886886"); + bankAccountNewRequest.setAccount("123456789123"); + + BaseRequest baseNewRequest = new BaseRequest<>(); + baseNewRequest.setRequestPayload(bankAccountNewRequest); + baseNewRequest.setId(0L); + baseNewRequest.setActionType(ActionType.NEW); + String jsonBaseNewRequest; + ObjectMapper objectMapper = new ObjectMapper(); + try { + jsonBaseNewRequest = objectMapper.writeValueAsString(baseNewRequest); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + + CommonDeleteRequest commonDeleteRequest = new CommonDeleteRequest(); + commonDeleteRequest.setId(0L); + BaseRequest baseDeleteRequest = new BaseRequest<>(); + baseDeleteRequest.setRequestPayload(commonDeleteRequest); + baseDeleteRequest.setId(0L); + baseDeleteRequest.setActionType(ActionType.DELETE); + String jsonDeleteNewRequest; + try { + jsonDeleteNewRequest = objectMapper.writeValueAsString(baseDeleteRequest); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + //KAFKA + mockConsumer.schedulePollTask(() -> { + mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC_ACCOUNT_NEW, PARTITION))); + mockConsumer.addRecord(new ConsumerRecord<>(TOPIC_ACCOUNT_NEW, PARTITION, 0, "key", jsonBaseNewRequest)); + }); + + + HashMap startOffsets = new HashMap<>(); + TopicPartition tp = new TopicPartition(TOPIC_ACCOUNT_NEW, PARTITION); + startOffsets.put(tp, 0L); + mockConsumer.updateBeginningOffsets(startOffsets); + + //ACT + //service set up + BankAccountService bankAccountService = new BankAccountService(mockConsumer, hazelcastServiceTest); + Thread.sleep(10000); + //callbacks set up + bankAccountService.afterPropertiesSet(); + Thread.sleep(10000); + + //KAFKA + mockConsumer.schedulePollTask(() -> { + mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC_ACCOUNT_DELETE, PARTITION))); + mockConsumer.addRecord(new ConsumerRecord<>(TOPIC_ACCOUNT_DELETE, PARTITION, 0, "key", jsonDeleteNewRequest)); + }); + HashMap startOffsetsDeleting = new HashMap<>(); + TopicPartition tpDeleting = new TopicPartition(TOPIC_ACCOUNT_DELETE, PARTITION); + startOffsetsDeleting.put(tpDeleting, 0L); + mockConsumer.updateBeginningOffsets(startOffsetsDeleting); + + //ASSERT + Thread.sleep(10000); + IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_BankAccount); + Assertions.assertEquals(0, iMap.size()); + } } \ No newline at end of file From ed20610c4f829871e06bde27781cc96c9fbb36f7 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Thu, 15 Sep 2022 18:41:02 +0300 Subject: [PATCH 13/33] http://git.mfd.msk/dashboard/issues?assignee_id=30 --- tree test done --- .../account/service/BankAccountService.java | 2 + .../HazelcastInstanceTestConfiguration.java | 29 -------------- .../HazelcastServiceTestConfiguration.java | 1 - .../service/BankAccountServiceTest.java | 40 ++++++++++++------- 4 files changed, 27 insertions(+), 45 deletions(-) delete mode 100644 clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastInstanceTestConfiguration.java diff --git a/clearing-parent/account-service/src/main/java/ru/spcex/clearing/account/service/BankAccountService.java b/clearing-parent/account-service/src/main/java/ru/spcex/clearing/account/service/BankAccountService.java index 11e168726..37e39d377 100644 --- a/clearing-parent/account-service/src/main/java/ru/spcex/clearing/account/service/BankAccountService.java +++ b/clearing-parent/account-service/src/main/java/ru/spcex/clearing/account/service/BankAccountService.java @@ -82,7 +82,9 @@ public class BankAccountService extends QueueConsumer implements InitializingBea CommonDeleteRequest req = userRequest.getRequestPayload(); log.debug("CommonDeleteRequest received id = {}", req.getId()); BankAccount bankAccount = bankAccountMap.getSingleObjectByID(req.getId()); + bankAccountMap.delete(bankAccount); + log.debug("successfully delete, existing bankAccount with id {}", bankAccount.getId()); } } diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastInstanceTestConfiguration.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastInstanceTestConfiguration.java deleted file mode 100644 index 410d8392d..000000000 --- a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastInstanceTestConfiguration.java +++ /dev/null @@ -1,29 +0,0 @@ -package ru.spcex.clearing.account.config; - -import com.hazelcast.config.Config; -import com.hazelcast.config.JoinConfig; -import com.hazelcast.config.MulticastConfig; -import com.hazelcast.config.NetworkConfig; -import com.hazelcast.core.Hazelcast; -import com.hazelcast.core.HazelcastInstance; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import java.util.Random; - -@Configuration -public class HazelcastInstanceTestConfiguration { - - @Bean(name = "hazelcastInstance") - public HazelcastInstance hazelcastInstance() { - Config cfg = new Config(); - cfg.setInstanceName("unittest_test_" + new Random().nextInt()); - NetworkConfig networkConfig = new NetworkConfig(); - JoinConfig joinConfig = new JoinConfig(); - joinConfig.setMulticastConfig(new MulticastConfig().setEnabled(false)); - networkConfig.setJoin(joinConfig); - cfg.setNetworkConfig(networkConfig); - return Hazelcast.newHazelcastInstance(cfg); - } - -} diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastServiceTestConfiguration.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastServiceTestConfiguration.java index 3a64d5190..60f94af16 100644 --- a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastServiceTestConfiguration.java +++ b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/config/HazelcastServiceTestConfiguration.java @@ -63,7 +63,6 @@ public class HazelcastServiceTestConfiguration { params.setClusterMembers("127.0.0.1"); params.setInstanceName("hzTestClient" + new Random().nextInt()); params.setNearCacheConfig(new NearCacheConfig()); - return params; } } diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java index 3763ec977..47c48f898 100644 --- a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java +++ b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java @@ -41,6 +41,7 @@ public class BankAccountServiceTest { private static final String TOPIC_ACCOUNT_NEW = Consts.DESTINATION_BANK_ACCOUNT_NEW; private static final String TOPIC_ACCOUNT_UPDATE = Consts.DESTINATION_BANK_ACCOUNT_UPDATE; private static final String TOPIC_ACCOUNT_DELETE = Consts.DESTINATION_BANK_ACCOUNT_DELETE; + private static Long currentId = 0L; @Autowired @Qualifier("hazelcastServiceTest") @@ -68,7 +69,7 @@ public class BankAccountServiceTest { BaseRequest baseNewRequest = new BaseRequest<>(); baseNewRequest.setRequestPayload(bankAccountNewRequest); - baseNewRequest.setId(0L); + baseNewRequest.setId(currentId); baseNewRequest.setActionType(ActionType.NEW); String jsonBaseNewRequest; ObjectMapper objectMapper = new ObjectMapper(); @@ -87,7 +88,7 @@ public class BankAccountServiceTest { predictableResult.setTaxpayerIdentificationNumber("848484848484"); predictableResult.setTaxRegistrationReasonCode("886886"); predictableResult.setAccount("123456789123"); - predictableResult.setId(0L); + predictableResult.setId(currentId); //KAFKA mockConsumer.schedulePollTask(() -> { mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC_ACCOUNT_NEW, PARTITION))); @@ -111,10 +112,13 @@ public class BankAccountServiceTest { //ASSERT IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_BankAccount); - BankAccount result = iMap.get(0L); - iMap.clear(); + BankAccount result = iMap.get(currentId); BANK_ACCOUNT_MATCHER.assertMatch(result, predictableResult); + + //reset hazelcastService for next test + iMap.clear(); + currentId++; } @Test @@ -133,7 +137,7 @@ public class BankAccountServiceTest { BaseRequest baseNewRequest = new BaseRequest<>(); baseNewRequest.setRequestPayload(bankAccountNewRequest); - baseNewRequest.setId(0L); + baseNewRequest.setId(currentId); baseNewRequest.setActionType(ActionType.NEW); String jsonBaseNewRequest; ObjectMapper objectMapper = new ObjectMapper(); @@ -143,7 +147,7 @@ public class BankAccountServiceTest { throw new RuntimeException(e); } BankAccountUpdateRequest bankAccountUpdateRequest = new BankAccountUpdateRequest(); - bankAccountUpdateRequest.setId(0L); + bankAccountUpdateRequest.setId(currentId); bankAccountUpdateRequest.setBankName("NEW BUNK NAME"); bankAccountUpdateRequest.setBankIdentificationCode("88888"); bankAccountUpdateRequest.setCorrespondentAccount("894984646541316"); @@ -156,7 +160,7 @@ public class BankAccountServiceTest { BaseRequest baseUpdateRequest = new BaseRequest<>(); baseUpdateRequest.setRequestPayload(bankAccountUpdateRequest); - baseUpdateRequest.setId(0L); + baseUpdateRequest.setId(currentId); baseUpdateRequest.setActionType(ActionType.UPDATE); String jsonBaseUpdateRequest; try { @@ -174,7 +178,7 @@ public class BankAccountServiceTest { predictableUpdateResult.setTaxpayerIdentificationNumber("65468461321"); predictableUpdateResult.setTaxRegistrationReasonCode("532137"); predictableUpdateResult.setAccount("326984656514"); - predictableUpdateResult.setId(0L); + predictableUpdateResult.setId(currentId); //KAFKA mockConsumer.schedulePollTask(() -> { @@ -207,9 +211,13 @@ public class BankAccountServiceTest { //ASSERT Thread.sleep(10000); IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_BankAccount); - BankAccount resultUpdating = iMap.get(0L); - iMap.clear(); + BankAccount resultUpdating = iMap.get(currentId); + BANK_ACCOUNT_MATCHER.assertMatch(resultUpdating, predictableUpdateResult); + + //reset hazelcastService for next test + iMap.clear(); + currentId++; } @Test @@ -228,7 +236,7 @@ public class BankAccountServiceTest { BaseRequest baseNewRequest = new BaseRequest<>(); baseNewRequest.setRequestPayload(bankAccountNewRequest); - baseNewRequest.setId(0L); + baseNewRequest.setId(currentId); baseNewRequest.setActionType(ActionType.NEW); String jsonBaseNewRequest; ObjectMapper objectMapper = new ObjectMapper(); @@ -239,10 +247,10 @@ public class BankAccountServiceTest { } CommonDeleteRequest commonDeleteRequest = new CommonDeleteRequest(); - commonDeleteRequest.setId(0L); + commonDeleteRequest.setId(currentId); BaseRequest baseDeleteRequest = new BaseRequest<>(); baseDeleteRequest.setRequestPayload(commonDeleteRequest); - baseDeleteRequest.setId(0L); + baseDeleteRequest.setId(currentId); baseDeleteRequest.setActionType(ActionType.DELETE); String jsonDeleteNewRequest; try { @@ -255,8 +263,6 @@ public class BankAccountServiceTest { mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC_ACCOUNT_NEW, PARTITION))); mockConsumer.addRecord(new ConsumerRecord<>(TOPIC_ACCOUNT_NEW, PARTITION, 0, "key", jsonBaseNewRequest)); }); - - HashMap startOffsets = new HashMap<>(); TopicPartition tp = new TopicPartition(TOPIC_ACCOUNT_NEW, PARTITION); startOffsets.put(tp, 0L); @@ -284,5 +290,9 @@ public class BankAccountServiceTest { Thread.sleep(10000); IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_BankAccount); Assertions.assertEquals(0, iMap.size()); + + //reset hazelcastService for next test + iMap.clear(); + currentId++; } } \ No newline at end of file From 225dc45046223ffa681f48ea22156027df3ba5fe Mon Sep 17 00:00:00 2001 From: psemenkov Date: Fri, 16 Sep 2022 12:41:39 +0300 Subject: [PATCH 14/33] --- ClearingMemberCategoryServiceTest test done --- clearing-parent/company-service/pom.xml | 5 + .../HazelcastServiceTestConfiguration.java | 68 ++++++++ .../ClearingMemberCategoryServiceTest.java | 165 ++++++++++++++++++ .../company/utils/MatcherFactory.java | 38 ++++ 4 files changed, 276 insertions(+) create mode 100644 clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/config/HazelcastServiceTestConfiguration.java create mode 100644 clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java create mode 100644 clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/utils/MatcherFactory.java diff --git a/clearing-parent/company-service/pom.xml b/clearing-parent/company-service/pom.xml index cd323c846..0e041276a 100644 --- a/clearing-parent/company-service/pom.xml +++ b/clearing-parent/company-service/pom.xml @@ -36,6 +36,11 @@ com.fasterxml.jackson.core jackson-databind + + org.springframework.boot + spring-boot-starter-test + test + diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/config/HazelcastServiceTestConfiguration.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/config/HazelcastServiceTestConfiguration.java new file mode 100644 index 000000000..0c7ca4069 --- /dev/null +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/config/HazelcastServiceTestConfiguration.java @@ -0,0 +1,68 @@ +package ru.spcex.clearing.company.config; + +import com.hazelcast.config.*; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import ru.spcex.platform.imdg.iml.hazelcast.config.HazelcastClientParams; +import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService; +import ru.spcex.platform.imdg.iml.hazelcast.util.HazelcastHelper; + +import java.util.List; +import java.util.Random; + +@Configuration +public class HazelcastServiceTestConfiguration { + private HazelcastInstance hazelcastInstance; + + private static ThreadPoolTaskExecutor createThreadPoolTaskExecutor(int maxPoolSz, boolean waitForCompletion) { + ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor(); + if (maxPoolSz > 2) { + pool.setKeepAliveSeconds(60); + pool.setAllowCoreThreadTimeOut(true); + } + pool.setCorePoolSize(maxPoolSz); + pool.setWaitForTasksToCompleteOnShutdown(waitForCompletion); + return pool; + } + + @Bean(name = "hazelcastServiceTest") + public HazelcastService hazelcastService(@Qualifier("taskExecutorHazelcastClientInitializer") ThreadPoolTaskExecutor taskExecutorHazelcastClientInitializer, @Qualifier("taskExecutorIdGeneratorAwaiter") ThreadPoolTaskExecutor taskExecutorIdGeneratorAwaiter, HazelcastClientParams params) { + Config cfg = new Config(); + cfg.setInstanceName("localhost"); + + NetworkConfig networkConfig = new NetworkConfig(); + JoinConfig joinConfig = new JoinConfig(); + joinConfig.setMulticastConfig(new MulticastConfig().setEnabled(false)); + joinConfig.setTcpIpConfig(new TcpIpConfig().setEnabled(true).setMembers(List.of("127.0.0.1"))); + networkConfig.setJoin(joinConfig); + cfg.setNetworkConfig(networkConfig); + hazelcastInstance = Hazelcast.newHazelcastInstance(cfg); + HazelcastHelper.otcSystem_setStorageState(true, hazelcastInstance); + return new HazelcastService(taskExecutorHazelcastClientInitializer, taskExecutorIdGeneratorAwaiter, params); + } + + @Bean(name = "taskExecutorHazelcastClientInitializer") + public ThreadPoolTaskExecutor taskExecutorHazelcastClientInitializer() { + return createThreadPoolTaskExecutor(1, true); + } + + @Bean(name = "taskExecutorIdGeneratorAwaiter") + public ThreadPoolTaskExecutor taskExecutorIdGeneratorAwaiter() { + return createThreadPoolTaskExecutor(1, false); + } + + @Bean(name = "hazelcastClientParams") + public HazelcastClientParams getHazelcastClientParams() { + HazelcastClientParams params = new HazelcastClientParams(); + params.setLogin("dev"); + params.setPassword("dev-pass"); + params.setClusterMembers("127.0.0.1"); + params.setInstanceName("hzTestClient" + new Random().nextInt()); + params.setNearCacheConfig(new NearCacheConfig()); + return params; + } +} diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java new file mode 100644 index 000000000..ef7083d7a --- /dev/null +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java @@ -0,0 +1,165 @@ +package ru.spcex.clearing.company.service; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.hazelcast.core.IMap; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.MockConsumer; +import org.apache.kafka.clients.consumer.OffsetResetStrategy; +import org.apache.kafka.common.TopicPartition; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +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; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import ru.clearing.classes.statics.data.generated.ClearingMemberCategory; +import ru.spcex.clearing.company.config.HazelcastServiceTestConfiguration; +import ru.spcex.clearing.company.utils.MatcherFactory.Matcher; +import ru.spcex.clearing.imdg.IMDGDistributedNames; +import ru.spcex.clearing.platform.messaging.domain.ActionType; +import ru.spcex.clearing.platform.messaging.domain.BaseRequest; +import ru.spcex.clearing.platform.messaging.domain.Consts; +import ru.spcex.clearing.platform.messaging.domain.cud.common.CommonDeleteRequest; +import ru.spcex.clearing.platform.messaging.domain.cud.company.ClearingMemberCategoryUpdateRequest; +import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService; + +import java.util.Collections; +import java.util.HashMap; + +import static ru.spcex.clearing.company.utils.MatcherFactory.usingIgnoringFieldsComparator; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { + HazelcastServiceTestConfiguration.class}) +class ClearingMemberCategoryServiceTest { + + public static final Matcher MEMBER_CATEGORY_MATCHER = usingIgnoringFieldsComparator("id"); + private static final int PARTITION = 0; + private static final String TOPIC_MEMBER_CATEGORY_UPDATE = Consts.DESTINATION_CLEARING_MEMBER_CATEGORY_UPDATE; + private static final String TOPIC_MEMBER_CATEGORY_DELETE = Consts.DESTINATION_CLEARING_MEMBER_CATEGORY_DELETE; + private static Long currentId = 0L; + + @Autowired + @Qualifier("hazelcastServiceTest") + private HazelcastService hazelcastServiceTest; + private MockConsumer mockConsumer; + + @BeforeEach + void setUp() { + mockConsumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); + } + + @Test + void clearingMemberCategoryUpdate() throws InterruptedException { + //ARRANGE + ClearingMemberCategory existsСlearingMemberCategory = new ClearingMemberCategory(); + existsСlearingMemberCategory.setId(currentId); + existsСlearingMemberCategory.setClearingMemberCategory("0000"); + + ClearingMemberCategoryUpdateRequest memberCategoryUpdateRequest = new ClearingMemberCategoryUpdateRequest(); + memberCategoryUpdateRequest.setId(currentId); + memberCategoryUpdateRequest.setClearingMemberCategory("1234"); + BaseRequest baseUpdateRequest = new BaseRequest<>(); + baseUpdateRequest.setRequestPayload(memberCategoryUpdateRequest); + baseUpdateRequest.setId(currentId); + baseUpdateRequest.setActionType(ActionType.NEW); + String jsonBaseForUpdatingRequest; + ObjectMapper objectMapper = new ObjectMapper(); + try { + jsonBaseForUpdatingRequest = objectMapper.writeValueAsString(baseUpdateRequest); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + + ClearingMemberCategory predictableClearingMemberCategory = new ClearingMemberCategory(); + predictableClearingMemberCategory.setId(currentId); + predictableClearingMemberCategory.setClearingMemberCategory("1234"); + + //ACT + //service set up + ClearingMemberCategoryService clearingMemberCategoryService = new ClearingMemberCategoryService(mockConsumer, hazelcastServiceTest); + Thread.sleep(10000); + //callbacks set up + clearingMemberCategoryService.afterPropertiesSet(); + Thread.sleep(10000); + + IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_ClearingMemberCategory); + iMap.put(currentId, existsСlearingMemberCategory); + + //KAFKA + mockConsumer.schedulePollTask(() -> { + mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC_MEMBER_CATEGORY_UPDATE, PARTITION))); + mockConsumer.addRecord(new ConsumerRecord<>(TOPIC_MEMBER_CATEGORY_UPDATE, PARTITION, 0, "key", jsonBaseForUpdatingRequest)); + }); + HashMap startOffsetsUpdating = new HashMap<>(); + TopicPartition tpUpdating = new TopicPartition(TOPIC_MEMBER_CATEGORY_UPDATE, PARTITION); + startOffsetsUpdating.put(tpUpdating, 0L); + mockConsumer.updateBeginningOffsets(startOffsetsUpdating); + + //ASSERT + Thread.sleep(10000); + ClearingMemberCategory resultUpdating = iMap.get(currentId); + MEMBER_CATEGORY_MATCHER.assertMatch(resultUpdating, predictableClearingMemberCategory); + // Assertions.assertEquals(0, iMap.size()); + + //preparing hazelcastImdgProvider for next test + iMap.clear(); + currentId++; + } + + @Test + void clearingMemberCategoryDelete() throws InterruptedException { + //ARRANGE + ClearingMemberCategory existsСlearingMemberCategory = new ClearingMemberCategory(); + existsСlearingMemberCategory.setId(currentId); + existsСlearingMemberCategory.setClearingMemberCategory("0000"); + + CommonDeleteRequest memberCategoryDeleteRequest = new CommonDeleteRequest(); + memberCategoryDeleteRequest.setId(currentId); + + BaseRequest baseDeleteRequest = new BaseRequest<>(); + baseDeleteRequest.setRequestPayload(memberCategoryDeleteRequest); + baseDeleteRequest.setId(currentId); + baseDeleteRequest.setActionType(ActionType.NEW); + String jsonBaseForDeleteRequest; + ObjectMapper objectMapper = new ObjectMapper(); + try { + jsonBaseForDeleteRequest = objectMapper.writeValueAsString(baseDeleteRequest); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + + //ACT + //service set up + ClearingMemberCategoryService clearingMemberCategoryService = new ClearingMemberCategoryService(mockConsumer, hazelcastServiceTest); + Thread.sleep(10000); + //callbacks set up + clearingMemberCategoryService.afterPropertiesSet(); + Thread.sleep(10000); + + IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_ClearingMemberCategory); + iMap.put(currentId, existsСlearingMemberCategory); + + //KAFKA + mockConsumer.schedulePollTask(() -> { + mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC_MEMBER_CATEGORY_DELETE, PARTITION))); + mockConsumer.addRecord(new ConsumerRecord<>(TOPIC_MEMBER_CATEGORY_DELETE, PARTITION, 0, "key", jsonBaseForDeleteRequest)); + }); + HashMap startOffsetsUpdating = new HashMap<>(); + TopicPartition tpDeleting = new TopicPartition(TOPIC_MEMBER_CATEGORY_DELETE, PARTITION); + startOffsetsUpdating.put(tpDeleting, 0L); + mockConsumer.updateBeginningOffsets(startOffsetsUpdating); + + //ASSERT + Thread.sleep(10000); + ClearingMemberCategory resultUpdating = iMap.get(currentId); + Assertions.assertEquals(0, iMap.size()); + + //preparing hazelcastImdgProvider for next test + iMap.clear(); + currentId++; + } +} \ No newline at end of file diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/utils/MatcherFactory.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/utils/MatcherFactory.java new file mode 100644 index 000000000..e850b89ef --- /dev/null +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/utils/MatcherFactory.java @@ -0,0 +1,38 @@ +package ru.spcex.clearing.company.utils; + +import java.util.Arrays; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Factory for creating test matchers. + *

+ * Comparing actual and expected objects via AssertJ + */ +public class MatcherFactory { + + public static Matcher usingIgnoringFieldsComparator(String... fieldsToIgnore) { + return new Matcher<>(fieldsToIgnore); + } + + public static class Matcher { + private final String[] fieldsToIgnore; + + private Matcher(String... fieldsToIgnore) { + this.fieldsToIgnore = fieldsToIgnore; + } + + public void assertMatch(T actual, T expected) { + assertThat(actual).usingRecursiveComparison().ignoringFields(fieldsToIgnore).isEqualTo(expected); + } + + @SafeVarargs + public final void assertMatch(Iterable actual, T... expected) { + assertMatch(actual, Arrays.asList(expected)); + } + + public void assertMatch(Iterable actual, Iterable expected) { + assertThat(actual).usingRecursiveFieldByFieldElementComparatorIgnoringFields(fieldsToIgnore).isEqualTo(expected); + } + } +} From b0a28cfb6c6bad764aa060c591a8badc5cb81cf3 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Fri, 16 Sep 2022 14:57:26 +0300 Subject: [PATCH 15/33] --- CompanyInfoServiceTest test done --- .../ClearingMemberCategoryServiceTest.java | 7 +- .../service/CompanyInfoServiceTest.java | 139 ++++++++++++++++++ 2 files changed, 142 insertions(+), 4 deletions(-) create mode 100644 clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java index ef7083d7a..f1ba03fc4 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java @@ -36,7 +36,7 @@ import static ru.spcex.clearing.company.utils.MatcherFactory.usingIgnoringFields HazelcastServiceTestConfiguration.class}) class ClearingMemberCategoryServiceTest { - public static final Matcher MEMBER_CATEGORY_MATCHER = usingIgnoringFieldsComparator("id"); + public static final Matcher MEMBER_CATEGORY_MATCHER = usingIgnoringFieldsComparator(); private static final int PARTITION = 0; private static final String TOPIC_MEMBER_CATEGORY_UPDATE = Consts.DESTINATION_CLEARING_MEMBER_CATEGORY_UPDATE; private static final String TOPIC_MEMBER_CATEGORY_DELETE = Consts.DESTINATION_CLEARING_MEMBER_CATEGORY_DELETE; @@ -65,7 +65,7 @@ class ClearingMemberCategoryServiceTest { BaseRequest baseUpdateRequest = new BaseRequest<>(); baseUpdateRequest.setRequestPayload(memberCategoryUpdateRequest); baseUpdateRequest.setId(currentId); - baseUpdateRequest.setActionType(ActionType.NEW); + baseUpdateRequest.setActionType(ActionType.UPDATE); String jsonBaseForUpdatingRequest; ObjectMapper objectMapper = new ObjectMapper(); try { @@ -103,7 +103,6 @@ class ClearingMemberCategoryServiceTest { Thread.sleep(10000); ClearingMemberCategory resultUpdating = iMap.get(currentId); MEMBER_CATEGORY_MATCHER.assertMatch(resultUpdating, predictableClearingMemberCategory); - // Assertions.assertEquals(0, iMap.size()); //preparing hazelcastImdgProvider for next test iMap.clear(); @@ -123,7 +122,7 @@ class ClearingMemberCategoryServiceTest { BaseRequest baseDeleteRequest = new BaseRequest<>(); baseDeleteRequest.setRequestPayload(memberCategoryDeleteRequest); baseDeleteRequest.setId(currentId); - baseDeleteRequest.setActionType(ActionType.NEW); + baseDeleteRequest.setActionType(ActionType.DELETE); String jsonBaseForDeleteRequest; ObjectMapper objectMapper = new ObjectMapper(); try { diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java new file mode 100644 index 000000000..076085986 --- /dev/null +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java @@ -0,0 +1,139 @@ +package ru.spcex.clearing.company.service; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.hazelcast.core.IMap; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.MockConsumer; +import org.apache.kafka.clients.consumer.OffsetResetStrategy; +import org.apache.kafka.common.TopicPartition; +import org.junit.jupiter.api.BeforeEach; +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; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import ru.clearing.classes.statics.data.profile.CompanyInfo; +import ru.spcex.clearing.company.config.HazelcastServiceTestConfiguration; +import ru.spcex.clearing.company.utils.MatcherFactory; +import ru.spcex.clearing.imdg.IMDGDistributedNames; +import ru.spcex.clearing.platform.messaging.domain.ActionType; +import ru.spcex.clearing.platform.messaging.domain.BaseRequest; +import ru.spcex.clearing.platform.messaging.domain.Consts; +import ru.spcex.clearing.platform.messaging.domain.cud.company.CompanyInfoUpdateRequest; +import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService; + +import java.util.Collections; +import java.util.HashMap; + +import static ru.spcex.clearing.company.utils.MatcherFactory.usingIgnoringFieldsComparator; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { + HazelcastServiceTestConfiguration.class}) +class CompanyInfoServiceTest { + + public static final MatcherFactory.Matcher COMPANY_INFO_MATCHER = usingIgnoringFieldsComparator(); + private static final int PARTITION = 0; + private static final String TOPIC_COMPANY_INFO_UPDATE = Consts.DESTINATION_COMPANY_INFO_UPDATE; + private static Long currentId = 0L; + + @Autowired + @Qualifier("hazelcastServiceTest") + private HazelcastService hazelcastServiceTest; + private MockConsumer mockConsumer; + + @BeforeEach + void setUp() { + mockConsumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); + } + + @Test + void companyInfoUpdate() throws InterruptedException { + //ARRANGE + CompanyInfo existsCompanyInfo = new CompanyInfo(); + existsCompanyInfo.setId(currentId); + existsCompanyInfo.setCorporationSoleType("0000"); + existsCompanyInfo.setCountryCode("0000"); + existsCompanyInfo.setDescription("exists description"); + existsCompanyInfo.setProfessionalSign("0000"); + existsCompanyInfo.setLegalKind("0000"); + existsCompanyInfo.setOrganizationType("0000"); + existsCompanyInfo.setResidence("0000"); + existsCompanyInfo.setShortNameEng("exists shortNameEng"); + existsCompanyInfo.setFullNameEng("exists fullNameEng"); + existsCompanyInfo.setShortName("exists shortName"); + existsCompanyInfo.setFullName("exists fullName"); + + CompanyInfoUpdateRequest companyInfoUpdateRequest = new CompanyInfoUpdateRequest(); + companyInfoUpdateRequest.setId(currentId); + companyInfoUpdateRequest.setCorporationSoleType("1234"); + companyInfoUpdateRequest.setCountryCode("1234"); + companyInfoUpdateRequest.setDescription("updated description"); + companyInfoUpdateRequest.setProfessionalSign("1234"); + companyInfoUpdateRequest.setLegalKind("1234"); + companyInfoUpdateRequest.setOrganizationType("1234"); + companyInfoUpdateRequest.setResidence("1234"); + companyInfoUpdateRequest.setShortNameEng("updated shortNameEng"); + companyInfoUpdateRequest.setFullNameEng("updated fullNameEng"); + companyInfoUpdateRequest.setShortName("updated shortName"); + companyInfoUpdateRequest.setFullName("updated fullName"); + + BaseRequest baseUpdateRequest = new BaseRequest<>(); + baseUpdateRequest.setRequestPayload(companyInfoUpdateRequest); + baseUpdateRequest.setId(currentId); + baseUpdateRequest.setActionType(ActionType.UPDATE); + String jsonBaseForUpdatingRequest; + ObjectMapper objectMapper = new ObjectMapper(); + try { + jsonBaseForUpdatingRequest = objectMapper.writeValueAsString(baseUpdateRequest); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + + CompanyInfo predictableCompanyInfo = new CompanyInfo(); + predictableCompanyInfo.setId(currentId); + predictableCompanyInfo.setCorporationSoleType("1234"); + predictableCompanyInfo.setCountryCode("1234"); + predictableCompanyInfo.setDescription("updated description"); + predictableCompanyInfo.setProfessionalSign("1234"); + predictableCompanyInfo.setLegalKind("1234"); + predictableCompanyInfo.setOrganizationType("1234"); + predictableCompanyInfo.setResidence("1234"); + predictableCompanyInfo.setShortNameEng("updated shortNameEng"); + predictableCompanyInfo.setFullNameEng("updated fullNameEng"); + predictableCompanyInfo.setShortName("updated shortName"); + predictableCompanyInfo.setFullName("updated fullName"); + + //ACT + //service set up + CompanyInfoService clearingMemberCategoryService = new CompanyInfoService(mockConsumer, hazelcastServiceTest); + Thread.sleep(10000); + //callbacks set up + clearingMemberCategoryService.afterPropertiesSet(); + Thread.sleep(10000); + + IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_Company); + iMap.put(currentId, existsCompanyInfo); + + //KAFKA + mockConsumer.schedulePollTask(() -> { + mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC_COMPANY_INFO_UPDATE, PARTITION))); + mockConsumer.addRecord(new ConsumerRecord<>(TOPIC_COMPANY_INFO_UPDATE, PARTITION, 0, "key", jsonBaseForUpdatingRequest)); + }); + HashMap startOffsetsUpdating = new HashMap<>(); + TopicPartition tpUpdating = new TopicPartition(TOPIC_COMPANY_INFO_UPDATE, PARTITION); + startOffsetsUpdating.put(tpUpdating, 0L); + mockConsumer.updateBeginningOffsets(startOffsetsUpdating); + + //ASSERT + Thread.sleep(10000); + CompanyInfo resultUpdating = iMap.get(currentId); + COMPANY_INFO_MATCHER.assertMatch(resultUpdating, predictableCompanyInfo); + + //preparing hazelcastImdgProvider for next test + iMap.clear(); + currentId++; + } +} \ No newline at end of file From a26d8dd27caea85661816ff2e698db82c54eea33 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Fri, 16 Sep 2022 16:07:48 +0300 Subject: [PATCH 16/33] http://git.mfd.msk/mfd/clearing/issues/6 --- CompanyServiceTest test done --- .../ClearingMemberCategoryServiceTest.java | 1 - .../company/service/CompanyServiceTest.java | 104 ++++++++++++++++++ 2 files changed, 104 insertions(+), 1 deletion(-) create mode 100644 clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java index f1ba03fc4..6ef2c71e1 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java @@ -154,7 +154,6 @@ class ClearingMemberCategoryServiceTest { //ASSERT Thread.sleep(10000); - ClearingMemberCategory resultUpdating = iMap.get(currentId); Assertions.assertEquals(0, iMap.size()); //preparing hazelcastImdgProvider for next test diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java new file mode 100644 index 000000000..fd1708dc6 --- /dev/null +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java @@ -0,0 +1,104 @@ +package ru.spcex.clearing.company.service; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.hazelcast.core.IMap; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.MockConsumer; +import org.apache.kafka.clients.consumer.OffsetResetStrategy; +import org.apache.kafka.common.TopicPartition; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +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; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import ru.clearing.classes.statics.data.company.Company; +import ru.clearing.classes.statics.data.generated.ClearingMemberCategory; +import ru.spcex.clearing.company.config.HazelcastServiceTestConfiguration; +import ru.spcex.clearing.company.utils.MatcherFactory; +import ru.spcex.clearing.imdg.IMDGDistributedNames; +import ru.spcex.clearing.platform.messaging.domain.ActionType; +import ru.spcex.clearing.platform.messaging.domain.BaseRequest; +import ru.spcex.clearing.platform.messaging.domain.Consts; +import ru.spcex.clearing.platform.messaging.domain.cud.common.CommonDeleteRequest; +import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService; + +import java.util.Collections; +import java.util.HashMap; + +import static ru.spcex.clearing.company.utils.MatcherFactory.usingIgnoringFieldsComparator; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { + HazelcastServiceTestConfiguration.class}) +class CompanyServiceTest { + + public static final MatcherFactory.Matcher COMPANY_MATCHER = usingIgnoringFieldsComparator(); + private static final int PARTITION = 0; + private static final String TOPIC_COMPANY_DELETE = Consts.DESTINATION_COMPANY_DELETE; + private static Long currentId = 0L; + + @Autowired + @Qualifier("hazelcastServiceTest") + private HazelcastService hazelcastServiceTest; + private MockConsumer mockConsumer; + + @BeforeEach + void setUp() { + mockConsumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); + } + + @Test + void deleteCompany() throws InterruptedException { + //ARRANGE + Company existsCompany = new Company(); + existsCompany.setId(currentId); + + CommonDeleteRequest memberCategoryDeleteRequest = new CommonDeleteRequest(); + memberCategoryDeleteRequest.setId(currentId); + + BaseRequest baseDeleteRequest = new BaseRequest<>(); + baseDeleteRequest.setRequestPayload(memberCategoryDeleteRequest); + baseDeleteRequest.setId(currentId); + baseDeleteRequest.setActionType(ActionType.DELETE); + String jsonBaseForDeleteRequest; + ObjectMapper objectMapper = new ObjectMapper(); + try { + jsonBaseForDeleteRequest = objectMapper.writeValueAsString(baseDeleteRequest); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + + //ACT + //service set up + CompanyService companyService = new CompanyService(mockConsumer, hazelcastServiceTest); + Thread.sleep(10000); + //callbacks set up + companyService.afterPropertiesSet(); + Thread.sleep(10000); + + IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_Company); + iMap.put(currentId, existsCompany); + + //KAFKA + mockConsumer.schedulePollTask(() -> { + mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC_COMPANY_DELETE, PARTITION))); + mockConsumer.addRecord(new ConsumerRecord<>(TOPIC_COMPANY_DELETE, PARTITION, 0, "key", jsonBaseForDeleteRequest)); + }); + HashMap startOffsetsUpdating = new HashMap<>(); + TopicPartition tpDeleting = new TopicPartition(TOPIC_COMPANY_DELETE, PARTITION); + startOffsetsUpdating.put(tpDeleting, 0L); + mockConsumer.updateBeginningOffsets(startOffsetsUpdating); + + //ASSERT + Thread.sleep(10000); + Assertions.assertEquals(0, iMap.size()); + + //preparing hazelcastImdgProvider for next test + iMap.clear(); + currentId++; + } +} \ No newline at end of file From 740a75823fc6fcf568a6a583bc011d1b08af12b6 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Fri, 16 Sep 2022 17:32:45 +0300 Subject: [PATCH 17/33] http://git.mfd.msk/mfd/clearing/issues/6 --- CompanySymbolServiceTest test done --- .../company/service/CompanySymbolService.java | 2 +- .../service/CompanySymbolServiceTest.java | 115 ++++++++++++++++++ .../company/service/ContactServiceTest.java | 108 ++++++++++++++++ 3 files changed, 224 insertions(+), 1 deletion(-) create mode 100644 clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java create mode 100644 clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java diff --git a/clearing-parent/company-service/src/main/java/ru/spcex/clearing/company/service/CompanySymbolService.java b/clearing-parent/company-service/src/main/java/ru/spcex/clearing/company/service/CompanySymbolService.java index 4a6f110af..86c968985 100644 --- a/clearing-parent/company-service/src/main/java/ru/spcex/clearing/company/service/CompanySymbolService.java +++ b/clearing-parent/company-service/src/main/java/ru/spcex/clearing/company/service/CompanySymbolService.java @@ -40,7 +40,7 @@ public class CompanySymbolService extends QueueConsumer implements InitializingB CompanySymbolUpdateRequest req = userRequest.getRequestPayload(); log.debug("CompanySymbolUpdateRequest received"); CompanySymbols companySymbols = companySymbolsMap.getSingleObjectByID(req.getId()); - companySymbols.setCompanySymbol(req.getCompanySymbol()); +// companySymbols.setCompanySymbol(req.getCompanySymbol()); по ТЗ не должен менятся при обновлении companySymbols.setCompanySymbolValue(req.getCompanySymbolValue()); companySymbolsMap.update(companySymbols); diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java new file mode 100644 index 000000000..e74ed25dd --- /dev/null +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java @@ -0,0 +1,115 @@ +package ru.spcex.clearing.company.service; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.hazelcast.core.IMap; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.MockConsumer; +import org.apache.kafka.clients.consumer.OffsetResetStrategy; +import org.apache.kafka.common.TopicPartition; +import org.junit.jupiter.api.BeforeEach; +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; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import ru.clearing.classes.statics.data.company.CompanySymbols; +import ru.spcex.clearing.company.config.HazelcastServiceTestConfiguration; +import ru.spcex.clearing.company.utils.MatcherFactory; +import ru.spcex.clearing.imdg.IMDGDistributedNames; +import ru.spcex.clearing.platform.messaging.domain.ActionType; +import ru.spcex.clearing.platform.messaging.domain.BaseRequest; +import ru.spcex.clearing.platform.messaging.domain.Consts; +import ru.spcex.clearing.platform.messaging.domain.cud.company.CompanySymbolUpdateRequest; +import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService; + +import java.util.Collections; +import java.util.HashMap; + +import static ru.spcex.clearing.company.utils.MatcherFactory.usingIgnoringFieldsComparator; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { + HazelcastServiceTestConfiguration.class}) +class CompanySymbolServiceTest { + + public static final MatcherFactory.Matcher COMPANY_SYMBOL_MATCHER = usingIgnoringFieldsComparator(); + private static final int PARTITION = 0; + private static final String TOPIC_COMPANY_SYMBOL_UPDATE = Consts.DESTINATION_COMPANY_SYMBOL_UPDATE; + private static Long currentId = 0L; + + @Autowired + @Qualifier("hazelcastServiceTest") + private HazelcastService hazelcastServiceTest; + private MockConsumer mockConsumer; + + @BeforeEach + void setUp() { + mockConsumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); + } + + @Test + void companySymbolUpdate() throws InterruptedException { + //ARRANGE + CompanySymbols existsCompanySymbols = new CompanySymbols(); + existsCompanySymbols.setId(currentId); + existsCompanySymbols.setCompanyId(currentId); + existsCompanySymbols.setCompanySymbol("0000"); + existsCompanySymbols.setCompanySymbolValue("exists companySymbolValue"); + + CompanySymbolUpdateRequest companySymbolUpdateRequest = new CompanySymbolUpdateRequest(); + companySymbolUpdateRequest.setId(currentId); + companySymbolUpdateRequest.setCompanyId(currentId); + companySymbolUpdateRequest.setCompanySymbol("1234"); + companySymbolUpdateRequest.setCompanySymbolValue("new companySymbolValue"); + + BaseRequest baseUpdateRequest = new BaseRequest<>(); + baseUpdateRequest.setRequestPayload(companySymbolUpdateRequest); + baseUpdateRequest.setId(currentId); + baseUpdateRequest.setActionType(ActionType.UPDATE); + String jsonBaseForUpdatingRequest; + ObjectMapper objectMapper = new ObjectMapper(); + try { + jsonBaseForUpdatingRequest = objectMapper.writeValueAsString(baseUpdateRequest); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + + CompanySymbols predictableCompanySymbols = new CompanySymbols(); + predictableCompanySymbols.setId(currentId); + predictableCompanySymbols.setCompanyId(currentId); + predictableCompanySymbols.setCompanySymbol("0000"); + predictableCompanySymbols.setCompanySymbolValue("new companySymbolValue"); + + //ACT + //service set up + CompanySymbolService companySymbolService = new CompanySymbolService(mockConsumer, hazelcastServiceTest); + Thread.sleep(10000); + //callbacks set up + companySymbolService.afterPropertiesSet(); + Thread.sleep(10000); + + IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_CompanySymbols); + iMap.put(currentId, existsCompanySymbols); + + //KAFKA + mockConsumer.schedulePollTask(() -> { + mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC_COMPANY_SYMBOL_UPDATE, PARTITION))); + mockConsumer.addRecord(new ConsumerRecord<>(TOPIC_COMPANY_SYMBOL_UPDATE, PARTITION, 0, "key", jsonBaseForUpdatingRequest)); + }); + HashMap startOffsetsUpdating = new HashMap<>(); + TopicPartition tpUpdating = new TopicPartition(TOPIC_COMPANY_SYMBOL_UPDATE, PARTITION); + startOffsetsUpdating.put(tpUpdating, 0L); + mockConsumer.updateBeginningOffsets(startOffsetsUpdating); + + //ASSERT + Thread.sleep(10000); + CompanySymbols resultUpdating = iMap.get(currentId); + COMPANY_SYMBOL_MATCHER.assertMatch(resultUpdating, predictableCompanySymbols); + + //preparing hazelcastImdgProvider for next test + iMap.clear(); + currentId++; + } +} \ No newline at end of file diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java new file mode 100644 index 000000000..6c0f2d770 --- /dev/null +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java @@ -0,0 +1,108 @@ +package ru.spcex.clearing.company.service; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.hazelcast.core.IMap; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.MockConsumer; +import org.apache.kafka.clients.consumer.OffsetResetStrategy; +import org.apache.kafka.common.TopicPartition; +import org.junit.jupiter.api.BeforeEach; +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; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import ru.clearing.classes.statics.data.generated.ClearingMemberCategory; +import ru.spcex.clearing.company.config.HazelcastServiceTestConfiguration; +import ru.spcex.clearing.company.utils.MatcherFactory; +import ru.spcex.clearing.imdg.IMDGDistributedNames; +import ru.spcex.clearing.platform.messaging.domain.ActionType; +import ru.spcex.clearing.platform.messaging.domain.BaseRequest; +import ru.spcex.clearing.platform.messaging.domain.Consts; +import ru.spcex.clearing.platform.messaging.domain.cud.company.ClearingMemberCategoryUpdateRequest; +import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService; + +import java.util.Collections; +import java.util.HashMap; + +import static ru.spcex.clearing.company.utils.MatcherFactory.usingIgnoringFieldsComparator; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { + HazelcastServiceTestConfiguration.class}) +class ContactServiceTest { + + public static final MatcherFactory.Matcher CONTACT_MATCHER = usingIgnoringFieldsComparator(); + private static final int PARTITION = 0; + private static final String TOPIC_CONTACT_UPDATE = Consts.DESTINATION_CONTACT_UPDATE; + private static Long currentId = 0L; + + @Autowired + @Qualifier("hazelcastServiceTest") + private HazelcastService hazelcastServiceTest; + private MockConsumer mockConsumer; + + @BeforeEach + void setUp() { + mockConsumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); + } + + @Test + void contactUpdate() throws InterruptedException { + //ARRANGE + ClearingMemberCategory existsСlearingMemberCategory = new ClearingMemberCategory(); + existsСlearingMemberCategory.setId(currentId); + existsСlearingMemberCategory.setClearingMemberCategory("0000"); + + ClearingMemberCategoryUpdateRequest memberCategoryUpdateRequest = new ClearingMemberCategoryUpdateRequest(); + memberCategoryUpdateRequest.setId(currentId); + memberCategoryUpdateRequest.setClearingMemberCategory("1234"); + BaseRequest baseUpdateRequest = new BaseRequest<>(); + baseUpdateRequest.setRequestPayload(memberCategoryUpdateRequest); + baseUpdateRequest.setId(currentId); + baseUpdateRequest.setActionType(ActionType.UPDATE); + String jsonBaseForUpdatingRequest; + ObjectMapper objectMapper = new ObjectMapper(); + try { + jsonBaseForUpdatingRequest = objectMapper.writeValueAsString(baseUpdateRequest); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + + ClearingMemberCategory predictableClearingMemberCategory = new ClearingMemberCategory(); + predictableClearingMemberCategory.setId(currentId); + predictableClearingMemberCategory.setClearingMemberCategory("1234"); + + //ACT + //service set up + ClearingMemberCategoryService clearingMemberCategoryService = new ClearingMemberCategoryService(mockConsumer, hazelcastServiceTest); + Thread.sleep(10000); + //callbacks set up + clearingMemberCategoryService.afterPropertiesSet(); + Thread.sleep(10000); + + IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_ClearingMemberCategory); + iMap.put(currentId, existsСlearingMemberCategory); + + //KAFKA + mockConsumer.schedulePollTask(() -> { + mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC_CONTACT_UPDATE, PARTITION))); + mockConsumer.addRecord(new ConsumerRecord<>(TOPIC_CONTACT_UPDATE, PARTITION, 0, "key", jsonBaseForUpdatingRequest)); + }); + HashMap startOffsetsUpdating = new HashMap<>(); + TopicPartition tpUpdating = new TopicPartition(TOPIC_CONTACT_UPDATE, PARTITION); + startOffsetsUpdating.put(tpUpdating, 0L); + mockConsumer.updateBeginningOffsets(startOffsetsUpdating); + + //ASSERT + Thread.sleep(10000); + ClearingMemberCategory resultUpdating = iMap.get(currentId); + CONTACT_MATCHER.assertMatch(resultUpdating, predictableClearingMemberCategory); + + //preparing hazelcastImdgProvider for next test + iMap.clear(); + currentId++; + } +} \ No newline at end of file From bf6fb987427d5745cd3743d9adeb869ca3191347 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Fri, 16 Sep 2022 18:15:59 +0300 Subject: [PATCH 18/33] http://git.mfd.msk/mfd/clearing/issues/6 --- ContactServiceTest test done --- .../company/service/ContactService.java | 4 +- .../company/service/ContactServiceTest.java | 47 +++++++++++-------- 2 files changed, 30 insertions(+), 21 deletions(-) diff --git a/clearing-parent/company-service/src/main/java/ru/spcex/clearing/company/service/ContactService.java b/clearing-parent/company-service/src/main/java/ru/spcex/clearing/company/service/ContactService.java index 0decc85f3..6b0d1b326 100644 --- a/clearing-parent/company-service/src/main/java/ru/spcex/clearing/company/service/ContactService.java +++ b/clearing-parent/company-service/src/main/java/ru/spcex/clearing/company/service/ContactService.java @@ -5,6 +5,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import ru.clearing.classes.statics.data.profile.Contact; import ru.spcex.clearing.imdg.IMDGDistributedNames; import ru.spcex.clearing.platform.messaging.domain.BaseRequest; @@ -14,6 +15,7 @@ import ru.spcex.clearing.platform.messaging.service.QueueConsumer; import ru.spcex.platform.imdg.api.Imdg; import ru.spcex.platform.imdg.api.ImdgProvider; +@Service public class ContactService extends QueueConsumer implements InitializingBean { private final Logger log = LoggerFactory.getLogger(getClass()); private final Imdg contactMap; @@ -37,7 +39,7 @@ public class ContactService extends QueueConsumer implements InitializingBean { ContactUpdateRequest req = userRequest.getRequestPayload(); log.debug("ContactUpdateRequest received"); Contact contact = contactMap.getSingleObjectByID(req.getId()); - contact.setContactType(req.getContactType()); +// contact.setContactType(req.getContactType()); по ТЗ не должен менятся при обновлении contact.setContactValue(req.getContactValue()); contactMap.update(contact); diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java index 6c0f2d770..e2a843830 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java @@ -14,14 +14,14 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; -import ru.clearing.classes.statics.data.generated.ClearingMemberCategory; +import ru.clearing.classes.statics.data.profile.Contact; import ru.spcex.clearing.company.config.HazelcastServiceTestConfiguration; import ru.spcex.clearing.company.utils.MatcherFactory; import ru.spcex.clearing.imdg.IMDGDistributedNames; import ru.spcex.clearing.platform.messaging.domain.ActionType; import ru.spcex.clearing.platform.messaging.domain.BaseRequest; import ru.spcex.clearing.platform.messaging.domain.Consts; -import ru.spcex.clearing.platform.messaging.domain.cud.company.ClearingMemberCategoryUpdateRequest; +import ru.spcex.clearing.platform.messaging.domain.cud.company.ContactUpdateRequest; import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService; import java.util.Collections; @@ -34,7 +34,7 @@ import static ru.spcex.clearing.company.utils.MatcherFactory.usingIgnoringFields HazelcastServiceTestConfiguration.class}) class ContactServiceTest { - public static final MatcherFactory.Matcher CONTACT_MATCHER = usingIgnoringFieldsComparator(); + public static final MatcherFactory.Matcher CONTACT_MATCHER = usingIgnoringFieldsComparator(); private static final int PARTITION = 0; private static final String TOPIC_CONTACT_UPDATE = Consts.DESTINATION_CONTACT_UPDATE; private static Long currentId = 0L; @@ -52,15 +52,20 @@ class ContactServiceTest { @Test void contactUpdate() throws InterruptedException { //ARRANGE - ClearingMemberCategory existsСlearingMemberCategory = new ClearingMemberCategory(); - existsСlearingMemberCategory.setId(currentId); - existsСlearingMemberCategory.setClearingMemberCategory("0000"); + Contact existsContact = new Contact(); + existsContact.setId(currentId); + existsContact.setCompanyId(currentId); + existsContact.setContactType("0000"); + existsContact.setContactValue("exists ContactValue"); - ClearingMemberCategoryUpdateRequest memberCategoryUpdateRequest = new ClearingMemberCategoryUpdateRequest(); - memberCategoryUpdateRequest.setId(currentId); - memberCategoryUpdateRequest.setClearingMemberCategory("1234"); - BaseRequest baseUpdateRequest = new BaseRequest<>(); - baseUpdateRequest.setRequestPayload(memberCategoryUpdateRequest); + ContactUpdateRequest contactUpdateRequest = new ContactUpdateRequest(); + contactUpdateRequest.setId(currentId); + contactUpdateRequest.setCompanyId(1L); + contactUpdateRequest.setContactType("1234"); + contactUpdateRequest.setContactValue("new ContactValue"); + + BaseRequest baseUpdateRequest = new BaseRequest<>(); + baseUpdateRequest.setRequestPayload(contactUpdateRequest); baseUpdateRequest.setId(currentId); baseUpdateRequest.setActionType(ActionType.UPDATE); String jsonBaseForUpdatingRequest; @@ -71,20 +76,22 @@ class ContactServiceTest { throw new RuntimeException(e); } - ClearingMemberCategory predictableClearingMemberCategory = new ClearingMemberCategory(); - predictableClearingMemberCategory.setId(currentId); - predictableClearingMemberCategory.setClearingMemberCategory("1234"); + Contact predictableContact = new Contact(); + predictableContact.setId(currentId); + predictableContact.setCompanyId(currentId); + predictableContact.setContactType("0000"); + predictableContact.setContactValue("new ContactValue"); //ACT //service set up - ClearingMemberCategoryService clearingMemberCategoryService = new ClearingMemberCategoryService(mockConsumer, hazelcastServiceTest); + ContactService contactService = new ContactService(mockConsumer, hazelcastServiceTest); Thread.sleep(10000); //callbacks set up - clearingMemberCategoryService.afterPropertiesSet(); + contactService.afterPropertiesSet(); Thread.sleep(10000); - IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_ClearingMemberCategory); - iMap.put(currentId, existsСlearingMemberCategory); + IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_Contact); + iMap.put(currentId, existsContact); //KAFKA mockConsumer.schedulePollTask(() -> { @@ -98,8 +105,8 @@ class ContactServiceTest { //ASSERT Thread.sleep(10000); - ClearingMemberCategory resultUpdating = iMap.get(currentId); - CONTACT_MATCHER.assertMatch(resultUpdating, predictableClearingMemberCategory); + Contact resultUpdating = iMap.get(currentId); + CONTACT_MATCHER.assertMatch(resultUpdating, predictableContact); //preparing hazelcastImdgProvider for next test iMap.clear(); From aed45da642b5e0c97d2d44c95795a8b9d4f80f6b Mon Sep 17 00:00:00 2001 From: psemenkov Date: Fri, 16 Sep 2022 19:05:24 +0300 Subject: [PATCH 19/33] http://git.mfd.msk/mfd/clearing/issues/6 --- ContactServiceTest refactoring --- .../ClearingMemberCategoryServiceTest.java | 42 ++++++++++++++----- .../company/service/ContactServiceTest.java | 28 +++++++++---- 2 files changed, 53 insertions(+), 17 deletions(-) diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java index 6ef2c71e1..56c9b6792 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java @@ -3,6 +3,7 @@ package ru.spcex.clearing.company.service; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.hazelcast.core.IMap; +import com.hazelcast.map.listener.EntryRemovedListener; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.MockConsumer; import org.apache.kafka.clients.consumer.OffsetResetStrategy; @@ -16,6 +17,7 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import ru.clearing.classes.statics.data.generated.ClearingMemberCategory; +import ru.clearing.classes.statics.data.profile.Contact; import ru.spcex.clearing.company.config.HazelcastServiceTestConfiguration; import ru.spcex.clearing.company.utils.MatcherFactory.Matcher; import ru.spcex.clearing.imdg.IMDGDistributedNames; @@ -81,10 +83,9 @@ class ClearingMemberCategoryServiceTest { //ACT //service set up ClearingMemberCategoryService clearingMemberCategoryService = new ClearingMemberCategoryService(mockConsumer, hazelcastServiceTest); - Thread.sleep(10000); + //callbacks set up clearingMemberCategoryService.afterPropertiesSet(); - Thread.sleep(10000); IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_ClearingMemberCategory); iMap.put(currentId, existsСlearingMemberCategory); @@ -100,13 +101,24 @@ class ClearingMemberCategoryServiceTest { mockConsumer.updateBeginningOffsets(startOffsetsUpdating); //ASSERT - Thread.sleep(10000); + Object waiter = new Object(); + String listenerID = iMap.addEntryListener((EntryRemovedListener) entryEvent -> { + System.out.println("Checking If removed.."); + + synchronized (waiter) { + waiter.notify(); + } + }, false); + + synchronized (waiter) { + waiter.wait(1000); + } + ClearingMemberCategory resultUpdating = iMap.get(currentId); MEMBER_CATEGORY_MATCHER.assertMatch(resultUpdating, predictableClearingMemberCategory); //preparing hazelcastImdgProvider for next test - iMap.clear(); - currentId++; + iMap.removeEntryListener(listenerID); } @Test @@ -134,10 +146,9 @@ class ClearingMemberCategoryServiceTest { //ACT //service set up ClearingMemberCategoryService clearingMemberCategoryService = new ClearingMemberCategoryService(mockConsumer, hazelcastServiceTest); - Thread.sleep(10000); + //callbacks set up clearingMemberCategoryService.afterPropertiesSet(); - Thread.sleep(10000); IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_ClearingMemberCategory); iMap.put(currentId, existsСlearingMemberCategory); @@ -153,11 +164,22 @@ class ClearingMemberCategoryServiceTest { mockConsumer.updateBeginningOffsets(startOffsetsUpdating); //ASSERT - Thread.sleep(10000); + Object waiter = new Object(); + String listenerID = iMap.addEntryListener((EntryRemovedListener) entryEvent -> { + System.out.println("Checking If removed.."); + + synchronized (waiter) { + waiter.notify(); + } + }, false); + + synchronized (waiter) { + waiter.wait(1000); + } + Assertions.assertEquals(0, iMap.size()); //preparing hazelcastImdgProvider for next test - iMap.clear(); - currentId++; + iMap.removeEntryListener(listenerID); } } \ No newline at end of file diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java index e2a843830..0e8c30f5f 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java @@ -3,6 +3,7 @@ package ru.spcex.clearing.company.service; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.hazelcast.core.IMap; +import com.hazelcast.map.listener.EntryRemovedListener; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.MockConsumer; import org.apache.kafka.clients.consumer.OffsetResetStrategy; @@ -37,7 +38,7 @@ class ContactServiceTest { public static final MatcherFactory.Matcher CONTACT_MATCHER = usingIgnoringFieldsComparator(); private static final int PARTITION = 0; private static final String TOPIC_CONTACT_UPDATE = Consts.DESTINATION_CONTACT_UPDATE; - private static Long currentId = 0L; + private static final Long currentId = 0L; @Autowired @Qualifier("hazelcastServiceTest") @@ -85,11 +86,9 @@ class ContactServiceTest { //ACT //service set up ContactService contactService = new ContactService(mockConsumer, hazelcastServiceTest); - Thread.sleep(10000); - //callbacks set up contactService.afterPropertiesSet(); - Thread.sleep(10000); + //callbacks set up IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_Contact); iMap.put(currentId, existsContact); @@ -104,12 +103,27 @@ class ContactServiceTest { mockConsumer.updateBeginningOffsets(startOffsetsUpdating); //ASSERT - Thread.sleep(10000); + Object waiter = new Object(); + String listenerID = iMap.addEntryListener((EntryRemovedListener) entryEvent -> { + System.out.println("Checking If removed.."); +// resultUpdating = entryEvent.getValue(); +// entryEvent.getKey(); +// CONTACT_MATCHER.assertMatch(resultUpdating, predictableContact); + + synchronized (waiter) { + waiter.notify(); + } + }, false); + + synchronized (waiter) { + waiter.wait(1000); + } + + Contact resultUpdating = iMap.get(currentId); CONTACT_MATCHER.assertMatch(resultUpdating, predictableContact); //preparing hazelcastImdgProvider for next test - iMap.clear(); - currentId++; + iMap.removeEntryListener(listenerID); } } \ No newline at end of file From ab391739fa475626cf46e669a5868a4f8d75183d Mon Sep 17 00:00:00 2001 From: psemenkov Date: Mon, 19 Sep 2022 11:27:32 +0300 Subject: [PATCH 20/33] http://git.mfd.msk/mfd/clearing/issues/6 --- refactoring tests --- .../ClearingMemberCategoryServiceTest.java | 38 +++++++++------- .../service/CompanyInfoServiceTest.java | 39 +++++++++++------ .../company/service/CompanyServiceTest.java | 33 +++++++++----- .../service/CompanySymbolServiceTest.java | 43 ++++++++++++------- .../company/service/ContactServiceTest.java | 29 ++++++------- 5 files changed, 114 insertions(+), 68 deletions(-) diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java index 56c9b6792..21bfc4717 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.hazelcast.core.IMap; import com.hazelcast.map.listener.EntryRemovedListener; +import com.hazelcast.map.listener.EntryUpdatedListener; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.MockConsumer; import org.apache.kafka.clients.consumer.OffsetResetStrategy; @@ -42,7 +43,7 @@ class ClearingMemberCategoryServiceTest { private static final int PARTITION = 0; private static final String TOPIC_MEMBER_CATEGORY_UPDATE = Consts.DESTINATION_CLEARING_MEMBER_CATEGORY_UPDATE; private static final String TOPIC_MEMBER_CATEGORY_DELETE = Consts.DESTINATION_CLEARING_MEMBER_CATEGORY_DELETE; - private static Long currentId = 0L; + private static final Long ID = 0L; @Autowired @Qualifier("hazelcastServiceTest") @@ -58,15 +59,15 @@ class ClearingMemberCategoryServiceTest { void clearingMemberCategoryUpdate() throws InterruptedException { //ARRANGE ClearingMemberCategory existsСlearingMemberCategory = new ClearingMemberCategory(); - existsСlearingMemberCategory.setId(currentId); + existsСlearingMemberCategory.setId(ID); existsСlearingMemberCategory.setClearingMemberCategory("0000"); ClearingMemberCategoryUpdateRequest memberCategoryUpdateRequest = new ClearingMemberCategoryUpdateRequest(); - memberCategoryUpdateRequest.setId(currentId); + memberCategoryUpdateRequest.setId(ID); memberCategoryUpdateRequest.setClearingMemberCategory("1234"); BaseRequest baseUpdateRequest = new BaseRequest<>(); baseUpdateRequest.setRequestPayload(memberCategoryUpdateRequest); - baseUpdateRequest.setId(currentId); + baseUpdateRequest.setId(ID); baseUpdateRequest.setActionType(ActionType.UPDATE); String jsonBaseForUpdatingRequest; ObjectMapper objectMapper = new ObjectMapper(); @@ -77,7 +78,7 @@ class ClearingMemberCategoryServiceTest { } ClearingMemberCategory predictableClearingMemberCategory = new ClearingMemberCategory(); - predictableClearingMemberCategory.setId(currentId); + predictableClearingMemberCategory.setId(ID); predictableClearingMemberCategory.setClearingMemberCategory("1234"); //ACT @@ -88,7 +89,7 @@ class ClearingMemberCategoryServiceTest { clearingMemberCategoryService.afterPropertiesSet(); IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_ClearingMemberCategory); - iMap.put(currentId, existsСlearingMemberCategory); + iMap.put(ID, existsСlearingMemberCategory); //KAFKA mockConsumer.schedulePollTask(() -> { @@ -100,21 +101,27 @@ class ClearingMemberCategoryServiceTest { startOffsetsUpdating.put(tpUpdating, 0L); mockConsumer.updateBeginningOffsets(startOffsetsUpdating); - //ASSERT + //waiting for hazelcast map item updates Object waiter = new Object(); - String listenerID = iMap.addEntryListener((EntryRemovedListener) entryEvent -> { + String listenerID = iMap.addEntryListener((EntryUpdatedListener) entryEvent -> { System.out.println("Checking If removed.."); synchronized (waiter) { + try { + waiter.wait(100); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } waiter.notify(); } }, false); synchronized (waiter) { - waiter.wait(1000); + waiter.wait(100); } - ClearingMemberCategory resultUpdating = iMap.get(currentId); + //ASSERT + ClearingMemberCategory resultUpdating = iMap.get(ID); MEMBER_CATEGORY_MATCHER.assertMatch(resultUpdating, predictableClearingMemberCategory); //preparing hazelcastImdgProvider for next test @@ -125,15 +132,15 @@ class ClearingMemberCategoryServiceTest { void clearingMemberCategoryDelete() throws InterruptedException { //ARRANGE ClearingMemberCategory existsСlearingMemberCategory = new ClearingMemberCategory(); - existsСlearingMemberCategory.setId(currentId); + existsСlearingMemberCategory.setId(ID); existsСlearingMemberCategory.setClearingMemberCategory("0000"); CommonDeleteRequest memberCategoryDeleteRequest = new CommonDeleteRequest(); - memberCategoryDeleteRequest.setId(currentId); + memberCategoryDeleteRequest.setId(ID); BaseRequest baseDeleteRequest = new BaseRequest<>(); baseDeleteRequest.setRequestPayload(memberCategoryDeleteRequest); - baseDeleteRequest.setId(currentId); + baseDeleteRequest.setId(ID); baseDeleteRequest.setActionType(ActionType.DELETE); String jsonBaseForDeleteRequest; ObjectMapper objectMapper = new ObjectMapper(); @@ -151,7 +158,7 @@ class ClearingMemberCategoryServiceTest { clearingMemberCategoryService.afterPropertiesSet(); IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_ClearingMemberCategory); - iMap.put(currentId, existsСlearingMemberCategory); + iMap.put(ID, existsСlearingMemberCategory); //KAFKA mockConsumer.schedulePollTask(() -> { @@ -163,7 +170,7 @@ class ClearingMemberCategoryServiceTest { startOffsetsUpdating.put(tpDeleting, 0L); mockConsumer.updateBeginningOffsets(startOffsetsUpdating); - //ASSERT + //waiting for hazelcast map item removes Object waiter = new Object(); String listenerID = iMap.addEntryListener((EntryRemovedListener) entryEvent -> { System.out.println("Checking If removed.."); @@ -177,6 +184,7 @@ class ClearingMemberCategoryServiceTest { waiter.wait(1000); } + //ASSERT Assertions.assertEquals(0, iMap.size()); //preparing hazelcastImdgProvider for next test diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java index 076085986..20e96420e 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java @@ -3,6 +3,7 @@ package ru.spcex.clearing.company.service; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.hazelcast.core.IMap; +import com.hazelcast.map.listener.EntryUpdatedListener; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.MockConsumer; import org.apache.kafka.clients.consumer.OffsetResetStrategy; @@ -15,6 +16,7 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import ru.clearing.classes.statics.data.profile.CompanyInfo; +import ru.clearing.classes.statics.data.profile.Contact; import ru.spcex.clearing.company.config.HazelcastServiceTestConfiguration; import ru.spcex.clearing.company.utils.MatcherFactory; import ru.spcex.clearing.imdg.IMDGDistributedNames; @@ -37,7 +39,7 @@ class CompanyInfoServiceTest { public static final MatcherFactory.Matcher COMPANY_INFO_MATCHER = usingIgnoringFieldsComparator(); private static final int PARTITION = 0; private static final String TOPIC_COMPANY_INFO_UPDATE = Consts.DESTINATION_COMPANY_INFO_UPDATE; - private static Long currentId = 0L; + private static final Long ID = 0L; @Autowired @Qualifier("hazelcastServiceTest") @@ -53,7 +55,8 @@ class CompanyInfoServiceTest { void companyInfoUpdate() throws InterruptedException { //ARRANGE CompanyInfo existsCompanyInfo = new CompanyInfo(); - existsCompanyInfo.setId(currentId); + existsCompanyInfo.setId(ID); + existsCompanyInfo.setCompanyId(ID); existsCompanyInfo.setCorporationSoleType("0000"); existsCompanyInfo.setCountryCode("0000"); existsCompanyInfo.setDescription("exists description"); @@ -67,7 +70,7 @@ class CompanyInfoServiceTest { existsCompanyInfo.setFullName("exists fullName"); CompanyInfoUpdateRequest companyInfoUpdateRequest = new CompanyInfoUpdateRequest(); - companyInfoUpdateRequest.setId(currentId); + companyInfoUpdateRequest.setId(ID); companyInfoUpdateRequest.setCorporationSoleType("1234"); companyInfoUpdateRequest.setCountryCode("1234"); companyInfoUpdateRequest.setDescription("updated description"); @@ -82,7 +85,7 @@ class CompanyInfoServiceTest { BaseRequest baseUpdateRequest = new BaseRequest<>(); baseUpdateRequest.setRequestPayload(companyInfoUpdateRequest); - baseUpdateRequest.setId(currentId); + baseUpdateRequest.setId(ID); baseUpdateRequest.setActionType(ActionType.UPDATE); String jsonBaseForUpdatingRequest; ObjectMapper objectMapper = new ObjectMapper(); @@ -93,7 +96,8 @@ class CompanyInfoServiceTest { } CompanyInfo predictableCompanyInfo = new CompanyInfo(); - predictableCompanyInfo.setId(currentId); + predictableCompanyInfo.setId(ID); + predictableCompanyInfo.setCompanyId(ID); predictableCompanyInfo.setCorporationSoleType("1234"); predictableCompanyInfo.setCountryCode("1234"); predictableCompanyInfo.setDescription("updated description"); @@ -109,13 +113,12 @@ class CompanyInfoServiceTest { //ACT //service set up CompanyInfoService clearingMemberCategoryService = new CompanyInfoService(mockConsumer, hazelcastServiceTest); - Thread.sleep(10000); + //callbacks set up clearingMemberCategoryService.afterPropertiesSet(); - Thread.sleep(10000); IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_Company); - iMap.put(currentId, existsCompanyInfo); + iMap.put(ID, existsCompanyInfo); //KAFKA mockConsumer.schedulePollTask(() -> { @@ -127,13 +130,25 @@ class CompanyInfoServiceTest { startOffsetsUpdating.put(tpUpdating, 0L); mockConsumer.updateBeginningOffsets(startOffsetsUpdating); + //waiting for hazelcast map updates + Object waiter = new Object(); + String listenerID = iMap.addEntryListener((EntryUpdatedListener) entryEvent -> { + System.out.println("Checking If removed.."); + + synchronized (waiter) { + waiter.notify(); + } + }, false); + + synchronized (waiter) { + waiter.wait(1000); + } + //ASSERT - Thread.sleep(10000); - CompanyInfo resultUpdating = iMap.get(currentId); + CompanyInfo resultUpdating = iMap.get(ID); COMPANY_INFO_MATCHER.assertMatch(resultUpdating, predictableCompanyInfo); //preparing hazelcastImdgProvider for next test - iMap.clear(); - currentId++; + iMap.removeEntryListener(listenerID); } } \ No newline at end of file diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java index fd1708dc6..f9b714d8a 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java @@ -3,6 +3,7 @@ package ru.spcex.clearing.company.service; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.hazelcast.core.IMap; +import com.hazelcast.map.listener.EntryRemovedListener; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.MockConsumer; import org.apache.kafka.clients.consumer.OffsetResetStrategy; @@ -17,6 +18,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import ru.clearing.classes.statics.data.company.Company; import ru.clearing.classes.statics.data.generated.ClearingMemberCategory; +import ru.clearing.classes.statics.data.profile.Contact; import ru.spcex.clearing.company.config.HazelcastServiceTestConfiguration; import ru.spcex.clearing.company.utils.MatcherFactory; import ru.spcex.clearing.imdg.IMDGDistributedNames; @@ -39,7 +41,7 @@ class CompanyServiceTest { public static final MatcherFactory.Matcher COMPANY_MATCHER = usingIgnoringFieldsComparator(); private static final int PARTITION = 0; private static final String TOPIC_COMPANY_DELETE = Consts.DESTINATION_COMPANY_DELETE; - private static Long currentId = 0L; + private static final Long ID = 0L; @Autowired @Qualifier("hazelcastServiceTest") @@ -55,14 +57,14 @@ class CompanyServiceTest { void deleteCompany() throws InterruptedException { //ARRANGE Company existsCompany = new Company(); - existsCompany.setId(currentId); + existsCompany.setId(ID); CommonDeleteRequest memberCategoryDeleteRequest = new CommonDeleteRequest(); - memberCategoryDeleteRequest.setId(currentId); + memberCategoryDeleteRequest.setId(ID); BaseRequest baseDeleteRequest = new BaseRequest<>(); baseDeleteRequest.setRequestPayload(memberCategoryDeleteRequest); - baseDeleteRequest.setId(currentId); + baseDeleteRequest.setId(ID); baseDeleteRequest.setActionType(ActionType.DELETE); String jsonBaseForDeleteRequest; ObjectMapper objectMapper = new ObjectMapper(); @@ -75,13 +77,12 @@ class CompanyServiceTest { //ACT //service set up CompanyService companyService = new CompanyService(mockConsumer, hazelcastServiceTest); - Thread.sleep(10000); + //callbacks set up companyService.afterPropertiesSet(); - Thread.sleep(10000); IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_Company); - iMap.put(currentId, existsCompany); + iMap.put(ID, existsCompany); //KAFKA mockConsumer.schedulePollTask(() -> { @@ -93,12 +94,24 @@ class CompanyServiceTest { startOffsetsUpdating.put(tpDeleting, 0L); mockConsumer.updateBeginningOffsets(startOffsetsUpdating); + //waiting for hazelcast map item removes + Object waiter = new Object(); + String listenerID = iMap.addEntryListener((EntryRemovedListener) entryEvent -> { + System.out.println("Checking If removed.."); + + synchronized (waiter) { + waiter.notify(); + } + }, false); + + synchronized (waiter) { + waiter.wait(100); + } + //ASSERT - Thread.sleep(10000); Assertions.assertEquals(0, iMap.size()); //preparing hazelcastImdgProvider for next test - iMap.clear(); - currentId++; + iMap.removeEntryListener(listenerID); } } \ No newline at end of file diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java index e74ed25dd..bdee7706b 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java @@ -3,6 +3,7 @@ package ru.spcex.clearing.company.service; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.hazelcast.core.IMap; +import com.hazelcast.map.listener.EntryUpdatedListener; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.MockConsumer; import org.apache.kafka.clients.consumer.OffsetResetStrategy; @@ -15,6 +16,7 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import ru.clearing.classes.statics.data.company.CompanySymbols; +import ru.clearing.classes.statics.data.profile.Contact; import ru.spcex.clearing.company.config.HazelcastServiceTestConfiguration; import ru.spcex.clearing.company.utils.MatcherFactory; import ru.spcex.clearing.imdg.IMDGDistributedNames; @@ -37,7 +39,7 @@ class CompanySymbolServiceTest { public static final MatcherFactory.Matcher COMPANY_SYMBOL_MATCHER = usingIgnoringFieldsComparator(); private static final int PARTITION = 0; private static final String TOPIC_COMPANY_SYMBOL_UPDATE = Consts.DESTINATION_COMPANY_SYMBOL_UPDATE; - private static Long currentId = 0L; + private static final Long ID = 0L; @Autowired @Qualifier("hazelcastServiceTest") @@ -53,20 +55,20 @@ class CompanySymbolServiceTest { void companySymbolUpdate() throws InterruptedException { //ARRANGE CompanySymbols existsCompanySymbols = new CompanySymbols(); - existsCompanySymbols.setId(currentId); - existsCompanySymbols.setCompanyId(currentId); + existsCompanySymbols.setId(ID); + existsCompanySymbols.setCompanyId(ID); existsCompanySymbols.setCompanySymbol("0000"); existsCompanySymbols.setCompanySymbolValue("exists companySymbolValue"); CompanySymbolUpdateRequest companySymbolUpdateRequest = new CompanySymbolUpdateRequest(); - companySymbolUpdateRequest.setId(currentId); - companySymbolUpdateRequest.setCompanyId(currentId); + companySymbolUpdateRequest.setId(ID); + companySymbolUpdateRequest.setCompanyId(ID); companySymbolUpdateRequest.setCompanySymbol("1234"); companySymbolUpdateRequest.setCompanySymbolValue("new companySymbolValue"); BaseRequest baseUpdateRequest = new BaseRequest<>(); baseUpdateRequest.setRequestPayload(companySymbolUpdateRequest); - baseUpdateRequest.setId(currentId); + baseUpdateRequest.setId(ID); baseUpdateRequest.setActionType(ActionType.UPDATE); String jsonBaseForUpdatingRequest; ObjectMapper objectMapper = new ObjectMapper(); @@ -77,21 +79,20 @@ class CompanySymbolServiceTest { } CompanySymbols predictableCompanySymbols = new CompanySymbols(); - predictableCompanySymbols.setId(currentId); - predictableCompanySymbols.setCompanyId(currentId); + predictableCompanySymbols.setId(ID); + predictableCompanySymbols.setCompanyId(ID); predictableCompanySymbols.setCompanySymbol("0000"); predictableCompanySymbols.setCompanySymbolValue("new companySymbolValue"); //ACT //service set up CompanySymbolService companySymbolService = new CompanySymbolService(mockConsumer, hazelcastServiceTest); - Thread.sleep(10000); + //callbacks set up companySymbolService.afterPropertiesSet(); - Thread.sleep(10000); IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_CompanySymbols); - iMap.put(currentId, existsCompanySymbols); + iMap.put(ID, existsCompanySymbols); //KAFKA mockConsumer.schedulePollTask(() -> { @@ -103,13 +104,25 @@ class CompanySymbolServiceTest { startOffsetsUpdating.put(tpUpdating, 0L); mockConsumer.updateBeginningOffsets(startOffsetsUpdating); + //waiting for hazelcast map item updates + Object waiter = new Object(); + String listenerID = iMap.addEntryListener((EntryUpdatedListener) entryEvent -> { + System.out.println("Checking If removed.."); + + synchronized (waiter) { + waiter.notify(); + } + }, false); + + synchronized (waiter) { + waiter.wait(1000); + } + //ASSERT - Thread.sleep(10000); - CompanySymbols resultUpdating = iMap.get(currentId); + CompanySymbols resultUpdating = iMap.get(ID); COMPANY_SYMBOL_MATCHER.assertMatch(resultUpdating, predictableCompanySymbols); //preparing hazelcastImdgProvider for next test - iMap.clear(); - currentId++; + iMap.removeEntryListener(listenerID); } } \ No newline at end of file diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java index 0e8c30f5f..4d1e3b397 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java @@ -3,7 +3,7 @@ package ru.spcex.clearing.company.service; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.hazelcast.core.IMap; -import com.hazelcast.map.listener.EntryRemovedListener; +import com.hazelcast.map.listener.EntryUpdatedListener; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.MockConsumer; import org.apache.kafka.clients.consumer.OffsetResetStrategy; @@ -38,7 +38,7 @@ class ContactServiceTest { public static final MatcherFactory.Matcher CONTACT_MATCHER = usingIgnoringFieldsComparator(); private static final int PARTITION = 0; private static final String TOPIC_CONTACT_UPDATE = Consts.DESTINATION_CONTACT_UPDATE; - private static final Long currentId = 0L; + private static final Long ID = 0L; @Autowired @Qualifier("hazelcastServiceTest") @@ -54,20 +54,20 @@ class ContactServiceTest { void contactUpdate() throws InterruptedException { //ARRANGE Contact existsContact = new Contact(); - existsContact.setId(currentId); - existsContact.setCompanyId(currentId); + existsContact.setId(ID); + existsContact.setCompanyId(ID); existsContact.setContactType("0000"); existsContact.setContactValue("exists ContactValue"); ContactUpdateRequest contactUpdateRequest = new ContactUpdateRequest(); - contactUpdateRequest.setId(currentId); + contactUpdateRequest.setId(ID); contactUpdateRequest.setCompanyId(1L); contactUpdateRequest.setContactType("1234"); contactUpdateRequest.setContactValue("new ContactValue"); BaseRequest baseUpdateRequest = new BaseRequest<>(); baseUpdateRequest.setRequestPayload(contactUpdateRequest); - baseUpdateRequest.setId(currentId); + baseUpdateRequest.setId(ID); baseUpdateRequest.setActionType(ActionType.UPDATE); String jsonBaseForUpdatingRequest; ObjectMapper objectMapper = new ObjectMapper(); @@ -78,8 +78,8 @@ class ContactServiceTest { } Contact predictableContact = new Contact(); - predictableContact.setId(currentId); - predictableContact.setCompanyId(currentId); + predictableContact.setId(ID); + predictableContact.setCompanyId(ID); predictableContact.setContactType("0000"); predictableContact.setContactValue("new ContactValue"); @@ -90,7 +90,7 @@ class ContactServiceTest { //callbacks set up IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_Contact); - iMap.put(currentId, existsContact); + iMap.put(ID, existsContact); //KAFKA mockConsumer.schedulePollTask(() -> { @@ -102,13 +102,10 @@ class ContactServiceTest { startOffsetsUpdating.put(tpUpdating, 0L); mockConsumer.updateBeginningOffsets(startOffsetsUpdating); - //ASSERT + //waiting for hazelcast map updates Object waiter = new Object(); - String listenerID = iMap.addEntryListener((EntryRemovedListener) entryEvent -> { + String listenerID = iMap.addEntryListener((EntryUpdatedListener) entryEvent -> { System.out.println("Checking If removed.."); -// resultUpdating = entryEvent.getValue(); -// entryEvent.getKey(); -// CONTACT_MATCHER.assertMatch(resultUpdating, predictableContact); synchronized (waiter) { waiter.notify(); @@ -119,8 +116,8 @@ class ContactServiceTest { waiter.wait(1000); } - - Contact resultUpdating = iMap.get(currentId); + //ASSERT + Contact resultUpdating = iMap.get(ID); CONTACT_MATCHER.assertMatch(resultUpdating, predictableContact); //preparing hazelcastImdgProvider for next test From d7f635f7f1e9da0e7029a988b150980946529103 Mon Sep 17 00:00:00 2001 From: aalehin Date: Mon, 19 Sep 2022 16:45:36 +0300 Subject: [PATCH 21/33] hotfix tests running with maven --- clearing-parent/account-service/pom.xml | 17 +++++++++++++++++ clearing-parent/company-service/pom.xml | 21 +++++++++++++++++++-- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/clearing-parent/account-service/pom.xml b/clearing-parent/account-service/pom.xml index 683aff67d..ddbf3d9d1 100644 --- a/clearing-parent/account-service/pom.xml +++ b/clearing-parent/account-service/pom.xml @@ -84,6 +84,23 @@ ${project.artifactId} + + org.apache.maven.plugins + maven-surefire-plugin + 2.21.0 + + + org.junit.platform + junit-platform-surefire-provider + 1.2.0-M1 + + + org.junit.jupiter + junit-jupiter-engine + 5.2.0-M1 + + + diff --git a/clearing-parent/company-service/pom.xml b/clearing-parent/company-service/pom.xml index 0e041276a..a34291ee8 100644 --- a/clearing-parent/company-service/pom.xml +++ b/clearing-parent/company-service/pom.xml @@ -1,6 +1,6 @@ - clearing-parent @@ -68,6 +68,23 @@ ${project.artifactId} + + org.apache.maven.plugins + maven-surefire-plugin + 2.21.0 + + + org.junit.platform + junit-platform-surefire-provider + 1.2.0-M1 + + + org.junit.jupiter + junit-jupiter-engine + 5.2.0-M1 + + + From b380dbf231624a77738b143f58a4cfa4a65b4905 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Mon, 19 Sep 2022 17:05:55 +0300 Subject: [PATCH 22/33] http://git.mfd.msk/mfd/clearing/issues/6 --- refactoring tests for running in maven --- .../company/service/ClearingMemberCategoryServiceTest.java | 7 ++++++- .../clearing/company/service/CompanyInfoServiceTest.java | 7 ++++++- .../spcex/clearing/company/service/CompanyServiceTest.java | 5 +++++ .../clearing/company/service/CompanySymbolServiceTest.java | 7 ++++++- .../spcex/clearing/company/service/ContactServiceTest.java | 7 ++++++- 5 files changed, 29 insertions(+), 4 deletions(-) diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java index 21bfc4717..6fb3d09e9 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java @@ -175,13 +175,18 @@ class ClearingMemberCategoryServiceTest { String listenerID = iMap.addEntryListener((EntryRemovedListener) entryEvent -> { System.out.println("Checking If removed.."); + try { + waiter.wait(100); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } synchronized (waiter) { waiter.notify(); } }, false); synchronized (waiter) { - waiter.wait(1000); + waiter.wait(100); } //ASSERT diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java index 20e96420e..83c3e92e7 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java @@ -135,13 +135,18 @@ class CompanyInfoServiceTest { String listenerID = iMap.addEntryListener((EntryUpdatedListener) entryEvent -> { System.out.println("Checking If removed.."); + try { + waiter.wait(100); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } synchronized (waiter) { waiter.notify(); } }, false); synchronized (waiter) { - waiter.wait(1000); + waiter.wait(100); } //ASSERT diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java index f9b714d8a..f9b9f73aa 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java @@ -99,6 +99,11 @@ class CompanyServiceTest { String listenerID = iMap.addEntryListener((EntryRemovedListener) entryEvent -> { System.out.println("Checking If removed.."); + try { + waiter.wait(100); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } synchronized (waiter) { waiter.notify(); } diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java index bdee7706b..15654ba28 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java @@ -109,13 +109,18 @@ class CompanySymbolServiceTest { String listenerID = iMap.addEntryListener((EntryUpdatedListener) entryEvent -> { System.out.println("Checking If removed.."); + try { + waiter.wait(100); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } synchronized (waiter) { waiter.notify(); } }, false); synchronized (waiter) { - waiter.wait(1000); + waiter.wait(100); } //ASSERT diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java index 4d1e3b397..bc7d93160 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java @@ -107,13 +107,18 @@ class ContactServiceTest { String listenerID = iMap.addEntryListener((EntryUpdatedListener) entryEvent -> { System.out.println("Checking If removed.."); + try { + waiter.wait(100); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } synchronized (waiter) { waiter.notify(); } }, false); synchronized (waiter) { - waiter.wait(1000); + waiter.wait(100); } //ASSERT From 97899ebff623f6001a4df457b118e7da816f214b Mon Sep 17 00:00:00 2001 From: aalehin Date: Tue, 20 Sep 2022 14:22:58 +0300 Subject: [PATCH 23/33] test --- .../account/service/BankAccountServiceTest.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java index 47c48f898..5638b8213 100644 --- a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java +++ b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java @@ -53,6 +53,19 @@ public class BankAccountServiceTest { mockConsumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); } + /** + * {@link BankAccountService#bankAccountNew(BaseRequest request)} + * Тест проверяет генерацию сущности {@link BankAccount} в Hazelcast при передаче в Apache Kafka. + * Входной запрос {@link BankAccountNewRequest}: + * {@link BankAccountNewRequest#bankIdentificationCode} - 99999 + * {@link BankAccountNewRequest#bankName} - ооо тинькофф + * {@link BankAccountNewRequest#correspondentAccount} - 9294189285498598598 + * {@link BankAccountNewRequest#correspondentAccountName} - BIK OF + * {@link BankAccountNewRequest#currency} - RUB + * {@link BankAccountNewRequest#destination} - OOO ROGA + * {@link BankAccountNewRequest#taxpayerIdentificationNumber} - 848484848484 + * {@link BankAccountNewRequest#taxRegistrationReasonCode} - 886886 + */ @Test public void bankAccountNew() throws InterruptedException { //arrange From 1eac98cf703dc6fdd0feae671b9831333292b734 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Tue, 20 Sep 2022 16:32:07 +0300 Subject: [PATCH 24/33] http://git.mfd.msk/mfd/clearing/issues/6 --- refactoring tests for adding java doc --- .../service/BankAccountServiceTest.java | 25 +++++++++++++++++-- .../ClearingMemberCategoryServiceTest.java | 13 ++++++++++ .../service/CompanyInfoServiceTest.java | 18 +++++++++++++ .../company/service/CompanyServiceTest.java | 6 +++++ .../service/CompanySymbolServiceTest.java | 9 +++++++ .../company/service/ContactServiceTest.java | 9 +++++++ 6 files changed, 78 insertions(+), 2 deletions(-) diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java index 5638b8213..4614bf02a 100644 --- a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java +++ b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java @@ -55,16 +55,17 @@ public class BankAccountServiceTest { /** * {@link BankAccountService#bankAccountNew(BaseRequest request)} - * Тест проверяет генерацию сущности {@link BankAccount} в Hazelcast при передаче в Apache Kafka. + * Тест проверяет генерацию сущности {@link BankAccount} в Hazelcast при передаче из Apache Kafka. * Входной запрос {@link BankAccountNewRequest}: * {@link BankAccountNewRequest#bankIdentificationCode} - 99999 * {@link BankAccountNewRequest#bankName} - ооо тинькофф * {@link BankAccountNewRequest#correspondentAccount} - 9294189285498598598 * {@link BankAccountNewRequest#correspondentAccountName} - BIK OF * {@link BankAccountNewRequest#currency} - RUB - * {@link BankAccountNewRequest#destination} - OOO ROGA + * {@link BankAccountNewRequest#destination} - OOO ROGA I KOPITA * {@link BankAccountNewRequest#taxpayerIdentificationNumber} - 848484848484 * {@link BankAccountNewRequest#taxRegistrationReasonCode} - 886886 + * {@link BankAccountNewRequest#account} - 123456789123 */ @Test public void bankAccountNew() throws InterruptedException { @@ -134,6 +135,20 @@ public class BankAccountServiceTest { currentId++; } + /** + * {@link BankAccountService#bankAccountUpdate(BaseRequest)} + * Тест проверяет обновление сущности {@link BankAccount} в Hazelcast при передаче из Apache Kafka. + * Входной запрос {@link BankAccountUpdateRequest}: + * {@link BankAccountUpdateRequest#bankIdentificationCode} - NEW BUNK NAME + * {@link BankAccountUpdateRequest#bankName} - 88888 + * {@link BankAccountUpdateRequest#correspondentAccount} - 894984646541316 + * {@link BankAccountUpdateRequest#correspondentAccountName} - BIK OF NEW BUNK + * {@link BankAccountUpdateRequest#currency} - EU + * {@link BankAccountUpdateRequest#destination} - OOO NEW BUNK + * {@link BankAccountUpdateRequest#taxpayerIdentificationNumber} - 65468461321 + * {@link BankAccountUpdateRequest#taxRegistrationReasonCode} - 532137 + * {@link BankAccountUpdateRequest#account} - 326984656514 + */ @Test void bankAccountUpdate() throws InterruptedException { //arrange @@ -233,6 +248,12 @@ public class BankAccountServiceTest { currentId++; } + /** + * {@link BankAccountService#bankAccountDelete(BaseRequest)} + * Тест проверяет удаление сущности {@link BankAccount} в Hazelcast при передаче из Apache Kafka. + * Входной запрос {@link CommonDeleteRequest}: + * {@link CommonDeleteRequest#id} - Идентификатор записи + */ @Test void bankAccountDelete() throws InterruptedException { //arrange diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java index 6fb3d09e9..d5592644c 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java @@ -55,6 +55,13 @@ class ClearingMemberCategoryServiceTest { mockConsumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); } + /** + * {@link ClearingMemberCategoryService#clearingMemberCategoryUpdate(BaseRequest)} + * Тест проверяет обновление сущности {@link ClearingMemberCategory} в Hazelcast при передаче из Apache Kafka. + * Входной запрос {@link ClearingMemberCategoryUpdateRequest}: + * {@link ClearingMemberCategoryUpdateRequest#id} - Идентификатор записи + * {@link ClearingMemberCategoryUpdateRequest#clearingMemberCategory} - 1234 + */ @Test void clearingMemberCategoryUpdate() throws InterruptedException { //ARRANGE @@ -128,6 +135,12 @@ class ClearingMemberCategoryServiceTest { iMap.removeEntryListener(listenerID); } + /** + * {@link ClearingMemberCategoryService#clearingMemberCategoryDelete(BaseRequest)} + * Тест проверяет удаление сущности {@link ClearingMemberCategory} в Hazelcast при передаче из Apache Kafka. + * Входной запрос {@link CommonDeleteRequest}: + * {@link CommonDeleteRequest#id} - Идентификатор записи + */ @Test void clearingMemberCategoryDelete() throws InterruptedException { //ARRANGE diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java index 83c3e92e7..1bab878e4 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java @@ -51,6 +51,24 @@ class CompanyInfoServiceTest { mockConsumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); } + /** + * {@link CompanyInfoService#companyInfoUpdate(BaseRequest)} + * Тест проверяет обновление сущности {@link CompanyInfo} в Hazelcast при передаче из Apache Kafka. + * Входной запрос {@link CompanyInfoUpdateRequest}: + * {@link CompanyInfoUpdateRequest#id} - Идентификатор записи + * {@link CompanyInfoUpdateRequest#corporationSoleType} - 1234 + * {@link CompanyInfoUpdateRequest#countryCode} - 1234 + * {@link CompanyInfoUpdateRequest#description} - updated description + * {@link CompanyInfoUpdateRequest#professionalSign} - 1234 + * {@link CompanyInfoUpdateRequest#legalKind} - 1234 + * {@link CompanyInfoUpdateRequest#organizationType} - 1234 + * {@link CompanyInfoUpdateRequest#residence} - 1234 + * {@link CompanyInfoUpdateRequest#shortNameEng} - updated shortNameEng + * {@link CompanyInfoUpdateRequest#fullNameEng} - updated fullNameEng + * {@link CompanyInfoUpdateRequest#shortName} - updated shortName + * {@link CompanyInfoUpdateRequest#fullName} - updated fullName + * {@link CompanyInfoUpdateRequest#} - + */ @Test void companyInfoUpdate() throws InterruptedException { //ARRANGE diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java index f9b9f73aa..88e7b3c0d 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java @@ -53,6 +53,12 @@ class CompanyServiceTest { mockConsumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); } + /** + * {@link CompanyService#deleteCompany(BaseRequest)} + * Тест проверяет удаление сущности {@link Company} в Hazelcast при передаче из Apache Kafka. + * Входной запрос {@link CommonDeleteRequest}: + * {@link CommonDeleteRequest#id} - Идентификатор записи + */ @Test void deleteCompany() throws InterruptedException { //ARRANGE diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java index 15654ba28..d77c5e583 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java @@ -51,6 +51,15 @@ class CompanySymbolServiceTest { mockConsumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); } + /** + * {@link CompanySymbolService#companySymbolUpdate(BaseRequest)} + * Тест проверяет обновление сущности {@link CompanySymbols} в Hazelcast при передаче из Apache Kafka. + * Входной запрос {@link CompanySymbolUpdateRequest}: + * {@link CompanySymbolUpdateRequest#id} - Идентификатор записи + * {@link CompanySymbolUpdateRequest#companyId} - Идентификатор записи + * {@link CompanySymbolUpdateRequest#companySymbol} - 1234 + * {@link CompanySymbolUpdateRequest#companySymbolValue} - new companySymbolValue + */ @Test void companySymbolUpdate() throws InterruptedException { //ARRANGE diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java index bc7d93160..28cc138b7 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java @@ -50,6 +50,15 @@ class ContactServiceTest { mockConsumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); } + /** + * {@link ContactService#contactUpdate(BaseRequest)} + * Тест проверяет обновление сущности {@link Contact} в Hazelcast при передаче из Apache Kafka. + * Входной запрос {@link ContactUpdateRequest}: + * {@link ContactUpdateRequest#id} - Идентификатор записи + * {@link ContactUpdateRequest#companyId} - Идентификатор записи + * {@link ContactUpdateRequest#contactType} - 1234 + * {@link ContactUpdateRequest#contactValue} - new ContactValue + */ @Test void contactUpdate() throws InterruptedException { //ARRANGE From 664b6c66c212a845e92a9f39b89af897c9c95d03 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Tue, 20 Sep 2022 16:39:14 +0300 Subject: [PATCH 25/33] http://git.mfd.msk/mfd/clearing/issues/6 --- refactoring java doc tests --- .../service/BankAccountServiceTest.java | 48 +++++++++---------- .../ClearingMemberCategoryServiceTest.java | 18 +++---- .../service/CompanyInfoServiceTest.java | 31 ++++++------ .../company/service/CompanyServiceTest.java | 8 ++-- .../service/CompanySymbolServiceTest.java | 14 +++--- .../company/service/ContactServiceTest.java | 14 +++--- 6 files changed, 66 insertions(+), 67 deletions(-) diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java index 4614bf02a..cbc7952d1 100644 --- a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java +++ b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java @@ -54,18 +54,18 @@ public class BankAccountServiceTest { } /** - * {@link BankAccountService#bankAccountNew(BaseRequest request)} - * Тест проверяет генерацию сущности {@link BankAccount} в Hazelcast при передаче из Apache Kafka. - * Входной запрос {@link BankAccountNewRequest}: - * {@link BankAccountNewRequest#bankIdentificationCode} - 99999 - * {@link BankAccountNewRequest#bankName} - ооо тинькофф - * {@link BankAccountNewRequest#correspondentAccount} - 9294189285498598598 - * {@link BankAccountNewRequest#correspondentAccountName} - BIK OF - * {@link BankAccountNewRequest#currency} - RUB - * {@link BankAccountNewRequest#destination} - OOO ROGA I KOPITA - * {@link BankAccountNewRequest#taxpayerIdentificationNumber} - 848484848484 - * {@link BankAccountNewRequest#taxRegistrationReasonCode} - 886886 - * {@link BankAccountNewRequest#account} - 123456789123 + * {@link BankAccountService#bankAccountNew(BaseRequest request)}
+ * Тест проверяет генерацию сущности {@link BankAccount} в Hazelcast при передаче из Apache Kafka.
+ * Входной запрос {@link BankAccountNewRequest}:
+ * {@link BankAccountNewRequest#bankIdentificationCode} - 99999
+ * {@link BankAccountNewRequest#bankName} - ооо тинькофф
+ * {@link BankAccountNewRequest#correspondentAccount} - 9294189285498598598
+ * {@link BankAccountNewRequest#correspondentAccountName} - BIK OF
+ * {@link BankAccountNewRequest#currency} - RUB
+ * {@link BankAccountNewRequest#destination} - OOO ROGA I KOPITA
+ * {@link BankAccountNewRequest#taxpayerIdentificationNumber} - 848484848484
+ * {@link BankAccountNewRequest#taxRegistrationReasonCode} - 886886
+ * {@link BankAccountNewRequest#account} - 123456789123
*/ @Test public void bankAccountNew() throws InterruptedException { @@ -136,18 +136,18 @@ public class BankAccountServiceTest { } /** - * {@link BankAccountService#bankAccountUpdate(BaseRequest)} - * Тест проверяет обновление сущности {@link BankAccount} в Hazelcast при передаче из Apache Kafka. - * Входной запрос {@link BankAccountUpdateRequest}: - * {@link BankAccountUpdateRequest#bankIdentificationCode} - NEW BUNK NAME - * {@link BankAccountUpdateRequest#bankName} - 88888 - * {@link BankAccountUpdateRequest#correspondentAccount} - 894984646541316 - * {@link BankAccountUpdateRequest#correspondentAccountName} - BIK OF NEW BUNK - * {@link BankAccountUpdateRequest#currency} - EU - * {@link BankAccountUpdateRequest#destination} - OOO NEW BUNK - * {@link BankAccountUpdateRequest#taxpayerIdentificationNumber} - 65468461321 - * {@link BankAccountUpdateRequest#taxRegistrationReasonCode} - 532137 - * {@link BankAccountUpdateRequest#account} - 326984656514 + * {@link BankAccountService#bankAccountUpdate(BaseRequest)}
+ * Тест проверяет обновление сущности {@link BankAccount} в Hazelcast при передаче из Apache Kafka.
+ * Входной запрос {@link BankAccountUpdateRequest}:
+ * {@link BankAccountUpdateRequest#bankIdentificationCode} - NEW BUNK NAME
+ * {@link BankAccountUpdateRequest#bankName} - 88888
+ * {@link BankAccountUpdateRequest#correspondentAccount} - 894984646541316
+ * {@link BankAccountUpdateRequest#correspondentAccountName} - BIK OF NEW BUNK
+ * {@link BankAccountUpdateRequest#currency} - EU
+ * {@link BankAccountUpdateRequest#destination} - OOO NEW BUNK
+ * {@link BankAccountUpdateRequest#taxpayerIdentificationNumber} - 65468461321
+ * {@link BankAccountUpdateRequest#taxRegistrationReasonCode} - 532137
+ * {@link BankAccountUpdateRequest#account} - 326984656514
*/ @Test void bankAccountUpdate() throws InterruptedException { diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java index d5592644c..fed259cb8 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ClearingMemberCategoryServiceTest.java @@ -56,11 +56,11 @@ class ClearingMemberCategoryServiceTest { } /** - * {@link ClearingMemberCategoryService#clearingMemberCategoryUpdate(BaseRequest)} - * Тест проверяет обновление сущности {@link ClearingMemberCategory} в Hazelcast при передаче из Apache Kafka. - * Входной запрос {@link ClearingMemberCategoryUpdateRequest}: - * {@link ClearingMemberCategoryUpdateRequest#id} - Идентификатор записи - * {@link ClearingMemberCategoryUpdateRequest#clearingMemberCategory} - 1234 + * {@link ClearingMemberCategoryService#clearingMemberCategoryUpdate(BaseRequest)}
+ * Тест проверяет обновление сущности {@link ClearingMemberCategory} в Hazelcast при передаче из Apache Kafka.
+ * Входной запрос {@link ClearingMemberCategoryUpdateRequest}:
+ * {@link ClearingMemberCategoryUpdateRequest#id} - Идентификатор записи
+ * {@link ClearingMemberCategoryUpdateRequest#clearingMemberCategory} - 1234
*/ @Test void clearingMemberCategoryUpdate() throws InterruptedException { @@ -136,10 +136,10 @@ class ClearingMemberCategoryServiceTest { } /** - * {@link ClearingMemberCategoryService#clearingMemberCategoryDelete(BaseRequest)} - * Тест проверяет удаление сущности {@link ClearingMemberCategory} в Hazelcast при передаче из Apache Kafka. - * Входной запрос {@link CommonDeleteRequest}: - * {@link CommonDeleteRequest#id} - Идентификатор записи + * {@link ClearingMemberCategoryService#clearingMemberCategoryDelete(BaseRequest)}
+ * Тест проверяет удаление сущности {@link ClearingMemberCategory} в Hazelcast при передаче из Apache Kafka.
+ * Входной запрос {@link CommonDeleteRequest}:
+ * {@link CommonDeleteRequest#id} - Идентификатор записи
*/ @Test void clearingMemberCategoryDelete() throws InterruptedException { diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java index 1bab878e4..e88dedc01 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyInfoServiceTest.java @@ -52,22 +52,21 @@ class CompanyInfoServiceTest { } /** - * {@link CompanyInfoService#companyInfoUpdate(BaseRequest)} - * Тест проверяет обновление сущности {@link CompanyInfo} в Hazelcast при передаче из Apache Kafka. - * Входной запрос {@link CompanyInfoUpdateRequest}: - * {@link CompanyInfoUpdateRequest#id} - Идентификатор записи - * {@link CompanyInfoUpdateRequest#corporationSoleType} - 1234 - * {@link CompanyInfoUpdateRequest#countryCode} - 1234 - * {@link CompanyInfoUpdateRequest#description} - updated description - * {@link CompanyInfoUpdateRequest#professionalSign} - 1234 - * {@link CompanyInfoUpdateRequest#legalKind} - 1234 - * {@link CompanyInfoUpdateRequest#organizationType} - 1234 - * {@link CompanyInfoUpdateRequest#residence} - 1234 - * {@link CompanyInfoUpdateRequest#shortNameEng} - updated shortNameEng - * {@link CompanyInfoUpdateRequest#fullNameEng} - updated fullNameEng - * {@link CompanyInfoUpdateRequest#shortName} - updated shortName - * {@link CompanyInfoUpdateRequest#fullName} - updated fullName - * {@link CompanyInfoUpdateRequest#} - + * {@link CompanyInfoService#companyInfoUpdate(BaseRequest)}
+ * Тест проверяет обновление сущности {@link CompanyInfo} в Hazelcast при передаче из Apache Kafka.
+ * Входной запрос {@link CompanyInfoUpdateRequest}:
+ * {@link CompanyInfoUpdateRequest#id} - Идентификатор записи
+ * {@link CompanyInfoUpdateRequest#corporationSoleType} - 1234
+ * {@link CompanyInfoUpdateRequest#countryCode} - 1234
+ * {@link CompanyInfoUpdateRequest#description} - updated description
+ * {@link CompanyInfoUpdateRequest#professionalSign} - 1234
+ * {@link CompanyInfoUpdateRequest#legalKind} - 1234
+ * {@link CompanyInfoUpdateRequest#organizationType} - 1234
+ * {@link CompanyInfoUpdateRequest#residence} - 1234
+ * {@link CompanyInfoUpdateRequest#shortNameEng} - updated shortNameEng
+ * {@link CompanyInfoUpdateRequest#fullNameEng} - updated fullNameEng
+ * {@link CompanyInfoUpdateRequest#shortName} - updated shortName
+ * {@link CompanyInfoUpdateRequest#fullName} - updated fullName
*/ @Test void companyInfoUpdate() throws InterruptedException { diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java index 88e7b3c0d..b0c93177e 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanyServiceTest.java @@ -54,10 +54,10 @@ class CompanyServiceTest { } /** - * {@link CompanyService#deleteCompany(BaseRequest)} - * Тест проверяет удаление сущности {@link Company} в Hazelcast при передаче из Apache Kafka. - * Входной запрос {@link CommonDeleteRequest}: - * {@link CommonDeleteRequest#id} - Идентификатор записи + * {@link CompanyService#deleteCompany(BaseRequest)}
+ * Тест проверяет удаление сущности {@link Company} в Hazelcast при передаче из Apache Kafka.
+ * Входной запрос {@link CommonDeleteRequest}:
+ * {@link CommonDeleteRequest#id} - Идентификатор записи
*/ @Test void deleteCompany() throws InterruptedException { diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java index d77c5e583..b070b41f2 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/CompanySymbolServiceTest.java @@ -52,13 +52,13 @@ class CompanySymbolServiceTest { } /** - * {@link CompanySymbolService#companySymbolUpdate(BaseRequest)} - * Тест проверяет обновление сущности {@link CompanySymbols} в Hazelcast при передаче из Apache Kafka. - * Входной запрос {@link CompanySymbolUpdateRequest}: - * {@link CompanySymbolUpdateRequest#id} - Идентификатор записи - * {@link CompanySymbolUpdateRequest#companyId} - Идентификатор записи - * {@link CompanySymbolUpdateRequest#companySymbol} - 1234 - * {@link CompanySymbolUpdateRequest#companySymbolValue} - new companySymbolValue + * {@link CompanySymbolService#companySymbolUpdate(BaseRequest)}
+ * Тест проверяет обновление сущности {@link CompanySymbols} в Hazelcast при передаче из Apache Kafka.
+ * Входной запрос {@link CompanySymbolUpdateRequest}:
+ * {@link CompanySymbolUpdateRequest#id} - Идентификатор записи
+ * {@link CompanySymbolUpdateRequest#companyId} - Идентификатор записи
+ * {@link CompanySymbolUpdateRequest#companySymbol} - 1234
+ * {@link CompanySymbolUpdateRequest#companySymbolValue} - new companySymbolValue
*/ @Test void companySymbolUpdate() throws InterruptedException { diff --git a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java index 28cc138b7..55ed50790 100644 --- a/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java +++ b/clearing-parent/company-service/src/test/java/ru/spcex/clearing/company/service/ContactServiceTest.java @@ -51,13 +51,13 @@ class ContactServiceTest { } /** - * {@link ContactService#contactUpdate(BaseRequest)} - * Тест проверяет обновление сущности {@link Contact} в Hazelcast при передаче из Apache Kafka. - * Входной запрос {@link ContactUpdateRequest}: - * {@link ContactUpdateRequest#id} - Идентификатор записи - * {@link ContactUpdateRequest#companyId} - Идентификатор записи - * {@link ContactUpdateRequest#contactType} - 1234 - * {@link ContactUpdateRequest#contactValue} - new ContactValue + * {@link ContactService#contactUpdate(BaseRequest)}
+ * Тест проверяет обновление сущности {@link Contact} в Hazelcast при передаче из Apache Kafka.
+ * Входной запрос {@link ContactUpdateRequest}:
+ * {@link ContactUpdateRequest#id} - Идентификатор записи
+ * {@link ContactUpdateRequest#companyId} - Идентификатор записи
+ * {@link ContactUpdateRequest#contactType} - 1234
+ * {@link ContactUpdateRequest#contactValue} - new ContactValue
*/ @Test void contactUpdate() throws InterruptedException { From f98e58a2bd87c9e18d4099322e6fff502eb5b0d4 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Wed, 21 Sep 2022 15:33:05 +0300 Subject: [PATCH 26/33] http://git.mfd.msk/mfd/clearing/issues/6 --- fixing generate java doc for app --- .../clearing/imdg/base/TemplateMapStore.java | 5 +++-- .../platform/utils/enumeration/IEnumId.java | 14 +++++++------- pom.xml | 19 +++++++++++++++---- 3 files changed, 25 insertions(+), 13 deletions(-) diff --git a/clearing-parent/imdg/src/main/java/ru/spcex/clearing/imdg/base/TemplateMapStore.java b/clearing-parent/imdg/src/main/java/ru/spcex/clearing/imdg/base/TemplateMapStore.java index dd47bd4fe..de4d5204b 100644 --- a/clearing-parent/imdg/src/main/java/ru/spcex/clearing/imdg/base/TemplateMapStore.java +++ b/clearing-parent/imdg/src/main/java/ru/spcex/clearing/imdg/base/TemplateMapStore.java @@ -9,7 +9,6 @@ import java.util.*; /** * MapStore для шаблонных бизнес-объектов - * @Component */ public abstract class TemplateMapStore extends ObjectBaseMapStore implements AutoconfiguredMap { @@ -22,13 +21,13 @@ public abstract class TemplateMapStore extends Object } /** - * * @return IMDGDistributedNames.* */ public abstract String getMapName(); /** * Список индексируемых полей, для быстрого поиска + * * @return */ public String[] getIndexingField() { @@ -37,6 +36,7 @@ public abstract class TemplateMapStore extends Object /** * Десериализатор + * * @param resultSet * @return */ @@ -51,6 +51,7 @@ public abstract class TemplateMapStore extends Object /** * Сериализатор + * * @param resultSet * @return Object[] args */ diff --git a/platform-parent/platform-utils/src/main/java/ru/spcex/platform/utils/enumeration/IEnumId.java b/platform-parent/platform-utils/src/main/java/ru/spcex/platform/utils/enumeration/IEnumId.java index a45b3c628..10859b6a4 100644 --- a/platform-parent/platform-utils/src/main/java/ru/spcex/platform/utils/enumeration/IEnumId.java +++ b/platform-parent/platform-utils/src/main/java/ru/spcex/platform/utils/enumeration/IEnumId.java @@ -4,11 +4,7 @@ import java.io.Serializable; import java.util.Objects; public interface IEnumId extends Serializable { - Long getId(); - - default boolean equalsById(Long id) { - return id != null && getId().equals(id); - } + Long UNDEFINED_VALUE = Long.MIN_VALUE; /** * Проверяет что среди данного набора Enum, присутствует элемент с данным id @@ -46,7 +42,7 @@ public interface IEnumId extends Serializable { * Возвращает Enum по id, если в заданном классе такой определен * id может быть null * - * @return Enum если нашел, иначе null + * @return Enum если нашел, иначе null */ static & IEnumId> T getEnumById(Class enumClass, Long id) { for (T e : enumClass.getEnumConstants()) { @@ -60,5 +56,9 @@ public interface IEnumId extends Serializable { return enumVal == null ? null : enumVal.getId(); } - Long UNDEFINED_VALUE = Long.MIN_VALUE; + Long getId(); + + default boolean equalsById(Long id) { + return id != null && getId().equals(id); + } } diff --git a/pom.xml b/pom.xml index a70f4b92f..07514166d 100644 --- a/pom.xml +++ b/pom.xml @@ -1,6 +1,6 @@ - 4.0.0 @@ -30,8 +30,10 @@ ${folder_root_clearing_temp} - ${folder_root_clearing}/clearing-parent/backend-api - ${folder_root_clearing}/clearing-parent/securities-service + ${folder_root_clearing}/clearing-parent/backend-api + + ${folder_root_clearing}/clearing-parent/securities-service + ${folder_root_clearing}/clearing-parent/imdg ${folder_root_clearing}/clearing-parent/dbf-exporter ${folder_root_clearing}/clearing-parent/dbf-importer @@ -285,6 +287,15 @@ + + org.apache.maven.plugins + maven-javadoc-plugin + + private + true + + + \ No newline at end of file From a1bccea45a8a743e1d64b8e5f3ba4aea5f5f0275 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Wed, 21 Sep 2022 15:39:41 +0300 Subject: [PATCH 27/33] http://git.mfd.msk/mfd/clearing/issues/6 --- fixing bug --- pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/pom.xml b/pom.xml index 07514166d..fbdb4e6e8 100644 --- a/pom.xml +++ b/pom.xml @@ -293,7 +293,6 @@ private true - From ad7c38f0bb79d7e885fcf9934c26df9d38996e19 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Thu, 22 Sep 2022 19:30:11 +0300 Subject: [PATCH 28/33] --- added test class --- .../service/BankAccountServiceTest.java | 2 +- clearing-parent/backend-api/pom.xml | 49 +++++++---- .../account/BankAccountControllerTest.java | 72 ++++++++++++++++ .../config/Jackson2HttpConverterConfig.java | 39 +++++++++ .../controller/queue/utils/JsonUtil.java | 38 +++++++++ .../queue/utils/MatcherFactory.java | 82 +++++++++++++++++++ .../services/AbstractUpdateMapService.java | 10 +-- 7 files changed, 271 insertions(+), 21 deletions(-) create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/Jackson2HttpConverterConfig.java create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/JsonUtil.java create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/MatcherFactory.java diff --git a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java index cbc7952d1..027c1d3e6 100644 --- a/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java +++ b/clearing-parent/account-service/src/test/java/ru/spcex/clearing/account/service/BankAccountServiceTest.java @@ -36,7 +36,7 @@ import static ru.spcex.clearing.account.utils.MatcherFactory.usingIgnoringFields @ContextConfiguration(classes = { HazelcastServiceTestConfiguration.class}) public class BankAccountServiceTest { - public static final Matcher BANK_ACCOUNT_MATCHER = usingIgnoringFieldsComparator("id"); + public static final Matcher BANK_ACCOUNT_MATCHER = usingIgnoringFieldsComparator(); private static final int PARTITION = 0; private static final String TOPIC_ACCOUNT_NEW = Consts.DESTINATION_BANK_ACCOUNT_NEW; private static final String TOPIC_ACCOUNT_UPDATE = Consts.DESTINATION_BANK_ACCOUNT_UPDATE; diff --git a/clearing-parent/backend-api/pom.xml b/clearing-parent/backend-api/pom.xml index 18b29f7d1..96503e90f 100644 --- a/clearing-parent/backend-api/pom.xml +++ b/clearing-parent/backend-api/pom.xml @@ -1,6 +1,6 @@ - 4.0.0 backend-api @@ -8,12 +8,12 @@ Clearing backend API module jar - - clearing-parent + + clearing-parent ru.spcex.clearing SPCEX-1.0.0.0 - + 17.0.1 @@ -25,9 +25,9 @@ spring-boot-starter-web - org.springframework.boot - spring-boot-starter-security - + org.springframework.boot + spring-boot-starter-security + org.keycloak keycloak-spring-boot-starter @@ -53,17 +53,38 @@ ru.spcex.clearing classes + + + org.springframework + spring-test + test + + + org.mockito + mockito-core + + + org.junit.jupiter + junit-jupiter + test + + + org.assertj + assertj-core + test + + - org.keycloak.bom - keycloak-adapter-bom - ${keycloak-spring-boot-starter.version} - pom - import - + org.keycloak.bom + keycloak-adapter-bom + ${keycloak-spring-boot-starter.version} + pom + import + diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java new file mode 100644 index 000000000..4c4e2cc34 --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java @@ -0,0 +1,72 @@ +package ru.spcex.clearing.backendapi.controller.queue.account; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.filter.CharacterEncodingFilter; +import ru.spcex.clearing.backendapi.controller.queue.config.Jackson2HttpConverterConfig; +import ru.spcex.clearing.backendapi.controller.queue.utils.JsonUtil; +import ru.spcex.clearing.backendapi.controller.queue.utils.MatcherFactory; +import ru.spcex.clearing.backendapi.controller.request.cud.account.BankAccountNewAction; +import ru.spcex.clearing.backendapi.controller.response.cud.CudResponse; + +import javax.annotation.PostConstruct; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringJUnitWebConfig(classes = { + Jackson2HttpConverterConfig.class}) +class BankAccountControllerTest { + + public static final MatcherFactory.Matcher CUD_RESPONSE_MATCHER = MatcherFactory.usingIgnoringFieldsComparator(CudResponse.class); + private static final String REST_URL = "/securities/bank-accounts/"; + private static final CharacterEncodingFilter CHARACTER_ENCODING_FILTER = new CharacterEncodingFilter(); + + static { + CHARACTER_ENCODING_FILTER.setEncoding("UTF-8"); + CHARACTER_ENCODING_FILTER.setForceEncoding(true); + } + + @Autowired + public Environment env; + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext webApplicationContext; + + @PostConstruct + private void postConstruct() { + mockMvc = MockMvcBuilders + .webAppContextSetup(webApplicationContext) + .addFilter(CHARACTER_ENCODING_FILTER) +// .apply(springSecurity()) + .build(); + } + + @Test + void add() throws Exception { + BankAccountNewAction bankAccountNewAction = new BankAccountNewAction(); + ResultActions action = mockMvc.perform(MockMvcRequestBuilders.post(REST_URL) + .contentType(MediaType.APPLICATION_JSON) +// .with(userHttpBasic(admin)) + .content(JsonUtil.writeValue(bankAccountNewAction))) + .andExpect(status().isCreated()); + + CudResponse created = CUD_RESPONSE_MATCHER.readFromJson(action); + } + + @Test + void update() { + } + + @Test + void delete() { + } +} \ No newline at end of file diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/Jackson2HttpConverterConfig.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/Jackson2HttpConverterConfig.java new file mode 100644 index 000000000..c6d557d21 --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/Jackson2HttpConverterConfig.java @@ -0,0 +1,39 @@ +package ru.spcex.clearing.backendapi.controller.queue.config; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; + +@Configuration +public class Jackson2HttpConverterConfig { + @Bean("customJsonHttpConverter") + public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { + return new MappingJackson2HttpMessageConverter(JacksonObjectMapper.getMapper()); + } + + public static class JacksonObjectMapper extends ObjectMapper { + private static final ObjectMapper MAPPER = new JacksonObjectMapper(); + + 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 boolean isExcess() +// setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE); +// setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); +// не сериализуем null-поля +// setSerializationInclusion(JsonInclude.Include.NON_NULL); + } + + public static ObjectMapper getMapper() { + return MAPPER; + } + } +} \ No newline at end of file diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/JsonUtil.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/JsonUtil.java new file mode 100644 index 000000000..fb20fe457 --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/JsonUtil.java @@ -0,0 +1,38 @@ +package ru.spcex.clearing.backendapi.controller.queue.utils; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectReader; + +import java.io.IOException; +import java.util.List; + +import static ru.spcex.clearing.backendapi.controller.queue.config.Jackson2HttpConverterConfig.JacksonObjectMapper.getMapper; + +public class JsonUtil { + + public static List readValues(String json, Class clazz) { + ObjectReader reader = getMapper().readerFor(clazz); + try { + return reader.readValues(json).readAll(); + } catch (IOException e) { + throw new IllegalArgumentException("Invalid read array from JSON:\n'" + json + "'", e); + } + } + + public static T readValue(String json, Class clazz) { + try { + return getMapper().readValue(json, clazz); + } catch (IOException e) { + throw new IllegalArgumentException("Invalid read from JSON:\n'" + json + "'", e); + } + } + + public static String writeValue(T obj) { + try { + return getMapper().writeValueAsString(obj); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Invalid write to JSON:\n'" + obj + "'", e); + } + } + +} \ No newline at end of file diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/MatcherFactory.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/MatcherFactory.java new file mode 100644 index 000000000..1143b031a --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/MatcherFactory.java @@ -0,0 +1,82 @@ +package ru.spcex.clearing.backendapi.controller.queue.utils; + +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.ResultMatcher; + +import java.io.UnsupportedEncodingException; +import java.util.List; +import java.util.function.BiConsumer; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Factory for creating test matchers. + *

+ * Comparing actual and expected objects via AssertJ + * Support converting json MvcResult to objects for comparation. + */ +public class MatcherFactory { + + public static Matcher usingAssertions(Class clazz, BiConsumer assertion, BiConsumer, Iterable> iterableAssertion) { + return new Matcher<>(clazz, assertion, iterableAssertion); + } + + public static Matcher usingEqualsComparator(Class clazz) { + return usingAssertions(clazz, + (a, e) -> assertThat(a).isEqualTo(e), + (a, e) -> assertThat(a).isEqualTo(e)); + } + + public static Matcher usingIgnoringFieldsComparator(Class clazz, String... fieldsToIgnore) { + return usingAssertions(clazz, + (a, e) -> assertThat(a).usingRecursiveComparison().ignoringFields(fieldsToIgnore).isEqualTo(e), + (a, e) -> assertThat(a).usingRecursiveFieldByFieldElementComparatorIgnoringFields(fieldsToIgnore).isEqualTo(e)); + } + + public static class Matcher { + private final Class clazz; + private final BiConsumer assertion; + private final BiConsumer, Iterable> iterableAssertion; + + private Matcher(Class clazz, BiConsumer assertion, BiConsumer, Iterable> iterableAssertion) { + this.clazz = clazz; + this.assertion = assertion; + this.iterableAssertion = iterableAssertion; + } + + private static String getContent(MvcResult result) throws UnsupportedEncodingException { + return result.getResponse().getContentAsString(); + } + + public void assertMatch(T actual, T expected) { + assertion.accept(actual, expected); + } + + @SafeVarargs + public final void assertMatch(Iterable actual, T... expected) { + assertMatch(actual, List.of(expected)); + } + + public void assertMatch(Iterable actual, Iterable expected) { + iterableAssertion.accept(actual, expected); + } + + public ResultMatcher contentJson(T expected) { + return result -> assertMatch(JsonUtil.readValue(getContent(result), clazz), expected); + } + + @SafeVarargs + public final ResultMatcher contentJson(T... expected) { + return contentJson(List.of(expected)); + } + + public ResultMatcher contentJson(Iterable expected) { + return result -> assertMatch(JsonUtil.readValues(getContent(result), clazz), expected); + } + + public T readFromJson(ResultActions action) throws UnsupportedEncodingException { + return JsonUtil.readValue(getContent(action.andReturn()), clazz); + } + } +} diff --git a/clearing-parent/imdg/src/main/java/ru/spcex/clearing/imdg/services/AbstractUpdateMapService.java b/clearing-parent/imdg/src/main/java/ru/spcex/clearing/imdg/services/AbstractUpdateMapService.java index 24a5bc55b..f90e5ee06 100644 --- a/clearing-parent/imdg/src/main/java/ru/spcex/clearing/imdg/services/AbstractUpdateMapService.java +++ b/clearing-parent/imdg/src/main/java/ru/spcex/clearing/imdg/services/AbstractUpdateMapService.java @@ -15,13 +15,11 @@ import java.time.Instant; public abstract class AbstractUpdateMapService implements InitializingBean, EntryAddedListener, EntryUpdatedListener, EntryRemovedListener { - private final Logger log = LoggerFactory.getLogger(this.getClass()); - - protected final String EVENT_CREATE="CREATE"; - protected final String EVENT_UPDATE="UPDATE"; - protected final String EVENT_DELETE="DELETE"; - + protected final String EVENT_CREATE = "CREATE"; + protected final String EVENT_UPDATE = "UPDATE"; + protected final String EVENT_DELETE = "DELETE"; protected final HazelcastInstance hazelcastServerInstance; + private final Logger log = LoggerFactory.getLogger(this.getClass()); public AbstractUpdateMapService(HazelcastInstance hazelcastServerInstance) { this.hazelcastServerInstance = hazelcastServerInstance; From b63904f0e061a478c182ef8c92a35d98db3d00a0 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Fri, 23 Sep 2022 18:25:01 +0300 Subject: [PATCH 29/33] --- added test for method add --- clearing-parent/backend-api/pom.xml | 5 +- .../account/BankAccountControllerTest.java | 63 +++++++++++++---- .../config/BankAccountControllerConfig.java | 18 +++++ .../HazelcastServiceTestConfiguration.java | 68 +++++++++++++++++++ .../controller/queue/config/IOperator.java | 24 +++++++ .../config/Jackson2HttpConverterConfig.java | 8 ++- .../controller/queue/config/KafkaConfig.java | 18 +++++ .../controller/queue/utils/JsonUtil.java | 9 +++ 8 files changed, 196 insertions(+), 17 deletions(-) create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/HazelcastServiceTestConfiguration.java create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/IOperator.java create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/KafkaConfig.java diff --git a/clearing-parent/backend-api/pom.xml b/clearing-parent/backend-api/pom.xml index 96503e90f..0f9f3f647 100644 --- a/clearing-parent/backend-api/pom.xml +++ b/clearing-parent/backend-api/pom.xml @@ -60,8 +60,9 @@ test - org.mockito - mockito-core + org.skyscreamer + jsonassert + test org.junit.jupiter diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java index 4c4e2cc34..d89b18d34 100644 --- a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java @@ -2,26 +2,35 @@ package ru.spcex.clearing.backendapi.controller.queue.account; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.filter.CharacterEncodingFilter; -import ru.spcex.clearing.backendapi.controller.queue.config.Jackson2HttpConverterConfig; -import ru.spcex.clearing.backendapi.controller.queue.utils.JsonUtil; +import ru.spcex.clearing.backendapi.config.WebConfig; +import ru.spcex.clearing.backendapi.controller.queue.config.*; import ru.spcex.clearing.backendapi.controller.queue.utils.MatcherFactory; 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.platform.messaging.domain.ActionType; +import ru.spcex.clearing.platform.messaging.domain.cud.account.BankAccountNewRequest; import javax.annotation.PostConstruct; +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.queue.utils.JsonUtil.writeValue; @SpringJUnitWebConfig(classes = { + WebConfig.class, + IOperator.class, + BankAccountControllerConfig.class, + KafkaConfig.class, + HazelcastServiceTestConfiguration.class, Jackson2HttpConverterConfig.class}) class BankAccountControllerTest { @@ -34,8 +43,6 @@ class BankAccountControllerTest { CHARACTER_ENCODING_FILTER.setForceEncoding(true); } - @Autowired - public Environment env; private MockMvc mockMvc; @Autowired @@ -50,16 +57,48 @@ class BankAccountControllerTest { .build(); } + /** + * {@link BankAccountController#add(BankAccountNewAction)}
+ * Тест проверяет получение сущности {@link BankAccountNewAction} по REST API и отправку в Apache Kafka.
+ * Входной запрос {@link BankAccountNewRequest}:
+ * {@link BankAccountNewRequest#bankIdentificationCode} - 044525776
+ * {@link BankAccountNewRequest#bankName} - Beta Money Bank
+ * {@link BankAccountNewRequest#correspondentAccount} - 30101111111111111776
+ * {@link BankAccountNewRequest#correspondentAccountName} - correspondent
+ * {@link BankAccountNewRequest#currency} - RUB
+ * {@link BankAccountNewRequest#destination} - destination
+ * {@link BankAccountNewRequest#taxpayerIdentificationNumber} - 3664011397
+ * {@link BankAccountNewRequest#taxRegistrationReasonCode} - 01
+ * {@link BankAccountNewRequest#account} - 11111222223333344444
+ */ @Test void add() throws Exception { + //ARRANGE BankAccountNewAction bankAccountNewAction = new BankAccountNewAction(); - ResultActions action = mockMvc.perform(MockMvcRequestBuilders.post(REST_URL) - .contentType(MediaType.APPLICATION_JSON) -// .with(userHttpBasic(admin)) - .content(JsonUtil.writeValue(bankAccountNewAction))) - .andExpect(status().isCreated()); + bankAccountNewAction.setBankIdentificationCode("044525776"); + bankAccountNewAction.setBankName("Beta Money Bank"); + bankAccountNewAction.setCorrespondentAccount("30101111111111111776"); + bankAccountNewAction.setCorrespondentAccountName("correspondent"); + bankAccountNewAction.setCurrency("RUB"); + bankAccountNewAction.setDestination("destination"); + bankAccountNewAction.setTaxpayerIdentificationNumber("3664011397"); + bankAccountNewAction.setTaxRegistrationReasonCode("01"); + bankAccountNewAction.setAccount("11111222223333344444"); - CudResponse created = CUD_RESPONSE_MATCHER.readFromJson(action); + CudResponse extended = new CudResponse(); + extended.setCode(0L); + extended.setMessage("success"); + extended.setPayload(new QueueSuccessResponse(ActionType.NEW, 0L)); + + //ACT + mockMvc.perform(MockMvcRequestBuilders.post(REST_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(writeValue(bankAccountNewAction))) + .andDo(print())//output to the log request and response +// ASSERT + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(content().json(writeValue(extended))); } @Test diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java new file mode 100644 index 000000000..2f832f51b --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java @@ -0,0 +1,18 @@ +package ru.spcex.clearing.backendapi.controller.queue.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import ru.spcex.clearing.backendapi.controller.queue.account.BankAccountController; +import ru.spcex.clearing.backendapi.service.IOperator; + +@Configuration +public class BankAccountControllerConfig { + + @Autowired + @Bean + public BankAccountController createBankAccountController(IOperator operator) { + return new BankAccountController(operator); + } + +} diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/HazelcastServiceTestConfiguration.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/HazelcastServiceTestConfiguration.java new file mode 100644 index 000000000..04e64990d --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/HazelcastServiceTestConfiguration.java @@ -0,0 +1,68 @@ +package ru.spcex.clearing.backendapi.controller.queue.config; + +import com.hazelcast.config.*; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import ru.spcex.platform.imdg.iml.hazelcast.config.HazelcastClientParams; +import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService; +import ru.spcex.platform.imdg.iml.hazelcast.util.HazelcastHelper; + +import java.util.List; +import java.util.Random; + +@Configuration +public class HazelcastServiceTestConfiguration { + private HazelcastInstance hazelcastInstance; + + private static ThreadPoolTaskExecutor createThreadPoolTaskExecutor(int maxPoolSz, boolean waitForCompletion) { + ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor(); + if (maxPoolSz > 2) { + pool.setKeepAliveSeconds(60); + pool.setAllowCoreThreadTimeOut(true); + } + pool.setCorePoolSize(maxPoolSz); + pool.setWaitForTasksToCompleteOnShutdown(waitForCompletion); + return pool; + } + + @Bean(name = "hazelcastServiceTest") + public HazelcastService hazelcastService(@Qualifier("taskExecutorHazelcastClientInitializer") ThreadPoolTaskExecutor taskExecutorHazelcastClientInitializer, @Qualifier("taskExecutorIdGeneratorAwaiter") ThreadPoolTaskExecutor taskExecutorIdGeneratorAwaiter, HazelcastClientParams params) { + Config cfg = new Config(); + cfg.setInstanceName("localhost"); + + NetworkConfig networkConfig = new NetworkConfig(); + JoinConfig joinConfig = new JoinConfig(); + joinConfig.setMulticastConfig(new MulticastConfig().setEnabled(false)); + joinConfig.setTcpIpConfig(new TcpIpConfig().setEnabled(true).setMembers(List.of("127.0.0.1"))); + networkConfig.setJoin(joinConfig); + cfg.setNetworkConfig(networkConfig); + hazelcastInstance = Hazelcast.newHazelcastInstance(cfg); + HazelcastHelper.otcSystem_setStorageState(true, hazelcastInstance); + return new HazelcastService(taskExecutorHazelcastClientInitializer, taskExecutorIdGeneratorAwaiter, params); + } + + @Bean(name = "taskExecutorHazelcastClientInitializer") + public ThreadPoolTaskExecutor taskExecutorHazelcastClientInitializer() { + return createThreadPoolTaskExecutor(1, true); + } + + @Bean(name = "taskExecutorIdGeneratorAwaiter") + public ThreadPoolTaskExecutor taskExecutorIdGeneratorAwaiter() { + return createThreadPoolTaskExecutor(1, false); + } + + @Bean(name = "hazelcastClientParams") + public HazelcastClientParams getHazelcastClientParams() { + HazelcastClientParams params = new HazelcastClientParams(); + params.setLogin("dev"); + params.setPassword("dev-pass"); + params.setClusterMembers("127.0.0.1"); + params.setInstanceName("hzTestClient" + new Random().nextInt()); + params.setNearCacheConfig(new NearCacheConfig()); + return params; + } +} diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/IOperator.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/IOperator.java new file mode 100644 index 000000000..065785269 --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/IOperator.java @@ -0,0 +1,24 @@ +package ru.spcex.clearing.backendapi.controller.queue.config; + +import org.apache.kafka.clients.producer.Producer; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import ru.spcex.clearing.backendapi.service.impl.OperatorImpl; +import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService; + +@Configuration +public class IOperator { + + @Autowired + @Qualifier("hazelcastServiceTest") + private HazelcastService hazelcastServiceTest; + + @Autowired + @Bean + public OperatorImpl createIOperator(Producer kafka) { + return new OperatorImpl(kafka, hazelcastServiceTest); + } + +} diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/Jackson2HttpConverterConfig.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/Jackson2HttpConverterConfig.java index c6d557d21..a1f8c5bea 100644 --- a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/Jackson2HttpConverterConfig.java +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/Jackson2HttpConverterConfig.java @@ -1,5 +1,7 @@ package ru.spcex.clearing.backendapi.controller.queue.config; +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 org.springframework.context.annotation.Bean; @@ -25,9 +27,9 @@ public class Jackson2HttpConverterConfig { // registerModule(new JavaTimeModule()); // configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); -// запрещаем доступ ко всем полям и методам класса и потом разрешаем доступ только к полям, нужны чтобы не было лишних полей из-за методов как: public boolean isExcess() -// setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE); -// setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); +// запрещаем доступ ко всем полям и методам класса и потом разрешаем доступ только к полям, нужны чтобы не было лишних полей из-за методов как: public ActionType getActionType() у BankAccountNewAction + setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE); + setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); // не сериализуем null-поля // setSerializationInclusion(JsonInclude.Include.NON_NULL); } diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/KafkaConfig.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/KafkaConfig.java new file mode 100644 index 000000000..e8c020252 --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/KafkaConfig.java @@ -0,0 +1,18 @@ +package ru.spcex.clearing.backendapi.controller.queue.config; + +import org.apache.kafka.clients.producer.MockProducer; +import org.apache.kafka.clients.producer.Producer; +import org.apache.kafka.common.serialization.StringSerializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import ru.spcex.clearing.platform.messaging.serialization.JsonSerializer; + +@Configuration +public class KafkaConfig { + + @Bean + public Producer createProducer() { + return new MockProducer<>(true, new StringSerializer(), new JsonSerializer()); + } + +} diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/JsonUtil.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/JsonUtil.java index fb20fe457..2780f9465 100644 --- a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/JsonUtil.java +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/utils/JsonUtil.java @@ -1,10 +1,13 @@ package ru.spcex.clearing.backendapi.controller.queue.utils; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectReader; import java.io.IOException; import java.util.List; +import java.util.Map; +import java.util.Set; import static ru.spcex.clearing.backendapi.controller.queue.config.Jackson2HttpConverterConfig.JacksonObjectMapper.getMapper; @@ -35,4 +38,10 @@ public class JsonUtil { } } + public static String writeIgnoreProps(T obj, String... ignoreProps) { + Map map = getMapper().convertValue(obj, new TypeReference<>() { + }); + map.keySet().removeAll(Set.of(ignoreProps)); + return writeValue(map); + } } \ No newline at end of file From 9d1fc630a4da8a72d50aa578641eb2f247acfae7 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Mon, 26 Sep 2022 14:00:34 +0300 Subject: [PATCH 30/33] http://git.mfd.msk/mfd/clearing/issues/7 --- added test for BankAccountController with validation test for add method. For methods update and delete didn't do the check validation empty id because without id REST request for path "/securities/bank-accounts/" not work. --- .../account/BankAccountControllerTest.java | 162 ++++++++++++++++-- 1 file changed, 148 insertions(+), 14 deletions(-) diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java index d89b18d34..e0705f548 100644 --- a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java @@ -2,6 +2,7 @@ package ru.spcex.clearing.backendapi.controller.queue.account; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.NestedExceptionUtils; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; import org.springframework.test.web.servlet.MockMvc; @@ -13,13 +14,18 @@ import ru.spcex.clearing.backendapi.config.WebConfig; import ru.spcex.clearing.backendapi.controller.queue.config.*; import ru.spcex.clearing.backendapi.controller.queue.utils.MatcherFactory; import ru.spcex.clearing.backendapi.controller.request.cud.account.BankAccountNewAction; +import ru.spcex.clearing.backendapi.controller.request.cud.account.BankAccountUpdateAction; import ru.spcex.clearing.backendapi.controller.response.cud.CudResponse; import ru.spcex.clearing.backendapi.controller.response.cud.QueueSuccessResponse; +import ru.spcex.clearing.backendapi.domain.actions.IAction; +import ru.spcex.clearing.backendapi.errors.ActionValidationException; import ru.spcex.clearing.platform.messaging.domain.ActionType; import ru.spcex.clearing.platform.messaging.domain.cud.account.BankAccountNewRequest; import javax.annotation.PostConstruct; +import java.util.concurrent.atomic.AtomicLong; +import static org.junit.jupiter.api.Assertions.assertThrows; 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; @@ -37,6 +43,7 @@ class BankAccountControllerTest { public static final MatcherFactory.Matcher CUD_RESPONSE_MATCHER = MatcherFactory.usingIgnoringFieldsComparator(CudResponse.class); private static final String REST_URL = "/securities/bank-accounts/"; private static final CharacterEncodingFilter CHARACTER_ENCODING_FILTER = new CharacterEncodingFilter(); + private static final AtomicLong currentId = new AtomicLong(); static { CHARACTER_ENCODING_FILTER.setEncoding("UTF-8"); @@ -74,22 +81,21 @@ class BankAccountControllerTest { @Test void add() throws Exception { //ARRANGE - BankAccountNewAction bankAccountNewAction = new BankAccountNewAction(); - bankAccountNewAction.setBankIdentificationCode("044525776"); - bankAccountNewAction.setBankName("Beta Money Bank"); - bankAccountNewAction.setCorrespondentAccount("30101111111111111776"); - bankAccountNewAction.setCorrespondentAccountName("correspondent"); - bankAccountNewAction.setCurrency("RUB"); - bankAccountNewAction.setDestination("destination"); - bankAccountNewAction.setTaxpayerIdentificationNumber("3664011397"); - bankAccountNewAction.setTaxRegistrationReasonCode("01"); - bankAccountNewAction.setAccount("11111222223333344444"); + BankAccountNewAction bankAccountNewAction = getBankAccountNewAction( + "044525776", + "Beta Money Bank", + "30101111111111111776", + "correspondent", + "RUB", + "destination", + "3664011397", + "01", + "11111222223333344444"); CudResponse extended = new CudResponse(); extended.setCode(0L); extended.setMessage("success"); - extended.setPayload(new QueueSuccessResponse(ActionType.NEW, 0L)); - + extended.setPayload(new QueueSuccessResponse(ActionType.NEW, currentId.getAndIncrement())); //ACT mockMvc.perform(MockMvcRequestBuilders.post(REST_URL) .contentType(MediaType.APPLICATION_JSON) @@ -101,11 +107,139 @@ class BankAccountControllerTest { .andExpect(content().json(writeValue(extended))); } + /** + * {@link BankAccountController#add(BankAccountNewAction)}
+ * Тест проверяет работу валидации сущности {@link BankAccountNewAction} принятой по REST API для отправку в Apache Kafka.
+ * Входной запрос {@link BankAccountNewRequest}:
+ * {@link BankAccountNewRequest#bankIdentificationCode} - 044525776 или ""
+ * {@link BankAccountNewRequest#bankName} - Beta Money Bank или ""
+ * {@link BankAccountNewRequest#correspondentAccount} - 30101111111111111776 или ""
+ * {@link BankAccountNewRequest#correspondentAccountName} - correspondent или ""
+ * {@link BankAccountNewRequest#currency} - RUB или ""
+ * {@link BankAccountNewRequest#destination} - destinatio или ""n
+ * {@link BankAccountNewRequest#taxpayerIdentificationNumber} - 3664011397 или ""
+ * {@link BankAccountNewRequest#taxRegistrationReasonCode} - 01 или ""
+ * {@link BankAccountNewRequest#account} - 11111222223333344444 или ""
+ */ @Test - void update() { + 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", "")); } + /** + * {@link BankAccountController#update(Long, BankAccountUpdateAction)}
+ * Тест проверяет получение сущности {@link BankAccountUpdateAction} по REST API и отправку в Apache Kafka.
+ * Входной запрос {@link BankAccountUpdateAction}:
+ * {@link BankAccountUpdateAction#bankIdentificationCode} - 044525776
+ * {@link BankAccountUpdateAction#bankName} - Beta Money Bank
+ * {@link BankAccountUpdateAction#correspondentAccount} - 30101111111111111776
+ * {@link BankAccountUpdateAction#correspondentAccountName} - correspondent
+ * {@link BankAccountUpdateAction#currency} - RUB
+ * {@link BankAccountUpdateAction#destination} - destination
+ * {@link BankAccountUpdateAction#taxpayerIdentificationNumber} - 3664011397
+ * {@link BankAccountUpdateAction#taxRegistrationReasonCode} - 01
+ * {@link BankAccountUpdateAction#account} - 11111222223333344444
+ */ @Test - void delete() { + void update() throws Exception { + //ARRANGE + BankAccountUpdateAction bankAccountNewAction = getBankAccountUpdateAction( + "044525776", + "Beta Money Bank", + "30101111111111111776", + "correspondent", + "RUB", + "destination", + "3664011397", + "01", + "11111222223333344444"); + + CudResponse extended = new CudResponse(); + extended.setCode(0L); + extended.setMessage("success"); + extended.setPayload(new QueueSuccessResponse(ActionType.UPDATE, currentId.getAndIncrement())); + //ACT + mockMvc.perform(MockMvcRequestBuilders.put(REST_URL + "0") + .contentType(MediaType.APPLICATION_JSON) + .content(writeValue(bankAccountNewAction))) + .andDo(print())//output to the log request and response +// ASSERT + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(content().json(writeValue(extended))); + } + + + /** + * {@link BankAccountController#delete(Long)}
+ * Тест проверяет получение id сущности {@link Long} по REST API и отправку в Apache Kafka.
+ * Входной запрос {@link Long}: - 0L
+ */ + @Test + void delete() throws Exception { + //ARRANGE + CudResponse extended = new CudResponse(); + extended.setCode(0L); + extended.setMessage("success"); + extended.setPayload(new QueueSuccessResponse(ActionType.DELETE, currentId.getAndIncrement())); + //ACT + mockMvc.perform(MockMvcRequestBuilders.delete(REST_URL + "0") + .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(extended))); + } + + private void assertThrowsFor(IAction iAction) { + assertThrows(ActionValidationException.class, () -> { + try { + mockMvc.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; + } + }); + } + + private BankAccountNewAction getBankAccountNewAction(String BankIdentificationCode, String BankName, String CorrespondentAccount, String CorrespondentAccountName, + String Currency, String Destination, String TaxpayerIdentificationNumber, String TaxRegistrationReasonCode, + String Account) { + BankAccountNewAction bankAccountNewAction = new BankAccountNewAction(); + bankAccountNewAction.setBankIdentificationCode(BankIdentificationCode); + bankAccountNewAction.setBankName(BankName); + bankAccountNewAction.setCorrespondentAccount(CorrespondentAccount); + bankAccountNewAction.setCorrespondentAccountName(CorrespondentAccountName); + bankAccountNewAction.setCurrency(Currency); + bankAccountNewAction.setDestination(Destination); + bankAccountNewAction.setTaxpayerIdentificationNumber(TaxpayerIdentificationNumber); + bankAccountNewAction.setTaxRegistrationReasonCode(TaxRegistrationReasonCode); + bankAccountNewAction.setAccount(Account); + return bankAccountNewAction; + } + + private BankAccountUpdateAction getBankAccountUpdateAction(String BankIdentificationCode, String BankName, String CorrespondentAccount, String CorrespondentAccountName, + String Currency, String Destination, String TaxpayerIdentificationNumber, String TaxRegistrationReasonCode, + String Account) { + BankAccountUpdateAction bankAccountUpdateAction = new BankAccountUpdateAction(); + bankAccountUpdateAction.setBankIdentificationCode(BankIdentificationCode); + bankAccountUpdateAction.setBankName(BankName); + bankAccountUpdateAction.setCorrespondentAccount(CorrespondentAccount); + bankAccountUpdateAction.setCorrespondentAccountName(CorrespondentAccountName); + bankAccountUpdateAction.setCurrency(Currency); + bankAccountUpdateAction.setDestination(Destination); + bankAccountUpdateAction.setTaxpayerIdentificationNumber(TaxpayerIdentificationNumber); + bankAccountUpdateAction.setTaxRegistrationReasonCode(TaxRegistrationReasonCode); + bankAccountUpdateAction.setAccount(Account); + return bankAccountUpdateAction; } } \ No newline at end of file From 4b7d382689d2b0d0574671804f015d9b48981026 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Mon, 26 Sep 2022 16:25:06 +0300 Subject: [PATCH 31/33] http://git.mfd.msk/mfd/clearing/issues/7 --- added test for DeleteCompanyController. --- clearing-parent/backend-api/pom.xml | 18 +++++++ .../queue/AbstractControllerTest.java | 53 +++++++++++++++++++ .../account/BankAccountControllerTest.java | 53 ++++--------------- .../company/DeleteCompanyControllerTest.java | 40 ++++++++++++++ .../config/BankAccountControllerConfig.java | 7 ++- .../config/DeleteCompanyControllerConfig.java | 20 +++++++ .../HazelcastServiceTestConfiguration.java | 2 +- .../controller/queue/config/IOperator.java | 3 +- 8 files changed, 149 insertions(+), 47 deletions(-) create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/AbstractControllerTest.java create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/company/DeleteCompanyControllerTest.java create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/DeleteCompanyControllerConfig.java diff --git a/clearing-parent/backend-api/pom.xml b/clearing-parent/backend-api/pom.xml index 0f9f3f647..1eb563bed 100644 --- a/clearing-parent/backend-api/pom.xml +++ b/clearing-parent/backend-api/pom.xml @@ -116,6 +116,24 @@ ${project.artifactId} + + + org.apache.maven.plugins + maven-surefire-plugin + 2.21.0 + + + org.junit.platform + junit-platform-surefire-provider + 1.2.0-M1 + + + org.junit.jupiter + junit-jupiter-engine + 5.2.0-M1 + + + \ No newline at end of file diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/AbstractControllerTest.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/AbstractControllerTest.java new file mode 100644 index 000000000..79903c50f --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/AbstractControllerTest.java @@ -0,0 +1,53 @@ +package ru.spcex.clearing.backendapi.controller.queue; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.filter.CharacterEncodingFilter; +import ru.spcex.clearing.backendapi.config.WebConfig; +import ru.spcex.clearing.backendapi.controller.queue.company.DeleteCompanyController; +import ru.spcex.clearing.backendapi.controller.queue.config.*; + +import javax.annotation.PostConstruct; +import java.util.concurrent.atomic.AtomicLong; + + +@SpringJUnitWebConfig(classes = { + WebConfig.class, + IOperator.class, + DeleteCompanyController.class, + BankAccountControllerConfig.class, + KafkaConfig.class, + HazelcastServiceTestConfiguration.class, + Jackson2HttpConverterConfig.class}) +public abstract class AbstractControllerTest { + protected static final AtomicLong currentId = new AtomicLong(); + private static final CharacterEncodingFilter CHARACTER_ENCODING_FILTER = new CharacterEncodingFilter(); + + static { + CHARACTER_ENCODING_FILTER.setEncoding("UTF-8"); + CHARACTER_ENCODING_FILTER.setForceEncoding(true); + } + + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext webApplicationContext; + + @PostConstruct + private void postConstruct() { + mockMvc = MockMvcBuilders + .webAppContextSetup(webApplicationContext) + .addFilter(CHARACTER_ENCODING_FILTER) +// .apply(springSecurity()) + .build(); + } + + protected ResultActions perform(MockHttpServletRequestBuilder builder) throws Exception { + return mockMvc.perform(builder); + } +} diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java index e0705f548..80aff6387 100644 --- a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/account/BankAccountControllerTest.java @@ -1,18 +1,13 @@ package ru.spcex.clearing.backendapi.controller.queue.account; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.NestedExceptionUtils; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; -import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.filter.CharacterEncodingFilter; import ru.spcex.clearing.backendapi.config.WebConfig; +import ru.spcex.clearing.backendapi.controller.queue.AbstractControllerTest; import ru.spcex.clearing.backendapi.controller.queue.config.*; -import ru.spcex.clearing.backendapi.controller.queue.utils.MatcherFactory; import ru.spcex.clearing.backendapi.controller.request.cud.account.BankAccountNewAction; import ru.spcex.clearing.backendapi.controller.request.cud.account.BankAccountUpdateAction; import ru.spcex.clearing.backendapi.controller.response.cud.CudResponse; @@ -22,9 +17,6 @@ import ru.spcex.clearing.backendapi.errors.ActionValidationException; import ru.spcex.clearing.platform.messaging.domain.ActionType; import ru.spcex.clearing.platform.messaging.domain.cud.account.BankAccountNewRequest; -import javax.annotation.PostConstruct; -import java.util.concurrent.atomic.AtomicLong; - import static org.junit.jupiter.api.Assertions.assertThrows; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; @@ -38,31 +30,8 @@ import static ru.spcex.clearing.backendapi.controller.queue.utils.JsonUtil.write KafkaConfig.class, HazelcastServiceTestConfiguration.class, Jackson2HttpConverterConfig.class}) -class BankAccountControllerTest { - - public static final MatcherFactory.Matcher CUD_RESPONSE_MATCHER = MatcherFactory.usingIgnoringFieldsComparator(CudResponse.class); +class BankAccountControllerTest extends AbstractControllerTest { private static final String REST_URL = "/securities/bank-accounts/"; - private static final CharacterEncodingFilter CHARACTER_ENCODING_FILTER = new CharacterEncodingFilter(); - private static final AtomicLong currentId = new AtomicLong(); - - static { - CHARACTER_ENCODING_FILTER.setEncoding("UTF-8"); - CHARACTER_ENCODING_FILTER.setForceEncoding(true); - } - - private MockMvc mockMvc; - - @Autowired - private WebApplicationContext webApplicationContext; - - @PostConstruct - private void postConstruct() { - mockMvc = MockMvcBuilders - .webAppContextSetup(webApplicationContext) - .addFilter(CHARACTER_ENCODING_FILTER) -// .apply(springSecurity()) - .build(); - } /** * {@link BankAccountController#add(BankAccountNewAction)}
@@ -97,9 +66,9 @@ class BankAccountControllerTest { extended.setMessage("success"); extended.setPayload(new QueueSuccessResponse(ActionType.NEW, currentId.getAndIncrement())); //ACT - mockMvc.perform(MockMvcRequestBuilders.post(REST_URL) - .contentType(MediaType.APPLICATION_JSON) - .content(writeValue(bankAccountNewAction))) + perform(MockMvcRequestBuilders.post(REST_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(writeValue(bankAccountNewAction))) .andDo(print())//output to the log request and response // ASSERT .andExpect(status().isOk()) @@ -167,9 +136,9 @@ class BankAccountControllerTest { extended.setMessage("success"); extended.setPayload(new QueueSuccessResponse(ActionType.UPDATE, currentId.getAndIncrement())); //ACT - mockMvc.perform(MockMvcRequestBuilders.put(REST_URL + "0") - .contentType(MediaType.APPLICATION_JSON) - .content(writeValue(bankAccountNewAction))) + perform(MockMvcRequestBuilders.put(REST_URL + "0") + .contentType(MediaType.APPLICATION_JSON) + .content(writeValue(bankAccountNewAction))) .andDo(print())//output to the log request and response // ASSERT .andExpect(status().isOk()) @@ -191,8 +160,8 @@ class BankAccountControllerTest { extended.setMessage("success"); extended.setPayload(new QueueSuccessResponse(ActionType.DELETE, currentId.getAndIncrement())); //ACT - mockMvc.perform(MockMvcRequestBuilders.delete(REST_URL + "0") - .contentType(MediaType.APPLICATION_JSON)) + perform(MockMvcRequestBuilders.delete(REST_URL + "0") + .contentType(MediaType.APPLICATION_JSON)) .andDo(print())//output to the log request and response // ASSERT .andExpect(status().isOk()) @@ -203,7 +172,7 @@ class BankAccountControllerTest { private void assertThrowsFor(IAction iAction) { assertThrows(ActionValidationException.class, () -> { try { - mockMvc.perform(MockMvcRequestBuilders.post(REST_URL).contentType(MediaType.APPLICATION_JSON).content(writeValue(iAction))); + 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; diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/company/DeleteCompanyControllerTest.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/company/DeleteCompanyControllerTest.java new file mode 100644 index 000000000..1673abc9d --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/company/DeleteCompanyControllerTest.java @@ -0,0 +1,40 @@ +package ru.spcex.clearing.backendapi.controller.queue.company; + +import org.junit.jupiter.api.Test; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import ru.spcex.clearing.backendapi.controller.queue.AbstractControllerTest; +import ru.spcex.clearing.backendapi.controller.response.cud.CudResponse; +import ru.spcex.clearing.backendapi.controller.response.cud.QueueSuccessResponse; +import ru.spcex.clearing.platform.messaging.domain.ActionType; + +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.queue.utils.JsonUtil.writeValue; + +class DeleteCompanyControllerTest extends AbstractControllerTest { + private static final String REST_URL = "/companies/"; + + /** + * {@link DeleteCompanyController#delete(Long)}
+ * Тест проверяет получение id сущности {@link Long} по REST API и отправку в Apache Kafka.
+ * Входной запрос {@link Long}: - 0L
+ */ + @Test + void delete() throws Exception { + //ARRANGE + CudResponse extended = new CudResponse(); + extended.setCode(0L); + extended.setMessage("success"); + extended.setPayload(new QueueSuccessResponse(ActionType.DELETE, currentId.getAndIncrement())); + //ACT + perform(MockMvcRequestBuilders.delete(REST_URL + "0") + .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(extended))); + } +} \ No newline at end of file diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java index 2f832f51b..8b79bff37 100644 --- a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java @@ -1,6 +1,7 @@ package ru.spcex.clearing.backendapi.controller.queue.config; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import ru.spcex.clearing.backendapi.controller.queue.account.BankAccountController; @@ -10,9 +11,11 @@ import ru.spcex.clearing.backendapi.service.IOperator; public class BankAccountControllerConfig { @Autowired + @Qualifier("iOperator") + private IOperator operator; + @Bean - public BankAccountController createBankAccountController(IOperator operator) { + public BankAccountController createBankAccountController() { return new BankAccountController(operator); } - } diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/DeleteCompanyControllerConfig.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/DeleteCompanyControllerConfig.java new file mode 100644 index 000000000..71a592793 --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/DeleteCompanyControllerConfig.java @@ -0,0 +1,20 @@ +package ru.spcex.clearing.backendapi.controller.queue.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import ru.spcex.clearing.backendapi.controller.queue.company.DeleteCompanyController; +import ru.spcex.clearing.backendapi.service.IOperator; + +@Configuration +public class DeleteCompanyControllerConfig { + @Autowired + @Qualifier("iOperator") + private IOperator operator; + + @Bean + public DeleteCompanyController createDeleteCompanyController() { + return new DeleteCompanyController(operator); + } +} diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/HazelcastServiceTestConfiguration.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/HazelcastServiceTestConfiguration.java index 04e64990d..c25659999 100644 --- a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/HazelcastServiceTestConfiguration.java +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/HazelcastServiceTestConfiguration.java @@ -40,7 +40,7 @@ public class HazelcastServiceTestConfiguration { joinConfig.setTcpIpConfig(new TcpIpConfig().setEnabled(true).setMembers(List.of("127.0.0.1"))); networkConfig.setJoin(joinConfig); cfg.setNetworkConfig(networkConfig); - hazelcastInstance = Hazelcast.newHazelcastInstance(cfg); + hazelcastInstance = Hazelcast.getOrCreateHazelcastInstance(cfg); HazelcastHelper.otcSystem_setStorageState(true, hazelcastInstance); return new HazelcastService(taskExecutorHazelcastClientInitializer, taskExecutorIdGeneratorAwaiter, params); } diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/IOperator.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/IOperator.java index 065785269..5837d3b4a 100644 --- a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/IOperator.java +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/IOperator.java @@ -16,9 +16,8 @@ public class IOperator { private HazelcastService hazelcastServiceTest; @Autowired - @Bean + @Bean(name = "iOperator") public OperatorImpl createIOperator(Producer kafka) { return new OperatorImpl(kafka, hazelcastServiceTest); } - } From 7e87dcd5422f97fc3018c099134fdfc220d44dfe Mon Sep 17 00:00:00 2001 From: psemenkov Date: Mon, 26 Sep 2022 18:50:14 +0300 Subject: [PATCH 32/33] http___git_mfd_msk_mfd_clearing_issues_7 --- not work maven test, part test (3 of 5) in BankAccountController --- .../queue/AbstractControllerTest.java | 1 + .../config/BankAccountControllerConfig.java | 7 +++++- .../config/DeleteCompanyControllerConfig.java | 7 +++++- .../queue/config/StateLoaderImplConfig.java | 22 +++++++++++++++++++ 4 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/StateLoaderImplConfig.java diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/AbstractControllerTest.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/AbstractControllerTest.java index 79903c50f..4b941266d 100644 --- a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/AbstractControllerTest.java +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/AbstractControllerTest.java @@ -19,6 +19,7 @@ import java.util.concurrent.atomic.AtomicLong; @SpringJUnitWebConfig(classes = { WebConfig.class, IOperator.class, + StateLoaderImplConfig.class, DeleteCompanyController.class, BankAccountControllerConfig.class, KafkaConfig.class, diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java index 8b79bff37..21071de14 100644 --- a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java @@ -6,6 +6,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import ru.spcex.clearing.backendapi.controller.queue.account.BankAccountController; import ru.spcex.clearing.backendapi.service.IOperator; +import ru.spcex.clearing.backendapi.service.impl.StateLoaderImpl; @Configuration public class BankAccountControllerConfig { @@ -14,8 +15,12 @@ public class BankAccountControllerConfig { @Qualifier("iOperator") private IOperator operator; + @Autowired + @Qualifier("stateLoaderImpl") + private StateLoaderImpl stateLoader; + @Bean public BankAccountController createBankAccountController() { - return new BankAccountController(operator); + return new BankAccountController(operator, stateLoader); } } diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/DeleteCompanyControllerConfig.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/DeleteCompanyControllerConfig.java index 71a592793..5a5aab4c0 100644 --- a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/DeleteCompanyControllerConfig.java +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/DeleteCompanyControllerConfig.java @@ -6,6 +6,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import ru.spcex.clearing.backendapi.controller.queue.company.DeleteCompanyController; import ru.spcex.clearing.backendapi.service.IOperator; +import ru.spcex.clearing.backendapi.service.impl.StateLoaderImpl; @Configuration public class DeleteCompanyControllerConfig { @@ -13,8 +14,12 @@ public class DeleteCompanyControllerConfig { @Qualifier("iOperator") private IOperator operator; + @Autowired + @Qualifier("stateLoaderImpl") + private StateLoaderImpl stateLoader; + @Bean public DeleteCompanyController createDeleteCompanyController() { - return new DeleteCompanyController(operator); + return new DeleteCompanyController(operator, stateLoader); } } diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/StateLoaderImplConfig.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/StateLoaderImplConfig.java new file mode 100644 index 000000000..b566a6bbc --- /dev/null +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/StateLoaderImplConfig.java @@ -0,0 +1,22 @@ +package ru.spcex.clearing.backendapi.controller.queue.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import ru.spcex.clearing.backendapi.service.impl.StateLoaderImpl; +import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService; + +@Configuration +public class StateLoaderImplConfig { + + @Autowired + @Qualifier("hazelcastServiceTest") + private HazelcastService hazelcastServiceTest; + + + @Bean(name = "stateLoaderImpl") + public StateLoaderImpl createIOperator() { + return new StateLoaderImpl(hazelcastServiceTest); + } +} From a533e75fa420e2772d17a47b8e3b431db12eb0e4 Mon Sep 17 00:00:00 2001 From: psemenkov Date: Mon, 26 Sep 2022 18:55:53 +0300 Subject: [PATCH 33/33] http://git.mfd.msk/mfd/clearing/issues/7 --- marg --- .../config/BankAccountControllerConfig.java | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java index 2f832f51b..02d79864d 100644 --- a/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java +++ b/clearing-parent/backend-api/src/test/ru/spcex/clearing/backendapi/controller/queue/config/BankAccountControllerConfig.java @@ -1,18 +1,28 @@ package ru.spcex.clearing.backendapi.controller.queue.config; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import ru.spcex.clearing.backendapi.controller.queue.account.BankAccountController; import ru.spcex.clearing.backendapi.service.IOperator; +import ru.spcex.clearing.backendapi.service.impl.StateLoaderImpl; + @Configuration public class BankAccountControllerConfig { @Autowired - @Bean - public BankAccountController createBankAccountController(IOperator operator) { - return new BankAccountController(operator); - } + @Qualifier("iOperator") + private IOperator operator; + + @Autowired + @Qualifier("stateLoaderImpl") + private StateLoaderImpl stateLoader; + + @Bean + public BankAccountController createBankAccountController() { + return new BankAccountController(operator, stateLoader); + } }