# HG changeset patch # User Josh VanderLinden # Date 1388693013 25200 # Thu Jan 02 13:03:33 2014 -0700 # Branch fix213 # Node ID 46ea7edc2c5405d9090eade251f5283d11b36d3c # Parent d356250e275daa62b2972521885f42fa639341e6 #213 - Allow mock_open to use __iter__ diff -r d356250e275d -r 46ea7edc2c54 mock.py --- a/mock.py Tue Apr 09 14:53:33 2013 +0100 +++ b/mock.py Thu Jan 02 13:03:33 2014 -0700 @@ -2335,7 +2335,7 @@ file_spec = None -def mock_open(mock=None, read_data=''): +def mock_open(mock=None, read_data='', lines=None): """ A helper function to create a mock to replace the use of `open`. It works for `open` called directly or used as a context manager. @@ -2364,6 +2364,9 @@ handle.__enter__.return_value = handle handle.read.return_value = read_data + if lines is not None: + handle.__iter__.return_value = iter(lines) + mock.return_value = handle return mock diff -r d356250e275d -r 46ea7edc2c54 tests/_testwith.py --- a/tests/_testwith.py Tue Apr 09 14:53:33 2013 +0100 +++ b/tests/_testwith.py Thu Jan 02 13:03:33 2014 -0700 @@ -176,6 +176,16 @@ self.assertEqual(result, 'foo') + def test_iter(self): + mock = mock_open(lines=['line 1', 'line 2', 'line 3']) + with patch('%s.open' % __name__, mock, create=True): + with open('bar') as fh: + res = [] + for line in fh: + res.insert(0, line) + + self.assertEqual(res, ['line 3', 'line 2', 'line 1']) + if __name__ == '__main__': unittest2.main()