2015-04-22 19:53:05 +02:00
|
|
|
package resource
|
|
|
|
|
|
|
|
import (
|
2016-08-17 04:40:05 +02:00
|
|
|
"regexp"
|
2015-04-22 19:53:05 +02:00
|
|
|
"strings"
|
|
|
|
"testing"
|
2017-06-13 22:58:31 +02:00
|
|
|
"time"
|
2015-04-22 19:53:05 +02:00
|
|
|
)
|
|
|
|
|
2017-06-13 22:58:31 +02:00
|
|
|
var allDigits = regexp.MustCompile(`^\d+$`)
|
2016-11-16 03:09:32 +01:00
|
|
|
var allHex = regexp.MustCompile(`^[a-f0-9]+$`)
|
2016-08-17 04:40:05 +02:00
|
|
|
|
2015-04-22 19:53:05 +02:00
|
|
|
func TestUniqueId(t *testing.T) {
|
2017-06-13 22:58:31 +02:00
|
|
|
split := func(rest string) (timestamp, increment string) {
|
|
|
|
return rest[:18], rest[18:]
|
|
|
|
}
|
|
|
|
|
2015-04-22 19:53:05 +02:00
|
|
|
iterations := 10000
|
|
|
|
ids := make(map[string]struct{})
|
2016-08-17 04:40:05 +02:00
|
|
|
var id, lastId string
|
2015-04-22 19:53:05 +02:00
|
|
|
for i := 0; i < iterations; i++ {
|
|
|
|
id = UniqueId()
|
|
|
|
|
|
|
|
if _, ok := ids[id]; ok {
|
|
|
|
t.Fatalf("Got duplicated id! %s", id)
|
|
|
|
}
|
|
|
|
|
2018-03-11 02:56:13 +01:00
|
|
|
if !strings.HasPrefix(id, UniqueIdPrefix) {
|
2015-04-22 19:53:05 +02:00
|
|
|
t.Fatalf("Unique ID didn't have terraform- prefix! %s", id)
|
|
|
|
}
|
|
|
|
|
2018-03-11 02:56:13 +01:00
|
|
|
rest := strings.TrimPrefix(id, UniqueIdPrefix)
|
2016-08-17 04:40:05 +02:00
|
|
|
|
2018-03-11 02:56:13 +01:00
|
|
|
if len(rest) != UniqueIDSuffixLength {
|
2016-08-17 04:40:05 +02:00
|
|
|
t.Fatalf("Post-prefix part has wrong length! %s", rest)
|
|
|
|
}
|
|
|
|
|
2017-06-13 22:58:31 +02:00
|
|
|
timestamp, increment := split(rest)
|
|
|
|
|
|
|
|
if !allDigits.MatchString(timestamp) {
|
|
|
|
t.Fatalf("Timestamp not all digits! %s", timestamp)
|
|
|
|
}
|
|
|
|
|
|
|
|
if !allHex.MatchString(increment) {
|
|
|
|
t.Fatalf("Increment part not all hex! %s", increment)
|
2016-08-17 04:40:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if lastId != "" && lastId >= id {
|
|
|
|
t.Fatalf("IDs not ordered! %s vs %s", lastId, id)
|
|
|
|
}
|
|
|
|
|
2015-04-22 19:53:05 +02:00
|
|
|
ids[id] = struct{}{}
|
2016-08-17 04:40:05 +02:00
|
|
|
lastId = id
|
2015-04-22 19:53:05 +02:00
|
|
|
}
|
2017-06-13 22:58:31 +02:00
|
|
|
|
|
|
|
id1 := UniqueId()
|
|
|
|
time.Sleep(time.Millisecond)
|
|
|
|
id2 := UniqueId()
|
2018-03-11 02:56:13 +01:00
|
|
|
timestamp1, _ := split(strings.TrimPrefix(id1, UniqueIdPrefix))
|
|
|
|
timestamp2, _ := split(strings.TrimPrefix(id2, UniqueIdPrefix))
|
2017-06-13 22:58:31 +02:00
|
|
|
|
|
|
|
if timestamp1 == timestamp2 {
|
|
|
|
t.Fatalf("Timestamp part should update at least once a millisecond %s %s",
|
|
|
|
id1, id2)
|
|
|
|
}
|
2015-04-22 19:53:05 +02:00
|
|
|
}
|