From 24cba526f92fdac8c7bd5e340a2b64a0ba49cb0e Mon Sep 17 00:00:00 2001 From: psemenkov Date: Thu, 16 Feb 2023 17:56:05 +0300 Subject: [PATCH] Adding test for LauncherController. And fixing NPE in LauncherController.addSpecific. --- .../queue/scheduler/LauncherController.java | 3 + .../queue/AbstractControllerTest.java | 13 +- .../scheduler/LauncherControllerTest.java | 186 ++++++++++++------ 3 files changed, 140 insertions(+), 62 deletions(-) diff --git a/clearing-parent/backend-api/src/main/java/ru/spcex/clearing/backendapi/controller/queue/scheduler/LauncherController.java b/clearing-parent/backend-api/src/main/java/ru/spcex/clearing/backendapi/controller/queue/scheduler/LauncherController.java index 1163100a5..3410976b7 100644 --- a/clearing-parent/backend-api/src/main/java/ru/spcex/clearing/backendapi/controller/queue/scheduler/LauncherController.java +++ b/clearing-parent/backend-api/src/main/java/ru/spcex/clearing/backendapi/controller/queue/scheduler/LauncherController.java @@ -93,6 +93,9 @@ public class LauncherController extends AbstractQueueController { @ResponseBody public CudResponse addSpecific(@ApiParam(value = "Параметры команды в JSON формате.", required = true) @RequestBody LauncherNew launcherNew) throws ExecutionException, InterruptedException { + if (launcherNew.getTask() == null) { + throw new NotFound404Exception("task dictionary element with code '" + launcherNew.getTask() + "'"); + } AbstractDictionary taskEnum = taskDictionary.getSingleObjectByFieldValues(Map.of("code", launcherNew.getTask())); if (taskEnum == null) { throw new NotFound404Exception("task dictionary element with code '" + launcherNew.getTask() + "'"); diff --git a/clearing-parent/backend-api/src/test/java/ru/spcex/clearing/backendapi/controller/queue/AbstractControllerTest.java b/clearing-parent/backend-api/src/test/java/ru/spcex/clearing/backendapi/controller/queue/AbstractControllerTest.java index 805024862..7d0535777 100644 --- a/clearing-parent/backend-api/src/test/java/ru/spcex/clearing/backendapi/controller/queue/AbstractControllerTest.java +++ b/clearing-parent/backend-api/src/test/java/ru/spcex/clearing/backendapi/controller/queue/AbstractControllerTest.java @@ -18,6 +18,7 @@ import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilde import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.filter.CharacterEncodingFilter; +import ru.clearing.classes.statics.data.user.User; import ru.spcex.clearing.backendapi.controller.config.*; import ru.spcex.clearing.backendapi.controller.queue.account.AccountBalanceController; import ru.spcex.clearing.backendapi.controller.queue.account.AccountController; @@ -34,8 +35,11 @@ import ru.spcex.clearing.backendapi.controller.utils.MatcherFactory; import ru.spcex.clearing.backendapi.controller.utils.TestUtils; import ru.spcex.clearing.backendapi.domain.actions.IAction; import ru.spcex.clearing.backendapi.meta.GetResponseFactory; +import ru.spcex.clearing.imdg.IMDGDistributedNames; import ru.spcex.clearing.platform.messaging.domain.BaseRequest; +import ru.spcex.platform.imdg.api.Imdg; import ru.spcex.platform.imdg.iml.hazelcast.service.HazelcastService; +import ru.spcex.platform.utils.enumeration.IMessageResolver; import javax.annotation.PostConstruct; import java.util.concurrent.atomic.AtomicLong; @@ -92,9 +96,14 @@ public abstract class AbstractControllerTest { CHARACTER_ENCODING_FILTER.setForceEncoding(true); } + @Autowired + @Qualifier("errorTestResolver") + protected IMessageResolver errorResolver; + @Autowired @Qualifier("hazelcastServiceTest") protected HazelcastService hazelcastServiceTest; + @Autowired @Qualifier("responseFactoryTest") protected GetResponseFactory responseFactory; @@ -102,9 +111,10 @@ public abstract class AbstractControllerTest { protected ArgumentCaptor producerRecord; @MockBean protected MockProducer producer; - private MockMvc mockMvc; + protected Imdg userImdg; @Autowired private WebApplicationContext webApplicationContext; + private MockMvc mockMvc; @PostConstruct private void postConstruct() { @@ -115,6 +125,7 @@ public abstract class AbstractControllerTest { .build(); TestUtils.FutureRecordMetadata future = spy(TestUtils.FutureRecordMetadata.class); doReturn(future).when(producer).send(producerRecord.capture()); + userImdg = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_User, User.class); } protected ResultActions perform(MockHttpServletRequestBuilder builder) throws Exception { diff --git a/clearing-parent/backend-api/src/test/java/ru/spcex/clearing/backendapi/controller/queue/scheduler/LauncherControllerTest.java b/clearing-parent/backend-api/src/test/java/ru/spcex/clearing/backendapi/controller/queue/scheduler/LauncherControllerTest.java index 95fb4e4bf..eb127e694 100644 --- a/clearing-parent/backend-api/src/test/java/ru/spcex/clearing/backendapi/controller/queue/scheduler/LauncherControllerTest.java +++ b/clearing-parent/backend-api/src/test/java/ru/spcex/clearing/backendapi/controller/queue/scheduler/LauncherControllerTest.java @@ -7,29 +7,30 @@ import org.keycloak.KeycloakSecurityContext; import org.keycloak.adapters.spi.KeycloakAccount; import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; import org.keycloak.representations.AccessToken; -import org.springframework.core.NestedExceptionUtils; import org.springframework.http.MediaType; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import ru.clearing.classes.statics.data.scheduler.Launcher; import ru.clearing.classes.statics.data.user.User; +import ru.clearing.platform.dictionary.AbstractDictionary; import ru.clearing.platform.dictionary.TaskDictionary; import ru.spcex.clearing.backendapi.controller.queue.AbstractControllerTest; -import ru.spcex.clearing.backendapi.controller.queue.account.BankAccountController; -import ru.spcex.clearing.backendapi.controller.request.cud.account.BankAccountNewAction; +import ru.spcex.clearing.backendapi.controller.request.cud.schedule.LauncherNew; +import ru.spcex.clearing.backendapi.controller.response.BasicSpcexResponse; import ru.spcex.clearing.backendapi.controller.response.cud.CudResponse; import ru.spcex.clearing.backendapi.controller.response.cud.QueueSuccessResponse; import ru.spcex.clearing.backendapi.controller.response.entity.CommonGetAllResponse; -import ru.spcex.clearing.backendapi.domain.actions.IAction; -import ru.spcex.clearing.backendapi.errors.ActionValidationException; +import ru.spcex.clearing.backendapi.errors.NotFound404Exception; import ru.spcex.clearing.imdg.IMDGDistributedNames; import ru.spcex.clearing.platform.messaging.domain.ActionType; -import ru.spcex.clearing.platform.messaging.domain.cud.account.BankAccountNewRequest; +import ru.spcex.clearing.platform.messaging.domain.Consts; +import ru.spcex.platform.enumeration.Task; +import ru.spcex.platform.imdg.api.Imdg; +import ru.spcex.platform.utils.enumeration.EnumMessage; import java.util.Collection; import java.util.Map; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; @@ -39,6 +40,9 @@ import static ru.spcex.clearing.backendapi.controller.utils.JsonUtil.writeValue; class LauncherControllerTest extends AbstractControllerTest { private static final String REST_URL = "/launchers/"; + private static final String CODE = "ABLK"; + private static final String START_OF_CLEARING = Task.startOfClearing.getKey(); + private static final long ID = 0; /** * {@link LauncherController#getAll()}
@@ -71,38 +75,142 @@ class LauncherControllerTest extends AbstractControllerTest { .andExpect(content().json(writeValue(expected))); } - - // @Test todo пока не работает ( + /** + * {@link LauncherController#add(String)}
+ * Тест проверяет получение сущности {@link LauncherController} по REST API и отправку в Apache Kafka.
+ */ + @Test void add() throws Exception { //ARRANGE TaskDictionary taskDictionary = new TaskDictionary(); - IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_TaskDictionary); - iMap.put(taskDictionary.getId(), taskDictionary); + taskDictionary.setCode(CODE); + taskDictionary.setId(ID); + Imdg imdgDictionary = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_TaskDictionary, AbstractDictionary.class); + imdgDictionary.insert(taskDictionary); + + LauncherNew launcherCommand = new LauncherNew(); + launcherCommand.setTask(CODE); + launcherCommand.setUserId(ID); CudResponse expected = new CudResponse(); expected.setCode(0L); expected.setMessage("success"); expected.setPayload(new QueueSuccessResponse(ActionType.NEW, currentId.getAndIncrement())); - setUserNameInMockSecurityContextAndMapUser("existUser"); + setUserNameInMockSecurityContextAndMapUser(CODE, ID); //ACT - perform(MockMvcRequestBuilders.post(REST_URL + "ABLK") + perform(MockMvcRequestBuilders.post(REST_URL + CODE) .contentType(MediaType.APPLICATION_JSON)) .andDo(print())//output to the log request and response //ASSERT .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(content().json(writeValue(expected))); + checkSendedMessegeFromKafka(Consts.LAUNCHER_NEW, launcherCommand); } - private void setUserNameInMockSecurityContextAndMapUser(String username) { + /** + * {@link LauncherController#add(String)}
+ * Тест проверяет работу валидации {@link LauncherController}
+ */ + @Test + void addWithException() throws Exception { + BasicSpcexResponse response = new BasicSpcexResponse(); + NotFound404Exception ex = new NotFound404Exception("task dictionary element with code 'null'"); + EnumMessage message = ex.getError(); + response.setCode(message.getSubject().getId()); + response.setMessage(errorResolver.resolve(message)); + //ACT + perform(MockMvcRequestBuilders.post(REST_URL + null) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(print())//output to the log request and response + //ASSERT + .andExpect(status().isNotFound()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(content().json(writeValue(response))); + } + + /** + * {@link LauncherController#addSpecific}
+ * Тест проверяет получение сущности {@link LauncherController} по REST API и отправку в Apache Kafka.
+ */ + @Test + void addSpecific() throws Exception { + //ARRANGE + LauncherNew launcherCommand = new LauncherNew(); + launcherCommand.setTask(START_OF_CLEARING); + launcherCommand.setUserId(ID); + launcherCommand.setCompanyId(ID); + launcherCommand.setSecurityId(ID); + + TaskDictionary taskDictionary = new TaskDictionary(); + taskDictionary.setCode(START_OF_CLEARING); + taskDictionary.setId(ID); + Imdg imdgDictionary = hazelcastServiceTest.getImdg(IMDGDistributedNames.Map_TaskDictionary, AbstractDictionary.class); + imdgDictionary.insert(taskDictionary); + + CudResponse expected = new CudResponse(); + expected.setCode(0L); + expected.setMessage("success"); + expected.setPayload(new QueueSuccessResponse(ActionType.NEW, currentId.getAndIncrement())); + + setUserNameInMockSecurityContextAndMapUser(START_OF_CLEARING, ID); + + //ACT + perform(MockMvcRequestBuilders.post(REST_URL + "specific") + .contentType(MediaType.APPLICATION_JSON) + .content(writeValue(launcherCommand))) + .andDo(print())//output to the log request and response + //ASSERT + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(content().json(writeValue(expected))); + checkSendedMessegeFromKafka(Consts.LAUNCHER_NEW, launcherCommand); + } + + /** + * {@link LauncherController#addSpecific}
+ * Тест проверяет работу валидации {@link LauncherController}
+ */ + @Test + void addSpecificWithException() throws Exception { + LauncherNew launcherCommand = new LauncherNew(); + launcherCommand.setTask(null); + + BasicSpcexResponse response = new BasicSpcexResponse(); + NotFound404Exception ex = new NotFound404Exception("task dictionary element with code 'null'"); + EnumMessage message = ex.getError(); + response.setCode(message.getSubject().getId()); + response.setMessage(errorResolver.resolve(message)); + //ACT + perform(MockMvcRequestBuilders.post(REST_URL + "specific") + .contentType(MediaType.APPLICATION_JSON) + .content(writeValue(launcherCommand))) + .andDo(print())//output to the log request and response + //ASSERT + .andExpect(status().isNotFound()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(content().json(writeValue(response))); + + launcherCommand.setTask("null"); + + perform(MockMvcRequestBuilders.post(REST_URL + "specific") + .contentType(MediaType.APPLICATION_JSON) + .content(writeValue(launcherCommand))) + .andDo(print())//output to the log request and response + //ASSERT + .andExpect(status().isNotFound()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(content().json(writeValue(response))); + } + + private void setUserNameInMockSecurityContextAndMapUser(String username, long id) { User user = new User(); user.setIdentifier(username); - user.setId(currentId.get()); + user.setId(id); - IMap iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_User); - iMap.put(user.getId(), user); + userImdg.insert(user); AccessToken accessToken = mock(AccessToken.class); when(accessToken.getPreferredUsername()).thenReturn(username); @@ -120,50 +228,6 @@ class LauncherControllerTest extends AbstractControllerTest { when(authentication.getDetails()).thenReturn(details); SecurityContextHolder.getContext().setAuthentication(authentication); } -// @Test -// void testWithPostProcessor() выдает Exception { -// perform(MockMvcRequestBuilders.get("/greet").with(jwt().jwt(jwt -> { -// jwt.claim("preferred_username", "Tonton Pirate"); -// }).authorities(List.of(new SimpleGrantedAuthority("NICE_GUY"), new SimpleGrantedAuthority("AUTHOR"))))) -// .andExpect(status().isOk()) -// .andExpect(content().string("Hi Tonton Pirate! You are granted with: [NICE_GUY, AUTHOR].")); -// } - /** - * {@link BankAccountController#add(BankAccountNewAction)}
- * Тест проверяет работу валидации сущности {@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 addWithException() { -// assertThrowsFor(getBankAccountNewAction("", "Beta Money Bank", "30101111111111111776", "correspondent", "RUB", "destination", "3664011397", "01", "11111222223333344444")); -// assertThrowsFor(getBankAccountNewAction("044525776", "", "30101111111111111776", "correspondent", "RUB", "destination", "3664011397", "01", "11111222223333344444")); -// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "", "correspondent", "RUB", "destination", "3664011397", "01", "11111222223333344444")); -// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "30101111111111111776", "", "RUB", "destination", "3664011397", "01", "11111222223333344444")); -// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "30101111111111111776", "correspondent", "", "destination", "3664011397", "01", "11111222223333344444")); -// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "30101111111111111776", "correspondent", "RUB", "", "3664011397", "01", "11111222223333344444")); -// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "30101111111111111776", "correspondent", "RUB", "destination", "", "01", "11111222223333344444")); -// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "30101111111111111776", "correspondent", "RUB", "destination", "3664011397", "", "11111222223333344444")); -// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "30101111111111111776", "correspondent", "RUB", "destination", "3664011397", "01", "")); - } - private void assertThrowsFor(IAction iAction) { - assertThrows(ActionValidationException.class, () -> { - try { - perform(MockMvcRequestBuilders.post(REST_URL).contentType(MediaType.APPLICATION_JSON).content(writeValue(iAction))); - } catch (Exception e) { - Throwable rootCause = NestedExceptionUtils.getRootCause(e); - throw rootCause != null ? rootCause : e; - } - }); - } } \ No newline at end of file