我可以在一个Python pytest方法中处理多个断言吗?

时间:2017-03-30 13:45:32

标签: python python-2.7 python-3.x unit-testing pytest

我正在用pytest编写测试,我遇到了下一个问题:我有一个测试某个变量的测试,然后我执行了一些繁重的计算,之后我想再执行一次测试。 / p>

问题是 - 如果第一个assert失败,整个测试失败,pystest没有执行第二次测试。 代码:

class TestSomething:
    def tests_method(self, some_variables):
        # Some actions that take a lot of time!
        assert some_var == 1
        # Some actions that take a lot of time!
        assert some_var == 2

我知道这种测试方法可以分为两种方法,但这里的性能问题至关重要。

有一种方法可以在一种方法中运行2个断言吗?

1 个答案:

答案 0 :(得分:5)

通常,我只是让第一个断言的测试失败。但是,如果您真的想要进行多次比较,请比较元组。这是一个简单的例子:

def foo(x):
    return x + 1


def bar(y):
    return y - 1


def test_foo():
    # some expensive calculation                                                                                                                                    
    a = foo(10)

    # another expensive calculation                                                                                                                                 
    b = bar(10)

    assert (a, b) == (10, 9)

当我用pytest运行时,它显示了两个值:

$ pytest scratch.py
============================= test session starts =============================
platform linux2 -- Python 2.7.12, pytest-3.0.7, py-1.4.33, pluggy-0.4.0
rootdir: /home/don/workspace/scratch, inifile:
collected 1 items

scratch.py F

================================== FAILURES ===================================
__________________________________ test_foo ___________________________________

def test_foo():
# some expensive calculation
a = foo(10)

# another expensive calculation
b = bar(10)

>       assert (a, b) == (10, 9)
E       assert (11, 9) == (10, 9)
E         At index 0 diff: 11 != 10
E         Use -v to get the full diff

scratch.py:16: AssertionError
========================== 1 failed in 0.02 seconds ===========================

我还尝试使用and来结合比较,但由于short circuiting而无效。例如,我尝试了这个断言:

assert a == 10 and b == 9

Pytest报告了这次失败:

>       assert a == 10 and b == 9
E       assert (11 == 10)

除非您使用b选项,否则它不会报告--showlocals的值。