test_migrations.py 4.01 KB
"""迁移的可重入性。

背景:没有版本表记录"跑到第几步",每次启动都会把 `MIGRATIONS` 整份重放一遍。
所以每一条语句都必须自己判断该不该执行:MySQL 的 DDL 是隐式提交的,
`CREATE TABLE` 没有 `IF NOT EXISTS` 的话第二次跑会报错;`DROP COLUMN` /
`DROP INDEX` 没有 `IF EXISTS`(MariaDB 才有),目标已经被删过的话直接跑会报错。
"""

from __future__ import annotations

from mcp_hive.core.db.migrations import MIGRATIONS, Conditional


def test_every_destructive_statement_is_guarded():
    """MySQL 的 DROP COLUMN / DROP INDEX 没有 IF EXISTS(MariaDB 才有),
    所以每一条都必须包在 Conditional 里,否则迁移中途失败后重跑会卡死。"""
    for name, statements in MIGRATIONS:
        for statement in statements:
            if isinstance(statement, Conditional):
                continue
            sql = statement.upper()
            assert "DROP COLUMN" not in sql, f"{name}: DROP COLUMN 必须用 Conditional 包起来"
            assert "DROP INDEX" not in sql, f"{name}: DROP INDEX 必须用 Conditional 包起来"


def test_plain_create_statements_are_idempotent():
    """裸 CREATE 必须带 IF NOT EXISTS——没有版本表兜底,每次启动都会重放整份列表。"""
    for name, statements in MIGRATIONS:
        for statement in statements:
            if isinstance(statement, Conditional):
                continue
            sql = " ".join(statement.upper().split())
            if "CREATE TABLE" in sql:
                assert "CREATE TABLE IF NOT EXISTS" in sql, f"{name}: 缺少 IF NOT EXISTS"


def test_conditional_checks_scope_to_the_current_database():
    """exists_sql 不能写死库名,否则换个库名就失效了。"""
    for _, statements in MIGRATIONS:
        for statement in statements:
            if isinstance(statement, Conditional):
                assert "DATABASE()" in statement.exists_sql


def test_migration_names_are_unique():
    names = [name for name, _ in MIGRATIONS]
    assert len(names) == len(set(names))


def test_all_tables_use_the_required_prefix():
    """约定:新建的表名必须以 mcph_ 开头。"""
    for name, statements in MIGRATIONS:
        for statement in statements:
            sql = statement.sql if isinstance(statement, Conditional) else statement
            upper = " ".join(sql.upper().split())
            if "CREATE TABLE IF NOT EXISTS" in upper:
                table = upper.split("CREATE TABLE IF NOT EXISTS")[1].split()[0].split("(")[0]
                assert table.startswith("MCPH_"), f"{name}: 表名 {table} 少了 mcph_ 前缀"


# ------------------------------------------------------------------ 循环导入


def test_every_module_can_be_imported_first():
    """任何一个模块被当成**第一个** import 时都不能炸。

    回归用:`core/config/__init__.py` 曾经 re-export 过 credentials,而 credentials
    依赖 `core.db.engine`、engine 又要从 `core.config.settings` 取配置 —— 于是
    「先 import core.db.migrations」就会撞上循环导入。平时跑不出来,
    是因为应用的导入顺序恰好绕开了它。
    """
    import pathlib as _pathlib
    import subprocess
    import sys

    root = _pathlib.Path(__file__).resolve().parents[1]
    src = root / "src"
    modules = sorted(
        ".".join(p.relative_to(src).with_suffix("").parts).removesuffix(".__init__")
        for p in (src / "mcp_hive").rglob("*.py")
        if "__pycache__" not in str(p)
    )
    assert modules, "没扫到任何模块,测试本身有问题"

    failures = []
    for module in modules:
        result = subprocess.run(
            [sys.executable, "-c", f"import sys; sys.path.insert(0, r'{src}'); import {module}"],
            capture_output=True,
            text=True,
        )
        if result.returncode != 0:
            failures.append(f"{module}: {result.stderr.strip().splitlines()[-1]}")
    joined = "; ".join(failures)
    assert not failures, f"这些模块不能作为第一个导入:{joined}"