简体   繁体   English

执行Python doctest代码

[英]Executing Python doctest code

I have simple Python code that uses dockets 我有使用坞站的简单Python代码

#!/usr/bin/python
# http://stackoverflow.com/questions/2708178/python-using-doctests-for-classes

class Test:
    def __init__(self, number):
        self._number=number

    def multiply_by_2(self):
        """
        >>> t.multiply_by_2()
        4
        """
        return self._number*2

if __name__ == "__main__":
    import doctest
    doctest.testmod(extraglobs={'t': Test(2)})

I can use it with python interpreter: 我可以将其与python解释器一起使用:

> python simple.py

However, when I execute the code from doctest module, I get this error: 但是,当我从doctest模块执行代码时,出现此错误:

> python -m doctest simple.py
**********************************************************************
File "simple.py", line 10, in simple.Test.multiply_by_2
Failed example:
    t.multiply_by_2()
Exception raised:
    Traceback (most recent call last):
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/doctest.py", line 1289, in __run
        compileflags, 1) in test.globs
      File "<doctest simple.Test.multiply_by_2[0]>", line 1, in <module>
        t.multiply_by_2()
    NameError: name 't' is not defined
**********************************************************************
1 items had failures:
   1 of   1 in simple.Test.multiply_by_2
***Test Failed*** 1 failures.

Why is this difference? 为什么会有这种差异? How to resolve this issue? 如何解决这个问题?

The difference is that when you execute via doctest , it is the __main__ module compared to executing directly where your script's if __name__ == '__main__' block will execute. 区别在于,当您通过doctest执行时,它是__main__模块,与直接执行脚本的位置( if __name__ == '__main__'块将直接执行脚本)相比。

I don't know of a good solution other than to put all the information you need in the docstring itself: 除了将您需要的所有信息放入文档字符串本身之外,我不知道有什么好的解决方案:

def multiply_by_2(self):
    """
    >>> t = Test(2)
    >>> t.multiply_by_2()
    4
    """
    return self._number * 2

This will have the added benefit that users who are reading your docstrings will know what's going on ... They won't have to stumble upon your extraglobs keyword to figure out what t is and how it was initialized. 这将带来额外的好处,即正在阅读您的文档字符串的用户将知道正在发生的事情……他们不必偶然发现您的extraglobs关键字即可确定t是什么以及如何对其进行初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM