Python 3 - Unittest with multiple inputs and print statement using mocking

后端 未结 1 1283
生来不讨喜
生来不讨喜 2021-01-27 00:19

I\'m studying Python and a few weeks ago I had created a game which the user needs to guess the number between an interval defined by the user himself. Now that I\'m learning ab

相关标签:
1条回答
  • 2021-01-27 01:14

    Your first problem is to get out of the loop. You can do this by adding a side effect to the mocked print function that raises an exception, and ignore that exception in the test. The mocked print can also be used to check for the printed message:

    @patch('randomgame.print')
    @patch('randomgame.input', create=True)
    def test_params_input_1(self, mock_input, mock_print):
        mock_input.side_effect = ['foo']
        mock_print.side_effect = [None, Exception("Break the loop")]
        with self.assertRaises(Exception):
            main()
        mock_print.assert_called_with('You need to enter a number!')
    

    Note that you have to add the side effect to the second print call, as the first one is used for issuing the welcome message.

    The second test would work exactly the same (if written the same way), but for one problem: in your code you catch a generic instead of a specific exception, so that your "break" exception will also be caught. This is generally bad practice, so instead of working around this it is better to catch the specific excpetion that is raised if the conversion to int fails:

    while True:
        try:
            low_param = int(input('Please enter the lower number: '))
            high_param = int(input('Please enter the higher number: '))
            if high_param <= low_param:
                print('No, first the lower number, then the higher number!')
            else:
                break
        except ValueError:  # catch a specific exception
            print('You need to enter a number!')
    

    The same is true for the second try/catch block in your code.

    0 讨论(0)
提交回复
热议问题