首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >具有异步的Pytest - python测试

具有异步的Pytest - python测试
EN

Stack Overflow用户
提问于 2017-07-31 08:06:48
回答 1查看 10.1K关注 0票数 8

是否可以将执行从函数返回到event loop。并且一旦Task完成,返回到函数并继续执行?

我正在尝试使用pytest-asyncio插件

示例:

代码语言:javascript
复制
@pytest.mark.asyncio
async def test_async1(event_loop):
    print('start 1')
    res = event_loop.create_task(
        send_async_request("http://test.com", limit=1000))) # here I need to return execution to event loop and continue only after getting response from send_async_request function 
    print('end1',res)



@pytest.mark.asyncio
async def test_async2(event_loop):
    print('start 2')
    res = event_loop.create_task(
        send_async_request("http://test2", limit=1000))) # here I need to return execution to event loop and continue only after getting response from send_async_request function
    print('end2', res)

send_async_request- aiohttp

代码语言:javascript
复制
@asyncio.coroutine
def send_async_request(url, method='GET'):
    with aiohttp.ClientSession() as session:
        resp = yield from session.get(url, timeout=60)
        if resp.status == 200:
            return resp.status, response
        else:
            return resp.status, False
EN

回答 1

Stack Overflow用户

发布于 2017-07-31 08:38:51

当您的测试被标记为pytest.mark.asyncio时,它们就变成了协同,所以您可以使用await语法:

代码语言:javascript
复制
@pytest.mark.asyncio
async def test_sleep(event_loop):
    result = await asyncio.sleep(1, result=3, loop=event_loop)
    assert result == 3

编辑:另一个例子,多个sleep操作:

代码语言:javascript
复制
@pytest.mark.asyncio
async def test_multiple_sleep(event_loop):
    tasks = [event_loop.create_task(asyncio.sleep(1, result=x))
             for x in range(10)]
    results = await asyncio.gather(*tasks)
    assert results == list(range(10))
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45410434

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档