Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

89 linhas
2.3 KiB

  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. package uid
  15. import (
  16. "fmt"
  17. "testing"
  18. "time"
  19. )
  20. func TestNew(t *testing.T) {
  21. tm := time.Date(2017, 1, 6, 0, 0, 0, 21, time.UTC)
  22. s := NewSpace("prefix", &Options{Time: tm})
  23. got := s.New()
  24. want := "prefix-20170106-21-0001"
  25. if got != want {
  26. t.Errorf("got %q, want %q", got, want)
  27. }
  28. s2 := NewSpace("prefix2", &Options{Sep: '_', Time: tm})
  29. got = s2.New()
  30. want = "prefix2_20170106_21_0001"
  31. if got != want {
  32. t.Errorf("got %q, want %q", got, want)
  33. }
  34. }
  35. func TestTimestamp(t *testing.T) {
  36. s := NewSpace("unique-ID", nil)
  37. startTime := s.Time
  38. uid := s.New()
  39. got, ok := s.Timestamp(uid)
  40. if !ok {
  41. t.Fatal("got ok = false, want true")
  42. }
  43. if !startTime.Equal(got) {
  44. t.Errorf("got %s, want %s", got, startTime)
  45. }
  46. got, ok = s.Timestamp("unique-ID-20160308-123-8")
  47. if !ok {
  48. t.Fatal("got false, want true")
  49. }
  50. if want := time.Date(2016, 3, 8, 0, 0, 0, 123, time.UTC); !want.Equal(got) {
  51. t.Errorf("got %s, want %s", got, want)
  52. }
  53. if _, ok = s.Timestamp("invalid-time-1234"); ok {
  54. t.Error("got true, want false")
  55. }
  56. }
  57. func TestOlder(t *testing.T) {
  58. s := NewSpace("uid", nil)
  59. // A non-matching ID returns false.
  60. id2 := NewSpace("different-prefix", nil).New()
  61. if got, want := s.Older(id2, time.Second), false; got != want {
  62. t.Errorf("got %t, want %t", got, want)
  63. }
  64. }
  65. func TestShorter(t *testing.T) {
  66. now := time.Now()
  67. shortSpace := NewSpace("uid", &Options{Short: true, Time: now})
  68. shortUID := shortSpace.New()
  69. want := fmt.Sprintf("uid-%d-01", now.UnixNano())
  70. if shortUID != want {
  71. t.Fatalf("expected %s, got %s", want, shortUID)
  72. }
  73. if got, ok := shortSpace.Timestamp(shortUID); !ok {
  74. t.Fatal("expected to be able to parse timestamp from short space, but was unable to")
  75. } else if got.UnixNano() != now.UnixNano() {
  76. t.Fatalf("expected to get %v, got %v", now, got)
  77. }
  78. }