github.com/sacloud/iaas-api-go@v1.12.0/helper/wait/simple_state_waiter_test.go (about) 1 // Copyright 2016-2022 The sacloud/iaas-api-go 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 wait 16 17 import ( 18 "context" 19 "errors" 20 "testing" 21 "time" 22 23 "github.com/stretchr/testify/require" 24 ) 25 26 func TestSimpleStateWaiter(t *testing.T) { 27 t.Run("timeout", func(t *testing.T) { 28 waiter := &SimpleStateWaiter{ 29 ReadStateFunc: func() (bool, error) { 30 return false, nil 31 }, 32 Timeout: 100 * time.Millisecond, 33 PollingInterval: 1 * time.Millisecond, 34 } 35 ctx := context.Background() 36 _, err := waiter.WaitForState(ctx) 37 require.Error(t, err) 38 require.EqualError(t, err, "context deadline exceeded") 39 }) 40 41 t.Run("parent context was canceled", func(t *testing.T) { 42 waiter := &SimpleStateWaiter{ 43 ReadStateFunc: func() (bool, error) { 44 return false, nil 45 }, 46 Timeout: 100 * time.Millisecond, 47 PollingInterval: 1 * time.Millisecond, 48 } 49 ctx, cancel := context.WithCancel(context.Background()) 50 defer cancel() 51 52 _, err := waiter.WaitForState(ctx) 53 go func() { 54 time.Sleep(5 * time.Millisecond) 55 cancel() 56 }() 57 58 require.Error(t, err) 59 require.EqualError(t, err, "context deadline exceeded") 60 }) 61 62 t.Run("ReadStateFunc returns false", func(t *testing.T) { 63 retry := 5 64 read := 0 65 waiter := &SimpleStateWaiter{ 66 ReadStateFunc: func() (bool, error) { 67 read++ 68 if read < retry { 69 return false, nil 70 } 71 return true, nil 72 }, 73 Timeout: 100 * time.Millisecond, 74 PollingInterval: 1 * time.Millisecond, 75 } 76 ctx := context.Background() 77 _, err := waiter.WaitForState(ctx) 78 79 require.NoError(t, err) 80 require.Equal(t, retry, read) 81 }) 82 83 t.Run("ReadStateFunc got unexpected error", func(t *testing.T) { 84 waiter := &SimpleStateWaiter{ 85 ReadStateFunc: func() (bool, error) { 86 return false, errors.New("dummy") 87 }, 88 Timeout: 100 * time.Millisecond, 89 PollingInterval: 1 * time.Millisecond, 90 } 91 ctx := context.Background() 92 _, err := waiter.WaitForState(ctx) 93 94 require.Error(t, err) 95 require.EqualError(t, err, "dummy") 96 }) 97 }