python logo

unit testing in python


Python hosting: Host, run, and code Python in the cloud!

In the automotive industry, when building a car, various sub-components such as the engine, wheels, and brakes are constructed. These components each have their own unique specifications and requirements.
Without the crucial process of testing, it’s nearly impossible to ascertain if the car will function as expected once all the components are assembled.
Image of a modular system Just as one wouldn’t rely on an untested car, the same principle applies to software development. Software is made up of different modules and components.
A significant insight to remember is that the overall quality of software is directly proportional to the quality of its least tested component.

Python Unit Testing with the unittest Module

Python’s unittest module offers a comprehensive framework for unit testing. Consider the following simple function:

def valuePlusOne(x):
return x+1

This function can be tested using the assertEquals method in the following way:

import unittest

def valuePlusOne(x):
return x+1

class Tests(unittest.TestCase):

def test(self):
self.assertEqual( valuePlusOne(2), 3)

def test_neg(self):
self.assertEqual( valuePlusOne(-1),0)

if __name__ == '__main__':
unittest.main()

When this testing script runs, the output will be:

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

Python Unit Testing with py.test

Another popular choice for unit testing in Python is the pytest module.
To utilize pytest, first, it needs to be installed:

pip install pytest

A simple test using pytest might look like:

def valuePlusOne(x):
return x+1

def test_value():
assert( valuePlusOne(2) == 3)

Python Unit Testing

To understand how pytest responds to failures, modify the function to return an incorrect value and see the result:

def valuePlusOne(x):
return x+2

def test_value():
assert( valuePlusOne(2) == 3)

Unit Testing in Python with incorrect result

Overview of Python Testing Modules

Python has a rich ecosystem of testing modules available. Some of the prominent ones include Nose, Tox, unittest2, and unittest.mock.






Leave a Reply: