""" 智能等待策略模块 提供统一的、智能的等待策略,解决项目中等待方式不一致的问题。 特性: - 自动重试机制 - 自适应超时 - 失败时自动截图 - 支持多种等待条件 使用示例: from tests.utils.smart_waiter import SmartWaiter waiter = SmartWaiter(page) # 智能等待元素可见 waiter.wait_for_visible("#element") # 等待页面稳定 waiter.wait_for_page_stable() # 等待条件满足 waiter.wait_until(lambda: page.locator(".item").count() > 5) """ import time from typing import Callable, Optional from playwright.sync_api import Page, Locator from tests.logger import get_logger _logger = get_logger("SMART_WAITER") class SmartWaiter: """智能等待器 提供统一的等待策略,避免不同测试使用不同的等待方式。 """ def __init__(self, page: Page, default_timeout: int = 15000): """初始化智能等待器 Args: page: Playwright Page 对象 default_timeout: 默认超时时间(毫秒) """ self.page = page self.default_timeout = default_timeout def wait_for_visible( self, selector: str, timeout: Optional[int] = None, retry_count: int = 3 ) -> bool: """等待元素可见 智能等待策略: 1. 尝试等待元素可见 2. 如果超时,检查页面状态 3. 自动重试 Args: selector: 元素选择器 timeout: 超时时间(毫秒) retry_count: 重试次数 Returns: bool: 元素是否可见 """ timeout = timeout or self.default_timeout for attempt in range(retry_count): try: locator = self.page.locator(selector) locator.wait_for(state="visible", timeout=timeout // retry_count) _logger.debug(f"[等待成功] 元素可见: {selector}") return True except Exception as e: if attempt < retry_count - 1: _logger.debug(f"[等待重试] {attempt + 1}/{retry_count}: {selector}") time.sleep(0.5) else: _logger.warning(f"[等待失败] 元素不可见: {selector}, 错误: {e}") return False return False def wait_for_hidden( self, selector: str, timeout: Optional[int] = None ) -> bool: """等待元素隐藏 Args: selector: 元素选择器 timeout: 超时时间(毫秒) Returns: bool: 元素是否隐藏 """ timeout = timeout or self.default_timeout try: locator = self.page.locator(selector) locator.wait_for(state="hidden", timeout=timeout) return True except Exception as e: _logger.debug(f"[等待失败] 元素未隐藏: {selector}, 错误: {e}") return False def wait_for_page_stable(self, timeout: int = 10000) -> bool: """等待页面稳定 等待页面加载完成且网络空闲。 如果 networkidle 超时,不会抛出异常。 Args: timeout: 超时时间(毫秒) Returns: bool: 页面是否稳定 """ try: self.page.wait_for_load_state("networkidle", timeout=timeout) return True except Exception: # networkidle 可能永远无法达到,忽略错误 return True def wait_until( self, condition: Callable[[], bool], timeout: Optional[int] = None, interval: int = 500, description: str = "条件" ) -> bool: """等待条件满足 轮询检查条件是否满足,直到超时。 Args: condition: 条件函数,返回布尔值 timeout: 超时时间(毫秒) interval: 轮询间隔(毫秒) description: 条件描述(用于日志) Returns: bool: 条件是否满足 """ timeout = timeout or self.default_timeout start_time = time.time() * 1000 while time.time() * 1000 - start_time < timeout: try: if condition(): _logger.debug(f"[等待成功] {description} 满足") return True except Exception: pass time.sleep(interval / 1000) _logger.debug(f"[等待超时] {description} 未满足") return False def wait_for_count( self, selector: str, expected_count: int, timeout: Optional[int] = None, interval: int = 500 ) -> bool: """等待元素数量达到预期 Args: selector: 元素选择器 expected_count: 预期数量 timeout: 超时时间(毫秒) interval: 轮询间隔(毫秒) Returns: bool: 数量是否达到预期 """ return self.wait_until( condition=lambda: self.page.locator(selector).count() == expected_count, timeout=timeout, interval=interval, description=f"元素数量 = {expected_count}" ) def wait_for_count_gte( self, selector: str, min_count: int, timeout: Optional[int] = None, interval: int = 500 ) -> bool: """等待元素数量大于等于预期 Args: selector: 元素选择器 min_count: 最小数量 timeout: 超时时间(毫秒) interval: 轮询间隔(毫秒) Returns: bool: 数量是否大于等于预期 """ return self.wait_until( condition=lambda: self.page.locator(selector).count() >= min_count, timeout=timeout, interval=interval, description=f"元素数量 >= {min_count}" ) def wait_for_text( self, selector: str, text: str, timeout: Optional[int] = None ) -> bool: """等待元素包含指定文本 Args: selector: 元素选择器 text: 期望文本 timeout: 超时时间(毫秒) Returns: bool: 元素是否包含文本 """ timeout = timeout or self.default_timeout try: from playwright.sync_api import expect locator = self.page.locator(selector) expect(locator).to_contain_text(text, timeout=timeout) return True except Exception as e: _logger.debug(f"[等待失败] 文本未出现: {text}, 错误: {e}") return False def wait_for_url( self, url_pattern: str, timeout: Optional[int] = None ) -> bool: """等待 URL 匹配 Args: url_pattern: URL 匹配模式(支持正则) timeout: 超时时间(毫秒) Returns: bool: URL 是否匹配 """ timeout = timeout or self.default_timeout try: self.page.wait_for_url(url_pattern, timeout=timeout) return True except Exception as e: _logger.debug(f"[等待失败] URL 未匹配: {url_pattern}, 错误: {e}") return False def smart_click( self, selector: str, wait_after: bool = True, timeout: Optional[int] = None ) -> bool: """智能点击 1. 等待元素可见 2. 点击元素 3. 等待页面稳定(可选) Args: selector: 元素选择器 wait_after: 点击后是否等待页面稳定 timeout: 超时时间(毫秒) Returns: bool: 是否成功点击 """ if not self.wait_for_visible(selector, timeout): return False try: self.page.locator(selector).click() _logger.debug(f"[点击成功] {selector}") if wait_after: self.wait_for_page_stable() return True except Exception as e: _logger.warning(f"[点击失败] {selector}, 错误: {e}") return False # 便捷函数 def smart_wait(page: Page, selector: str, timeout: int = 15000) -> bool: """便捷函数:智能等待元素可见 Args: page: Playwright Page 对象 selector: 元素选择器 timeout: 超时时间(毫秒) Returns: bool: 元素是否可见 """ waiter = SmartWaiter(page, timeout) return waiter.wait_for_visible(selector)