number_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package humanize
  2. import (
  3. "math"
  4. "testing"
  5. )
  6. type TestStruct struct {
  7. name string
  8. format string
  9. num float64
  10. formatted string
  11. }
  12. func TestFormatFloat(t *testing.T) {
  13. tests := []TestStruct{
  14. {"default", "", 12345.6789, "12,345.68"},
  15. {"#", "#", 12345.6789, "12345.678900000"},
  16. {"#.", "#.", 12345.6789, "12346"},
  17. {"#,#", "#,#", 12345.6789, "12345,7"},
  18. {"#,##", "#,##", 12345.6789, "12345,68"},
  19. {"#,###", "#,###", 12345.6789, "12345,679"},
  20. {"#,###.", "#,###.", 12345.6789, "12,346"},
  21. {"#,###.##", "#,###.##", 12345.6789, "12,345.68"},
  22. {"#,###.###", "#,###.###", 12345.6789, "12,345.679"},
  23. {"#,###.####", "#,###.####", 12345.6789, "12,345.6789"},
  24. {"#.###,######", "#.###,######", 12345.6789, "12.345,678900"},
  25. {"bug46", "#,###.##", 52746220055.92342, "52,746,220,055.92"},
  26. {"#\u202f###,##", "#\u202f###,##", 12345.6789, "12 345,68"},
  27. // special cases
  28. {"NaN", "#", math.NaN(), "NaN"},
  29. {"+Inf", "#", math.Inf(1), "Infinity"},
  30. {"-Inf", "#", math.Inf(-1), "-Infinity"},
  31. {"signStr <= -0.000000001", "", -0.000000002, "-0.00"},
  32. {"signStr = 0", "", 0, "0.00"},
  33. {"Format directive must start with +", "+000", 12345.6789, "+12345.678900000"},
  34. }
  35. for _, test := range tests {
  36. got := FormatFloat(test.format, test.num)
  37. if got != test.formatted {
  38. t.Errorf("On %v (%v, %v), got %v, wanted %v",
  39. test.name, test.format, test.num, got, test.formatted)
  40. }
  41. }
  42. // Test a single integer
  43. got := FormatInteger("#", 12345)
  44. if got != "12345.000000000" {
  45. t.Errorf("On %v (%v, %v), got %v, wanted %v",
  46. "integerTest", "#", 12345, got, "12345.000000000")
  47. }
  48. // Test the things that could panic
  49. panictests := []TestStruct{
  50. {"RenderFloat(): invalid positive sign directive", "-", 12345.6789, "12,345.68"},
  51. {"RenderFloat(): thousands separator directive must be followed by 3 digit-specifiers", "0.01", 12345.6789, "12,345.68"},
  52. }
  53. for _, test := range panictests {
  54. didPanic := false
  55. var message interface{}
  56. func() {
  57. defer func() {
  58. if message = recover(); message != nil {
  59. didPanic = true
  60. }
  61. }()
  62. // call the target function
  63. _ = FormatFloat(test.format, test.num)
  64. }()
  65. if didPanic != true {
  66. t.Errorf("On %v, should have panic and did not.",
  67. test.name)
  68. }
  69. }
  70. }