P3 §7: 引入 pytest 基础设施 + 9 个核心模块冒烟/单元测试
§7-1 pytest 基础设施
- pyproject.toml 加 [tool.pytest.ini_options]
(testpaths / python_files / strict markers / smoke + slow marker 注册)
- tests/conftest.py 自动把项目根加到 sys.path
§7-2 核心模块测试(242 passed, 1 skipped)
- test_filter_logging.py(重写为 pytest):should_skip_fudai_by_config
+ is_watch_task_fudai + _is_short_countdown_text 共 29 用例
- test_time_utils.py:parse_mm_ss + extract_2digits 共 22 用例
- test_douyin_text_utils.py:4 个 OCR 解析函数 25 用例
- test_douyin_utils.py:extract_prize_value_yuan + normalize_countdown_text 21 用例
- test_path_config.py:10 个路径函数结构断言 + 路径间互不重复 20 用例
- test_logger_helpers.py:8 个 print→logger helper 的统一接口测试 20 用例
- test_unified_logger_mdc.py:MDC 7 个方法 + 线程隔离 13 用例
- test_io_utils.py:_verify_png_integrity / _safe_replace_file /
_ensure_parent_dir 11 用例
- test_imports.py:78 个核心模块的 import 冒烟 + 关键类/函数导出验证
修订老测试
- test_ocr_comparison.py:用 pytest.importorskip 跳过缺失的 psutil/easyocr/paddleocr,
并整体标 @pytest.mark.slow(需要 'pytest -m slow' 才会跑)
- test_webgui.py:原会真的启 HTTP 服务卡死,改为 import 冒烟 + helper 调用测试
README
- 重写 "## ✅ 测试" 段,给出实际可用的 pytest 命令、测试约定、marker 说明
回归:tests/ 142 项测试 PASS / 1 SKIP / 0 FAIL;全部纯函数 + 不依赖 ADB / OCR / 设备。
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
1 parent
818c3139b1
commit
ecffba94b4
15 files changed
+1215
-74
No files matched your search
@@ -170,16 +170,29 @@ Issue 模板参考:
|
||||
|
||||
## ✅ 测试
|
||||
|
||||
本仓库包含若干测试文件(`tests/` 目录),可使用以下方式运行:
|
||||
`tests/` 目录下是 pytest 风格的单元测试 + 业务冒烟测试,覆盖路径配置、文本解析、
|
||||
福袋筛选决策、logger helper、MDC 上下文、io_utils 等核心纯函数链路。
|
||||
|
||||
```bash
|
||||
# 运行所有测试
|
||||
pytest -q
|
||||
# 安装 pytest(已加进开发依赖示例,没装的话)
|
||||
pip install pytest
|
||||
|
||||
# 运行单个测试文件
|
||||
pytest tests/unit/test_example.py::test_some_behavior -q
|
||||
# 运行全部测试(约 250 用例 / <1 秒,全部纯函数)
|
||||
pytest
|
||||
|
||||
# 单文件 / 单用例
|
||||
pytest tests/test_filter_logging.py
|
||||
pytest tests/test_path_config.py::TestSpecificPaths::test_reservations_path_in_douyin_core_state -v
|
||||
|
||||
# 跑较慢的测试(性能对比脚本,需要 paddleocr/easyocr/psutil)
|
||||
pytest -m slow
|
||||
```
|
||||
|
||||
测试约定:
|
||||
- `tests/conftest.py` 自动把项目根加到 `sys.path`,无需在每个测试文件重复
|
||||
- 测试不依赖 ADB / 真实设备 / OCR 引擎;性能对比脚本用 `pytest.importorskip` 自动跳过
|
||||
- 自定义 marker:`smoke`(业务关键链路)/`slow`(慢测试);新增 marker 要先在 `pyproject.toml` 注册
|
||||
|
||||
---
|
||||
|
||||
## 📜 许可(License)
|
||||
|
||||
@@ -8,4 +8,19 @@ disable = [
|
||||
"redefined-outer-name",
|
||||
"pointless-string-statement",
|
||||
"unreachable"
|
||||
]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
# pytest 配置:默认从 tests/ 目录收集,仅识别 test_*.py
|
||||
# 当前测试有意写得"轻":业务级冒烟 + 纯函数单元测试,不依赖 ADB / OCR / 设备
|
||||
testpaths = ["tests"]
|
||||
python_files = ["test_*.py"]
|
||||
python_classes = ["Test*"]
|
||||
python_functions = ["test_*"]
|
||||
# -ra:显示所有非 PASS 的测试结果摘要;-q:精简输出
|
||||
# --strict-markers:自定义 marker 必须先注册,避免笔误静默通过
|
||||
addopts = "-ra -q --strict-markers"
|
||||
markers = [
|
||||
"smoke: 冒烟测试,覆盖业务关键链路的最小用例",
|
||||
"slow: 较慢的测试(>1s),CI 中可单独跑",
|
||||
]
|
||||
@@ -0,0 +1,13 @@
|
||||
"""pytest 全局配置:把项目根目录加入 sys.path,便于测试直接 import douyin.* / gui.*。
|
||||
|
||||
不做 fixture 全局共享,单文件测试自包含;通用 fixture 写到对应 test_*.py 里。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
# 项目根 = tests/ 的父目录
|
||||
_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if _PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, _PROJECT_ROOT)
|
||||
@@ -0,0 +1,131 @@
|
||||
"""douyin/utils/douyin_text_utils 的 pytest 单元测试。
|
||||
|
||||
覆盖福袋内容/倒计时/价值/参与人数 4 个 OCR 文本解析函数。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from douyin.utils.douyin_text_utils import (
|
||||
_safe_str,
|
||||
extract_fudai_content,
|
||||
extract_fudai_countdown,
|
||||
extract_fudai_value,
|
||||
extract_participants_count,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# _safe_str
|
||||
# ============================================================
|
||||
|
||||
class TestSafeStr:
|
||||
@pytest.mark.parametrize(
|
||||
"value,expected",
|
||||
[
|
||||
(None, ""),
|
||||
("", ""),
|
||||
("abc", "abc"),
|
||||
(123, "123"),
|
||||
(0, "0"),
|
||||
],
|
||||
)
|
||||
def test_safe_str(self, value, expected):
|
||||
assert _safe_str(value) == expected
|
||||
|
||||
|
||||
# ============================================================
|
||||
# extract_fudai_content
|
||||
# ============================================================
|
||||
|
||||
class TestExtractFudaiContent:
|
||||
@pytest.mark.parametrize(
|
||||
"text,expected_substr",
|
||||
[
|
||||
("福袋内容:现金红包 100 元", "现金红包 100 元"),
|
||||
("奖品内容:iPhone 15", "iPhone 15"),
|
||||
("内容:手机一台", "手机一台"),
|
||||
# 全/半角冒号都支持
|
||||
("福袋内容: 现金", "现金"),
|
||||
],
|
||||
)
|
||||
def test_with_prefix(self, text, expected_substr):
|
||||
result = extract_fudai_content(text)
|
||||
assert expected_substr in result
|
||||
|
||||
def test_no_prefix_returns_original(self):
|
||||
text = "随便一段没有前缀的描述"
|
||||
# 没有前缀时返回原文(去首尾空白),不抛异常
|
||||
assert extract_fudai_content(text) == text.strip()
|
||||
|
||||
@pytest.mark.parametrize("value", ["", None])
|
||||
def test_empty(self, value):
|
||||
assert extract_fudai_content(value) == ""
|
||||
|
||||
|
||||
# ============================================================
|
||||
# extract_fudai_countdown
|
||||
# ============================================================
|
||||
|
||||
class TestExtractFudaiCountdown:
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
["", None],
|
||||
)
|
||||
def test_empty_returns_empty_string(self, value):
|
||||
assert extract_fudai_countdown(value) == ""
|
||||
|
||||
def test_returns_string_type(self):
|
||||
# 复杂文本走 normalize_countdown_text,结果应总是 str
|
||||
result = extract_fudai_countdown("剩余 05:30 开奖")
|
||||
assert isinstance(result, str)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# extract_fudai_value
|
||||
# ============================================================
|
||||
|
||||
class TestExtractFudaiValue:
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
["", None],
|
||||
)
|
||||
def test_empty_returns_zero(self, value):
|
||||
assert extract_fudai_value(value) == 0.0
|
||||
|
||||
def test_returns_float(self):
|
||||
# 不论输入是什么,返回值必须是 float
|
||||
result = extract_fudai_value("价值 100 元")
|
||||
assert isinstance(result, float)
|
||||
# 至少应该解析出一个非负数
|
||||
assert result >= 0.0
|
||||
|
||||
|
||||
# ============================================================
|
||||
# extract_participants_count
|
||||
# ============================================================
|
||||
|
||||
class TestExtractParticipantsCount:
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
["", None],
|
||||
)
|
||||
def test_empty_returns_zero(self, value):
|
||||
assert extract_participants_count(value) == 0
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text,expected",
|
||||
[
|
||||
("已1173人已参与", 1173),
|
||||
("已经500人参与", 500),
|
||||
("1173人已参与", 1173),
|
||||
("1000人参与", 1000),
|
||||
],
|
||||
)
|
||||
def test_extract_pattern(self, text, expected):
|
||||
assert extract_participants_count(text) == expected
|
||||
|
||||
def test_returns_int(self):
|
||||
result = extract_participants_count("100 人")
|
||||
assert isinstance(result, int)
|
||||
assert result >= 0
|
||||
@@ -0,0 +1,94 @@
|
||||
"""douyin/utils/douyin_utils 的 pytest 单元测试。
|
||||
|
||||
覆盖两个核心 OCR 文本解析纯函数:
|
||||
- extract_prize_value_yuan:从 OCR 文本里抽取奖品价值(元)
|
||||
- normalize_countdown_text:把各种倒计时文本归一化为 "m:ss"
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from douyin.utils.douyin_utils import (
|
||||
extract_prize_value_yuan,
|
||||
normalize_countdown_text,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# extract_prize_value_yuan
|
||||
# ============================================================
|
||||
|
||||
class TestExtractPrizeValueYuan:
|
||||
@pytest.mark.parametrize(
|
||||
"text,expected",
|
||||
[
|
||||
# 标准 ¥ 前缀
|
||||
("¥100", 100.0),
|
||||
("¥99.50", 99.5),
|
||||
("¥100.5", 100.5),
|
||||
("¥200元", 200.0),
|
||||
# 千分位逗号
|
||||
("价值¥1,000", 1000.0),
|
||||
# 中文/纯数字描述("价值 100 元")
|
||||
("价值 100 元", 100.0),
|
||||
# OCR 字母 → 数字纠错(l→1, O→0)
|
||||
("¥l00", 100.0),
|
||||
],
|
||||
)
|
||||
def test_extract_valid(self, text, expected):
|
||||
assert extract_prize_value_yuan(text) == expected
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text",
|
||||
[
|
||||
"",
|
||||
None,
|
||||
"没有金额",
|
||||
"随便一段文本",
|
||||
],
|
||||
)
|
||||
def test_extract_zero_when_no_value(self, text):
|
||||
# 没有有效金额的文本应返回 0.0
|
||||
assert extract_prize_value_yuan(text) == 0.0
|
||||
|
||||
def test_returns_float(self):
|
||||
# 任何输入都应返回 float(不是 int / None)
|
||||
assert isinstance(extract_prize_value_yuan("¥100"), float)
|
||||
assert isinstance(extract_prize_value_yuan(""), float)
|
||||
assert isinstance(extract_prize_value_yuan(None), float)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# normalize_countdown_text
|
||||
# ============================================================
|
||||
|
||||
class TestNormalizeCountdownText:
|
||||
@pytest.mark.parametrize(
|
||||
"text,expected",
|
||||
[
|
||||
# 基本归一化:去除前导 0、统一冒号
|
||||
("00:30", "0:30"),
|
||||
("5:30", "5:30"),
|
||||
("02:30", "2:30"),
|
||||
# 中文冒号
|
||||
("5:30", "5:30"),
|
||||
# 中文分秒
|
||||
("5分30秒", "5:30"),
|
||||
# 嵌在文本里:能抽出
|
||||
("剩余 03:25 开奖", "3:25"),
|
||||
],
|
||||
)
|
||||
def test_normalize_known_patterns(self, text, expected):
|
||||
assert normalize_countdown_text(text) == expected
|
||||
|
||||
def test_empty_returns_empty(self):
|
||||
assert normalize_countdown_text("") == ""
|
||||
|
||||
def test_returns_string(self):
|
||||
# 任何输入都应返回 str
|
||||
assert isinstance(normalize_countdown_text("00:30"), str)
|
||||
assert isinstance(normalize_countdown_text(""), str)
|
||||
|
||||
def test_two_digit_minute_preserved(self):
|
||||
# 双位分钟数应保留,不被误处理
|
||||
assert normalize_countdown_text("12:34") == "12:34"
|
||||
+168
-32
@@ -1,38 +1,174 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys
|
||||
import os
|
||||
"""douyin/fudai/core/fudai_filter.should_skip_fudai_by_config 的 pytest 单元测试。
|
||||
|
||||
detail tuple 的字段顺序:
|
||||
(content, time_text, participants, copies, prize_value_yuan, countdown)
|
||||
|
||||
countdown = (start_ts, end_ts),end_ts 用 time.time()+offset 表示开奖时间戳。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
# 添加项目根目录到路径
|
||||
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, PROJECT_ROOT)
|
||||
import pytest
|
||||
|
||||
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
|
||||
|
||||
|
||||
# 创建一个模拟的 analyser 对象
|
||||
class MockAnalyser:
|
||||
def _log_kv(self, category, message, **kwargs):
|
||||
print(f"[{category}] {message}")
|
||||
for key, value in kwargs.items():
|
||||
print(f" {key}: {value}")
|
||||
|
||||
|
||||
# 测试筛选逻辑
|
||||
analyser = MockAnalyser()
|
||||
|
||||
# 测试数据:detail 是一个元组,包含福袋的详细信息
|
||||
# 格式为 (prize_value_yuan, participants, copies, content, button_text, countdown_tuple, ...)
|
||||
detail = (
|
||||
75.0, # prize_value_yuan
|
||||
10, # participants
|
||||
1, # copies
|
||||
"", # content
|
||||
"一键发表评论", # button_text
|
||||
(time.time() + 120, time.time() + 120), # countdown (start, end)
|
||||
from douyin.fudai.core.fudai_filter import (
|
||||
is_watch_task_fudai,
|
||||
should_skip_fudai_by_config,
|
||||
_is_short_countdown_text,
|
||||
)
|
||||
|
||||
result, reason = should_skip_fudai_by_config(analyser=analyser, detail=detail)
|
||||
|
||||
print(f"\n筛选结果: {'跳过' if result else '参与'}, 原因: {reason}")
|
||||
class MockAnalyser:
|
||||
"""最小可用的 analyser 假对象。
|
||||
|
||||
fudai_filter 业务逻辑会读 needswitch 和若干配置,但所有配置最终都通过
|
||||
getattr(analyser, name, default) 取,所以这里只挂常用的几个字段就够。
|
||||
"""
|
||||
|
||||
def __init__(self, **overrides):
|
||||
# 默认全开"切换模式 + 不限价"——让筛选只看其他字段
|
||||
self.needswitch = True
|
||||
self.min_prize_value_yuan = 0.0
|
||||
self.min_participants = 0
|
||||
self.max_participants = 0
|
||||
self.skip_if_countdown_lt_seconds = 0
|
||||
self.contains_want = []
|
||||
self.contains_not_want = []
|
||||
# 测试时按需覆盖
|
||||
for k, v in overrides.items():
|
||||
setattr(self, k, v)
|
||||
self.logs = []
|
||||
|
||||
def _log_kv(self, category, message, **kwargs):
|
||||
# 收集日志便于断言(但默认只 append 不打印,避免污染测试输出)
|
||||
self.logs.append((category, message, kwargs))
|
||||
|
||||
|
||||
def _make_detail(
|
||||
content="现金红包",
|
||||
time_text="2分钟",
|
||||
participants=10,
|
||||
copies=1,
|
||||
prize_value_yuan=100.0,
|
||||
countdown_offset=120,
|
||||
):
|
||||
"""构造 fudai_filter 期望的 detail tuple。"""
|
||||
end_ts = time.time() + countdown_offset
|
||||
return (content, time_text, participants, copies, prize_value_yuan, (end_ts, end_ts))
|
||||
|
||||
|
||||
# ============================================================
|
||||
# is_watch_task_fudai:观看任务福袋识别
|
||||
# ============================================================
|
||||
|
||||
class TestIsWatchTaskFudai:
|
||||
@pytest.mark.parametrize(
|
||||
"content",
|
||||
[
|
||||
"观看3分钟即可参与",
|
||||
"观看5分钟",
|
||||
"需要观看10分钟",
|
||||
"观看时长3分钟",
|
||||
],
|
||||
)
|
||||
def test_watch_task_detected(self, content):
|
||||
assert is_watch_task_fudai(content) is True
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"content",
|
||||
[
|
||||
"现金红包",
|
||||
"iPhone 15",
|
||||
"",
|
||||
"请关注本直播间",
|
||||
"观看10秒后可领取", # 没有"分钟",不是观看任务福袋
|
||||
],
|
||||
)
|
||||
def test_non_watch_task(self, content):
|
||||
assert is_watch_task_fudai(content) is False
|
||||
|
||||
|
||||
# ============================================================
|
||||
# _is_short_countdown_text:判断剩余时间是否 ≤ 2 秒
|
||||
# ============================================================
|
||||
|
||||
class TestIsShortCountdownText:
|
||||
@pytest.mark.parametrize(
|
||||
"text,expected",
|
||||
[
|
||||
("00:00", True),
|
||||
("00:01", True),
|
||||
("00:02", True),
|
||||
("0:00", True),
|
||||
("0:02", True),
|
||||
("00秒", True),
|
||||
("02秒", True),
|
||||
("00:03", False), # 3 秒不算短
|
||||
("3秒", False), # 单位"秒"但 >= 03 不命中
|
||||
("10秒", False),
|
||||
("2分钟", False),
|
||||
("1:30", False),
|
||||
("", False),
|
||||
],
|
||||
)
|
||||
def test_short_countdown(self, text, expected):
|
||||
assert _is_short_countdown_text(text) is expected
|
||||
|
||||
|
||||
# ============================================================
|
||||
# should_skip_fudai_by_config:核心筛选决策
|
||||
# ============================================================
|
||||
|
||||
class TestShouldSkipFudaiByConfig:
|
||||
def test_high_value_passes(self):
|
||||
"""高价值(1000 元)+ 全开筛选 → 应参与。"""
|
||||
a = MockAnalyser()
|
||||
skip, reason = should_skip_fudai_by_config(a, _make_detail(prize_value_yuan=1000.0))
|
||||
assert skip is False
|
||||
assert reason == "ok"
|
||||
|
||||
def test_watch_task_skipped(self):
|
||||
"""观看任务 → 必跳过,不论价值。"""
|
||||
a = MockAnalyser()
|
||||
detail = _make_detail(content="观看3分钟即可参与", prize_value_yuan=10000.0)
|
||||
skip, reason = should_skip_fudai_by_config(a, detail)
|
||||
assert skip is True
|
||||
assert "watch" in reason.lower() or "观看" in reason
|
||||
|
||||
def test_low_value_skipped(self):
|
||||
"""min_prize_value_yuan=200 + 价值 75 → 跳过。"""
|
||||
a = MockAnalyser(min_prize_value_yuan=200.0)
|
||||
detail = _make_detail(prize_value_yuan=75.0)
|
||||
skip, reason = should_skip_fudai_by_config(a, detail)
|
||||
assert skip is True
|
||||
assert "value" in reason.lower() or "价值" in reason
|
||||
|
||||
def test_blacklist_keyword_skipped(self):
|
||||
"""contains_not_want 命中 → 跳过。"""
|
||||
a = MockAnalyser(contains_not_want=["袜子", "首饰盒"])
|
||||
detail = _make_detail(content="精美袜子礼盒", prize_value_yuan=500.0)
|
||||
skip, reason = should_skip_fudai_by_config(a, detail)
|
||||
assert skip is True
|
||||
|
||||
def test_whitelist_pass(self):
|
||||
"""contains_want 命中 → 不跳过。"""
|
||||
a = MockAnalyser(contains_want=["现金", "红包"])
|
||||
detail = _make_detail(content="现金红包 100 元", prize_value_yuan=100.0)
|
||||
skip, reason = should_skip_fudai_by_config(a, detail)
|
||||
assert skip is False
|
||||
|
||||
def test_invalid_detail_tuple(self):
|
||||
"""detail 不是 6 元素 tuple → detail_tuple_invalid 不跳过(不应崩)。"""
|
||||
a = MockAnalyser()
|
||||
skip, reason = should_skip_fudai_by_config(a, ("just-one-element",))
|
||||
# 不抛异常 + 给出明确原因即可,具体值可以随实现微调
|
||||
assert isinstance(skip, bool)
|
||||
assert isinstance(reason, str)
|
||||
|
||||
def test_single_room_mode_never_skip(self):
|
||||
"""needswitch=False → 单间模式,远超价值阈值也不跳过。"""
|
||||
a = MockAnalyser(needswitch=False, min_prize_value_yuan=1e9)
|
||||
detail = _make_detail(prize_value_yuan=1.0)
|
||||
skip, reason = should_skip_fudai_by_config(a, detail)
|
||||
assert skip is False
|
||||
assert "single" in reason.lower() or "single_room" in reason
|
||||
@@ -0,0 +1,162 @@
|
||||
"""核心模块导入冒烟测试。
|
||||
|
||||
验证 douyin/* 全树关键模块都能正常 import;任何 import-time 错误(语法 / 循环
|
||||
依赖 / 顶层初始化失败)都会在这里被捕获,避免运行时才发现。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
# 项目核心包:这些模块顶层 import 不应失败
|
||||
CORE_MODULES = [
|
||||
# 入口与基础
|
||||
"douyin.core.path_config",
|
||||
"douyin.core.version",
|
||||
"douyin.core.io_utils",
|
||||
"douyin.core.underlying_operations",
|
||||
"douyin.core.douyin_fudai",
|
||||
"douyin.core.douyin_main_flow",
|
||||
"douyin.core.douyin_flow_control",
|
||||
# fudai_modules(Mixin)
|
||||
"douyin.core.fudai_modules.base_interface",
|
||||
"douyin.core.fudai_modules.fudai_navigation",
|
||||
"douyin.core.fudai_modules.fudai_stage_detection",
|
||||
"douyin.core.fudai_modules.fudai_popup_handler",
|
||||
"douyin.core.fudai_modules.fudai_lottery_result",
|
||||
"douyin.core.fudai_modules.fudai_room_utils",
|
||||
"douyin.core.fudai_modules.fudai_main_logic",
|
||||
# 检测 / 阶段
|
||||
"douyin.detection.douyin_detection",
|
||||
"douyin.detection.douyin_pixel",
|
||||
"douyin.stage.douyin_stage",
|
||||
"douyin.stage.douyin_stage_handler",
|
||||
# 福袋核心
|
||||
"douyin.fudai.douyin_fudai_core",
|
||||
"douyin.fudai.douyin_fudai_finder",
|
||||
"douyin.fudai.douyin_fudai_detail",
|
||||
"douyin.fudai.douyin_fudai_flow",
|
||||
"douyin.fudai.core.coords",
|
||||
"douyin.fudai.core.fudai_filter",
|
||||
"douyin.fudai.core.fudai_attend",
|
||||
"douyin.fudai.core.fudai_debug_utils",
|
||||
"douyin.fudai.core.fudai_result_checker",
|
||||
# 处理器
|
||||
"douyin.handlers.douyin_screenshot_handler",
|
||||
"douyin.handlers.douyin_screenshot_manager",
|
||||
"douyin.handlers.douyin_swipe_handler",
|
||||
"douyin.handlers.douyin_swipe_ops",
|
||||
"douyin.handlers.douyin_popup_handler",
|
||||
# 预约
|
||||
"douyin.reservation.douyin_reservation",
|
||||
"douyin.reservation.douyin_reservation_handler",
|
||||
"douyin.reservation.douyin_reservation_logic",
|
||||
"douyin.reservation.douyin_reservation_verify",
|
||||
"douyin.reservation.core", # 子包
|
||||
# 日志
|
||||
"douyin.logging.douyin_logging",
|
||||
"douyin.logging.douyin_logging_wrapper",
|
||||
"douyin.logging.unified_logger",
|
||||
"douyin.logging.action_logger",
|
||||
"douyin.logging.internal_loggers",
|
||||
"douyin.logging.log_formatter",
|
||||
"douyin.logging.performance_tracker",
|
||||
# 其他业务
|
||||
"douyin.other.douyin_yanghao",
|
||||
"douyin.other.douyin_robot",
|
||||
"douyin.other.douyin_popups",
|
||||
"douyin.other.douyin_high_value_room",
|
||||
"douyin.other.douyin_live_room",
|
||||
"douyin.other.douyin_lottery",
|
||||
# 工具
|
||||
"douyin.utils.douyin_config",
|
||||
"douyin.utils.douyin_helpers",
|
||||
"douyin.utils.douyin_utils",
|
||||
"douyin.utils.douyin_text_utils",
|
||||
"douyin.utils.ocr_preprocess",
|
||||
"douyin.utils.time_utils",
|
||||
"douyin.utils.param_usage_tracer",
|
||||
"douyin.utils.param_usage_tracker",
|
||||
# operations 兼容包
|
||||
"operations",
|
||||
"operations.ocr_operations",
|
||||
"operations.screenshot_operations",
|
||||
"operations.screenshot_service",
|
||||
# GUI(不实例化,仅 import)
|
||||
"gui.gui_core",
|
||||
"gui.gui_app",
|
||||
"gui.web_gui",
|
||||
"gui.webgui_launcher",
|
||||
"gui.components.actions_log_viewer",
|
||||
"gui.components.device_selector",
|
||||
"gui.components.error_log_viewer",
|
||||
"gui.components.log_color_config",
|
||||
"gui.components.log_viewer",
|
||||
"gui.components.mapping_table",
|
||||
"gui.components.mapping_utils",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module_name", CORE_MODULES)
|
||||
def test_module_importable(module_name):
|
||||
"""每个核心模块都应可以 import 而不抛异常。"""
|
||||
importlib.import_module(module_name)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 关键类/函数应正确导出
|
||||
# ============================================================
|
||||
|
||||
class TestKeyExports:
|
||||
def test_fudai_analyse_class(self):
|
||||
from douyin.core.douyin_fudai import fudai_analyse
|
||||
|
||||
assert fudai_analyse.__name__ == "fudai_analyse"
|
||||
# 必有的关键方法
|
||||
for method in ("fudai_choujiang", "run_once_basic", "load_config"):
|
||||
assert hasattr(fudai_analyse, method), f"fudai_analyse 缺少 {method}"
|
||||
|
||||
def test_underlying_operations_class(self):
|
||||
from douyin.core.underlying_operations import underlying_operations
|
||||
|
||||
assert underlying_operations.__name__ == "underlying_operations"
|
||||
# 必有的关键方法
|
||||
for method in ("get_screenshot", "click", "swipe", "analyse_pic_word"):
|
||||
assert hasattr(underlying_operations, method), (
|
||||
f"underlying_operations 缺少 {method}"
|
||||
)
|
||||
|
||||
def test_path_config_functions(self):
|
||||
from douyin.core import path_config
|
||||
|
||||
# 关键函数
|
||||
for fn_name in (
|
||||
"get_project_root",
|
||||
"get_config_path",
|
||||
"get_logs_dir",
|
||||
"get_state_dir",
|
||||
"get_reservations_path",
|
||||
):
|
||||
assert callable(getattr(path_config, fn_name, None)), (
|
||||
f"path_config 缺少 {fn_name}"
|
||||
)
|
||||
|
||||
def test_unified_logger_mdc(self):
|
||||
from douyin.logging.unified_logger import MDC
|
||||
|
||||
for method in ("put", "get", "get_all", "remove", "clear"):
|
||||
assert callable(getattr(MDC, method, None)), f"MDC 缺少 {method}"
|
||||
|
||||
def test_operations_package_exports(self):
|
||||
import operations
|
||||
|
||||
# operations 包对外暴露的符号
|
||||
for name in (
|
||||
"underlying_operations",
|
||||
"analyse_pic_word",
|
||||
"get_screenshot",
|
||||
"_safe_replace_file",
|
||||
):
|
||||
assert hasattr(operations, name), f"operations 包缺少导出 {name}"
|
||||
@@ -0,0 +1,130 @@
|
||||
"""douyin/core/io_utils 的 pytest 单元测试。
|
||||
|
||||
覆盖三个底层 IO 辅助函数:
|
||||
- _verify_png_integrity:PNG 文件头/尾完整性检查
|
||||
- _safe_replace_file:原子替换(处理 Windows 文件锁)
|
||||
- _ensure_parent_dir:确保父目录存在
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import struct
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from douyin.core.io_utils import (
|
||||
_ensure_parent_dir,
|
||||
_safe_replace_file,
|
||||
_verify_png_integrity,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 构造合法 / 不合法 PNG 字节
|
||||
# ============================================================
|
||||
|
||||
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
||||
|
||||
|
||||
def _make_minimal_png_bytes() -> bytes:
|
||||
"""构造一个语法上"勉强合法"的最小 PNG:
|
||||
8 字节签名 + 1 个空 IHDR 块 + 1 个 IEND 块。
|
||||
|
||||
注:_verify_png_integrity 只检查头 8 字节签名 + 末尾 12 字节里有 'IEND',
|
||||
不做完整 chunk 校验,所以不需要真实 CRC。
|
||||
"""
|
||||
ihdr_body = b"\x00" * 13 # 13 字节正确长度的 IHDR 数据
|
||||
ihdr_chunk = struct.pack(">I", 13) + b"IHDR" + ihdr_body + b"\x00" * 4 # 长度 + 类型 + 数据 + 占位 CRC
|
||||
iend_chunk = struct.pack(">I", 0) + b"IEND" + b"\x00" * 4 # 0 字节 IEND
|
||||
return PNG_SIGNATURE + ihdr_chunk + iend_chunk
|
||||
|
||||
|
||||
# ============================================================
|
||||
# _verify_png_integrity
|
||||
# ============================================================
|
||||
|
||||
class TestVerifyPngIntegrity:
|
||||
def test_valid_png(self, tmp_path):
|
||||
f = tmp_path / "ok.png"
|
||||
f.write_bytes(_make_minimal_png_bytes())
|
||||
assert _verify_png_integrity(str(f)) is True
|
||||
|
||||
def test_missing_file(self, tmp_path):
|
||||
f = tmp_path / "nonexistent.png"
|
||||
assert _verify_png_integrity(str(f)) is False
|
||||
|
||||
def test_wrong_signature(self, tmp_path):
|
||||
f = tmp_path / "bad.png"
|
||||
f.write_bytes(b"NOTAPNGFILE" + b"\x00" * 100)
|
||||
assert _verify_png_integrity(str(f)) is False
|
||||
|
||||
def test_truncated_file_no_iend(self, tmp_path):
|
||||
f = tmp_path / "truncated.png"
|
||||
# 有正确签名,但末尾没有 IEND 块
|
||||
f.write_bytes(PNG_SIGNATURE + b"\x00" * 50)
|
||||
assert _verify_png_integrity(str(f)) is False
|
||||
|
||||
def test_too_short(self, tmp_path):
|
||||
# 文件长度 < 8 字节签名长度
|
||||
f = tmp_path / "tiny.png"
|
||||
f.write_bytes(b"\x89PN")
|
||||
assert _verify_png_integrity(str(f)) is False
|
||||
|
||||
|
||||
# ============================================================
|
||||
# _safe_replace_file
|
||||
# ============================================================
|
||||
|
||||
class TestSafeReplaceFile:
|
||||
def test_replace_creates_target(self, tmp_path):
|
||||
src = tmp_path / "src.txt"
|
||||
dst = tmp_path / "dst.txt"
|
||||
src.write_text("hello")
|
||||
result = _safe_replace_file(str(src), str(dst))
|
||||
assert result is True
|
||||
assert dst.read_text() == "hello"
|
||||
# 源文件应被消费(os.replace 的语义:移动而非复制)
|
||||
# 但由于实现可能用 copy + remove 兜底,src 是否还在不强求
|
||||
|
||||
def test_replace_existing_target(self, tmp_path):
|
||||
src = tmp_path / "src.txt"
|
||||
dst = tmp_path / "dst.txt"
|
||||
src.write_text("new content")
|
||||
dst.write_text("old content")
|
||||
result = _safe_replace_file(str(src), str(dst))
|
||||
assert result is True
|
||||
assert dst.read_text() == "new content"
|
||||
|
||||
def test_missing_source_returns_false(self, tmp_path):
|
||||
# 源文件不存在 → 应返回 False,不抛
|
||||
src = tmp_path / "nonexistent.txt"
|
||||
dst = tmp_path / "dst.txt"
|
||||
result = _safe_replace_file(str(src), str(dst))
|
||||
# 不强求 True/False,但绝不能抛异常
|
||||
assert isinstance(result, bool)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# _ensure_parent_dir
|
||||
# ============================================================
|
||||
|
||||
class TestEnsureParentDir:
|
||||
def test_creates_missing_parent(self, tmp_path):
|
||||
target = tmp_path / "a" / "b" / "c" / "file.txt"
|
||||
# 父目录此时不存在
|
||||
assert not target.parent.exists()
|
||||
|
||||
_ensure_parent_dir(str(target))
|
||||
|
||||
assert target.parent.is_dir()
|
||||
|
||||
def test_existing_parent_no_error(self, tmp_path):
|
||||
# 父目录已存在 → 应静默通过
|
||||
target = tmp_path / "file.txt"
|
||||
_ensure_parent_dir(str(target))
|
||||
assert tmp_path.is_dir()
|
||||
|
||||
def test_returns_none(self, tmp_path):
|
||||
target = tmp_path / "x" / "file.txt"
|
||||
assert _ensure_parent_dir(str(target)) is None
|
||||
@@ -0,0 +1,122 @@
|
||||
"""8 个 print→logger helper 的 pytest 单元测试。
|
||||
|
||||
每个 helper 都遵循同一模式:
|
||||
- 优先走 logger(INFO/WARNING/ERROR/DEBUG 分级)
|
||||
- logger 异常时兜底到 stdout
|
||||
- 不抛异常
|
||||
|
||||
带 analyser 参数的 helper(_yanghao_log / _robot_log)还会优先尝试 analyser._log_kv。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 8 个 helper 的元信息
|
||||
# ============================================================
|
||||
# (module_path, helper_name, takes_analyser)
|
||||
HELPERS = [
|
||||
("douyin.other.douyin_yanghao", "_yanghao_log", True),
|
||||
("douyin.other.douyin_robot", "_robot_log", True),
|
||||
("douyin.handlers.douyin_screenshot_manager", "_mgr_log", False),
|
||||
("operations.screenshot_service", "_svc_log", False),
|
||||
("operations.screenshot_operations", "_ops_log", False),
|
||||
("operations.ocr_operations", "_ocr_log", False),
|
||||
("gui.web_gui", "_wg_log", False),
|
||||
("douyin.core.underlying_operations", "_uo_log", False),
|
||||
]
|
||||
|
||||
|
||||
def _import_helper(module_path, helper_name):
|
||||
mod = __import__(module_path, fromlist=[helper_name])
|
||||
return getattr(mod, helper_name)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 通用:调用不抛异常 + 走 logger
|
||||
# ============================================================
|
||||
|
||||
@pytest.mark.parametrize("module_path,helper_name,takes_analyser", HELPERS)
|
||||
def test_helper_does_not_raise(module_path, helper_name, takes_analyser, caplog):
|
||||
"""正常调用 helper 不应抛异常,且至少有一条对应级别的 log 被发射。"""
|
||||
fn = _import_helper(module_path, helper_name)
|
||||
with caplog.at_level(logging.DEBUG):
|
||||
if takes_analyser:
|
||||
fn(None, "[test] info-level")
|
||||
fn(None, "[test] warn", level="WARNING")
|
||||
fn(None, "[test] err", level="ERROR")
|
||||
fn(None, "[test] dbg", level="DEBUG")
|
||||
else:
|
||||
fn("[test] info-level")
|
||||
fn("[test] warn", level="WARNING")
|
||||
fn("[test] err", level="ERROR")
|
||||
fn("[test] dbg", level="DEBUG")
|
||||
# 至少捕获到 1 条记录(不要求全部,因为 DEBUG 可能被父 logger 过滤)
|
||||
assert any("[test]" in r.message for r in caplog.records), (
|
||||
f"{module_path}.{helper_name} 未发射任何 [test] 日志"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module_path,helper_name,takes_analyser", HELPERS)
|
||||
def test_helper_with_unknown_level(module_path, helper_name, takes_analyser, caplog):
|
||||
"""传未知 level 也应不抛(一般会兜底为 INFO)。"""
|
||||
fn = _import_helper(module_path, helper_name)
|
||||
with caplog.at_level(logging.DEBUG):
|
||||
if takes_analyser:
|
||||
fn(None, "[test] unknown-level", level="WHATEVER")
|
||||
else:
|
||||
fn("[test] unknown-level", level="WHATEVER")
|
||||
# 不抛即通过
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 带 analyser 参数的 helper:优先调用 analyser._log_kv
|
||||
# ============================================================
|
||||
|
||||
class FakeAnalyser:
|
||||
"""收集 _log_kv 调用,用于断言。"""
|
||||
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
def _log_kv(self, *args, **kwargs):
|
||||
self.calls.append((args, kwargs))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"module_path,helper_name",
|
||||
[
|
||||
("douyin.other.douyin_yanghao", "_yanghao_log"),
|
||||
("douyin.other.douyin_robot", "_robot_log"),
|
||||
],
|
||||
)
|
||||
def test_analyser_log_kv_preferred(module_path, helper_name):
|
||||
"""analyser 提供 _log_kv 时,helper 应优先走 _log_kv。"""
|
||||
fn = _import_helper(module_path, helper_name)
|
||||
a = FakeAnalyser()
|
||||
fn(a, "[test] should-go-to-log-kv", level="WARNING")
|
||||
assert a.calls, f"{helper_name} 未调用 analyser._log_kv"
|
||||
|
||||
|
||||
class BrokenAnalyser:
|
||||
"""_log_kv 总是抛异常,模拟 analyser 处于异常状态。"""
|
||||
|
||||
def _log_kv(self, *args, **kwargs):
|
||||
raise RuntimeError("analyser._log_kv broken")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"module_path,helper_name",
|
||||
[
|
||||
("douyin.other.douyin_yanghao", "_yanghao_log"),
|
||||
("douyin.other.douyin_robot", "_robot_log"),
|
||||
],
|
||||
)
|
||||
def test_broken_analyser_does_not_raise(module_path, helper_name):
|
||||
"""analyser._log_kv 抛异常时,helper 应静默兜底而非把异常抛给调用方。"""
|
||||
fn = _import_helper(module_path, helper_name)
|
||||
# 不应抛任何异常
|
||||
fn(BrokenAnalyser(), "[test] broken", level="ERROR")
|
||||
@@ -3,12 +3,28 @@
|
||||
"""
|
||||
OCR引擎性能对比测试
|
||||
测试 EasyOCR vs PaddleOCR 的各项性能参数
|
||||
|
||||
注意:本文件是性能对比脚本,不是单元测试。它会真实加载 OCR 引擎、跑识别流程,
|
||||
耗时通常数十秒到数分钟,且依赖 psutil / easyocr / paddleocr 全部可用。
|
||||
pytest 自动跑会失败/超时——通过 importorskip 把这些可选依赖缺失时跳过整个文件。
|
||||
|
||||
要跑性能对比,直接执行:
|
||||
python tests/test_ocr_comparison.py
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
# 缺任一可选依赖时整个文件跳过;同时正常以脚本运行 (__main__) 时也走这条 import
|
||||
psutil = pytest.importorskip("psutil", reason="性能对比脚本,需要 psutil")
|
||||
pytest.importorskip("easyocr", reason="性能对比脚本,需要 easyocr")
|
||||
pytest.importorskip("paddleocr", reason="性能对比脚本,需要 paddleocr")
|
||||
|
||||
# 整个模块用 slow marker 标记;CI 默认不跑,要跑就 'pytest -m slow tests/test_ocr_comparison.py'
|
||||
pytestmark = pytest.mark.slow
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import psutil
|
||||
import gc
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
"""douyin/core/path_config 的 pytest 单元测试。
|
||||
|
||||
只做"返回值类型正确 + 路径在项目根下 + 路径不重复"等结构性断言,
|
||||
不假设具体绝对路径(避免在不同机器上脆弱)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
|
||||
PROJECT_ROOT = path_config.get_project_root()
|
||||
|
||||
|
||||
def _is_under_root(p: str) -> bool:
|
||||
"""检查路径是否在项目根之内。"""
|
||||
return os.path.commonpath([os.path.abspath(p), PROJECT_ROOT]) == PROJECT_ROOT
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 项目根
|
||||
# ============================================================
|
||||
|
||||
class TestProjectRoot:
|
||||
def test_root_is_absolute(self):
|
||||
assert os.path.isabs(PROJECT_ROOT)
|
||||
|
||||
def test_root_exists(self):
|
||||
assert os.path.isdir(PROJECT_ROOT)
|
||||
|
||||
def test_root_contains_douyin_package(self):
|
||||
assert os.path.isdir(os.path.join(PROJECT_ROOT, "douyin"))
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 各路径函数:返回类型 + 在项目根下
|
||||
# ============================================================
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"fn_name",
|
||||
[
|
||||
"get_project_root",
|
||||
"get_config_path",
|
||||
"get_logs_dir",
|
||||
"get_pic_dir",
|
||||
"get_screenshot_path",
|
||||
"get_state_dir",
|
||||
"get_reservations_path",
|
||||
"get_high_value_rooms_path",
|
||||
"get_assets_dir",
|
||||
"get_actions_log_path",
|
||||
],
|
||||
)
|
||||
def test_path_function_returns_path_under_root(fn_name):
|
||||
fn = getattr(path_config, fn_name)
|
||||
p = fn()
|
||||
assert isinstance(p, str), f"{fn_name} 应返回 str"
|
||||
assert p, f"{fn_name} 不应返回空字符串"
|
||||
assert _is_under_root(p), f"{fn_name}={p} 应位于项目根 {PROJECT_ROOT} 下"
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 关键路径具体形态
|
||||
# ============================================================
|
||||
|
||||
class TestSpecificPaths:
|
||||
def test_config_path_endswith_config_json(self):
|
||||
assert path_config.get_config_path().endswith(
|
||||
os.path.join("config", "config.json")
|
||||
)
|
||||
|
||||
def test_reservations_path_in_douyin_core_state(self):
|
||||
# main 上重构后的"实际位置"
|
||||
assert path_config.get_reservations_path().endswith(
|
||||
os.path.join("douyin", "core", "state", "reservations.json")
|
||||
)
|
||||
|
||||
def test_state_dir_at_root_level(self):
|
||||
# state/ 是项目根下的目录(与 reservations.json 实际位置不同)
|
||||
state_dir = path_config.get_state_dir()
|
||||
assert state_dir.endswith(os.sep + "state") or state_dir.endswith("/state")
|
||||
|
||||
def test_high_value_rooms_path_in_state_dir(self):
|
||||
path = path_config.get_high_value_rooms_path()
|
||||
assert path.endswith(
|
||||
os.path.join("state", "high_value_rooms.json")
|
||||
)
|
||||
|
||||
def test_screenshot_path_in_pic_dir(self):
|
||||
path = path_config.get_screenshot_path()
|
||||
assert path.endswith(os.path.join("pic", "screenshot.png"))
|
||||
|
||||
def test_actions_log_in_logs_dir(self):
|
||||
path = path_config.get_actions_log_path()
|
||||
assert path.endswith(os.path.join("logs", "actions.log"))
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 路径间不应互相重复
|
||||
# ============================================================
|
||||
|
||||
def test_distinct_paths():
|
||||
paths = {
|
||||
path_config.get_config_path(),
|
||||
path_config.get_logs_dir(),
|
||||
path_config.get_pic_dir(),
|
||||
path_config.get_state_dir(),
|
||||
path_config.get_reservations_path(),
|
||||
path_config.get_high_value_rooms_path(),
|
||||
path_config.get_assets_dir(),
|
||||
path_config.get_screenshot_path(),
|
||||
path_config.get_actions_log_path(),
|
||||
}
|
||||
# set 长度 = 元素数量 → 全部路径互不相同
|
||||
expected = 9
|
||||
assert len(paths) == expected, f"应有 {expected} 条不同路径,实际 {len(paths)}"
|
||||
@@ -0,0 +1,69 @@
|
||||
"""douyin/utils/time_utils 的 pytest 单元测试。
|
||||
|
||||
覆盖 parse_mm_ss(mm:ss 解析)和 extract_2digits(数字提取)两个纯函数。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from douyin.utils.time_utils import extract_2digits, parse_mm_ss
|
||||
|
||||
|
||||
# ============================================================
|
||||
# parse_mm_ss
|
||||
# ============================================================
|
||||
|
||||
class TestParseMmSs:
|
||||
@pytest.mark.parametrize(
|
||||
"text,expected",
|
||||
[
|
||||
("11:37", (11, 37)),
|
||||
("00:00", (0, 0)),
|
||||
("5:30", (5, 30)),
|
||||
("12:59", (12, 59)),
|
||||
# 中文冒号
|
||||
("11:37".replace(":", ":"), (11, 37)),
|
||||
("5:30后开奖".replace(":", ":"), (5, 30)),
|
||||
# 嵌在文本里
|
||||
("剩余 03:25 开奖", (3, 25)),
|
||||
],
|
||||
)
|
||||
def test_valid(self, text, expected):
|
||||
assert parse_mm_ss(text) == expected
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text",
|
||||
[
|
||||
"",
|
||||
None,
|
||||
"abc",
|
||||
"12分钟", # 没冒号
|
||||
"12",
|
||||
"::",
|
||||
],
|
||||
)
|
||||
def test_invalid(self, text):
|
||||
assert parse_mm_ss(text) is None
|
||||
|
||||
|
||||
# ============================================================
|
||||
# extract_2digits
|
||||
# ============================================================
|
||||
|
||||
class TestExtract2Digits:
|
||||
@pytest.mark.parametrize(
|
||||
"text,expected",
|
||||
[
|
||||
("12", "12"),
|
||||
("123", "12"), # 取前 2 位
|
||||
("9", "09"), # 单位补 0
|
||||
("a3b", "03"), # 过滤非数字
|
||||
("10秒", "10"),
|
||||
("剩余3", "03"),
|
||||
("", ""), # 无数字 → 空
|
||||
("abc", ""),
|
||||
(None, ""),
|
||||
],
|
||||
)
|
||||
def test_extract(self, text, expected):
|
||||
assert extract_2digits(text) == expected
|
||||
@@ -0,0 +1,127 @@
|
||||
"""douyin/logging/unified_logger.MDC 的 pytest 单元测试。
|
||||
|
||||
MDC(Mapped Diagnostic Context)用线程本地存储跟踪 trace_id 等上下文。
|
||||
覆盖 put / get / get_all / remove / clear / set_trace_id / get_trace_id 7 个方法。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from douyin.logging.unified_logger import MDC
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_mdc_after_each_test():
|
||||
"""每个测试结束都清空 MDC,避免相互污染。"""
|
||||
yield
|
||||
MDC.clear()
|
||||
|
||||
|
||||
# ============================================================
|
||||
# put / get / get_all / remove / clear
|
||||
# ============================================================
|
||||
|
||||
class TestPutGet:
|
||||
def test_put_and_get(self):
|
||||
MDC.put("user_id", "alice")
|
||||
assert MDC.get("user_id") == "alice"
|
||||
|
||||
def test_get_default_when_missing(self):
|
||||
assert MDC.get("nonexistent") is None
|
||||
assert MDC.get("nonexistent", "fallback") == "fallback"
|
||||
|
||||
def test_get_all_returns_copy(self):
|
||||
MDC.put("k1", "v1")
|
||||
MDC.put("k2", "v2")
|
||||
all_ctx = MDC.get_all()
|
||||
assert all_ctx == {"k1": "v1", "k2": "v2"}
|
||||
# 修改返回的字典不应影响 MDC 内部状态
|
||||
all_ctx["k3"] = "v3"
|
||||
assert MDC.get("k3") is None
|
||||
|
||||
def test_overwrite_value(self):
|
||||
MDC.put("k", "v1")
|
||||
MDC.put("k", "v2")
|
||||
assert MDC.get("k") == "v2"
|
||||
|
||||
|
||||
class TestRemove:
|
||||
def test_remove_existing_key(self):
|
||||
MDC.put("k", "v")
|
||||
MDC.remove("k")
|
||||
assert MDC.get("k") is None
|
||||
|
||||
def test_remove_nonexistent_does_not_raise(self):
|
||||
# 删不存在的 key 不应抛
|
||||
MDC.remove("nonexistent")
|
||||
|
||||
|
||||
class TestClear:
|
||||
def test_clear_removes_everything(self):
|
||||
MDC.put("k1", "v1")
|
||||
MDC.put("k2", "v2")
|
||||
MDC.clear()
|
||||
assert MDC.get("k1") is None
|
||||
assert MDC.get("k2") is None
|
||||
assert MDC.get_all() == {}
|
||||
|
||||
def test_clear_on_empty_does_not_raise(self):
|
||||
MDC.clear() # 空状态再 clear 也应不抛
|
||||
|
||||
|
||||
# ============================================================
|
||||
# trace_id
|
||||
# ============================================================
|
||||
|
||||
class TestTraceId:
|
||||
def test_set_explicit_trace_id(self):
|
||||
result = MDC.set_trace_id("abc-123")
|
||||
assert result == "abc-123"
|
||||
assert MDC.get_trace_id() == "abc-123"
|
||||
|
||||
def test_set_auto_generates_trace_id(self):
|
||||
result = MDC.set_trace_id()
|
||||
# 自动生成的应是非空字符串
|
||||
assert isinstance(result, str)
|
||||
assert len(result) > 0
|
||||
assert MDC.get_trace_id() == result
|
||||
|
||||
def test_get_trace_id_when_unset(self):
|
||||
# 没设过的话,get 返回 None
|
||||
assert MDC.get_trace_id() is None
|
||||
|
||||
def test_clear_removes_trace_id(self):
|
||||
MDC.set_trace_id("abc")
|
||||
MDC.clear()
|
||||
assert MDC.get_trace_id() is None
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 线程隔离:MDC 是线程本地存储
|
||||
# ============================================================
|
||||
|
||||
class TestThreadLocal:
|
||||
def test_mdc_is_thread_local(self):
|
||||
"""主线程的 MDC 不应污染其他线程。"""
|
||||
MDC.put("main_thread_key", "main_value")
|
||||
|
||||
results = {}
|
||||
|
||||
def worker():
|
||||
# 子线程里看不到主线程的值
|
||||
results["child_get"] = MDC.get("main_thread_key")
|
||||
MDC.put("child_thread_key", "child_value")
|
||||
results["child_self"] = MDC.get("child_thread_key")
|
||||
|
||||
t = threading.Thread(target=worker)
|
||||
t.start()
|
||||
t.join()
|
||||
|
||||
assert results["child_get"] is None, "子线程不应看到主线程的 MDC 值"
|
||||
assert results["child_self"] == "child_value"
|
||||
# 主线程也不应看到子线程的值
|
||||
assert MDC.get("child_thread_key") is None
|
||||
# 主线程自己的值还在
|
||||
assert MDC.get("main_thread_key") == "main_value"
|
||||
+28
-34
@@ -1,41 +1,35 @@
|
||||
import sys
|
||||
import os
|
||||
import time
|
||||
import subprocess
|
||||
import threading
|
||||
"""gui/web_gui 的 import 冒烟测试。
|
||||
|
||||
# Add project root to path
|
||||
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if project_root not in sys.path:
|
||||
sys.path.insert(0, project_root)
|
||||
老版本会真实启动 HTTP 服务并请求 /api/config,pytest 运行时会卡住。
|
||||
重写为只验证模块能正常加载、关键属性存在;启动服务的端到端验证留给手动测试。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import gui.web_gui as wg
|
||||
|
||||
def test_server():
|
||||
# Start server in background thread
|
||||
def run_server():
|
||||
try:
|
||||
wg.main()
|
||||
except SystemExit:
|
||||
pass
|
||||
def test_web_gui_module_importable():
|
||||
"""模块能 import,不抛异常。"""
|
||||
import gui.web_gui as wg
|
||||
|
||||
server_thread = threading.Thread(target=run_server, daemon=True)
|
||||
server_thread.start()
|
||||
# 关键符号存在
|
||||
assert hasattr(wg, "main"), "gui.web_gui 应导出 main()"
|
||||
assert callable(wg.main)
|
||||
|
||||
# Wait for server to start
|
||||
time.sleep(2)
|
||||
|
||||
# Test API
|
||||
try:
|
||||
import requests
|
||||
response = requests.get('http://localhost:8001/api/config', timeout=5)
|
||||
print(f"Status: {response.status_code}")
|
||||
print(f"Response length: {len(response.text)}")
|
||||
data = response.json()
|
||||
print(f"Config keys: {len(data)}")
|
||||
print(f"Sample keys: {list(data.keys())[:5]}")
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
def test_web_gui_helper_functions():
|
||||
"""模块级 helper 应可调用。"""
|
||||
import gui.web_gui as wg
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_server()
|
||||
assert callable(wg.read_config)
|
||||
assert callable(wg.find_adb_executable)
|
||||
assert callable(wg.list_adb_devices)
|
||||
# _wg_log 是项目里 print→logger 改造引入的内部 helper
|
||||
assert callable(wg._wg_log)
|
||||
|
||||
|
||||
def test_web_gui_log_helper_does_not_raise():
|
||||
"""_wg_log 不应抛异常。"""
|
||||
import gui.web_gui as wg
|
||||
|
||||
wg._wg_log("[smoke] info")
|
||||
wg._wg_log("[smoke] warn", level="WARNING")
|
||||
wg._wg_log("[smoke] error", level="ERROR")
|
||||
+2
-2
@@ -19,7 +19,7 @@
|
||||
} catch (e) {}
|
||||
})();
|
||||
</script>
|
||||
<link rel="stylesheet" href="styles.css?v=console-20260520-theme-v34" />
|
||||
<link rel="stylesheet" href="styles.css?v=console-20260520-theme-v35" />
|
||||
</head>
|
||||
<body>
|
||||
<div class="app">
|
||||
@@ -1274,6 +1274,6 @@
|
||||
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m18 15-6-6-6 6"/></svg>
|
||||
</button>
|
||||
|
||||
<script src="app.js?v=console-20260520-theme-v34"></script>
|
||||
<script src="app.js?v=console-20260520-theme-v35"></script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user