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("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