Skip to content

Commit

Permalink
ADM-987 [backend]: make @value autowire in test (#1537)
Browse files Browse the repository at this point in the history
* ADM-987 [backend]: adjust the logs for share

* ADM-987 [backend]: fix test

* ADM-987 [backend]: fix sonar issues

* ADM-987 [backend]: fix sonar issues

* ADM-987 [backend]: fix sonar issues

* ADM-987 [backend]: change the order for the expired files

* ADM-987 [backend]: modify the log to make it clearer

* ADM-987 [backend]: modify the log to make it clearer

* ADM-987 [backend]: fix the calendar name

* ADM-988 [backend]: fix comments

* ADM-987 [backend]: fix comments

* ADM-987 [backend]: fix comments

* ADM-987 [backend]: fix comments

* ADM-987 [backend]: fix test

* ADM-987 [backend]: make @value autowire in test

* ADM-987 [backend]: fix the exception when file is expired but not deleted

* ADM-987 [backend]: fix sonar
  • Loading branch information
zhou-yinyuan authored Jul 18, 2024
1 parent 84d148b commit c98e739
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import java.net.URI;

@Component
@Profile(value = "e2e")
@Profile(value = { "e2e", "test" })
public class MockJiraUriGenerator implements JiraUriGenerator {

@Value("${jira.url}")
Expand Down
31 changes: 23 additions & 8 deletions backend/src/main/java/heartbeat/service/report/ReportService.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import heartbeat.util.TimeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.core.io.InputStreamResource;
import org.springframework.stereotype.Service;

Expand All @@ -37,6 +38,8 @@
@Slf4j
public class ReportService {

public static final String GET_SHARE_DETAIL_ERROR_LOG = "Failed to get share details result, reportId: {}";

private final CSVFileGenerator csvFileGenerator;

private final AsyncMetricsDataHandler asyncMetricsDataHandler;
Expand Down Expand Up @@ -101,26 +104,38 @@ private boolean isNotGenerateMetricError(ReportMetricsError reportMetricsError)
}

public ShareApiDetailsResponse getShareReportInfo(String uuid) {
List<String> reportUrls;
List<Pair<String, String>> timestampAndReportUrls;
try {
reportUrls = fileRepository.getFiles(FileType.REPORT, uuid)
timestampAndReportUrls = fileRepository.getFiles(FileType.REPORT, uuid)
.stream()
.map(it -> it.split(FILENAME_SEPARATOR))
.filter(it -> it.length > 2)
.map(it -> this.generateReportCallbackUrl(uuid, it[1], it[2]))
.distinct()
.filter(it -> it.length == 4)
.map(it -> Pair.of(it[3], this.generateReportCallbackUrl(uuid, it[1], it[2])))
.toList();
}
catch (NotFoundException e) {
log.error("Failed to get share details result, reportId: {}", uuid);
log.error(GET_SHARE_DETAIL_ERROR_LOG, uuid);
throw new NotFoundException(String.format("Don't find the %s folder in the report files", uuid));
}

if (reportUrls.isEmpty()) {
log.error("Failed to get share details result, reportId: {}", uuid);
if (timestampAndReportUrls.isEmpty()) {
log.error(GET_SHARE_DETAIL_ERROR_LOG, uuid);
throw new NotFoundException(
String.format("Don't get the data, please check the uuid: %s, maybe it's expired or error", uuid));
}

boolean isExpired = timestampAndReportUrls.stream()
.map(Pair::getLeft)
.distinct()
.map(Long::parseLong)
.anyMatch(it -> fileRepository.isExpired(System.currentTimeMillis(), it));
if (isExpired) {
log.error(GET_SHARE_DETAIL_ERROR_LOG, uuid);
throw new NotFoundException(
String.format("Don't get the data, please check the uuid: %s, maybe it's expired or error", uuid));
}
List<String> reportUrls = timestampAndReportUrls.stream().map(Pair::getRight).distinct().toList();

List<SavedRequestInfo> savedRequestInfoList = fileRepository.getFiles(FileType.CONFIGS, uuid)
.stream()
.map(it -> it.split(FILENAME_SEPARATOR))
Expand Down
38 changes: 18 additions & 20 deletions backend/src/test/java/heartbeat/repository/FileRepositoryTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,20 @@
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedConstruction;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.core.io.InputStreamResource;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import java.io.BufferedReader;
import java.io.File;
Expand Down Expand Up @@ -54,24 +55,22 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
@ExtendWith({ SpringExtension.class })
@Slf4j
@SpringBootTest
@ActiveProfiles("test")
class FileRepositoryTest {

private static final String BASE_PATH = "./app";

private static final String TEST_UUID = "test-uuid";

@Value("${heartbeat.expiredDays}")
private int expiredDays;

private static final long ONE_DAY_MILLISECONDS = 1000L * 3600 * 24;

@Mock
@MockBean
Gson gson;

@InjectMocks
@Autowired
FileRepository fileRepository;

ObjectMapper objectMapper = new ObjectMapper();
Expand Down Expand Up @@ -678,7 +677,7 @@ void shouldRemoveSuccessfullyWhenDirectoryIsEmpty() throws IOException {
void shouldRemoveSuccessfullyWhenDirectoryIsNotEmpty() throws IOException {
FileType fileType = FileType.CSV;
long timestamp = 123L;
long currentTimestamp = ONE_DAY_MILLISECONDS * expiredDays + timestamp + 10000L;
long currentTimestamp = ONE_DAY_MILLISECONDS * fileRepository.expiredDays + timestamp + 10000L;

String expectedFilePath = "./app/output/csv/" + TEST_UUID;
Path path = Paths.get(expectedFilePath);
Expand All @@ -701,7 +700,7 @@ void shouldRemoveSuccessfullyWhenDirectoryIsNotEmpty() throws IOException {
void shouldRemoveErrorWhenFileIsNotExpired() throws IOException {
FileType fileType = FileType.CSV;
long timestamp = 123L;
long currentTimestamp = ONE_DAY_MILLISECONDS * expiredDays + timestamp - 10000L;
long currentTimestamp = ONE_DAY_MILLISECONDS * fileRepository.expiredDays + timestamp - 10000L;

Path path = Paths.get("./app/output/csv/" + TEST_UUID);
Files.createDirectories(path);
Expand All @@ -724,7 +723,7 @@ void shouldRemoveErrorWhenFileIsNotExpired() throws IOException {
void shouldRemoveErrorWhenDeleteThrowException() throws IOException {
FileType fileType = FileType.CSV;
long timestamp = 123L;
long currentTimestamp = ONE_DAY_MILLISECONDS * expiredDays + timestamp + 10000L;
long currentTimestamp = ONE_DAY_MILLISECONDS * fileRepository.expiredDays + timestamp + 10000L;

Path path = Paths.get("./app/output/csv/" + TEST_UUID);
Files.createDirectories(path);
Expand Down Expand Up @@ -868,7 +867,7 @@ class IsExpired {
@Test
void shouldExpired() {
long startTime = 123L;
long endTime = startTime + ONE_DAY_MILLISECONDS * expiredDays + 10000L;
long endTime = startTime + ONE_DAY_MILLISECONDS * fileRepository.expiredDays + 10000L;

boolean expired = fileRepository.isExpired(endTime, startTime);

Expand All @@ -877,9 +876,8 @@ void shouldExpired() {

@Test
void shouldNotExpired() {
System.out.println(expiredDays);
long startTime = 123L;
long endTime = startTime + ONE_DAY_MILLISECONDS * expiredDays - 10000L;
long endTime = startTime + ONE_DAY_MILLISECONDS * fileRepository.expiredDays - 10000L;

boolean expired = fileRepository.isExpired(endTime, startTime);

Expand All @@ -891,14 +889,14 @@ void shouldNotExpired() {
@Nested
class ReadStringFromCsvFile {

@BeforeAll
static void beforeAll() throws IOException {
@BeforeEach
void beforeEach() throws IOException {
Path path = Paths.get("./app/output/csv/test-uuid");
Files.createDirectories(path);
}

@AfterAll
static void afterAll() throws IOException {
@AfterEach
void afterEach() throws IOException {
Path path = Paths.get("./app/output/csv/test-uuid");
Files.deleteIfExists(path);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

Expand Down Expand Up @@ -396,6 +397,7 @@ void shouldGetReportUrlsSuccessfully() {
DeploymentEnvironment.builder().id("1").name("pipeline2").step("step1").build(),
DeploymentEnvironment.builder().id("1").name("pipeline2").step("step2").build()
)).build());
when(fileRepository.isExpired(anyLong(), anyLong())).thenReturn(false);

ShareApiDetailsResponse shareReportInfo = reportService.getShareReportInfo(TEST_UUID);
List<String> metrics = shareReportInfo.getMetrics();
Expand All @@ -418,10 +420,11 @@ void shouldGetReportUrlsSuccessfully() {
assertEquals("pipeline2/step1", pipelines.get(2));
assertEquals("pipeline2/step2", pipelines.get(3));

verify(fileRepository).getFiles(FileType.CONFIGS, TEST_UUID);
verify(fileRepository).getFiles(FileType.REPORT, TEST_UUID);
verify(fileRepository).getFiles(FileType.CONFIGS, TEST_UUID);
verify(fileRepository).readFileByType(eq(FileType.CONFIGS), eq(TEST_UUID), eq("0-0-0"), any(), any());
verify(fileRepository).readFileByType(eq(FileType.CONFIGS), eq(TEST_UUID), eq("9-9-9"), any(), any());
verify(fileRepository, times(2)).isExpired(anyLong(), anyLong());

}

Expand All @@ -447,6 +450,19 @@ void shouldThrowExceptionWhenFilenameIsInvalid() {
verify(fileRepository).getFiles(FileType.REPORT, TEST_UUID);
}

@Test
void shouldThrowExceptionWhenFileIsExpired() {
when(fileRepository.getFiles(FileType.REPORT, TEST_UUID)).thenReturn(List.of("board-1-2-3", "board-2-3-4"));
when(fileRepository.isExpired(anyLong(), anyLong())).thenReturn(true);

NotFoundException notFoundException = assertThrows(NotFoundException.class, () -> reportService.getShareReportInfo(TEST_UUID));

assertEquals("Don't get the data, please check the uuid: test-uuid, maybe it's expired or error", notFoundException.getMessage());

verify(fileRepository).getFiles(FileType.REPORT, TEST_UUID);
verify(fileRepository).isExpired(anyLong(), anyLong());
}

}

@Nested
Expand Down
2 changes: 1 addition & 1 deletion backend/src/test/resources/application-test.yml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
heartbeat:
expiredDays: ${EXPIRED_DAYS:9}
expiredDays: 9999

0 comments on commit c98e739

Please sign in to comment.