views:

66

answers:

1

Hi,

I want to overload failUnlessEqual in unittest.TestCase so I created a new TestCase class:

import unittest

class MyTestCase(unittest.TestCase):
    def failUnlessEqual(self, first, second, msg=None):
        if msg:
            msg += ' Expected: %r - Received %r' % (first, second)
        unittest.TestCase.failUnlessEqual(self, first, second, msg)

And I am using it like:

class test_MyTest(MyTestCase):
    def testi(self):
        i = 1
        self.assertEqual(i, 2, 'Checking value of i')
    def testx(self):
        x = 1
        self.assertEqual(x, 2, 'Checking value of i')

This is what I get when I run the tests

>>> unittest.main()
FF
======================================================================
FAIL: testi (__main__.test_MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "<stdin>", line 4, in testi
AssertionError: Checking value of i

======================================================================
FAIL: testx (__main__.test_MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "<stdin>", line 7, in testx
AssertionError: Checking value of x

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (failures=2)

I was expecting that the the message would be 'Checking value of x Expecting: 2 - Received: 1'

MyTestCase class is not being used at all. Can you tell me what I am doing wrong?

+1  A: 

You are calling assertEqual, but define failUnlessEqual. So why would you expect that your method is called - you are calling a different method, after all?

Perhaps you have looked at the definition of TestCase, and seen the line

assertEqual = assertEquals = failUnlessEqual

This means that the method assertEqual has the same definition as failUnlessEqual. Unfortunately, that does not mean that overriding failUnlessEqual will also override assertEqual - assertEqual remains an alias for the failUnlessEqual definition in the base class.

To make it work correctly, you need to repeat the assignments in your subclass, thereby redefining all three names.

Martin v. Löwis
Of course. Thanks.
francisco santos