【发布时间】:2018-10-14 04:24:22
【问题描述】:
我是 Python 新手,刚刚开始学习如何使用类。我实现了一个最大大小为 50 的基于数组的列表。我还有一个 append 方法,其中 self.count 指的是列表中的下一个可用位置。现在我正在尝试为我的追加方法编写一个单元测试,但我想知道,除了追加 50 次之外,我如何检查断言错误?有没有办法手动更改我的 self.count?
这是我的追加方法。
def append(self,item):
assert self.count<=50
if self.count>50:
raise AssertionError("Array is full")
self.array[self.count]=item
self.count+=1
这是我为我的单元测试尝试的:
def testAppend(self):
a_list=List()
a_list.append(2)
self.assertEqual(a_list[0],2)
# test for assertion error
任何帮助将不胜感激!
编辑:好吧,在所有有用的建议之后,我意识到我应该提出一个异常。
def append(self,item):
try:
self.array[self.count]=item
except IndexError:
print('Array is full')
self.count+=1
现在这是我的单元测试,但我收到了警告
Warning (from warnings module):
File "C:\Users\User\Desktop\task1unitTest.py", line 57
self.assertRaises(IndexError,a_list.append(6))
DeprecationWarning: callable is None
.......
def testAppend(self):
a_list=List()
a_list.append(2)
self.assertEqual(a_list[0],2)
a_list.count=51
self.assertRaises(IndexError,a_list.append(6))
【问题讨论】:
-
请注意,
AssertionError永远不会被提升,因为AssertionError将首先被提升。 -
另外,可以禁用断言。不要使用它们来强制数据结构中的不变量。
-
@chepner,正如this thread,python wiki 提出了相反的建议(为了检查数据结构不变量,也许这不是强制执行的)。您能否详细说明为什么不为此目的使用断言。
-
是的,它们对于检查不变量很有用,直到有人 runs your code without assertions。它们对于执行不变量不是很有用。
-
assertRaise将要调用的函数及其参数作为单独的参数,而不是调用它的结果。self.assertRaises(IndexError, a_list.append, 6).
标签: python unit-testing