Sau khi đọc bài viết này: How do I mock an open used in a with statement (using the Mock framework in Python)?Python Mock - Mocking vài mở
Tôi có thể thử chức năng mở trong python sử dụng:
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)
Nó hoạt động tốt khi thử nghiệm phương pháp của tôi sử dụng một tuyên bố mở. Đây là phương pháp được thử nghiệm của tôi:
def diff(self, a, b):
with open(a, 'r') as old:
with open(b, 'r') as new:
oldtext = old.read()
newtext = new.read()
Giá trị của oldtext và newtext đều giống nhau ('text1' ở đây).
Tôi muốn có 'text1' cho oldtext và 'text2' cho newtext.
Tôi làm cách nào để thực hiện việc này?