Unit Test - Jaber-Al-Siam/Online_Courier_Service_Management GitHub Wiki

unittest — Unit testing framework

Python Unit Test Module

Overview

The unittest unit testing framework was originally inspired by JUnit and has a similar flavor as major unit testing frameworks in other languages. It supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework.

To achieve this, unittest supports some important concepts in an object-oriented way:

Test fixture

A test case is the individual unit of testing. It checks for a specific response to a particular set of inputs. unittest provides a base class, TestCase, which may be used to create new test cases.

Test suite

A test suite is a collection of test cases, test suites, or both. It is used to aggregate tests that should be executed together.

Test runner

A test runner is a component that orchestrates the execution of tests and provides the outcome to the user. The runner may use a graphical interface, a textual interface, or return a special value to indicate the results of executing the tests.

Basic Example

import unittest

class TestStringMethods(unittest.TestCase):

def test_upper(self):
    self.assertEqual('cse'.upper(), 'CSE')

def test_isupper(self):
    self.assertTrue('CSE'.isupper())
    self.assertFalse('Mushfique Anwar'.isupper())

def test_split(self):
    str = 'Software Engineering'
    self.assertEqual(str.split(), ['Software', 'Engineering'])
    # check that str.split fails when the separator is not a string
    with self.assertRaises(TypeError):
        str.split(2)

if name == 'main': unittest.main()

Usage

  • Import unittest
  • Test name must start with test_
  • From terminal run command: python file_name.py

Testing these methods:

def add(x, y): return x + y

def subtract(x, y): return x - y

def multiply(x, y): return x * y

def divide(x, y): if y == 0: raise ValueError('Can not divide by zero!') return x / y

Test Class

import unittest import calc

class TestCalc(unittest.TestCase):

def test_add(self):
    self.assertEqual(calc.add(10, 20), 30)
    self.assertEqual(calc.add(-5, 15), 10)

def test_subtract(self):
    self.assertEqual(calc.subtract(50, 30), 20)
    self.assertEqual(calc.subtract(5, 15), -10)

def test_multiply(self):
    self.assertEqual(calc.multiply(10, 20), 200)
    self.assertEqual(calc.multiply(3, -9), -27)

def test_divide(self):
    self.assertEqual(calc.divide(50, 10), 5)
    self.assertEqual(calc.divide(28, 4), 7)

if name == 'main': unittest.main()