199 lines
9.1 KiB
Java
199 lines
9.1 KiB
Java
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<PostStatus> VISIBLE = EnumSet.of(PostStatus.ACTIVE, PostStatus.CLOSED);
|
||
|
||
private static NamedParameterJdbcTemplate jdbc;
|
||
private static PostSearchService service;
|
||
private static TransactionTemplate tx;
|
||
private static final Map<String, Long> 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<Long> 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<Long> 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<Long> 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<Long> all = search("кот").getContent();
|
||
List<Long> paged = new ArrayList<>();
|
||
for (int page = 0; page < all.size(); page++) {
|
||
PageRequest request = PageRequest.of(page, 1);
|
||
Page<Long> 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<Long> search(String text) {
|
||
return search(text, PostFeedFilter.NONE);
|
||
}
|
||
|
||
private static Page<Long> 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);
|
||
}
|
||
}
|