Python的“unittest”缺少“assertHasAttr”方法,我应该使用什么替代?

2024-04-18 23:25:52 发布

您现在位置:Python中文网/ 问答频道 /正文

Python's standard ^{} package中的众多assert方法中,.assertHasAttr()中奇怪地缺少。在编写一些单元测试时,我遇到了一个情况,我想测试一个对象实例中是否存在属性。在

对于丢失的.assertHasAttr()方法,什么是安全/正确的替代方法?在


Tags: 对象实例方法package属性情况assert单元测试
3条回答

最简洁的答案是:

self.assertTrue(hasattr(myInstance, "myAttribute"))

尽管丹在评论中的暗示也是一个有效的答案:

^{pr2}$

只是在语法上与unittest包中的典型断言不太一致。在

你可以自己写:

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,而不是{}。例如:

^{pr2}$

我在写问题的时候想出了一个答案。给定从unittest.TestCase继承的类/测试用例,您只需添加一个基于.assertTrue()的方法:

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

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

嗯。在

我以前在谷歌搜索的时候没有找到任何东西,所以我把这个放在这里,以防其他人遇到类似的问题。在

相关问题 更多 >