assert.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Package assert contains functions for making assertions in unit tests
  2. package assert
  3. import (
  4. "fmt"
  5. "path/filepath"
  6. "runtime"
  7. "strings"
  8. )
  9. // TestingT is an interface which defines the methods of testing.T that are
  10. // required by this package
  11. type TestingT interface {
  12. Fatalf(string, ...interface{})
  13. }
  14. // Equal compare the actual value to the expected value and fails the test if
  15. // they are not equal.
  16. func Equal(t TestingT, actual, expected interface{}) {
  17. if expected != actual {
  18. fatal(t, "Expected '%v' (%T) got '%v' (%T)", expected, expected, actual, actual)
  19. }
  20. }
  21. //EqualStringSlice compares two slices and fails the test if they do not contain
  22. // the same items.
  23. func EqualStringSlice(t TestingT, actual, expected []string) {
  24. if len(actual) != len(expected) {
  25. fatal(t, "Expected (length %d): %q\nActual (length %d): %q",
  26. len(expected), expected, len(actual), actual)
  27. }
  28. for i, item := range actual {
  29. if item != expected[i] {
  30. fatal(t, "Slices differ at element %d, expected %q got %q",
  31. i, expected[i], item)
  32. }
  33. }
  34. }
  35. // NilError asserts that the error is nil, otherwise it fails the test.
  36. func NilError(t TestingT, err error) {
  37. if err != nil {
  38. fatal(t, "Expected no error, got: %s", err.Error())
  39. }
  40. }
  41. // Error asserts that error is not nil, and contains the expected text,
  42. // otherwise it fails the test.
  43. func Error(t TestingT, err error, contains string) {
  44. if err == nil {
  45. fatal(t, "Expected an error, but error was nil")
  46. }
  47. if !strings.Contains(err.Error(), contains) {
  48. fatal(t, "Expected error to contain '%s', got '%s'", contains, err.Error())
  49. }
  50. }
  51. // Contains asserts that the string contains a substring, otherwise it fails the
  52. // test.
  53. func Contains(t TestingT, actual, contains string) {
  54. if !strings.Contains(actual, contains) {
  55. fatal(t, "Expected '%s' to contain '%s'", actual, contains)
  56. }
  57. }
  58. // NotNil fails the test if the object is nil
  59. func NotNil(t TestingT, obj interface{}) {
  60. if obj == nil {
  61. fatal(t, "Expected non-nil value.")
  62. }
  63. }
  64. func fatal(t TestingT, format string, args ...interface{}) {
  65. t.Fatalf(errorSource()+format, args...)
  66. }
  67. // See testing.decorate()
  68. func errorSource() string {
  69. _, filename, line, ok := runtime.Caller(3)
  70. if !ok {
  71. return ""
  72. }
  73. return fmt.Sprintf("%s:%d: ", filepath.Base(filename), line)
  74. }