您可能应该模拟内置
input功能,可以在每次测试后使用
teardown提供的功能
pytest还原为原始
input功能。
import module # The module which contains the call to inputclass 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模块与一起使用
withstatement。这样,您就不需要使用拆解,并且修补的方法只会存在于
with范围内。
import mockimport moduledef test_function(): with mock.patch.object(__builtins__, 'input', lambda: 'some_input'): assert module.function() == 'expected_output'



