fix(metadata-parsers): improve ISBN search logic and fallback strategies for metadata fetching (#2502)
* fix(metadata-parsers): improve ISBN search logic and fallback strategies for metadata fetching - Update GoogleParser, HardcoverParser, and ComicvineBookParser to prioritize ISBN search and implement robust fallbacks to title+author and title-only queries - Refactor GoogleParser to allow dependency injection for HttpClient and Jsoup connections, improving testability - Enhance HardcoverParser to retry with title-only search if combined title+author results are filtered out - Adjust MetadataRefreshService to prefer ISBN-13 over ISBN-10 when building fetch requests - Add JsoupConnectionFactory and DefaultJsoupConnectionFactory for injectable Jsoup connections - Expand and improve unit tests for GoogleParser and HardcoverParser to cover new fallback behaviors Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> * fix(google-parser): handle null primary file and correct search term return Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> --------- Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
+5
-1
@@ -407,8 +407,12 @@ public class MetadataRefreshService {
|
||||
|
||||
private FetchMetadataRequest buildFetchMetadataRequestFromBook(Book book) {
|
||||
BookMetadata metadata = book.getMetadata();
|
||||
String isbn = metadata.getIsbn13();
|
||||
if (isbn == null || isbn.isBlank()) {
|
||||
isbn = metadata.getIsbn10();
|
||||
}
|
||||
return FetchMetadataRequest.builder()
|
||||
.isbn(metadata.getIsbn10())
|
||||
.isbn(isbn)
|
||||
.asin(metadata.getAsin())
|
||||
.author(metadata.getAuthors() != null ? String.join(", ", metadata.getAuthors()) : null)
|
||||
.title(metadata.getTitle())
|
||||
|
||||
+10
@@ -84,6 +84,16 @@ public class ComicvineBookParser implements BookParser {
|
||||
|
||||
@Override
|
||||
public List<BookMetadata> fetchMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
|
||||
// 1. Try ISBN Search
|
||||
String isbn = ParserUtils.cleanIsbn(fetchMetadataRequest.getIsbn());
|
||||
if (isbn != null && !isbn.isEmpty()) {
|
||||
log.info("Comicvine: Searching by ISBN: {}", isbn);
|
||||
// ComicVine "search" endpoint with "query" parameter performs a general search.
|
||||
List<BookMetadata> results = searchGeneral(isbn);
|
||||
if (!results.isEmpty()) return results;
|
||||
log.info("Comicvine: ISBN search returned no results, falling back to Title/Term.");
|
||||
}
|
||||
|
||||
String searchTerm = getSearchTerm(book, fetchMetadataRequest);
|
||||
if (searchTerm == null) {
|
||||
log.warn("No valid search term provided for metadata fetch.");
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.adityachandel.booklore.service.metadata.parser;
|
||||
|
||||
import org.jsoup.Connection;
|
||||
import org.jsoup.Jsoup;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class DefaultJsoupConnectionFactory implements JsoupConnectionFactory {
|
||||
@Override
|
||||
public Connection connect(String url) {
|
||||
return Jsoup.connect(url);
|
||||
}
|
||||
}
|
||||
+7
-3
@@ -495,9 +495,13 @@ public class GoodReadsParser implements BookParser {
|
||||
}
|
||||
|
||||
private String getSearchTerm(Book book, FetchMetadataRequest request) {
|
||||
return (request.getTitle() != null && !request.getTitle().isEmpty())
|
||||
? request.getTitle()
|
||||
: (book.getPrimaryFile() != null && book.getPrimaryFile().getFileName() != null && !book.getPrimaryFile().getFileName().isEmpty()
|
||||
if (request.getTitle() != null && !request.getTitle().isEmpty()) {
|
||||
if (request.getAuthor() != null && !request.getAuthor().isEmpty()) {
|
||||
return request.getTitle() + " " + request.getAuthor();
|
||||
}
|
||||
return request.getTitle();
|
||||
}
|
||||
return (book.getPrimaryFile() != null && book.getPrimaryFile().getFileName() != null && !book.getPrimaryFile().getFileName().isEmpty()
|
||||
? BookUtils.cleanFileName(book.getPrimaryFile().getFileName())
|
||||
: null);
|
||||
}
|
||||
|
||||
+65
-14
@@ -8,9 +8,9 @@ import com.adityachandel.booklore.model.enums.MetadataProvider;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.util.BookUtils;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jsoup.Jsoup;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
@@ -31,7 +31,6 @@ import java.util.stream.Stream;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GoogleParser implements BookParser {
|
||||
|
||||
private static final Pattern FOUR_DIGIT_YEAR_PATTERN = Pattern.compile("^(\\d{4})$");
|
||||
@@ -44,10 +43,21 @@ public class GoogleParser implements BookParser {
|
||||
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
private final ObjectMapper objectMapper;
|
||||
private final AppSettingService appSettingService;
|
||||
private final HttpClient httpClient = HttpClient.newHttpClient();
|
||||
private final HttpClient httpClient;
|
||||
private static final String GOOGLE_BOOKS_API_URL = "https://www.googleapis.com/books/v1/volumes";
|
||||
private final AtomicLong lastRequestTime = new AtomicLong(0);
|
||||
|
||||
@Autowired
|
||||
public GoogleParser(ObjectMapper objectMapper, AppSettingService appSettingService) {
|
||||
this(objectMapper, appSettingService, HttpClient.newHttpClient());
|
||||
}
|
||||
|
||||
public GoogleParser(ObjectMapper objectMapper, AppSettingService appSettingService, HttpClient httpClient) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.appSettingService = appSettingService;
|
||||
this.httpClient = httpClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BookMetadata fetchTopMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
|
||||
List<BookMetadata> fetchedBookMetadata = fetchMetadata(book, fetchMetadataRequest);
|
||||
@@ -56,11 +66,56 @@ public class GoogleParser implements BookParser {
|
||||
|
||||
@Override
|
||||
public List<BookMetadata> fetchMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
|
||||
// 1. Try ISBN Search
|
||||
if (fetchMetadataRequest.getIsbn() != null && !fetchMetadataRequest.getIsbn().isBlank()) {
|
||||
return getMetadataListByIsbn(ParserUtils.cleanIsbn(fetchMetadataRequest.getIsbn()));
|
||||
List<BookMetadata> isbnResults = getMetadataListByIsbn(ParserUtils.cleanIsbn(fetchMetadataRequest.getIsbn()));
|
||||
if (!isbnResults.isEmpty()) {
|
||||
return isbnResults;
|
||||
}
|
||||
log.info("Google Books: ISBN search returned no results, falling back to Title+Author search.");
|
||||
}
|
||||
String searchTerm = getSearchTerm(book, fetchMetadataRequest);
|
||||
return searchTerm != null ? getMetadataListByTerm(searchTerm) : List.of();
|
||||
|
||||
String title = fetchMetadataRequest.getTitle();
|
||||
String author = fetchMetadataRequest.getAuthor();
|
||||
String fileName = book.getPrimaryFile() != null ? book.getPrimaryFile().getFileName() : null;
|
||||
|
||||
List<BookMetadata> results = Collections.emptyList();
|
||||
|
||||
// 2. Try Title + Author Search
|
||||
if (title != null && !title.isBlank() && author != null && !author.isBlank()) {
|
||||
String term = buildSearchTerm(title, author);
|
||||
log.info("Google Books: Searching with Title + Author: {}", term);
|
||||
results = getMetadataListByTerm(term);
|
||||
}
|
||||
|
||||
// 3. Try Title Only Search (if Title+Author failed or wasn't attempted)
|
||||
if (results.isEmpty()) {
|
||||
String term = null;
|
||||
if (title != null && !title.isBlank()) {
|
||||
term = buildSearchTerm(title, null);
|
||||
log.info("Google Books: Searching with Title Only: {}", term);
|
||||
} else if (fileName != null && !fileName.isBlank()) {
|
||||
term = buildSearchTerm(BookUtils.cleanFileName(fileName), null);
|
||||
log.info("Google Books: Searching with Filename: {}", term);
|
||||
}
|
||||
|
||||
if (term != null) {
|
||||
results = getMetadataListByTerm(term);
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
private String buildSearchTerm(String title, String author) {
|
||||
String searchTerm = SPECIAL_CHARACTERS_PATTERN.matcher(title).replaceAll("").trim();
|
||||
searchTerm = "intitle:" + truncateToMaxWords(searchTerm);
|
||||
|
||||
if (author != null && !author.isBlank()) {
|
||||
searchTerm += " inauthor:" + author;
|
||||
}
|
||||
|
||||
return searchTerm;
|
||||
}
|
||||
|
||||
private List<BookMetadata> getMetadataListByIsbn(String isbn) {
|
||||
@@ -454,13 +509,6 @@ public class GoogleParser implements BookParser {
|
||||
return null;
|
||||
}
|
||||
|
||||
searchTerm = SPECIAL_CHARACTERS_PATTERN.matcher(searchTerm).replaceAll("").trim();
|
||||
searchTerm = "intitle:" + truncateToMaxWords(searchTerm);
|
||||
|
||||
if (request.getAuthor() != null && !request.getAuthor().isEmpty()) {
|
||||
searchTerm += " inauthor:" + request.getAuthor();
|
||||
}
|
||||
|
||||
return searchTerm;
|
||||
}
|
||||
|
||||
@@ -594,4 +642,7 @@ public class GoogleParser implements BookParser {
|
||||
|
||||
return count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
+56
-49
@@ -4,7 +4,10 @@ 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 com.adityachandel.booklore.service.metadata.parser.hardcover.GraphQLResponse;
|
||||
import com.adityachandel.booklore.service.metadata.parser.hardcover.HardcoverBookDetails;
|
||||
import com.adityachandel.booklore.service.metadata.parser.hardcover.HardcoverBookSearchService;
|
||||
import com.adityachandel.booklore.service.metadata.parser.hardcover.HardcoverMoodFilter;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.text.WordUtils;
|
||||
@@ -33,69 +36,73 @@ public class HardcoverParser implements BookParser {
|
||||
String isbnCleaned = ParserUtils.cleanIsbn(fetchMetadataRequest.getIsbn());
|
||||
boolean searchByIsbn = isbnCleaned != null && !isbnCleaned.isBlank();
|
||||
|
||||
List<GraphQLResponse.Hit> hits;
|
||||
if (searchByIsbn) {
|
||||
log.info("Hardcover: Fetching metadata using ISBN {}", fetchMetadataRequest.getIsbn());
|
||||
hits = hardcoverBookSearchService.searchBooks(fetchMetadataRequest.getIsbn());
|
||||
} else {
|
||||
// Use improved search strategy with title cleaning and fallbacks
|
||||
hits = performSmartSearch(fetchMetadataRequest);
|
||||
List<GraphQLResponse.Hit> hits = hardcoverBookSearchService.searchBooks(fetchMetadataRequest.getIsbn());
|
||||
return processHits(hits, fetchMetadataRequest, true);
|
||||
}
|
||||
|
||||
if (hits == null || hits.isEmpty()) {
|
||||
log.info("Hardcover: No results found for {}",
|
||||
searchByIsbn ? "ISBN " + fetchMetadataRequest.getIsbn() : "title " + fetchMetadataRequest.getTitle());
|
||||
return List.of();
|
||||
}
|
||||
|
||||
FuzzyScore fuzzyScore = new FuzzyScore(Locale.ENGLISH);
|
||||
String searchAuthor = fetchMetadataRequest.getAuthor() != null ? fetchMetadataRequest.getAuthor() : "";
|
||||
|
||||
// Filter by author and map to metadata
|
||||
List<GraphQLResponse.Document> matchedDocs = hits.stream()
|
||||
.map(GraphQLResponse.Hit::getDocument)
|
||||
.filter(doc -> filterByAuthor(doc, searchAuthor, searchByIsbn, fuzzyScore))
|
||||
.toList();
|
||||
|
||||
if (matchedDocs.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
// Only fetch detailed mood data for the TOP match to minimize API calls
|
||||
// Other results use the basic mood data from search
|
||||
List<BookMetadata> results = new ArrayList<>();
|
||||
boolean isFirst = true;
|
||||
|
||||
for (GraphQLResponse.Document doc : matchedDocs) {
|
||||
BookMetadata metadata = mapDocumentToMetadata(doc, fetchMetadataRequest, isFirst);
|
||||
results.add(metadata);
|
||||
isFirst = false;
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
private List<GraphQLResponse.Hit> performSmartSearch(FetchMetadataRequest request) {
|
||||
String title = request.getTitle();
|
||||
String author = request.getAuthor();
|
||||
String title = fetchMetadataRequest.getTitle();
|
||||
String author = fetchMetadataRequest.getAuthor();
|
||||
|
||||
if (title == null || title.isBlank()) {
|
||||
log.warn("Hardcover: No title provided for search");
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
List<BookMetadata> results = Collections.emptyList();
|
||||
|
||||
// 1. Try Title + Author
|
||||
if (author != null && !author.isBlank()) {
|
||||
String combinedQuery = title.trim() + " " + author.trim();
|
||||
log.info("Hardcover: Searching with title+author: '{}'", combinedQuery);
|
||||
List<GraphQLResponse.Hit> results = hardcoverBookSearchService.searchBooks(combinedQuery);
|
||||
if (results != null && !results.isEmpty()) {
|
||||
return results;
|
||||
}
|
||||
List<GraphQLResponse.Hit> hits = hardcoverBookSearchService.searchBooks(combinedQuery);
|
||||
results = processHits(hits, fetchMetadataRequest, false);
|
||||
}
|
||||
|
||||
log.info("Hardcover: Searching with title: '{}'", title);
|
||||
List<GraphQLResponse.Hit> results = hardcoverBookSearchService.searchBooks(title.trim());
|
||||
return results != null ? results : Collections.emptyList();
|
||||
// 2. If no valid results found (or no author provided), Try Title only
|
||||
if (results.isEmpty()) {
|
||||
log.info("Hardcover: Searching with title only: '{}'", title);
|
||||
List<GraphQLResponse.Hit> hits = hardcoverBookSearchService.searchBooks(title.trim());
|
||||
results = processHits(hits, fetchMetadataRequest, false);
|
||||
}
|
||||
|
||||
if (results.isEmpty()) {
|
||||
log.info("Hardcover: No results found for title '{}'", title);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
private List<BookMetadata> processHits(List<GraphQLResponse.Hit> hits, FetchMetadataRequest request, boolean searchByIsbn) {
|
||||
if (hits == null || hits.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
FuzzyScore fuzzyScore = new FuzzyScore(Locale.ENGLISH);
|
||||
String searchAuthor = request.getAuthor() != null ? request.getAuthor() : "";
|
||||
|
||||
// Filter by author
|
||||
List<GraphQLResponse.Document> matchedDocs = hits.stream()
|
||||
.map(GraphQLResponse.Hit::getDocument)
|
||||
.filter(doc -> filterByAuthor(doc, searchAuthor, searchByIsbn, fuzzyScore))
|
||||
.toList();
|
||||
|
||||
if (matchedDocs.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
// Only fetch detailed mood data for the TOP match to minimize API calls
|
||||
List<BookMetadata> results = new ArrayList<>();
|
||||
boolean isFirst = true;
|
||||
|
||||
for (GraphQLResponse.Document doc : matchedDocs) {
|
||||
BookMetadata metadata = mapDocumentToMetadata(doc, request, isFirst);
|
||||
results.add(metadata);
|
||||
isFirst = false;
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
private boolean filterByAuthor(GraphQLResponse.Document doc, String searchAuthor,
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.adityachandel.booklore.service.metadata.parser;
|
||||
|
||||
import org.jsoup.Connection;
|
||||
|
||||
public interface JsoupConnectionFactory {
|
||||
Connection connect(String url);
|
||||
}
|
||||
+116
-31
@@ -1,69 +1,154 @@
|
||||
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.dto.settings.AppSettings;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataProviderSettings;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class GoogleParserTest {
|
||||
|
||||
@Mock
|
||||
private AppSettingService appSettingService;
|
||||
|
||||
@Mock
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@Mock
|
||||
private HttpClient httpClient;
|
||||
|
||||
private GoogleParser googleParser;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
googleParser = new GoogleParser(objectMapper, appSettingService);
|
||||
objectMapper = new ObjectMapper();
|
||||
|
||||
// Mock AppSettings chain
|
||||
MetadataProviderSettings.Google googleSettings = new MetadataProviderSettings.Google();
|
||||
googleSettings.setLanguage("en");
|
||||
|
||||
MetadataProviderSettings providerSettings = new MetadataProviderSettings();
|
||||
providerSettings.setGoogle(googleSettings);
|
||||
|
||||
AppSettings appSettings = AppSettings.builder()
|
||||
.metadataProviderSettings(providerSettings)
|
||||
.build();
|
||||
|
||||
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
googleParser = new GoogleParser(objectMapper, appSettingService, httpClient);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCleanDescription_null() {
|
||||
assertNull(googleParser.cleanDescription(null));
|
||||
void testFetchMetadata_IsbnSearch() throws Exception {
|
||||
// Mock ISBN Response (success) - Added author to pass relevance filter
|
||||
mockResponse("{\"totalItems\": 1, \"items\": [{\"volumeInfo\": {\"title\": \"ISBN Found\", \"authors\": [\"Test Author\"]}}]}");
|
||||
|
||||
FetchMetadataRequest request = FetchMetadataRequest.builder()
|
||||
.isbn("1234567890")
|
||||
.build();
|
||||
|
||||
List<BookMetadata> results = googleParser.fetchMetadata(Book.builder().build(), request);
|
||||
|
||||
assertEquals(1, results.size());
|
||||
assertEquals("ISBN Found", results.get(0).getTitle());
|
||||
|
||||
// Verify only 1 call was made (ISBN search)
|
||||
verify(httpClient, times(1)).send(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCleanDescription_empty() {
|
||||
assertNull(googleParser.cleanDescription(""));
|
||||
assertNull(googleParser.cleanDescription(" "));
|
||||
void testFetchMetadata_IsbnFail_FallbackToTitleAuthor() throws Exception {
|
||||
// Mock ISBN Response (empty) then Title+Author Response (success)
|
||||
mockResponseSequence(
|
||||
"{\"totalItems\": 0}",
|
||||
"{\"totalItems\": 1, \"items\": [{\"volumeInfo\": {\"title\": \"TitleAuthor Found\", \"authors\": [\"Test Author\"]}}]}"
|
||||
);
|
||||
|
||||
FetchMetadataRequest request = FetchMetadataRequest.builder()
|
||||
.isbn("1234567890")
|
||||
.title("My Title")
|
||||
.author("My Author")
|
||||
.build();
|
||||
|
||||
List<BookMetadata> results = googleParser.fetchMetadata(Book.builder().build(), request);
|
||||
|
||||
assertEquals(1, results.size());
|
||||
assertEquals("TitleAuthor Found", results.get(0).getTitle());
|
||||
|
||||
// Verify 2 calls
|
||||
ArgumentCaptor<HttpRequest> captor = ArgumentCaptor.forClass(HttpRequest.class);
|
||||
verify(httpClient, times(2)).send(captor.capture(), any());
|
||||
|
||||
List<HttpRequest> requests = captor.getAllValues();
|
||||
String uri = requests.get(1).uri().toString();
|
||||
assertTrue(uri.contains("inauthor") || uri.contains("inauthor%3A"));
|
||||
assertTrue(uri.contains("My") && uri.contains("Author"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCleanDescription_withHtmlTags() {
|
||||
String input = "This is <i>italic</i> and <b>bold</b>. <br> New line.";
|
||||
String expected = "This is italic and bold. New line.";
|
||||
assertEquals(expected, googleParser.cleanDescription(input));
|
||||
void testFetchMetadata_AllFail_FallbackToTitleOnly() throws Exception {
|
||||
// ISBN fail, Title+Author fail, Title success
|
||||
mockResponseSequence(
|
||||
"{\"totalItems\": 0}", // ISBN
|
||||
"{\"totalItems\": 0}", // Title+Author
|
||||
"{\"totalItems\": 1, \"items\": [{\"volumeInfo\": {\"title\": \"Title Only Found\", \"authors\": [\"Test Author\"]}}]}" // Title
|
||||
);
|
||||
|
||||
FetchMetadataRequest request = FetchMetadataRequest.builder()
|
||||
.isbn("1234567890")
|
||||
.title("My Title")
|
||||
.author("My Author")
|
||||
.build();
|
||||
|
||||
List<BookMetadata> results = googleParser.fetchMetadata(Book.builder().build(), request);
|
||||
|
||||
assertEquals(1, results.size());
|
||||
assertEquals("Title Only Found", results.get(0).getTitle());
|
||||
|
||||
// Verify 3 calls
|
||||
verify(httpClient, times(3)).send(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCleanDescription_withEntities() {
|
||||
String input = "Tom & Jerry < Disney > Pixar "Toy Story" 'test'";
|
||||
String expected = "Tom & Jerry < Disney > Pixar \"Toy Story\" 'test'";
|
||||
assertEquals(expected, googleParser.cleanDescription(input));
|
||||
// Helper to mock single response
|
||||
private void mockResponse(String jsonBody) throws IOException, InterruptedException {
|
||||
HttpResponse<String> mockResponse = mock(HttpResponse.class);
|
||||
when(mockResponse.body()).thenReturn(jsonBody);
|
||||
when(mockResponse.statusCode()).thenReturn(200);
|
||||
when(httpClient.send(any(HttpRequest.class), any(HttpResponse.BodyHandler.class)))
|
||||
.thenReturn(mockResponse);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCleanDescription_withNestedTagsAndWhitespace() {
|
||||
String input = """
|
||||
<div> <p>Some text </p>
|
||||
<span>More text</span> </div>""";
|
||||
String expected = "Some text More text";
|
||||
assertEquals(expected, googleParser.cleanDescription(input));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCleanDescription_withUnclosedTags() {
|
||||
String input = "This is <i>italic and <b>bold";
|
||||
String expected = "This is italic and bold";
|
||||
assertEquals(expected, googleParser.cleanDescription(input));
|
||||
// Helper to mock sequence of responses
|
||||
private void mockResponseSequence(String... jsonBodies) throws IOException, InterruptedException {
|
||||
HttpResponse<String>[] responses = new HttpResponse[jsonBodies.length];
|
||||
for (int i = 0; i < jsonBodies.length; i++) {
|
||||
HttpResponse<String> mockInfo = mock(HttpResponse.class);
|
||||
when(mockInfo.body()).thenReturn(jsonBodies[i]);
|
||||
when(mockInfo.statusCode()).thenReturn(200);
|
||||
responses[i] = mockInfo;
|
||||
}
|
||||
|
||||
when(httpClient.send(any(HttpRequest.class), any(HttpResponse.BodyHandler.class)))
|
||||
.thenReturn(responses[0], Arrays.copyOfRange(responses, 1, responses.length));
|
||||
}
|
||||
}
|
||||
|
||||
+32
-2
@@ -4,7 +4,9 @@ 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 com.adityachandel.booklore.service.metadata.parser.hardcover.GraphQLResponse;
|
||||
import com.adityachandel.booklore.service.metadata.parser.hardcover.HardcoverBookDetails;
|
||||
import com.adityachandel.booklore.service.metadata.parser.hardcover.HardcoverBookSearchService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
@@ -15,7 +17,8 @@ import org.mockito.MockitoAnnotations;
|
||||
import java.util.*;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.contains;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
@@ -87,6 +90,33 @@ class HardcoverParserTest {
|
||||
verify(hardcoverBookSearchService).searchBooks("Some Book");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should fall back to title-only search when combined search returns results but they are filtered out")
|
||||
void fetchMetadata_combinedSearchFilteredOut_fallsBackToTitleOnly() {
|
||||
Book book = Book.builder().title("Portrait of a Thief").build();
|
||||
FetchMetadataRequest request = FetchMetadataRequest.builder()
|
||||
.title("Portrait of a Thief")
|
||||
.author("Grace D. Li")
|
||||
.build();
|
||||
|
||||
// Simulate combined search returning a result that DOES NOT match the author (e.g. some other book matched the string)
|
||||
GraphQLResponse.Hit badHit = createHitWithAuthor("Portrait of something", "Random Person");
|
||||
when(hardcoverBookSearchService.searchBooks("Portrait of a Thief Grace D. Li"))
|
||||
.thenReturn(List.of(badHit)); // Returns a hit, but fuzzy score will fail or simple check will fail
|
||||
|
||||
// Fallback search should match
|
||||
GraphQLResponse.Hit goodHit = createHitWithAuthor("Portrait of a Thief", "Grace D. Li");
|
||||
when(hardcoverBookSearchService.searchBooks("Portrait of a Thief"))
|
||||
.thenReturn(List.of(goodHit));
|
||||
|
||||
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
||||
|
||||
verify(hardcoverBookSearchService).searchBooks("Portrait of a Thief Grace D. Li");
|
||||
verify(hardcoverBookSearchService).searchBooks("Portrait of a Thief");
|
||||
assertThat(results).hasSize(1);
|
||||
assertThat(results.get(0).getTitle()).isEqualTo("Portrait of a Thief");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should search by ISBN when provided")
|
||||
void fetchMetadata_isbnProvided_searchesByIsbn() {
|
||||
|
||||
Reference in New Issue
Block a user