【问题标题】:Parametrize set of tests using PyTest使用 PyTest 参数化测试集
【发布时间】:2014-06-19 14:30:45
【问题描述】:

我有以下问题,我需要使用pytest执行一堆测试,每个测试基本相同,唯一不同的是参数。

例如我必须执行:

  ./command_line arg1
  ./command_line arg2
  ...
  ./command_line argN

然后我需要验证可执行文件 command 是否总是返回预期的给定结果。

我知道this,所以我想请教一条关于哪种方法最适合我的问题的建议。

提前谢谢你!

编辑: 最后我在 StackOverflow 中找到了question,建议查看this page,我发现它对我的情况很有用。

【问题讨论】:

  • 不再推荐使用 yield 生成测试,如您链接的博客文章(我写的)中所述(它是在 2008 年写的!)。下面@sashk 提供的答案就是这样做的方法。

标签: python unit-testing testing pytest


【解决方案1】:

我通常使用pytest.mark.parametrize 执行此操作,它的工作原理如下:

import pytest


@pytest.mark.parametrize('arg, result', [
 ('arg1', 'result1'),
 ('arg2', 'result2'),
 ('arg3', 'result3'),
 ('argN', 'resultN'),
])
def test_cmd0(arg, result):
    out = subprocess.check_output(['cmd', arg])
    assert out.rstrip() == out

arg1, .. argN - 你的论点,result1, .., resultN 你的预期结果。

在上面的示例中,我展示了如何启动外部命令并在每次运行时期望不同的结果。如果预期结果相同,您可以随时在参数化中跳过 result 并执行以下操作:

assert out.rstrip() == 'expected result'

【讨论】:

  • 即使我已经使用我在编辑中添加的链接解决了我的问题,我也会选择@sashk 的答案,因为我知道它也解决了我提出的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-15
  • 2018-02-24
  • 2023-01-20
  • 1970-01-01
  • 1970-01-01
  • 2021-09-13
相关资源
最近更新 更多