IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 开发测试 -> 全网最全面的pytest测试框架进阶-conftest文件重写采集和运行测试用例的hook函数 -> 正文阅读

[开发测试]全网最全面的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("\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_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("\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_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("\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_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
启动测试采集器<Session seleniumtest exitstatus=<ExitCode.OK: 0> 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,采集节点为:[<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'\n + 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 =========================

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

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

【记得(备注“csdn000”)】

【或私信000】

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

项目实战:

大型电商平台:

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

?

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

?

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

?

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

?

?

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

  开发测试 最新文章
pytest系列——allure之生成测试报告(Wind
某大厂软件测试岗一面笔试题+二面问答题面试
iperf 学习笔记
关于Python中使用selenium八大定位方法
【软件测试】为什么提升不了?8年测试总结再
软件测试复习
PHP笔记-Smarty模板引擎的使用
C++Test使用入门
【Java】单元测试
Net core 3.x 获取客户端地址
上一篇文章      下一篇文章      查看所有文章
加:2022-10-31 12:30:26  更:2022-10-31 12:30:58 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年3日历 -2024/3/29 19:57:35-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码