Using unittest.mock to patch input() in Python 3

后端 未结 4 1278
说谎
说谎 2020-12-06 05:03

How do you use the @patch decorator to patch the built-in input() function?

For example, here\'s a function in question.py that I\'d like to test, which contains a c

4条回答
  •  忘掉有多难
    2020-12-06 06:05

    Or use Mock's return_value attribute. I couldn't get it to work as a decorator, but here's how to do it with a context manager:

    >>> import unittest.mock
    >>> def test_input_mocking():
    ...     with unittest.mock.patch('builtins.input', return_value='y'):
    ...         assert input() == 'y'
    ...
    >>> def test_input_mocking():
    ...     with unittest.mock.patch('builtins.input', return_value='y'):
    ...         assert input() == 'y'
    ...         print('we got here, so the ad hoc test succeeded')
    ...
    >>> test_input_mocking()
    we got here, so the ad hoc test succeeded
    >>>
    

提交回复
热议问题