Skip to content

Commit

Permalink
gh-99941: Ensure that asyncio.Protocol.data_received receives immutab…
Browse files Browse the repository at this point in the history
…le bytes (#100053)
  • Loading branch information
DarioDaF committed Dec 10, 2022
1 parent d5f8a2b commit 1bb68ba
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 4 deletions.
3 changes: 2 additions & 1 deletion Lib/asyncio/proactor_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,8 @@ def _loop_reading(self, fut=None):
# we got end-of-file so no need to reschedule a new read
return

data = self._data[:length]
# It's a new slice so make it immutable so protocols upstream don't have problems
data = bytes(memoryview(self._data)[:length])
else:
# the future will be replaced by next proactor.recv call
fut.cancel()
Expand Down
4 changes: 2 additions & 2 deletions Lib/asyncio/streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -688,7 +688,7 @@ async def read(self, n=-1):
await self._wait_for_data('read')

# This will work right even if buffer is less than n bytes
data = bytes(self._buffer[:n])
data = bytes(memoryview(self._buffer)[:n])
del self._buffer[:n]

self._maybe_resume_transport()
Expand Down Expand Up @@ -730,7 +730,7 @@ async def readexactly(self, n):
data = bytes(self._buffer)
self._buffer.clear()
else:
data = bytes(self._buffer[:n])
data = bytes(memoryview(self._buffer)[:n])
del self._buffer[:n]
self._maybe_resume_transport()
return data
Expand Down
5 changes: 4 additions & 1 deletion Lib/test/test_asyncio/test_proactor_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,10 @@ def test_loop_reading_data(self):
called_buf = bytearray(self.buffer_size)
called_buf[:len(buf)] = buf
self.loop._proactor.recv_into.assert_called_with(self.sock, called_buf)
self.protocol.data_received.assert_called_with(bytearray(buf))
self.protocol.data_received.assert_called_with(buf)
# assert_called_with maps bytearray and bytes to the same thing so check manually
# regression test for https://github.com/python/cpython/issues/99941
self.assertIsInstance(self.protocol.data_received.call_args.args[0], bytes)

@unittest.skipIf(sys.flags.optimize, "Assertions are disabled in optimized mode")
def test_loop_reading_no_data(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Ensure that :func:`asyncio.Protocol.data_received` receives an immutable
:class:`bytes` object (as documented), instead of :class:`bytearray`.

0 comments on commit 1bb68ba

Please sign in to comment.