github.com/lfch/etcd-io/tests/v3@v3.0.0-20221004140520-eac99acd3e9d/integration/clientv3/experimental/recipes/v3_barrier_test.go (about) 1 // Copyright 2016 The etcd 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 recipes_test 16 17 import ( 18 "testing" 19 "time" 20 21 "github.com/lfch/etcd-io/client/v3" 22 recipe "github.com/lfch/etcd-io/client/v3/experimental/recipes" 23 integration2 "github.com/lfch/etcd-io/tests/v3/framework/integration" 24 ) 25 26 func TestBarrierSingleNode(t *testing.T) { 27 integration2.BeforeTest(t) 28 clus := integration2.NewCluster(t, &integration2.ClusterConfig{Size: 1}) 29 defer clus.Terminate(t) 30 testBarrier(t, 5, func() *clientv3.Client { return clus.Client(0) }) 31 } 32 33 func TestBarrierMultiNode(t *testing.T) { 34 integration2.BeforeTest(t) 35 clus := integration2.NewCluster(t, &integration2.ClusterConfig{Size: 3}) 36 defer clus.Terminate(t) 37 testBarrier(t, 5, func() *clientv3.Client { return clus.RandClient() }) 38 } 39 40 func testBarrier(t *testing.T, waiters int, chooseClient func() *clientv3.Client) { 41 b := recipe.NewBarrier(chooseClient(), "test-barrier") 42 if err := b.Hold(); err != nil { 43 t.Fatalf("could not hold barrier (%v)", err) 44 } 45 if err := b.Hold(); err == nil { 46 t.Fatalf("able to double-hold barrier") 47 } 48 49 donec := make(chan struct{}) 50 stopc := make(chan struct{}) 51 defer close(stopc) 52 53 for i := 0; i < waiters; i++ { 54 go func() { 55 br := recipe.NewBarrier(chooseClient(), "test-barrier") 56 if err := br.Wait(); err != nil { 57 t.Errorf("could not wait on barrier (%v)", err) 58 } 59 select { 60 case donec <- struct{}{}: 61 case <-stopc: 62 } 63 64 }() 65 } 66 67 select { 68 case <-donec: 69 t.Fatalf("barrier did not wait") 70 default: 71 } 72 73 if err := b.Release(); err != nil { 74 t.Fatalf("could not release barrier (%v)", err) 75 } 76 77 timerC := time.After(time.Duration(waiters*100) * time.Millisecond) 78 for i := 0; i < waiters; i++ { 79 select { 80 case <-timerC: 81 t.Fatalf("barrier timed out") 82 case <-donec: 83 } 84 } 85 }