当我写问题时想出了答案。给定一个继承自的类/测试用例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=}')
Duh.
我之前在谷歌搜索时没有找到任何东西,所以我将把它留在这里,以防其他人遇到类似的问题。
update
我已经更新了我的答案以使用整洁的新f 字符串的“自记录”功能 https://docs.python.org/3/whatsnew/3.8.html#f-strings-support-for-self-documenting-expressions-and-debugging这是在 python 3.8 中添加的。如果你想要一个assertHasAttr
func 将与任何 python(包括
# last line of original answer, will work with any python
self.assertTrue(testBool, msg='obj lacking an attribute. obj: %s, intendedAttr: %s' % (obj, intendedAttr))