Python: Unit Tests

One way to write unit tests in Python is by using Nose Tools. If you don’t have it installed, it can be done via command line by typing in pip install nose in the terminal.

from nose.tools import assert_equal

def solution(num1, num2):
    return num1+num2

class SolutionTest(object):
    
    def test(self, sol):
        assert_equal(sol(2,2),4)
        assert_equal(sol(4,4),8)
        
        print("All test cases passed")
        
# run tests
t1 = SolutionTest()
t1.test(solution)

In the code above, we import assert_equal from nose.tools. The function solution below it accepts two numbers and returns their sum.

Then we have a class SolutionTest that has a test function accepting self and sol as two arguments to it.

The assert_equal function then checks whether the output of its first argument is equal to the second. e.g it checks whether sol(2,2) equals to 4.

Our code above returns “All test cases passed” as the output.

However, if we modify the code to assert_equal(sol(2,2),4), it’ll return AssertionError: 5 != 4.

Using this basic idea, you can implement unit tests in Python. Thanks for reading! 🙂

Leave a comment