微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

pytest 异常自动截图装饰器

如何在遇到异常时软件自动截图和保留page source?

解决方法:使用自定义的装饰器

如何编写装饰器:

1.先搭建装饰器的架子

def wrapper(func):
  def inner(*arg,**kwargs):
    func(*arg,**kwargs) #func为被装饰的方法

    #实现逻辑

  return inner

2. 编写里面的逻辑

在这里就是当func方法出现异常即截图和获取page source;这里用try catch捕获异常;

3.引用装饰器

在用例上使用:@wrapper

如下:

import time

import allure


def fail_screenshot(func):
    def inner(*arg,**kwargs):
        driver = arg[0].search_ele.driver #这里比较重要,因为driver需要先调试寻找,看看怎么取到。因为在用例setup里面实例化search_ele,所以driver在里面
        try:
            func(*arg,**kwargs)
        except Exception:
            print("error!!!")
            timestamp = int(time.time())
            img_path = f"../screenshots/xueqiuTest_{timestamp}.PNG"
            page_source_path = f"../screenshots/source_page_xueqiuTest_{timestamp}.html"
            driver.save_screenshot(img_path)
            with open(page_source_path,'w',encoding="utf-8") as f:
                f.write(driver.page_source)

            allure.attach.file(img_path,name="screenshot",attachment_type=allure.attachment_type.PNG)
            raise Exception
    return inner

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