|
| 1 | +package premium |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "testing" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/stretchr/testify/require" |
| 10 | +) |
| 11 | + |
| 12 | +type quotaResponse struct { |
| 13 | + hasQuota bool |
| 14 | + err error |
| 15 | +} |
| 16 | + |
| 17 | +func newFakeQuotaMonitor(hasQuota ...quotaResponse) *fakeQuotaMonitor { |
| 18 | + return &fakeQuotaMonitor{responses: hasQuota} |
| 19 | +} |
| 20 | + |
| 21 | +type fakeQuotaMonitor struct { |
| 22 | + responses []quotaResponse |
| 23 | + calls int |
| 24 | +} |
| 25 | + |
| 26 | +func (f *fakeQuotaMonitor) HasQuota(_ context.Context) (bool, error) { |
| 27 | + resp := f.responses[f.calls] |
| 28 | + if f.calls < len(f.responses)-1 { |
| 29 | + f.calls++ |
| 30 | + } |
| 31 | + return resp.hasQuota, resp.err |
| 32 | +} |
| 33 | + |
| 34 | +func TestWithCancelOnQuotaExceeded_NoInitialQuota(t *testing.T) { |
| 35 | + ctx := context.Background() |
| 36 | + |
| 37 | + responses := []quotaResponse{ |
| 38 | + {false, nil}, |
| 39 | + } |
| 40 | + _, err := WithCancelOnQuotaExceeded(ctx, newFakeQuotaMonitor(responses...)) |
| 41 | + |
| 42 | + require.Error(t, err) |
| 43 | +} |
| 44 | + |
| 45 | +func TestWithCancelOnQuotaExceeded_NoQuota(t *testing.T) { |
| 46 | + ctx := context.Background() |
| 47 | + |
| 48 | + responses := []quotaResponse{ |
| 49 | + {true, nil}, |
| 50 | + {false, nil}, |
| 51 | + } |
| 52 | + ctx, err := WithCancelOnQuotaExceeded(ctx, newFakeQuotaMonitor(responses...), WithQuotaCheckPeriod(1*time.Millisecond)) |
| 53 | + require.NoError(t, err) |
| 54 | + |
| 55 | + <-ctx.Done() |
| 56 | + cause := context.Cause(ctx) |
| 57 | + require.Equal(t, ErrNoQuota, cause) |
| 58 | +} |
| 59 | + |
| 60 | +func TestWithCancelOnQuotaCheckConsecutiveFailures(t *testing.T) { |
| 61 | + ctx := context.Background() |
| 62 | + |
| 63 | + responses := []quotaResponse{ |
| 64 | + {true, nil}, |
| 65 | + {false, errors.New("test2")}, |
| 66 | + {false, errors.New("test3")}, |
| 67 | + } |
| 68 | + ctx, err := WithCancelOnQuotaExceeded(ctx, |
| 69 | + newFakeQuotaMonitor(responses...), |
| 70 | + WithQuotaCheckPeriod(1*time.Millisecond), |
| 71 | + WithQuotaMaxConsecutiveFailures(2), |
| 72 | + ) |
| 73 | + require.NoError(t, err) |
| 74 | + <-ctx.Done() |
| 75 | + cause := context.Cause(ctx) |
| 76 | + require.Equal(t, "test2\ntest3", cause.Error()) |
| 77 | +} |
0 commit comments