github.com/tushar-armorcode/terraform@v0.11.12-beta1/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  	iterations := 10000
    19  	ids := make(map[string]struct{})
    20  	var id, lastId string
    21  	for i := 0; i < iterations; i++ {
    22  		id = UniqueId()
    23  
    24  		if _, ok := ids[id]; ok {
    25  			t.Fatalf("Got duplicated id! %s", id)
    26  		}
    27  
    28  		if !strings.HasPrefix(id, UniqueIdPrefix) {
    29  			t.Fatalf("Unique ID didn't have terraform- prefix! %s", id)
    30  		}
    31  
    32  		rest := strings.TrimPrefix(id, UniqueIdPrefix)
    33  
    34  		if len(rest) != UniqueIDSuffixLength {
    35  			t.Fatalf("PrefixedUniqueId is out of sync with UniqueIDSuffixLength, post-prefix part has wrong length! %s", rest)
    36  		}
    37  
    38  		timestamp, increment := split(rest)
    39  
    40  		if !allDigits.MatchString(timestamp) {
    41  			t.Fatalf("Timestamp not all digits! %s", timestamp)
    42  		}
    43  
    44  		if !allHex.MatchString(increment) {
    45  			t.Fatalf("Increment part not all hex! %s", increment)
    46  		}
    47  
    48  		if lastId != "" && lastId >= id {
    49  			t.Fatalf("IDs not ordered! %s vs %s", lastId, id)
    50  		}
    51  
    52  		ids[id] = struct{}{}
    53  		lastId = id
    54  	}
    55  
    56  	id1 := UniqueId()
    57  	time.Sleep(time.Millisecond)
    58  	id2 := UniqueId()
    59  	timestamp1, _ := split(strings.TrimPrefix(id1, UniqueIdPrefix))
    60  	timestamp2, _ := split(strings.TrimPrefix(id2, UniqueIdPrefix))
    61  
    62  	if timestamp1 == timestamp2 {
    63  		t.Fatalf("Timestamp part should update at least once a millisecond %s %s",
    64  			id1, id2)
    65  	}
    66  }