【问题标题】:Writing unit test for append method in my array based list implementation在我的基于数组的列表实现中为 append 方法编写单元测试
【发布时间】: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


【解决方案1】:

与其直接调整count属性,不如追加50次得到完整列表。

def test_append_full(self):
    a = List()
    for i in range(50):
        a.append(i)
    with self.assertRaises(AssertionError):
        a.append(0)

这可确保您的测试不依赖于您如何限制列表大小的任何特定于实现的细节。假设您将List.append 更改为从 50 开始倒数,而不是从 0 开始计数?这个测试不在乎;无论您决定如何提高它,它都会测试AssertionError


请注意,可以在运行时禁用断言;它们更适合调试。相反,请定义您自己的异常,以便在尝试追加到完整列表时引发:

class ListFullError(RuntimeError):
    pass


def append(self,item):
    if self.count > 50:
        raise ListFullError
    self.array[self.count] = item
    self.count += 1

【讨论】:

    【解决方案2】:

    如果您只想测试 self.count 超过 50 的那一刻,您可以简单地将 self.count 设置为 51:

    a_list=List()
    a_list.count = 51
    a_list.append(2)
    

    您的对象 count 属性设置为 51,将引发异常。

    【讨论】:

      猜你喜欢
      • 2021-09-25
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多