format_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. // Copyright 2017 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package number
  5. import (
  6. "fmt"
  7. "testing"
  8. "golang.org/x/text/feature/plural"
  9. "golang.org/x/text/language"
  10. "golang.org/x/text/message"
  11. )
  12. func TestWrongVerb(t *testing.T) {
  13. testCases := []struct {
  14. f Formatter
  15. fmt string
  16. want string
  17. }{{
  18. f: Decimal(12),
  19. fmt: "%e",
  20. want: "%!e(int=12)",
  21. }, {
  22. f: Scientific(12),
  23. fmt: "%f",
  24. want: "%!f(int=12)",
  25. }, {
  26. f: Engineering(12),
  27. fmt: "%f",
  28. want: "%!f(int=12)",
  29. }, {
  30. f: Percent(12),
  31. fmt: "%e",
  32. want: "%!e(int=12)",
  33. }}
  34. for _, tc := range testCases {
  35. t.Run("", func(t *testing.T) {
  36. tag := language.Und
  37. got := message.NewPrinter(tag).Sprintf(tc.fmt, tc.f)
  38. if got != tc.want {
  39. t.Errorf("got %q; want %q", got, tc.want)
  40. }
  41. })
  42. }
  43. }
  44. func TestDigits(t *testing.T) {
  45. testCases := []struct {
  46. f Formatter
  47. scale int
  48. want string
  49. }{{
  50. f: Decimal(3),
  51. scale: 0,
  52. want: "digits:[3] exp:1 comma:0 end:1",
  53. }, {
  54. f: Decimal(3.1),
  55. scale: 0,
  56. want: "digits:[3] exp:1 comma:0 end:1",
  57. }, {
  58. f: Scientific(3.1),
  59. scale: 0,
  60. want: "digits:[3] exp:1 comma:1 end:1",
  61. }, {
  62. f: Scientific(3.1),
  63. scale: 3,
  64. want: "digits:[3 1] exp:1 comma:1 end:4",
  65. }}
  66. for _, tc := range testCases {
  67. t.Run("", func(t *testing.T) {
  68. d := tc.f.Digits(nil, language.Croatian, tc.scale)
  69. got := fmt.Sprintf("digits:%d exp:%d comma:%d end:%d", d.Digits, d.Exp, d.Comma, d.End)
  70. if got != tc.want {
  71. t.Errorf("got %v; want %v", got, tc.want)
  72. }
  73. })
  74. }
  75. }
  76. func TestPluralIntegration(t *testing.T) {
  77. testCases := []struct {
  78. f Formatter
  79. want string
  80. }{{
  81. f: Decimal(1),
  82. want: "one: 1",
  83. }, {
  84. f: Decimal(5),
  85. want: "other: 5",
  86. }}
  87. for _, tc := range testCases {
  88. t.Run("", func(t *testing.T) {
  89. message.Set(language.English, "num %f", plural.Selectf(1, "%f",
  90. "one", "one: %f",
  91. "other", "other: %f"))
  92. p := message.NewPrinter(language.English)
  93. // Indirect the call to p.Sprintf through the variable f
  94. // to avoid Go tip failing a vet check.
  95. // TODO: remove once vet check has been fixed. See Issue #22936.
  96. f := p.Sprintf
  97. got := f("num %f", tc.f)
  98. if got != tc.want {
  99. t.Errorf("got %q; want %q", got, tc.want)
  100. }
  101. })
  102. }
  103. }