自动化测试(七)python-异步(asyncio)

114 阅读1分钟

1. 并发执行多个任务

async def download(url):
    print(f"开始下载 {url}")
    await asyncio.sleep(1)  # 模拟网络请求
    print(f"下载完成 {url}")

async def main():
    urls = ["url1", "url2", "url3"]
    tasks = [asyncio.create_task(download(url)) for url in urls]
    await asyncio.gather(*tasks)  # 并发执行

2. 超时控制

async def long_operation():
    await asyncio.sleep(10)

async def main():
    try:
        await asyncio.wait_for(long_operation(), timeout=3)
    except asyncio.TimeoutError:
        print("操作超时")

3. 异步上下文管理器

class AsyncConnection:
    async def __aenter__(self):
        self.conn = await connect_db()
        return self.conn

    async def __aexit__(self, *args):
        await self.conn.close()

async with AsyncConnection() as conn:
    await conn.execute("SELECT ...")