Skip to content

Commit

Permalink
feat: 添加 Assertion.When
Browse files Browse the repository at this point in the history
  • Loading branch information
caixw committed Apr 19, 2024
1 parent aacbd71 commit 005ede1
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
2 changes: 1 addition & 1 deletion assert.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
//
// // 也可以对 testing.B 使用
// func Benchmark1(b *testing.B) {
// a := assert.New(b)
// a := assert.New(b, false)
// a.True(false)
// for(i:=0; i<b.N; i++) {
// // do something
Expand Down
15 changes: 14 additions & 1 deletion assertion.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ type Assertion struct {

// New 返回 [Assertion] 对象
//
// fatal 决定在出错时是调用 tb.Error 还是 tb.Fatal;
// fatal 决定在出错时是调用 [testing.TB.Error] 还是 [testing.TB.Fatal]
func New(tb testing.TB, fatal bool) *Assertion {
p := tb.Error
if fatal {
Expand Down Expand Up @@ -211,6 +211,19 @@ func (a *Assertion) NotMatch(reg *regexp.Regexp, v interface{}, msg ...interface
}
}

// When 断言 expr 为 true 且在条件成立时调用 f
//
// 当有一组依赖 expr 的断言时,可以调用此方法。f 的参数 a 即为当前实例。
func (a *Assertion) When(expr bool, f func(a *Assertion), msg ...interface{}) *Assertion {
if expr {
f(a)
} else {
a.TB().Helper()
a.Assert(false, NewFailure("When", msg, nil))
}
return a
}

// Wait 等待一定时间再执行后续操作
func (a *Assertion) Wait(d time.Duration) *Assertion {
time.Sleep(d)
Expand Down
8 changes: 8 additions & 0 deletions assertion_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,3 +143,11 @@ func TestAssertion_Match(t *testing.T) {
a.Match(regexp.MustCompile("^[1-9]*$"), []byte("123"))
a.NotMatch(regexp.MustCompile("^[1-9]*$"), []byte("x123"))
}

func TestAssert_When(t *testing.T) {
a := New(t, false)

a.When(true, func(a *Assertion) {
a.True(true)
})
}

0 comments on commit 005ede1

Please sign in to comment.