How to use trio - 10 common examples

To help you get started, we’ve selected a few trio examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ethereum / trinity / tests-trio / p2p-trio / test_service.py View on Github external
async def test_trio_service_lifecycle_run_and_clean_exit():
    trigger_exit = trio.Event()

    @as_service
    async def ServiceTest(manager):
        await trigger_exit.wait()

    service = ServiceTest()
    manager = Manager(service)

    await do_service_lifecycle_check(
        manager=manager,
        manager_run_fn=manager.run,
        trigger_exit_condition_fn=trigger_exit.set,
        should_be_cancelled=False,
    )
github ethereum / trinity / tests-trio / p2p-trio / test_service.py View on Github external
service_finished = trio.Event()

    @as_service
    async def RunTaskService(manager):
        async def task_fn():
            # this will never complete
            await task_event.wait()

        manager.run_task(task_fn)
        # the task is set to run in the background but then  the service exits.
        # We want to be sure that the task is allowed to continue till
        # completion unless explicitely cancelled.
        service_finished.set()

    async with background_service(RunTaskService()) as manager:
        with trio.fail_after(0.01):
            await service_finished.wait()

        # show that the service hangs waiting for the task to complete.
        with trio.move_on_after(0.01) as cancel_scope:
            await manager.wait_stopped()
        assert cancel_scope.cancelled_caught is True

        # trigger cancellation and see that the service actually stops
        manager.cancel()
        with trio.fail_after(0.01):
            await manager.wait_stopped()
github M-o-a-T / qbroker / tests / test_unit.py View on Github external
async def test_reg():
    async with unit(1) as unit1:
        async with unit(2) as unit2:
            rx = 0
            async for d in unit2.poll("qbroker.ping", max_delay=TIMEOUT, result_conv=CC_DATA):
                if d['uuid'] == unit1.uuid:
                    assert d['app'] == unit1.app
                    rx += 1
                elif d['uuid'] == unit2.uuid:
                    assert d['app'] == unit2.app
                    rx += 1
                # There may be others.
            assert rx == 2

            with pytest.raises(trio.TooSlowError):
                async for d in unit2.poll("qbroker.ping", min_replies=99, max_delay=TIMEOUT / 2,
                                          result_conv=CC_DATA):
                    pass

            res = await unit2.rpc("qbroker.ping", dest=unit1.app)
            assert res['app'] == unit1.app
            assert "rpc.qbroker.ping" in res['endpoints'], res['endpoints']
github python-trio / trio-amqp / tests / test_properties.py View on Github external
async def _server(
        self,
        amqp,
        server_future,
        exchange_name,
        routing_key,
        task_status=trio.TASK_STATUS_IGNORED
    ):
        """Consume messages and reply to them by publishing messages back
        to the client using routing key set to the reply_to property
        """
        async with amqp.new_channel() as channel:
            await channel.queue_declare(server_queue_name, exclusive=False, no_wait=False)
            await channel.exchange_declare(exchange_name, type_name='direct')
            await channel.queue_bind(server_queue_name, exchange_name, routing_key=routing_key)

            async with trio.open_nursery() as n:
                await n.start(self._server_consumer, channel, server_future)
                task_status.started()
                await server_future.wait()
                self._server_scope.cancel()
github vmware / concord-bft / tests / test_skvbc_linearizability.py View on Github external
def test_healthy(self):
        """
        Run a bunch of concurrrent requests in batches and verify
        linearizability. The system is healthy and stable and no faults are
        intentionally generated.
        """
        trio.run(self._test_healthy)
github vmware / concord-bft / tests / test_skvbc_fast_path.py View on Github external
def test_fast_path_resilience_to_crashes(self):
        """
        In this test we check the fast path's resilience when up to "c" nodes fail.

        As a first step, we bring down no more than c replicas,
        triggering initially the slow path.

        Then we write a series of known K/V entries, making sure
        the fast path is eventually restored and becomes prevalent.

        Finally we check if a known K/V write has been executed.
        """
        trio.run(self._test_fast_path_resilience_to_crashes)
github python-trio / trio-amqp / tests / test_basic.py View on Github external
async def test_basic_cancel(self, channel):
        async def callback(channel, body, envelope, _properties):
            pass

        queue_name = 'queue_name'
        exchange_name = 'exchange_name'
        await channel.queue_declare(queue_name)
        await channel.exchange_declare(exchange_name, type_name='direct')
        await channel.queue_bind(queue_name, exchange_name, routing_key='')
        result = await channel.basic_consume(callback, queue_name=queue_name)
        result = await channel.basic_cancel(result['consumer_tag'])

        result = await channel.publish("payload", exchange_name, routing_key='')

        await trio.sleep(1)
        result = await channel.queue_declare(queue_name, passive=True)
        assert result['message_count'] == 1
        assert result['consumer_count'] == 0
github M-o-a-T / qbroker / tests / test_unit.py View on Github external
async def sleep2():
                nonlocal nhit
                nhit += 1
                await trio.sleep(TIMEOUT)
                return False
github vmware / concord-bft / tests / util / skvbc.py View on Github external
async def send_indefinite_write_requests(self):
        msg = self.write_req(
            [], [(self.random_key(), self.random_value())], 0)
        while True:
            client = self.bft_network.random_client()
            try:
                await client.write(msg)
            except:
                pass
            await trio.sleep(.1)
github ethereum / trinity / tests-trio / p2p-trio / test_packer.py View on Github external
async def test_packer_processes_handshake_initiation(nursery,
                                                     packer,
                                                     enr,
                                                     remote_enr,
                                                     remote_endpoint,
                                                     incoming_packet_channels):
    assert not packer.is_peer_packer_registered(remote_enr.node_id)

    # receive packet
    tag = compute_tag(source_node_id=remote_enr.node_id, destination_node_id=enr.node_id)
    incoming_packet = IncomingPacket(
        packet=AuthTagPacketFactory(tag=tag),
        sender_endpoint=remote_endpoint,
    )
    await incoming_packet_channels[0].send(incoming_packet)
    await trio.sleep(0)
    assert packer.is_peer_packer_registered(remote_enr.node_id)