198 lines
8.1 KiB
Python
198 lines
8.1 KiB
Python
"""推送改版回归(2026-12-03,用户三项要求):
|
|
1. 发送失败不重试,但必须记录原因
|
|
2. 每轮扫描每个用户只发一条聚合推送,正文列出本轮全部信号点
|
|
3. 每条推送带 receipt_token,客户端回执后写入 received_at(到达率统计)
|
|
"""
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
import pytest
|
|
|
|
from app.notify import push as push_mod
|
|
|
|
|
|
def _item(symbol="RB", interval="30m", dt="2026-12-03 09:30", kind="divergence", sid=1):
|
|
return {"id": sid, "signal_id": sid, "symbol": symbol, "interval": interval,
|
|
"divergence_time": dt, "kind": kind}
|
|
|
|
|
|
_BATCH = {"id": 7, "receipt_token": "tok-abcdefgh"}
|
|
|
|
|
|
# ---- 正文:列出本轮全部信号点 -------------------------------------------------------
|
|
|
|
def test_content_single_signal_keeps_kind_style():
|
|
assert push_mod.build_content([_item()]) == "【量价背离】RB · 30m · 12-03 09:30"
|
|
|
|
|
|
def test_content_multiple_lists_each_point():
|
|
items = [
|
|
_item("RB", "30m", "2026-12-03 09:30"),
|
|
_item("CU", "90m", "2026-12-03 10:00", "short_ignition", 2),
|
|
]
|
|
text = push_mod.build_content(items)
|
|
assert text.startswith("本轮 2 个信号:")
|
|
assert "量价背离 RB 30m 12-03 09:30" in text
|
|
assert "做空起爆点 CU 90m 12-03 10:00" in text
|
|
|
|
|
|
def test_content_truncates_after_three_but_states_total():
|
|
items = [_item(f"S{i}", "30m", f"2026-12-03 0{i}:30", sid=i) for i in range(1, 6)]
|
|
text = push_mod.build_content(items)
|
|
assert text.startswith("本轮 5 个信号:")
|
|
assert "等 5 个" in text
|
|
assert text.count("量价背离") == 3 # 只列前 3 个
|
|
|
|
|
|
# ---- 载荷:聚合 + 回执令牌 ---------------------------------------------------------
|
|
|
|
def test_payload_digest_carries_all_signal_ids_and_receipt():
|
|
items = [_item(sid=1), _item("CU", sid=2)]
|
|
p = push_mod.build_payload(items, ["rid1"], _BATCH)
|
|
ex = p["message"]["extras"]
|
|
assert ex["kind"] == "digest"
|
|
assert ex["signal_ids"] == "1,2"
|
|
assert ex["receipt_token"] == "tok-abcdefgh"
|
|
assert ex["batch_id"] == "7"
|
|
assert ex["summary"].startswith("本轮 2 个信号")
|
|
assert p["audience"]["registration_id"] == ["rid1"]
|
|
assert p["message"]["msg_content"] == ex["summary"]
|
|
|
|
|
|
def test_payload_single_signal_keeps_its_kind():
|
|
ex = push_mod.build_payload([_item(kind="bd_resonance")], ["r"], _BATCH)["message"]["extras"]
|
|
assert ex["kind"] == "bd_resonance"
|
|
assert ex["receipt_token"] == "tok-abcdefgh"
|
|
|
|
|
|
# ---- 失败:不重试,必须记录原因 ----------------------------------------------------
|
|
|
|
def test_http_error_records_response_body(monkeypatch):
|
|
class Resp:
|
|
status_code = 400
|
|
text = '{"error":{"code":1003,"message":"invalid parameter"}}'
|
|
|
|
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_round_push([_item()], ["r"], _BATCH)
|
|
assert status == "failed"
|
|
assert "HTTP 400" in err and "1003" in err
|
|
|
|
|
|
def test_network_exception_is_recorded(monkeypatch):
|
|
def boom(*a, **k):
|
|
raise TimeoutError("read timed out")
|
|
|
|
monkeypatch.setattr(push_mod.httpx, "post", boom)
|
|
monkeypatch.setattr(push_mod.settings, "jpush_app_key", "k")
|
|
monkeypatch.setattr(push_mod.settings, "jpush_master_secret", "s")
|
|
status, err = push_mod.send_round_push([_item()], ["r"], _BATCH)
|
|
assert status == "failed"
|
|
assert "TimeoutError" in err and "read timed out" in err
|
|
|
|
|
|
def test_missing_credentials_fail_with_reason(monkeypatch):
|
|
monkeypatch.setattr(push_mod.settings, "jpush_app_key", "")
|
|
status, err = push_mod.send_round_push([_item()], ["r"], _BATCH)
|
|
assert status == "failed" and "凭证" in err
|
|
|
|
|
|
def test_success_has_no_error(monkeypatch):
|
|
class Resp:
|
|
status_code = 200
|
|
text = ""
|
|
|
|
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")
|
|
assert push_mod.send_round_push([_item()], ["r"], _BATCH) == ("success", None)
|
|
|
|
|
|
# ---- 分发:每轮每用户一条推送 -------------------------------------------------------
|
|
|
|
@pytest.fixture()
|
|
def seeded(monkeypatch):
|
|
"""两个用户各 2 个信号、一台设备;第三个用户无设备。"""
|
|
from app import db
|
|
from app.services import dispatch
|
|
|
|
db.init_db()
|
|
# 同一临时库会被多个用例复用:先清空相关表
|
|
for t in ("notifications", "signals", "devices", "users", "push_batches", "push_log"):
|
|
db.execute(f"DELETE FROM {t}")
|
|
now = (datetime.now(timezone(timedelta(hours=8)))).strftime("%Y-%m-%d %H:%M:%S")
|
|
dt = now # 新鲜信号,不被 30 分钟闸门拦
|
|
for uid in (1, 2, 3):
|
|
db.execute(
|
|
"INSERT OR REPLACE INTO users(id, phone, password_hash, active_until, is_banned, created_at)"
|
|
" VALUES(?,?,?,?,0,?)", (uid, f"13{uid:09d}", "x", "2099-01-01", now),
|
|
)
|
|
for uid in (1, 2):
|
|
db.execute(
|
|
"INSERT INTO devices(user_id, device_id, brand, jpush_rid, rid_invalid, last_seen)"
|
|
" VALUES(?,?,?,?,0,?)", (uid, f"dev{uid}", "android", f"rid-{uid}", now),
|
|
)
|
|
sig_ids = []
|
|
for i, (sym, kind) in enumerate([("RB", "divergence"), ("CU", "short_ignition")], start=1):
|
|
db.execute(
|
|
"INSERT INTO signals(symbol, interval, divergence_time, kind, created_at)"
|
|
" VALUES(?,?,?,?,?)", (sym, "30m", dt, kind, now),
|
|
)
|
|
sig_ids.append(db.query("SELECT last_insert_rowid() AS i")[0]["i"])
|
|
for uid in (1, 2, 3):
|
|
for sid in sig_ids:
|
|
db.execute(
|
|
"INSERT INTO notifications(user_id, signal_id, created_at, push_status) VALUES(?,?,?,?)",
|
|
(uid, sid, now, "pending"),
|
|
)
|
|
calls = []
|
|
|
|
def fake_send(items, rids, batch):
|
|
calls.append({"items": items, "rids": rids, "batch": batch})
|
|
return "success", None
|
|
|
|
monkeypatch.setattr("app.notify.push.send_round_push", fake_send)
|
|
dispatch.push_pending()
|
|
return {"calls": calls, "sig_ids": sig_ids, "db": db}
|
|
|
|
|
|
def test_one_push_per_user_per_round(seeded):
|
|
"""两个有设备的用户各只有 1 次发送调用,且各含本轮全部 2 个信号。"""
|
|
calls = seeded["calls"]
|
|
assert len(calls) == 2
|
|
for c in calls:
|
|
assert len(c["items"]) == 2 # 聚合,不按信号拆多条
|
|
assert len({it["id"] for it in c["items"]}) == 2 # JOIN devices 未造成重复
|
|
|
|
|
|
def test_batch_row_and_notification_status(seeded):
|
|
db = seeded["db"]
|
|
batch = db.query("SELECT id, status, item_count, signal_ids, received_at FROM push_batches ORDER BY id")
|
|
assert len(batch) == 2
|
|
assert all(b["status"] == "success" and b["item_count"] == 2 for b in batch)
|
|
assert all(b["received_at"] is None for b in batch) # 未回执前为空
|
|
st = db.query("SELECT push_status, COUNT(*) c FROM notifications GROUP BY push_status")
|
|
status = {r["push_status"]: r["c"] for r in st}
|
|
assert status.get("success") == 4 # 1、2 号用户各 2 条
|
|
assert status.get("pending") == 2 # 3 号用户无设备,保持 pending
|
|
|
|
|
|
def test_failure_is_recorded_not_retried(seeded, monkeypatch):
|
|
from app import db
|
|
from app.services import dispatch
|
|
|
|
db.execute("UPDATE notifications SET push_status='pending'")
|
|
db.execute("DELETE FROM push_batches")
|
|
db.execute("DELETE FROM push_log")
|
|
monkeypatch.setattr(
|
|
"app.notify.push.send_round_push", lambda items, rids, batch: ("failed", "HTTP 500: boom"),
|
|
)
|
|
dispatch.push_pending()
|
|
rows = db.query("SELECT status, error FROM push_batches")
|
|
assert len(rows) == 2 and all(r["status"] == "failed" and "boom" in r["error"] for r in rows)
|
|
logs = db.query("SELECT status, error FROM push_log")
|
|
assert logs and all(r["status"] == "failed" and r["error"] for r in logs)
|
|
# 失败不重试:再跑一轮,pending 已清零,不应产生新批次
|
|
n_before = len(db.query("SELECT id FROM push_batches"))
|
|
dispatch.push_pending()
|
|
assert len(db.query("SELECT id FROM push_batches")) == n_before |