| 1 |
/* |
| 2 |
Copyright 2016 The Kubernetes 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 retry |
| 18 |
|
| 19 |
import ( |
| 20 |
"fmt" |
| 21 |
"testing" |
| 22 |
|
| 23 |
"k8s.io/apimachinery/pkg/api/errors" |
| 24 |
"k8s.io/apimachinery/pkg/runtime/schema" |
| 25 |
"k8s.io/apimachinery/pkg/util/wait" |
| 26 |
) |
| 27 |
|
| 28 |
func TestRetryOnConflict(t *testing.T) { |
| 29 |
opts := wait.Backoff{Factor: 1.0, Steps: 3} |
| 30 |
conflictErr := errors.NewConflict(schema.GroupResource{Resource: "test"}, "other", nil) |
| 31 |
|
| 32 |
// never returns |
| 33 |
err := RetryOnConflict(opts, func() error { |
| 34 |
return conflictErr |
| 35 |
}) |
| 36 |
if err != conflictErr { |
| 37 |
t.Errorf("unexpected error: %v", err) |
| 38 |
} |
| 39 |
|
| 40 |
// returns immediately |
| 41 |
i := 0 |
| 42 |
err = RetryOnConflict(opts, func() error { |
| 43 |
i++ |
| 44 |
return nil |
| 45 |
}) |
| 46 |
if err != nil || i != 1 { |
| 47 |
t.Errorf("unexpected error: %v", err) |
| 48 |
} |
| 49 |
|
| 50 |
// returns immediately on error |
| 51 |
testErr := fmt.Errorf("some other error") |
| 52 |
err = RetryOnConflict(opts, func() error { |
| 53 |
return testErr |
| 54 |
}) |
| 55 |
if err != testErr { |
| 56 |
t.Errorf("unexpected error: %v", err) |
| 57 |
} |
| 58 |
|
| 59 |
// keeps retrying |
| 60 |
i = 0 |
| 61 |
err = RetryOnConflict(opts, func() error { |
| 62 |
if i < 2 { |
| 63 |
i++ |
| 64 |
return errors.NewConflict(schema.GroupResource{Resource: "test"}, "other", nil) |
| 65 |
} |
| 66 |
return nil |
| 67 |
}) |
| 68 |
if err != nil || i != 2 { |
| 69 |
t.Errorf("unexpected error: %v", err) |
| 70 |
} |
| 71 |
} |