github.com/songzhibin97/gkit@v1.2.13/window/array_test.go (about)

     1  package window
     2  
     3  import (
     4  	"sync/atomic"
     5  	"testing"
     6  	"unsafe"
     7  
     8  	"github.com/songzhibin97/gkit/internal/clock"
     9  	"github.com/stretchr/testify/assert"
    10  	"github.com/stretchr/testify/mock"
    11  )
    12  
    13  const (
    14  	// BucketSize 桶大小
    15  	BucketSize uint64 = 500
    16  	// N: 长度
    17  	N uint64 = 20
    18  	// IntervalSize 时间间隔 10s
    19  	IntervalSize uint64 = 10 * 1000
    20  )
    21  
    22  // mock ArrayMock and implement BucketGenerator
    23  type Mock struct {
    24  	mock.Mock
    25  }
    26  
    27  func (bla *Mock) NewEmptyBucket() interface{} {
    28  	return new(int64)
    29  }
    30  
    31  func (bla *Mock) Reset(b *Bucket, startTime uint64) *Bucket {
    32  	b.Start = startTime
    33  	b.Value.Store(new(int64))
    34  	return b
    35  }
    36  
    37  func TestBucketSize(t *testing.T) {
    38  	b := &Bucket{
    39  		Start: clock.GetTimeMillis(),
    40  		Value: atomic.Value{},
    41  	}
    42  	if !assert.Equal(t, int(unsafe.Sizeof(*b)), 24) {
    43  		t.Errorf("the size of Bucket is not equal 24.\n")
    44  	}
    45  	if !assert.Equal(t, int(unsafe.Sizeof(b)), 8) {
    46  		t.Errorf("the size of Bucket pointer is not equal 8.\n")
    47  	}
    48  }
    49  
    50  func TestGetBucket(t *testing.T) {
    51  	n := (uint64)(5)
    52  	array := NewAtomicArray(n, BucketSize, &Mock{})
    53  	for i := (uint64)(0); i < n; i++ {
    54  		b := array.getBucket(i)
    55  		if !assert.Equal(t, b, array.data[i]) {
    56  			t.Error("getBucket not equal")
    57  		}
    58  	}
    59  }
    60  
    61  func TestCompareAndSwap(t *testing.T) {
    62  	n := (uint64)(5)
    63  	array := NewAtomicArray(n, BucketSize, &Mock{})
    64  	for i := (uint64)(0); i < n; i++ {
    65  		if !array.compareAndSwap(i, array.getBucket(i), array.getBucket(i)) {
    66  			t.Error("compareAndSwap not equal")
    67  		}
    68  	}
    69  }