print success messages for asserts in python
Solution 1
Yes, the simplest is surely to place a print below the assert:
assert self.clnt.stop_io()==1, "IO stop failed"
print("IO stop passed at location ==1")
Solution 2
Write a simple helper function:
def myfunc(msg='assert OK'):
print msg
return True
Include that in the condition on the right-side, after an and
:
assert self.clnt.stop_io()==1 and myfunc("IO stop succeeded"), "IO stop failed"
Solution 3
This has been added to the pytest module v5 as the hook pytest_assertion_pass
in your conftest.py
def pytest_assertion_pass(item, lineno, orig, expl):
log.info("asserting that {}, {}, {}, {}".format(item, lineno, orig, expl))
and in pytest.ini
enable_assertion_pass_hook = true
Solution 4
If you are really feeling adventurous, you can just write your own extensible assert wrapper - with which you can count the number of asserts failed or add functionality like testing in quiet or verbose modes eg:
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
Solution 5
I would combine @dashingdw and @Reblochon Masque solution
def my_assert(condition, fail_str, suc_str):
assert condition, fail_str
print suc_str
From my point of view this is less "dangerous" and you don't need to insert an additional print
line every time.
cool77
Updated on June 22, 2022Comments
-
cool77 almost 2 years
I am using assert in python. Every time an assert fails I get the failure message which I would have put there to be printed. I was wondering if there is a way to print a custom success message when the assert condition passes?
I am using py.test framework.
for instance:
assert self.clnt.stop_io()==1, "IO stop failed"
for the above assert I get message "IO stop failed" if assert fails but I am looking to have "IO stop succeeded" if assert passes. something like this:
assert self.clnt.stop_io()==1, "IO stop failed", "IO stop succeeded"
-
cool77 almost 8 yearsthat's right. i thought about this one. the real worry is the internal framework that we have is designed in such a way as to ignore certain tests (asserts) in some scenarios and continue further. and in those scenarios, would this not be a false message which would get printed no matter assert passed or failed?
-
Reblochon Masque almost 8 yearsYes, if somehow the assert is ignored, the following instruction will be executed, giving you a wrong feedback. You need to tell us how the asserts are skipped here.
-
Rilwan over 3 yearswithout extra function, but ugly:
assert self.clnt.stop_io()==1 and not print("IO stop succeeded"), "IO stop failed"