api_key_service_delete_test.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. //go:build unit
  2. // API Key 服务删除方法的单元测试
  3. // 测试 APIKeyService.Delete 方法在各种场景下的行为,
  4. // 包括权限验证、缓存清理和错误处理
  5. package service
  6. import (
  7. "context"
  8. "errors"
  9. "strings"
  10. "testing"
  11. "time"
  12. "github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
  13. "github.com/stretchr/testify/require"
  14. )
  15. // apiKeyRepoStub 是 APIKeyRepository 接口的测试桩实现。
  16. // 用于隔离测试 APIKeyService.Delete 方法,避免依赖真实数据库。
  17. //
  18. // 设计说明:
  19. // - apiKey/getByIDErr: 模拟 GetKeyAndOwnerID 返回的记录与错误
  20. // - deleteErr: 模拟 Delete 返回的错误
  21. // - deletedIDs: 记录被调用删除的 API Key ID,用于断言验证
  22. type apiKeyRepoStub struct {
  23. apiKey *APIKey // GetKeyAndOwnerID 的返回值
  24. getByIDErr error // GetKeyAndOwnerID 的错误返回值
  25. deleteErr error // Delete 的错误返回值
  26. updateErr error // Update 的错误返回值
  27. deletedIDs []int64 // 记录已删除的 API Key ID 列表
  28. updatedKeys []APIKey
  29. allowListByUserID bool
  30. listByUserIDKeys []APIKey
  31. listByUserIDErr error
  32. listByUserIDCalls []int64
  33. listByUserIDParams []pagination.PaginationParams
  34. listByUserIDFilters []APIKeyListFilters
  35. allowListAllByUserID bool
  36. listAllByUserIDKeys []APIKey
  37. listAllByUserIDErr error
  38. listAllByUserIDCalls []int64
  39. listAllByUserIDFilters []APIKeyListFilters
  40. updateLastUsed func(ctx context.Context, id int64, usedAt time.Time) error
  41. touchedIDs []int64
  42. touchedUsedAts []time.Time
  43. }
  44. // 以下方法在本测试中不应被调用,使用 panic 确保测试失败时能快速定位问题
  45. func (s *apiKeyRepoStub) Create(ctx context.Context, key *APIKey) error {
  46. panic("unexpected Create call")
  47. }
  48. func (s *apiKeyRepoStub) GetByID(ctx context.Context, id int64) (*APIKey, error) {
  49. if s.getByIDErr != nil {
  50. return nil, s.getByIDErr
  51. }
  52. if s.apiKey != nil {
  53. clone := *s.apiKey
  54. return &clone, nil
  55. }
  56. panic("unexpected GetByID call")
  57. }
  58. func (s *apiKeyRepoStub) GetKeyAndOwnerID(ctx context.Context, id int64) (string, int64, error) {
  59. if s.getByIDErr != nil {
  60. return "", 0, s.getByIDErr
  61. }
  62. if s.apiKey != nil {
  63. return s.apiKey.Key, s.apiKey.UserID, nil
  64. }
  65. return "", 0, ErrAPIKeyNotFound
  66. }
  67. func (s *apiKeyRepoStub) GetByKey(ctx context.Context, key string) (*APIKey, error) {
  68. panic("unexpected GetByKey call")
  69. }
  70. func (s *apiKeyRepoStub) GetByKeyForAuth(ctx context.Context, key string) (*APIKey, error) {
  71. panic("unexpected GetByKeyForAuth call")
  72. }
  73. func (s *apiKeyRepoStub) Update(ctx context.Context, key *APIKey, _ APIKeyUpdateFields) error {
  74. if key != nil {
  75. s.updatedKeys = append(s.updatedKeys, *key)
  76. }
  77. return s.updateErr
  78. }
  79. // Delete 记录被删除的 API Key ID 并返回预设的错误。
  80. // 通过 deletedIDs 可以验证删除操作是否被正确调用。
  81. func (s *apiKeyRepoStub) Delete(ctx context.Context, id int64) error {
  82. s.deletedIDs = append(s.deletedIDs, id)
  83. return s.deleteErr
  84. }
  85. // DeleteWithAudit 与 Delete 一样记录被删除的 ID,供 service 测试断言。
  86. func (s *apiKeyRepoStub) DeleteWithAudit(ctx context.Context, id int64) error {
  87. s.deletedIDs = append(s.deletedIDs, id)
  88. return s.deleteErr
  89. }
  90. // 以下是接口要求实现但本测试不关心的方法
  91. func (s *apiKeyRepoStub) ListByUserID(ctx context.Context, userID int64, params pagination.PaginationParams, filters APIKeyListFilters) ([]APIKey, *pagination.PaginationResult, error) {
  92. if !s.allowListByUserID {
  93. panic("unexpected ListByUserID call")
  94. }
  95. s.listByUserIDCalls = append(s.listByUserIDCalls, userID)
  96. s.listByUserIDParams = append(s.listByUserIDParams, params)
  97. s.listByUserIDFilters = append(s.listByUserIDFilters, filters)
  98. if s.listByUserIDErr != nil {
  99. return nil, nil, s.listByUserIDErr
  100. }
  101. keys := append([]APIKey(nil), s.listByUserIDKeys...)
  102. return keys, &pagination.PaginationResult{
  103. Total: int64(len(keys)),
  104. Page: params.Page,
  105. PageSize: params.PageSize,
  106. Pages: 1,
  107. }, nil
  108. }
  109. func (s *apiKeyRepoStub) ListAllByUserID(ctx context.Context, userID int64, filters APIKeyListFilters) ([]APIKey, error) {
  110. if !s.allowListAllByUserID {
  111. panic("unexpected ListAllByUserID call")
  112. }
  113. s.listAllByUserIDCalls = append(s.listAllByUserIDCalls, userID)
  114. s.listAllByUserIDFilters = append(s.listAllByUserIDFilters, filters)
  115. if s.listAllByUserIDErr != nil {
  116. return nil, s.listAllByUserIDErr
  117. }
  118. source := s.listByUserIDKeys
  119. if s.listAllByUserIDKeys != nil {
  120. source = s.listAllByUserIDKeys
  121. }
  122. return filterAPIKeyStubKeys(userID, source, filters), nil
  123. }
  124. func filterAPIKeyStubKeys(userID int64, keys []APIKey, filters APIKeyListFilters) []APIKey {
  125. result := make([]APIKey, 0, len(keys))
  126. search := strings.ToLower(filters.Search)
  127. for _, key := range keys {
  128. if key.UserID != userID {
  129. continue
  130. }
  131. if search != "" &&
  132. !strings.Contains(strings.ToLower(key.Name), search) &&
  133. !strings.Contains(strings.ToLower(key.Key), search) {
  134. continue
  135. }
  136. if filters.Status != "" && key.Status != filters.Status {
  137. continue
  138. }
  139. if filters.GroupID != nil {
  140. if *filters.GroupID == 0 {
  141. if key.GroupID != nil {
  142. continue
  143. }
  144. } else if key.GroupID == nil || *key.GroupID != *filters.GroupID {
  145. continue
  146. }
  147. }
  148. result = append(result, key)
  149. }
  150. return result
  151. }
  152. func (s *apiKeyRepoStub) VerifyOwnership(ctx context.Context, userID int64, apiKeyIDs []int64) ([]int64, error) {
  153. panic("unexpected VerifyOwnership call")
  154. }
  155. func (s *apiKeyRepoStub) CountByUserID(ctx context.Context, userID int64) (int64, error) {
  156. panic("unexpected CountByUserID call")
  157. }
  158. func (s *apiKeyRepoStub) ExistsByKey(ctx context.Context, key string) (bool, error) {
  159. panic("unexpected ExistsByKey call")
  160. }
  161. func (s *apiKeyRepoStub) ListByGroupID(ctx context.Context, groupID int64, params pagination.PaginationParams) ([]APIKey, *pagination.PaginationResult, error) {
  162. panic("unexpected ListByGroupID call")
  163. }
  164. func (s *apiKeyRepoStub) SearchAPIKeys(ctx context.Context, userID int64, keyword string, limit int) ([]APIKey, error) {
  165. panic("unexpected SearchAPIKeys call")
  166. }
  167. func (s *apiKeyRepoStub) ClearGroupIDByGroupID(ctx context.Context, groupID int64) (int64, error) {
  168. panic("unexpected ClearGroupIDByGroupID call")
  169. }
  170. func (s *apiKeyRepoStub) UpdateGroupIDByUserAndGroup(ctx context.Context, userID, oldGroupID, newGroupID int64) (int64, error) {
  171. panic("unexpected UpdateGroupIDByUserAndGroup call")
  172. }
  173. func (s *apiKeyRepoStub) CountByGroupID(ctx context.Context, groupID int64) (int64, error) {
  174. panic("unexpected CountByGroupID call")
  175. }
  176. func (s *apiKeyRepoStub) ListKeysByUserID(ctx context.Context, userID int64) ([]string, error) {
  177. panic("unexpected ListKeysByUserID call")
  178. }
  179. func (s *apiKeyRepoStub) ListKeysByGroupID(ctx context.Context, groupID int64) ([]string, error) {
  180. panic("unexpected ListKeysByGroupID call")
  181. }
  182. func (s *apiKeyRepoStub) IncrementQuotaUsed(ctx context.Context, id int64, amount float64) (float64, error) {
  183. panic("unexpected IncrementQuotaUsed call")
  184. }
  185. func (s *apiKeyRepoStub) UpdateLastUsed(ctx context.Context, id int64, usedAt time.Time) error {
  186. s.touchedIDs = append(s.touchedIDs, id)
  187. s.touchedUsedAts = append(s.touchedUsedAts, usedAt)
  188. if s.updateLastUsed != nil {
  189. return s.updateLastUsed(ctx, id, usedAt)
  190. }
  191. return nil
  192. }
  193. func (s *apiKeyRepoStub) IncrementRateLimitUsage(ctx context.Context, id int64, cost float64) error {
  194. panic("unexpected IncrementRateLimitUsage call")
  195. }
  196. func (s *apiKeyRepoStub) ResetRateLimitWindows(ctx context.Context, id int64) error {
  197. panic("unexpected ResetRateLimitWindows call")
  198. }
  199. func (s *apiKeyRepoStub) GetRateLimitData(ctx context.Context, id int64) (*APIKeyRateLimitData, error) {
  200. panic("unexpected GetRateLimitData call")
  201. }
  202. // apiKeyCacheStub 是 APIKeyCache 接口的测试桩实现。
  203. // 用于验证删除操作时缓存清理逻辑是否被正确调用。
  204. //
  205. // 设计说明:
  206. // - invalidated: 记录被清除缓存的用户 ID 列表
  207. type apiKeyCacheStub struct {
  208. invalidated []int64 // 记录调用 DeleteCreateAttemptCount 时传入的用户 ID
  209. deleteAuthKeys []string // 记录调用 DeleteAuthCache 时传入的缓存 key
  210. }
  211. // GetCreateAttemptCount 返回 0,表示用户未超过创建次数限制
  212. func (s *apiKeyCacheStub) GetCreateAttemptCount(ctx context.Context, userID int64) (int, error) {
  213. return 0, nil
  214. }
  215. // IncrementCreateAttemptCount 空实现,本测试不验证此行为
  216. func (s *apiKeyCacheStub) IncrementCreateAttemptCount(ctx context.Context, userID int64) error {
  217. return nil
  218. }
  219. // DeleteCreateAttemptCount 记录被清除缓存的用户 ID。
  220. // 删除 API Key 时会调用此方法清除用户的创建尝试计数缓存。
  221. func (s *apiKeyCacheStub) DeleteCreateAttemptCount(ctx context.Context, userID int64) error {
  222. s.invalidated = append(s.invalidated, userID)
  223. return nil
  224. }
  225. // IncrementDailyUsage 空实现,本测试不验证此行为
  226. func (s *apiKeyCacheStub) IncrementDailyUsage(ctx context.Context, apiKey string) error {
  227. return nil
  228. }
  229. // SetDailyUsageExpiry 空实现,本测试不验证此行为
  230. func (s *apiKeyCacheStub) SetDailyUsageExpiry(ctx context.Context, apiKey string, ttl time.Duration) error {
  231. return nil
  232. }
  233. func (s *apiKeyCacheStub) GetAuthCache(ctx context.Context, key string) (*APIKeyAuthCacheEntry, error) {
  234. return nil, nil
  235. }
  236. func (s *apiKeyCacheStub) SetAuthCache(ctx context.Context, key string, entry *APIKeyAuthCacheEntry, ttl time.Duration) error {
  237. return nil
  238. }
  239. func (s *apiKeyCacheStub) DeleteAuthCache(ctx context.Context, key string) error {
  240. s.deleteAuthKeys = append(s.deleteAuthKeys, key)
  241. return nil
  242. }
  243. func (s *apiKeyCacheStub) PublishAuthCacheInvalidation(ctx context.Context, cacheKey string) error {
  244. return nil
  245. }
  246. func (s *apiKeyCacheStub) SubscribeAuthCacheInvalidation(ctx context.Context, handler func(cacheKey string)) error {
  247. return nil
  248. }
  249. // TestApiKeyService_Delete_OwnerMismatch 测试非所有者尝试删除时返回权限错误。
  250. // 预期行为:
  251. // - GetKeyAndOwnerID 返回所有者 ID 为 1
  252. // - 调用者 userID 为 2(不匹配)
  253. // - 返回 ErrInsufficientPerms 错误
  254. // - Delete 方法不被调用
  255. // - 缓存不被清除
  256. func TestApiKeyService_Delete_OwnerMismatch(t *testing.T) {
  257. repo := &apiKeyRepoStub{
  258. apiKey: &APIKey{ID: 10, UserID: 1, Key: "k"},
  259. }
  260. cache := &apiKeyCacheStub{}
  261. svc := &APIKeyService{apiKeyRepo: repo, cache: cache}
  262. err := svc.Delete(context.Background(), 10, 2) // API Key ID=10, 调用者 userID=2
  263. require.ErrorIs(t, err, ErrInsufficientPerms)
  264. require.Empty(t, repo.deletedIDs) // 验证删除操作未被调用
  265. require.Empty(t, cache.invalidated) // 验证缓存未被清除
  266. require.Empty(t, cache.deleteAuthKeys)
  267. }
  268. // TestApiKeyService_Delete_Success 测试所有者成功删除 API Key 的场景。
  269. // 预期行为:
  270. // - GetKeyAndOwnerID 返回所有者 ID 为 7
  271. // - 调用者 userID 为 7(匹配)
  272. // - Delete 成功执行
  273. // - 缓存被正确清除(使用 ownerID)
  274. // - 返回 nil 错误
  275. func TestApiKeyService_Delete_Success(t *testing.T) {
  276. repo := &apiKeyRepoStub{
  277. apiKey: &APIKey{ID: 42, UserID: 7, Key: "k"},
  278. }
  279. cache := &apiKeyCacheStub{}
  280. svc := &APIKeyService{apiKeyRepo: repo, cache: cache}
  281. svc.lastUsedTouchL1.Store(int64(42), time.Now())
  282. err := svc.Delete(context.Background(), 42, 7) // API Key ID=42, 调用者 userID=7
  283. require.NoError(t, err)
  284. require.Equal(t, []int64{42}, repo.deletedIDs) // 验证正确的 API Key 被删除
  285. require.Equal(t, []int64{7}, cache.invalidated) // 验证所有者的缓存被清除
  286. require.Equal(t, []string{svc.authCacheKey("k")}, cache.deleteAuthKeys)
  287. _, exists := svc.lastUsedTouchL1.Load(int64(42))
  288. require.False(t, exists, "delete should clear touch debounce cache")
  289. }
  290. // TestApiKeyService_Delete_NotFound 测试删除不存在的 API Key 时返回正确的错误。
  291. // 预期行为:
  292. // - GetKeyAndOwnerID 返回 ErrAPIKeyNotFound 错误
  293. // - 返回 ErrAPIKeyNotFound 错误(被 fmt.Errorf 包装)
  294. // - Delete 方法不被调用
  295. // - 缓存不被清除
  296. func TestApiKeyService_Delete_NotFound(t *testing.T) {
  297. repo := &apiKeyRepoStub{getByIDErr: ErrAPIKeyNotFound}
  298. cache := &apiKeyCacheStub{}
  299. svc := &APIKeyService{apiKeyRepo: repo, cache: cache}
  300. err := svc.Delete(context.Background(), 99, 1)
  301. require.ErrorIs(t, err, ErrAPIKeyNotFound)
  302. require.Empty(t, repo.deletedIDs)
  303. require.Empty(t, cache.invalidated)
  304. require.Empty(t, cache.deleteAuthKeys)
  305. }
  306. func TestAPIKeyService_List_FillsCurrentConcurrency(t *testing.T) {
  307. repo := &apiKeyRepoStub{
  308. allowListByUserID: true,
  309. listByUserIDKeys: []APIKey{
  310. {ID: 10, UserID: 7, Key: "sk-10", Name: "key-10"},
  311. {ID: 11, UserID: 7, Key: "sk-11", Name: "key-11"},
  312. },
  313. }
  314. concurrency := NewConcurrencyService(&stubConcurrencyCacheForTest{
  315. apiKeyConcurrency: map[int64]int{10: 2, 11: 0},
  316. })
  317. svc := &APIKeyService{apiKeyRepo: repo, concurrencyService: concurrency}
  318. keys, _, err := svc.List(context.Background(), 7, pagination.PaginationParams{Page: 1, PageSize: 20}, APIKeyListFilters{})
  319. require.NoError(t, err)
  320. require.Len(t, keys, 2)
  321. require.Equal(t, 2, keys[0].CurrentConcurrency)
  322. require.Equal(t, 0, keys[1].CurrentConcurrency)
  323. }
  324. func TestAPIKeyService_List_SortByCurrentConcurrency(t *testing.T) {
  325. groupID := int64(42)
  326. keys := []APIKey{
  327. {ID: 1, UserID: 7, Key: "sk-target-1", Name: "target-one", GroupID: &groupID, Status: StatusActive},
  328. {ID: 2, UserID: 7, Key: "sk-target-2", Name: "target-two", GroupID: &groupID, Status: StatusActive},
  329. {ID: 3, UserID: 7, Key: "sk-target-3", Name: "target-three", GroupID: &groupID, Status: StatusActive},
  330. {ID: 4, UserID: 7, Key: "sk-target-4", Name: "target-four", GroupID: &groupID, Status: StatusActive},
  331. {ID: 9, UserID: 7, Key: "sk-target-9", Name: "target-inactive", GroupID: &groupID, Status: StatusDisabled},
  332. {ID: 10, UserID: 7, Key: "sk-other-10", Name: "other", GroupID: &groupID, Status: StatusActive},
  333. {ID: 11, UserID: 7, Key: "sk-target-11", Name: "target-no-group", Status: StatusActive},
  334. {ID: 12, UserID: 8, Key: "sk-target-12", Name: "target-other-user", GroupID: &groupID, Status: StatusActive},
  335. }
  336. filters := APIKeyListFilters{
  337. Search: "target",
  338. Status: StatusActive,
  339. GroupID: &groupID,
  340. }
  341. repo := &apiKeyRepoStub{
  342. allowListAllByUserID: true,
  343. listAllByUserIDKeys: keys,
  344. }
  345. concurrency := NewConcurrencyService(&stubConcurrencyCacheForTest{
  346. apiKeyConcurrency: map[int64]int{
  347. 1: 5,
  348. 2: 5,
  349. 3: 2,
  350. 4: 8,
  351. 9: 99,
  352. 10: 99,
  353. 11: 99,
  354. 12: 99,
  355. },
  356. })
  357. svc := &APIKeyService{apiKeyRepo: repo, concurrencyService: concurrency}
  358. got, page, err := svc.List(context.Background(), 7, pagination.PaginationParams{
  359. Page: 2,
  360. PageSize: 2,
  361. SortBy: "current_concurrency",
  362. SortOrder: "desc",
  363. }, filters)
  364. require.NoError(t, err)
  365. require.Equal(t, []int64{1, 3}, apiKeyTestIDs(got))
  366. require.Equal(t, int64(4), page.Total)
  367. require.Equal(t, 2, page.Page)
  368. require.Equal(t, 2, page.PageSize)
  369. require.Equal(t, 2, page.Pages)
  370. require.Empty(t, repo.listByUserIDCalls)
  371. require.Equal(t, []int64{7}, repo.listAllByUserIDCalls)
  372. require.Len(t, repo.listAllByUserIDFilters, 1)
  373. require.Equal(t, filters.Search, repo.listAllByUserIDFilters[0].Search)
  374. require.Equal(t, filters.Status, repo.listAllByUserIDFilters[0].Status)
  375. require.NotNil(t, repo.listAllByUserIDFilters[0].GroupID)
  376. require.Equal(t, groupID, *repo.listAllByUserIDFilters[0].GroupID)
  377. }
  378. func TestAPIKeyService_List_SortByCurrentConcurrencyAscTiesByID(t *testing.T) {
  379. repo := &apiKeyRepoStub{
  380. allowListAllByUserID: true,
  381. listAllByUserIDKeys: []APIKey{
  382. {ID: 1, UserID: 7, Key: "sk-1", Name: "one", Status: StatusActive},
  383. {ID: 2, UserID: 7, Key: "sk-2", Name: "two", Status: StatusActive},
  384. {ID: 3, UserID: 7, Key: "sk-3", Name: "three", Status: StatusActive},
  385. {ID: 4, UserID: 7, Key: "sk-4", Name: "four", Status: StatusActive},
  386. },
  387. }
  388. concurrency := NewConcurrencyService(&stubConcurrencyCacheForTest{
  389. apiKeyConcurrency: map[int64]int{1: 5, 2: 5, 3: 2, 4: 8},
  390. })
  391. svc := &APIKeyService{apiKeyRepo: repo, concurrencyService: concurrency}
  392. got, page, err := svc.List(context.Background(), 7, pagination.PaginationParams{
  393. Page: 1,
  394. PageSize: 4,
  395. SortBy: "current_concurrency",
  396. SortOrder: "asc",
  397. }, APIKeyListFilters{})
  398. require.NoError(t, err)
  399. require.Equal(t, []int64{3, 1, 2, 4}, apiKeyTestIDs(got))
  400. require.Equal(t, 4, page.PageSize)
  401. }
  402. func apiKeyTestIDs(keys []APIKey) []int64 {
  403. ids := make([]int64, 0, len(keys))
  404. for _, key := range keys {
  405. ids = append(ids, key.ID)
  406. }
  407. return ids
  408. }
  409. func TestAPIKeyService_GetByID_FillsCurrentConcurrency(t *testing.T) {
  410. repo := &apiKeyRepoStub{
  411. apiKey: &APIKey{ID: 10, UserID: 7, Key: "sk-10", Name: "key-10"},
  412. }
  413. concurrency := NewConcurrencyService(&stubConcurrencyCacheForTest{
  414. apiKeyConcurrency: map[int64]int{10: 4},
  415. })
  416. svc := &APIKeyService{apiKeyRepo: repo, concurrencyService: concurrency}
  417. key, err := svc.GetByID(context.Background(), 10)
  418. require.NoError(t, err)
  419. require.Equal(t, 4, key.CurrentConcurrency)
  420. }
  421. // TestApiKeyService_Delete_DeleteFails 测试删除操作失败时的错误处理。
  422. // 预期行为:
  423. // - GetKeyAndOwnerID 返回正确的所有者 ID
  424. // - 所有权验证通过
  425. // - DeleteWithAudit 被调用但返回错误
  426. // - 删除失败时缓存不被清除(缓存清理在删除成功后执行,消除竞态)
  427. // - 返回包含 "delete api key" 的错误信息
  428. func TestApiKeyService_Delete_DeleteFails(t *testing.T) {
  429. repo := &apiKeyRepoStub{
  430. apiKey: &APIKey{ID: 42, UserID: 3, Key: "k"},
  431. deleteErr: errors.New("delete failed"),
  432. }
  433. cache := &apiKeyCacheStub{}
  434. svc := &APIKeyService{apiKeyRepo: repo, cache: cache}
  435. err := svc.Delete(context.Background(), 3, 3) // API Key ID=3, 调用者 userID=3
  436. require.Error(t, err)
  437. require.ErrorContains(t, err, "delete api key")
  438. require.Equal(t, []int64{3}, repo.deletedIDs) // 验证 DeleteWithAudit 被调用
  439. require.Empty(t, cache.invalidated) // 验证删除失败时缓存未被清除(新顺序:先删后清)
  440. require.Empty(t, cache.deleteAuthKeys) // 验证删除失败时 auth 缓存未被清除
  441. }