2014-11-06 23:13:45 +01:00
|
|
|
// Written in 2011-2014 by Dmitry Chestnykh
|
|
|
|
//
|
|
|
|
// The author(s) have dedicated all copyright and related and
|
|
|
|
// neighboring rights to this software to the public domain
|
|
|
|
// worldwide. Distributed without any warranty.
|
|
|
|
// http://creativecommons.org/publicdomain/zero/1.0/
|
|
|
|
|
2011-04-05 17:57:25 +02:00
|
|
|
package uniuri
|
|
|
|
|
|
|
|
import "testing"
|
|
|
|
|
2014-08-09 15:08:44 +02:00
|
|
|
func validateChars(t *testing.T, u string, chars []byte) {
|
2011-04-05 17:57:25 +02:00
|
|
|
for _, c := range u {
|
|
|
|
var present bool
|
2015-01-21 19:39:59 +01:00
|
|
|
for _, a := range chars {
|
2012-01-16 14:29:26 +01:00
|
|
|
if rune(a) == c {
|
2011-04-05 17:57:25 +02:00
|
|
|
present = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !present {
|
|
|
|
t.Fatalf("chars not allowed in %q", u)
|
|
|
|
}
|
|
|
|
}
|
2014-08-09 15:08:44 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func TestNew(t *testing.T) {
|
|
|
|
u := New()
|
|
|
|
// Check length
|
|
|
|
if len(u) != StdLen {
|
|
|
|
t.Fatalf("wrong length: expected %d, got %d", StdLen, len(u))
|
|
|
|
}
|
|
|
|
// Check that only allowed characters are present
|
|
|
|
validateChars(t, u, StdChars)
|
|
|
|
|
2011-04-05 17:57:25 +02:00
|
|
|
// Generate 1000 uniuris and check that they are unique
|
|
|
|
uris := make([]string, 1000)
|
2015-01-21 10:07:48 +01:00
|
|
|
for i := range uris {
|
2011-04-05 17:57:25 +02:00
|
|
|
uris[i] = New()
|
|
|
|
}
|
|
|
|
for i, u := range uris {
|
|
|
|
for j, u2 := range uris {
|
|
|
|
if i != j && u == u2 {
|
2015-01-21 10:07:48 +01:00
|
|
|
t.Fatalf("not unique: %d:%q and %d:%q", i, u, j, u2)
|
2011-04-05 17:57:25 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2014-08-09 15:08:44 +02:00
|
|
|
|
2015-01-21 18:36:13 +01:00
|
|
|
func TestNewLen(t *testing.T) {
|
|
|
|
for i := 0; i < 100; i++ {
|
|
|
|
u := NewLen(i)
|
|
|
|
if len(u) != i {
|
|
|
|
t.Fatalf("request length %d, got %d", i, len(u))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-08-09 15:08:44 +02:00
|
|
|
func TestNewLenChars(t *testing.T) {
|
|
|
|
length := 10
|
|
|
|
chars := []byte("01234567")
|
|
|
|
u := NewLenChars(length, chars)
|
|
|
|
|
|
|
|
// Check length
|
|
|
|
if len(u) != length {
|
|
|
|
t.Fatalf("wrong length: expected %d, got %d", StdLen, len(u))
|
|
|
|
}
|
|
|
|
// Check that only allowed characters are present
|
|
|
|
validateChars(t, u, chars)
|
2014-08-09 17:03:38 +02:00
|
|
|
|
|
|
|
// Check that two generated strings are different
|
|
|
|
u2 := NewLenChars(length, chars)
|
|
|
|
if u == u2 {
|
|
|
|
t.Fatalf("not unique: %q and %q", u, u2)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestNewLenCharsMaxLength(t *testing.T) {
|
|
|
|
defer func() {
|
|
|
|
if r := recover(); r == nil {
|
|
|
|
t.Fatal("didn't panic")
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
chars := make([]byte, 257)
|
|
|
|
NewLenChars(32, chars)
|
2014-08-09 15:08:44 +02:00
|
|
|
}
|