【发布时间】:2020-07-01 17:20:42
【问题描述】:
我有一个 Python 程序,它根据输入规范生成 C 代码。我正在用 pytest 编写测试。当然,测试策略包括对生成的 C 代码的一些测试。
对于这些测试,计划如下所示:
-
我们有一组目录,每个目录都包含一个规范文件和一组适用的输入/预期输出案例。
-
fixture 将处理生成 C 代码并编译它。该夹具将在一组规范文件(由测试脚本以编程方式读取)上进行参数化。这样做的好处是,对于该规范下的所有测试用例,构建只能完成一次(因为构建成本很高)。
-
一个测试函数将从夹具中获取
GeneratedCode对象,使用特定输入运行它,并验证预期的输出。这将在一组输入/输出案例(也由脚本以编程方式读取)上进行参数化。
这样,添加新的测试用例就像添加新的规范或测试用例文件一样简单。测试脚本中无需复制粘贴代码。
我想象它看起来像这样:
# Get the list of specification files and test cases programmatically
specification_names = get_list_of_specifications()
test_cases = dict()
for spec in specification_names:
# get_list_of_test_cases() returns a list of (input, output) tuples
test_cases[spec] = get_list_of_test_cases(spec)
class GeneratedCode:
def __init__(spec):
"""Generate the C code for spec in a temp directory"""
self.name = spec
...
def build():
"""Build the generated C code"""
...
def run(input):
"""Run the code on given input."""
...
def cleanup():
...
@pytest.fixture(scope="module", params=specification_names)
def generated_code(request):
code = GeneratedCode(request.param)
code.build()
yield code
code.cleanup()
@pytest.mark.parametrize('test_input,expected_output', test_cases[???])
def test_generated_code(generated_code, test_input, expected_output):
assert generated_code.run(test_input) == expected_output
当然,这里的问题是@pytest.mark.parametrize() 不能每次都使用同一组测试用例,因为它取决于生成代码的规范。如果我们可以获取当前灯具的参数,我们可以在test_cases 字典中查找它,但我不确定如何做到这一点,或者是否有可能。
有没有办法做到这一点?我还有其他方法可以进行这些测试吗?
【问题讨论】: