Issue #23004: mock_open() now reads binary data correctly when the type of read_data is bytes.
Initial patch by Aaron Hill.
diff --git a/NEWS b/NEWS
index f3f0086..9c0ff3c 100644
--- a/NEWS
+++ b/NEWS
@@ -1,6 +1,9 @@
Library
-------
+- Issue #23004: mock_open() now reads binary data correctly when the type of
+ read_data is bytes. Initial patch by Aaron Hill.
+
- Issue #21750: mock_open.read_data can now be read from each instance, as it
could in Python 3.3.
diff --git a/mock/mock.py b/mock/mock.py
index d2c469b..358537d 100644
--- a/mock/mock.py
+++ b/mock/mock.py
@@ -2442,9 +2442,10 @@
# Helper for mock_open:
# Retrieve lines from read_data via a generator so that separate calls to
# readline, read, and readlines are properly interleaved
- data_as_list = ['{0}\n'.format(l) for l in read_data.split('\n')]
+ sep = b'\n' if isinstance(read_data, bytes) else '\n'
+ data_as_list = [l + sep for l in read_data.split(sep)]
- if data_as_list[-1] == '\n':
+ if data_as_list[-1] == sep:
# If the last line ended in a newline, the list comprehension will have an
# extra entry that's just a newline. Remove this.
data_as_list = data_as_list[:-1]
@@ -2477,7 +2478,7 @@
def _read_side_effect(*args, **kwargs):
if handle.read.return_value is not None:
return handle.read.return_value
- return ''.join(_state[0])
+ return type(read_data)().join(_state[0])
def _readline_side_effect():
if handle.readline.return_value is not None:
diff --git a/mock/tests/testwith.py b/mock/tests/testwith.py
index b9cfab1..aa7812b 100644
--- a/mock/tests/testwith.py
+++ b/mock/tests/testwith.py
@@ -229,6 +229,34 @@
self.assertEqual(result, ['foo\n', 'bar\n', 'baz'])
+ def test_read_bytes(self):
+ mock = mock_open(read_data=b'\xc6')
+ with patch('%s.open' % __name__, mock, create=True):
+ with open('abc', 'rb') as f:
+ result = f.read()
+ self.assertEqual(result, b'\xc6')
+
+
+ def test_readline_bytes(self):
+ m = mock_open(read_data=b'abc\ndef\nghi\n')
+ with patch('%s.open' % __name__, m, create=True):
+ with open('abc', 'rb') as f:
+ line1 = f.readline()
+ line2 = f.readline()
+ line3 = f.readline()
+ self.assertEqual(line1, b'abc\n')
+ self.assertEqual(line2, b'def\n')
+ self.assertEqual(line3, b'ghi\n')
+
+
+ def test_readlines_bytes(self):
+ m = mock_open(read_data=b'abc\ndef\nghi\n')
+ with patch('%s.open' % __name__, m, create=True):
+ with open('abc', 'rb') as f:
+ result = f.readlines()
+ self.assertEqual(result, [b'abc\n', b'def\n', b'ghi\n'])
+
+
def test_mock_open_read_with_argument(self):
# At one point calling read with an argument was broken
# for mocks returned by mock_open