github.com/sacloud/iaas-api-go@v1.12.0/helper/query/referenced_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 query 16 17 import ( 18 "context" 19 "sync" 20 "testing" 21 "time" 22 23 "github.com/sacloud/iaas-api-go" 24 "github.com/sacloud/iaas-api-go/testutil" 25 "github.com/sacloud/iaas-api-go/types" 26 "github.com/stretchr/testify/require" 27 ) 28 29 func TestCheckReferenced_withTimeout(t *testing.T) { 30 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) 31 defer cancel() 32 33 caller := testutil.SingletonAPICaller() 34 var f referenceFindFunc = func(ctx context.Context, caller iaas.APICaller, zone string, id types.ID) (bool, error) { 35 time.Sleep(10 * time.Millisecond) 36 return false, ctx.Err() 37 } 38 39 _, err := checkReferenced(ctx, caller, []string{"tk1v"}, types.ID(0), []referenceFindFunc{f, f}) 40 require.Error(t, err) 41 require.EqualValues(t, "context deadline exceeded", err.Error()) 42 } 43 44 func TestCheckReferenced_withMultipleZone(t *testing.T) { 45 ctx := context.Background() 46 caller := testutil.SingletonAPICaller() 47 var mu sync.Mutex 48 called := 0 49 50 f := func(ctx context.Context, caller iaas.APICaller, zone string, id types.ID) (bool, error) { 51 mu.Lock() 52 defer mu.Unlock() 53 called++ 54 return false, nil 55 } 56 57 zones := []string{"1", "2", "3"} 58 funcs := []referenceFindFunc{f, f, f} 59 result, err := checkReferenced(ctx, caller, zones, types.ID(0), funcs) 60 require.Equal(t, len(zones)*len(funcs), called) 61 require.Equal(t, result, false) 62 require.NoError(t, err) 63 } 64 65 func TestCheckReferenced_shortCircuit(t *testing.T) { 66 ctx := context.Background() 67 caller := testutil.SingletonAPICaller() 68 var mu sync.Mutex 69 called := 0 70 71 f := func(ctx context.Context, caller iaas.APICaller, zone string, id types.ID) (bool, error) { 72 mu.Lock() 73 defer mu.Unlock() 74 called++ 75 if called == 2 { 76 return true, nil 77 } 78 return false, nil 79 } 80 81 zones := []string{"1", "2", "3"} 82 funcs := []referenceFindFunc{f, f, f} 83 result, err := checkReferenced(ctx, caller, zones, types.ID(0), funcs) 84 85 require.Equal(t, 2, called) 86 require.Equal(t, result, true) 87 require.NoError(t, err) 88 }