pro*_*eek 7 python doctest unit-testing
我有一个像这样的样本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()
Run Code Online (Sandbox Code Playgroud)
当我执行此代码时,我收到此错误.
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 "<doctest __main__.iniFileGenerator.hello[0]>", line 1, in <module>
f.hello()
NameError: name 'f' is not defined
Run Code Online (Sandbox Code Playgroud)
此错误是由访问测试hello()方法时无法访问的"f"引起的.
有没有办法分享之前创建的对象?没有它,人们需要在必要时始终创建对象.
def hello(self):
"""
hintFile = "./tests/unit_test_files/hint.txt"
>>> f = iniFileGenerator(hintFile)
>>> f.hello()
hello
"""
print "hello"
Run Code Online (Sandbox Code Playgroud)
您可以用来testmod(extraglobs={'f': initFileGenerator('')})全局定义可重用对象。
正如doctest博士所说,
extraglobs给出了一个dict,它被合并到用于执行示例的全局变量中。这就像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'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1024 次 |
| 最近记录: |