1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Python: using doctest with assert

Discussão em 'Python' iniciado por Stack, Abril 21, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página