Assuming a python file with a whole bunch of functions I want to write tests for the functions using doctest
. For example every function takes a string and a connection object (httplib.HTTPConnection(...)
). So I want to test every function if the string is empty or None
. The tests would look like this.
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
As you can see, the test are identical, only the function name changes. Is it possible to refactor that to avoid code repetition?
Or is there a better way to lump together such tests?
Never used doctest.
def genDocText(func_name):
return r'''
>>> conn = httplib.HTTPConnection(...)
>>> %(func_name)s(None, conn)
Traceback (most recent call last):
NoneAsInputError: `mystring` should be a string and not `None`!
>>> %(func_name)s("", conn)
Traceback (most recent call last):
EmptyStringError: `mystring` should not be an empty string!
''' % {'func_name': func_name}
def function_1(mystring, conn):
pass
function_1.__doc__ = genDocText('function_1')
Is this a bad way?
UPDATE: Using decorators the solution above can be written as:
def genDocText(func):
func.__doc__ = r'''
>>> conn = httplib.HTTPConnection(...)
>>> %(func_name)s(None, conn)
Traceback (most recent call last):
NoneAsInputError: `mystring` should be a string and not `None`!
>>> %(func_name)s("", conn)
Traceback (most recent call last):
EmptyStringError: `mystring` should not be an empty string!
''' % {'func_name': func.__name__}
return func
@genDocText
def function_1(mystring, conn):
pass
@genDocText
def function_2(mystring, conn):
pass
@genDocText
def function_n(mystring, conn):
pass
if __name__ == '__main__':
print function_1.__doc__
print function_2.__doc__
print function_n.__doc__