全网最全面的pytest测试框架进阶-conftest文件重写采集和运行测试用例的hook函数
创始人
2024-01-16 06:33:18
0

【文章末尾有.......】

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

构建一个简单的测试脚本

import pytest
import requestsdef add(a,b):if type(a) is str or type(b) is str:return str(a) + str(b)return a+bdef chengfa(a,b):if type(a) is str or type(b) is str:return 0return a*bclass TestMath(object):@pytest.fixture(scope='session',autouse=True)def starter(self):print('开始')yieldprint('结束')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 = yieldprint('最终测试采集结果' + 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 = yieldprint("结束运行" + 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 = yieldprint("当前节点" +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 = yieldprint('当前采集模块' + 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 = yieldprint("结束运行" + 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 = yieldprint("结束运行" + 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 = yieldprint('测试顺序为'+ 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 = yieldprint('用例采集完成')print("结束运行" + sys._getframe().f_code.co_name)print("\n")

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 = yieldprint('测试用例集合测试结果为' + 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 = yieldprint("结束运行" + 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 = yieldprint("结束运行" + 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 = yieldprint("结束运行" + 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 = yieldprint("结束运行" + 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 = yieldprint("结束运行" + 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 = yieldprint(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 = yieldprint("结束运行" + sys._getframe().f_code.co_name)print("\n")

运行结果

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 = yieldprint("结束运行" + 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 = yieldprint("结束运行" + 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 = yieldprint("结束运行" + 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 = yieldprint(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 = yieldprint('断言结果为:' + 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 = yieldprint("结束运行" + 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 = yieldprint("结束运行" + sys._getframe().f_code.co_name)print("\n")

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:\PycharmProjects\seleniumtest
plugins: allure-pytest-2.8.22, html-3.0.0, metadata-1.10.0
当前运行pytest_collection
启动测试采集器 testsfailed=0 testscollected=0>
当前运行pytest_collectstart
当前节点
结束运行pytest_collectstart

 


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

 


当前节点,采集结果:passed,采集节点为:[]
结束运行pytest_make_collect_report

 


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

 


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

 


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

 


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

 


当前运行pytest_make_collect_report
当前节点testmath.py::TestMath,采集结果:passed,采集节点为:[]
结束运行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,采集节点为:[, ]
结束运行pytest_make_collect_report

 


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

 


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

 


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

 


当前运行pytest_collection_modifyitems
测试顺序为[, ]
结束运行pytest_collection_modifyitems

 


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

 


用例采集完成
结束运行pytest_collection_finish

 


最终测试采集结果[, ]
结束运行pytest_collection

 


当前运行pytest_runtestloop
开始测试测试用例集合[, ]
当前运行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_模块
正在执行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_模块
正在执行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

结束运行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

 


测试用例集合测试结果为 testsfailed=1 testscollected=2>
结束运行pytest_runtestloop

 

 


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

 

self =

 

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
通过的用例为[]
失败的用例为[]
结束运行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 =========================

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

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

【记得(备注“csdn000”)】

【或私信000】

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

项目实战:

大型电商平台:

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

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

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

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

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

上一篇:不同的选择

下一篇:漫谈栏

相关内容

热门资讯

常用商务英语口语   商务英语是以适应职场生活的语言要求为目的,内容涉及到商务活动的方方面面。下面是小编收集的常用商务...
六年级上册英语第一单元练习题   一、根据要求写单词。  1.dry(反义词)__________________  2.writ...
复活节英文怎么说 复活节英文怎么说?复活节的英语翻译是什么?复活节:Easter;"Easter,anniversar...
2008年北京奥运会主题曲 2008年北京奥运会(第29届夏季奥林匹克运动会),2008年8月8日到2008年8月24日在中华人...
英语道歉信 英语道歉信15篇  在日常生活中,道歉信的使用频率越来越高,通过道歉信,我们可以更好地解释事情发生的...
六年级英语专题训练(连词成句... 六年级英语专题训练(连词成句30题)  1. have,playhouse,many,I,toy,i...
上班迟到情况说明英语   每个人都或多或少的迟到过那么几次,因为各种原因,可能生病,可能因为交通堵车,可能是因为天气冷,有...
小学英语教学论文 小学英语教学论文范文  引导语:英语教育一直都是每个家长所器重的,那么有关小学英语教学论文要怎么写呢...
英语口语学习必看的方法技巧 英语口语学习必看的方法技巧如何才能说流利的英语? 说外语时,我们主要应做到四件事:理解、回答、提问、...
四级英语作文选:Birth ... 四级英语作文范文选:Birth controlSince the Chinese Governmen...
金融专业英语面试自我介绍 金融专业英语面试自我介绍3篇  金融专业的学生面试时,面试官要求用英语做自我介绍该怎么说。下面是小编...
我的李老师走了四年级英语日记... 我的李老师走了四年级英语日记带翻译  我上了五个学期的小学却换了六任老师,李老师是带我们班最长的语文...
小学三年级英语日记带翻译捡玉... 小学三年级英语日记带翻译捡玉米  今天,我和妈妈去外婆家,外婆家有刚剥的`玉米棒上带有玉米籽,好大的...
七年级英语优秀教学设计 七年级英语优秀教学设计  作为一位兢兢业业的人民教师,常常要写一份优秀的教学设计,教学设计是把教学原...
我的英语老师作文 我的英语老师作文(通用21篇)  在日常生活或是工作学习中,大家都有写作文的经历,对作文很是熟悉吧,...
英语老师教学经验总结 英语老师教学经验总结(通用19篇)  总结是指社会团体、企业单位和个人对某一阶段的学习、工作或其完成...
初一英语暑假作业答案 初一英语暑假作业答案  英语练习一(基础训练)第一题1.D2.H3.E4.F5.I6.A7.J8.C...
大学生的英语演讲稿 大学生的英语演讲稿范文(精选10篇)  使用正确的写作思路书写演讲稿会更加事半功倍。在现实社会中,越...
VOA美国之音英语学习网址 VOA美国之音英语学习推荐网址 美国之音网站已经成为语言学习最重要的资源站点,在互联网上还有若干网站...
商务英语期末试卷 Part I Term Translation (20%)Section A: Translate ...