#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 测试截图错误处理和重试机制 """ import time import sys import os import subprocess from unittest.mock import patch, MagicMock # 添加项目根目录到路径 sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) def test_adb_error_codes(): """测试ADB错误码处理""" print("测试ADB错误码处理...") print("=" * 50) from operations.screenshot_operations import ScreenshotOperations ops = ScreenshotOperations() # 测试错误码4294967295的处理 print("\n1. 测试错误码4294967295 (设备连接失败)") try: # 模拟adb命令返回4294967295 with patch('subprocess.Popen') as mock_popen: mock_process = MagicMock() mock_process.wait.return_value = 4294967295 mock_process.stdout.read.side_effect = [b'', b''] # 空数据 mock_popen.return_value = mock_process result = ops._get_screenshot_direct("test_device") print(f"截图结果: {result}") print("预期: False (截图失败)") except Exception as e: print(f"异常: {e}") print("\n2. 测试正常截图流程") # 这里不实际测试,因为需要真实的adb环境 print("跳过实际截图测试(需要真实设备)") def test_retry_mechanism(): """测试重试机制""" print("\n3. 测试重试机制模拟") # 模拟3次失败后成功的情况 retry_count = 0 max_retries = 3 success = False for retry in range(max_retries): retry_count = retry + 1 print(f"重试 {retry_count}/{max_retries}") # 模拟前两次失败,第3次成功 if retry < 2: print(" 截图失败") else: print(" 截图成功") success = True break if retry < max_retries - 1: print(" 等待1秒后重试...") time.sleep(0.1) # 实际测试中用较短时间 print(f"\n最终结果: {'成功' if success else '失败'}") print(f"重试次数: {retry_count}") def test_error_messages(): """测试错误消息""" print("\n4. 测试错误消息") # 模拟不同的错误情况 error_scenarios = [ (4294967295, "设备连接失败"), (1, "ADB命令错误"), ("timeout", "操作超时"), ("unknown", "未知错误") ] for error_code, expected_desc in error_scenarios: print(f"错误码 {error_code}: {expected_desc}") print("\n错误处理改进:") print("- 添加了设备连接状态检查") print("- 区分不同类型的ADB错误") print("- 提供更详细的错误诊断信息") print("- 实现截图失败时的重试机制") if __name__ == "__main__": test_adb_error_codes() test_retry_mechanism() test_error_messages() print("\n" + "=" * 50) print("截图错误处理测试完成") print("修复内容:") print("1. 添加ADB错误码4294967295的特殊处理") print("2. 改进错误消息,提供更详细的诊断信息") print("3. 在douyin_fudai.py中添加截图重试机制") print("4. 当截图失败时会重试3次,而不是直接放弃")