Search code examples
pythonpython-3.xclasspython-unittestassert

How do you test lists in UnitTest?


Below is the UnitTest code to find the last occurrence of an element in a list or string. How do I test the below code using 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)

The first two statements work fine but the third one throws the below error as it is not able to count the last occurence :

 AssertionError: -1 != 3

Below is the function to find this last occurrence:

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

How do we test lists in UnitTest?


Solution

  • list.index(x[, start[, end]]), x should be the element of the list. So the [22] should be 22.

    E.g.

    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()
    

    test result:

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