github.com/alibaba/ilogtail/pkg@v0.0.0-20250526110833-c53b480d046c/helper/async/count_helper.go (about) 1 // Copyright 2023 iLogtail 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 async 16 17 import ( 18 "fmt" 19 "sync/atomic" 20 "time" 21 ) 22 23 type UnittestCounter interface { 24 Begin(callback func()) bool 25 End(timeout time.Duration, expectNum int64) error 26 AddDelta(num int64) 27 } 28 29 type UnitTestCounterHelper struct { 30 signal chan struct{} 31 num int64 32 callback func() 33 } 34 35 func (a *UnitTestCounterHelper) Begin(callback func()) bool { 36 a.signal = make(chan struct{}) 37 a.callback = callback 38 go func() { 39 <-a.signal 40 a.callback() 41 }() 42 return true 43 } 44 45 func (a *UnitTestCounterHelper) End(timeout time.Duration, expectNum int64) error { 46 begin := time.Now() 47 for { 48 if time.Since(begin).Nanoseconds() > timeout.Nanoseconds() { 49 return fmt.Errorf("timeout because unable to go enough events, expect: %d, current: %d", expectNum, atomic.LoadInt64(&a.num)) 50 } 51 if atomic.LoadInt64(&a.num) == expectNum { 52 close(a.signal) 53 break 54 } 55 time.Sleep(time.Millisecond) 56 } 57 return nil 58 } 59 60 func (a *UnitTestCounterHelper) AddDelta(num int64) { 61 atomic.AddInt64(&a.num, num) 62 }