1

right so I am getting an error with unit testing where I can't use selfassertAlmostEqual

in assertAlmostEqual
    diff = abs(first - second)
TypeError: unsupported operand type(s) for -: 'list' and 'list

this is my unittest method where I am getting the error any ideas as to how could I fix it thank you.

def test_method_04(self):
        self.set_up()
        actual = self.bookshop.method_4(self.orders)
        expected = [(1, 678.33),(2, 494.46),(3, 364.8),(4, 492.57)]
        self.assertAlmostEqual(actual, expected, places = 2)
        print("METHOD4 \nACTUAL:")
        for line in actual:
            print(line)
        print("EXPECTED:")
        for line in expected:
            print(line)
'
Progman
  • 16,827
  • 6
  • 33
  • 48
bart
  • 21
  • 3

1 Answers1

0

You can't use self.assertAlmostEqual with lists. You can only use it with numbers. Your error arises because self.assertAlmostEqual subtracts the two numbers it is comparing and asserts that the difference is small enough. You're passing self.assertAlmostEqual two lists, and it can't subtract lists.

While a lot of objects in Python can be compared to be equal, not every object can be considered to be almost equal. For example, could two strings be considered to be almost equal to 2 decimal places?

Unfortunately this means comparing your two lists gets a little trickier. There's no built-in assertion to compare your two lists and assert that all of the numbers in corresponding positions are almost equal. Instead, you have to assert that your lists have the same length, and then for each corresponding pair of 2-tuples in the lists, assert that the first values of the tuples are equal (or perhaps almost equal - this isn't clear from your question) and the second values are almost equal.

Try something like the following:

self.assertEqual(len(expected), len(actual))
for i in range(len(expected)):
    self.assertEqual(expected[i][0], actual[i][0])
    self.assertAlmostEqual(expected[i][1], actual[i][1], places = 2)

or perhaps

self.assertEqual(len(expected), len(actual))
for ((expected_a, expected_b), (actual_a, actual_b)) in zip(expected, actual):
    self.assertEqual(expected_a, actual_a)
    self.assertAlmostEqual(expected_b, actual_b, places = 2)

Feel free to give more meaningful names to the variable names expected_a and so on: I don't know what the pairs of numbers in your lists mean.

Luke Woodward
  • 63,336
  • 16
  • 89
  • 104