master
go 110 lines 2.44 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package strmutil
4
5 import (
6 "strings"
7 "testing"
8
9 "github.com/stretchr/testify/assert"
10 )
11
12 func TestTruncateText(t *testing.T) {
13 tests := map[string]struct {
14 input string
15 maxLen int
16 expected string
17 }{
18 "short text unchanged": {
19 input: "hello",
20 maxLen: 100,
21 expected: "hello",
22 },
23 "text exactly at limit": {
24 input: "hello",
25 maxLen: 5,
26 expected: "hello",
27 },
28 "text truncated with ellipsis": {
29 input: "hello world",
30 maxLen: 8,
31 expected: "hello...",
32 },
33 "empty string": {
34 input: "",
35 maxLen: 100,
36 expected: "",
37 },
38 "UTF-8 characters preserved": {
39 input: "日本語テスト",
40 maxLen: 13, // 3 chars * 3 bytes each = 9 bytes + "..." = 12 bytes fits in 13
41 expected: "日本語...",
42 },
43 "mixed UTF-8 and ASCII": {
44 input: "hello世界test",
45 maxLen: 13, // "hello" (5) + "世" (3) + "界" (3) = 11 bytes + "..." = 14, so truncate to fit
46 expected: "hello世...",
47 },
48 "very small maxLen": {
49 input: "hello",
50 maxLen: 4, // only room for 1 char + "..."
51 expected: "h...",
52 },
53 "emoji handling": {
54 input: "test🚀emoji",
55 maxLen: 8, // "test" (4) + "..." (3) = 7 bytes fits in 8
56 expected: "test...",
57 },
58 "maxLen zero": {
59 input: "hello",
60 maxLen: 0,
61 expected: "",
62 },
63 "maxLen negative": {
64 input: "hello",
65 maxLen: -1,
66 expected: "",
67 },
68 "maxLen one ASCII": {
69 input: "hello",
70 maxLen: 1,
71 expected: "h",
72 },
73 "maxLen two ASCII": {
74 input: "hello",
75 maxLen: 2,
76 expected: "he",
77 },
78 "maxLen one UTF-8 too small": {
79 input: "日本語", // each char is 3 bytes
80 maxLen: 1, // can't fit any full rune
81 expected: "",
82 },
83 "maxLen two UTF-8 too small": {
84 input: "日本語",
85 maxLen: 2, // still can't fit a 3-byte rune
86 expected: "",
87 },
88 "maxLen three with long text": {
89 input: "日本語",
90 maxLen: 3, // only room for ellipsis, no content
91 expected: "...",
92 },
93 }
94
95 for name, tc := range tests {
96 t.Run(name, func(t *testing.T) {
97 result := TruncateText(tc.input, tc.maxLen)
98 assert.Equal(t, tc.expected, result)
99 })
100 }
101 }
102
103 func TestTruncateText_LongQuery(t *testing.T) {
104 // Simulate a real SQL query scenario
105 longQuery := strings.Repeat("SELECT * FROM table WHERE id = ?; ", 200)
106 result := TruncateText(longQuery, 4096)
107
108 assert.LessOrEqual(t, len(result), 4096)
109 assert.True(t, strings.HasSuffix(result, "..."))
110 }