@@ -1360,3 +1360,36 @@ def test_cachedir_tag(pytester: Pytester) -> None:
13601360def test_clioption_with_cacheshow_and_help (pytester : Pytester ) -> None :
13611361 result = pytester .runpytest ("--cache-show" , "--help" )
13621362 assert result .ret == 0
1363+
1364+
1365+ def test_make_cachedir_cleans_up_on_base_exception (
1366+ tmp_path : Path ,
1367+ monkeypatch : MonkeyPatch ,
1368+ ) -> None :
1369+ """Ensure _make_cachedir cleans up the temp directory on BaseException.
1370+
1371+ When a BaseException (like KeyboardInterrupt) is raised during cache
1372+ directory creation, the temporary directory should be cleaned up before
1373+ re-raising the exception.
1374+ """
1375+ from _pytest .cacheprovider import _make_cachedir
1376+
1377+ target = tmp_path / ".pytest_cache"
1378+
1379+ def raise_keyboard_interrupt (self : Path , target : Path ) -> None :
1380+ raise KeyboardInterrupt ("simulated interrupt" )
1381+
1382+ # Patch Path.rename only for the duration of the _make_cachedir call
1383+ with monkeypatch .context () as m :
1384+ m .setattr (Path , "rename" , raise_keyboard_interrupt )
1385+
1386+ # Verify the exception is re-raised
1387+ with pytest .raises (KeyboardInterrupt , match = "simulated interrupt" ):
1388+ _make_cachedir (target )
1389+
1390+ # Verify no temp directories were left behind
1391+ temp_dirs = list (tmp_path .glob ("pytest-cache-files-*" ))
1392+ assert temp_dirs == [], f"Temp directories not cleaned up: { temp_dirs } "
1393+
1394+ # Verify the target directory was not created
1395+ assert not target .exists ()
0 commit comments