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

后端 未结 4 1152
说谎
说谎 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 05:56

    For Python 3.8 the accepted answer didn't work for me. It didn't like the positional parameter even though my code was actually utilizing it. What worked for me was simply:

    @patch('builtins.input')
    

    Not sure if I am doing something wrong, but here you are.

    0 讨论(0)
  • 2020-12-06 06:04

    For Python 2.x:

    @patch('__builtin__.input')
    

    worked for me.

    0 讨论(0)
  • 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
    >>>
    
    0 讨论(0)
  • 2020-12-06 06:08

    __builtin__ module is renamed to builtins in Python 3. Replace as follow:

    @patch('builtins.input', lambda *args: 'y')
    

    UPDATE

    input has an optional parameter. updated the code to accept the optional parameter.

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