I follow the general strategy of, if a variable will be used in multiple test functions, I define it in the setUp(). If it will only be used once local to a specific function, define it in that function.
Take the following example:
Say I have a python module in package program called list_utils.py and in list_utils.py I have the following functions:
def list_to_string(mylist):
""" Takes a list of strings and joins them into a single string.
"""
return ' '.join(mylist)
def list_extender(mylist, extend_item):
return mylist.extend(extend_item)
Then I setup my unittest script with specifying mytestlist because it will be used in multiple test functions:
from program import list_utils as lu
class TestListUtils(unittest.TestCase):
"""
A subclass of unittest to test list_utils.py
"""
def setUp(self):
self.mytestlist = ['Hi', 'there']
def test_list_to_string(self):
"""
Ensures my list is converted to string
"""
self.assertTrue(isinstance(lu.list_to_string(self.mytestlist), string))
def test_list_extender(self):
"""
Ensures list is extended when argument is passed.
"""
mylocalvariable = 'Adam'
self.assertTrue(lu.list_extender(self.mytestlist, mylocalvariable)[-1] == 'Adam')
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
You see that for list_extender I passed in mylocalvariable because I would only use it in the scope of that function, but mytestlist was defined in setUp because I used it multiple times. By following this general approach, you shouldn't bloat your setUp too much, and you also won't have to re-instantiate variables at each specific unittest if they will be used multiple times.
setUpand global, class or instance variables are relevant here.setUpreturnsNone, but I need a setup function that returns a value. The problem is whether to not usesetUpat all and make your own setup function and call it in every test method or usesetUpbut set some global variables in it.