| 1 |
package plural |
| 2 |
|
| 3 |
import ( |
| 4 |
"strconv" |
| 5 |
"strings" |
| 6 |
"testing" |
| 7 |
|
| 8 |
"golang.org/x/text/language" |
| 9 |
) |
| 10 |
|
| 11 |
type pluralFormTest struct { |
| 12 |
num interface{} |
| 13 |
form Form |
| 14 |
} |
| 15 |
|
| 16 |
func runTests(t *testing.T, pluralRuleID string, tests []pluralFormTest) { |
| 17 |
if pluralRuleID == "root" { |
| 18 |
return |
| 19 |
} |
| 20 |
pluralRules := DefaultRules() |
| 21 |
tag := language.MustParse(pluralRuleID) |
| 22 |
if rule := pluralRules.Rule(tag); rule != nil { |
| 23 |
for _, test := range tests { |
| 24 |
ops, err := NewOperands(test.num) |
| 25 |
if err != nil { |
| 26 |
t.Errorf("%s: NewOperands(%d) errored with %s", pluralRuleID, test.num, err) |
| 27 |
break |
| 28 |
} |
| 29 |
if pluralForm := rule.PluralFormFunc(ops); pluralForm != test.form { |
| 30 |
t.Errorf("%s: PluralFormFunc(%#v) returned %q, %v; expected %q", pluralRuleID, ops, pluralForm, err, test.form) |
| 31 |
} |
| 32 |
} |
| 33 |
} else { |
| 34 |
t.Errorf("could not find plural rule for locale %s", pluralRuleID) |
| 35 |
} |
| 36 |
|
| 37 |
} |
| 38 |
|
| 39 |
func appendIntegerTests(tests []pluralFormTest, form Form, examples []string) []pluralFormTest { |
| 40 |
for _, ex := range expandExamples(examples) { |
| 41 |
i, err := strconv.ParseInt(ex, 10, 64) |
| 42 |
if err != nil { |
| 43 |
panic(err) |
| 44 |
} |
| 45 |
tests = append(tests, pluralFormTest{ex, form}, pluralFormTest{i, form}) |
| 46 |
} |
| 47 |
return tests |
| 48 |
} |
| 49 |
|
| 50 |
func appendDecimalTests(tests []pluralFormTest, form Form, examples []string) []pluralFormTest { |
| 51 |
for _, ex := range expandExamples(examples) { |
| 52 |
tests = append(tests, pluralFormTest{ex, form}) |
| 53 |
} |
| 54 |
return tests |
| 55 |
} |
| 56 |
|
| 57 |
func expandExamples(examples []string) []string { |
| 58 |
var expanded []string |
| 59 |
for _, ex := range examples { |
| 60 |
if parts := strings.Split(ex, "~"); len(parts) == 2 { |
| 61 |
for ex := parts[0]; ; ex = increment(ex) { |
| 62 |
expanded = append(expanded, ex) |
| 63 |
if ex == parts[1] { |
| 64 |
break |
| 65 |
} |
| 66 |
} |
| 67 |
} else { |
| 68 |
expanded = append(expanded, ex) |
| 69 |
} |
| 70 |
} |
| 71 |
return expanded |
| 72 |
} |
| 73 |
|
| 74 |
func increment(dec string) string { |
| 75 |
runes := []rune(dec) |
| 76 |
carry := true |
| 77 |
for i := len(runes) - 1; carry && i >= 0; i-- { |
| 78 |
switch runes[i] { |
| 79 |
case '.': |
| 80 |
continue |
| 81 |
case '9': |
| 82 |
runes[i] = '0' |
| 83 |
default: |
| 84 |
runes[i]++ |
| 85 |
carry = false |
| 86 |
} |
| 87 |
} |
| 88 |
if carry { |
| 89 |
runes = append([]rune{'1'}, runes...) |
| 90 |
} |
| 91 |
return string(runes) |
| 92 |
} |