微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

FastAPI61- 异步测试

FastAPI(61)- 异步测试 

 

前言

 

FastAPI 代码

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Tomato"}

 

单元测试代码

需要先安装

pip install httpx
pip install trio
pip install anyio

 

测试代码

import pytest
from httpx import Asyncclient

from .main import app


@pytest.mark.anyio
async def test_root():
    async with Asyncclient(app=app, base_url="http://test") as ac:
        response = await ac.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Tomato"}

 

httpx

  • 即使 FastAPI 应用程序使用普通 def 函数而不是 async def,它仍然是一个异步应用程序
  • TestClient 在内部使用标准 pytest 在正常 def 测试函数调用异步 FastAPI 应用程序做了一些魔术
  • 但是当在异步函数中使用调用异步 FastAPI 应用程序时,这种魔法就不再起作用了
  • 通过异步运行测试用例,不能再在测试函数中使用 TestClient,此时有一个不错的替代方案,称为 HTTPX
  • HTTPX 是 Python 3 的 HTTP 客户端,它允许像使用 TestClient 一样查询 FastAPI 应用程序
  • HTTPX 的 API 和 requests 库几乎相同
  • 重要的区别:用 HTTPX 不仅限于同步,还可以发出异步请求 

 

@pytest.mark.anyio

告诉 pytest 这个测试函数应该异步调用

 

Asyncclient

  • 通过使用 FastAPI app 创建一个 Asyncclient,并使用 await 向它发送异步请求
  • 需要搭配 async/await 一起使用

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