test(db): 测试改用真实 MySQL,方言差异不再漏到生产
生产是 MySQL 8、测试是 SQLite,两者的方言差异在本地完全测不出来。今天为此 付出了两次代价: 1. `ORDER BY ck_checked_at ASC NULLS FIRST` 在 SQLite 上完全正常,本地 258 条 全绿,一部署到生产第一次巡检就 1064 语法错误(MySQL 不支持 NULLS FIRST); 2. P1b 自动重登的结算复用调度器事务读取,在 SQLite 下看不出问题,但在 MySQL 的 REPEATABLE READ 下读到的是批次开始前的快照 —— 10 条实际成功的重登全部被记成 失败。SQLite 的读一致性与 MySQL 不同,这类问题跑一万遍也复现不出来。 改动: - 新增 tests/support/db.py:测试专用引擎/会话工具,连接串从 .env 读取, 默认指向独立的 douyu_login_test 库; - 新增 tests/conftest.py:会话级建好表结构,每个用例前后清空所有表做隔离; - 根 conftest.py 接管连接串设置:它在 pytest 收集阶段最先执行,在这里把 DATABASE_URL 指向测试库,应用模块首次 import 拿到就是 MySQL,不依赖任何 import 顺序(原先这里是 sqlite:// 兜底,改造后会变成「先建 SQLite engine 再打补丁换成 MySQL」,顺序一变就静默跑错库); - 21 个测试文件的 setup 样板统一改用共享测试引擎; - 两个迁移测试改为在临时库 douyu_login_mig_<随机> 上跑完整 alembic upgrade head, 跑完 drop —— 迁移脚本本身也终于在 MySQL 上被验证; - dev.sh 与 README 的过时说明一并更新(原先写着「不需要 MySQL / .env 配置」; 「测试各自建 SQLite 内存库」)。 安全与易用: - 测试库名与开发库同名时**直接拒绝运行**(clear_tables 会 DELETE 所有表, 一旦 TEST_MYSQL_DATABASE 被指到 douyu_login 就是数据灾难); - 连不上 MySQL 时给出可操作提示(先 ./dev.sh 起库 / 用 TEST_MYSQL_DATABASE 覆盖), 而不是抛一段 SQLAlchemy 原始堆栈。 验收: - 全量 301 条通过,连跑两次结果一致(隔离有效),耗时约 12.5 秒(原 SQLite 约 3.6 秒); - 单文件独立运行通过(不依赖全量执行顺序); - `grep -rn sqlite tests/ conftest.py` 已无实际用法; - **方言确实生效**:临时把一条查询改回 `NULLS FIRST`,13 条测试立刻变红(含运行期 失败),还原即恢复;这条由 test_generated_sql_is_mysql_compatible 长期守着。 代价(已在 README 与规划附录 C.2 记明):跑测试前必须先有 MySQL,pre-push 钩子 同理;CI 需要 service container。
This commit is contained in:
+55
-47
@@ -1,22 +1,26 @@
|
||||
"""Alembic 迁移链冒烟测试(不依赖真实 MySQL)。
|
||||
"""Alembic 迁移链冒烟测试(在真实 MySQL 临时库上执行)。
|
||||
|
||||
覆盖三件事:
|
||||
1. 链完整性:只有一个头版本、头与最新迁移一致、每个修订的
|
||||
down_revision 都能回溯到根(无悬挂引用、无分叉链)。
|
||||
2. 全部迁移脚本可编译:防止迁移文件被改坏后部署流程才暴露。
|
||||
3. 空库整链执行:迁移脚本自带方言防护(MySQL 专属 DDL 有 _is_mysql()
|
||||
之类分支),整条链可在 SQLite 上真实执行 `upgrade head`,随后校验
|
||||
表/列/索引与 Base.metadata 模型元数据对齐(模型要求的不允许缺失),
|
||||
3. 空库整链执行:迁移脚本在真实 MySQL 临时库上执行 `upgrade head`,
|
||||
随后校验表/列/索引与 Base.metadata 模型元数据对齐(模型要求的不允许缺失),
|
||||
并确认迁移新增的复合查询索引确实落库。
|
||||
"""
|
||||
|
||||
import tempfile
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote_plus
|
||||
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
from alembic.script import ScriptDirectory
|
||||
from sqlalchemy import create_engine, inspect
|
||||
from sqlalchemy import create_engine, inspect, text
|
||||
|
||||
import web.backend.database as database_module
|
||||
from tests.support.db import get_mysql_credentials, get_test_engine
|
||||
from web.backend.database import Base
|
||||
|
||||
TESTS_DIR = Path(__file__).resolve().parent
|
||||
PROJECT_ROOT = TESTS_DIR.parent
|
||||
@@ -66,52 +70,56 @@ class TestMigrationSmoke:
|
||||
source = path.read_text(encoding="utf-8")
|
||||
compile(source, str(path), "exec") # 语法/缩进等编译错误会在此抛出
|
||||
|
||||
def test_full_chain_applies_on_fresh_sqlite_and_matches_models(self):
|
||||
def test_full_chain_applies_on_fresh_mysql_and_matches_models(self):
|
||||
"""空库执行整条迁移链,校验表/列/索引与模型元数据对齐。"""
|
||||
import web.backend.database as database_module
|
||||
from web.backend.database import Base
|
||||
creds = get_mysql_credentials()
|
||||
mig_db = f"douyu_login_mig_{secrets.token_hex(4)}"
|
||||
mig_url = f"mysql+pymysql://{quote_plus(creds['user'])}:{quote_plus(creds['password'])}@{creds['host']}:{creds['port']}/{mig_db}?charset=utf8mb4"
|
||||
|
||||
admin_engine = get_test_engine()
|
||||
with admin_engine.begin() as conn:
|
||||
conn.execute(
|
||||
text(
|
||||
f"CREATE DATABASE `{mig_db}` CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;"
|
||||
)
|
||||
)
|
||||
|
||||
original_url = database_module.DATABASE_URL
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db_path = Path(tmp) / "migrate.db"
|
||||
try:
|
||||
# env.py 会用模块级 DATABASE_URL 覆盖配置里的 sqlalchemy.url。
|
||||
database_module.DATABASE_URL = f"sqlite:///{db_path}"
|
||||
command.upgrade(_migration_config(), "head")
|
||||
try:
|
||||
database_module.DATABASE_URL = mig_url
|
||||
cfg = _migration_config()
|
||||
cfg.set_main_option("sqlalchemy.url", mig_url)
|
||||
command.upgrade(cfg, "head")
|
||||
|
||||
inspector = inspect(create_engine(f"sqlite:///{db_path}"))
|
||||
db_tables = set(inspector.get_table_names())
|
||||
assert db_tables
|
||||
inspector = inspect(create_engine(mig_url))
|
||||
db_tables = set(inspector.get_table_names())
|
||||
assert db_tables
|
||||
|
||||
model_tables = Base.metadata.tables
|
||||
missing_tables = set(model_tables) - db_tables
|
||||
assert not missing_tables
|
||||
model_tables = Base.metadata.tables
|
||||
missing_tables = set(model_tables) - db_tables
|
||||
assert not missing_tables
|
||||
|
||||
all_db_indexes = set()
|
||||
for name, table in model_tables.items():
|
||||
db_columns = {
|
||||
column["name"] for column in inspector.get_columns(name)
|
||||
}
|
||||
model_columns = set(table.columns.keys())
|
||||
missing_columns = model_columns - db_columns
|
||||
assert not missing_columns
|
||||
all_db_indexes = set()
|
||||
for name, table in model_tables.items():
|
||||
db_columns = {column["name"] for column in inspector.get_columns(name)}
|
||||
model_columns = set(table.columns.keys())
|
||||
missing_columns = model_columns - db_columns
|
||||
assert not missing_columns
|
||||
|
||||
db_indexes = set()
|
||||
for index in inspector.get_indexes(name):
|
||||
index_name = index["name"]
|
||||
if index_name and not index_name.startswith("sqlite_autoindex"):
|
||||
db_indexes.add(index_name)
|
||||
all_db_indexes |= db_indexes
|
||||
model_indexes = {
|
||||
index.name for index in table.indexes if index.name
|
||||
}
|
||||
missing_indexes = model_indexes - db_indexes
|
||||
assert not missing_indexes
|
||||
db_indexes = set()
|
||||
for index in inspector.get_indexes(name):
|
||||
index_name = index["name"]
|
||||
if index_name:
|
||||
db_indexes.add(index_name)
|
||||
all_db_indexes |= db_indexes
|
||||
model_indexes = {index.name for index in table.indexes if index.name}
|
||||
missing_indexes = model_indexes - db_indexes
|
||||
assert not missing_indexes
|
||||
|
||||
# 迁移新增的复合查询索引(不入模型,但应存在)。
|
||||
for index_name in EXTRA_INDEXES:
|
||||
assert index_name in all_db_indexes, (
|
||||
f"迁移链未创建索引 {index_name}"
|
||||
)
|
||||
finally:
|
||||
database_module.DATABASE_URL = original_url
|
||||
# 迁移新增的复合查询索引(不入模型,但应存在)。
|
||||
for index_name in EXTRA_INDEXES:
|
||||
assert index_name in all_db_indexes, f"迁移链未创建索引 {index_name}"
|
||||
finally:
|
||||
database_module.DATABASE_URL = original_url
|
||||
with admin_engine.begin() as conn:
|
||||
conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;"))
|
||||
|
||||
Reference in New Issue
Block a user