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.
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.
- 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.
No comments:
Post a Comment