summaryrefslogtreecommitdiff
path: root/tests/test_thread.py
blob: c41eeaada634d5f8a97a1fb4794c6932588f603d (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import eventlet
import tests
threading = eventlet.patcher.original('threading')
try:
    import asyncio
except ImportError:
    import trollius as asyncio

try:
    get_ident = threading.get_ident   # Python 3
except AttributeError:
    get_ident = threading._get_ident   # Python 2

class ThreadTests(tests.TestCase):
    def test_ident(self):
        result = {'ident': None}

        def work():
            result['ident'] = get_ident()

        fut = self.loop.run_in_executor(None, work)
        self.loop.run_until_complete(fut)

        # ensure that work() was executed in a different thread
        work_ident = result['ident']
        self.assertIsNotNone(work_ident)
        self.assertNotEqual(work_ident, get_ident())

    def test_run_twice(self):
        result = []

        def work():
            result.append("run")

        fut = self.loop.run_in_executor(None, work)
        self.loop.run_until_complete(fut)
        self.assertEqual(result, ["run"])

        # ensure that run_in_executor() can be called twice
        fut = self.loop.run_in_executor(None, work)
        self.loop.run_until_complete(fut)
        self.assertEqual(result, ["run", "run"])

    def test_policy(self):
        result = {'loop': 'not set'}   # sentinel, different than None

        def work():
            try:
                result['loop'] = asyncio.get_event_loop()
            except AssertionError as exc:
                result['loop'] = exc

        # get_event_loop() must return None in a different thread
        fut = self.loop.run_in_executor(None, work)
        self.loop.run_until_complete(fut)
        self.assertIsInstance(result['loop'], AssertionError)

    def test_run_in_thread(self):
        class LoopThread(threading.Thread):
            def __init__(self, event):
                super(LoopThread, self).__init__()
                self.loop = None
                self.event = event

            def run(self):
                self.loop = asyncio.new_event_loop()
                try:
                    self.loop.set_debug(True)
                    asyncio.set_event_loop(self.loop)

                    self.event.set()
                    self.loop.run_forever()
                finally:
                    self.loop.close()
                    asyncio.set_event_loop(None)

        result = []

        # start an event loop in a thread
        event = threading.Event()
        thread = LoopThread(event)
        thread.start()
        event.wait()
        loop = thread.loop

        def func(loop):
            result.append(threading.current_thread().ident)
            loop.stop()

        # FIXME: call_soon() must raise an exception if if the main thread
        # has no event loop, bugs.python.org/issue22926
        #self.loop.close()
        #asyncio.set_event_loop(None)
        # call_soon() must fail when called from the wrong thread
        self.assertRaises(RuntimeError, loop.call_soon, func, loop)

        # call func() in a different thread using the event loop
        tid = thread.ident
        loop.call_soon_threadsafe(func, loop)

        # stop the event loop
        thread.join()
        self.assertEqual(result, [tid])


if __name__ == '__main__':
    import unittest
    unittest.main()