hi-server/scripts/README.md
shanshanzhong 1bcfa321b7
All checks were successful
Build docker and publish / build (20.15.1) (push) Successful in 7m9s
feat: 添加测试数据清理脚本并改进设备登录逻辑
docs(scripts): 添加测试数据清理脚本的详细使用文档
fix(auth): 修复设备登录时处理孤立认证方法的问题
refactor(public): 改进邮箱绑定逻辑中的推荐码处理
2025-10-27 22:20:18 -07:00

149 lines
3.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 测试数据清理脚本
## 问题背景
在运行测试案例 `test/device.go` 时,可能会遇到以下错误:
```
[ERROR] 2025/01/28 11:40:59 [DeviceLoginLogic] FindOne Error: record not found
```
这个错误通常是由于测试数据清理不完整导致的,具体表现为:
- 设备记录存在,但对应的用户记录已被删除
- 数据库中存在孤立的记录
- 测试用户数据没有完全清理
## 解决方案
使用 `cleanup_test_data.go` 脚本来清理测试数据,确保数据一致性。
## 使用方法
### 1. 配置脚本
编辑 `cleanup_test_data.go` 文件,修改以下配置:
```go
const (
// 服务器地址
baseURL = "http://localhost:8080"
// 管理员认证信息
adminEmail = "admin@example.com"
adminPassword = "admin123"
// 测试用户邮箱前缀
testEmailPrefix = "test_"
)
```
### 2. 运行清理脚本
```bash
# 进入scripts目录
cd scripts
# 查看帮助信息
go run cleanup_test_data.go --help
# 运行清理脚本
go run cleanup_test_data.go
```
### 3. 脚本功能
脚本会自动执行以下操作:
1. **管理员登录**: 使用配置的管理员账户登录系统
2. **识别测试用户**: 根据邮箱规则识别测试用户:
- 邮箱以 `test_` 开头
- 邮箱包含 `test` 关键字
- 邮箱包含 `example.com` 域名
3. **批量删除**: 使用管理员API批量删除测试用户
4. **数据一致性检查**: 检查剩余用户数据的完整性
## API接口说明
脚本使用以下管理员API接口
| 接口 | 方法 | 说明 |
|------|------|------|
| `/v1/auth/login` | POST | 管理员登录 |
| `/v1/admin/user` | GET | 获取用户列表 |
| `/v1/admin/user/batch` | DELETE | 批量删除用户 |
| `/v1/admin/user/{id}` | GET | 获取用户详情 |
## 清理规则
### 用户删除规则
脚本会删除符合以下条件的用户:
```go
isTestUser := strings.HasPrefix(user.Email, testEmailPrefix) ||
strings.Contains(user.Email, "test") ||
strings.Contains(user.Email, "example.com")
```
### 数据清理范围
根据 `internal/model/user/default.go` 中的 `Delete` 方法,删除用户时会自动清理:
- 用户基本信息 (`User` 表)
- 用户认证方式 (`AuthMethods` 表)
- 用户订阅信息 (`Subscribe` 表)
- 用户设备信息 (`Device` 表)
- 相关缓存数据
## 安全注意事项
⚠️ **重要提醒**
1. **仅在测试环境使用**: 此脚本会删除用户数据,请勿在生产环境运行
2. **备份数据**: 运行前建议备份数据库
3. **确认配置**: 确保管理员账户信息正确
4. **检查规则**: 确认测试用户识别规则符合预期
## 故障排除
### 常见错误
1. **登录失败**
```
❌ 管理员登录失败: 登录失败 (Code: 401): Invalid credentials
```
- 检查管理员邮箱和密码是否正确
- 确认服务器是否正在运行
2. **连接失败**
```
❌ 管理员登录失败: 登录请求失败: dial tcp [::1]:8080: connect: connection refused
```
- 检查服务器地址是否正确
- 确认服务器是否启动
3. **权限不足**
```
❌ 获取用户列表失败: 获取用户列表失败 (Code: 403): Forbidden
```
- 确认使用的是管理员账户
- 检查管理员权限配置
### 验证清理效果
清理完成后,可以重新运行测试脚本验证:
```bash
cd test
go run device.go
```
如果清理成功,应该不再出现 "record not found" 错误。
## 相关文件
- `test/device.go` - 测试脚本
- `internal/logic/admin/user/deleteUserLogic.go` - 单个用户删除逻辑
- `internal/logic/admin/user/batchDeleteUserLogic.go` - 批量用户删除逻辑
- `internal/model/user/default.go` - 用户模型删除方法
- `apis/admin/user.api` - 管理员用户API定义