示例#1
0
    def test_task_list(self):
        tasks = None

        async def do_get_task_list():
            nonlocal tasks
            tasks = await imbroglio.tasks()

        imbroglio.run(do_get_task_list())
        self.assertEqual(([], []), tasks)

        # current task is not on the list
        async def sleep_forever():
            await imbroglio.sleep(None)

        task = None

        async def do_get_waiting_task():
            nonlocal task
            task = await imbroglio.spawn(sleep_forever())
            print(await imbroglio.tasks())
            await do_get_task_list()
            print(await imbroglio.tasks())
            task.cancel()
            await imbroglio.sleep()  # so task gets reaped

        imbroglio.run(do_get_waiting_task())

        self.assertEqual(2, len(tasks))
        runnable, waiting = tasks
        print(runnable)
        print(waiting)
        self.assertEqual(0, len(runnable))
        self.assertEqual(1, len(waiting))
        self.assertEqual([task], waiting)
示例#2
0
    def test_time_warning(self):
        async def sleeper():
            time.sleep(.2)

        imbroglio.run(sleeper())
        with self.assertLogs('imbroglio', level='WARNING'):
            imbroglio.run(sleeper())
示例#3
0
    def test_sleepy_cancel(self):
        alarmed = False

        def alarm(*args, **kw):
            nonlocal alarmed
            alarmed = True

        handler = signal.signal(signal.SIGALRM, alarm)
        try:
            signal.alarm(2)

            async def sleepy():
                await imbroglio.sleep(1)

            async def driver():
                task = await imbroglio.spawn(sleepy())
                await imbroglio.sleep()
                task.cancel()

            imbroglio.run(driver())
            signal.alarm(0)

            self.assertFalse(alarmed)
        finally:
            signal.alarm(0)
            signal.signal(signal.SIGALRM, handler)
示例#4
0
    def test_get_supervisor(self):
        supervisor = None

        async def do_get_supervisor():
            nonlocal supervisor
            supervisor = await imbroglio.get_supervisor()

        imbroglio.run(do_get_supervisor())
        self.assertIsInstance(supervisor, imbroglio.Supervisor)
示例#5
0
    def test_taskwait_done(self):
        async def quick():
            pass

        async def driver():
            t = await imbroglio.spawn(quick())
            await t
            self.assertEquals((False, 0.0), (await imbroglio.taskwait(t)))

        imbroglio.run(driver())
示例#6
0
    def test_weird_upcall(self):
        class Thing:
            def __await__(self):
                yield self

        async def caller():
            await Thing()

        with self.assertRaises(imbroglio.ImbroglioException):
            imbroglio.run(caller())
示例#7
0
    def test_sleep(self):
        # single coroutine that sleeps for a second
        async def coro():
            await imbroglio.sleep(1.0)

        t0 = time.time()

        imbroglio.run(coro())

        self.assertGreaterEqual(time.time(), t0 + 1.0)
示例#8
0
    def test_simple(self):
        # single coroutine with a single call
        val = None

        async def coro():
            nonlocal val
            val = await imbroglio.this_task()

        imbroglio.run(coro())

        self.assertIsInstance(val, imbroglio.Task)
示例#9
0
    def test_process_filter(self):
        async def test():
            self.assertEqual(
                (0, 'foo\n'),
                (await imbroglio.process_filter(['echo', 'foo'], '')))
            self.assertEqual((0, 'foo'),
                             (await imbroglio.process_filter(['cat'], 'foo')))
            self.assertEqual(
                (0, 'FOO'),
                (await imbroglio.process_filter(['tr', 'a-z', 'A-Z'], 'foo')))

        imbroglio.run(test())
示例#10
0
    def test_noncoro(self):
        # coroutine that isn't

        val = None

        async def coro():
            nonlocal val
            val = 17

        imbroglio.run(coro())

        self.assertEqual(17, val)
示例#11
0
    def test_run_in_thread_exception(self):
        class DistinctException(Exception):
            pass

        def sleep_then_raise():
            time.sleep(1)
            raise DistinctException('foo')

        async def check_raise():
            with self.assertRaises(DistinctException):
                await imbroglio.run_in_thread(sleep_then_raise)

        imbroglio.run(check_raise())
示例#12
0
    def test_task_misc(self):
        with self.assertRaises(TypeError):
            imbroglio.Task(lambda: None, None)

        async def nothing():
            await imbroglio.sleep(.1)

        coro = nothing()

        t = imbroglio.Task(coro, None)
        with self.assertRaises(imbroglio.UnfinishedError):
            t.result()

        imbroglio.run(coro)
示例#13
0
    def test_taskwait(self):
        async def longsleep():
            await imbroglio.sleep(1)

        async def shortsleep():
            await imbroglio.sleep(.5)

        async def driver():
            sleepers = [(await imbroglio.spawn(longsleep()))
                        for i in range(10)]
            task = await imbroglio.spawn(shortsleep())
            await task
            self.assertTrue(all(not t.is_done() for t in sleepers))

        imbroglio.run(driver())
