gpt4 book ai didi

python - Doctest 在 python3 中失败,但如果手动测试则可以工作

转载 作者:行者123 更新时间:2023-12-01 06:40:25 26 4
gpt4 key购买 nike

我刚刚开始学习Python,并且正在听我大学的一些在线讲座。我刚刚被介绍在脚本中编写文档测试。下面是我的代码:

 """ Our first python source file. """

from operator import floordiv, mod

def divide_exact(n,d):
""" Return the quotient and remainder.

>>> q, r = divide_exact(2013, 10)
>>> q
201
>>> r
3
"""
return floordiv(n, d), mod(n, d)

当我运行时

python3 -m doctest -v lec3video3

我通过了 0 个测试用例。我收到此错误

    File "lec3video3test", line 7, in lec3video3test
Failed example:
q, r = divide_exact(2013, 10)
Exception raised:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/doctest.py", line 1329, in __run
compileflags, 1), test.globs)
File "<doctest lec3video3test[0]>", line 1, in <module>
q, r = divide_exact(2013, 10)
NameError: name 'divide_exact' is not defined

我不知道为什么,因为我知道我的代码可以工作。我究竟做错了什么?我已经在交互模式下测试了我的代码,一切都是正确的。

最佳答案

当前版本的代码中存在IndentationError。但是,我想这只是复制和粘贴过程中发生的错误,因为您会收到完全不同的错误消息。

关于您描述的NameError:如果我输入您给定的代码

""" Our first python source file. """

from operator import floordiv, mod

def divide_exact(n,d):
""" Return the quotient and remainder.

>>> q, r = divide_exact(2013, 10)
>>> q
201
>>> r
3
"""
return floordiv(n, d), mod(n, d)

在文件 example.py 中并使用以下命令调用 doctest,我得到:

$ python3 -m doctest -v example.py
Trying:
q, r = divide_exact(2013, 10)
Expecting nothing
ok
Trying:
q
Expecting:
201
ok
Trying:
r
Expecting:
3
ok
1 items had no tests:
example
1 items passed all tests:
3 tests in example.divide_exact
3 tests in 2 items.
3 passed and 0 failed.
Test passed.

上面写着

1 items had no tests:
example

因为模块文档字符串中没有测试。除此之外,divide_exact 函数文档字符串中的所有三个测试都按预期通过。

因此,您只需确保您的文件位于正确的文件夹中,并且您的命令遵循 doctest 模块所需的语法。

关于python - Doctest 在 python3 中失败,但如果手动测试则可以工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59481827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com