繁体   English   中英

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

[英]Can I handle multiple asserts within a single Python pytest method?

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

问题是 - 如果第一个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个断言吗?

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

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结合比较,但由于短路 ,这不起作用。 例如,我尝试了这个断言:

assert a == 10 and b == 9

Pytest报告了这次失败:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM