11

I am relatively new to Python. According to unittest.setUp documentation:

setUp()
Method called to prepare the test fixture. This is called immediately before calling the test method; any exception raised by this method will be considered an error rather than a test failure. The default implementation does nothing.

My question about setUp is as follows:

In our testing code base, I have seen that we customized the Python testing framework by inheriting from unittest.TestCase. Originally, unittest.TestCase has names setUp and tearDown.In the customized class, we have setUpTestCase and tearDownTestCase. So each time those two functions will be called instead of those original counterparts.

My questions are:

  1. How are those setUp and tearDown functions being called by the underlying test runner?
  2. Is it required that those functions used to set up test cases should start with setUp and functions used to tear down test cases should start with tearDown? Or it can be named as any valid identifier?

Thank you.

1 Answer 1

15
  1. setUp() and tearDown() methods are automatically used when they are available in your classes inheriting from unittest.TestCase.
  2. They should be named setUp() and tearDown(), only those are used when test methods are executed.

Example:

class MyTestCase(unittest.TestCase):
  def setUp(self):
     self.setUpMyStuff()

  def tearDown(self):
     self.tearDownMyStuff()

class TestSpam(MyTestCase):
  def setUpMyStuff(self):
    # called before execution of every method named test_...
    self.cnx = # ... connect to database

  def tearDownMyStuff(self):
    # called after execution of every method named test_...
    self.cnx.close()

  def test_get_data(self):
    cur = self.cnx.cursor()
    ...
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your reply. Do you mean that they are automatically used when I have function names starts with setUp and tearDown? Their names don't need to be exactly only contain setUp and tearDown, they could be setUpThisCase, is this right?
setUp() and tearDown() are automatically called before and after the methods named 'test_*', for example 'test_ham' or 'test_spam', are being executed. I don't understand the other question.
Thanks. That part I understand. My question is: could I change the name of setUp to something else like setUpTest, if possible, in this case, would setUpTest be automatically used?
I have updated the example to show how to 'rename' the setUp/tearDown. But not sure if that's really useful?
Thanks. I think it answers my question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.