recv函数返回0_Hook函数pytest_runtest_protocol——让你在执行代码时获取用例的结果...

005231b856d8ddd662b731ff78daa047.png

很多时候,我们要在执行测试时就要对case的结果做些额外的处理,比如把测试结果上传某个测试管理系统(Testail, X-ray, etc), 又或者更重要的是在测试跑失败时抓取现场的环境。这个时候我们希望测试框架可以提供一个接口可以捕获case的run result,而不是在每个用例里去写逻辑,pytest中hook函数pytest_runtest_protocol就可以满足你的需求。

conftest.py

from _pytest.runner import runtestprotocol


def pytest_runtest_protocol(item, nextitem):
    reports = runtestprotocol(item=item, nextitem=nextitem)
    for report in reports:
        if report.when == "call":
            if report.outcome == "failed":
                print("failure in call step...capture log")
        elif report.when == "setup":
            if report.outcome == "failed":
                print("failure in setup step...capture log")
        elif report.when == "teardown":
            if report.outcome == "failed":
                print("failure in teardown step...capture log")

test_ping.py

import os
import re
import pytest
import time

def get_ping_response(ip_addr):
    pid = os.popen("ping " + ip_addr)
    prompt = pid.read()
    m = re.search(r"Sent = (d+), Received = (d+), Lost = (d+) ((d+)% loss)", prompt)
    sent_num = int(m.group(1))
    recv_num = int(m.group(2))
    lost_num = int(m.group(3))
    lost_rate = int(m.group(4))
    return sent_num, recv_num, lost_num, lost_rate

@pytest.fixture()
def my_fixture():
    print("setup")
    raise Exception("setup failure")
    yield
    print("teardown")
    raise Exception("teardown failure")

def test_case2(my_fixture):
    lost_rate = get_ping_response("127.0.0.1")[3]
    assert lost_rate == 0

在pytest_runtest_protocol中我们调用了pytest.runner里的runtestprotocol函数返回每个case 的TestReport对象,TestReport对象的when字段指的是用例的执行阶段,包含setup,call和teardown。TestReport对象的outcome字段则是用例结果,包括passed,failed和skipped。这里逻辑很明显了,就是在测试用例执行的三个阶段,都handle了failed结果,定位问题非常清晰。

运行结果

C:UsersthinkPycharmProjectslearnpytestping_test>pytest -s --ip_type loopback test_ping.py::test
_case2
Test session starts (platform: win32, Python 3.7.0, pytest 5.1.3, pytest-sugar 0.9.2)
rootdir: C:UsersthinkPycharmProjectslearnpytestping_test, inifile: pytest.ini
plugins: allure-pytest-2.8.11, assume-2.2.0, html-2.0.0, metadata-1.8.0, sugar-0.9.2
collecting ... setup


?????????????????????????????????? ERROR at setup of test_case2 ???????????????????????????????????

    @pytest.fixture()
    def my_fixture():
        print("setup")
>       raise Exception("setup failure")
E       Exception: setup failure

test_ping.py:19: Exception
                                                                                     100% ██████████
failure in setup...capture log


Results (0.09s):
       1 error
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值