github.com/uber/kraken@v0.1.4/utils/syncutil/counters_test.go (about)

     1  // Copyright (c) 2016-2019 Uber Technologies, Inc.
     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  package syncutil
    15  
    16  import (
    17  	"sync"
    18  	"testing"
    19  
    20  	"github.com/stretchr/testify/require"
    21  )
    22  
    23  func TestCountersIncrement(t *testing.T) {
    24  	require := require.New(t)
    25  
    26  	c := NewCounters(10)
    27  
    28  	wg := sync.WaitGroup{}
    29  	for k := 0; k < 100; k++ {
    30  		wg.Add(1)
    31  		go func(k int) {
    32  			defer wg.Done()
    33  			c.Increment(k % c.Len())
    34  		}(k)
    35  	}
    36  	wg.Wait()
    37  
    38  	for k := 0; k < c.Len(); k++ {
    39  		require.Equal(10, c.Get(k))
    40  	}
    41  }
    42  
    43  func TestCountersDecrement(t *testing.T) {
    44  	require := require.New(t)
    45  
    46  	c := NewCounters(10)
    47  	for k := 0; k < c.Len(); k++ {
    48  		c.Set(k, 10)
    49  	}
    50  
    51  	wg := sync.WaitGroup{}
    52  	for k := 0; k < 100; k++ {
    53  		wg.Add(1)
    54  		go func(k int) {
    55  			defer wg.Done()
    56  			c.Decrement(k % c.Len())
    57  		}(k)
    58  	}
    59  	wg.Wait()
    60  
    61  	for k := 0; k < c.Len(); k++ {
    62  		require.Equal(0, c.Get(k))
    63  	}
    64  }
    65  
    66  func TestCountersSet(t *testing.T) {
    67  	require := require.New(t)
    68  
    69  	c := NewCounters(10)
    70  
    71  	wg := sync.WaitGroup{}
    72  	for k := 0; k < 100; k++ {
    73  		wg.Add(1)
    74  		go func(k int) {
    75  			defer wg.Done()
    76  			c.Set(k%c.Len(), -1)
    77  		}(k)
    78  	}
    79  	wg.Wait()
    80  
    81  	for k := 0; k < c.Len(); k++ {
    82  		require.Equal(-1, c.Get(k))
    83  	}
    84  }