Python 3.x 在模块体中模拟输入()
我读了很多资料,但没有任何帮助。我试图使用Python 3.x 在模块体中模拟输入(),python-3.x,unit-testing,testing,input,pytest,Python 3.x,Unit Testing,Testing,Input,Pytest,我读了很多资料,但没有任何帮助。我试图使用pytest编写一些单元测试,但遇到了以下问题:我可以在我想要测试的函数中模拟input()(使用@mock.patch或monkeypatch.setattr来模拟内置.input) 这是我的模块中的代码: def double(): a = input() return int(a) * 2 这是我的测试文件: # @mock.patch('builtins.input', return_value='13') def testin
pytest
编写一些单元测试,但遇到了以下问题:我可以在我想要测试的函数中模拟input()
(使用@mock.patch
或monkeypatch.setattr
来模拟内置.input
)
这是我的模块中的代码:
def double():
a = input()
return int(a) * 2
这是我的测试文件:
# @mock.patch('builtins.input', return_value='13')
def testing(monkeypatch):
monkeypatch.setattr('builtins.input', lambda: "13")
assert double() == 26
但是当我的模块主体中有input()
时,我会得到一个错误-OSError:pytest:在捕获输出时从stdin读取!考虑使用-S.
例如:
def double(a):
return int(a) * 2
x = input()
我可以通过在
x=input()
之前添加来解决这个问题,但我很好奇是否可以用其他方法解决这个问题。提前感谢您的帮助 模块级的代码将在导入时执行,因此将在测试之前执行x=input()。因此,蒙基修补将来得太迟,无法避免错误。例如,您可以在测试函数中移动模块导入,首先monkeypatch.setattr(…)
,然后从mymod导入double,然后断言double()==26
,但这也是一个笨拙的解决方案。最好是避免在模块级执行代码。非常感谢您的详细回答!模块级的代码将在导入时执行,因此将在测试之前执行x=input()。因此,蒙基修补将来得太迟,无法避免错误。例如,您可以在测试函数中移动模块导入,首先monkeypatch.setattr(…)
,然后从mymod导入double,然后断言double()==26
,但这也是一个笨拙的解决方案。最好是避免在模块级执行代码。非常感谢您的详细回答!