trunc_test.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package common_test
  2. import (
  3. "strings"
  4. "testing"
  5. "github.com/labring/aiproxy/core/common"
  6. "github.com/smartystreets/goconvey/convey"
  7. )
  8. func TestTruncateByRune(t *testing.T) {
  9. convey.Convey("TruncateByRune", t, func() {
  10. convey.Convey("should truncate normal string", func() {
  11. s := "hello world"
  12. convey.So(common.TruncateByRune(s, 5), convey.ShouldEqual, "hello")
  13. })
  14. convey.Convey("should handle chinese characters", func() {
  15. s := "你好世界"
  16. // Each chinese char is 3 bytes
  17. // 5 bytes is not enough for 2 chars (6 bytes), so it should return "你好" which is 6 bytes?
  18. // Wait, TruncateByRune implementation:
  19. // for _, r := range s { runeLen := utf8.RuneLen(r) ... total += runeLen }
  20. // It truncates based on byte length but respecting rune boundaries.
  21. // "你" (3 bytes)
  22. // "你好" (6 bytes)
  23. // TruncateByRune("你好世界", 5)
  24. // 1. r='你', len=3. total=3 <= 5. ok.
  25. // 2. r='好', len=3. total=6 > 5. return s[:3] -> "你"
  26. convey.So(common.TruncateByRune(s, 5), convey.ShouldEqual, "你")
  27. convey.So(common.TruncateByRune(s, 6), convey.ShouldEqual, "你好")
  28. })
  29. convey.Convey("should handle string shorter than length", func() {
  30. s := "abc"
  31. convey.So(common.TruncateByRune(s, 10), convey.ShouldEqual, "abc")
  32. })
  33. convey.Convey("should handle empty string", func() {
  34. s := ""
  35. convey.So(common.TruncateByRune(s, 5), convey.ShouldEqual, "")
  36. })
  37. convey.Convey("should handle mixed string", func() {
  38. s := "a你好"
  39. // 'a' (1), '你' (3), '好' (3)
  40. // len 4: 'a' (1) + '你' (3) = 4. Exact.
  41. convey.So(common.TruncateByRune(s, 4), convey.ShouldEqual, "a你")
  42. // len 3: 'a' (1) + '你' (3) = 4 > 3. Returns 'a'
  43. convey.So(common.TruncateByRune(s, 3), convey.ShouldEqual, "a")
  44. })
  45. })
  46. }
  47. func TestTruncateBytesByRune(t *testing.T) {
  48. convey.Convey("TruncateBytesByRune", t, func() {
  49. convey.Convey("should truncate bytes respecting runes", func() {
  50. s := "你好世界"
  51. b := []byte(s)
  52. // Same logic as string
  53. convey.So(string(common.TruncateBytesByRune(b, 5)), convey.ShouldEqual, "你")
  54. convey.So(string(common.TruncateBytesByRune(b, 6)), convey.ShouldEqual, "你好")
  55. })
  56. convey.Convey("should handle long string", func() {
  57. // Generate a long string
  58. s := strings.Repeat("a", 1000)
  59. b := []byte(s)
  60. convey.So(len(common.TruncateBytesByRune(b, 500)), convey.ShouldEqual, 500)
  61. })
  62. })
  63. }