我正在使用Go的验证程序包验证我的配置文件
我作为string读取的配置文件中的一个字段(string),希望确保它是一个有效的时间duration
type Config struct{
...
CreateTime string `yaml:"createTime" validate:"duration,required"`
...
}因此,我编写了如下自定义验证函数:
import (
"time"
"github.com/go-playground/validator/v10"
)
// isValidDuration is a custom validation function, and it will check if the given string is a valid time duration
func isValidDuration(fl validator.FieldLevel) bool {
if _, err := time.ParseDuration(fl.Field().String()); err != nil {
return false
}
return true
}用于验证的内容如下:
func (configObject *Config) Validate() error {
// Validate configurations
validate := validator.New()
if err := validate.RegisterValidation("duration", isValidDuration); err != nil {
return err
}
return validate.Struct(configObject)
}自定义验证器工作正常,我想为isValidDuration函数编写一个单元测试。下面是IDE生成的单元测试样板:
import (
"testing"
"github.com/go-playground/validator/v10"
)
func Test_isValidDuration(t *testing.T) {
type args struct {
fl validator.FieldLevel
}
var tests = []struct {
name string
args args
want bool
}{
// TODO: Add test cases.
{name: "positive", args: ???????, want: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isValidDuration(tt.args.fl); got != tt.want {
t.Errorf("isValidDuration() = %v, want %v", got, tt.want)
}
})
}
}我是新手,不知道在上面的testcase的args字段中传递什么。如何创建包含一个struct字段的validator.FieldLevel?
理想情况下,我希望将类似于"10m"的内容作为args传递,并且由于它是一个有效的持续时间,因此希望isValidDuration输出为true,因为"10m"是一个有效的持续时间。我正在尝试这个:{name: "positive", args: struct{ fl validator.FieldLevel }{fl: "10m"}, want: true},但得到这封信:'"10m"' (type string) cannot be represented by the type validator.FieldLevel
如何创建一个值等于validator.FieldLevel的"10m"变量?有人能帮帮我吗?
发布于 2022-02-07 04:12:23
problem1
一个语言语义问题,fl不是类型字符串。
{
name: "positive",
args: args{
fl: validator.FieldLevel{
// ....
},
},
want: true,
},problem2
如何使用validator.FieldLevel。
在代码库中,我们可以看到FieldLevel是一个接口,您需要创建结构validate,它不是导出的,不应该被用户使用。
type FieldLevel interface
// ...
var _ FieldLevel = new(validate)回答
所以,最好像UT那样编写验证器包。不要使用IDE中的代码!
// have a look at this UT
// github.com/go-playground/validator/v10@v10.10.0/validator_test.go
func TestKeysCustomValidation(t *testing.T) {https://stackoverflow.com/questions/71008310
复制相似问题