| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166 |
- # -*- coding: utf-8 -*-
- """ui.py 单元测试:数据供给函数 + 循环线程 stop_event 停止语义。
- 不实例化 Tk 窗口(避免测试弹窗/事件循环);界面层由人工冒烟
- (python -m kuaishou_tool.ui)。
- """
- import copy
- import sys
- import threading
- import time
- from pathlib import Path
- import pytest
- pytest.importorskip('tkinter', reason='无 tkinter 环境')
- ROOT = Path(__file__).resolve().parent.parent
- sys.path.insert(0, str(ROOT))
- from kuaishou_tool import config, db, niu, publish, scheduler, ui # noqa: E402
- @pytest.fixture(autouse=True)
- def _tmp_db(tmp_path):
- cfg = {'db_path': str(tmp_path / 'data.db'),
- 'dirs': {k: str(tmp_path / k) for k in config.DEFAULTS['dirs']}}
- old = db._CONN
- db._CONN = None
- db.conn(cfg)
- yield
- try:
- db._CONN.close()
- except Exception:
- pass
- db._CONN = old
- # ---- 数据供给(界面解离的纯查询) ----
- def test_row_providers():
- db.exe("INSERT INTO anchor (uid, userName, rizhi, yue, ciliroi, cookie1, cookie2) "
- "VALUES ('U1','号A','等待投递','12.50','1.2000','ck1','ck2')")
- db.exe("INSERT INTO monitoring (name, uid, fensishu) VALUES ('甲','u1',88)")
- db.exe("INSERT INTO publishvideo (videoId, state, liveTime) "
- "VALUES ('v1','排队','2026-01-01 00:00:00')")
- a = ui.anchor_rows()
- assert a[0]['uid'] == 'U1' and a[0]['yue'] == '12.50' and a[0]['ciliroi'] == '1.2000'
- assert a[0]['ck'] == '✓/✓/–' # 网页✓ 小店✓ 分销无
- m = ui.monitoring_rows()
- assert m[0]['name'] == '甲' and m[0]['fensishu'] == 88
- q = ui.queue_rows()
- assert q[0]['videoId'] == 'v1' and q[0]['state'] == '排队'
- def test_monitoring_rows_fenlei_filter():
- db.exe("INSERT INTO monitoring (name, uid, fenlei) VALUES ('甲','u1','A组')")
- db.exe("INSERT INTO monitoring (name, uid, fenlei) VALUES ('乙','u2','B组')")
- assert [r['name'] for r in ui.monitoring_rows('A组')] == ['甲']
- assert len(ui.monitoring_rows()) == 2
- # ---- 设置面板纯函数(J线参数面板的表单读写) ----
- def test_settings_fields_sane():
- paths = [p for _g, p, _l, _t, _d in ui.SETTINGS_FIELDS]
- assert len(paths) == len(set(paths)) # 键路径唯一
- types = {_t for _g, _p, _l, _t, _d in ui.SETTINGS_FIELDS}
- assert types <= {'int', 'float', 'str', 'bool', 'list'}
- def test_form_roundtrip():
- """cfg → 表单值 → 写回空 cfg:各字段值无损还原。"""
- cfg = {}
- expect = {}
- for _g, path, _l, typ, default in ui.SETTINGS_FIELDS:
- expect[path] = {'int': 7, 'float': 1.5, 'str': 'x', 'bool': True,
- 'list': ['a', 'b']}[typ]
- ui._bury(cfg, path, expect[path])
- vals = ui.form_values(cfg)
- out = {}
- ui.apply_form(out, vals)
- for path in expect:
- got = ui._dig(out, path)
- assert got == expect[path] or (
- isinstance(expect[path], float) and abs(got - expect[path]) < 1e-9), path
- def test_apply_form_parsing():
- cfg = {}
- ui.apply_form(cfg, {
- 'collect.filters.min_likes': '12', # int
- 'collect.filters.max_age_hours': '2.5', # float
- 'collect.filters.keywords_block': '福利, 免费领、秒杀', # list(中英文逗号/顿号)
- 'collect.filters.need_goods': '0', # bool
- 'ads.enabled': 'true', # bool 词形
- 'ai.model': 'cogview-3-flash', # str
- })
- assert cfg['collect']['filters']['min_likes'] == 12
- assert cfg['collect']['filters']['max_age_hours'] == 2.5
- assert cfg['collect']['filters']['keywords_block'] == ['福利', '免费领', '秒杀']
- assert cfg['collect']['filters']['need_goods'] is False
- assert cfg['ads']['enabled'] is True
- assert cfg['ai']['model'] == 'cogview-3-flash'
- def test_form_values_defaults():
- """空 cfg → 全部取字段默认值(不抛 KeyError)。"""
- vals = ui.form_values({})
- assert vals['collect.filters.min_likes'] == '0'
- assert vals['caption.box'] == '1'
- assert vals['ads.enabled'] == '0'
- assert vals['translate.baidu_appid'] == ''
- # ---- 循环线程 stop_event(UI 启停的地基) ----
- def test_run_dispatcher_stop_event_idle():
- """空队列空转期收到停止信号 → 立即返回(不等 DISPATCHER_IDLE_SEC)。"""
- ev = threading.Event()
- ev.set()
- t0 = time.time()
- publish.run_dispatcher({'dirs': {}}, stop_event=ev)
- assert time.time() - t0 < 3
- def test_run_auto_stop_after_round(monkeypatch):
- """首轮 auto_round 后置位 stop → 恰好一轮退出,等待期可打断。"""
- calls = []
- ev = threading.Event()
- def fake_round(cfg):
- calls.append(1)
- ev.set()
- monkeypatch.setattr(scheduler, 'auto_round', fake_round)
- monkeypatch.setattr(scheduler.publish, 'run_dispatcher', lambda cfg, **kw: None)
- t0 = time.time()
- scheduler.run_auto({'collect': {'poll_interval_sec': 30}}, interval=30,
- stop_event=ev)
- assert calls == [1] and time.time() - t0 < 3
- def test_run_auto_stop_before_first_round(monkeypatch):
- """启动前 stop 已置位 → 一轮都不跑。"""
- calls = []
- monkeypatch.setattr(scheduler, 'auto_round', lambda cfg: calls.append(1))
- monkeypatch.setattr(scheduler.publish, 'run_dispatcher', lambda cfg, **kw: None)
- ev = threading.Event()
- ev.set()
- scheduler.run_auto({'collect': {}}, stop_event=ev)
- assert calls == []
- def test_niu_run_auto_stop_after_round(monkeypatch):
- db.exe("INSERT INTO anchor (uid, userName) VALUES ('U1','号A')")
- calls = []
- ev = threading.Event()
- def fake_manage(cfg, row, **kw):
- calls.append(row['uid'])
- ev.set()
- monkeypatch.setattr(niu, 'auto_manage', fake_manage)
- t0 = time.time()
- niu.run_auto({'ads': {'interval_sec': 30}}, interval_sec=30, stop_event=ev)
- assert calls == ['U1'] and time.time() - t0 < 3
|