我有一个用Python编写的控制台程序.它使用以下命令询问用户问题:
some_input = input('Answer the question:', ...)
如何使用pytest
测试包含输入调用的函数?
我不想强迫测试人员多次输入文本只完成一次测试运行.
解决方法:
您应该模拟内置的input
功能,您可以使用pytest
提供的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范围内使用.
import mock
import module
def test_function():
with mock.patch.object(__builtins__, 'input', lambda: 'some_input'):
assert module.function() == 'expected_output'
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。