Pytest----当fixture重名时如何调用

DevOps技术社区 2022-08-29 15:49:35

一、fixture覆盖重写规则

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 ===========================================================================
...全文
225 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

32

社区成员

发帖
与我相关
我的任务
社区描述
围绕测试开发、Devops、软件工程等方向,学习交流,共享技术新动态、新方向。求助工作中的问题,困惑等,互相交流,共同成长
软件工程测试工具devops 技术论坛(原bbs) 江苏省·南京市
社区管理员
  • redrose2100
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

1、社区话题和文章主要围绕DevOps技术栈

2、有广告需求请联系微信 Redrose2100

 

试试用AI创作助手写篇文章吧