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:

class MyTestCase(testtools.TestCase):

    @mock.patch("open", create=True)
    def test_some(self, mock_open):
        mock_open.side_effect = [

        self.assertEqual("Data1", some("fileA"))

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

Read More