id_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2015 CoreOS, Inc.
  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 idutil
  15. import (
  16. "testing"
  17. "time"
  18. )
  19. func TestNewGenerator(t *testing.T) {
  20. g := NewGenerator(0x12, time.Unix(0, 0).Add(0x3456*time.Millisecond))
  21. id := g.Next()
  22. wid := uint64(0x1200000034560001)
  23. if id != wid {
  24. t.Errorf("id = %x, want %x", id, wid)
  25. }
  26. }
  27. func TestNewGeneratorUnique(t *testing.T) {
  28. g := NewGenerator(0, time.Time{})
  29. id := g.Next()
  30. // different server generates different ID
  31. g1 := NewGenerator(1, time.Time{})
  32. if gid := g1.Next(); id == gid {
  33. t.Errorf("generate the same id %x using different server ID", id)
  34. }
  35. // restarted server generates different ID
  36. g2 := NewGenerator(0, time.Now())
  37. if gid := g2.Next(); id == gid {
  38. t.Errorf("generate the same id %x after restart", id)
  39. }
  40. }
  41. func TestNext(t *testing.T) {
  42. g := NewGenerator(0x12, time.Unix(0, 0).Add(0x3456*time.Millisecond))
  43. wid := uint64(0x1200000034560001)
  44. for i := 0; i < 1000; i++ {
  45. id := g.Next()
  46. if id != wid+uint64(i) {
  47. t.Errorf("id = %x, want %x", id, wid+uint64(i))
  48. }
  49. }
  50. }