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 Overflow
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ unittest.html
unittest โ€” Unit testing framework
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:
๐ŸŒ
CSDN
devpress.csdn.net โ€บ python โ€บ 62fd94917e66823466192947.html
Python unitest - Use variables defined in module and class level setup functions, in tests_python_Mangs-Python
I am doing Python unit testing using nosetests to experiment with Python class and module fixtures, to have minimal setup across my tests. The problem is I am not sure how to use any variables defined in the setupUpModule and the setUpClass functions in my tests (example: test_1). ... import unittest def setUpModule(): a = "Setup Module variable" print "Setup Module" def tearDownModule(): print "Closing Module" class TrialTest(unittest.TestCase): @classmethod def setUpClass(cls): print a #<====== b = "Setup Class variable" @classmethod def tearDownClass(cls): print "Closing Setup Class" def test_1(self): print "in test 1" print a #<====== print b #<====== def test_2(self): print "in test 2" def test_3(self): print "in test 3" def test_4(self): print "in test 4" def test_5(self): print "in test 5" if __name__ == "__main__": unittest.main()
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 39988152 โ€บ using-variable-inside-setupclass-class-method-unittest-python
Using variable inside setUpClass (class method) - unittest python - Stack Overflow
I would like to use a variable which I initialize in the subclass to be used in the setUpClass of parent class , here is the code snippet below: class BaseTest(unittest.TestCase): def __init__(cls, arg): unittest.TestCase.__init__(cls, arg) @classmethod def setUpClass(cls): print "Base.setUp()" ,cls.param @classmethod def tearDownClass(cls): print "Base.tearDown()" class TestSomething(BaseTest): def __init__(cls, arg): BaseTest.__init__(cls, arg) cls.param = 'hello' def test_silly(self): print "Test method" self.assertTrue(1+1 == 2) def test_silly1(self): print "Test method" self.assertTrue(1+1 == 2)
๐ŸŒ
GitHub
github.com โ€บ python โ€บ mypy โ€บ issues โ€บ 8723
Support adding class variables to class through assignment ยท Issue #8723 ยท python/mypy
April 25, 2020 - Support adding class variables to class through assignment#8723 ยท Copy link ยท Labels ยท featurepriority-2-low ยท PeterJCLaw ยท opened ยท on Apr 25, 2020 ยท Issue body actions ยท Mypy supports adding items to self during test setUp, which is great. However in many cases it's useful to be able to add items to the class during setUpClass (or Django's setUpTestData). import unittest class Tests(unittest.TestCase): @classmethod def setUpClass(cls) -> None: cls.foo = 42 # "Type[Tests]" has no attribute "foo" def test_foo(self) -> None: print(self.foo) # "Tests" has no attribute "foo" Adding a ClassVar allows for a workaround to this, however it would be nice if that wasn't needed.
Author: python
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-to-write-unit-tests-for-instance-methods-in-python
How to Write Unit Tests for Instance Methods in Python
January 31, 2023 - Letโ€™s add the setUpClass() and tearDownClass() class methods to the TestBook class. from book import Book import unittest class TestBook(unittest.TestCase): @classmethod def setUpClass(cls): print("\nsetUpClass method: Runs before all tests...") def setUp(self): print("\nRunning setUp method...") self.book_1 = Book('Deep Work','Cal Newport',304,15,0.05) self.book_2 = Book('Grit','Angela Duckworth',447,16,0.15) def tearDown(self): print("Running tearDown method...") def test_reading_time(self): print("Running test_reading_time...") self.assertEqual(self.book_1.get_reading_time(), f"{304*1.5}
๐ŸŒ
Medium
medium.com โ€บ @urkude.nikesh โ€บ python-basic-unittest-example-b72b4c9d89cf
Python basic unittest example. Python Unit Test | by Nikesh Urkude | Medium
September 25, 2020 - In the below example for tearDown(self) the method, which show's how data erased from variable a and b ยท def tearDown(self): self.calc.first = 0 self.calc.second = 0 ยท Find below complete example for unittest with python predefined methods ยท import unittestfrom test.calculator.simplecalculator import Calculatorclass TestSimpleCalculator(unittest.TestCase): @classmethod def setUpClass(cls): cls.calc = Calculator(0, 0) @classmethod def tearDownClass(cls): del cls.calc def setUp(self): self.calc.a = 5 self.calc.b = 4 def test_simpleadd(self): self.assertEqual(self.calc.add(), 9) def test_simplesub(self): self.assertEqual(self.calc.subs(), 1) def test_simplesubfail(self): self.assertEqual(self.calc.subs(), 5) def tearDown(self) -> None: self.calc.a = 0 self.calc.b = 0 if __name__ == '__main__': unittest.main() Python Programming ยท
Find elsewhere
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 40980381 โ€บ python-unit-test-setupclass-with-variables-from-config-file
Python unit test SetupClass with variables from config file - Stack Overflow
December 6, 2016 - class MyUnitTestBase(unittest.TestCase): @classmethod def SetupClass(self, var1, var2,...): some_internal_setup_stuff using var1 etc.
Top answer
1 of 3
249

The 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.

2 of 3
35

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.

๐ŸŒ
Adam Johnson
adamj.eu โ€บ tech โ€บ 2020 โ€บ 10 โ€บ 13 โ€บ how-to-mock-environment-variables-with-pythons-unittest
Python: mock environment variables with unittest - Adam Johnson
October 13, 2020 - import os from unittest import TestCase, mock class SettingsTests(TestCase): @classmethod def setUpClass(cls): cls.enterClassContext( mock.patch.dict(os.environ, {"FROBNICATION_COLOUR": "ROUGE"}) ) # set from this point until tearDownClass() def test_frobnication_colour(self): self.assertEqual(os.environ["FROBNICATION_COLOUR"], "ROUGE") The above example uses enterClassContext, new in Python 3.11, as I covered in a recent post.
Top answer
1 of 3
73

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.

2 of 3
15

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

๐ŸŒ
GitHub
gist.github.com โ€บ twolfson โ€บ 13f5f5784f67fd49b245
Python unittest `setUp` inheritance ยท GitHub
In some cases for Python unit tests, we want to automatically perform setUp methods in as declared in a base class. However, we still want setUp to work as per normal in the subclass. The following code will proxy the new setUp function to run it's base class' and the new one. # Define a common test base for starting servers class MyBaseTestCase(unittest.TestCase): @classmethod def setUpClass(cls): """On inherited classes, run our `setUp` method""" # Inspired via http://stackoverflow.com/questions/1323455/python-unit-test-with-base-and-sub-class/17696807#17696807 if cls is not MyBaseTestCase a
Top answer
1 of 2
2

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.

2 of 2
0

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 makeTrafficLightInGreenState for a helper factory to produce a specific type of traffic light object. In this example I could then also have makeTrafficLightInRedState for a different group of tests. I find this preferrable over a common Setup method which just creates both the green and the red traffic light: In the end you get confused which part of Setup is 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 into Setup without 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.

๐ŸŒ
Blogger
stezz.blogspot.com โ€บ 2011 โ€บ 04 โ€บ calling-only-once-setup-in-unittest-in.html
somethingMeaningful: Calling only once setUp in unittest in python
April 25, 2011 - Remove the setUp() method and rename setupClass to setUpClass(self). ALso use the decorator @classmethod Your code will look like this: [code language="python" highlight=6,7] import unittest from my_program import MyClass class MyClassTest(unittest.TestCase): @classmethod def setUpClass(self): # create an instance of object MyClass() so that # you can access it later in the code self.myclass = MyClass() # (you can call this later with self.myclass) [/code]ReplyDelete ยท
๐ŸŒ
CodingNomads
codingnomads.com โ€บ python-test-setup-teardown
Python Test `setup()` and `tearDown()`
When writing tests for your web scraper script, you might have defined a variable for the index URL or for an individual recipe URL multiple times. Instead of defining such information in every test method, you can define it only once in the .setUp() method: import unittest import rescrape class TestRescrape(unittest.TestCase): def setUp(self): self.BASE_URL = "https://codingnomads.github.io/recipes/" self.url = f"{self.BASE_URL}recipes/11-making-my-own-baguet.html" # snip
๐ŸŒ
Python
docs.python.org โ€บ 3.4 โ€บ library โ€บ unittest.html
26.3. unittest โ€” Unit testing framework โ€” Python 3.4.10 documentation
import unittest class Test(unittest.TestCase): @classmethod def setUpClass(cls): cls._connection = createExpensiveConnectionObject() @classmethod def tearDownClass(cls): cls._connection.destroy()