github.com/qioalice/ekago/v3@v3.3.2-0.20221202205325-5c262d586ee4/ekastr/interpolation_test.go (about) 1 // Copyright © 2020. All rights reserved. 2 // Author: Ilya Stroy. 3 // Contacts: iyuryevich@pm.me, https://github.com/qioalice 4 // License: https://opensource.org/licenses/MIT 5 6 package ekastr_test 7 8 import ( 9 "fmt" 10 "testing" 11 12 "github.com/qioalice/ekago/v3/ekastr" 13 14 "github.com/stretchr/testify/assert" 15 ) 16 17 type ( 18 /* 19 _TITC is Interpolation's test cases 20 */ 21 _TITC struct { 22 str string 23 expected []_TITCSP 24 } 25 26 /* 27 _TITCSP is Interpolation test cases' string parts 28 */ 29 _TITCSP struct { 30 part string 31 isVerb bool 32 } 33 ) 34 35 var ( 36 itc = []_TITC{ 37 { 38 str: "Hello, {{name}}! Nice to meet you.", 39 expected: []_TITCSP{ 40 {"Hello, ", false}, 41 {"{{name}}", true}, 42 {"! Nice to meet you.", false}, 43 }, 44 }, 45 { 46 str: "А вот и {{utf8}} текст с {{даже}} utf8 {{глаголом}}", 47 expected: []_TITCSP{ 48 {"А вот и ", false}, 49 {"{{utf8}}", true}, 50 {" текст с ", false}, 51 {"{{даже}}", true}, 52 {" utf8 ", false}, 53 {"{{глаголом}}", true}, 54 }, 55 }, 56 } 57 ) 58 59 func TestInterpolateb(t *testing.T) { 60 61 var ( 62 gotParts = make([]_TITCSP, 0, 32) 63 gotPartsPtr = &gotParts 64 ) 65 66 gotVerb := func(verb []byte) { 67 *gotPartsPtr = append(*gotPartsPtr, _TITCSP{ 68 part: string(verb), 69 isVerb: true, 70 }) 71 } 72 73 gotJustText := func(text []byte) { 74 *gotPartsPtr = append(*gotPartsPtr, _TITCSP{ 75 part: string(text), 76 }) 77 } 78 79 for i, testCase := range itc { 80 gotParts = gotParts[:0] 81 ekastr.Interpolateb([]byte(testCase.str), gotVerb, gotJustText) 82 assert.Equal(t, testCase.expected, gotParts, "%i test case", i) 83 } 84 } 85 86 func BenchmarkInterpolate(b *testing.B) { 87 const S = "This is some {{kind}} of string that must be {{interpolated}}." 88 b.ReportAllocs() 89 cb := func(_ string) {} 90 for i := 0; i < b.N; i++ { 91 ekastr.Interpolate(S, cb, cb) 92 } 93 } 94 95 func BenchmarkInterpolateb(b *testing.B) { 96 const S = "This is some {{kind}} of string that must be {{interpolated}}." 97 b.ReportAllocs() 98 cb := func(_ []byte) {} 99 for i := 0; i < b.N; i++ { 100 arr := ekastr.S2B(S) 101 ekastr.Interpolateb(arr, cb, cb) 102 } 103 } 104 105 func BenchmarkPrintf(b *testing.B) { 106 const S = "This is some %s of string that must be %s." 107 b.ReportAllocs() 108 for i := 0; i < b.N; i++ { 109 _ = fmt.Sprintf(S, "kind", "interpolated") 110 } 111 }