一般我们在做自动化测试时,测试结束后都会用的发送邮件或者钉钉消息,这个时候我们就会可以通过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 如何发送钉钉消息》
执行结果:

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



被折叠的 条评论
为什么被折叠?



