155 lines
6.9 KiB
Python
155 lines
6.9 KiB
Python
"""测试信号走批次+回执、推送统计的触达状态与延迟(2026-12-03)。
|
|
|
|
用户要求:后端所有发送方式一致、每次发送及时触达、触达有明确通知。
|
|
- 测试信号与真实信号同一条链路(批次 + 回执令牌),可在统计里巡检
|
|
- 统计里 success ≠ 触达;触达以回执为准,超时未回执要一眼可见
|
|
"""
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
import pytest
|
|
|
|
from app import db
|
|
from app.routers import admin
|
|
|
|
|
|
def _bj(offset_sec: int = 0, fmt: str = "%Y-%m-%d %H:%M:%S") -> str:
|
|
return (datetime.now(timezone(timedelta(hours=8))) + timedelta(seconds=offset_sec)).strftime(fmt)
|
|
|
|
|
|
@pytest.fixture()
|
|
def clean():
|
|
db.init_db()
|
|
for t in ("notifications", "signals", "devices", "users", "push_batches", "push_log"):
|
|
db.execute(f"DELETE FROM {t}")
|
|
db.execute(
|
|
"INSERT OR REPLACE INTO users(id, phone, password_hash, active_until, is_banned, created_at)"
|
|
" VALUES(1,'1','x','2099-01-01',0,'2026-01-01')",
|
|
)
|
|
|
|
|
|
# ---- 测试信号:每台测试机一条批次,带类型标记 --------------------------------------
|
|
|
|
def test_test_signal_creates_tracked_batch_per_tester(clean, monkeypatch):
|
|
for i, (dev, rid, tester) in enumerate([("d1", "rid-A", 1), ("d2", "rid-B", 1), ("d3", "rid-OLD", 0)], 1):
|
|
db.execute(
|
|
"INSERT INTO devices(user_id, device_id, brand, jpush_rid, rid_invalid, last_seen, is_tester)"
|
|
" VALUES(1,?,?,?,0,?,?)", (dev, "android", rid, _bj(), tester),
|
|
)
|
|
calls = []
|
|
monkeypatch.setattr("app.notify.push.send_test_push",
|
|
lambda rid, batch: (calls.append(rid), ("success", None))[1])
|
|
res = admin.test_signal(admin.TestSignalIn(), None)
|
|
data = res["data"]
|
|
assert data["devices"] == 2 # 旧版设备 rid-OLD 不发
|
|
assert sorted(calls) == ["rid-A", "rid-B"]
|
|
rows = db.query("SELECT rid, push_type, status, receipt_token FROM push_batches ORDER BY rid")
|
|
assert [r["rid"] for r in rows] == ["rid-A", "rid-B"]
|
|
assert all(r["push_type"] == "test" and r["status"] == "success" and r["receipt_token"] for r in rows)
|
|
|
|
|
|
def test_test_signal_without_tester_sends_nothing(clean):
|
|
db.execute(
|
|
"INSERT INTO devices(user_id, device_id, brand, jpush_rid, rid_invalid, last_seen, is_tester)"
|
|
" VALUES(1,'d-old','android','rid-OLD',0,?,0)", (_bj(),),
|
|
)
|
|
with pytest.raises(Exception):
|
|
admin.test_signal(admin.TestSignalIn(), None)
|
|
assert db.query("SELECT COUNT(*) AS c FROM push_batches")[0]["c"] == 0
|
|
|
|
|
|
def test_test_push_failure_records_reason(monkeypatch):
|
|
from app.notify import push as push_mod
|
|
|
|
class Resp:
|
|
status_code = 400
|
|
text = '{"error":{"code":1011,"message":"cannot find user by this audience"}}'
|
|
|
|
monkeypatch.setattr(push_mod.httpx, "post", lambda *a, **k: Resp())
|
|
monkeypatch.setattr(push_mod.settings, "jpush_app_key", "k")
|
|
monkeypatch.setattr(push_mod.settings, "jpush_master_secret", "s")
|
|
status, err = push_mod.send_test_push("rid-x", {"id": 1, "receipt_token": "t"})
|
|
assert status == "failed" and "1011" in err
|
|
|
|
|
|
def test_test_push_payload_carries_receipt_token(monkeypatch):
|
|
from app.notify import push as push_mod
|
|
|
|
seen = {}
|
|
|
|
class Resp:
|
|
status_code = 200
|
|
text = ""
|
|
|
|
def capture(url, json=None, **k):
|
|
seen.update(json)
|
|
return Resp()
|
|
|
|
monkeypatch.setattr(push_mod.httpx, "post", capture)
|
|
monkeypatch.setattr(push_mod.settings, "jpush_app_key", "k")
|
|
monkeypatch.setattr(push_mod.settings, "jpush_master_secret", "s")
|
|
assert push_mod.send_test_push("rid-x", {"id": 5, "receipt_token": "tok123"}) == ("success", None)
|
|
ex = seen["message"]["extras"]
|
|
assert ex["type"] == "signal_alarm" and ex["kind"] == "test" # 走闹钟链路
|
|
assert ex["receipt_token"] == "tok123" and ex["batch_id"] == "5"
|
|
assert seen["audience"] == {"registration_id": ["rid-x"]} # 只发这一台
|
|
|
|
|
|
# ---- 统计:触达状态与延迟 ---------------------------------------------------------
|
|
|
|
def _batch(rid, sent_off, recv_off=None, status="success", ptype="signal", sig_ids="", user=1):
|
|
token = f"tok-{rid}-{sent_off}-{recv_off}-{ptype}"
|
|
db.execute(
|
|
"INSERT INTO push_batches(user_id, rid, signal_ids, item_count, status, push_type, receipt_token, sent_at, received_at)"
|
|
" VALUES(?,?,?,?,?,?,?,?,?)",
|
|
(user, rid, sig_ids, 1 if sig_ids else 0, status, ptype, token, _bj(sent_off),
|
|
_bj(recv_off) if recv_off is not None else None),
|
|
)
|
|
return db.query("SELECT id FROM push_batches WHERE receipt_token=?", (token,))[0]["id"]
|
|
|
|
|
|
def test_stats_states_received_waiting_overdue_failed(clean):
|
|
_batch("r-recv", -600, -598) # 已回执
|
|
_batch("r-wait", -10, None) # 刚发出,未满 2 分钟
|
|
_batch("r-over", -600, None) # 发出很久,无回执
|
|
_batch("r-fail", -600, None, status="failed")
|
|
d = admin.push_stats(1, None)["data"]
|
|
states = sorted(r["state"] for r in d["recent"])
|
|
assert states == ["failed", "overdue", "received", "waiting"]
|
|
assert d["total"] == 4 and d["received"] == 1 and d["overdue"] == 1 and d["failed"] == 1
|
|
assert d["rate"] == 25.0
|
|
|
|
|
|
def test_stats_backend_delay_from_bar_close(clean):
|
|
# 信号 K 线收盘 10:00,推送发出 10:01:55 → 后端延迟 115 秒
|
|
db.execute("INSERT INTO signals(symbol, interval, divergence_time, kind, created_at)"
|
|
" VALUES('RB','30m','2026-12-03 10:00','divergence','2026-12-03 10:01:40')")
|
|
sid = db.query("SELECT last_insert_rowid() AS i")[0]["i"]
|
|
_batch("r-sig", 0, None, sig_ids=str(sid))
|
|
db.execute("UPDATE push_batches SET sent_at='2026-12-03 10:01:55'")
|
|
d = admin.push_stats(1, None)["data"]
|
|
row = d["recent"][0]
|
|
assert row["send_delay"] == 115
|
|
assert d["send_avg"] == 115 and d["send_max"] == 115
|
|
|
|
|
|
def test_stats_test_batch_has_no_backend_delay(clean):
|
|
_batch("r-test", 0, 3, ptype="test")
|
|
d = admin.push_stats(1, None)["data"]
|
|
row = d["recent"][0]
|
|
assert row["push_type"] == "test" and row["send_delay"] is None
|
|
assert row["recv_delay"] == 3 and row["state"] == "received"
|
|
|
|
|
|
def test_receipt_marks_only_first_time(clean):
|
|
from app.routers import notifications
|
|
|
|
bid = _batch("r-rcpt", -30, None)
|
|
tok = db.query("SELECT receipt_token FROM push_batches WHERE id=?", (bid,))[0]["receipt_token"]
|
|
first = notifications.push_receipt(notifications.ReceiptIn(token=tok))["data"]
|
|
got = db.query("SELECT received_at FROM push_batches WHERE id=?", (bid,))[0]["received_at"]
|
|
assert first["recorded"] is True and got is not None
|
|
notifications.push_receipt(notifications.ReceiptIn(token=tok))
|
|
again = db.query("SELECT received_at FROM push_batches WHERE id=?", (bid,))[0]["received_at"]
|
|
assert again == got # 幂等:不覆盖首次回执时间
|
|
assert notifications.push_receipt(notifications.ReceiptIn(token="no-such-token-xyz"))["data"]["recorded"] is False
|