免费获取学习方案
ARTICLE DETAIL

资讯详情

深耕编程基础知识与建站技术分享的一线实战洞察。

【Pytest】2026 学习总结

【Pytest】2026 学习总结 文章目录1. unittest 与 pytest 对比2. pytest 安装、执行、结果2.1 pytest 运行用例的方法核心掌握2.2 pytest 执行结果的各项意义简单举例2.3 pytest 的用例结果包含的情况及含义结果截图示例3. pytest 用例规则用例发现规则、用例内容规则3.1 用例发现规则pytest 如何去找到要执行的用例3.2 用例内容规则了解4. 配置框架4.1 pytest 有哪些入参分别是什么意思5. 标记用例mark5.1 pytest.mark 用户自定义标记5.2 pytest.mark 内置标记6. fixture 的深度理解6.1 创建fixture6.2 使用fixture 的方式6.3 使用fixture 的不同场景6.4 使用conftest.py的应用fixture实现全局的共享7. pytest 插件管理与本章4.1结合 重7.0 pytest 常用插件的使用方式7.1 pytest 常用插件 及 对应功能7.1.1 pytest-html 如何使用生成html报告7.1.2 pytest-xdist分布式执行用例多进程7.1.3 pytest-rerunfailures用例执行失败后重新执行7.1.4 pytest-result-log 用例结果记录至日志文件仅在配置文件中使用,因为配置参数较多7.1.5 allure-pytest 测试报告美化企业级测试报告7.2 allure 装饰用例自定义测试报告继本章7.1.51. unittest 与 pytest 对比unittestpytest安装、卸载无需安装手动安装升级、降级无法改变版本可以指定版本代码风格java语言python语言插件生态只有几个插件1400插件涵盖各个方面备注由python官方维护完全兼容unittest2. pytest 安装、执行、结果pip install pytest# 安装pip install pytest-U# 升级最新版2.1 pytest 运行用例的方法核心掌握1.pytest的程序运行的方法 a.主函数模式 运行所有case: pytest.main()指定模块所有case: pytest.main([-vs,test_module.py])指定目录所有casepytest.main([-vs,./test_manage])指定nodeid执行用例nodeid由模块名、分隔符、类名、方法名、函数名组成。 egpytest.main([-vs,./api_testcase/testlogin.py::TestLogin::test_01_login])b.命令行模式 运行所有pytest 执行模块pytest-vstest_login.py 执行目录pytest-vs./api_testcase 指定nodeid执行用例: pytest-vs./api_testcase/testlogin.py::TestLogin::test_01_login c.通过读取pytest.ini配置文件运行最为常用的方式0.pytest.ini是pytest单元测试框架的核心配置文件不管是主函数模式/命令行模式运行都会读取该文件1.pytest.ini一般放置在项目的根目录2.pytest.ini的编码必须是GBK(最近发现可以)ANSI,可以使用notepad修改编码格式(不可有中文)3.作用改变pytest的默认的行为[pytest]# 命令行入参全部放置在addopts,以空格间隔addopts-vs# 测试用例文件夹testpaths../pytest_demo# 文件名python_filestest*.py test_* *_test test*# 类名python_classesTest* test*# 用例函数python_functionstest_* test*# 控制台实时输出日志(批量运行耗费性能)log_cliTrue# 如case被xfail标记预期失败但是实际却成功了结果会显示xfailed,True时结果显示failedxfail_strictTrue# 标记case的模块名称分组执行如冒烟测试:1.用例装饰pytest.mark.smoke;2.ini配置3.执行带参数 -mmarkerssmoke: justdoa smoketest login: login api userinfo: user info api2.2 pytest 执行结果的各项意义简单举例testsession startsplatform win32 -- Python3.13.14, pytest-9.1.1, pluggy-1.6.0 rootdir: D:\study\pytest2026-sample plugins: allure-pytest-2.16.0, anyio-4.14.2 collected2items test_cases.py .F[100%]FAILURES____________________________ test_fail ___________________________________________ def test_fail():assert False E assert False test_cases.py:9: AssertionErrorshorttestsummary infoFAILED test_cases.py::test_fail - assert False1failed,1passedin0.10s执行环境版本、根目录、用例数量执行过程文件名称、用例结果、执行进度失败详情用例内容、断言失败原因提示整体摘要结果情况、结果数量、花费时间2.3 pytest 的用例结果包含的情况及含义结果截图示例缩写单词含义.passed通过Ffailed失败用例执行时报错Eerror出错fixture执行报错sskiped跳过Xxpassed预期外的通过(不符合预期)xxfailed预期内的失败符合预期3. pytest 用例规则用例发现规则、用例内容规则3.1 用例发现规则pytest 如何去找到要执行的用例**用例发现**测试框架在识别、加载用例的过程称之为用例发现。pytest的用例发现步骤1. 遍历所有的目录例外.venv,.开头的目录及文件不在遍历范围2. 打开遍历目录下的所有以test_开头或_test结尾的py文件3. 遍历测试类必须以Test开头而且类不允许含有__init__方法4. 收集test开头的函数或者方法3.2 用例内容规则了解pytest对用例内容的要求1. 可调用函数、方法、类、对象2. 名字test开头3. 没有参数参数有另外含义4. 没有返回值默认为None4. 配置框架配置可以改变pytest的默认规则。详见本章 2.11. 命令参数2. ini配置文件---pytest.ini pytest.ini是pytest单元测试框架的核心配置文件不管是主函数模式/命令行模式运行都会读取该文件,一般放置在项目的根目录。pytest.ini的编码必须是GBK(最近发现可以)ANSI,可以使用notepad修改编码格式(不可有中文)。4.1 pytest 有哪些入参分别是什么意思4. 首先了解pytest运行都有哪些常用的入参各自是什么意思如何使用 -s: 输出调试信息其中包含在代码中print的内容 -v: 显示更为详细的信息相对与-s而已-vs更详细备注-vs这两个参数一起使用 -n: 支持多线程、更或者分布式运行测试用例--reruns{num}: 失败用例重新执行测试设置 -m: 指定装饰器装饰的case的运行用例(注意:步骤1.装饰器装饰case, pytest.mark.o;步骤2.pytest.ini中配置 markerso: TTT smoke: just a smoketestlogin: login api 步骤3.执行时加上参数-m模块)-k: 根据测试用例的部分字符串指定要执行测试用例eg:pytest-vs./testcase-n2-x-ktest--htmlpath 生成html报告 -x: 只要有一个case失败所有case停止--maxfail2: 出现2个用例失败就停止即--maxfail{num}设置用例最大失败次数--alluredirpath: 临时json报告再生成allure报告os.system(allure generate ./temp -o ./report --clean)——————————————————————————————————————————————————————————————————————————————————————————---- 下载allurehttps://github.com/allure-framework/allure2/releases allure generate:allure命令 第一个入参 ./temp, 临时的json格式报告的路径-o:output后面跟具体输出到的目录 --clean 清空 -o后面跟的目录的原有的报告5. 标记用例mark标记让用例与众不同进而可以让用例被(区别/过滤)执行。1. 用户自定义标记只能实现用例筛选配合 pytest-m参数 执行。2. 框架内置标记除了过滤用例还可为用例增加特殊的执行效果。5.1 pytest.mark 用户自定义标记5.2 pytest.mark 内置标记内置标记不需要在pytest.ini配置文件中去配置。是pytest自带的。 1. pytest.mark.skip():无条件跳过 2. pytest.mark.skipif():有条件跳过 3. pytest.mark.xfail():预期失败 4. pytest.mark.parametrize():参数化最用的多的 5. pytest.mark.usefixtures():使用fixture参数化示例eg:pytest.mark.parametrize(args,[123,456,789])pytest.mark.odeftest_todo_02(self,args):print(todo----2%s%args,end\r\n)pytest.mark.parametrize(name,age,[[代华,12],[不代华,9]])pytest.mark.odeftest_todo_03(self,name,age):print(todo----2%s%s%(name,age),end\r\n)截图示例6. fixture 的深度理解6.1 创建fixtureimportpytestpytest.fixturedeff():# 前置操作print(前置操作)yield返回值# 后置操作print(后置操作)截图示例加强理解6.2 使用fixture 的方式1.方式一在用例的参数中传入fixture装饰的方法名称。2.方式二使用pytest.mark.usefixtures(fixture方法名称)装饰用例。示例6.3 使用fixture 的不同场景1.自动使用 autouseTrue,所有同区域下的用例无差别执行2.依赖使用 fixture 装饰的函数调用依赖fixture直接入参fixture装饰的函数不可使用usefixtures(),只可入参的方式调用依赖3.返回内容yieldres 用例如何接收yield后的返回值 fixture装饰的方法的名称传入用例即方式一来使用fixture4.范围共享 fixture(scope范围)默认范围scopefunction全局范围scopesession,同一命名文件下才可调用不同test_case.py、test_case2.py实际session也不能全局共享 实现真正的全局范围scopesession使用**conftest.py**文件5.多调用一个用例函数调用多个fixture自动使用的示例依赖调用的示例获取返回值的示例依赖共享的示例6.4 使用conftest.py的应用fixture实现全局的共享7. pytest 插件管理与本章4.1结合 重pytest插件生态是pytest特别的优势。插件分为两类1.不需要安装内置插件2.需要安装第三方插件7.0 pytest 常用插件的使用方式插件的启用管理1.启用-p xxx插件2.禁用-p no:xxx插件 插件的使用方式1.参数2.配置文件3.fixture4.mark7.1 pytest 常用插件 及 对应功能常用插件 pytest-html#生成html报告 pip install pytest-htmlpytest-xdist# 测试用例的分布式执行。多进程 pip install pytest-xdistpytest-rerunfailures# 用例失败重新执行 pip install pytest-rerunfailuresallure-pytest# 生成较为美观的测试报告 pip install allure-pytestpytest-repeat# 指定重复用例执行次数pytest-result-log# 把用例的执行结果记录到日志文件中 pip install pytest-result-logpytest-ordering# 改变用例执行顺序7.1.1 pytest-html 如何使用生成html报告主函数模式‘–htmlreport.html’, ‘–self-contained-html’pytest.main([-v,-s,--htmlreport.html,--self-contained-html])# 或者 使用字符串所有参数用空格分隔# pytest.main(-v -s --htmlreport.html --self-contained-html)命令行模式pytest-vs--htmlreport.html --self-contained-htmlpytest.ini配置文件模式:[pytest];addopts-vs--alluredir./temp--clean-alluredir addopts-vs--html./report/report.html--self-contained-html;addopts-vs--html./report/report.html--self-contained-html-m smoke--reruns3--headless testpaths./testcase python_filestest*.py test_**_test test*python_classesTest*test*python_functionstest_*test*log_cliTruelog_levelinfo log_cli_format%(asctime)s[%(levelname)s]%(message)s[%(filename)s:%(lineno)s]log_cli_date_format%Y-%m-%d%H:%M:%S log_file./log/debug_run.log log_file_levelinfo log_file_format%(asctime)s[%(levelname)s]%(message)s[%(filename)s:%(lineno)s]log_file_date_format%Y-%m-%d%H:%M:%S xfail_strictTruemarkerssmoke:just a smoke test smoke1:nota test[env]prehttp://httpbin.org/testhttp://httpbin.org/prohttp://httpbin.org/7.1.2 pytest-xdist分布式执行用例多进程1.只有在任务本身耗时较长超出调用成本很多的时候才有意义2.分布式执行有并发问题资源竞争、乱序只有在用例间对执行顺序无要求即用例间没有依赖才可分布式执行。命令行模式# 100进程执行pytest-n100主函数模式pytest.main([-v,-s,--htmlreport.html,--self-contained-html,-n3])pytest.ini配置文件模式addopts-vs--html./report/report.html --self-contained-html-n37.1.3 pytest-rerunfailures用例执行失败后重新执行命令行模式# 执行用例失败重新执行5次pytest--reruns5pytest--reruns5--reruns-delay10# 重新执行间隔时间 10s主函数模式pytest.main([-v,-s,--htmlreport.html,--self-contained-html,-n3,--reruns5])pytest.ini配置文件模式addopts-vs--html./report/report.html --self-contained-html-n3--reruns3--reruns-delay107.1.4 pytest-result-log 用例结果记录至日志文件仅在配置文件中使用,因为配置参数较多配置文件****pytest.ini中配置[pytest]log_file./log/debug_run.log log_file_levelinfo log_file_format%(asctime)s[%(levelname)s]%(message)s[%(filename)s:%(lineno)s]log_file_date_format%Y-%m-%d%H:%M:%S;记录测试结果 result_log_enableTrue;记录用例分割线 result_log_separator1;分割线等级 result_log_level_separatorwarning;异常信息等级 result_log_level_verboseinfo7.1.5 allure-pytest 测试报告美化企业级测试报告allure 本身是一个测试报告框架. 使用allure-pytest 需要先本地安装allure ,否则在生成报告时识别不到allure命令。 allure-pytest 以allure 开头说明了allure-pytest 本身是allure的插件。前往allure下载最新的 allure-x.x.x.zip 百度网盘也有存储解压至一个固定目录D:\soft\allure配置D:\soft\allure\allure-2.45.0\bin环境变量PATH重启环境变量配置文件模式pytest.ini:[pytest];--alluredir 指定临时数据目录--clean-alluredir 清除原有数据 addopts--alluredir./temp--clean-alluredir配置后执行用例不会直接生成报告只是将数据放在/temp目录下还需要执行allure命令。生成报告配置文件pytest.ini中--alluredirpath: 临时json报告, 再生成allure报告,需要执行在主函数附加下面 os.system(allure generate ./temp -o ./report --clean)或者命令行allure generate ./temp-o./report--clean参数示意 ./temp 临时的json格式报告的路径-o:output后面跟具体输出到的目录 --clean清空 -o后面跟的目录的原有的报告7.2 allure 装饰用例自定义测试报告继本章7.1.5allure支持对用例进行分组和关联使用相同装饰器的用例自动并入同一组。allure.epic项目allure.feature模块allure.story功能allure.title用例allure装饰用例分组报告示例
返回列表