Strange classmethod mock behavior

Fabio Zadrozny fabiofz at gmail.com
Tue Oct 25 07:09:28 EDT 2011


I'm trying to mock a classmethod in a superclass but when restoring it
a strange behavior happens in subclasses (tested on Python 2.5)

Anyone knows why this happens? (see test case below for details)
Is there any way to restore that original method to have the original behavior?

import unittest

class Test(unittest.TestCase):

    def testClassmethod(self):
        class Super():
            @classmethod
            def GetCls(cls):
                return cls

        class Sub(Super):
            pass

        self.assertEqual(Sub.GetCls(), Sub)

        original = Super.GetCls
        #Mock Super.GetCls, and do tests...
        Super.GetCls = original #Restore the original classmethod
        self.assertEqual(Sub.GetCls(), Sub) #The call to the
classmethod subclass returns the cls as Super and not Sub as expected!

if __name__ == '__main__':
    unittest.main()



More information about the Python-list mailing list