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.
Is this a bad way?
UPDATE:
Using decorators the solution above can be written as: