pythonunit-testing

how to write a unit testing function for my function?


This is a function i created:

def hab(h, a, b= None):
    if b != None:
        result = ("{} , {} , {}".format(h, b, a))
    else:
        result = ("{} , {}".format(h, a))
    return result

I'm trying to write a unit testing for my function, the unit test should assert the function correctness when two or three parameters are provided.

This is my frame:

class hab_Test_Class(unittest.TestCase):
   def test_pass2(self):

   def test_pass3(self):

# i'll use code below to run the unit test
t = hab_Test_Class()
suite = unittest.TestLoader().loadTestsFromModule(t)
unittest.TextTestRunner().run(suite)

I really have little sense of what the unit testing is doing, but not quite get it.


Solution

  • Suppose you have all your codes in main.py

    def format_person_info(h, a, b= None):
        if b != None:
            a = ("{} , {} , {}".format(h, b, a))
        else:
            a = ("{} , {}".format(h, a))
        return a
    

    You can run unit test for this method like below in tests.py:

    import main
    import unittest
    class hab_Test_Class(unittest.TestCase):
       def test_pass2(self):
           return_value = main.format_person_info("shovon","ar")
           self.assertIsInstance(return_value, str, "The return type is not string")
           self.assertEqual(return_value, "shovon , ar", "The return value does not match for 2 parameters")
    
       def test_pass3(self):
           return_value = main.format_person_info("shovon","ar",18)
           self.assertIsInstance(return_value, str, "The return type is not string")
           self.assertEqual(return_value, "shovon , 18 , ar",  "The return value does not match for 3 parameters")
    
    # i will use code below to run the unit test
    t = hab_Test_Class()
    suite = unittest.TestLoader().loadTestsFromModule(t)
    unittest.TextTestRunner().run(suite)
    

    When you run the tests the output will be like below:

    ..
    ----------------------------------------------------------------------
    Ran 2 tests in 0.016s
    
    OK
    

    Now lets see what we have done. We checked that the return type is string as we expected using assertIsInstance and we checked the output for two and three parameters using assertEqual. You may play with this using a set of valid and invalid tests with assertEqual. The official documentation has a brief description about unittest in this official doc Unit testing framework.