test_searcher.py 3.03 KB
import os
import sys
import tempfile

sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))

from app.core.db import get_connection, init_fts5_merchants


def setup_test_db(db_path):
    conn = get_connection(db_path)
    init_fts5_merchants(conn)
    cursor = conn.cursor()
    test_data = [
        ("10001", "格林赛克深圳旗舰店"),
        ("10002", "格林赛克广州分店"),
        ("10003", "岚图深圳南山塘朗门店"),
        ("10004", "波波的单店门店"),
        ("10005", "测试A&B门店"),
    ]
    cursor.executemany(
        "INSERT INTO merchants (merchantNo, name) VALUES (?, ?);",
        test_data
    )
    conn.commit()
    conn.close()


class TestSearchMerchants:
    def test_search_no_database(self, monkeypatch):
        from app.search import searcher
        monkeypatch.setattr(searcher, 'DB_PATH', "/nonexistent/test.db")
        result = searcher.search_merchants("测试")
        assert "error" in result
        assert "数据库文件不存在" in result["error"]
        assert result["query"] == "测试"

    def test_search_empty_query(self, monkeypatch):
        from app.search import searcher
        monkeypatch.setattr(searcher, 'DB_PATH', "/nonexistent/test.db")
        result = searcher.search_merchants("")
        assert result["query"] == ""
        assert result["count"] == 0

    def test_search_suffix_removal(self, tmp_path, monkeypatch):
        db_path = os.path.join(tmp_path, "test.db")
        setup_test_db(db_path)
        from app.search import searcher
        monkeypatch.setattr(searcher, 'DB_PATH', db_path)

        result = searcher.search_merchants("岚图深圳南山塘朗门店")
        assert result["count"] >= 1
        assert result["query"] == "岚图深圳南山塘朗"

    def test_search_fts5_match(self, tmp_path, monkeypatch):
        db_path = os.path.join(tmp_path, "test.db")
        setup_test_db(db_path)
        from app.search import searcher
        monkeypatch.setattr(searcher, 'DB_PATH', db_path)

        result = searcher.search_merchants("格林赛克")
        assert result["count"] >= 2
        names = [item["merchant_name"] for item in result["data"]]
        assert "格林赛克深圳旗舰店" in names
        assert "格林赛克广州分店" in names

    def test_search_like_fallback(self, tmp_path, monkeypatch):
        db_path = os.path.join(tmp_path, "test.db")
        setup_test_db(db_path)
        from app.search import searcher
        monkeypatch.setattr(searcher, 'DB_PATH', db_path)

        result = searcher.search_merchants("深圳 旗舰")
        assert result["count"] >= 1
        names = [item["merchant_name"] for item in result["data"]]
        assert "格林赛克深圳旗舰店" in names

    def test_search_limit(self, tmp_path, monkeypatch):
        db_path = os.path.join(tmp_path, "test.db")
        setup_test_db(db_path)
        from app.search import searcher
        monkeypatch.setattr(searcher, 'DB_PATH', db_path)

        result = searcher.search_merchants("门店", limit=1)
        assert result["count"] <= 1