-
Notifications
You must be signed in to change notification settings - Fork 1
feat: ai, slack test 코드 작성 #113
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
174 changes: 174 additions & 0 deletions
174
ai-service/src/test/java/com/msa/ai_service/service/AiMessageServiceTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,174 @@ | ||
| package com.msa.ai_service.service; | ||
|
|
||
| import com.msa.ai_service.dto.AiMessageResponse; | ||
| import com.msa.ai_service.entity.AiMessage; | ||
| import com.msa.ai_service.entity.AiMessageStatus; | ||
| import com.msa.ai_service.entity.AiRequestType; | ||
| import com.msa.ai_service.exception.AiErrorCode; | ||
| import com.msa.ai_service.repository.AiMessageRepository; | ||
| import com.msa.core_common.auth.UserRole; | ||
| import com.msa.core_common.error.exception.CustomException; | ||
| import com.msa.core_common.response.paging.PageRes; | ||
| import org.junit.jupiter.api.BeforeEach; | ||
| import org.junit.jupiter.api.DisplayName; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.junit.jupiter.api.extension.ExtendWith; | ||
| import org.mockito.InjectMocks; | ||
| import org.mockito.Mock; | ||
| import org.mockito.junit.jupiter.MockitoExtension; | ||
| import org.springframework.data.domain.Page; | ||
| import org.springframework.data.domain.PageImpl; | ||
| import org.springframework.data.domain.PageRequest; | ||
| import org.springframework.data.domain.Pageable; | ||
|
|
||
| import java.time.LocalDateTime; | ||
| import java.util.List; | ||
| import java.util.Optional; | ||
| import java.util.UUID; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
| import static org.junit.jupiter.api.Assertions.assertThrows; | ||
| import static org.mockito.ArgumentMatchers.any; | ||
| import static org.mockito.ArgumentMatchers.eq; | ||
| import static org.mockito.Mockito.times; | ||
| import static org.mockito.Mockito.verify; | ||
| import static org.mockito.Mockito.when; | ||
|
|
||
| @ExtendWith(MockitoExtension.class) | ||
| class AiMessageServiceTest { | ||
| @InjectMocks | ||
| private AiMessageService aiMessageService; | ||
|
|
||
| @Mock | ||
| private AiMessageRepository aiMessageRepository; | ||
|
|
||
| private UUID aiMessageId; | ||
| private UUID deliveryId; | ||
| private AiMessage aiMessage; | ||
|
|
||
| @BeforeEach | ||
| void setUp() { | ||
| aiMessageId = UUID.randomUUID(); | ||
| deliveryId = UUID.randomUUID(); | ||
|
|
||
| aiMessage = AiMessage.builder() | ||
| .aiMessageId(aiMessageId) | ||
| .deliveryId(deliveryId) | ||
| .requestType(AiRequestType.DELIVERY_DEADLINE) | ||
| .prompt("프롬프트") | ||
| .requestPayload("{payload}") | ||
| .status(AiMessageStatus.PENDING) | ||
| .errorMessage("") | ||
| .build(); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("saveMessage - 요청 이력 저장 성공") | ||
| void saveMessage_Success() { | ||
| when(aiMessageRepository.save(any(AiMessage.class))).thenReturn(aiMessage); | ||
|
|
||
| AiMessage result = aiMessageService.saveMessage( | ||
| deliveryId, | ||
| AiRequestType.DELIVERY_DEADLINE, | ||
| "프롬프트", | ||
| "{payload}" | ||
| ); | ||
|
|
||
| assertThat(result).isNotNull(); | ||
| assertThat(result.getAiMessageId()).isEqualTo(aiMessageId); | ||
| verify(aiMessageRepository, times(1)).save(any(AiMessage.class)); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("markCompleted - 상태를 SUCCESS로 변경") | ||
| void markCompleted_Success() { | ||
| LocalDateTime deadline = LocalDateTime.of(2026, 5, 30, 15, 0); | ||
| String response = "최종 발송 시한 안내"; | ||
|
|
||
| when(aiMessageRepository.findByAiMessageIdAndDeletedAtIsNull(aiMessageId)) | ||
| .thenReturn(Optional.of(aiMessage)); | ||
|
|
||
| aiMessageService.markCompleted(aiMessageId, deadline, response); | ||
|
|
||
| assertThat(aiMessage.getStatus()).isEqualTo(AiMessageStatus.SUCCESS); | ||
| assertThat(aiMessage.getFinalDepartureDeadline()).isEqualTo(deadline); | ||
| assertThat(aiMessage.getResponseContent()).isEqualTo(response); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("markFailed - 상태를 FAILED로 변경") | ||
| void markFailed_Success() { | ||
| when(aiMessageRepository.findByAiMessageIdAndDeletedAtIsNull(aiMessageId)) | ||
| .thenReturn(Optional.of(aiMessage)); | ||
|
|
||
| aiMessageService.markFailed(aiMessageId, "AI 응답 파싱 실패"); | ||
|
|
||
| assertThat(aiMessage.getStatus()).isEqualTo(AiMessageStatus.FAILED); | ||
| assertThat(aiMessage.getErrorMessage()).isEqualTo("AI 응답 파싱 실패"); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("getAiMessages - MASTER 권한으로 목록 조회 성공") | ||
| void getAiMessages_Success_Master() { | ||
| Pageable pageable = PageRequest.of(0, 10); | ||
| Page<AiMessage> page = new PageImpl<>(List.of(aiMessage), pageable, 1); | ||
|
|
||
| when(aiMessageRepository.findAllByCondition( | ||
| eq(AiRequestType.DELIVERY_DEADLINE), | ||
| eq(AiMessageStatus.PENDING), | ||
| eq(pageable) | ||
| )).thenReturn(page); | ||
|
|
||
| PageRes<AiMessageResponse> result = aiMessageService.getAiMessages( | ||
| UserRole.MASTER.name(), | ||
| AiRequestType.DELIVERY_DEADLINE, | ||
| AiMessageStatus.PENDING, | ||
| pageable | ||
| ); | ||
|
|
||
| assertThat(result.getContent()).hasSize(1); | ||
| assertThat(result.getContent().get(0).getAiMessageId()).isEqualTo(aiMessageId); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("getAiMessage - MASTER 권한으로 단건 조회 성공") | ||
| void getAiMessage_Success_Master() { | ||
| when(aiMessageRepository.findByAiMessageIdAndDeletedAtIsNull(aiMessageId)) | ||
| .thenReturn(Optional.of(aiMessage)); | ||
|
|
||
| AiMessageResponse result = aiMessageService.getAiMessage("MASTER", aiMessageId); | ||
|
|
||
| assertThat(result.getAiMessageId()).isEqualTo(aiMessageId); | ||
| assertThat(result.getRequestType()).isEqualTo(AiRequestType.DELIVERY_DEADLINE); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("getAiMessages - MASTER 권한이 아니면 접근 거부") | ||
| void getAiMessages_Fail_NotMaster() { | ||
| CustomException exception = assertThrows( | ||
| CustomException.class, | ||
| () -> aiMessageService.getAiMessages( | ||
| "HUB_MANAGER", | ||
| AiRequestType.DELIVERY_DEADLINE, | ||
| AiMessageStatus.PENDING, | ||
| PageRequest.of(0, 10) | ||
| ) | ||
| ); | ||
|
|
||
| assertThat(exception.getErrorCode()).isEqualTo(AiErrorCode.AI_MESSAGE_ACCESS_DENIED); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("getAiMessageEntity - 존재하지 않는 메시지 조회 시 예외 발생") | ||
| void getAiMessageEntity_Fail_NotFound() { | ||
| when(aiMessageRepository.findByAiMessageIdAndDeletedAtIsNull(aiMessageId)) | ||
| .thenReturn(Optional.empty()); | ||
|
|
||
| CustomException exception = assertThrows( | ||
| CustomException.class, | ||
| () -> aiMessageService.getAiMessageEntity(aiMessageId) | ||
| ); | ||
|
|
||
| assertThat(exception.getErrorCode()).isEqualTo(AiErrorCode.AI_MESSAGE_NOT_FOUND); | ||
| } | ||
| } | ||
180 changes: 180 additions & 0 deletions
180
ai-service/src/test/java/com/msa/ai_service/service/AiServiceTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,180 @@ | ||
| package com.msa.ai_service.service; | ||
|
|
||
| import com.fasterxml.jackson.core.JsonProcessingException; | ||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import com.msa.ai_service.client.AiClient; | ||
| import com.msa.ai_service.dto.AiDeadlineResult; | ||
| import com.msa.ai_service.dto.AiResponse; | ||
| import com.msa.ai_service.entity.AiMessage; | ||
| import com.msa.ai_service.entity.AiRequestType; | ||
| import com.msa.ai_service.exception.AiErrorCode; | ||
| import com.msa.ai_service.parser.AiResponseParser; | ||
| import com.msa.ai_service.prompt.DeadlinePromptGenerator; | ||
| import com.msa.ai_service.stream.event.DeadlineNotificationRequestedEvent; | ||
| import com.msa.core_common.error.exception.CustomException; | ||
| import org.junit.jupiter.api.BeforeEach; | ||
| import org.junit.jupiter.api.DisplayName; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.junit.jupiter.api.extension.ExtendWith; | ||
| import org.mockito.InjectMocks; | ||
| import org.mockito.Mock; | ||
| import org.mockito.junit.jupiter.MockitoExtension; | ||
|
|
||
| import java.time.LocalDateTime; | ||
| import java.time.LocalTime; | ||
| import java.util.List; | ||
| import java.util.UUID; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
| import static org.junit.jupiter.api.Assertions.assertThrows; | ||
| import static org.mockito.ArgumentMatchers.anyString; | ||
| import static org.mockito.ArgumentMatchers.eq; | ||
| import static org.mockito.Mockito.*; | ||
|
|
||
| @ExtendWith(MockitoExtension.class) | ||
| class AiServiceTest { | ||
| @InjectMocks | ||
| private AiService aiService; | ||
|
|
||
| @Mock | ||
| private AiClient aiClient; | ||
|
|
||
| @Mock | ||
| private DeadlinePromptGenerator deadlinePromptGenerator; | ||
|
|
||
| @Mock | ||
| private AiMessageService aiMessageService; | ||
|
|
||
| @Mock | ||
| private ObjectMapper objectMapper; | ||
|
|
||
| @Mock | ||
| private AiResponseParser aiResponseParser; | ||
|
|
||
| private DeadlineNotificationRequestedEvent event; | ||
| private UUID aiMessageId; | ||
| private UUID deliveryId; | ||
|
|
||
| @BeforeEach | ||
| void setUp() { | ||
| aiMessageId = UUID.randomUUID(); | ||
| deliveryId = UUID.randomUUID(); | ||
|
|
||
| event = DeadlineNotificationRequestedEvent.builder() | ||
| .eventId(UUID.randomUUID()) | ||
| .deliveryId(deliveryId) | ||
| .orderId(UUID.randomUUID()) | ||
| .ordererName("홍길동") | ||
| .ordererEmail("hong@test.com") | ||
| .orderedAt(LocalDateTime.of(2026, 5, 29, 9, 0)) | ||
| .requestMessage("문 앞 배송") | ||
| .receiverUserId(UUID.randomUUID()) | ||
| .receiverSlackId("U123456") | ||
| .products(List.of(DeadlineNotificationRequestedEvent.ProductInfo.builder() | ||
| .productName("콜라") | ||
| .quantity(2) | ||
| .build())) | ||
| .requestedArrivalAt(LocalDateTime.of(2026, 5, 30, 18, 0)) | ||
| .departureHubName("서울 허브") | ||
| .destinationAddress("서울시 강남구") | ||
| .deliveryManagerName("김매니저") | ||
| .deliveryManagerEmail("manager@test.com") | ||
| .routeInfo(List.of(DeadlineNotificationRequestedEvent.RouteInfo.builder() | ||
| .departureHubName("서울 허브") | ||
| .arrivalHubName("강남 허브") | ||
| .estimatedDistanceKm(10.0) | ||
| .estimatedDurationMin(30) | ||
| .routeType("HUB_TO_HUB") | ||
| .build())) | ||
| .workStartTime(LocalTime.of(9, 0)) | ||
| .workEndTime(LocalTime.of(18, 0)) | ||
| .build(); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("generateDeadline - AI 호출 성공 시 완료 처리 및 결과 반환") | ||
| void generateDeadline_Success() throws JsonProcessingException { | ||
| String prompt = "프롬프트"; | ||
| String payload = "{\"deliveryId\":\"123\"}"; | ||
| LocalDateTime deadline = LocalDateTime.of(2026, 5, 30, 15, 0); | ||
| String message = "최종 발송 시한은 2026-05-30 15:00 입니다."; | ||
|
|
||
| AiMessage savedMessage = AiMessage.builder() | ||
| .aiMessageId(aiMessageId) | ||
| .deliveryId(deliveryId) | ||
| .requestType(AiRequestType.DELIVERY_DEADLINE) | ||
| .prompt(prompt) | ||
| .requestPayload(payload) | ||
| .build(); | ||
|
|
||
| AiResponse aiResponse = mock(AiResponse.class); | ||
|
|
||
| when(deadlinePromptGenerator.generatePrompt(event)).thenReturn(prompt); | ||
| when(objectMapper.writeValueAsString(event)).thenReturn(payload); | ||
| when(aiMessageService.saveMessage(deliveryId, AiRequestType.DELIVERY_DEADLINE, prompt, payload)) | ||
| .thenReturn(savedMessage); | ||
| when(aiClient.generate(prompt)).thenReturn(aiResponse); | ||
| when(aiResponse.getText()).thenReturn("{json}"); | ||
| when(aiResponseParser.parseDeadlineResponse("{json}")) | ||
| .thenReturn(AiDeadlineResult.of(null, deadline, message)); | ||
|
|
||
| AiDeadlineResult result = aiService.generateDeadline(event); | ||
|
|
||
| assertThat(result.getAiMessageId()).isEqualTo(aiMessageId); | ||
| assertThat(result.getFinalDepartureDeadline()).isEqualTo(deadline); | ||
| assertThat(result.getMessage()).isEqualTo(message); | ||
|
|
||
| verify(aiMessageService, times(1)).markCompleted(aiMessageId, deadline, message); | ||
| verify(aiMessageService, never()).markFailed(any(), anyString()); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("generateDeadline - AI 응답이 비어있으면 실패 처리 후 예외 발생") | ||
| void generateDeadline_Fail_EmptyAiResponse() throws JsonProcessingException { | ||
| String prompt = "프롬프트"; | ||
| String payload = "{\"deliveryId\":\"123\"}"; | ||
|
|
||
| AiMessage savedMessage = AiMessage.builder() | ||
| .aiMessageId(aiMessageId) | ||
| .deliveryId(deliveryId) | ||
| .requestType(AiRequestType.DELIVERY_DEADLINE) | ||
| .prompt(prompt) | ||
| .requestPayload(payload) | ||
| .build(); | ||
|
|
||
| AiResponse aiResponse = mock(AiResponse.class); | ||
|
|
||
| when(deadlinePromptGenerator.generatePrompt(event)).thenReturn(prompt); | ||
| when(objectMapper.writeValueAsString(event)).thenReturn(payload); | ||
| when(aiMessageService.saveMessage(deliveryId, AiRequestType.DELIVERY_DEADLINE, prompt, payload)) | ||
| .thenReturn(savedMessage); | ||
| when(aiClient.generate(prompt)).thenReturn(aiResponse); | ||
| when(aiResponse.getText()).thenReturn(" "); | ||
|
|
||
| IllegalStateException exception = assertThrows( | ||
| IllegalStateException.class, | ||
| () -> aiService.generateDeadline(event) | ||
| ); | ||
|
|
||
| assertThat(exception.getMessage()).isEqualTo("AI 응답이 비어 있습니다."); | ||
| verify(aiMessageService, times(1)).markFailed(eq(aiMessageId), eq("AI 응답이 비어 있습니다.")); | ||
| verify(aiMessageService, never()).markCompleted(any(), any(), anyString()); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("generateDeadline - 요청 payload 변환 실패 시 커스텀 예외 발생") | ||
| void generateDeadline_Fail_RequestPayloadConvert() throws JsonProcessingException { | ||
| when(deadlinePromptGenerator.generatePrompt(event)).thenReturn("프롬프트"); | ||
| when(objectMapper.writeValueAsString(event)) | ||
| .thenThrow(new JsonProcessingException("직렬화 실패") { | ||
| }); | ||
|
|
||
| CustomException exception = assertThrows( | ||
| CustomException.class, | ||
| () -> aiService.generateDeadline(event) | ||
| ); | ||
|
|
||
| assertThat(exception.getErrorCode()).isEqualTo(AiErrorCode.AI_REQUEST_PAYLOAD_CONVERT_FAILED); | ||
| verify(aiMessageService, never()).saveMessage(any(), any(), anyString(), anyString()); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.