Want to call a method only once for unittest.TestCase--but not sure how?

Oltmans rolf.oltmans at gmail.com
Mon Sep 28 06:45:28 EDT 2009


Hello fellow python hackers,

I'm not an expert when it comes to Python and I'm totally stuck in a
situation. All of our unit tests are written using built-in 'unittest'
module. We've a requirement where we want to run a method only once
for our unit tests. Some background: all of our tests are sub-classes
of unittest.TestCase module just like following (copy pasting from
idle)

class Calculator(unittest.TestCase):

    def setUp(self): pass
    def tearDown(self): pass


    def test_add(self):

        print 'adder'
        print '---------------'

    def test_multiply(self):
        print 'multiplier'
        print '---------------'

    def test_divide(self):
        print '==========='
        print 'Divide test'
        print '==========='

Our requirement is that for every unit test class we want to run a
method only once. Method setUp() won't help because it will be called
before every test method. I've tried using the following

def __init__(self):
        unittest.TestCase.__init__(self)

but it throws the following error


E:\PyPy\Practice>python runner.py

Traceback (most recent call last):
    suite  = unittest.defaultTestLoader.loadTestsFromNames
(['Tests.Calculator.Te
stCase'])
  File "C:\Python25\lib\unittest.py", line 565, in loadTestsFromNames
    suites = [self.loadTestsFromName(name, module) for name in names]
  File "C:\Python25\lib\unittest.py", line 547, in loadTestsFromName
    return self.loadTestsFromTestCase(obj)
  File "C:\Python25\lib\unittest.py", line 507, in
loadTestsFromTestCase
    return self.suiteClass(map(testCaseClass, testCaseNames))
TypeError: __init__() takes exactly 1 argument (2 given)

So I'm completely stumped as to how to create a method that will only
be called only once for Calculator class. Can you please suggest any
ideas? Any help will be highly appreciated. Thanks in advance.



More information about the Python-list mailing list