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

标签 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)”,它是一个索引越界错误...应该很简单,但我只需要一点帮助。

最佳答案

在您上次的测试中,该函数访问了超出范围的 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

关于python - 简单的线性搜索测试(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18835663/

相关文章:

python - Windows WSL 的 Poetry 安装不起作用,忽略 $HOME

testing - 使用虚拟机进行软件的操作系统兼容性测试

amazon-web-services - 如何在 AWS 设备场中运行测试脚本?

python - 修补包内的函数 __init__ 并在同一包内的模块中使用它

python - 拆分为 n 个字符串时返回字符串的所有可能组合

python - 线性判别分析后仅绘制了 2 个簇,而不是 3 个

python - 为什么 pandas 有时在选择列时似乎会更改字符串编码?

php - 为 Braintree webhook 构建 PHPUnit 测试时间接修改重载属性

Python 测试多个子类的继承

python - 找不到文件 - Python 单元测试