gpt4 book ai didi

GoConvey 自定义断言未按预期工作

转载 作者:数据小太阳 更新时间:2023-10-29 03:11:42 24 4
gpt4 key购买 nike

不确定为什么以下自定义断言不起作用,这似乎是一个编译错误,但我使用的语法似乎符合他们 wiki 页面中解释的内容:https://github.com/smartystreets/goconvey/wiki/Custom-Assertions

我基本上想断言在结构中归档的 time.Time 表示过去 24 小时内的日期。

// func shouldBeInTheLast24Hours(targetDate time.Time, foo time.Time) string {
func shouldBeInTheLast24Hours(targetDate time.Time) string {
if targetDate.Before(time.Now().Add(time.Duration(-24) * time.Hour)) {
return ""
} else {
return "The target date is assumed to be in the last 24 hours, go *THERE* and fix stuff"
}
}

type DateStuff struct {
VipDate time.Time
}

func TestDateStuff(t *testing.T) {
Convey("Given date stuff", t, func() {
Convey("should verify some custom assertions are working", func() {
myDateStruct := &DateStuff{VipDate: time.Now()}

// So(myDateStruct.VipDate, shouldBeInTheLast24Hours, nil) // this throws "cannot use shouldBeInTheLast24Hours (type func(time.Time, time.Time) string) as type convey.assertion in argument to convey.So"
So(myDateStruct.VipDate, shouldBeInTheLast24Hours) // this throws "cannot use shouldBeInTheLast24Hours (type func(time.Time) string) as type convey.assertion in argument to convey.So"
})
})
}

在检查我使用的 Go Convey 版本时,我看到了这个:

$ cd $GOPATH/src/github.com/smartystreets/goconvey/ && git log -n 1 | grep Date
Date: Fri Aug 25 16:14:26 2017 -0600

在 wiki 页面上的日期(2013 年 11 月 15 日)之后,所以更新我的 $GOPATH 中的 Go Convey 库应该不是问题。

我不太熟悉这种闭包语法,但在我看来我并没有滥用它,但是我看到了编译错误,所以我一定是遗漏了一些陷阱。

最佳答案

下面是我将如何编写自定义断言:

func shouldBeInTheLast24Hours(actual interface{}, _ ...interface{}) string {
providedDate := actual.(time.Time)
theshold := time.Now().Add(time.Hour * -24)
if providedDate.After(theshold) {
return ""
} else {
return "The target date is assumed to be in the last 24 hours, go *THERE* and fix stuff"
}
}

func TestDateStuff(t *testing.T) {
Convey("Given date stuff", t, func() {
Convey("should verify some custom assertions are working", func() {
vipDate := time.Now()
So(vipDate, shouldBeInTheLast24Hours)
})
})
}

自定义断言的函数签名必须匹配断言函数类型:

// assertion is an alias for a function with a signature that the convey.So()
// method can handle. Any future or custom assertions should conform to this
// method signature. The return value should be an empty string if the assertion
// passes and a well-formed failure message if not.
type assertion func(actual interface{}, expected ...interface{}) string

但是,正如评论中所述,已经定义了一个可以满足您需要的断言:

So(vipDate, ShouldHappenWithin, time.Hour*24, time.Now())

关于GoConvey 自定义断言未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50020919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com