github.com/kovansky/hugo@v0.92.3-0.20220224232819-63076e4ff19f/identity/identity_test.go (about)

     1  // Copyright 2019 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 identity
    15  
    16  import (
    17  	"fmt"
    18  	"math/rand"
    19  	"strconv"
    20  	"testing"
    21  
    22  	qt "github.com/frankban/quicktest"
    23  )
    24  
    25  func TestIdentityManager(t *testing.T) {
    26  	c := qt.New(t)
    27  
    28  	id1 := testIdentity{name: "id1"}
    29  	im := NewManager(id1)
    30  
    31  	c.Assert(im.Search(id1).GetIdentity(), qt.Equals, id1)
    32  	c.Assert(im.Search(testIdentity{name: "notfound"}), qt.Equals, nil)
    33  }
    34  
    35  func BenchmarkIdentityManager(b *testing.B) {
    36  	createIds := func(num int) []Identity {
    37  		ids := make([]Identity, num)
    38  		for i := 0; i < num; i++ {
    39  			ids[i] = testIdentity{name: fmt.Sprintf("id%d", i)}
    40  		}
    41  		return ids
    42  	}
    43  
    44  	b.Run("Add", func(b *testing.B) {
    45  		c := qt.New(b)
    46  		b.StopTimer()
    47  		ids := createIds(b.N)
    48  		im := NewManager(testIdentity{"first"})
    49  		b.StartTimer()
    50  
    51  		for i := 0; i < b.N; i++ {
    52  			im.Add(ids[i])
    53  		}
    54  
    55  		b.StopTimer()
    56  		c.Assert(im.GetIdentities(), qt.HasLen, b.N+1)
    57  	})
    58  
    59  	b.Run("Search", func(b *testing.B) {
    60  		c := qt.New(b)
    61  		b.StopTimer()
    62  		ids := createIds(b.N)
    63  		im := NewManager(testIdentity{"first"})
    64  
    65  		for i := 0; i < b.N; i++ {
    66  			im.Add(ids[i])
    67  		}
    68  
    69  		b.StartTimer()
    70  
    71  		for i := 0; i < b.N; i++ {
    72  			name := "id" + strconv.Itoa(rand.Intn(b.N))
    73  			id := im.Search(testIdentity{name: name})
    74  			c.Assert(id.GetIdentity().Name(), qt.Equals, name)
    75  		}
    76  	})
    77  }
    78  
    79  type testIdentity struct {
    80  	name string
    81  }
    82  
    83  func (id testIdentity) GetIdentity() Identity {
    84  	return id
    85  }
    86  
    87  func (id testIdentity) Name() string {
    88  	return id.name
    89  }