SetUp unittest function for Python

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

Setup ()
A method designed to prepare a test device. Called immediately before calling the test method ; any exception thrown by this method will be considered an error, not a test error. The default implementation does nothing.

My question about setUp as follows:

In our test code base, I saw that we set up the Python testing framework, inheriting from unittest.TestCase . Initially unittest.TestCase has the names setUp and tearDown . In the custom class, we have setUpTestCase and tearDownTestCase . Therefore, each time these two functions will be called instead of these original copies.

My questions:

  • How are those setUp and tearDown called by the base test runner?
  • Is it required that the functions used to configure test cases begin with setUp , and the functions used to break test cases begin with tearDown ? Or can it be called any valid identifier?

Thanks.

+4
source share
1 answer
  • Methods
  • setUp () and tearDown () are automatically used when they are available in your classes inheriting from unittest.TestCase.
  • They should be called setUp () and tearDown (), only those used when executing test methods.

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() ... 
+7
source

Source: https://habr.com/ru/post/1491463/


All Articles