pytest测试框架进阶-conftest文件重写采集和运行测试用例的hook函数

使用pytest不仅仅局限于进行单元测试,作为底层模块可扩展性强,有必要理解其运行机制,便于进行二次开发扩展,通过文档的学习很容易理解。

构建一个简单的测试脚本

import pytest
import requests

def add(a,b):
if type(a) is str or type(b) is str:
return str(a) + str(b)
return a+b

def chengfa(a,b):
if type(a) is str or type(b) is str:
return 0
return a*b

class TestMath(object):

@pytest.fixture(scope='session',autouse=True)
def starter(self):
print('开始')
yield
print('结束')

def testadd(self):
'''测试加法程序'''
print("正在执行testadd")
assert add('a',1) == 'a1'
print("验证成功")

def testchengfa(self):
'''测试加法程序'''
print("正在执行testadd")
assert chengfa('a',1) == 'a'
print("验证成功")

if __name__ == '__main__':
pytest.main(['-s','testmath.py'])

采集测试用例相关函数

@pytest.hookimpl(hookwrapper=True)
def pytest_collection(session):
print("当前运行"+sys._getframe().f_code.co_name)
print('启动测试采集器'+str(session))
result = yield
print('最终测试采集结果' + str(session.items))
print("结束运行" + sys._getframe().f_code.co_name)
print(" ")


@pytest.hookimpl(hookwrapper=True)
def pytest_collectstart(collector):
print("当前运行" + sys._getframe().f_code.co_name)
print("当前节点" +collector.nodeid)
result = yield
print("结束运行" + sys._getframe().f_code.co_name)
print(" ")

@pytest.hookimpl(hookwrapper=True)
def pytest_make_collect_report(collector):
print("当前运行" + sys._getframe().f_code.co_name)
result = yield
print("当前节点" +result.get_result().nodeid + ",采集结果:"+result.get_result().outcome+ ",采集节点为:"+str(result.get_result().result))
print("结束运行" + sys._getframe().f_code.co_name)
print(" ")

@pytest.hookimpl(hookwrapper=True)
def pytest_pycollect_makemodule(path, parent):
print("当前运行" + sys._getframe().f_code.co_name)
print('在目录' + str(parent.fspath) + '采集到测试脚本'+str(path))
result = yield
print('当前采集模块' + result.get_result().nodeid)
print("结束运行" + sys._getframe().f_code.co_name)
print(" ")

@pytest.hookimpl(hookwrapper=True)
def pytest_generate_tests(metafunc):
print("当前运行" + sys._getframe().f_code.co_name)
result = yield
print("结束运行" + sys._getframe().f_code.co_name)
print(" ")

@pytest.hookimpl(hookwrapper=True)
def pytest_collectreport(report):
print("当前运行" + sys._getframe().f_code.co_name)
print('在节点' + report.nodeid + '采集到' + str(report.result))
result = yield
print("结束运行" + sys._getframe().f_code.co_name)
print(" ")

@pytest.hookimpl(hookwrapper=True)
def pytest_collection_modifyitems(session, config, items):
print("当前运行" + sys._getframe().f_code.co_name)
result = yield
print('测试顺序为'+ str(items))
print("结束运行" + sys._getframe().f_code.co_name)
print(" ")



@pytest.hookimpl(hookwrapper=True)
def pytest_collection_finish(session):
print("当前运行" + sys._getframe().f_code.co_name)
result = yield
print('用例采集完成')
print("结束运行" + sys._getframe().f_code.co_name)
print(" ")

pytest_collection(session)

执行给定会话的采集协议。循环运行pytest_collectstart,pytest_make_collect_report遍历查找测试用例,直到所有用例采集成功

session:Session对象,基类_pytest.nodes.FSCollector

pytest_collectstart(collector)

Collector开始采集。

collector:Collector对象

采集器实例通过collect()创建子项,从而迭代地构建树。意思就是来寻找符合规则的测试节点变成Collector的nodeid,给pytest_make_collect_report使用。

pytest_make_collect_report(collector)

