github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/dm/pkg/utils/string_test.go (about) 1 // Copyright 2019 PingCAP, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package utils 15 16 import ( 17 "testing" 18 19 "github.com/stretchr/testify/require" 20 ) 21 22 func TestTruncateString(t *testing.T) { 23 t.Parallel() 24 25 cases := []struct { 26 s string 27 n int 28 expect string 29 }{ 30 {s: "", n: 0, expect: ""}, 31 {s: "", n: 3, expect: ""}, 32 {s: "abc", n: 0, expect: "..."}, 33 {s: "abc", n: 1, expect: "a..."}, 34 {s: "abc", n: 3, expect: "abc"}, 35 {s: "abc", n: 9, expect: "abc"}, 36 {s: "abcdefg", n: 5, expect: "abcde..."}, 37 {s: "abcdefg", n: 10, expect: "abcdefg"}, 38 } 39 40 for _, cs := range cases { 41 require.Equal(t, cs.expect, TruncateString(cs.s, cs.n)) 42 } 43 } 44 45 func TestTruncateInterface(t *testing.T) { 46 t.Parallel() 47 48 type compose struct { 49 b bool 50 i int 51 s string 52 } 53 54 var ( 55 i1 = compose{b: true, i: 123, s: "abc"} 56 i2 = compose{b: true, i: 456, s: "def"} 57 i3 = compose{b: false, i: 321, s: "cba"} 58 i4 = compose{b: false, i: 654, s: "fed"} 59 iis [][]interface{} 60 ) 61 iis = append(iis, []interface{}{i1, i2}, []interface{}{i3, i4}) 62 63 cases := []struct { 64 v interface{} 65 n int 66 expect string 67 }{ 68 {v: nil, n: -1, expect: "<nil>"}, 69 {v: nil, n: 0, expect: "..."}, 70 {v: nil, n: 3, expect: "<ni..."}, 71 {v: nil, n: 9, expect: "<nil>"}, 72 {v: 123, n: 0, expect: "..."}, 73 {v: 123, n: 3, expect: "123"}, 74 {v: compose{b: true, i: 123, s: "abc"}, n: 3, expect: "{b:..."}, 75 {v: compose{b: true, i: 123, s: "abc"}, n: 9, expect: "{b:true i..."}, 76 {v: compose{b: true, i: 123, s: "abc"}, n: 99, expect: "{b:true i:123 s:abc}"}, 77 {v: []string{"abc", "123"}, n: 3, expect: "[ab..."}, 78 {v: []string{"abc", "123"}, n: 9, expect: "[abc 123]"}, 79 {v: []compose{{b: true, i: 123, s: "abc"}, {b: false, i: 456, s: "def"}}, n: 3, expect: "[{b..."}, 80 {v: []compose{{b: true, i: 123, s: "abc"}, {b: false, i: 456, s: "def"}}, n: 99, expect: "[{b:true i:123 s:abc} {b:false i:456 s:def}]"}, 81 {v: iis, n: 3, expect: "[[{..."}, 82 {v: iis, n: 9, expect: "[[{b:true..."}, 83 {v: iis, n: 99, expect: "[[{b:true i:123 s:abc} {b:true i:456 s:def}] [{b:false i:321 s:cba} {b:false i:654 s:fed}]]"}, 84 } 85 86 for _, cs := range cases { 87 require.Equal(t, cs.expect, TruncateInterface(cs.v, cs.n)) 88 } 89 }