pytest

pytest-关于固件(fixture)的一些小知识

2021-08-09  本文已影响0人  Rainbow想喝奶茶

pytest的固件即fixture,感觉就是可以替换之前知道的setup以及teardown,利用它自身的参数(scopenameautouseparamsids)进行灵活应用。

应用

首先注意标明@pytest.fixture(),其次是测试函数中引用,即传入函数名称作为参数。
fixtureyield为界限,在这之前即是执行测试用例之前需要执行的语句(setup),在这之后是测试用例执行完成后继续执行的语句(teardown)。

import pytest
@pytest.fixture()
def connection():
    print("start connection")
    yield
    print("connection closed")
#固件可以通过测试函数名称传入
def test_one(connection):
    assert 1==1
    print("test_one")

def test_two(connection):
    assert 2==2
    print("test_two")

重命名name

如果fixture中标明name,即@pytest.fixture(name='connect'),在引用时就需要将connect作为参数传入,而不能是函数名称。

作用范围scope

fixture的作用范围可分为会话级、模块级、类级以及函数级,创建fixture时可以通过scope参数进行标记对应的作用域。

@pytest.fixture(scope='session')
# 不传scope参数,默认是函数级
def session():
    print("start connection")
    yield
    print("connection closed")

会话级、模块级以及函数级均可以在测试函数直接传入参数。如果是类执行作用域,则需要在类前进行mark标记@pytest.mark.usefixtures('class_scope')。如果对应的class_scope传参scope='class',则该类会在最开始执行yield之前的语句,然后执行该类包含的测试用例,所有的函数执行完毕后,执行yield之后的语句。

自动应用autouse

如果在fixture传递autouse参数,测试函数在参数中不引用,也会自动执行。

@pytest.fixture(autouse=True)
#增加autouse参数,下方函数无需引用
def connection():
    print("start connection")
    yield
    print("connection closed")
def test_one():
    assert 1==1
    print("test_one")

参数化params

固件传入参数,是通过params传递,而后通过调用request.param获取参数。

@pytest.fixture(params=[('redis','111'),('mongo','222')])
def param(request):
    return request.param

@pytest.fixture(autouse=True)
def db(param):
    print("start collection %s:%s" % param)
    yield
    print("close collection %s:%s" % param)

def test_param():
    assert 1==1

另一种我觉得比较清晰的方式,更新一下:

import pytest
@pytest.fixture()
def tparam(request):
    name=request.param
    return name

data=["Lisa","Elsa"]

@pytest.mark.parametrize("tparam",data)
def test_fixture_param(tparam):
    print("名称是%s" % tparam)

运行结果如下图所示:


fixture传参运行结果

自我记录,有错误欢迎指正~

上一篇下一篇

猜你喜欢

热点阅读