示例#14
0
    def test_process_filter(self):
        async def test():
            self.assertEqual(
                (0, 'foo\n'),
                (await imbroglio.process_filter(['echo', 'foo'], '')))
            self.assertEqual((0, 'foo'),
                             (await imbroglio.process_filter(['cat'], 'foo')))
            self.assertEqual(
                (0, 'FOO'),
                (await imbroglio.process_filter(['tr', 'a-z', 'A-Z'], 'foo')))
            with self.assertRaises(FileNotFoundError):
                await imbroglio.process_filter(
                    ['fake_command_that_will_error_out'], '')

        imbroglio.run(test())
示例#15
0
    def test_throw_exception_type(self):
        # throw a bare type as an inspection.  To spice it up, make sure that
        # it sucessfully cancells a task in a long sleep.

        async def sleepy():
            await imbroglio.sleep(float('Inf'))

        async def driver():
            task = await imbroglio.spawn(sleepy())
            await imbroglio.sleep(0)
            task.throw(NotADirectoryError)
            await imbroglio.sleep(0)
            self.assertTrue(task.is_done())

        imbroglio.run(driver())
示例#16
0
    def test_wait_timeout(self):
        # spawn a reader and let it timeout

        a, b = socket.socketpair()

        try:

            async def reader():
                timedout, duration = \
                    await imbroglio.readwait(a.fileno(), .1)
                self.assertTrue(timedout)

            imbroglio.run(reader())
        finally:
            a.close()
            b.close()
示例#17
0
    def test_timeout(self):
        flag = False

        async def driver():
            nonlocal flag
            async with imbroglio.Timeout(.1):
                await imbroglio.sleep(1)
                flag = True
            self.assertFalse(flag)
            async with imbroglio.Timeout(1) as t:
                await imbroglio.sleep(.1)
                flag = True
            self.assertTrue(flag)
            self.assertTrue(t.is_done())

        imbroglio.run(driver())
        self.assertTrue(flag)
示例#18
0
    def test_run_in_thread(self):
        t0 = None
        t1 = None

        async def thread_sleep():
            nonlocal t1
            await imbroglio.run_in_thread(time.sleep, 1)
            t1 = time.time()

        async def do_thing():
            nonlocal t0
            await imbroglio.spawn(thread_sleep())
            t0 = time.time()

        imbroglio.run(do_thing())

        self.assertLess(t0, t1)
示例#19
0
    def test_wait(self):
        # spawn a counter, a reader, and a writer.

        counter = 0

        a, b = socket.socketpair()

        try:

            async def driver():
                await imbroglio.spawn(reader())
                await imbroglio.spawn(ticker())
                await imbroglio.spawn(writer())

            async def reader():
                timedout, duration = await imbroglio.readwait(a.fileno())
                self.assertFalse(timedout)
                self.assertEqual(b'X', a.recv(1))

            async def ticker():
                nonlocal counter

                for i in range(5):
                    await imbroglio.sleep(.1)
                    counter += 1

            async def writer():
                await imbroglio.sleep(.5)

                # make sure the ticker's been running while the reader's
                # been waiting
                self.assertGreater(counter, 3)

                # should come back immediately
                timedout, duration = \
                    await imbroglio.writewait(b.fileno(), 10)
                self.assertFalse(timedout)
                b.send(b'X')

            imbroglio.run(driver())
        finally:
            a.close()
            b.close()
示例#20
0
    def test_wait_zero(self):
        a, b = socket.socketpair()

        try:

            async def waiter():
                timedout, duration = \
                    await imbroglio.readwait(a.fileno(), 0)
                self.assertTrue(timedout)

                b.send(b'foo')

                timedout, duration = \
                    await imbroglio.readwait(a.fileno(), 0)
                self.assertFalse(timedout)

            imbroglio.run(waiter())
        finally:
            a.close()
            b.close()
示例#21
0
    def test_cancellation(self):
        counter = 0

        async def ticker():
            nonlocal counter

            while True:
                await imbroglio.sleep(.1)
                counter += 1

        async def driver():
            task = await imbroglio.spawn(ticker())
            await imbroglio.sleep(1)
            try:
                task.cancel()
            except BaseException:
                raise

        imbroglio.run(driver())

        self.assertGreater(counter, 3)
示例#22
0
    def test(self):
        with patch('snipe.util.HTTP_WS', MockHTTP_WS()) as _HTTP_WS:
            jws = snipe.util.JSONWebSocket(logging.getLogger('test'))

            self.assertFalse(_HTTP_WS._open)
            imbroglio.run(jws.connect('/bar'))
            self.assertIs(jws.conn, _HTTP_WS)
            self.assertTrue(_HTTP_WS._open)

            _HTTP_WS._toread = json.dumps('foo')
            self.assertEqual(imbroglio.run(jws.read()), 'foo')

            imbroglio.run(jws.write('bar'))
            self.assertEqual(json.loads(_HTTP_WS._wrote), 'bar')

            _HTTP_WS._toread = 'bleah'
            with self.assertRaisesRegex(snipe.util.JSONDecodeError,
                                        '.*bleah.*'):
                imbroglio.run(jws.read())

            imbroglio.run(jws.close())
            self.assertFalse(_HTTP_WS._open)
