Pytest学习(四) - fixture的使用
前言
写这篇文章,整体还是比较坎坷的,我发现有知识断层,理解再整理写出来,还真的有些难。
作为java党硬磕Python,虽然对我而言是常事了(因为我比较爱折腾,哈哈),但这并不能影响我的热情。
执念这东西,有时真的很强大,回想下,你有多久没有特别想坚持学一样技能或者看一本书了呢。
之前就有很多粉丝和我说,六哥pytest很简单,都是入门的东西不爱看,网上有很多教程,能不能写点干货呀,但我为什么还是要坚持写呢?
简单呀,因为我想学,我之前都是拿来改改直接用,“哪里不会点哪里”,个中细节处理不是很懂,想好好消化下,再整理写出来。
fixture功能
- 传入测试中的数据集
- 配置测试前系统的数据准备,即初始化数据
- 为批量测试提供数据源
fixture可以当做参数传入
如何使用
在函数上加个装饰器@pytest.fixture(),个人理解为,就是java的注解在方法上标记下,依赖注入就能用了。
fixture是有返回值,没有返回值默认为None。用例调用fixture返回值时,把fixture的函数名当做变量用就可以了,示例代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/24 18:23
# @Author : longrong.lang
# @FileName: test_fixture_AsParam.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
import pytest
@pytest.fixture()
def param():
return "fixture当做参数"
def test_Asparam(param):
print('param : '+param)
输出结果:

多个fixture的使用
示例代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/24 18:43
# @Author : longrong.lang
# @FileName: test_Multiplefixture.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
多个fixture使用情况
'''
import pytest
@pytest.fixture()
def username():
return '软件测试君'
@pytest.fixture()
def password():
return '123456'
def test_login(username, password):
print('\n输入用户名:'+username)
print('输入密码:'+password)
print('登录成功,传入多个fixture参数成功')
输出结果:

fixture的参数使用
示例代码如下:
@pytest.fixture(scope="function", params=None, autouse=False, ids=None, name=None)
def test():
print("fixture初始化参数列表")
参数说明:
- scope:即作用域,function"(默认),"class","module","session"四个
- params:可选参数列表,它将导致多个参数调用fixture函数和所有测试使用它。
- autouse:默认:False,需要用例手动调用该fixture;如果是True,所有作用域内的测试用例都会自动调用该fixture
- ids:params测试ID的一部分。如果没有将从params自动生成.
- name:默认:装饰器的名称,同一模块的fixture相互调用建议写个不同的name。
- session的作用域:是整个测试会话,即开始执行pytest到结束测试
scope参数作用范围
控制fixture的作用范围:session>module>class>function
- function:每一个函数或方法都会调用
- class:每一个类调用一次,一个类中可以有多个方法
- module:每一个.py文件调用一次,该文件内又有多个function和class
- session:是多个文件调用一次,可以跨.py文件调用,每个.py文件就是module
scope四个参数的范围
1、scope="function
@pytest.fixture()如果不写参数,参数就是scope="function",它的作用范围是每个测试用例执行之前运行一次,销毁代码在测试用例之后运行。在类中的调用也是一样的。
示例代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/24 19:05
# @Author : longrong.lang
# @FileName: test_fixture_scopeFunction.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
scope="function"示例
'''
import pytest
# 默认不填写
@pytest.fixture()
def test1():
print('\n默认不填写参数')
# 写入默认参数
@pytest.fixture(scope='function')
def test2():
print('\n写入默认参数function')
def test_defaultScope1(test1):
print('test1被调用')
def test_defaultScope2(test2):
print('test2被调用')
class Testclass(object):
def test_defaultScope2(self, test2):
print('\ntest2,被调用,无返回值时,默认为None')
assert test2 == None
if __name__ == '__main__':
pytest.main(["-q", "test_fixture_scopeFunction.py"])
输出结果:

