1import salt.ext.tornado.gen
2import salt.ext.tornado.testing
3import salt.utils.asynchronous as asynchronous
4from salt.ext.tornado.testing import AsyncTestCase
5
6
7class HelperA:
8
9    async_methods = [
10        "sleep",
11    ]
12
13    def __init__(self, io_loop=None):
14        pass
15
16    @salt.ext.tornado.gen.coroutine
17    def sleep(self):
18        yield salt.ext.tornado.gen.sleep(0.1)
19        raise salt.ext.tornado.gen.Return(True)
20
21
22class HelperB:
23
24    async_methods = [
25        "sleep",
26    ]
27
28    def __init__(self, a=None, io_loop=None):
29        if a is None:
30            a = asynchronous.SyncWrapper(HelperA)
31        self.a = a
32
33    @salt.ext.tornado.gen.coroutine
34    def sleep(self):
35        yield salt.ext.tornado.gen.sleep(0.1)
36        self.a.sleep()
37        raise salt.ext.tornado.gen.Return(False)
38
39
40class TestSyncWrapper(AsyncTestCase):
41    @salt.ext.tornado.testing.gen_test
42    def test_helpers(self):
43        """
44        Test that the helper classes do what we expect within a regular asynchronous env
45        """
46        ha = HelperA()
47        ret = yield ha.sleep()
48        self.assertTrue(ret)
49
50        hb = HelperB()
51        ret = yield hb.sleep()
52        self.assertFalse(ret)
53
54    def test_basic_wrap(self):
55        """
56        Test that we can wrap an asynchronous caller.
57        """
58        sync = asynchronous.SyncWrapper(HelperA)
59        ret = sync.sleep()
60        self.assertTrue(ret)
61
62    def test_double(self):
63        """
64        Test when the asynchronous wrapper object itself creates a wrap of another thing
65
66        This works fine since the second wrap is based on the first's IOLoop so we
67        don't have to worry about complex start/stop mechanics
68        """
69        sync = asynchronous.SyncWrapper(HelperB)
70        ret = sync.sleep()
71        self.assertFalse(ret)
72
73    def test_double_sameloop(self):
74        """
75        Test asynchronous wrappers initiated from the same IOLoop, to ensure that
76        we don't wire up both to the same IOLoop (since it causes MANY problems).
77        """
78        a = asynchronous.SyncWrapper(HelperA)
79        sync = asynchronous.SyncWrapper(HelperB, (a,))
80        ret = sync.sleep()
81        self.assertFalse(ret)
82