From 0dba36f3aad4fcc1bc993593f2968a6c271bb686 Mon Sep 17 00:00:00 2001 From: SlimusMinus Date: Wed, 21 Oct 2026 00:15:54 +0300 Subject: [PATCH] added tests --- .../search/PostSearchIntegrationTest.java | 198 ++++++++++++++++++ .../search/SearchSuggestIntegrationTest.java | 139 ++++++++++++ .../refound/search/SynonymExpanderTest.java | 46 ++++ 3 files changed, 383 insertions(+) create mode 100644 src/test/java/com/krylov/refound/search/PostSearchIntegrationTest.java create mode 100644 src/test/java/com/krylov/refound/search/SearchSuggestIntegrationTest.java create mode 100644 src/test/java/com/krylov/refound/search/SynonymExpanderTest.java diff --git a/src/test/java/com/krylov/refound/search/PostSearchIntegrationTest.java b/src/test/java/com/krylov/refound/search/PostSearchIntegrationTest.java new file mode 100644 index 0000000..e368dbf --- /dev/null +++ b/src/test/java/com/krylov/refound/search/PostSearchIntegrationTest.java @@ -0,0 +1,198 @@ +package com.krylov.refound.search; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.krylov.refound.enums.PostCategory; +import com.krylov.refound.enums.PostStatus; +import com.krylov.refound.enums.PostType; +import java.sql.Connection; +import java.sql.DriverManager; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import liquibase.Liquibase; +import liquibase.database.DatabaseFactory; +import liquibase.database.jvm.JdbcConnection; +import liquibase.resource.ClassLoaderResourceAccessor; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Поиск по объявлениям на настоящем PostgreSQL: схема накатывается тем же + * changelog Liquibase, что и в приложении. + */ +@Testcontainers +class PostSearchIntegrationTest { + + @Container + static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:15"); + + private static final Set VISIBLE = EnumSet.of(PostStatus.ACTIVE, PostStatus.CLOSED); + + private static NamedParameterJdbcTemplate jdbc; + private static PostSearchService service; + private static TransactionTemplate tx; + private static final Map IDS = new java.util.HashMap<>(); + + @BeforeAll + static void setUp() throws Exception { + try (Connection connection = DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())) { + var database = DatabaseFactory.getInstance() + .findCorrectDatabaseImplementation(new JdbcConnection(connection)); + new Liquibase("db/changelog/db.changelog-master.yaml", new ClassLoaderResourceAccessor(), database) + .update(""); + } + + var dataSource = new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + jdbc = new NamedParameterJdbcTemplate(dataSource); + tx = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + + SearchProperties properties = new SearchProperties(); + properties.setSynonyms(List.of( + List.of("кот", "кошка", "котёнок"), + List.of("собака", "пёс", "щенок"))); + service = new PostSearchService(new PostSearchRepository(jdbc), properties); + + jdbc.getJdbcTemplate().update( + "insert into users (id, email, login, password) values (1, 'u@test', 'tester', 'x')"); + + post("ginger", "Потерялся рыжий кот", "Откликается на Барсик", PostType.LOSS, PostCategory.ANIMAL, "Москва", 1); + post("grey", "Найден серый кот у подъезда", "Сидит у двери", PostType.FOUND, PostCategory.ANIMAL, "Казань", 2); + post("cats", "Пропали коты", "Двое котов", PostType.LOSS, PostCategory.ANIMAL, "Москва", 3); + post("cat_f", "Убежала кошка Муся", "Трёхцветная", PostType.LOSS, PostCategory.ANIMAL, "Москва", 4); + post("kitten", "Найден котёнок", "Маленький", PostType.FOUND, PostCategory.ANIMAL, "Москва", 5); + post("which", "Сумка, который год ищу", "Кожаная сумка", PostType.LOSS, PostCategory.THING, "Москва", 6); + post("desc_cat", "Найден ошейник", "Похоже, от кота", PostType.FOUND, PostCategory.THING, "Москва", 7); + post("puppy", "Найден щенок без ошейника", "Рыжий, пушистый", PostType.FOUND, PostCategory.ANIMAL, "Москва", 8); + post("phone", "Потерян телефон Samsung", "Чёрный чехол", PostType.LOSS, PostCategory.THING, "Москва", 9); + post("bag", "Потеряна барсетка", "Чёрная, кожаная", PostType.LOSS, PostCategory.THING, "Москва", 11); + post("hidden", "Кот на модерации", "", PostType.LOSS, PostCategory.ANIMAL, "Москва", 10, PostStatus.MODERATION); + } + + @Test + void stemmingFindsWordFormsButNotOtherWordsWithSameStart() { + List ids = search("кот").getContent(); + + assertThat(ids).contains(id("ginger"), id("grey"), id("cats"), id("desc_cat")); + assertThat(ids).doesNotContain(id("which"), id("hidden")); + } + + @Test + void synonymsExpandTheQuery() { + assertThat(search("кот").getContent()).contains(id("cat_f"), id("kitten")); + assertThat(search("собака").getContent()).containsExactly(id("puppy")); + } + + @Test + void titleMatchesRankAboveDescriptionMatches() { + List ids = search("кот").getContent(); + + assertThat(ids.indexOf(id("desc_cat"))).isGreaterThan(ids.indexOf(id("ginger"))); + assertThat(ids.get(ids.size() - 1)).isEqualTo(id("desc_cat")); + } + + @Test + void websearchSyntaxAndGarbageDoNotFail() { + assertThat(search("кот -рыжий").getContent()).doesNotContain(id("ginger")).contains(id("grey")); + assertThat(search("\"серый кот\"").getContent()).containsExactly(id("grey")); + assertThat(search("кот!!! ((( & | :* '").getContent()).contains(id("ginger")); + assertThat(search("кот or телефон").getContent()).contains(id("phone"), id("ginger")); + } + + @Test + void lastWordIsSearchedAsPrefixWhileTyping() { + assertThat(search("кош").getContent()).containsExactly(id("cat_f")); + assertThat(search("потерян тел").getContent()).containsExactly(id("phone")); + } + + @Test + void prefixPrefersTitlesOverIncidentalWordsInDescriptions() { + // «Барсик» есть только в описании кота — префикс «барс» ищет то, что потеряли, а не кличку + assertThat(search("барс").getContent()).containsExactly(id("bag")); + // Полное слово по-прежнему находится и в описании + assertThat(search("барсик").getContent()).containsExactly(id("ginger")); + } + + @Test + void prefixFallsBackToDescriptionsWhenNoTitleMatches() { + assertThat(search("откл").getContent()).containsExactly(id("ginger")); + } + + @Test + void typosFallBackToTrigramSimilarity() { + assertThat(search("телефн").getContent()).containsExactly(id("phone")); + assertThat(search("ошейнк").getContent()).contains(id("desc_cat"), id("puppy")); + } + + @Test + void nothingFoundReturnsEmptyPage() { + Page page = search("холодильник"); + assertThat(page.getContent()).isEmpty(); + assertThat(page.getTotalElements()).isZero(); + } + + @Test + void filtersCombineWithSearch() { + PostFeedFilter found = PostFeedFilter.of("found", null, null); + assertThat(search("кот", found).getContent()).contains(id("grey"), id("kitten")).doesNotContain(id("ginger")); + + PostFeedFilter kazan = PostFeedFilter.of(null, null, List.of("Казань")); + assertThat(search("кот", kazan).getContent()).containsExactly(id("grey")); + + PostFeedFilter things = PostFeedFilter.of(null, List.of("Вещь"), null); + assertThat(search("кот", things).getContent()).containsExactly(id("desc_cat")); + } + + @Test + void paginationIsStableAcrossPages() { + List all = search("кот").getContent(); + List paged = new ArrayList<>(); + for (int page = 0; page < all.size(); page++) { + PageRequest request = PageRequest.of(page, 1); + Page result = tx.execute(s -> service.search("кот", PostFeedFilter.NONE, VISIBLE, request)); + assertThat(result.getTotalElements()).isEqualTo(all.size()); + paged.addAll(result.getContent()); + } + assertThat(paged).containsExactlyElementsOf(all); + } + + private static Page search(String text) { + return search(text, PostFeedFilter.NONE); + } + + private static Page search(String text, PostFeedFilter filter) { + return tx.execute(s -> service.search(text, filter, VISIBLE, PageRequest.of(0, 50))); + } + + private static long id(String key) { + return IDS.get(key); + } + + private static void post(String key, String title, String description, PostType type, PostCategory category, + String city, int ageDays) { + post(key, title, description, type, category, city, ageDays, PostStatus.ACTIVE); + } + + private static void post(String key, String title, String description, PostType type, PostCategory category, + String city, int ageDays, PostStatus status) { + Long id = jdbc.getJdbcTemplate().queryForObject(""" + insert into posts (title, description, type, category, city, status, created_at, user_id, rules_accepted) + values (?, ?, ?, ?, ?, ?, now() - make_interval(days => ?), 1, true) + returning id + """, Long.class, title, description, type.name(), category.name(), city, status.name(), ageDays); + IDS.put(key, id); + } +} diff --git a/src/test/java/com/krylov/refound/search/SearchSuggestIntegrationTest.java b/src/test/java/com/krylov/refound/search/SearchSuggestIntegrationTest.java new file mode 100644 index 0000000..2aeb922 --- /dev/null +++ b/src/test/java/com/krylov/refound/search/SearchSuggestIntegrationTest.java @@ -0,0 +1,139 @@ +package com.krylov.refound.search; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.krylov.refound.enums.PostStatus; +import java.sql.Connection; +import java.sql.DriverManager; +import liquibase.Liquibase; +import liquibase.database.DatabaseFactory; +import liquibase.database.jvm.JdbcConnection; +import liquibase.resource.ClassLoaderResourceAccessor; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Подсказки при вводе на настоящем PostgreSQL: словарь строится из заголовков + * объявлений тем же SQL, что и в приложении. + */ +@Testcontainers +class SearchSuggestIntegrationTest { + + @Container + static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:15"); + + private static NamedParameterJdbcTemplate jdbc; + private static SearchSuggestService service; + + @BeforeAll + static void setUp() throws Exception { + try (Connection connection = DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())) { + var database = DatabaseFactory.getInstance() + .findCorrectDatabaseImplementation(new JdbcConnection(connection)); + new Liquibase("db/changelog/db.changelog-master.yaml", new ClassLoaderResourceAccessor(), database) + .update(""); + } + jdbc = new NamedParameterJdbcTemplate(new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())); + service = new SearchSuggestService(new SearchWordRepository(jdbc), new SearchProperties()); + + jdbc.getJdbcTemplate().update( + "insert into users (id, email, login, password) values (1, 'u@test', 'tester', 'x')"); + } + + @BeforeEach + void cleanUp() { + jdbc.getJdbcTemplate().update("delete from posts"); + jdbc.getJdbcTemplate().update("delete from search_words"); + } + + @Test + void completesLastWordFromTitles() { + post("Потеряна барсетка", PostStatus.ACTIVE); + post("Найдена барсетка у метро", PostStatus.ACTIVE); + post("Пропал кот Барсик", PostStatus.ACTIVE); + service.rebuildDictionary(); + + // барсетка в двух объявлениях — выше барсика + assertThat(service.suggest("барс")).containsExactly("барсетка", "барсик"); + assertThat(service.suggest("черная БАРСЕ")).containsExactly("барсетка"); + } + + @Test + void skipsStopWordsNumbersHiddenPostsAndFinishedInput() { + post("Ключи для дома 2024", PostStatus.ACTIVE); + post("Барсетка на модерации", PostStatus.MODERATION); + service.rebuildDictionary(); + + assertThat(service.suggest("дл")).isEmpty(); + assertThat(service.suggest("20")).isEmpty(); + assertThat(service.suggest("бар")).isEmpty(); + // слово уже дописано — подсказывать нечего + assertThat(service.suggest("ключи")).isEmpty(); + assertThat(service.suggest("ключ ")).isEmpty(); + assertThat(service.suggest("к")).isEmpty(); + } + + @Test + void yoAndYeAreTheSameWord() { + post("Найден котёнок", PostStatus.ACTIVE); + service.rebuildDictionary(); + + assertThat(service.suggest("котен")).containsExactly("котёнок"); + assertThat(service.suggest("котё")).containsExactly("котёнок"); + } + + @Test + void popularSearchesRankHigher() { + post("Потеряна барсетка", PostStatus.ACTIVE); + post("Пропал кот Барсик", PostStatus.ACTIVE); + service.rebuildDictionary(); + + service.recordSearch("барсик"); + service.recordSearch("кот барсик"); + service.recordSearch("барсикк"); // нет в словаре — не учитывается + service.flushSearchCounts(); + + assertThat(service.suggest("барс")).containsExactly("барсик", "барсетка"); + } + + @Test + void typoFallsBackToSimilarWords() { + post("Потеряна барсетка", PostStatus.ACTIVE); + service.rebuildDictionary(); + + assertThat(service.suggest("барст")).containsExactly("барсетка"); + } + + @Test + void rebuildDropsWordsOfDeletedPostsButKeepsSearchStats() { + post("Потеряна барсетка", PostStatus.ACTIVE); + service.rebuildDictionary(); + service.recordSearch("барсетка"); + service.flushSearchCounts(); + + jdbc.getJdbcTemplate().update("delete from posts"); + service.rebuildDictionary(); + assertThat(service.suggest("барс")).isEmpty(); + + post("Найдена барсетка", PostStatus.ACTIVE); + service.rebuildDictionary(); + assertThat(service.suggest("барс")).containsExactly("барсетка"); + assertThat(jdbc.getJdbcTemplate().queryForObject( + "select search_count from search_words where norm = 'барсетка'", Long.class)).isEqualTo(1L); + } + + private static void post(String title, PostStatus status) { + jdbc.getJdbcTemplate().update(""" + insert into posts (title, description, type, category, city, status, created_at, user_id, rules_accepted) + values (?, '', 'LOSS', 'THING', 'Москва', ?, now(), 1, true) + """, title, status.name()); + } +} diff --git a/src/test/java/com/krylov/refound/search/SynonymExpanderTest.java b/src/test/java/com/krylov/refound/search/SynonymExpanderTest.java new file mode 100644 index 0000000..572abfe --- /dev/null +++ b/src/test/java/com/krylov/refound/search/SynonymExpanderTest.java @@ -0,0 +1,46 @@ +package com.krylov.refound.search; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +class SynonymExpanderTest { + + // Упрощённый «стеммер» для теста — в приложении лексемы даёт Postgres + private static final Map> STEMS = Map.of( + "кот", List.of("кот"), + "кошка", List.of("кошк"), + "собака", List.of("собак"), + "пёс", List.of("пес"), + "сотовый телефон", List.of("сотов", "телефон")); + + private final SynonymExpander expander = new SynonymExpander( + List.of(List.of("кот", "кошка"), List.of("собака", "пёс", "сотовый телефон")), + word -> STEMS.getOrDefault(word, List.of())); + + @Test + void replacesLexemeWithItsGroup() { + assertThat(expander.expand("'рыж' & 'кот'")).isEqualTo("'рыж' & ( 'кот' | 'кошк' )"); + } + + @Test + void keepsNegationAndPhraseStructure() { + assertThat(expander.expand("'кот' & !'собак'")) + .isEqualTo("( 'кот' | 'кошк' ) & !( 'собак' | 'пес' )"); + assertThat(expander.expand("'рыж' <-> 'кошк'")).isEqualTo("'рыж' <-> ( 'кот' | 'кошк' )"); + } + + @Test + void leavesPrefixLexemesAndUnknownWordsAlone() { + assertThat(expander.expand("'кот':*")).isEqualTo("'кот':*"); + assertThat(expander.expand("'ключ'")).isEqualTo("'ключ'"); + assertThat(expander.expand("")).isEmpty(); + } + + @Test + void skipsMultiWordSynonyms() { + assertThat(expander.expand("'телефон'")).isEqualTo("'телефон'"); + } +}