Debian Codegraph @

Lib/test/test_asyncio/test_threads.py

raw
1 """Tests for asyncio/threads.py"""
2
3 import asyncio
4 import unittest
5
6 from contextvars import ContextVar
7 from unittest import mock
8
9
10 def tearDownModule():
11 asyncio.events._set_event_loop_policy(None)
12
13
14 class ToThreadTests(unittest.IsolatedAsyncioTestCase):
15 async def test_to_thread(self):
16 result = await asyncio.to_thread(sum, [40, 2])
17 self.assertEqual(result, 42)
18
19 async def test_to_thread_exception(self):
20 def raise_runtime():
21 raise RuntimeError("test")
22
23 with self.assertRaisesRegex(RuntimeError, "test"):
24 await asyncio.to_thread(raise_runtime)
25
26 async def test_to_thread_once(self):
27 func = mock.Mock()
28
29 await asyncio.to_thread(func)
30 func.assert_called_once()
31
32 async def test_to_thread_concurrent(self):
33 calls = []
34 def func():
35 calls.append(1)
36
37 futs = []
38 for _ in range(10):
39 fut = asyncio.to_thread(func)
40 futs.append(fut)
41 await asyncio.gather(*futs)
42
43 self.assertEqual(sum(calls), 10)
44
45 async def test_to_thread_args_kwargs(self):
46 # Unlike run_in_executor(), to_thread() should directly accept kwargs.
47 func = mock.Mock()
48
49 await asyncio.to_thread(func, 'test', something=True)
50
51 func.assert_called_once_with('test', something=True)
52
53 async def test_to_thread_contextvars(self):
54 test_ctx = ContextVar('test_ctx')
55
56 def get_ctx():
57 return test_ctx.get()
58
59 test_ctx.set('parrot')
60 result = await asyncio.to_thread(get_ctx)
61
62 self.assertEqual(result, 'parrot')
63
64
65 if __name__ == "__main__":
66 unittest.main()