|
| 1 | +/* |
| 2 | +Copyright 2019 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 util |
| 18 | + |
| 19 | +import ( |
| 20 | + "fmt" |
| 21 | + "testing" |
| 22 | + "time" |
| 23 | +) |
| 24 | + |
| 25 | +func TestWaitUntilTimeout(t *testing.T) { |
| 26 | + tests := []struct { |
| 27 | + desc string |
| 28 | + timeout time.Duration |
| 29 | + execFunc ExecFunc |
| 30 | + timeoutFunc TimeoutFunc |
| 31 | + expectedErr error |
| 32 | + }{ |
| 33 | + { |
| 34 | + desc: "execFunc returns error", |
| 35 | + timeout: 1 * time.Second, |
| 36 | + execFunc: func() error { |
| 37 | + return fmt.Errorf("execFunc error") |
| 38 | + }, |
| 39 | + timeoutFunc: func() error { |
| 40 | + return fmt.Errorf("timeout error") |
| 41 | + }, |
| 42 | + expectedErr: fmt.Errorf("execFunc error"), |
| 43 | + }, |
| 44 | + { |
| 45 | + desc: "execFunc timeout", |
| 46 | + timeout: 1 * time.Second, |
| 47 | + execFunc: func() error { |
| 48 | + time.Sleep(2 * time.Second) |
| 49 | + return nil |
| 50 | + }, |
| 51 | + timeoutFunc: func() error { |
| 52 | + return fmt.Errorf("timeout error") |
| 53 | + }, |
| 54 | + expectedErr: fmt.Errorf("timeout error"), |
| 55 | + }, |
| 56 | + { |
| 57 | + desc: "execFunc completed successfully", |
| 58 | + timeout: 1 * time.Second, |
| 59 | + execFunc: func() error { |
| 60 | + return nil |
| 61 | + }, |
| 62 | + timeoutFunc: func() error { |
| 63 | + return fmt.Errorf("timeout error") |
| 64 | + }, |
| 65 | + expectedErr: nil, |
| 66 | + }, |
| 67 | + } |
| 68 | + |
| 69 | + for _, test := range tests { |
| 70 | + err := WaitUntilTimeout(test.timeout, test.execFunc, test.timeoutFunc) |
| 71 | + if err != nil && (err.Error() != test.expectedErr.Error()) { |
| 72 | + t.Errorf("unexpected error: %v, expected error: %v", err, test.expectedErr) |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments