Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameter order for unittest.TestCase.assertEqual

Is it assertEqual(actual, expected) or assertEqual(expected, actual)?

On the one hand I'm seeing lots of code using assertEqual(actual, expected). This includes examples in the unittest docs and examples in the Django docs.

However, this test assertEqual('foo', 'bar') is giving me the output

- foo
+ bar

Which happens to be the same as for a PHPUnit test with assertEquals( 'foo', 'bar' );

-'foo'
+'bar'

And PHPUnit has $expected as first parameter, followed by $actual. This diff is also what I'd expect for expected, actual.

So is all this Python code I'm seeing doing it wrong?

I checked the definition of the unittest method, though that has the extremely helpful first, second parameter names.

like image 496
Jeroen De Dauw Avatar asked Dec 03 '16 06:12

Jeroen De Dauw


2 Answers

As per the assertEqual document:

Test that first and second are equal. If the values do not compare equal, the test will fail.

So, you may put expected and actual at any place and it will return the same result. But it is the common practice to use actual result as the first argument and expected result as the second argument. It is also demonstrated in Python 3's Unittest Example:

s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
like image 183
Moinuddin Quadri Avatar answered Nov 12 '22 13:11

Moinuddin Quadri


I typically use assertEqual(expected, actual) because the output message makes more sense.

Code:

from unittest import TestCase

class TestClass(TestCase):
    def test_equal(self):
        expected = 1
        actual = 2
        self.assertEqual(expected, actual)

Output:

2 != 1

Expected :1
Actual   :2

If order is reversed, then the message will incorrectly say:

Expected :2
Actual   :1
like image 39
Charles Avatar answered Nov 12 '22 13:11

Charles