Skip to content

doctest expecting asserts behaves differently than stdlib #12417

Description

@isidroas

The following file,

import math

def square_root(n):
    """
    >>> square_root(4)
    2.0

    >>> square_root(-1)
    Traceback (most recent call last):
        ...
    AssertionError: number must not be negative

    """
    assert n>= 0, 'number must not be negative'
    return math.sqrt(n)

works well with the doctest of stdlib,

$ python -m doctest test.py

$ echo $?
0

but it fails using pytest:

$ python -m doctest test.py
$ pytest --doctest-modules test.py
============================= test session starts ==============================
platform linux -- Python 3.11.6, pytest-8.2.1, pluggy-1.5.0
rootdir: /tmp
collected 1 item

test.py F                                                                [100%]

=================================== FAILURES ===================================
__________________________ [doctest] test.square_root __________________________
004 
005     >>> square_root(4)
006     2.0
007 
008     >>> square_root(-1)
Differences (unified diff with -expected +actual):
    @@ -1,3 +1,9 @@
     Traceback (most recent call last):
    -    ...
    +  File "/usr/lib/python3.11/doctest.py", line 1351, in __run
    +    exec(compile(example.source, filename, "single",
    +  File "<doctest test.square_root[1]>", line 1, in <module>
    +    square_root(-1)
    +  File "/tmp/test.py", line 14, in square_root
    +    assert n>= 0, 'number must not be negative'
     AssertionError: number must not be negative
    +assert -1 >= 0

/tmp/test.py:8: DocTestFailure
=========================== short test summary info ============================
FAILED test.py::test.square_root
============================== 1 failed in 0.01s ===============================

due to that assert -1 >= 0 extra line

Activity

  1. shannoncai commented on Dec 5, 2024

    @shannoncai

    I can take a look into this issue! I'll create a pull request soon but let me know if there's anything else.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    plugin: doctestsrelated to the doctests builtin plugin

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions