Example #1
0
async def main(loop: asyncio.AbstractEventLoop):
    print("creating task")
    task = loop.create_task(task_func())
    loop.call_soon(task_canceller, task)
    try:
        await task
    except asyncio.CancelledError:
        print("main() also sees task as canceled")
Example #2
0
    def wrap_to_future(loop: asyncio.AbstractEventLoop, func: Callable[..., T],
                       *args: Any, **kwargs: Any) -> asyncio.Future:
        future = loop.create_future()

        def _inner():  # type: ignore
            try:
                return future.set_result(func(*args, **kwargs))
            except Exception as e:
                return future.set_exception(e)

        loop.call_soon(_inner)
        return future
Example #3
0
def teardown_test_loop(loop: asyncio.AbstractEventLoop, fast: bool = False) -> None:
    """Teardown and cleanup an event_loop created by setup_test_loop."""
    closed = loop.is_closed()
    if not closed:
        loop.call_soon(loop.stop)
        loop.run_forever()
        loop.close()

    if not fast:
        gc.collect()

    asyncio.set_event_loop(None)
Example #4
0
def teardown_test_loop(loop: asyncio.AbstractEventLoop,
                       fast: bool = False) -> None:
    closed = loop.is_closed()
    if not closed:
        loop.call_soon(loop.stop)
        loop.run_forever()
        loop.close()

    if not fast:
        gc.collect()

    asyncio.set_event_loop(None)
Example #5
0
async def test_select(loop: asyncio.AbstractEventLoop):
    f_one = asyncio.Event()
    f_two = asyncio.Event()

    loop.call_soon(f_one.set)
    loop.call_later(1, f_two.set)

    one, two = await aiomisc.select(f_one.wait(), f_two.wait())

    assert one
    assert two is None

    one, two = await aiomisc.select(f_one.wait(), f_two.wait())
    assert one
    def sigint_handler(self, loop: AbstractEventLoop):
        print("got sigint")
        self.aiter.stop()

        def stop_if_only_one():
            tasks = asyncio.all_tasks(loop)
            if len(tasks) == 0:
                print("work done, stopping loop")
                loop.stop()
            else:
                print("left over work to do, check again in ~.5s.")
                loop.call_later(0.5, stop_if_only_one)

        loop.call_soon(stop_if_only_one)
        print("exiting sigint")
Example #7
0
def teardown_test_loop(loop: asyncio.AbstractEventLoop,
                       fast: bool=False) -> None:
    """Teardown and cleanup an event_loop created
    by setup_test_loop.

    """
    closed = loop.is_closed()
    if not closed:
        loop.call_soon(loop.stop)
        loop.run_forever()
        loop.close()

    if not fast:
        gc.collect()

    asyncio.set_event_loop(None)
Example #8
0
async def start_tls(
    loop: asyncio.AbstractEventLoop,
    transport: asyncio.Transport,
    protocol: asyncio.Protocol,
    sslcontext: ssl.SSLContext,
    server_side: bool = False,
    server_hostname: Optional[str] = None,
    ssl_handshake_timeout: Optional[Union[float, int]] = None,
) -> asyncio.Transport:
    # We use hasattr here, as uvloop also supports start_tls.
    if hasattr(loop, "start_tls"):
        return await loop.start_tls(  # type: ignore
            transport,
            protocol,
            sslcontext,
            server_side=server_side,
            server_hostname=server_hostname,
            ssl_handshake_timeout=ssl_handshake_timeout,
        )

    waiter = loop.create_future()
    ssl_protocol = SSLProtocol(loop, protocol, sslcontext, waiter, server_side,
                               server_hostname)

    # Pause early so that "ssl_protocol.data_received()" doesn't
    # have a chance to get called before "ssl_protocol.connection_made()".
    transport.pause_reading()

    # Use set_protocol if we can
    if hasattr(transport, "set_protocol"):
        transport.set_protocol(ssl_protocol)  # type: ignore
    else:
        transport._protocol = ssl_protocol  # type: ignore

    conmade_cb = loop.call_soon(ssl_protocol.connection_made, transport)
    resume_cb = loop.call_soon(transport.resume_reading)

    try:
        await asyncio.wait_for(waiter, timeout=ssl_handshake_timeout)
    except Exception:
        transport.close()
        conmade_cb.cancel()
        resume_cb.cancel()
        raise

    return ssl_protocol._app_transport
def wrap_call_soon(loop: asyncio.AbstractEventLoop,
                   sync_fn: typing.Callable[[], T]) -> typing.Awaitable[T]:
    f = _get_event_loop().create_future()

    def _():
        try:
            f.set_result(sync_fn())
        except Exception as e:
            f.set_exception(e)

    h = loop.call_soon(_)
    orig_cancel = f.cancel

    def _cancel():
        h.cancel()
        orig_cancel()

    f.cancel = _cancel  # type: ignore
    return f
Example #10
0
 def hotfix(
     loop: asyncio.AbstractEventLoop,
 ) -> asyncio.AbstractEventLoop:
     loop.call_soon(_wakeup, loop, 1.0)
     return loop