生产是 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。
151 lines
5.5 KiB
Python
151 lines
5.5 KiB
Python
"""虎牙多选登录:单线程、失败重试、号间间隔。"""
|
|
|
|
from unittest.mock import patch
|
|
|
|
from core.huya.app_login import HuyaAppQrAuthRequiredError
|
|
from core.huya.login import HuyaCredentialError, HuyaLoginResult
|
|
from tests.support.db import get_test_engine, make_test_session
|
|
from web.backend.models import HuyaAccount, User
|
|
from web.backend.routers.huya.login import app_password_login_selected_accounts
|
|
from web.backend.schemas import HuyaPasswordLoginSelectedRequest
|
|
|
|
SUCCESS_COOKIE = (
|
|
"udb_cred=mock_cred_123; yyuid=1199666914671; "
|
|
"udb_uid=1199666914671; username=mock_test_huya_user"
|
|
)
|
|
|
|
|
|
def _ok_result() -> HuyaLoginResult:
|
|
return HuyaLoginResult(
|
|
success=True,
|
|
cookie=SUCCESS_COOKIE,
|
|
message="App协议登录成功",
|
|
sdid="mock_sdid_123",
|
|
)
|
|
|
|
|
|
def _fail_result(
|
|
message: str = "网络超时", code: str = "LOGIN_FAILED"
|
|
) -> HuyaLoginResult:
|
|
return HuyaLoginResult(success=False, message=message, code=code)
|
|
|
|
|
|
class TestSelectedAppLoginQueue:
|
|
def setup_method(self):
|
|
self.engine = get_test_engine()
|
|
self.session = make_test_session(self.engine)
|
|
self.admin = User(username="admin", password_hash="hash", role="super_admin")
|
|
self.session.add(self.admin)
|
|
self.session.commit()
|
|
|
|
def teardown_method(self):
|
|
self.session.close()
|
|
|
|
def _add_account(self, username: str, password: str = "pw") -> HuyaAccount:
|
|
account = HuyaAccount(
|
|
username=username,
|
|
account_password=password,
|
|
cookie="",
|
|
status="password_imported",
|
|
)
|
|
self.session.add(account)
|
|
self.session.commit()
|
|
return account
|
|
|
|
def _run(self, ids: list[int], **kwargs):
|
|
req = HuyaPasswordLoginSelectedRequest(
|
|
account_ids=ids,
|
|
max_attempts=kwargs.get("max_attempts", 2),
|
|
interval_seconds=kwargs.get("interval_seconds", 8),
|
|
retry_delay_seconds=kwargs.get("retry_delay_seconds", 3),
|
|
)
|
|
return app_password_login_selected_accounts(
|
|
req=req, db=self.session, current=self.admin
|
|
)
|
|
|
|
def test_retries_then_succeeds(self):
|
|
account = self._add_account("hy_retry_ok")
|
|
with (
|
|
patch("web.backend.routers.huya.login.time.sleep") as m_sleep,
|
|
patch(
|
|
"web.backend.routers.huya.login.login_huya_app_password",
|
|
side_effect=[_fail_result(), _ok_result()],
|
|
) as m_login,
|
|
):
|
|
resp = self._run([account.id])
|
|
assert resp["count"] == 1
|
|
assert resp["failed"] == 0
|
|
assert resp["results"][0]["success"]
|
|
assert resp["results"][0]["attempts"] == 2
|
|
assert m_login.call_count == 2
|
|
m_sleep.assert_called_once_with(3)
|
|
|
|
def test_fails_twice_then_moves_on(self):
|
|
first = self._add_account("hy_fail_twice")
|
|
second = self._add_account("hy_next_ok")
|
|
with (
|
|
patch("web.backend.routers.huya.login.time.sleep") as m_sleep,
|
|
patch(
|
|
"web.backend.routers.huya.login.login_huya_app_password",
|
|
side_effect=[_fail_result(), _fail_result(), _ok_result()],
|
|
) as m_login,
|
|
):
|
|
resp = self._run(
|
|
[first.id, second.id],
|
|
interval_seconds=8,
|
|
retry_delay_seconds=3,
|
|
)
|
|
assert resp["count"] == 1
|
|
assert resp["failed"] == 1
|
|
assert resp["results"][0]["success"] is False
|
|
assert resp["results"][0]["attempts"] == 2
|
|
assert "已尝试 2 次" in resp["results"][0]["message"]
|
|
assert resp["results"][1]["success"]
|
|
assert m_login.call_count == 3
|
|
assert m_sleep.call_args_list == [((3,),), ((8,),)]
|
|
|
|
def test_qr_auth_is_not_retried(self):
|
|
account = self._add_account("hy_need_qr")
|
|
with (
|
|
patch("web.backend.routers.huya.login.time.sleep") as m_sleep,
|
|
patch(
|
|
"web.backend.routers.huya.login.login_huya_app_password",
|
|
side_effect=HuyaAppQrAuthRequiredError("要求扫码验证"),
|
|
) as m_login,
|
|
):
|
|
resp = self._run([account.id])
|
|
assert resp["failed"] == 1
|
|
assert resp["results"][0]["attempts"] == 1
|
|
assert m_login.call_count == 1
|
|
m_sleep.assert_not_called()
|
|
|
|
def test_wrong_password_is_not_retried(self):
|
|
account = self._add_account("hy_bad_pw")
|
|
with (
|
|
patch("web.backend.routers.huya.login.time.sleep") as m_sleep,
|
|
patch(
|
|
"web.backend.routers.huya.login.login_huya_app_password",
|
|
side_effect=HuyaCredentialError("账号或密码错误"),
|
|
) as m_login,
|
|
):
|
|
resp = self._run([account.id])
|
|
assert resp["failed"] == 1
|
|
assert resp["results"][0]["attempts"] == 1
|
|
assert m_login.call_count == 1
|
|
m_sleep.assert_not_called()
|
|
|
|
def test_sms_auth_result_is_not_retried(self):
|
|
account = self._add_account("hy_sms")
|
|
with (
|
|
patch("web.backend.routers.huya.login.time.sleep") as m_sleep,
|
|
patch(
|
|
"web.backend.routers.huya.login.login_huya_app_password",
|
|
return_value=_fail_result("需要短信验证", "SMS_AUTH_REQUIRED"),
|
|
) as m_login,
|
|
):
|
|
resp = self._run([account.id])
|
|
assert resp["failed"] == 1
|
|
assert resp["results"][0]["attempts"] == 1
|
|
assert m_login.call_count == 1
|
|
m_sleep.assert_not_called()
|