我可以在 pytest 中执行多个断言吗? [英] Can I perform multiple assertions in pytest?

查看:214
本文介绍了我可以在 pytest 中执行多个断言吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 pytest 进行 selenium 测试,想知道是否可以在单个测试中包含多个断言?

I'm using pytest for my selenium tests and wanted to know if it's possible to have multiple assertions in a single test?

我调用了一个比较多个值的函数,我希望测试报告所有不匹配的值.我遇到的问题是,一旦发现不匹配的值,使用assert"或pytest.fail"就会停止测试.

I call a function that compares multiple values and I want the test to report on all the values that don't match up. The problem I'm having is that using "assert" or "pytest.fail" stops the test as soon as it finds a value that doesn't match up.

有没有办法让测试继续运行并报告所有不匹配的值?

Is there a way to make the test carry on running and report on all values that don't match?

推荐答案

正如 Jon Clements 所评论的,您可以填充错误消息列表,然后断言列表为空,当断言为假时显示每条消息.

As Jon Clements commented, you can fill a list of error messages and then assert the list is empty, displaying each message when the assertion is false.

具体来说,可能是这样的:

concretely, it could be something like that:

def test_something(self):
    errors = []

    # replace assertions by conditions
    if not condition_1:
        errors.append("an error message")
    if not condition_2:
        errors.append("an other error message")

    # assert no error message has been registered, else print messages
    assert not errors, "errors occured:\n{}".format("\n".join(errors))

原始断言被替换为 if 语句,如果条件不满足,这些语句会将消息附加到 errors 列表中.然后断言 errors 列表为空(空列表为 False)并使断言消息包含 errors 列表的每条消息.

The original assertions are replaced by if statements which append messages to an errors list in case condition are not met. Then you assert the errors list is empty (an empty list is False) and make the assertion message contains each message of the errors list.

您还可以按照 nose 文档中所述制作测试生成器.我没有找到任何描述它的 pytest 文档,但我知道 pytest 处理这个的方式与鼻子完全相同.

You could also make a test generator as described in the nose documentation. I did not find any pytest doc which describes it, but I know that pytest handled this exactly the same manner as nose.

这篇关于我可以在 pytest 中执行多个断言吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