test_ui.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. # -*- coding: utf-8 -*-
  2. """ui.py 单元测试:数据供给函数 + 循环线程 stop_event 停止语义。
  3. 不实例化 Tk 窗口(避免测试弹窗/事件循环);界面层由人工冒烟
  4. (python -m kuaishou_tool.ui)。
  5. """
  6. import copy
  7. import sys
  8. import threading
  9. import time
  10. from pathlib import Path
  11. import pytest
  12. pytest.importorskip('tkinter', reason='无 tkinter 环境')
  13. ROOT = Path(__file__).resolve().parent.parent
  14. sys.path.insert(0, str(ROOT))
  15. from kuaishou_tool import config, db, niu, publish, scheduler, ui # noqa: E402
  16. @pytest.fixture(autouse=True)
  17. def _tmp_db(tmp_path):
  18. cfg = {'db_path': str(tmp_path / 'data.db'),
  19. 'dirs': {k: str(tmp_path / k) for k in config.DEFAULTS['dirs']}}
  20. old = db._CONN
  21. db._CONN = None
  22. db.conn(cfg)
  23. yield
  24. try:
  25. db._CONN.close()
  26. except Exception:
  27. pass
  28. db._CONN = old
  29. # ---- 数据供给(界面解离的纯查询) ----
  30. def test_row_providers():
  31. db.exe("INSERT INTO anchor (uid, userName, rizhi, yue, ciliroi, cookie1, cookie2) "
  32. "VALUES ('U1','号A','等待投递','12.50','1.2000','ck1','ck2')")
  33. db.exe("INSERT INTO monitoring (name, uid, fensishu) VALUES ('甲','u1',88)")
  34. db.exe("INSERT INTO publishvideo (videoId, state, liveTime) "
  35. "VALUES ('v1','排队','2026-01-01 00:00:00')")
  36. a = ui.anchor_rows()
  37. assert a[0]['uid'] == 'U1' and a[0]['yue'] == '12.50' and a[0]['ciliroi'] == '1.2000'
  38. assert a[0]['ck'] == '✓/✓/–' # 网页✓ 小店✓ 分销无
  39. m = ui.monitoring_rows()
  40. assert m[0]['name'] == '甲' and m[0]['fensishu'] == 88
  41. q = ui.queue_rows()
  42. assert q[0]['videoId'] == 'v1' and q[0]['state'] == '排队'
  43. def test_monitoring_rows_fenlei_filter():
  44. db.exe("INSERT INTO monitoring (name, uid, fenlei) VALUES ('甲','u1','A组')")
  45. db.exe("INSERT INTO monitoring (name, uid, fenlei) VALUES ('乙','u2','B组')")
  46. assert [r['name'] for r in ui.monitoring_rows('A组')] == ['甲']
  47. assert len(ui.monitoring_rows()) == 2
  48. # ---- 设置面板纯函数(J线参数面板的表单读写) ----
  49. def test_settings_fields_sane():
  50. paths = [p for _g, p, _l, _t, _d in ui.SETTINGS_FIELDS]
  51. assert len(paths) == len(set(paths)) # 键路径唯一
  52. types = {_t for _g, _p, _l, _t, _d in ui.SETTINGS_FIELDS}
  53. assert types <= {'int', 'float', 'str', 'bool', 'list'}
  54. def test_form_roundtrip():
  55. """cfg → 表单值 → 写回空 cfg:各字段值无损还原。"""
  56. cfg = {}
  57. expect = {}
  58. for _g, path, _l, typ, default in ui.SETTINGS_FIELDS:
  59. expect[path] = {'int': 7, 'float': 1.5, 'str': 'x', 'bool': True,
  60. 'list': ['a', 'b']}[typ]
  61. ui._bury(cfg, path, expect[path])
  62. vals = ui.form_values(cfg)
  63. out = {}
  64. ui.apply_form(out, vals)
  65. for path in expect:
  66. got = ui._dig(out, path)
  67. assert got == expect[path] or (
  68. isinstance(expect[path], float) and abs(got - expect[path]) < 1e-9), path
  69. def test_apply_form_parsing():
  70. cfg = {}
  71. ui.apply_form(cfg, {
  72. 'collect.filters.min_likes': '12', # int
  73. 'collect.filters.max_age_hours': '2.5', # float
  74. 'collect.filters.keywords_block': '福利, 免费领、秒杀', # list(中英文逗号/顿号)
  75. 'collect.filters.need_goods': '0', # bool
  76. 'ads.enabled': 'true', # bool 词形
  77. 'ai.model': 'cogview-3-flash', # str
  78. })
  79. assert cfg['collect']['filters']['min_likes'] == 12
  80. assert cfg['collect']['filters']['max_age_hours'] == 2.5
  81. assert cfg['collect']['filters']['keywords_block'] == ['福利', '免费领', '秒杀']
  82. assert cfg['collect']['filters']['need_goods'] is False
  83. assert cfg['ads']['enabled'] is True
  84. assert cfg['ai']['model'] == 'cogview-3-flash'
  85. def test_form_values_defaults():
  86. """空 cfg → 全部取字段默认值(不抛 KeyError)。"""
  87. vals = ui.form_values({})
  88. assert vals['collect.filters.min_likes'] == '0'
  89. assert vals['caption.box'] == '1'
  90. assert vals['ads.enabled'] == '0'
  91. assert vals['translate.baidu_appid'] == ''
  92. # ---- 循环线程 stop_event(UI 启停的地基) ----
  93. def test_run_dispatcher_stop_event_idle():
  94. """空队列空转期收到停止信号 → 立即返回(不等 DISPATCHER_IDLE_SEC)。"""
  95. ev = threading.Event()
  96. ev.set()
  97. t0 = time.time()
  98. publish.run_dispatcher({'dirs': {}}, stop_event=ev)
  99. assert time.time() - t0 < 3
  100. def test_run_auto_stop_after_round(monkeypatch):
  101. """首轮 auto_round 后置位 stop → 恰好一轮退出,等待期可打断。"""
  102. calls = []
  103. ev = threading.Event()
  104. def fake_round(cfg):
  105. calls.append(1)
  106. ev.set()
  107. monkeypatch.setattr(scheduler, 'auto_round', fake_round)
  108. monkeypatch.setattr(scheduler.publish, 'run_dispatcher', lambda cfg, **kw: None)
  109. t0 = time.time()
  110. scheduler.run_auto({'collect': {'poll_interval_sec': 30}}, interval=30,
  111. stop_event=ev)
  112. assert calls == [1] and time.time() - t0 < 3
  113. def test_run_auto_stop_before_first_round(monkeypatch):
  114. """启动前 stop 已置位 → 一轮都不跑。"""
  115. calls = []
  116. monkeypatch.setattr(scheduler, 'auto_round', lambda cfg: calls.append(1))
  117. monkeypatch.setattr(scheduler.publish, 'run_dispatcher', lambda cfg, **kw: None)
  118. ev = threading.Event()
  119. ev.set()
  120. scheduler.run_auto({'collect': {}}, stop_event=ev)
  121. assert calls == []
  122. def test_niu_run_auto_stop_after_round(monkeypatch):
  123. db.exe("INSERT INTO anchor (uid, userName) VALUES ('U1','号A')")
  124. calls = []
  125. ev = threading.Event()
  126. def fake_manage(cfg, row, **kw):
  127. calls.append(row['uid'])
  128. ev.set()
  129. monkeypatch.setattr(niu, 'auto_manage', fake_manage)
  130. t0 = time.time()
  131. niu.run_auto({'ads': {'interval_sec': 30}}, interval_sec=30, stop_event=ev)
  132. assert calls == ['U1'] and time.time() - t0 < 3