全网最全面的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测试框架进阶-conftest文件重写采集和运行测试用例的hook函数

采集测试用例相关函数

全网最全面的pytest测试框架进阶-conftest文件重写采集和运行测试用例的hook函数
@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("\n")

@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("\n")

@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("\n")

@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("\n")

@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("\n")

@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("\n")

@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("\n")

@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("\n")

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

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测试框架进阶-conftest文件重写采集和运行测试用例的hook函数
@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("\n")

@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("\n")

@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("\n")

@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("\n")

@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("\n")

@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("\n")

@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("\n")

@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("\n")

@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("\n")

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

运行结果

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测试框架进阶-conftest文件重写采集和运行测试用例的hook函数
@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("\n")

@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("\n")

@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("\n")

@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("\n")

@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("\n")

@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("\n")

@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("\n")

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

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测试框架进阶-conftest文件重写采集和运行测试用例的hook函数

当前运行pytest_report_header
结束运行pytest_report_header

undefined

rootdir: D:\PycharmProjects\seleniumtest
plugins: allure-pytest-2.8.22, html-3.0.0, metadata-1.10.0
当前运行pytest_collection
启动测试采集器

undefined

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

undefined

当前节点,采集结果:passed,采集节点为:[

undefined

当前运行pytest_collectreport
在节点采集到[

undefined

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

undefined

当前运行pytest_make_collect_report
当前节点testmath.py,采集结果:passed,采集节点为:[

undefined

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

undefined

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

undefined

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

undefined

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

undefined

当前运行pytest_generate_tests
结束运行pytest_generate_tests

undefined

当前节点testmath.py::TestMath,采集结果:passed,采集节点为:[

undefined

当前运行pytest_collectreport
在节点testmath.py::TestMath采集到[

undefined

当前运行pytest_collectreport
在节点testmath.py::TestMath采集到[

undefined

当前运行pytest_collectreport
在节点testmath.py采集到[

undefined

当前运行pytest_collection_modifyitems
测试顺序为[

undefined

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

undefined

用例采集完成
结束运行pytest_collection_finish

undefined

最终测试采集结果[

undefined

当前运行pytest_runtestloop
开始测试测试用例集合[

undefined

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

undefined

结束运行pytest_runtest_setup

undefined

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

undefined

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

undefined

结束运行pytest_runtest_logreport

undefined

当前运行pytest_runtest_call
当前运行pytest_pyfunc_call
执行test_模块

undefined

结束运行pytest_runtest_call

undefined

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

undefined

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

undefined

.结束运行pytest_runtest_logreport

undefined

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

undefined

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

undefined

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

undefined

结束运行pytest_runtest_logreport

undefined

结束运行pytest_runtest_protocol

undefined

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

undefined

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

undefined

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

undefined

结束运行pytest_runtest_logreport

undefined

当前运行pytest_runtest_call
当前运行pytest_pyfunc_call
执行test_模块

undefined

结束运行pytest_pyfunc_call

undefined

结束运行pytest_runtest_call

undefined

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

undefined

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

undefined

F结束运行pytest_runtest_logreport

undefined

当前运行pytest_exception_interact

undefined

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

undefined

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

undefined

结束运行pytest_runtest_teardown

undefined

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

undefined

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

undefined

结束运行pytest_runtest_logreport

undefined

结束运行pytest_runtest_protocol

undefined

测试用例集合测试结果为

undefined

undefined

================================== FAILURES ===================================
____ TestMath.testchengfa _____

undefined

self =

undefined

def testchengfa(self):
”’测试加法程序”’
print(“正在执行testadd”)

assert chengfa(‘a’,1) == ‘a’
E AssertionError: assert 0 == ‘a’
E + where 0 = chengfa(‘a’, 1)

undefined

testmath.py:31: AssertionError
当前运行pytest_terminal_summary
此次测试结果为ExitCode.TESTS_FAILED
通过的用例为[

undefined

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

undefined

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

重点:学习资料学习当然离不开资料,这里当然也给你们准备了600G的学习资料

【需要的可以扫描文章末尾的qq群二维码自助拿走】

【记得(备注”csdn000″)】

【或私信000】

群里的免费资料都是笔者十多年测试生涯的精华。还有同行大神一起交流技术哦。

项目实战:

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

大型电商平台:

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

全套软件测试自动化测试教学视频

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

300G教程资料下载【视频教程+PPT+项目源码】

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

全套软件测试自动化测试大厂面经

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

python自动化测试++全套模板+性能测试

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

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

听说关注我并三连的铁汁都已经升职加薪暴富了哦!!!!

Original: https://blog.csdn.net/m0_60054525/article/details/127481517
Author: 阿里测试君
Title: 全网最全面的pytest测试框架进阶-conftest文件重写采集和运行测试用例的hook函数

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/773949/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球