Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog.d/1403.fixed.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fixed cancellation during temporary directory creation leaving the directory behind
while its context manager is retained
2 changes: 1 addition & 1 deletion src/anyio/_core/_tempfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,7 @@ async def __aenter__(self) -> str:
self._tempdir = await to_thread.run_sync(
lambda: tempfile.TemporaryDirectory(**params)
)
return await to_thread.run_sync(self._tempdir.__enter__)
return self._tempdir.name

async def __aexit__(
self,
Expand Down
27 changes: 26 additions & 1 deletion tests/test_tempfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import pathlib
import shutil
import tempfile
from typing import AnyStr
from typing import Any, AnyStr
from unittest.mock import patch

import pytest
Expand All @@ -15,11 +15,13 @@
SpooledTemporaryFile,
TemporaryDirectory,
TemporaryFile,
from_thread,
gettempdir,
gettempdirb,
mkdtemp,
mkstemp,
)
from anyio.lowlevel import checkpoint


class TestTemporaryFile:
Expand Down Expand Up @@ -140,6 +142,29 @@ async def test_readinto1(self) -> None:


class TestTemporaryDirectory:
async def test_cancellation_during_creation(self) -> None:
original = tempfile.TemporaryDirectory
manager = TemporaryDirectory()
paths: list[pathlib.Path] = []

def create(**kwargs: Any) -> tempfile.TemporaryDirectory[str]:
directory = original(**kwargs)
paths.append(pathlib.Path(directory.name))
from_thread.run_sync(scope.cancel)
return directory

with CancelScope() as scope:
with patch("anyio._core._tempfile.tempfile.TemporaryDirectory", create):
async with manager:
await checkpoint()

try:
assert scope.cancelled_caught
assert len(paths) == 1
assert not paths[0].exists()
finally:
await manager.cleanup()

async def test_context_manager(self) -> None:
async with TemporaryDirectory() as td:
td_path = pathlib.Path(td)
Expand Down
Loading