在python中打印断言的成功消息

时间:2016-04-25 07:45:09

标签: python unit-testing pytest assertions

我在python中使用assert。 每次断言失败时,我都会得到失败的消息,我会把它放在那里打印。但我想知道在断言条件通过时是否有任何方法可以打印自定义成功消息? 我正在使用py.test框架。

示例:

assert self.clnt.stop_io()==1, "IO stop failed"

对于上述断言我得到消息" IO停止失败"如果断言失败但我希望" IO停止成功"如果断言通过。

之类的东西
 assert self.clnt.stop_io()==1, "IO stop failed", "IO stop succeeded"

5 个答案:

答案 0 :(得分:6)

是的,最简单的肯定是在断言下方放置一个印刷品:

assert self.clnt.stop_io()==1, "IO stop failed"
print("IO stop passed at location ==1")

答案 1 :(得分:2)

如果您真的喜欢冒险,那么您可以编写自己的可扩展断言包装器 - 您可以使用它来计算失败的断言数或添加安静或详细模式下的测试等功能 例如:

def assert(condition, fail_str, suc_str):
     if condition:
          print fail_str
     else:
          num_tests_passed = num_tests_passed + 1
          if verbose_enabled:
              print suc_str

答案 2 :(得分:2)

编写一个简单的辅助函数:

def myfunc(msg='assert OK'):
    print msg
    return True

and之后的<{1}}

之后包括在右侧的条件中
assert self.clnt.stop_io()==1 and myfunc("IO stop succeeded"), "IO stop failed"

答案 3 :(得分:1)

我会结合@dashingdw和@Reblochon Masque解决方案

print

从我的观点来看,这不那么“危险”,而且您不需要每次都插入额外的var myButton = $(this).parents('tr').find('input[type=button]'); // accesing the button in a function 行。

答案 4 :(得分:1)

它已作为钩子pytest_assertion_pass

添加到pytest模块中。

在您的conftest.py

def pytest_assertion_pass(item, lineno, orig, expl):
log.info("asserting that {}, {}, {}, {}".format(item, lineno, orig, expl))

和pytest.ini

enable_assertion_pass_hook = true