Files
douyi_guaji_main/deleted_tests_backup/test_direct_screenshot.py
T
Your Name 0b5f150691 Refactor and clean up code across multiple scripts
- Removed trailing whitespace and ensured files end with a single newline in cleanup_unused_files.py.
- Added fix_trailing_whitespace.py to batch remove trailing whitespace from Python files.
- Updated install_dependencies.py to improve dependency installation prompts.
- Cleaned up pick_coords.py by removing unnecessary whitespace and improving code readability.
- Enhanced region_selector.py by disabling specific pylint checks for better compatibility with third-party libraries.
- Improved WPS流程图生成工具.py by cleaning up whitespace and enhancing readability.
- Updated __init__.py in typings to remove unnecessary lines.
- Modified app.js to adjust default configuration values and clean up unused code.
2026-01-02 23:57:03 +08:00

288 lines
9.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
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.
#!/usr/bin/env python3
"""
测试直接截图功能
验证所有截图调用都使用直接模式(use_service=False)
"""
import os
import sys
import time
from datetime import datetime
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def test_screenshot_operations():
"""测试 operations.screenshot_operations 模块"""
print("=" * 80)
print("测试 1: operations.screenshot_operations.get_screenshot()")
print("=" * 80)
try:
from operations.screenshot_operations import get_screenshot, ScreenshotOperations
# 获取设备ID
device_id = os.environ.get("DEVICE_ID", "")
if not device_id:
print("[WARN] 未设置 DEVICE_ID 环境变量,尝试从配置读取...")
try:
import json
import path_config
config_path = path_config.get_config_path()
# 尝试从常见位置读取
device_id = "MB75DEFQZHZTGMLJ" # 从日志中看到的设备ID
except Exception:
print("[ERROR] 无法获取设备ID,请设置环境变量 DEVICE_ID")
return False
print(f"设备ID: {device_id}")
print(f"测试模式: 直接截图 (use_service=False)")
print()
# 测试1: 使用默认参数(应该是 False)
print("测试 1.1: 使用默认参数调用 get_screenshot()")
start = time.time()
try:
result = get_screenshot(device_id)
elapsed = (time.time() - start) * 1000
status = "[OK] 成功" if result else "[FAIL] 失败"
print(f" 结果: {status}, 耗时: {elapsed:.1f}ms")
except Exception as e:
elapsed = (time.time() - start) * 1000
print(f" [ERROR] 异常: {e}, 耗时: {elapsed:.1f}ms")
print()
# 测试2: 显式传递 use_service=False
print("测试 1.2: 显式传递 use_service=False")
start = time.time()
try:
ops = ScreenshotOperations()
result = ops.get_screenshot(device_id, use_service=False)
elapsed = (time.time() - start) * 1000
status = "[OK] 成功" if result else "[FAIL] 失败"
print(f" 结果: {status}, 耗时: {elapsed:.1f}ms")
except Exception as e:
elapsed = (time.time() - start) * 1000
print(f" [ERROR] 异常: {e}, 耗时: {elapsed:.1f}ms")
print()
# 测试3: 验证不会使用服务模式
print("测试 1.3: 验证不会调用后台服务")
try:
from operations.screenshot_service import ScreenshotService
service = ScreenshotService.get_instance()
service_running_before = service.is_running()
print(f" 服务运行状态(测试前): {service_running_before}")
# 调用截图(应该不会启动服务)
get_screenshot(device_id)
service_running_after = service.is_running()
print(f" 服务运行状态(测试后): {service_running_after}")
if not service_running_after:
print(" [OK] 确认:服务未被启动(符合预期)")
else:
print(" [WARN] 警告:服务仍在运行(可能之前已启动)")
except Exception as e:
print(f" [WARN] 无法检查服务状态: {e}")
return True
except ImportError as e:
print(f"[ERROR] 导入错误: {e}")
return False
except Exception as e:
print(f"[ERROR] 测试失败: {e}")
import traceback
traceback.print_exc()
return False
def test_underlying_operations():
"""测试 Underlying_Operations 模块"""
print()
print("=" * 80)
print("测试 2: Underlying_Operations.get_screenshot()")
print("=" * 80)
try:
from Underlying_Operations import underlying_operations
device_id = os.environ.get("DEVICE_ID", "MB75DEFQZHZTGMLJ")
print(f"设备ID: {device_id}")
print()
ops = underlying_operations()
# 测试默认参数
print("测试 2.1: 使用默认参数(应该是 False)")
start = time.time()
try:
result = ops.get_screenshot(device_id)
elapsed = (time.time() - start) * 1000
status = "[OK] 成功" if result else "[FAIL] 失败"
print(f" 结果: {status}, 耗时: {elapsed:.1f}ms")
if elapsed > 2000:
print(f" [WARN] 警告:耗时较长 ({elapsed:.1f}ms),但应该 < 2秒")
elif elapsed > 6000:
print(f" [ERROR] 错误:耗时过长 ({elapsed:.1f}ms),可能仍在使用服务模式")
else:
print(f" [OK] 正常:耗时在预期范围内")
except Exception as e:
elapsed = (time.time() - start) * 1000
print(f" [ERROR] 异常: {e}, 耗时: {elapsed:.1f}ms")
import traceback
traceback.print_exc()
return True
except Exception as e:
print(f"[ERROR] 测试失败: {e}")
import traceback
traceback.print_exc()
return False
def test_stage_diagnosis_screenshot():
"""测试阶段诊断中的截图调用"""
print()
print("=" * 80)
print("测试 3: 阶段诊断截图调用(模拟)")
print("=" * 80)
try:
# 检查关键文件中的调用
import inspect
from douyin.core import douyin_fudai
# 查找 get_screenshot 调用
source_file = inspect.getfile(douyin_fudai.fudai_analyse)
with open(source_file, 'r', encoding='utf-8') as f:
content = f.read()
# 检查是否包含 use_service=False
if 'get_screenshot(self.device_id, use_service=False)' in content:
print(" [OK] 确认:douyin_fudai.py 中已使用 use_service=False")
elif 'get_screenshot(self.device_id)' in content:
print(" [WARN] 警告:douyin_fudai.py 中未显式传递 use_service=False")
print(" (但默认值应该是 False)")
else:
print(" [WARN] 未找到 get_screenshot 调用")
return True
except Exception as e:
print(f" [WARN] 无法检查: {e}")
return False
def check_logs_for_timeouts():
"""检查日志中是否有超时记录"""
print()
print("=" * 80)
print("测试 4: 检查日志中的超时记录")
print("=" * 80)
try:
import glob
log_files = glob.glob("logs/unified_*.log")
if not log_files:
print(" [WARN] 未找到日志文件")
return True
# 读取最新的日志文件
latest_log = max(log_files, key=os.path.getmtime)
print(f" 检查日志文件: {latest_log}")
timeout_count = 0
screenshot_count = 0
with open(latest_log, 'r', encoding='utf-8', errors='ignore') as f:
# 只读取最后 1000 行
lines = f.readlines()[-1000:]
for line in lines:
if '[TIMEOUT] 等待超时' in line or '等待超时' in line:
timeout_count += 1
if 'screenshot_elapsed_seconds' in line:
screenshot_count += 1
# 提取耗时
try:
import re
match = re.search(r'screenshot_elapsed_seconds=([\d.]+)', line)
if match:
elapsed = float(match.group(1))
if elapsed > 5.0:
print(f" [WARN] 发现耗时过长的截图: {elapsed:.2f}秒")
except Exception:
pass
print(f" 超时记录数(最近1000行): {timeout_count}")
print(f" 截图耗时记录数: {screenshot_count}")
if timeout_count == 0:
print(" [OK] 未发现超时记录(符合预期)")
else:
print(f" [WARN] 发现 {timeout_count} 条超时记录")
return True
except Exception as e:
print(f" [WARN] 无法检查日志: {e}")
return False
def main():
"""主测试函数"""
print()
print("=" * 80)
print("直接截图功能测试")
print("=" * 80)
print(f"测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print()
results = []
# 测试1: screenshot_operations
results.append(("screenshot_operations", test_screenshot_operations()))
# 测试2: underlying_operations
results.append(("underlying_operations", test_underlying_operations()))
# 测试3: 代码检查
results.append(("stage_diagnosis", test_stage_diagnosis_screenshot()))
# 测试4: 日志检查
results.append(("log_check", check_logs_for_timeouts()))
# 总结
print()
print("=" * 80)
print("测试总结")
print("=" * 80)
passed = sum(1 for _, result in results if result)
total = len(results)
for name, result in results:
status = "[PASS] 通过" if result else "[FAIL] 失败"
print(f" {name}: {status}")
print()
print(f"总计: {passed}/{total} 测试通过")
if passed == total:
print("[SUCCESS] 所有测试通过!")
return 0
else:
print("[WARN] 部分测试未通过,请检查上述输出")
return 1
if __name__ == "__main__":
exit(main())