Unit Tests with Python
unit testing in python

    
    In the automotive industry, when building a car, various sub-components such as the engine, wheels, and brakes are constructed. These components each have their own unique specifications and requirements.Without the crucial process of testing, it’s nearly impossible to ascertain if the car will function as expected once all the components are assembled. Just as one wouldn’t rely on an untested car, the same principle applies to software development. Software is made up of different modules and components.A significant insight to remember is that the overall quality of software is directly proportional to the quality of its least tested component.
Python Unit Testing with the unittest ModulePython’s unittest module offers a comprehensive framework for unit testing. Consider the following simple function:
def valuePlusOne(x):    return x+1
This function can be tested using the assertEquals method in the following way:
import unittestdef valuePlusOne(x):    return x+1class Tests(unittest.TestCase):    def test(self):        self.assertEqual( valuePlusOne(2), 3)    def test_neg(self):        self.assertEqual( valuePlusOne(-1),0)if __name__ == '__main__':    unittest.main()
When this testing script runs, the output will be:
----------------------------------------------------------------------Ran 2 tests in 0.000sOK
Python Unit Testing with py.testAnother popular choice for unit testing in Python is the pytest module.To utilize pytest, first, it needs to be installed:
pip install pytest
A simple test using pytest might look like:
def valuePlusOne(x):    return x+1def test_value():    assert( valuePlusOne(2) == 3)

To understand how pytest responds to failures, modify the function to return an incorrect value and see the result:
def valuePlusOne(x):    return x+2def test_value():    assert( valuePlusOne(2) == 3)

Overview of Python Testing ModulesPython has a rich ecosystem of testing modules available. Some of the prominent ones include Nose, Tox, unittest2, and unittest.mock.

    
  