Flask Test Client API
FlaskClient 是一个模拟浏览器,可以在不启动服务器的情况下发送请求并验证响应。
通过 app.test_client() 创建实例。
创建测试客户端
| 方式 | 说明 |
|---|---|
| app.test_client(use_cookies=True) | 标准创建方式。use_cookies=False 禁用 Cookie 处理 |
| with app.test_client() as client: | 上下文管理器。退出时自动清理请求上下文 |
请求方法
所有方法返回 TestResponse 对象(继承自 Response)。
| 方法 | 说明 |
|---|---|
| get(path, **kwargs) | 发送 GET 请求 |
| post(path, **kwargs) | 发送 POST 请求 |
| put(path, **kwargs) | 发送 PUT 请求 |
| delete(path, **kwargs) | 发送 DELETE 请求 |
| patch(path, **kwargs) | 发送 PATCH 请求 |
| open(path, method, **kwargs) | 通用请求方法,需显式指定 method |
请求参数(kwargs)
| 参数 | 说明 |
|---|---|
| data | 请求体(字符串或字节)。用于表单提交 |
| json | JSON 数据,自动序列化并设置 Content-Type: application/json |
| query_string | URL 查询参数字符串或字典 |
| headers | 请求头字典 |
| content_type | 自定义 Content-Type |
| follow_redirects | bool,是否自动跟随重定向。默认为 False |
| buffered | bool,是否缓冲响应。默认为 False |
响应对象(TestResponse)
| 属性/方法 | 说明 |
|---|---|
| status_code | HTTP 状态码(int) |
| status | HTTP 状态文本,如 "200 OK" |
| data | 响应体(bytes) |
| text | 以文本方式获取响应体(str) |
| get_json() | 将响应体解析为 JSON。返回 dict 或 list |
| headers | 响应头(Headers 对象) |
| location | 重定向目标 URL(仅 3xx 响应) |
| json_module | 用于 JSON 序列化的模块(默认为 app.json) |
Session 测试
| 方法 | 说明 |
|---|---|
| session_transaction(**kwargs) | 上下文管理器,用于直接读写 session。返回 SessionMixin 对象 |
代码示例
实例
from app import create_app
app = create_app()
app.config["TESTING"] = True
def test_api():
with app.test_client() as client:
# GET 请求
resp = client.get("/api/posts")
assert resp.status_code == 200
data = resp.get_json()
assert isinstance(data, list)
# POST JSON 请求
resp = client.post("/api/posts", json={
"title": "RUNOOB 教程",
"body": "入门内容"
})
assert resp.status_code == 201
assert resp.get_json()["title"] == "RUNOOB 教程"
# 带查询参数的请求
resp = client.get("/search?q=flask")
assert b"flask" in resp.data
# 模拟已登录状态
with client.session_transaction() as sess:
sess["username"] = "runoob"
resp = client.get("/dashboard")
assert b"runoob" in resp.data
# 跟随重定向
resp = client.post("/login", data={
"username": "admin"
}, follow_redirects=True)
assert resp.status_code == 200
app = create_app()
app.config["TESTING"] = True
def test_api():
with app.test_client() as client:
# GET 请求
resp = client.get("/api/posts")
assert resp.status_code == 200
data = resp.get_json()
assert isinstance(data, list)
# POST JSON 请求
resp = client.post("/api/posts", json={
"title": "RUNOOB 教程",
"body": "入门内容"
})
assert resp.status_code == 201
assert resp.get_json()["title"] == "RUNOOB 教程"
# 带查询参数的请求
resp = client.get("/search?q=flask")
assert b"flask" in resp.data
# 模拟已登录状态
with client.session_transaction() as sess:
sess["username"] = "runoob"
resp = client.get("/dashboard")
assert b"runoob" in resp.data
# 跟随重定向
resp = client.post("/login", data={
"username": "admin"
}, follow_redirects=True)
assert resp.status_code == 200
