2021-09-16 15:31:20 +03:00
|
|
|
package id
|
|
|
|
|
|
|
|
import (
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/require"
|
2021-09-16 15:40:06 +03:00
|
|
|
mid "github.com/unistack-org/micro/v3/util/id"
|
2021-09-16 15:31:20 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestHasNoCollisions(t *testing.T) {
|
|
|
|
tries := 100_000
|
|
|
|
used := make(map[string]bool, tries)
|
|
|
|
for i := 0; i < tries; i++ {
|
2021-09-16 15:40:06 +03:00
|
|
|
id := mid.Must()
|
2021-09-16 15:31:20 +03:00
|
|
|
require.False(t, used[id], "shouldn't return colliding IDs")
|
|
|
|
used[id] = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestFlatDistribution(t *testing.T) {
|
|
|
|
tries := 100_000
|
|
|
|
alphabet := "abcdefghij"
|
|
|
|
size := 10
|
|
|
|
chars := make(map[rune]int)
|
|
|
|
for i := 0; i < tries; i++ {
|
2021-09-16 15:40:06 +03:00
|
|
|
id := mid.Must(mid.Alphabet(alphabet), mid.Size(size))
|
2021-09-16 15:31:20 +03:00
|
|
|
for _, r := range id {
|
|
|
|
chars[r]++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, count := range chars {
|
|
|
|
require.InEpsilon(t, size*tries/len(alphabet), count, .01, "should have flat distribution")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Benchmark id generator
|
|
|
|
func BenchmarkNanoid(b *testing.B) {
|
|
|
|
for n := 0; n < b.N; n++ {
|
2021-09-16 15:40:06 +03:00
|
|
|
_, _ = mid.New()
|
2021-09-16 15:31:20 +03:00
|
|
|
}
|
|
|
|
}
|