Python Tutorial

Tuesday, March 31, 2015

Nose unittest OOP example


Here we will test helloWorld.py using nose
All source code are available on github
# testHelloWorldOOP.py
__author__ = 'AbuZahedJony'

from helloWorld import add_two_num
from helloWorld import multi_two_num

class TestHelloWorld:
    def __init__(self):
        pass

    # This function will run before any test case (only once)
    @classmethod
    def setup_class(cls):
        print "Main Setup"

    # This function will run after all test case (only once)
    @classmethod
    def teardown_class(cls):
        print "Main Teardown"

    # This function will call per test case (before)
    def setup(self):
        print "SETUP"

    # This function will call per test case (after)
    def teardown(self):
        print "TEAR-DOWN"

    def test_add_num(self):
        print 10*"*"+" Test add num"
        assert add_two_num(2, 3) == 5
        assert add_two_num(-2, 3) == 1

    def test_multi_num(self):
        print 10*"*"+" Test multi num"
        assert multi_two_num(2, 3) == 6
        assert multi_two_num(-2, 3) == -6
  

RUN: nosetests -s testHelloWorldOOP.py

Output:
Main Setup
SETUP
********** Test add num
TEAR-DOWN
.SETUP
********** Test multi num
TEAR-DOWN
.Main Teardown

----------------------------------------------------------------------
Ran 2 tests in 0.002s

OK

Nose unittest simple example


Here we will test helloWorld.py using nose
All source code are available on github
# testHelloWorld.py
from nose import with_setup

__author__ = 'AbuZahedJony'

from helloWorld import add_two_num
from helloWorld import multi_two_num

def m_setup():
    print "\nRun SETUP"

def m_teardown():
    print "Run TEAR-DOWN"

@with_setup(m_setup, m_teardown)
def test_add_num():
    print "Running test ADD"
    assert add_two_num(2, 3) == 5
    assert add_two_num(-2, 3) == 1
    assert add_two_num(-2, -3) == -5

@with_setup(m_setup, m_teardown)
def test_multi_num():
    print "Running test MULTI"
    assert multi_two_num(2, 3) == 6
    assert multi_two_num(-2, 3) == -6
    assert multi_two_num(-2, -3) == 6


RUN: nosetests -s testHelloWorld.py

Output:

Run SETUP
Running test ADD
Run TEAR-DOWN
.
Run SETUP
Running test MULTI
Run TEAR-DOWN
.
----------------------------------------------------------------------
Ran 2 tests in 0.002s

OK

Nose python unittest framework


Nose official doc

Setup

pip install nose

Please install pip if required