github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/utils/strutil/format_test.go (about) 1 package strutil 2 3 import ( 4 "testing" 5 6 "github.com/stretchr/testify/assert" 7 ) 8 9 func TestFormat_AutoNumber(t *testing.T) { 10 str := "some test {} and {test1} {} with {test2}" 11 got := Format(str, map[string]any{"test1": "abc", "test2": 123}, "position1", []string{"sliceElem1", "sliceElem2"}) 12 want := "some test position1 and abc [sliceElem1 sliceElem2] with 123" 13 assert.Equal(t, want, got) 14 } 15 16 func TestFormat_ManualNumber(t *testing.T) { 17 str := "some test {0} and {test1} {1} with {test2} {0}" 18 got := Format(str, map[string]any{"test1": "abc", "test2": 123}, "position1", []string{"sliceElem1", "sliceElem2"}) 19 want := "some test position1 and abc [sliceElem1 sliceElem2] with 123 position1" 20 assert.Equal(t, want, got) 21 } 22 23 func TestFormat_Struct(t *testing.T) { 24 str := "some test {Field1:%s} and {Field2:08d}" 25 got := Format(str, &testObject{Field1: "abc", Field2: 123}) 26 want := "some test abc and 00000123" 27 assert.Equal(t, want, got) 28 } 29 30 func TestFormat_EscapeWing(t *testing.T) { 31 got := Format("{{ some text }}", nil) 32 want := "{ some text }" 33 assert.Equal(t, want, got) 34 } 35 36 func TestFormat_Malformed(t *testing.T) { 37 str1 := "some test {} {0} {} {1}" 38 got1 := Format(str1, nil, "abc", "123") 39 want1 := "some test abc {0} 123 {1}" 40 assert.Equal(t, want1, got1) 41 42 str2 := "some test {1} {} {0} {}" 43 got2 := Format(str2, nil, "abc", "123") 44 want2 := "some test 123 {} abc {}" 45 assert.Equal(t, want2, got2) 46 47 str3 := "some test {abc} {{abc}} {key2}" 48 got3 := Format(str3, map[string]any{"abc": "123"}) 49 want3 := "some test 123 {abc} {key2}" 50 assert.Equal(t, want3, got3) 51 52 str4 := "some test {Field1} {Field3:%.8f} {private:08d}" 53 got4 := Format(str4, &testObject{Field1: "abc", Field2: 123, private: 456}) 54 want4 := "some test abc {Field3:%.8f} 00000456" 55 assert.Equal(t, want4, got4) 56 } 57 58 func TestFormat_StringInterfaceMap(t *testing.T) { 59 str := "some test {abc} {{abc}} {key2}" 60 kwArgs := map[String]any{"abc": "123"} 61 got := Format(str, kwArgs) 62 want := "some test 123 {abc} {key2}" 63 assert.Equal(t, want, got) 64 } 65 66 type String string 67 68 type testObject struct { 69 Field1 string 70 Field2 int64 71 private int32 72 }