FastAPI 学习之路(三十九)对开发接口进行测试

概况

对于开发好的接口需要进行测试之后才能发布。当我们在开发的时候,没有提前测试,我们也要对我们自己的接口进行测试,那么FastApi自身也带有针对开发的接口进行测试的功能。我们看下FastApi官方给我们提供了什么样的支持。

接口还是基于FastAPI 学习之路(三十七)元数据和文档 URL实现。我们看下如何测试。

TestClient

复制代码
from routers.items import item_router
from routers.users import user_router
from fastapi import FastAPI


app = FastAPI(
    title="这是测试Title",
    description="这是测试description",
    version="这是测试version"
)

app.include_router(user_router, prefix="/u", tags=["users"])
app.include_router(item_router, prefix="/i", tags=["items"])

# ------------------------------以下是进行测试的方法---------------------------------
# 这是fastapi提供给我们来进行测试的类
from fastapi.testclient import TestClient

client = TestClient(app)


def test_get_user_view():
    response = client.get("/u/user?uid=1")
    assert response.status_code == 200
    assert isinstance(response.json(), dict) and "email" in response.json()


if __name__ == '__main__':
    test_get_user_view()

其实很简单,fastapi里面有个模块,我们直接导入进来,编写用例即可。

运行看下:

可是我们简单的写的,运行后只是没有报错而已。证明执行成功,但是在实际中,我们做还是不够的,我们想要看着是否执行通过。如何实现呢。

我们可以使用python自带的unittest来组织测试用例。

unittest

我们看下改造后的。

复制代码
from routers.items import item_router
from routers.users import user_router
from fastapi import FastAPI


app = FastAPI(
    title="这是测试Title",
    description="这是测试description",
    version="这是测试version"
)

app.include_router(user_router, prefix="/u", tags=["users"])
app.include_router(item_router, prefix="/i", tags=["items"])

# ------------------------改造------------------------------
import unittest
from fastapi.testclient import TestClient

client = TestClient(app)


class FastApiTest(unittest.TestCase):

    def setUp(self) -> None:
        self.client = TestClient(app)

    def tearDown(self) -> None:
        self.client = None

    def test_get_user_view(self):
        response = self.client.get("/u/user?uid=3")
        self.assertEqual(response.status_code, 200)
        self.assertIn("email", response.json())

    def test_get_item_by_uid_view(self):
        response = self.client.get("/i/items/1")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json()[0]["id"], 3)


if __name__ == '__main__':
    unittest.main()

运行看下:

当然,你也可以单独创建一个test文件,将测试流程单独放置于test文件中。

这样我们就实现了对fastapi在开发过程中的接口测试,很简单,我们也不用启动服务端。

相关推荐
梦因you而美16 小时前
LangChain-ReAct-Agent 智能客服系统 · 项目技术文档
langchain·agent·fastapi·扫地机器人·langgraph·rag 检索增强·react 智能客服
jsjzsl220 小时前
独立自由度框架下位置自由度的本体论特征、物理现象与新技术路径
python·flask·fastapi
嘻哈baby21 小时前
FastAPI + SQLite 从 0 写一个真正能用的待办 API
数据库·sqlite·fastapi
陈驰_05041 天前
需求列表接口 422 Unprocessable Entity 排查与修复全记录
状态模式·fastapi·vue 3
Json____1 天前
基于 FastAPI + Vue3 的在线拍卖系统技术解析
spring boot·后端·fastapi·wwwoop.com
创新技术阁1 天前
FastapiAdmin 实战:二次开发前的准备(环境配置与项目启动)
前端·后端·fastapi
神秘的猪头2 天前
新版 LangChain Agent 核心架构:State、Context、ToolRuntime 与 Middleware
langchain·llm·fastapi
神秘的猪头2 天前
新版 LangChain Agent 入门:从 `bind_tools + while` 到 `create_agent`
langchain·fastapi
神秘的猪头2 天前
把新版 LangChain Agent 做成真正应用:Memory、Streaming、SSE 与 Structured Output
langchain·fastapi
minhuan2 天前
搭建本地人脸识别系统:解析FastAPI+InsightFace+FAISS全栈实现原理与优化方案26.6
fastapi·faiss·insightface·大模型应用·人脸识别模型·本地化人脸识别系统