Skip to content
Advertisement

AssertEqual failing when comparing two seemingly identical IndexErrors

I have a DynamicArray class shown below. (I have only included relevant methods. The rest can be viewed from https://www.geeksforgeeks.org/implementation-of-dynamic-array-in-python/)

import ctypes


class DynamicArray:
    '''
    Dynamic Array class
    '''

    def __init__(self):
        self.n = 0 # count number of elements
        self.capacity = 1 # default capacity
        self.A = self.make_array(self.capacity)

    def __len__(self):
        """
        Return number of elements in the array
        """
        return self.n

    def __getitem__(self,k):
        """
        Return element at k index
        """

        #Check if K index is out of bounds#
        if not 0 <= k < self.n:
            return IndexError('{} is out of bounds'.format(k))

        return self.A[k] #Retrieve from the array at index k#

Then I have another unit test file down below

from DynamicArray import DynamicArray
import unittest


class MyTestCase(unittest.TestCase):
    def setUp(self) -> None:
        self.a = DynamicArray()  # empty array

        self.b = DynamicArray()
        self.b.append(0)

        self.c = DynamicArray()
        self.c.append(0)
        self.c.append(1)

    def test_getitem(self):
        self.assertEqual(self.a.__getitem__(0),IndexError('0 is out of bounds'))

When I run the test I expect self.a.__getitem__(0) to throw IndexError('0 is out of bounds') and I can’t see why the assertion fails? The only difference is that self.a.__getitem__(0) will yield IndexError('{} is out of bounds'.format(0)), which seems to me the same as IndexError('0 is out of bounds')

I tried running below code to see if the string by themselves were any different

    if '{} is out of bounds'.format(0) == '0 is out of bounds':
        print('str equal')
    if '{} is out of bounds'.format(0).__len__() == '0 is out of bounds'.__len__():
        print('len equal')
    if IndexError('{} is out of bounds'.format(0)) == IndexError('0 is out of bounds'):
        print('IndexError equal')

and confirmed that only the third if statement did not print

below is the photo of the console

enter image description here

Thanks in advance. Constructive criticisms and feedbacks are welcome.

Advertisement

Answer

Exceptions can’t be conpared with assertEqual.

with self.assertRaises(IndexError, msg='0 is out of bounds'):
    self.a[0]

And Exceptions must be raiseed to be captured.
You’re returning IndexError

raise IndexError('{} is out of bounds'.format(k))

https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement