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

如何在pytest同一测试用例中同时传入fixture和参数化参数

错误原因
  • @pytest.mark.parametrize 中你声明了3个参数位my_graph, vertex, expected,但每组测试数据只提供了2个值,参数数量完全不匹配
  • 将fixture名称my_graph写入参数化列表的写法是错误的,pytest会将其识别为普通待填充的参数变量,不会触发fixture加载,同时还会导致后续的vertex、expected参数错位,pytest找不到对应的参数值就会报错提示找不到fixture
正确写法

参数化列表中仅声明需要动态传入的vertex和expected即可,my_graph fixture直接作为测试函数的入参,pytest会自动完成fixture的实例注入。
修正后可运行的完整代码如下:

import pytest
from typing import Union, List
import adjacency_list

@pytest.fixture
def my_graph() -> adjacency_list.Graph:
    return adjacency_list.Graph()

@pytest.mark.parametrize("vertex, expected", [
    ('A', ['A']),
    (1, [1])
])
def test_add_vertex(my_graph: adjacency_list.Graph, vertex: Union[str, int], expected: List[Union[str, int]]):
    my_graph.add_vertex(vertex)
    # 同时修复原代码中zip后缺失的右括号语法错误
    assert all(a == b for a, b in zip(my_graph.get_vertices(), expected))

补充说明:每个测试用例运行时都会拿到全新的my_graph实例,不同用例之间的图数据完全隔离,不会互相干扰,符合单元测试的预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 20:51:02