coo*_*l77 2 python unit-testing pytest assertion
我在python中使用assert.每次断言失败时,我都会得到失败的消息,我会把它放在那里打印.但我想知道在断言条件通过时是否有任何方法可以打印自定义成功消息?我正在使用py.test框架.
例:
assert self.clnt.stop_io()==1, "IO stop failed"
Run Code Online (Sandbox Code Playgroud)
对于上面的断言,如果断言失败,我得到消息"IO stop failed"但是如果assert通过,我希望"IO stop succeeded".就像是
assert self.clnt.stop_io()==1, "IO stop failed", "IO stop succeeded"
Run Code Online (Sandbox Code Playgroud)
是的,最简单的肯定是在断言下面放置一个打印:
assert self.clnt.stop_io()==1, "IO stop failed"
print("IO stop passed at location ==1")
Run Code Online (Sandbox Code Playgroud)
编写一个简单的辅助函数:
def myfunc(msg='assert OK'):
print msg
return True
Run Code Online (Sandbox Code Playgroud)
将其包含在右侧的条件中,在 之后and:
assert self.clnt.stop_io()==1 and myfunc("IO stop succeeded"), "IO stop failed"
Run Code Online (Sandbox Code Playgroud)
这已作为钩子pytest_assertion_pass添加到 pytest 模块 v5
在你的 conftest.py
def pytest_assertion_pass(item, lineno, orig, expl):
log.info("asserting that {}, {}, {}, {}".format(item, lineno, orig, expl))
Run Code Online (Sandbox Code Playgroud)
并在 pytest.ini
enable_assertion_pass_hook = true
Run Code Online (Sandbox Code Playgroud)