2023/03/21

Mock Open Write On Python

ๅœจ python ็š„ๆธฌ่ฉฆไธญ,ๆœ‰ๆ™‚ๅ€™ mock ๅช่ฆ mock a.b.c ๅฐฑๅฏไปฅๆˆๅŠŸ,ไฝ†ๆˆ‘ๅ€‘ไฝฟ็”จไบ† with ็š„ๆƒ…ๆณไธ‹,ๅฐฑๅฟ…้ ˆๅ€ŸๅŠฉ __enter__ ้€™ๅ€‹้ญ”่ก“ๆ–นๆณ•ไพ†ๆธฌ่ฉฆไบ†,ๆˆ‘ๅ€‘ไป‹็ดนๅ…ฉ็จฎๅฏซๆณ•。

my_open.py

def write(path, context):
    with open(path) as f:
        f.write(context)

test_my_open.py

import unittest
import my_open

from unittest.mock import mock_open, patch


class MyTestCase(unittest.TestCase):
    def test_my_open_1(self):
        with patch('builtins.open', mock_open()) as o:
            path = '/tmp/test.txt'
            context = 'hello'
            my_open.write(path, context)

            o.assert_called_once_with(path)
            o().write.assert_called_once_with(context)

    @patch('builtins.open')
    def test_my_open_2(self, mock_o: mock_open):
        path = '/tmp/test.txt'
        context = 'hello'
        my_open.write(path, context)

        mock_o.assert_called_once_with(path)
        handle = mock_o.return_value.__enter__.return_value
        handle.write.assert_called_once_with(context)


if __name__ == '__main__':
    unittest.main()