生产是 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。
98 lines
4.3 KiB
Python
98 lines
4.3 KiB
Python
"""回归:时间列统一走 ``UTCDateTime`` —— 读出来必须带时区,写进去必须存 UTC。
|
||
|
||
背景:库里存的是 naive UTC,读出来也是裸时间,于是每一处比较/输出都要自己记得
|
||
补时区。项目里因此散了三份 ``_as_utc`` 和一堆 ``replace(tzinfo=UTC)``,还踩过一次
|
||
|
||
TypeError: can't compare offset-naive and offset-aware datetimes
|
||
|
||
(P1a 的 CK 巡检排下一轮时间时炸的)。现在把边界收在 ``UTCDateTime``:
|
||
写时 aware→UTC 裸值、naive 视为 UTC;读时一律补 UTC 时区。
|
||
|
||
这组测试盯三件事:读出来是 aware、能和 ``datetime.now(UTC)`` 直接比、写进去
|
||
落的是 UTC 而不是本地时间。
|
||
"""
|
||
|
||
from datetime import UTC, datetime, timedelta, timezone
|
||
|
||
from sqlalchemy import text
|
||
|
||
from tests.support.db import get_test_engine, make_test_session
|
||
from web.backend.database import Base, UTCDateTime
|
||
from web.backend.models import Account, AutomationRun, LoginTask, User
|
||
|
||
|
||
class TestUtcDateTime:
|
||
def setup_method(self):
|
||
self.engine = get_test_engine()
|
||
self.session = make_test_session(self.engine)
|
||
|
||
def teardown_method(self):
|
||
self.session.close()
|
||
|
||
def _row(self, started_at):
|
||
self.session.add(
|
||
AutomationRun(job_key="k", started_at=started_at, status="success")
|
||
)
|
||
self.session.commit()
|
||
return self.session.query(AutomationRun).one()
|
||
|
||
def test_read_back_is_timezone_aware(self):
|
||
row = self._row(datetime(2026, 10, 2, 12, 0, tzinfo=UTC))
|
||
assert row.started_at.tzinfo is not None
|
||
assert row.started_at.utcoffset() == timedelta(0)
|
||
|
||
def test_read_back_value_can_compare_with_now(self):
|
||
"""这条就是当初炸掉的写法:库里的时间直接和 datetime.now(UTC) 比。"""
|
||
row = self._row(datetime.now(UTC) - timedelta(minutes=1))
|
||
assert row.started_at < datetime.now(UTC) # 不再 TypeError
|
||
|
||
def test_write_converts_local_aware_to_utc(self):
|
||
"""带 +08:00 的时间要按 UTC 落库,不能把本地壁钟直接存进去。"""
|
||
local = datetime(2026, 10, 2, 20, 0, tzinfo=timezone(timedelta(hours=8)))
|
||
row = self._row(local)
|
||
assert row.started_at == datetime(2026, 10, 2, 12, 0, tzinfo=UTC)
|
||
raw = self.session.execute(
|
||
text("SELECT started_at FROM automation_runs")
|
||
).scalar()
|
||
assert str(raw).startswith("2026-10-02 12:00")
|
||
|
||
def test_naive_write_is_treated_as_utc(self):
|
||
"""库里读出来的裸值再写回去(常见于搬迁/复制)不能被当成本地时间再减 8 小时。"""
|
||
naive_utc = datetime(2026, 10, 2, 12, 0) # noqa: DTZ001 刻意构造裸 UTC
|
||
row = self._row(naive_utc)
|
||
assert row.started_at == datetime(2026, 10, 2, 12, 0, tzinfo=UTC)
|
||
|
||
def test_none_stays_none(self):
|
||
assert UTCDateTime().process_bind_param(None, None) is None
|
||
assert UTCDateTime().process_result_value(None, None) is None
|
||
|
||
def test_all_model_datetime_columns_use_utc_type(self):
|
||
"""新增时间列若忘了用 UTCDateTime,这里直接失败。"""
|
||
offenders = []
|
||
for table in Base.metadata.sorted_tables:
|
||
for column in table.columns:
|
||
if isinstance(column.type, UTCDateTime):
|
||
continue
|
||
if str(column.type).upper().startswith("DATETIME"):
|
||
offenders.append(f"{table.name}.{column.name}")
|
||
assert not offenders, f"这些时间列没用 UTCDateTime: {offenders}"
|
||
|
||
def test_login_task_attempt_at_round_trips_as_utc(self):
|
||
"""真实模型抽查:写 aware、读 aware、能直接比较。"""
|
||
user = User(username="u", password_hash="p", role="admin")
|
||
account = Account(username="a", password="p", email="e", email_password="ep")
|
||
self.session.add_all([user, account])
|
||
self.session.commit()
|
||
task = LoginTask(
|
||
batch_id="b",
|
||
account_id=account.id,
|
||
created_by=user.id,
|
||
attempt_at=datetime(2026, 10, 2, 12, 0, tzinfo=UTC),
|
||
)
|
||
self.session.add(task)
|
||
self.session.commit()
|
||
self.session.refresh(task)
|
||
assert task.attempt_at == datetime(2026, 10, 2, 12, 0, tzinfo=UTC)
|
||
# 模型侧保证 aware,所以业务代码可以直接比较
|
||
assert task.attempt_at < datetime.now(UTC)
|