Pytest - 错误与失败

Gil*_*tes 10 python testing pytest python-unittest

我从PyUnit迁移到Pytest,我发现,与PyUnit不同,Pytest在运行测试(打印点)时不会在快速报告中区分测试报告中的失败和错误.怎么教Pytest做的呢?

UPDATE

看起来它只适用于使用Pytest执行的PyUnit测试,感谢flub的线索.

码:

import unittest

class TestErrorFail(unittest.TestCase):
    def test_error(self):
        raise Exception('oops')

    def test_fail(self):
        self.assertTrue(False)
Run Code Online (Sandbox Code Playgroud)

输出:

================================ test session starts =================================
platform linux2 -- Python 2.7.3 -- py-1.4.20 -- pytest-2.5.2
plugins: django
collected 2 items 

sometests.py FF

====================================== FAILURES ======================================
______________________________ TestErrorFail.test_error ______________________________

self = <sometests.TestErrorFail testMethod=test_error>

    def test_error(self):
>       raise Exception('oops')
E       Exception: oops

sometests.py:5: Exception
______________________________ TestErrorFail.test_fail _______________________________

self = <sometests.TestErrorFail testMethod=test_fail>

    def test_fail(self):
>       self.assertTrue(False)
E       AssertionError: False is not true

sometests.py:8: AssertionError
============================== 2 failed in 0.69 seconds ==============================
Run Code Online (Sandbox Code Playgroud)

flu*_*lub 8

据我所知,py.test可以区分失败和错误,请考虑以下示例:

import pytest

def test_fail():
    assert 1 == 2

@pytest.fixture
def fix():
    raise Exception('oops')

def test_error(fix):
    assert fix == 2
Run Code Online (Sandbox Code Playgroud)

运行此测试模块会出现一个故障和一个错误:

================ test session starts =========================
platform linux2 -- Python 2.7.5 -- py-1.4.20 -- pytest-2.5.2
plugins: timeout, capturelog, xdist
collected 2 items 

../../tmp/test_foo.py FE

======================= ERRORS ===============================
_________________ ERROR at setup of test_error _______________

    @pytest.fixture
    def fix():
>       raise Exception('oops')
E       Exception: oops

/tmp/test_foo.py:8: Exception
====================== FAILURES ==============================
__________________________ test_fail ____________________________

    def test_fail():
>       assert 1 == 2
E       assert 1 == 2

/tmp/test_foo.py:4: AssertionError
============= 1 failed, 1 error in 0.12 seconds ================
Run Code Online (Sandbox Code Playgroud)

UPDATE

但请注意,py.test会将异常期间引发的任何异常视为正常故障.这实际上是一件好事,通常你希望能够通过异常而不是AssertionError(或其子类)来使测试失败.在上面的示例中,您将发现错误条件是通过在夹具中引发异常而不是在测试期间触发的.

然而,尝试使用UnitTest类,结果表明在.setUp()方法中引发异常确实会导致失败而不是错误.这可能是一个错误,如果你愿意,你可以报告它.


Okk*_*ken 8

对于pytest,测试函数中抛出的任何未捕获的异常都是失败的,包括但不限于断言错误.

错误保留给夹具中的故障.
在命名的pytest fixture中,例如在flub的示例中,或在xUnit样式的setup/teardown fixture中,未捕获的异常会导致Error而不是失败.

我个人喜欢这种区别.
失败表示测试以某种方式失败.
错误表示您无法进行正确的测试.

请注意,即使在拆除例外的情况下也会发生错误.
在这种情况下,您完成了测试,并且拆卸在某种程度上失败了.