fixture的作用类似于setup/teardown。
fixture命名不以test开头,用于区分用例。
在函数前使用装饰器@pytest.fixture(),括号中有个scope的参数,用于控制fixture的范围。默认取值为function,控制范围的排序为:session > module > class > function。取值范围如下所示:
代码如下:定义了一个init方法,作为参数传入test_1和test_02函数,在test_1函数中对init的返回值做了断言
import pytest
@pytest.fixture()
def init():
print('init...')
return 1
def test_1(init):
print('test1')
assert init == 1
def test_2(init):
print('test2')
输出如下:
======================================================================== test session starts ========================================================================
platform win32 -- Python 3.7.6, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 -- d:\python3.7.6\python.exe
cachedir: .pytest_cache
rootdir: D:\pythonProject\my_selenium_project\testcases\pytest, configfile: pytest.ini
collected 2 items
test_fixture.py::test_1 init...
test1
PASSED
test_fixture.py::test_2 init...
test2
PASSED
========================================================================= 2 passed in 0.03s =========================================================================