refactor(books): paginate /api/v1/books/page with cursor, sort, facet, search (#1853)
Co-authored-by: James Ward <james@notjam.es>
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
package org.booklore.browse;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class BrowsePageTest {
|
||||
|
||||
@Test
|
||||
void derivesPageNumberFromOffsetAndLimit() {
|
||||
BrowsePage<String> page = BrowsePage.of(List.of("a"), 80, 20, 100, "cur", List.of());
|
||||
assertThat(page.page().number()).isEqualTo(4);
|
||||
assertThat(page.page().size()).isEqualTo(20);
|
||||
}
|
||||
|
||||
@Test
|
||||
void derivesTotalPagesWithCeiling() {
|
||||
// 101 elements, size 20 -> 6 pages
|
||||
BrowsePage<String> page = BrowsePage.of(List.of(), 0, 20, 101, "cur", List.of());
|
||||
assertThat(page.page().totalPages()).isEqualTo(6);
|
||||
}
|
||||
|
||||
@Test
|
||||
void exactMultipleTotalPages() {
|
||||
BrowsePage<String> page = BrowsePage.of(List.of(), 0, 20, 100, "cur", List.of());
|
||||
assertThat(page.page().totalPages()).isEqualTo(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstPageNumberIsZero() {
|
||||
BrowsePage<String> page = BrowsePage.of(List.of(), 0, 20, 100, "cur", List.of());
|
||||
assertThat(page.page().number()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyResultHasZeroPages() {
|
||||
BrowsePage<String> page = BrowsePage.of(List.of(), 0, 20, 0, "cur", List.of());
|
||||
assertThat(page.page().totalPages()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void zeroLimitDoesNotDivideByZero() {
|
||||
BrowsePage<String> page = BrowsePage.of(List.of(), 0, 0, 50, "cur", List.of());
|
||||
assertThat(page.page().number()).isZero();
|
||||
assertThat(page.page().totalPages()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void carriesCursorAndTotals() {
|
||||
BrowsePage<String> page = BrowsePage.of(List.of("a", "b"), 0, 20, 42, "the-cursor", List.of());
|
||||
assertThat(page.page().cursor()).isEqualTo("the-cursor");
|
||||
assertThat(page.page().totalElements()).isEqualTo(42);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package org.booklore.browse;
|
||||
|
||||
import org.booklore.exception.APIException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class CursorCodecTest {
|
||||
|
||||
private final CursorCodec codec = new CursorCodec();
|
||||
|
||||
@Test
|
||||
void roundTripsBasicState() {
|
||||
CursorState state = new CursorState(80, 40, "seriesName,-seriesNumber", "abc123def456");
|
||||
CursorState decoded = codec.decode(codec.encode(state));
|
||||
assertEquals(state, decoded);
|
||||
}
|
||||
|
||||
@Test
|
||||
void producesUrlSafeUnpaddedToken() {
|
||||
CursorState state = new CursorState(12345, 40, "title", "hash00000000");
|
||||
String cursor = codec.encode(state);
|
||||
assertEquals(cursor.indexOf('+'), -1);
|
||||
assertEquals(cursor.indexOf('/'), -1);
|
||||
assertEquals(cursor.indexOf('='), -1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankCursorIsRejected() {
|
||||
assertThrows(APIException.class, () -> codec.decode(null));
|
||||
assertThrows(APIException.class, () -> codec.decode(" "));
|
||||
}
|
||||
|
||||
@Test
|
||||
void garbageCursorIsRejected() {
|
||||
assertThrows(APIException.class, () -> codec.decode("not-a-cursor!!"));
|
||||
assertThrows(APIException.class, () -> codec.decode("YWJjZGVm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void verifyParamsMatchPassesOnEqualHash() {
|
||||
CursorState state = new CursorState(0, 20, "title", "samehash0000");
|
||||
assertDoesNotThrow(() -> codec.verifyParamsMatch(state, "samehash0000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void verifyParamsMatchThrowsOnDifferentHash() {
|
||||
CursorState state = new CursorState(0, 20, "title", "samehash0000");
|
||||
assertThrows(APIException.class, () -> codec.verifyParamsMatch(state, "otherhash000"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package org.booklore.browse;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class FacetLogicTest {
|
||||
|
||||
@Test
|
||||
void defaultsToAndForNullOrBlank() {
|
||||
assertEquals(FacetLogic.AND, FacetLogic.from(null));
|
||||
assertEquals(FacetLogic.AND, FacetLogic.from(""));
|
||||
assertEquals(FacetLogic.AND, FacetLogic.from(" "));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parsesKnownValuesCaseInsensitively() {
|
||||
assertEquals(FacetLogic.OR, FacetLogic.from("or"));
|
||||
assertEquals(FacetLogic.OR, FacetLogic.from("OR"));
|
||||
assertEquals(FacetLogic.NOT, FacetLogic.from("Not"));
|
||||
assertEquals(FacetLogic.AND, FacetLogic.from("and"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownValueFallsBackToAnd() {
|
||||
assertEquals(FacetLogic.AND, FacetLogic.from("xor"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package org.booklore.browse;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class LinksBuilderTest {
|
||||
|
||||
private final CursorCodec codec = new CursorCodec();
|
||||
private final LinksBuilder builder = new LinksBuilder(codec);
|
||||
|
||||
private LinksBuilder.Context context(long offset, int limit, long total, String preservedQuery) {
|
||||
CursorState base = new CursorState(offset, limit, "title", "hash00000000");
|
||||
return new LinksBuilder.Context("/api/v1/books/page", preservedQuery, offset, limit, total, base);
|
||||
}
|
||||
|
||||
private boolean hasRel(List<Link> links, String rel) {
|
||||
return links.stream().anyMatch(l -> l.rel().contains(rel));
|
||||
}
|
||||
|
||||
private Link withRel(List<Link> links, String rel) {
|
||||
Optional<Link> found = links.stream().filter(l -> l.rel().contains(rel)).findFirst();
|
||||
assertTrue(found.isPresent(), "expected a link with rel " + rel);
|
||||
return found.get();
|
||||
}
|
||||
|
||||
@Test
|
||||
void selfAndFirstAlwaysPresent() {
|
||||
List<Link> links = builder.build(context(40, 20, 100, ""));
|
||||
assertTrue(hasRel(links, "self"));
|
||||
assertTrue(hasRel(links, "first"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstPageOmitsPreviousButHasNext() {
|
||||
List<Link> links = builder.build(context(0, 20, 100, ""));
|
||||
assertFalse(hasRel(links, "previous"));
|
||||
assertTrue(hasRel(links, "next"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void middlePageHasPreviousAndNext() {
|
||||
List<Link> links = builder.build(context(40, 20, 100, ""));
|
||||
assertTrue(hasRel(links, "previous"));
|
||||
assertTrue(hasRel(links, "next"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lastPageOmitsNext() {
|
||||
List<Link> links = builder.build(context(80, 20, 100, ""));
|
||||
assertTrue(hasRel(links, "previous"));
|
||||
assertFalse(hasRel(links, "next"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void singlePageOmitsBothPreviousAndNext() {
|
||||
List<Link> links = builder.build(context(0, 20, 12, ""));
|
||||
assertFalse(hasRel(links, "previous"));
|
||||
assertFalse(hasRel(links, "next"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyResultHasNoPreviousOrNext() {
|
||||
List<Link> links = builder.build(context(0, 20, 0, ""));
|
||||
assertFalse(hasRel(links, "previous"));
|
||||
assertFalse(hasRel(links, "next"));
|
||||
assertTrue(hasRel(links, "self"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pagingLinksCarryPreservedQueryAndCursor() {
|
||||
Link next = withRel(builder.build(context(0, 20, 100, "facet=genre%3AFiction")), "next");
|
||||
assertTrue(next.href().startsWith("/api/v1/books/page?facet=genre%3AFiction&cursor="));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nextCursorAdvancesByLimit() {
|
||||
Link next = withRel(builder.build(context(0, 20, 100, "")), "next");
|
||||
String cursor = next.href().substring(next.href().indexOf("cursor=") + "cursor=".length());
|
||||
assertEquals(20, codec.decode(cursor).offset());
|
||||
}
|
||||
|
||||
@Test
|
||||
void previousCursorClampsAtZero() {
|
||||
// offset 10, limit 20 -> previous offset clamps to 0
|
||||
Link prev = withRel(builder.build(context(10, 20, 100, "")), "previous");
|
||||
String cursor = prev.href().substring(prev.href().indexOf("cursor=") + "cursor=".length());
|
||||
assertEquals(0, codec.decode(cursor).offset());
|
||||
}
|
||||
|
||||
@Test
|
||||
void selfCursorReflectsCurrentOffset() {
|
||||
Link self = withRel(builder.build(context(40, 20, 100, "")), "self");
|
||||
String cursor = self.href().substring(self.href().indexOf("cursor=") + "cursor=".length());
|
||||
assertEquals(40, codec.decode(cursor).offset());
|
||||
}
|
||||
|
||||
@Test
|
||||
void preservedQueryAbsentWhenBlank() {
|
||||
Predicate<Link> isPageLink = l -> l.href().startsWith("/api/v1/books/page");
|
||||
builder.build(context(0, 20, 100, "")).stream().filter(isPageLink)
|
||||
.forEach(l -> assertTrue(l.href().startsWith("/api/v1/books/page?cursor=")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullPreservedQueryStillProducesValidLinks() {
|
||||
List<Link> links = builder.build(new LinksBuilder.Context(
|
||||
"/api/v1/books/page", null, 0, 20, 5,
|
||||
new CursorState(0, 20, "title", "hash00000000")));
|
||||
assertTrue(hasRel(links, "self"));
|
||||
Link self = withRel(links, "self");
|
||||
assertTrue(self.href().startsWith("/api/v1/books/page?cursor="));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package org.booklore.browse;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class ParamsHashTest {
|
||||
|
||||
@Test
|
||||
void isTwelveCharacters() {
|
||||
assertThat(ParamsHash.compute("q", Map.of(), FacetLogic.AND)).hasSize(12);
|
||||
}
|
||||
|
||||
@Test
|
||||
void isDeterministic() {
|
||||
Map<String, List<String>> facets = Map.of("author", List.of("Tolkien"));
|
||||
assertThat(ParamsHash.compute("hobbit", facets, FacetLogic.AND))
|
||||
.isEqualTo(ParamsHash.compute("hobbit", facets, FacetLogic.AND));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isIndependentOfFacetKeyOrder() {
|
||||
String a = ParamsHash.compute(null, Map.of("author", List.of("A"), "genre", List.of("G")), FacetLogic.AND);
|
||||
String b = ParamsHash.compute(null, Map.of("genre", List.of("G"), "author", List.of("A")), FacetLogic.AND);
|
||||
assertThat(a).isEqualTo(b);
|
||||
}
|
||||
|
||||
@Test
|
||||
void isIndependentOfValueOrderWithinAFacet() {
|
||||
String a = ParamsHash.compute(null, Map.of("author", List.of("A", "B")), FacetLogic.AND);
|
||||
String b = ParamsHash.compute(null, Map.of("author", List.of("B", "A")), FacetLogic.AND);
|
||||
assertThat(a).isEqualTo(b);
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryChangesHash() {
|
||||
assertThat(ParamsHash.compute("one", Map.of(), FacetLogic.AND))
|
||||
.isNotEqualTo(ParamsHash.compute("two", Map.of(), FacetLogic.AND));
|
||||
}
|
||||
|
||||
@Test
|
||||
void facetLogicChangesHash() {
|
||||
Map<String, List<String>> facets = Map.of("author", List.of("A"));
|
||||
assertThat(ParamsHash.compute(null, facets, FacetLogic.AND))
|
||||
.isNotEqualTo(ParamsHash.compute(null, facets, FacetLogic.OR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void facetSelectionChangesHash() {
|
||||
assertThat(ParamsHash.compute(null, Map.of("author", List.of("A")), FacetLogic.AND))
|
||||
.isNotEqualTo(ParamsHash.compute(null, Map.of("author", List.of("B")), FacetLogic.AND));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullQueryAndEmptyFacetsAreStable() {
|
||||
assertThat(ParamsHash.compute(null, Map.of(), FacetLogic.AND))
|
||||
.isEqualTo(ParamsHash.compute(null, Map.of(), FacetLogic.AND));
|
||||
}
|
||||
|
||||
@Test
|
||||
void valuesWithDelimitersDoNotCollide() {
|
||||
assertThat(ParamsHash.compute(null, Map.of("author", List.of("A,B")), FacetLogic.AND))
|
||||
.isNotEqualTo(ParamsHash.compute(null, Map.of("author", List.of("A", "B")), FacetLogic.AND));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package org.booklore.browse;
|
||||
|
||||
import org.booklore.exception.APIException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
class SortParserTest {
|
||||
|
||||
private static final Set<String> KEYS = Set.of("id", "title", "seriesName", "seriesNumber");
|
||||
|
||||
@Test
|
||||
void blankSortYieldsTiebreakerOnly() {
|
||||
assertThat(SortParser.parse(null, KEYS)).containsExactly(new SortTerm("id", false));
|
||||
assertThat(SortParser.parse(" ", KEYS)).containsExactly(new SortTerm("id", false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parsesSingleAscendingKeyAndAppendsTiebreaker() {
|
||||
assertThat(SortParser.parse("title", KEYS))
|
||||
.containsExactly(new SortTerm("title", false), new SortTerm("id", false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dashPrefixMarksDescending() {
|
||||
assertThat(SortParser.parse("-title", KEYS))
|
||||
.containsExactly(new SortTerm("title", true), new SortTerm("id", false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parsesMultipleTermsInOrder() {
|
||||
assertThat(SortParser.parse("seriesName,-seriesNumber", KEYS))
|
||||
.containsExactly(new SortTerm("seriesName", false), new SortTerm("seriesNumber", true), new SortTerm("id", false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void trimsWhitespaceAroundTokens() {
|
||||
assertThat(SortParser.parse(" title , -seriesNumber ", KEYS))
|
||||
.containsExactly(new SortTerm("title", false), new SortTerm("seriesNumber", true), new SortTerm("id", false));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", "title", "-title", "seriesName,-seriesNumber"})
|
||||
void alwaysEndsWithIdAscendingTiebreaker(String sort) {
|
||||
List<SortTerm> terms = SortParser.parse(sort.isEmpty() ? null : sort, KEYS);
|
||||
assertThat(terms).endsWith(new SortTerm("id", false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void idIsRejectedLikeAnUnknownSortKey() {
|
||||
assertThatThrownBy(() -> SortParser.parse("id", KEYS)).isInstanceOf(APIException.class);
|
||||
assertThatThrownBy(() -> SortParser.parse("-id", KEYS)).isInstanceOf(APIException.class);
|
||||
assertThatThrownBy(() -> SortParser.parse("id,title", KEYS)).isInstanceOf(APIException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownKeyIsRejected() {
|
||||
assertThatThrownBy(() -> SortParser.parse("bogus", KEYS)).isInstanceOf(APIException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyTokenIsRejected() {
|
||||
assertThatThrownBy(() -> SortParser.parse("title,,id", KEYS)).isInstanceOf(APIException.class);
|
||||
assertThatThrownBy(() -> SortParser.parse("-", KEYS)).isInstanceOf(APIException.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package org.booklore.browse;
|
||||
|
||||
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||
import jakarta.persistence.criteria.CriteriaQuery;
|
||||
import jakarta.persistence.criteria.Order;
|
||||
import jakarta.persistence.criteria.Root;
|
||||
import org.booklore.exception.APIException;
|
||||
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.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class SortRegistryTest {
|
||||
|
||||
@Mock
|
||||
private Root<Object> root;
|
||||
@Mock
|
||||
private CriteriaQuery<?> query;
|
||||
@Mock
|
||||
private CriteriaBuilder cb;
|
||||
|
||||
@Test
|
||||
void registersAndExposesKeysInOrder() {
|
||||
SortRegistry<Object> registry = new SortRegistry<>()
|
||||
.register("id", ascOn("id"))
|
||||
.register("title", ascOn("title"));
|
||||
assertTrue(registry.has("id"));
|
||||
assertTrue(registry.has("title"));
|
||||
assertEquals(List.of("id", "title"), List.copyOf(registry.keys()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dispatchesEachTermToItsBuilderInOrder() {
|
||||
Order idOrder = mock(Order.class);
|
||||
Order titleOrder = mock(Order.class);
|
||||
SortRegistry<Object> registry = new SortRegistry<>()
|
||||
.register("title", ctx -> List.of(titleOrder))
|
||||
.register("id", ctx -> List.of(idOrder));
|
||||
|
||||
List<Order> orders = registry.toOrders(
|
||||
List.of(new SortTerm("title", false), new SortTerm("id", false)), root, query, cb, 7L);
|
||||
|
||||
assertEquals(List.of(titleOrder, idOrder), orders);
|
||||
}
|
||||
|
||||
@Test
|
||||
void passesDirectionAndUserIdToBuilder() {
|
||||
boolean[] sawDescending = {false};
|
||||
Long[] sawUser = {null};
|
||||
SortRegistry<Object> registry = new SortRegistry<>().register("title", ctx -> {
|
||||
sawDescending[0] = ctx.descending();
|
||||
sawUser[0] = ctx.userId();
|
||||
return List.of(mock(Order.class));
|
||||
});
|
||||
|
||||
registry.toOrders(List.of(new SortTerm("title", true)), root, query, cb, 42L);
|
||||
|
||||
assertTrue(sawDescending[0]);
|
||||
assertEquals(42L, sawUser[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownKeyThrows() {
|
||||
SortRegistry<Object> registry = new SortRegistry<>().register("id", ascOn("id"));
|
||||
assertThrows(APIException.class,
|
||||
() -> registry.toOrders(List.of(new SortTerm("bogus", false)), root, query, cb, null));
|
||||
}
|
||||
|
||||
private SortOrderBuilder<Object> ascOn(String attribute) {
|
||||
return ctx -> List.of(mock(Order.class));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package org.booklore.service.browse;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.PersistenceContext;
|
||||
import org.booklore.BookloreApplication;
|
||||
import org.booklore.browse.FacetLogic;
|
||||
import org.booklore.browse.SortParser;
|
||||
import org.booklore.browse.SortTerm;
|
||||
import org.booklore.model.entity.AuthorEntity;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.model.entity.BookMetadataEntity;
|
||||
import org.booklore.model.entity.CategoryEntity;
|
||||
import org.booklore.model.entity.LibraryEntity;
|
||||
import org.booklore.model.entity.LibraryPathEntity;
|
||||
import org.booklore.model.entity.UserBookProgressEntity;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.model.enums.ReadStatus;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.service.task.TaskCronService;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.TestConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@SpringBootTest(classes = BookloreApplication.class)
|
||||
@Transactional
|
||||
@TestPropertySource(properties = {
|
||||
"spring.flyway.enabled=false",
|
||||
"spring.jpa.hibernate.ddl-auto=create-drop",
|
||||
"spring.jpa.database-platform=org.hibernate.dialect.H2Dialect",
|
||||
"spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect",
|
||||
"spring.datasource.url=jdbc:h2:mem:browsetest;DB_CLOSE_DELAY=-1;NON_KEYWORDS=VALUE",
|
||||
"spring.datasource.driver-class-name=org.h2.Driver",
|
||||
"spring.datasource.username=sa",
|
||||
"spring.datasource.password=",
|
||||
"app.path-config=build/tmp/test-config",
|
||||
"app.bookdrop-folder=build/tmp/test-bookdrop",
|
||||
"spring.main.allow-bean-definition-overriding=true",
|
||||
"spring.task.scheduling.enabled=false",
|
||||
"app.task.scan-library-cron=*/1 * * * * *",
|
||||
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
||||
"app.features.oidc-enabled=false"
|
||||
})
|
||||
@Import(BookBrowseRegistryTest.TestConfig.class)
|
||||
class BookBrowseRegistryTest {
|
||||
|
||||
@Autowired
|
||||
private BookRepository bookRepository;
|
||||
@Autowired
|
||||
private BookSortRegistry sortRegistry;
|
||||
@Autowired
|
||||
private BookFacetRegistry facetRegistry;
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager em;
|
||||
|
||||
private BookLoreUserEntity user;
|
||||
private LibraryEntity library;
|
||||
private LibraryPathEntity libraryPath;
|
||||
private final Map<String, CategoryEntity> categories = new HashMap<>();
|
||||
private final Map<String, AuthorEntity> authors = new HashMap<>();
|
||||
|
||||
@TestConfiguration
|
||||
public static class TestConfig {
|
||||
@Bean("flyway")
|
||||
@Primary
|
||||
public Flyway flyway() {
|
||||
return org.mockito.Mockito.mock(Flyway.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public TaskCronService taskCronService() {
|
||||
return org.mockito.Mockito.mock(TaskCronService.class);
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void seed() {
|
||||
user = BookLoreUserEntity.builder().username("reader").passwordHash("x").name("Reader").build();
|
||||
em.persist(user);
|
||||
library = LibraryEntity.builder().name("Lib").icon("book").watch(false)
|
||||
.formatPriority(List.of(BookFileType.EPUB)).build();
|
||||
em.persist(library);
|
||||
libraryPath = LibraryPathEntity.builder().library(library).path("/p").build();
|
||||
em.persist(libraryPath);
|
||||
}
|
||||
|
||||
private BookEntity book(String title) {
|
||||
return book(title, null, null, Instant.now(), List.of(), List.of(), null);
|
||||
}
|
||||
|
||||
private BookEntity book(String title, String seriesName, Float seriesNumber, Instant addedOn,
|
||||
List<String> categoryNames, List<String> authorNames, String isbn13) {
|
||||
BookEntity bookEntity = BookEntity.builder()
|
||||
.library(library).libraryPath(libraryPath).addedOn(addedOn).deleted(false).build();
|
||||
em.persist(bookEntity);
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||
.book(bookEntity).title(title).seriesName(seriesName).seriesNumber(seriesNumber)
|
||||
.isbn13(isbn13).publishedDate(LocalDate.of(2020, 1, 1)).build();
|
||||
metadata.setCategories(categoryNames.stream().map(this::category).collect(Collectors.toSet()));
|
||||
metadata.setAuthors(authorNames.stream().map(this::author).toList());
|
||||
em.persist(metadata);
|
||||
bookEntity.setMetadata(metadata);
|
||||
return bookEntity;
|
||||
}
|
||||
|
||||
private void progress(BookEntity book, BookLoreUserEntity forUser, Integer personalRating,
|
||||
ReadStatus status, Float epubPercent, Float pdfPercent) {
|
||||
UserBookProgressEntity p = UserBookProgressEntity.builder()
|
||||
.user(forUser).book(book).personalRating(personalRating).readStatus(status)
|
||||
.epubProgressPercent(epubPercent).pdfProgressPercent(pdfPercent)
|
||||
.lastReadTime(Instant.now()).build();
|
||||
em.persist(p);
|
||||
}
|
||||
|
||||
private CategoryEntity category(String name) {
|
||||
return categories.computeIfAbsent(name, n -> {
|
||||
CategoryEntity e = CategoryEntity.builder().name(n).build();
|
||||
em.persist(e);
|
||||
return e;
|
||||
});
|
||||
}
|
||||
|
||||
private AuthorEntity author(String name) {
|
||||
return authors.computeIfAbsent(name, n -> {
|
||||
AuthorEntity e = AuthorEntity.builder().name(n).build();
|
||||
em.persist(e);
|
||||
return e;
|
||||
});
|
||||
}
|
||||
|
||||
private List<Long> sortedIds(String sortString, Long userId) {
|
||||
List<SortTerm> terms = SortParser.parse(sortString, sortRegistry.registry().keys());
|
||||
Specification<BookEntity> spec = (root, query, cb) -> {
|
||||
query.orderBy(sortRegistry.registry().toOrders(terms, root, query, cb, userId));
|
||||
return cb.conjunction();
|
||||
};
|
||||
return bookRepository.findAll(spec).stream().map(BookEntity::getId).toList();
|
||||
}
|
||||
|
||||
private Set<Long> facetIds(String facet, List<String> values, FacetLogic logic, Long userId) {
|
||||
return bookRepository.findAll(facetRegistry.toSpecification(facet, values, logic, userId)).stream()
|
||||
.map(BookEntity::getId).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
// ---- sorts ----
|
||||
|
||||
@Test
|
||||
void titleAscendingAndDescending() {
|
||||
Long a = book("Alpha").getId();
|
||||
Long b = book("Bravo").getId();
|
||||
Long c = book("Charlie").getId();
|
||||
em.flush();
|
||||
assertThat(sortedIds("title", user.getId())).containsExactly(a, b, c);
|
||||
assertThat(sortedIds("-title", user.getId())).containsExactly(c, b, a);
|
||||
}
|
||||
|
||||
@Test
|
||||
void idTiebreakerOrdersEqualKeysById() {
|
||||
Long first = book("Same").getId();
|
||||
Long second = book("Same").getId();
|
||||
em.flush();
|
||||
assertThat(sortedIds("title", user.getId())).containsExactly(first, second);
|
||||
}
|
||||
|
||||
@Test
|
||||
void addedOnSorts() {
|
||||
Long older = book("Old", null, null, Instant.parse("2020-01-01T00:00:00Z"), List.of(), List.of(), null).getId();
|
||||
Long newer = book("New", null, null, Instant.parse("2024-01-01T00:00:00Z"), List.of(), List.of(), null).getId();
|
||||
em.flush();
|
||||
assertThat(sortedIds("addedOn", user.getId())).containsExactly(older, newer);
|
||||
assertThat(sortedIds("-addedOn", user.getId())).containsExactly(newer, older);
|
||||
}
|
||||
|
||||
@Test
|
||||
void perUserPersonalRatingSorts() {
|
||||
BookEntity low = book("Low");
|
||||
BookEntity high = book("High");
|
||||
progress(low, user, 3, ReadStatus.READ, null, null);
|
||||
progress(high, user, 7, ReadStatus.READ, null, null);
|
||||
em.flush();
|
||||
assertThat(sortedIds("personalRating", user.getId())).containsExactly(low.getId(), high.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void perUserSortIgnoresOtherUsersProgress() {
|
||||
BookLoreUserEntity other = BookLoreUserEntity.builder().username("other").passwordHash("x").name("Other").build();
|
||||
em.persist(other);
|
||||
BookEntity book = book("Rated");
|
||||
progress(book, other, 9, ReadStatus.READ, null, null);
|
||||
em.flush();
|
||||
// The requesting user has no progress row, so the rating is null, not 9.
|
||||
List<Long> byRating = sortedIds("-personalRating", user.getId());
|
||||
assertThat(byRating).containsExactly(book.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void readingProgressUsesGreatestOfPercentFields() {
|
||||
BookEntity half = book("Half");
|
||||
BookEntity nearlyDone = book("NearlyDone");
|
||||
progress(half, user, null, ReadStatus.READING, 0.5f, null);
|
||||
progress(nearlyDone, user, null, ReadStatus.READING, null, 0.9f);
|
||||
em.flush();
|
||||
assertThat(sortedIds("-readingProgress", user.getId())).containsExactly(nearlyDone.getId(), half.getId());
|
||||
}
|
||||
|
||||
// ---- facets ----
|
||||
|
||||
@Test
|
||||
void genreFacetOrAndNot() {
|
||||
Long horror = book("H", null, null, Instant.now(), List.of("Horror"), List.of(), null).getId();
|
||||
Long romance = book("R", null, null, Instant.now(), List.of("Romance"), List.of(), null).getId();
|
||||
em.flush();
|
||||
assertThat(facetIds("genre", List.of("Horror"), FacetLogic.OR, user.getId())).containsExactlyInAnyOrder(horror);
|
||||
assertThat(facetIds("genre", List.of("Horror"), FacetLogic.NOT, user.getId())).contains(romance).doesNotContain(horror);
|
||||
}
|
||||
|
||||
@Test
|
||||
void readStatusFacetIsPerUser() {
|
||||
BookEntity read = book("Read");
|
||||
BookEntity unread = book("Unread");
|
||||
progress(read, user, null, ReadStatus.READ, null, null);
|
||||
progress(unread, user, null, ReadStatus.UNREAD, null, null);
|
||||
em.flush();
|
||||
assertThat(facetIds("read_status", List.of("READ"), FacetLogic.OR, user.getId())).containsExactlyInAnyOrder(read.getId());
|
||||
}
|
||||
|
||||
// ---- query ----
|
||||
|
||||
@Test
|
||||
void queryMatchesTitleAuthorAndIsbn() {
|
||||
Long byTitle = book("The Hobbit", null, null, Instant.now(), List.of(), List.of(), null).getId();
|
||||
Long byAuthor = book("Unrelated", null, null, Instant.now(), List.of(), List.of("J.R.R. Tolkien"), null).getId();
|
||||
Long byIsbn = book("Another", null, null, Instant.now(), List.of(), List.of(), "9780261103344").getId();
|
||||
em.flush();
|
||||
|
||||
assertThat(matchIds("hobbit")).containsExactlyInAnyOrder(byTitle);
|
||||
assertThat(matchIds("tolkien")).containsExactlyInAnyOrder(byAuthor);
|
||||
assertThat(matchIds("9780261103344")).containsExactlyInAnyOrder(byIsbn);
|
||||
}
|
||||
|
||||
private Set<Long> matchIds(String query) {
|
||||
return bookRepository.findAll(BookSearchSpecification.matching(query)).stream()
|
||||
.map(BookEntity::getId).collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
package org.booklore.service.browse;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.PersistenceContext;
|
||||
import org.booklore.BookloreApplication;
|
||||
import org.booklore.browse.BrowsePage;
|
||||
import org.booklore.browse.Link;
|
||||
import org.booklore.exception.APIException;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.model.dto.Book;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.Library;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.model.entity.BookMetadataEntity;
|
||||
import org.booklore.model.entity.CategoryEntity;
|
||||
import org.booklore.model.entity.LibraryEntity;
|
||||
import org.booklore.model.entity.LibraryPathEntity;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.service.task.TaskCronService;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.TestConfiguration;
|
||||
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SpringBootTest(classes = BookloreApplication.class)
|
||||
@Transactional
|
||||
@TestPropertySource(properties = {
|
||||
"spring.flyway.enabled=false",
|
||||
"spring.jpa.hibernate.ddl-auto=create-drop",
|
||||
"spring.jpa.database-platform=org.hibernate.dialect.H2Dialect",
|
||||
"spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect",
|
||||
"spring.datasource.url=jdbc:h2:mem:browseservicetest;DB_CLOSE_DELAY=-1;NON_KEYWORDS=VALUE",
|
||||
"spring.datasource.driver-class-name=org.h2.Driver",
|
||||
"spring.datasource.username=sa",
|
||||
"spring.datasource.password=",
|
||||
"app.path-config=build/tmp/test-config",
|
||||
"app.bookdrop-folder=build/tmp/test-bookdrop",
|
||||
"spring.main.allow-bean-definition-overriding=true",
|
||||
"spring.task.scheduling.enabled=false",
|
||||
"app.task.scan-library-cron=*/1 * * * * *",
|
||||
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
||||
"app.features.oidc-enabled=false"
|
||||
})
|
||||
@Import(BookBrowseServiceTest.TestConfig.class)
|
||||
class BookBrowseServiceTest {
|
||||
|
||||
@Autowired
|
||||
private BookBrowseService browseService;
|
||||
@Autowired
|
||||
private BookRepository bookRepository;
|
||||
@MockitoBean
|
||||
private AuthenticationService authenticationService;
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager em;
|
||||
|
||||
private BookLoreUserEntity userEntity;
|
||||
private LibraryEntity library;
|
||||
private LibraryPathEntity libraryPath;
|
||||
private final Map<String, CategoryEntity> categories = new HashMap<>();
|
||||
|
||||
@TestConfiguration
|
||||
public static class TestConfig {
|
||||
@Bean("flyway")
|
||||
@Primary
|
||||
public Flyway flyway() {
|
||||
return mock(Flyway.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public TaskCronService taskCronService() {
|
||||
return mock(TaskCronService.class);
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void seed() {
|
||||
userEntity = BookLoreUserEntity.builder().username("reader").passwordHash("x").name("Reader").build();
|
||||
em.persist(userEntity);
|
||||
library = LibraryEntity.builder().name("Lib").icon("book").watch(false)
|
||||
.formatPriority(List.of(BookFileType.EPUB)).build();
|
||||
em.persist(library);
|
||||
libraryPath = LibraryPathEntity.builder().library(library).path("/p").build();
|
||||
em.persist(libraryPath);
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(nonAdminUser());
|
||||
}
|
||||
|
||||
private BookLoreUser nonAdminUser() {
|
||||
BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions();
|
||||
permissions.setAdmin(false);
|
||||
return BookLoreUser.builder()
|
||||
.id(userEntity.getId())
|
||||
.assignedLibraries(List.of(Library.builder().id(library.getId()).build()))
|
||||
.permissions(permissions)
|
||||
.build();
|
||||
}
|
||||
|
||||
private BookEntity book(String title, List<String> categoryNames) {
|
||||
BookEntity bookEntity = BookEntity.builder()
|
||||
.library(library).libraryPath(libraryPath).addedOn(Instant.now()).deleted(false).build();
|
||||
em.persist(bookEntity);
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder().book(bookEntity).title(title).build();
|
||||
metadata.setCategories(categoryNames.stream().map(this::category).collect(Collectors.toSet()));
|
||||
em.persist(metadata);
|
||||
bookEntity.setMetadata(metadata);
|
||||
return bookEntity;
|
||||
}
|
||||
|
||||
private CategoryEntity category(String name) {
|
||||
return categories.computeIfAbsent(name, n -> {
|
||||
CategoryEntity e = CategoryEntity.builder().name(n).build();
|
||||
em.persist(e);
|
||||
return e;
|
||||
});
|
||||
}
|
||||
|
||||
private BrowsePage<Book> browse(String sort, List<String> facet, String query, String cursor, int page, int size) {
|
||||
return browseService.browse(sort, facet, null, query, cursor, PageRequest.of(page, size));
|
||||
}
|
||||
|
||||
private String nextCursor(BrowsePage<Book> page) {
|
||||
Link next = page.links().stream().filter(l -> l.rel().contains("next")).findFirst().orElseThrow();
|
||||
return next.href().substring(next.href().indexOf("cursor=") + "cursor=".length());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsPageWithTotalsAndCursorAndLinks() {
|
||||
book("Alpha", List.of());
|
||||
book("Bravo", List.of());
|
||||
em.flush();
|
||||
|
||||
BrowsePage<Book> result = browse(null, null, null, null, 0, 20);
|
||||
|
||||
assertThat(result.content()).hasSize(2);
|
||||
assertThat(result.page().totalElements()).isEqualTo(2);
|
||||
assertThat(result.page().cursor()).isNotBlank();
|
||||
assertThat(result.links().stream().anyMatch(l -> l.rel().contains("self"))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void sortIsApplied() {
|
||||
Long b = book("Bravo", List.of()).getId();
|
||||
Long a = book("Alpha", List.of()).getId();
|
||||
em.flush();
|
||||
assertThat(browse("title", null, null, null, 0, 20).content().stream().map(Book::getId)).containsExactly(a, b);
|
||||
assertThat(browse("-title", null, null, null, 0, 20).content().stream().map(Book::getId)).containsExactly(b, a);
|
||||
}
|
||||
|
||||
@Test
|
||||
void facetIsApplied() {
|
||||
Long horror = book("H", List.of("Horror")).getId();
|
||||
book("R", List.of("Romance"));
|
||||
em.flush();
|
||||
BrowsePage<Book> result = browse(null, List.of("genre:Horror"), null, null, 0, 20);
|
||||
assertThat(result.content().stream().map(Book::getId)).containsExactly(horror);
|
||||
assertThat(result.page().totalElements()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryIsApplied() {
|
||||
Long hobbit = book("The Hobbit", List.of()).getId();
|
||||
book("Dune", List.of());
|
||||
em.flush();
|
||||
assertThat(browse(null, null, "hobbit", null, 0, 20).content().stream().map(Book::getId)).containsExactly(hobbit);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cursorWalkIsConsistent() {
|
||||
for (int i = 0; i < 5; i++) {
|
||||
book(String.format("Book%02d", i), List.of());
|
||||
}
|
||||
em.flush();
|
||||
|
||||
BrowsePage<Book> page0 = browse("title", null, null, null, 0, 2);
|
||||
assertThat(page0.content()).hasSize(2);
|
||||
assertThat(page0.page().totalElements()).isEqualTo(5);
|
||||
|
||||
BrowsePage<Book> page1 = browse("title", null, null, nextCursor(page0), 0, 2);
|
||||
assertThat(page1.content()).hasSize(2);
|
||||
assertThat(page1.content().stream().map(Book::getId))
|
||||
.doesNotContainAnyElementsOf(page0.content().stream().map(Book::getId).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cursorWithConflictingFacetsIsRejected() {
|
||||
book("Alpha", List.of("Horror"));
|
||||
em.flush();
|
||||
String cursor = browse(null, null, null, null, 0, 20).page().cursor();
|
||||
assertThatThrownBy(() -> browse(null, List.of("genre:Horror"), null, cursor, 0, 20))
|
||||
.isInstanceOfSatisfying(APIException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST))
|
||||
.hasMessageContaining("does not match");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deferredSortKeyIsRejected() {
|
||||
book("Alpha", List.of());
|
||||
em.flush();
|
||||
assertThatThrownBy(() -> browse("random", null, null, null, 0, 20))
|
||||
.isInstanceOfSatisfying(APIException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST))
|
||||
.hasMessageContaining("Unknown sort key");
|
||||
assertThatThrownBy(() -> browse("fileSizeKb", null, null, null, 0, 20))
|
||||
.isInstanceOfSatisfying(APIException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST))
|
||||
.hasMessageContaining("Unknown sort key");
|
||||
}
|
||||
|
||||
@Test
|
||||
void wrapLegacyAddsCursorAndLinksToExistingPage() {
|
||||
Book book = Book.builder().id(1L).build();
|
||||
org.springframework.data.domain.Page<Book> page =
|
||||
new org.springframework.data.domain.PageImpl<>(List.of(book), PageRequest.of(0, 20), 1);
|
||||
|
||||
BrowsePage<Book> wrapped = browseService.wrapLegacy(page, PageRequest.of(0, 20));
|
||||
|
||||
assertThat(wrapped.content()).hasSize(1);
|
||||
assertThat(wrapped.page().totalElements()).isEqualTo(1);
|
||||
assertThat(wrapped.page().cursor()).isNotBlank();
|
||||
assertThat(wrapped.links().stream().anyMatch(l -> l.rel().contains("self"))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonAdminSeesOnlyAssignedLibraries() {
|
||||
book("InLibrary", List.of());
|
||||
LibraryEntity otherLibrary = LibraryEntity.builder().name("Other").icon("book").watch(false)
|
||||
.formatPriority(List.of(BookFileType.EPUB)).build();
|
||||
em.persist(otherLibrary);
|
||||
LibraryPathEntity otherPath = LibraryPathEntity.builder().library(otherLibrary).path("/o").build();
|
||||
em.persist(otherPath);
|
||||
BookEntity outside = BookEntity.builder()
|
||||
.library(otherLibrary).libraryPath(otherPath).addedOn(Instant.now()).deleted(false).build();
|
||||
em.persist(outside);
|
||||
BookMetadataEntity md = BookMetadataEntity.builder().book(outside).title("Outside").build();
|
||||
em.persist(md);
|
||||
em.flush();
|
||||
|
||||
BrowsePage<Book> result = browse(null, null, null, null, 0, 20);
|
||||
assertThat(result.content()).hasSize(1);
|
||||
assertThat(result.content().get(0).getId()).isNotEqualTo(outside.getId());
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package org.booklore.service.browse;
|
||||
|
||||
import org.booklore.browse.FacetLogic;
|
||||
import org.booklore.exception.APIException;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.service.opds.MagicShelfBookService;
|
||||
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.data.jpa.domain.Specification;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class BookFacetRegistryMagicShelfTest {
|
||||
|
||||
@Mock
|
||||
private MagicShelfBookService magicShelfBookService;
|
||||
|
||||
@InjectMocks
|
||||
private BookFacetRegistry registry;
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void magicShelfValueShortCircuitsToMagicShelfSpecification() {
|
||||
Specification<BookEntity> magicSpec = mock(Specification.class);
|
||||
when(magicShelfBookService.toSpecification(7L, 42L)).thenReturn(magicSpec);
|
||||
|
||||
registry.toSpecification("shelf", List.of("magic:42"), FacetLogic.OR, 7L);
|
||||
|
||||
verify(magicShelfBookService).toSpecification(7L, 42L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void regularShelfValueDoesNotTouchMagicShelfService() {
|
||||
registry.toSpecification("shelf", List.of("3"), FacetLogic.OR, 7L);
|
||||
verifyNoInteractions(magicShelfBookService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownFacetThrows() {
|
||||
assertThatThrownBy(() -> registry.toSpecification("bogus", List.of("x"), FacetLogic.AND, 1L))
|
||||
.isInstanceOf(APIException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedMagicShelfIdThrows() {
|
||||
assertThatThrownBy(() -> registry.toSpecification("shelf", List.of("magic:not-a-number"), FacetLogic.AND, 1L))
|
||||
.isInstanceOf(APIException.class);
|
||||
assertThatThrownBy(() -> registry.toSpecification("shelf", List.of("magic:"), FacetLogic.AND, 1L))
|
||||
.isInstanceOf(APIException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyShelfValuesDoesNotThrow() {
|
||||
assertThatCode(() -> registry.toSpecification("shelf", List.of(), FacetLogic.AND, 1L))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankAndNullShelfTokensAreIgnored() {
|
||||
assertThatCode(() -> registry.toSpecification("shelf", Arrays.asList(null, "", " "), FacetLogic.AND, 1L))
|
||||
.doesNotThrowAnyException();
|
||||
verifyNoInteractions(magicShelfBookService);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user