Running Unittests in the iPython Notebook


In preparation for the Software Engineering exam in a couple of days I created a couple of questions that would be interesting to solve. One of them was to duplicate the map functionality and to test it I wanted to use the unittest module from within iPython Notebook. So to get it working I had to use a TestRunner.

Python Unittest Module

Link to the Test Prep iPython Notebook

1) Write a generator of all fibonacci numbers. 1 1 2 3 5 8  should never deplete, take an optional max argument.
2) Create a Iteratable class that lists the first 10 powers of 2 … so till 2^10
3) Write the map function
4) Write a list comprehension that creates a list of the following:
– squares all even numbers
– double all odd
given a = [1,2,3,4,5]
x = [ ? ]
print(list(x))  # [2,4,6,16,10]

Cell 1

## Write the Map function.
def _map(f,list1,*list2):
  if len(list2) > 0:
      zipper = zip(list1,*list2)
      return (f(*a) for a in zipper)
      return (f(a) for a in list1)

Cell 2

from operator import *
from unittest import *

a = [1,2,3,4,5]
b = [5,4,3,2,1]
c = [10,20,30,40,50]
x = map(lambda x: x, a)
y = map(lambda x,y: x+y ,a,b)
z = map(lambda x,y,z: x+y+z ,a,b,c)


w= _map(lambda x: x, a)
ww = _map(lambda x,y: x+y ,a,b)
www = _map(lambda x,y,z: x+y+z ,a,b,c)


Cell 3

from io import StringIO
from unittest import *

class TestMap (TestCase):
def test_map_1 (self):
a = [1,2,3,4,5]
b = [5,4,3,2,1]
w = map(lambda x,y: x+y ,a,b)
ww = _map(lambda x,y: x+y ,a,b)

def test_map_2 (self):
a = [4,5]
b = [3,1]
c = [3,2]
w = map(lambda x,y,z: x+y-z ,a,b,c)
ww = _map(lambda x,y,z: x+y+z ,a,b,c)

def test_map_3 (self):
a = [4,5,3,2,1]
b = [4,3,3,2,1]
w = map(lambda x,y: x+y ,a,b)
ww = _map(lambda x,y: x+y ,a,b)

a = TestMap()
# unittest.TextTestRunner().run(a)

suite = unittest.TestLoader().loadTestsFromModule(a)

Ran 3 tests in 0.003s



Leave a Reply

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

You are commenting using your 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