Implement task scheduling system (#1427)

* Implement task scheduling system

* Remove tests
This commit is contained in:
Aditya Chandel
2025-10-23 22:49:42 -06:00
committed by GitHub
parent 2f6ae855dd
commit 5fe62ac576
130 changed files with 3355 additions and 1608 deletions
@@ -3,10 +3,10 @@ package com.adityachandel.booklore;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.service.BookDownloadService;
import com.adityachandel.booklore.service.BookQueryService;
import com.adityachandel.booklore.service.BookService;
import com.adityachandel.booklore.service.UserProgressService;
import com.adityachandel.booklore.service.book.BookDownloadService;
import com.adityachandel.booklore.service.book.BookQueryService;
import com.adityachandel.booklore.service.book.BookService;
import com.adityachandel.booklore.service.user.UserProgressService;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import com.adityachandel.booklore.util.FileService;
import org.junit.jupiter.api.BeforeEach;
@@ -1,7 +1,7 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.progress.KoreaderProgress;
import com.adityachandel.booklore.service.KoreaderService;
import com.adityachandel.booklore.service.koreader.KoreaderService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.*;
@@ -1,7 +1,7 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.KoreaderUser;
import com.adityachandel.booklore.service.KoreaderUserService;
import com.adityachandel.booklore.service.koreader.KoreaderUserService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.*;
@@ -1,53 +0,0 @@
package com.adityachandel.booklore.scheduler;
import com.adityachandel.booklore.repository.MetadataFetchJobRepository;
import com.adityachandel.booklore.service.scheduler.MetadataFetchCleanupService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.*;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import static org.mockito.Mockito.*;
class MetadataFetchCleanupServiceTest {
@Mock
private MetadataFetchJobRepository metadataFetchJobRepository;
@InjectMocks
private MetadataFetchCleanupService cleanupService;
@Captor
private ArgumentCaptor<Instant> instantCaptor;
@BeforeEach
void setup() {
MockitoAnnotations.openMocks(this);
}
@Test
void cleanupOldMetadataFetchJobs_shouldCallRepositoryWithCorrectCutoff() {
when(metadataFetchJobRepository.deleteAllByCompletedAtBefore(any())).thenReturn(5);
cleanupService.cleanupOldMetadataFetchJobs();
verify(metadataFetchJobRepository, times(1)).deleteAllByCompletedAtBefore(instantCaptor.capture());
Instant cutoff = instantCaptor.getValue();
Instant expectedCutoff = Instant.now().minus(5, ChronoUnit.DAYS);
long deltaSeconds = Math.abs(cutoff.getEpochSecond() - expectedCutoff.getEpochSecond());
assert deltaSeconds < 5 : "Cutoff instant should be about 5 days ago";
}
@Test
void cleanupOldMetadataFetchJobs_shouldLogDeletedCount() {
when(metadataFetchJobRepository.deleteAllByCompletedAtBefore(any())).thenReturn(10);
cleanupService.cleanupOldMetadataFetchJobs();
verify(metadataFetchJobRepository, times(1)).deleteAllByCompletedAtBefore(any());
}
}
@@ -7,6 +7,7 @@ import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.AdditionalFileType;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.service.file.AdditionalFileService;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -11,6 +11,7 @@ import com.adityachandel.booklore.model.entity.BookNoteEntity;
import com.adityachandel.booklore.repository.BookNoteRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.service.book.BookNoteService;
import jakarta.persistence.EntityNotFoundException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -14,6 +14,7 @@ import com.adityachandel.booklore.model.enums.MetadataProvider;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.BookReviewRepository;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.book.BookReviewService;
import com.adityachandel.booklore.service.metadata.BookReviewUpdateService;
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
import jakarta.persistence.EntityNotFoundException;
@@ -14,6 +14,7 @@ import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.UserBookProgressRepository;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.repository.KoreaderUserRepository;
import com.adityachandel.booklore.service.koreader.KoreaderService;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.*;
@@ -11,6 +11,7 @@ import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.model.entity.KoreaderUserEntity;
import com.adityachandel.booklore.repository.KoreaderUserRepository;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.service.koreader.KoreaderUserService;
import com.adityachandel.booklore.util.Md5Util;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -30,7 +31,8 @@ class KoreaderUserServiceTest {
@Mock UserRepository userRepository;
@Mock KoreaderUserRepository koreaderUserRepository;
@Mock com.adityachandel.booklore.mapper.KoreaderUserMapper koreaderUserMapper;
@InjectMocks KoreaderUserService service;
@InjectMocks
KoreaderUserService service;
private BookLoreUser ownerDto;
private BookLoreUserEntity ownerEntity;
@@ -13,6 +13,7 @@ import com.adityachandel.booklore.model.enums.FetchedMetadataProposalStatus;
import com.adityachandel.booklore.model.enums.MetadataFetchTaskStatus;
import com.adityachandel.booklore.repository.MetadataFetchJobRepository;
import com.adityachandel.booklore.repository.MetadataFetchProposalRepository;
import com.adityachandel.booklore.service.metadata.MetadataTaskService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.*;
@@ -24,7 +25,7 @@ import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
class MetadataTaskServiceTest {
class MetadataTaskHistoryServiceTest {
@Mock
private MetadataFetchJobRepository jobRepository;
@@ -11,6 +11,7 @@ import com.adityachandel.booklore.repository.BookOpdsRepository;
import com.adityachandel.booklore.repository.ShelfRepository;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.service.library.LibraryService;
import com.adityachandel.booklore.service.opds.OpdsBookService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -9,6 +9,7 @@ import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.model.entity.OpdsUserV2Entity;
import com.adityachandel.booklore.repository.OpdsUserV2Repository;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.service.opds.OpdsUserV2Service;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
@@ -1,157 +0,0 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.model.dto.response.TaskStatusResponse;
import com.adityachandel.booklore.model.entity.TaskEntity;
import com.adityachandel.booklore.model.enums.TaskType;
import com.adityachandel.booklore.repository.TaskRepository;
import com.adityachandel.booklore.task.TaskStatus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.*;
import java.time.LocalDateTime;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class TaskHistoryServiceTest {
@Mock
private TaskRepository taskRepository;
@Mock
private TaskMetadataService taskMetadataService;
@InjectMocks
private TaskHistoryService taskHistoryService;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
void testCreateTask() {
String taskId = "task1";
TaskType type = TaskType.CLEAR_CBX_CACHE;
Long userId = 123L;
Map<String, Object> options = new HashMap<>();
TaskEntity mockTask = TaskEntity.builder()
.id(taskId)
.type(type)
.status(TaskStatus.ACCEPTED)
.userId(userId)
.createdAt(LocalDateTime.now())
.progressPercentage(0)
.taskOptions(options)
.build();
when(taskRepository.save(any(TaskEntity.class))).thenReturn(mockTask);
TaskEntity result = taskHistoryService.createTask(taskId, type, userId, options);
assertNotNull(result);
assertEquals(taskId, result.getId());
assertEquals(type, result.getType());
assertEquals(TaskStatus.ACCEPTED, result.getStatus());
assertEquals(userId, result.getUserId());
}
@Test
void testUpdateTaskStatus() {
String taskId = "task2";
TaskEntity task = TaskEntity.builder()
.id(taskId)
.type(TaskType.CLEAR_PDF_CACHE)
.status(TaskStatus.ACCEPTED)
.build();
when(taskRepository.findById(taskId)).thenReturn(Optional.of(task));
when(taskRepository.save(any(TaskEntity.class))).thenReturn(task);
taskHistoryService.updateTaskStatus(taskId, TaskStatus.COMPLETED, "Done");
assertEquals(TaskStatus.COMPLETED, task.getStatus());
assertEquals("Done", task.getMessage());
assertEquals(100, task.getProgressPercentage());
assertNotNull(task.getCompletedAt());
}
@Test
void testUpdateTaskStatus_TaskNotFound() {
String taskId = "notfound";
when(taskRepository.findById(taskId)).thenReturn(Optional.empty());
assertDoesNotThrow(() -> taskHistoryService.updateTaskStatus(taskId, TaskStatus.COMPLETED, "Done"));
verify(taskRepository, never()).save(any());
}
@Test
void testUpdateTaskError() {
String taskId = "task3";
TaskEntity task = TaskEntity.builder()
.id(taskId)
.type(TaskType.RE_SCAN_LIBRARY)
.status(TaskStatus.ACCEPTED)
.build();
when(taskRepository.findById(taskId)).thenReturn(Optional.of(task));
when(taskRepository.save(any(TaskEntity.class))).thenReturn(task);
taskHistoryService.updateTaskError(taskId, "Some error");
assertEquals(TaskStatus.FAILED, task.getStatus());
assertEquals("Some error", task.getErrorDetails());
assertNotNull(task.getCompletedAt());
}
@Test
void testUpdateTaskError_TaskNotFound() {
String taskId = "notfound";
when(taskRepository.findById(taskId)).thenReturn(Optional.empty());
assertDoesNotThrow(() -> taskHistoryService.updateTaskError(taskId, "error"));
verify(taskRepository, never()).save(any());
}
@Test
void testGetLatestTasksForEachType() {
TaskEntity cbxTask = TaskEntity.builder()
.id("t1")
.type(TaskType.CLEAR_CBX_CACHE)
.status(TaskStatus.COMPLETED)
.build();
TaskEntity pdfTask = TaskEntity.builder()
.id("t2")
.type(TaskType.CLEAR_PDF_CACHE)
.status(TaskStatus.ACCEPTED)
.build();
List<TaskEntity> latestTasks = Arrays.asList(cbxTask, pdfTask);
when(taskRepository.findLatestTaskForEachType()).thenReturn(latestTasks);
when(taskMetadataService.getMetadataForTaskType(any(TaskType.class))).thenReturn(Collections.emptyMap());
TaskStatusResponse response = taskHistoryService.getLatestTasksForEachType();
assertNotNull(response);
assertEquals(TaskType.values().length, response.getTasks().size());
assertTrue(response.getTasks().stream().anyMatch(t -> t.getType() == TaskType.CLEAR_CBX_CACHE));
assertTrue(response.getTasks().stream().anyMatch(t -> t.getType() == TaskType.CLEAR_PDF_CACHE));
}
@Test
void testGetLatestTasksForEachType_NoTasks() {
when(taskRepository.findLatestTaskForEachType()).thenReturn(Collections.emptyList());
when(taskMetadataService.getMetadataForTaskType(any(TaskType.class))).thenReturn(Collections.emptyMap());
TaskStatusResponse response = taskHistoryService.getLatestTasksForEachType();
assertNotNull(response);
assertEquals(TaskType.values().length, response.getTasks().size());
assertTrue(response.getTasks().stream().allMatch(t -> t.getId() == null));
}
@Test
void testCreateTask_NullOptions() {
String taskId = "task4";
TaskType type = TaskType.RE_SCAN_LIBRARY;
Long userId = 456L;
TaskEntity mockTask = TaskEntity.builder()
.id(taskId)
.type(type)
.status(TaskStatus.ACCEPTED)
.userId(userId)
.createdAt(LocalDateTime.now())
.progressPercentage(0)
.taskOptions(null)
.build();
when(taskRepository.save(any(TaskEntity.class))).thenReturn(mockTask);
TaskEntity result = taskHistoryService.createTask(taskId, type, userId, null);
assertNotNull(result);
assertEquals(taskId, result.getId());
assertNull(result.getTaskOptions());
}
}
@@ -1,107 +0,0 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.exception.APIException;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.dto.request.TaskCreateRequest;
import com.adityachandel.booklore.model.dto.response.TaskCancelResponse;
import com.adityachandel.booklore.model.dto.response.TaskCreateResponse;
import com.adityachandel.booklore.model.enums.TaskType;
import com.adityachandel.booklore.task.TaskCancellationManager;
import com.adityachandel.booklore.task.TaskStatus;
import com.adityachandel.booklore.task.tasks.Task;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.*;
import org.springframework.http.HttpStatus;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class TaskServiceTest {
@Mock AuthenticationService authenticationService;
@Mock TaskHistoryService taskHistoryService;
@Mock TaskCancellationManager cancellationManager;
@Mock Executor taskExecutor;
@Mock ObjectMapper objectMapper;
@Mock Task task;
TaskService taskService;
BookLoreUser user;
TaskCreateRequest request;
@BeforeEach
void setUp() throws Exception {
MockitoAnnotations.openMocks(this);
user = new BookLoreUser();
user.setId(1L);
user.setUsername("testuser");
request = new TaskCreateRequest();
request.setTaskType(TaskType.CLEAR_CBX_CACHE);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(task.getTaskType()).thenReturn(TaskType.CLEAR_CBX_CACHE);
when(task.execute(any())).thenReturn(TaskCreateResponse.builder()
.taskType(TaskType.CLEAR_CBX_CACHE)
.status(TaskStatus.COMPLETED)
.build());
taskService = new TaskService(authenticationService, taskHistoryService, List.of(task), cancellationManager, taskExecutor, objectMapper);
}
@Test
void testRunSyncTaskSuccess() {
TaskCreateResponse response = taskService.run(request);
assertNotNull(response);
assertEquals(TaskType.CLEAR_CBX_CACHE, response.getTaskType());
assertEquals(TaskStatus.COMPLETED, response.getStatus());
verify(taskHistoryService).createTask(anyString(), eq(TaskType.CLEAR_CBX_CACHE), eq(1L), any());
verify(taskHistoryService).updateTaskStatus(anyString(), eq(TaskStatus.IN_PROGRESS), anyString());
verify(taskHistoryService).updateTaskStatus(anyString(), eq(TaskStatus.COMPLETED), anyString());
}
@Test
void testRunWithNullRequestThrowsException() {
APIException ex = assertThrows(APIException.class, () -> taskService.run(null));
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatus());
}
@Test
void testRunWithNullTaskTypeThrowsException() {
request.setTaskType(null);
APIException ex = assertThrows(APIException.class, () -> taskService.run(request));
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatus());
}
@Test
void testCancelTaskNotFoundThrowsException() {
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
APIException ex = assertThrows(APIException.class, () -> taskService.cancelTask("notfound"));
assertEquals(HttpStatus.NOT_FOUND, ex.getStatus());
}
@Test
void testCancelTaskSuccess() throws Exception {
String taskId = "task123";
var field = TaskService.class.getDeclaredField("runningTasks");
field.setAccessible(true);
@SuppressWarnings("unchecked")
Map<TaskType, String> runningTasks = (Map<TaskType, String>) field.get(taskService);
runningTasks.put(TaskType.RE_SCAN_LIBRARY, taskId);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
TaskCancelResponse response = taskService.cancelTask(taskId);
assertTrue(response.isCancelled());
assertEquals(taskId, response.getTaskId());
verify(cancellationManager).cancelTask(taskId);
verify(taskHistoryService).updateTaskStatus(taskId, TaskStatus.CANCELLED, "Task cancellation requested by user");
}
}
@@ -12,8 +12,8 @@ import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.FileProcessStatus;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.BookCreatorService;
import com.adityachandel.booklore.service.FileFingerprint;
import com.adityachandel.booklore.service.book.BookCreatorService;
import com.adityachandel.booklore.service.file.FileFingerprint;
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
import com.adityachandel.booklore.util.FileService;
import jakarta.persistence.EntityManager;
@@ -4,7 +4,7 @@ import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.FileFingerprint;
import com.adityachandel.booklore.service.file.FileFingerprint;
import com.adityachandel.booklore.service.event.AdminEventBroadcaster;
import com.adityachandel.booklore.service.event.BookEventBroadcaster;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
@@ -12,7 +12,7 @@ import com.adityachandel.booklore.service.event.BookEventBroadcaster;
import com.adityachandel.booklore.service.event.AdminEventBroadcaster;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.FileFingerprint;
import com.adityachandel.booklore.service.file.FileFingerprint;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.util.FileUtils;
@@ -14,10 +14,10 @@ import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.metadata.BookMetadataUpdater;
import com.adityachandel.booklore.service.metadata.extractor.MetadataExtractorFactory;
import com.adityachandel.booklore.task.RescanLibraryContext;
import com.adityachandel.booklore.task.options.RescanLibraryContext;
import com.adityachandel.booklore.task.TaskCancellationManager;
import com.adityachandel.booklore.task.TaskStatus;
import com.adityachandel.booklore.task.tasks.options.LibraryRescanOptions;
import com.adityachandel.booklore.task.options.LibraryRescanOptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -228,7 +228,7 @@ class LibraryRescanHelperTest {
assertEquals(3, payloads.size());
assertEquals(0, payloads.get(0).getProgress());
assertEquals(TaskStatus.IN_PROGRESS, payloads.get(0).getTaskStatus());
assertEquals(TaskType.RE_SCAN_LIBRARY, payloads.get(0).getTaskType());
assertEquals(TaskType.REFRESH_LIBRARY_METADATA, payloads.get(0).getTaskType());
assertEquals(TaskStatus.IN_PROGRESS, payloads.get(1).getTaskStatus());
assertEquals(100, payloads.get(2).getProgress());
assertEquals(TaskStatus.COMPLETED, payloads.get(2).getTaskStatus());
@@ -8,7 +8,6 @@ import com.adityachandel.booklore.model.dto.Library;
import com.adityachandel.booklore.model.dto.OpdsUserV2;
import com.adityachandel.booklore.model.entity.ShelfEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.service.OpdsBookService;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -0,0 +1,260 @@
package com.adityachandel.booklore.service.task;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.exception.APIException;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.dto.request.TaskCronConfigRequest;
import com.adityachandel.booklore.model.dto.response.CronConfig;
import com.adityachandel.booklore.model.entity.TaskCronConfigurationEntity;
import com.adityachandel.booklore.model.enums.TaskType;
import com.adityachandel.booklore.repository.TaskCronConfigurationRepository;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.HttpStatus;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class TaskCronServiceTest {
@Mock
private TaskCronConfigurationRepository repository;
@Mock
private AuthenticationService authService;
@InjectMocks
private TaskCronService service;
private AutoCloseable mocks;
@BeforeEach
void setUp() {
mocks = MockitoAnnotations.openMocks(this);
}
@AfterEach
void tearDown() throws Exception {
if (mocks != null) {
mocks.close();
}
}
private TaskCronConfigurationEntity buildEntity(TaskType type, String cron, boolean enabled) {
return TaskCronConfigurationEntity.builder()
.id(1L)
.taskType(type)
.cronExpression(cron)
.enabled(enabled)
.createdBy(10L)
.createdAt(LocalDateTime.now())
.updatedAt(LocalDateTime.now())
.build();
}
@Test
void testGetAllEnabledCronConfigs_returnsList() {
List<TaskCronConfigurationEntity> configs = List.of(
buildEntity(TaskType.CLEAR_CBX_CACHE, "0 0 1 * * *", true)
);
when(repository.findByEnabledTrue()).thenReturn(configs);
List<TaskCronConfigurationEntity> result = service.getAllEnabledCronConfigs();
assertEquals(1, result.size());
assertEquals(TaskType.CLEAR_CBX_CACHE, result.get(0).getTaskType());
}
@Test
void testGetCronConfigOrDefault_existingConfig() {
TaskType type = TaskType.CLEAR_CBX_CACHE;
TaskCronConfigurationEntity entity = buildEntity(type, "0 0 1 * * *", true);
when(repository.findByTaskType(type)).thenReturn(Optional.of(entity));
CronConfig config = service.getCronConfigOrDefault(type);
assertEquals(type, config.getTaskType());
assertEquals("0 0 1 * * *", config.getCronExpression());
assertTrue(config.getEnabled());
}
@Test
void testGetCronConfigOrDefault_noConfig_returnsDefault() {
TaskType type = TaskType.CLEAR_CBX_CACHE;
when(repository.findByTaskType(type)).thenReturn(Optional.empty());
CronConfig config = service.getCronConfigOrDefault(type);
assertEquals(type, config.getTaskType());
assertFalse(config.getEnabled());
assertNull(config.getCronExpression());
}
@Test
void testGetCronConfigOrDefault_invalidTaskType_throws() {
TaskType type = mock(TaskType.class);
when(type.isCronSupported()).thenReturn(false);
APIException ex = assertThrows(APIException.class, () -> service.getCronConfigOrDefault(type));
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatus());
assertTrue(ex.getMessage().contains("does not support cron scheduling"));
}
@Test
void testGetCronConfigOrDefault_nullTaskType_throws() {
APIException ex = assertThrows(APIException.class, () -> service.getCronConfigOrDefault(null));
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatus());
assertTrue(ex.getMessage().contains("Task type is required"));
}
@Test
void testPatchCronConfig_updateExisting() {
TaskType type = TaskType.CLEAR_CBX_CACHE;
BookLoreUser user = BookLoreUser.builder().id(10L).build();
TaskCronConfigurationEntity entity = buildEntity(type, "0 0 1 * * *", false);
when(authService.getAuthenticatedUser()).thenReturn(user);
when(repository.findByTaskType(type)).thenReturn(Optional.of(entity));
when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));
TaskCronConfigRequest req = new TaskCronConfigRequest();
req.setCronExpression("0 0 2 * * *");
req.setEnabled(true);
CronConfig config = service.patchCronConfig(type, req);
assertEquals("0 0 2 * * *", config.getCronExpression());
assertTrue(config.getEnabled());
}
@Test
void testPatchCronConfig_createNew() {
TaskType type = TaskType.CLEAR_CBX_CACHE;
BookLoreUser user = BookLoreUser.builder().id(10L).build();
when(authService.getAuthenticatedUser()).thenReturn(user);
when(repository.findByTaskType(type)).thenReturn(Optional.empty());
when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));
TaskCronConfigRequest req = new TaskCronConfigRequest();
req.setCronExpression("0 0 3 * * *");
req.setEnabled(true);
CronConfig config = service.patchCronConfig(type, req);
assertEquals("0 0 3 * * *", config.getCronExpression());
assertTrue(config.getEnabled());
assertEquals(type, config.getTaskType());
}
@Test
void testPatchCronConfig_invalidCronExpression_throws() {
TaskType type = TaskType.CLEAR_CBX_CACHE;
BookLoreUser user = BookLoreUser.builder().id(10L).build();
when(authService.getAuthenticatedUser()).thenReturn(user);
when(repository.findByTaskType(type)).thenReturn(Optional.empty());
TaskCronConfigRequest req = new TaskCronConfigRequest();
req.setCronExpression("invalid cron");
req.setEnabled(true);
APIException ex = assertThrows(APIException.class, () -> service.patchCronConfig(type, req));
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatus());
assertTrue(ex.getMessage().contains("Invalid cron expression format"));
}
@Test
void testPatchCronConfig_invalidTaskType_throws() {
TaskType type = mock(TaskType.class);
when(type.isCronSupported()).thenReturn(false);
TaskCronConfigRequest req = new TaskCronConfigRequest();
req.setCronExpression("0 0 1 * * *");
req.setEnabled(true);
APIException ex = assertThrows(APIException.class, () -> service.patchCronConfig(type, req));
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatus());
assertTrue(ex.getMessage().contains("does not support cron scheduling"));
}
@Test
void testValidateCronExpression_valid() {
String cron = "0 0 1 * * *";
assertDoesNotThrow(() -> {
var method = TaskCronService.class.getDeclaredMethod("validateCronExpression", String.class);
method.setAccessible(true);
method.invoke(service, cron);
});
}
@Test
void testValidateCronExpression_invalidFieldCount() {
String cron = "0 0 1 * *";
Exception ex = assertThrows(Exception.class, () -> {
var method = TaskCronService.class.getDeclaredMethod("validateCronExpression", String.class);
method.setAccessible(true);
method.invoke(service, cron);
});
Throwable cause = ex.getCause();
assertNotNull(cause);
assertInstanceOf(APIException.class, cause);
assertTrue(cause.getMessage().contains("Expected 6 fields"));
}
@Test
void testValidateCronExpression_invalidFormat() {
String cron = "invalid cron expression";
Exception ex = assertThrows(Exception.class, () -> {
var method = TaskCronService.class.getDeclaredMethod("validateCronExpression", String.class);
method.setAccessible(true);
method.invoke(service, cron);
});
Throwable cause = ex.getCause();
assertNotNull(cause);
assertInstanceOf(APIException.class, cause);
assertTrue(cause.getMessage().contains("Invalid cron expression format"));
}
@Test
void testValidateTaskTypeForCron_supported() {
TaskType type = TaskType.CLEAR_CBX_CACHE;
assertDoesNotThrow(() -> {
var method = TaskCronService.class.getDeclaredMethod("validateTaskTypeForCron", TaskType.class);
method.setAccessible(true);
method.invoke(service, type);
});
}
@Test
void testValidateTaskTypeForCron_notSupported() {
TaskType type = mock(TaskType.class);
when(type.isCronSupported()).thenReturn(false);
Exception ex = assertThrows(Exception.class, () -> {
var method = TaskCronService.class.getDeclaredMethod("validateTaskTypeForCron", TaskType.class);
method.setAccessible(true);
method.invoke(service, type);
});
Throwable cause = ex.getCause();
assertNotNull(cause);
assertInstanceOf(APIException.class, cause);
assertTrue(cause.getMessage().contains("does not support cron scheduling"));
}
@Test
void testValidateTaskTypeForCron_nullType() {
Exception ex = assertThrows(Exception.class, () -> {
var method = TaskCronService.class.getDeclaredMethod("validateTaskTypeForCron", TaskType.class);
method.setAccessible(true);
method.invoke(service, (Object) null);
});
Throwable cause = ex.getCause();
assertNotNull(cause);
assertInstanceOf(APIException.class, cause);
assertTrue(cause.getMessage().contains("Task type is required"));
}
}
@@ -0,0 +1,285 @@
package com.adityachandel.booklore.service.task;
import com.adityachandel.booklore.repository.TaskHistoryRepository;
import com.adityachandel.booklore.model.entity.TaskHistoryEntity;
import com.adityachandel.booklore.task.TaskStatus;
import com.adityachandel.booklore.model.dto.response.TasksHistoryResponse;
import com.adityachandel.booklore.model.enums.TaskType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.*;
import java.time.LocalDateTime;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class TaskHistoryServiceTest {
@Mock
private TaskHistoryRepository taskHistoryRepository;
@InjectMocks
private TaskHistoryService taskHistoryService;
private AutoCloseable mocks;
@BeforeEach
void setUp() {
mocks = MockitoAnnotations.openMocks(this);
}
@AfterEach
void tearDown() throws Exception {
if (mocks != null) {
mocks.close();
}
}
@Test
void testCreateTask_savesEntity() {
String taskId = "task1";
TaskType type = TaskType.REFRESH_LIBRARY_METADATA;
Long userId = 123L;
Map<String, Object> options = new HashMap<>();
options.put("key", "value");
ArgumentCaptor<TaskHistoryEntity> captor = ArgumentCaptor.forClass(TaskHistoryEntity.class);
taskHistoryService.createTask(taskId, type, userId, options);
verify(taskHistoryRepository, times(1)).save(captor.capture());
TaskHistoryEntity saved = captor.getValue();
assertEquals(taskId, saved.getId());
assertEquals(type, saved.getType());
assertEquals(TaskStatus.ACCEPTED, saved.getStatus());
assertEquals(userId, saved.getUserId());
assertEquals(0, saved.getProgressPercentage());
assertEquals(options, saved.getTaskOptions());
assertNotNull(saved.getCreatedAt());
}
@Test
void testUpdateTaskStatus_foundAndUpdated() {
String taskId = "task2";
TaskHistoryEntity entity = TaskHistoryEntity.builder()
.id(taskId)
.type(TaskType.SYNC_LIBRARY_FILES)
.status(TaskStatus.ACCEPTED)
.progressPercentage(0)
.createdAt(LocalDateTime.now())
.build();
when(taskHistoryRepository.findById(taskId)).thenReturn(Optional.of(entity));
taskHistoryService.updateTaskStatus(taskId, TaskStatus.COMPLETED, "Done");
assertEquals(TaskStatus.COMPLETED, entity.getStatus());
assertEquals("Done", entity.getMessage());
assertEquals(100, entity.getProgressPercentage());
assertNotNull(entity.getCompletedAt());
assertNotNull(entity.getUpdatedAt());
verify(taskHistoryRepository).save(entity);
}
@Test
void testUpdateTaskStatus_notFound() {
when(taskHistoryRepository.findById("notfound")).thenReturn(Optional.empty());
taskHistoryService.updateTaskStatus("notfound", TaskStatus.FAILED, "Error");
verify(taskHistoryRepository, never()).save(any());
}
@Test
void testUpdateTaskError_foundAndUpdated() {
String taskId = "task3";
TaskHistoryEntity entity = TaskHistoryEntity.builder()
.id(taskId)
.type(TaskType.REFRESH_LIBRARY_METADATA)
.status(TaskStatus.ACCEPTED)
.progressPercentage(0)
.createdAt(LocalDateTime.now())
.build();
when(taskHistoryRepository.findById(taskId)).thenReturn(Optional.of(entity));
taskHistoryService.updateTaskError(taskId, "Some error");
assertEquals(TaskStatus.FAILED, entity.getStatus());
assertEquals("Some error", entity.getErrorDetails());
assertEquals(0, entity.getProgressPercentage());
assertNotNull(entity.getCompletedAt());
assertNotNull(entity.getUpdatedAt());
verify(taskHistoryRepository).save(entity);
}
@Test
void testUpdateTaskError_notFound() {
when(taskHistoryRepository.findById("notfound")).thenReturn(Optional.empty());
taskHistoryService.updateTaskError("notfound", "Error");
verify(taskHistoryRepository, never()).save(any());
}
@Test
void testGetLatestTasksForEachType_success() {
TaskHistoryEntity importTask = TaskHistoryEntity.builder()
.id("t1")
.type(TaskType.REFRESH_LIBRARY_METADATA)
.status(TaskStatus.COMPLETED)
.progressPercentage(100)
.createdAt(LocalDateTime.now())
.build();
TaskHistoryEntity exportTask = TaskHistoryEntity.builder()
.id("t2")
.type(TaskType.SYNC_LIBRARY_FILES)
.status(TaskStatus.ACCEPTED)
.progressPercentage(50)
.createdAt(LocalDateTime.now())
.build();
when(taskHistoryRepository.findLatestTaskForEachType())
.thenReturn(Arrays.asList(importTask, exportTask));
TasksHistoryResponse response = taskHistoryService.getLatestTasksForEachType();
assertNotNull(response);
List<TasksHistoryResponse.TaskHistory> histories = response.getTaskHistories();
assertTrue(histories.stream().anyMatch(h -> TaskType.REFRESH_LIBRARY_METADATA.equals(h.getType()) && "t1".equals(h.getId())));
assertTrue(histories.stream().anyMatch(h -> TaskType.SYNC_LIBRARY_FILES.equals(h.getType()) && "t2".equals(h.getId())));
assertFalse(histories.stream().anyMatch(h -> h.getType() != null && h.getType().isHiddenFromUI()));
assertTrue(histories.stream().anyMatch(h -> h.getId() == null));
}
@Test
void testGetLatestTasksForEachType_exceptionHandled() {
when(taskHistoryRepository.findLatestTaskForEachType()).thenThrow(new RuntimeException("DB error"));
TasksHistoryResponse response = taskHistoryService.getLatestTasksForEachType();
assertNotNull(response);
assertTrue(response.getTaskHistories().stream().allMatch(h -> h.getId() == null));
}
@Test
void testGetLatestTasksForEachType_skipsInvalidType() {
TaskHistoryEntity invalidTask = TaskHistoryEntity.builder()
.id("t3")
.type(null)
.status(TaskStatus.FAILED)
.progressPercentage(0)
.createdAt(LocalDateTime.now())
.build();
when(taskHistoryRepository.findLatestTaskForEachType()).thenReturn(Collections.singletonList(invalidTask));
TasksHistoryResponse response = taskHistoryService.getLatestTasksForEachType();
assertNotNull(response);
assertTrue(response.getTaskHistories().stream().allMatch(h -> h.getId() == null || h.getType() != null));
}
@Test
void testCreateTask_withNullOptions() {
String taskId = "taskNullOptions";
TaskType type = TaskType.CLEANUP_TEMP_METADATA;
Long userId = 456L;
ArgumentCaptor<TaskHistoryEntity> captor = ArgumentCaptor.forClass(TaskHistoryEntity.class);
taskHistoryService.createTask(taskId, type, userId, null);
verify(taskHistoryRepository, times(1)).save(captor.capture());
TaskHistoryEntity saved = captor.getValue();
assertNull(saved.getTaskOptions());
}
@Test
void testUpdateTaskStatus_withNullMessage() {
String taskId = "taskNullMsg";
TaskHistoryEntity entity = TaskHistoryEntity.builder()
.id(taskId)
.type(TaskType.CLEANUP_TEMP_METADATA)
.status(TaskStatus.ACCEPTED)
.progressPercentage(0)
.createdAt(LocalDateTime.now())
.build();
when(taskHistoryRepository.findById(taskId)).thenReturn(Optional.of(entity));
taskHistoryService.updateTaskStatus(taskId, TaskStatus.COMPLETED, null);
assertEquals(TaskStatus.COMPLETED, entity.getStatus());
assertNull(entity.getMessage());
assertEquals(100, entity.getProgressPercentage());
assertNotNull(entity.getCompletedAt());
verify(taskHistoryRepository).save(entity);
}
@Test
void testUpdateTaskError_withNullErrorDetails() {
String taskId = "taskNullError";
TaskHistoryEntity entity = TaskHistoryEntity.builder()
.id(taskId)
.type(TaskType.CLEANUP_TEMP_METADATA)
.status(TaskStatus.ACCEPTED)
.progressPercentage(0)
.createdAt(LocalDateTime.now())
.build();
when(taskHistoryRepository.findById(taskId)).thenReturn(Optional.of(entity));
taskHistoryService.updateTaskError(taskId, null);
assertEquals(TaskStatus.FAILED, entity.getStatus());
assertNull(entity.getErrorDetails());
assertEquals(0, entity.getProgressPercentage());
assertNotNull(entity.getCompletedAt());
verify(taskHistoryRepository).save(entity);
}
@Test
void testCreateTask_withNullType() {
String taskId = "taskNullType";
Long userId = 789L;
Map<String, Object> options = new HashMap<>();
assertDoesNotThrow(() -> taskHistoryService.createTask(taskId, null, userId, options));
ArgumentCaptor<TaskHistoryEntity> captor = ArgumentCaptor.forClass(TaskHistoryEntity.class);
verify(taskHistoryRepository, times(1)).save(captor.capture());
TaskHistoryEntity saved = captor.getValue();
assertNull(saved.getType());
}
@Test
void testGetLatestTasksForEachType_emptyRepository() {
when(taskHistoryRepository.findLatestTaskForEachType()).thenReturn(Collections.emptyList());
TasksHistoryResponse response = taskHistoryService.getLatestTasksForEachType();
assertNotNull(response);
assertTrue(response.getTaskHistories().stream().allMatch(h -> h.getId() == null));
}
@Test
void testGetLatestTasksForEachType_allTypesHidden() {
List<TaskType> hiddenTypes = Arrays.asList(TaskType.values());
TaskHistoryEntity dummyTask = TaskHistoryEntity.builder()
.id("dummy")
.type(TaskType.CLEAR_CBX_CACHE)
.status(TaskStatus.FAILED)
.progressPercentage(0)
.createdAt(LocalDateTime.now())
.build();
when(taskHistoryRepository.findLatestTaskForEachType()).thenReturn(Collections.singletonList(dummyTask));
hiddenTypes.forEach(type -> {
try {
java.lang.reflect.Field field = TaskType.class.getDeclaredField("hiddenFromUI");
field.setAccessible(true);
field.set(type, true);
} catch (Exception ignored) {
}
});
TasksHistoryResponse response = taskHistoryService.getLatestTasksForEachType();
assertNotNull(response);
assertTrue(response.getTaskHistories().isEmpty());
}
}
@@ -0,0 +1,278 @@
package com.adityachandel.booklore.service.task;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.exception.APIException;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.dto.TaskInfo;
import com.adityachandel.booklore.model.dto.request.TaskCreateRequest;
import com.adityachandel.booklore.model.dto.response.CronConfig;
import com.adityachandel.booklore.model.dto.response.TaskCreateResponse;
import com.adityachandel.booklore.model.enums.TaskType;
import com.adityachandel.booklore.task.tasks.Task;
import com.adityachandel.booklore.task.TaskCancellationManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.TaskScheduler;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class TaskServiceTest {
private AuthenticationService authenticationService;
private TaskHistoryService taskHistoryService;
private TaskCronService taskCronService;
private TaskCancellationManager cancellationManager;
private Executor taskExecutor;
private ObjectMapper objectMapper;
private TaskScheduler taskScheduler;
private TaskService taskService;
private Task mockTask;
@BeforeEach
void setUp() {
authenticationService = mock(AuthenticationService.class);
taskHistoryService = mock(TaskHistoryService.class);
taskCronService = mock(TaskCronService.class);
cancellationManager = mock(TaskCancellationManager.class);
taskExecutor = mock(Executor.class);
objectMapper = mock(ObjectMapper.class);
taskScheduler = mock(TaskScheduler.class);
mockTask = mock(Task.class);
when(mockTask.getTaskType()).thenReturn(TaskType.CLEANUP_TEMP_METADATA);
taskService = new TaskService(
authenticationService,
taskHistoryService,
taskCronService,
List.of(mockTask),
cancellationManager,
taskExecutor,
objectMapper,
taskScheduler
);
}
@Test
void testRunAsUserThrowsExceptionForNullRequest() {
APIException ex = assertThrows(APIException.class, () -> taskService.runAsUser(null));
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatus());
}
@Test
void testRunAsUserThrowsExceptionForNullTaskType() {
TaskCreateRequest req = TaskCreateRequest.builder().build();
APIException ex = assertThrows(APIException.class, () -> taskService.runAsUser(req));
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatus());
}
@Test
@Disabled
void testGetAvailableTasksReturnsNonNull() {
CronConfig cronConfig = CronConfig.builder()
.taskType(TaskType.CLEANUP_TEMP_METADATA)
.enabled(false)
.build();
when(taskCronService.getCronConfigOrDefault(any())).thenReturn(cronConfig);
List<TaskInfo> tasks = taskService.getAvailableTasks();
assertNotNull(tasks);
assertTrue(tasks.stream().anyMatch(t -> t.getTaskType() == TaskType.CLEANUP_TEMP_METADATA));
}
@Test
void testRunAsUserSyncTask() {
BookLoreUser user = new BookLoreUser();
user.setId(1L);
user.setUsername("user1");
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(mockTask.execute(any())).thenReturn(TaskCreateResponse.builder().taskType(TaskType.CLEANUP_TEMP_METADATA).build());
TaskCreateRequest req = TaskCreateRequest.builder().taskType(TaskType.CLEANUP_TEMP_METADATA).build();
TaskCreateResponse resp = taskService.runAsUser(req);
assertEquals(TaskType.CLEANUP_TEMP_METADATA, resp.getTaskType());
}
@Test
void testExecuteTaskThrowsForUnknownTaskType() {
TaskCreateRequest req = TaskCreateRequest.builder().taskType(TaskType.CLEAR_CBX_CACHE).build();
BookLoreUser user = new BookLoreUser();
user.setId(1L);
user.setUsername("user1");
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
assertThrows(UnsupportedOperationException.class, () -> taskService.runAsUser(req));
}
@Test
void testParallelTaskAllowsMultipleRuns() {
TaskType parallelType = TaskType.CLEANUP_TEMP_METADATA;
when(mockTask.getTaskType()).thenReturn(parallelType);
when(mockTask.execute(any())).thenReturn(TaskCreateResponse.builder().taskType(parallelType).build());
BookLoreUser user = new BookLoreUser();
user.setId(2L);
user.setUsername("parallelUser");
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
TaskCreateRequest req1 = TaskCreateRequest.builder().taskType(parallelType).build();
TaskCreateRequest req2 = TaskCreateRequest.builder().taskType(parallelType).build();
TaskCreateResponse resp1 = taskService.runAsUser(req1);
TaskCreateResponse resp2 = taskService.runAsUser(req2);
assertEquals(parallelType, resp1.getTaskType());
assertEquals(parallelType, resp2.getTaskType());
}
@Test
void testNonParallelTaskBlocksSecondRunAsUser() {
TaskType nonParallelType = TaskType.REFRESH_LIBRARY_METADATA;
Task nonParallelTask = mock(Task.class);
when(nonParallelTask.getTaskType()).thenReturn(nonParallelType);
when(nonParallelTask.execute(any())).thenReturn(TaskCreateResponse.builder().taskType(nonParallelType).build());
taskService = new TaskService(
authenticationService,
taskHistoryService,
taskCronService,
List.of(nonParallelTask),
cancellationManager,
taskExecutor,
objectMapper,
taskScheduler
);
BookLoreUser user = new BookLoreUser();
user.setId(3L);
user.setUsername("nonParallelUser");
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
TaskCreateRequest req = TaskCreateRequest.builder().taskType(nonParallelType).build();
taskService.runAsUser(req);
APIException ex = assertThrows(APIException.class, () -> taskService.runAsUser(req));
assertEquals(HttpStatus.CONFLICT, ex.getStatus());
}
@Test
void testCancelNonExistentTaskThrowsException() {
BookLoreUser user = new BookLoreUser();
user.setId(4L);
user.setUsername("cancelUser");
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
String fakeTaskId = "not-running-task-id";
assertThrows(APIException.class, () -> taskService.cancelTask(fakeTaskId));
}
@Test
void testAsyncTaskReturnsAcceptedStatus() {
TaskType asyncType = TaskType.UPDATE_BOOK_RECOMMENDATIONS;
Task asyncTask = mock(Task.class);
when(asyncTask.getTaskType()).thenReturn(asyncType);
when(asyncTask.execute(any())).thenReturn(TaskCreateResponse.builder().taskType(asyncType).build());
taskService = new TaskService(
authenticationService,
taskHistoryService,
taskCronService,
List.of(asyncTask),
cancellationManager,
taskExecutor,
objectMapper,
taskScheduler
);
BookLoreUser user = new BookLoreUser();
user.setId(5L);
user.setUsername("asyncUser");
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
TaskCreateRequest req = TaskCreateRequest.builder().taskType(asyncType).build();
TaskCreateResponse resp = taskService.runAsUser(req);
assertEquals(asyncType, resp.getTaskType());
assertEquals(com.adityachandel.booklore.task.TaskStatus.ACCEPTED, resp.getStatus());
}
@Test
void testNullOptionsHandledGracefully() {
TaskType type = TaskType.CLEANUP_TEMP_METADATA;
when(mockTask.getTaskType()).thenReturn(type);
when(mockTask.execute(any())).thenReturn(TaskCreateResponse.builder().taskType(type).build());
BookLoreUser user = new BookLoreUser();
user.setId(6L);
user.setUsername("nullOptionsUser");
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
TaskCreateRequest req = TaskCreateRequest.builder().taskType(type).options(null).build();
TaskCreateResponse resp = taskService.runAsUser(req);
assertEquals(type, resp.getTaskType());
}
@Test
void testExceptionInTaskExecutionPropagates() {
TaskType type = TaskType.CLEANUP_TEMP_METADATA;
when(mockTask.getTaskType()).thenReturn(type);
when(mockTask.execute(any())).thenThrow(new RuntimeException("Task failed"));
BookLoreUser user = new BookLoreUser();
user.setId(7L);
user.setUsername("exceptionUser");
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
TaskCreateRequest req = TaskCreateRequest.builder().taskType(type).build();
assertThrows(RuntimeException.class, () -> taskService.runAsUser(req));
}
@Test
void testRunAsUserThrowsExceptionForNullUser() {
when(authenticationService.getAuthenticatedUser()).thenReturn(null);
TaskCreateRequest req = TaskCreateRequest.builder().taskType(TaskType.CLEANUP_TEMP_METADATA).build();
assertThrows(NullPointerException.class, () -> taskService.runAsUser(req));
}
@Test
void testExecuteTaskThrowsForMissingTaskInRegistry() {
TaskCreateRequest req = TaskCreateRequest.builder().taskType(TaskType.CLEANUP_DELETED_BOOKS).build();
BookLoreUser user = new BookLoreUser();
user.setId(8L);
user.setUsername("missingTaskUser");
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
assertThrows(UnsupportedOperationException.class, () -> taskService.runAsUser(req));
}
@Test
void testConvertOptionsToMapHandlesInvalidType() {
BookLoreUser user = new BookLoreUser();
user.setId(9L);
user.setUsername("invalidOptionsUser");
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(objectMapper.convertValue(any(), eq(Map.class))).thenThrow(new IllegalArgumentException("Conversion failed"));
TaskCreateRequest req = TaskCreateRequest.builder().taskType(TaskType.CLEANUP_TEMP_METADATA).options(new Object()).build();
when(mockTask.execute(any())).thenReturn(TaskCreateResponse.builder().taskType(TaskType.CLEANUP_TEMP_METADATA).build());
TaskCreateResponse resp = taskService.runAsUser(req);
assertEquals(TaskType.CLEANUP_TEMP_METADATA, resp.getTaskType());
}
@Test
void testInitializeScheduledTasksDoesNotThrow() {
when(taskCronService.getAllEnabledCronConfigs()).thenReturn(List.of());
assertDoesNotThrow(() -> taskService.initializeScheduledTasks());
}
@Test
void testRescheduleTaskDoesNotThrowWhenEnabled() {
CronConfig cronConfig = CronConfig.builder()
.taskType(TaskType.CLEANUP_TEMP_METADATA)
.enabled(true)
.cronExpression("0 0 0 1 1 0")
.build();
when(taskCronService.getCronConfigOrDefault(TaskType.CLEANUP_TEMP_METADATA)).thenReturn(cronConfig);
assertDoesNotThrow(() -> taskService.rescheduleTask(TaskType.CLEANUP_TEMP_METADATA));
}
}
@@ -14,12 +14,10 @@ import com.adityachandel.booklore.model.enums.AdditionalFileType;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.FileFingerprint;
import com.adityachandel.booklore.service.file.FileFingerprint;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.file.FileMovingHelper;
import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor;
import com.adityachandel.booklore.service.metadata.extractor.MetadataExtractorFactory;
import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -9,7 +9,7 @@ import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.enums.*;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.FileFingerprint;
import com.adityachandel.booklore.service.file.FileFingerprint;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.util.FileUtils;