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

pytest通过indirect向fixture传参提示fixture未找到如何解决

问题原因

报错是fixture的参数接收逻辑写错导致的:使用indirect方式给fixture传参时,pytest不会把传入的参数作为同名入参注入fixture,所有传入的参数都需要通过内置的request fixture的param属性获取。
你写的sorted_array fixture声明了to_power入参,pytest会默认这个入参是另一个需要被加载的fixture,找不到对应实现就会抛出fixture 'to_power' not found错误。

修复代码

把fixture的入参改为内置的request,通过request.param拿到传入的幂次值即可,修正后的可运行代码:

import math
import pytest

@pytest.fixture(scope="function")
def sorted_array(request):
    pow_value = request.param
    assert pow_value >= 2
    size = int(math.pow(2, pow_value))
    return [i for i in range(size)]


@pytest.mark.parametrize(
    "sorted_array",
    [2],
    indirect=["sorted_array"],
)
def test_binary_search_2(sorted_array):
    times_elapsed = []
    # 补充你的测试逻辑
补充说明
  • 原代码里parametrize的参数列表写的[(2)]在Python语法中等价于整数2,不是单元素元组,单值传参直接写[2]即可;如果需要传多参数,可以传元组、字典结构,再从request.param中拆解取值。
  • 当parametrize仅声明了一个测试参数时,indirect=True和indirect=["sorted_array"]的效果完全一致,可以按需选择写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 06:39:25