diff --git a/booklore-api/src/main/java/org/booklore/service/BookRuleEvaluatorService.java b/booklore-api/src/main/java/org/booklore/service/BookRuleEvaluatorService.java index afa7d0930..95cace500 100644 --- a/booklore-api/src/main/java/org/booklore/service/BookRuleEvaluatorService.java +++ b/booklore-api/src/main/java/org/booklore/service/BookRuleEvaluatorService.java @@ -572,25 +572,25 @@ public class BookRuleEvaluatorService { private Predicate buildGreaterThan(Rule rule, CriteriaBuilder cb, Root root, Join progressJoin) { return buildComparisonPredicate(rule, cb, root, progressJoin, (field, dateValue) -> cb.greaterThan(field.as(LocalDateTime.class), dateValue), - (field, numValue) -> cb.gt(field.as(Double.class), numValue)); + (field, numValue) -> cb.gt(toNumericExpression(field), numValue)); } private Predicate buildGreaterThanEqual(Rule rule, CriteriaBuilder cb, Root root, Join progressJoin) { return buildComparisonPredicate(rule, cb, root, progressJoin, (field, dateValue) -> cb.greaterThanOrEqualTo(field.as(LocalDateTime.class), dateValue), - (field, numValue) -> cb.ge(field.as(Double.class), numValue)); + (field, numValue) -> cb.ge(toNumericExpression(field), numValue)); } private Predicate buildLessThan(Rule rule, CriteriaBuilder cb, Root root, Join progressJoin) { return buildComparisonPredicate(rule, cb, root, progressJoin, (field, dateValue) -> cb.lessThan(field.as(LocalDateTime.class), dateValue), - (field, numValue) -> cb.lt(field.as(Double.class), numValue)); + (field, numValue) -> cb.lt(toNumericExpression(field), numValue)); } private Predicate buildLessThanEqual(Rule rule, CriteriaBuilder cb, Root root, Join progressJoin) { return buildComparisonPredicate(rule, cb, root, progressJoin, (field, dateValue) -> cb.lessThanOrEqualTo(field.as(LocalDateTime.class), dateValue), - (field, numValue) -> cb.le(field.as(Double.class), numValue)); + (field, numValue) -> cb.le(toNumericExpression(field), numValue)); } private Predicate buildComparisonPredicate(Rule rule, CriteriaBuilder cb, Root root, @@ -605,6 +605,7 @@ public class BookRuleEvaluatorService { if (value instanceof LocalDateTime) { return dateComparator.apply(field, (LocalDateTime) value); } + if (!(value instanceof Number)) return cb.conjunction(); return numberComparator.apply(field, ((Number) value).doubleValue()); } @@ -625,7 +626,9 @@ public class BookRuleEvaluatorService { return cb.conjunction(); } - return cb.between(field.as(Double.class), ((Number) start).doubleValue(), ((Number) end).doubleValue()); + @SuppressWarnings("unchecked") + Expression numField = (Expression) (Expression) field; + return cb.between(numField, ((Number) start).doubleValue(), ((Number) end).doubleValue()); } private Predicate buildIsEmpty(Rule rule, CriteriaQuery query, CriteriaBuilder cb, Root root, Join progressJoin) { @@ -849,6 +852,13 @@ public class BookRuleEvaluatorService { return value; } + if (isNumericField(field)) { + try { + return Double.parseDouble(value.toString()); + } catch (NumberFormatException ignored) { + } + } + return value.toString().toLowerCase(); } @@ -878,6 +888,26 @@ public class BookRuleEvaluatorService { return Collections.singletonList(value.toString()); } + private static final Set NUMERIC_FIELDS = Set.of( + RuleField.METADATA_SCORE, RuleField.FILE_SIZE, RuleField.PAGE_COUNT, + RuleField.SERIES_NUMBER, RuleField.SERIES_TOTAL, RuleField.AGE_RATING, + RuleField.PERSONAL_RATING, RuleField.READING_PROGRESS, RuleField.AUDIOBOOK_DURATION, + RuleField.AMAZON_RATING, RuleField.AMAZON_REVIEW_COUNT, + RuleField.GOODREADS_RATING, RuleField.GOODREADS_REVIEW_COUNT, + RuleField.HARDCOVER_RATING, RuleField.HARDCOVER_REVIEW_COUNT, + RuleField.LUBIMYCZYTAC_RATING, RuleField.RANOBEDB_RATING, + RuleField.AUDIBLE_RATING, RuleField.AUDIBLE_REVIEW_COUNT + ); + + private static boolean isNumericField(RuleField field) { + return field != null && NUMERIC_FIELDS.contains(field); + } + + @SuppressWarnings("unchecked") + private static Expression toNumericExpression(Expression expr) { + return (Expression) expr; + } + private String escapeLike(String value) { return value.replace("\\", "\\\\") .replace("%", "\\%") diff --git a/booklore-api/src/test/java/org/booklore/service/BookRuleEvaluatorEdgeCasesTest.java b/booklore-api/src/test/java/org/booklore/service/BookRuleEvaluatorEdgeCasesTest.java new file mode 100644 index 000000000..6c984bc03 --- /dev/null +++ b/booklore-api/src/test/java/org/booklore/service/BookRuleEvaluatorEdgeCasesTest.java @@ -0,0 +1,724 @@ +package org.booklore.service; + +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import org.booklore.BookloreApplication; +import org.booklore.model.dto.*; +import org.booklore.model.entity.*; +import org.booklore.model.enums.ReadStatus; +import org.booklore.repository.BookRepository; +import org.booklore.service.task.TaskCronService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +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.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.mockito.Mockito.mock; + +@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:ruleeval_edge;DB_CLOSE_DELAY=-1", + "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(BookRuleEvaluatorEdgeCasesTest.TestConfig.class) +class BookRuleEvaluatorEdgeCasesTest { + + @TestConfiguration + static class TestConfig { + @Bean("flyway") + @Primary + public org.flywaydb.core.Flyway flyway() { + return mock(org.flywaydb.core.Flyway.class); + } + + @Bean + @Primary + public TaskCronService taskCronService() { + return mock(TaskCronService.class); + } + } + + @Autowired + private BookRuleEvaluatorService evaluator; + + @Autowired + private BookRepository bookRepository; + + @PersistenceContext + private EntityManager em; + + private LibraryEntity library; + private LibraryPathEntity libraryPath; + private BookLoreUserEntity user; + + @BeforeEach + void setUp() { + library = LibraryEntity.builder().name("Test Library").icon("book").watch(false).build(); + em.persist(library); + em.flush(); + + libraryPath = LibraryPathEntity.builder().library(library).path("/test/path").build(); + em.persist(libraryPath); + em.flush(); + + user = BookLoreUserEntity.builder() + .username("testuser") + .passwordHash("hash") + .isDefaultPassword(true) + .name("Test User") + .build(); + em.persist(user); + em.flush(); + } + + private BookEntity createBook(String title) { + BookEntity book = BookEntity.builder() + .library(library) + .libraryPath(libraryPath) + .addedOn(Instant.now()) + .deleted(false) + .build(); + em.persist(book); + em.flush(); + + BookMetadataEntity metadata = BookMetadataEntity.builder() + .book(book) + .bookId(book.getId()) + .title(title) + .build(); + em.persist(metadata); + em.flush(); + + book.setMetadata(metadata); + return book; + } + + private List findMatchingIds(GroupRule group) { + Specification spec = evaluator.toSpecification(group, user.getId()); + return bookRepository.findAll(spec).stream().map(BookEntity::getId).distinct().toList(); + } + + private GroupRule singleRule(RuleField field, RuleOperator operator, Object value) { + Rule rule = new Rule(); + rule.setField(field); + rule.setOperator(operator); + rule.setValue(value); + GroupRule group = new GroupRule(); + group.setJoin(JoinType.AND); + group.setRules(List.of(rule)); + return group; + } + + @Nested + class NullRuleHandlingTests { + @Test + void nullFieldOnRule_returnsAllBooks() { + BookEntity book = createBook("Any Book"); + em.flush(); + em.clear(); + + Rule rule = new Rule(); + rule.setField(null); + rule.setOperator(RuleOperator.EQUALS); + rule.setValue("test"); + + GroupRule group = new GroupRule(); + group.setJoin(JoinType.AND); + group.setRules(List.of(rule)); + + List ids = findMatchingIds(group); + assertThat(ids).contains(book.getId()); + } + + @Test + void nullOperatorOnRule_returnsAllBooks() { + BookEntity book = createBook("Any Book"); + em.flush(); + em.clear(); + + Rule rule = new Rule(); + rule.setField(RuleField.TITLE); + rule.setOperator(null); + rule.setValue("test"); + + GroupRule group = new GroupRule(); + group.setJoin(JoinType.AND); + group.setRules(List.of(rule)); + + List ids = findMatchingIds(group); + assertThat(ids).contains(book.getId()); + } + + @Test + void nullRulesInGroup_matchesAllBooks() { + BookEntity book = createBook("Any Book"); + em.flush(); + em.clear(); + + GroupRule group = new GroupRule(); + group.setJoin(JoinType.AND); + group.setRules(null); + + List ids = findMatchingIds(group); + assertThat(ids).contains(book.getId()); + } + + @Test + void nullRuleObjectInList_skipped() { + BookEntity book = createBook("Any Book"); + em.flush(); + em.clear(); + + List rules = new ArrayList<>(); + rules.add(null); + + GroupRule group = new GroupRule(); + group.setJoin(JoinType.AND); + group.setRules(rules); + + List ids = findMatchingIds(group); + assertThat(ids).contains(book.getId()); + } + } + + @Nested + class MalformedRuleTests { + @Test + void invalidRuleObject_loggedAndSkipped() { + BookEntity book = createBook("Any Book"); + em.flush(); + em.clear(); + + Map badRule = new HashMap<>(); + badRule.put("field", "INVALID_FIELD"); + badRule.put("operator", "EQUALS"); + badRule.put("value", "test"); + + GroupRule group = new GroupRule(); + group.setJoin(JoinType.AND); + group.setRules(List.of(badRule)); + + assertThatCode(() -> findMatchingIds(group)).doesNotThrowAnyException(); + } + + @Test + void inBetween_withNullStart_returnsAllBooks() { + BookEntity book = createBook("Any Book"); + book.getMetadata().setPageCount(300); + em.merge(book.getMetadata()); + em.flush(); + em.clear(); + + Rule rule = new Rule(); + rule.setField(RuleField.PAGE_COUNT); + rule.setOperator(RuleOperator.IN_BETWEEN); + rule.setValueStart(null); + rule.setValueEnd(500); + + GroupRule group = new GroupRule(); + group.setJoin(JoinType.AND); + group.setRules(List.of(rule)); + + List ids = findMatchingIds(group); + assertThat(ids).contains(book.getId()); + } + + @Test + void inBetween_withNullEnd_returnsAllBooks() { + BookEntity book = createBook("Any Book"); + book.getMetadata().setPageCount(300); + em.merge(book.getMetadata()); + em.flush(); + em.clear(); + + Rule rule = new Rule(); + rule.setField(RuleField.PAGE_COUNT); + rule.setOperator(RuleOperator.IN_BETWEEN); + rule.setValueStart(100); + rule.setValueEnd(null); + + GroupRule group = new GroupRule(); + group.setJoin(JoinType.AND); + group.setRules(List.of(rule)); + + List ids = findMatchingIds(group); + assertThat(ids).contains(book.getId()); + } + } + + @Nested + class EmptyGroupTests { + @Test + void emptyAndGroup_matchesAll() { + BookEntity book = createBook("Any Book"); + em.flush(); + em.clear(); + + GroupRule group = new GroupRule(); + group.setJoin(JoinType.AND); + group.setRules(new ArrayList<>()); + + List ids = findMatchingIds(group); + assertThat(ids).contains(book.getId()); + } + + @Test + void emptyOrGroup_matchesAll() { + BookEntity book = createBook("Any Book"); + em.flush(); + em.clear(); + + GroupRule group = new GroupRule(); + group.setJoin(JoinType.OR); + group.setRules(new ArrayList<>()); + + List ids = findMatchingIds(group); + assertThat(ids).contains(book.getId()); + } + } + + @Nested + class MultiUserIsolationTests { + @Test + void progressFromDifferentUser_notVisible() { + BookLoreUserEntity user2 = BookLoreUserEntity.builder() + .username("otheruser") + .passwordHash("hash2") + .isDefaultPassword(true) + .name("Other User") + .build(); + em.persist(user2); + + BookEntity book = createBook("Shared Book"); + + UserBookProgressEntity otherProgress = UserBookProgressEntity.builder() + .user(user2) + .book(book) + .readStatus(ReadStatus.READ) + .build(); + em.persist(otherProgress); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.READ_STATUS, RuleOperator.EQUALS, "READ")); + assertThat(ids).doesNotContain(book.getId()); + } + } + + @Nested + class NestedGroupEdgeCasesTests { + @Test + void deeplyNestedGroups_evaluateCorrectly() { + BookEntity match = createBook("Deep Match"); + match.getMetadata().setPageCount(200); + match.getMetadata().setLanguage("en"); + match.getMetadata().setPublisher("Test Publisher"); + em.merge(match.getMetadata()); + + BookEntity noMatch = createBook("Deep No Match"); + noMatch.getMetadata().setPageCount(200); + noMatch.getMetadata().setLanguage("fr"); + em.merge(noMatch.getMetadata()); + em.flush(); + em.clear(); + + Rule langRule = new Rule(); + langRule.setField(RuleField.LANGUAGE); + langRule.setOperator(RuleOperator.EQUALS); + langRule.setValue("en"); + + Rule pubRule = new Rule(); + pubRule.setField(RuleField.PUBLISHER); + pubRule.setOperator(RuleOperator.CONTAINS); + pubRule.setValue("test"); + + GroupRule innerGroup = new GroupRule(); + innerGroup.setType("group"); + innerGroup.setJoin(JoinType.AND); + innerGroup.setRules(List.of(langRule, pubRule)); + + Rule pageRule = new Rule(); + pageRule.setField(RuleField.PAGE_COUNT); + pageRule.setOperator(RuleOperator.GREATER_THAN); + pageRule.setValue(100); + + GroupRule outerGroup = new GroupRule(); + outerGroup.setJoin(JoinType.AND); + outerGroup.setRules(List.of(pageRule, innerGroup)); + + List ids = findMatchingIds(outerGroup); + assertThat(ids).contains(match.getId()); + assertThat(ids).doesNotContain(noMatch.getId()); + } + + @Test + void mixedAndOrGroups_evaluateCorrectly() { + BookEntity matchA = createBook("Match A"); + matchA.getMetadata().setLanguage("en"); + matchA.getMetadata().setPageCount(500); + em.merge(matchA.getMetadata()); + + BookEntity matchB = createBook("Match B"); + matchB.getMetadata().setLanguage("fr"); + matchB.getMetadata().setPageCount(500); + matchB.getMetadata().setPublisher("Big Publisher"); + em.merge(matchB.getMetadata()); + + BookEntity noMatch = createBook("No Match"); + noMatch.getMetadata().setLanguage("fr"); + noMatch.getMetadata().setPageCount(500); + em.merge(noMatch.getMetadata()); + em.flush(); + em.clear(); + + // Outer AND: pageCount > 300 AND (language = en OR publisher contains "big") + Rule pageRule = new Rule(); + pageRule.setField(RuleField.PAGE_COUNT); + pageRule.setOperator(RuleOperator.GREATER_THAN); + pageRule.setValue(300); + + Rule langRule = new Rule(); + langRule.setField(RuleField.LANGUAGE); + langRule.setOperator(RuleOperator.EQUALS); + langRule.setValue("en"); + + Rule pubRule = new Rule(); + pubRule.setField(RuleField.PUBLISHER); + pubRule.setOperator(RuleOperator.CONTAINS); + pubRule.setValue("big"); + + GroupRule orGroup = new GroupRule(); + orGroup.setType("group"); + orGroup.setJoin(JoinType.OR); + orGroup.setRules(List.of(langRule, pubRule)); + + GroupRule outerGroup = new GroupRule(); + outerGroup.setJoin(JoinType.AND); + outerGroup.setRules(List.of(pageRule, orGroup)); + + List ids = findMatchingIds(outerGroup); + assertThat(ids).contains(matchA.getId(), matchB.getId()); + assertThat(ids).doesNotContain(noMatch.getId()); + } + } + + @Nested + class MultipleRulesOnSameFieldTests { + @Test + void twoComparisonsOnSameField_actsAsRange() { + BookEntity low = createBook("Low Pages"); + low.getMetadata().setPageCount(50); + em.merge(low.getMetadata()); + + BookEntity mid = createBook("Mid Pages"); + mid.getMetadata().setPageCount(250); + em.merge(mid.getMetadata()); + + BookEntity high = createBook("High Pages"); + high.getMetadata().setPageCount(600); + em.merge(high.getMetadata()); + em.flush(); + em.clear(); + + Rule gtRule = new Rule(); + gtRule.setField(RuleField.PAGE_COUNT); + gtRule.setOperator(RuleOperator.GREATER_THAN); + gtRule.setValue(100); + + Rule ltRule = new Rule(); + ltRule.setField(RuleField.PAGE_COUNT); + ltRule.setOperator(RuleOperator.LESS_THAN); + ltRule.setValue(500); + + GroupRule group = new GroupRule(); + group.setJoin(JoinType.AND); + group.setRules(List.of(gtRule, ltRule)); + + List ids = findMatchingIds(group); + assertThat(ids).contains(mid.getId()); + assertThat(ids).doesNotContain(low.getId(), high.getId()); + } + } + + @Nested + class ReadStatusEdgeCasesTests { + @Test + void allReadStatuses_matchCorrectBooks() { + BookEntity reading = createBook("Reading Book"); + UserBookProgressEntity p1 = UserBookProgressEntity.builder() + .user(user).book(reading).readStatus(ReadStatus.READING).build(); + em.persist(p1); + + BookEntity read = createBook("Read Book"); + UserBookProgressEntity p2 = UserBookProgressEntity.builder() + .user(user).book(read).readStatus(ReadStatus.READ).build(); + em.persist(p2); + + BookEntity paused = createBook("Paused Book"); + UserBookProgressEntity p3 = UserBookProgressEntity.builder() + .user(user).book(paused).readStatus(ReadStatus.PAUSED).build(); + em.persist(p3); + + BookEntity reReading = createBook("ReReading Book"); + UserBookProgressEntity p4 = UserBookProgressEntity.builder() + .user(user).book(reReading).readStatus(ReadStatus.RE_READING).build(); + em.persist(p4); + + BookEntity unread = createBook("Unread Book"); + UserBookProgressEntity p5 = UserBookProgressEntity.builder() + .user(user).book(unread).readStatus(ReadStatus.UNREAD).build(); + em.persist(p5); + em.flush(); + em.clear(); + + List readingIds = findMatchingIds(singleRule(RuleField.READ_STATUS, RuleOperator.EQUALS, "READING")); + assertThat(readingIds).contains(reading.getId()); + assertThat(readingIds).doesNotContain(read.getId(), paused.getId(), reReading.getId(), unread.getId()); + + List pausedIds = findMatchingIds(singleRule(RuleField.READ_STATUS, RuleOperator.EQUALS, "PAUSED")); + assertThat(pausedIds).contains(paused.getId()); + + List reReadingIds = findMatchingIds(singleRule(RuleField.READ_STATUS, RuleOperator.EQUALS, "RE_READING")); + assertThat(reReadingIds).contains(reReading.getId()); + } + + @Test + void excludesAll_withUnset_excludesBooksWithNoProgress() { + BookEntity noProgress = createBook("No Progress"); + + BookEntity readBook = createBook("Read Book"); + UserBookProgressEntity p = UserBookProgressEntity.builder() + .user(user).book(readBook).readStatus(ReadStatus.READ).build(); + em.persist(p); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.READ_STATUS, RuleOperator.EXCLUDES_ALL, List.of("UNSET"))); + assertThat(ids).contains(readBook.getId()); + assertThat(ids).doesNotContain(noProgress.getId()); + } + } + + @Nested + class ComparisonWithNullFieldValueTests { + @Test + void greaterThan_onNullField_doesNotMatch() { + BookEntity book = createBook("No Page Count"); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.PAGE_COUNT, RuleOperator.GREATER_THAN, 0)); + assertThat(ids).doesNotContain(book.getId()); + } + + @Test + void lessThan_onNullField_doesNotMatch() { + BookEntity book = createBook("No Page Count"); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.PAGE_COUNT, RuleOperator.LESS_THAN, 999999)); + assertThat(ids).doesNotContain(book.getId()); + } + + @Test + void inBetween_onNullField_doesNotMatch() { + BookEntity book = createBook("No Score"); + em.flush(); + em.clear(); + + Rule rule = new Rule(); + rule.setField(RuleField.METADATA_SCORE); + rule.setOperator(RuleOperator.IN_BETWEEN); + rule.setValueStart(0); + rule.setValueEnd(100); + + GroupRule group = new GroupRule(); + group.setJoin(JoinType.AND); + group.setRules(List.of(rule)); + + List ids = findMatchingIds(group); + assertThat(ids).doesNotContain(book.getId()); + } + + @Test + void equals_onNullField_doesNotMatchNumericValue() { + BookEntity book = createBook("No Rating"); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.AMAZON_RATING, RuleOperator.EQUALS, 0)); + assertThat(ids).doesNotContain(book.getId()); + } + } + + @Nested + class WithinLastEdgeCasesTests { + @Test + void withinLast_withStringAmount_parsesCorrectly() { + BookEntity recent = createBook("Recent"); + recent.setAddedOn(Instant.now().minusSeconds(86400)); + em.merge(recent); + em.flush(); + em.clear(); + + Rule rule = new Rule(); + rule.setField(RuleField.ADDED_ON); + rule.setOperator(RuleOperator.WITHIN_LAST); + rule.setValue("7"); + rule.setValueEnd("days"); + + GroupRule group = new GroupRule(); + group.setJoin(JoinType.AND); + group.setRules(List.of(rule)); + + List ids = findMatchingIds(group); + assertThat(ids).contains(recent.getId()); + } + + @Test + void withinLast_withDefaultUnit_usesDays() { + BookEntity recent = createBook("Recent"); + recent.setAddedOn(Instant.now().minusSeconds(86400)); + em.merge(recent); + em.flush(); + em.clear(); + + Rule rule = new Rule(); + rule.setField(RuleField.ADDED_ON); + rule.setOperator(RuleOperator.WITHIN_LAST); + rule.setValue(7); + + GroupRule group = new GroupRule(); + group.setJoin(JoinType.AND); + group.setRules(List.of(rule)); + + List ids = findMatchingIds(group); + assertThat(ids).contains(recent.getId()); + } + + @Test + void thisPeriod_defaultsToYear() { + BookEntity recent = createBook("Recent"); + recent.setAddedOn(Instant.now().minusSeconds(86400)); + em.merge(recent); + em.flush(); + em.clear(); + + Rule rule = new Rule(); + rule.setField(RuleField.ADDED_ON); + rule.setOperator(RuleOperator.THIS_PERIOD); + rule.setValue(null); + + GroupRule group = new GroupRule(); + group.setJoin(JoinType.AND); + group.setRules(List.of(rule)); + + List ids = findMatchingIds(group); + assertThat(ids).contains(recent.getId()); + } + } + + @Nested + class CombinedRuleTypeTests { + @Test + void presenceAndComparisonRules_combinedCorrectly() { + BookEntity matchBoth = createBook("Match Both"); + matchBoth.getMetadata().setDescription("Has description"); + matchBoth.getMetadata().setPageCount(400); + em.merge(matchBoth.getMetadata()); + + BookEntity hasDescLowPages = createBook("Desc Low Pages"); + hasDescLowPages.getMetadata().setDescription("Has description too"); + hasDescLowPages.getMetadata().setPageCount(50); + em.merge(hasDescLowPages.getMetadata()); + + BookEntity highPagesNoDesc = createBook("High Pages No Desc"); + highPagesNoDesc.getMetadata().setPageCount(400); + em.merge(highPagesNoDesc.getMetadata()); + em.flush(); + em.clear(); + + Rule presenceRule = new Rule(); + presenceRule.setField(RuleField.METADATA_PRESENCE); + presenceRule.setOperator(RuleOperator.EQUALS); + presenceRule.setValue("description"); + + Rule pageRule = new Rule(); + pageRule.setField(RuleField.PAGE_COUNT); + pageRule.setOperator(RuleOperator.GREATER_THAN); + pageRule.setValue(200); + + GroupRule group = new GroupRule(); + group.setJoin(JoinType.AND); + group.setRules(List.of(presenceRule, pageRule)); + + List ids = findMatchingIds(group); + assertThat(ids).contains(matchBoth.getId()); + assertThat(ids).doesNotContain(hasDescLowPages.getId(), highPagesNoDesc.getId()); + } + + @Test + void stringAndNumericRules_combinedCorrectly() { + BookEntity match = createBook("The Great Gatsby"); + match.getMetadata().setPageCount(180); + match.getMetadata().setLanguage("en"); + em.merge(match.getMetadata()); + + BookEntity wrongLang = createBook("El Gran Gatsby"); + wrongLang.getMetadata().setPageCount(180); + wrongLang.getMetadata().setLanguage("es"); + em.merge(wrongLang.getMetadata()); + em.flush(); + em.clear(); + + Rule titleRule = new Rule(); + titleRule.setField(RuleField.TITLE); + titleRule.setOperator(RuleOperator.CONTAINS); + titleRule.setValue("gatsby"); + + Rule langRule = new Rule(); + langRule.setField(RuleField.LANGUAGE); + langRule.setOperator(RuleOperator.EQUALS); + langRule.setValue("en"); + + GroupRule group = new GroupRule(); + group.setJoin(JoinType.AND); + group.setRules(List.of(titleRule, langRule)); + + List ids = findMatchingIds(group); + assertThat(ids).contains(match.getId()); + assertThat(ids).doesNotContain(wrongLang.getId()); + } + } +} diff --git a/booklore-api/src/test/java/org/booklore/service/BookRuleEvaluatorFieldCoverageTest.java b/booklore-api/src/test/java/org/booklore/service/BookRuleEvaluatorFieldCoverageTest.java new file mode 100644 index 000000000..243083734 --- /dev/null +++ b/booklore-api/src/test/java/org/booklore/service/BookRuleEvaluatorFieldCoverageTest.java @@ -0,0 +1,980 @@ +package org.booklore.service; + +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import org.booklore.BookloreApplication; +import org.booklore.model.dto.*; +import org.booklore.model.entity.*; +import org.booklore.model.enums.ReadStatus; +import org.booklore.repository.BookRepository; +import org.booklore.service.task.TaskCronService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +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.time.temporal.ChronoUnit; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +@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:ruleeval_fields;DB_CLOSE_DELAY=-1", + "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(BookRuleEvaluatorFieldCoverageTest.TestConfig.class) +class BookRuleEvaluatorFieldCoverageTest { + + @TestConfiguration + static class TestConfig { + @Bean("flyway") + @Primary + public org.flywaydb.core.Flyway flyway() { + return mock(org.flywaydb.core.Flyway.class); + } + + @Bean + @Primary + public TaskCronService taskCronService() { + return mock(TaskCronService.class); + } + } + + @Autowired + private BookRuleEvaluatorService evaluator; + + @Autowired + private BookRepository bookRepository; + + @PersistenceContext + private EntityManager em; + + private LibraryEntity library; + private LibraryEntity library2; + private LibraryPathEntity libraryPath; + private LibraryPathEntity libraryPath2; + private BookLoreUserEntity user; + + @BeforeEach + void setUp() { + library = LibraryEntity.builder().name("Test Library").icon("book").watch(false).build(); + em.persist(library); + + library2 = LibraryEntity.builder().name("Second Library").icon("book").watch(false).build(); + em.persist(library2); + em.flush(); + + libraryPath = LibraryPathEntity.builder().library(library).path("/test/path").build(); + em.persist(libraryPath); + + libraryPath2 = LibraryPathEntity.builder().library(library2).path("/test/path2").build(); + em.persist(libraryPath2); + em.flush(); + + user = BookLoreUserEntity.builder() + .username("testuser") + .passwordHash("hash") + .isDefaultPassword(true) + .name("Test User") + .build(); + em.persist(user); + em.flush(); + } + + private BookEntity createBook(String title) { + return createBook(title, library, libraryPath); + } + + private BookEntity createBook(String title, LibraryEntity lib, LibraryPathEntity libPath) { + BookEntity book = BookEntity.builder() + .library(lib) + .libraryPath(libPath) + .addedOn(Instant.now()) + .deleted(false) + .build(); + em.persist(book); + em.flush(); + + BookMetadataEntity metadata = BookMetadataEntity.builder() + .book(book) + .bookId(book.getId()) + .title(title) + .build(); + em.persist(metadata); + em.flush(); + + book.setMetadata(metadata); + return book; + } + + private UserBookProgressEntity createProgress(BookEntity book, ReadStatus status) { + UserBookProgressEntity progress = UserBookProgressEntity.builder() + .user(user) + .book(book) + .readStatus(status) + .build(); + em.persist(progress); + em.flush(); + return progress; + } + + private List findMatchingIds(GroupRule group) { + Specification spec = evaluator.toSpecification(group, user.getId()); + return bookRepository.findAll(spec).stream().map(BookEntity::getId).distinct().toList(); + } + + private GroupRule singleRule(RuleField field, RuleOperator operator, Object value) { + return singleRule(field, operator, value, null, null); + } + + private GroupRule singleRule(RuleField field, RuleOperator operator, Object value, Object valueStart, Object valueEnd) { + Rule rule = new Rule(); + rule.setField(field); + rule.setOperator(operator); + rule.setValue(value); + rule.setValueStart(valueStart); + rule.setValueEnd(valueEnd); + GroupRule group = new GroupRule(); + group.setJoin(JoinType.AND); + group.setRules(List.of(rule)); + return group; + } + + @Nested + class LibraryFieldTests { + @Test + void equals_matchesBookInLibrary() { + BookEntity book1 = createBook("Lib1 Book", library, libraryPath); + BookEntity book2 = createBook("Lib2 Book", library2, libraryPath2); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.LIBRARY, RuleOperator.EQUALS, library.getId())); + assertThat(ids).contains(book1.getId()); + assertThat(ids).doesNotContain(book2.getId()); + } + + @Test + void notEquals_excludesBookInLibrary() { + BookEntity book1 = createBook("Lib1 Book", library, libraryPath); + BookEntity book2 = createBook("Lib2 Book", library2, libraryPath2); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.LIBRARY, RuleOperator.NOT_EQUALS, library.getId())); + assertThat(ids).contains(book2.getId()); + assertThat(ids).doesNotContain(book1.getId()); + } + + @Test + void includesAny_matchesBooksInMultipleLibraries() { + BookEntity book1 = createBook("Lib1 Book", library, libraryPath); + BookEntity book2 = createBook("Lib2 Book", library2, libraryPath2); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.LIBRARY, RuleOperator.INCLUDES_ANY, + List.of(String.valueOf(library.getId()), String.valueOf(library2.getId())))); + assertThat(ids).contains(book1.getId(), book2.getId()); + } + } + + @Nested + class ShelfFieldTests { + @Test + void equals_matchesBookOnShelf() { + ShelfEntity shelf = ShelfEntity.builder().user(user).name("Favorites").build(); + em.persist(shelf); + + BookEntity onShelf = createBook("On Shelf"); + onShelf.setShelves(new HashSet<>(Set.of(shelf))); + em.merge(onShelf); + + BookEntity offShelf = createBook("Off Shelf"); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.SHELF, RuleOperator.EQUALS, + List.of(String.valueOf(shelf.getId())))); + assertThat(ids).contains(onShelf.getId()); + assertThat(ids).doesNotContain(offShelf.getId()); + } + + @Test + void isEmpty_matchesBookWithNoShelves() { + ShelfEntity shelf = ShelfEntity.builder().user(user).name("My Shelf").build(); + em.persist(shelf); + + BookEntity onShelf = createBook("On Shelf"); + onShelf.setShelves(new HashSet<>(Set.of(shelf))); + em.merge(onShelf); + + BookEntity noShelf = createBook("No Shelf"); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.SHELF, RuleOperator.IS_EMPTY, null)); + assertThat(ids).contains(noShelf.getId()); + assertThat(ids).doesNotContain(onShelf.getId()); + } + + @Test + void isNotEmpty_matchesBookWithShelves() { + ShelfEntity shelf = ShelfEntity.builder().user(user).name("My Shelf 2").build(); + em.persist(shelf); + + BookEntity onShelf = createBook("On Shelf"); + onShelf.setShelves(new HashSet<>(Set.of(shelf))); + em.merge(onShelf); + + BookEntity noShelf = createBook("No Shelf"); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.SHELF, RuleOperator.IS_NOT_EMPTY, null)); + assertThat(ids).contains(onShelf.getId()); + assertThat(ids).doesNotContain(noShelf.getId()); + } + + @Test + void includesAny_matchesBookOnAnyShelf() { + ShelfEntity shelf1 = ShelfEntity.builder().user(user).name("Shelf One").build(); + em.persist(shelf1); + ShelfEntity shelf2 = ShelfEntity.builder().user(user).name("Shelf Two").build(); + em.persist(shelf2); + + BookEntity onShelf1 = createBook("On Shelf 1"); + onShelf1.setShelves(new HashSet<>(Set.of(shelf1))); + em.merge(onShelf1); + + BookEntity onShelf2 = createBook("On Shelf 2"); + onShelf2.setShelves(new HashSet<>(Set.of(shelf2))); + em.merge(onShelf2); + + BookEntity noShelf = createBook("No Shelf"); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.SHELF, RuleOperator.INCLUDES_ANY, + List.of(String.valueOf(shelf1.getId())))); + assertThat(ids).contains(onShelf1.getId()); + assertThat(ids).doesNotContain(onShelf2.getId(), noShelf.getId()); + } + + @Test + void excludesAll_excludesBooksOnShelves() { + ShelfEntity shelf1 = ShelfEntity.builder().user(user).name("Excluded Shelf").build(); + em.persist(shelf1); + ShelfEntity shelf2 = ShelfEntity.builder().user(user).name("Other Shelf").build(); + em.persist(shelf2); + + BookEntity onExcluded = createBook("On Excluded Shelf"); + onExcluded.setShelves(new HashSet<>(Set.of(shelf1))); + em.merge(onExcluded); + + BookEntity onOther = createBook("On Other Shelf"); + onOther.setShelves(new HashSet<>(Set.of(shelf2))); + em.merge(onOther); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.SHELF, RuleOperator.EXCLUDES_ALL, + List.of(String.valueOf(shelf1.getId())))); + assertThat(ids).contains(onOther.getId()); + assertThat(ids).doesNotContain(onExcluded.getId()); + } + } + + @Nested + class SubtitleFieldTests { + @Test + void contains_matchesSubtitleSubstring() { + BookEntity with = createBook("Book With Subtitle"); + with.getMetadata().setSubtitle("A Journey Through Time"); + em.merge(with.getMetadata()); + + BookEntity without = createBook("Book Without Match"); + without.getMetadata().setSubtitle("Cooking Adventures"); + em.merge(without.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.SUBTITLE, RuleOperator.CONTAINS, "journey")); + assertThat(ids).contains(with.getId()); + assertThat(ids).doesNotContain(without.getId()); + } + + @Test + void equals_caseInsensitive() { + BookEntity book = createBook("Some Book"); + book.getMetadata().setSubtitle("The Complete Guide"); + em.merge(book.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.SUBTITLE, RuleOperator.EQUALS, "the complete guide")); + assertThat(ids).contains(book.getId()); + } + + @Test + void isEmpty_matchesNullSubtitle() { + BookEntity noSub = createBook("No Subtitle"); + + BookEntity withSub = createBook("With Subtitle"); + withSub.getMetadata().setSubtitle("Has Subtitle"); + em.merge(withSub.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.SUBTITLE, RuleOperator.IS_EMPTY, null)); + assertThat(ids).contains(noSub.getId()); + assertThat(ids).doesNotContain(withSub.getId()); + } + } + + @Nested + class DescriptionFieldTests { + @Test + void contains_matchesDescriptionSubstring() { + BookEntity match = createBook("Matching Book"); + match.getMetadata().setDescription("An epic tale of adventure and mystery"); + em.merge(match.getMetadata()); + + BookEntity noMatch = createBook("Non Matching"); + noMatch.getMetadata().setDescription("A cookbook for beginners"); + em.merge(noMatch.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.DESCRIPTION, RuleOperator.CONTAINS, "adventure")); + assertThat(ids).contains(match.getId()); + assertThat(ids).doesNotContain(noMatch.getId()); + } + + @Test + void doesNotContain_excludesDescriptionSubstring() { + BookEntity scifi = createBook("Sci-Fi Book"); + scifi.getMetadata().setDescription("A story about space exploration"); + em.merge(scifi.getMetadata()); + + BookEntity romance = createBook("Romance Book"); + romance.getMetadata().setDescription("A love story set in Paris"); + em.merge(romance.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.DESCRIPTION, RuleOperator.DOES_NOT_CONTAIN, "space")); + assertThat(ids).contains(romance.getId()); + assertThat(ids).doesNotContain(scifi.getId()); + } + } + + @Nested + class PublisherFieldTests { + @Test + void equals_matchesPublisher() { + BookEntity penguin = createBook("Penguin Book"); + penguin.getMetadata().setPublisher("Penguin Random House"); + em.merge(penguin.getMetadata()); + + BookEntity harper = createBook("Harper Book"); + harper.getMetadata().setPublisher("HarperCollins"); + em.merge(harper.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.PUBLISHER, RuleOperator.EQUALS, "penguin random house")); + assertThat(ids).contains(penguin.getId()); + assertThat(ids).doesNotContain(harper.getId()); + } + + @Test + void startsWith_matchesPublisherPrefix() { + BookEntity penguin = createBook("Penguin Book"); + penguin.getMetadata().setPublisher("Penguin Random House"); + em.merge(penguin.getMetadata()); + + BookEntity harper = createBook("Harper Book"); + harper.getMetadata().setPublisher("HarperCollins"); + em.merge(harper.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.PUBLISHER, RuleOperator.STARTS_WITH, "penguin")); + assertThat(ids).contains(penguin.getId()); + assertThat(ids).doesNotContain(harper.getId()); + } + + @Test + void contains_matchesPublisherSubstring() { + BookEntity book = createBook("Random House Book"); + book.getMetadata().setPublisher("Penguin Random House"); + em.merge(book.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.PUBLISHER, RuleOperator.CONTAINS, "random")); + assertThat(ids).contains(book.getId()); + } + } + + @Nested + class LanguageFieldTests { + @Test + void equals_matchesLanguage() { + BookEntity english = createBook("English Book"); + english.getMetadata().setLanguage("en"); + em.merge(english.getMetadata()); + + BookEntity french = createBook("French Book"); + french.getMetadata().setLanguage("fr"); + em.merge(french.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.LANGUAGE, RuleOperator.EQUALS, "en")); + assertThat(ids).contains(english.getId()); + assertThat(ids).doesNotContain(french.getId()); + } + + @Test + void notEquals_excludesLanguage() { + BookEntity english = createBook("English Book"); + english.getMetadata().setLanguage("en"); + em.merge(english.getMetadata()); + + BookEntity french = createBook("French Book"); + french.getMetadata().setLanguage("fr"); + em.merge(french.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.LANGUAGE, RuleOperator.NOT_EQUALS, "en")); + assertThat(ids).contains(french.getId()); + assertThat(ids).doesNotContain(english.getId()); + } + } + + @Nested + class NarratorFieldTests { + @Test + void contains_matchesNarratorName() { + BookEntity book1 = createBook("Narrated Book"); + book1.getMetadata().setNarrator("Stephen Fry"); + em.merge(book1.getMetadata()); + + BookEntity book2 = createBook("Other Narrator"); + book2.getMetadata().setNarrator("Jim Dale"); + em.merge(book2.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.NARRATOR, RuleOperator.CONTAINS, "fry")); + assertThat(ids).contains(book1.getId()); + assertThat(ids).doesNotContain(book2.getId()); + } + + @Test + void equals_caseInsensitive() { + BookEntity book = createBook("Narrated Book"); + book.getMetadata().setNarrator("Stephen Fry"); + em.merge(book.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.NARRATOR, RuleOperator.EQUALS, "stephen fry")); + assertThat(ids).contains(book.getId()); + } + } + + @Nested + class IsbnFieldTests { + @Test + void isbn13_equals_matchesExact() { + BookEntity book = createBook("ISBN Book"); + book.getMetadata().setIsbn13("9781234567890"); + em.merge(book.getMetadata()); + + BookEntity other = createBook("Other ISBN"); + other.getMetadata().setIsbn13("9789876543210"); + em.merge(other.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.ISBN13, RuleOperator.EQUALS, "9781234567890")); + assertThat(ids).contains(book.getId()); + assertThat(ids).doesNotContain(other.getId()); + } + + @Test + void isbn10_contains_matchesSubstring() { + BookEntity book = createBook("ISBN10 Book"); + book.getMetadata().setIsbn10("0123456789"); + em.merge(book.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.ISBN10, RuleOperator.CONTAINS, "01234")); + assertThat(ids).contains(book.getId()); + } + } + + @Nested + class ContentRatingFieldTests { + @Test + void equals_matchesContentRating() { + BookEntity mature = createBook("Mature Book"); + mature.getMetadata().setContentRating("MATURE"); + em.merge(mature.getMetadata()); + + BookEntity teen = createBook("Teen Book"); + teen.getMetadata().setContentRating("TEEN"); + em.merge(teen.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.CONTENT_RATING, RuleOperator.EQUALS, "mature")); + assertThat(ids).contains(mature.getId()); + assertThat(ids).doesNotContain(teen.getId()); + } + } + + @Nested + class SeriesNameFieldTests { + @Test + void contains_matchesSeriesNameSubstring() { + BookEntity hp = createBook("HP Book"); + hp.getMetadata().setSeriesName("Harry Potter"); + em.merge(hp.getMetadata()); + + BookEntity lotr = createBook("LOTR Book"); + lotr.getMetadata().setSeriesName("Lord of the Rings"); + em.merge(lotr.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.SERIES_NAME, RuleOperator.CONTAINS, "potter")); + assertThat(ids).contains(hp.getId()); + assertThat(ids).doesNotContain(lotr.getId()); + } + + @Test + void startsWith_matchesSeriesNamePrefix() { + BookEntity hp = createBook("HP Book"); + hp.getMetadata().setSeriesName("Harry Potter"); + em.merge(hp.getMetadata()); + + BookEntity lotr = createBook("LOTR Book"); + lotr.getMetadata().setSeriesName("Lord of the Rings"); + em.merge(lotr.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.SERIES_NAME, RuleOperator.STARTS_WITH, "harry")); + assertThat(ids).contains(hp.getId()); + assertThat(ids).doesNotContain(lotr.getId()); + } + + @Test + void isEmpty_matchesNoSeriesName() { + BookEntity noSeries = createBook("No Series"); + + BookEntity hasSeries = createBook("Has Series"); + hasSeries.getMetadata().setSeriesName("Some Series"); + em.merge(hasSeries.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.SERIES_NAME, RuleOperator.IS_EMPTY, null)); + assertThat(ids).contains(noSeries.getId()); + assertThat(ids).doesNotContain(hasSeries.getId()); + } + } + + @Nested + class LastReadTimeTests { + @Test + void withinLast_matchesRecentlyRead() { + BookEntity recent = createBook("Recently Read"); + UserBookProgressEntity p1 = createProgress(recent, ReadStatus.READING); + p1.setLastReadTime(Instant.now().minus(1, ChronoUnit.DAYS)); + em.merge(p1); + + BookEntity old = createBook("Read Long Ago"); + UserBookProgressEntity p2 = createProgress(old, ReadStatus.READING); + p2.setLastReadTime(Instant.now().minus(60, ChronoUnit.DAYS)); + em.merge(p2); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.LAST_READ_TIME, RuleOperator.WITHIN_LAST, 7, null, "days")); + assertThat(ids).contains(recent.getId()); + assertThat(ids).doesNotContain(old.getId()); + } + + @Test + void olderThan_matchesOldRead() { + BookEntity old = createBook("Read Long Ago"); + UserBookProgressEntity p1 = createProgress(old, ReadStatus.READING); + p1.setLastReadTime(Instant.now().minus(90, ChronoUnit.DAYS)); + em.merge(p1); + + BookEntity recent = createBook("Recently Read"); + UserBookProgressEntity p2 = createProgress(recent, ReadStatus.READING); + p2.setLastReadTime(Instant.now().minus(1, ChronoUnit.DAYS)); + em.merge(p2); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.LAST_READ_TIME, RuleOperator.OLDER_THAN, 30, null, "days")); + assertThat(ids).contains(old.getId()); + assertThat(ids).doesNotContain(recent.getId()); + } + } + + @Nested + class AddedOnRelativeDateTests { + @Test + void withinLast_weeks_matchesRecentBook() { + BookEntity recent = createBook("Recent Book"); + recent.setAddedOn(Instant.now().minus(5, java.time.temporal.ChronoUnit.DAYS)); + em.merge(recent); + + BookEntity old = createBook("Old Book"); + old.setAddedOn(Instant.now().minus(30, java.time.temporal.ChronoUnit.DAYS)); + em.merge(old); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.ADDED_ON, RuleOperator.WITHIN_LAST, 2, null, "weeks")); + assertThat(ids).contains(recent.getId()); + assertThat(ids).doesNotContain(old.getId()); + } + + @Test + void olderThan_weeks_matchesOldBook() { + BookEntity old = createBook("Old Book"); + old.setAddedOn(Instant.now().minus(30, java.time.temporal.ChronoUnit.DAYS)); + em.merge(old); + + BookEntity recent = createBook("Recent Book"); + recent.setAddedOn(Instant.now().minus(3, java.time.temporal.ChronoUnit.DAYS)); + em.merge(recent); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.ADDED_ON, RuleOperator.OLDER_THAN, 2, null, "weeks")); + assertThat(ids).contains(old.getId()); + assertThat(ids).doesNotContain(recent.getId()); + } + } + + @Nested + class PublishedDateFieldTests { + @Test + void equals_matchesExactDate() { + BookEntity book = createBook("Exact Date Book"); + book.getMetadata().setPublishedDate(LocalDate.of(2023, 6, 15)); + em.merge(book.getMetadata()); + + BookEntity other = createBook("Other Date Book"); + other.getMetadata().setPublishedDate(LocalDate.of(2020, 1, 1)); + em.merge(other.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.PUBLISHED_DATE, RuleOperator.EQUALS, "2023-06-15")); + assertThat(ids).contains(book.getId()); + assertThat(ids).doesNotContain(other.getId()); + } + + @Test + void isEmpty_matchesNullPublishedDate() { + BookEntity noDate = createBook("No Date"); + + BookEntity withDate = createBook("With Date"); + withDate.getMetadata().setPublishedDate(LocalDate.of(2023, 1, 1)); + em.merge(withDate.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.PUBLISHED_DATE, RuleOperator.IS_EMPTY, null)); + assertThat(ids).contains(noDate.getId()); + assertThat(ids).doesNotContain(withDate.getId()); + } + } + + @Nested + class CategoryFieldTests { + @Test + void contains_matchesCategorySubstring() { + BookEntity fiction = createBook("Fiction Book"); + CategoryEntity cat = CategoryEntity.builder().name("Science Fiction").build(); + em.persist(cat); + fiction.getMetadata().setCategories(new HashSet<>(Set.of(cat))); + em.merge(fiction.getMetadata()); + + BookEntity history = createBook("History Book"); + CategoryEntity cat2 = CategoryEntity.builder().name("Ancient History").build(); + em.persist(cat2); + history.getMetadata().setCategories(new HashSet<>(Set.of(cat2))); + em.merge(history.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.CATEGORIES, RuleOperator.CONTAINS, "fiction")); + assertThat(ids).contains(fiction.getId()); + assertThat(ids).doesNotContain(history.getId()); + } + + @Test + void isEmpty_matchesBookWithNoCategories() { + BookEntity noCats = createBook("No Categories"); + + BookEntity withCats = createBook("With Categories"); + CategoryEntity cat = CategoryEntity.builder().name("Fantasy FC").build(); + em.persist(cat); + withCats.getMetadata().setCategories(new HashSet<>(Set.of(cat))); + em.merge(withCats.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.CATEGORIES, RuleOperator.IS_EMPTY, null)); + assertThat(ids).contains(noCats.getId()); + assertThat(ids).doesNotContain(withCats.getId()); + } + } + + @Nested + class MoodFieldTests { + @Test + void includesAny_matchesMood() { + BookEntity darkBook = createBook("Dark Book"); + MoodEntity dark = MoodEntity.builder().name("Dark").build(); + em.persist(dark); + darkBook.getMetadata().setMoods(new HashSet<>(Set.of(dark))); + em.merge(darkBook.getMetadata()); + + BookEntity lightBook = createBook("Light Book"); + MoodEntity light = MoodEntity.builder().name("Light").build(); + em.persist(light); + lightBook.getMetadata().setMoods(new HashSet<>(Set.of(light))); + em.merge(lightBook.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.MOODS, RuleOperator.INCLUDES_ANY, List.of("Dark"))); + assertThat(ids).contains(darkBook.getId()); + assertThat(ids).doesNotContain(lightBook.getId()); + } + + @Test + void isEmpty_matchesBookWithNoMoods() { + BookEntity noMoods = createBook("No Moods"); + + BookEntity withMoods = createBook("With Moods"); + MoodEntity mood = MoodEntity.builder().name("Happy FC").build(); + em.persist(mood); + withMoods.getMetadata().setMoods(new HashSet<>(Set.of(mood))); + em.merge(withMoods.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.MOODS, RuleOperator.IS_EMPTY, null)); + assertThat(ids).contains(noMoods.getId()); + assertThat(ids).doesNotContain(withMoods.getId()); + } + } + + @Nested + class TagFieldTests { + @Test + void includesAll_matchesBookWithAllTags() { + BookEntity bookBoth = createBook("Both Tags"); + TagEntity tag1 = TagEntity.builder().name("Tag1 FC").build(); + TagEntity tag2 = TagEntity.builder().name("Tag2 FC").build(); + em.persist(tag1); + em.persist(tag2); + bookBoth.getMetadata().setTags(new HashSet<>(Set.of(tag1, tag2))); + em.merge(bookBoth.getMetadata()); + + BookEntity bookOne = createBook("One Tag"); + TagEntity tag3 = TagEntity.builder().name("Tag1 FC2").build(); + em.persist(tag3); + bookOne.getMetadata().setTags(new HashSet<>(Set.of(tag3))); + em.merge(bookOne.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.TAGS, RuleOperator.INCLUDES_ALL, List.of("Tag1 FC", "Tag2 FC"))); + assertThat(ids).contains(bookBoth.getId()); + assertThat(ids).doesNotContain(bookOne.getId()); + } + + @Test + void isEmpty_matchesBookWithNoTags() { + BookEntity noTags = createBook("No Tags"); + + BookEntity withTags = createBook("With Tags"); + TagEntity tag = TagEntity.builder().name("SomeTag FC").build(); + em.persist(tag); + withTags.getMetadata().setTags(new HashSet<>(Set.of(tag))); + em.merge(withTags.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.TAGS, RuleOperator.IS_EMPTY, null)); + assertThat(ids).contains(noTags.getId()); + assertThat(ids).doesNotContain(withTags.getId()); + } + } + + @Nested + class IsPhysicalFieldTests { + @Test + void equals_true_matchesPhysical() { + BookEntity physical = createBook("Physical Book"); + physical.setIsPhysical(true); + em.merge(physical); + + BookEntity digital = createBook("Digital Book"); + digital.setIsPhysical(false); + em.merge(digital); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.IS_PHYSICAL, RuleOperator.EQUALS, "true")); + assertThat(ids).contains(physical.getId()); + assertThat(ids).doesNotContain(digital.getId()); + } + + @Test + void notEquals_true_matchesDigital() { + BookEntity physical = createBook("Physical Book"); + physical.setIsPhysical(true); + em.merge(physical); + + BookEntity digital = createBook("Digital Book"); + digital.setIsPhysical(false); + em.merge(digital); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.IS_PHYSICAL, RuleOperator.NOT_EQUALS, "true")); + assertThat(ids).contains(digital.getId()); + assertThat(ids).doesNotContain(physical.getId()); + } + } + + @Nested + class AbridgedFieldTests { + @Test + void equals_true_matchesAbridged() { + BookEntity abridged = createBook("Abridged Book"); + abridged.getMetadata().setAbridged(true); + em.merge(abridged.getMetadata()); + + BookEntity full = createBook("Full Book"); + full.getMetadata().setAbridged(false); + em.merge(full.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.ABRIDGED, RuleOperator.EQUALS, "true")); + assertThat(ids).contains(abridged.getId()); + assertThat(ids).doesNotContain(full.getId()); + } + + @Test + void equals_false_matchesUnabridged() { + BookEntity abridged = createBook("Abridged Book"); + abridged.getMetadata().setAbridged(true); + em.merge(abridged.getMetadata()); + + BookEntity full = createBook("Full Book"); + full.getMetadata().setAbridged(false); + em.merge(full.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.ABRIDGED, RuleOperator.EQUALS, "false")); + assertThat(ids).contains(full.getId()); + assertThat(ids).doesNotContain(abridged.getId()); + } + } + + @Nested + class DateFinishedRelativeTests { + @Test + void thisPeriod_year_matchesThisYearFinished() { + BookEntity thisYear = createBook("Recently Finished"); + UserBookProgressEntity p1 = createProgress(thisYear, ReadStatus.READ); + p1.setDateFinished(Instant.now().minus(10, java.time.temporal.ChronoUnit.DAYS)); + em.merge(p1); + + BookEntity lastYear = createBook("Finished Last Year"); + UserBookProgressEntity p2 = createProgress(lastYear, ReadStatus.READ); + p2.setDateFinished(Instant.now().minus(400, java.time.temporal.ChronoUnit.DAYS)); + em.merge(p2); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.DATE_FINISHED, RuleOperator.THIS_PERIOD, "year")); + assertThat(ids).contains(thisYear.getId()); + assertThat(ids).doesNotContain(lastYear.getId()); + } + } + + @Nested + class StringEdgeCaseTests { + @Test + void contains_caseInsensitive() { + BookEntity book = createBook("The Great Gatsby"); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.TITLE, RuleOperator.CONTAINS, "GREAT")); + assertThat(ids).contains(book.getId()); + } + + @Test + void endsWith_matchesTitleSuffix() { + BookEntity book = createBook("Lord of the Rings"); + BookEntity other = createBook("Harry Potter"); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.TITLE, RuleOperator.ENDS_WITH, "rings")); + assertThat(ids).contains(book.getId()); + assertThat(ids).doesNotContain(other.getId()); + } + } +} diff --git a/booklore-api/src/test/java/org/booklore/service/BookRuleEvaluatorNumericFieldsTest.java b/booklore-api/src/test/java/org/booklore/service/BookRuleEvaluatorNumericFieldsTest.java new file mode 100644 index 000000000..97da5848d --- /dev/null +++ b/booklore-api/src/test/java/org/booklore/service/BookRuleEvaluatorNumericFieldsTest.java @@ -0,0 +1,866 @@ +package org.booklore.service; + +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import org.booklore.BookloreApplication; +import org.booklore.model.dto.*; +import org.booklore.model.entity.*; +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.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +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.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +@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:ruleeval_numeric;DB_CLOSE_DELAY=-1", + "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(BookRuleEvaluatorNumericFieldsTest.TestConfig.class) +class BookRuleEvaluatorNumericFieldsTest { + + @TestConfiguration + static class TestConfig { + @Bean("flyway") + @Primary + public org.flywaydb.core.Flyway flyway() { + return mock(org.flywaydb.core.Flyway.class); + } + + @Bean + @Primary + public TaskCronService taskCronService() { + return mock(TaskCronService.class); + } + } + + @Autowired + private BookRuleEvaluatorService evaluator; + + @Autowired + private BookRepository bookRepository; + + @PersistenceContext + private EntityManager em; + + private LibraryEntity library; + private LibraryPathEntity libraryPath; + private BookLoreUserEntity user; + + @BeforeEach + void setUp() { + library = LibraryEntity.builder().name("Test Library").icon("book").watch(false).build(); + em.persist(library); + em.flush(); + + libraryPath = LibraryPathEntity.builder().library(library).path("/test/path").build(); + em.persist(libraryPath); + em.flush(); + + user = BookLoreUserEntity.builder() + .username("testuser") + .passwordHash("hash") + .isDefaultPassword(true) + .name("Test User") + .build(); + em.persist(user); + em.flush(); + } + + private BookEntity createBook(String title) { + BookEntity book = BookEntity.builder() + .library(library) + .libraryPath(libraryPath) + .addedOn(Instant.now()) + .deleted(false) + .build(); + em.persist(book); + em.flush(); + + BookMetadataEntity metadata = BookMetadataEntity.builder() + .book(book) + .bookId(book.getId()) + .title(title) + .build(); + em.persist(metadata); + em.flush(); + + book.setMetadata(metadata); + return book; + } + + private UserBookProgressEntity createProgress(BookEntity book, ReadStatus status) { + UserBookProgressEntity progress = UserBookProgressEntity.builder() + .user(user) + .book(book) + .readStatus(status) + .build(); + em.persist(progress); + em.flush(); + return progress; + } + + private List findMatchingIds(GroupRule group) { + Specification spec = evaluator.toSpecification(group, user.getId()); + return bookRepository.findAll(spec).stream().map(BookEntity::getId).distinct().toList(); + } + + private GroupRule singleRule(RuleField field, RuleOperator operator, Object value) { + return singleRule(field, operator, value, null, null); + } + + private GroupRule singleRule(RuleField field, RuleOperator operator, Object value, Object valueStart, Object valueEnd) { + Rule rule = new Rule(); + rule.setField(field); + rule.setOperator(operator); + rule.setValue(value); + rule.setValueStart(valueStart); + rule.setValueEnd(valueEnd); + GroupRule group = new GroupRule(); + group.setJoin(JoinType.AND); + group.setRules(List.of(rule)); + return group; + } + + @Nested + class StringValueAsNumberTests { + @Test + void lessThan_withStringValue_parsesCorrectly() { + BookEntity low = createBook("Low Score"); + low.setMetadataMatchScore(30f); + em.merge(low); + + BookEntity high = createBook("High Score"); + high.setMetadataMatchScore(80f); + em.merge(high); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.METADATA_SCORE, RuleOperator.LESS_THAN, "50")); + assertThat(ids).contains(low.getId()); + assertThat(ids).doesNotContain(high.getId()); + } + + @Test + void greaterThan_withStringValue_parsesCorrectly() { + BookEntity low = createBook("Low Score"); + low.setMetadataMatchScore(30f); + em.merge(low); + + BookEntity high = createBook("High Score"); + high.setMetadataMatchScore(80f); + em.merge(high); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.METADATA_SCORE, RuleOperator.GREATER_THAN, "50")); + assertThat(ids).contains(high.getId()); + assertThat(ids).doesNotContain(low.getId()); + } + + @Test + void greaterThanEqual_withStringValue_parsesCorrectly() { + BookEntity exact = createBook("Exact Score"); + exact.setMetadataMatchScore(50f); + em.merge(exact); + + BookEntity below = createBook("Below Score"); + below.setMetadataMatchScore(49f); + em.merge(below); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.METADATA_SCORE, RuleOperator.GREATER_THAN_EQUAL_TO, "50")); + assertThat(ids).contains(exact.getId()); + assertThat(ids).doesNotContain(below.getId()); + } + + @Test + void lessThanEqual_withStringValue_parsesCorrectly() { + BookEntity exact = createBook("Exact Score"); + exact.setMetadataMatchScore(50f); + em.merge(exact); + + BookEntity above = createBook("Above Score"); + above.setMetadataMatchScore(51f); + em.merge(above); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.METADATA_SCORE, RuleOperator.LESS_THAN_EQUAL_TO, "50")); + assertThat(ids).contains(exact.getId()); + assertThat(ids).doesNotContain(above.getId()); + } + + @Test + void inBetween_withStringValues_parsesCorrectly() { + BookEntity inRange = createBook("In Range"); + inRange.setMetadataMatchScore(60f); + em.merge(inRange); + + BookEntity outOfRange = createBook("Out of Range"); + outOfRange.setMetadataMatchScore(90f); + em.merge(outOfRange); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.METADATA_SCORE, RuleOperator.IN_BETWEEN, null, "40", "70")); + assertThat(ids).contains(inRange.getId()); + assertThat(ids).doesNotContain(outOfRange.getId()); + } + + @Test + void pageCount_greaterThan_withStringValue() { + BookEntity longBook = createBook("Long Book"); + longBook.getMetadata().setPageCount(500); + em.merge(longBook.getMetadata()); + + BookEntity shortBook = createBook("Short Book"); + shortBook.getMetadata().setPageCount(100); + em.merge(shortBook.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.PAGE_COUNT, RuleOperator.GREATER_THAN, "300")); + assertThat(ids).contains(longBook.getId()); + assertThat(ids).doesNotContain(shortBook.getId()); + } + + @Test + void nonNumericStringValue_returnsAllBooks() { + BookEntity book = createBook("Any Book"); + book.setMetadataMatchScore(50f); + em.merge(book); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.METADATA_SCORE, RuleOperator.GREATER_THAN, "not_a_number")); + assertThat(ids).contains(book.getId()); + } + } + + @Nested + class MetadataScoreTests { + @Test + void greaterThan_matchesHighScore() { + BookEntity high = createBook("High Score"); + high.setMetadataMatchScore(90f); + em.merge(high); + + BookEntity low = createBook("Low Score"); + low.setMetadataMatchScore(20f); + em.merge(low); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.METADATA_SCORE, RuleOperator.GREATER_THAN, 50)); + assertThat(ids).contains(high.getId()); + assertThat(ids).doesNotContain(low.getId()); + } + + @Test + void lessThan_matchesLowScore() { + BookEntity high = createBook("High Score"); + high.setMetadataMatchScore(90f); + em.merge(high); + + BookEntity low = createBook("Low Score"); + low.setMetadataMatchScore(20f); + em.merge(low); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.METADATA_SCORE, RuleOperator.LESS_THAN, 50)); + assertThat(ids).contains(low.getId()); + assertThat(ids).doesNotContain(high.getId()); + } + + @Test + void equals_matchesExactScore() { + BookEntity exact = createBook("Exact Score"); + exact.setMetadataMatchScore(75f); + em.merge(exact); + + BookEntity other = createBook("Other Score"); + other.setMetadataMatchScore(50f); + em.merge(other); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.METADATA_SCORE, RuleOperator.EQUALS, 75)); + assertThat(ids).contains(exact.getId()); + assertThat(ids).doesNotContain(other.getId()); + } + + @Test + void inBetween_matchesScoreInRange() { + BookEntity inRange = createBook("In Range"); + inRange.setMetadataMatchScore(60f); + em.merge(inRange); + + BookEntity tooLow = createBook("Too Low"); + tooLow.setMetadataMatchScore(20f); + em.merge(tooLow); + + BookEntity tooHigh = createBook("Too High"); + tooHigh.setMetadataMatchScore(95f); + em.merge(tooHigh); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.METADATA_SCORE, RuleOperator.IN_BETWEEN, null, 40, 80)); + assertThat(ids).contains(inRange.getId()); + assertThat(ids).doesNotContain(tooLow.getId(), tooHigh.getId()); + } + + @Test + void nullScore_doesNotMatchComparison() { + BookEntity noScore = createBook("No Score"); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.METADATA_SCORE, RuleOperator.GREATER_THAN, 0)); + assertThat(ids).doesNotContain(noScore.getId()); + } + } + + @Nested + class RatingFieldTests { + @Test + void amazonRating_greaterThan() { + BookEntity highRated = createBook("High Rated"); + highRated.getMetadata().setAmazonRating(4.5); + em.merge(highRated.getMetadata()); + + BookEntity lowRated = createBook("Low Rated"); + lowRated.getMetadata().setAmazonRating(2.0); + em.merge(lowRated.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.AMAZON_RATING, RuleOperator.GREATER_THAN, 3.5)); + assertThat(ids).contains(highRated.getId()); + assertThat(ids).doesNotContain(lowRated.getId()); + } + + @Test + void goodreadsRating_lessThanEqual() { + BookEntity rated3 = createBook("Rated 3"); + rated3.getMetadata().setGoodreadsRating(3.0); + em.merge(rated3.getMetadata()); + + BookEntity rated5 = createBook("Rated 5"); + rated5.getMetadata().setGoodreadsRating(5.0); + em.merge(rated5.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.GOODREADS_RATING, RuleOperator.LESS_THAN_EQUAL_TO, 3.0)); + assertThat(ids).contains(rated3.getId()); + assertThat(ids).doesNotContain(rated5.getId()); + } + + @Test + void hardcoverRating_inBetween() { + BookEntity low = createBook("Low HC"); + low.getMetadata().setHardcoverRating(1.0); + em.merge(low.getMetadata()); + + BookEntity mid = createBook("Mid HC"); + mid.getMetadata().setHardcoverRating(3.5); + em.merge(mid.getMetadata()); + + BookEntity high = createBook("High HC"); + high.getMetadata().setHardcoverRating(5.0); + em.merge(high.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.HARDCOVER_RATING, RuleOperator.IN_BETWEEN, null, 3.0, 4.0)); + assertThat(ids).contains(mid.getId()); + assertThat(ids).doesNotContain(low.getId(), high.getId()); + } + + @Test + void amazonReviewCount_greaterThan() { + BookEntity popular = createBook("Popular"); + popular.getMetadata().setAmazonReviewCount(5000); + em.merge(popular.getMetadata()); + + BookEntity niche = createBook("Niche"); + niche.getMetadata().setAmazonReviewCount(10); + em.merge(niche.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.AMAZON_REVIEW_COUNT, RuleOperator.GREATER_THAN, 1000)); + assertThat(ids).contains(popular.getId()); + assertThat(ids).doesNotContain(niche.getId()); + } + + @Test + void goodreadsReviewCount_lessThan() { + BookEntity popular = createBook("Popular"); + popular.getMetadata().setGoodreadsReviewCount(10000); + em.merge(popular.getMetadata()); + + BookEntity obscure = createBook("Obscure"); + obscure.getMetadata().setGoodreadsReviewCount(5); + em.merge(obscure.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.GOODREADS_REVIEW_COUNT, RuleOperator.LESS_THAN, 100)); + assertThat(ids).contains(obscure.getId()); + assertThat(ids).doesNotContain(popular.getId()); + } + + @Test + void audibleRating_greaterThanWithStringValue() { + BookEntity rated = createBook("Well Rated Audiobook"); + rated.getMetadata().setAudibleRating(4.8); + em.merge(rated.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.AUDIBLE_RATING, RuleOperator.GREATER_THAN, "4.0")); + assertThat(ids).contains(rated.getId()); + } + + @Test + void lubimyczytacRating_equals() { + BookEntity rated = createBook("Lubimyczytac Book"); + rated.getMetadata().setLubimyczytacRating(4.0); + em.merge(rated.getMetadata()); + + BookEntity other = createBook("Other Rating"); + other.getMetadata().setLubimyczytacRating(3.0); + em.merge(other.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.LUBIMYCZYTAC_RATING, RuleOperator.EQUALS, 4.0)); + assertThat(ids).contains(rated.getId()); + assertThat(ids).doesNotContain(other.getId()); + } + + @Test + void ranobedbRating_lessThan() { + BookEntity low = createBook("Low Ranobe"); + low.getMetadata().setRanobedbRating(2.5); + em.merge(low.getMetadata()); + + BookEntity high = createBook("High Ranobe"); + high.getMetadata().setRanobedbRating(4.5); + em.merge(high.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.RANOBEDB_RATING, RuleOperator.LESS_THAN, 3.0)); + assertThat(ids).contains(low.getId()); + assertThat(ids).doesNotContain(high.getId()); + } + } + + @Nested + class PersonalRatingTests { + @Test + void greaterThan_matchesHighRating() { + BookEntity highRated = createBook("Loved It"); + UserBookProgressEntity p1 = createProgress(highRated, ReadStatus.READ); + p1.setPersonalRating(5); + em.merge(p1); + + BookEntity lowRated = createBook("Meh"); + UserBookProgressEntity p2 = createProgress(lowRated, ReadStatus.READ); + p2.setPersonalRating(2); + em.merge(p2); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.PERSONAL_RATING, RuleOperator.GREATER_THAN, 3)); + assertThat(ids).contains(highRated.getId()); + assertThat(ids).doesNotContain(lowRated.getId()); + } + + @Test + void equals_matchesExactRating() { + BookEntity rated4 = createBook("Rated 4"); + UserBookProgressEntity p1 = createProgress(rated4, ReadStatus.READ); + p1.setPersonalRating(4); + em.merge(p1); + + BookEntity rated2 = createBook("Rated 2"); + UserBookProgressEntity p2 = createProgress(rated2, ReadStatus.READ); + p2.setPersonalRating(2); + em.merge(p2); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.PERSONAL_RATING, RuleOperator.EQUALS, 4)); + assertThat(ids).contains(rated4.getId()); + assertThat(ids).doesNotContain(rated2.getId()); + } + + @Test + void inBetween_matchesRatingInRange() { + BookEntity rated1 = createBook("Rated 1"); + UserBookProgressEntity p1 = createProgress(rated1, ReadStatus.READ); + p1.setPersonalRating(1); + em.merge(p1); + + BookEntity rated3 = createBook("Rated 3"); + UserBookProgressEntity p2 = createProgress(rated3, ReadStatus.READ); + p2.setPersonalRating(3); + em.merge(p2); + + BookEntity rated5 = createBook("Rated 5"); + UserBookProgressEntity p3 = createProgress(rated5, ReadStatus.READ); + p3.setPersonalRating(5); + em.merge(p3); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.PERSONAL_RATING, RuleOperator.IN_BETWEEN, null, 2, 4)); + assertThat(ids).contains(rated3.getId()); + assertThat(ids).doesNotContain(rated1.getId(), rated5.getId()); + } + + @Test + void greaterThan_withStringValue_parsesCorrectly() { + BookEntity rated5 = createBook("Top Rated"); + UserBookProgressEntity p = createProgress(rated5, ReadStatus.READ); + p.setPersonalRating(5); + em.merge(p); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.PERSONAL_RATING, RuleOperator.GREATER_THAN, "3")); + assertThat(ids).contains(rated5.getId()); + } + } + + @Nested + class AgeRatingTests { + @Test + void greaterThan_matchesMatureContent() { + BookEntity mature = createBook("Mature Book"); + mature.getMetadata().setAgeRating(18); + em.merge(mature.getMetadata()); + + BookEntity kids = createBook("Kids Book"); + kids.getMetadata().setAgeRating(6); + em.merge(kids.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.AGE_RATING, RuleOperator.GREATER_THAN, 12)); + assertThat(ids).contains(mature.getId()); + assertThat(ids).doesNotContain(kids.getId()); + } + + @Test + void lessThanEqual_matchesYoungAudience() { + BookEntity teens = createBook("Teen Book"); + teens.getMetadata().setAgeRating(13); + em.merge(teens.getMetadata()); + + BookEntity adult = createBook("Adult Book"); + adult.getMetadata().setAgeRating(18); + em.merge(adult.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.AGE_RATING, RuleOperator.LESS_THAN_EQUAL_TO, 13)); + assertThat(ids).contains(teens.getId()); + assertThat(ids).doesNotContain(adult.getId()); + } + } + + @Nested + class PageCountComparisonTests { + @Test + void greaterThanEqual_matchesBoundary() { + BookEntity exact = createBook("Exact Pages"); + exact.getMetadata().setPageCount(300); + em.merge(exact.getMetadata()); + + BookEntity below = createBook("Below Pages"); + below.getMetadata().setPageCount(299); + em.merge(below.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.PAGE_COUNT, RuleOperator.GREATER_THAN_EQUAL_TO, 300)); + assertThat(ids).contains(exact.getId()); + assertThat(ids).doesNotContain(below.getId()); + } + + @Test + void lessThanEqual_matchesBoundary() { + BookEntity exact = createBook("Exact Pages"); + exact.getMetadata().setPageCount(200); + em.merge(exact.getMetadata()); + + BookEntity above = createBook("Above Pages"); + above.getMetadata().setPageCount(201); + em.merge(above.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.PAGE_COUNT, RuleOperator.LESS_THAN_EQUAL_TO, 200)); + assertThat(ids).contains(exact.getId()); + assertThat(ids).doesNotContain(above.getId()); + } + + @Test + void inBetween_matchesPageRange() { + BookEntity short_ = createBook("Short"); + short_.getMetadata().setPageCount(50); + em.merge(short_.getMetadata()); + + BookEntity medium = createBook("Medium"); + medium.getMetadata().setPageCount(250); + em.merge(medium.getMetadata()); + + BookEntity long_ = createBook("Long"); + long_.getMetadata().setPageCount(800); + em.merge(long_.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.PAGE_COUNT, RuleOperator.IN_BETWEEN, null, 100, 500)); + assertThat(ids).contains(medium.getId()); + assertThat(ids).doesNotContain(short_.getId(), long_.getId()); + } + } + + @Nested + class SeriesNumberTests { + @Test + void greaterThan_matchesHighSeriesNumber() { + BookEntity book1 = createBook("Book 1"); + book1.getMetadata().setSeriesName("Test Series"); + book1.getMetadata().setSeriesNumber(1f); + em.merge(book1.getMetadata()); + + BookEntity book5 = createBook("Book 5"); + book5.getMetadata().setSeriesName("Test Series"); + book5.getMetadata().setSeriesNumber(5f); + em.merge(book5.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.SERIES_NUMBER, RuleOperator.GREATER_THAN, 3)); + assertThat(ids).contains(book5.getId()); + assertThat(ids).doesNotContain(book1.getId()); + } + + @Test + void equals_matchesExactSeriesNumber() { + BookEntity book2 = createBook("Book 2"); + book2.getMetadata().setSeriesName("Test Series"); + book2.getMetadata().setSeriesNumber(2f); + em.merge(book2.getMetadata()); + + BookEntity book3 = createBook("Book 3"); + book3.getMetadata().setSeriesName("Test Series"); + book3.getMetadata().setSeriesNumber(3f); + em.merge(book3.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.SERIES_NUMBER, RuleOperator.EQUALS, 2)); + assertThat(ids).contains(book2.getId()); + assertThat(ids).doesNotContain(book3.getId()); + } + } + + @Nested + class AudiobookDurationTests { + @Test + void greaterThan_matchesLongAudiobook() { + BookEntity longBook = createBook("Long Audiobook"); + BookFileEntity longFile = BookFileEntity.builder() + .book(longBook) + .fileName("long.m4b") + .fileSubPath("") + .isBookFormat(true) + .bookType(BookFileType.AUDIOBOOK) + .durationSeconds(36000L) + .build(); + em.persist(longFile); + + BookEntity shortBook = createBook("Short Audiobook"); + BookFileEntity shortFile = BookFileEntity.builder() + .book(shortBook) + .fileName("short.m4b") + .fileSubPath("") + .isBookFormat(true) + .bookType(BookFileType.AUDIOBOOK) + .durationSeconds(1800L) + .build(); + em.persist(shortFile); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.AUDIOBOOK_DURATION, RuleOperator.GREATER_THAN, 7200)); + assertThat(ids).contains(longBook.getId()); + assertThat(ids).doesNotContain(shortBook.getId()); + } + + @Test + void lessThan_matchesShortAudiobook() { + BookEntity longBook = createBook("Long Audiobook"); + BookFileEntity longFile = BookFileEntity.builder() + .book(longBook) + .fileName("long2.m4b") + .fileSubPath("") + .isBookFormat(true) + .bookType(BookFileType.AUDIOBOOK) + .durationSeconds(36000L) + .build(); + em.persist(longFile); + + BookEntity shortBook = createBook("Short Audiobook"); + BookFileEntity shortFile = BookFileEntity.builder() + .book(shortBook) + .fileName("short2.m4b") + .fileSubPath("") + .isBookFormat(true) + .bookType(BookFileType.AUDIOBOOK) + .durationSeconds(1800L) + .build(); + em.persist(shortFile); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.AUDIOBOOK_DURATION, RuleOperator.LESS_THAN, 3600)); + assertThat(ids).contains(shortBook.getId()); + assertThat(ids).doesNotContain(longBook.getId()); + } + + @Test + void inBetween_matchesMidLengthAudiobook() { + BookEntity shortBook = createBook("Short"); + BookFileEntity sf = BookFileEntity.builder() + .book(shortBook).fileName("s.m4b").fileSubPath("") + .isBookFormat(true).bookType(BookFileType.AUDIOBOOK) + .durationSeconds(600L).build(); + em.persist(sf); + + BookEntity midBook = createBook("Medium"); + BookFileEntity mf = BookFileEntity.builder() + .book(midBook).fileName("m.m4b").fileSubPath("") + .isBookFormat(true).bookType(BookFileType.AUDIOBOOK) + .durationSeconds(7200L).build(); + em.persist(mf); + + BookEntity longBook = createBook("Long"); + BookFileEntity lf = BookFileEntity.builder() + .book(longBook).fileName("l.m4b").fileSubPath("") + .isBookFormat(true).bookType(BookFileType.AUDIOBOOK) + .durationSeconds(72000L).build(); + em.persist(lf); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.AUDIOBOOK_DURATION, RuleOperator.IN_BETWEEN, null, 3600, 36000)); + assertThat(ids).contains(midBook.getId()); + assertThat(ids).doesNotContain(shortBook.getId(), longBook.getId()); + } + } + + @Nested + class HardcoverReviewCountTests { + @Test + void greaterThanEqual_matchesBoundary() { + BookEntity exact = createBook("Exact Reviews"); + exact.getMetadata().setHardcoverReviewCount(100); + em.merge(exact.getMetadata()); + + BookEntity below = createBook("Below Reviews"); + below.getMetadata().setHardcoverReviewCount(99); + em.merge(below.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.HARDCOVER_REVIEW_COUNT, RuleOperator.GREATER_THAN_EQUAL_TO, 100)); + assertThat(ids).contains(exact.getId()); + assertThat(ids).doesNotContain(below.getId()); + } + } + + @Nested + class AudibleReviewCountTests { + @Test + void lessThanEqual_matchesLowCount() { + BookEntity few = createBook("Few Reviews"); + few.getMetadata().setAudibleReviewCount(10); + em.merge(few.getMetadata()); + + BookEntity many = createBook("Many Reviews"); + many.getMetadata().setAudibleReviewCount(5000); + em.merge(many.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.AUDIBLE_REVIEW_COUNT, RuleOperator.LESS_THAN_EQUAL_TO, 50)); + assertThat(ids).contains(few.getId()); + assertThat(ids).doesNotContain(many.getId()); + } + } + + @Nested + class SeriesTotalTests { + @Test + void greaterThan_matchesLongSeries() { + BookEntity longSeries = createBook("Long Series Book"); + longSeries.getMetadata().setSeriesName("Long Series"); + longSeries.getMetadata().setSeriesTotal(20); + em.merge(longSeries.getMetadata()); + + BookEntity shortSeries = createBook("Short Series Book"); + shortSeries.getMetadata().setSeriesName("Short Series"); + shortSeries.getMetadata().setSeriesTotal(3); + em.merge(shortSeries.getMetadata()); + em.flush(); + em.clear(); + + List ids = findMatchingIds(singleRule(RuleField.SERIES_TOTAL, RuleOperator.GREATER_THAN, 10)); + assertThat(ids).contains(longSeries.getId()); + assertThat(ids).doesNotContain(shortSeries.getId()); + } + } +}