Unittest library helps you to test your program and inform you whether it is working fine. It is useful to recheck if a program is running fine when you make certain changes to any related code. Making a test file makes testing easy. All you need to do later is run this file and it will inform you if a program that you are testing is working fine with all possible inputs.
Here is an example of Unitest file working on another file:
CAP.PY FILE
def capitalizing_text(text):
'''
Input string's first letter is capitalized.
'''
return text.cap()
TEST_CAP.PY FILE
#importing unitest library
import unittest
import cap
class TestCap(unittest.TestCase):
#functions in test file must start with the word 'test'
def test_one_word(self):
text = 'python'
#running the program
result = cap.capitalizing_text(text)
#The following line checks if the result and expected result match
self.assertEqual(result, 'Python')
#second function to test a different set of input
def test_multiple_words(self):
text='monty python'
result = cap.capitalizing_text(text)
self.assertEqual(result, 'Monty Python')
#The following if statement is used to run the program directly from command prompt without having to call from a different file
if __name__=='__main__':
unittest.main()
On running the test file, it will inform you that there is an error with the result in the second function. It is not returning as expected. On making the following changes to the program and running the test program again, the errors will be gone.
CAP.PY
def capitalizing_text(text):
'''
Input string's first letter is capitalized.
'''
return text.title()
Comments
Post a Comment