Jamie Hannaford | 2aaf1a6 | 2014-10-16 12:55:50 +0200 | [diff] [blame^] | 1 | package testhelper |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "path/filepath" |
| 6 | "reflect" |
| 7 | "runtime" |
| 8 | "testing" |
| 9 | ) |
| 10 | |
| 11 | func prefix() string { |
| 12 | _, file, line, _ := runtime.Caller(3) |
| 13 | return fmt.Sprintf("Failure in %s, line %d:", filepath.Base(file), line) |
| 14 | } |
| 15 | |
| 16 | func green(str interface{}) string { |
| 17 | return fmt.Sprintf("\033[0m\033[1;32m%#v\033[0m\033[1;31m", str) |
| 18 | } |
| 19 | |
| 20 | func yellow(str interface{}) string { |
| 21 | return fmt.Sprintf("\033[0m\033[1;33m%#v\033[0m\033[1;31m", str) |
| 22 | } |
| 23 | |
| 24 | func logFatal(t *testing.T, str string) { |
| 25 | t.Fatalf("\033[1;31m%s %s\033[0m", prefix(), str) |
| 26 | } |
| 27 | |
| 28 | func logError(t *testing.T, str string) { |
| 29 | t.Errorf("\033[1;31m%s %s\033[0m", prefix(), str) |
| 30 | } |
| 31 | |
| 32 | // AssertEquals compares two arbitrary values and performs a comparison. If the |
| 33 | // comparison fails, a fatal error is raised that will fail the test |
| 34 | func AssertEquals(t *testing.T, expected, actual interface{}) { |
| 35 | if expected != actual { |
| 36 | logFatal(t, fmt.Sprintf("expected %s but got %s", green(expected), yellow(actual))) |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | // CheckEquals is similar to AssertEquals, except with a non-fatal error |
| 41 | func CheckEquals(t *testing.T, expected, actual interface{}) { |
| 42 | if expected != actual { |
| 43 | logError(t, fmt.Sprintf("expected %s but got %s", green(expected), yellow(actual))) |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | // AssertDeepEquals - like Equals - performs a comparison - but on more complex |
| 48 | // structures that requires deeper inspection |
| 49 | func AssertDeepEquals(t *testing.T, expected, actual interface{}) { |
| 50 | if !reflect.DeepEqual(expected, actual) { |
| 51 | logFatal(t, fmt.Sprintf("expected %s but got %s", green(expected), yellow(actual))) |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | // CheckDeepEquals is similar to AssertDeepEquals, except with a non-fatal error |
| 56 | func CheckDeepEquals(t *testing.T, expected, actual interface{}) { |
| 57 | if !reflect.DeepEqual(expected, actual) { |
| 58 | logError(t, fmt.Sprintf("expected %s but got %s", green(expected), yellow(actual))) |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | // AssertNoErr is a convenience function for checking whether an error value is |
| 63 | // an actual error |
| 64 | func AssertNoErr(t *testing.T, e error) { |
| 65 | if e != nil { |
| 66 | logFatal(t, fmt.Sprintf("unexpected error %s", yellow(e.Error()))) |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | // CheckNoErr is similar to AssertNoErr, except with a non-fatal error |
| 71 | func CheckNoErr(t *testing.T, e error) { |
| 72 | if e != nil { |
| 73 | logError(t, fmt.Sprintf("unexpected error %s", yellow(e.Error()))) |
| 74 | } |
| 75 | } |