python自动化笔记:pytest框架

目录

一、pytest介绍

二、测试用例命名规则

2.1、pytest命名规则

1、模块名必须以test_开头或者_test结尾。

2、测试类必须以Test开头,并且不能带有init方法。

3、测试用例必须以test_开头。

2.2、python命名规范

1、模块名:一般全小写:多个英文之间用_隔开。

2、类名:类名一般是首字母大写

3、方法名:一般全小写:多个英文之间用_隔开。

三、pytest运行方式

3.1、主函数方式

python 复制代码
import pytest

class TestApi:

    def test_sheshou():
        print("鲁班")

    def test_fashi():
        print("安琪拉")

if _name_ == '_main_':
    pytest.main()

常见参数

参数 描述 案例
-v 输出更加详细的信息,比如文件和用例名称等 pytest.main(['-v'])
-s 输出调试信息。打印信息等 pytest.main(['-s'])
--reruns N 失败重跑N次(N是数字)
--x 只要有一个用例执行失败,就停止执行测试
--maxfail=N 出现N个失败就终止测试(N是数字)
--html=report.html 生成html的测试报告
-n 多线程
-k 运行测试用例名称中包含指定字符串的用例 ,可以使用and或or pytest.main(['-vs','-k','one or two'])

指定模块运行

python 复制代码
if _name_ == '_main_':
    pytest.main(['-vs','testcases/test_api2.py'])

指定整个文件夹运行

python 复制代码
if _name_ == '_main_':
    pytest.main(['-vs','testcases/'])

通过node id的方式运行测试用例。

python 复制代码
if _name_ == '_main_':
    pytest.main(['-vs','testcases/test_api.py::TestApi::test_sheshou'])

3.2、命令行方式

3.3、通过pytest.ini的配置文件运行(常用)

注:不管是命令行还是主函数都会读取这个配置文件

pytest.ini:全局配置文件,通常放在项目的根目录下,用于改变pytest的运行方式和设置配置信息

python 复制代码
[pytest]
addopts = -vs -n 2 
testpaths =./test_case 
python_files = test_*.py  
python_classes = Test* 
python_functions = test  
markers =              
  smoke:冒烟用例     # 中文可有可无,标记字段说明    
  usermanage:用户管理模块     
  productmanage:商品管理模块
参数 描述
addopts 命令行参数,多个参数之间用空格分隔
testpaths 配置搜索测试用例的范围
python_files 改变默认的文件搜索规则
python_classes 改变默认的类搜索规则
python_function 改变默认的测试用例的搜索规则
markers 标记,用于指定用例执行,与装饰器@pytest.mark.标记名 配合使用,需要在addopts中使用【-m smoke】才能生效,其中smoke是标记名,可以替换

特别提示:此文件中最好不要出现中文, 如果有中文的情况下,可使用notpad++改成GBK的编码。

用例里面加标记

python 复制代码
class TestApi:

    @pytest.mark.smoke
    def test_sheshou():
        print("鲁班")

    @pytest.mark.productmanage
    def test_fashi():
        print("安琪拉")

执行的时候通过-m参数指定标记

python 复制代码
addopts = ‐vs ‐m smoke

四、跳过测试用例

4.1 无条件跳过

python 复制代码
class TestApi:
	@pytest.mark.skip(reason="粒度不需要")
    @pytest.mark.smoke
    def test_sheshou():
        print("鲁班")

4.2 有条件跳过

python 复制代码
class TestApi:
	@pytest.mark.skipif(age>2,reason="以后版本都不执行")
    @pytest.mark.productmanage
    def test_fashi():
        print("安琪拉")

五、用例的前后置,固件,夹具,钩子函数

未完待续

相关推荐
2301_8227032034 分钟前
鸿蒙flutter三方库实战——教育与学习平台:Flutter Markdown
学习·算法·flutter·华为·harmonyos·鸿蒙
码喽7号1 小时前
vue学习四:Axios网络请求
前端·vue.js·学习
星幻元宇VR1 小时前
VR科普行走平台适用哪些科普教育主题
科技·学习·安全·vr·虚拟现实
xinzheng新政1 小时前
Javascript 深入学习基础·4
javascript·学习·servlet
雷工笔记2 小时前
MES / WMS / AGV 交互时序图及生产管理模块界面设计清单
人工智能·笔记
大邳草民2 小时前
Python 中 global 与 nonlocal 的语义与机制
开发语言·笔记·python
charlie1145141912 小时前
通用GUI编程技术——图形渲染实战(二十九)——Direct2D架构与资源体系:GPU加速2D渲染入门
开发语言·c++·学习·架构·图形渲染·win32
landuochong2002 小时前
claude-obsidian 再升级
人工智能·笔记·claudecode
CheerWWW2 小时前
C++学习笔记——线程、计时器、多维数组、排序
c++·笔记·学习
克里斯蒂亚诺·罗纳尔达2 小时前
智能体学习16——学习与适应(Learning-and-Adaptation)-深入解读
深度学习·学习·机器学习