You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

truncate_test.go 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package util
  4. import (
  5. "testing"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func TestSplitString(t *testing.T) {
  9. type testCase struct {
  10. input string
  11. n int
  12. leftSub string
  13. ellipsis string
  14. }
  15. test := func(tc []*testCase, f func(input string, n int) (left, right string)) {
  16. for _, c := range tc {
  17. l, r := f(c.input, c.n)
  18. if c.ellipsis != "" {
  19. assert.Equal(t, c.leftSub+c.ellipsis, l, "test split %q at %d, expected leftSub: %q", c.input, c.n, c.leftSub)
  20. assert.Equal(t, c.ellipsis+c.input[len(c.leftSub):], r, "test split %s at %d, expected rightSub: %q", c.input, c.n, c.input[len(c.leftSub):])
  21. } else {
  22. assert.Equal(t, c.leftSub, l, "test split %q at %d, expected leftSub: %q", c.input, c.n, c.leftSub)
  23. assert.Equal(t, "", r, "test split %q at %d, expected rightSub: %q", c.input, c.n, "")
  24. }
  25. }
  26. }
  27. tc := []*testCase{
  28. {"abc123xyz", 0, "", utf8Ellipsis},
  29. {"abc123xyz", 1, "", utf8Ellipsis},
  30. {"abc123xyz", 4, "a", utf8Ellipsis},
  31. {"啊bc123xyz", 4, "", utf8Ellipsis},
  32. {"啊bc123xyz", 6, "啊", utf8Ellipsis},
  33. {"啊bc", 5, "啊bc", ""},
  34. {"啊bc", 6, "啊bc", ""},
  35. {"abc\xef\x03\xfe", 3, "", asciiEllipsis},
  36. {"abc\xef\x03\xfe", 4, "a", asciiEllipsis},
  37. {"\xef\x03", 1, "\xef\x03", ""},
  38. }
  39. test(tc, SplitStringAtByteN)
  40. tc = []*testCase{
  41. {"abc123xyz", 0, "", utf8Ellipsis},
  42. {"abc123xyz", 1, "", utf8Ellipsis},
  43. {"abc123xyz", 4, "abc", utf8Ellipsis},
  44. {"啊bc123xyz", 4, "啊bc", utf8Ellipsis},
  45. {"啊bc123xyz", 6, "啊bc12", utf8Ellipsis},
  46. {"啊bc", 3, "啊bc", ""},
  47. {"啊bc", 4, "啊bc", ""},
  48. {"abc\xef\x03\xfe", 3, "", asciiEllipsis},
  49. {"abc\xef\x03\xfe", 4, "a", asciiEllipsis},
  50. {"\xef\x03", 1, "\xef\x03", ""},
  51. }
  52. test(tc, SplitStringAtRuneN)
  53. }