执行collector.collect()并返回CollectReport对象。返回采集当前节点采集测试节点是否成功,如果当前采集到节点是方法,会运行pytest_generate_tests生成测试用例对象。

pytest_pycollect_makemodule(path, parent) 

path:pytest测试的根目录,也可通过命令行设置,例如pytest C://xxx.py,path就为C://xxx.py

parent:任何新节点都需要将指定parent的父节点作为父节点

根据path目录向下查找,提取存在测试类的py文件。将为每个匹配的测试模块路径调用此Hook方法。如果要为不匹配的文件创建测试模块作为测试模块,则需要使用pytest_collect_fileHook方法。

pytest_collectreport(report)

report:CollectReport对象采集报告

Collector完成采集时调用,pytest_make_collect_report采集结果成功或失败,失败则报异常

pytest_generate_tests(metafunc)

metafunc: Metafunc对象

生成测试用例的方法,将自定义的fixture、parameters给测试函数调用变成测试用例对象。

pytest_collection_modifyitems(session, config, items):

config:Config对象,根据配置进行相应行为

 在执行收集后调用,可以就地过滤或重新排序项目。

pytest_collection_finish(session)

返回最终采集结果及数量

运行测试用例相关函数

@pytest.hookimpl(hookwrapper=True)
def pytest_runtestloop(session):
print("当前运行" + sys._getframe().f_code.co_name)
print('开始测试测试用例集合' + str(session.items))
result = yield
print('测试用例集合测试结果为' + str(session))
print("结束运行" + sys._getframe().f_code.co_name)
print(" ")

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_protocol(item,nextitem):
print("当前运行" + sys._getframe().f_code.co_name)
print('开始测试用例:'+str(item.name))
result = yield
print("结束运行" + sys._getframe().f_code.co_name)
print(" ")

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_setup(item):
print("当前运行" + sys._getframe().f_code.co_name)
print('执行setup模块')
result = yield
print("结束运行" + sys._getframe().f_code.co_name)
print(" ")

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_call(item):
print("当前运行" + sys._getframe().f_code.co_name)
result = yield
print("结束运行" + sys._getframe().f_code.co_name)
print(" ")

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_teardown(item):
print("当前运行" + sys._getframe().f_code.co_name)
print('执行teardown模块')
result = yield
print("结束运行" + sys._getframe().f_code.co_name)
print(" ")

@pytest.hookimpl(hookwrapper=True)
def pytest_fixture_post_finalizer(fixturedef,request):
print("当前运行" + sys._getframe().f_code.co_name)
print('开始卸载fixture模块-' + str(request.fixturename))
result = yield
print("结束运行" + sys._getframe().f_code.co_name)
print(" ")

@pytest.hookimpl(hookwrapper=True)
def pytest_fixture_setup(fixturedef,request):
print("当前运行" + sys._getframe().f_code.co_name)
# print('开始执行fixture模块-' + str(request.fixturename))
result = yield
# if result.excinfo == None:
# print(request.fixturename + '运行完毕')
# else:
# print('出现异常' + str(result.excinfo))
print("结束运行" + sys._getframe().f_code.co_name)
print(" ")

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item,call):
print("当前运行" + sys._getframe().f_code.co_name)
print(str(item.name) + str(call.when) + '运行结束')
result = yield
print(result.get_result().when + "阶段测试结果:" + result.get_result().outcome)
print("结束运行" + sys._getframe().f_code.co_name)
print(" ")

@pytest.hookimpl(hookwrapper=True)
def pytest_pyfunc_call(pyfuncitem):
print("当前运行" + sys._getframe().f_code.co_name)
print('执行test_模块' + str(pyfuncitem))
result = yield
print("结束运行" + sys._getframe().f_code.co_name)
print(" ")

运行结果

pytest_runtestloop(session)

收集完成后执行所有采集到的测试用例,调用pytest_runtest_protocol循环调用测试用例对象。

pytest_runtest_protocol(item,nextitem)

item:当前测试用例对象

nextitem:下一个测试用例

依次调用pytest_runtest_setup,pytest_runtest_call,pytest_runtest_teardown进行循环测试,本次测试用例运行不出现程序异常就返回true,非错误

