How enable ellipsis when calling Python doctest?
Asked Answered
A

3

29

In Python (3.3.2) doctest, ellipsis (...) can match any string. So, for the code below

def foo():
    """
    >>> foo()
    hello ...
    """
    print("hello world")

when running doctest it shouldn't raise any error. But

$ python -m doctest foo.py 
**********************************************************************
File "./foo.py", line 3, in foo.foo
Failed example:
    foo()
Expected:
    hello ...
Got:
    hello world
**********************************************************************
1 items had failures:
   1 of   1 in foo.foo
***Test Failed*** 1 failures.

What I must do to enable the ellipis? As far as I can tell it is disable by default.

I know that add # doctest: +ELLIPSIS, as in the code below, solve it, but I like to enable ellipsis for all tests.

def foo():
    """
    >>> foo() # doctest: +ELLIPSIS
    hello ...
    """
    print("hello world")
Aultman answered 13/6, 2013 at 16:24 Comment(0)
A
30

You can pass in optionflags to the testmod method, but this requires you to run the module itself instead of the doctest module:

def foo():
    """
    >>> foo()
    hello ...
    """
    print("hello world")

if __name__ == "__main__":
    import doctest
    doctest.testmod(verbose=True, optionflags=doctest.ELLIPSIS)

Output:

$ python foo.py
Trying:
    foo()
Expecting:
    hello ...
ok
1 items had no tests:
    __main__
1 items passed all tests:
   1 tests in __main__.foo
1 tests in 2 items.
1 passed and 0 failed.
Test passed.
Amalgamation answered 13/6, 2013 at 17:3 Comment(0)
D
9

You can enable options for an individual example like this:

'''
>>> 'foobarbaz' # doctest: +ELLIPSIS
'foo...baz'
'''

The doctest directives documentation is hard to understand because the actual directives seem to be parsed away and aren't visible. There is an open bug report for this. In the meantime you can view the raw documentation source instead.

Doane answered 6/8, 2020 at 8:43 Comment(1)
This answer is a life saver since it doesn't change global behaviour and doesn't need additional setup code in your doctest call.Snort
R
6

Since Python 3.4, you can pass the option with the -o flag:

$ python -m doctest -o=ELLIPSIS foo.py

Source: https://docs.python.org/3/library/doctest.html#option-flags

Richel answered 1/6, 2020 at 21:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.