我有一个像这样的样本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()
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'