[Python-Dev] Review of Pull Request 5974 please

Anthony Flury anthony.flury at btinternet.com
Sun Apr 29 07:39:18 EDT 2018


All,

Can someone please review Pull Request 5974 
<https://github.com/python/cpython/pull/5974> on Python3.8 - the Pull 
request was submitted on 4th March - this pull request is associated 
with bpo-32933 <https://bugs.python.org/issue32933>

To summarize the point of this pull request:

It fixes a bug of omission within mock_open 
<https://docs.python.org/3/library/unittest.mock.html?highlight=mock_open#unittest.mock.mock_open> 
(part of unittest.mock)

The functionality of mock_open enables the test code to mock a file 
being opened with some data which can be read. Importantly, mock_open 
has a read_data attrribute which can be used to specify the data to read 
from the file.

The mocked file which is opened correctly supports file.read(), 
file.readlines(), file.readline(). These all make use of the read_data 
as expected, and the mocked file also supports being opened as a context 
manager.

But the mock_open file does not support iteration  - so pythonic code 
which uses a for loop to iterate around the file content will only ever 
appear to iterate around an empty file, regardless of the read_data 
attribute when the mock_open is created

So non-pythonic methods to iterate around the file contents - such as 
this :

     data = opened_file.readlines()
     for line in data:
         process_line(line)

and this :

        line = opened_file.readline()
        while line:
                process_line(line)
                line = opened_file.readline()

Can both be tested with the mocked file containing simulated data (using 
the read_data attribute) as expected.

But this code (which by any standard is the 'correct' way to iterate 
around the file content of a text file):

     for line in opened_file:
         process_line(line)

Will only ever appear to iterate around an empty file when tested using 
mock_open.

I would like this to be reviewed so it can be back-ported into Python3.7 
and 3.6 if at all possible. I know that the bug has existed since the 
original version of mock_open, but it does seem strange that code under 
test which uses a pythonic code structure can't be fully tested fully 
using the standard library.

-- 
Anthony Flury
email : *Anthony.flury at btinternet.com*
Twitter : *@TonyFlury <https://twitter.com/TonyFlury/>*



More information about the Python-Dev mailing list