- 新事件 account.status.summary:总数/正常/异常/状态分布/异常账号清单 - 计划收尾检测 read_text(account_status) 才发,普通发布计划不刷屏 - 每日 09:30 全量汇总;ACCOUNT_STATUS_DAILY/ACCOUNT_STATUS_SUMMARY_AT 可配 - 生产企微 webhook 已订阅该事件;测试与文档同步
249 lines
12 KiB
Python
249 lines
12 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""账号库用例(名字 ↔ 哪台手机):解析 / 粘贴导入 / 按名字找设备。
|
||
|
||
场景(用户 2026-10-16 的用法):**改名字不改号** —— 40 个号全改了名、抖音号一个没变,
|
||
所以导入必须**按抖音号认同一行**,否则一改名就duplicate出一堆。
|
||
铁律一致:**临时 SQLite**,不连真机、不碰真实数据(设备池用桩)。
|
||
"""
|
||
import io
|
||
import os
|
||
import sys
|
||
import tempfile
|
||
|
||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||
_TMP = tempfile.mkdtemp(prefix="roster_test_")
|
||
os.environ['DATABASE_URL'] = 'sqlite:///' + os.path.join(_TMP, 'ac.db').replace('\\', '/')
|
||
os.environ['DATA_VIDEO_DIR'] = os.path.join(_TMP, 'videos')
|
||
os.environ['DATA_ACCOUNT_DIR'] = os.path.join(_TMP, 'accounts')
|
||
os.environ['DEPLOY_ENV'] = 'dev'
|
||
os.environ['DB_ALLOW_SQLITE_FALLBACK'] = '1'
|
||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
||
os.chdir(sys.path[0])
|
||
|
||
from flask import Flask # noqa: E402
|
||
from core.models import db, init_db, DeviceAccount, Device # noqa: E402
|
||
from core import account_folder as af # noqa: E402
|
||
from core import account_probe as ap # noqa: E402
|
||
from core import device_pool # noqa: E402
|
||
from tasks.generic import task as gt # noqa: E402
|
||
|
||
fails = []
|
||
|
||
|
||
def check(label, got, want):
|
||
ok = got == want
|
||
if not ok:
|
||
fails.append(label)
|
||
print((' ✅ ' if ok else ' ❌ ') + label + ('' if ok else '\n 得到 %r\n 期望 %r' % (got, want)))
|
||
|
||
|
||
app = Flask(__name__)
|
||
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
|
||
with app.app_context():
|
||
init_db(app)
|
||
af.init_app(app)
|
||
# 整个用例都在一个 app 上下文里:这些函数平时是从**请求上下文**里调的(web 层),
|
||
# 用例里没请求,就自己推一个(不然 db.session 会报 Working outside of application context)。
|
||
app.app_context().push()
|
||
|
||
# ==================== ① 解析粘贴的清单 ====================
|
||
print("▶ ① 解析:设备号 / 账号名 / 抖音号")
|
||
check("制表符分隔", af.parse_roster("A01\t周周逛苏州\t49057596509"),
|
||
[{"device_name": "A01", "nickname": "周周逛苏州", "douyin_id": "49057596509"}])
|
||
check("空格分隔(表格粘出来常是空格)",
|
||
af.parse_roster("A02 周周苏州周末去哪 35769022192"),
|
||
[{"device_name": "A02", "nickname": "周周苏州周末去哪", "douyin_id": "35769022192"}])
|
||
check("名字里有空格也能认(最后一个纯数字词才是抖音号)",
|
||
af.parse_roster("A03\t有牛奶面包 你吃吗?\t52189681315"),
|
||
[{"device_name": "A03", "nickname": "有牛奶面包 你吃吗?", "douyin_id": "52189681315"}])
|
||
check("没有抖音号 → 只有名字(按名字认)",
|
||
af.parse_roster("A04 老周姑苏健康闲谈"),
|
||
[{"device_name": "A04", "nickname": "老周姑苏健康闲谈", "douyin_id": ""}])
|
||
check("空行 / #注释 忽略", af.parse_roster("\n# 这是表头\n\n"), [])
|
||
check("只写了一段 → 标为认不出来",
|
||
[p.get("_bad") for p in af.parse_roster("乱七八糟一行")], ["只有一段"])
|
||
|
||
# ==================== ② 导入:按抖音号认同一行 ====================
|
||
print("▶ ② 导入:改名不改号")
|
||
r = af.import_roster("A01\t最爱吃土豆\t26828346705\nA02\t翻斗花园我最强\t68365981453")
|
||
check("首次导入:新增 2 行", (r["added"], r["updated"], r["unchanged"]), (2, 0, 0))
|
||
check("库里就是 2 行", len(af.roster_rows()), 2)
|
||
|
||
r = af.import_roster("A01\t周周苏州吃喝玩乐\t26828346705") # 同一个抖音号,改了名
|
||
check("同一个抖音号改名 → 只更新,不新增", (r["added"], r["updated"]), (0, 1))
|
||
rows = af.roster_rows()
|
||
check("名字真的换了", [x["nickname"] for x in rows if x["douyin_id"] == "26828346705"],
|
||
["周周苏州吃喝玩乐"])
|
||
check("还是 2 行(没duplicate)", len(rows), 2)
|
||
|
||
r = af.import_roster("A01\t周周苏州吃喝玩乐\t26828346705")
|
||
check("再导一遍同样的 → 没变化", (r["added"], r["updated"], r["unchanged"]), (0, 0, 1))
|
||
|
||
r = af.import_roster("A01\t周周苏州吃喝玩乐\t26828346705", dry_run=True)
|
||
check("dry_run 只算不写(unchanged 计数照给)", (r["dry_run"], r["unchanged"]), (True, 1))
|
||
r = af.import_roster("A09\t锋哥苏州探店实录\t53117759686", dry_run=True)
|
||
check("dry_run 不会真的新增", (r["added"], len(af.roster_rows())), (1, 2))
|
||
|
||
print("▶ ②b 库里多出来的:一条都不删,只列出来")
|
||
r = af.import_roster("A01\t周周苏州吃喝玩乐\t26828346705")
|
||
check("没提到的那行进 stale", [(x["device_name"], x["nickname"]) for x in r["stale"]],
|
||
[("A02", "翻斗花园我最强")])
|
||
check("…但库里还在(导入永远不删)", len(af.roster_rows()), 2)
|
||
|
||
print("▶ ②c 设备换台:同一个号挪到另一台手机上")
|
||
r = af.import_roster("A07\t周周苏州吃喝玩乐\t26828346705")
|
||
check("认得出是同一个号、只是换设备", (r["added"], r["updated"]), (0, 1))
|
||
check("设备号更新了",
|
||
[x["device_name"] for x in af.roster_rows() if x["douyin_id"] == "26828346705"], ["A07"])
|
||
|
||
print("▶ ②d 清单自己重复 / 认不出来的行")
|
||
r = af.import_roster("A01\t甲\t111\nA01\t甲\t111\nA01\t乙\t111")
|
||
check("同一个号填了几遍 → 只算一条(第一次为准)",
|
||
[(x["nickname"], x["douyin_id"]) for x in af.roster_rows() if x["douyin_id"] == "111"],
|
||
[("甲", "111")])
|
||
r = af.import_roster("一行乱七八糟")
|
||
check("认不出来的行进 bad、不写库", (len(r["bad"]), r["added"]), (1, 0))
|
||
|
||
# ==================== ③ 按名字找设备 ====================
|
||
print("▶ ③ 名字 → 哪台手机(设备池用桩)")
|
||
_orig_devs, _orig_online = device_pool.list_devices, device_pool.list_online
|
||
device_pool.list_devices = lambda: [
|
||
{"serial": "192.168.20.82:5555", "name": "A07", "model": "x"},
|
||
{"serial": "192.168.20.91:5555", "name": "A03", "model": "x"}]
|
||
device_pool.list_online = lambda: ["192.168.20.82:5555"]
|
||
try:
|
||
af.import_roster("A07\t周周苏州吃喝玩乐\t26828346705\nA03\t锋哥苏州康养探店\t75846988463\n"
|
||
"A09\t锋哥苏州探店实录\t53117759686")
|
||
rows = af.devices_for_names(["周周苏州吃喝玩乐", "锋哥苏州康养探店", "锋哥苏州探店实录", "没这个号"])
|
||
check("名字→设备→地址,顺序跟输入一致",
|
||
[(x["name"], x["device_name"], x["serial"]) for x in rows[:3]],
|
||
[("周周苏州吃喝玩乐", "A07", "192.168.20.82:5555"),
|
||
("锋哥苏州康养探店", "A03", "192.168.20.91:5555"),
|
||
("锋哥苏州探店实录", "A09", "")])
|
||
check("在线的能跑(没 reason)", rows[0]["reason"], "")
|
||
check("离线的那台 → 明确说离线(照样能定位到设备)",
|
||
("离线" in rows[1]["reason"], rows[1]["serial"]), (True, "192.168.20.91:5555"))
|
||
check("没入设备池的 → 明确说没入池", "还没入设备池" in rows[2]["reason"], True)
|
||
check("账号库里没有的名字 → 明确说没有", "账号库里没有" in rows[3]["reason"], True)
|
||
check("也能按抖音号找(用户可能只记得号)",
|
||
af.device_of_name("26828346705")["device_name"], "A07")
|
||
finally:
|
||
device_pool.list_devices, device_pool.list_online = _orig_devs, _orig_online
|
||
|
||
print("▶ ④ 删一行(只有页面点删除才走)")
|
||
row = [x for x in af.roster_rows() if x["nickname"] == "锋哥苏州探店实录"][0]
|
||
check("删得掉", af.delete_roster_row(row["id"]), True)
|
||
check("删不存在的 → False", af.delete_roster_row("nope"), False)
|
||
|
||
print("▶ ⑤ 账号状态:手动写 + 任务变量回写")
|
||
check("手动写状态", af.set_account_status("周周苏州吃喝玩乐", "账号异常"), True)
|
||
check("roster_rows 带出状态",
|
||
[x["account_status"] for x in af.roster_rows()
|
||
if x["nickname"] == "周周苏州吃喝玩乐"], ["账号异常"])
|
||
check("账号库里没有的号 → 不新建行",
|
||
af.set_account_status("没这个号", "正常"), False)
|
||
|
||
|
||
class _El:
|
||
def __init__(self, flag, text=""):
|
||
self._flag, self._text = flag, text
|
||
|
||
def wait(self, timeout=0):
|
||
return self._flag
|
||
|
||
def get_text(self, timeout=None):
|
||
return self._text
|
||
|
||
|
||
class _D:
|
||
def __init__(self, flag, text=""):
|
||
self.flag, self.text = flag, text
|
||
|
||
def xpath(self, v):
|
||
return _El(self.flag, self.text)
|
||
|
||
|
||
w = gt.GenericStepsWorker("S1", {})
|
||
w._vars["target_name"] = "周周苏州吃喝玩乐"
|
||
p = {"selector_type": "xpath", "selector_value": "//x", "var": "account_status",
|
||
"clean": "strip", "on_missing": "skip"}
|
||
w._exec_read_text(_D(True, "账号异常"), p)
|
||
db.session.expire_all()
|
||
check("任务变量 account_status 回写账号库",
|
||
DeviceAccount.query.filter_by(nickname="周周苏州吃喝玩乐").first().account_status,
|
||
"账号异常")
|
||
w._exec_read_text(_D(False, ""), p)
|
||
db.session.expire_all()
|
||
check("读不到 → 不覆盖原值(不推断成「正常」)",
|
||
DeviceAccount.query.filter_by(nickname="周周苏州吃喝玩乐").first().account_status,
|
||
"账号异常")
|
||
|
||
print("▶ ⑥ 完整昵称缓存:轮询的打码名不覆盖完整名")
|
||
db.session.add(Device(serial="A11:5555", name="A11", enabled=True))
|
||
db.session.commit()
|
||
check("广播后记住完整名", ap.remember_name("A11:5555", "锋哥苏州百业探访"), True)
|
||
check("Device 行里是完整名",
|
||
Device.query.get("A11:5555").cur_account_name, "锋哥苏州百业探访")
|
||
ap.cache_names({"A11:5555": {"name": "锋哥苏***探访"}})
|
||
db.session.expire_all()
|
||
check("匹配的打码名不覆盖完整名",
|
||
Device.query.get("A11:5555").cur_account_name, "锋哥苏州百业探访")
|
||
ap.cache_names({"A11:5555": {"name": "周周苏***探访"}})
|
||
db.session.expire_all()
|
||
check("换了号(打码名对不上)→ 更新成新探测值",
|
||
Device.query.get("A11:5555").cur_account_name, "周周苏***探访")
|
||
|
||
print("▶ ⑦ 手机手动切号:打码名按账号库还原完整昵称")
|
||
db.session.add(DeviceAccount(id="r11a", device_name="A11",
|
||
nickname="锋哥苏州百业探访", douyin_id="x1"))
|
||
db.session.commit()
|
||
ap.remember_name("A11:5555", "锋哥苏州百业探访")
|
||
check("唯一匹配 → 还原完整名",
|
||
ap.resolve_masked_name("A11:5555", "锋哥苏***探访"), "锋哥苏州百业探访")
|
||
check("对不上任何账号 → 返回空(不猜)",
|
||
ap.resolve_masked_name("A11:5555", "某某***某某"), "")
|
||
# 再加两个也能匹配同一打码名 → 用上次的完整名做 tiebreak
|
||
db.session.add_all([
|
||
DeviceAccount(id="r11b", device_name="A11", nickname="锋哥苏州甲探访", douyin_id="x2"),
|
||
DeviceAccount(id="r11c", device_name="A11", nickname="锋哥苏州乙探访", douyin_id="x3"),
|
||
])
|
||
db.session.commit()
|
||
check("多个匹配时用上次完整名 tiebreak",
|
||
ap.resolve_masked_name("A11:5555", "锋哥苏***探访"), "锋哥苏州百业探访")
|
||
row = Device.query.get("A11:5555"); row.cur_account_name = ""; db.session.commit()
|
||
check("分不清且没有历史 → 返回空",
|
||
ap.resolve_masked_name("A11:5555", "锋哥苏***探访"), "")
|
||
|
||
print("▶ ⑧ 账号状态汇总通知(事件 account.status.summary)")
|
||
with app.app_context():
|
||
r = DeviceAccount.query.filter_by(nickname="锋哥苏州百业探访").first()
|
||
if r:
|
||
r.account_status = "正常"
|
||
r2 = DeviceAccount.query.filter_by(nickname="周周苏州吃喝玩乐").first()
|
||
if r2:
|
||
r2.account_status = "账号异常"
|
||
db.session.commit()
|
||
|
||
notes = []
|
||
from core import notifier as _notifier # noqa: E402
|
||
_orig_notify = _notifier.notify
|
||
_notifier.notify = lambda ev, **kw: notes.append((ev, kw))
|
||
try:
|
||
ok = af.notify_account_status_summary(job_name="检测账号", source="计划运行")
|
||
finally:
|
||
_notifier.notify = _orig_notify
|
||
check("汇总函数返回 True", ok, True)
|
||
check("事件名", notes[0][0] if notes else "", "account.status.summary")
|
||
kw = notes[0][1] if notes else {}
|
||
check("总数等于账号库", kw.get("total"), len(af.roster_rows()))
|
||
check("有异常账号", (kw.get("abnormal") or 0) >= 1, True)
|
||
check("有正常账号", (kw.get("normal") or 0) >= 1, True)
|
||
check("异常清单包含具体账号",
|
||
any("周周苏州吃喝玩乐" in x for x in (kw.get("abnormal_accounts") or [])), True)
|
||
|
||
print()
|
||
if fails:
|
||
print("❌ 失败 %d 项:%s" % (len(fails), "、".join(fails)))
|
||
sys.exit(1)
|
||
print("✅ test_roster 全部通过(临时库,没碰真实数据)")
|