为何用sleep(1 - (time() - initTime))而非sleep(1)?超时场景解析
UI自动化测试延时逻辑疑问解答
问题背景
分析这段UI自动化测试代码时,疑惑为何使用initTime = time()后调用sleep(1 - (time() - initTime)),而非直接使用sleep(1)?二者在实现最长30秒超时倒计时的逻辑中有何差异?
代码片段
from time import time, sleep def __wait_for_element__(self, element_tag, locator, timeout=30): """等待元素出现,最长30秒""" result = False self.driver.implicitly_wait(0) locator = locator.upper() for i in range(timeout): initTime = time() try: if locator == 'ID' and self.is_element_present(By.ID, element_tag): result = True break elif locator == 'NAME' and self.is_element_present(By.NAME, element_tag): result = True break elif locator == 'XPATH' and self.is_element_present(By.XPATH, element_tag): result = True break elif locator == 'CSS' and self.is_element_present(By.CSS_SELECTORS, element_tag): result = True break else: logging.info(f"错误:定位方式不正确 = {locator}") except Exception as e: logging.error(e) print(f"__wait_for_element__ 执行异常: {e}") sleep(1 - (time() - initTime)) else: print( f"超时未找到元素,定位方式: {locator},元素标识: {element_tag}") self.driver.implicitly_wait(DEFAULT_IMPLICIT_WAIT) return result
二者核心差异
1. 直接使用sleep(1)的问题
每次循环的实际耗时 = 元素存在性检查的耗时 + 1秒。而is_element_present这类操作需要和浏览器交互,必然会消耗一定时间(比如0.2~0.5秒不等)。如果循环30次,总耗时会是30秒 + 30次检查的总耗时,最终实际超时时间会远大于设定的30秒,无法精准控制超时阈值。
2. 使用sleep(1 - (time() - initTime))的目的
这段代码的核心是让每次循环的总时长尽可能严格接近1秒:
- 先记录循环开始的时间
initTime - 执行元素检查操作后,计算已经消耗的时间
time() - initTime - 只sleep「1秒减去已消耗时间」的剩余时长,确保整个循环从开始到结束的总时长刚好接近1秒
这样30次循环的总耗时就能严格控制在30秒左右,完全符合代码注释中“最长30秒超时”的设计要求,不会因为检查操作的额外耗时导致超时时间失控。
内容的提问来源于stack exchange,提问作者Wagner Rusth
相关产品推荐
相关产品推荐

