为什么doctest在使用tesfile执行时找不到在同一文件上定义的函数?

2024-09-26 22:46:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包mypackage,其中我有foo.py

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

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

def bar():
    return "bar"

如果我运行python -m doctest mypackage/foo.py,它就像一个符咒,但是。如果我创建一个带有

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

。。。在与mypackage相同的文件夹中,并运行此文件,它将失败

**********************************************************************
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 

我的问题是为什么,以及如何解决


Tags: inpyfooexampledeflinebarusers
1条回答
网友
1楼 · 发布于 2024-09-26 22:46:00

只需确保在运行doctest时导入bar。例如,在同一个目录中,我有example.txtfoo.py

# example.txt
>>> from foo import bar

>>> 1
1

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

现在python解释器将显示0条失败的测试行

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

但是,如果省略>>> from foo import bar行,将出现以下错误

>>> 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)

相关问题 更多 >

    热门问题