示例#23
0
    def test_spawn(self):
        # spawn three coroutines that increment a thing and then sleep
        counter = 0

        async def spawned():
            nonlocal counter
            counter += 1
            await imbroglio.sleep(1)

        async def spawner():
            for i in range(3):
                await imbroglio.spawn(spawned())

            return 85

        self.assertEqual(85, imbroglio.run(spawner()))
        self.assertEqual(3, counter)
示例#24
0
    def test_gather(self):
        a = False
        b = False

        async def f():
            nonlocal a
            await imbroglio.sleep(0)
            await imbroglio.sleep(.1)
            a = True

        async def g():
            nonlocal b
            await imbroglio.sleep(0)
            await imbroglio.sleep(.2)
            b = True

        t0 = time.time()
        imbroglio.run(imbroglio.gather(f(), g()))
        self.assertTrue(a and b)
        self.assertGreater(time.time() - t0, .2)

        class DistinctException(Exception):
            pass

        async def h():
            raise DistinctException()

        imbroglio.run(imbroglio.gather(f(), g(), h(), return_exceptions=True))

        with self.assertRaises(DistinctException):
            imbroglio.run(imbroglio.gather(f(), g(), h()))

        fc = f()
        with self.assertRaises(imbroglio.ImbroglioException):
            imbroglio.run(imbroglio.gather(fc, False))
        fc.close()
示例#25
0
    def test_promise(self):
        p = imbroglio.Promise()
        p.set_result(5)
        self.assertEqual(5, p.result)

        r = None

        async def get_result():
            nonlocal r
            r = await p

        imbroglio.run(get_result())

        self.assertEqual(5, r)

        p = imbroglio.Promise()

        async def set_result():
            await imbroglio.spawn(get_result())
            await imbroglio.sleep(.1)
            p.set_result(6)

        imbroglio.run(set_result())

        self.assertEqual(6, r)

        class DistinctException(Exception):
            pass

        p = imbroglio.Promise()
        t = None

        async def set_exception():
            nonlocal t
            t = await imbroglio.spawn(get_result())
            await imbroglio.sleep(.1)
            p.set_result_exception(DistinctException('foo'))

        imbroglio.run(set_exception())

        with self.assertRaises(DistinctException):
            t.result()
示例#26
0
    def test(self):
        async def self_cancel():
            raise imbroglio.Cancelled

        wrapped = snipe.util.coro_cleanup(self_cancel)

        self.assertTrue(inspect.iscoroutinefunction(wrapped))

        with self.assertRaises(imbroglio.Cancelled):
            imbroglio.run(wrapped())

        async def key_error(*args):
            return {}[0]

        with self.assertLogs('coro_cleanup'):
            imbroglio.run(snipe.util.coro_cleanup(key_error)())

        class X:
            log = logging.getLogger('test_coro_cleanup')

        with self.assertLogs('test_coro_cleanup'):
            imbroglio.run(snipe.util.coro_cleanup(key_error)(X))
示例#27
0
 def test(self):
     imbroglio.run(self._test())
示例#28
0
    def test(self):
        with patch('snipe.util.HTTP', MockHTTP()) as _HTTP:
            hjm = JSONMixinTester()

            hjm.log = logging.getLogger('test_http_json_mixin')
            hjm.url = 'http://example.com'

            hjm.setup_client_session()
            self.assertIn('User-Agent', dict(hjm._JSONmixin_headers))

            imbroglio.run(hjm.reset_client_session_headers())

            _HTTP.blobs = [json.dumps('foo').encode()]
            self.assertEqual('foo', imbroglio.run(hjm._post('/foo')))

            imbroglio.run(hjm.reset_client_session_headers({'foo': 'bar'}))
            self.assertEqual(dict(hjm._JSONmixin_headers)['foo'], 'bar')

            _HTTP.blobs = [b'zog']

            with self.assertRaises(snipe.util.JSONDecodeError) as ar:
                imbroglio.run(hjm._post_json('/bar', baz='quux'))

            self.assertIn('zog', str(ar.exception))
            self.assertEqual(_HTTP._method, 'POST')

            _HTTP.blobs = [json.dumps('foo').encode()]
            self.assertEqual('foo', imbroglio.run(hjm._get('/foo')))
            self.assertEqual(_HTTP._method, 'GET')

            self.assertEqual('foo', imbroglio.run(hjm._patch('/foo')))
            self.assertEqual(_HTTP._method, 'PATCH')

            imbroglio.run(hjm.shutdown())
            self.assertTrue(hjm._is_shutdown)
示例#29
0
    def test_exception(self):
        async def keyerror():
            {}[None]

        with self.assertRaises(KeyError):
            imbroglio.run(keyerror(), exception=True)