如何在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
相关产品推荐
相关产品推荐

