search_truncate_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. //go:build unit
  2. package admin
  3. import (
  4. "testing"
  5. "github.com/stretchr/testify/require"
  6. )
  7. // truncateSearchByRune 模拟 user_handler.go 中的 search 截断逻辑
  8. func truncateSearchByRune(search string, maxRunes int) string {
  9. if runes := []rune(search); len(runes) > maxRunes {
  10. return string(runes[:maxRunes])
  11. }
  12. return search
  13. }
  14. func TestTruncateSearchByRune(t *testing.T) {
  15. tests := []struct {
  16. name string
  17. input string
  18. maxRunes int
  19. wantLen int // 期望的 rune 长度
  20. }{
  21. {
  22. name: "纯中文超长",
  23. input: string(make([]rune, 150)),
  24. maxRunes: 100,
  25. wantLen: 100,
  26. },
  27. {
  28. name: "纯 ASCII 超长",
  29. input: string(make([]byte, 150)),
  30. maxRunes: 100,
  31. wantLen: 100,
  32. },
  33. {
  34. name: "空字符串",
  35. input: "",
  36. maxRunes: 100,
  37. wantLen: 0,
  38. },
  39. {
  40. name: "恰好 100 个字符",
  41. input: string(make([]rune, 100)),
  42. maxRunes: 100,
  43. wantLen: 100,
  44. },
  45. {
  46. name: "不足 100 字符不截断",
  47. input: "hello世界",
  48. maxRunes: 100,
  49. wantLen: 7,
  50. },
  51. }
  52. for _, tc := range tests {
  53. t.Run(tc.name, func(t *testing.T) {
  54. result := truncateSearchByRune(tc.input, tc.maxRunes)
  55. require.Equal(t, tc.wantLen, len([]rune(result)))
  56. })
  57. }
  58. }
  59. func TestTruncateSearchByRune_PreservesMultibyte(t *testing.T) {
  60. // 101 个中文字符,截断到 100 个后应该仍然是有效 UTF-8
  61. input := ""
  62. for i := 0; i < 101; i++ {
  63. input += "中"
  64. }
  65. result := truncateSearchByRune(input, 100)
  66. require.Equal(t, 100, len([]rune(result)))
  67. // 验证截断结果是有效的 UTF-8(每个中文字符 3 字节)
  68. require.Equal(t, 300, len(result))
  69. }
  70. func TestTruncateSearchByRune_MixedASCIIAndMultibyte(t *testing.T) {
  71. // 50 个 ASCII + 51 个中文 = 101 个 rune
  72. input := ""
  73. for i := 0; i < 50; i++ {
  74. input += "a"
  75. }
  76. for i := 0; i < 51; i++ {
  77. input += "中"
  78. }
  79. result := truncateSearchByRune(input, 100)
  80. runes := []rune(result)
  81. require.Equal(t, 100, len(runes))
  82. // 前 50 个应该是 'a',后 50 个应该是 '中'
  83. require.Equal(t, 'a', runes[0])
  84. require.Equal(t, 'a', runes[49])
  85. require.Equal(t, '中', runes[50])
  86. require.Equal(t, '中', runes[99])
  87. }