istio
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
15package retry16
17import (18"fmt"19"testing"20"time"21)
22
23func TestConverge(t *testing.T) {24t.Run("no converge", func(t *testing.T) {25flipFlop := true26err := UntilSuccess(func() error {27flipFlop = !flipFlop28if flipFlop {29return fmt.Errorf("flipFlop was true")30}31return nil32}, Converge(2), Timeout(time.Millisecond*10), Delay(time.Millisecond))33if err == nil {34t.Fatal("expected no convergence, but test passed")35}36})37
38t.Run("converge", func(t *testing.T) {39n := 040err := UntilSuccess(func() error {41n++42if n < 10 {43return fmt.Errorf("%v is too low, try again", n)44}45return nil46}, Converge(2), Timeout(time.Second*10000), Delay(time.Millisecond))47if err != nil {48t.Fatalf("expected convergence, but test failed: %v", err)49}50})51
52t.Run("attempts fail", func(t *testing.T) {53n := 054err := UntilSuccess(func() error {55n++56return fmt.Errorf("oops")57}, MaxAttempts(10), Delay(0))58if err == nil {59t.Fatalf("expected error")60}61if n != 10 {62t.Fatalf("expected exactly 10 attempts, got %d", n)63}64})65
66t.Run("attempts success", func(t *testing.T) {67n := 068err := UntilSuccess(func() error {69n++70if n == 7 {71return nil72}73return fmt.Errorf("oops")74}, MaxAttempts(10), Delay(0))75if err != nil {76t.Fatalf("expected no error, got %v", err)77}78if n != 7 {79t.Fatalf("expected exactly 7 attempts, got %d", n)80}81})82}
83