16.2.5 测试位置
目前为止的例子中,所有测试都写在所测试的函数的docstring中。对于查看docstring的用户来说这很方便,可以帮助他们使用这个函数(特别是对于pydoc),不过doctest还会在其他地方查找测试。最可能完成测试的地方就是在模块中其他位置找到的docstring.
"""Tests can appear in any docstring within the module.
Module-level tests cross class and function boundaries.
>>> A('a') == B('b')
False
"""
class A:
"""Simple class.
>>> A('instance_name').name
'instance_name'
"""
def __init__(self,name):
self.name = name
def method(self):
"""Returns an unusual value.
>>> A('name').method()
'eman'
"""
return ''.join(reversed(self.name))
class B(A):
"""Another simple class.
>>> B('different_name').name
'different_name'
"""
模块级、类级和函数级的docstring都可以包含测试。
有些情况下,模块的测试应当包含在源代码中,而不是放在模块的帮助文本中。在这种情况下,需要把测试放在docstring以外的位置。doctest海湖i擦孩子一个模块级变量,名为__test__,用它来找到其他测试。__test__的值应当是一个字典,将测试集合名(字符串)映射为字符串、模块、类或函数。
import doctest_private_tests_external
__test__ = {
'numbers':"""
>>> my_function(2,3)
6
>>> my_function(2.0,3)
6.0
""",
'strings':"""
>>> my_function('a',3)
'aaa'
>>> my_function(3,'a')
'aaa'
""",
'external': doctest_private_tests_external,
}
def my_function(a,b):
"""Returns a * b
"""
return a * b
如果与一个键关联的值是字符串,那么其会被处理为一个docstring,并在其中扫描测试。如果值是一个类或函数,则doctest会递归地搜索docstring,然后在其中扫描测试。在下面这个例子中,模块doctest_private_tests_external的docstring内有一个测试。
"""External tests associated with doctest_private_tests.py.
>>> my_function(['A','B','C'],2)
['A','B','C','A','B','C']
"""
扫描示例文件之后,doctest总共找到了5个要运行的测试。