Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

py.test: format failed assert AND print custom message

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?

like image 460
Bluu Avatar asked Oct 11 '13 01:10

Bluu


People also ask

How do you fix an assertion error in Python?

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.

What happens when Python assert fails?

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.

What does assert mean in pytest?

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.


1 Answers

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.

like image 88
hpk42 Avatar answered Sep 27 '22 20:09

hpk42