github.com/searKing/golang/go@v1.2.117/exp/container/queue/queue_test.go (about)

     1  // Copyright 2022 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package queue_test
     6  
     7  import (
     8  	"testing"
     9  
    10  	"github.com/searKing/golang/go/exp/container/queue"
    11  )
    12  
    13  // For debugging - keep around.
    14  func dump(t *testing.T, r *queue.Queue[int]) {
    15  	if r == nil {
    16  		t.Logf("empty")
    17  		return
    18  	}
    19  	var i int
    20  	r.Do(func(e int) {
    21  		t.Logf("%4d: %d\n", i, e)
    22  		i++
    23  	})
    24  	t.Logf("\n")
    25  }
    26  
    27  func verify(t *testing.T, r *queue.Queue[int], N int, sum int) {
    28  	// Len
    29  	n := r.Len()
    30  	if n != N {
    31  		t.Errorf("r.Len() == %d; expected %d", n, N)
    32  	}
    33  
    34  	// iteration
    35  	n = 0
    36  	s := 0
    37  	r.Do(func(p int) {
    38  		n++
    39  		s += p
    40  	})
    41  	if n != N {
    42  		t.Errorf("number of forward iterations == %d; expected %d", n, N)
    43  	}
    44  	if sum >= 0 && s != sum {
    45  		t.Errorf("forward queue sum = %d; expected %d", s, sum)
    46  	}
    47  
    48  	if r == nil {
    49  		return
    50  	}
    51  }
    52  
    53  func TestCornerCases(t *testing.T) {
    54  	var (
    55  		r0 queue.Queue[int]
    56  		r1 queue.Queue[int]
    57  	)
    58  	r0.PushBack(1)
    59  
    60  	// Basics
    61  	verify(t, &r0, 1, 1)
    62  	verify(t, &r1, 0, 0)
    63  	// Insert
    64  	r1.PushBackQueue(&r0)
    65  	r1.ShrinkToFit()
    66  	verify(t, &r0, 1, 1)
    67  	verify(t, &r1, 1, 1)
    68  	// Insert
    69  	r1.PushBackQueue(&r0)
    70  	r1.ShrinkToFit()
    71  	verify(t, &r0, 1, 1)
    72  	verify(t, &r1, 2, 2)
    73  	// Remove
    74  	r1.PopFront()
    75  	r1.ShrinkToFit()
    76  	verify(t, &r0, 1, 1)
    77  	verify(t, &r1, 1, 1)
    78  	// Remove
    79  	r1.PopFront()
    80  	r1.ShrinkToFit()
    81  	verify(t, &r0, 1, 1)
    82  	verify(t, &r1, 0, 0)
    83  }
    84  
    85  func makeN(n int) *queue.Queue[int] {
    86  	r := queue.New[int]()
    87  	for i := 1; i <= n; i++ {
    88  		r.PushBack(i)
    89  	}
    90  	return r
    91  }
    92  
    93  func sumN(n int) int { return (n*n + n) / 2 }
    94  
    95  func TestNew(t *testing.T) {
    96  	for i := 0; i < 10; i++ {
    97  		r := queue.New[int]()
    98  		verify(t, r, 0, -1)
    99  	}
   100  	for i := 0; i < 10; i++ {
   101  		r := makeN(i)
   102  		verify(t, r, i, sumN(i))
   103  	}
   104  }