如何在UnitTest中测试列表?



下面是UnitTest代码,用于查找列表或字符串中元素的最后一次出现。我如何使用UnitTest测试下面的代码?

class LastOccurenceTest(unittest.TestCase):
def test_find_last(self) -> None:
""" Test case to find index of last occurence of the item in string or list"""
self.assertEqual(find_last('p','apple','s'),2)
self.assertEqual(find_last('q','apple','s'),-1) # Target not found
self.assertEqual(find_last([22],[22,22,33,22],'l'),3)

前两个语句工作正常,但第三个语句抛出以下错误,因为它无法计算最后出现的次数:

AssertionError: -1 != 3

下面是查找最后一次出现的函数:

def find_last(target: Any, seq: Sequence[Any],a) -> Optional[int]:
''' return the offset from 0 of the last occurrence of target in seq '''
try:
if a=='s':

b: str=""
c: int= b.join(seq).rindex(target)
return c
elif a=='l':
seq.reverse()
index = seq.index(target)
return(len(seq) - index - 1)
except:
return -1

如何在UnitTest中测试列表?

list.index(x[, start[, end]]),x应为列表中的元素。所以[22]应该是22

find_last.py:

from typing import Any, Optional, Sequence

def find_last(target: Any, seq: Sequence[Any], a) -> Optional[int]:
''' return the offset from 0 of the last occurrence of target in seq '''
try:
if a == 's':
b: str = ""
c: int = b.join(seq).rindex(target)
return c
elif a == 'l':
seq.reverse()
index = seq.index(target)
return(len(seq) - index - 1)
except:
return -1

test_find_last.py:

import unittest
from find_last import find_last

class LastOccurenceTest(unittest.TestCase):
def test_find_last(self) -> None:
""" Test case to find index of last occurence of the item in string or list"""
self.assertEqual(find_last('p', 'apple', 's'), 2)
self.assertEqual(find_last('q', 'apple', 's'), -1)
self.assertEqual(find_last(22, [22, 22, 33, 22], 'l'), 3)

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

测试结果:

.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK

最新更新