How to test a function with input call?

后端 未结 6 1071
野性不改
野性不改 2020-11-29 04:16

I have a console program written in Python. It asks the user questions using the command:

some_input = input(\'Answer the question:\', ...)

6条回答
  •  长情又很酷
    2020-11-29 04:52

    You can do it with mock.patch as follows.

    First, in your code, create a dummy function for the calls to input:

    def __get_input(text):
        return input(text)
    

    In your test functions:

    import my_module
    from mock import patch
    
    @patch('my_module.__get_input', return_value='y')
    def test_what_happens_when_answering_yes(self, mock):
        """
        Test what happens when user input is 'y'
        """
        # whatever your test function does
    

    For example if you have a loop checking that the only valid answers are in ['y', 'Y', 'n', 'N'] you can test that nothing happens when entering a different value instead.

    In this case we assume a SystemExit is raised when answering 'N':

    @patch('my_module.__get_input')
    def test_invalid_answer_remains_in_loop(self, mock):
        """
        Test nothing's broken when answer is not ['Y', 'y', 'N', 'n']
        """
        with self.assertRaises(SystemExit):
            mock.side_effect = ['k', 'l', 'yeah', 'N']
            # call to our function asking for input
    

提交回复
热议问题