add test cases

This commit is contained in:
TangBin
2018-11-21 11:32:36 +08:00
parent 26cd847262
commit 6dc3d879c7
2 changed files with 44 additions and 10 deletions

View File

@@ -1,6 +1,7 @@
package httperrors
import (
"bytes"
"fmt"
"yunion.io/x/onecloud/pkg/util/httputils"
)
@@ -18,39 +19,38 @@ func msgToTemplate(msg string) string {
fmtstr := false
lst := []rune(msg)
lastIndex := len(lst) - 1
temp := []rune{}
temp := bytes.Buffer{}
index := 0
for i, c := range lst {
switch c {
case '%':
if fmtstr || i == lastIndex {
temp = append(temp, c)
temp.WriteRune(c)
fmtstr = false
} else {
fmtstr = true
}
case 'v', 'T', 't', 'b', 'c', 'd', 'o', 'q', 'x', 'X', 'U', 'e', 'E', 'f', 'F', 'g', 'G', 's', 'p':
if fmtstr {
i := []rune(fmt.Sprintf("%d", index))
temp = append(temp, '{')
temp = append(temp, i...)
temp = append(temp, '}')
temp.WriteRune('{')
temp.WriteString(fmt.Sprintf("%d", index))
temp.WriteRune('}')
index++
fmtstr = false
} else {
temp = append(temp, c)
temp.WriteRune(c)
}
default:
if fmtstr {
temp = append(temp, '%')
temp.WriteRune('%')
}
temp = append(temp, c)
temp.WriteRune(c)
fmtstr = false
}
}
return string(temp)
return temp.String()
}
func errorMessage(msg string, params ...interface{}) (string, httputils.Error) {

View File

@@ -50,3 +50,37 @@ func TestVariadic(t *testing.T) {
})
}
}
func TestMsgToTemplate(t *testing.T) {
cases := []struct {
name string
msg string
params []interface{}
out string
}{
{
name: "non-empty msg to template",
msg: "%% baremetals %s delete.time %d%",
out: "% baremetals {0} delete.time {1}%",
},
{
name: "empty msg to template",
msg: "",
out: "",
},
{
name: "non-empty with zh-utf8 characters msg to template",
msg: "%% baremetals %s 中文%d ¥%%",
out: "% baremetals {0} 中文{1} ¥%",
},
}
for _, c := range cases{
t.Run(c.name, func(t *testing.T) {
resp := msgToTemplate(c.msg)
if resp != c.out {
t.Errorf("want %s, got %s", c.out, resp)
}
})
}
}