Showing posts with label Factorial. Show all posts
Showing posts with label Factorial. Show all posts

Tuesday, December 31, 2019

Python Unit Test: Basics 1

 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.


def factorial(n):
if(n==0):
return 1
else:
return n*factorial(n-1)
view raw n_factorial.py hosted with ❤ by GitHub

                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.



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.

Finally i wrote a python code and tested it ❤️

മധുരം മലയാളം. ഒരു മലയാളം പ്രോബ്ലം സോൾവിങ്

എനിക്ക് പലപ്പോഴും തോന്നിയിട്ടുണ്ട് നമ്മുടെ ഏതു ഭാഷയിലാണ് നമ്മളുടെ ബ്രെയിൻ പ്രവർത്തിക്കുന്നത് എന്ന്. ഇന്റർനെറ്റിൽ പരതുമ്പോൾ നമ്മുക്ക് മനസിലാക...