istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/test/util/retry/retry_test.go (about)

     1  //  Copyright Istio Authors
     2  //
     3  //  Licensed under the Apache License, Version 2.0 (the "License");
     4  //  you may not use this file except in compliance with the License.
     5  //  You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  //  Unless required by applicable law or agreed to in writing, software
    10  //  distributed under the License is distributed on an "AS IS" BASIS,
    11  //  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  //  See the License for the specific language governing permissions and
    13  //  limitations under the License.
    14  
    15  package retry
    16  
    17  import (
    18  	"fmt"
    19  	"testing"
    20  	"time"
    21  )
    22  
    23  func TestConverge(t *testing.T) {
    24  	t.Run("no converge", func(t *testing.T) {
    25  		flipFlop := true
    26  		err := UntilSuccess(func() error {
    27  			flipFlop = !flipFlop
    28  			if flipFlop {
    29  				return fmt.Errorf("flipFlop was true")
    30  			}
    31  			return nil
    32  		}, Converge(2), Timeout(time.Millisecond*10), Delay(time.Millisecond))
    33  		if err == nil {
    34  			t.Fatal("expected no convergence, but test passed")
    35  		}
    36  	})
    37  
    38  	t.Run("converge", func(t *testing.T) {
    39  		n := 0
    40  		err := UntilSuccess(func() error {
    41  			n++
    42  			if n < 10 {
    43  				return fmt.Errorf("%v is too low, try again", n)
    44  			}
    45  			return nil
    46  		}, Converge(2), Timeout(time.Second*10000), Delay(time.Millisecond))
    47  		if err != nil {
    48  			t.Fatalf("expected convergence, but test failed: %v", err)
    49  		}
    50  	})
    51  
    52  	t.Run("attempts fail", func(t *testing.T) {
    53  		n := 0
    54  		err := UntilSuccess(func() error {
    55  			n++
    56  			return fmt.Errorf("oops")
    57  		}, MaxAttempts(10), Delay(0))
    58  		if err == nil {
    59  			t.Fatalf("expected error")
    60  		}
    61  		if n != 10 {
    62  			t.Fatalf("expected exactly 10 attempts, got %d", n)
    63  		}
    64  	})
    65  
    66  	t.Run("attempts success", func(t *testing.T) {
    67  		n := 0
    68  		err := UntilSuccess(func() error {
    69  			n++
    70  			if n == 7 {
    71  				return nil
    72  			}
    73  			return fmt.Errorf("oops")
    74  		}, MaxAttempts(10), Delay(0))
    75  		if err != nil {
    76  			t.Fatalf("expected no error, got %v", err)
    77  		}
    78  		if n != 7 {
    79  			t.Fatalf("expected exactly 7 attempts, got %d", n)
    80  		}
    81  	})
    82  }