Pytest学习4 -fixture的详细使用

  • 前面一篇讲了setup、teardown可以实现在执行用例前或结束后加入一些操作,但这种都是针对整个脚本全局生效的
  • 如果有以下场景:用例 1 需要先登录,用例 2 不需要登录,用例 3 需要先登录。很显然无法用 setup 和 teardown 来实现了
  • fixture可以让我们自定义测试用例的前置条件
fixture功能
传入测试中的数据集
配置测试前系统的数据准备,即初始化数据
为批量测试提供数据源
fixture可以当做参数传入

优势

命名方式灵活,不局限于 setup 和teardown 这几个命名
conftest.py 配置里可以实现数据共享,不需要 import 就能自动找到fixture
scope="module" 可以实现多个.py 跨文件共享前置
scope="session" 以实现多个.py 跨文件使用一个 session 来完成多个用例    

如何使用
在函数上加个装饰器@pytest.fixture(),个人理解为,就是java的注解在方法上标记下,依赖注入就能用了。
fixture是有返回值,没有返回值默认为None。用例调用fixture返回值时,把fixture的函数名当做变量用就可以了,示例代码如下:

# -*- coding: utf-8 -*-

# @FileName: test_Multiplefixture.py

'''
多个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参数成功')

输出结果

图片.png

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 -*-

# @FileName: test_fixture_scopeFunction.py

'''
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"])

输出结果


图片.png

2、scope="class"
fixture为class级别的时候,如果一个class里面有多个用例,都调用了此fixture,那么此fixture只在此class里所有用例开始前执行一次。
示例代码如下:

# -*- coding: utf-8 -*-

# @FileName: test_fixture_scopeClass.py

'''
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"])

输出结果


图片.png

3、scope="module"
fixture为module时,在当前.py脚本里面所有用例开始前只执行一次。
示例代码如下:

# -*- coding: utf-8 -*-

# @FileName: test_scopeModule.py

'''
fixture为module示例
'''
import pytest
@pytest.fixture(scope='module')
def data():
    return '\nscope为module'
    
def test1(data):
    print(data)
class TestClass(object):
    def test2(self, data):
        print('我在类中了哦,' + data)
if __name__ == '__main__':
    pytest.main(["-q", "test_scopeModule.py"])

输出结果


图片.png

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


图片.png

创建公共数据,命名为conftest.py,示例代码如下:

# -*- coding: utf-8 -*-

# @FileName: conftest.py

import pytest
@pytest.fixture(scope='session')
def commonData():
    str = ' 通过conftest.py 共享fixture'
    print('获取到%s' % str)
    return str

创建测试脚本test_scope1.py,示例代码如下:

# -*- coding: utf-8 -*-

# @FileName: test_scope1.py

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 -*-

# @FileName: test_scope2.py

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

输出结果


图片.png

知识点:
一个工程下可以有多个conftest.py的文件,在工程根目录下设置的conftest文件起到全局作用。在不同子目录下也可以放conftest.py的文件,作用范围只能在改层级以及以下目录生效,另conftest是不能跨模块调用的。

fixture的调用

将fixture名作为测试用例函数的输入参数
测试用例加上装饰器:@pytest.mark.usefixtures(fixture_name)
fixture设置autouse=True

示例代码如下:

# -*- coding: utf-8 -*-
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
__title__  =
__Time__   = 2020-04-06 15:50
__Author__ = 小菠萝测试笔记
__Blog__   = https://www.cnblogs.com/poloyy/
"""
import pytest

# 调用方式一
@pytest.fixture
def login():
    print("输入账号,密码先登录")


def test_s1(login):
    print("用例 1:登录之后其它动作 111")


def test_s2():  # 不传 login
    print("用例 2:不需要登录,操作 222")


# 调用方式二
@pytest.fixture
def login2():
    print("please输入账号,密码先登录")


@pytest.mark.usefixtures("login2", "login")
def test_s11():
    print("用例 11:登录之后其它动作 111")


# 调用方式三
@pytest.fixture(autouse=True)
def login3():
    print("====auto===")


# 不是test开头,加了装饰器也不会执行fixture
@pytest.mark.usefixtures("login2")
def loginss():
    print(123)

输出结果


图片.png

小结:
在类声明上面加 @pytest.mark.usefixtures() ,代表这个类里面所有测试用例都会调用该fixture
可以叠加多个 @pytest.mark.usefixtures() ,先执行的放底层,后执行的放上层
可以传多个fixture参数,先执行的放前面,后执行的放后面
如果fixture有返回值,用 @pytest.mark.usefixtures() 是无法获取到返回值的,必须用传参的方式(方式一)
不是test开头,加了装饰器也不会执行fixture

实例化顺序:
较高 scope 范围的fixture(session)在较低 scope 范围的fixture( function 、 class )之前实例化【session > package > module > class > function】
具有相同作用域的fixture遵循测试函数中声明的顺序,并遵循fixture之间的依赖关系【在fixture_A里面依赖的fixture_B优先实例化,然后到fixture_A实例化】
自动使用(autouse=True)的fixture将在显式使用(传参或装饰器)的fixture之前实例化

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest

order = []

@pytest.fixture(scope="session")
def s1():
    order.append("s1")

@pytest.fixture(scope="module")
def m1():
    order.append("m1")

@pytest.fixture
def f1(f3, a1):
    # 先实例化f3, 再实例化a1, 最后实例化f1
    order.append("f1")
    assert f3 == 123

@pytest.fixture
def f3():
    order.append("f3")
    a = 123
    yield a

@pytest.fixture
def a1():
    order.append("a1")

@pytest.fixture
def f2():
    order.append("f2")

def test_order(f1, m1, f2, s1):
    print(order)
    # m1、s1在f1后,但因为scope范围大,所以会优先实例化
    assert order == ["s1", "m1", "f3", "a1", "f1", "f2"]

图片.png

fixture依赖其他fixture的调用
添加了 @pytest.fixture ,如果fixture还想依赖其他fixture,需要用函数传参的方式,不能用 @pytest.mark.usefixtures() 的方式,否则会不生效

示例代码如下:

# -*- coding: utf-8 -*-

# @FileName: test_fixtureRelyCall.py

'''
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 -*-

# @FileName: test_fixtureParams.py

'''
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

图片.png

fixture之yield实现teardown
fixture里面的teardown,可以用yield来唤醒teardown的执行,示例代码如下:

# -*- 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"])

图片.png

yield遇到异常
还在刚才的代码中修改,将test01函数中添加异常,具体代码如下:

# -*- 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内容还是会正常执行

图片.png

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相似,应该是最近新版本改成一致了)
可以声明多个终结函数并调用

图片.png


参考链接
https://www.cnblogs.com/longronglang/p/13869445.html
https://www.cnblogs.com/poloyy/category/1690628.html?page=2

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,108评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,699评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,812评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,236评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,583评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,739评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,957评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,704评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,447评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,643评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,133评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,486评论 3 256
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,151评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,889评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,782评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,681评论 2 272