Unit testing in Python

According to wikipedia: In computer programming, unit testing is a method by which individual units of source code are tested to determine if they are fit for use. A unit is the smallest testable part of an application. In procedural programming a unit could be an entire module but is more commonly an individual function or procedure. In object-oriented programming a unit is often an entire interface, such as a class, but could be an individual method.

This post is about testing in Python, mainly using the Python standard library testing framework unittest. For an example to test, first import the Unit Test module by:

import unittest

unittestis an object oriented framework based around test fixtures. In unittest the test fixture is the TestCase class. To write a testcase class, we have to write a class that derives from the TestCase class of the unittest module. On the class statement, the base class (or classes) goes in parentheses after the name of the class. The usual four-phase unit test includes Setup, Exercise, Verify and Teardown.

The snapshot of my sample unit testing program is shown below:

In the above program add is a simple adding function to demo unittest. MyTest is the class in which all functions will be ran by unittest. The function setUp will always be ran in order to setup the test environment before all the tests have run. The function tearDown will always be ran in order to cleanup the test environment after all the tests have run. After that, the function beginning with ‘add’ will be ran as a unit test. AssertEqual checks the values given in the parentheses are equal. The TestCase class provides a number of methods to check for and report failures, such as:

assertEqual (a,b) → a == b

assertNotEqual (a,b) → a != b

assertTrue (x) → bool(x) is True

assertFalse(x) → bool(x) is False

assertIs (a,b) → a is b

assertIsNot(a,b) → a is not b

assertIn (a,b) → a in b

assertNotIn (a,b) → a not in b

When we run the above program, we get an output like this:

If there is error in the output or if it is not compiled properly, it will be printed in the terminal. Here , the code is correct. So, we get the output as ‘OK’.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The WordPress.com Blog

The latest news on WordPress.com and the WordPress community.

%d bloggers like this: