Archive for March, 2015

Simple Example using Unit Testing in Python

March 13, 2015 Leave a comment

This is simple example how to use unit testing in python. For example, you want to create module that generate fibonacci numbers and want to test whether the module is working properly or not.

Below is simple script for module to generate fibonacci numbers :

# Fibonacci numbers module
def fib2(n): # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while b < n:
        a, b = b, a+b
    return result

def main():
    print fib2(100)

if __name__ == '__main__' : main()

And here simple script to test that module:

import fibonacci
import unittest

class TestFibonacciFunctions(unittest.TestCase):

    def test_series_100(self):
        print('\nTest Series 100')
        wanted_result = [1,1,2,3,5,8,13,21,34,55,89]
        test_result = fibonacci.fib2(100)

    def test_series_50(self):
        print('\nTest Series 50')
        wanted_result = [1,1,2,3,5,8,13,21,34]
        test_result = fibonacci.fib2(50)

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

Run script with command


You will get following output if the wanted_result and test_result are equal

Test Series 100
Test Series 50
Ran 2 tests in 0.000s

Categories: Programming, Python