如果你对软件测试、面试经验交流感兴趣欢迎加入软件测试技术群:695458161,群里发放的免费资料都是笔者十多年测试生涯的精华。还有同行大神一起交流技术哦。

自动化测试中的三类等待深入剥析

上一篇 / 下一篇  2020-05-14 22:21:24 / 个人分类:WEB自动化

一、前言

  • 在自动化过程中,常常需要用到等待时间的设置方法,这里整理一下!

二、三类等待详解

1. 强制等待(线程等待)

  • 需要设置固定的等待时间,无论元素是否加载完成,均需等待该时间
  • 由time.sleep()方法实现
  • 不推荐使用
import time time.sleep(5)     # 固定此段等待时间为5s

2. 隐式等待

  • 隐式等待是由webdriver提供的超时等待方法;
  • implicitly_wait()比 time.sleep() 更加智能,implicitly_wait()是在一个时间范围内智能等待,time.sleep() 只能选择一个固定的时间的等待;
  • 当使用了隐式等待执行测试的时候,如果 WebDriver没有在 DOM中找到元素,将继续等待,超出设定时间后则抛出找不到元素的异常;
  • 换句话说,当查找元素或元素并没有立即出现的时候,隐式等待将等待一段时间再查找 DOM,默认的时间是0;
  • 一旦设置了隐式等待,则它存在整个 WebDriver 对象实例的声明周期中,隐式的等到会让一个正常响应的应用的测试变慢;
  • 它将会在寻找每个元素的时候都进行等待,这样会增加整个测试执行的时间。
# 针对全局元素设置的等待时间self.driver.implicitly_wait(20)
  • 如果你觉得此文对你有帮助,如果你对软件测试、面试经验感兴趣欢迎加入软件测试技术群:695458161,群里发放的免费资料都是笔者十多年测试生涯的精华。还有同行大神一起交流技术哦。


3. 显示等待

  • 显式等待是针对某个元素来设置的等待时间
  • 在设置时间内,默认每隔一段时间检测一次当前。页面元素是否存在,如果超过设置时间检测不到则抛出异常。
  • 详细格式如下:
classWebDriverWait(object):def__init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None):"""Constructor, takes a WebDriver instance and timeout in seconds.

          :Args:
           - driver - Instance of WebDriver (Ie, Firefox, Chrome or Remote)
           - timeout - Number of seconds before timing out
           - poll_frequency - sleep interval between calls
             By default, it is 0.5 second.
           - ignored_exceptions - iterable structure of exception classes ignored during calls.
             By default, it contains NoSuchElementException only.

          Example:
           from selenium.webdriver.support.ui import WebDriverWait \n
           element = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("someId")) \n
           is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)).\ \n
                       until_not(lambda x: x.find_element_by_id("someId").is_displayed())
       """self._driver = driver
       self._timeout = timeout
       self._poll = poll_frequency# avoid the divide by zeroifself._poll ==0:
           self._poll = POLL_FREQUENCY
       exceptions = list(IGNORED_EXCEPTIONS)ifignored_exceptionsisnotNone:try:
               exceptions.extend(iter(ignored_exceptions))exceptTypeError:# ignored_exceptions is not iterableexceptions.append(ignored_exceptions)
       self._ignored_exceptions = tuple(exceptions)def__repr__(self):return'<{0.__module__}.{0.__name__} (session="{1}")>'.format(
           type(self), self._driver.session_id)defuntil(self, method, message=''):"""Calls the method provided with the driver as an argument until the \
       return value is not False."""screen =Nonestacktrace =Noneend_time = time.time() + self._timeoutwhileTrue:try:
               value = method(self._driver)ifvalue:returnvalueexceptself._ignored_exceptionsasexc:
               screen = getattr(exc,'screen',None)
               stacktrace = getattr(exc,'stacktrace',None)
           time.sleep(self._poll)iftime.time() > end_time:breakraiseTimeoutException(message, screen, stacktrace)defuntil_not(self, method, message=''):"""Calls the method provided with the driver as an argument until the \
       return value is False."""end_time = time.time() + self._timeoutwhileTrue:try:
               value = method(self._driver)ifnotvalue:returnvalueexceptself._ignored_exceptions:returnTruetime.sleep(self._poll)iftime.time() > end_time:breakraiseTimeoutException(message)
  • 一般搭配until()或until_not()方法配合使用,另外,lambda还提供了一个运行时动态创建函数的方法。
from selenium.webdriver.support.ui import WebDriverWait

WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id('test'))

三、等待方法在自动化框架中如何封装

#定位元素deffind_ele(self,*args):try:
            ele = WebDriverWait(self.driver,10).until(lambdax:x.find_element(*args))returneleexceptException:#在页面上没有定位到元素self.logger.error("元素定位失败:通过"+args[0]+"定位,元素是"+args[1]+"")



TAG:

 

评分:0

我来说两句

诸葛_

诸葛_

如果你对软件测试、面试经验交流感兴趣欢迎加入软件测试技术群:695458161,群里发放的免费资料都是笔者十多年测试生涯的精华。还有同行大神一起交流技术哦。

日历

« 2024-03-25  
     12
3456789
10111213141516
17181920212223
24252627282930
31      

数据统计

  • 访问量: 21896
  • 日志数: 38
  • 建立时间: 2020-04-01
  • 更新时间: 2020-06-29

RSS订阅

Open Toolbar