Demystifying Python assertEqual() With Examples

As developers, we all know the importance of unit testing to ensure that the code we write meets standard quality. In this article, let’s look at how we can use Python assertEqual( ), which is part of the unittest library with examples.

Installation of Python assertEqual()

assertEqual() is part of the unittest module and comes built-int with python.

What is assertEqual()?

AssertEqual( ) is a unittest function. That is used for checking if two variables are equal or not. If the results are equal, it will return a True or else False. Sounds simple, right. Let’s look at the basic syntax of the assertEqual() function.

assertequall(value1, value2, message)

Parameters

(value1, value2, message)

Where,

  • value1: a variable which is to be used in comparison by assertEqual( )
  • value2: a variable which is to be used in comparison by the function.
  • message: custom message which will get displayed if test case failed.

How to use Python assertEqual()

Firstly to use the assertEqual( ) function, you need to import unittest and then inherit it in another class. Let’s take a look at an example for a better understanding.

Example 1(Positive)

#Sample assertEqual()
import unittest                 #importing 
class sampletesting(unittest.TestCase):     
    def testing(self):      # test function to test equality of two value
        value1= 10 + 5
        value2= 20 - 5
        # error message if the case failed
        message = "values are not equal"
         # assertEqual() to check wether the variables are equal or not
        self.assertEqual(value1,value2,message)

obj = sampletesting()
obj.testing()

Explanation

In the above-given Example 1, first import unittest. Then initialized a class sampletesting and inherited (unittest.TestCase) in sampletesting.

Then we created a function testing in class sampletesting. This function takes no variables. In this function, we first initialized two variables, value1 and value2.

Secondly, we have initialized the message variable to display error messages if the program fails. Then we have used the assertequal() function and provided it the three variables value1, value2 and message.

Example 2(Negative)

#Sample assertEqual()
import unittest                 #importing 
class sampletesting(unittest.TestCase):     
    def testing(self):      # test function to test equality of two value
        value1= 10 + 5
        value2= 20 - 10
        # error message if the case failed
        message = "values are not equal"
         # assertEqual() to check wether the variables are equal or not
        self.assertEqual(value1,value2,message)

obj = sampletesting()
obj.testing()

#Output

AssertionError: 15 != 10 : values are not equal

Explanation

The above-given example is similar to the first example, except in Example 2, the value1 and value2 are not equal. This will trigger the AssertionError, which will display the values that are not equal and the constructed message we gave in the parameters.

Python assertequal Vs assertdictequal

AssertEqual function uses assertDictEqual by default for comparing two dictionaries.

import unittest
class sampletesting(unittest.TestCase):
    def testing(self):
        value1= {"a":1,"b":2,"c":4}      #dictionary values
        value2= {"a":1,"b":2,"c":3}
        message = "values are not equal"
        #using assertDictEqual() to check wether the dictionaries are equal or not
        self.assertDictEqual(value1,value2,message)

obj = sampletesting()
obj.testing()

#Output

AssertionError: {'a': 1, 'b': 2, 'c': 4} != {'a': 1, 'b': 2, 'c': 3}
- {'a': 1, 'b': 2, 'c': 4}
?                       ^

+ {'a': 1, 'b': 2, 'c': 3}
?                       ^
 : values are not equal

Explanation

In the above-given example, first import unittest. Then initialized a class sampletesting and inherited (unittest.TestCase) in sampletesting.

Then we created a function. This function takes no variables. In this function, we first initialized two variables, value1 and value2.

Secondly, we have initialized the message variable to display error messages if the program fails. Then, we used the assertDictEqual() function instead of assertequal and provided the three variables value1,value2, and message.

Python assert Vs assertequal

Python assert statement is used to check if a condition is True or Not. If the given condition is true, the program continues or throws a constructed error message. While assertEqual is used to compare two variables and check whether they are equal or not.

a = -7
#using assert to check if the numbe meets the condition
assert a < 0 'only negative numbers are allowed'
print('a is a negative number.')

Explanation

In the above example, we have created a variable a = -7. Then we have used the assert function and provided the condition in our case it is a< 0 and the message to be displayed if the case fails. And lastly, using the handy print function, we demonstrated a message to show that a is indeed a negative number.

Python assertequal array

This function can also be used to compare two arrays. And check whether they are equal or not. Here is an example of how to do it.

import unittest
class sampletesting(unittest.TestCase):
    def testing(self):
        value1= [1,2,3,4,5,7]     # arrays
        value2= [1,2,3,4,5,6]
        message = "values are not equal"
        self.assertEqual(value1,value2,message)

obj = sampletesting()
obj.testing()

#Output

AssertionError: Lists differ: [1, 2, 3, 4, 5, 7] != [1, 2, 3, 4, 5, 6]

First differing element 5:
7
6

- [1, 2, 3, 4, 5, 7]
?                 ^

+ [1, 2, 3, 4, 5, 6]
?                 ^
 : values are not equal

As you can see from the output, it shows pretty detailed information on the differences and which elements differ.

Explanation

In the above-given example, we have first imported unittest. Then initialized a class sampletesting and inherited (unittest.TestCase) in sampletesting.

Then we created a function testing. This function takes no variables. In this function, we first initialized two arrays, value1 and value2. Then we have initialized the message variable to display error messages in case the program fails.

Then we have used the assertequal() function and provided it the three variables value1,value2 and message. Since the arrays, value1 and value2 are not equal the program will throw a AssertionError: Lists differ: [1, 2, 3, 4, 5, 7] != [1, 2, 3, 4, 5, 6].

Python assert approximately equal

While comparing floating numbers, it’s common to round off the values. So instead of the assertequal function, you can use assertAlmostEqual to compare floating numbers.

import unittest
class sampletesting(unittest.TestCase):
    def testing(self):
        value1= 1.1234567863783
        value2= 1.1234567852663
        #providing decimal value till where to compare 
        place=8
        #using self.assertAlmostEqual
        self.assertAlmostEqual(value1,value2,place)


obj = sampletesting()
obj.testing()

The assertAlmosEqual takes extra parameter places to provide the decimal value until you want to compare. In the above example, we have provided 8.

Explanation

In the above-given example, first import unittest. Then initialized a class sampletesting and inherited (unittest.TestCase) in sampletesting.

Then we created a function. This function takes no variables. In this function, we first initialized two variables, value1 and value2.

Secondly, we have initialized the place variable and provided it with the decimal value until we compare. Then we used the assertAlmostEqual() function instead of assertequal and provided the three variables value1,value2, and place.

None Supported

Objects like NumPy.array, data frame, and bytes cannot be checked using assertEqual()

FAQs on assertEqual Python

What is the difference between assertEqual and assertEquals?

assertEquals() is just a (deprecated) alias forĀ TestCase.assertEqual.

What is the precision of python assertEqual?

assertEqual() is quite precise and can compare values till the 15th decimal.

Conclusion

So, this was all about the python assertEqual() function, which takes two variables and checks if they are equal or not for testing purposes.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments