如何使用输入调用测试功能?

发布于 2021-01-29 19:20:23

我有一个用Python编写的控制台程序。它使用以下命令询问用户问题:

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

如何测试包含对inputusing的调用的函数pytest?我不想强迫测试人员多次输入文本只是为了完成一次测试运行。

关注者
0
被浏览
65
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您可能应该模拟内置input功能,可以在每次测试后使用teardown提供的功能pytest还原为原始input功能。

    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
    

    更好的解决方案是将mock模块与一起使用with statement。这样,您就不需要使用拆解,并且修补的方法只会存在于with范围内。

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看