assert.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Package assert contains functions for making assertions in unit tests
  2. package assert
  3. import (
  4. "strings"
  5. )
  6. // TestingT is an interface which defines the methods of testing.T that are
  7. // required by this package
  8. type TestingT interface {
  9. Fatalf(string, ...interface{})
  10. }
  11. // Equal compare the actual value to the expected value and fails the test if
  12. // they are not equal.
  13. func Equal(t TestingT, actual, expected interface{}) {
  14. if expected != actual {
  15. t.Fatalf("Expected '%v' (%T) got '%v' (%T)", expected, expected, actual, actual)
  16. }
  17. }
  18. // NilError asserts that the error is nil, otherwise it fails the test.
  19. func NilError(t TestingT, err error) {
  20. if err != nil {
  21. t.Fatalf("Expected no error, got: %s", err.Error())
  22. }
  23. }
  24. // Error asserts that error is not nil, and contains the expected text,
  25. // otherwise it fails the test.
  26. func Error(t TestingT, err error, contains string) {
  27. if err == nil {
  28. t.Fatalf("Expected an error, but error was nil")
  29. }
  30. if !strings.Contains(err.Error(), contains) {
  31. t.Fatalf("Expected error to contain '%s', got '%s'", contains, err.Error())
  32. }
  33. }
  34. // Contains asserts that the string contains a substring, otherwise it fails the
  35. // test.
  36. func Contains(t TestingT, actual, contains string) {
  37. if !strings.Contains(actual, contains) {
  38. t.Fatalf("Expected '%s' to contain '%s'", actual, contains)
  39. }
  40. }