Lets have a look on python Test Driven Development, which is an great thing to practice. This is just a basic of TDD in python.

TDD, in basic terms,this is the process of implementing code by writing your tests first, seeing them fail, then writing the code to make the tests pass.

TDD is very much like a cycle, with my code going through as many iterations of tests, until the feature is finished. By implementing these tests before i write the code, it brings out a natural tendency to think about my problem first. While i start to construct my test, I have to think about the way i design my code. What will my function or method return? What if i get an exception here? And so on.So this a very useful thing of us. My uncle always push me to practice this :)

Now let's see the workflow

Step 1: Write Failing Test;  
Step 2: Run and Fail Test;   
Step 3: Write Code to Pass;  
Step 4: Run and Pass Test;      
Step 5: Refactor and Repeat Step 1;

How to get started

  1. unittest
  2. nose
  3. pytest

These are three module to use for TDD in python.

In this case we will use the unittest module that comes with python by default.

import unittest

Then we will test our file like i mentioned here in my code.

	def test_add(self):
		self.assertEqual(calc.add(10, 10), 15)
		self.assertEqual(calc.add(-1, 1), 0)
		self.assertEqual(calc.add(-1, -1), -2)

In this way here i said that my function add() should return 20 for add(10, 10) to pass the test and so on .

Run

$ python test_calc.py

Output

....
----------------------------------------------------------------------
Ran 4 tests in 0.001s


OK

look its saying that all our functions are working fine no problem .

But if we make change to any of our function say for example

 def add(x, y):
	return x-y # we changed (+) to (-) sign

Run Again

$ python test_calc.py

Now Output

F...
======================================================================
FAIL: test_add (__main__.TestCalc)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/media/munna/Engineering/python3_projects/test_calc.py", line 7, in test_add
    self.assertEqual(calc.add(10, 10), 20)
AssertionError: 0 != 20


----------------------------------------------------------------------
Ran 4 tests in 0.002s


FAILED (failures=1)

look at this is saying that something is wrong, because our add(x,y) not working properly it should return 20 for add(10, 10) but it's returning the wrong value. rest function are working fine.so Ran 4 tests in 0.002s and FAILED(failures = 1 ).

Now we will go to add() and solve the problem.

I hope this would help you.