2、scope="class"
fixture为class级别的时候,如果一个class里面有多个用例,都调用了此fixture,那么此fixture只在此class里所有用例开始前执行一次。
示例代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/24 19:15
# @Author : longrong.lang
# @FileName: test_fixture_scopeClass.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
scope="class"示例
'''
import pytest
@pytest.fixture(scope='class')
def data():
# 这是测试数据
print('这是我的数据源,优先准备着哈')
return [1, 2, 3, 4, 5]
class TestClass(object):
def test1(self, data):
# self可以理解为它自己的,英译汉我就是这么学的哈哈
print('\n输出我的数据源:' + str(data))
if __name__ == '__main__':
pytest.main(["-q", "test_fixture_scopeClass.py"])
输出结果:

3、scope="module"
fixture为module时,在当前.py脚本里面所有用例开始前只执行一次。
示例代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/24 19:27
# @Author : longrong.lang
# @FileName: test_scopeModule.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
fixture为module示例
'''
import pytest
@pytest.fixture(scope='module')
def data():
return '\nscope为module'
def test1(data):
print(data)
class TestClass(object):
def text2(self, data):
print('我在类中了哦,' + data)
if __name__ == '__main__':
pytest.main(["-q", "test_scopeModule.py"])
输出结果:

4、scope="session"
fixture为session,允许跨.py模块调用,通过conftest.py 共享fixture。
也就是当我们有多个.py文件的用例的时候,如果多个用例只需调用一次fixture也是可以实现的。
必须以conftest.py命名,才会被pytest自动识别该文件。放到项目的根目录下就可以全局调用了,如果放到某个package下,那就在该package内有效。
文件目录结构如下:

创建公共数据,命名为conftest.py,示例代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/24 19:37
# @Author : longrong.lang
# @FileName: conftest.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
import pytest
@pytest.fixture(scope='session')
def commonData():
str = ' 通过conftest.py 共享fixture'
print('获取到%s' % str)
return str
创建测试脚本test_scope1.py,示例代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/24 19:45
# @Author : longrong.lang
# @FileName: test_scope1.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
import pytest
def testScope1(commonData):
print(commonData)
assert commonData == ' 通过conftest.py 共享fixture'
if __name__ == '__main__':
pytest.main(["-q", "test_scope1.py"])
创建测试脚本test_scope2.py,示例代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/24 19:45
# @Author : longrong.lang
# @FileName: test_scope1.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
import pytest
def testScope2(commonData):
print(commonData)
assert commonData == ' 通过conftest.py 共享fixture'
if __name__ == '__main__':
pytest.main(["-q", "test_scope2.py"])
然后同时执行两个文件,cmd到脚本所在目录,输入命令
pytest -s test_scope2.py test_scope1.py
输出结果:

知识点:
一个工程下可以有多个conftest.py的文件,在工程根目录下设置的conftest文件起到全局作用。在不同子目录下也可以放conftest.py的文件,作用范围只能在改层级以及以下目录生效,另conftest是不能跨模块调用的。
fixture的调用
- 将fixture名作为测试用例函数的输入参数
- 测试用例加上装饰器:@pytest.mark.usefixtures(fixture_name)
- fixture设置autouse=True
示例代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/24 20:10
# @Author : longrong.lang
# @FileName: test_fixtureCall.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
fixture调用示例
'''
import pytest
# 调用方式一
@pytest.fixture
def login1():
print('第一种调用')
# 传login
def test_case1(login1):
print("\n测试用例1")
# 不传login
def test_case2():
print("\n测试用例2")
# 调用方式二
@pytest.fixture
def login2():
print("第二种调用")
@pytest.mark.usefixtures("login2", "login1")
def test_case3():
print("\n测试用例3")
# 调用方式三
@pytest.fixture(autouse=True)
def login3():
print("\n第三种调用")
# 不是test开头,加了装饰器也不会执行fixture
@pytest.mark.usefixtures("login2")
def loginss():
print(123)
if __name__ == '__main__':
pytest.main(["-q", "test_fixtureCall.py"])
输出结果:

小结:
- 在类声明上面加 @pytest.mark.usefixtures() ,代表这个类里面所有测试用例都会调用该fixture
- 可以叠加多个 @pytest.mark.usefixtures() ,先执行的放底层,后执行的放上层
- 可以传多个fixture参数,先执行的放前面,后执行的放后面
- 如果fixture有返回值,用 @pytest.mark.usefixtures() 是无法获取到返回值的,必须用传参的方式(参考方式一)
- 不是test开头,加了装饰器也不会执行fixture
fixture依赖其他fixture的调用
添加了 @pytest.fixture ,如果fixture还想依赖其他fixture,需要用函数传参的方式,不能用 @pytest.mark.usefixtures() 的方式,否则会不生效
示例代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/24 20:23
# @Author : longrong.lang
# @FileName: test_fixtureRelyCall.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
fixture依赖其他fixture的调用示例
'''
import pytest
@pytest.fixture(scope='session')
# 打开浏览器
def openBrowser():
print('\n打开Chrome浏览器')
# @pytest.mark.usefixtures('openBrowser')这么写是不行的哦,肯定不好使
@pytest.fixture()
# 输入账号密码
def loginAction(openBrowser):
print('\n输入账号密码')
# 登录过程
def test_login(loginAction):
print('\n点击登录进入系统')
if __name__ == '__main__':
pytest.main(["-q", "test_fixtureRelyCall.py"])
输出结果:

