format_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package log
  2. import (
  3. "math"
  4. "math/big"
  5. "math/rand"
  6. "testing"
  7. )
  8. func TestPrettyInt64(t *testing.T) {
  9. tests := []struct {
  10. n int64
  11. s string
  12. }{
  13. {0, "0"},
  14. {10, "10"},
  15. {-10, "-10"},
  16. {100, "100"},
  17. {-100, "-100"},
  18. {1000, "1000"},
  19. {-1000, "-1000"},
  20. {10000, "10000"},
  21. {-10000, "-10000"},
  22. {99999, "99999"},
  23. {-99999, "-99999"},
  24. {100000, "100,000"},
  25. {-100000, "-100,000"},
  26. {1000000, "1,000,000"},
  27. {-1000000, "-1,000,000"},
  28. {math.MaxInt64, "9,223,372,036,854,775,807"},
  29. {math.MinInt64, "-9,223,372,036,854,775,808"},
  30. }
  31. for i, tt := range tests {
  32. if have := FormatLogfmtInt64(tt.n); have != tt.s {
  33. t.Errorf("test %d: format mismatch: have %s, want %s", i, have, tt.s)
  34. }
  35. }
  36. }
  37. func TestPrettyUint64(t *testing.T) {
  38. tests := []struct {
  39. n uint64
  40. s string
  41. }{
  42. {0, "0"},
  43. {10, "10"},
  44. {100, "100"},
  45. {1000, "1000"},
  46. {10000, "10000"},
  47. {99999, "99999"},
  48. {100000, "100,000"},
  49. {1000000, "1,000,000"},
  50. {math.MaxUint64, "18,446,744,073,709,551,615"},
  51. }
  52. for i, tt := range tests {
  53. if have := FormatLogfmtUint64(tt.n); have != tt.s {
  54. t.Errorf("test %d: format mismatch: have %s, want %s", i, have, tt.s)
  55. }
  56. }
  57. }
  58. func TestPrettyBigInt(t *testing.T) {
  59. tests := []struct {
  60. int string
  61. s string
  62. }{
  63. {"111222333444555678999", "111,222,333,444,555,678,999"},
  64. {"-111222333444555678999", "-111,222,333,444,555,678,999"},
  65. {"11122233344455567899900", "11,122,233,344,455,567,899,900"},
  66. {"-11122233344455567899900", "-11,122,233,344,455,567,899,900"},
  67. }
  68. for _, tt := range tests {
  69. v, _ := new(big.Int).SetString(tt.int, 10)
  70. if have := formatLogfmtBigInt(v); have != tt.s {
  71. t.Errorf("invalid output %s, want %s", have, tt.s)
  72. }
  73. }
  74. }
  75. var sink string
  76. func BenchmarkPrettyInt64Logfmt(b *testing.B) {
  77. b.ReportAllocs()
  78. for i := 0; i < b.N; i++ {
  79. sink = FormatLogfmtInt64(rand.Int63())
  80. }
  81. }
  82. func BenchmarkPrettyUint64Logfmt(b *testing.B) {
  83. b.ReportAllocs()
  84. for i := 0; i < b.N; i++ {
  85. sink = FormatLogfmtUint64(rand.Uint64())
  86. }
  87. }