def simple_read_write():
with open("file", "r") as f:
data = json.load(f)
data["change"] = "some content"
with open("file", "w") as f:
json.dump(data, f)
如何模拟此场景,其中以读取模式打开同一文件并读取其内容。然后更改内容后,再次以写入模式打开同一文件以更新内容。
我在使用
mock_open
模拟这个场景时遇到了障碍。
我为测试上述代码而实现的功能如下。它给了我断言错误,并且我无法正确模拟同一文件的读写场景。
class Example(unittest.TestCase):
@patch("builtins.open", new_callable=mock_open, read_data=json.dumps({"change":"old data"}))
@patch("builtins.open", new_callable=mock_open)
def TestSimpleReadWrite(self, write_mock, read_mock):
SampleFile.simple_read_write()
read_mock.assert_called_with("file", "r")
write_mock.assert_called_with("file", "w")
write_mock().write.assert_called_with(json.dumps({"change": "some content"}))
我终于找到了解决上述问题的方法。
import unittest
from unittest.mock import patch, call
import check
class Example(unittest.TestCase):
@patch("json.load")
@patch("json.dump")
def test_simple_rtead_write(self, jdump_mock, jload_mock):
with patch("builtins.open") as open_mock:
jload_mock.return_value = {"change": "previous content", "prev": "yes"}
jdump_mock.side_effect = [True]
ret = check.simple_read_write()
self.assertEqual(ret["change"], "some content")
assert call("file", "r") in open_mock.call_args_list and \
call("file", "w") in open_mock.call_args_list
if __name__ == "__main__":
unittest.main()
我只需模拟
json.load
和 json.dump
并分别使用 return_value
和 side_effect
。
之前,我犯了一个错误,添加了两个builtins.open
而不是一个。由于同一个 builtins.open
模拟将包含对 read
和 write
的调用,我只需要使用 call
来检查 read
和 write
是否已执行。