您如何在 UnitTest 中测试列表?

How do you test lists in 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