Python's `unittest` lacks an `assertHasAttr` method, what should I use instead?

Came up with an answer as I was writing the question. Given a class/test case that inherits from unittest.TestCase, you can just add a method based on .assertTrue():

def assertHasAttr(self, obj, intendedAttr):
    testBool = hasattr(obj, intendedAttr)

    self.assertTrue(testBool, msg='obj lacking an attribute. obj: %s, intendedAttr: %s' % (obj, intendedAttr))

Duh.

I didn't find anything on google when I was searching before, so I'll leave this here in case anyone else runs into a similar issue.


You can write your own:

HAS_ATTR_MESSAGE = '{} should have an attribute {}'

class BaseTestCase(TestCase):

    def assertHasAttr(self, obj, attrname, message=None):
        if not hasattr(obj, attrname):
            if message is not None:
                self.fail(message)
            else:
                self.fail(HAS_ATTR_MESSAGE.format(obj, attrname))

Then you can subclass BaseTestCase insteadof TestCase with tests. For example:

class TestDict(BaseTestCase):

    def test_dictionary_attributes(self):
        self.assertHasAttr({}, 'pop')  # will succeed
        self.assertHasAttr({}, 'blablablablabla')  # will fail