From 0378c681e8765478b1f16e813672e26198c6fac5 Mon Sep 17 00:00:00 2001 From: Victor Blomqvist Date: Thu, 12 Sep 2013 13:24:50 +0800 Subject: [PATCH] added new assert WithinDuration --- assert/assertions.go | 16 ++++++++++++++++ assert/assertions_test.go | 12 ++++++++++++ assert/doc.go | 3 +++ 3 files changed, 31 insertions(+) diff --git a/assert/assertions.go b/assert/assertions.go index 179661e..cc027cb 100644 --- a/assert/assertions.go +++ b/assert/assertions.go @@ -6,6 +6,7 @@ import ( "runtime" "strings" "testing" + "time" ) // Comparison a custom function that returns true on success and false on failure @@ -414,6 +415,21 @@ func NotPanics(t *testing.T, f PanicTestFunc, msgAndArgs ...interface{}) bool { return true } +// WithinDuration asserts that the two times are within duration delta of each other. +// +// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") +// +// Returns whether the assertion was successful (true) or not (false). +func WithinDuration(t *testing.T, a, b time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { + + dt := a.Sub(b) + if dt < -delta || dt > delta { + return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", a, b, dt, delta), msgAndArgs...) + } + + return true +} + /* Errors */ diff --git a/assert/assertions_test.go b/assert/assertions_test.go index e7ea5a9..0c3a821 100644 --- a/assert/assertions_test.go +++ b/assert/assertions_test.go @@ -3,6 +3,7 @@ package assert import ( "errors" "testing" + "time" ) // AssertionTesterInterface defines an interface to be used for testing assertion methods @@ -361,3 +362,14 @@ func TestNotEmpty(t *testing.T) { True(t, NotEmpty(mockT, true), "True value is not empty") } + +func TestWithinDuration(t *testing.T) { + + mockT := new(testing.T) + a := time.Now() + b := a.Add(10 * time.Second) + + True(t, WithinDuration(mockT, a, b, 10*time.Second), "A 10s difference is within a 10s time difference") + + False(t, WithinDuration(mockT, a, b, 9*time.Second), "A 10s difference is not within a 9s time difference") +} diff --git a/assert/doc.go b/assert/doc.go index 17397e3..25f699b 100644 --- a/assert/doc.go +++ b/assert/doc.go @@ -68,4 +68,7 @@ // // call code that should not panic // // } [, message [, format-args]]) +// +// assert.WithinDuration(t, timeA, timeB, deltaTime, [, message [, format-args]]) + package assert