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

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

未完待续

相关推荐
有谁看见我的剑了?23 分钟前
stress 服务器压力测试的工具学习
服务器·学习·压力测试
有谁看见我的剑了?23 分钟前
stress-ng 服务器压力测试的工具学习
服务器·学习·压力测试
牛奶咖啡131 小时前
学习设计模式《十二》——命令模式
学习·设计模式·命令模式·队列请求·宏命令·可撤销恢复操作·参数化配置
余厌厌厌1 小时前
go语言学习 第9章:映射(Map)
服务器·学习·golang
委婉待续1 小时前
Qt的学习(一)
开发语言·qt·学习
哆啦A梦的口袋呀2 小时前
基于Python学习《Head First设计模式》第七章 适配器和外观模式
python·学习·设计模式
笑鸿的学习笔记2 小时前
虚幻引擎5-Unreal Engine笔记之SET节点的输出引脚获取设置后的最新变量值
笔记·ue5·虚幻
恰薯条的屑海鸥2 小时前
零基础在实践中学习网络安全-皮卡丘靶场(第十期-Over Permission 模块)
学习·安全·web安全·渗透测试·网络安全学习
草莓熊Lotso2 小时前
【数据结构初阶】--算法复杂度的深度解析
c语言·开发语言·数据结构·经验分享·笔记·其他·算法
东京老树根2 小时前
SAP学习笔记 - 开发27 - 前端Fiori开发 Routing and Navigation(路由和导航)
笔记·学习