feat(mobile): add author and series endpoints

This commit is contained in:
acx10
2026-02-28 18:39:52 -07:00
parent e26ac45ae9
commit a1666932cb
12 changed files with 1831 additions and 0 deletions
@@ -0,0 +1,158 @@
package org.booklore.mobile.controller;
import org.booklore.mobile.dto.*;
import org.booklore.mobile.service.MobileSeriesService;
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.http.ResponseEntity;
import java.time.Instant;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class MobileSeriesControllerTest {
@Mock
private MobileSeriesService mobileSeriesService;
@InjectMocks
private MobileSeriesController controller;
@Test
void getSeries_defaultParams_delegatesCorrectly() {
MobilePageResponse<MobileSeriesSummary> expected = buildSeriesPage();
when(mobileSeriesService.getSeries(0, 20, "recentlyAdded", "desc", null, null, false))
.thenReturn(expected);
ResponseEntity<MobilePageResponse<MobileSeriesSummary>> response =
controller.getSeries(0, 20, "recentlyAdded", "desc", null, null, null);
assertEquals(200, response.getStatusCode().value());
assertSame(expected, response.getBody());
verify(mobileSeriesService).getSeries(0, 20, "recentlyAdded", "desc", null, null, false);
}
@Test
void getSeries_withLibraryId_passesLibraryId() {
MobilePageResponse<MobileSeriesSummary> expected = buildSeriesPage();
when(mobileSeriesService.getSeries(0, 20, "recentlyAdded", "desc", 5L, null, false))
.thenReturn(expected);
ResponseEntity<MobilePageResponse<MobileSeriesSummary>> response =
controller.getSeries(0, 20, "recentlyAdded", "desc", 5L, null, null);
assertEquals(200, response.getStatusCode().value());
verify(mobileSeriesService).getSeries(0, 20, "recentlyAdded", "desc", 5L, null, false);
}
@Test
void getSeries_withSearch_passesSearch() {
MobilePageResponse<MobileSeriesSummary> expected = buildSeriesPage();
when(mobileSeriesService.getSeries(0, 20, "recentlyAdded", "desc", null, "harry", false))
.thenReturn(expected);
ResponseEntity<MobilePageResponse<MobileSeriesSummary>> response =
controller.getSeries(0, 20, "recentlyAdded", "desc", null, "harry", null);
assertEquals(200, response.getStatusCode().value());
verify(mobileSeriesService).getSeries(0, 20, "recentlyAdded", "desc", null, "harry", false);
}
@Test
void getSeries_withInProgressStatus_setsInProgressTrue() {
MobilePageResponse<MobileSeriesSummary> expected = buildSeriesPage();
when(mobileSeriesService.getSeries(0, 20, "recentlyAdded", "desc", null, null, true))
.thenReturn(expected);
ResponseEntity<MobilePageResponse<MobileSeriesSummary>> response =
controller.getSeries(0, 20, "recentlyAdded", "desc", null, null, "in-progress");
assertEquals(200, response.getStatusCode().value());
verify(mobileSeriesService).getSeries(0, 20, "recentlyAdded", "desc", null, null, true);
}
@Test
void getSeries_withUnknownStatus_treatedAsNotInProgress() {
MobilePageResponse<MobileSeriesSummary> expected = buildSeriesPage();
when(mobileSeriesService.getSeries(0, 20, "recentlyAdded", "desc", null, null, false))
.thenReturn(expected);
ResponseEntity<MobilePageResponse<MobileSeriesSummary>> response =
controller.getSeries(0, 20, "recentlyAdded", "desc", null, null, "completed");
assertEquals(200, response.getStatusCode().value());
verify(mobileSeriesService).getSeries(0, 20, "recentlyAdded", "desc", null, null, false);
}
@Test
void getSeriesBooks_defaultParams_delegatesCorrectly() {
MobilePageResponse<MobileBookSummary> expected = buildBookPage();
when(mobileSeriesService.getSeriesBooks("Dune", 0, 20, "seriesNumber", "asc", null))
.thenReturn(expected);
ResponseEntity<MobilePageResponse<MobileBookSummary>> response =
controller.getSeriesBooks("Dune", 0, 20, "seriesNumber", "asc", null);
assertEquals(200, response.getStatusCode().value());
assertSame(expected, response.getBody());
verify(mobileSeriesService).getSeriesBooks("Dune", 0, 20, "seriesNumber", "asc", null);
}
@Test
void getSeriesBooks_withLibraryId_passesLibraryId() {
MobilePageResponse<MobileBookSummary> expected = buildBookPage();
when(mobileSeriesService.getSeriesBooks("Dune", 0, 20, "seriesNumber", "asc", 5L))
.thenReturn(expected);
ResponseEntity<MobilePageResponse<MobileBookSummary>> response =
controller.getSeriesBooks("Dune", 0, 20, "seriesNumber", "asc", 5L);
assertEquals(200, response.getStatusCode().value());
verify(mobileSeriesService).getSeriesBooks("Dune", 0, 20, "seriesNumber", "asc", 5L);
}
@Test
void getSeriesBooks_encodedSeriesName_passedAsIs() {
MobilePageResponse<MobileBookSummary> expected = buildBookPage();
when(mobileSeriesService.getSeriesBooks("A Song of Ice and Fire", 0, 20, "seriesNumber", "asc", null))
.thenReturn(expected);
ResponseEntity<MobilePageResponse<MobileBookSummary>> response =
controller.getSeriesBooks("A Song of Ice and Fire", 0, 20, "seriesNumber", "asc", null);
assertEquals(200, response.getStatusCode().value());
verify(mobileSeriesService).getSeriesBooks("A Song of Ice and Fire", 0, 20, "seriesNumber", "asc", null);
}
// ---- Helpers ----
private MobilePageResponse<MobileSeriesSummary> buildSeriesPage() {
MobileSeriesSummary summary = MobileSeriesSummary.builder()
.seriesName("Test Series")
.bookCount(5)
.seriesTotal(5)
.booksRead(2)
.authors(List.of("Author A"))
.latestAddedOn(Instant.now())
.coverBooks(List.of())
.build();
return MobilePageResponse.of(List.of(summary), 0, 20, 1);
}
private MobilePageResponse<MobileBookSummary> buildBookPage() {
MobileBookSummary summary = MobileBookSummary.builder()
.id(1L)
.title("Test Book")
.authors(List.of("Author A"))
.seriesName("Dune")
.seriesNumber(1.0f)
.build();
return MobilePageResponse.of(List.of(summary), 0, 20, 1);
}
}
@@ -0,0 +1,377 @@
package org.booklore.mobile.service;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.APIException;
import org.booklore.mobile.dto.MobileAuthorDetail;
import org.booklore.mobile.dto.MobileAuthorSummary;
import org.booklore.mobile.dto.MobilePageResponse;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.Library;
import org.booklore.model.entity.AuthorEntity;
import org.booklore.repository.AuthorRepository;
import org.booklore.util.FileService;
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.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class MobileAuthorServiceTest {
@Mock private EntityManager entityManager;
@Mock private AuthenticationService authenticationService;
@Mock private AuthorRepository authorRepository;
@Mock private FileService fileService;
private MobileAuthorService service;
private final Long userId = 1L;
@BeforeEach
void setUp() {
service = new MobileAuthorService(authorRepository, authenticationService, fileService, entityManager);
}
// ---- getAuthors tests ----
@Nested
class GetAuthorsTests {
@Test
void getAuthors_admin_noFilters_returnsPage() {
mockAdminUser();
mockCountQuery(2L);
mockDataQuery(List.<Object[]>of(
new Object[]{buildAuthor(1L, "Author A"), 5L},
new Object[]{buildAuthor(2L, "Author B"), 3L}
));
mockAuthorThumbnailExists(1L, true);
mockAuthorThumbnailExists(2L, false);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, "name", "asc", null, null, null);
assertNotNull(result);
assertEquals(2, result.getContent().size());
assertEquals("Author A", result.getContent().get(0).getName());
assertEquals(5, result.getContent().get(0).getBookCount());
assertTrue(result.getContent().get(0).isHasPhoto());
assertEquals("Author B", result.getContent().get(1).getName());
assertEquals(3, result.getContent().get(1).getBookCount());
assertFalse(result.getContent().get(1).isHasPhoto());
assertEquals(2, result.getTotalElements());
}
@Test
void getAuthors_admin_emptyResult_returnsEmptyPage() {
mockAdminUser();
mockCountQuery(0L);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, null, null, null, null, null);
assertNotNull(result);
assertTrue(result.getContent().isEmpty());
assertEquals(0, result.getTotalElements());
}
@Test
void getAuthors_nonAdmin_withAccessibleLibrary_succeeds() {
mockNonAdminUser(Set.of(5L, 10L));
mockCountQuery(1L);
mockDataQuery(List.<Object[]>of(
new Object[]{buildAuthor(3L, "Author C"), 2L}
));
mockAuthorThumbnailExists(3L, false);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, null, null, 5L, null, null);
assertNotNull(result);
assertEquals(1, result.getContent().size());
assertEquals("Author C", result.getContent().get(0).getName());
}
@Test
void getAuthors_nonAdmin_noLibraryFilter_usesAccessibleLibraries() {
mockNonAdminUser(Set.of(5L));
mockCountQuery(1L);
mockDataQuery(List.<Object[]>of(
new Object[]{buildAuthor(4L, "Author D"), 1L}
));
mockAuthorThumbnailExists(4L, true);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, null, null, null, null, null);
assertNotNull(result);
assertEquals(1, result.getContent().size());
}
@Test
void getAuthors_withSearch_filtersResultsByName() {
mockAdminUser();
mockCountQuery(1L);
mockDataQuery(List.<Object[]>of(
new Object[]{buildAuthor(5L, "Brandon Sanderson"), 12L}
));
mockAuthorThumbnailExists(5L, true);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, null, null, null, "brandon", null);
assertNotNull(result);
assertEquals(1, result.getContent().size());
assertEquals("Brandon Sanderson", result.getContent().get(0).getName());
}
@Test
void getAuthors_withHasPhotoTrue_filtersToAuthorsWithPhotos() {
mockAdminUser();
mockCountQuery(2L);
mockDataQuery(List.<Object[]>of(
new Object[]{buildAuthor(6L, "Author E"), 4L},
new Object[]{buildAuthor(7L, "Author F"), 2L}
));
mockAuthorThumbnailExists(6L, true);
mockAuthorThumbnailExists(7L, false);
// Mock the hasPhoto count query
mockAuthorEntityQuery(List.of(buildAuthor(6L, "Author E"), buildAuthor(7L, "Author F")));
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, null, null, null, null, true);
assertNotNull(result);
assertEquals(1, result.getContent().size());
assertEquals("Author E", result.getContent().get(0).getName());
assertTrue(result.getContent().get(0).isHasPhoto());
}
@Test
void getAuthors_withHasPhotoFalse_filtersToAuthorsWithoutPhotos() {
mockAdminUser();
mockCountQuery(2L);
mockDataQuery(List.<Object[]>of(
new Object[]{buildAuthor(8L, "Author G"), 3L},
new Object[]{buildAuthor(9L, "Author H"), 1L}
));
mockAuthorThumbnailExists(8L, true);
mockAuthorThumbnailExists(9L, false);
mockAuthorEntityQuery(List.of(buildAuthor(8L, "Author G"), buildAuthor(9L, "Author H")));
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, null, null, null, null, false);
assertNotNull(result);
assertEquals(1, result.getContent().size());
assertEquals("Author H", result.getContent().get(0).getName());
assertFalse(result.getContent().get(0).isHasPhoto());
}
@Test
void getAuthors_paginationDefaults_appliedCorrectly() {
mockAdminUser();
mockCountQuery(0L);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(null, null, null, null, null, null, null);
assertEquals(0, result.getPage());
assertEquals(30, result.getSize());
}
@Test
void getAuthors_pageSizeCapped_atMax() {
mockAdminUser();
mockCountQuery(0L);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 100, null, null, null, null, null);
assertEquals(50, result.getSize());
}
@Test
void getAuthors_sortByName_asc() {
mockAdminUser();
mockCountQuery(0L);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, "name", "asc", null, null, null);
assertNotNull(result);
}
@Test
void getAuthors_sortByBookCount_desc() {
mockAdminUser();
mockCountQuery(0L);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, "bookCount", "desc", null, null, null);
assertNotNull(result);
}
@Test
void getAuthors_sortByRecent_desc() {
mockAdminUser();
mockCountQuery(0L);
MobilePageResponse<MobileAuthorSummary> result = service.getAuthors(0, 30, "recent", "desc", null, null, null);
assertNotNull(result);
}
}
// ---- getAuthorDetail tests ----
@Nested
class GetAuthorDetailTests {
@Test
void getAuthorDetail_admin_returnsDetail() {
mockAdminUser();
AuthorEntity author = buildAuthor(1L, "J.R.R. Tolkien");
author.setDescription("English writer and philologist.");
author.setAsin("B000AP9MCS");
when(authorRepository.findById(1L)).thenReturn(Optional.of(author));
mockAuthorThumbnailExists(1L, true);
mockBookCountQuery(3);
MobileAuthorDetail result = service.getAuthorDetail(1L);
assertNotNull(result);
assertEquals(1L, result.getId());
assertEquals("J.R.R. Tolkien", result.getName());
assertEquals("English writer and philologist.", result.getDescription());
assertEquals("B000AP9MCS", result.getAsin());
assertEquals(3, result.getBookCount());
assertTrue(result.isHasPhoto());
}
@Test
void getAuthorDetail_nonAdmin_withAccess_returnsDetail() {
mockNonAdminUser(Set.of(5L));
AuthorEntity author = buildAuthor(2L, "Frank Herbert");
when(authorRepository.findById(2L)).thenReturn(Optional.of(author));
when(authorRepository.existsByIdAndLibraryIds(eq(2L), anySet())).thenReturn(true);
mockAuthorThumbnailExists(2L, false);
mockBookCountQuery(6);
MobileAuthorDetail result = service.getAuthorDetail(2L);
assertNotNull(result);
assertEquals("Frank Herbert", result.getName());
assertEquals(6, result.getBookCount());
assertFalse(result.isHasPhoto());
}
@Test
void getAuthorDetail_nonAdmin_noAccess_throwsNotFound() {
mockNonAdminUser(Set.of(5L));
AuthorEntity author = buildAuthor(3L, "Secret Author");
when(authorRepository.findById(3L)).thenReturn(Optional.of(author));
when(authorRepository.existsByIdAndLibraryIds(eq(3L), anySet())).thenReturn(false);
assertThrows(APIException.class, () -> service.getAuthorDetail(3L));
}
@Test
void getAuthorDetail_nonExistentAuthor_throwsNotFound() {
mockAdminUser();
when(authorRepository.findById(999L)).thenReturn(Optional.empty());
assertThrows(APIException.class, () -> service.getAuthorDetail(999L));
}
@Test
void getAuthorDetail_nonAdmin_emptyLibraries_throwsNotFound() {
mockNonAdminUser(Collections.emptySet());
AuthorEntity author = buildAuthor(4L, "Author X");
when(authorRepository.findById(4L)).thenReturn(Optional.of(author));
assertThrows(APIException.class, () -> service.getAuthorDetail(4L));
}
}
// ---- Helpers ----
private void mockAdminUser() {
var permissions = new BookLoreUser.UserPermissions();
permissions.setAdmin(true);
BookLoreUser user = BookLoreUser.builder()
.id(userId)
.permissions(permissions)
.build();
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
}
private void mockNonAdminUser(Set<Long> libraryIds) {
List<Library> assignedLibraries = libraryIds.stream()
.map(id -> Library.builder().id(id).build())
.toList();
var permissions = new BookLoreUser.UserPermissions();
permissions.setAdmin(false);
BookLoreUser user = BookLoreUser.builder()
.id(userId)
.permissions(permissions)
.assignedLibraries(assignedLibraries)
.build();
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
}
@SuppressWarnings("unchecked")
private void mockCountQuery(long count) {
TypedQuery<Long> countQ = mock(TypedQuery.class);
when(countQ.setParameter(anyString(), any())).thenReturn(countQ);
when(countQ.getSingleResult()).thenReturn(count);
when(entityManager.createQuery(anyString(), eq(Long.class))).thenReturn(countQ);
}
@SuppressWarnings("unchecked")
private void mockDataQuery(List<Object[]> results) {
TypedQuery<Object[]> dataQ = mock(TypedQuery.class);
when(dataQ.setParameter(anyString(), any())).thenReturn(dataQ);
when(dataQ.setFirstResult(anyInt())).thenReturn(dataQ);
when(dataQ.setMaxResults(anyInt())).thenReturn(dataQ);
when(dataQ.getResultList()).thenReturn(results);
when(entityManager.createQuery(anyString(), eq(Object[].class))).thenReturn(dataQ);
}
@SuppressWarnings("unchecked")
private void mockAuthorEntityQuery(List<AuthorEntity> authors) {
TypedQuery<AuthorEntity> authorQ = mock(TypedQuery.class);
when(authorQ.setParameter(anyString(), any())).thenReturn(authorQ);
when(authorQ.getResultList()).thenReturn(authors);
when(entityManager.createQuery(anyString(), eq(AuthorEntity.class))).thenReturn(authorQ);
}
@SuppressWarnings("unchecked")
private void mockBookCountQuery(int count) {
TypedQuery<Long> countQ = mock(TypedQuery.class);
when(countQ.setParameter(anyString(), any())).thenReturn(countQ);
when(countQ.getSingleResult()).thenReturn((long) count);
when(entityManager.createQuery(anyString(), eq(Long.class))).thenReturn(countQ);
}
private void mockAuthorThumbnailExists(Long authorId, boolean exists) {
String path = "/mock/authors/" + authorId + "/thumbnail.jpg";
when(fileService.getAuthorThumbnailFile(authorId)).thenReturn(path);
// Since Files.exists checks real filesystem, a non-existent mock path returns false.
// For "exists = true" tests, we need a path that actually exists.
if (exists) {
// Use a path we know exists — the temp directory
when(fileService.getAuthorThumbnailFile(authorId)).thenReturn(System.getProperty("java.io.tmpdir"));
}
}
private AuthorEntity buildAuthor(Long id, String name) {
return AuthorEntity.builder()
.id(id)
.name(name)
.build();
}
}
@@ -0,0 +1,488 @@
package org.booklore.mobile.service;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Tuple;
import jakarta.persistence.TypedQuery;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.APIException;
import org.booklore.mobile.dto.MobileBookSummary;
import org.booklore.mobile.dto.MobilePageResponse;
import org.booklore.mobile.dto.MobileSeriesSummary;
import org.booklore.mobile.mapper.MobileBookMapper;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.Library;
import org.booklore.model.entity.*;
import org.booklore.model.enums.BookFileType;
import org.booklore.repository.BookRepository;
import org.booklore.repository.UserBookProgressRepository;
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.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import java.time.Instant;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class MobileSeriesServiceTest {
@Mock private EntityManager entityManager;
@Mock private AuthenticationService authenticationService;
@Mock private BookRepository bookRepository;
@Mock private UserBookProgressRepository userBookProgressRepository;
@Mock private MobileBookMapper mobileBookMapper;
private MobileSeriesService service;
private final Long userId = 1L;
@BeforeEach
void setUp() {
service = new MobileSeriesService(
entityManager, authenticationService, bookRepository,
userBookProgressRepository, mobileBookMapper
);
}
// ---- getSeries tests ----
@Nested
class GetSeriesTests {
@Test
void getSeries_admin_noParams_returnsPage() {
mockAdminUser();
mockAggregateQuery(List.of(
mockSeriesTuple("The Expanse", 9L, 9, Instant.now(), 3L)
));
mockCountQuery(1L);
mockBooksQuery(List.of(buildBook(1L, "The Expanse", 1.0f, "Author A")));
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, null, null, null, null, false);
assertNotNull(result);
assertEquals(1, result.getContent().size());
assertEquals("The Expanse", result.getContent().getFirst().getSeriesName());
assertEquals(9, result.getContent().getFirst().getBookCount());
assertEquals(3, result.getContent().getFirst().getBooksRead());
}
@Test
void getSeries_admin_emptyResult_returnsEmptyPage() {
mockAdminUser();
mockAggregateQuery(Collections.emptyList());
mockCountQuery(0L);
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, null, null, null, null, false);
assertNotNull(result);
assertTrue(result.getContent().isEmpty());
assertEquals(0, result.getTotalElements());
}
@Test
void getSeries_nonAdmin_withAccessibleLibrary_succeeds() {
mockNonAdminUser(Set.of(5L, 10L));
mockAggregateQuery(List.of(
mockSeriesTuple("Dune", 6L, 6, Instant.now(), 2L)
));
mockCountQuery(1L);
mockBooksQuery(List.of(buildBook(2L, "Dune", 1.0f, "Frank Herbert")));
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, null, null, 5L, null, false);
assertNotNull(result);
assertEquals(1, result.getContent().size());
}
@Test
void getSeries_nonAdmin_noAccessToLibrary_throwsForbidden() {
mockNonAdminUser(Set.of(10L));
assertThrows(APIException.class, () ->
service.getSeries(0, 20, null, null, 5L, null, false));
}
@Test
void getSeries_withSearch_passesSearchPattern() {
mockAdminUser();
mockAggregateQuery(List.of(
mockSeriesTuple("Harry Potter", 7L, 7, Instant.now(), 7L)
));
mockCountQuery(1L);
mockBooksQuery(List.of(buildBook(3L, "Harry Potter", 1.0f, "J.K. Rowling")));
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, null, null, null, "harry", false);
assertNotNull(result);
assertEquals(1, result.getContent().size());
}
@Test
void getSeries_inProgressOnly_returnsFilteredResults() {
mockAdminUser();
mockAggregateQueryInProgress(List.of(
mockSeriesTupleInProgress("The Expanse", 9L, 9, Instant.now(), 3L, Instant.now())
));
mockCountQueryInProgress(1L);
mockBooksQuery(List.of(buildBook(1L, "The Expanse", 1.0f, "Author A")));
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, null, null, null, null, true);
assertNotNull(result);
assertEquals(1, result.getContent().size());
}
@Test
void getSeries_paginationDefaults_appliedCorrectly() {
mockAdminUser();
mockAggregateQuery(Collections.emptyList());
mockCountQuery(0L);
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(null, null, null, null, null, null, false);
assertEquals(0, result.getPage());
assertEquals(20, result.getSize());
}
@Test
void getSeries_pageSizeCapped_atMax() {
mockAdminUser();
mockAggregateQuery(Collections.emptyList());
mockCountQuery(0L);
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 100, null, null, null, null, false);
assertEquals(50, result.getSize());
}
@Test
void getSeries_enrichesCoverBooksAndAuthors() {
mockAdminUser();
BookEntity book1 = buildBook(10L, "Series X", 1.0f, "Author A");
BookEntity book2 = buildBook(11L, "Series X", 2.0f, "Author B");
mockAggregateQuery(List.of(
mockSeriesTuple("Series X", 2L, 3, Instant.now(), 1L)
));
mockCountQuery(1L);
mockBooksQuery(List.of(book1, book2));
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, null, null, null, null, false);
MobileSeriesSummary series = result.getContent().getFirst();
assertEquals(2, series.getCoverBooks().size());
assertEquals(2, series.getAuthors().size());
// Cover books should be ordered by seriesNumber ASC
assertEquals(1.0f, series.getCoverBooks().get(0).getSeriesNumber());
assertEquals(2.0f, series.getCoverBooks().get(1).getSeriesNumber());
}
@Test
void getSeries_sortByName_asc() {
mockAdminUser();
mockAggregateQuery(Collections.emptyList());
mockCountQuery(0L);
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, "name", "asc", null, null, false);
assertNotNull(result);
}
@Test
void getSeries_sortByBookCount_desc() {
mockAdminUser();
mockAggregateQuery(Collections.emptyList());
mockCountQuery(0L);
MobilePageResponse<MobileSeriesSummary> result = service.getSeries(0, 20, "bookCount", "desc", null, null, false);
assertNotNull(result);
}
}
// ---- getSeriesBooks tests ----
@Nested
class GetSeriesBooksTests {
@Test
void getSeriesBooks_admin_returnsBooks() {
mockAdminUser();
BookEntity book = buildBook(1L, "Dune", 1.0f, "Frank Herbert");
mockBookPage(List.of(book), 1L);
mockProgress(Collections.emptyList());
mockMapperSummary();
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", 0, 20, null, null, null);
assertNotNull(result);
assertEquals(1, result.getContent().size());
assertEquals(1, result.getTotalElements());
}
@Test
void getSeriesBooks_nonAdmin_withAccess_succeeds() {
mockNonAdminUser(Set.of(5L));
BookEntity book = buildBook(2L, "Dune", 2.0f, "Frank Herbert");
mockBookPage(List.of(book), 1L);
mockProgress(Collections.emptyList());
mockMapperSummary();
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", 0, 20, null, null, 5L);
assertNotNull(result);
assertEquals(1, result.getContent().size());
}
@Test
void getSeriesBooks_nonAdmin_noAccess_throwsForbidden() {
mockNonAdminUser(Set.of(10L));
assertThrows(APIException.class, () ->
service.getSeriesBooks("Dune", 0, 20, null, null, 5L));
}
@Test
void getSeriesBooks_emptyResult_returnsEmptyPage() {
mockAdminUser();
mockBookPage(Collections.emptyList(), 0L);
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Nonexistent", 0, 20, null, null, null);
assertNotNull(result);
assertTrue(result.getContent().isEmpty());
assertEquals(0, result.getTotalElements());
}
@Test
void getSeriesBooks_sortByTitle_desc() {
mockAdminUser();
mockBookPage(Collections.emptyList(), 0L);
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", 0, 20, "title", "desc", null);
assertNotNull(result);
}
@Test
void getSeriesBooks_sortByRecentlyAdded_asc() {
mockAdminUser();
mockBookPage(Collections.emptyList(), 0L);
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", 0, 20, "recentlyAdded", "asc", null);
assertNotNull(result);
}
@Test
void getSeriesBooks_defaultSort_isSeriesNumber() {
mockAdminUser();
mockBookPage(Collections.emptyList(), 0L);
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", 0, 20, null, null, null);
assertNotNull(result);
}
@Test
void getSeriesBooks_paginationDefaults() {
mockAdminUser();
mockBookPage(Collections.emptyList(), 0L);
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", null, null, null, null, null);
assertEquals(0, result.getPage());
assertEquals(20, result.getSize());
}
@Test
void getSeriesBooks_pageSizeCapped() {
mockAdminUser();
mockBookPage(Collections.emptyList(), 0L);
MobilePageResponse<MobileBookSummary> result = service.getSeriesBooks("Dune", 0, 200, null, null, null);
assertEquals(50, result.getSize());
}
}
// ---- Helpers ----
private void mockAdminUser() {
var permissions = new BookLoreUser.UserPermissions();
permissions.setAdmin(true);
BookLoreUser user = BookLoreUser.builder()
.id(userId)
.permissions(permissions)
.build();
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
}
private void mockNonAdminUser(Set<Long> libraryIds) {
List<Library> assignedLibraries = libraryIds.stream()
.map(id -> Library.builder().id(id).build())
.toList();
var permissions = new BookLoreUser.UserPermissions();
permissions.setAdmin(false);
BookLoreUser user = BookLoreUser.builder()
.id(userId)
.permissions(permissions)
.assignedLibraries(assignedLibraries)
.build();
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
}
private Tuple mockSeriesTuple(String name, Long count, Integer total, Instant addedOn, Long booksRead) {
Tuple tuple = mock(Tuple.class);
when(tuple.get(0, String.class)).thenReturn(name);
when(tuple.get(1, Long.class)).thenReturn(count);
when(tuple.get(2, Integer.class)).thenReturn(total);
when(tuple.get(3, Instant.class)).thenReturn(addedOn);
when(tuple.get(4, Long.class)).thenReturn(booksRead);
return tuple;
}
private Tuple mockSeriesTupleInProgress(String name, Long count, Integer total, Instant addedOn, Long booksRead, Instant lastReadTime) {
Tuple tuple = mockSeriesTuple(name, count, total, addedOn, booksRead);
when(tuple.get(5, Instant.class)).thenReturn(lastReadTime);
return tuple;
}
@SuppressWarnings("unchecked")
private void mockAggregateQuery(List<Tuple> results) {
TypedQuery<Tuple> aggregateQ = mock(TypedQuery.class);
when(aggregateQ.setParameter(anyString(), any())).thenReturn(aggregateQ);
when(aggregateQ.setFirstResult(anyInt())).thenReturn(aggregateQ);
when(aggregateQ.setMaxResults(anyInt())).thenReturn(aggregateQ);
when(aggregateQ.getResultList()).thenReturn(results);
TypedQuery<BookEntity> booksQ = mock(TypedQuery.class);
when(booksQ.setParameter(anyString(), any())).thenReturn(booksQ);
when(booksQ.getResultList()).thenReturn(Collections.emptyList());
when(entityManager.createQuery(anyString(), eq(Tuple.class))).thenReturn(aggregateQ);
when(entityManager.createQuery(anyString(), eq(BookEntity.class))).thenReturn(booksQ);
}
@SuppressWarnings("unchecked")
private void mockAggregateQueryInProgress(List<Tuple> results) {
// Pre-compute series names before setting up mocks to avoid calling .get() on mock Tuples during stubbing
List<String> seriesNames = new ArrayList<>();
for (Tuple t : results) {
seriesNames.add(t.get(0, String.class));
}
TypedQuery<Tuple> aggregateQ = mock(TypedQuery.class);
when(aggregateQ.setParameter(anyString(), any())).thenReturn(aggregateQ);
when(aggregateQ.setFirstResult(anyInt())).thenReturn(aggregateQ);
when(aggregateQ.setMaxResults(anyInt())).thenReturn(aggregateQ);
when(aggregateQ.getResultList()).thenReturn(results);
TypedQuery<BookEntity> booksQ = mock(TypedQuery.class);
when(booksQ.setParameter(anyString(), any())).thenReturn(booksQ);
when(booksQ.getResultList()).thenReturn(Collections.emptyList());
// In-progress count uses String.class query
TypedQuery<String> countQ = mock(TypedQuery.class);
when(countQ.setParameter(anyString(), any())).thenReturn(countQ);
when(countQ.getResultList()).thenReturn(seriesNames);
when(entityManager.createQuery(anyString(), eq(Tuple.class))).thenReturn(aggregateQ);
when(entityManager.createQuery(anyString(), eq(BookEntity.class))).thenReturn(booksQ);
when(entityManager.createQuery(anyString(), eq(String.class))).thenReturn(countQ);
}
@SuppressWarnings("unchecked")
private void mockCountQuery(long count) {
TypedQuery<Long> countQ = mock(TypedQuery.class);
when(countQ.setParameter(anyString(), any())).thenReturn(countQ);
when(countQ.getSingleResult()).thenReturn(count);
when(entityManager.createQuery(anyString(), eq(Long.class))).thenReturn(countQ);
}
@SuppressWarnings("unchecked")
private void mockCountQueryInProgress(long count) {
TypedQuery<String> countQ = mock(TypedQuery.class);
when(countQ.setParameter(anyString(), any())).thenReturn(countQ);
List<String> names = new ArrayList<>();
for (int i = 0; i < count; i++) names.add("series" + i);
when(countQ.getResultList()).thenReturn(names);
when(entityManager.createQuery(anyString(), eq(String.class))).thenReturn(countQ);
}
@SuppressWarnings("unchecked")
private void mockBooksQuery(List<BookEntity> books) {
TypedQuery<BookEntity> booksQ = mock(TypedQuery.class);
when(booksQ.setParameter(anyString(), any())).thenReturn(booksQ);
when(booksQ.getResultList()).thenReturn(books);
when(entityManager.createQuery(anyString(), eq(BookEntity.class))).thenReturn(booksQ);
}
@SuppressWarnings("unchecked")
private void mockBookPage(List<BookEntity> books, long total) {
var page = new PageImpl<>(books, Pageable.ofSize(20), total);
when(bookRepository.findAll(any(Specification.class), any(Pageable.class))).thenReturn(page);
}
private void mockProgress(List<UserBookProgressEntity> progressList) {
when(userBookProgressRepository.findByUserIdAndBookIdIn(eq(userId), anySet()))
.thenReturn(progressList);
}
private void mockMapperSummary() {
when(mobileBookMapper.toSummary(any(BookEntity.class), any()))
.thenAnswer(inv -> {
BookEntity b = inv.getArgument(0);
return MobileBookSummary.builder()
.id(b.getId())
.title(b.getMetadata() != null ? b.getMetadata().getTitle() : null)
.build();
});
}
private BookEntity buildBook(Long id, String seriesName, Float seriesNumber, String authorName) {
AuthorEntity author = new AuthorEntity();
author.setName(authorName);
BookMetadataEntity metadata = BookMetadataEntity.builder()
.bookId(id)
.title(seriesName + " #" + seriesNumber.intValue())
.seriesName(seriesName)
.seriesNumber(seriesNumber)
.coverUpdatedOn(Instant.now())
.authors(Set.of(author))
.build();
BookFileEntity bookFile = BookFileEntity.builder()
.id(id)
.bookType(BookFileType.EPUB)
.build();
List<BookFileEntity> bookFiles = new ArrayList<>(List.of(bookFile));
BookEntity book = BookEntity.builder()
.id(id)
.metadata(metadata)
.addedOn(Instant.now())
.bookFiles(bookFiles)
.build();
metadata.setBook(book);
bookFile.setBook(book);
return book;
}
}