David Silva
David Silva

Reputation: 2017

assertEqual - two identical lists, why I get strange result?

I have unit tests:

import unittest

class TestFail(unittest.TestCase):
    def testFail(self):
        data = range(5)
        self.assertEqual(data, insertion_sorting(data))

class TestSuccess(unittest.TestCase):   
    def testSuccess(self):
        data = range(5)
        self.assertEqual([0,1,2,3,4], insertion_sorting(data))


def insertion_sorting(data):
        result = []
        while len(data):
            min_index = 0
            for i in range(len(data)):
                if data[i] < data[min_index]: min_index = i
            result.append(data[min_index])
            del data[min_index] 
        return result 

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

TestSuccess ran successful, but TestFail raises:

AssertionError: Lists differ: [] != [0, 1, 2, 3, 4]

Second list contains 5 additional elements. First extra element 0: 0

  • []
  • [0, 1, 2, 3, 4]

Could you explain me, why TestSuccess ran successful, but TestFail not?

Upvotes: 4

Views: 2792

Answers (2)

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262979

Your insertion_sorting() function is destructive: it modifies in-place the list you pass. Therefore, the list referenced by the data variable defined in TestFail() will indeed be cleared during the call to insertion_sorting().

A simple workaround would be to operate on a copy of the list:

self.assertEqual(data, insertion_sorting(data[:]))

A more complicated option would be to refactor insertion_sorting() so it is not destructive.

Upvotes: 2

dmg
dmg

Reputation: 7706

Try the following:

data = range(5)
print data
print insertion_sorting(data)
print data

Do you see what happens? You delete the contents of data.

And to answer your real question - TestFail failed because data is empty after the sorting, while in TestSuccess you check against a different list.

Upvotes: 1

Related Questions