python3的doctest失败,但手动测试可以正常工作

2024-05-14 07:45:00 发布

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

我刚刚开始学习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

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


Tags: 代码in脚本modlineourdoctestexact
1条回答
网友
1楼 · 发布于 2024-05-14 07:45:00

当前版本的代码中有一个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

因为模块docstring中没有测试。除此之外,divide_exact函数docstring中的所有三个测试都按预期通过。你知道吗

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

相关问题 更多 >

    热门问题