Skip to content

Commit c97e497

Browse files
improve test
1 parent 787c9fc commit c97e497

File tree

1 file changed

+16
-12
lines changed

1 file changed

+16
-12
lines changed

Lib/test/test_asyncio/test_tasks.py

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3681,24 +3681,28 @@ def task_factory(loop, coro):
36813681
self.assertEqual(context['exception'], exc_context.exception)
36823682

36833683
def test_run_coroutine_threadsafe_and_cancel(self):
3684+
task = None
3685+
thread_future = None
3686+
# Use a custom task factory to capture the created Task
3687+
def task_factory(loop, coro):
3688+
nonlocal task
3689+
task = asyncio.Task(coro, loop=loop)
3690+
return task
3691+
3692+
self.addCleanup(self.loop.set_task_factory,
3693+
self.loop.get_task_factory())
3694+
36843695
async def target():
3685-
# self.loop.run_in_executor(None, _in_another_thread)
3686-
thread_future = asyncio.run_coroutine_threadsafe(self.add(1, 2), self.loop)
3696+
nonlocal thread_future
3697+
self.loop.set_task_factory(task_factory)
3698+
thread_future = asyncio.run_coroutine_threadsafe(asyncio.sleep(10), self.loop)
36873699
await asyncio.sleep(0)
36883700

36893701
thread_future.cancel()
36903702

3691-
await asyncio.sleep(0)
3692-
36933703
self.loop.run_until_complete(target())
3694-
3695-
# For windows, it's likely to see asyncio.proactor_events
3696-
# .BaseProactorEventLoop._loop_self_reading as ready task
3697-
# We should filter it out.
3698-
ready_tasks = [
3699-
i for i in self.loop._ready
3700-
if i._callback.__name__ != "_loop_self_reading"]
3701-
self.assertEqual(0, len(ready_tasks))
3704+
self.assertTrue(task.cancelled())
3705+
self.assertTrue(thread_future.cancelled())
37023706

37033707

37043708
class SleepTests(test_utils.TestCase):

0 commit comments

Comments
 (0)