code.gitea.io/gitea@v1.19.3/modules/util/truncate_test.go (about)

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