For the string variable a, the only solution is global a. If you look at the Python 2 and Python 3 source code, setupModule() doesn't appear to do anything magical, so all the usual namespace rules apply.
If a were a mutable variable, like a list, you could define it at global scope and then append to it within setupModule.
Variable b is easier to work with because it is defined within a class. Try this:
@classmethod
def setUpClass(cls):
cls.b = "Setup Class variable"
def test_1(self):
print self.b
Answer from nofinator on Stack OverflowThe difference manifests itself when you have more than one test method in your class. setUpClass and tearDownClass are run once for the whole class; setUp and tearDown are run before and after each test method.
For example:
class Example(unittest.TestCase):
@classmethod
def setUpClass(cls):
print("setUpClass")
def setUp(self):
print("setUp")
def test1(self):
print("test1")
def test2(self):
print("test2")
def tearDown(self):
print("tearDown")
@classmethod
def tearDownClass(cls):
print("tearDownClass")
When you run this test, it prints:
setUpClass
setUp
test1
tearDown
.setUp
test2
tearDown
.tearDownClass
(The dots (.) are unittest's default output when a test passes.) Observe that setUp and tearDown appear before and after test1 and test2, whereas setUpClass and tearDownClass appear only once, at the beginning and end of the whole test case.
What is the difference between setUp() and setUpClass() in the Python unittest framework?
The main difference (as noted in the answer by Benjamin Hodgson) is that setUpClass is called only once and that is before all the tests, while setUp is called immediately before each and every test. (NB: The same applies to the equivalent methods in other xUnit test frameworks, not just Python's unittest.)
From the unittest documentation:
setUpClass()A class method called before tests in an individual class are run. setUpClass is called with the class as the only argument and must be decorated as a classmethod():
@classmethod
def setUpClass(cls):
...
and:
setUp()Method called to prepare the test fixture. This is called immediately before calling the test method; other than AssertionError or SkipTest, any exception raised by this method will be considered an error rather than a test failure. The default implementation does nothing.
Why would setup be handled in one method over the other?
This part of the question has not been answered yet. As per my comment in response to the answer by Gearon, the setUp method is meant for elements of the fixture that are common to all tests (to avoid duplicating that code in each test). I find this is often useful as removing duplication (usually) improves readability and reduces the maintenance burden.
The setUpClass method is for expensive elements that you would rather only have to do once, such as opening a database connection, opening a temporary file on the filesystem, loading a shared library for testing, etc. Doing such things before each test would slow down the test suite too much, so we just do it once before all the tests. This is a slight degradation in the independence of the tests but a necessary optimization in some situations. Arguably, one should not be doing such things in unit tests as it is usually possible to mock the database / filesystem / library / whatever without using the real thing. As such, I find that setUpClass is rarely needed. However, it is useful when testing the above examples (or similar) becomes necessary.
As some comments have echoed, structuring your tests in this manner is probably a design flaw in the tests themselves and you should consider restructuring them. However, if you want to do this and rely on the fact that the test runner you are using executes them in an alphabetical (seemingly) order then I suggest the following.
Similar to what @Matthias was saying but I would do one thing differently for the cases where you may decide to inherit from the class at a later date.
from unittest import TestCase, main as unittest_main
class TestSimpleFoo(TestCase):
foo = 'bar'
def setUp(self):
pass
def test_a(self):
self.assertEqual(self.__class__.foo, 'bar')
self.__class__.foo = 'can'
def test_f(self):
self.assertEqual(self.__class__.foo, 'can')
if __name__ == '__main__':
unittest_main()
The difference between this answer and @Matthias's answer you accepted is the explicit declaration of the class versus the lookup of said class reference.
TestSimpleFoo vs self.__class__
I prefer the dynamicness so I can inherit the tests later and run both test classes back to back and not have any cross over between the two. Because if you would choose to inherit from this class, explicitly naming the class reference would cause both test classes to run against that reference rather than their own respective classes.
I like your own answer for the simplicity of it, but if you want to keep distinct unit tests:
Apparently unittest runs separate tests with fresh instances of the TestCase. Well, just bind the objects to be persisted to something else but self. For example:
from unittest import TestCase, main as unittest_main
class TestSimpleFoo(TestCase):
def setUp(self):
pass
def test_a(self):
TestSimpleFoo.foo = 'can'
def test_f(self):
self.assertEqual(TestSimpleFoo.foo, 'can')
if __name__ == '__main__':
unittest_main()
You might be interesed in setUpClass and tearDownClass too: https://docs.python.org/3/library/unittest.html#setupclass-and-teardownclass
Also take care about the execution order of your unit tests: https://docs.python.org/2/library/unittest.html#unittest.TestLoader.sortTestMethodsUsing
As of 2.7 (per the documentation) you get setUpClass and tearDownClass which execute before and after the tests in a given class are run, respectively. Alternatively, if you have a group of them in one file, you can use setUpModule and tearDownModule (documentation).
EDIT: Note that setUpClass and tearDownClass must be declared using @classmethod. Another answer to this question includes sample code.
Otherwise your best bet is probably going to be to create your own derived TestSuite and override run(). All other calls would be handled by the parent, and run would call your setup and teardown code around a call up to the parent's run method.
I have the same scenario, for me setUpClass and tearDownClass methods works perfectly
import unittest
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls._connection = createExpensiveConnectionObject()
@classmethod
def tearDownClass(cls):
cls._connection.destroy()
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.
Note my destinction between setup and Setup below: Each test has to so some setup activities, but these are not necessarily put into the Setup method.
My preference is that each test function should be easily understood by itself. I don't want to look at test code wondering "where does this value suddenly come from" or the like. Which means, I avoid a common Setup method but instead use helper functions / methods that also have descriptive names. To be more precise:
- If a test case needs a specific setup, I normally embed it directly into the test.
- If a subset of the test cases have an identical or similar setup, I consider creating a helper method to extract the common parts. The name of that helper method should be descriptive, like
makeTrafficLightInGreenStatefor a helper factory to produce a specific type of traffic light object. In this example I could then also havemakeTrafficLightInRedStatefor a different group of tests. I find this preferrable over a commonSetupmethod which just creates both the green and the red traffic light: In the end you get confused which part ofSetupis relevant for which test. Certainly, when writing your helper methods, you are also free to give them parameters, which could in the traffic light example result in 'makeTrafficLightInState(green)'. But, which approach to choose here is situation specific. - Even if all tests have something in common, like the creation of a certain object, I prefer putting this in a descriptively named helper method rather than relying on the implicit call to
Setup. - Sometimes I also use
Setup, but only for activities that are not necessary for understanding the logic of the test cases. For example, if there is some original state that needs to be preserved at the beginning of the test cases and to be restored afterwards, this could be put intoSetupwithout any negative impact on the readability of the individual test cases.
In your case, you seem to already have a function with parameters that is suited to deliver test case specific data. I would simply call that function from each test case that needs it. Or, if calling that function is not simple (you have to create additional objects as arguments for it or the like), again put it into a helper method.