lundi 22 août 2016

Testing functions that take user input with Python and Mock

In one of my python test files, I am trying to test a function that takes a user input, and based on that input calls another method. I am using Mock.Patch to call the function in my test file and assert that another function is called. When I run the tests it prompts me for an input, and if I enter the right input for the function I want to be called, the test passes. My question is how do I handle multiple tests that use the same function, but have multiple different outcomes ? One test will always pass depending on what I enter, but the other tests will fail. Is there a way I can say in my tests 'If system input equals this' after the function is called ?

tests.py

import unittest

from mock import patch

import worklog
import datetime

class WorkLogTests(unittest.TestCase):
    def setUp(self):
        self.date1 = datetime.datetime.now()
        self.Entry1 = worklog.Entry.create(date=self.date1, employee="Tim", title="Do Laundry", notes="NA")

    @patch('__main__.worklog.create_new_task')
    def test_create_new_task_called(self, mock):
        worklog.work_log()
        self.assertTrue(mock.called)

if __name__ == '__main__':
    unittest.main()

work_log function from worklog.py

def work_log():
    while True:
        user_input = input("Would you like to create a new entry(c), or look up old ones(L) c/L ? ")
        if user_input == 'c':
            create_new_task()
            break
        elif user_input == 'L':
            search_task()
            break
        else:
            print("That is not a valid response")

Aucun commentaire:

Enregistrer un commentaire