You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

conftest.py中已存在fix_test fixture,运行测试时却提示找不到

问题描述

这是我的测试类:

import pytest


class TestInstallation:
    def test_some(self, fix_test):
        print(fix_test)

conftest.py

import pytest


@pytest.fixture()
def fix_test():
    return 123

运行测试时收到如下错误:

def test_install(self, fix_test): E       fixture 'fix_test' not found
       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig,
record_property, record_testsuite_property, record_xml_attribute,
recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
       use 'pytest --fixtures [testpath]' for help on them.

但把fixture放在测试类内部时,测试运行正常。请问哪里操作出错了?

问题原因及解决方法

出现这个问题的核心是pytest无法正确加载你的conftest.py文件,以下是具体排查和解决步骤:

  • 检查conftest.py的位置:pytest只会在测试文件所在目录及其父级目录中查找conftest.py。确保该文件和测试文件处于同一目录,或者测试文件所在目录的上层目录中。比如测试文件放在tests/子目录,conftest.py要么放在tests/里,要么放在项目根目录。
  • 确认文件名拼写:必须严格是conftest.py,不能有拼写错误(比如写成conf_test.py),Linux/macOS系统还要注意大小写,不能写成Conftest.py。
  • 检查pytest运行路径:如果运行pytest时指定了具体子目录,而conftest.py在上级目录,建议切换到项目根目录再运行pytest,这样pytest能递归找到所有层级的conftest.py。
  • 验证fixture定义:确保conftest.py里的fixture没有语法错误(比如缩进错误、函数定义错误),这类问题也会导致pytest无法加载该fixture。

内容的提问来源于stack exchange,提问作者Dana Yeger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 23:41:23