Pytest测试框架系列 - pytest_runtest_makereport 配合自动提交缺陷!

本文介绍了如何在自动化测试中利用pytest框架获取测试用例执行状态,并在用例失败时自动提交缺陷到Redmine系统。通过分析pytest_runtest_makereport的执行流程,关注'call'阶段的执行结果,实现用例失败时的缺陷报告。同时,演示了如何使用python-redmine库来对接Redmine系统并创建缺陷。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

我们都知道测试用例执行失败后,我们会提交相应缺陷到公司缺陷平台,那我们自动化测试完成了,对于执行失败的用例,是不是也需要将失败的用例也提交相应缺陷呢,这种肯定的。作为测试人员,提交缺陷是我们工作的必不可缺少的部分,如何测试人员不提交缺陷了,那就代表已经脱离了测试人员的职责了。

那么在做自动化测试的时候,肯定希望如果用例执行失败了就自动提交缺陷,这样大大减少了人工再去提交缺陷的时间成本,那我们该怎么做呢,我们在这里面需要考虑一些问题。

  • 在用例执行过程中,如何获取用例执行状态
  • 如何对接缺陷系统,提交缺陷

获取用例执行状态

pytest框架 pytest_runtest_makereport 查看源码:

def pytest_runtest_makereport(item: Item, call: CallInfo[None]) -> TestReport:
    return TestReport.from_item_and_call(item, call)

说明:item是测试用例,call是测试步骤,具体执行过程如下:

  • 先执行when=‘setup’ 返回setup 的执行结果
  • 然后执行when=‘call’ 返回call 的执行结果
  • 最后执行when='teardown’返回teardown 的执行结果

使用方法:

@hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item: Item, call: CallInfo[None]):
    outcome = yield
    rep = outcome.get_result()
    xfailed = item._store.get(xfailed_key, None)
    # unittest special case, see setting of unexpectedsuccess_key
    if unexpectedsuccess_key in item._store and rep.when == "call":
        reason = item._store[unexpectedsuccess_key]
        .............

基本使用

根据源码及使用方式,我们先尝试使用一下:
conftest.py

# !/usr/bin/python3
# _*_coding:utf-8 _*_
""""
# @Time  :2021/7/20 18:39
# @Author  : king
# @File    :conftest.py
# @Software  :PyCharm
# @blog     :https://blog.youkuaiyun.com/u010454117
# @WeChat Official Account: 【测试之路笔记】
"""
from _pytest.config import hookimpl

@hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    out = yield

    report = out.get_result()
    print("当前有哪些方法", report.__dict__)
    print("***************************************")

test_report.py

# !/usr/bin/python3
# _*_coding:utf-8 _*_
""""
# @Time  :2021/7/20 18:45
# @Author  : king
# @File    :test_report.py
# @Software  :PyCharm
# @blog     :https://blog.youkuaiyun.com/u010454117
# @WeChat Official Account: 【测试之路笔记】
"""
import pytest

def test_01():
    """用例描述:test_01"""
    print("我是测试用例 test_01 ")

if __name__ == '__main__':
    pytest.main()

执行 pytest -v -s test_report.py ,查看结果:
执行结果
从执行结果可以看出来 pytest_runtest_makereport 经过三个阶段:'when': 'setup''when': 'call''when': 'teardown'

这样我们就可以使用属性 whenoutcome 来判断用例执行结果,那我们该怎么来使用,在哪个阶段进行判断。再看下用例存在setupteardown时的情况。
contest.py 增加一个fixture函数,如下:

@pytest.fixture(scope="session", autouse=True)
def login():
    print("setup 前置操作")
    yield 
    print("teardown 后置操作"
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

测试之路king

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值