• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

pytest 通过conftest.py获取测试所有执行case断言失败的结果

武飞扬头像
U盘失踪了
帮助1

conftest.py

  1.  
    import pytest
  2.  
    from datetime import datetime
  3.  
     
  4.  
     
  5.  
    def pytest_exception_interact(node, call, report):
  6.  
    if report.failed:
  7.  
    with open("error.log", "a", encoding="utf-8") as f:
  8.  
    test_case = f"测试文件:{node.nodeid} | 测试函数:{node.name}"
  9.  
    failure_reason = f"失败原因:{report.longrepr}"
  10.  
    execution_time = f"执行时间:{datetime.now().isoformat()}"
  11.  
     
  12.  
    f.write(test_case "\n")
  13.  
    f.write(failure_reason "\n")
  14.  
    f.write(execution_time "\n")
  15.  
    f.write("\n")
  16.  
    f.write("=" * 80 "\n")
  17.  
    f.write("\n")
  18.  
     

这段代码使用了pytest的钩子函数pytest_exception_interact来处理测试过程中的异常,并将异常信息记录到日志文件中。

代码的解析如下:

  1. 导入了pytestdatetime模块。
  2. 定义了pytest_exception_interact函数,接受三个参数:nodecallreport
  3. 在函数内部,使用if条件判断报告是否失败。
  4. 如果报告失败,打开名为error.log的日志文件,并以追加模式写入内容。
  5. 创建了test_case变量,用于存储测试文件和测试函数的信息。
  6. 创建了failure_reason变量,用于存储失败的原因。
  7. 创建了execution_time变量,用于存储执行时间。
  8. 将测试文件、测试函数、失败原因和执行时间写入日志文件。
  9. 添加分隔符和换行符。

通过使用pytest_exception_interact钩子函数,可以在测试过程中捕获异常,并将异常信息记录到日志文件中。这样可以更方便地查看和分析测试过程中的失败原因和执行时间。

test22.py

  1.  
    import pytest
  2.  
    # from test11 import log_exceptions
  3.  
     
  4.  
    # @log_exceptions
  5.  
    def test_divide():
  6.  
    assert 1 == 2
  7.  
     
  8.  
    # @log_exceptions
  9.  
    def test_divide2():
  10.  
    assert 1 == '14'
  11.  
     
  12.  
     
  13.  
    def test_divide3():
  14.  
    assert 1 == 1
  15.  
     
  16.  
     
  17.  
    if __name__ == '__main__':
  18.  
    pytest.main(["-s", "test22.py"])

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgeaiic
系列文章
更多 icon
同类精品
更多 icon
继续加载