The "first" and "second" Arguments of assertEqual in Django's Unit Tests are Actually "expected" and "actual"

Django Python
2024-03-28 09:41 (8 months ago) ytyng

When we look at the assertEqual method in Django's unit tests:

def assertEqual(self, first, second, msg=None):
    """Fail if the two objects are unequal as determined by the '=='
       operator.
    """
    assertion_func = self._getAssertEqualityFunc(first, second)
    assertion_func(first, second, msg=msg)

The first argument is named first and the second argument is named second, and it seems like there is no difference in their usage.

However, if you write code like the following:

from django.test import TestCase

class AssertTest(TestCase):
    def test_assert_equal(self):
        self.assertEqual(
            'expected',
            'actual'
        )

When the test actually fails, the result will output:

Failure
Expected :'expected'
Actual   :'actual'

Therefore, you should consider the first argument to be Expected and the second argument to be Actual.

For this reason, the hardcoded value in the unit test is Expected, so it should be the first argument. The result of the method execution or the variable holding the result is Actual, so it should be the second argument.

self.assertEqual(
    110,
    get_tax_included_price(100)
)

Nevertheless, if you look at actual examples of Django's unit tests, you will notice that the order can be reversed. So, in practice, either order is acceptable.

Ideally, a tool like Black would decide on one to standardize.

Currently unrated

Comments

Archive

2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011