以前介绍过测试函数的参数化,fixture 本身也是函数 也可以进行参数化.
比如我们想用不同的用户进行登录,就可以用这个特性, 进行登录初始化.
对测试函数进行参数化处理,可以多次运行的只是该测试函数,而使用参数化fixture
,每个使用该fixture的测试函数都可以被运行多次,fixture 的这个特性非常强大.
直接看例子 :
import pytest
data=[1,2,4]
@pytest.fixture(params=data)
def class_scope(request):
return request.param+1
def test_01(class_scope):
print(class_scope)
assert class_scope==2
打印结果 被认为三个方法 :
platform win32 -- Python 3.6.6, pytest-4.0.0, py-1.7.0, pluggy-0.8.0
rootdir: D:\tasks_proj\tests, inifile: pytest.inicollected 3 items
test_add.py .2
F3
func\test_add.py:7 (test_01[2])
2 != 3
Expected :3
Actual :2
<Click to see difference>
class_scope = 3
def test_01(class_scope):
print(class_scope)
> assert class_scope==2
E assert 3 == 2
test_add.py:10: AssertionError
F5
func\test_add.py:7 (test_01[4])
2 != 5
Expected :5
Actual :2
<Click to see difference>
class_scope = 5
def test_01(class_scope):
print(class_scope)
> assert class_scope==2
E assert 5 == 2
test_add.py:10: AssertionError
[100%]
================================== FAILURES ===================================
_________________________________ test_01[2] __________________________________
class_scope = 3
def test_01(class_scope):
print(class_scope)
> assert class_scope==2
E assert 3 == 2
test_add.py:10: AssertionError
---------------------------- Captured stdout call -----------------------------
3
_________________________________ test_01[4] __________________________________
class_scope = 5
def test_01(class_scope):
print(class_scope)
> assert class_scope==2
E assert 5 == 2
test_add.py:10: AssertionError
---------------------------- Captured stdout call -----------------------------
5
===================== 2 failed, 1 passed in 0.09 seconds ======================
Process finished with exit code 0