forgejo/modules/util/truncate_test.go
Mopcho 64cc883ac1 Fix discord webhook 400 status code when description limit is exceeded (#34084)
Fixes [#34027](https://github.com/go-gitea/gitea/issues/34027)

Discord does not allow for description bigger than 2048 bytes. If the
description is bigger than that it will throw 400 and the event won't
appear in discord. To fix that, in the createPayload method we now slice
the description to ensure it doesn’t exceed the limit.

---------

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
(cherry picked from commit 013b2686fe6d306c4fb800147207b099866683b9)
2025-04-07 18:27:08 +02:00

61 lines
1.8 KiB
Go

// Copyright 2021 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package util
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSplitString(t *testing.T) {
type testCase struct {
input string
n int
leftSub string
ellipsis string
}
test := func(tc []*testCase, f func(input string, n int) (left, right string)) {
for _, c := range tc {
l, r := f(c.input, c.n)
if c.ellipsis != "" {
assert.Equal(t, c.leftSub+c.ellipsis, l, "test split %q at %d, expected leftSub: %q", c.input, c.n, c.leftSub)
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):])
} else {
assert.Equal(t, c.leftSub, l, "test split %q at %d, expected leftSub: %q", c.input, c.n, c.leftSub)
assert.Empty(t, r, "test split %q at %d, expected rightSub: %q", c.input, c.n, "")
}
}
}
tc := []*testCase{
{"abc123xyz", 0, "", utf8Ellipsis},
{"abc123xyz", 1, "", utf8Ellipsis},
{"abc123xyz", 4, "a", utf8Ellipsis},
{"啊bc123xyz", 4, "", utf8Ellipsis},
{"啊bc123xyz", 6, "啊", utf8Ellipsis},
{"啊bc", 5, "啊bc", ""},
{"啊bc", 6, "啊bc", ""},
{"abc\xef\x03\xfe", 3, "", asciiEllipsis},
{"abc\xef\x03\xfe", 4, "a", asciiEllipsis},
{"\xef\x03", 1, "\xef\x03", ""},
}
test(tc, SplitStringAtByteN)
}
func TestTruncateRunes(t *testing.T) {
assert.Empty(t, TruncateRunes("", 0))
assert.Empty(t, TruncateRunes("", 1))
assert.Empty(t, TruncateRunes("ab", 0))
assert.Equal(t, "a", TruncateRunes("ab", 1))
assert.Equal(t, "ab", TruncateRunes("ab", 2))
assert.Equal(t, "ab", TruncateRunes("ab", 3))
assert.Empty(t, TruncateRunes("测试", 0))
assert.Equal(t, "测", TruncateRunes("测试", 1))
assert.Equal(t, "测试", TruncateRunes("测试", 2))
assert.Equal(t, "测试", TruncateRunes("测试", 3))
}