假设一个包含一大堆函数的 python 文件,我想使用doctest
. 例如,每个函数都接受一个字符串和一个连接对象 ( httplib.HTTPConnection(...)
)。因此,如果字符串为空或None
. 测试看起来像这样。
def function_1(mystring, conn):
r'''
>>> conn = httplib.HTTPConnection(...)
>>> function_1(None, conn)
Traceback (most recent call last):
NoneAsInputError: `mystring` should be a string and not `None`!
>>> function_1("", conn)
Traceback (most recent call last):
EmptyStringError: `mystring` should not be an empty string!
'''
pass
def function_2(mystring, conn):
r'''
>>> conn = httplib.HTTPConnection(...)
>>> function_2(None, conn)
Traceback (most recent call last):
NoneAsInputError: `mystring` should be a string and not `None`!
>>> function_2("", conn)
Traceback (most recent call last):
EmptyStringError: `mystring` should not be an empty string!
'''
pass
[...]
def function_n(mystring, conn):
r'''
>>> conn = httplib.HTTPConnection(...)
>>> function_n(None, conn)
Traceback (most recent call last):
NoneAsInputError: `mystring` should be a string and not `None`!
>>> function_n("", conn)
Traceback (most recent call last):
EmptyStringError: `mystring` should not be an empty string!
'''
pass
如您所见,测试是相同的,只是函数名称发生了变化。是否可以对其进行重构以避免代码重复?
或者有没有更好的方法将这些测试集中在一起?