python doctest中的对象重用

前端之家收集整理的这篇文章主要介绍了python doctest中的对象重用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一个像这样的样本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'
原文链接:https://www.f2er.com/python/439402.html

猜你在找的Python相关文章