assertions.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package goblin
  2. import (
  3. "fmt"
  4. "reflect"
  5. "strings"
  6. )
  7. // Assertion represents a fact stated about a source object. It contains the source object and function to call
  8. type Assertion struct {
  9. src interface{}
  10. fail func(interface{})
  11. }
  12. func objectsAreEqual(a, b interface{}) bool {
  13. if reflect.TypeOf(a) != reflect.TypeOf(b) {
  14. return false
  15. }
  16. if reflect.DeepEqual(a, b) {
  17. return true
  18. }
  19. if fmt.Sprintf("%#v", a) == fmt.Sprintf("%#v", b) {
  20. return true
  21. }
  22. return false
  23. }
  24. func formatMessages(messages ...string) string {
  25. if len(messages) > 0 {
  26. return ", " + strings.Join(messages, " ")
  27. }
  28. return ""
  29. }
  30. // Eql is a shorthand alias of Equal for convenience
  31. func (a *Assertion) Eql(dst interface{}) {
  32. a.Equal(dst)
  33. }
  34. // Equal takes a destination object and asserts that a source object and
  35. // destination object are equal to one another. It will fail the assertion and
  36. // print a corresponding message if the objects are not equivalent.
  37. func (a *Assertion) Equal(dst interface{}) {
  38. if !objectsAreEqual(a.src, dst) {
  39. a.fail(fmt.Sprintf("%#v %s %#v", a.src, "does not equal", dst))
  40. }
  41. }
  42. // IsTrue asserts that a source is equal to true. Optional messages can be
  43. // provided for inclusion in the displayed message if the assertion fails. It
  44. // will fail the assertion if the source does not resolve to true.
  45. func (a *Assertion) IsTrue(messages ...string) {
  46. if !objectsAreEqual(a.src, true) {
  47. message := fmt.Sprintf("%v %s%s", a.src, "expected false to be truthy", formatMessages(messages...))
  48. a.fail(message)
  49. }
  50. }
  51. // IsFalse asserts that a source is equal to false. Optional messages can be
  52. // provided for inclusion in the displayed message if the assertion fails. It
  53. // will fail the assertion if the source does not resolve to false.
  54. func (a *Assertion) IsFalse(messages ...string) {
  55. if !objectsAreEqual(a.src, false) {
  56. message := fmt.Sprintf("%v %s%s", a.src, "expected true to be falsey", formatMessages(messages...))
  57. a.fail(message)
  58. }
  59. }