# 测试规范 本仓库的测试分两层:**纯函数单测**(无外部依赖,几百毫秒)和**集成测试**(走真实 HTTP + Postgres,端到端验证业务行为)。 ## 跑测试 ### 1. 纯函数单测(默认) ```bash go test -short ./server/ ``` 包含 `classification_test.go` / `display_name_test.go` / `instance_governance_test.go` 中所有不依赖 DB 的函数验证。 11 个用例,约 0.7s。 ### 2. 集成测试(端到端,需真实 PG) ```bash go test -tags=integration -timeout 90s ./server/ ``` 包含 `integration_test.go` 中 5 个核心业务回归用例: | 用例 | 验证 | 关联 | |---|---|---| | `TestIntegration_EnumValidation` | 枚举越界返回 400 / `enum_violation`,空值放行,合法值落库 | issue #5-① | | `TestIntegration_ClassificationFilter` | manager 见全部,analyst(L0,L1) 只见 L0/L1,越级直取 404 | issue #5-③④ | | `TestIntegration_FieldSensitivity` | `properties.sensitivity` 越级 redact 为 `***`,公开字段保留 | issue #5-② | | `TestIntegration_RestoreEdges` | 删除级联清边 + 存快照 → 恢复时 `edges_created=1` + 边真重建 | issue #4 | | `TestIntegration_RecomputeApply` | dry_run 不落库、apply=true 修正错误分级 | issue #5-⑩ | #### 前置条件 - 本地 PG 可达,默认 `localhost:15432/shangshu`(dev docker `jnpf-postgres`)。 - 覆盖默认连接:设置环境变量 `TEST_DATABASE_URL`: ```bash export TEST_DATABASE_URL="postgres://dacli:dacli123@localhost:15432/shangshu?sslmode=disable" ``` - 每个测试用 `TestRgo__` 唯一化对象类型名 + t.Cleanup 物理清理; `analyst` 共享主体不清(仅扩大可见集不影响正确性)。 ### 3. 全部(CI 用) ```bash go test -tags=integration -timeout 120s ./server/... ``` ## 编写新测试的约定 ### 单测:放 `*_test.go` 同包,无需 build tag - 必须纯函数:不引 `*app.pool` / `*pgxpool.Pool` / `os.Getenv`。 - 用标准库 `testing` + 表驱动 + 明确 want/期望。 ### 集成测试:放 `integration_test.go`(或新文件加 `//go:build integration`) - 走真实 HTTP:`httptest.NewServer(registerRoutes(r, a))`。 - 调用 `setupTestEnv(t)` 拿 `*testEnv`,自动清理测试类型。 - **必须清缓存**:`invalidateClassCache()` + `authzCache.Range(...Delete...)`, 否则前一次测试的 `authzCache[analyst]=空 Authz` 会让后续测试以为"无 clearance"。 - 验证状态用 `body["xxx"]` 断言时记得 nil-check,宁可 `if got, ok := body["x"].(string); !ok` 不要硬断言。 ### 提交前 - 跑完 `go test -tags=integration ./server/` 全绿再 commit。 - 涉及缓存/连接/事务的改动要新增/更新集成测试,确保下次重构能立刻发现回归。