pytest_runtest_setup(item)

调用以执行采集的测试项的setup阶段。运行当前的测试用例测试前需要调用pytest_fixture_setup方法运行fixture函数

pytest_runtest_call(item)

调用以执行采集的测试项。

pytest_runtest_teardown

调用以执行采集的测试项的setup阶段。销毁当前的测试用例测试前运行的fixture函数

pytest_fixture_setup(fixturedef,request)

查找并执行所有的fixture函数。

pytest_fixture_post_finalizer(fixturedef,request)

测试用例运行结束后销毁fixture

pytest_pyfunc_call(pyfuncitem: Function)

运行测试方法pyfuncitem

生成测试报告相关函数

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_logreport(report):
    print("当前运行" + sys._getframe().f_code.co_name)
    result = yield
    print("结束运行" + sys._getframe().f_code.co_name)
    print("
")

@pytest.hookimpl(hookwrapper=True)
def pytest_report_header(config, startdir):
    print("当前运行" + sys._getframe().f_code.co_name)
    result = yield
    print("结束运行" + sys._getframe().f_code.co_name)
    print("
")

@pytest.hookimpl(hookwrapper=True)
def pytest_report_collectionfinish(config, startdir, items) :
    print("当前运行" + sys._getframe().f_code.co_name)
    result = yield
    print("结束运行" + sys._getframe().f_code.co_name)
    print("
")

@pytest.hookimpl(hookwrapper=True)
def pytest_report_teststatus(report, config):
    print("当前运行" + sys._getframe().f_code.co_name)
    result = yield
    print(result.get_result())
    print("结束运行" + sys._getframe().f_code.co_name)
    print("
")

@pytest.hookimpl(hookwrapper=True)
def pytest_assertrepr_compare(config,op,left,right):
    print("当前运行" + sys._getframe().f_code.co_name)
    print('开始断言' + str(left) + str(op) + str(right))
    result = yield
    print('断言结果为:' + str(result.get_result()))
    print("结束运行" + sys._getframe().f_code.co_name)
    print("
")

@pytest.hookimpl(hookwrapper=True)
def pytest_exception_interact(call, report):
    print("当前运行" + sys._getframe().f_code.co_name)
    print(str(call.excinfo))
    # print(str(report.longreprtext))
    result = yield
    print("结束运行" + sys._getframe().f_code.co_name)
    print("
")


@pytest.hookimpl(hookwrapper=True)
def pytest_terminal_summary(terminalreporter,exitstatus,config):
    print("当前运行" + sys._getframe().f_code.co_name)
    print('此次测试结果为' + str(exitstatus))
    print('通过的用例为' + str(terminalreporter.stats['passed']))
    print('失败的用例为' + str(terminalreporter.stats['failed']))
    result = yield
    print("结束运行" + sys._getframe().f_code.co_name)
    print("
")

pytest_runtest_makereport(item,call)

call:CallInfo对象,可以通过参数查看测试结果/异常信息,具体参数参考CallInfo

当pytest_runtest_setup,pytest_runtest_call,pytest_runtest_teardown运行完,生成一个TestReport对象。

TestReport对象:基本测试报告对象

pytest_report_teststatus(report, config)

根据pytest_runtest_makereport运行返回测试结果的集合成功为('passed', '.', 'PASSED'),失败为('failed', 'F', 'FAILED')。

pytest_assertrepr_compare(config,op,left,right)

op:比较符号

用例assert时调用,返回失败的断言表达式中的比较解释。

pytest_runtest_logreport(report)

根据report打印测试用例运行结果

pytest_exception_interact(call, report)

pytest_report_teststatus结果运行失败,在引发异常时调用,可以交互式处理。只有在引发的异常不是内部异常, 如skip.Exception时才会调用此Hook方法。

pytest_terminal_summary(terminalreporter,exitstatus,config)

所有用例对象遍历完成后,对结果进行统计报告。

pytest_report_header(config: Config, startdir: py._path.local.LocalPath)

返回要显示为标题信息的字符串或字符串列表,以进行终端报告。

pytest_report_collectionfinish(config: Config, startdir: py._path.local.LocalPath, items: Sequence[Item])

返回成功完成收集后将显示的字符串或字符串列表。

输出结果:

当前运行pytest_report_header
结束运行pytest_report_header



rootdir: D:PycharmProjectsseleniumtest
plugins: allure-pytest-2.8.22, html-3.0.0, metadata-1.10.0
当前运行pytest_collection
启动测试采集器<Session seleniumtest exitstatus=<ExitCode.OK: 0> testsfailed=0 testscollected=0>
当前运行pytest_collectstart
当前节点
结束运行pytest_collectstart



当前运行pytest_make_collect_report
当前运行pytest_pycollect_makemodule
在目录D:PycharmProjectsseleniumtest采集到测试脚本D:PycharmProjectsseleniumtest estmath.py
当前采集模块testmath.py
结束运行pytest_pycollect_makemodule



当前节点,采集结果:passed,采集节点为:[<Module testmath.py>]
结束运行pytest_make_collect_report



当前运行pytest_collectreport
在节点采集到[<Module testmath.py>]
结束运行pytest_collectreport



当前运行pytest_collectstart
当前节点testmath.py
结束运行pytest_collectstart



当前运行pytest_make_collect_report
当前节点testmath.py,采集结果:passed,采集节点为:[<Class TestMath>]
结束运行pytest_make_collect_report



当前运行pytest_collectstart
当前节点testmath.py::TestMath
结束运行pytest_collectstart



当前运行pytest_make_collect_report
当前节点testmath.py::TestMath,采集结果:passed,采集节点为:[<Instance ()>]
结束运行pytest_make_collect_report



当前运行pytest_collectstart
当前节点testmath.py::TestMath
结束运行pytest_collectstart



当前运行pytest_make_collect_report
当前运行pytest_generate_tests
结束运行pytest_generate_tests



当前运行pytest_generate_tests
结束运行pytest_generate_tests



当前节点testmath.py::TestMath,采集结果:passed,采集节点为:[<Function testadd>, <Function testchengfa>]
结束运行pytest_make_collect_report



当前运行pytest_collectreport
在节点testmath.py::TestMath采集到[<Function testadd>, <Function testchengfa>]
结束运行pytest_collectreport



当前运行pytest_collectreport
在节点testmath.py::TestMath采集到[<Instance ()>]
结束运行pytest_collectreport



当前运行pytest_collectreport
在节点testmath.py采集到[<Class TestMath>]
结束运行pytest_collectreport



当前运行pytest_collection_modifyitems
测试顺序为[<Function testadd>, <Function testchengfa>]
结束运行pytest_collection_modifyitems



当前运行pytest_collection_finish
collected 2 items
当前运行pytest_report_collectionfinish
结束运行pytest_report_collectionfinish



用例采集完成
结束运行pytest_collection_finish



最终测试采集结果[<Function testadd>, <Function testchengfa>]
结束运行pytest_collection



当前运行pytest_runtestloop
开始测试测试用例集合[<Function testadd>, <Function testchengfa>]
当前运行pytest_runtest_protocol
开始测试用例:testadd


testmath.py 当前运行pytest_runtest_setup
执行setup模块
当前运行pytest_fixture_setup
开始执行fixture模块-starter
开始
starter运行完毕
结束运行pytest_fixture_setup



结束运行pytest_runtest_setup



当前运行pytest_runtest_makereport
testaddsetup运行结束
setup阶段测试结果:passed
结束运行pytest_runtest_makereport



当前运行pytest_runtest_logreport
当前运行pytest_report_teststatus
('', '', '')
结束运行pytest_report_teststatus



结束运行pytest_runtest_logreport



当前运行pytest_runtest_call
当前运行pytest_pyfunc_call
执行test_模块<Function testadd>
正在执行testadd
验证成功
结束运行pytest_pyfunc_call



结束运行pytest_runtest_call



当前运行pytest_runtest_makereport
testaddcall运行结束
call阶段测试结果:passed
结束运行pytest_runtest_makereport



当前运行pytest_runtest_logreport
当前运行pytest_report_teststatus
('passed', '.', 'PASSED')
结束运行pytest_report_teststatus



.结束运行pytest_runtest_logreport



当前运行pytest_runtest_teardown
执行teardown模块
结束运行pytest_runtest_teardown



当前运行pytest_runtest_makereport
testaddteardown运行结束
teardown阶段测试结果:passed
结束运行pytest_runtest_makereport



当前运行pytest_runtest_logreport
当前运行pytest_report_teststatus
('', '', '')
结束运行pytest_report_teststatus



结束运行pytest_runtest_logreport



结束运行pytest_runtest_protocol



当前运行pytest_runtest_protocol
开始测试用例:testchengfa
当前运行pytest_runtest_setup
执行setup模块
结束运行pytest_runtest_setup



当前运行pytest_runtest_makereport
testchengfasetup运行结束
setup阶段测试结果:passed
结束运行pytest_runtest_makereport



当前运行pytest_runtest_logreport
当前运行pytest_report_teststatus
('', '', '')
结束运行pytest_report_teststatus



结束运行pytest_runtest_logreport



当前运行pytest_runtest_call
当前运行pytest_pyfunc_call
执行test_模块<Function testchengfa>
正在执行testadd
当前运行pytest_assertrepr_compare
开始断言0==a
断言结果为:[]
结束运行pytest_assertrepr_compare



结束运行pytest_pyfunc_call



结束运行pytest_runtest_call



当前运行pytest_runtest_makereport
testchengfacall运行结束
call阶段测试结果:failed
结束运行pytest_runtest_makereport



当前运行pytest_runtest_logreport
当前运行pytest_report_teststatus
('failed', 'F', 'FAILED')
结束运行pytest_report_teststatus



F结束运行pytest_runtest_logreport



当前运行pytest_exception_interact
<ExceptionInfo AssertionError("assert 0 == 'a' + where 0 = chengfa('a', 1)") tblen=1>
结束运行pytest_exception_interact



当前运行pytest_runtest_teardown
执行teardown模块
结束
当前运行pytest_fixture_post_finalizer
开始卸载fixture模块-starter
结束运行pytest_fixture_post_finalizer



当前运行pytest_fixture_post_finalizer
开始卸载fixture模块-starter
结束运行pytest_fixture_post_finalizer



结束运行pytest_runtest_teardown



当前运行pytest_runtest_makereport
testchengfateardown运行结束
teardown阶段测试结果:passed
结束运行pytest_runtest_makereport



当前运行pytest_runtest_logreport
当前运行pytest_report_teststatus
('', '', '')
结束运行pytest_report_teststatus



结束运行pytest_runtest_logreport



结束运行pytest_runtest_protocol



测试用例集合测试结果为<Session seleniumtest exitstatus=<ExitCode.OK: 0> testsfailed=1 testscollected=2>
结束运行pytest_runtestloop





================================== FAILURES ===================================
____________________________ TestMath.testchengfa _____________________________


self = <testmath.TestMath object at 0x039F6BD0>


def testchengfa(self):
'''测试加法程序'''
print("正在执行testadd")
> assert chengfa('a',1) == 'a'
E AssertionError: assert 0 == 'a'
E + where 0 = chengfa('a', 1)


testmath.py:31: AssertionError
当前运行pytest_terminal_summary
此次测试结果为ExitCode.TESTS_FAILED
通过的用例为[<TestReport 'testmath.py::TestMath::testadd' when='call' outcome='passed'>]
失败的用例为[<TestReport 'testmath.py::TestMath::testchengfa' when='call' outcome='failed'>]
结束运行pytest_terminal_summary



当前运行pytest_report_teststatus
('failed', 'F', 'FAILED')
结束运行pytest_report_teststatus



=========================== short test summary info ===========================
FAILED testmath.py::TestMath::testchengfa - AssertionError: assert 0 == 'a'
========================= 1 failed, 1 passed in 0.12s =========================

 
原文地址:https://www.cnblogs.com/zerotest/p/13612511.html