size_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright (C) 2017 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package config
  7. import "testing"
  8. func TestParseSize(t *testing.T) {
  9. cases := []struct {
  10. in string
  11. ok bool
  12. val float64
  13. pct bool
  14. }{
  15. // We accept upper case SI units
  16. {"5K", true, 5e3, false}, // even when they should be lower case
  17. {"4 M", true, 4e6, false},
  18. {"3G", true, 3e9, false},
  19. {"2 T", true, 2e12, false},
  20. // We accept lower case SI units out of user friendliness
  21. {"1 k", true, 1e3, false},
  22. {"2m", true, 2e6, false},
  23. {"3 g", true, 3e9, false},
  24. {"4t", true, 4e12, false},
  25. // Fractions are OK
  26. {"123.456 k", true, 123.456e3, false},
  27. {"0.1234 m", true, 0.1234e6, false},
  28. {"3.45 g", true, 3.45e9, false},
  29. // We don't parse negative numbers
  30. {"-1", false, 0, false},
  31. {"-1k", false, 0, false},
  32. {"-0.45g", false, 0, false},
  33. // We accept various unit suffixes on the unit prefix
  34. {"100 KBytes", true, 100e3, false},
  35. {"100 Kbps", true, 100e3, false},
  36. {"100 MAU", true, 100e6, false},
  37. // Percentages are OK
  38. {"1%", true, 1, true},
  39. {"200%", true, 200, true}, // even large ones
  40. {"200K%", true, 200e3, true}, // even with prefixes, although this makes no sense
  41. {"2.34%", true, 2.34, true}, // fractions are A-ok
  42. // The empty string is a valid zero
  43. {"", true, 0, false},
  44. {" ", true, 0, false},
  45. }
  46. for _, tc := range cases {
  47. size, err := ParseSize(tc.in)
  48. if !tc.ok {
  49. if err == nil {
  50. t.Errorf("Unexpected nil error in UnmarshalText(%q)", tc.in)
  51. }
  52. continue
  53. }
  54. if err != nil {
  55. t.Errorf("Unexpected error in UnmarshalText(%q): %v", tc.in, err)
  56. continue
  57. }
  58. if size.BaseValue() > tc.val*1.001 || size.BaseValue() < tc.val*0.999 {
  59. // Allow 0.1% slop due to floating point multiplication
  60. t.Errorf("Incorrect value in UnmarshalText(%q): %v, wanted %v", tc.in, size.BaseValue(), tc.val)
  61. }
  62. if size.Percentage() != tc.pct {
  63. t.Errorf("Incorrect percentage bool in UnmarshalText(%q): %v, wanted %v", tc.in, size.Percentage(), tc.pct)
  64. }
  65. }
  66. }