Adding test for LauncherController. And fixing NPE in LauncherController.addSpecific.
This commit is contained in:
parent
4345254674
commit
24cba526f9
3 changed files with 140 additions and 62 deletions
|
|
@ -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() + "'");
|
||||
|
|
|
|||
|
|
@ -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> producerRecord;
|
||||
@MockBean
|
||||
protected MockProducer<String, Object> producer;
|
||||
private MockMvc mockMvc;
|
||||
protected Imdg<User> 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 {
|
||||
|
|
|
|||
|
|
@ -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()} <br>
|
||||
|
|
@ -71,38 +75,142 @@ class LauncherControllerTest extends AbstractControllerTest {
|
|||
.andExpect(content().json(writeValue(expected)));
|
||||
}
|
||||
|
||||
|
||||
// @Test todo пока не работает (
|
||||
/**
|
||||
* {@link LauncherController#add(String)}<br>
|
||||
* Тест проверяет получение сущности {@link LauncherController} по REST API и отправку в Apache Kafka.<br>
|
||||
*/
|
||||
@Test
|
||||
void add() throws Exception {
|
||||
//ARRANGE
|
||||
TaskDictionary taskDictionary = new TaskDictionary();
|
||||
IMap<Long, TaskDictionary> iMap = hazelcastServiceTest.getHazelcast().getMap(IMDGDistributedNames.Map_TaskDictionary);
|
||||
iMap.put(taskDictionary.getId(), taskDictionary);
|
||||
taskDictionary.setCode(CODE);
|
||||
taskDictionary.setId(ID);
|
||||
Imdg<AbstractDictionary> 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)}<br>
|
||||
* Тест проверяет работу валидации {@link LauncherController}<br>
|
||||
*/
|
||||
@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}<br>
|
||||
* Тест проверяет получение сущности {@link LauncherController} по REST API и отправку в Apache Kafka.<br>
|
||||
*/
|
||||
@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<AbstractDictionary> 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}<br>
|
||||
* Тест проверяет работу валидации {@link LauncherController}<br>
|
||||
*/
|
||||
@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<Long, User> 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)}<br>
|
||||
* Тест проверяет работу валидации сущности {@link BankAccountNewAction} принятой по REST API для отправку в Apache Kafka.<br>
|
||||
* Входной запрос {@link BankAccountNewRequest}:<br>
|
||||
* {@link BankAccountNewRequest#bankIdentificationCode} - 044525776 или ""<br>
|
||||
* {@link BankAccountNewRequest#bankName} - Beta Money Bank или ""<br>
|
||||
* {@link BankAccountNewRequest#correspondentAccount} - 30101111111111111776 или ""<br>
|
||||
* {@link BankAccountNewRequest#correspondentAccountName} - correspondent или ""<br>
|
||||
* {@link BankAccountNewRequest#currency} - RUB или ""<br>
|
||||
* {@link BankAccountNewRequest#destination} - destinatio или ""n<br>
|
||||
* {@link BankAccountNewRequest#taxpayerIdentificationNumber} - 3664011397 или ""<br>
|
||||
* {@link BankAccountNewRequest#taxRegistrationReasonCode} - 01 или ""<br>
|
||||
* {@link BankAccountNewRequest#account} - 11111222223333344444 или ""<br>
|
||||
*/
|
||||
@Test
|
||||
void addWithException() {
|
||||
// assertThrowsFor(getBankAccountNewAction("", "Beta Money Bank", "30101111111111111776", "correspondent", "RUB", "destination", "3664011397", "01", "11111222223333344444"));
|
||||
// assertThrowsFor(getBankAccountNewAction("044525776", "", "30101111111111111776", "correspondent", "RUB", "destination", "3664011397", "01", "11111222223333344444"));
|
||||
// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "", "correspondent", "RUB", "destination", "3664011397", "01", "11111222223333344444"));
|
||||
// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "30101111111111111776", "", "RUB", "destination", "3664011397", "01", "11111222223333344444"));
|
||||
// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "30101111111111111776", "correspondent", "", "destination", "3664011397", "01", "11111222223333344444"));
|
||||
// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "30101111111111111776", "correspondent", "RUB", "", "3664011397", "01", "11111222223333344444"));
|
||||
// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "30101111111111111776", "correspondent", "RUB", "destination", "", "01", "11111222223333344444"));
|
||||
// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "30101111111111111776", "correspondent", "RUB", "destination", "3664011397", "", "11111222223333344444"));
|
||||
// assertThrowsFor(getBankAccountNewAction("044525776", "Beta Money Bank", "30101111111111111776", "correspondent", "RUB", "destination", "3664011397", "01", ""));
|
||||
}
|
||||
|
||||
private void assertThrowsFor(IAction<?> iAction) {
|
||||
assertThrows(ActionValidationException.class, () -> {
|
||||
try {
|
||||
perform(MockMvcRequestBuilders.post(REST_URL).contentType(MediaType.APPLICATION_JSON).content(writeValue(iAction)));
|
||||
} catch (Exception e) {
|
||||
Throwable rootCause = NestedExceptionUtils.getRootCause(e);
|
||||
throw rootCause != null ? rootCause : e;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue