mirror of
https://github.com/yunionio/cloudpods.git
synced 2026-07-01 03:24:29 +08:00
add test cases
This commit is contained in:
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user