0

I'm having trouble preventing Unittest from calling sys.exit(). I found Unittest causing sys.exit() searching for an answer.I modified the code to

unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(run_tests.Compare))

and put it in my main. I believe the only thing I changed is that my test is in a seperate file named run_tests.py. It looks as such

import unittest
from list_of_globals import globvar

value1 = globvar.relerror
value2 = globvar.tolerance

class Compare(unittest.TestCase):
    def __init__(self,value1,value2):
        super(Compare, self).__init__()
        self.value1 = value1
        self.value2 = value2

    def runTest(self):
        self.assertTrue(self.value1 <  self.value2)

When I run my main function I receive the following error

File "./main.py", line 44, in <module> unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(run_tests.Compare)) File "/usr/lib64/python2.6/unittest.py", line 550, in loadTestsFromTestCase return self.suiteClass(map(testCaseClass, testCaseNames)) TypeError: __init__() takes exactly 3 arguments (2 given)

I don't understand why this error occurs or how to go about fixing it. Any help would be much appreciated. I am using python 2.6 on linux

Community
  • 1
  • 1
Viragos
  • 561
  • 6
  • 15
  • `sys.exit` just throws an exception. You can catch the exception and prevent python from exiting. Alternatively, you could use a mock library to patch exit so that it doesn't throw an exception. – Dunes Aug 07 '14 at 12:39
  • @Dunes, sounds like an answer, not a comment... – Sam Holder Aug 07 '14 at 13:37

1 Answers1

1

Your problem is with your unit test class.

When writing unit tests you are not meant to override init -- as the init method is used to process which tests are to be run. For test configurations, such as setting variables, you should write a method called setUp which takes no parameters. For instance:

class Compare(unittest.TestCase):

    def setUp(self):
        self.value1 = globvar.relerror
        self.value2 = globvar.tolerance

    def runTest(self):
        self.assertTrue(self.value1 <  self.value2)

The problem in the linked question is that unittest.main exits python after all tests have been run. That was not the desired outcome for that user as they were running tests from IPython Notebook, which is essentially an enhanced interpreter. As such it was also terminated by sys.exit. That is, exit is called outside of the test rather than in the test. I'd assumed a function under test was calling exit.

Dunes
  • 37,291
  • 7
  • 81
  • 97