github.com/graemephi/kahugo@v0.62.3-0.20211121071557-d78c0423784d/common/types/evictingqueue_test.go (about)

     1  // Copyright 2017-present The Hugo Authors. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  // http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package types
    15  
    16  import (
    17  	"sync"
    18  	"testing"
    19  
    20  	qt "github.com/frankban/quicktest"
    21  )
    22  
    23  func TestEvictingStringQueue(t *testing.T) {
    24  	c := qt.New(t)
    25  
    26  	queue := NewEvictingStringQueue(3)
    27  
    28  	c.Assert(queue.Peek(), qt.Equals, "")
    29  	queue.Add("a")
    30  	queue.Add("b")
    31  	queue.Add("a")
    32  	c.Assert(queue.Peek(), qt.Equals, "b")
    33  	queue.Add("b")
    34  	c.Assert(queue.Peek(), qt.Equals, "b")
    35  
    36  	queue.Add("a")
    37  	queue.Add("b")
    38  
    39  	c.Assert(queue.Contains("a"), qt.Equals, true)
    40  	c.Assert(queue.Contains("foo"), qt.Equals, false)
    41  
    42  	c.Assert(queue.PeekAll(), qt.DeepEquals, []string{"b", "a"})
    43  	c.Assert(queue.Peek(), qt.Equals, "b")
    44  	queue.Add("c")
    45  	queue.Add("d")
    46  	// Overflowed, a should now be removed.
    47  	c.Assert(queue.PeekAll(), qt.DeepEquals, []string{"d", "c", "b"})
    48  	c.Assert(len(queue.PeekAllSet()), qt.Equals, 3)
    49  	c.Assert(queue.PeekAllSet()["c"], qt.Equals, true)
    50  }
    51  
    52  func TestEvictingStringQueueConcurrent(t *testing.T) {
    53  	var wg sync.WaitGroup
    54  	val := "someval"
    55  
    56  	queue := NewEvictingStringQueue(3)
    57  
    58  	for j := 0; j < 100; j++ {
    59  		wg.Add(1)
    60  		go func() {
    61  			defer wg.Done()
    62  			queue.Add(val)
    63  			v := queue.Peek()
    64  			if v != val {
    65  				t.Error("wrong val")
    66  			}
    67  			vals := queue.PeekAll()
    68  			if len(vals) != 1 || vals[0] != val {
    69  				t.Error("wrong val")
    70  			}
    71  		}()
    72  	}
    73  	wg.Wait()
    74  }