Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyUnit tearDown and setUp vs __init__ and __del__

Is there a difference between using tearDown and setUp versus __init__ and __del__ when using the pyUnit testing framework? If so, what is it exactly and what is the preferred method of use?

like image 921
Derek Litz Avatar asked Feb 26 '10 20:02

Derek Litz


People also ask

What is setUp and tearDown in Python?

The setUp method is run prior to each test in the class. tearDown is run at the end of every test. These methods are optional.

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.

What is tearDown and setUp?

For that it has two important methods, setUp() and tearDown() . setUp() — This method is called before the invocation of each test method in the given class. tearDown() — This method is called after the invocation of each test method in given class.

What does Unittest main () do?

Internally, unittest. main() is using a few tricks to figure out the name of the module (source file) that contains the call to main() . It then imports this modules, examines it, gets a list of all classes and functions which could be tests (according the configuration) and then creates a test case for each of them.


1 Answers

setUp is called before every test, and tearDown is called after every test. __init__ is called once when the class is instantiated -- but since a new TestCase instance is created for each individual test method, __init__ is also called once per test.

You generally do not need to define __init__ or __del__ when writing unit tests, though you could use __init__ to define a constant used by many tests.


This code shows the order in which the methods are called:

import unittest import sys  class TestTest(unittest.TestCase):      def __init__(self, methodName='runTest'):         # A new TestTest instance is created for each test method         # Thus, __init__ is called once for each test method         super(TestTest, self).__init__(methodName)         print('__init__')      def setUp(self):         #         # setUp is called once before each test         #         print('setUp')      def tearDown(self):         #         # tearDown is called once after each test         #         print('tearDown')      def test_A(self):         print('test_A')      def test_B(self):         print('test_B')      def test_C(self):         print('test_C')    if __name__ == '__main__':     sys.argv.insert(1, '--verbose')     unittest.main(argv=sys.argv) 

prints

__init__ __init__ __init__ test_A (__main__.TestTest) ... setUp test_A tearDown ok test_B (__main__.TestTest) ... setUp test_B tearDown ok test_C (__main__.TestTest) ... setUp test_C tearDown ok  ---------------------------------------------------------------------- Ran 3 tests in 0.000s  OK 
like image 156
unutbu Avatar answered Sep 22 '22 14:09

unutbu