【问题标题】:Why does py.test show my xfail tests as skipped?为什么 py.test 将我的 xfail 测试显示为已跳过?
【发布时间】:2016-11-30 06:05:39
【问题描述】:

我有一些 python 代码和一堆 pytest 测试。

我预计会失败的一些测试(也就是说,我正在测试错误处理,所以我传递了应该导致我的代码抛出异常的输入。)

为了做到这一点,我有这样的代码:

CF_TESTDATA =[('data/1_input.csv', 'data/1_input.csv', 'utf-8'),
              pytest.mark.xfail(('data/1_input_unknown_encoding.txt', '', 'utf-8')),
              ('data/1_input_macintosh.txt', 'data/1_converted_macroman.csv', 'macroman')]
@pytest.mark.parametrize('input_file, expected_output, encoding', CF_TESTDATA)

def test_convert_file(testdir, tmpdir, input_file, expected_output, encoding):
    '''
    Test the function that converts a file to UTF-8.
    '''
...

这里的想法是这个测试的第二次运行,input_file = 'data/1_input_unknown_encoding.txt',我预计被测代码会失败。

这似乎工作正常,当我从命令行运行时,pytest 告诉我测试已经失败。我可以按照调试器中的代码查看它是否引发了预期的异常。所以这一切都很好。

但 Jenkins 将这个测试显示为已跳过。当我查看输出时,我看到了以下消息:

Skip Message

expected test failure

为什么测试显示为已跳过?似乎测试运行,并且按预期失败。这与跳过的测试不同。

【问题讨论】:

  • 当您从 Jenkins 运行时,您是否从与交互式运行相同的当前目录运行它?
  • 我猜 Jenkins 会读取 JUnitXML 输出?我猜JUnitXML 根本没有办法说xfail,所以pytest 使用skip。但我真的不知道。
  • @TheCompiler 是 jenkins junit 插件读取 junit xml。 junit xml 包含一个类似<skipped message="the skipped message"> 的标签,用于跳过或预期的失败测试。该消息可以是来自 skip() 调用中消息的自定义消息。在 xfail 或 xpass 的情况下,消息由 pytest 设置为“预期的测试失败”或“xfail 标记的测试意外通过”。

标签: python unit-testing jenkins pytest


【解决方案1】:

答案是我错误地使用了 xfail。它不应该用于预期测试失败。它不这样做。如果测试失败或不失败,则记录为通过。

我需要做的是更改测试以捕获我期望的异常,如果没有抛出异常则出错。然后我将删除 xfails。

xfail 似乎适用于您的测试暂时失败并且您希望测试套件通过的情况。所以与其说是期待失败,不如说是不在乎失败。

虽然测试仍在运行,但未检查结果,因此报告显示此测试被跳过是合理的。

我的测试现在看起来像这样:

# Test the run function. 
ex1 = False 
try:
        result = main.run(base_dir + '/'+ input_file, \
                 client_config['properties']) 
except ValueError as e:
        ex1 = True
        print e

if expect_fail:
        assert ex1 
else:
        assert not ex1
        assert filecmp.cmp(result, base_dir + '/' + expected_output), \
            "Ouput file is not the same as the expected file: " + expected_output

【讨论】:

  • 它应该用于预期失败,问题是当被测代码行为正确(抛出异常)时,您的测试不应该失败。只有当代码 not 行为正确(未能引发异常)时,您的测试才会失败。
【解决方案2】:

添加一个答案来解释为什么 expectedFail 被标记为已跳过。

在py.test中测试状态可以是:

  • 通过或
  • 失败或
  • 跳过。 xfail(又名expectedFailure)是skipped的一个子集:

    • 带有@unittest.skip("message") 标记的测试未运行。
    • 带有@unittest.expectedFailure 标记的测试确实运行并且:

      • skipped message 设置为 xfail “预期测试失败”,如果结果为失败或
      • xpass “xfail 标记的测试意外通过”如果结果通过。

参考:

http://doc.pytest.org/en/latest/skipping.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    相关资源
    最近更新 更多