Mocking/patching open and readlines in Python


I often want to mock reading from a file when writing unit tests in Python, and I always struggle to find the right solution again. So I'm posting it on my own blog in the hope of finding it later 🤣 My solution is to return a StringIO object from open.

import io
import unittest
from unittest import mock

from mymodule import function_to_test

@mock.patch("", create=True)
class FooTest(unittest.TestCase):
    def test_foo(self, _open):
        fake_file = io.StringIO("foo\nbar\n")
        _open.return_value = fake_file
        self.assertEqual(["foo", "bar"], function_to_test())



Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.
DjangoPythonBitcoinTuxDebianHTML5 badgeSaltStackUpset confused bugMoneyHackerUpset confused bugX.OrggitFirefoxWindowMakerBashIs it worth the time?i3 window managerWagtailContainerIrssiNginxSilenceUse a maskWorldInternet securityPianoFontGnuPGThunderbirdJenkinshome-assistant-logo