pytest框架精髓—fixture(pytest+allure框架)
off999 2024-10-23 12:43 27 浏览 0 评论
简介
一直在和大家聊pytest的一些内容,今天呢想和大家分享pytest框架的精髓,话不多说,我们直接开始吧,还有喜欢的记得关注我哟。
介绍:
fixture区别于unnitest的传统单元测试(setup/teardown)有显著改进:
1.有独立的命名,并通过声明它们从测试函数、模块、类或整个项目中的使用来激活。
2.按模块化的方式实现,每个fixture都可以互相调用。
3.fixture的范围从简单的单元测试到复杂的功能测试,可以对fixture配置参数,或者跨函数function,类class,模块module或整个测试session范围。
谨记:当我们使用pytest框架写case的时候,一定要拿它的命令规范去case,这样框架才能识别到哪些case需要执行,哪些不需要执行。
用例设计原则
文件名以test_*.py文件和*_test.py
以test_开头的函数
以Test开头的类
以test_开头的方法
fixture可以当做参数传入
定义fixture跟定义普通函数差不多,唯一区别就是在函数上加个装饰器@pytest.fixture(),fixture命名不要以test开头,跟用例区分开。fixture是有返回值得,没有返回值默认为None。用例调用fixture的返回值,直接就是把fixture的函数名称当做变量名称。
ex:
import pytest
@pytest.fixture()
def test1():
a = 'leo'
return a
def test2(test1):
assert test1 == 'leo'
if __name__ == '__main__':
pytest.main('-q test_fixture.py')
输出:
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 1 item
test_fixture.py . [100%]
========================== 1 passed in 0.02 seconds ===========================
Process finished with exit code 0使用多个fixture
如果用例需要用到多个fixture的返回数据,fixture也可以返回一个元祖,list或字典,然后从里面取出对应数据。
ex:
import pytest
@pytest.fixture()
def test1():
a = 'leo'
b = '123456'
print('传出a,b')
return (a, b)
def test2(test1):
u = test1[0]
p = test1[1]
assert u == 'leo'
assert p == '123456'
print('元祖形式正确')
if __name__ == '__main__':
pytest.main('-q test_fixture.py')
输出结果:
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 1 item
test_fixture.py 传出a,b
.元祖形式正确
[100%]
========================== 1 passed in 0.02 seconds ===========================
Process finished with exit code 0当然也可以分成多个fixture,然后在用例中传多个fixture参数
import pytest
@pytest.fixture()
def test1():
a = 'leo'
print('\n传出a')
return a
@pytest.fixture()
def test2():
b = '123456'
print('传出b')
return b
def test3(test1, test2):
u = test1
p = test2
assert u == 'leo'
assert p == '123456'
print('传入多个fixture参数正确')
if __name__ == '__main__':
pytest.main('-q test_fixture.py')
输出结果:
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 1 item
test_fixture.py
传出a
传出b
.传入多个fixture参数正确fixture互相调用
import pytest
@pytest.fixture()
def test1():
a = 'leo'
print('\n传出a')
return a
def test2(test1):
assert test1 == 'leo'
print('fixture传参成功')
if __name__ == '__main__':
pytest.main('-q test_fixture.py')
输出结果:
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 1 item
test_fixture.py
传出a
.fixture传参成功
[100%]
========================== 1 passed in 0.03 seconds ===========================
Process finished with exit code 0介绍完了fixture的使用方式,现在介绍一下fixture的作用范围(scope)
fixture的作用范围
fixture里面有个scope参数可以控制fixture的作用范围:session>module>class>function
-function:每一个函数或方法都会调用
-class:每一个类调用一次,一个类中可以有多个方法
-module:每一个.py文件调用一次,该文件内又有多个function和class
-session:是多个文件调用一次,可以跨.py文件调用,每个.py文件就是module
fixture源码详解
fixture(scope='function',params=None,autouse=False,ids=None,name=None):
scope:有四个级别参数"function"(默认),"class","module","session"
params:一个可选的参数列表,它将导致多个参数调用fixture功能和所有测试使用它。
autouse:如果True,则为所有测试激活fixture func可以看到它。如果为False则显示需要参考来激活fixture
ids:每个字符串id的列表,每个字符串对应于params这样他们就是测试ID的一部分。如果没有提供ID它们将从params自动生成
name:fixture的名称。这默认为装饰函数的名称。如果fixture在定义它的统一模块中使用,夹具的功能名称将被请求夹具的功能arg遮蔽,解决这个问题的一种方法时将装饰函数命令"fixture_<fixturename>"然后使用"@pytest.fixture(name='<fixturename>')"。
具体阐述一下scope四个参数的范围
scope="function"
@pytest.fixture()如果不写参数,参数就是scope="function",它的作用范围是每个测试用例来之前运行一次,销毁代码在测试用例之后运行。
import pytest
@pytest.fixture()
def test1():
a = 'leo'
print('\n传出a')
return a
@pytest.fixture(scope='function')
def test2():
b = '男'
print('\n传出b')
return b
def test3(test1):
name = 'leo'
print('找到name')
assert test1 == name
def test4(test2):
sex = '男'
print('找到sex')
assert test2 == sex
if __name__ == '__main__':
pytest.main('-q test_fixture.py')
输出结果:
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 2 items
test_fixture.py
传出a
.找到name
传出b
.找到sex
[100%]
========================== 2 passed in 0.04 seconds ===========================放在类中实现结果也是一样的
import pytest
@pytest.fixture()
def test1():
a = 'leo'
print('\n传出a')
return a
@pytest.fixture(scope='function')
def test2():
b = '男'
print('\n传出b')
return b
class TestCase:
def test3(self, test1):
name = 'leo'
print('找到name')
assert test1 == name
def test4(self, test2):
sex = '男'
print('找到sex')
assert test2 == sex
if __name__ == '__main__':
pytest.main(['-s', 'test_fixture.py'])
输出结果:
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 2 items
test_fixture.py
传出a
.找到name
传出b
.找到sex
[100%]
========================== 2 passed in 0.03 seconds ===========================
Process finished with exit code 0scope="class"
fixture为class级别的时候,如果一个class里面有多个用例,都调用了次fixture,那么此fixture只在此class里所有用例开始前执行一次。
import pytest
@pytest.fixture(scope='class')
def test1():
b = '男'
print('传出了%s, 且只在class里所有用例开始前执行一次!!!' % b)
return b
class TestCase:
def test3(self, test1):
name = '男'
print('找到name')
assert test1 == name
def test4(self, test1):
sex = '男'
print('找到sex')
assert test1 == sex
if __name__ == '__main__':
pytest.main(['-s', 'test_fixture.py'])
输出结果:
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 2 items
test_fixture.py 传出了男, 且只在class里所有用例开始前执行一次!!!
.找到name
.找到sex
[100%]
========================== 2 passed in 0.05 seconds ===========================
Process finished with exit code 0scope="module"
fixture为module时,在当前.py脚本里面所有用例开始前只执行一次。
import pytest
##test_fixture.py
@pytest.fixture(scope='module')
def test1():
b = '男'
print('传出了%s, 且在当前py文件下执行一次!!!' % b)
return b
def test3(test1):
name = '男'
print('找到name')
assert test1 == name
class TestCase:
def test4(self, test1):
sex = '男'
print('找到sex')
assert test1 == sex
if __name__ == '__main__':
pytest.main(['-s', 'test_fixture.py'])
输出结果:
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 2 items
test_fixture.py 传出了男, 且在当前py文件下执行一次!!!
.找到sex
.找到name
[100%]
========================== 2 passed in 0.03 seconds ===========================
Process finished with exit code 0scope="session"
fixture为session级别是可以跨.py模块调用的,也就是当我们有多个.py文件的用例的时候,如果多个用例只需调用一次fixture,那就可以设置为scope="session",并且写到conftest.py文件里。
conftest.py文件名称时固定的,pytest会自动识别该文件。放到项目的根目录下就可以全局调用了,如果放到某个package下,那就在改package内有效。
文件目录为
import pytest
# conftest.py
@pytest.fixture(scope='session')
def test1():
sex = '男'
print('获取到%s' % sex)
return seximport pytest
# test_fixture.py
def test3(test1):
name = '男'
print('找到name')
assert test1 == name
if __name__ == '__main__':
pytest.main(['-s', 'test_fixture.py'])import pytest
# test_fixture1.py
class TestCase:
def test4(self, test1):
sex = '男'
print('找到sex')
assert test1 == sex
if __name__ == '__main__':
pytest.main(['-s', 'test_fixture1.py'])如果需要同时执行两个py文件,可以在cmd中在文件py文件所在目录下执行命令:pytest -s test_fixture.py test_fixture1.py
执行结果为:
================================================= test session starts =================================================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:
collected 2 items
test_fixture.py 获取到男
找到name
.
test_fixture1.py 找到sex
.
============================================== 2 passed in 0.05 seconds ===============================================调用fixture的三种方法
1.函数或类里面方法直接传fixture的函数参数名称
import pytest
# test_fixture1.py
@pytest.fixture()
def test1():
print('\n开始执行function')
def test_a(test1):
print('---用例a执行---')
class TestCase:
def test_b(self, test1):
print('---用例b执行')
输出结果:
test_fixture1.py
开始执行function
.---用例a执行---
开始执行function
.---用例b执行
[100%]
========================== 2 passed in 0.05 seconds ===========================
Process finished with exit code 02.使用装饰器@pytest.mark.usefixtures()修饰需要运行的用例
import pytest
# test_fixture1.py
@pytest.fixture()
def test1():
print('\n开始执行function')
@pytest.mark.usefixtures('test1')
def test_a():
print('---用例a执行---')
@pytest.mark.usefixtures('test1')
class TestCase:
def test_b(self):
print('---用例b执行---')
def test_c(self):
print('---用例c执行---')
if __name__ == '__main__':
pytest.main(['-s', 'test_fixture1.py'])
输出结果:
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 3 items
test_fixture1.py
开始执行function
.---用例a执行---
开始执行function
.---用例b执行---
开始执行function
.---用例c执行---
[100%]
========================== 3 passed in 0.06 seconds ===========================
Process finished with exit code 0叠加usefixtures
如果一个方法或者一个class用例想要同时调用多个fixture,可以使用@pytest.mark.usefixture()进行叠加。注意叠加顺序,先执行的放底层,后执行的放上层。
import pytest
# test_fixture1.py
@pytest.fixture()
def test1():
print('\n开始执行function1')
@pytest.fixture()
def test2():
print('\n开始执行function2')
@pytest.mark.usefixtures('test1')
@pytest.mark.usefixtures('test2')
def test_a():
print('---用例a执行---')
@pytest.mark.usefixtures('test2')
@pytest.mark.usefixtures('test1')
class TestCase:
def test_b(self):
print('---用例b执行---')
def test_c(self):
print('---用例c执行---')
if __name__ == '__main__':
pytest.main(['-s', 'test_fixture1.py'])
输出结果:
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 3 items
test_fixture1.py
开始执行function2
开始执行function1
.---用例a执行---
开始执行function1
开始执行function2
.---用例b执行---
开始执行function1
开始执行function2
.---用例c执行---
[100%]
========================== 3 passed in 0.03 seconds ===========================
Process finished with exit code 0usefixtures与传fixture区别
如果fixture有返回值,那么usefixture就无法获取到返回值,这个是装饰器usefixture与用例直接传fixture参数的区别。
当fixture需要用到return出来的参数时,只能讲参数名称直接当参数传入,不需要用到return出来的参数时,两种方式都可以。
fixture自动使用autouse=True
当用例很多的时候,每次都传这个参数,会很麻烦。fixture里面有个参数autouse,默认是False没开启的,可以设置为True开启自动使用fixture功能,这样用例就不用每次都去传参了
autouse设置为True,自动调用fixture功能
import pytest
# test_fixture1.py
@pytest.fixture(scope='module', autouse=True)
def test1():
print('\n开始执行module')
@pytest.fixture(scope='class', autouse=True)
def test2():
print('\n开始执行class')
@pytest.fixture(scope='function', autouse=True)
def test3():
print('\n开始执行function')
def test_a():
print('---用例a执行---')
def test_d():
print('---用例d执行---')
class TestCase:
def test_b(self):
print('---用例b执行---')
def test_c(self):
print('---用例c执行---')
if __name__ == '__main__':
pytest.main(['-s', 'test_fixture1.py'])
输出结果:
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 4 items
test_fixture1.py
开始执行module
开始执行class
开始执行function
.---用例a执行---
开始执行class
开始执行function
.---用例d执行---
开始执行class
开始执行function
.---用例b执行---
开始执行function
.---用例c执行---
[100%]conftest.py的作用范围
一个工程下可以建多个conftest.py的文件,一般在工程根目录下设置的conftest文件起到全局作用。在不同子目录下也可以放conftest.py的文件,作用范围只能在改层级以及以下目录生效。
项目实例:
目录结构:
1.conftest在不同的层级间的作用域不一样
# conftest层级展示/conftest.py
import pytest
@pytest.fixture(scope='session', autouse=True)
def login():
print('----准备登录----')
# conftest层级展示/sougou_login/conftest
import pytest
@pytest.fixture(scope='session', autouse=True)
def bai_du():
print('-----登录百度页面-----')
# conftest层级展示/sougou_login/login_website
import pytest
class TestCase:
def test_login(self):
print('hhh,成功登录百度')
if __name__ == '__main__':
pytest.main(['-s', 'login_website.py'])
输出结果:
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\conftest层级演示\sougou_login, inifile:collected 1 item
login_website.py ----准备登录----
-----登录百度页面-----
.hhh,成功登录百度
[100%]
========================== 1 passed in 0.03 seconds ===========================
Process finished with exit code 02.conftest是不能跨模块调用的(这里没有使用模块调用)
# conftest层级演示/log/contfest.py
import pytest
@pytest.fixture(scope='function', autouse=True)
def log_web():
print('打印页面日志成功')
# conftest层级演示/log/log_website.py
import pytest
def test_web():
print('hhh,成功一次打印日志')
def test_web1():
print('hhh,成功两次打印日志')
if __name__ == '__main__':
pytest.main(['-s', 'log_website.py'])
输出结果:
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\conftest层级演示\log, inifile:
collected 2 items
log_website.py ----准备登录----
打印页面日志成功
hhh,成功一次打印日志
.打印页面日志成功
hhh,成功两次打印日志
.
========================== 2 passed in 0.02 seconds ===========================好了今天的分享就到这里啦,有喜欢的小伙伴可以给我点点关注,给这个文章点点赞,你的每一次点赞对于我来说都是动力。
相关推荐
- 截图电脑(截图电脑怎么操作)
-
方法一:系统自带截图具体操作:同时按下电脑的自带截图键【Windows+shift+S】,可以选择其中一种方式来截取图片:截屏有矩形截屏、任意形状截屏、窗口截屏和全屏截图。?方法二:QQ截图具体操作:...
- 显卡参数对比(rtx50系列显卡参数对比)
-
在规格方面:显卡容量大(大容量显卡在大型游戏中比较有用);显卡速度快(比如DDR5比DDR3快);核心频率高(比如4830在500MHZ左右,4870能到700多)这是显卡很重要的参数;还有流处理器...
- n卡驱动下载官网(n卡驱动官网网址)
-
1可能下载不了。2可能的原因是网速不稳定或者网络连接不畅,还有就是可能是服务器维护或者更新的原因。3如果下载不了,可以尝试换一个时间或者尝试使用其他的下载方式或者下载其他版本的驱动。另外,也可以...
- android模拟器下载安装(安卓模拟器软件下载)
-
电脑版安卓模拟器可以通过网上下载并安装。首先选择一个安卓模拟器,比如NoxPlayer、BlueStacks、LDPlayer等,然后在官网或其他可靠的下载网站下载对应的安装包。下载完成后,双击安装包...
- win7明明是管理员却没有权限
-
答:win7没有管理员权限的解决方法。1.为Windows7的右键菜单添加取得所有权的菜单:具体实现的方法不难,将以下内容另存为文本文件; 2.然后修改该文件的扩展名为.reg,双击导...
- 电脑c盘格式化了怎么装系统(电脑c盘格式化后还能用吗)
-
C盘只有格式化才能中心装系统吗?不是的。C盘格式化是为了让C盘更清洁,这样装了的系统比较纯净的。没有系统来及,用起来更是的速度快。格式化(format)是指对磁盘或磁盘中的分区(partition)进...
- 佳能(中国)官网下载(佳能(中国)官网下载appstore)
-
需要先进入佳能官网的下载页面,选择手机APP下载选项,根据手机操作系统的不同选择相应的下载链接即可成功下载佳能手机APP。下载链接通常会在网站的首页或者是产品页面上提供。总的来说,下载佳能手机APP非...
- c盘右边有个恢复分区怎么删除
-
1、从网上下载“分区助手专业6.2(或5.6)”,它能无损分区,下载后打开按提示安装,点击分区助手桌面快捷方式图标,打开分区助手专业版6.2主界面。2、右击要调出空间的分区,如E,选“分配自由空间”,...
- 电脑插着电源却不充电怎么办
-
电脑插上电源但无法充电可能有以下原因:1.电池没有完全安装,需要检查电池是否完全插入笔记本电脑中。2.电池损坏,如果电池老化或发生机械故障、磨损和损伤,充电电流将会被阻塞从而无法进行充电,需要更换...
-
- 如何格式化手机(华为p50如何格式化手机)
-
步骤/方式1软件格式化:利用psiloc公司的软件sTools,进行格式化手机,锁码为12345步骤/方式2软格:在手机上输入*#7370#之后要求你输入锁码,初始密码是:12345步骤/方式3硬格:先关机,再开机的时候按住拨号键、“*...
-
2025-12-17 12:03 off999
- win10自动更新的禁用方法(win10自动更新的禁用方法是什么)
-
方法一:Windows设置 要想关闭Win10自动更新,比较简单的一种方法就是进入到Windows设置中,将Windows更新直接关闭。步骤如下: 1、按“Windows+I”键,打开Wind...
- 优化win7系统运行速度(优化win7系统运行速度多少)
-
优化WIN7系统开机启动项的操作方法1、在桌面上按组合键(win键+R)打开运行窗口,接着输入“regedit”,回车确认,2、打开注册表编辑器后,我们依次点击展开“HKEY_CURRENT_USE...
欢迎 你 发表评论:
- 一周热门
-
-
抖音上好看的小姐姐,Python给你都下载了
-
全网最简单易懂!495页Python漫画教程,高清PDF版免费下载
-
Python 3.14 的 UUIDv6/v7/v8 上新,别再用 uuid4 () 啦!
-
飞牛NAS部署TVGate Docker项目,实现内网一键转发、代理、jx
-
python入门到脱坑 输入与输出—str()函数
-
宝塔面板如何添加免费waf防火墙?(宝塔面板开启https)
-
Python三目运算基础与进阶_python三目运算符判断三个变量
-
(新版)Python 分布式爬虫与 JS 逆向进阶实战吾爱分享
-
失业程序员复习python笔记——条件与循环
-
使用 python-fire 快速构建 CLI_如何搭建python项目架构
-
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)
