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("安琪拉")

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

未完待续

相关推荐
天水幼麟3 小时前
动手学深度学习-学习笔记(总)
笔记·深度学习·学习
天水幼麟6 小时前
动手学深度学习-学习笔记【二】(基础知识)
笔记·深度学习·学习
绿皮的猪猪侠6 小时前
算法笔记上机训练实战指南刷题
笔记·算法·pta·上机·浙大
沧海一笑-dj6 小时前
【51单片机】51单片机学习笔记-课程简介
笔记·学习·51单片机·江科大·江科大学习笔记·江科大单片机·江科大51单片机
老虎06276 小时前
JavaWeb(苍穹外卖)--学习笔记04(前端:HTML,CSS,JavaScript)
前端·javascript·css·笔记·学习·html
大苏打seven7 小时前
Docker学习笔记:Docker网络
笔记·学习·docker
Green1Leaves9 小时前
pytorch学习-9.多分类问题
人工智能·pytorch·学习
慕y2749 小时前
Java学习第十五部分——MyBatis
java·学习·mybatis
碣石潇湘无限路10 小时前
【AI篇】当Transformer模型开始学习《孙子兵法》
人工智能·学习
kikikidult11 小时前
(2025.07)解决——ubuntu20.04系统开机黑屏,左上角光标闪烁
笔记·ubuntu