The py.test assert docs say
... if you specify a message with the assertion like this:
assert a % 2 == 0, "value was odd, should be even"
then no assertion introspection takes places at all and the message will be simply shown in the traceback.
Python's builtin unittest
module does this too, unless your TestCase
sets longMessage = True
.
Having the nice assert formatting is test developer friendly, while the custom message is more business-requirement / human friendly. The custom message is especially helpful when you're not in the context of the test, i.e. it answers what that assert is doing there, without having to look at the code. So, I'd like to have both messages.
Is there any way to get py.test's nice assert introspection and formatting AND print a custom message?
If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback.
If an assertion fails, then your program should crash because a condition that was supposed to be true became false. You shouldn't change this intended behavior by catching the exception with a try … except block. A proper use of assertions is to inform developers about unrecoverable errors in a program.
Definition and Usage The assert keyword is used when debugging code. The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError.
There isn't a way to enable assertion extra info plus a message currently. I think it could be added but not sure how much effort is needed. So far this issue hasn't come to my knowledge. Feel free to file an issue or try a pull request. Note, however, that if you go through the effort of writing a custom human-readable message, you can probably also put in some interesting values from the expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With