Python的`unittest`缺少`assertHasAttr`方法,我应该使用什么呢?

问题描述 投票:7回答:2

Python's standard unittest package的许多断言方法中,.assertHasAttr()奇怪地缺席。在编写一些单元测试时,我遇到了一个案例,我想测试对象实例中是否存在属性。

对于缺少的.assertHasAttr()方法,什么是安全/正确的替代方案?

python unit-testing assert python-unittest assertion
2个回答
4
投票

在我写这个问题时想出了答案。给定继承自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))

咄。

我之前在搜索时没有在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))

然后你可以通过测试继承qazxsw poi而不是qazxsw poi。例如:

BaseTestCase
© www.soinside.com 2019 - 2024. All rights reserved.