-
@ChatGPT FastAPI单元测试讲解实例,以学生管理为例
-
guest说:
FastAPI单元测试讲解实例,以学生管理为例
目录
1、准备工作
在开始编写测试代码之前,我们需要准备一些必要的工作:
-
安装
pytest要进行FastAPI的单元测试,我们需要安装
pytest,它是一款功能强大的Python测试框架,支持测试用例的编写、执行以及结果的收集,所以我们需要先安装它:$ pip install pytest -
安装
uvicornuvicorn是一款异步非阻塞的Python Web服务器,它支持ASGI协议,所以我们可以使用它来启动我们的FastAPI应用,并用于进行测试:$ pip install uvicorn -
编写FastAPI应用
为了方便讲解,我们编写一个简单的学生管理的FastAPI应用:
# main.py from typing import List from fastapi import FastAPI, Depends, HTTPException from pydantic import BaseModel class Student(BaseModel): name: str age: int gender: str students = [ { "name": "Bob", "age": 20, "gender": "male" }, { "name": "Alice", "age": 18, "gender": "female" } ] app = FastAPI() @app.get("/students/") async def get_students(): return students @app.post("/students/") async def create_student(student: Student): students.append(student.dict()) return student @app.put("/students/{name}") async def update_student(name: str, student: Student): for index, item in enumerate(students): if item["name"] == name: students[index] = student.dict() break else: raise HTTPException(status_code=404, detail="Student not found") return student @app.delete("/students/{name}") async def delete_student(name: str): for index, item in enumerate(students): if item["name"] == name: del students[index] break else: raise HTTPException(status_code=404, detail="Student not found") return {"msg": "delete success"}
2、编写测试代码
2.1 测试获取学生列表
首先,我们来测试获取学生列表的接口,编写测试用例:
# test_main.py import json from typing import List import pytest import requests from main import app @pytest.fixture(scope="module") def test_client(): test_client = app.test_client() return test_client def test_get_students(test_client): response = test_client.get("/students/") data = json.loads(response.data) assert len(data) == 2 students = [ { "name": "Bob", "age": 20, "gender": "male" }, { "name": "Alice", "age": 18, "gender": "female" } ] assert data == students测试用例:
- 先通过
pytest.fixture定义一个fixture,用于创建一个FastAPI的客户端,用于发送测试请求; - 然后编写测试函数,函数参数为上面定义的fixture,这样
pytest就会自动执行fixture,将它的返回值传入测试函数; - 通过客户端发送
GET请求,验证返回结果是否正确。
2.2 测试创建学生
接下来,我们来测试创建学生的接口,编写测试用例:
# test_main.py import json import pytest from main import app @pytest.fixture(scope="module") def test_client(): test_client = app.test_client() return test_client def test_create_student(test_client): # 构造数据 data = { "name": "Tom", "age": 20, "gender": "male" } # 发送请求 response = test_client.post("/students/", json=data) # 验证结果 assert response.status_code == 200 data = json.loads(response.data) assert data == data测试用例:
- 通过
pytest.fixture定义一个fixture,用于创建一个FastAPI的客户端; - 编写测试函数,函数参数为上面定义的fixture;
- 构造测试数据;
- 通过客户端发送
POST请求; - 验证返回结果是否正确。
2.3 测试更新学生信息
接下来,我们来测试更新学生信息的接口,编写测试用例:
# test_main.py import json import pytest from main import app @pytest.fixture(scope="module") def test_client(): test_client = app.test_client() return test_client def test_update_student(test_client): # 构造数据 data = { "name": "Bob", "age": 21, "gender": "male" } # 发送请求 response = test_client.put("/students/Bob", json=data) # 验证结果 assert response.status_code == 200 data = json.loads(response.data) assert data == data测试用例:
- 通过
pytest.fixture定义一个fixture,用于创建一个FastAPI的客户端; - 编写测试函数,函数参数为上面定义的fixture;
- 构造测试数据;
- 通过客户端发送
PUT请求; - 验证返回结果是否正确。
2.4 测试删除学生
最后,我们来测试删除学生的接口,编写测试用例:
# test_main.py import json import pytest from main import app @pytest.fixture(scope="module") def test_client(): test_client = app.test_client() return test_client def test_delete_student(test_client): # 发送请求 response = test_client.delete("/students/Bob") # 验证结果 assert response.status_code == 200 data = json.loads(response.data) assert data == {"msg": "delete success"}测试用例:
- 通过
pytest.fixture定义一个fixture,用于创建一个FastAPI的客户端; - 编写测试函数,函数参数为上面定义的fixture;
- 通过客户端发送
DELETE请求; - 验证返回结果是否正确。
3、编写测试执行程序
-
-
@ChatGPT 举例讲解下FastAPI的单元测试,以学生信息管理为例,举例讲解下原理和使用方法
-
guest说:
举例讲解下FastAPI的单元测试,以学生信息管理为例,举例讲解下原理和使用方法
- 单元测试的原理:
单元测试是指分离的测试,它的目的是检查每个独立的单元是否正确工作,单元测试可以帮助检测单元之间的相互依赖,从而确保程序的稳定性和正确性。
- 使用FastAPI进行单元测试:
(1)安装pytest,并在项目根目录创建 tests/ 目录;
(2)在 tests/ 目录下创建一个 test_students.py 文件,用来编写学生信息管理的测试用例;
(3)使用 pytest 在 tests/ 目录下执行 test_students.py 文件,检查测试用例是否正确;
(4)如果测试用例通过,则代表学生信息管理的功能是正常工作的。
-
我想知道俄乌战争近况
-
能问医疗方面的知识吗
-
游客 说:
能问医疗方面的知识吗
-
@ChatGPT 你懂医疗方面的知识吗?
-
游客 说:
@ChatGPT 你懂医疗方面的知识吗?
-
粗体字
-
@ChatGPT 知道我在网络上的信息吗?
-
麦当劳好吃还是肯德基
-
世界杯阿根廷和法国那个是冠军?
-
@ChatGPT 新冠病毒是不是人为制造出来的
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register Login