Python asyncio.sleep() Examples

The following are 30 code examples of asyncio.sleep(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module asyncio , or try the search function .
Example #1
Source File: test_show_typing_middleware.py    From botbuilder-python with MIT License 6 votes vote down vote up
def test_should_automatically_send_a_typing_indicator(self):
        async def aux(context):
            await asyncio.sleep(0.600)
            await context.send_activity(f"echo:{context.activity.text}")

        def assert_is_typing(activity, description):  # pylint: disable=unused-argument
            assert activity.type == ActivityTypes.typing

        adapter = TestAdapter(aux)
        adapter.use(ShowTypingMiddleware())

        step1 = await adapter.send("foo")
        step2 = await step1.assert_reply(assert_is_typing)
        step3 = await step2.assert_reply("echo:foo")
        step4 = await step3.send("bar")
        step5 = await step4.assert_reply(assert_is_typing)
        await step5.assert_reply("echo:bar") 
Example #2
Source File: test_hachiko.py    From hachiko with MIT License 6 votes vote down vote up
def check_output_is_expected(directory, capsys):
    """Create, move, and delete a file."""
    # Create file
    original_filename = os.path.join(directory, 'file.txt')
    pathlib.Path(original_filename).touch()
    await asyncio.sleep(0.1)  # force release to stdout
    captured = capsys.readouterr()
    assert captured.out == 'File created!\n'
    # Move file
    new_filename = os.path.join(directory, 'new_filename.txt')
    os.rename(original_filename, new_filename)
    await asyncio.sleep(0.1)  # force release to stdout
    captured = capsys.readouterr()
    assert captured.out == 'File moved!\n'
    # Delete file
    os.remove(new_filename)
    await asyncio.sleep(0.1)  # force release to stdout
    captured = capsys.readouterr()
    assert captured.out == 'File deleted!\n' 
Example #3
Source File: test_async.py    From clashroyale with MIT License 6 votes vote down vote up
def test_get_clan_battles(self):
        """This test will test out:
        - Normal clan battles fetching
        - All battles fetching
        - Clan war battles only fetching
        """

        tag = '29UQQ282'
        battles = await self.cr.get_clan_battles(tag)
        self.assertTrue(isinstance(battles, list))
        await asyncio.sleep(2)
        battles = await self.cr.get_clan_battles(tag, type='all')
        self.assertTrue(isinstance(battles, list))
        await asyncio.sleep(2)
        battles = await self.cr.get_clan_battles(tag, type='war')
        self.assertTrue(isinstance(battles, list)) 
Example #4
Source File: lolz.py    From Dumb-Cogs with MIT License 6 votes vote down vote up
def patcher(self):
        await self.bot.wait_until_ready()
        try:
            await asyncio.sleep(6)  # be safe lolz
            while True:
                if not hasattr(self.bot.send_message, 'old'):
                    print(
                        '[WARNING:] -- Overwriting bot.send_message with '
                        'send_lolz. If bot.send_message is not reloaded,')
                    print(
                        '[WARNING:] -- in the event of a crash of the lolz '
                        'cog, you may not be able revert to bot.send_message '
                        'without a restart/reloading lolz')
                    self.bot.send_message = self.send_lolz(self.bot.send_message)
                await asyncio.sleep(1)
        except asyncio.CancelledError:
            pass 
Example #5
Source File: hal.py    From Dumb-Cogs with MIT License 6 votes vote down vote up
def hal(self, ctx, *, question="none"):
        """Speak with HAL"""
        author = ctx.message.author
        msg = ""
        found = []
        for k,v in self.responses.items():
            if k in question.lower():
                found.append(v)
        if found:
            msg = randchoice(randchoice(found))
        if not msg:
            msg = randchoice(self.responses["none"])
        await asyncio.sleep(1)
        await self.bot.say(msg.format(author=author))
        if "sing it for me" in question.lower() and "Audio" in self.bot.cogs and author.voice_channel:
            audio = self.bot.get_cog("Audio")
            if audio.music_player.is_done():
                link = "https://www.youtube.com/watch?v=hchUl3QlJZE"
                # probably dont need. just too lazy to check.
                ctx.message.content = "{}play {}".format(ctx.prefix, link)
                if await audio.check_voice(ctx.message.author, ctx.message):
                    audio.queue.append(link) 
Example #6
Source File: asyncioCondition.py    From Learning-Concurrency-in-Python with MIT License 6 votes vote down vote up
def manipulate_condition(condition):
    print('starting manipulate_condition')

    # pause to let consumers start
    await asyncio.sleep(0.1)

    for i in range(1, 3):
        with await condition:
            print('notifying {} consumers'.format(i))
            condition.notify(n=i)
        await asyncio.sleep(0.1)

    with await condition:
        print('notifying remaining consumers')
        condition.notify_all()

    print('ending manipulate_condition') 
Example #7
Source File: test_async_client_validation.py    From gql with MIT License 6 votes vote down vote up
def server_starwars(ws, path):
    await WebSocketServer.send_connection_ack(ws)

    try:
        await ws.recv()

        reviews = [starwars_expected_one, starwars_expected_two]

        for review in reviews:

            data = (
                '{"type":"data","id":"1","payload":{"data":{"reviewAdded": '
                + json.dumps(review)
                + "}}}"
            )
            await ws.send(data)
            await asyncio.sleep(2 * MS)

        await WebSocketServer.send_complete(ws, 1)
        await WebSocketServer.wait_connection_terminate(ws)

    except websockets.exceptions.ConnectionClosedOK:
        pass

    print("Server is now closed") 
Example #8
Source File: test_websocket_subscription.py    From gql with MIT License 6 votes vote down vote up
def test_websocket_subscription_slow_consumer(
    event_loop, client_and_server, subscription_str
):

    session, server = client_and_server

    count = 10
    subscription = gql(subscription_str.format(count=count))

    async for result in session.subscribe(subscription):
        await asyncio.sleep(10 * MS)

        number = result["number"]
        print(f"Number received: {number}")

        assert number == count

        count -= 1

    assert count == -1 
Example #9
Source File: test_websocket_subscription.py    From gql with MIT License 6 votes vote down vote up
def server_countdown_close_connection_in_middle(ws, path):
    await WebSocketServer.send_connection_ack(ws)

    result = await ws.recv()
    json_result = json.loads(result)
    assert json_result["type"] == "start"
    payload = json_result["payload"]
    query = payload["query"]
    query_id = json_result["id"]

    count_found = search("count: {:d}", query)
    count = count_found[0]
    stopping_before = count // 2
    print(f"Countdown started from: {count}, stopping server before {stopping_before}")
    for number in range(count, stopping_before, -1):
        await ws.send(countdown_server_answer.format(query_id=query_id, number=number))
        await asyncio.sleep(2 * MS)

    print("Closing server while subscription is still running now")
    await ws.close()
    await ws.wait_closed()
    print("Server is now closed") 
Example #10
Source File: test_websocket_online.py    From gql with MIT License 6 votes vote down vote up
def test_websocket_sending_invalid_payload():

    # Get Websockets transport
    sample_transport = WebsocketsTransport(
        url="wss://countries.trevorblades.com/graphql", ssl=True
    )

    # Instanciate client
    async with Client(transport=sample_transport):

        invalid_payload = '{"id": "1", "type": "start", "payload": "BLAHBLAH"}'

        print(f">>> {invalid_payload}")
        await sample_transport.websocket.send(invalid_payload)

        await asyncio.sleep(2) 
Example #11
Source File: test_websocket_exceptions.py    From gql with MIT License 6 votes vote down vote up
def test_websocket_non_regression_bug_105(event_loop, server):

    # This test will check a fix to a race condition which happens if the user is trying
    # to connect using the same client twice at the same time
    # See bug #105

    url = f"ws://{server.hostname}:{server.port}/graphql"
    print(f"url = {url}")

    sample_transport = WebsocketsTransport(url=url)

    client = Client(transport=sample_transport)

    # Create a coroutine which start the connection with the transport but does nothing
    async def client_connect(client):
        async with client:
            await asyncio.sleep(2 * MS)

    # Create two tasks which will try to connect using the same client (not allowed)
    connect_task1 = asyncio.ensure_future(client_connect(client))
    connect_task2 = asyncio.ensure_future(client_connect(client))

    with pytest.raises(TransportAlreadyConnected):
        await asyncio.gather(connect_task1, connect_task2) 
Example #12
Source File: test_templating.py    From quart with MIT License 5 votes vote down vote up
def test_template_context_processors(app: Quart, blueprint: Blueprint) -> None:
    @blueprint.context_processor
    async def blueprint_context() -> dict:
        await asyncio.sleep(0.01)  # Test the ability to await
        return {"context": "foo"}

    @blueprint.app_context_processor
    async def app_blueprint_context() -> dict:
        return {"global_context": "boo"}

    @app.context_processor
    async def app_context() -> dict:
        return {"context": "bar"}

    app.register_blueprint(blueprint)

    async with app.app_context():
        rendered = await render_template_string("{{ context }}")
    assert rendered == "bar"

    async with app.test_request_context("/"):
        rendered = await render_template_string("{{ context }} {{ global_context }}")
    assert rendered == "foo boo"

    async with app.test_request_context("/other"):
        rendered = await render_template_string("{{ context }} {{ global_context }}")
    assert rendered == "bar boo" 
Example #13
Source File: test_worker.py    From sanic with MIT License 5 votes vote down vote up
def gunicorn_worker():
    command = (
        "gunicorn "
        "--bind 127.0.0.1:1337 "
        "--worker-class sanic.worker.GunicornWorker "
        "examples.simple_server:app"
    )
    worker = subprocess.Popen(shlex.split(command))
    time.sleep(3)
    yield
    worker.kill() 
Example #14
Source File: request.py    From quart with MIT License 5 votes vote down vote up
def send(self, data: AnyStr) -> None:
        # Must allow for the event loop to act if the user has say
        # setup a tight loop sending data over a websocket (as in the
        # example). So yield via the sleep.
        await asyncio.sleep(0)
        await self.accept()
        await self._send(data) 
Example #15
Source File: test_response_timeout.py    From sanic with MIT License 5 votes vote down vote up
def handler_1(request):
    await asyncio.sleep(2)
    return text("OK") 
Example #16
Source File: testing.py    From quart with MIT License 5 votes vote down vote up
def _check_for_response(self) -> None:
        await asyncio.sleep(0)  # Give serving task an opportunity to respond
        if self.task.done() and self.task.result() is not None:
            raise WebsocketResponse(self.task.result()) 
Example #17
Source File: progress_bar.py    From quart with MIT License 5 votes vote down vote up
def some_work():
    global aredis
    await aredis.set('state', 'running')
    work_to_do = range(1, 26)
    await aredis.set('length_of_work', len(work_to_do))
    for i in work_to_do:
        await aredis.set('processed', i)
        await asyncio.sleep(random.random())
    await aredis.set('state', 'ready')
    await aredis.set('percent', 100) 
Example #18
Source File: test_response_timeout.py    From sanic with MIT License 5 votes vote down vote up
def handler_3(request):
    await asyncio.sleep(2)
    return text("OK") 
Example #19
Source File: test_response_timeout.py    From sanic with MIT License 5 votes vote down vote up
def handler_2(request):
    await asyncio.sleep(2)
    return text("OK") 
Example #20
Source File: test_async.py    From clashroyale with MIT License 5 votes vote down vote up
def tearDown(self):
        await self.cr.close()
        await asyncio.sleep(2)

    # MISC METHODS # 
Example #21
Source File: example.py    From hachiko with MIT License 5 votes vote down vote up
def watch_fs(watch_dir):
    evh = MyEventHandler()
    watch = AIOWatchdog(watch_dir, event_handler=evh)
    watch.start()
    for _ in range(20):
        await asyncio.sleep(1)
    watch.stop() 
Example #22
Source File: notifications.py    From SpaceXLaunchBot with MIT License 5 votes vote down vote up
def notification_task(client: discord.Client) -> None:
    """An async task to send out launching soon & launch info notifications."""
    await client.wait_until_ready()
    logging.info("Starting")

    while not client.is_closed():
        await _check_and_send_notifs(client)
        await asyncio.sleep(ONE_MINUTE * config.NOTIF_TASK_API_INTERVAL) 
Example #23
Source File: test_contextvars.py    From opentracing-python with Apache License 2.0 5 votes vote down vote up
def submit_subtasks(self):
        async def task(name):
            logger.info('Running %s' % name)
            with self.tracer.start_active_span(name):
                await asyncio.sleep(0.1)

        self.loop.create_task(task('task1'))
        self.loop.create_task(task('task2')) 
Example #24
Source File: test_asyncio.py    From opentracing-python with Apache License 2.0 5 votes vote down vote up
def submit_subtasks(self, parent_span):
        async def task(name):
            logger.info('Running %s' % name)
            with self.tracer.scope_manager.activate(parent_span, False):
                with self.tracer.start_active_span(name):
                    await asyncio.sleep(0.1)

        self.loop.create_task(task('task1'))
        self.loop.create_task(task('task2')) 
Example #25
Source File: test_asyncio.py    From opentracing-python with Apache License 2.0 5 votes vote down vote up
def task(self, interval, parent_span):
        logger.info('Starting task')

        with self.tracer.scope_manager.activate(parent_span, False):
            with self.tracer.start_active_span('task'):
                await asyncio.sleep(interval) 
Example #26
Source File: test_contextvars.py    From opentracing-python with Apache License 2.0 5 votes vote down vote up
def test_tasks_with_no_parent_scope(self):

        async def task(name):
            await asyncio.sleep(0.1)
            with self.tracer.start_active_span(name):
                await asyncio.sleep(0.1)

        async def tasks():
            self.loop.create_task(task('task_1'))
            with no_parent_scope():
                self.loop.create_task(task('task_2'))
            self.loop.create_task(task('task_3'))

        with self.tracer.start_active_span('root'):
            self.loop.create_task(tasks())

        stop_loop_when(self.loop,
                       lambda: len(self.tracer.finished_spans()) == 4)
        self.loop.run_forever()

        root, task1, task2, task3 = self.tracer.finished_spans()

        self.assertEmptySpan(root, 'root')

        self.assertEmptySpan(task1, 'task_1')
        self.assertIsChildOf(task1, root)

        # Third task was scheduled out `no_parent_scope`.
        self.assertEmptySpan(task3, 'task_3')
        self.assertIsChildOf(task3, root)

        # Second task "wrapped" by `no_parent_scope`.
        self.assertEmptySpan(task2, 'task_2')
        self.assertHasNoParent(task2) 
Example #27
Source File: test_contextvars.py    From opentracing-python with Apache License 2.0 5 votes vote down vote up
def test_recursive_scheduling_with_ignoring_active_span(self):

        tasks = 4

        async def task(n=0):
            await asyncio.sleep(0.1)
            if n < tasks / 2:
                with self.tracer.start_active_span(str(n)):
                    self.loop.create_task(task(n+1))
            elif n < tasks:
                with self.tracer.start_active_span(
                    operation_name=str(n),
                    ignore_active_span=True
                ):
                    self.loop.create_task(task(n+1))

        self.loop.create_task(task())

        stop_loop_when(self.loop,
                       lambda: len(self.tracer.finished_spans()) == tasks)
        self.loop.run_forever()

        s0, s1, s2, s3 = self.tracer.finished_spans()

        self.assertEmptySpan(s0, '0')
        self.assertHasNoParent(s0)

        self.assertEmptySpan(s1, '1')
        self.assertIsChildOf(s1, s0)

        self.assertEmptySpan(s2, '2')
        self.assertHasNoParent(s2)

        self.assertEmptySpan(s3, '3')
        self.assertHasNoParent(s3) 
Example #28
Source File: test_contextvars.py    From opentracing-python with Apache License 2.0 5 votes vote down vote up
def test_recursive_scheduling_task(self):

        tasks = 4

        async def task(n=0):
            await asyncio.sleep(0.1)
            with self.tracer.start_active_span(
                operation_name=str(n),
                child_of=self.tracer.active_span
            ):
                if n < tasks:
                    self.loop.create_task(task(n+1))

        self.loop.create_task(task())

        stop_loop_when(self.loop,
                       lambda: len(self.tracer.finished_spans()) == tasks)
        self.loop.run_forever()

        spans = self.tracer.finished_spans()

        for i in range(tasks):
            self.assertEmptySpan(spans[i], str(i))
            if i == 0:
                self.assertIsNone(spans[i].parent_id)
            else:
                self.assertIsChildOf(spans[i], spans[i-1]) 
Example #29
Source File: test_contextvars.py    From opentracing-python with Apache License 2.0 5 votes vote down vote up
def test_coroutines_scheduling_task(self):

        async def _task(op_name):
            await asyncio.sleep(0.1)
            with self.tracer.start_active_span(
                operation_name=op_name,
                child_of=self.tracer.active_span
            ):
                pass

        async def task(op_name):
            with self.tracer.start_active_span(
                operation_name=op_name,
                child_of=self.tracer.active_span
            ):
                self.loop.create_task(_task('childof:{}'.format(op_name)))

        with self.tracer.start_active_span('root'):
            self.loop.create_task(task('task1'))
            self.loop.create_task(task('task2'))

        stop_loop_when(self.loop,
                       lambda: len(self.tracer.finished_spans()) == 5)
        self.loop.run_forever()

        root, task1, task2, child1, child2 = self.tracer.finished_spans()

        self.assertEmptySpan(root, 'root')
        self.assertEmptySpan(task1, 'task1')
        self.assertEmptySpan(task2, 'task2')
        self.assertEmptySpan(child1, 'childof:task1')
        self.assertEmptySpan(child2, 'childof:task2')

        self.assertIsChildOf(task1, root)
        self.assertIsChildOf(task2, root)
        self.assertIsChildOf(child1, task1)
        self.assertIsChildOf(child2, task2) 
Example #30
Source File: an_app6.py    From wuy with GNU General Public License v2.0 5 votes vote down vote up
def doTheJob(self,pb,speed):
        for i in range(101):
            await asyncio.sleep(speed)    # simulate the job
            self.emit("percent",pb,i)
        return "Job Done %s!" % pb