简介:场景假设 - 当运行pytest完成后,需要针对运行的结果进行即时的反馈,打印 PASS 或者 FAIL,及其运行失败的原因,最后将结果推送给消息机器人。
历史攻略:
Python配置与测试利器:Hydra + pytest的完美结合
Playwright - 04:pytest并行、并发、运行浏览器兼容性测试
分析源码:
pytest.main()的执行结果为枚举,依次为以下6种情况。
@final
class ExitCode(enum.IntEnum):
#: Tests passed.
OK = 0
#: Tests failed.
TESTS_FAILED = 1
#: pytest was interrupted.
INTERRUPTED = 2
#: An internal error got in the way.
INTERNAL_ERROR = 3
#: pytest was misused.
USAGE_ERROR = 4
#: pytest couldn't find tests.
NO_TESTS_COLLECTED = 5
根据结果进行判断输出,使用艺术字模块打印 PASS 或者 FAIL即可。
案例源码:
# -*- coding: utf-8 -*-
# time: 2024/3/22 0:30
# file: main.py
# 公众号: 玩转测试开发
import os
import pytest
from pyfiglet import Figlet
from colorama import Fore, Back, Style
if __name__ == "__main__":
# step-1:use pytest run test_case
result = pytest.main(["-s", "test_case/test_demo.py", "-n=3", "--alluredir", "./report"])
f = Figlet(font='slant')
if result == 0:
print(Fore.GREEN + Back.BLACK + Style.BRIGHT + f.renderText('PASS'))
elif result == 1:
print(Fore.RED + Back.BLACK + Style.BRIGHT + f.renderText('FAIL'))
else:
pass
# step-2:auto report json data,zip to allure-html
os.system("allure serve report")
# os.popen("allure serve report")
requirements.txt
pytest
colorama
pyfiglet
pytest-html
pytest-xdist
allure-pytest
pytest-repeat
pytest-assume
pytest-rerunfailures
test_case/test_demo.py
# -*- coding: utf-8 -*-
# time: 2024/3/22 0:34
# file: test_demo.py
# 公众号: 玩转测试开发
import time
import unittest
class TestDemo(unittest.TestCase):
def test_01(self):
time.sleep(0.1)
print('测试用例1执行')
def test_02(self):
time.sleep(0.1)
print('测试用例2执行')
def test_03(self):
time.sleep(0.1)
print('测试用例3执行')
运行结果:
即:根据pytest的运行结果,控制台输出打印PASS或者FAIL,并显示allure报告,推送机器人(略),详见前一篇攻略。