"""A cancelled upload must not release memory/file leases while its thread runs.""" import asyncio import tempfile import threading import unittest from src.offload import complete_thread class CancellationTest(unittest.IsolatedAsyncioTestCase): async def test_file_and_permit_live_until_worker_finishes(self): entered, finish = threading.Event(), threading.Event() semaphore = asyncio.Semaphore(1) observed = [] def blocking(file): entered.set() if not finish.wait(3): raise AssertionError('Test failed to release blocking worker') observed.append(file.closed) file.write(b'still owned') async def request(): async with semaphore: with tempfile.TemporaryFile() as file: await complete_thread(blocking, file) request_task = asyncio.create_task(request()) try: self.assertTrue(await asyncio.to_thread(entered.wait, 3)) request_task.cancel() await asyncio.sleep(.02) self.assertTrue(semaphore.locked()) self.assertFalse(request_task.done()) finally: finish.set() with self.assertRaises(asyncio.CancelledError): await request_task self.assertEqual(observed, [False]) self.assertFalse(semaphore.locked()) if __name__ == '__main__': unittest.main()