test_syncer.py 2.33 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
from app.sync.syncer import sync_merchants, preprocess_text


class TestPreprocessText:
    def test_empty_text(self):
        assert preprocess_text(None) == ""
        assert preprocess_text("") == ""

    def test_strip_text(self):
        assert preprocess_text("  门店A  ") == "门店A"

    def test_normal_text(self):
        assert preprocess_text("格林赛克深圳旗舰店") == "格林赛克深圳旗舰店"


class TestSyncMerchants:
    def test_sync_empty_data(self, tmp_path):
        db_path = os.path.join(tmp_path, "test.db")
        conn = get_connection(db_path)
        init_fts5_merchants(conn)

        sync_merchants(conn, [])

        cursor = conn.cursor()
        cursor.execute("SELECT COUNT(*) FROM merchants")
        count = cursor.fetchone()[0]
        assert count == 0
        conn.close()

    def test_sync_merchants_deduplication(self, tmp_path):
        db_path = os.path.join(tmp_path, "test.db")
        conn = get_connection(db_path)
        init_fts5_merchants(conn)

        api_rows = [
            {"merchantId": "10001", "merchantName": "门店A"},
            {"merchantId": "10002", "merchantName": "门店B"},
            {"merchantId": "10001", "merchantName": "门店A"},
        ]

        sync_merchants(conn, api_rows)

        cursor = conn.cursor()
        cursor.execute("SELECT COUNT(*) FROM merchants")
        count = cursor.fetchone()[0]
        assert count == 2
        conn.close()

    def test_sync_data_content(self, tmp_path):
        db_path = os.path.join(tmp_path, "test.db")
        conn = get_connection(db_path)
        init_fts5_merchants(conn)

        api_rows = [
            {"merchantId": "10001", "merchantName": "格林赛克深圳旗舰店"},
            {"merchantId": "10002", "merchantName": "格林赛克广州分店"},
        ]

        sync_merchants(conn, api_rows)

        cursor = conn.cursor()
        cursor.execute(
            "SELECT merchantNo, name FROM merchants ORDER BY merchantNo"
        )
        rows = cursor.fetchall()
        assert len(rows) == 2
        assert rows[0] == ("10001", "格林赛克深圳旗舰店")
        assert rows[1] == ("10002", "格林赛克广州分店")
        conn.close()