tel*_*tel 7 python unit-testing assert assertion python-unittest
在许多许多断言方法的Python的标准unittest包装,.assertHasAttr()是好奇地缺席.在编写一些单元测试时,我遇到了一个案例,我想测试对象实例中是否存在属性.
丢失.assertHasAttr()方法的安全/正确替代方法是什么?
tel*_*tel 10
在我写问题的时候想出了一个答案。给定一个继承自 的类/测试用例unittest.TestCase,您只需添加一个基于 的方法.assertTrue():
def assertHasAttr(self, obj, intendedAttr):
testBool = hasattr(obj, intendedAttr)
# python >=3.8 only, see below for older pythons
self.assertTrue(testBool, msg=f'obj lacking an attribute. {obj=}, {intendedAttr=}')
Run Code Online (Sandbox Code Playgroud)
呃。
我之前搜索时在谷歌上没有找到任何东西,所以我会把它留在这里以防其他人遇到类似的问题。
我已经更新了我的答案,以对python 3.8 中添加的f 字符串使用简洁的新“自我记录”功能。如果您想要一个assertHasAttr兼容任何 python(包括 <=3.7)的func,请将最后一行改为:
def assertHasAttr(self, obj, intendedAttr):
testBool = hasattr(obj, intendedAttr)
# python >=3.8 only, see below for older pythons
self.assertTrue(testBool, msg=f'obj lacking an attribute. {obj=}, {intendedAttr=}')
Run Code Online (Sandbox Code Playgroud)
你可以自己写:
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))
Run Code Online (Sandbox Code Playgroud)
然后你可以子类而BaseTestCase不是TestCase测试。例如:
class TestDict(BaseTestCase):
def test_dictionary_attributes(self):
self.assertHasAttr({}, 'pop') # will succeed
self.assertHasAttr({}, 'blablablablabla') # will fail
Run Code Online (Sandbox Code Playgroud)