Created
January 29, 2020 10:09
-
-
Save byrnedo/f9ef7bed4761ac63bcfb9987127c47bb to your computer and use it in GitHub Desktop.
Small assertion helper for testing in go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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