github.com/cloudwego/kitex@v0.9.0/pkg/utils/max_counter_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 utils
    18  
    19  import (
    20  	"sync"
    21  	"sync/atomic"
    22  	"testing"
    23  
    24  	"github.com/cloudwego/kitex/internal/test"
    25  )
    26  
    27  func TestMaxCounter_Inc(t *testing.T) {
    28  	var wg sync.WaitGroup
    29  	var cnt int64
    30  
    31  	// max > 0
    32  	counter := NewMaxCounter(10)
    33  	for i := 0; i < 100; i++ {
    34  		wg.Add(1)
    35  		go func() {
    36  			defer wg.Done()
    37  			if counter.Inc() {
    38  				atomic.AddInt64(&cnt, 1)
    39  			}
    40  		}()
    41  	}
    42  	wg.Wait()
    43  	test.Assert(t, cnt == 10)
    44  
    45  	// max == 0
    46  	cnt = 0
    47  	counter = NewMaxCounter(0)
    48  	for i := 0; i < 100; i++ {
    49  		wg.Add(1)
    50  		go func() {
    51  			defer wg.Done()
    52  			if counter.Inc() {
    53  				atomic.AddInt64(&cnt, 1)
    54  			}
    55  		}()
    56  	}
    57  	wg.Wait()
    58  	test.Assert(t, cnt == 0)
    59  
    60  	// max < 0
    61  	cnt = 0
    62  	counter = NewMaxCounter(-1)
    63  	for i := 0; i < 100; i++ {
    64  		wg.Add(1)
    65  		go func() {
    66  			defer wg.Done()
    67  			if counter.Inc() {
    68  				atomic.AddInt64(&cnt, 1)
    69  			}
    70  		}()
    71  	}
    72  	wg.Wait()
    73  	test.Assert(t, cnt == 0)
    74  }
    75  
    76  func TestMaxCounter_Dec(t *testing.T) {
    77  	var wg sync.WaitGroup
    78  
    79  	counter := NewMaxCounter(10)
    80  	for i := 0; i < 100; i++ {
    81  		wg.Add(1)
    82  		go func() {
    83  			defer wg.Done()
    84  			counter.Dec()
    85  		}()
    86  	}
    87  	wg.Wait()
    88  	test.Assert(t, atomic.LoadInt64(&counter.now) == -100)
    89  }