...

Source file src/go.etcd.io/etcd/pkg/v3/idutil/id_test.go

Documentation: go.etcd.io/etcd/pkg/v3/idutil

     1  // Copyright 2015 The etcd Authors
     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  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package idutil
    16  
    17  import (
    18  	"testing"
    19  	"time"
    20  )
    21  
    22  func TestNewGenerator(t *testing.T) {
    23  	g := NewGenerator(0x12, time.Unix(0, 0).Add(0x3456*time.Millisecond))
    24  	id := g.Next()
    25  	wid := uint64(0x12000000345601)
    26  	if id != wid {
    27  		t.Errorf("id = %x, want %x", id, wid)
    28  	}
    29  }
    30  
    31  func TestNewGeneratorUnique(t *testing.T) {
    32  	g := NewGenerator(0, time.Time{})
    33  	id := g.Next()
    34  	// different server generates different ID
    35  	g1 := NewGenerator(1, time.Time{})
    36  	if gid := g1.Next(); id == gid {
    37  		t.Errorf("generate the same id %x using different server ID", id)
    38  	}
    39  	// restarted server generates different ID
    40  	g2 := NewGenerator(0, time.Now())
    41  	if gid := g2.Next(); id == gid {
    42  		t.Errorf("generate the same id %x after restart", id)
    43  	}
    44  }
    45  
    46  func TestNext(t *testing.T) {
    47  	g := NewGenerator(0x12, time.Unix(0, 0).Add(0x3456*time.Millisecond))
    48  	wid := uint64(0x12000000345601)
    49  	for i := 0; i < 1000; i++ {
    50  		id := g.Next()
    51  		if id != wid+uint64(i) {
    52  			t.Errorf("id = %x, want %x", id, wid+uint64(i))
    53  		}
    54  	}
    55  }
    56  
    57  func BenchmarkNext(b *testing.B) {
    58  	g := NewGenerator(0x12, time.Now())
    59  
    60  	b.ResetTimer()
    61  	for i := 0; i < b.N; i++ {
    62  		g.Next()
    63  	}
    64  }
    65  

View as plain text