- 账号总表新增抖音号列 - 近7天状态:account_status_log 近7天异常 + 人工异常,显示 无异常/N天前异常/今天异常(人工) - 导出 CSV 同步增加近7天状态/最近异常时间/异常来源 - test_roster 覆盖计算规则
343 lines
18 KiB
Python
343 lines
18 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
|
||
AccountStatusLog)
|
||
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 = "账号异常"
|
||
r3 = DeviceAccount.query.filter_by(nickname="锋哥苏州甲探访").first()
|
||
if r3:
|
||
r3.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("只发一条消息", len(notes), 1)
|
||
check("事件名", notes[0][0] if notes else "", "account.status.summary")
|
||
kw = notes[0][1] if notes else {}
|
||
groups = kw.get("groups") or ""
|
||
check("包含「账号异常」分类", "账号异常:" in groups, True)
|
||
check("账号异常列表", "周周苏州吃喝玩乐" in groups, True)
|
||
check("包含「账号安全待提升」分类", "账号安全待提升:" in groups, True)
|
||
check("待提升列表", "锋哥苏州甲探访" in groups, True)
|
||
check("包含「账号正常」分类", "账号正常:" in groups, True)
|
||
check("账号正常列表", "锋哥苏州百业探访" in groups, True)
|
||
check("没有统计字段(一个消息按类型列账号)",
|
||
("total" in kw or "normal" in kw or "abnormal" in kw), False)
|
||
|
||
print("▶ ⑨ 账号状态检测记录(每次检测/手改留痕)")
|
||
af.set_account_status("锋哥苏州乙探访", "作品异常", source="任务运行", run_id="runA")
|
||
af.set_account_status("锋哥苏州乙探访", "作品异常", source="任务运行", run_id="runA")
|
||
af.set_account_status("锋哥苏州乙探访", "账号正常", source="任务运行", run_id="runB")
|
||
with app.app_context():
|
||
logs = (AccountStatusLog.query.filter_by(nickname="锋哥苏州乙探访")
|
||
.order_by(AccountStatusLog.detected_at).all())
|
||
check("同一次运行只留一条", len([x for x in logs if x.run_id == "runA"]), 1)
|
||
check("下一次运行记录新状态",
|
||
[x.status for x in logs if x.run_id == "runB"], ["账号正常"])
|
||
row = DeviceAccount.query.filter_by(nickname="锋哥苏州乙探访").first()
|
||
check("账号库最新状态", row.account_status, "账号正常")
|
||
check("检测时间已写", bool(row.status_checked_at), True)
|
||
|
||
print("▶ ⑩ 人工标记:优先于自动状态,自动检测不覆盖")
|
||
check("设置人工标记", af.set_manual_status("锋哥苏州乙探访", "账号异常"), True)
|
||
db.session.expire_all()
|
||
row = DeviceAccount.query.filter_by(nickname="锋哥苏州乙探访").first()
|
||
check("自动状态保持原值(账号正常)", row.account_status, "账号正常")
|
||
check("有效状态 = 人工标记", row.effective_status, "账号异常")
|
||
check("roster_rows 同时带人工/有效状态",
|
||
[(x["manual_status"], x["effective_status"]) for x in af.roster_rows()
|
||
if x["nickname"] == "锋哥苏州乙探访"], [("账号异常", "账号异常")])
|
||
acct = [x for x in af.list_accounts() if x["name"] == "锋哥苏州乙探访"][0]
|
||
check("资产总表带人工/有效状态",
|
||
(acct["manual_status"], acct["effective_status"]), ("账号异常", "账号异常"))
|
||
|
||
af.set_account_status("锋哥苏州乙探访", "账号正常", source="任务运行", run_id="runC")
|
||
db.session.expire_all()
|
||
row = DeviceAccount.query.filter_by(nickname="锋哥苏州乙探访").first()
|
||
check("任务自动检测不覆盖人工标记", row.effective_status, "账号异常")
|
||
check("自动列仍按检测值写", row.account_status, "账号正常")
|
||
|
||
notes = []
|
||
_orig_notify = _notifier.notify
|
||
_notifier.notify = lambda ev, **kw: notes.append((ev, kw))
|
||
try:
|
||
af.notify_account_status_summary(job_name="检测账号", source="计划运行")
|
||
finally:
|
||
_notifier.notify = _orig_notify
|
||
groups = notes[0][1].get("groups") or ""
|
||
line_abn = next((ln for ln in groups.splitlines() if ln.startswith("账号异常:")), "")
|
||
line_ok = next((ln for ln in groups.splitlines() if ln.startswith("账号正常:")), "")
|
||
check("人工标记进「账号异常」分类", "锋哥苏州乙探访" in line_abn, True)
|
||
check("不再出现在「账号正常」分类", "锋哥苏州乙探访" in line_ok, False)
|
||
|
||
db.session.expire_all()
|
||
af.set_manual_status("锋哥苏州乙探访", "")
|
||
db.session.expire_all()
|
||
row = DeviceAccount.query.filter_by(nickname="锋哥苏州乙探访").first()
|
||
check("清除人工标记后回落到自动状态", row.effective_status, "账号正常")
|
||
check("账号库里没有的号 → 不新建行",
|
||
af.set_manual_status("没这个号", "账号异常"), False)
|
||
|
||
print("▶ ⑪ 近7天异常计算(自动日志 + 人工标记)")
|
||
import datetime # noqa: E402
|
||
_now = datetime.datetime.now()
|
||
with app.app_context():
|
||
db.session.add(DeviceAccount(id="r7d", device_name="A01", nickname="七天测试号",
|
||
douyin_id="9001"))
|
||
db.session.add(DeviceAccount(id="rno", device_name="A02", nickname="无异常测试号",
|
||
douyin_id="9002"))
|
||
db.session.add(DeviceAccount(id="rman", device_name="A03", nickname="人工异常测试号",
|
||
douyin_id="9003", manual_status="账号异常",
|
||
updated_at=_now.strftime("%Y-%m-%d %H:%M:%S")))
|
||
db.session.add(AccountStatusLog(
|
||
id="log7d", account_id="r7d", nickname="七天测试号", status="账号异常",
|
||
source="计划运行",
|
||
detected_at=(_now - datetime.timedelta(days=3)).strftime("%Y-%m-%d %H:%M:%S"),
|
||
created_at=(_now - datetime.timedelta(days=3)).strftime("%Y-%m-%d %H:%M:%S")))
|
||
db.session.commit()
|
||
_accts = {a["name"]: a for a in af.list_accounts()}
|
||
check("7天内有异常标记", _accts["七天测试号"]["status_7d_abnormal"], True)
|
||
check("7天异常天数", _accts["七天测试号"]["status_7d_days"], 3)
|
||
check("7天异常文案", _accts["七天测试号"]["status_7d_text"], "3天前异常")
|
||
check("无异常文案", _accts["无异常测试号"]["status_7d_text"], "无异常")
|
||
check("人工异常按今天显示", _accts["人工异常测试号"]["status_7d_text"], "今天异常(人工)")
|
||
check("抖音号列", _accts["七天测试号"]["douyin_id"], "9001")
|
||
|
||
print("▶ ⑫ 导出账号列表 + 状态")
|
||
_csv = af.export_accounts_csv().decode("utf-8-sig")
|
||
check("CSV 有表头", "账号昵称" in _csv and "有效状态" in _csv, True)
|
||
check("CSV 带账号", "周周苏州吃喝玩乐" in _csv, True)
|
||
check("CSV 带自动/人工状态列", ("自动状态" in _csv and "人工标记" in _csv), True)
|
||
|
||
print()
|
||
if fails:
|
||
print("❌ 失败 %d 项:%s" % (len(fails), "、".join(fails)))
|
||
sys.exit(1)
|
||
print("✅ test_roster 全部通过(临时库,没碰真实数据)")
|