Files
chengshishouce/TESTING.md

163 lines
2.6 KiB
Markdown
Raw Permalink Normal View History

# API 测试指南
## 测试后端 API
### 1. 获取 Token (登录)
```bash
curl -X POST http://localhost:8000/api/auth/login/ \
-H "Content-Type: application/json" \
-d '{
"email": "your@email.com",
"password": "your_password"
}'
```
响应示例:
```json
{
"access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
"refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
"user": {
"id": 1,
"email": "your@email.com",
"username": "your_username",
"first_name": "First",
"last_name": "Last"
}
}
```
### 2. 刷新 Token
```bash
curl -X POST http://localhost:8000/api/auth/token/refresh/ \
-H "Content-Type: application/json" \
-d '{
"refresh": "your_refresh_token"
}'
```
### 3. 获取用户列表 (需要认证)
```bash
curl -X GET http://localhost:8000/api/users/ \
-H "Authorization: Bearer your_access_token"
```
### 4. 获取当前用户
```bash
curl -X GET http://localhost:8000/api/users/me/ \
-H "Authorization: Bearer your_access_token"
```
## GraphQL 测试
访问 http://localhost:8000/graphql/?graphiql
### 查询所有用户
```graphql
query {
allUsers {
id
email
username
firstName
lastName
}
}
```
### 查询当前用户
```graphql
query {
me {
id
email
username
firstName
lastName
}
}
```
## Postman 集合
你可以导入以下 Postman 集合来测试 API
### 环境变量
- `base_url`: http://localhost:8000
- `access_token`: (登录后自动填充)
### 请求示例
**1. 登录**
- Method: POST
- URL: `{{base_url}}/api/auth/login/`
- Body:
```json
{
"email": "test@example.com",
"password": "testpass123"
}
```
- Tests (自动提取 token):
```javascript
var jsonData = pm.response.json();
pm.environment.set("access_token", jsonData.access);
```
**2. 获取用户**
- Method: GET
- URL: `{{base_url}}/api/users/`
- Headers:
```
Authorization: Bearer {{access_token}}
```
**3. 获取当前用户**
- Method: GET
- URL: `{{base_url}}/api/users/me/`
- Headers:
```
Authorization: Bearer {{access_token}}
```
## 自动化测试
### 后端测试
```bash
cd backend
python manage.py test
```
### 前端测试
```bash
cd frontend
npm test
```
## 常见错误
### 401 Unauthorized
- Token 过期,使用 refresh_token 刷新
- Token 格式错误,确保 `Bearer` 前缀存在
- Token 被吊销
### 403 Forbidden
- 权限不足,检查用户是否有相应权限
- CSRF token 问题(开发环境可能遇到)
### 404 Not Found
- 端点不存在,检查 URL 路径
- 检查 Django 是否正确启动
### 500 Server Error
- 检查 Django 日志
- 检查数据库连接
- 检查代码语法错误