fixture的params
@pytest.fixture有一个params参数,接受一个列表,列表中每个数据都可以作为用例的输入。也就说有多少数据,就会形成多少用例,具体示例代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/24 20:30
# @Author : longrong.lang
# @FileName: test_fixtureParams.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
fixture的params示例
'''
import pytest
seq=[1,2]
@pytest.fixture(params=seq)
def params(request):
# request用来接收param列表数据
return request.param
def test_params(params):
print(params)
assert 1 == params
输出结果:

fixture之yield实现teardown
fixture里面的teardown,可以用yield来唤醒teardown的执行,示例代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/24 20:44
# @Author : longrong.lang
# @FileName: test_fixtrueYield.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
fixture之yield示例
'''
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
@pytest.fixture(scope='module')
def open():
print("打开浏览器!!!")
yield
print('关闭浏览器!!!')
def test01():
print("\n我是第一个用例")
def test02(open):
print("\n我是第二个用例")
if __name__ == '__main__':
pytest.main(["-q", "test_fixtrueYield.py"])
输出结果:

yield遇到异常
还在刚才的代码中修改,将test01函数中添加异常,具体代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/24 20:44
# @Author : longrong.lang
# @FileName: test_fixtrueYield.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
'''
fixture之yield示例
'''
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
@pytest.fixture(scope='module')
def open():
print("打开浏览器!!!")
yield
print('关闭浏览器!!!')
def test01():
print("\n我是第一个用例")
# 如果第一个用例异常了,不影响其他的用例执行
raise Exception #此处异常
def test02(open):
print("\n我是第二个用例")
if __name__ == '__main__':
pytest.main(["-q", "test_fixtrueYield.py"])
输出结果:

