assert.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package assert
  2. // Testing helpers for doozer.
  3. import (
  4. "github.com/kr/pretty"
  5. "reflect"
  6. "testing"
  7. "runtime"
  8. "fmt"
  9. )
  10. func assert(t *testing.T, result bool, f func(), cd int) {
  11. if !result {
  12. _, file, line, _ := runtime.Caller(cd + 1)
  13. t.Errorf("%s:%d", file, line)
  14. f()
  15. t.FailNow()
  16. }
  17. }
  18. func equal(t *testing.T, exp, got interface{}, cd int, args ...interface{}) {
  19. fn := func() {
  20. for _, desc := range pretty.Diff(exp, got) {
  21. t.Error("!", desc)
  22. }
  23. if len(args) > 0 {
  24. t.Error("!", " -", fmt.Sprint(args...))
  25. }
  26. }
  27. result := reflect.DeepEqual(exp, got)
  28. assert(t, result, fn, cd+1)
  29. }
  30. func tt(t *testing.T, result bool, cd int, args ...interface{}) {
  31. fn := func() {
  32. t.Errorf("! Failure")
  33. if len(args) > 0 {
  34. t.Error("!", " -", fmt.Sprint(args...))
  35. }
  36. }
  37. assert(t, result, fn, cd+1)
  38. }
  39. func T(t *testing.T, result bool, args ...interface{}) {
  40. tt(t, result, 1, args...)
  41. }
  42. func Tf(t *testing.T, result bool, format string, args ...interface{}) {
  43. tt(t, result, 1, fmt.Sprintf(format, args...))
  44. }
  45. func Equal(t *testing.T, exp, got interface{}, args ...interface{}) {
  46. equal(t, exp, got, 1, args...)
  47. }
  48. func Equalf(t *testing.T, exp, got interface{}, format string, args ...interface{}) {
  49. equal(t, exp, got, 1, fmt.Sprintf(format, args...))
  50. }
  51. func NotEqual(t *testing.T, exp, got interface{}, args ...interface{}) {
  52. fn := func() {
  53. t.Errorf("! Unexpected: <%#v>", exp)
  54. if len(args) > 0 {
  55. t.Error("!", " -", fmt.Sprint(args...))
  56. }
  57. }
  58. result := !reflect.DeepEqual(exp, got)
  59. assert(t, result, fn, 1)
  60. }
  61. func Panic(t *testing.T, err interface{}, fn func()) {
  62. defer func() {
  63. equal(t, err, recover(), 3)
  64. }()
  65. fn()
  66. }