id_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package idutil
  14. import (
  15. "testing"
  16. "time"
  17. )
  18. func TestNewGenerator(t *testing.T) {
  19. g := NewGenerator(0x12, time.Unix(0, 0).Add(0x3456*time.Millisecond))
  20. id := g.Next()
  21. wid := uint64(0x1200000034560001)
  22. if id != wid {
  23. t.Errorf("id = %x, want %x", id, wid)
  24. }
  25. }
  26. func TestNewGeneratorUnique(t *testing.T) {
  27. g := NewGenerator(0, time.Time{})
  28. id := g.Next()
  29. // different server generates different ID
  30. g1 := NewGenerator(1, time.Time{})
  31. if gid := g1.Next(); id == gid {
  32. t.Errorf("generate the same id %x using different server ID", id)
  33. }
  34. // restarted server generates different ID
  35. g2 := NewGenerator(0, time.Now())
  36. if gid := g2.Next(); id == gid {
  37. t.Errorf("generate the same id %x after restart", id)
  38. }
  39. }
  40. func TestNext(t *testing.T) {
  41. g := NewGenerator(0x12, time.Unix(0, 0).Add(0x3456*time.Millisecond))
  42. wid := uint64(0x1200000034560001)
  43. for i := 0; i < 1000; i++ {
  44. id := g.Next()
  45. if id != wid+uint64(i) {
  46. t.Errorf("id = %x, want %x", id, wid+uint64(i))
  47. }
  48. }
  49. }