Why doctest can't find functions defined on the same file when executed with tesfile?

Viewed 285

I have a package mypackage where I have foo.py

# mypackage/foo.py
def foo():
    """
    >>> 1
    1

    >>> bar()
    'bar'
    """
    pass

def bar():
    return "bar"

If I run python -m doctest mypackage/foo.py it works like a charm, but. If I create a test file with ...

import doctest 
doctest.testfile("foo.py", package="mypackage")

... in the same folder as mypackage, and run this file, it fails with

**********************************************************************
File "/Users/gecko/code/python/doctesttest/mypackage/foo.py", line 6, in foo.py
Failed example:
    bar()
Exception raised:
    Traceback (most recent call last):
      File "/Users/gecko/.pyenv/versions/3.8.2/lib/python3.8/doctest.py", line 1329, in __run
        exec(compile(example.source, filename, "single",
      File "<doctest foo.py[1]>", line 1, in <module>
        bar()
    NameError: name 'bar' is not defined
**********************************************************************
1 items had failures:
   1 of   2 in foo.py
***Test Failed*** 1 failures.
āžœ  doctesttest 

My question is why, and how to fix it?

1 Answers

Just make sure to import bar when running doctest. For example, in the same directory I have example.txt and foo.py

# example.txt
>>> from foo import bar

>>> 1
1

>>> bar()
'bar'
# foo.py
def bar():
    return "bar"

now the python interpreter will show 0 failed tested lines.

import doctest
doctest.testfile('example.txt')
>>> TestResults(failed=0, attempted=3)

However, if I omit the line >>> from foo import bar, I'll get the following error

>>> doctest.testfile('example.txt')
**********************************************************************
File "./example.txt", line 6, in example.txt
Failed example:
    bar()
Exception raised:
    Traceback (most recent call last):
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/doctest.py", line 1329, in __run
        exec(compile(example.source, filename, "single",
      File "<doctest example.txt[1]>", line 1, in <module>
        bar()
    NameError: name 'bar' is not defined
**********************************************************************
1 items had failures:
   1 of   2 in example.txt
***Test Failed*** 1 failures.
TestResults(failed=1, attempted=2)
Related