小结
- 如果yield前面的代码,即setup部分已经抛出异常了,则不会执行yield后面的teardown内容
- 如果测试用例抛出异常,yield后面的teardown内容还是会正常执行
addfinalizer终结函数(不太熟悉)
@pytest.fixture(scope="module")
def test_addfinalizer(request):
# 前置操作setup
print("==再次打开浏览器==")
test = "test_addfinalizer"
def fin():
# 后置操作teardown
print("==再次关闭浏览器==")
request.addfinalizer(fin)
# 返回前置操作的变量
return test
def test_anthor(test_addfinalizer):
print("==最新用例==", test_addfinalizer)
小结:
- 如果 request.addfinalizer() 前面的代码,即setup部分已经抛出异常了,则不会执行 request.addfinalizer() 的teardown内容(和yield相似,应该是最近新版本改成一致了)
- 可以声明多个终结函数并调用
Pytest学习(四) - fixture的使用的更多相关文章
- pytest学习笔记
From: https://blog.csdn.net/gaowg11/article/details/54910974 由于对测试框架了解比较少,所以最近看了下pytest测试框架,对学习心得做个记 ...
- pytest框架之fixture前置和后置
一.conftest.py 定义公共的fixture,多个测试类中都可以调用 pytest提供了conftest.py文件,可以将fixture定义在此文件中 运行测试用例时,不需要去导入这个文件,会 ...
- [转载]pytest学习笔记
pytest学习笔记(三) 接着上一篇的内容,这里主要讲下参数化,pytest很好的支持了测试函数中变量的参数化 一.pytest的参数化 1.通过命令行来实现参数化 文档中给了一个简单的例子, ...
- Pytest学习(三) - setup和teardown的使用
一.前言 从文章标题可以看出,就是初始化和释放的操作,根据我的java习惯来学习pytest,个人感觉没差太多,理解上也不是很难. 哦,对了,差点跑题了,这个框架是基于Python语言的,在学习的时候 ...
- Pytest学习笔记3-fixture
前言 个人认为,fixture是pytest最精髓的地方,也是学习pytest必会的知识点. fixture用途 用于执行测试前后的初始化操作,比如打开浏览器.准备测试数据.清除之前的测试数据等等 用 ...
- TweenMax动画库学习(四)
目录 TweenMax动画库学习(一) TweenMax动画库学习(二) TweenMax动画库学习(三) Tw ...
- pytest进阶之fixture
前言 学pytest就不得不说fixture,fixture是pytest的精髓所在,就像unittest中的setup和teardown一样,如果不学fixture那么使用pytest和使用unit ...
- SVG 学习<四> 基础API
目录 SVG 学习<一>基础图形及线段 SVG 学习<二>进阶 SVG世界,视野,视窗 stroke属性 svg分组 SVG 学习<三>渐变 SVG 学习<四 ...
- Android JNI学习(四)——JNI的常用方法的中文API
本系列文章如下: Android JNI(一)——NDK与JNI基础 Android JNI学习(二)——实战JNI之“hello world” Android JNI学习(三)——Java与Nati ...
- SCARA——OpenGL入门学习四(颜色)
OpenGL入门学习[四] 本次学习的是颜色的选择.终于要走出黑白的世界了~~ OpenGL支持两种颜色模式:一种是RGBA,一种是颜色索引模式. 无论哪种颜色模式,计算机都必须为每一个像素保存一些数 ...
随机推荐
- x86-TSO : 适用于x86体系架构并发编程的内存模型
Abstract : 如今大数据,云计算,分布式系统等对算力要求高的方向如火如荼.提升计算机算力的一个低成本方法是增加CPU核心,而不是提高单个硬件工作效率. 这就要求软件开发者们能准确,熟悉地运用高 ...
- 手把手教你配置git和git仓库
今天是git专题的第二篇,我们来介绍一下git的基本配置,以及建立一个git仓库的基本方法. 首先申明一点,本文不会介绍git的安装.一方面是大部分个人PC的系统当中都是已经装好了git的,另外一方面 ...
- 腾讯云ClickHouse如何实现自动化的数据均衡?
一.引言 ClickHouse 是一个用于联机分析( OLAP )的列式数据库管理系统( DBMS ).它于 2016 年以 Apache 2.0 协议开源,以优秀的查询性能,深受广大大数据工程师欢 ...
- Ubuntu16环境安装和使用NFS
通过NFS服务我们可以方便的读写服务器上的文件,一起来实战Ubuntu16环境安装和使用NFS: 文章概要 本次实战由以下步骤组成: 列举环境信息: 在192.168.119.128安装NFS服务,将 ...
- Java Web学习(十)Java拦截器
文章更新时间:2020/04/07 一.引言 既然要用拦截器,首先先得简单了解一下什么是拦截器: 概念:java里的拦截器是动态拦截Action调用的对象,它提供了一种机制可以使开发者在一个Actio ...
- Spring学习(七)bean装配详解之 【通过注解装配 Bean】【自动装配的歧义解决】
自动装配 1.歧义性 我们知道用@Autowired可以对bean进行注入(按照type注入),但如果有两个相同类型的bean在IOC容器中注册了,要怎么去区分对哪一个Bean进行注入呢? 如下情况, ...
- spring Boot面试题(2020最新版)
概述 什么是 Spring Boot? Spring Boot 是 Spring 开源组织下的子项目,是 Spring 组件一站式解决方案,主要是简化了使用 Spring 的难度,简省了繁重的配置,提 ...
- Chrome使用video无法正常播放MP4视频的解决方案
H5的video标签让前端开发者用一行代码就可以实现视频和音频的播放,然而,有时候我们会突然发现,某些Mp4格式的视频在Chrome下居然无法正常播放?这究竟是什么原因呢?这篇文章主要分析了部分Mp4 ...
- 开源 UI 库中,唯一同时实现了大表格虚拟化和树表格的 Table 组件
背景 有这样一个需求,一位 React Suite(以下简称 rsuite)的用户,他需要一个 Table 组件能够像 Jira Portfolio 一样,支持树形数据,同时需要支持大数据渲染. 截止 ...
- 简述application.properties和application.yml 以及 @ConfigurationProperties 和@PropertySource @Value 和@ImportResource的用法,区别
问题: 如何在application.properties和application.yml中配置String,Date,Object,Map,List类型的属性,并且idea能提示 先写一个Perso ...