feat(hardcover): implement book details response and search service enhancements (#2303)

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
Balázs Szücs
2026-01-18 18:19:58 -07:00
committed by GitHub
parent 0a3c6d72fa
commit a0f4c8e43e
8 changed files with 1474 additions and 125 deletions
@@ -0,0 +1,558 @@
package com.adityachandel.booklore.service.metadata.parser;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
import com.adityachandel.booklore.model.enums.MetadataProvider;
import com.adityachandel.booklore.service.metadata.parser.hardcover.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
/**
* Unit tests for HardcoverParser.
*
* These tests verify:
* - Combined title+author search strategy for better reliability
* - ISBN search behavior
* - Author filtering logic
* - Mood/genre/tag mapping with quality filtering
* - Edge cases and error handling
*/
class HardcoverParserTest {
@Mock
private HardcoverBookSearchService hardcoverBookSearchService;
private HardcoverParser parser;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
parser = new HardcoverParser(hardcoverBookSearchService);
}
@Nested
@DisplayName("Search Strategy Tests")
class SearchStrategyTests {
@Test
@DisplayName("Should search with combined title+author when both provided")
void fetchMetadata_titleAndAuthor_searchesCombined() {
Book book = Book.builder().title("Lamb").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Lamb")
.author("Christopher Moore")
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("Lamb: The Gospel According to Biff", "Christopher Moore");
when(hardcoverBookSearchService.searchBooks("Lamb Christopher Moore"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
verify(hardcoverBookSearchService).searchBooks("Lamb Christopher Moore");
assertThat(results).hasSize(1);
assertThat(results.get(0).getTitle()).isEqualTo("Lamb: The Gospel According to Biff");
}
@Test
@DisplayName("Should fall back to title-only search when combined search returns empty")
void fetchMetadata_combinedSearchEmpty_fallsBackToTitleOnly() {
Book book = Book.builder().title("Some Book").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Some Book")
.author("Unknown Author")
.build();
when(hardcoverBookSearchService.searchBooks("Some Book Unknown Author"))
.thenReturn(Collections.emptyList());
GraphQLResponse.Hit hit = createHitWithAuthor("Some Book", "Different Author");
when(hardcoverBookSearchService.searchBooks("Some Book"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
verify(hardcoverBookSearchService).searchBooks("Some Book Unknown Author");
verify(hardcoverBookSearchService).searchBooks("Some Book");
}
@Test
@DisplayName("Should search by ISBN when provided")
void fetchMetadata_isbnProvided_searchesByIsbn() {
Book book = Book.builder().title("Any Title").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Any Title")
.isbn("978-0316769488")
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("The Catcher in the Rye", "J.D. Salinger");
hit.getDocument().setIsbns(List.of("9780316769488", "0316769487"));
when(hardcoverBookSearchService.searchBooks("978-0316769488"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
verify(hardcoverBookSearchService).searchBooks("978-0316769488");
verify(hardcoverBookSearchService, never()).searchBooks(contains("title"));
}
@Test
@DisplayName("Should search title-only when no author provided")
void fetchMetadata_noAuthor_searchesTitleOnly() {
Book book = Book.builder().title("The Prince").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("The Prince")
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("The Prince", "Niccolò Machiavelli");
when(hardcoverBookSearchService.searchBooks("The Prince"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
verify(hardcoverBookSearchService).searchBooks("The Prince");
}
}
@Nested
@DisplayName("Author Filtering Tests")
class AuthorFilteringTests {
@Test
@DisplayName("Should filter results by author name when author provided")
void fetchMetadata_authorProvided_filtersResults() {
Book book = Book.builder().title("The Prince").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("The Prince")
.author("Machiavelli")
.build();
List<GraphQLResponse.Hit> hits = List.of(
createHitWithAuthor("The Prince", "Kiera Cass"),
createHitWithAuthor("The Prince", "Niccolò Machiavelli"),
createHitWithAuthor("The Prince", "Tiffany Reisz")
);
when(hardcoverBookSearchService.searchBooks("The Prince Machiavelli"))
.thenReturn(hits);
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results).hasSize(1);
assertThat(results.get(0).getAuthors()).contains("Niccolò Machiavelli");
}
@Test
@DisplayName("Should use fuzzy matching for author names")
void fetchMetadata_fuzzyAuthorMatch_includesPartialMatches() {
Book book = Book.builder().title("Test Book").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test Book")
.author("Moore")
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("Test Book", "Christopher Moore");
when(hardcoverBookSearchService.searchBooks("Test Book Moore"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results).hasSize(1);
}
@Test
@DisplayName("Should not filter by author for ISBN searches")
void fetchMetadata_isbnSearch_noAuthorFilter() {
Book book = Book.builder().title("Any Book").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Any Book")
.isbn("1234567890")
.author("Wrong Author") // Should be ignored
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("Any Book", "Correct Author");
when(hardcoverBookSearchService.searchBooks("1234567890"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results).hasSize(1); // Should not filter out
}
}
@Nested
@DisplayName("Metadata Mapping Tests")
class MetadataMappingTests {
@Test
@DisplayName("Should map all basic metadata fields correctly")
void fetchMetadata_fullDocument_mapsAllFields() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.isbn("9781234567890")
.build();
GraphQLResponse.Hit hit = createFullyPopulatedHit();
when(hardcoverBookSearchService.searchBooks("9781234567890"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results).hasSize(1);
BookMetadata metadata = results.get(0);
assertThat(metadata.getTitle()).isEqualTo("Test Book");
assertThat(metadata.getSubtitle()).isEqualTo("A Subtitle");
assertThat(metadata.getDescription()).isEqualTo("A description");
assertThat(metadata.getHardcoverId()).isEqualTo("test-book-slug");
assertThat(metadata.getHardcoverBookId()).isEqualTo(12345);
assertThat(metadata.getHardcoverRating()).isEqualTo(4.25);
assertThat(metadata.getHardcoverReviewCount()).isEqualTo(100);
assertThat(metadata.getPageCount()).isEqualTo(350);
assertThat(metadata.getAuthors()).contains("Test Author");
assertThat(metadata.getSeriesName()).isEqualTo("Test Series");
assertThat(metadata.getSeriesNumber()).isEqualTo(2.0f);
assertThat(metadata.getSeriesTotal()).isEqualTo(5);
assertThat(metadata.getIsbn13()).isEqualTo("9781234567890");
assertThat(metadata.getIsbn10()).isEqualTo("1234567890");
assertThat(metadata.getProvider()).isEqualTo(MetadataProvider.Hardcover);
}
@Test
@DisplayName("Should map thumbnail URL correctly")
void fetchMetadata_withImage_mapsThumbnailUrl() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author");
GraphQLResponse.Image image = new GraphQLResponse.Image();
image.setUrl("https://example.com/cover.jpg");
hit.getDocument().setImage(image);
when(hardcoverBookSearchService.searchBooks("Test"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results.get(0).getThumbnailUrl()).isEqualTo("https://example.com/cover.jpg");
}
@Test
@DisplayName("Should handle null image gracefully")
void fetchMetadata_nullImage_handlesGracefully() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author");
hit.getDocument().setImage(null);
when(hardcoverBookSearchService.searchBooks("Test"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results.get(0).getThumbnailUrl()).isNull();
}
}
@Nested
@DisplayName("Mood and Genre Filtering Tests")
class MoodFilteringTests {
@Test
@DisplayName("Should fetch detailed book info for mood filtering when book ID available")
void fetchMetadata_withBookId_fetchesDetailedMoods() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author");
hit.getDocument().setId("12345");
hit.getDocument().setMoods(List.of("sad", "dark", "funny", "hopeful"));
when(hardcoverBookSearchService.searchBooks("Test"))
.thenReturn(List.of(hit));
HardcoverBookDetails details = createBookDetailsWithMoodCounts();
when(hardcoverBookSearchService.fetchBookDetails(12345))
.thenReturn(details);
List<BookMetadata> results = parser.fetchMetadata(book, request);
verify(hardcoverBookSearchService).fetchBookDetails(12345);
assertThat(results.get(0).getMoods()).isNotNull();
}
@Test
@DisplayName("Should fall back to basic mood filtering when detail fetch fails")
void fetchMetadata_detailFetchFails_fallsBackToBasicFilter() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author");
hit.getDocument().setId("12345");
hit.getDocument().setMoods(List.of("sad", "funny", "invalid-mood"));
when(hardcoverBookSearchService.searchBooks("Test"))
.thenReturn(List.of(hit));
when(hardcoverBookSearchService.fetchBookDetails(12345))
.thenReturn(null); // Simulate failure
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results.get(0).getMoods())
.containsAnyOf("Sad", "Funny")
.doesNotContain("Invalid-Mood");
}
@Test
@DisplayName("Should handle books without moods")
void fetchMetadata_noMoods_handlesGracefully() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author");
hit.getDocument().setMoods(null);
when(hardcoverBookSearchService.searchBooks("Test"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results).hasSize(1);
}
}
@Nested
@DisplayName("Edge Cases and Error Handling")
class EdgeCaseTests {
@Test
@DisplayName("Should return empty list when search returns null")
void fetchMetadata_nullResponse_returnsEmptyList() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.build();
when(hardcoverBookSearchService.searchBooks(anyString()))
.thenReturn(null);
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results).isEmpty();
}
@Test
@DisplayName("Should return empty list when search returns empty")
void fetchMetadata_emptyResponse_returnsEmptyList() {
Book book = Book.builder().title("Nonexistent Book").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Nonexistent Book")
.build();
when(hardcoverBookSearchService.searchBooks(anyString()))
.thenReturn(Collections.emptyList());
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results).isEmpty();
}
@Test
@DisplayName("Should handle invalid book ID gracefully")
void fetchMetadata_invalidBookId_handlesGracefully() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author");
hit.getDocument().setId("not-a-number");
when(hardcoverBookSearchService.searchBooks("Test"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results).hasSize(1);
assertThat(results.get(0).getHardcoverBookId()).isNull();
}
@Test
@DisplayName("Should handle null title in request")
void fetchMetadata_nullTitle_returnsEmptyList() {
Book book = Book.builder().build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.author("Some Author")
.build();
when(hardcoverBookSearchService.searchBooks(anyString()))
.thenReturn(Collections.emptyList());
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results).isEmpty();
}
@Test
@DisplayName("Should handle invalid date format gracefully")
void fetchMetadata_invalidDate_handlesGracefully() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author");
hit.getDocument().setReleaseDate("invalid-date");
when(hardcoverBookSearchService.searchBooks("Test"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results).hasSize(1);
assertThat(results.get(0).getPublishedDate()).isNull();
}
}
@Nested
@DisplayName("fetchTopMetadata Tests")
class FetchTopMetadataTests {
@Test
@DisplayName("Should return first result")
void fetchTopMetadata_hasResults_returnsFirst() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.build();
List<GraphQLResponse.Hit> hits = List.of(
createHitWithAuthor("First Book", "Author 1"),
createHitWithAuthor("Second Book", "Author 2")
);
when(hardcoverBookSearchService.searchBooks("Test"))
.thenReturn(hits);
BookMetadata result = parser.fetchTopMetadata(book, request);
assertThat(result).isNotNull();
assertThat(result.getTitle()).isEqualTo("First Book");
}
@Test
@DisplayName("Should return null when no results")
void fetchTopMetadata_noResults_returnsNull() {
Book book = Book.builder().title("Nonexistent").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Nonexistent")
.build();
when(hardcoverBookSearchService.searchBooks(anyString()))
.thenReturn(Collections.emptyList());
BookMetadata result = parser.fetchTopMetadata(book, request);
assertThat(result).isNull();
}
}
private GraphQLResponse.Hit createHitWithAuthor(String title, String author) {
GraphQLResponse.Document doc = new GraphQLResponse.Document();
doc.setTitle(title);
doc.setSlug(title.toLowerCase().replace(" ", "-"));
doc.setAuthorNames(Set.of(author));
doc.setId(String.valueOf(new Random().nextInt(100000)));
GraphQLResponse.Hit hit = new GraphQLResponse.Hit();
hit.setDocument(doc);
return hit;
}
private GraphQLResponse.Hit createFullyPopulatedHit() {
GraphQLResponse.Document doc = new GraphQLResponse.Document();
doc.setId("12345");
doc.setSlug("test-book-slug");
doc.setTitle("Test Book");
doc.setSubtitle("A Subtitle");
doc.setDescription("A description");
doc.setAuthorNames(Set.of("Test Author"));
doc.setRating(4.25);
doc.setRatingsCount(100);
doc.setPages(350);
doc.setReleaseDate("2023-01-15");
doc.setIsbns(List.of("9781234567890", "1234567890"));
doc.setGenres(List.of("Fiction", "Fantasy"));
doc.setMoods(List.of("adventurous", "exciting"));
doc.setTags(List.of("Epic"));
// Series info
GraphQLResponse.Series series = new GraphQLResponse.Series();
series.setName("Test Series");
series.setBooksCount(5);
GraphQLResponse.FeaturedSeries featuredSeries = new GraphQLResponse.FeaturedSeries();
featuredSeries.setSeries(series);
featuredSeries.setPosition(2);
doc.setFeaturedSeries(featuredSeries);
// Image
GraphQLResponse.Image image = new GraphQLResponse.Image();
image.setUrl("https://example.com/cover.jpg");
doc.setImage(image);
GraphQLResponse.Hit hit = new GraphQLResponse.Hit();
hit.setDocument(doc);
return hit;
}
private HardcoverBookDetails createBookDetailsWithMoodCounts() {
HardcoverBookDetails details = new HardcoverBookDetails();
details.setId(12345);
details.setTitle("Test Book");
Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags = new HashMap<>();
List<HardcoverBookDetails.CachedTag> moods = new ArrayList<>();
moods.add(createCachedTag("sad", 15));
moods.add(createCachedTag("dark", 12));
moods.add(createCachedTag("emotional", 8));
moods.add(createCachedTag("funny", 2)); // Low count, should be filtered
cachedTags.put("Mood", moods);
List<HardcoverBookDetails.CachedTag> genres = new ArrayList<>();
genres.add(createCachedTag("Fiction", 10));
genres.add(createCachedTag("Drama", 8));
cachedTags.put("Genre", genres);
details.setCachedTags(cachedTags);
return details;
}
private HardcoverBookDetails.CachedTag createCachedTag(String tag, int count) {
HardcoverBookDetails.CachedTag cachedTag = new HardcoverBookDetails.CachedTag();
cachedTag.setTag(tag);
cachedTag.setCount(count);
return cachedTag;
}
}
@@ -0,0 +1,114 @@
package com.adityachandel.booklore.service.metadata.parser.hardcover;
import com.adityachandel.booklore.model.dto.settings.AppSettings;
import com.adityachandel.booklore.model.dto.settings.MetadataProviderSettings;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
class HardcoverBookSearchServiceTest {
@Mock
private AppSettingService appSettingService;
private HardcoverBookSearchService searchService;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
searchService = new HardcoverBookSearchService(appSettingService);
}
@Nested
@DisplayName("API Token Validation Tests")
class ApiTokenTests {
@Test
@DisplayName("Should return empty list when API token is null")
void searchBooks_nullToken_returnsEmptyList() {
setupAppSettingsWithToken(null);
List<GraphQLResponse.Hit> results = searchService.searchBooks("test query");
assertThat(results).isEmpty();
}
@Test
@DisplayName("Should return empty list when API token is empty")
void searchBooks_emptyToken_returnsEmptyList() {
setupAppSettingsWithToken("");
List<GraphQLResponse.Hit> results = searchService.searchBooks("test query");
assertThat(results).isEmpty();
}
}
@Nested
@DisplayName("Search Parameter Tests")
class SearchParameterTests {
@Test
@DisplayName("Default per_page should be 10")
void defaultPerPage_is10() {
assertThat(HardcoverBookSearchService.DEFAULT_PER_PAGE).isEqualTo(10);
}
@Test
@DisplayName("searchBooks with perPage should respect the parameter")
void searchBooks_withPerPage_respectsParameter() {
setupAppSettingsWithToken(null); // Will return empty but logic is tested
List<GraphQLResponse.Hit> results = searchService.searchBooks("test", 50);
assertThat(results).isEmpty();
}
}
@Nested
@DisplayName("fetchBookDetails Tests")
class FetchBookDetailsTests {
@Test
@DisplayName("Should return null when API token is not set")
void fetchBookDetails_noToken_returnsNull() {
setupAppSettingsWithToken(null);
HardcoverBookDetails result = searchService.fetchBookDetails(12345);
assertThat(result).isNull();
}
@Test
@DisplayName("Should return null when API token is empty")
void fetchBookDetails_emptyToken_returnsNull() {
setupAppSettingsWithToken("");
HardcoverBookDetails result = searchService.fetchBookDetails(12345);
assertThat(result).isNull();
}
}
private void setupAppSettingsWithToken(String token) {
AppSettings appSettings = new AppSettings();
MetadataProviderSettings providerSettings = new MetadataProviderSettings();
MetadataProviderSettings.Hardcover hardcover = new MetadataProviderSettings.Hardcover();
hardcover.setApiKey(token);
providerSettings.setHardcover(hardcover);
appSettings.setMetadataProviderSettings(providerSettings);
when(appSettingService.getAppSettings()).thenReturn(appSettings);
}
}
@@ -0,0 +1,258 @@
package com.adityachandel.booklore.service.metadata.parser.hardcover;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
class HardcoverMoodFilterTest {
@Test
@DisplayName("filterBasicMoods should return empty set for null input")
void filterBasicMoods_nullInput_returnsEmptySet() {
Set<String> result = HardcoverMoodFilter.filterBasicMoods(null);
assertThat(result).isEmpty();
}
@Test
@DisplayName("filterBasicMoods should return empty set for empty list")
void filterBasicMoods_emptyList_returnsEmptySet() {
Set<String> result = HardcoverMoodFilter.filterBasicMoods(Collections.emptyList());
assertThat(result).isEmpty();
}
@Test
@DisplayName("filterBasicMoods should only return recognized moods")
void filterBasicMoods_mixedMoods_returnsOnlyRecognized() {
List<String> moods = List.of("funny", "invalid-mood", "sad", "not-a-mood", "dark");
Set<String> result = HardcoverMoodFilter.filterBasicMoods(moods);
assertThat(result)
.containsExactlyInAnyOrder("funny", "sad", "dark")
.doesNotContain("invalid-mood", "not-a-mood");
}
@Test
@DisplayName("filterBasicMoods should normalize case to lowercase")
void filterBasicMoods_mixedCase_normalizesToLowercase() {
List<String> moods = List.of("FUNNY", "Sad", "DaRk", "Emotional");
Set<String> result = HardcoverMoodFilter.filterBasicMoods(moods);
assertThat(result)
.containsExactlyInAnyOrder("funny", "sad", "dark", "emotional");
}
@Test
@DisplayName("filterBasicMoods should limit results to MAX_MOODS")
void filterBasicMoods_tooManyMoods_limitsToMax() {
List<String> moods = List.of(
"funny", "sad", "dark", "emotional", "tense",
"hopeful", "romantic", "scary", "mysterious", "reflective"
);
Set<String> result = HardcoverMoodFilter.filterBasicMoods(moods);
assertThat(result).hasSize(HardcoverMoodFilter.MAX_MOODS);
}
@Test
@DisplayName("filterBasicMoods should handle null entries in list")
void filterBasicMoods_nullEntries_ignoresNulls() {
List<String> moods = new ArrayList<>();
moods.add("funny");
moods.add(null);
moods.add("sad");
moods.add(null);
Set<String> result = HardcoverMoodFilter.filterBasicMoods(moods);
assertThat(result).containsExactlyInAnyOrder("funny", "sad");
}
@Test
@DisplayName("filterBasicMoods should trim whitespace from moods")
void filterBasicMoods_whitespace_trimsCorrectly() {
List<String> moods = List.of(" funny ", " sad", "dark ");
Set<String> result = HardcoverMoodFilter.filterBasicMoods(moods);
assertThat(result).containsExactlyInAnyOrder("funny", "sad", "dark");
}
@Test
@DisplayName("filterMoodsWithCounts should return empty set for null cached_tags")
void filterMoodsWithCounts_nullCachedTags_returnsEmptySet() {
Set<String> result = HardcoverMoodFilter.filterMoodsWithCounts(null);
assertThat(result).isEmpty();
}
@Test
@DisplayName("filterMoodsWithCounts should return empty set when no Mood category")
void filterMoodsWithCounts_noMoodCategory_returnsEmptySet() {
Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags = new HashMap<>();
cachedTags.put("Genre", List.of(createCachedTag("Fiction", 10)));
Set<String> result = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags);
assertThat(result).isEmpty();
}
@Test
@DisplayName("filterMoodsWithCounts should filter out low-vote moods")
void filterMoodsWithCounts_mixedVotes_filtersLowVotes() {
// Simulating "All Quiet on the Western Front" scenario
// "sad" has 17 votes, "funny" has 4 votes
// With max=17 and MIN_VOTE_RATIO=0.15, threshold is ~3
// But "funny" at 4 votes should still be filtered if we use higher threshold
Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags = new HashMap<>();
cachedTags.put("Mood", List.of(
createCachedTag("sad", 17),
createCachedTag("dark", 16),
createCachedTag("emotional", 10),
createCachedTag("funny", 4), // Low relative to "sad"
createCachedTag("hopeful", 1), // Very low
createCachedTag("scary", 1) // Very low
));
Set<String> result = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags);
// Top moods should be included
assertThat(result).contains("sad", "dark", "emotional");
// Low-vote moods should be filtered
assertThat(result).doesNotContain("hopeful", "scary");
}
@Test
@DisplayName("filterMoodsWithCounts should respect MAX_MOODS limit")
void filterMoodsWithCounts_manyHighVoteMoods_limitsToMax() {
Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags = new HashMap<>();
List<HardcoverBookDetails.CachedTag> moodTags = new ArrayList<>();
// Create 10 moods all with high vote counts
for (int i = 0; i < 10; i++) {
moodTags.add(createCachedTag("mood" + i, 20 - i));
}
cachedTags.put("Mood", moodTags);
Set<String> result = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags);
assertThat(result).hasSize(HardcoverMoodFilter.MAX_MOODS);
}
@Test
@DisplayName("filterMoodsWithCounts should order moods by vote count (highest first)")
void filterMoodsWithCounts_orderedByVoteCount() {
Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags = new HashMap<>();
cachedTags.put("Mood", List.of(
createCachedTag("emotional", 5),
createCachedTag("sad", 15),
createCachedTag("dark", 10)
));
Set<String> result = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags);
// Result should be LinkedHashSet preserving order
List<String> resultList = new ArrayList<>(result);
assertThat(resultList).containsExactly("sad", "dark", "emotional");
}
@Test
@DisplayName("filterMoodsWithCounts should handle null vote counts")
void filterMoodsWithCounts_nullVoteCounts_handlesGracefully() {
Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags = new HashMap<>();
HardcoverBookDetails.CachedTag tagWithNullCount = createCachedTag("mysterious", null);
cachedTags.put("Mood", List.of(
createCachedTag("sad", 10),
tagWithNullCount,
createCachedTag("dark", 8)
));
Set<String> result = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags);
assertThat(result).containsExactlyInAnyOrder("sad", "dark");
assertThat(result).doesNotContain("mysterious");
}
@Test
@DisplayName("filterMoodsWithCounts should return empty when all votes are zero")
void filterMoodsWithCounts_allZeroVotes_returnsEmpty() {
Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags = new HashMap<>();
cachedTags.put("Mood", List.of(
createCachedTag("sad", 0),
createCachedTag("dark", 0)
));
Set<String> result = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags);
assertThat(result).isEmpty();
}
@Test
@DisplayName("filterGenresWithCounts should return filtered genres")
void filterGenresWithCounts_validData_returnsFiltered() {
Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags = new HashMap<>();
cachedTags.put("Genre", List.of(
createCachedTag("Fiction", 10),
createCachedTag("War", 8),
createCachedTag("Classics", 5),
createCachedTag("Comics", 0) // Should be filtered out
));
Set<String> result = HardcoverMoodFilter.filterGenresWithCounts(cachedTags);
assertThat(result).containsExactlyInAnyOrder("Fiction", "War", "Classics");
assertThat(result).doesNotContain("Comics");
}
@Test
@DisplayName("filterTagsWithCounts should filter tags with low votes")
void filterTagsWithCounts_mixedVotes_filtersLowVotes() {
Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags = new HashMap<>();
cachedTags.put("Tag", List.of(
createCachedTag("Loveable Characters", 13),
createCachedTag("Strong Character Development", 9),
createCachedTag("Plot driven", 1) // Should be filtered (below threshold)
));
Set<String> result = HardcoverMoodFilter.filterTagsWithCounts(cachedTags);
assertThat(result).contains("Loveable Characters", "Strong Character Development");
assertThat(result).doesNotContain("Plot driven");
}
@Test
@DisplayName("normalizeMood should return null for null input")
void normalizeMood_nullInput_returnsNull() {
String result = HardcoverMoodFilter.normalizeMood(null);
assertThat(result).isNull();
}
@Test
@DisplayName("normalizeMood should lowercase and trim")
void normalizeMood_mixedCaseWithWhitespace_normalizes() {
String result = HardcoverMoodFilter.normalizeMood(" FuNnY ");
assertThat(result).isEqualTo("funny");
}
@Test
@DisplayName("All recognized moods should be in the set")
void recognizedMoods_containsExpectedMoods() {
assertThat(HardcoverMoodFilter.RECOGNIZED_MOODS)
.contains("adventurous", "challenging", "dark", "emotional", "funny",
"hopeful", "informative", "inspiring", "lighthearted", "mysterious",
"reflective", "relaxing", "romantic", "sad", "scary", "tense");
}
/**
* Helper method to create a CachedTag for testing.
*/
private HardcoverBookDetails.CachedTag createCachedTag(String tag, Integer count) {
HardcoverBookDetails.CachedTag cachedTag = new HardcoverBookDetails.CachedTag();
cachedTag.setTag(tag);
cachedTag.setCount(count);
return cachedTag;
}
}