Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python unittest setUp function

Tags:

python

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.

like image 423
taocp Avatar asked Jul 15 '13 15:07

taocp


People also ask

What is setUp in unittest Python?

setUp allows us to write preparation code that is run for all of our tests in a TestCase subclass. Note: If you have multiple test files with TestCase subclasses that you'd like to run, consider using python -m unittest discover to run more than one test file.

Where will you use setUp () and tearDown () methods?

Prepare and Tear Down State for a Test Class XCTest runs setUp() once before the test class begins. If you need to clean up temporary files or capture any data that you want to analyze after the test class is complete, use the tearDown() class method on XCTestCase .

Does setUp run before every test Python?

Does setUp run before every test Python? The setUp() runs before every test method in the test class. The tearDown() runs after every test method in the test class.


1 Answers

  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()
    ...
like image 122
geertjanvdk Avatar answered Oct 03 '22 08:10

geertjanvdk