加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python doctest中的对象重用

发布时间:2020-12-16 21:58:49 所属栏目:Python 来源:网络整理
导读:我有一个像这样的样本doctest. """This is the "iniFileGenerator" module. hintFile = "./tests/unit_test_files/hint.txt" f = iniFileGenerator(hintFile) print f.hintFilePath./tests/unit_test_files/hint.txt"""class iniFileGenerator: def __init__

我有一个像这样的样本doctest.

"""
This is the "iniFileGenerator" module.
>>> hintFile = "./tests/unit_test_files/hint.txt"
>>> f = iniFileGenerator(hintFile)
>>> print f.hintFilePath
./tests/unit_test_files/hint.txt
"""
class iniFileGenerator:
    def __init__(self,hintFilePath):
        self.hintFilePath = hintFilePath
    def hello(self):
        """
        >>> f.hello()
        hello
        """
        print "hello"
if __name__ == "__main__":
    import doctest
    doctest.testmod()

当我执行此代码时,我收到此错误.

Failed example:
    f.hello()
Exception raised:
    Traceback (most recent call last):
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/doctest.py",line 1254,in __run
        compileflags,1) in test.globs
      File "

此错误是由访问测试hello()方法时无法访问的’f’引起的.

有没有办法分享之前创建的对象?没有它,人们需要在必要时始终创建对象.

def hello(self):
    """
    hintFile = "./tests/unit_test_files/hint.txt"
    >>> f = iniFileGenerator(hintFile)
    >>> f.hello()
    hello
    """
    print "hello"
最佳答案
您可以使用testmod(extraglobs = {‘f’:initFileGenerator(”)})来全局定义可重用对象.

正如doctest doc所说,

extraglobs gives a dict merged into the globals used to execute examples. This works like dict.update()

但我曾经在所有方法之前测试类的__doc__中的所有方法.

class MyClass(object):
    """MyClass
    >>> m = MyClass()
    >>> m.hello()
    hello
    >>> m.world()
    world
    """

    def hello(self):
        """method hello"""
        print 'hello'

    def world(self):
        """method world"""
        print 'world'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读