Python unittest; assertTrue() strange behavior

Viewed 115

I was amazed to see something like this in a code review request today:

import unittest
class SomeTestClass(unittest.TestCase):
@classmethod
def setUpClass(cls):
  ...
  cls.assertTrue(some_condition, "a message")

This sparked my interest as I know in python2.7 you could not call assertXXX methods in a classmethod or a staticmethod and it would have failed there. I quickly put up some test code to check:

import unittest
class TestClass(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
      var = 34
      cls.assertTrue(var == 34)
      cls.assertTrue(var == 33)

    def test_123(self):
      self.assertFalse(False)

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

Hoping for python language to fail on calling assertTrue which is an instance method in a static context and if it works (I thought may be in python3 it changed) then cls.assertTrue(var == 33) to raise an AssertionError. But to much of my surprize None of the above happened and I see:

.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK

I am using python3.7. My questions are:

  1. shouldn't this fail as assertTrue is an instance method? note that assertFalse and other such method do cause a failure
  2. If it does work shouldn't assertTrue fail when the condition evaluate to False ?
1 Answers

This has to do with how functions are bound in 3.x. Consider a simpler example:

class Example:
    def method(self):
        print(f'Example.method called on {self!r}')

Example.method('a string')
Related