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

pytest-生命周期钩子函数

武飞扬头像
weixin_44153651
帮助1

1、增加自定义参数

  1.  
    def pytest_addoption(parser):
  2.  
    # pytest的钩子函数,自动执行
  3.  
    # 增加自定义参数
  4.  
    parser.addoption(
  5.  
    "--browser_type",
  6.  
    action="store",
  7.  
    default="chrome",
  8.  
    help="浏览器类型"
  9.  
    )

2、定制化自带的html报告

  1.  
    def pytest_html_results_summary(prefix, summary, postfix):
  2.  
    # 在Summary中增加项目名称
  3.  
    prefix.extend([html.p("项目名称: xxxx")])
  4.  
     
  5.  
    def pytest_html_report_title(report):
  6.  
    report.title = "UI测试报告"
  7.  
     
  8.  
    def pytest_html_results_table_header(cells):
  9.  
    # 表头增加列和删除列
  10.  
    cells.insert(2, html.th('Description'))
  11.  
    cells.insert(3, html.th('Time', class_='sortable time', col='time'))
  12.  
    cells.pop(-1) # 删除link列
  13.  
     
  14.  
     
  15.  
    @pytest.mark.optionalhook
  16.  
    def pytest_html_results_table_row(report, cells):
  17.  
    # 表格内容增加列和删除列
  18.  
    cells.insert(2, html.td(report.description))
  19.  
    cells.insert(3, html.td(datetime.utcnow(), class_='col-time'))
  20.  
    cells.pop(-1) # 删除link列
  21.  
     
  22.  
    @pytest.hookimpl(hookwrapper=True)
  23.  
    def pytest_runtest_makereport(item):
  24.  
    """
  25.  
    报告列表中添加描述信息
  26.  
    当测试失败的时候,自动截图,展示到html报告中
  27.  
    """
  28.  
    pytest_html = item.config.pluginmanager.getplugin('html')
  29.  
    outcome = yield
  30.  
    report = outcome.get_result()
  31.  
    report.description = str(item.function.__doc__)
  32.  
    # report.nodeid = report.nodeid.encode("utf-8").decode("unicode_escape") # 设置编码显示中文
  33.  
    extra = getattr(report, 'extra', [])
  34.  
     
  35.  
    if report.when == 'call' or report.when == "setup":
  36.  
    xfail = hasattr(report, 'wasxfail')
  37.  
    if (report.skipped and xfail) or (report.failed and not xfail):
  38.  
    screen_img = _capture_screenshot()
  39.  
    if screen_img:
  40.  
    html = '<div><img src="data:image/png;base64,%s" alt="screenshot" style="width:1024px;height:768px;" ' \
  41.  
    'onclick="window.open(this.src)" align="right"/></div>' % screen_img
  42.  
    extra.append(pytest_html.extras.html(html))
  43.  
    report.extra = extra
  44.  
     
  45.  
     
  46.  
    def _capture_screenshot():
  47.  
    """截图保存为base64"""
  48.  
     
  49.  
    now_time, screen_file = cm.screen_path
  50.  
    driver.save_screenshot(screen_file)
  51.  
    allure.attach.file(screen_file, "失败截图{}".format(now_time), allure.attachment_type.PNG)
  52.  
    with open(screen_file, 'rb') as f:
  53.  
    imagebase64 = base64.b64encode(f.read())
  54.  
    return imagebase64.decode()
学新通

3、收集测试结果

  1.  
    def pytest_terminal_summary(terminalreporter, exitstatus, config):
  2.  
    """
  3.  
    收集测试结果,用于jenkins发送邮件
  4.  
    """
  5.  
    # print('==================收集测试结果')
  6.  
    total = terminalreporter._numcollected
  7.  
    passed = len([i for i in terminalreporter.stats.get('passed', []) if i.when != 'teardown'])
  8.  
    failed = len([i for i in terminalreporter.stats.get('failed', []) if i.when != 'teardown'])
  9.  
    error = len([i for i in terminalreporter.stats.get('error', []) if i.when != 'teardown'])
  10.  
    skipped = len([i for i in terminalreporter.stats.get('skipped', []) if i.when != 'teardown'])
  11.  
    successful = (len(terminalreporter.stats.get('passed', [])) / terminalreporter._numcollected * 100)
  12.  
    duration = time.time() - terminalreporter._sessionstarttime
  13.  
    failed_cases_list = [{'name': i.location[-1], 'desc': i.description} for i in terminalreporter.stats.get('failed', []) if i.when != 'teardown']
  14.  
    error_cases_list = [{'name': i.location[-1], 'desc': i.description} for i in terminalreporter.stats.get('error', []) if i.when != 'teardown']
  15.  
     
  16.  
    # 将结果保存在本地,供jenkins调用
  17.  
    with open("result.txt", "w", encoding="utf-8") as fp:
  18.  
    fp.write("TOTAL=%s" % total "\n")
  19.  
    fp.write("PASSED=%s" % passed "\n")
  20.  
    fp.write("FAILED=%s" % failed "\n")
  21.  
    fp.write("ERROR=%s" % error "\n")
  22.  
    fp.write("SKIPPED=%s" % skipped "\n")
  23.  
    fp.write("SUCCESSFUL=%.2f%%" % successful "\n")
  24.  
    fp.write("TOTAL_TIMES=%.2fs" % duration "\n")
学新通

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

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