match_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2015 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 internal
  5. import (
  6. "strings"
  7. "testing"
  8. "golang.org/x/text/language"
  9. )
  10. func TestInheritanceMatcher(t *testing.T) {
  11. for i, tt := range []struct {
  12. haveTags string
  13. wantTags string
  14. match string
  15. conf language.Confidence
  16. }{
  17. {"und,en,en-US", "en-US", "en-US", language.Exact}, // most specific match
  18. {"zh-Hant,zh", "zh-TW", "zh-Hant", language.High}, // zh-TW implies Hant.
  19. {"und,zh", "zh-TW", "und", language.High}, // zh-TW does not match zh.
  20. {"zh", "zh-TW", "und", language.No}, // zh-TW does not match zh.
  21. {"iw,en,nl", "he", "he", language.Exact}, // matches after canonicalization
  22. {"he,en,nl", "iw", "he", language.Exact}, // matches after canonicalization
  23. // Prefer first match over more specific match for various reasons:
  24. // a) consistency of user interface is more important than an exact match,
  25. // b) _if_ und is specified, it should be considered a correct and useful match,
  26. // Note that a call to this Match will almost always be with a single tag.
  27. {"und,en,en-US", "he,en-US", "und", language.High},
  28. } {
  29. have := parseTags(tt.haveTags)
  30. m := NewInheritanceMatcher(have)
  31. tag, index, conf := m.Match(parseTags(tt.wantTags)...)
  32. want := language.Raw.Make(tt.match)
  33. if tag != want {
  34. t.Errorf("%d:tag: got %q; want %q", i, tag, want)
  35. }
  36. if conf != language.No {
  37. if got, _ := language.All.Canonicalize(have[index]); got != want {
  38. t.Errorf("%d:index: got %q; want %q ", i, got, want)
  39. }
  40. }
  41. if conf != tt.conf {
  42. t.Errorf("%d:conf: got %v; want %v", i, conf, tt.conf)
  43. }
  44. }
  45. }
  46. func parseTags(list string) (out []language.Tag) {
  47. for _, s := range strings.Split(list, ",") {
  48. out = append(out, language.Raw.Make(strings.TrimSpace(s)))
  49. }
  50. return out
  51. }