github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/queues/testutils_test.go (about)

     1  package goqueuestest
     2  
     3  import (
     4  	"sync"
     5  	"testing"
     6  	"time"
     7  )
     8  
     9  const (
    10  	testItemCount = 1000
    11  	testTimeout   = 10 * time.Second
    12  )
    13  
    14  func timeout() chan int {
    15  	done := make(chan int)
    16  	go func() {
    17  		select {
    18  		case <-time.After(testTimeout):
    19  			panic("Timeout")
    20  		case <-done:
    21  		}
    22  	}()
    23  	return done
    24  }
    25  
    26  func testReturn(t *testing.T, got interface{}, wasOk bool, expected interface{}, expectedOk bool) {
    27  	if wasOk != expectedOk {
    28  		t.Fatalf("Returned ok=%v expected %v", wasOk, expectedOk)
    29  	}
    30  
    31  	if got != expected {
    32  		t.Fatalf("Returned %v expected %v", got, expected)
    33  	}
    34  }
    35  
    36  func fifoTest(t *testing.T, q Queue) {
    37  	done := timeout()
    38  
    39  	N := testItemCount
    40  	for i := 0; i < N; i += 1 {
    41  		q.Enqueue(i)
    42  	}
    43  
    44  	for i := 0; i < N; i += 1 {
    45  		val, ok := q.Dequeue()
    46  		testReturn(t, val, ok, i, true)
    47  	}
    48  
    49  	for i := 0; i < 5; i += 1 {
    50  		val, ok := q.Dequeue()
    51  		testReturn(t, val, ok, nil, false)
    52  	}
    53  
    54  	done <- 1
    55  }
    56  
    57  func lifoTest(t *testing.T, q Queue) {
    58  	done := timeout()
    59  
    60  	N := testItemCount
    61  	for i := 0; i < N; i += 1 {
    62  		q.Enqueue(i)
    63  	}
    64  
    65  	for i := N - 1; i >= 0; i -= 1 {
    66  		val, ok := q.Dequeue()
    67  		testReturn(t, val, ok, i, true)
    68  	}
    69  
    70  	for i := 0; i < 5; i += 1 {
    71  		val, ok := q.Dequeue()
    72  		testReturn(t, val, ok, nil, false)
    73  	}
    74  	done <- 1
    75  }
    76  
    77  func runParallelTest(t *testing.T, test func(int)) {
    78  	done := timeout()
    79  	cpus := 4
    80  	N := testItemCount / cpus
    81  	wg := &sync.WaitGroup{}
    82  	for i := 0; i < cpus; i += 1 {
    83  		wg.Add(1)
    84  		go func() {
    85  			test(N)
    86  			wg.Done()
    87  		}()
    88  	}
    89  	wg.Wait()
    90  	done <- 1
    91  }
    92  
    93  func queuePTest(t *testing.T, q Queue) {
    94  	runParallelTest(t, func(N int) {
    95  		for i := 0; i < N; i += 1 {
    96  			q.Enqueue(i)
    97  		}
    98  
    99  		for i := 0; i < N; i += 1 {
   100  			_, ok := q.Dequeue()
   101  			if !ok {
   102  				t.Fatalf("Was unable to get value")
   103  			}
   104  		}
   105  	})
   106  }
   107  
   108  func queueP2Test(t *testing.T, q Queue) {
   109  	runParallelTest(t, func(N int) {
   110  		for i := 0; i < N; i += 1 {
   111  			q.Enqueue(i)
   112  			_, ok := q.Dequeue()
   113  			if !ok {
   114  				t.Fatalf("Was unable to get value")
   115  			}
   116  		}
   117  	})
   118  }