32
社区成员
发帖
与我相关
我的任务
分享fixture的覆盖重写简单点来说就是遵循就近原则,即在测试函数中总是调用离测试函数最近的fixture,具体点说就是:
(1)内层的conftest.py中的fixture会覆盖外层conftest.py中的fixture
(2)测试模块中的fixture会覆盖conftest.py中的同名fixture
(3)参数化中的参数会覆盖测试模块中的同名fixture
目录结构如下:
tests
|----conftest.py
|----demo
|----__init__.py
|----conftest.py
|----test_demo.py
其中tests/conftest.py内容如下:
import pytest
@pytest.fixture()
def conf_fixture():
print("in outer conftest.py fixture...")
tests/demo/conftest.py内容如下:
import pytest
@pytest.fixture()
def conf_fixture():
print("in inner conftest.py fixture...")
@pytest.fixture()
def module_fixture():
print("in conftest.py module fixture...")
test_demo.py内容如下:
import pytest
@pytest.fixture()
def module_fixture():
print("in test_demo.py module fixture...")
@pytest.fixture()
def f1():
return "hello f1 function"
def test_01(conf_fixture):
print("in test_01...")
def test_02(module_fixture):
print("in test_02")
@pytest.mark.parametrize("f1",["hello zhangwuji"])
def test_03(f1):
print("in test_03...")
print(f1)
执行结果如下,可以看出,test_01函数调用了内层的conftest.py中的fixture,test_02函数调用了test_demo.py中的fixture,test_03函数则直接调用了参数化的参数,即均遵循就近原则
$ pytest -s
========================================================================= test session starts ==========================================================================
platform win32 -- Python 3.9.6, pytest-6.2.5, py-1.10.0, pluggy-1.0.0
rootdir: G:\src\blog\tests
plugins: allure-pytest-2.9.43, caterpillar-pytest-0.0.2, hypothesis-6.31.6, forked-1.3.0, rerunfailures-10.1, xdist-2.3.0
collected 3 items
demo\test_demo.py in inner conftest.py fixture...
in test_01...
.in test_demo.py module fixture...
in test_02
.in test_03...
hello zhangwuji
.
========================================================================== 3 passed in 0.07s ===========================================================================