Files
butubb d0ad687561 feat(流水线): 资产管理 + 计划编排 + 运行监测 + 切号/发布修复
- 流水线收口为四栏:资产管理 / 动作 / 计划调度 / 运行监测
- 资产管理:账号总表与设备筛选、素材 13 列、模板批量导入(数量+文件名校验)、
  单条上传、删除账号(归档不删原件)、发布记录
- 计划调度:segments 多动作组/任务编排(发布素材/循环/条件/回主页)、
  内置切号可见可编辑、每账号切号前亮屏
- 运行监测:计划/账号/设备三维度、按需截图、按账号拆分显示
- 修复:图片相册索引误报、切号重试与重复点「我」、发布任务校验跳过、
  多号同机假账号目录、编辑器 expect_el 未声明变量
- 文档与测试同步(14/14)
2026-10-18 13:02:38 +08:00

256 lines
13 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""资产管理用例:模板批量导入(两项校验/分拣/去重/音频)、项目级素材操作(指定取/编辑/删除)。
铁律一致:**临时 SQLite + 临时根目录**,不碰真实账号文件夹与素材。
"""
import io
import json
import os
import sys
import tempfile
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
_TMP = tempfile.mkdtemp(prefix="assets_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, VideoPlan, VideoPublishLog # noqa: E402
from core import account_folder as af # noqa: E402
from core import video_plan as vp # noqa: E402
fails = []
def fresh():
"""刷新本会话的缓存。
被调用的函数(`import_asset` / `claim` 等)内部会 `with app.app_context()` ——
Flask-SQLAlchemy 按"当前 app context"划 session,嵌套一层就是**另一个 session**;
它提交后,外层这个 session 里的对象还缓存着旧值。生产里每个请求/线程本来就各用各的
session,所以这只是**测试口径**问题:断言前先 expire 一下。
"""
try:
db.session.expire_all()
except Exception:
pass
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)
vp.init_app(app)
app.app_context().push()
for i, (dev, nick, did) in enumerate([("A01", "号甲", "111"), ("A03", "号乙", "222")]):
db.session.add(DeviceAccount(id="acc%d" % i, device_name=dev, nickname=nick,
douyin_id=did, created_at="2026-10-17"))
db.session.commit()
# 造两个"上传的文件"(FileStorage 形状:.filename + .stream)
class FU:
def __init__(self, name, data=b"x"):
self.filename = name
self.stream = io.BytesIO(data)
def csv_bytes(text):
return ("" + text).encode("utf-8")
TABLE = (
"文件名,账号,标题,内容,话题,分类,展示方式,备注\n"
"01.mp4,号甲,甲的第一条,内容A,#苏州,美食,口播,一镜到底\n"
"02.mp4,号乙,乙的第一条,,#探店,生活,大字报,\n"
)
# ==================== ① 解析 ====================
print("▶ ① 表格解析(BOM / 引号 / 空行 / 表头)")
rows, errs = af._parse_assets_csv(csv_bytes(TABLE + "\n,,\n"))
check("两行有效 + 空行忽略", len(rows), 2)
check("表头映射对(账号/标题/展示方式)",
(rows[0]["account"], rows[0]["title"], rows[0]["display_mode"]), ("号甲", "甲的第一条", "口播"))
check("带引号的字段也能解析",
af._parse_assets_csv(csv_bytes('文件名,账号,标题\n"a,01.mp4",号甲,"标题,带逗号"\n'))[0][0]["title"],
"标题,带逗号")
# ==================== ② 两项校验 ====================
print("▶ ② 两项校验:数量一致 / 文件名一一对应(不过就整批不导入)")
files = [FU("01.mp4", b"aaa"), FU("02.mp4", b"bbb")]
base = {"durations": {"01.mp4": 12.5}}
r = af.import_assets(files[:1], csv_bytes(TABLE), **base)
check("数量不一致 → 整批拒收", (r["ok"], any("数量不一致" in e["error"] for e in r["errors"])), (False, True))
r = af.import_assets(files, csv_bytes(TABLE.replace("02.mp4", "03.mp4")), **base)
check("文件名对不上 → 整批拒收",
any("找不到这个文件名" in e["error"] for e in r["errors"]), True)
check("表里有、文件里没有 → 也拒收", r["ok"], False)
r = af.import_assets(files + [FU("extra.mp4", b"c")], csv_bytes(TABLE), **base)
check("多传了一个文件(表里没写)→ 拒收",
(r["ok"], any("表里没有写" in e["error"] for e in r["errors"])), (False, True))
r = af.import_assets(files, csv_bytes(TABLE.replace("号甲", "没这个号")), **base)
check("账号不在账号库 → 拒收并提示先加号",
any("不在账号库里" in e["error"] for e in r["errors"]), True)
r = af.import_assets(files, csv_bytes(TABLE.replace("甲的第一条", "")), **base)
check("标题为空 → 拒收", any("标题是空的" in e["error"] for e in r["errors"]), True)
r = af.import_assets([FU("01.txt", b"a"), FU("02.mp4", b"b")],
csv_bytes(TABLE.replace("01.mp4", "01.txt")), **base)
check("扩展名不支持 → 拒收", any("不支持的格式" in e["error"] for e in r["errors"]), True)
check("校验失败时**没有**写任何记录", VideoPlan.query.count(), 0)
# ==================== ③ 正式导入 ====================
print("▶ ③ 导入:分拣落盘 + 元数据 + 编号按表序")
files = [FU("01.mp4", b"aaa"), FU("02.mp4", b"bbb")]
r = af.import_assets(files, csv_bytes(TABLE), durations={"01.mp4": 12.5, "02.mp4": 7})
check("导入成功", (r["ok"], r["added"], r["updated"]), (True, 2, 0))
root = af.account_root()
check("按账号分拣到各自的文件夹",
(os.path.isfile(os.path.join(root, "号甲", "01.mp4")),
os.path.isfile(os.path.join(root, "号乙", "02.mp4"))), (True, True))
a = VideoPlan.query.filter(VideoPlan.nickname == "号甲").first()
check("元数据全写进去了",
(a.title, a.body, a.topics, a.category, a.display_mode, a.note, a.duration_s),
("甲的第一条", "内容A", "#苏州", "美食", "口播", "一镜到底", 12.5 and 12))
check("状态 = 未发布(有标题)", a.status, vp.ST_READY)
check("编号从 1 起、按表序", (a.seq, VideoPlan.query.filter(VideoPlan.nickname == "号乙").first().seq),
(1, 1))
check("来源记录(src_path 指回账号目录)", a.src_path, "号甲/01.mp4")
check("媒体类型按扩展名现算", vp.media_type_of(a.video_name), "video")
print("▶ ③b 重复导入(同一张表)→ 只更新元数据,不新建行")
r = af.import_assets([FU("01.mp4", b"aaa"), FU("02.mp4", b"bbb")],
csv_bytes(TABLE.replace("甲的第一条", "甲改过的标题")),
durations={"01.mp4": 12.5})
check("识别为更新", (r["added"], r["updated"]), (0, 2))
check("行数没变(没发两遍的风险)", VideoPlan.query.count(), 2)
fresh()
check("标题被更新", VideoPlan.query.filter(VideoPlan.nickname == "号甲").first().title, "甲改过的标题")
print("▶ ③c 音频入库 = 仅素材·不发布")
r = af.import_assets([FU("03.mp3", b"sound")],
csv_bytes("文件名,账号,标题\n03.mp3,号甲,配音\n"))
check("导入成功", r["ok"], True)
au = VideoPlan.query.filter(VideoPlan.video_name == "03.mp3").first()
check("状态 = asset", au.status, vp.ST_ASSET)
check("类型 = audio", vp.media_type_of(au.video_name), "audio")
check("音频**不会**被发布取数拿到",
[x["id"] for x in vp.take_for_name(["号甲"], vp._today()) if x["id"] == au.id], [])
# ==================== ④ 指定素材 / 编辑 / 删除 ====================
print("▶ ④ 指定素材(勾了哪条发哪条)")
p1 = VideoPlan.query.filter(VideoPlan.nickname == "号甲", VideoPlan.status == vp.ST_READY).first()
got = vp.take_by_ids([p1.id], owner="号甲")
check("指定的那条被占位拿到", [x["id"] for x in got], [p1.id])
fresh()
check("占位后状态 = 推送中", VideoPlan.query.get(p1.id).status, vp.ST_PUSHING)
check("不属于这个号 → 跳过", vp.take_by_ids([p1.id], owner="号乙"), [])
print("▶ ④b 编辑元数据只改传入字段")
p2 = VideoPlan.query.filter(VideoPlan.nickname == "号乙").first()
row, err = vp.set_meta(p2.id, {"topics": "#新话题"})
check("只改了话题,标题没被清空",
(row["topics"], row["title"]), ("#新话题", "乙的第一条"))
row, err = vp.set_meta(p2.id, {"title": "换了个标题"})
check("改标题 → 状态跟着走(ready 保持)", row["status"], vp.ST_READY)
row, err = vp.set_meta(au.id, {"title": "音频也有标题"})
check("asset 不会被 set_meta 改成 ready", row["status"], vp.ST_ASSET)
row, err = vp.set_meta(p2.id, {"title": "x" * 200})
check("标题超长 → 拒绝", bool(err), True)
print("▶ ④c 删除不误删共享文件(内容寻址)")
p3 = VideoPlan.query.get(p2.id)
p4 = VideoPlan(id="duprow", nickname="号甲", release_date="2026-10-17", seq=9,
title="同文件", video_file=p3.video_file, video_sha1=p3.video_sha1,
status=vp.ST_READY, created_at="2026-10-17", updated_at="2026-10-17")
db.session.add(p4)
db.session.commit()
path = vp._video_path(p3.video_file)
check("文件存在", bool(path and os.path.exists(path)), True)
vp.delete_plan(p3.id)
check("还有别的行引用 → 平台副本保留", os.path.exists(path), True)
vp.delete_plan("duprow")
check("最后一行删掉后 → 平台副本删掉", os.path.exists(path), False)
print("▶ ④e 文案拼接:素材自带话题")
_cap = {"title": "T", "body": "B", "topics": "#苏州 #探店"}
check("正文自动带素材话题(空格分隔也认)",
vp.build_caption(_cap, "", key="body"), ("B #苏州 #探店", ""))
check("标题不重复带话题", vp.build_caption(_cap, "", key="title"), ("T", ""))
check("单框 title_body 也带话题",
vp.build_caption(_cap, "", key="title_body"), ("T\nB #苏州 #探店", ""))
check("标题 + 素材话题(输入来源 release_title_topics)",
vp.build_caption(_cap, _cap["topics"], key="title"), ("T #苏州 #探店", ""))
from tasks.generic.task import RELEASE_TEXT_SOURCES # noqa: E402
check("输入文字支持 release_title_topics 来源",
RELEASE_TEXT_SOURCES.get("release_title_topics"), "title")
print("▶ ④d 发布记录")
log = vp.log_publish("anyrow", "published", account="号甲", device_name="A01",
share_url="https://v.douyin.com/x/")
check("写得进、读得出", [x["result"] for x in vp.publish_logs("anyrow")], ["published"])
# ==================== ⑤ 账号表计数 ====================
print("▶ ⑤ 资产账号表:目录 ∪ 账号库 + 池计数")
# 把占位那条放回未发布,让计数有个确定值
vp.set_status(p1.id, vp.ST_READY)
fresh()
accs = {x["name"]: x for x in af.list_accounts()}
check("账号库里登记了、没有文件夹的号也在表里", "号乙" in accs, True)
check("未发布计数(不按日期)", accs["号甲"]["pending"], 1) # 音频是 asset、p1 是 pushing
check("只素材·不发布的不算未发布", accs["号甲"]["pending"], 1)
check("账号带所属设备名", accs["号甲"]["device_name"], "A01")
# ==================== ⑥ 单条素材上传 ====================
print("▶ ⑥ 单条上传(每行「上传素材」:一个文件 + 手填明细)")
root = af.account_root()
before = VideoPlan.query.count()
r = af.import_one("号甲", FU("single.mp4", b"single-content"), meta={
"title": "单条标题", "body": "单条文", "topics": "#单条", "category": "生活",
"display_mode": "混剪", "note": "手录"}, duration_s=8.4)
check("单条入库成功", (r["ok"], r["action"], r["media_type"]), (True, "add", "video"))
check("文件落在账号目录", os.path.isfile(os.path.join(root, "号甲", "single.mp4")), True)
fresh()
row = VideoPlan.query.get(r["item"]["id"])
check("手填的明细全写进去了",
(row.title, row.body, row.topics, row.category, row.display_mode,
row.note, row.duration_s),
("单条标题", "单条文", "#单条", "生活", "混剪", "手录", 8))
check("状态 = 未发布", row.status, vp.ST_READY)
check("编号接着池子往后排", row.seq, 3) # 号甲已占 1、2
check("src_path 指回账号目录", row.src_path, "号甲/single.mp4")
r2 = af.import_one("号甲", FU("silent.mp4", b"silent"), meta={"title": ""})
check("没标题 → 待文案(不会被发布)", (r2["ok"], r2["status"]), (True, vp.ST_PENDING))
r3 = af.import_one("号甲", FU("broll.mp4", b"broll"),
meta={"title": "备用素材", "status": "asset"})
check("手选「仅素材」→ asset", r3["status"], vp.ST_ASSET)
r4 = af.import_one("号甲", FU("voice.mp3", b"voice"), meta={"title": "配音"})
check("音频自动 asset", r4["status"], vp.ST_ASSET)
r5 = af.import_one("没这个号", FU("x.mp4", b"x"), meta={"title": "x"})
check("不存在的账号 → 拒收", (r5["ok"], "不存在" in (r5.get("error") or "")), (False, True))
r6 = af.import_one("号甲", FU("single.mp4", b"single-content"), meta={"title": "改了标题"})
fresh()
check("同内容重传 → 只更新、不新增",
(r6["action"], VideoPlan.query.count()), ("update", before + 4))
check("重传把标题改了", VideoPlan.query.get(r["item"]["id"]).title, "改了标题")
print()
if fails:
print("❌ 失败 %d 项:%s" % (len(fails), "、".join(fails)))
sys.exit(1)
print("✅ test_assets 全部通过(临时库 + 临时目录,没碰真实素材)")