Python测试框架pytest(12)
Hooks函数
其他Hooks函数
1、pytest_report_teststatus自定义测试结果
pytest_report_teststatus(report, config) 钩子函数返回结果类别,状态报告的短字母和详细单词。
结果类别是对结果进行计数的类别,例如 "passed"、"skipped"、"error" 或空字符串。
在测试过程中会显示短字母,例如 "."、"s"、"E" 或空字符串。
在详细模式下,随着测试的进行,将显示详细单词,例如 "PASSED"、"SKIPPED"、"ERROR" 或空字符串。
参数:
创建test_case.py文件
脚本代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公众号:AllTests软件测试
"""
import pytest
@pytest.fixture()
def my_setup():
print("前置操作")
assert 0 == 1
@pytest.fixture()
def my_teardown():
yield
print("后置操作")
assert 0 == 1
def test_case1(my_setup):
assert 1 == 1
def test_case2():
assert 0 == 1
def test_case3():
assert 1 == 1
def test_case4():
assert 1 == 0
def test_case5(my_teardown):
assert 1 == 1
命令行执行命令:
pytest test_case.py
运行结果:
命令行执行pytest用例,默认情况下.代表通过的用例,F代表失败的用例,E代表异常的用例。
如果想自定义测试结果,就可以使用pytest_report_teststatus钩子函数,将函数写在conftest.py文件里。
创建conftest.py文件
将测试结果.自定义为√,F自定义为x,setup的error自定义为0,teardown的error自定义为1,跳过skipped自定义为/
脚本代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公众号:AllTests软件测试
"""
def pytest_report_teststatus(report, config):
if report.when == 'call' and report.passed:
return (report.outcome, '√', 'passed')
if report.when == 'call' and report.failed:
return (report.outcome, 'x', 'failed')
if report.when == 'setup' and report.failed:
return (report.outcome, '0', 'error')
if report.when == 'teardown' and report.failed:
return (report.outcome, '1', 'error')
if report.skipped:
return (report.outcome, '/', 'skipped')
命令行再次执行命令:
pytest test_case.py
运行结果:
按照自定义结果显示在控制台里。
2、pytest_generate_tests参数化生成测试用例
pytest_generate_tests 在测试用例参数化收集前调用此钩子函数,并根据测试配置或定义测试函数的类或模块中指定的参数值生成测试用例。
1、创建conftest.py文件
自定义参数化的钩子, 判断当测试用例传param参数时,生成参数化的用例。
通过传入的metafunc对象,检查请求的测试上下文,并可以调用metafunc.parametrize()方法进行参数化。
脚本代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公众号:AllTests软件测试
"""
def pytest_generate_tests(metafunc):
if "param" in metafunc.fixturenames:
metafunc.parametrize("param", metafunc.module.case_data, ids=metafunc.module.case_id, scope="function")
2、创建test_case.py文件
case_id为用例ID,case_data为用例数据
脚本代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公众号:AllTests软件测试
"""
case_id = ["001", "002"]
case_data = [{"url": "https://www.baidu.com/"},
{"url": "https://www.cnblogs.com/alltests/"}]
def test_url(param):
print("\n参数:" + str(param))
3、打开命令行,输入执行命令:
pytest -s -v test_case.py
运行结果:
3、更多Hooks函数
Hooks钩子函数总共有6大类:
关于Hooks钩子函数的详细使用,可查看官方文档:
https://docs.pytest.org/en/latest/reference/reference.html#hooks
本文分享自 AllTests软件测试 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!