summaryrefslogtreecommitdiffstats
path: root/Lib/test/test_asyncio/test_threads.py
blob: 99a00f21832f3e4cf1854d07cf7e11e43dcb386f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""Tests for asyncio/threads.py"""

import asyncio
import unittest

from unittest import mock
from test.test_asyncio import utils as test_utils


def tearDownModule():
    asyncio.set_event_loop_policy(None)


class ToThreadTests(test_utils.TestCase):
    def setUp(self):
        super().setUp()
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)

    def tearDown(self):
        self.loop.run_until_complete(
            self.loop.shutdown_default_executor())
        self.loop.close()
        asyncio.set_event_loop(None)
        self.loop = None
        super().tearDown()

    def test_to_thread(self):
        async def main():
            return await asyncio.to_thread(sum, [40, 2])

        result = self.loop.run_until_complete(main())
        self.assertEqual(result, 42)

    def test_to_thread_exception(self):
        def raise_runtime():
            raise RuntimeError("test")

        async def main():
            await asyncio.to_thread(raise_runtime)

        with self.assertRaisesRegex(RuntimeError, "test"):
            self.loop.run_until_complete(main())

    def test_to_thread_once(self):
        func = mock.Mock()

        async def main():
            await asyncio.to_thread(func)

        self.loop.run_until_complete(main())
        func.assert_called_once()

    def test_to_thread_concurrent(self):
        func = mock.Mock()

        async def main():
            futs = []
            for _ in range(10):
                fut = asyncio.to_thread(func)
                futs.append(fut)
            await asyncio.gather(*futs)

        self.loop.run_until_complete(main())
        self.assertEqual(func.call_count, 10)

    def test_to_thread_args_kwargs(self):
        # Unlike run_in_executor(), to_thread() should directly accept kwargs.
        func = mock.Mock()

        async def main():
            await asyncio.to_thread(func, 'test', something=True)

        self.loop.run_until_complete(main())
        func.assert_called_once_with('test', something=True)


if __name__ == "__main__":
    unittest.main()