简单的线性搜索测试(python)

时间:2013-09-16 19:22:43

标签: python testing python-unittest linear-search

问题是要故意修复错误的代码,以便可以执行pyUnit测试。使用测试找到代码中的错误,然后进行更正。我的上一次测试在代码中生成错误,但我无法发现它!

给定代码(带错误)

def linear( target, list ):
""" returns the position of target,
if not found returns -1"""
position = 0
if len(list)==0:
    return -1

else:
    while position <= (len(list)+1):
        if target == list[position]:
            return position
        position += 1
return -1

和我的测试:

import unittest

# import the module(s) to be tested:
from LinearSearch import *

class TestLinearSearch(unittest.TestCase):

# setUp - run prior to the start of each test case
def setUp(self):
    # initialize test fixtures
    return

    def test_smoke(self):
        # very simple test to insure test framework is correct
        self.assertTrue(1)

    # additional test_xxx methods follow....
    def test_emptyList(self):
        self.assertEqual(linear(4,[]),-1)

    def test_singleChar(self):
        self.assertEqual(linear(1,[1]),0)

    def test_isInList(self):
        self.assertEqual(linear(4,[1,2,3,4,5]),3)

    def test_isNotInList(self):
        self.assertEqual(linear(8,[1,2,3,4,5]),-1)


if __name__ == '__main__':
    unittest.main()

生成我的错误的测试是最后一个测试:“test_isNotInList(self)”,它是一个超出范围的索引错误...应该很简单但我只需要一些帮助。

1 个答案:

答案 0 :(得分:2)

在上一次测试中,该函数访问list[5],这超出了范围。这会导致IndexError。您可以在不引发异常的情况下访问的最大索引比列表的长度少一个。您可以通过修改while循环的条件来解决此问题:

while position < len(list):

甚至更好,只需直接遍历列表,使用enumerate确定位置:

def linear( target, list ):
    """ returns the position of target,
    if not found returns -1"""
    for idx, element in enumerate(list):
        if element == target:
            return idx
    return -1