fix(goodreads): use autocomplete endpoint for metadata provider (#1456)

This commit is contained in:
James Ward
2026-05-25 06:37:09 -04:00
committed by GitHub
parent 7da24d1508
commit 673f00864d
4 changed files with 448 additions and 153 deletions
@@ -0,0 +1,217 @@
package org.booklore.service.metadata.parser;
import org.booklore.model.dto.Book;
import org.booklore.model.dto.BookMetadata;
import org.booklore.model.dto.request.FetchMetadataRequest;
import org.booklore.model.dto.settings.AppSettings;
import org.booklore.model.dto.settings.MetadataProviderSettings;
import org.booklore.model.dto.settings.MetadataPublicReviewsSettings;
import org.booklore.model.enums.MetadataProvider;
import org.booklore.service.appsettings.AppSettingService;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.io.InputStream;
import java.net.http.HttpClient;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.List;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
public class GoodReadsParserTest {
@Mock
private AppSettingService appSettingService;
@Mock
private HttpClient httpClient;
private MockedStatic<Jsoup> mockJsoup;
@InjectMocks
private GoodReadsParser parser;
private String exampleSearchJsonFixture;
private String exampleBookHtmlFixture;
@BeforeEach
void setUp() throws IOException {
exampleSearchJsonFixture = readFixture("example-search.json");
exampleBookHtmlFixture = readFixture("example-book.html");
mockJsoup = mockStatic(Jsoup.class);
}
@AfterEach
void tearDown() {
mockJsoup.close();
}
private void mockSettings(boolean enabled) {
AppSettings appSettings = new AppSettings();
MetadataProviderSettings providerSettings = new MetadataProviderSettings();
MetadataProviderSettings.Goodreads goodreads = new MetadataProviderSettings.Goodreads();
goodreads.setEnabled(enabled);
providerSettings.setGoodReads(goodreads);
appSettings.setMetadataProviderSettings(providerSettings);
MetadataPublicReviewsSettings.ReviewProviderConfig provider = MetadataPublicReviewsSettings.ReviewProviderConfig.builder()
.provider(MetadataProvider.GoodReads)
.enabled(enabled)
.build();
MetadataPublicReviewsSettings reviewSettings = MetadataPublicReviewsSettings.builder()
.providers(Set.of(provider))
.build();
appSettings.setMetadataPublicReviewsSettings(reviewSettings);
when(appSettingService.getAppSettings()).thenReturn(appSettings);
}
private String readFixture(String fixtureName) throws IOException {
String filename = Paths.get("goodreads", fixtureName + ".fixture").toString();
try (InputStream is = getClass().getClassLoader().getResourceAsStream(filename)) {
assert is != null;
return new String(is.readAllBytes(), StandardCharsets.UTF_8);
}
}
@SuppressWarnings("unchecked")
private HttpResponse<String> getMockResponse(int statusCode, String response) {
HttpResponse<String> httpResponse = (HttpResponse<String>) mock(HttpResponse.class);
when(httpResponse.statusCode()).thenReturn(statusCode);
if (response != null) {
when(httpResponse.body()).thenReturn(response);
}
return httpResponse;
}
private void mockHttpClientResponse(String urlPrefix, int statusCode, String response) throws Exception {
when(
httpClient.<String>send(
argThat(r -> r.uri().toString().startsWith(urlPrefix)),
any()
)
).thenAnswer((_) -> getMockResponse(statusCode, response));
}
private void mockJsoupResponse(String urlPrefix, String response) throws Exception {
Connection mockConnection = mock(Connection.class);
when(mockConnection.header(anyString(), anyString())).thenReturn(mockConnection);
when(mockConnection.method(any())).thenReturn(mockConnection);
// There may be a better way to get the parse to work here.
// However, this was the quickest and simplest way I could find.
mockJsoup.when(() -> Jsoup.parse(response)).thenCallRealMethod();
when(mockConnection.get()).thenAnswer(i -> Jsoup.parse(response));
mockJsoup.when(() -> Jsoup.connect(startsWith(urlPrefix))).thenReturn(mockConnection);
}
@Test
void testFetchMetadata_EmptyQuery() {
// Given
Book book = Book.builder()
.title("Test Book")
.build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.build();
// Empty query - no title or ISBN
// When
List<BookMetadata> results = parser.fetchMetadata(book, request);
// Then
assertThat(results).isNotNull();
assertThat(results).as("Should return empty list when query is empty").isEmpty();
}
@Test
void testFetchMetadata_parsesBook() throws Exception {
// Given
Book book = Book.builder()
.title("A Clockwork Orange")
.build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("A Clockwork Orange")
.author("Anthony Burgess")
.build();
// Mock enabled provider
mockSettings(true);
// Two expected URLs
mockHttpClientResponse("https://www.goodreads.com/book/auto_complete", 200, exampleSearchJsonFixture);
mockJsoupResponse("https://www.goodreads.com/book/show/", exampleBookHtmlFixture);
// When
List<BookMetadata> results = parser.fetchMetadata(book, request);
// Then
assertThat(results).isNotNull();
assertThat(results).as("Should return results for real book").isNotEmpty();
BookMetadata result = results.getFirst();
assertThat(result.getTitle()).isEqualTo("A Clockwork Orange");
assertThat(result.getIsbn10()).isEqualTo("0393341763");
assertThat(result.getIsbn13()).isEqualTo("9780393341768");
assertThat(result.getGoodreadsId()).isEqualTo("41817486");
assertThat(result.getAuthors()).isNotNull();
assertThat(result.getAuthors()).hasSize(1);
assertThat(result.getAuthors().getFirst()).isEqualTo("Anthony Burgess");
// The description is very long, but we need to make sure we're in the right ballpark.
assertThat(result.getDescription()).startsWith("In Anthony Burgess's influential");
assertThat(result.getDescription()).hasSize(511);
}
@Test
void testFetchMetadata_withRateLimitingError() throws Exception {
// Given
Book book = Book.builder()
.title("A Clockwork Orange")
.build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("A Clockwork Orange")
.author("Anthony Burgess")
.build();
// Two expected URLs
mockHttpClientResponse("https://www.goodreads.com/book/auto_complete", 429, null);
// When
List<BookMetadata> results = parser.fetchMetadata(book, request);
// Then
assertThat(results).isNotNull();
assertThat(results).as("Should not return results").isEmpty();
}
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,142 @@
[
{
"imageUrl":"https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1549260060i/41817486._SX50_.jpg",
"bookId":"41817486",
"workId":"23596",
"bookUrl":"/book/show/41817486-a-clockwork-orange",
"from_search":true,
"from_srp":true,
"qid":"Gdu5vdYSS1",
"rank":1,
"title":"A Clockwork Orange",
"bookTitleBare":"A Clockwork Orange",
"numPages":240,
"avgRating":"4.00",
"ratingsCount":782433,
"author":{
"id":5735,
"name":"Anthony Burgess",
"isGoodreadsAuthor":false,
"profileUrl":"https://www.goodreads.com/author/show/5735.Anthony_Burgess",
"worksListUrl":"https://www.goodreads.com/author/list/5735.Anthony_Burgess"
},
"kcrPreviewUrl":"https://read.amazon.com/kp/embed?asin=B005HSGB6W\u0026ref=x_gr_w_preview_new_nf_story-20\u0026tag=x_gr_w_preview_new_nf_story-20\u0026preview=inline",
"description":{
"html":"In Anthony Burgess\u0026apos;s influential nightmare vision of the future, criminals take over after dark. Teen gang leader Alex narrates in fantastically inventive slang that echoes th…",
"truncated":true,
"fullContentUrl":"https://www.goodreads.com/book/show/41817486-a-clockwork-orange"
}
},
{
"imageUrl":"https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1388286789i/8809._SY75_.jpg",
"bookId":"8809",
"workId":"1416684",
"bookUrl":"/book/show/8809.The_Wanting_Seed",
"from_search":true,
"from_srp":true,
"qid":"Gdu5vdYSS1",
"rank":2,
"title":"The Wanting Seed",
"bookTitleBare":"The Wanting Seed",
"numPages":288,
"avgRating":"3.72",
"ratingsCount":6995,
"author":{
"id":5735,
"name":"Anthony Burgess",
"isGoodreadsAuthor":false,
"profileUrl":"https://www.goodreads.com/author/show/5735.Anthony_Burgess",
"worksListUrl":"https://www.goodreads.com/author/list/5735.Anthony_Burgess"
},
"kcrPreviewUrl":null,
"description":{
"html":"Set in the near future, The Wanting Seed is a Malthusian comedy about the strange world overpopulation will produce. Tristram Foxe and his wife, Beatrice-Joanna, live in the…",
"truncated":true,
"fullContentUrl":"https://www.goodreads.com/book/show/8809.The_Wanting_Seed"
}
},
{
"imageUrl":"https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1171476306i/101118._SY75_.jpg",
"bookId":"101118",
"workId":"97495",
"bookUrl":"/book/show/101118.Byrne",
"from_search":true,
"from_srp":true,
"qid":"Gdu5vdYSS1",
"rank":3,
"title":"Byrne (Burgess, Anthony)",
"bookTitleBare":"Byrne",
"numPages":160,
"avgRating":"3.40",
"ratingsCount":181,
"author":{
"id":5735,
"name":"Anthony Burgess",
"isGoodreadsAuthor":false,
"profileUrl":"https://www.goodreads.com/author/show/5735.Anthony_Burgess",
"worksListUrl":"https://www.goodreads.com/author/list/5735.Anthony_Burgess"
},
"kcrPreviewUrl":null,
"description":{
"html":"The first American publication of the late writer\u0026apos;s comic-satiric epic novel in verse tells the story of a Don Juan-type Irish artist who vanishes under Hitler\u0026apos;s regime. By th…",
"truncated":true,
"fullContentUrl":"https://www.goodreads.com/book/show/101118.Byrne"
}
},
{
"imageUrl":"https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1355598044i/8822._SY75_.jpg",
"bookId":"8822",
"workId":"1282899",
"bookUrl":"/book/show/8822.Earthly_Powers",
"from_search":true,
"from_srp":true,
"qid":"Gdu5vdYSS1",
"rank":4,
"title":"Earthly Powers",
"bookTitleBare":"Earthly Powers",
"numPages":649,
"avgRating":"4.13",
"ratingsCount":3449,
"author":{
"id":5735,
"name":"Anthony Burgess",
"isGoodreadsAuthor":false,
"profileUrl":"https://www.goodreads.com/author/show/5735.Anthony_Burgess",
"worksListUrl":"https://www.goodreads.com/author/list/5735.Anthony_Burgess"
},
"kcrPreviewUrl":"https://read.amazon.com/kp/embed?asin=B08Q61J6ZH\u0026ref=x_gr_w_preview_new_nf_story-20\u0026tag=x_gr_w_preview_new_nf_story-20\u0026preview=inline",
"description":{
"html":"Anthony Burgess, author of \u003ci\u003eA Clockwork Orange,\u003c/i\u003e is regarded as one of the most original and daring writers in the English language. His work is illuminated by a dazzling imagin…",
"truncated":true,
"fullContentUrl":"https://www.goodreads.com/book/show/8822.Earthly_Powers"
}
},
{
"imageUrl":"https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1347654176i/2418008._SY75_.jpg",
"bookId":"2418008",
"workId":"2425185",
"bookUrl":"/book/show/2418008.Anthony_Burgess",
"from_search":true,
"from_srp":true,
"qid":"Gdu5vdYSS1",
"rank":5,
"title":"Anthony Burgess",
"bookTitleBare":"Anthony Burgess",
"numPages":400,
"avgRating":"2.68",
"ratingsCount":81,
"author":{
"id":15095,
"name":"Roger Lewis",
"isGoodreadsAuthor":false,
"profileUrl":"https://www.goodreads.com/author/show/15095.Roger_Lewis",
"worksListUrl":"https://www.goodreads.com/author/list/15095.Roger_Lewis"
},
"kcrPreviewUrl":"https://read.amazon.com/kp/embed?asin=B00HFTZWGG\u0026ref=x_gr_w_preview_new_nf_story-20\u0026tag=x_gr_w_preview_new_nf_story-20\u0026preview=inline",
"description":{
"html":"This biography is the culmination and distillation of 20 years\u0026apos; work on Anthony Burgess (1917-1993), the author who remains best known for \u0026quot;A Clockwork Orange\u0026quot;, the source for…",
"truncated":true,
"fullContentUrl":"https://www.goodreads.com/book/show/2418008.Anthony_Burgess"
}
}
]