Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -2364,6 +2364,12 @@ def _readline_side_effect():
while True:
yield type(read_data)()

def _iter_side_effect():
if handle.readline.return_value is not None:
while True:
yield handle.readline.return_value
for line in _state[0]:
yield line

global file_spec
if file_spec is None:
Expand All @@ -2388,6 +2394,8 @@ def _readline_side_effect():
handle.readline.side_effect = _state[1]
handle.readlines.side_effect = _readlines_side_effect

handle.__iter__.side_effect = _iter_side_effect

def reset_data(*args, **kwargs):
_state[0] = _iterate_read_data(read_data)
if handle.readline.side_effect == _state[1]:
Expand Down
8 changes: 8 additions & 0 deletions Lib/unittest/test/testmock/testmock.py
Original file line number Diff line number Diff line change
Expand Up @@ -1450,6 +1450,14 @@ def test_mock_open_reuse_issue_21750(self):
f2_data = f2.read()
self.assertEqual(f1_data, f2_data)

def test_mock_open_dunder_iter_issue_32933(self):
mocked_open = mock.mock_open(read_data='Remarkable Bird\nThe Norwegian Blue\nBeautiful Plumage')
f1 = mocked_open('a-name')
lines = [line for line in f1]
self.assertEqual(lines[0], 'Remarkable Bird\n')
self.assertEqual(lines[1], 'The Norwegian Blue\n')
self.assertEqual(lines[2], 'Beautiful Plumage')

def test_mock_open_write(self):
# Test exception in file writing write()
mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV'))
Expand Down
10 changes: 10 additions & 0 deletions Lib/unittest/test/testmock/testwith.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,16 @@ def test_readlines_data(self):

self.assertEqual(result, ['foo\n', 'bar\n', 'baz'])

def test_dunder_iter_data(self):
# Check that dunder_iter will return all the lines from the fake file
# Added to test Issue 32933
mock = mock_open(read_data='foo\nbar\nbaz\n')
with patch('%s.open' % __name__, mock, create=True):
h = open('bar')
lines = [l for l in h]
self.assertEqual(lines[0], 'foo\n')
self.assertEqual(lines[1], 'bar\n')
self.assertEqual(lines[2], 'baz\n')

def test_read_bytes(self):
mock = mock_open(read_data=b'\xc6')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
unittest.mock.mock_open helper function supports iterator protocol. Patch by
Tony Flury