24.异常自动截图

发布时间 2023-12-29 14:16:52作者: 想要暴富的小男孩

目录

 
  • 异常截图场景
  • 异常截图实现

异常截图场景

 
  • 场景:
    • 增加自动化测试代码的可测性
    • 丰富报告

实现原理

 
  • 装饰器
  • 自动化关键数据记录
    • 截图
    • 日志
    • page_source

实现代码

 
# 装饰器逻辑
def ui_exception_record(func):
    def run(*args, **kwargs):
        self = args[0]
        try:
            return func(*args, **kwargs)
        except Exception as e:
            # 这里添加所有的异常情况处理
            # 日志
            logger.warning("执行过程中发生异常")
            # 截图
            timestamp = int(time.time())
            image_path = f"./images/image_{timestamp}.PNG"
            page_source_path = f"./page_source/{timestamp}_page_source.html"
            # page_source
            with open(f"./page_source/{timestamp}_page_source.html", "w", encoding="u8") as f:
                f.write(self.driver.page_source)
            self.driver.save_screenshot(image_path)
            allure.attach.file(image_path, name="image", attachment_type=allure.attachment_type.PNG)
            # allure.attach.file(page_source_path, name="page_source", attachment_type=allure.attachment_type.HTML)
            allure.attach.file(page_source_path, name="page_source", attachment_type=allure.attachment_type.TEXT)
            raise e
    return run
# 错误的用例
class TestWeb:
    def setup_class(self):
        self.driver = webdriver.Chrome()

    @ui_exception_record
    def test_web(self):
        self.driver.get("https://www.baidu.com/")
        self.driver.find_element(By.ID, "su11")

    def teardown_class(self):
        self.driver.quit()