Mocking/patching open and readlines in Python

Glasses

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.

Raw
import io
import unittest
from unittest import mock

from mymodule import function_to_test


@mock.patch("builtins.open", 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())

0 comments

Reply

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