1// Copyright 2017 Google LLC 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15package uid 16 17import ( 18 "fmt" 19 "testing" 20 "time" 21) 22 23func TestNew(t *testing.T) { 24 tm := time.Date(2017, 1, 6, 0, 0, 0, 21, time.UTC) 25 s := NewSpace("prefix", &Options{Time: tm}) 26 got := s.New() 27 want := "prefix-20170106-21-0001" 28 if got != want { 29 t.Errorf("got %q, want %q", got, want) 30 } 31 32 s2 := NewSpace("prefix2", &Options{Sep: '_', Time: tm}) 33 got = s2.New() 34 want = "prefix2_20170106_21_0001" 35 if got != want { 36 t.Errorf("got %q, want %q", got, want) 37 } 38} 39 40func TestTimestamp(t *testing.T) { 41 s := NewSpace("unique-ID", nil) 42 startTime := s.Time 43 uid := s.New() 44 got, ok := s.Timestamp(uid) 45 if !ok { 46 t.Fatal("got ok = false, want true") 47 } 48 if !startTime.Equal(got) { 49 t.Errorf("got %s, want %s", got, startTime) 50 } 51 52 got, ok = s.Timestamp("unique-ID-20160308-123-8") 53 if !ok { 54 t.Fatal("got false, want true") 55 } 56 if want := time.Date(2016, 3, 8, 0, 0, 0, 123, time.UTC); !want.Equal(got) { 57 t.Errorf("got %s, want %s", got, want) 58 } 59 if _, ok = s.Timestamp("invalid-time-1234"); ok { 60 t.Error("got true, want false") 61 } 62} 63 64func TestOlder(t *testing.T) { 65 s := NewSpace("uid", nil) 66 // A non-matching ID returns false. 67 id2 := NewSpace("different-prefix", nil).New() 68 if got, want := s.Older(id2, time.Second), false; got != want { 69 t.Errorf("got %t, want %t", got, want) 70 } 71} 72 73func TestShorter(t *testing.T) { 74 now := time.Now() 75 shortSpace := NewSpace("uid", &Options{Short: true, Time: now}) 76 shortUID := shortSpace.New() 77 78 want := fmt.Sprintf("uid-%d-01", now.UnixNano()) 79 if shortUID != want { 80 t.Fatalf("expected %s, got %s", want, shortUID) 81 } 82 83 if got, ok := shortSpace.Timestamp(shortUID); !ok { 84 t.Fatal("expected to be able to parse timestamp from short space, but was unable to") 85 } else if got.UnixNano() != now.UnixNano() { 86 t.Fatalf("expected to get %v, got %v", now, got) 87 } 88} 89