分享几个自动化测试中常用的功能函数

栏目: 编程工具 · 发布时间: 7年前

内容简介:在自动化测试中会有很多意料之中意料之外的情况需要处理,你可以对特定的case写特定的逻辑,不过一些万金油式的功能函数还是能解决很多问题的。本文权当抛砖引玉,有兴趣的读者欢迎留言指教。完整的代码示范请移步GitHub:

在自动化测试中会有很多意料之中意料之外的情况需要处理,你可以对特定的case写特定的逻辑,不过一些万金油式的功能函数还是能解决很多问题的。本文权当抛砖引玉,有兴趣的读者欢迎留言指教。

完整的代码示范请移步GitHub: https://github.com/tobyqin/python_automation_utils

wait_for

函数实现

def wait_for(method, timeout=DEFAULT_TIMEOUT, poll_time=DEFAULT_POLL_TIME):
    """
    Wait for a method with timeout, return its result or raise error.
    The expecting result should NOT be False or equal to False.
    """

    end_time = time.time() + timeout
    exc_info = ()

    while True:
        try:
            value = method()
            if value:
                return value

        except Exception as exc:
            args_as_str = [str(x) for x in exc.args]
            exc_info = (type(exc).__name__, ','.join(args_as_str))

        time.sleep(poll_time)
        if time.time() > end_time:
            break

    message = "Timeout to wait for '{}()' in {} seconds.".format(
        method.__name__, timeout)

    if exc_info:
        message += " [{}]: {}".format(exc_info[0], exc_info[1])

    raise Exception(message)

调用示范

# 例一:等待页面
def page_ready():
    ...

wait_for(page_ready)
then_do_something()

# 例二:等待长操作
def calculation():
    # cost long time
    return something

result = wait_for(calculation,timeout=100,poll_time=10)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Learn Python the Hard Way

Learn Python the Hard Way

Zed A. Shaw / Addison-Wesley Professional / 2013-10-11 / USD 39.99

Master Python and become a programmer-even if you never thought you could! This breakthrough book and CD can help practically anyone get started in programming. It's called "The Hard Way," but it's re......一起来看看 《Learn Python the Hard Way》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

SHA 加密
SHA 加密

SHA 加密工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具