github.com/GoWebProd/gip@v0.0.0-20230623090727-b60d41d5d320/stack/stack_test.go (about)

     1  package stack
     2  
     3  import (
     4  	"testing"
     5  )
     6  
     7  func TestStack(t *testing.T) {
     8  	var s Stack[int]
     9  
    10  	_, ok := s.Pop()
    11  	if ok {
    12  		t.Fatal("pop empty stack returns non-nil")
    13  	}
    14  
    15  	i1 := 1
    16  	i2 := 2
    17  	i3 := 3
    18  
    19  	s.Push(i1)
    20  	s.Push(i2)
    21  
    22  	v, _ := s.Pop()
    23  	if v != i2 {
    24  		t.Fatal("pop returns bad value")
    25  	}
    26  
    27  	s.Push(i3)
    28  
    29  	v, _ = s.Pop()
    30  	if v != i3 {
    31  		t.Fatal("pop returns bad value")
    32  	}
    33  
    34  	v, _ = s.Pop()
    35  	if v != i1 {
    36  		t.Fatal("pop returns bad value")
    37  	}
    38  
    39  	_, ok = s.Pop()
    40  	if ok {
    41  		t.Fatal("pop empty stack returns non-nil")
    42  	}
    43  }
    44  
    45  func TestStack2(t *testing.T) {
    46  	var s Stack[int]
    47  
    48  	for i := 0; i < 5; i++ {
    49  		s.Push(i)
    50  	}
    51  
    52  	for i := 4; i >= 0; i-- {
    53  		v, ok := s.Pop()
    54  		if !ok {
    55  			t.Fatal("no value")
    56  		}
    57  
    58  		if v != i {
    59  			t.Fatalf("bad value: %d, expected: %d", v, i)
    60  		}
    61  	}
    62  }
    63  
    64  func BenchmarkLockFree(b *testing.B) {
    65  	var s Stack[int]
    66  
    67  	for i := 0; i < b.N; i++ {
    68  		s.Push(i)
    69  		s.Pop()
    70  	}
    71  }
    72  
    73  func BenchmarkMutex(b *testing.B) {
    74  	s := NewMutexStack[int]()
    75  
    76  	for i := 0; i < b.N; i++ {
    77  		s.Push(i)
    78  		s.Pop()
    79  	}
    80  }