-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add ThreadPoolTaskExecutor for non running loop context
- Loading branch information
Showing
2 changed files
with
123 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
import asyncio | ||
import sys | ||
import threading | ||
import unittest | ||
|
||
from win32more.asyncui import async_callback | ||
|
||
|
||
class TestAsyncui(unittest.TestCase): | ||
@unittest.skipIf(sys.version_info < (3, 12), "eager task is not supported") | ||
def test_task_will_start_in_current_running_loop(self): | ||
@async_callback | ||
async def f(): | ||
trace.append(2) | ||
await asyncio.sleep(0) | ||
trace.append(4) | ||
|
||
async def main(): | ||
trace.append(1) | ||
f() | ||
trace.append(3) | ||
await asyncio.sleep(0) | ||
trace.append(5) | ||
|
||
trace = [] | ||
asyncio.run(main()) | ||
|
||
self.assertEqual(trace, [1, 2, 3, 4, 5]) | ||
|
||
def test_task_will_start_eagerly_and_continue_in_background_thread(self): | ||
@async_callback | ||
async def f(): | ||
asyncio.current_task().add_done_callback(lambda _: event.set()) | ||
trace.append(threading.get_native_id()) # <- caller's thread | ||
await asyncio.sleep(0) | ||
trace.append(threading.get_native_id()) # <- background thread | ||
|
||
trace = [] | ||
event = threading.Event() | ||
f() | ||
self.assertTrue(event.wait(5)) | ||
self.assertEqual(trace[0], threading.get_native_id()) | ||
self.assertNotEqual(trace[1], threading.get_native_id()) | ||
|
||
def test_task_will_start_eagerly_and_dont_start_thread_when_task_was_done(self): | ||
@async_callback | ||
async def f(): | ||
asyncio.current_task().add_done_callback(lambda _: event.set()) | ||
asyncio.current_task().add_done_callback(lambda _: trace.append((2, threading.get_native_id()))) | ||
trace.append((1, threading.get_native_id())) | ||
|
||
trace = [] | ||
event = threading.Event() | ||
f() | ||
self.assertTrue(event.wait(5)) | ||
self.assertEqual(trace[0], (1, threading.get_native_id())) | ||
self.assertEqual(trace[1], (2, threading.get_native_id())) | ||
|
||
|
||
if __name__ == "__main__": | ||
unittest.main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters