| 1 |
package check |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"encoding/json" |
| 7 |
"errors" |
| 8 |
"fmt" |
| 9 |
"math" |
| 10 |
"os" |
| 11 |
"reflect" |
| 12 |
"regexp" |
| 13 |
"strings" |
| 14 |
"testing" |
| 15 |
"time" |
| 16 |
|
| 17 |
"github.com/powerman/check/internal/deepequal" |
| 18 |
) |
| 19 |
|
| 20 |
//nolint:gochecknoglobals // Const. |
| 21 |
var ( |
| 22 |
typString = reflect.TypeFor[string]() |
| 23 |
typBytes = reflect.TypeFor[[]byte]() |
| 24 |
typFloat64 = reflect.TypeFor[float64]() |
| 25 |
) |
| 26 |
|
| 27 |
// C wraps [*testing.T] to make it convenient to call checkers in test. |
| 28 |
type C struct { |
| 29 |
// C is a thin [*testing.T]-only compatibility shell built on the same machinery as [TB]: |
| 30 |
// it embeds [*testing.T] (its sole, unambiguous [testing.TB] source - |
| 31 |
// so Helper/Cleanup/Log/... and friends stay genuinely zero-cost) |
| 32 |
// and *checks (which provides the wide checker API for free |
| 33 |
// and never collides with [*testing.T]'s own method names). |
| 34 |
// Error, Errorf, Fatal, Fatalf, Fail, FailNow and Context are the one exception: |
| 35 |
// check needs to intercept them (for statistics/TODO/Must and the merged Context), |
| 36 |
// so each gets a short explicit override below - direct declarations always win |
| 37 |
// over promoted ones, so this doesn't reintroduce any ambiguity. |
| 38 |
*checks |
| 39 |
*testing.T |
| 40 |
} |
| 41 |
|
| 42 |
const ( |
| 43 |
nameActual = "Actual" |
| 44 |
nameExpected = "Expected" |
| 45 |
) |
| 46 |
|
| 47 |
var _ testing.TB = (*C)(nil) |
| 48 |
|
| 49 |
// T creates and returns new *C, which wraps given tt and supposed to be |
| 50 |
// used inplace of it, providing you with access to many useful helpers in |
| 51 |
// addition to standard methods of [*testing.T]. |
| 52 |
// |
| 53 |
// It's convenient to rename Test function's arg from t to something |
| 54 |
// else, create wrapped variable with usual name t and use only t: |
| 55 |
// |
| 56 |
// func TestSomething(tt *testing.T) { |
| 57 |
// t := check.T(tt) |
| 58 |
// // use only t in test and don't touch tt anymore |
| 59 |
// } |
| 60 |
// |
| 61 |
// T is a soft-mode, [*testing.T]-only legacy constructor kept for backward compatibility. |
| 62 |
// For new tests prefer [Must], which also works with [*testing.B] and [*testing.F]. |
| 63 |
func T(tt *testing.T) *C { //nolint:thelper // With check we name it tt! |
| 64 |
return &C{checks: &checks{tb: tt}, T: tt} |
| 65 |
} |
| 66 |
|
| 67 |
// TODO is like [TB.TODO], but keeps working with *C and [*testing.T]. |
| 68 |
func (t *C) TODO() *C { |
| 69 |
return &C{checks: t.withTODO(), T: t.T} |
| 70 |
} |
| 71 |
|
| 72 |
// MustAll is like [TB.MustAll], but keeps working with *C and [*testing.T]. |
| 73 |
func (t *C) MustAll() *C { |
| 74 |
return &C{checks: t.withMustAll(), T: t.T} |
| 75 |
} |
| 76 |
|
| 77 |
// Context returns the context associated with t: |
| 78 |
// the context merged in by the most recent [C.MergeContext] call if any, |
| 79 |
// otherwise the standard [*testing.T.Context](). |
| 80 |
func (t *C) Context() context.Context { |
| 81 |
return t.context() |
| 82 |
} |
| 83 |
|
| 84 |
// MergeContext is like [TB.MergeContext], but keeps working with *C and [*testing.T]. |
| 85 |
func (t *C) MergeContext(ctx context.Context) *C { |
| 86 |
merged, cancel := t.mergeContext(ctx) |
| 87 |
t.Cleanup(cancel) |
| 88 |
return &C{checks: merged, T: t.T} |
| 89 |
} |
| 90 |
|
| 91 |
// Error is equivalent to Log followed by Fail. |
| 92 |
// |
| 93 |
// It is like t.Errorf with TODO() and statistics support. |
| 94 |
func (t *C) Error(args ...any) { |
| 95 |
t.Helper() |
| 96 |
t.report0(args, false) |
| 97 |
} |
| 98 |
|
| 99 |
// Errorf is equivalent to Logf followed by Fail. |
| 100 |
// |
| 101 |
// It is like t.Errorf with TODO() and statistics support. |
| 102 |
func (t *C) Errorf(format string, args ...any) { |
| 103 |
t.Helper() |
| 104 |
t.report0(append([]any{format}, args...), false) |
| 105 |
} |
| 106 |
|
| 107 |
// Fatal is equivalent to Log followed by FailNow. |
| 108 |
// |
| 109 |
// It is like t.Fatal with TODO() and statistics support. |
| 110 |
func (t *C) Fatal(args ...any) { |
| 111 |
t.Helper() |
| 112 |
t.report0(args, false) |
| 113 |
if !t.todo { |
| 114 |
t.T.FailNow() // Already counted above: bypass the counting FailNow wrapper. |
| 115 |
} |
| 116 |
} |
| 117 |
|
| 118 |
// Fatalf is equivalent to Logf followed by FailNow. |
| 119 |
// |
| 120 |
// It is like t.Fatalf with TODO() and statistics support. |
| 121 |
func (t *C) Fatalf(format string, args ...any) { |
| 122 |
t.Helper() |
| 123 |
t.report0(append([]any{format}, args...), false) |
| 124 |
if !t.todo { |
| 125 |
t.T.FailNow() // Already counted above: bypass the counting FailNow wrapper. |
| 126 |
} |
| 127 |
} |
| 128 |
|
| 129 |
// Fail marks the function as having failed but continues execution. |
| 130 |
// |
| 131 |
// Unlike plain [*testing.T.Fail], calling it directly (rather than through a checker) |
| 132 |
// is still counted in check's pass/fail statistics. |
| 133 |
func (t *C) Fail() { |
| 134 |
t.fail() |
| 135 |
t.T.Fail() |
| 136 |
} |
| 137 |
|
| 138 |
// FailNow marks the function as having failed and stops its execution. |
| 139 |
// |
| 140 |
// Unlike plain [*testing.T.FailNow], calling it directly (rather than through a checker) |
| 141 |
// is still counted in check's pass/fail statistics. |
| 142 |
func (t *C) FailNow() { |
| 143 |
t.fail() |
| 144 |
t.T.FailNow() |
| 145 |
} |
| 146 |
|
| 147 |
// Should is like [TB.Should], but keeps working with *C and [*testing.T]. |
| 148 |
// |
| 149 |
// [ShouldFunc1]/[ShouldFunc2] callbacks always receive a *[TB] (never *C): |
| 150 |
// there's only one pair of callback types, shared by TB and C alike. |
| 151 |
func (t *C) Should(anyShouldFunc any, args ...any) bool { |
| 152 |
t.Helper() |
| 153 |
tb := &TB{TB: t.T, checks: t.checks} |
| 154 |
switch f := anyShouldFunc.(type) { |
| 155 |
case func(t *TB, actual any) bool: |
| 156 |
return tb.should1(f, args...) |
| 157 |
case func(t *TB, actual, expected any) bool: |
| 158 |
return tb.should2(f, args...) |
| 159 |
default: |
| 160 |
panic("anyShouldFunc is not a ShouldFunc1 or ShouldFunc2") |
| 161 |
} |
| 162 |
} |
| 163 |
|
| 164 |
// Nil checks for actual == nil. |
| 165 |
// |
| 166 |
// There is one subtle difference between this check and Go `== nil` (if |
| 167 |
// this surprises you then you should read |
| 168 |
// https://golang.org/doc/faq#nil_error first): |
| 169 |
// |
| 170 |
// var intPtr *int |
| 171 |
// var empty interface{} |
| 172 |
// var notEmpty interface{} = intPtr |
| 173 |
// t.True(intPtr == nil) // TRUE |
| 174 |
// t.True(empty == nil) // TRUE |
| 175 |
// t.True(notEmpty == nil) // FALSE |
| 176 |
// |
| 177 |
// When you call this function your actual value will be stored in |
| 178 |
// interface{} argument, and this makes any typed nil pointer value `!= |
| 179 |
// nil` inside this function (just like in example above happens with |
| 180 |
// notEmpty variable). |
| 181 |
// |
| 182 |
// As it is very common case to check some typed pointer using Nil this |
| 183 |
// check has to work around and detect nil even if usual `== nil` return |
| 184 |
// false. But this has nasty side effect: if actual value already was of |
| 185 |
// interface type and contains some typed nil pointer (which is usually |
| 186 |
// bad thing and should be avoid) then Nil check will pass (which may be |
| 187 |
// not what you want/expect): |
| 188 |
// |
| 189 |
// t.Nil(nil) // TRUE |
| 190 |
// t.Nil(intPtr) // TRUE |
| 191 |
// t.Nil(empty) // TRUE |
| 192 |
// t.Nil(notEmpty) // WARNING: also TRUE! |
| 193 |
// |
| 194 |
// Second subtle case is less usual: uintptr(0) is sorta nil, but not |
| 195 |
// really, so Nil(uintptr(0)) will fail. Nil(unsafe.Pointer(nil)) will |
| 196 |
// also fail, for the same reason. Please do not use this and consider |
| 197 |
// this behaviour undefined, because it may change in the future. |
| 198 |
func (t *checks) Nil(actual any, msg ...any) bool { |
| 199 |
t.tb.Helper() |
| 200 |
return t.report1(actual, msg, |
| 201 |
isNil(actual)) |
| 202 |
} |
| 203 |
|
| 204 |
func isNil(actual any) bool { |
| 205 |
switch val := reflect.ValueOf(actual); val.Kind() { |
| 206 |
case reflect.Invalid: |
| 207 |
return actual == nil |
| 208 |
case reflect.Chan, reflect.Func, reflect.Map, reflect.Pointer, reflect.Slice: |
| 209 |
return val.IsNil() |
| 210 |
case reflect.Uintptr, reflect.UnsafePointer, // Subtle cases documented above. |
| 211 |
reflect.Interface, // ??? |
| 212 |
// Can't be nil: |
| 213 |
reflect.Struct, reflect.Array, reflect.Bool, reflect.String, |
| 214 |
reflect.Complex128, reflect.Complex64, reflect.Float32, reflect.Float64, |
| 215 |
reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int8, |
| 216 |
reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint8: |
| 217 |
} |
| 218 |
return false |
| 219 |
} |
| 220 |
|
| 221 |
// NotNil checks for actual != nil. |
| 222 |
// |
| 223 |
// See Nil about subtle case in check logic. |
| 224 |
func (t *checks) NotNil(actual any, msg ...any) bool { |
| 225 |
t.tb.Helper() |
| 226 |
return t.report0(msg, |
| 227 |
!isNil(actual)) |
| 228 |
} |
| 229 |
|
| 230 |
// True checks for cond == true. |
| 231 |
// |
| 232 |
// This can be useful to use your own custom checks, but this way you |
| 233 |
// won't get nice dump/diff for actual/expected values. You'll still have |
| 234 |
// statistics about passed/failed checks and it's shorter than usual: |
| 235 |
// |
| 236 |
// if !cond { |
| 237 |
// t.Errorf(msg...) |
| 238 |
// } |
| 239 |
func (t *checks) True(cond bool, msg ...any) bool { |
| 240 |
t.tb.Helper() |
| 241 |
return t.report0(msg, |
| 242 |
cond) |
| 243 |
} |
| 244 |
|
| 245 |
// False checks for cond == false. |
| 246 |
func (t *checks) False(cond bool, msg ...any) bool { |
| 247 |
t.tb.Helper() |
| 248 |
return t.report0(msg, |
| 249 |
!cond) |
| 250 |
} |
| 251 |
|
| 252 |
// Equal checks for actual == expected. |
| 253 |
// |
| 254 |
// Note: For [time.Time] it uses actual.Equal(expected) instead. |
| 255 |
func (t *checks) Equal(actual, expected any, msg ...any) bool { |
| 256 |
t.tb.Helper() |
| 257 |
return t.report2(actual, expected, msg, |
| 258 |
isEqual(actual, expected)) |
| 259 |
} |
| 260 |
|
| 261 |
func isEqual(actual, expected any) bool { |
| 262 |
switch actual := actual.(type) { |
| 263 |
case time.Time: |
| 264 |
return actual.Equal(expected.(time.Time)) |
| 265 |
default: |
| 266 |
return actual == expected |
| 267 |
} |
| 268 |
} |
| 269 |
|
| 270 |
// EQ is a synonym for Equal. |
| 271 |
func (t *checks) EQ(actual, expected any, msg ...any) bool { |
| 272 |
t.tb.Helper() |
| 273 |
return t.Equal(actual, expected, msg...) |
| 274 |
} |
| 275 |
|
| 276 |
// NotEqual checks for actual != expected. |
| 277 |
func (t *checks) NotEqual(actual, expected any, msg ...any) bool { |
| 278 |
t.tb.Helper() |
| 279 |
return t.report2(actual, expected, msg, |
| 280 |
!isEqual(actual, expected)) |
| 281 |
} |
| 282 |
|
| 283 |
// NE is a synonym for NotEqual. |
| 284 |
func (t *checks) NE(actual, expected any, msg ...any) bool { |
| 285 |
t.tb.Helper() |
| 286 |
return t.NotEqual(actual, expected, msg...) |
| 287 |
} |
| 288 |
|
| 289 |
// BytesEqual checks for [bytes.Equal](actual, expected). |
| 290 |
// |
| 291 |
// Hint: BytesEqual([]byte{}, []byte(nil)) is true (unlike DeepEqual). |
| 292 |
func (t *checks) BytesEqual(actual, expected []byte, msg ...any) bool { |
| 293 |
t.tb.Helper() |
| 294 |
return t.report2(actual, expected, msg, |
| 295 |
bytes.Equal(actual, expected)) |
| 296 |
} |
| 297 |
|
| 298 |
// NotBytesEqual checks for !bytes.Equal(actual, expected). |
| 299 |
// |
| 300 |
// Hint: NotBytesEqual([]byte{}, []byte(nil)) is false (unlike NotDeepEqual). |
| 301 |
func (t *checks) NotBytesEqual(actual, expected []byte, msg ...any) bool { |
| 302 |
t.tb.Helper() |
| 303 |
return t.report1(actual, msg, |
| 304 |
!bytes.Equal(actual, expected)) |
| 305 |
} |
| 306 |
|
| 307 |
// hasMethod reports whether v has a method with the given name. |
| 308 |
func hasMethod(v any, name string) bool { |
| 309 |
t := reflect.TypeOf(v) |
| 310 |
if t == nil { |
| 311 |
return false |
| 312 |
} |
| 313 |
_, found := t.MethodByName(name) |
| 314 |
return found |
| 315 |
} |
| 316 |
|
| 317 |
// DeepEqual checks for [deepequal.DeepEqual](actual, expected). |
| 318 |
// It will use Equal method for types which implements it |
| 319 |
// (e.g. [time.Time], decimal.Decimal, etc.). |
| 320 |
// |
| 321 |
// Custom equal checkers registered via [RegisterEqualChecker] run first. |
| 322 |
func (t *checks) DeepEqual(actual, expected any, msg ...any) bool { |
| 323 |
t.tb.Helper() |
| 324 |
equal, claimed := runEqualCheckers(actual, expected) |
| 325 |
if !claimed { |
| 326 |
if hasMethod(actual, "ProtoReflect") || hasMethod(expected, "ProtoReflect") { |
| 327 |
panic("check: protobuf message detected; " + |
| 328 |
"import github.com/powerman/checkproto to compare protobuf messages") |
| 329 |
} |
| 330 |
equal = deepequal.DeepEqual(actual, expected) |
| 331 |
} |
| 332 |
return t.report2(actual, expected, msg, equal) |
| 333 |
} |
| 334 |
|
| 335 |
// NotDeepEqual checks for . |
| 336 |
// It will use Equal method for types which implements it |
| 337 |
// (e.g. [time.Time], decimal.Decimal, etc.). |
| 338 |
// |
| 339 |
// Custom equal checkers registered via [RegisterEqualChecker] run first. |
| 340 |
func (t *checks) NotDeepEqual(actual, expected any, msg ...any) bool { |
| 341 |
t.tb.Helper() |
| 342 |
equal, claimed := runEqualCheckers(actual, expected) |
| 343 |
if claimed { |
| 344 |
return t.report1(actual, msg, !equal) |
| 345 |
} |
| 346 |
if hasMethod(actual, "ProtoReflect") || hasMethod(expected, "ProtoReflect") { |
| 347 |
panic("check: protobuf message detected; " + |
| 348 |
"import github.com/powerman/checkproto to compare protobuf messages") |
| 349 |
} |
| 350 |
return t.report1(actual, msg, |
| 351 |
!deepequal.DeepEqual(actual, expected)) |
| 352 |
} |
| 353 |
|
| 354 |
// Match checks for regex.MatchString(actual). |
| 355 |
// |
| 356 |
// Regex type can be either [*regexp.Regexp] or string. |
| 357 |
// |
| 358 |
// Actual type can be: |
| 359 |
// - string - will match with actual |
| 360 |
// - []byte - will match with string(actual) |
| 361 |
// - []rune - will match with string(actual) |
| 362 |
// - [fmt.Stringer] - will match with actual.String() |
| 363 |
// - error - will match with actual.Error() |
| 364 |
// - nil - will not match (even with empty regex) |
| 365 |
func (t *checks) Match(actual, regex any, msg ...any) bool { |
| 366 |
t.tb.Helper() |
| 367 |
ok := isMatch(&actual, regex) |
| 368 |
return t.report2(actual, regex, msg, |
| 369 |
ok) |
| 370 |
} |
| 371 |
|
| 372 |
// isMatch updates actual to be a real string used for matching, to make |
| 373 |
// dump easier to understand, but this result in losing type information. |
| 374 |
func isMatch(actual *any, regex any) bool { |
| 375 |
if *actual == nil { |
| 376 |
return false |
| 377 |
} |
| 378 |
if !stringify(actual) { |
| 379 |
panic("actual is not a string, []byte, []rune, fmt.Stringer, error or nil") |
| 380 |
} |
| 381 |
s := (*actual).(string) //nolint:forcetypeassert // False positive. |
| 382 |
|
| 383 |
switch v := regex.(type) { |
| 384 |
case *regexp.Regexp: |
| 385 |
return v.MatchString(s) |
| 386 |
case string: |
| 387 |
return regexp.MustCompile(v).MatchString(s) |
| 388 |
} |
| 389 |
panic("regex is not a *regexp.Regexp or string") |
| 390 |
} |
| 391 |
|
| 392 |
func stringify(arg *any) bool { |
| 393 |
switch v := (*arg).(type) { |
| 394 |
case nil: |
| 395 |
return false |
| 396 |
case json.RawMessage: |
| 397 |
// Go 1.27 made json.RawMessage an alias for jsontext.Value, which |
| 398 |
// (unlike the pre-1.27 json.RawMessage) implements fmt.Stringer. |
| 399 |
// Handle it explicitly to keep behavior identical across Go versions: |
| 400 |
// json.RawMessage stays supported (as a []byte), *json.RawMessage stays not. |
| 401 |
// This also covers a directly used jsontext.Value/*jsontext.Value, since |
| 402 |
// on Go 1.27 it's the exact same type as json.RawMessage/*json.RawMessage. |
| 403 |
// |
| 404 |
// encoding/json/jsontext only exists once GOEXPERIMENT=jsonv2 is the |
| 405 |
// default (Go 1.27+), so once support for Go 1.26 is dropped, these two |
| 406 |
// cases could import encoding/json/jsontext and match jsontext.Value / |
| 407 |
// *jsontext.Value directly instead, which would read more naturally. |
| 408 |
*arg = string(v) |
| 409 |
case *json.RawMessage: |
| 410 |
return false |
| 411 |
case error: |
| 412 |
*arg = v.Error() |
| 413 |
case fmt.Stringer: |
| 414 |
*arg = v.String() |
| 415 |
default: |
| 416 |
typ := reflect.TypeOf(*arg) |
| 417 |
switch typ.Kind() { //nolint:exhaustive // Covered by default case. |
| 418 |
case reflect.String: |
| 419 |
case reflect.Slice: |
| 420 |
switch typ.Elem().Kind() { //nolint:exhaustive // Covered by default case. |
| 421 |
case reflect.Uint8, reflect.Int32: |
| 422 |
default: |
| 423 |
return false |
| 424 |
} |
| 425 |
default: |
| 426 |
return false |
| 427 |
} |
| 428 |
*arg = reflect.ValueOf(*arg).Convert(typString).Interface() |
| 429 |
} |
| 430 |
return true |
| 431 |
} |
| 432 |
|
| 433 |
// NotMatch checks for !regex.MatchString(actual). |
| 434 |
// |
| 435 |
// See Match about supported actual/regex types and check logic. |
| 436 |
func (t *checks) NotMatch(actual, regex any, msg ...any) bool { |
| 437 |
t.tb.Helper() |
| 438 |
ok := !isMatch(&actual, regex) |
| 439 |
return t.report2(actual, regex, msg, |
| 440 |
ok) |
| 441 |
} |
| 442 |
|
| 443 |
// Contains checks is actual contains substring/element expected. |
| 444 |
// |
| 445 |
// Element of array/slice/map is checked using == expected. |
| 446 |
// |
| 447 |
// Type of expected depends on type of actual: |
| 448 |
// - if actual is a string, then expected should be a string |
| 449 |
// - if actual is an array, then expected should have array's element type |
| 450 |
// - if actual is a slice, then expected should have slice's element type |
| 451 |
// - if actual is a map, then expected should have map's value type |
| 452 |
// |
| 453 |
// Hint: In a map it looks for a value, if you need to look for a key - |
| 454 |
// use HasKey instead. |
| 455 |
func (t *checks) Contains(actual, expected any, msg ...any) bool { |
| 456 |
t.tb.Helper() |
| 457 |
return t.report2(actual, expected, msg, |
| 458 |
isContains(actual, expected)) |
| 459 |
} |
| 460 |
|
| 461 |
func isContains(actual, expected any) (found bool) { |
| 462 |
switch valActual := reflect.ValueOf(actual); valActual.Kind() { //nolint:exhaustive // Covered by default case. |
| 463 |
case reflect.String: |
| 464 |
strActual := valActual.Convert(typString).Interface().(string) //nolint:forcetypeassert // False positive. |
| 465 |
valExpected := reflect.ValueOf(expected) |
| 466 |
if valExpected.Kind() != reflect.String { |
| 467 |
panic("expected underlying type is not a string") |
| 468 |
} |
| 469 |
strExpected := valExpected.Convert(typString).Interface().(string) //nolint:forcetypeassert // False positive. |
| 470 |
found = strings.Contains(strActual, strExpected) |
| 471 |
|
| 472 |
case reflect.Map: |
| 473 |
if valActual.Type().Elem() != reflect.TypeOf(expected) { |
| 474 |
panic("expected type not match actual element type") |
| 475 |
} |
| 476 |
keys := valActual.MapKeys() |
| 477 |
for i := 0; i < len(keys) && !found; i++ { |
| 478 |
found = valActual.MapIndex(keys[i]).Interface() == expected |
| 479 |
} |
| 480 |
|
| 481 |
case reflect.Slice, reflect.Array: |
| 482 |
if valActual.Type().Elem() != reflect.TypeOf(expected) { |
| 483 |
panic("expected type not match actual element type") |
| 484 |
} |
| 485 |
for i := 0; i < valActual.Len() && !found; i++ { |
| 486 |
found = valActual.Index(i).Interface() == expected |
| 487 |
} |
| 488 |
|
| 489 |
default: |
| 490 |
panic("actual is not a string, array, slice or map") |
| 491 |
} |
| 492 |
return found |
| 493 |
} |
| 494 |
|
| 495 |
// NotContains checks is actual not contains substring/element expected. |
| 496 |
// |
| 497 |
// See Contains about supported actual/expected types and check logic. |
| 498 |
func (t *checks) NotContains(actual, expected any, msg ...any) bool { |
| 499 |
t.tb.Helper() |
| 500 |
return t.report2(actual, expected, msg, |
| 501 |
!isContains(actual, expected)) |
| 502 |
} |
| 503 |
|
| 504 |
// HasKey checks is actual has key expected. |
| 505 |
func (t *checks) HasKey(actual, expected any, msg ...any) bool { |
| 506 |
t.tb.Helper() |
| 507 |
return t.report2(actual, expected, msg, |
| 508 |
hasKey(actual, expected)) |
| 509 |
} |
| 510 |
|
| 511 |
func hasKey(actual, expected any) bool { |
| 512 |
return reflect.ValueOf(actual).MapIndex(reflect.ValueOf(expected)).IsValid() |
| 513 |
} |
| 514 |
|
| 515 |
// NotHasKey checks is actual has no key expected. |
| 516 |
func (t *checks) NotHasKey(actual, expected any, msg ...any) bool { |
| 517 |
t.tb.Helper() |
| 518 |
return t.report2(actual, expected, msg, |
| 519 |
!hasKey(actual, expected)) |
| 520 |
} |
| 521 |
|
| 522 |
// Zero checks is actual is zero value of it's type. |
| 523 |
func (t *checks) Zero(actual any, msg ...any) bool { |
| 524 |
t.tb.Helper() |
| 525 |
return t.report1(actual, msg, |
| 526 |
isZero(actual)) |
| 527 |
} |
| 528 |
|
| 529 |
func isZero(actual any) bool { |
| 530 |
if isNil(actual) { |
| 531 |
return true |
| 532 |
} else if typ := reflect.TypeOf(actual); typ.Comparable() { |
| 533 |
// Not Func, Map, Slice, Array with non-comparable |
| 534 |
// elements, Struct with non-comparable fields. |
| 535 |
return actual == reflect.Zero(typ).Interface() |
| 536 |
} else if typ.Kind() == reflect.Array { |
| 537 |
zero := true |
| 538 |
val := reflect.ValueOf(actual) |
| 539 |
for i := 0; i < val.Len() && zero; i++ { |
| 540 |
zero = isZero(val.Index(i).Interface()) |
| 541 |
} |
| 542 |
return zero |
| 543 |
} |
| 544 |
// Func, Struct with non-comparable fields. |
| 545 |
// Non-nil Map, Slice. |
| 546 |
return false |
| 547 |
} |
| 548 |
|
| 549 |
// NotZero checks is actual is not zero value of it's type. |
| 550 |
func (t *checks) NotZero(actual any, msg ...any) bool { |
| 551 |
t.tb.Helper() |
| 552 |
return t.report1(actual, msg, |
| 553 |
!isZero(actual)) |
| 554 |
} |
| 555 |
|
| 556 |
// Len checks is len(actual) == expected. |
| 557 |
func (t *checks) Len(actual any, expected int, msg ...any) bool { |
| 558 |
t.tb.Helper() |
| 559 |
l := reflect.ValueOf(actual).Len() |
| 560 |
return t.report2(l, expected, msg, |
| 561 |
l == expected) |
| 562 |
} |
| 563 |
|
| 564 |
// NotLen checks is len(actual) != expected. |
| 565 |
func (t *checks) NotLen(actual any, expected int, msg ...any) bool { |
| 566 |
t.tb.Helper() |
| 567 |
l := reflect.ValueOf(actual).Len() |
| 568 |
return t.report2(l, expected, msg, |
| 569 |
l != expected) |
| 570 |
} |
| 571 |
|
| 572 |
// Err checks is actual error is the same as expected error. |
| 573 |
// |
| 574 |
// Custom error checkers registered via [RegisterErrChecker] run first. |
| 575 |
// If none claims the pair the built-in comparison operates on the |
| 576 |
// original error found by recursively unwrapping actual with |
| 577 |
// [errors.Unwrap]() and [github.com/pkg/errors.Cause]() |
| 578 |
// (multi-error takes only the first), |
| 579 |
// and then compares it using Equal() method or same type and value ([deepequal.DeepEqual]), |
| 580 |
// so they may be different instances, but must have the same type and value. |
| 581 |
// |
| 582 |
// If both of these fail the comparison falls back to [errors.Is]() |
| 583 |
// on the original actual (not the unwrapped one). |
| 584 |
// |
| 585 |
// Checking for nil is okay, but using Nil(actual) instead is more clean. |
| 586 |
func (t *checks) Err(actual, expected error, msg ...any) bool { |
| 587 |
t.tb.Helper() |
| 588 |
equal, claimed := runCheckers(actual, expected) |
| 589 |
if !claimed { |
| 590 |
actual2 := unwrapErr(actual) |
| 591 |
if hasMethod(actual2, "GRPCStatus") || hasMethod(expected, "GRPCStatus") { |
| 592 |
panic("check: gRPC status error detected; " + |
| 593 |
"import github.com/powerman/checkgrpc to compare gRPC status errors") |
| 594 |
} |
| 595 |
equal = reflect.TypeOf(actual2) == reflect.TypeOf(expected) && |
| 596 |
deepequal.DeepEqual(actual2, expected) |
| 597 |
} |
| 598 |
if !equal { |
| 599 |
equal = errors.Is(actual, expected) |
| 600 |
} |
| 601 |
return t.report2(actual, expected, msg, equal) |
| 602 |
} |
| 603 |
|
| 604 |
// cause replicates github.com/pkg/errors.Cause using duck typing, |
| 605 |
// to support that (archived) package without depending on it. |
| 606 |
func cause(err error) error { |
| 607 |
for err != nil { |
| 608 |
c, ok := err.(interface{ Cause() error }) |
| 609 |
if !ok { |
| 610 |
break |
| 611 |
} |
| 612 |
err = c.Cause() |
| 613 |
} |
| 614 |
return err |
| 615 |
} |
| 616 |
|
| 617 |
func unwrapErr(err error) (actual error) { |
| 618 |
defer func() { _ = recover() }() |
| 619 |
actual = err |
| 620 |
for { |
| 621 |
actual = cause(actual) |
| 622 |
var unwrapped error |
| 623 |
switch wrapped := actual.(type) { //nolint:errorlint // False positive. |
| 624 |
case interface{ Unwrap() error }: |
| 625 |
unwrapped = wrapped.Unwrap() |
| 626 |
case interface{ Unwrap() []error }: |
| 627 |
unwrappeds := wrapped.Unwrap() |
| 628 |
if len(unwrappeds) > 0 { |
| 629 |
unwrapped = unwrappeds[0] |
| 630 |
} |
| 631 |
} |
| 632 |
if unwrapped == nil { |
| 633 |
break |
| 634 |
} |
| 635 |
actual = unwrapped |
| 636 |
} |
| 637 |
return actual |
| 638 |
} |
| 639 |
|
| 640 |
// NotErr checks is actual error is not the same as expected error. |
| 641 |
// |
| 642 |
// It tries to recursively unwrap actual before checking using |
| 643 |
// [errors.Unwrap]() and [github.com/pkg/errors.Cause](). |
| 644 |
// In case of multi-error (Unwrap() []error) it use only first error. |
| 645 |
// |
| 646 |
// They must have either different types or values (or one should be nil). |
| 647 |
// Different instances with same type and value will be considered the |
| 648 |
// same error, and so is both nil. |
| 649 |
// |
| 650 |
// Finally it'll use ![errors.Is](). |
| 651 |
func (t *checks) NotErr(actual, expected error, msg ...any) bool { |
| 652 |
t.tb.Helper() |
| 653 |
equal, claimed := runCheckers(actual, expected) |
| 654 |
var notEqual bool |
| 655 |
if claimed { |
| 656 |
notEqual = !equal |
| 657 |
} else { |
| 658 |
actual2 := unwrapErr(actual) |
| 659 |
if hasMethod(actual2, "GRPCStatus") || hasMethod(expected, "GRPCStatus") { |
| 660 |
panic("check: gRPC status error detected; " + |
| 661 |
"import github.com/powerman/checkgrpc to compare gRPC status errors") |
| 662 |
} |
| 663 |
notEqual = reflect.TypeOf(actual2) != reflect.TypeOf(expected) || |
| 664 |
!deepequal.DeepEqual(actual2, expected) |
| 665 |
} |
| 666 |
if notEqual { |
| 667 |
notEqual = !errors.Is(actual, expected) |
| 668 |
} |
| 669 |
return t.report1(actual, msg, notEqual) |
| 670 |
} |
| 671 |
|
| 672 |
// ErrIs checks for [errors.Is](). |
| 673 |
// |
| 674 |
// Unlike Err which tries to unwrap to root cause and compare values, |
| 675 |
// ErrIs uses pure [errors.Is] semantics for exact error matching. |
| 676 |
// |
| 677 |
// See Err for value-equality checks. ErrIs is preferred when you want |
| 678 |
// the standard Go unwrapping semantics without value comparison. |
| 679 |
func (t *checks) ErrIs(actual, expected error, msg ...any) bool { |
| 680 |
t.tb.Helper() |
| 681 |
return t.report2(actual, expected, msg, |
| 682 |
errors.Is(actual, expected)) |
| 683 |
} |
| 684 |
|
| 685 |
// NotErrIs checks for ![errors.Is](). |
| 686 |
// |
| 687 |
// See ErrIs for details. Note that nil is not matched by [errors.Is] |
| 688 |
// against any non-nil error, so NotErrIs(nil, [io.EOF]) passes. |
| 689 |
func (t *checks) NotErrIs(actual, expected error, msg ...any) bool { |
| 690 |
t.tb.Helper() |
| 691 |
return t.report1(actual, msg, |
| 692 |
!errors.Is(actual, expected)) |
| 693 |
} |
| 694 |
|
| 695 |
// ErrAs checks for [errors.As]. |
| 696 |
// |
| 697 |
// target must be a non-nil pointer to an error type or to an interface, |
| 698 |
// as required by [errors.As]. On success target is filled |
| 699 |
// with the matched error value. See [errors.As] documentation for details. |
| 700 |
func (t *checks) ErrAs(actual error, target any, msg ...any) bool { |
| 701 |
t.tb.Helper() |
| 702 |
return t.report2(actual, target, msg, |
| 703 |
errors.As(actual, target)) |
| 704 |
} |
| 705 |
|
| 706 |
// NotErrAs checks for ![errors.As]. |
| 707 |
// |
| 708 |
// target must be a non-nil pointer to an error type or to an interface, |
| 709 |
// as required by [errors.As]. Note that [errors.As] may still fill target |
| 710 |
// with a matched error even when this check returns true, |
| 711 |
// because [errors.As] is always called regardless of the negated result. |
| 712 |
func (t *checks) NotErrAs(actual error, target any, msg ...any) bool { |
| 713 |
t.tb.Helper() |
| 714 |
return t.report1(actual, msg, |
| 715 |
!errors.As(actual, target)) |
| 716 |
} |
| 717 |
|
| 718 |
// Panic checks is actual() panics. |
| 719 |
// |
| 720 |
// It is able to detect panic(nil)… but you should try to avoid using this. |
| 721 |
func (t *checks) Panic(actual func(), msg ...any) bool { |
| 722 |
t.tb.Helper() |
| 723 |
didPanic := true |
| 724 |
func() { |
| 725 |
defer func() { _ = recover() }() |
| 726 |
actual() |
| 727 |
didPanic = false |
| 728 |
}() |
| 729 |
return t.report0(msg, |
| 730 |
didPanic) |
| 731 |
} |
| 732 |
|
| 733 |
// NotPanic checks is actual() don't panics. |
| 734 |
// |
| 735 |
// It is able to detect panic(nil)… but you should try to avoid using this. |
| 736 |
func (t *checks) NotPanic(actual func(), msg ...any) bool { |
| 737 |
t.tb.Helper() |
| 738 |
didPanic := true |
| 739 |
func() { |
| 740 |
defer func() { _ = recover() }() |
| 741 |
actual() |
| 742 |
didPanic = false |
| 743 |
}() |
| 744 |
return t.report0(msg, |
| 745 |
!didPanic) |
| 746 |
} |
| 747 |
|
| 748 |
// PanicMatch checks is actual() panics and panic text match regex. |
| 749 |
// |
| 750 |
// Regex type can be either [*regexp.Regexp] or string. |
| 751 |
// |
| 752 |
// In case of panic(nil) it will match like panic("<nil>"). |
| 753 |
func (t *checks) PanicMatch(actual func(), regex any, msg ...any) bool { |
| 754 |
t.tb.Helper() |
| 755 |
var panicVal any |
| 756 |
didPanic := true |
| 757 |
func() { |
| 758 |
defer func() { panicVal = recover() }() |
| 759 |
actual() |
| 760 |
didPanic = false |
| 761 |
}() |
| 762 |
if !didPanic { |
| 763 |
return t.report0(msg, |
| 764 |
false) |
| 765 |
} |
| 766 |
|
| 767 |
switch panicVal.(type) { |
| 768 |
case string, error: |
| 769 |
default: |
| 770 |
panicVal = fmt.Sprintf("%#v", panicVal) |
| 771 |
} |
| 772 |
|
| 773 |
ok := isMatch(&panicVal, regex) |
| 774 |
return t.report2(panicVal, regex, msg, |
| 775 |
ok) |
| 776 |
} |
| 777 |
|
| 778 |
// PanicNotMatch checks is actual() panics and panic text not match regex. |
| 779 |
// |
| 780 |
// Regex type can be either [*regexp.Regexp] or string. |
| 781 |
// |
| 782 |
// In case of panic(nil) it will match like panic("<nil>"). |
| 783 |
func (t *checks) PanicNotMatch(actual func(), regex any, msg ...any) bool { |
| 784 |
t.tb.Helper() |
| 785 |
var panicVal any |
| 786 |
didPanic := true |
| 787 |
func() { |
| 788 |
defer func() { panicVal = recover() }() |
| 789 |
actual() |
| 790 |
didPanic = false |
| 791 |
}() |
| 792 |
if !didPanic { |
| 793 |
return t.report0(msg, |
| 794 |
false) |
| 795 |
} |
| 796 |
|
| 797 |
switch panicVal.(type) { |
| 798 |
case string, error: |
| 799 |
default: |
| 800 |
panicVal = fmt.Sprintf("%#v", panicVal) |
| 801 |
} |
| 802 |
|
| 803 |
ok := !isMatch(&panicVal, regex) |
| 804 |
return t.report2(panicVal, regex, msg, |
| 805 |
ok) |
| 806 |
} |
| 807 |
|
| 808 |
// Less checks for actual < expected. |
| 809 |
// |
| 810 |
// Both actual and expected must be either: |
| 811 |
// - signed integers |
| 812 |
// - unsigned integers |
| 813 |
// - floats |
| 814 |
// - strings |
| 815 |
// - [time.Time] |
| 816 |
func (t *checks) Less(actual, expected any, msg ...any) bool { |
| 817 |
t.tb.Helper() |
| 818 |
return t.report2(actual, expected, msg, |
| 819 |
isLess(actual, expected)) |
| 820 |
} |
| 821 |
|
| 822 |
func isLess(actual, expected any) bool { |
| 823 |
switch v1, v2 := reflect.ValueOf(actual), reflect.ValueOf(expected); v1.Kind() { //nolint:exhaustive // Covered by default case. |
| 824 |
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 825 |
return v1.Int() < v2.Int() |
| 826 |
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: |
| 827 |
return v1.Uint() < v2.Uint() |
| 828 |
case reflect.Float32, reflect.Float64: |
| 829 |
return v1.Float() < v2.Float() |
| 830 |
case reflect.String: |
| 831 |
return v1.String() < v2.String() |
| 832 |
default: |
| 833 |
if actualTime, ok := actual.(time.Time); ok { |
| 834 |
return actualTime.Before(expected.(time.Time)) |
| 835 |
} |
| 836 |
} |
| 837 |
panic("actual is not a number, string or time.Time") |
| 838 |
} |
| 839 |
|
| 840 |
// LT is a synonym for Less. |
| 841 |
func (t *checks) LT(actual, expected any, msg ...any) bool { |
| 842 |
t.tb.Helper() |
| 843 |
return t.Less(actual, expected, msg...) |
| 844 |
} |
| 845 |
|
| 846 |
// LessOrEqual checks for actual <= expected. |
| 847 |
// |
| 848 |
// Both actual and expected must be either: |
| 849 |
// - signed integers |
| 850 |
// - unsigned integers |
| 851 |
// - floats |
| 852 |
// - strings |
| 853 |
// - [time.Time] |
| 854 |
func (t *checks) LessOrEqual(actual, expected any, msg ...any) bool { |
| 855 |
t.tb.Helper() |
| 856 |
return t.report2(actual, expected, msg, |
| 857 |
!isGreater(actual, expected)) |
| 858 |
} |
| 859 |
|
| 860 |
func isGreater(actual, expected any) bool { |
| 861 |
switch v1, v2 := reflect.ValueOf(actual), reflect.ValueOf(expected); v1.Kind() { //nolint:exhaustive // Covered by default case. |
| 862 |
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 863 |
return v1.Int() > v2.Int() |
| 864 |
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: |
| 865 |
return v1.Uint() > v2.Uint() |
| 866 |
case reflect.Float32, reflect.Float64: |
| 867 |
return v1.Float() > v2.Float() |
| 868 |
case reflect.String: |
| 869 |
return v1.String() > v2.String() |
| 870 |
default: |
| 871 |
if actualTime, ok := actual.(time.Time); ok { |
| 872 |
return actualTime.After(expected.(time.Time)) |
| 873 |
} |
| 874 |
} |
| 875 |
panic("actual is not a number, string or time.Time") |
| 876 |
} |
| 877 |
|
| 878 |
// LE is a synonym for LessOrEqual. |
| 879 |
func (t *checks) LE(actual, expected any, msg ...any) bool { |
| 880 |
t.tb.Helper() |
| 881 |
return t.LessOrEqual(actual, expected, msg...) |
| 882 |
} |
| 883 |
|
| 884 |
// Greater checks for actual > expected. |
| 885 |
// |
| 886 |
// Both actual and expected must be either: |
| 887 |
// - signed integers |
| 888 |
// - unsigned integers |
| 889 |
// - floats |
| 890 |
// - strings |
| 891 |
// - [time.Time] |
| 892 |
func (t *checks) Greater(actual, expected any, msg ...any) bool { |
| 893 |
t.tb.Helper() |
| 894 |
return t.report2(actual, expected, msg, |
| 895 |
isGreater(actual, expected)) |
| 896 |
} |
| 897 |
|
| 898 |
// GT is a synonym for Greater. |
| 899 |
func (t *checks) GT(actual, expected any, msg ...any) bool { |
| 900 |
t.tb.Helper() |
| 901 |
return t.Greater(actual, expected, msg...) |
| 902 |
} |
| 903 |
|
| 904 |
// GreaterOrEqual checks for actual >= expected. |
| 905 |
// |
| 906 |
// Both actual and expected must be either: |
| 907 |
// - signed integers |
| 908 |
// - unsigned integers |
| 909 |
// - floats |
| 910 |
// - strings |
| 911 |
// - [time.Time] |
| 912 |
func (t *checks) GreaterOrEqual(actual, expected any, msg ...any) bool { |
| 913 |
t.tb.Helper() |
| 914 |
return t.report2(actual, expected, msg, |
| 915 |
!isLess(actual, expected)) |
| 916 |
} |
| 917 |
|
| 918 |
// GE is a synonym for GreaterOrEqual. |
| 919 |
func (t *checks) GE(actual, expected any, msg ...any) bool { |
| 920 |
t.tb.Helper() |
| 921 |
return t.GreaterOrEqual(actual, expected, msg...) |
| 922 |
} |
| 923 |
|
| 924 |
// Between checks for min < actual < max. |
| 925 |
// |
| 926 |
// All three actual, min and max must be either: |
| 927 |
// - signed integers |
| 928 |
// - unsigned integers |
| 929 |
// - floats |
| 930 |
// - strings |
| 931 |
// - [time.Time] |
| 932 |
func (t *checks) Between(actual, minimum, maximum any, msg ...any) bool { |
| 933 |
t.tb.Helper() |
| 934 |
return t.report3(actual, minimum, maximum, msg, |
| 935 |
isBetween(actual, minimum, maximum)) |
| 936 |
} |
| 937 |
|
| 938 |
func isBetween(actual, minimum, maximum any) bool { |
| 939 |
switch v, vmin, vmax := reflect.ValueOf(actual), reflect.ValueOf(minimum), reflect.ValueOf(maximum); v.Kind() { //nolint:exhaustive // Covered by default case. |
| 940 |
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 941 |
return vmin.Int() < v.Int() && v.Int() < vmax.Int() |
| 942 |
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: |
| 943 |
return vmin.Uint() < v.Uint() && v.Uint() < vmax.Uint() |
| 944 |
case reflect.Float32, reflect.Float64: |
| 945 |
return vmin.Float() < v.Float() && v.Float() < vmax.Float() |
| 946 |
case reflect.String: |
| 947 |
return vmin.String() < v.String() && v.String() < vmax.String() |
| 948 |
default: |
| 949 |
if actualTime, ok := actual.(time.Time); ok { |
| 950 |
minTime := minimum.(time.Time) //nolint:forcetypeassert // Want panic. |
| 951 |
maxTime := maximum.(time.Time) //nolint:forcetypeassert // Want panic. |
| 952 |
return minTime.Before(actualTime) && actualTime.Before(maxTime) |
| 953 |
} |
| 954 |
} |
| 955 |
panic("actual is not a number, string or time.Time") |
| 956 |
} |
| 957 |
|
| 958 |
// NotBetween checks for actual <= min or max <= actual. |
| 959 |
// |
| 960 |
// All three actual, min and max must be either: |
| 961 |
// - signed integers |
| 962 |
// - unsigned integers |
| 963 |
// - floats |
| 964 |
// - strings |
| 965 |
// - [time.Time] |
| 966 |
func (t *checks) NotBetween(actual, minimum, maximum any, msg ...any) bool { |
| 967 |
t.tb.Helper() |
| 968 |
return t.report3(actual, minimum, maximum, msg, |
| 969 |
!isBetween(actual, minimum, maximum)) |
| 970 |
} |
| 971 |
|
| 972 |
// BetweenOrEqual checks for min <= actual <= max. |
| 973 |
// |
| 974 |
// All three actual, min and max must be either: |
| 975 |
// - signed integers |
| 976 |
// - unsigned integers |
| 977 |
// - floats |
| 978 |
// - strings |
| 979 |
// - [time.Time] |
| 980 |
func (t *checks) BetweenOrEqual(actual, minimum, maximum any, msg ...any) bool { |
| 981 |
t.tb.Helper() |
| 982 |
return t.report3(actual, minimum, maximum, msg, |
| 983 |
isBetween(actual, minimum, maximum) || isEqual(actual, minimum) || isEqual(actual, maximum)) |
| 984 |
} |
| 985 |
|
| 986 |
// NotBetweenOrEqual checks for actual < min or max < actual. |
| 987 |
// |
| 988 |
// All three actual, min and max must be either: |
| 989 |
// - signed integers |
| 990 |
// - unsigned integers |
| 991 |
// - floats |
| 992 |
// - strings |
| 993 |
// - [time.Time] |
| 994 |
func (t *checks) NotBetweenOrEqual(actual, minimum, maximum any, msg ...any) bool { |
| 995 |
t.tb.Helper() |
| 996 |
return t.report3(actual, minimum, maximum, msg, |
| 997 |
!isBetween(actual, minimum, maximum) && !isEqual(actual, minimum) && !isEqual(actual, maximum)) |
| 998 |
} |
| 999 |
|
| 1000 |
// InDelta checks for expected-delta <= actual <= expected+delta. |
| 1001 |
// |
| 1002 |
// All three actual, expected and delta must be either: |
| 1003 |
// - signed integers |
| 1004 |
// - unsigned integers |
| 1005 |
// - floats |
| 1006 |
// - [time.Time] (in this case delta must be [time.Duration]) |
| 1007 |
func (t *checks) InDelta(actual, expected, delta any, msg ...any) bool { |
| 1008 |
t.tb.Helper() |
| 1009 |
return t.report3(actual, expected, delta, msg, |
| 1010 |
isInDelta(actual, expected, delta)) |
| 1011 |
} |
| 1012 |
|
| 1013 |
func isInDelta(actual, expected, delta any) bool { |
| 1014 |
switch v, e, d := reflect.ValueOf(actual), reflect.ValueOf(expected), reflect.ValueOf(delta); v.Kind() { //nolint:exhaustive // Covered by default case. |
| 1015 |
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 1016 |
dd := d.Int() |
| 1017 |
if dd < 0 { |
| 1018 |
return false // negative delta: preserve old always-false behavior |
| 1019 |
} |
| 1020 |
a, e2 := v.Int(), e.Int() |
| 1021 |
var diff uint64 // |a-e2| computed without overflow via two's complement |
| 1022 |
if a >= e2 { |
| 1023 |
diff = uint64(a) - uint64(e2) //nolint:gosec // Two's complement: exact even when a-e2 overflows int64. |
| 1024 |
} else { |
| 1025 |
diff = uint64(e2) - uint64(a) //nolint:gosec // Two's complement: exact even when e2-a overflows int64. |
| 1026 |
} |
| 1027 |
return diff <= uint64(dd) |
| 1028 |
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: |
| 1029 |
a, e2, dd := v.Uint(), e.Uint(), d.Uint() |
| 1030 |
var diff uint64 |
| 1031 |
if a >= e2 { |
| 1032 |
diff = a - e2 |
| 1033 |
} else { |
| 1034 |
diff = e2 - a |
| 1035 |
} |
| 1036 |
return diff <= dd |
| 1037 |
case reflect.Float32, reflect.Float64: |
| 1038 |
minimum, maximum := e.Float()-d.Float(), e.Float()+d.Float() |
| 1039 |
return minimum <= v.Float() && v.Float() <= maximum |
| 1040 |
default: |
| 1041 |
if actualTime, ok := actual.(time.Time); ok { |
| 1042 |
expectedTime := expected.(time.Time) //nolint:forcetypeassert // Want panic. |
| 1043 |
dur := delta.(time.Duration) //nolint:forcetypeassert // Want panic. |
| 1044 |
minTime, maxTime := expectedTime.Add(-dur), expectedTime.Add(dur) |
| 1045 |
return minTime.Before(actualTime) && actualTime.Before(maxTime) || |
| 1046 |
actualTime.Equal(minTime) || |
| 1047 |
actualTime.Equal(maxTime) |
| 1048 |
} |
| 1049 |
} |
| 1050 |
panic("actual is not a number or time.Time") |
| 1051 |
} |
| 1052 |
|
| 1053 |
// NotInDelta checks for actual < expected-delta or expected+delta < actual. |
| 1054 |
// |
| 1055 |
// All three actual, expected and delta must be either: |
| 1056 |
// - signed integers |
| 1057 |
// - unsigned integers |
| 1058 |
// - floats |
| 1059 |
// - [time.Time] (in this case delta must be [time.Duration]) |
| 1060 |
func (t *checks) NotInDelta(actual, expected, delta any, msg ...any) bool { |
| 1061 |
t.tb.Helper() |
| 1062 |
return t.report3(actual, expected, delta, msg, |
| 1063 |
!isInDelta(actual, expected, delta)) |
| 1064 |
} |
| 1065 |
|
| 1066 |
// InSMAPE checks that actual and expected have a symmetric mean absolute |
| 1067 |
// percentage error (SMAPE) is less than given smape. |
| 1068 |
// |
| 1069 |
// Both actual and expected must be either: |
| 1070 |
// - signed integers |
| 1071 |
// - unsigned integers |
| 1072 |
// - floats |
| 1073 |
// |
| 1074 |
// Allowed smape values are: 0.0 < smape < 100.0. |
| 1075 |
// |
| 1076 |
// Used formula returns SMAPE value between 0 and 100 (percents): |
| 1077 |
// - 0.0 when actual == expected |
| 1078 |
// - ~0.5 when they differs in ~1% |
| 1079 |
// - ~5 when they differs in ~10% |
| 1080 |
// - ~20 when they differs in 1.5 times |
| 1081 |
// - ~33 when they differs in 2 times |
| 1082 |
// - 50.0 when they differs in 3 times |
| 1083 |
// - ~82 when they differs in 10 times |
| 1084 |
// - 99.0+ when actual and expected differs in 200+ times |
| 1085 |
// - 100.0 when only one of actual or expected is 0 or one of them is |
| 1086 |
// positive while another is negative |
| 1087 |
func (t *checks) InSMAPE(actual, expected any, smape float64, msg ...any) bool { |
| 1088 |
t.tb.Helper() |
| 1089 |
return t.report3(actual, expected, smape, msg, |
| 1090 |
isInSMAPE(actual, expected, smape)) |
| 1091 |
} |
| 1092 |
|
| 1093 |
func isInSMAPE(actual, expected any, smape float64) bool { |
| 1094 |
if !(0 < smape && smape < 100) { |
| 1095 |
panic("smape is not in allowed range: 0 < smape < 100") |
| 1096 |
} |
| 1097 |
a := reflect.ValueOf(actual).Convert(typFloat64).Float() |
| 1098 |
e := reflect.ValueOf(expected).Convert(typFloat64).Float() |
| 1099 |
if a == 0 && e == 0 { |
| 1100 |
return true // avoid division by zero in legal use case |
| 1101 |
} |
| 1102 |
return 100*math.Abs(e-a)/(math.Abs(e)+math.Abs(a)) < smape |
| 1103 |
} |
| 1104 |
|
| 1105 |
// NotInSMAPE checks that actual and expected have a symmetric mean |
| 1106 |
// absolute percentage error (SMAPE) is greater than or equal to given |
| 1107 |
// smape. |
| 1108 |
// |
| 1109 |
// See InSMAPE about supported actual/expected types and check logic. |
| 1110 |
func (t *checks) NotInSMAPE(actual, expected any, smape float64, msg ...any) bool { |
| 1111 |
t.tb.Helper() |
| 1112 |
return t.report3(actual, expected, smape, msg, |
| 1113 |
!isInSMAPE(actual, expected, smape)) |
| 1114 |
} |
| 1115 |
|
| 1116 |
// HasPrefix checks for [strings.HasPrefix](actual, expected). |
| 1117 |
// |
| 1118 |
// Both actual and expected may have any of these types: |
| 1119 |
// - string - will use as is |
| 1120 |
// - []byte - will convert with string() |
| 1121 |
// - []rune - will convert with string() |
| 1122 |
// - [fmt.Stringer] - will convert with actual.String() |
| 1123 |
// - error - will convert with actual.Error() |
| 1124 |
// - nil - check will always fail |
| 1125 |
func (t *checks) HasPrefix(actual, expected any, msg ...any) bool { |
| 1126 |
t.tb.Helper() |
| 1127 |
ok := isHasPrefix(&actual, &expected) |
| 1128 |
return t.report2(actual, expected, msg, |
| 1129 |
ok) |
| 1130 |
} |
| 1131 |
|
| 1132 |
// isHasPrefix updates actual and expected to be a real string used for check, |
| 1133 |
// to make dump easier to understand, but this result in losing type information. |
| 1134 |
func isHasPrefix(actual, expected *any) bool { |
| 1135 |
if *actual == nil || *expected == nil { |
| 1136 |
return false |
| 1137 |
} |
| 1138 |
if !stringify(actual) { |
| 1139 |
panic("actual is not a string, []byte, []rune, fmt.Stringer, error or nil") |
| 1140 |
} |
| 1141 |
if !stringify(expected) { |
| 1142 |
panic("expected is not a string, []byte, []rune, fmt.Stringer, error or nil") |
| 1143 |
} |
| 1144 |
return strings.HasPrefix((*actual).(string), (*expected).(string)) |
| 1145 |
} |
| 1146 |
|
| 1147 |
// NotHasPrefix checks for !strings.HasPrefix(actual, expected). |
| 1148 |
// |
| 1149 |
// See HasPrefix about supported actual/expected types and check logic. |
| 1150 |
func (t *checks) NotHasPrefix(actual, expected any, msg ...any) bool { |
| 1151 |
t.tb.Helper() |
| 1152 |
ok := !isHasPrefix(&actual, &expected) |
| 1153 |
return t.report2(actual, expected, msg, |
| 1154 |
ok) |
| 1155 |
} |
| 1156 |
|
| 1157 |
// HasSuffix checks for [strings.HasSuffix](actual, expected). |
| 1158 |
// |
| 1159 |
// Both actual and expected may have any of these types: |
| 1160 |
// - string - will use as is |
| 1161 |
// - []byte - will convert with string() |
| 1162 |
// - []rune - will convert with string() |
| 1163 |
// - [fmt.Stringer] - will convert with actual.String() |
| 1164 |
// - error - will convert with actual.Error() |
| 1165 |
// - nil - check will always fail |
| 1166 |
func (t *checks) HasSuffix(actual, expected any, msg ...any) bool { |
| 1167 |
t.tb.Helper() |
| 1168 |
ok := isHasSuffix(&actual, &expected) |
| 1169 |
return t.report2(actual, expected, msg, |
| 1170 |
ok) |
| 1171 |
} |
| 1172 |
|
| 1173 |
// isHasSuffix updates actual and expected to be a real string used for check, |
| 1174 |
// to make dump easier to understand, but this result in losing type information. |
| 1175 |
func isHasSuffix(actual, expected *any) bool { |
| 1176 |
if *actual == nil || *expected == nil { |
| 1177 |
return false |
| 1178 |
} |
| 1179 |
if !stringify(actual) { |
| 1180 |
panic("actual is not a string, []byte, []rune, fmt.Stringer, error or nil") |
| 1181 |
} |
| 1182 |
if !stringify(expected) { |
| 1183 |
panic("expected is not a string, []byte, []rune, fmt.Stringer, error or nil") |
| 1184 |
} |
| 1185 |
return strings.HasSuffix((*actual).(string), (*expected).(string)) |
| 1186 |
} |
| 1187 |
|
| 1188 |
// NotHasSuffix checks for !strings.HasSuffix(actual, expected). |
| 1189 |
// |
| 1190 |
// See HasSuffix about supported actual/expected types and check logic. |
| 1191 |
func (t *checks) NotHasSuffix(actual, expected any, msg ...any) bool { |
| 1192 |
t.tb.Helper() |
| 1193 |
ok := !isHasSuffix(&actual, &expected) |
| 1194 |
return t.report2(actual, expected, msg, |
| 1195 |
ok) |
| 1196 |
} |
| 1197 |
|
| 1198 |
// JSONEqual normalize formatting of actual and expected (if they're valid |
| 1199 |
// JSON) and then checks for [bytes.Equal](actual, expected). |
| 1200 |
// |
| 1201 |
// Both actual and expected may have any of these types: |
| 1202 |
// - string |
| 1203 |
// - []byte |
| 1204 |
// - [json.RawMessage] |
| 1205 |
// - [*json.RawMessage] |
| 1206 |
// - nil |
| 1207 |
// |
| 1208 |
// In case any of actual or expected is nil or empty or (for string or |
| 1209 |
// []byte) is invalid JSON - check will fail. |
| 1210 |
func (t *checks) JSONEqual(actual, expected any, msg ...any) bool { |
| 1211 |
t.tb.Helper() |
| 1212 |
ok := isJSONEqual(actual, expected) |
| 1213 |
if !ok { |
| 1214 |
if buf := jsonify(actual); len(buf) != 0 { |
| 1215 |
actual = buf |
| 1216 |
} |
| 1217 |
if buf := jsonify(expected); len(buf) != 0 { |
| 1218 |
expected = buf |
| 1219 |
} |
| 1220 |
} |
| 1221 |
return t.report2(actual, expected, msg, |
| 1222 |
ok) |
| 1223 |
} |
| 1224 |
|
| 1225 |
func isJSONEqual(actual, expected any) bool { |
| 1226 |
jsonActual, jsonExpected := jsonify(actual), jsonify(expected) |
| 1227 |
return len(jsonActual) != 0 && len(jsonExpected) != 0 && |
| 1228 |
bytes.Equal(jsonActual, jsonExpected) |
| 1229 |
} |
| 1230 |
|
| 1231 |
func jsonify(arg any) json.RawMessage { |
| 1232 |
switch v := arg.(type) { |
| 1233 |
case nil: |
| 1234 |
return nil |
| 1235 |
case json.RawMessage: |
| 1236 |
return v |
| 1237 |
case *json.RawMessage: |
| 1238 |
if v == nil { |
| 1239 |
return nil |
| 1240 |
} |
| 1241 |
return *v |
| 1242 |
} |
| 1243 |
buf := reflect.ValueOf(arg).Convert(typBytes).Interface().([]byte) //nolint:forcetypeassert // Want panic. |
| 1244 |
|
| 1245 |
var v any |
| 1246 |
err := json.Unmarshal(buf, &v) |
| 1247 |
if err != nil { |
| 1248 |
return nil |
| 1249 |
} |
| 1250 |
buf, err = json.Marshal(v) |
| 1251 |
if err != nil { |
| 1252 |
return nil |
| 1253 |
} |
| 1254 |
return buf |
| 1255 |
} |
| 1256 |
|
| 1257 |
// HasType checks is actual has same type as expected. |
| 1258 |
func (t *checks) HasType(actual, expected any, msg ...any) bool { |
| 1259 |
t.tb.Helper() |
| 1260 |
return t.report2(actual, expected, msg, |
| 1261 |
reflect.TypeOf(actual) == reflect.TypeOf(expected)) |
| 1262 |
} |
| 1263 |
|
| 1264 |
// NotHasType checks is actual has not same type as expected. |
| 1265 |
func (t *checks) NotHasType(actual, expected any, msg ...any) bool { |
| 1266 |
t.tb.Helper() |
| 1267 |
return t.report2(actual, expected, msg, |
| 1268 |
reflect.TypeOf(actual) != reflect.TypeOf(expected)) |
| 1269 |
} |
| 1270 |
|
| 1271 |
// Implements checks is actual implements interface pointed by expected. |
| 1272 |
// |
| 1273 |
// You must use pointer to interface type in expected: |
| 1274 |
// |
| 1275 |
// t.Implements(os.Stdin, (*io.Reader)(nil)) |
| 1276 |
func (t *checks) Implements(actual, expected any, msg ...any) bool { |
| 1277 |
t.tb.Helper() |
| 1278 |
return t.report2(actual, expected, msg, |
| 1279 |
isImplements(actual, expected)) |
| 1280 |
} |
| 1281 |
|
| 1282 |
func isImplements(actual, expected any) bool { |
| 1283 |
typActual := reflect.TypeOf(actual) |
| 1284 |
if typActual.Kind() != reflect.Pointer { |
| 1285 |
typActual = reflect.PointerTo(typActual) |
| 1286 |
} |
| 1287 |
return typActual.Implements(reflect.TypeOf(expected).Elem()) |
| 1288 |
} |
| 1289 |
|
| 1290 |
// NotImplements checks is actual does not implements interface pointed by expected. |
| 1291 |
// |
| 1292 |
// You must use pointer to interface type in expected: |
| 1293 |
// |
| 1294 |
// t.NotImplements(os.Stdin, (*fmt.Stringer)(nil)) |
| 1295 |
func (t *checks) NotImplements(actual, expected any, msg ...any) bool { |
| 1296 |
t.tb.Helper() |
| 1297 |
return t.report2(actual, expected, msg, |
| 1298 |
!isImplements(actual, expected)) |
| 1299 |
} |
| 1300 |
|
| 1301 |
// SortEqual checks that actual and expected contain the same elements, |
| 1302 |
// ignoring order (multiset equality, duplicates counted). |
| 1303 |
// |
| 1304 |
// Both actual and expected must be slices or arrays. |
| 1305 |
// Elements need not be sortable and are compared like DeepEqual. |
| 1306 |
// Nil and empty slices are equal (like BytesEqual, unlike DeepEqual). |
| 1307 |
func (t *checks) SortEqual(actual, expected any, msg ...any) bool { |
| 1308 |
t.tb.Helper() |
| 1309 |
return t.report2(actual, expected, msg, |
| 1310 |
isSortEqual(actual, expected)) |
| 1311 |
} |
| 1312 |
|
| 1313 |
// NotSortEqual checks !SortEqual(actual, expected). |
| 1314 |
// |
| 1315 |
// See SortEqual about supported actual/expected types and check logic. |
| 1316 |
func (t *checks) NotSortEqual(actual, expected any, msg ...any) bool { |
| 1317 |
t.tb.Helper() |
| 1318 |
return t.report1(actual, msg, |
| 1319 |
!isSortEqual(actual, expected)) |
| 1320 |
} |
| 1321 |
|
| 1322 |
func isSortEqual(actual, expected any) bool { |
| 1323 |
va, ve := reflect.ValueOf(actual), reflect.ValueOf(expected) |
| 1324 |
if va.Kind() != reflect.Slice && va.Kind() != reflect.Array { |
| 1325 |
panic("actual is not a slice or array") |
| 1326 |
} |
| 1327 |
if ve.Kind() != reflect.Slice && ve.Kind() != reflect.Array { |
| 1328 |
panic("expected is not a slice or array") |
| 1329 |
} |
| 1330 |
if va.Len() != ve.Len() { |
| 1331 |
return false |
| 1332 |
} |
| 1333 |
return isMultisetIn(va, ve) |
| 1334 |
} |
| 1335 |
|
| 1336 |
// isMultisetIn reports whether every element of small has a distinct, |
| 1337 |
// not-yet-used matching element in big, i.e. small is a multiset-subset of big. |
| 1338 |
func isMultisetIn(small, big reflect.Value) bool { |
| 1339 |
used := make([]bool, big.Len()) |
| 1340 |
for i := range small.Len() { |
| 1341 |
found := false |
| 1342 |
for j := range big.Len() { |
| 1343 |
if !used[j] && elemEqual(small.Index(i).Interface(), big.Index(j).Interface()) { |
| 1344 |
used[j], found = true, true |
| 1345 |
break |
| 1346 |
} |
| 1347 |
} |
| 1348 |
if !found { |
| 1349 |
return false |
| 1350 |
} |
| 1351 |
} |
| 1352 |
return true |
| 1353 |
} |
| 1354 |
|
| 1355 |
// Subset checks that actual contains all elements of expected: |
| 1356 |
// for slices/arrays - as multisets (duplicates counted), ignoring order; |
| 1357 |
// for maps - every key of expected exists in actual with an equal value. |
| 1358 |
// |
| 1359 |
// actual and expected must both be slices/arrays or both be maps. |
| 1360 |
// Elements/values are compared like DeepEqual. |
| 1361 |
// An empty/nil expected is a subset of anything of the same kind. |
| 1362 |
// |
| 1363 |
// Note: unlike testify's Subset, duplicates are counted, so [1,1] is not a subset of [1]. |
| 1364 |
func (t *checks) Subset(actual, expected any, msg ...any) bool { |
| 1365 |
t.tb.Helper() |
| 1366 |
return t.report2(actual, expected, msg, |
| 1367 |
isSubset(actual, expected)) |
| 1368 |
} |
| 1369 |
|
| 1370 |
// NotSubset checks !Subset(actual, expected). |
| 1371 |
// |
| 1372 |
// See Subset about supported actual/expected types and check logic. |
| 1373 |
func (t *checks) NotSubset(actual, expected any, msg ...any) bool { |
| 1374 |
t.tb.Helper() |
| 1375 |
return t.report1(actual, msg, |
| 1376 |
!isSubset(actual, expected)) |
| 1377 |
} |
| 1378 |
|
| 1379 |
func isSubset(actual, expected any) bool { |
| 1380 |
va, ve := reflect.ValueOf(actual), reflect.ValueOf(expected) |
| 1381 |
switch ve.Kind() { //nolint:exhaustive // Covered by default case. |
| 1382 |
case reflect.Map: |
| 1383 |
if va.Kind() != reflect.Map { |
| 1384 |
panic("actual is not a map") |
| 1385 |
} |
| 1386 |
return isMapSubset(va, ve) |
| 1387 |
case reflect.Slice, reflect.Array: |
| 1388 |
if va.Kind() != reflect.Slice && va.Kind() != reflect.Array { |
| 1389 |
panic("actual is not a slice or array") |
| 1390 |
} |
| 1391 |
return isMultisetIn(ve, va) |
| 1392 |
default: |
| 1393 |
panic("expected is not a slice, array or map") |
| 1394 |
} |
| 1395 |
} |
| 1396 |
|
| 1397 |
func isMapSubset(actual, expected reflect.Value) bool { |
| 1398 |
iter := expected.MapRange() |
| 1399 |
for iter.Next() { |
| 1400 |
v := actual.MapIndex(iter.Key()) |
| 1401 |
if !v.IsValid() || !elemEqual(v.Interface(), iter.Value().Interface()) { |
| 1402 |
return false |
| 1403 |
} |
| 1404 |
} |
| 1405 |
return true |
| 1406 |
} |
| 1407 |
|
| 1408 |
// FileExists checks that path exists and is not a directory. |
| 1409 |
// |
| 1410 |
// A Stat error other than "not exists" (e.g. permission denied) |
| 1411 |
// counts as "does not exist", same as testify. |
| 1412 |
func (t *checks) FileExists(path string, msg ...any) bool { |
| 1413 |
t.tb.Helper() |
| 1414 |
fi, err := os.Stat(path) |
| 1415 |
return t.report1(path, msg, |
| 1416 |
err == nil && !fi.IsDir()) |
| 1417 |
} |
| 1418 |
|
| 1419 |
// NotFileExists checks that path does not exist or is a directory. |
| 1420 |
// |
| 1421 |
// See FileExists about Stat error handling. |
| 1422 |
func (t *checks) NotFileExists(path string, msg ...any) bool { |
| 1423 |
t.tb.Helper() |
| 1424 |
fi, err := os.Stat(path) |
| 1425 |
return t.report1(path, msg, |
| 1426 |
err != nil || fi.IsDir()) |
| 1427 |
} |
| 1428 |
|
| 1429 |
// DirExists checks that path exists and is a directory. |
| 1430 |
// |
| 1431 |
// See FileExists about Stat error handling. |
| 1432 |
func (t *checks) DirExists(path string, msg ...any) bool { |
| 1433 |
t.tb.Helper() |
| 1434 |
fi, err := os.Stat(path) |
| 1435 |
return t.report1(path, msg, |
| 1436 |
err == nil && fi.IsDir()) |
| 1437 |
} |
| 1438 |
|
| 1439 |
// NotDirExists checks that path does not exist or is not a directory. |
| 1440 |
// |
| 1441 |
// See FileExists about Stat error handling. |
| 1442 |
func (t *checks) NotDirExists(path string, msg ...any) bool { |
| 1443 |
t.tb.Helper() |
| 1444 |
fi, err := os.Stat(path) |
| 1445 |
return t.report1(path, msg, |
| 1446 |
err != nil || !fi.IsDir()) |
| 1447 |
} |