When comes to any programming language what i check first is how to write a unit test on it.
"Coding is not difficult- Bill Gates" So what is difficult? I would say testing is difficult. Here is a basic example on how to test a small piece of python code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def factorial(n): | |
if(n==0): | |
return 1 | |
else: | |
return n*factorial(n-1) |
The above snippet is a basic recursive program which will return the factorial of a number. Lets see how we can write a basic test case for this. I have my directory structure as follows.
Lets see the contents of n_factorial_tests.py.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from basics.functions import n_factorial | |
import unittest | |
class TestNFactorial(unittest.TestCase): | |
def testRecursion(self): | |
self.assertEqual(n_factorial.factorial(5),120) |
- The first line is on importing the program to the test class.
- Next we are importing unittest : This module provides a rich set of tools for constructing and running tests.
- While defining a function you can see we have used an object "self". This used to represent an instance of a class. Here it means accessing the contents of unittest.TestCase which is being inherited to this class.
- Now we can access the functions defined unittest.TestCase module. Because we have inherited that to our test class.
- self.assertEqual(n_factorial.factorial(5),120) : This is the statement where we assert for our expectation vs the actual value.
- If you run this on PyCharm we can see the below.