You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.3 KiB

  1. package humanize
  2. import (
  3. "math"
  4. "testing"
  5. )
  6. func TestSI(t *testing.T) {
  7. tests := []struct {
  8. name string
  9. num float64
  10. formatted string
  11. }{
  12. {"e-24", 1e-24, "1 yF"},
  13. {"e-21", 1e-21, "1 zF"},
  14. {"e-18", 1e-18, "1 aF"},
  15. {"e-15", 1e-15, "1 fF"},
  16. {"e-12", 1e-12, "1 pF"},
  17. {"e-12", 2.2345e-12, "2.2345 pF"},
  18. {"e-12", 2.23e-12, "2.23 pF"},
  19. {"e-11", 2.23e-11, "22.3 pF"},
  20. {"e-10", 2.2e-10, "220 pF"},
  21. {"e-9", 2.2e-9, "2.2 nF"},
  22. {"e-8", 2.2e-8, "22 nF"},
  23. {"e-7", 2.2e-7, "220 nF"},
  24. {"e-6", 2.2e-6, "2.2 µF"},
  25. {"e-6", 1e-6, "1 µF"},
  26. {"e-5", 2.2e-5, "22 µF"},
  27. {"e-4", 2.2e-4, "220 µF"},
  28. {"e-3", 2.2e-3, "2.2 mF"},
  29. {"e-2", 2.2e-2, "22 mF"},
  30. {"e-1", 2.2e-1, "220 mF"},
  31. {"e+0", 2.2e-0, "2.2 F"},
  32. {"e+0", 2.2, "2.2 F"},
  33. {"e+1", 2.2e+1, "22 F"},
  34. {"0", 0, "0 F"},
  35. {"e+1", 22, "22 F"},
  36. {"e+2", 2.2e+2, "220 F"},
  37. {"e+2", 220, "220 F"},
  38. {"e+3", 2.2e+3, "2.2 kF"},
  39. {"e+3", 2200, "2.2 kF"},
  40. {"e+4", 2.2e+4, "22 kF"},
  41. {"e+4", 22000, "22 kF"},
  42. {"e+5", 2.2e+5, "220 kF"},
  43. {"e+6", 2.2e+6, "2.2 MF"},
  44. {"e+6", 1e+6, "1 MF"},
  45. {"e+7", 2.2e+7, "22 MF"},
  46. {"e+8", 2.2e+8, "220 MF"},
  47. {"e+9", 2.2e+9, "2.2 GF"},
  48. {"e+10", 2.2e+10, "22 GF"},
  49. {"e+11", 2.2e+11, "220 GF"},
  50. {"e+12", 2.2e+12, "2.2 TF"},
  51. {"e+15", 2.2e+15, "2.2 PF"},
  52. {"e+18", 2.2e+18, "2.2 EF"},
  53. {"e+21", 2.2e+21, "2.2 ZF"},
  54. {"e+24", 2.2e+24, "2.2 YF"},
  55. // special case
  56. {"1F", 1000 * 1000, "1 MF"},
  57. {"1F", 1e6, "1 MF"},
  58. // negative number
  59. {"-100 F", -100, "-100 F"},
  60. }
  61. for _, test := range tests {
  62. got := SI(test.num, "F")
  63. if got != test.formatted {
  64. t.Errorf("On %v (%v), got %v, wanted %v",
  65. test.name, test.num, got, test.formatted)
  66. }
  67. gotf, gotu, err := ParseSI(test.formatted)
  68. if err != nil {
  69. t.Errorf("Error parsing %v (%v): %v", test.name, test.formatted, err)
  70. continue
  71. }
  72. if math.Abs(1-(gotf/test.num)) > 0.01 {
  73. t.Errorf("On %v (%v), got %v, wanted %v (±%v)",
  74. test.name, test.formatted, gotf, test.num,
  75. math.Abs(1-(gotf/test.num)))
  76. }
  77. if gotu != "F" {
  78. t.Errorf("On %v (%v), expected unit F, got %v",
  79. test.name, test.formatted, gotu)
  80. }
  81. }
  82. // Parse error
  83. gotf, gotu, err := ParseSI("x1.21JW") // 1.21 jigga whats
  84. if err == nil {
  85. t.Errorf("Expected error on x1.21JW, got %v %v", gotf, gotu)
  86. }
  87. }
  88. func BenchmarkParseSI(b *testing.B) {
  89. for i := 0; i < b.N; i++ {
  90. ParseSI("2.2346ZB")
  91. }
  92. }