1// Copyright 2016-2018 The NATS Authors
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
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
14package nuid
15
16import (
17	"bytes"
18	"testing"
19)
20
21func TestDigits(t *testing.T) {
22	if len(digits) != base {
23		t.Fatalf("digits length does not match base modulo")
24	}
25}
26
27func TestGlobalNUIDInit(t *testing.T) {
28	if globalNUID == nil {
29		t.Fatalf("Expected g to be non-nil\n")
30	}
31	if globalNUID.pre == nil || len(globalNUID.pre) != preLen {
32		t.Fatalf("Expected prefix to be initialized\n")
33	}
34	if globalNUID.seq == 0 {
35		t.Fatalf("Expected seq to be non-zero\n")
36	}
37}
38
39func TestNUIDRollover(t *testing.T) {
40	globalNUID.seq = maxSeq
41	// copy
42	oldPre := append([]byte{}, globalNUID.pre...)
43	Next()
44	if bytes.Equal(globalNUID.pre, oldPre) {
45		t.Fatalf("Expected new pre, got the old one\n")
46	}
47}
48
49func TestGUIDLen(t *testing.T) {
50	nuid := Next()
51	if len(nuid) != totalLen {
52		t.Fatalf("Expected len of %d, got %d\n", totalLen, len(nuid))
53	}
54}
55
56func TestProperPrefix(t *testing.T) {
57	min := byte(255)
58	max := byte(0)
59	for i := 0; i < len(digits); i++ {
60		if digits[i] < min {
61			min = digits[i]
62		}
63		if digits[i] > max {
64			max = digits[i]
65		}
66	}
67	total := 100000
68	for i := 0; i < total; i++ {
69		n := New()
70		for j := 0; j < preLen; j++ {
71			if n.pre[j] < min || n.pre[j] > max {
72				t.Fatalf("Iter %d. Valid range for bytes prefix: [%d..%d]\nIncorrect prefix at pos %d: %v (%s)",
73					i, min, max, j, n.pre, string(n.pre))
74			}
75		}
76	}
77}
78
79func BenchmarkNUIDSpeed(b *testing.B) {
80	n := New()
81	b.ReportAllocs()
82	for i := 0; i < b.N; i++ {
83		n.Next()
84	}
85}
86
87func BenchmarkGlobalNUIDSpeed(b *testing.B) {
88	b.ReportAllocs()
89	for i := 0; i < b.N; i++ {
90		Next()
91	}
92}
93