Skip to content

Instantly share code, notes, and snippets.

@byrnedo
Created January 29, 2020 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save byrnedo/f9ef7bed4761ac63bcfb9987127c47bb to your computer and use it in GitHub Desktop.
Save byrnedo/f9ef7bed4761ac63bcfb9987127c47bb to your computer and use it in GitHub Desktop.
Small assertion helper for testing in go
package tutils
import (
"path"
"reflect"
"runtime"
"testing"
)
func AssertNotNil(t *testing.T, obj interface{}) {
pc, file, line, _ := runtime.Caller(1)
f := runtime.FuncForPC(pc)
if asNil(obj) {
t.Fatalf("%s:%d: %s\n%s was nil", path.Base(file), line, path.Base(f.Name()), obj)
}
}
func asNil(obj interface{}) bool {
return obj == nil || (reflect.ValueOf(obj).Kind() == reflect.Ptr && reflect.ValueOf(obj).IsNil())
}
func AssertNil(t *testing.T, obj interface{}) {
pc, file, line, _ := runtime.Caller(1)
f := runtime.FuncForPC(pc)
if !asNil(obj) {
t.Fatalf("%s:%d: %s\nexpected nil, got %s", path.Base(file), line, path.Base(f.Name()), obj)
}
}
func AssertEqual(t *testing.T, a interface{}, b interface{}) {
if reflect.DeepEqual(a, b) == false {
pc, file, line, _ := runtime.Caller(1)
f := runtime.FuncForPC(pc)
t.Fatalf("%s:%d: %s\n%+v\n not equal to\n%+v", path.Base(file), line, path.Base(f.Name()), a, b)
}
}
func AssertNotEqual(t *testing.T, a interface{}, b interface{}) {
if reflect.DeepEqual(a, b) == true {
pc, file, line, _ := runtime.Caller(1)
f := runtime.FuncForPC(pc)
t.Fatalf("%s:%d: %s\n%+v\n equal to\n%+v", path.Base(file), line, path.Base(f.Name()), a, b)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment