How to test a function with input call?

后端 未结 6 1070
野性不改
野性不改 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:48

    You should probably mock the built-in input function, you can use the teardown functionality provided by pytest to revert back to the original input function after each test.

    import module  # The module which contains the call to input
    
    class TestClass:
    
        def test_function_1(self):
            # Override the Python built-in input method 
            module.input = lambda: 'some_input'
            # Call the function you would like to test (which uses input)
            output = module.function()  
            assert output == 'expected_output'
    
        def test_function_2(self):
            module.input = lambda: 'some_other_input'
            output = module.function()  
            assert output == 'another_expected_output'        
    
        def teardown_method(self, method):
            # This method is being called after each test case, and it will revert input back to original function
            module.input = input  
    

    A more elegant solution would be to use the mock module together with a with statement. This way you don't need to use teardown and the patched method will only live within the with scope.

    import mock
    import module
    
    def test_function():
        with mock.patch.object(__builtins__, 'input', lambda: 'some_input'):
            assert module.function() == 'expected_output'
    

提交回复
热议问题