py.test: format failed assert AND print custom message
Asked Answered
R

3

13

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?

Reams answered 11/10, 2013 at 1:17 Comment(0)
M
4

The message can be formatted:

assert  a % 2 == 0, f"a was {a}, was odd, should be even"
Megen answered 20/9, 2021 at 15:23 Comment(0)
A
1

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.

Abstract answered 13/10, 2013 at 14:32 Comment(3)
"you can probably also put in some interesting values from the expression" - definitely, but at the cost of repeating myself, and I don't get the nice formatting. Anyway, I will follow up on the project's BitBucket.Reams
I didn't see any discussion of this on the bitbucket page for py.test. Was adding this ever discussed?Monoceros
@Monoceros no, it fell off my radar, as I settled for repeating myself (and slightly less expressive output).Reams
F
1

Add the next additional flag to the run configuration Additional Arguments: --tb=short

You can edit the configuration templates to make it the default.

More info can be found here: https://youtrack.jetbrains.com/issue/PY-49150/pytest-output-in-PyCharm-lacks-information-about-assertion-failures-in-helper-methods

enter image description here

Fulgurous answered 10/6 at 12:35 Comment(1)
Weird that the message is only included in the short version, you'd think the long version would have all the info.Verdun

© 2022 - 2024 — McMap. All rights reserved.