Exemplo n.º 1
0
    def test_pass_nonfuture(self):
        async def foo():
            pass

        try:
            coro = foo()
            with self.assertRaisesRegex(TypeError,
                                        "First argument must be a future."):
                _AwaitingFuture(foo)
        finally:
            coro.close()
Exemplo n.º 2
0
 def test_complete_immediately(self):
     done = self.loop.create_future()
     done.set_result(42)
     fut = _AwaitingFuture(done, loop=self.loop)
     self.assertFalse(fut.done())
     test_utils.run_briefly(self.loop)
     self.assertTrue(fut.done())
Exemplo n.º 3
0
 async def waiter(coro, loop):
     t = loop.create_task(outer(coro))
     f = _AwaitingFuture(t, loop=loop)
     await f
     return t.result()
Exemplo n.º 4
0
 def _new_future(self):
     awaited = self.loop.create_future()
     fut = _AwaitingFuture(awaited, loop=self.loop)
     self.awaited[fut] = awaited
     return fut
Exemplo n.º 5
0
async def wait_for(fut, timeout, *, loop=None):
    """Wait for the single Future or coroutine to complete, with timeout.

    Coroutine will be wrapped in Task.

    Returns result of the Future or coroutine.  When a timeout occurs,
    it cancels the task and raises TimeoutError.  To avoid the task
    cancellation, wrap it in shield().

    If the wait is cancelled, the task is also cancelled.

    This function is a coroutine.
    """
    if loop is None:
        loop = events.get_running_loop()
    else:
        warnings.warn(
            "The loop argument is deprecated since Python 3.8, "
            "and scheduled for removal in Python 3.10.",
            DeprecationWarning,
            stacklevel=2)

    if timeout is None:
        return await fut

    if timeout <= 0:
        fut = ensure_future(fut, loop=loop)

        if fut.done():
            return fut.result()

        fut.cancel()
        raise exceptions.TimeoutError()

    fut = ensure_future(fut, loop=loop)
    waiter = _asyncio._AwaitingFuture(fut, loop=loop)
    timed_out = False

    def on_timeout(waiter, *args):
        nonlocal timed_out
        timed_out = True
        waiter.cancel()

    timeout_handle = loop.call_later(timeout, on_timeout, waiter)

    try:
        # wait until the future completes or the timeout
        try:
            await waiter
        except exceptions.CancelledError:
            if fut.done():
                # The future may have completed in the same trip of the event
                # loop as the timeout occurring.
                return fut.result()
            if timed_out:
                # We must ensure that the task is not running
                # after wait_for() returns.
                # See https://bugs.python.org/issue32751
                await _cancel_and_wait(fut, loop=loop)
                raise exceptions.TimeoutError()
            fut.cancel()
            raise
        return fut.result()
    finally:
        timeout_handle.cancel()