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

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

未完待续

相关推荐
AI机器学习算法4 小时前
《动手学深度学习PyTorch版》笔记
人工智能·学习·机器学习
贺一航【Niki】4 小时前
【学习笔记】杂乱知识
笔记·学习
白雪茫茫5 小时前
监督学习、半监督学习、无监督学习算法详解
python·学习·算法·ai
つ安静与叛逆的小籹人5 小时前
小红书API:通过笔记ID获取笔记详情数据教程
笔记·python
ClutchoQ7 小时前
【你指的API是哪个API?软件工程师跨服聊天实录】
笔记·其他
二哈赛车手9 小时前
新人笔记---Spring AI的Advisor以及其底层机制讲解(涉及源码),包含一些遇见的Spring AI的Advisor缺陷问题的解决方案
java·人工智能·spring boot·笔记·spring
red_redemption10 小时前
自由学习记录(181)
学习
wuxinyan12310 小时前
大模型学习之路007:RAG 零基础入门教程(第四篇):生成侧核心技术与大模型集成
人工智能·学习·rag
阿豪只会阿巴11 小时前
【没事学点啥】TurboBlog轻量级个人博客项目——Turbo Blog 项目学习与上线指南
开发语言·python·学习·状态模式
Slow菜鸟11 小时前
Docker 学习篇(三)| Docker安装指南(Linux版)
linux·学习·docker