Search code examples
pythonunit-testingpython-unittestpython-mock

How to test a function call using Python and unittest library


I just had a question on how you write a test for the following function? Here is my test for the part that is covered, but I am not sure how I would change the test to cover the print statement and calling the get_employee_name function again. Any help would be appreciated!

function to test

Here is my code to test the covered part:

DATA = {
"employee_name": "Brian Weber",
"minutes": 120,
"task_name": "Surfing",
"notes": "These are my notes.",
"date": "2016-12-25"
}
​
​
class WorkLogTests(unittest.TestCase):
    def test_get_employee_name(self):
        with mock.patch('builtins.input',
            return_value=DATA["employee_name"]):
            assert worklog.get_employee_name() == DATA["employee_name"]

Solution

  • The first problem I had was using recursion if the user didn't enter anything. So I refactored my code to use a while loop using continue if there was no user input. Here is the new code and the test covering all lines:

    def get_employee_name():
        """Prompt the employee for their name."""
        while True:
            employee_name = input("Enter employee name: ")
            if len(employee_name) == 0:
                print("\nYou must enter your name!\n")
                continue
            else:
                return employee_name
    
    def test_get_employee_name(self):
        with mock.patch('builtins.input', side_effect=["", "Brian Weber"],
            return_value=DATA["employee_name"]):
            assert worklog.get_employee_name() == DATA["employee_name"]