jsatt / mock

Automatically exported from code.google.com/p/mock
BSD 2-Clause "Simplified" License
0 stars 0 forks source link

Add __iter__ support for mock_open #213

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
What steps will reproduce the problem?
1.    Want to mock this:
with open(source_file, 'r') as f:             
    for line_num, line_text in enumerate(f):
        print line_text

2.  Tried this:
with patch('__builtin__.open', mock_open(read_data='text'), create=True) as p:

3.  enumerate causes a call to __iter__() which is not handled by the mock_open 
code.

What is the expected output? What do you see instead?

The __iter__ is allowed on the returned file handle

What version of the product are you using? On what operating system?

latest

Please provide any additional information below.

Patch would have mock_open setup handle.__iter__.return_value to a passed in 
parm or if none, possibly a iter(StringIO(read_data)) on the existing read_data 
parm to keep the interface unchanged.

Original issue reported on code.google.com by kram4...@gmail.com on 12 Sep 2013 at 10:34

GoogleCodeExporter commented 8 years ago
I would like to use this as well. I've come up with a patch that implements the 
functionality, along with a unit test for it.

Original comment by wheaties...@gmail.com on 2 Jan 2014 at 8:05

Attachments:

GoogleCodeExporter commented 8 years ago
Apparently there's a better way to make patches with hg :)

Original comment by wheaties...@gmail.com on 2 Jan 2014 at 8:06

Attachments:

GoogleCodeExporter commented 8 years ago
I implemented this using a new optional argument to mock_open called "lines". 
It could be useful to instead just set handle.__iter__.return_value = 
read_data.splitlines(), but that may break existing tests.

Original comment by wheaties...@gmail.com on 2 Jan 2014 at 8:09

GoogleCodeExporter commented 8 years ago
Looks like there are some whitespace issues, but otherwise this LGTM and would 
be helpful in making mock_open usage much cleaner

Original comment by Yasumo...@gmail.com on 18 Apr 2014 at 1:52

GoogleCodeExporter commented 8 years ago
If you take a look at http://bugs.python.org/issue17467, you may want to check 
read data to see if it's a list and patch appropriately vs. adding a new lines 
argument too tho. Since mock's in the std lib, you'll want to move this to 
bugs.python.org if you wanna carry this over the finish line too, I think :)

Original comment by Yasumo...@gmail.com on 18 Apr 2014 at 2:25