stringsx_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright (c) Tailscale Inc & contributors
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package stringsx
  4. import (
  5. "cmp"
  6. "strings"
  7. "testing"
  8. )
  9. func TestCompareFold(t *testing.T) {
  10. tests := []struct {
  11. a, b string
  12. }{
  13. // Basic ASCII cases
  14. {"", ""},
  15. {"a", "a"},
  16. {"a", "A"},
  17. {"A", "a"},
  18. {"a", "b"},
  19. {"b", "a"},
  20. {"abc", "ABC"},
  21. {"ABC", "abc"},
  22. {"abc", "abd"},
  23. {"abd", "abc"},
  24. // Length differences
  25. {"abc", "ab"},
  26. {"ab", "abc"},
  27. // Unicode cases
  28. {"世界", "世界"},
  29. {"Hello世界", "hello世界"},
  30. {"世界Hello", "世界hello"},
  31. {"世界", "世界x"},
  32. {"世界x", "世界"},
  33. // Special case folding examples
  34. {"ß", "ss"}, // German sharp s
  35. {"fi", "fi"}, // fi ligature
  36. {"Σ", "σ"}, // Greek sigma
  37. {"İ", "i\u0307"}, // Turkish dotted I
  38. // Mixed cases
  39. {"HelloWorld", "helloworld"},
  40. {"HELLOWORLD", "helloworld"},
  41. {"helloworld", "HELLOWORLD"},
  42. {"HelloWorld", "helloworld"},
  43. {"helloworld", "HelloWorld"},
  44. // Edge cases
  45. {" ", " "},
  46. {"1", "1"},
  47. {"123", "123"},
  48. {"!@#", "!@#"},
  49. }
  50. wants := []int{}
  51. for _, tt := range tests {
  52. got := CompareFold(tt.a, tt.b)
  53. want := cmp.Compare(strings.ToLower(tt.a), strings.ToLower(tt.b))
  54. if got != want {
  55. t.Errorf("CompareFold(%q, %q) = %v, want %v", tt.a, tt.b, got, want)
  56. }
  57. wants = append(wants, want)
  58. }
  59. if n := testing.AllocsPerRun(1000, func() {
  60. for i, tt := range tests {
  61. if CompareFold(tt.a, tt.b) != wants[i] {
  62. panic("unexpected")
  63. }
  64. }
  65. }); n > 0 {
  66. t.Errorf("allocs = %v; want 0", int(n))
  67. }
  68. }