Python';s'unittest'缺少'assertHasAttr'方法,我应该使用什么来代替?
在中的许多assert方法中,Python';s'unittest'缺少'assertHasAttr'方法,我应该使用什么来代替?,python,unit-testing,assert,python-unittest,assertion,Python,Unit Testing,Assert,Python Unittest,Assertion,在中的许多assert方法中,.assertHasAttr()奇怪地不存在。在编写一些单元测试时,我遇到了一个案例,我想测试对象实例中是否存在属性 缺少的.assertHasAttr()方法的安全/正确替代方法是什么?您可以编写自己的: HAS_ATTR_MESSAGE = '{} should have an attribute {}' class BaseTestCase(TestCase): def assertHasAttr(self, obj, attrname, mess
.assertHasAttr()
奇怪地不存在。在编写一些单元测试时,我遇到了一个案例,我想测试对象实例中是否存在属性
缺少的
.assertHasAttr()
方法的安全/正确替代方法是什么?您可以编写自己的:
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))
然后,您可以使用tests子类化BaseTestCase
,而不是TestCase
。例如:
class TestDict(BaseTestCase):
def test_dictionary_attributes(self):
self.assertHasAttr({}, 'pop') # will succeed
self.assertHasAttr({}, 'blablablablabla') # will fail
我在写问题的时候想出了一个答案。给定从
unittest.TestCase
继承的类/测试用例,您只需添加一个基于.assertTrue()
的方法即可:
嗯
我以前搜索时在谷歌上没有找到任何东西,所以我将把这个留在这里,以防其他人遇到类似的问题
更新
我已经更新了我的答案,使用了python 3.8中添加的简洁的新答案。如果您想要一个与任何python兼容的
assertHasAttr
func(包括到目前为止最简洁的答案):
self.assertTrue(hasattr(myInstance, "myAttribute"))
阿尔托·丹在对OP的评论中的暗示也是一个有效的答案:
assert hasattr(myInstance, "myAttribute"))
只是在语法上与unittest包中的典型断言不太一致。Nice。我不知道
TestCase.fail()
只使用assert hasattr(…)
assert hasattr(myInstance, "myAttribute"))