|
| 1 | +"""Tests for asyncio/threads.py""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import unittest |
| 5 | + |
| 6 | +from unittest import mock |
| 7 | +from test.test_asyncio import utils as test_utils |
| 8 | + |
| 9 | + |
| 10 | +def tearDownModule(): |
| 11 | + asyncio.set_event_loop_policy(None) |
| 12 | + |
| 13 | + |
| 14 | +class ToThreadTests(test_utils.TestCase): |
| 15 | + def setUp(self): |
| 16 | + super().setUp() |
| 17 | + self.loop = asyncio.new_event_loop() |
| 18 | + asyncio.set_event_loop(self.loop) |
| 19 | + |
| 20 | + def tearDown(self): |
| 21 | + self.loop.run_until_complete( |
| 22 | + self.loop.shutdown_default_executor()) |
| 23 | + self.loop.close() |
| 24 | + asyncio.set_event_loop(None) |
| 25 | + self.loop = None |
| 26 | + super().tearDown() |
| 27 | + |
| 28 | + def test_to_thread(self): |
| 29 | + async def main(): |
| 30 | + return await asyncio.to_thread(sum, [40, 2]) |
| 31 | + |
| 32 | + result = self.loop.run_until_complete(main()) |
| 33 | + self.assertEqual(result, 42) |
| 34 | + |
| 35 | + def test_to_thread_exception(self): |
| 36 | + def raise_runtime(): |
| 37 | + raise RuntimeError("test") |
| 38 | + |
| 39 | + async def main(): |
| 40 | + await asyncio.to_thread(raise_runtime) |
| 41 | + |
| 42 | + with self.assertRaisesRegex(RuntimeError, "test"): |
| 43 | + self.loop.run_until_complete(main()) |
| 44 | + |
| 45 | + def test_to_thread_once(self): |
| 46 | + func = mock.Mock() |
| 47 | + |
| 48 | + async def main(): |
| 49 | + await asyncio.to_thread(func) |
| 50 | + |
| 51 | + self.loop.run_until_complete(main()) |
| 52 | + func.assert_called_once() |
| 53 | + |
| 54 | + def test_to_thread_concurrent(self): |
| 55 | + func = mock.Mock() |
| 56 | + |
| 57 | + async def main(): |
| 58 | + futs = [] |
| 59 | + for _ in range(10): |
| 60 | + fut = asyncio.to_thread(func) |
| 61 | + futs.append(fut) |
| 62 | + await asyncio.gather(*futs) |
| 63 | + |
| 64 | + self.loop.run_until_complete(main()) |
| 65 | + self.assertEqual(func.call_count, 10) |
| 66 | + |
| 67 | + def test_to_thread_args_kwargs(self): |
| 68 | + # Unlike run_in_executor(), to_thread() should directly accept kwargs. |
| 69 | + func = mock.Mock() |
| 70 | + |
| 71 | + async def main(): |
| 72 | + await asyncio.to_thread(func, 'test', something=True) |
| 73 | + |
| 74 | + self.loop.run_until_complete(main()) |
| 75 | + func.assert_called_once_with('test', something=True) |
| 76 | + |
| 77 | + |
| 78 | +if __name__ == "__main__": |
| 79 | + unittest.main() |
0 commit comments