import unittest
from unittest.mock import patch
import module_under_test
class MyTestCase(unittest.TestCase):
def setUp(self):
# raw_input is untouched before test
assert module_under_test.raw_input is __builtins__.raw_input
def test_using_with(self):
input_data = "123"
expected = int(input_data)
with patch.object(module_under_test, "raw_input", create=True,
return_value=expected):
# create=True is needed as raw_input is not in the globals of
# module_under_test, but actually found in __builtins__ .
actual = module_under_test.function()
self.assertEqual(expected, actual)
@patch.object(module_under_test, "raw_input", create=True)
def test_using_decorator(self, raw_input):
raw_input.return_value = input_data = "123"
expected = int(input_data)
actual = module_under_test.function()
self.assertEqual(expected, actual)
def tearDown(self):
# raw input is restored after test
assert module_under_test.raw_input is __builtins__.raw_input
if __name__ == "__main__":
unittest.main()
# where module_under_test.function is:
def function():
return int(raw_input("prompt> "))
先前的答案--替换sys.stdin
我想系统模块可能就是你要找的。
你可以这样做
import sys
# save actual stdin in case we need it again later
stdin = sys.stdin
sys.stdin = open('simulatedInput.txt','r')
# or whatever else you want to provide the input eg. StringIO
简而言之,答案是monkey patch
raw_input()
。在How to display the redirected stdin in Python?的答案中有一些很好的例子
下面是一个简单的例子,使用一个
lambda
来丢弃提示并返回我们想要的内容。测试中的系统
测试用例:
用
StringIO
的实例替换sys.stdin
,并用通过sys.stdin
返回的数据加载StringIO
实例。而且,sys.__stdin__
包含原始的sys.stdin
对象,因此在测试后恢复sys.stdin
就如同sys.stdin = sys.__stdin__
一样简单。Fudge是一个很棒的python模拟模块,有方便的装饰器来为您进行这样的修补,并具有自动清理功能。你应该去看看。
更新——使用unittest.mock.patch
自从python3.3以来,
unittest
有了一个新的子模块mock,它可以完成您需要做的事情。对于那些使用python 2.6或更高版本的用户,可以找到mock
的后台端口here。先前的答案--替换sys.stdin
我想系统模块可能就是你要找的。
你可以这样做
无论何时调用,原始输入都将从simulatedInput.txt中读取。如果模拟输入的内容是
然后第一次调用raw_input将返回“hello”,第二次调用“bob”,第三次调用将抛出一个eoferor,因为没有更多的文本可供阅读。
相关问题 更多 >
编程相关推荐