AssertEqual - two identical lists, why am I getting a 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 completed successfully, but TestFail raises:

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

The second list contains 5 additional items. First optional item 0: 0

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

Could you explain to me why TestSuccess completed successfully, but TestFail is not?

+4
source share
2 answers

Your insertion_sorting() function is destructive: it changes the list you pass in place. Therefore, the list referenced by the data variable defined in TestFail() will indeed be deleted when insertion_sorting() called.

A simple workaround would be to work with a copy of the list:

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

A more complicated option would be refactoring insertion_sorting() so that it is not destructive.

+2
source

Try the following:

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

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

And to answer your real question - TestFail failed, because data empty after sorting, and in TestSuccess you check another list.

+1
source

All Articles