|
| 1 | +/* |
| 2 | +Copyright 2026 The Knative Authors |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package utils |
| 18 | + |
| 19 | +import ( |
| 20 | + "testing" |
| 21 | + "time" |
| 22 | + |
| 23 | + eventingduckv1 "knative.dev/eventing/pkg/apis/duck/v1" |
| 24 | + "knative.dev/eventing/pkg/kncloudevents" |
| 25 | +) |
| 26 | + |
| 27 | +func TestCalculateNakDelayForRetryNumber(t *testing.T) { |
| 28 | + delay := "PT1S" |
| 29 | + backoffMax := "PT10S" |
| 30 | + exponential := eventingduckv1.BackoffPolicyExponential |
| 31 | + linear := eventingduckv1.BackoffPolicyLinear |
| 32 | + |
| 33 | + newConfig := func(policy eventingduckv1.BackoffPolicyType, max *string) *kncloudevents.RetryConfig { |
| 34 | + t.Helper() |
| 35 | + config, err := kncloudevents.RetryConfigFromDeliverySpec(eventingduckv1.DeliverySpec{ |
| 36 | + BackoffPolicy: &policy, |
| 37 | + BackoffDelay: &delay, |
| 38 | + BackoffMax: max, |
| 39 | + }) |
| 40 | + if err != nil { |
| 41 | + t.Fatal(err) |
| 42 | + } |
| 43 | + return &config |
| 44 | + } |
| 45 | + |
| 46 | + tests := []struct { |
| 47 | + name string |
| 48 | + attempt int |
| 49 | + config *kncloudevents.RetryConfig |
| 50 | + want time.Duration |
| 51 | + }{ |
| 52 | + {name: "nil config", attempt: 1, want: 0}, |
| 53 | + {name: "config without backoff", attempt: 1, config: &kncloudevents.RetryConfig{}, want: 0}, |
| 54 | + {name: "first exponential retry", attempt: 1, config: newConfig(exponential, &backoffMax), want: 2 * time.Second}, |
| 55 | + {name: "uncapped exponential retry", attempt: 4, config: newConfig(exponential, nil), want: 16 * time.Second}, |
| 56 | + {name: "capped exponential retry", attempt: 4, config: newConfig(exponential, &backoffMax), want: 10 * time.Second}, |
| 57 | + {name: "capped linear retry", attempt: 20, config: newConfig(linear, &backoffMax), want: 10 * time.Second}, |
| 58 | + {name: "huge retry stays capped", attempt: int(^uint(0) >> 1), config: newConfig(exponential, &backoffMax), want: 10 * time.Second}, |
| 59 | + } |
| 60 | + |
| 61 | + for _, tt := range tests { |
| 62 | + t.Run(tt.name, func(t *testing.T) { |
| 63 | + if got := CalculateNakDelayForRetryNumber(tt.attempt, tt.config); got != tt.want { |
| 64 | + t.Errorf("CalculateNakDelayForRetryNumber() = %v, want %v", got, tt.want) |
| 65 | + } |
| 66 | + }) |
| 67 | + } |
| 68 | +} |
0 commit comments