生产是 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。
289 lines
11 KiB
Python
289 lines
11 KiB
Python
"""斗鱼鱼翅充值渠道分流测试。"""
|
|
|
|
import asyncio
|
|
import os
|
|
from unittest.mock import ANY, AsyncMock, Mock, patch
|
|
|
|
from core.douyu import FishFinRechargeClient, FishFinRechargeConfig
|
|
from tests.support.db import get_test_engine, make_test_session
|
|
from web.backend.models import Account, AuditLog, DouyuTask, LoginTask, User
|
|
from web.backend.routers.douyu import get_recharge_channel, supplier_recharge_callback
|
|
from web.backend.services.audit_service import record_audit
|
|
from web.backend.services.douyu_runner import DouyuBatchRunner
|
|
from web.backend.services.douyu_service import ensure_douyu_config
|
|
|
|
|
|
class TestDouyuGoldRechargeChannel:
|
|
def setup_method(self):
|
|
self.engine = get_test_engine()
|
|
self.session = make_test_session(self.engine)
|
|
user = User(username="operator", password_hash="hash", role="super_admin")
|
|
self.session.add(user)
|
|
self.session.commit()
|
|
self.account = Account(
|
|
username="douyu-user",
|
|
password="password",
|
|
email="mail@example.com",
|
|
email_password="mail-password",
|
|
uid="10001",
|
|
nickname="罗炅729",
|
|
)
|
|
self.session.add(self.account)
|
|
self.session.commit()
|
|
self.task = DouyuTask(
|
|
batch_id="batch",
|
|
account_id=self.account.id,
|
|
task_type="create_gold_qr",
|
|
handbook_scope="elite",
|
|
status="running",
|
|
created_by=user.id,
|
|
)
|
|
self.session.add(self.task)
|
|
self.session.commit()
|
|
self.runner = DouyuBatchRunner(self.session, "batch", "create_gold_qr")
|
|
os.environ["FISH_FIN_RECHARGE_BASE_URL"] = "https://supplier.example"
|
|
os.environ["FISH_FIN_RECHARGE_APP_ID"] = "test-app"
|
|
os.environ["FISH_FIN_RECHARGE_APP_SECRET"] = "test-secret"
|
|
|
|
def teardown_method(self):
|
|
self.session.close()
|
|
|
|
@patch("web.backend.services.douyu_runner_gold.FishFinRechargeClient")
|
|
def test_supplier_channel_creates_order_using_nickname_and_finishes_on_success(
|
|
self, client_class
|
|
):
|
|
supplier = Mock()
|
|
supplier.create_order.return_value = {
|
|
"code": 200,
|
|
"result": {"order_status": 2, "order_id": "supplier-001"},
|
|
"sign": "not-stored",
|
|
}
|
|
client_class.return_value = supplier
|
|
config = {
|
|
"gold_recharge_channel": "supplier_api",
|
|
"gold_api_product_id": "gold-product",
|
|
"gold_api_account_template_name": "斗鱼账号",
|
|
}
|
|
|
|
self.task.result = {"payload": {"amount": 10}}
|
|
self.session.commit()
|
|
self.runner._execute_create_gold_qr(
|
|
self.session,
|
|
self.task,
|
|
self.account,
|
|
"acf_uid=10001",
|
|
config,
|
|
)
|
|
|
|
expected_order_id = self.runner._supplier_out_order_id(self.task)
|
|
supplier.create_order.assert_called_once_with(
|
|
buy_num=10,
|
|
pay_amount=ANY,
|
|
out_order_id=expected_order_id,
|
|
product_id="gold-product",
|
|
recharge_arg=[{"templateName": "斗鱼账号", "templateVal": "罗炅729"}],
|
|
order_type=0,
|
|
notify_url=ANY,
|
|
)
|
|
assert str(supplier.create_order.call_args.kwargs["pay_amount"]) == "10"
|
|
self.session.refresh(self.task)
|
|
assert self.task.status == "success"
|
|
task_result = self.task.result
|
|
assert isinstance(task_result, dict)
|
|
assert task_result["recharge_channel"] == "supplier_api"
|
|
assert task_result["supplier_order_status"] == 2
|
|
assert task_result["buy_num"] == 10
|
|
assert task_result["out_order_id"] == expected_order_id
|
|
assert task_result["recharge_account"] == "罗炅729"
|
|
assert task_result["douyu_uid"] == "10001"
|
|
assert task_result["order_id"] == "supplier-001"
|
|
assert task_result["pay_amount"] == "10"
|
|
assert "pay_url" not in task_result
|
|
assert "sign" not in task_result["supplier_order"]
|
|
|
|
@patch("web.backend.services.douyu_runner_gold.FishFinRechargeClient")
|
|
def test_supplier_channel_rejects_account_without_nickname(self, client_class):
|
|
self.account.nickname = ""
|
|
self.session.commit()
|
|
config = {
|
|
"gold_recharge_channel": "supplier_api",
|
|
"gold_api_product_id": "gold-product",
|
|
"gold_api_account_template_name": "斗鱼昵称",
|
|
}
|
|
|
|
self.runner._execute_create_gold_qr(
|
|
self.session,
|
|
self.task,
|
|
self.account,
|
|
"acf_uid=10001",
|
|
config,
|
|
)
|
|
|
|
client_class.assert_not_called()
|
|
self.session.refresh(self.task)
|
|
assert self.task.status == "failed"
|
|
assert "斗鱼昵称" in self.task.message
|
|
|
|
def test_supplier_out_order_id_reuses_persisted_value(self):
|
|
self.task.supplier_out_order_id = "DYGFHISTORICAL-001"
|
|
assert self.runner._supplier_out_order_id(self.task) == "DYGFHISTORICAL-001"
|
|
|
|
def test_recharge_channel_can_be_read_without_full_config(self):
|
|
config = ensure_douyu_config(self.session)
|
|
config.gold_recharge_channel = "supplier_api"
|
|
self.session.commit()
|
|
|
|
channel = get_recharge_channel(
|
|
db=self.session,
|
|
current=self.session.get(User, self.task.created_by),
|
|
)
|
|
|
|
assert channel == {"gold_recharge_channel": "supplier_api"}
|
|
|
|
def test_recharge_audit_detail_includes_safe_account_identity(self):
|
|
record_audit(
|
|
self.session,
|
|
self.session.get(User, self.task.created_by),
|
|
action="recharge:douyu:create",
|
|
detail={
|
|
"recharge_accounts": [
|
|
{
|
|
"username": self.account.username,
|
|
"douyu_uid": self.account.uid,
|
|
"douyu_nickname": self.account.nickname,
|
|
}
|
|
],
|
|
},
|
|
)
|
|
self.session.commit()
|
|
|
|
audit = self.session.query(AuditLog).one()
|
|
assert "douyu_uid" in audit.detail
|
|
assert "10001" in audit.detail
|
|
assert "password" not in audit.detail
|
|
|
|
@patch("web.backend.services.douyu_runner_gold.FishFinRechargeClient")
|
|
def test_supplier_channel_marks_non_200_create_response_as_failed(
|
|
self, client_class
|
|
):
|
|
supplier = Mock()
|
|
supplier.create_order.return_value = {"code": 400, "msg": "商品已下架"}
|
|
client_class.return_value = supplier
|
|
config = {
|
|
"gold_recharge_channel": "supplier_api",
|
|
"gold_api_product_id": "gold-product",
|
|
"gold_api_account_template_name": "斗鱼UID",
|
|
}
|
|
|
|
self.runner._execute_create_gold_qr(
|
|
self.session,
|
|
self.task,
|
|
self.account,
|
|
"acf_uid=10001",
|
|
config,
|
|
)
|
|
|
|
self.session.refresh(self.task)
|
|
assert self.task.status == "failed"
|
|
assert self.task.message == "商品已下架"
|
|
|
|
@patch("web.backend.services.douyu_runner.check_douyu_cookie")
|
|
@patch("web.backend.services.douyu_runner.SessionLocal")
|
|
def test_invalid_cookie_skips_activity_and_marks_relogin_required(
|
|
self, session_local, check_cookie
|
|
):
|
|
login_task = LoginTask(
|
|
batch_id="login-batch",
|
|
account_id=self.account.id,
|
|
created_by=self.task.created_by,
|
|
status="success",
|
|
cookie="acf_uid=10001",
|
|
)
|
|
self.task.status = "planned"
|
|
self.session.add(login_task)
|
|
self.session.commit()
|
|
task_id = self.task.id
|
|
login_task_id = login_task.id
|
|
session_local.return_value = self.session
|
|
check_cookie.return_value = {
|
|
"valid": False,
|
|
"message": "鱼丸接口: 未登录;等级接口: 未登录",
|
|
"fish_ball": None,
|
|
"nickname": None,
|
|
"level": None,
|
|
"checked_at": None,
|
|
}
|
|
self.runner._execute_create_gold_qr = Mock()
|
|
|
|
self.runner._execute_one(task_id, {}, 1)
|
|
|
|
self.runner._execute_create_gold_qr.assert_not_called()
|
|
verify_session = make_test_session(self.engine)
|
|
try:
|
|
task = verify_session.get(DouyuTask, task_id)
|
|
checked_login = verify_session.get(LoginTask, login_task_id)
|
|
assert task is not None
|
|
assert checked_login is not None
|
|
assert task.status == "failed"
|
|
assert "Cookie 已失效,请重新登录" in task.message
|
|
assert checked_login.ck_check_status == "invalid"
|
|
check_result = checked_login.ck_check_result
|
|
assert isinstance(check_result, dict)
|
|
assert check_result["message"] == "鱼丸接口: 未登录;等级接口: 未登录"
|
|
finally:
|
|
verify_session.close()
|
|
|
|
def test_supplier_callback_verifies_signature_and_updates_terminal_task(self):
|
|
self.task.supplier_out_order_id = f"DYGFBATCHT{self.task.id}"
|
|
self.task.result = {
|
|
"recharge_channel": "supplier_api",
|
|
"out_order_id": self.task.supplier_out_order_id,
|
|
}
|
|
self.session.commit()
|
|
client = FishFinRechargeClient(
|
|
FishFinRechargeConfig(
|
|
base_url="https://supplier.example",
|
|
app_id="test-app",
|
|
app_secret="test-secret",
|
|
)
|
|
)
|
|
payload = {
|
|
"app_id": "test-app",
|
|
"timestamp": 1786629000,
|
|
"out_order_id": self.task.supplier_out_order_id,
|
|
"order_id": "supplier-001",
|
|
"order_type": 0,
|
|
"order_status": 2,
|
|
"create_time": "2026/8/13 21:30",
|
|
}
|
|
payload["sign"] = client.sign(payload, "POST")
|
|
request = Mock()
|
|
request.json = AsyncMock(return_value=payload)
|
|
|
|
response = asyncio.run(supplier_recharge_callback(request, self.session))
|
|
|
|
assert response["code"] == 200
|
|
assert response["message"] == "success"
|
|
assert client.verify_response_sign(response, "POST")
|
|
self.session.refresh(self.task)
|
|
assert self.task.status == "success"
|
|
assert self.task.message == "供应商直充成功(异步通知)"
|
|
self.session.refresh(self.account)
|
|
assert self.account.bind_status == "gold_recharged"
|
|
task_result = self.task.result
|
|
assert isinstance(task_result, dict)
|
|
assert task_result["order_id"] == "supplier-001"
|
|
assert task_result["supplier_order_status"] == 2
|
|
audit = (
|
|
self.session.query(AuditLog)
|
|
.filter(AuditLog.action == "recharge:douyu:callback")
|
|
.one()
|
|
)
|
|
assert audit.username == "supplier"
|
|
assert audit.success
|
|
assert "sign" not in audit.detail
|
|
# 同一终态回调可重复投递,不会改写已结束任务。
|
|
asyncio.run(supplier_recharge_callback(request, self.session))
|
|
self.session.refresh(self.task)
|
|
assert self.task.status == "success"
|