Skip to content

Commit 68684f3

Browse files
Flush AsyncBytesProvider on exit
This updates the __aexit__ on AsyncBytesProvider to flush all written data before closing. This aligns better with the expectations of using this class as a context manager, as it's rather surprising to lose data from an automatic close.
1 parent 8cb6502 commit 68684f3

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

python-packages/smithy-core/smithy_core/aio/types.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -424,4 +424,4 @@ async def __aenter__(self) -> Self:
424424
return self
425425

426426
async def __aexit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
427-
await self.close()
427+
await self.close(flush=True)

python-packages/smithy-core/tests/unit/aio/test_types.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,3 +439,29 @@ async def test_close_with_flush() -> None:
439439
assert result == [b"foo"]
440440
with pytest.raises(SmithyException):
441441
await write_task
442+
443+
444+
async def test_aexit_flushes() -> None:
445+
# Initialize a provider, keeping track of it in the top scope just to make
446+
# sure it doesn't get GC'd
447+
provider = AsyncBytesProvider()
448+
449+
# Use the provider in a context manager. When this exits, it should flush
450+
# and close the provider.
451+
async with provider:
452+
453+
# Write some data to the provider.
454+
await provider.write(b"foo")
455+
456+
# Start the task to read data from the provider and exit. Explictly do
457+
# not await it here because the exit function should pass priority while
458+
# it waits for the queue to drain.
459+
result: list[bytes] = []
460+
drain_task = asyncio.create_task(drain_provider(provider, result))
461+
462+
# The queue should have been read by this point.
463+
assert result == [b"foo"]
464+
465+
# The draining task should be able to complete without errors. When next it
466+
# tries to get a chunk, the provider's iterator will exit.
467+
await drain_task

0 commit comments

Comments
 (0)