I've been using doctest for a while now, and I like it most of the time. It's annoying when I expect a number that has to fall within a certain range or a string that has to meet certain conditions. In this case, the recommended approach seems to be to encode the condition as a logical operator returning True
or False
, e.g.,
"""
>>> from math import pi
>>> 3.14 < pi < 3.15
True
"""
But this approach leads to a lot of True
lines in my doctests. And if a test fails, I get a message that says something like, "Expected True; got False."
But I just discovered that I can use assert
to accomplish the same thing:
"""
>>> from math import pi
>>> assert 3.14 < pi < 3.15
"""
The input is more compact. And this way, if the assertion fails, doctest
says, "Expected nothing; got AssertionError..." followed by the offending assert
statement, which is more readable. Is there any reason not to do this?
It really depends on the kind of feedback you want to receive from doctorest
using assert in your test is a more compact approach. It works by ensuring that if the condition fails, Python raises an assertionerror. On the other hand, encoding your condition as a logical operator returning true or false will result in lines like true/ false in the output which might be less informative when the condition fails.
There’s no major reason not to use ASSERT as long as youre comfortable with the exception based error reporting and want a more compact test.