Python `unittest` is missing the` assertHasAttr` method, what should I use instead?

Of the many, many assert methods in the Python standard unittestpackage , it is .assertHasAttr()curiously absent. When writing some unit tests, I came across a situation in which I would like to check for an attribute in an instance of an object.

What is a safe / proper alternative to the missing method .assertHasAttr()?

+4
source share
2 answers

The answer came when I wrote a question. Given a class / test case that inherits from unittest.TestCase, you can simply 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.

google, , , - .

+2

:

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))

BaseTestCase TestCase . :

class TestDict(BaseTestCase):

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

Source: https://habr.com/ru/post/1691686/


All Articles