【发布时间】:2012-03-10 02:02:10
【问题描述】:
读完后:How do I mock an open used in a with statement (using the Mock framework in Python)?
我可以使用以下方法在 python 中模拟 open 函数:
with patch(open_name, create=True) as mock_open:
mock_open.return_value = MagicMock(spec=file)
m_file = mock_open.return_value.__enter__.return_value
m_file.read.return_value = 'text1'
diffman = Diffman()
diffman.diff(path1, path2)
当我测试的方法使用一个 open 语句时,它运行良好。这是我测试过的方法:
def diff(self, a, b):
with open(a, 'r') as old:
with open(b, 'r') as new:
oldtext = old.read()
newtext = new.read()
oldtext 和 newtext 的值是一样的(这里是'text1')。
我希望旧文本使用“text1”,新文本使用“text2”。
我该怎么做?
【问题讨论】:
标签: python file-io mocking with-statement