pytest解读fixture有效性及跨文件共享fixtures

Finn
Finn
发布时间:2026-10-15| 5人浏览过
原创

本文详细解析pytest中fixture的作用范围与请求机制,说明fixture仅在定义范围内有效,但可通过依赖链跨类访问。重点介绍利用conftest.py实现跨文件共享fixture的最佳实践,包括目录层级下的搜索规则与边界限制,帮助开发者构建可复用的测试基础设施。

fixture有效性及跨文件共享fixtures

一、fixture有效性

所谓fixture的有效性,指的是fixture函数仅在其定义的作用域内可被请求。例如,若在类中定义fixture,则仅有该类中的测试函数能够调用它;若fixture定义在模块级别,则该模块下所有测试函数均可请求该fixture。

此外,还有一个影响fixture有效性的参数autouse=True,默认值为False。当设置为True时,该fixture将在其他fixture之前执行,具体机制后续章节详述,此处仅作简要提及。

值得注意的是,一个fixture函数可以请求任何其他fixture函数,无论被请求的fixture定义在何处。只要测试函数请求了它们,fixture函数即可正常调用。

参考示例代码(为直观展示效果,在官方代码基础上增加了几个fixture函数的print输出):

#  content of test_module1.py 
import pytest
@pytest.fixture
def order():
    print("\n运行fixture函数-order")
    return []
@pytest.fixture
def outer(order, inner):
    print("运行fixture函数-outer")
    order.append("outer")
class TestOne:
    @pytest.fixture
    def inner(self, order):
        print("运行TestOne下的fixture-inner")
        order.append("one")
    def test_order(self, order, outer):
        assert order == ["one", "outer"]
class TestTwo:
    @pytest.fixture
    def inner(self, order):
        print("运行TestTwo下的fixture-inner")
        order.append("two")
    def test_order(self, order, outer):
        assert order == ["two", "outer"]

注意:

  • 此处存在一个位于测试类外部的fixture函数outer
  • 另有两个名称均为inner的fixture函数,分别定义在测试类TestOne和TestTwo中。
  • 在外部fixture函数outer中,进一步请求了内部fixture函数inner。

现在仅运行类TestOne,观察运行结果:

test_module1.py 
运行fixture函数-order
运行TestOne下的fixture-inner
运行fixture函数-outer
.                                                        [100%]
============================== 1 passed in 0.01s ==============================
Process finished with exit code 0

上述结果表明测试函数中的断言通过。在测试函数执行期间,外部outer请求的inner实际上来自TestOne。尽管TestOne类下的inner仅作用于TestOne内的测试函数,但由于测试函数请求了外部outer,因此外部outer也能成功获取内部inner。

官方提供了一张示意图,可结合上述思路进行理解。

需特别注意,fixture定义的范围与其被实例化的顺序无关:实例化顺序由调用逻辑强制执行。

详细参考:https://www.jb51.net/article/250148.htm

二、跨文件共享fixtures

若将fixture函数放置于conftest.py文件中,则该文件所在目录下的所有测试均可直接请求其中的fixture,无需显式导入。

在实际场景中,测试目录或包可能存在多层嵌套结构,此时每个目录均可拥有自己的conftest文件。例如:

各层级目录内容如下:

tests/
    __init__.py
    conftest.py
        # content of tests/conftest.py
        import pytest
        @pytest.fixture
        def order():
            return []
        @pytest.fixture
        def top(order, innermost):
            order.append("top")
    test_top.py
        # content of tests/test_top.py
        import pytest
        @pytest.fixture
        def innermost(order):
            order.append("innermost top")
        def test_order(order, top):
            assert order == ["innermost top", "top"]
    subpackage/
        __init__.py
        conftest.py
            # content of tests/subpackage/conftest.py
            import pytest
            @pytest.fixture
            def mid(order):
                order.append("mid subpackage")
        test_subpackage.py
            # content of tests/subpackage/test_subpackage.py
            import pytest
            @pytest.fixture
            def innermost(order, mid):
                order.append("innermost subpackage")
            def test_order(order, top):
                assert order == ["mid subpackage", "innermost subpackage", "top"]

同样,此处提供一张作用域边界图以辅助理解。

关键知识点:

  • 顶层conftest中的order和top对当前层及下层级的所有可用fixture生效(每个圈对应各自的作用域)。
  • 测试函数仅可向上层级搜索可用的fixture函数(即“出圈”),但在出圈查找过程中,不能再进入其他圈子向下查找。因此,tests/subpackage/test_subpackage.py::test_order可找到定义在tests/subpackage/test_subpackage.py中的innermost,但另一个定义在tests/test_top.py中且名为innermost的fixture,对test_order而言不可用。

简而言之,若想使用conftest中的fixture函数,仅能调用同层级或上层级的fixture。上级目录中的其他兄弟目录或包,以及其下层级的conftest,均无法被访问。

尽管官方文档使用“圈子”描述较为严谨,但上述白话解释更易于理解。

以上为pytest解读fixture有效性及跨文件共享fixtures的详细内容,更多关于pytest解读fixtures的资料请关注本站其它相关文章!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。