pytest 通过HOOK获取执行结果

    一般我们在做自动化测试时,测试结束后都会用的发送邮件或者钉钉消息,这个时候我们就会可以通过HOOK方法获取测试结果,然后发送邮件或者钉钉内容。我们用到的HOOK方法是:pytest_terminal_summary()---这个方法会返回所有的测试结果。

    以下是示例方法:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/2/20 10:17
# @Author  : herry
# @File    : pytest模块分享之hook.py
# @software: PyCharm
# @describe: pytest模块分享之hook


import pytest




def setup():
    print("setup_function")




@pytest.mark.L1
@pytest.mark.B
def test_A():
    print("AAA")




@pytest.mark.A
def test_B():
    print("BBB")


class TestA:
    def setup(self):
        print("aaa")
    @pytest.mark.A
    def testA1(self):
        print("test1111")


    @pytest.mark.A
    def testA2(self):
        print("test2222")
        assert  False


    @pytest.mark.A
    @pytest.mark.skip
    def testA3(self):
        print("test333")


    @pytest.fixture()
    def fix(self):
        raise  Exception("ERROR")


    @pytest.mark.A
    def testA4(self,fix):
        assert fix


    def teardown(self):
        print("bbbb")




if __name__ == "__main__":
    pytest.main([("pytest模块分享之hook.py"), ("-s"), ("-m=A")])

conftest.py文件:

def pytest_terminal_summary(terminalreporter,exitstatus,config):
    '''收集测试结果'''


    total=terminalreporter._numcollected
    passed=len(terminalreporter.stats.get("passed",[]))
    failed=len(terminalreporter.stats.get("failed",[]) )
    error=len(terminalreporter.stats.get("error",[]))
    skipped=len(terminalreporter.stats.get("skipped",[]))
    duration = time.time() - terminalreporter._sessionstarttime
    deselected=len(terminalreporter.stats.get("deselected",[])) #过滤的用例数
    content="【自动化测试报告】\t\n" \
            "用例总数:%s\t\n" \
            "执行用例总数:%s \t\n" \
            "执行成功数:%s \t\n" \
            "执行失败数:%s \t\n" \
            "执行ERROR数:%s \t\n" \
            "执行SKIP数:%s \t\n" \
            "执行成功数:%.2f %%  \t\n" \
            "执行时长:%.2f 秒 \t\n"%(total,total-deselected,passed,failed,error,skipped,passed/(total-deselected)*100,duration)


    print(content)
    ###后面可以调用钉钉、发邮件等方法

发送邮件方法:《python 如何发送邮件》

发送钉钉消息:《python 如何发送钉钉消息

执行结果:

4ab2e22f53bee406389193bfa0af1fa1.png

-----------最后------------

 更多软件测试相关内容请关注“软件测试道与术”公众号或扫描下方二维码

d736dc48ca87edbd5d3189437e915bd7.jpeg

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值