This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author xtreak
Recipients cjw296, mariocj89, michael.foord, ron.rothman, xtreak
Date 2018-12-16.08:16:23
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
Internally mock_open implementation uses line based iteration [0] to keep track of the state change between read calls. So readline too ignores the argument. There is issue25690 for an alternate mock_open implementation but the code change is large and adds a lot of features. A simpler approach would be to use StringIO or BytesIO to keep track of state changes and they provide read, readline and readlines API. mock_open docs mentions about using a customized mock for complex cases but I don't know if worthy enough to make this enhancement given the internal implementation change to support the API or to document this behavior. 

Looking further there also seems to be a test case for it [1] which will fail if this is fixed since this returns all characters instead of first 10 like using open().read(10).

    def test_mock_open_read_with_argument(self):
        # At one point calling read with an argument was broken
        # for mocks returned by mock_open
        some_data = 'foo\nbar\nbaz'
        mock = mock_open(read_data=some_data)
        self.assertEqual(mock().read(10), some_data)

$ echo -n 'foo\nbar\nbaz' > /tmp/a.txt
$ ./python.exe
Python 3.8.0a0 (heads/master:f5107dfd42, Dec 16 2018, 13:41:57)
[Clang 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> with open('/tmp/a.txt') as f:
...     actual =
...     actual, len(actual)
('foo\nbar\nba', 10)
>>> with open('/tmp/a.txt') as f:
...     from unittest.mock import mock_open
...     mock = mock_open(
...     mock_data = mock().read(10)
...     mock_data, len(mock_data)
('foo\nbar\nbaz', 11)

Date User Action Args
2018-12-16 08:16:24xtreaksetrecipients: + xtreak, cjw296, michael.foord, mariocj89, ron.rothman
2018-12-16 08:16:24xtreaksetmessageid: <>
2018-12-16 08:16:24xtreaklinkissue31855 messages
2018-12-16 08:16:23xtreakcreate