feat(api): 增强 API 测试框架功能与文档

- 在 Api 结构中新增 lastResp 字段以存储最近请求的响应
- 添加 Verify 方法,支持自定义校验函数并返回 ApiCase 构建器
- 新增 Resp 方法,获取最近一次请求的响应以便于断言
- 在 TestCollector 中添加 Visited 字段,记录已调用的路径
- 更新 GenerateSwagger 方法,支持部分运行时保留未运行端点的已有数据
- 完善文档,增加用例编写范式和示例,提升测试框架的可用性与易用性
This commit is contained in:
2026-03-30 01:55:07 +08:00
parent 3681564ca4
commit 37a67f5810
14 changed files with 2665 additions and 639 deletions
+25 -5
View File
@@ -44,10 +44,11 @@ type ApiTestDef struct {
// Api 测试 API 入口,由 RunTests 自动创建并注入
type Api struct {
app *TestApp
path string
t *testing.T
session Map
app *TestApp
path string
t *testing.T
session Map
lastResp *ApiResponse
}
// WithSession 返回一个携带 session 的新 Api 实例
@@ -111,6 +112,14 @@ func (a *Api) Delete(desc string, status int, expect ...interface{}) *ApiRespons
return a.newCase().Delete(desc, status, expect...)
}
// Verify 设置请求后的校验函数,返回 ApiCase 构建器
// 在回调中可用 a.Resp() 做响应值断言 + a.DB() 做数据库校验
func (a *Api) Verify(fn func(a *Api) error) *ApiCase {
c := a.newCase()
c.verifyFn = fn
return c
}
// Note 为下一条用例设置备注,返回可继续链式的 ApiCase
func (a *Api) Note(note string) *ApiCase {
c := a.newCase()
@@ -123,6 +132,11 @@ func (a *Api) DB() *HoTimeDB {
return &a.app.Db
}
// Resp 获取最近一次请求的响应,在 Verify 回调中用于响应值断言
func (a *Api) Resp() *ApiResponse {
return a.lastResp
}
func (a *Api) newCase() *ApiCase {
return &ApiCase{
api: a,
@@ -292,6 +306,7 @@ func (c *ApiCase) execute(method, desc string, expectStatus int, expectArgs ...i
}
}
c.api.lastResp = resp
var verifyError string
if passed && c.verifyFn != nil {
if err := c.verifyFn(c.api); err != nil {
@@ -440,11 +455,16 @@ func (r *ApiResponse) GetMsg() string {
return ""
}
// GetBody 获取完整的响应 body
// GetBody 获取完整的响应 body(JSON 解析后的 Map,可链式 Get*)
func (r *ApiResponse) GetBody() Map {
return r.Body
}
// GetRawBody 获取原始响应字节(用于非 JSON 响应如文件下载、二进制流校验)
func (r *ApiResponse) GetRawBody() []byte {
return r.RawBody
}
// Fail 手动标记测试失败(用于自定义断言)
func (r *ApiResponse) Fail(msg string) {
if r.t != nil {