328 lines
11 KiB
Python
328 lines
11 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
预约回退错误场景测试脚本
|
||
=======================
|
||
|
||
特意制造各种差错,测试预约系统能否正确回退。
|
||
|
||
测试内容:
|
||
1. 滑动操作失败:模拟ADB命令执行失败
|
||
2. 位置计算错误:模拟room_pos更新异常
|
||
3. 校验失败重试:模拟校验失败后的重试逻辑
|
||
4. 回退超时:模拟回退操作超时
|
||
5. 映射表不一致:模拟运行时映射表与预约记录不匹配
|
||
6. 最大回退次数限制:测试超出限制后的处理
|
||
|
||
运行方法:
|
||
python test_reservation_error_scenarios.py
|
||
|
||
预期结果:
|
||
系统能在各种错误情况下正确处理并成功回退
|
||
"""
|
||
|
||
import time
|
||
import sys
|
||
import os
|
||
import random
|
||
|
||
# 添加项目根目录到路径
|
||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||
|
||
from douyin.reservation.douyin_reservation_verify import validate_back_to_reservation
|
||
|
||
|
||
class MockOperation:
|
||
"""模拟操作对象"""
|
||
|
||
def __init__(self):
|
||
self.mock_ocr_result = "美女主播在线" # 默认OCR结果
|
||
|
||
def get_screenshot(self, device_id):
|
||
"""模拟截图"""
|
||
pass
|
||
|
||
def analyse_pic_word(self, cut_name, change_color):
|
||
"""模拟OCR识别"""
|
||
return self.mock_ocr_result
|
||
|
||
|
||
class MockAnalyser:
|
||
"""模拟分析器对象,支持各种错误场景"""
|
||
|
||
def __init__(self, error_scenario=None):
|
||
# 基本配置
|
||
self.reservation_back_verify_enabled = True
|
||
self.high_value_fudai_max_swipe_back = 5 # 较小的限制便于测试
|
||
self.reservation_back_total_timeout_seconds = 5.0
|
||
|
||
# 位置信息
|
||
self.room_pos = 5 # 当前在第5个直播间
|
||
self._room_pos_to_title_map = {
|
||
1: ("主播小明直播间", "主播小明直播间"),
|
||
2: ("美女主播在线", "美女主播在线"),
|
||
3: ("游戏直播高手", "游戏直播高手"),
|
||
4: ("音乐现场直播", "音乐现场直播"),
|
||
5: ("科技数码直播", "科技数码直播"), # 当前位置
|
||
6: ("美食烹饪教学", "美食烹饪教学"),
|
||
7: ("旅游风景直播", "旅游风景直播"),
|
||
}
|
||
|
||
# 滑动计数器和错误控制
|
||
self.swipe_up_count = 0
|
||
self.swipe_down_count = 0
|
||
self.swipe_failures = 0
|
||
self.position_update_failures = 0
|
||
|
||
# 错误场景控制
|
||
self.error_scenario = error_scenario
|
||
self.retry_count = 0
|
||
self.max_retries = 3
|
||
|
||
# 日志
|
||
self.logs = []
|
||
|
||
# Mock operation对象
|
||
self.operation = MockOperation()
|
||
self.device_id = "mock_device"
|
||
|
||
def _log_kv(self, tag, message, **kwargs):
|
||
"""记录日志"""
|
||
log_entry = f"[{tag}] {message}"
|
||
if kwargs:
|
||
log_entry += f" {kwargs}"
|
||
self.logs.append(log_entry)
|
||
print(log_entry)
|
||
|
||
def cut_pic(self, x1, y1, x2, y2, filename, desc, y_pianyi=0):
|
||
"""模拟截图裁剪"""
|
||
pass
|
||
|
||
def _simulate_swipe_error(self):
|
||
"""模拟滑动错误"""
|
||
if self.error_scenario == "swipe_failure" and random.random() < 0.3:
|
||
self.swipe_failures += 1
|
||
print(f"模拟滑动失败 #{self.swipe_failures}")
|
||
return False
|
||
return True
|
||
|
||
def _simulate_position_error(self):
|
||
"""模拟位置更新错误"""
|
||
if self.error_scenario == "position_update_failure" and random.random() < 0.2:
|
||
self.position_update_failures += 1
|
||
print(f"模拟位置更新失败 #{self.position_update_failures}")
|
||
return False
|
||
return True
|
||
|
||
def _seek_reservation_room_with_errors(self, item):
|
||
"""带错误模拟的回退函数"""
|
||
target_pos = int(item.get("pos_seen", 0))
|
||
current_pos = self.room_pos
|
||
pos_diff = target_pos - current_pos
|
||
|
||
print(f"模拟回退:从位置 {current_pos} 到位置 {target_pos} (差值: {pos_diff})")
|
||
|
||
if pos_diff == 0:
|
||
print("已在目标位置")
|
||
return True
|
||
|
||
# 计算需要滑动的次数
|
||
if pos_diff < 0:
|
||
# 向上回退
|
||
max_steps = min(abs(pos_diff), self.high_value_fudai_max_swipe_back)
|
||
direction = "down"
|
||
else:
|
||
# 向下前进
|
||
max_steps = min(pos_diff, self.high_value_fudai_max_swipe_back)
|
||
direction = "up"
|
||
|
||
print(f"需要执行 {max_steps} 次向{direction}滑动")
|
||
|
||
# 模拟滑动过程,包含错误
|
||
actual_steps = 0
|
||
for i in range(max_steps):
|
||
if not self._simulate_swipe_error():
|
||
print(f"滑动失败,停止在步骤 {i+1}")
|
||
break
|
||
|
||
# 执行滑动
|
||
if direction == "down":
|
||
self.swipe_down_count += 1
|
||
if self._simulate_position_error():
|
||
self.room_pos -= 1
|
||
else:
|
||
self.swipe_up_count += 1
|
||
if self._simulate_position_error():
|
||
self.room_pos += 1
|
||
|
||
actual_steps += 1
|
||
print(f"步骤 {i+1}: 滑动成功,当前位置 {self.room_pos}")
|
||
|
||
# 检查是否到达目标
|
||
if self.room_pos == target_pos:
|
||
print(f"成功到达目标位置 {target_pos}")
|
||
return True
|
||
|
||
# 检查最终位置
|
||
if self.room_pos == target_pos:
|
||
print("最终成功到达目标位置")
|
||
return True
|
||
else:
|
||
print(f"回退未完成:当前位置 {self.room_pos}, 目标位置 {target_pos}")
|
||
return False
|
||
|
||
|
||
def test_error_scenarios():
|
||
"""测试各种错误场景"""
|
||
|
||
print("=" * 80)
|
||
print("预约回退错误场景测试")
|
||
print("=" * 80)
|
||
|
||
test_cases = [
|
||
{"name": "正常情况", "scenario": None, "description": "无错误情况下的正常回退"},
|
||
{
|
||
"name": "滑动失败",
|
||
"scenario": "swipe_failure",
|
||
"description": "模拟滑动操作随机失败",
|
||
},
|
||
{
|
||
"name": "位置更新失败",
|
||
"scenario": "position_update_failure",
|
||
"description": "模拟位置更新随机失败",
|
||
},
|
||
{
|
||
"name": "组合错误",
|
||
"scenario": "combined_errors",
|
||
"description": "同时模拟滑动和位置更新错误",
|
||
},
|
||
]
|
||
|
||
# 测试预约项
|
||
test_reservation = {
|
||
"future_ts": time.time() + 300, # 5分钟后
|
||
"prize_value_yuan": 100.0,
|
||
"created_ts": time.time() - 100,
|
||
"pos_seen": 2, # 目标位置(距离较远,便于测试错误)
|
||
"room_title": "美女主播在线",
|
||
"room_title_raw": "美女主播在线",
|
||
}
|
||
|
||
for i, test_case in enumerate(test_cases, 1):
|
||
print(f"\n测试{i}:{test_case['name']}")
|
||
print("-" * 50)
|
||
print(f"描述:{test_case['description']}")
|
||
|
||
# 创建分析器
|
||
analyser = MockAnalyser(test_case["scenario"])
|
||
|
||
# 设置随机种子以便重现
|
||
random.seed(42 + i)
|
||
|
||
# 重置状态
|
||
analyser.room_pos = 5
|
||
analyser.swipe_up_count = 0
|
||
analyser.swipe_down_count = 0
|
||
analyser.swipe_failures = 0
|
||
analyser.position_update_failures = 0
|
||
|
||
print(f"初始位置: {analyser.room_pos}")
|
||
print(f"目标位置: {test_reservation['pos_seen']}")
|
||
|
||
# 执行回退
|
||
start_time = time.time()
|
||
result = analyser._seek_reservation_room_with_errors(test_reservation)
|
||
end_time = time.time()
|
||
|
||
# 输出结果
|
||
print(f"回退结果: {'成功' if result else '失败'}")
|
||
print(f"最终位置: {analyser.room_pos}")
|
||
print(
|
||
f"滑动统计: 向上{analyser.swipe_up_count}次, 向下{analyser.swipe_down_count}次"
|
||
)
|
||
print(
|
||
f"错误统计: 滑动失败{analyser.swipe_failures}次, 位置更新失败{analyser.position_update_failures}次"
|
||
)
|
||
print(f"执行时间: {end_time - start_time:.2f}秒")
|
||
# 验证结果
|
||
if result and analyser.room_pos == test_reservation["pos_seen"]:
|
||
print("✓ 测试通过:成功回退到目标位置")
|
||
elif not result and analyser.room_pos != test_reservation["pos_seen"]:
|
||
print("✓ 测试通过:正确处理了错误情况")
|
||
else:
|
||
print("✗ 测试失败:结果不符合预期")
|
||
|
||
# 测试校验失败重试逻辑
|
||
print("\n测试5:校验失败重试逻辑")
|
||
print("-" * 50)
|
||
|
||
analyser = MockAnalyser()
|
||
analyser.room_pos = 5 # 故意设置错误位置
|
||
|
||
# 模拟校验失败后的重试
|
||
max_retry_attempts = 3
|
||
for attempt in range(max_retry_attempts):
|
||
print(f"重试次数 {attempt + 1}/{max_retry_attempts}")
|
||
|
||
# 模拟回退操作
|
||
analyser.room_pos = 5 # 重置到错误位置
|
||
analyser._seek_reservation_room_with_errors(test_reservation)
|
||
|
||
# 执行校验
|
||
result, detail = validate_back_to_reservation(analyser, test_reservation)
|
||
|
||
if result:
|
||
print(f"✓ 第{attempt + 1}次重试成功")
|
||
break
|
||
else:
|
||
print(f"✗ 第{attempt + 1}次校验失败,继续重试")
|
||
# 在实际系统中,这里会再次尝试回退
|
||
analyser.room_pos = 5 # 模拟重新开始
|
||
|
||
if not result:
|
||
print("✗ 重试逻辑测试失败:多次重试后仍未成功")
|
||
|
||
# 测试超时情况
|
||
print("\n测试6:超时情况")
|
||
print("-" * 50)
|
||
|
||
analyser = MockAnalyser()
|
||
analyser.reservation_back_total_timeout_seconds = 0.1 # 很短的超时时间
|
||
|
||
start_time = time.time()
|
||
# 模拟耗时操作
|
||
time.sleep(0.2) # 超过超时时间
|
||
end_time = time.time()
|
||
|
||
if end_time - start_time > analyser.reservation_back_total_timeout_seconds:
|
||
print("✓ 超时检测正确:操作时间超过限制")
|
||
else:
|
||
print("✗ 超时检测失败")
|
||
|
||
# 测试映射表不一致
|
||
print("\n测试7:映射表不一致")
|
||
print("-" * 50)
|
||
|
||
analyser = MockAnalyser()
|
||
analyser.room_pos = 2 # 在目标位置
|
||
|
||
# 修改映射表,使当前位置的标题与预约记录不一致
|
||
analyser._room_pos_to_title_map[2] = ("错误的直播间", "错误的直播间")
|
||
|
||
# 设置OCR识别结果为错误的标题
|
||
analyser.operation.mock_ocr_result = "错误的直播间"
|
||
|
||
result, detail = validate_back_to_reservation(analyser, test_reservation)
|
||
|
||
if not result:
|
||
print("✓ 映射表不一致检测正确:校验失败")
|
||
else:
|
||
print("✗ 映射表不一致检测失败:校验错误通过")
|
||
|
||
print("\n" + "=" * 80)
|
||
print("错误场景测试完成")
|
||
print("=" * 80)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
test_error_scenarios()
|