github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/util/ring/buffer_test.go (about)

     1  // Licensed under the Apache License, Version 2.0 (the "License");
     2  // you may not use this file except in compliance with the License.
     3  // You may obtain a copy of the License at
     4  //
     5  //     https://www.apache.org/licenses/LICENSE-2.0
     6  //
     7  // Unless required by applicable law or agreed to in writing, software
     8  // distributed under the License is distributed on an "AS IS" BASIS,
     9  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    10  // See the License for the specific language governing permissions and
    11  // limitations under the License.
    12  //
    13  // Original source: github.com/micro/go-micro/v3/util/ring/buffer_test.go
    14  
    15  package ring
    16  
    17  import (
    18  	"testing"
    19  	"time"
    20  )
    21  
    22  func TestBuffer(t *testing.T) {
    23  	b := New(10)
    24  
    25  	// test one value
    26  	b.Put("foo")
    27  	v := b.Get(1)
    28  
    29  	if val := v[0].Value.(string); val != "foo" {
    30  		t.Fatalf("expected foo got %v", val)
    31  	}
    32  
    33  	b = New(10)
    34  
    35  	// test 10 values
    36  	for i := 0; i < 10; i++ {
    37  		b.Put(i)
    38  	}
    39  
    40  	d := time.Now()
    41  	v = b.Get(10)
    42  
    43  	for i := 0; i < 10; i++ {
    44  		val := v[i].Value.(int)
    45  
    46  		if val != i {
    47  			t.Fatalf("expected %d got %d", i, val)
    48  		}
    49  	}
    50  
    51  	// test more values
    52  
    53  	for i := 0; i < 10; i++ {
    54  		v := i * 2
    55  		b.Put(v)
    56  	}
    57  
    58  	v = b.Get(10)
    59  
    60  	for i := 0; i < 10; i++ {
    61  		val := v[i].Value.(int)
    62  		expect := i * 2
    63  		if val != expect {
    64  			t.Fatalf("expected %d got %d", expect, val)
    65  		}
    66  	}
    67  
    68  	// sleep 100 ms
    69  	time.Sleep(time.Millisecond * 100)
    70  
    71  	// assume we'll get everything
    72  	v = b.Since(d)
    73  
    74  	if len(v) != 10 {
    75  		t.Fatalf("expected 10 entries but got %d", len(v))
    76  	}
    77  
    78  	// write 1 more entry
    79  	d = time.Now()
    80  	b.Put(100)
    81  
    82  	// sleep 100 ms
    83  	time.Sleep(time.Millisecond * 100)
    84  
    85  	v = b.Since(d)
    86  	if len(v) != 1 {
    87  		t.Fatalf("expected 1 entries but got %d", len(v))
    88  	}
    89  
    90  	if v[0].Value.(int) != 100 {
    91  		t.Fatalf("expected value 100 got %v", v[0])
    92  	}
    93  }