github.com/cloudwego/kitex@v0.9.0/pkg/limiter/connection_limiter_test.go (about) 1 /* 2 * Copyright 2021 CloudWeGo Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package limiter 18 19 import ( 20 "context" 21 "sync" 22 "sync/atomic" 23 "testing" 24 "time" 25 26 "github.com/cloudwego/kitex/internal/test" 27 ) 28 29 func TestConnectionLimiter(t *testing.T) { 30 connLimit := 50 31 ctx := context.Background() 32 lim := NewConnectionLimiter(connLimit) 33 34 var wg sync.WaitGroup 35 var connCount int32 36 for i := 0; i < 100; i++ { 37 wg.Add(1) 38 go func() { 39 defer wg.Done() 40 for j := 0; j < 10; j++ { 41 if lim.Acquire(ctx) { 42 atomic.AddInt32(&connCount, 1) 43 time.Sleep(time.Millisecond) 44 } else { 45 lim.Release(ctx) 46 time.Sleep(time.Millisecond) 47 } 48 _, curr := lim.Status(ctx) 49 test.Assert(t, curr <= 60, curr) 50 } 51 }() 52 } 53 wg.Wait() 54 test.Assert(t, int(connCount) == connLimit) 55 56 // still limited 57 var newConnCount int32 58 for j := 0; j < 10; j++ { 59 if lim.Acquire(ctx) { 60 atomic.AddInt32(&newConnCount, 1) 61 } else { 62 lim.Release(ctx) 63 } 64 } 65 test.Assert(t, newConnCount == 0) 66 67 // release then new connection can be used 68 for j := 0; j < 10; j++ { 69 lim.Release(ctx) 70 if lim.Acquire(ctx) { 71 atomic.AddInt32(&newConnCount, 1) 72 } else { 73 lim.Release(ctx) 74 } 75 } 76 test.Assert(t, newConnCount == 10) 77 78 lim.(Updatable).UpdateLimit(0) 79 var failedConnCount int32 80 81 for i := 0; i < 100; i++ { 82 wg.Add(1) 83 go func() { 84 defer wg.Done() 85 for j := 0; j < 10; j++ { 86 if !lim.Acquire(ctx) { 87 atomic.AddInt32(&failedConnCount, 1) 88 } 89 } 90 }() 91 } 92 wg.Wait() 93 test.Assert(t, failedConnCount == 0) 94 }