The simplest way in python to mock open() during unit testing

I believe that the most of python developers are familiar with pretty mock framework. It’s one of the simplest way to avoid unit testing of not interesting parts of your code: such like DB, files, API of other services, some heavy libs like libvirt and so on..

Unfortunately, there is one unclear place (at least for me)  how to mock open() properly especially in case where when with open() in used in code.

I spend a bit of time to resolve this problem and here is the code snippet:

import testtools
import mock


def some(file_path):

    with open(file_path) as f:
        return f.read()


class MyTestCase(testtools.TestCase):

    @mock.patch("open", create=True)
    def test_some(self, mock_open):
        mock_open.side_effect = [
            mock.mock_open(read_data="Data1").return_value,
            mock.mock_open(read_data="Data2").return_value
        ]

        self.assertEqual("Data1", some("fileA"))
        mock_open.assert_called_once_with("fileA")
        mock_open.reset_mock()

        self.assertEqual("Data2", some("fileB"))
        mock_open.assert_called_once_with("fileB")

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA Image

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>