scheduler_snapshot_cancellation_test.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //go:build unit
  2. package service
  3. import (
  4. "context"
  5. "testing"
  6. "github.com/stretchr/testify/require"
  7. )
  8. type schedulerCancellationCache struct {
  9. SchedulerCache
  10. cancel context.CancelFunc
  11. tokenCaptures int
  12. }
  13. func (c *schedulerCancellationCache) GetSnapshot(ctx context.Context, _ SchedulerBucket) ([]*Account, bool, error) {
  14. c.cancel()
  15. return nil, false, ctx.Err()
  16. }
  17. func (c *schedulerCancellationCache) CaptureBucketWriteToken(ctx context.Context, _ SchedulerBucket) (SchedulerBucketWriteToken, error) {
  18. c.tokenCaptures++
  19. return SchedulerBucketWriteToken{}, ctx.Err()
  20. }
  21. func (c *schedulerCancellationCache) GetAccount(ctx context.Context, _ int64) (*Account, error) {
  22. c.cancel()
  23. return nil, ctx.Err()
  24. }
  25. type schedulerCancellationAccountRepo struct {
  26. AccountRepository
  27. listCalls int
  28. getByIDCalls int
  29. }
  30. func (r *schedulerCancellationAccountRepo) ListSchedulableUngroupedByPlatform(ctx context.Context, _ string) ([]Account, error) {
  31. r.listCalls++
  32. return nil, ctx.Err()
  33. }
  34. func (r *schedulerCancellationAccountRepo) GetByID(ctx context.Context, _ int64) (*Account, error) {
  35. r.getByIDCalls++
  36. return nil, ctx.Err()
  37. }
  38. func TestSchedulerSnapshotListStopsAfterRequestCancellation(t *testing.T) {
  39. ctx, cancel := context.WithCancel(context.Background())
  40. t.Cleanup(cancel)
  41. cache := &schedulerCancellationCache{cancel: cancel}
  42. repo := &schedulerCancellationAccountRepo{}
  43. svc := NewSchedulerSnapshotService(cache, nil, repo, nil, nil)
  44. accounts, useMixed, err := svc.ListSchedulableAccounts(ctx, nil, PlatformOpenAI, false)
  45. require.ErrorIs(t, err, context.Canceled)
  46. require.Nil(t, accounts)
  47. require.False(t, useMixed)
  48. require.Zero(t, cache.tokenCaptures, "canceled requests must not capture a cache publish token")
  49. require.Zero(t, repo.listCalls, "canceled requests must not fall back to the database")
  50. }
  51. func TestSchedulerSnapshotGetAccountStopsAfterRequestCancellation(t *testing.T) {
  52. ctx, cancel := context.WithCancel(context.Background())
  53. t.Cleanup(cancel)
  54. cache := &schedulerCancellationCache{cancel: cancel}
  55. repo := &schedulerCancellationAccountRepo{}
  56. svc := NewSchedulerSnapshotService(cache, nil, repo, nil, nil)
  57. account, err := svc.GetAccount(ctx, 42)
  58. require.ErrorIs(t, err, context.Canceled)
  59. require.Nil(t, account)
  60. require.Zero(t, repo.getByIDCalls, "canceled requests must not fall back to the database")
  61. }