go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/assert/its_in_time_delta.go (about) 1 /* 2 3 Copyright (c) 2023 - Present. Will Charczuk. All rights reserved. 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository. 5 6 */ 7 8 package assert 9 10 import ( 11 "testing" 12 "time" 13 ) 14 15 // ItsInTimeDelta is a test helper to verify that two times are within a given duration. 16 // 17 // It works strictly in an absolute sense, that is if one time is before another, or vice versa 18 // the delta will always be positive. 19 func ItsInTimeDelta(t *testing.T, t0, t1 time.Time, d time.Duration, userMessage ...any) { 20 t.Helper() 21 if !areInTimeDelta(t0, t1, d) { 22 Fatalf(t, "expected %v and %v to be within delta %v", []any{t0, t1, d}, userMessage) 23 } 24 } 25 26 // ItsNotInTimeDelta is a test helper to verify that two times are within a given duration. 27 // 28 // It works strictly in an absolute sense, that is if one time is before another, or vice versa 29 // the delta will always be positive. 30 func ItsNotInTimeDelta(t *testing.T, t0, t1 time.Time, d time.Duration, userMessage ...any) { 31 t.Helper() 32 if areInTimeDelta(t0, t1, d) { 33 Fatalf(t, "expected %v and %v not to be within delta %v", []any{t0, t1, d}, userMessage) 34 } 35 } 36 37 func areInTimeDelta(t0, t1 time.Time, d time.Duration) bool { 38 var diff time.Duration 39 if t0.After(t1) { 40 diff = t0.Sub(t1) 41 } else { 42 diff = t1.Sub(t0) 43 } 44 return diff < d 45 }