github.com/ticketmaster/terraform@v0.10.0-beta2.0.20170711045249-a12daf5aba4f/helper/resource/id_test.go (about)

     1  package resource
     2  
     3  import (
     4  	"regexp"
     5  	"strings"
     6  	"testing"
     7  	"time"
     8  )
     9  
    10  var allDigits = regexp.MustCompile(`^\d+$`)
    11  var allHex = regexp.MustCompile(`^[a-f0-9]+$`)
    12  
    13  func TestUniqueId(t *testing.T) {
    14  	split := func(rest string) (timestamp, increment string) {
    15  		return rest[:18], rest[18:]
    16  	}
    17  
    18  	const prefix = "terraform-"
    19  
    20  	iterations := 10000
    21  	ids := make(map[string]struct{})
    22  	var id, lastId string
    23  	for i := 0; i < iterations; i++ {
    24  		id = UniqueId()
    25  
    26  		if _, ok := ids[id]; ok {
    27  			t.Fatalf("Got duplicated id! %s", id)
    28  		}
    29  
    30  		if !strings.HasPrefix(id, prefix) {
    31  			t.Fatalf("Unique ID didn't have terraform- prefix! %s", id)
    32  		}
    33  
    34  		rest := strings.TrimPrefix(id, prefix)
    35  
    36  		if len(rest) != 26 {
    37  			t.Fatalf("Post-prefix part has wrong length! %s", rest)
    38  		}
    39  
    40  		timestamp, increment := split(rest)
    41  
    42  		if !allDigits.MatchString(timestamp) {
    43  			t.Fatalf("Timestamp not all digits! %s", timestamp)
    44  		}
    45  
    46  		if !allHex.MatchString(increment) {
    47  			t.Fatalf("Increment part not all hex! %s", increment)
    48  		}
    49  
    50  		if lastId != "" && lastId >= id {
    51  			t.Fatalf("IDs not ordered! %s vs %s", lastId, id)
    52  		}
    53  
    54  		ids[id] = struct{}{}
    55  		lastId = id
    56  	}
    57  
    58  	id1 := UniqueId()
    59  	time.Sleep(time.Millisecond)
    60  	id2 := UniqueId()
    61  	timestamp1, _ := split(strings.TrimPrefix(id1, prefix))
    62  	timestamp2, _ := split(strings.TrimPrefix(id2, prefix))
    63  
    64  	if timestamp1 == timestamp2 {
    65  		t.Fatalf("Timestamp part should update at least once a millisecond %s %s",
    66  			id1, id2)
    67  	}
    68  }