id_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package span
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "strings"
  6. "testing"
  7. )
  8. func TestIDMarshalJSON(t *testing.T) {
  9. id := ID(10018820)
  10. buf := bytes.NewBuffer(nil)
  11. json.NewEncoder(buf).Encode(id)
  12. want := `"000000000098e004"`
  13. got := strings.TrimSpace(buf.String())
  14. if got != want {
  15. t.Errorf("got %v, want %v", got, want)
  16. }
  17. }
  18. func TestIDUnmarshalJSONHexString(t *testing.T) {
  19. j := []byte(`"000000000098e004"`)
  20. var got ID
  21. if err := json.Unmarshal(j, &got); err != nil {
  22. t.Fatal(err)
  23. }
  24. want := ID(10018820)
  25. if got != want {
  26. t.Errorf("got %v, want %v", got, want)
  27. }
  28. }
  29. func TestIDUnmarshalJSONInt(t *testing.T) {
  30. j := []byte(`10018820`)
  31. var got ID
  32. if err := json.Unmarshal(j, &got); err != nil {
  33. t.Fatal(err)
  34. }
  35. want := ID(10018820)
  36. if got != want {
  37. t.Errorf("got %v, want %v", got, want)
  38. }
  39. }
  40. func TestIDUnmarshalJSONNonInt(t *testing.T) {
  41. j := []byte(`[]`)
  42. var got ID
  43. err := json.Unmarshal(j, &got)
  44. if err == nil {
  45. t.Fatalf("unexpectedly unmarshalled %v", got)
  46. }
  47. }
  48. func TestIDUnmarshalJSONNonHexString(t *testing.T) {
  49. j := []byte(`"woo"`)
  50. var got ID
  51. err := json.Unmarshal(j, &got)
  52. if err == nil {
  53. t.Fatalf("unexpectedly unmarshalled %v", got)
  54. }
  55. }
  56. func TestIDGeneration(t *testing.T) {
  57. n := 10000
  58. ids := make(map[ID]bool, n)
  59. for i := 0; i < n; i++ {
  60. id := generateID()
  61. if ids[id] {
  62. t.Errorf("duplicate ID: %v", id)
  63. }
  64. ids[id] = true
  65. }
  66. }
  67. func TestParseID(t *testing.T) {
  68. want := ID(10018181901)
  69. got, err := ParseID(want.String())
  70. if err != nil {
  71. t.Error(err)
  72. }
  73. if got != want {
  74. t.Errorf("got %v, want %v", got, want)
  75. }
  76. }
  77. func TestParseIDError(t *testing.T) {
  78. id, err := ParseID("woo")
  79. if err == nil {
  80. t.Errorf("unexpectedly parsed value: %v", id)
  81. }
  82. }
  83. func BenchmarkIDGeneration(b *testing.B) {
  84. for i := 0; i < b.N; i++ {
  85. generateID()
  86. }
  87. }