我有一个用Python编写的控制台程序。它使用以下命令询问用户问题:
some_input = input('Answer the question:', ...)
如何测试包含对inputusing的调用的函数pytest?我不想强迫测试人员多次输入文本只是为了完成一次测试运行。
input
pytest
您可能应该模拟内置input功能,可以在每次测试后使用teardown提供的功能pytest还原为原始input功能。
teardown
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范围内。
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'