assertions.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. package assert
  2. import (
  3. "fmt"
  4. "reflect"
  5. "runtime"
  6. "strings"
  7. "testing"
  8. "time"
  9. )
  10. // Comparison a custom function that returns true on success and false on failure
  11. type Comparison func() (success bool)
  12. /*
  13. Helper functions
  14. */
  15. // ObjectsAreEqual determines if two objects are considered equal.
  16. //
  17. // This function does no assertion of any kind.
  18. func ObjectsAreEqual(a, b interface{}) bool {
  19. if reflect.DeepEqual(a, b) {
  20. return true
  21. }
  22. if reflect.ValueOf(a) == reflect.ValueOf(b) {
  23. return true
  24. }
  25. // Last ditch effort
  26. if fmt.Sprintf("%#v", a) == fmt.Sprintf("%#v", b) {
  27. return true
  28. }
  29. return false
  30. }
  31. /* CallerInfo is necessary because the assert functions use the testing object
  32. internally, causing it to print the file:line of the assert method, rather than where
  33. the problem actually occured in calling code.*/
  34. // CallerInfo returns a string containing the file and line number of the assert call
  35. // that failed.
  36. func CallerInfo() string {
  37. file := ""
  38. line := 0
  39. ok := false
  40. for i := 0; ; i++ {
  41. _, file, line, ok = runtime.Caller(i)
  42. if !ok {
  43. return ""
  44. }
  45. parts := strings.Split(file, "/")
  46. dir := parts[len(parts)-2]
  47. file = parts[len(parts)-1]
  48. if (dir != "assert" && dir != "mock") || file == "mock_test.go" {
  49. break
  50. }
  51. }
  52. return fmt.Sprintf("%s:%d", file, line)
  53. }
  54. // getWhitespaceString returns a string that is long enough to overwrite the default
  55. // output from the go testing framework.
  56. func getWhitespaceString() string {
  57. _, file, line, ok := runtime.Caller(1)
  58. if !ok {
  59. return ""
  60. }
  61. parts := strings.Split(file, "/")
  62. file = parts[len(parts)-1]
  63. return strings.Repeat(" ", len(fmt.Sprintf("%s:%d: ", file, line)))
  64. }
  65. func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
  66. if len(msgAndArgs) == 0 || msgAndArgs == nil {
  67. return ""
  68. }
  69. if len(msgAndArgs) == 1 {
  70. return msgAndArgs[0].(string)
  71. }
  72. if len(msgAndArgs) > 1 {
  73. return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
  74. }
  75. return ""
  76. }
  77. // Fail reports a failure through
  78. func Fail(t *testing.T, failureMessage string, msgAndArgs ...interface{}) bool {
  79. message := messageFromMsgAndArgs(msgAndArgs...)
  80. if len(message) > 0 {
  81. t.Errorf("\r%s\r\tLocation:\t%s\n\r\tError:\t\t%s\n\r\tMessages:\t%s\n\r", getWhitespaceString(), CallerInfo(), failureMessage, message)
  82. } else {
  83. t.Errorf("\r%s\r\tLocation:\t%s\n\r\tError:\t\t%s\n\r", getWhitespaceString(), CallerInfo(), failureMessage)
  84. }
  85. return false
  86. }
  87. // Implements asserts that an object is implemented by the specified interface.
  88. //
  89. // assert.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject")
  90. func Implements(t *testing.T, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
  91. interfaceType := reflect.TypeOf(interfaceObject).Elem()
  92. if !reflect.TypeOf(object).Implements(interfaceType) {
  93. return Fail(t, fmt.Sprintf("Object must implement %v", interfaceType), msgAndArgs...)
  94. }
  95. return true
  96. }
  97. // IsType asserts that the specified objects are of the same type.
  98. func IsType(t *testing.T, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
  99. if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) {
  100. return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...)
  101. }
  102. return true
  103. }
  104. // Equal asserts that two objects are equal.
  105. //
  106. // assert.Equal(t, 123, 123, "123 and 123 should be equal")
  107. //
  108. // Returns whether the assertion was successful (true) or not (false).
  109. func Equal(t *testing.T, a, b interface{}, msgAndArgs ...interface{}) bool {
  110. if !ObjectsAreEqual(a, b) {
  111. return Fail(t, fmt.Sprintf("Not equal: %#v != %#v", a, b), msgAndArgs...)
  112. }
  113. return true
  114. }
  115. // Exactly asserts that two objects are equal is value and type.
  116. //
  117. // assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal")
  118. //
  119. // Returns whether the assertion was successful (true) or not (false).
  120. func Exactly(t *testing.T, a, b interface{}, msgAndArgs ...interface{}) bool {
  121. aType := reflect.TypeOf(a)
  122. bType := reflect.TypeOf(b)
  123. if aType != bType {
  124. return Fail(t, "Types expected to match exactly", "%v != %v", aType, bType)
  125. }
  126. return Equal(t, a, b, msgAndArgs...)
  127. }
  128. // NotNil asserts that the specified object is not nil.
  129. //
  130. // assert.NotNil(t, err, "err should be something")
  131. //
  132. // Returns whether the assertion was successful (true) or not (false).
  133. func NotNil(t *testing.T, object interface{}, msgAndArgs ...interface{}) bool {
  134. var success bool = true
  135. if object == nil {
  136. success = false
  137. } else {
  138. value := reflect.ValueOf(object)
  139. kind := value.Kind()
  140. if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() {
  141. success = false
  142. }
  143. }
  144. if !success {
  145. Fail(t, "Expected not to be nil.", msgAndArgs...)
  146. }
  147. return success
  148. }
  149. // Nil asserts that the specified object is nil.
  150. //
  151. // assert.Nil(t, err, "err should be nothing")
  152. //
  153. // Returns whether the assertion was successful (true) or not (false).
  154. func Nil(t *testing.T, object interface{}, msgAndArgs ...interface{}) bool {
  155. if object == nil {
  156. return true
  157. } else {
  158. value := reflect.ValueOf(object)
  159. kind := value.Kind()
  160. if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() {
  161. return true
  162. }
  163. }
  164. return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
  165. }
  166. // isEmpty gets whether the specified object is considered empty or not.
  167. func isEmpty(object interface{}) bool {
  168. if object == nil {
  169. return true
  170. } else if object == "" {
  171. return true
  172. } else if object == 0 {
  173. return true
  174. } else if object == false {
  175. return true
  176. }
  177. objValue := reflect.ValueOf(object)
  178. switch objValue.Kind() {
  179. case reflect.Slice:
  180. {
  181. return (objValue.Len() == 0)
  182. }
  183. }
  184. return false
  185. }
  186. // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or a
  187. // slice with len == 0.
  188. //
  189. // assert.Empty(t, obj)
  190. //
  191. // Returns whether the assertion was successful (true) or not (false).
  192. func Empty(t *testing.T, object interface{}, msgAndArgs ...interface{}) bool {
  193. pass := isEmpty(object)
  194. if !pass {
  195. Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
  196. }
  197. return pass
  198. }
  199. // Empty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or a
  200. // slice with len == 0.
  201. //
  202. // if assert.NotEmpty(t, obj) {
  203. // assert.Equal(t, "two", obj[1])
  204. // }
  205. //
  206. // Returns whether the assertion was successful (true) or not (false).
  207. func NotEmpty(t *testing.T, object interface{}, msgAndArgs ...interface{}) bool {
  208. pass := !isEmpty(object)
  209. if !pass {
  210. Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...)
  211. }
  212. return pass
  213. }
  214. // True asserts that the specified value is true.
  215. //
  216. // assert.True(t, myBool, "myBool should be true")
  217. //
  218. // Returns whether the assertion was successful (true) or not (false).
  219. func True(t *testing.T, value bool, msgAndArgs ...interface{}) bool {
  220. if value != true {
  221. return Fail(t, "Should be true", msgAndArgs...)
  222. }
  223. return true
  224. }
  225. // False asserts that the specified value is true.
  226. //
  227. // assert.False(t, myBool, "myBool should be false")
  228. //
  229. // Returns whether the assertion was successful (true) or not (false).
  230. func False(t *testing.T, value bool, msgAndArgs ...interface{}) bool {
  231. if value != false {
  232. return Fail(t, "Should be false", msgAndArgs...)
  233. }
  234. return true
  235. }
  236. // NotEqual asserts that the specified values are NOT equal.
  237. //
  238. // assert.NotEqual(t, obj1, obj2, "two objects shouldn't be equal")
  239. //
  240. // Returns whether the assertion was successful (true) or not (false).
  241. func NotEqual(t *testing.T, a, b interface{}, msgAndArgs ...interface{}) bool {
  242. if ObjectsAreEqual(a, b) {
  243. return Fail(t, "Should not be equal", msgAndArgs...)
  244. }
  245. return true
  246. }
  247. // Contains asserts that the specified string contains the specified substring.
  248. //
  249. // assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'")
  250. //
  251. // Returns whether the assertion was successful (true) or not (false).
  252. func Contains(t *testing.T, s, contains string, msgAndArgs ...interface{}) bool {
  253. if !strings.Contains(s, contains) {
  254. return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...)
  255. }
  256. return true
  257. }
  258. // NotContains asserts that the specified string does NOT contain the specified substring.
  259. //
  260. // assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'")
  261. //
  262. // Returns whether the assertion was successful (true) or not (false).
  263. func NotContains(t *testing.T, s, contains string, msgAndArgs ...interface{}) bool {
  264. if strings.Contains(s, contains) {
  265. return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...)
  266. }
  267. return true
  268. }
  269. // Uses a Comparison to assert a complex condition.
  270. func Condition(t *testing.T, comp Comparison, msgAndArgs ...interface{}) bool {
  271. result := comp()
  272. if !result {
  273. Fail(t, "Condition failed!", msgAndArgs...)
  274. }
  275. return result
  276. }
  277. // PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics
  278. // methods, and represents a simple func that takes no arguments, and returns nothing.
  279. type PanicTestFunc func()
  280. // didPanic returns true if the function passed to it panics. Otherwise, it returns false.
  281. func didPanic(f PanicTestFunc) (bool, interface{}) {
  282. var didPanic bool = false
  283. var message interface{}
  284. func() {
  285. defer func() {
  286. if message = recover(); message != nil {
  287. didPanic = true
  288. }
  289. }()
  290. // call the target function
  291. f()
  292. }()
  293. return didPanic, message
  294. }
  295. // Panics asserts that the code inside the specified PanicTestFunc panics.
  296. //
  297. // assert.Panics(t, func(){
  298. // GoCrazy()
  299. // }, "Calling GoCrazy() should panic")
  300. //
  301. // Returns whether the assertion was successful (true) or not (false).
  302. func Panics(t *testing.T, f PanicTestFunc, msgAndArgs ...interface{}) bool {
  303. if funcDidPanic, panicValue := didPanic(f); !funcDidPanic {
  304. return Fail(t, fmt.Sprintf("func %#v should panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...)
  305. }
  306. return true
  307. }
  308. // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
  309. //
  310. // assert.NotPanics(t, func(){
  311. // RemainCalm()
  312. // }, "Calling RemainCalm() should NOT panic")
  313. //
  314. // Returns whether the assertion was successful (true) or not (false).
  315. func NotPanics(t *testing.T, f PanicTestFunc, msgAndArgs ...interface{}) bool {
  316. if funcDidPanic, panicValue := didPanic(f); funcDidPanic {
  317. return Fail(t, fmt.Sprintf("func %#v should not panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...)
  318. }
  319. return true
  320. }
  321. // WithinDuration asserts that the two times are within duration delta of each other.
  322. //
  323. // assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s")
  324. //
  325. // Returns whether the assertion was successful (true) or not (false).
  326. func WithinDuration(t *testing.T, a, b time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
  327. dt := a.Sub(b)
  328. if dt < -delta || dt > delta {
  329. return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", a, b, dt, delta), msgAndArgs...)
  330. }
  331. return true
  332. }
  333. /*
  334. Errors
  335. */
  336. // NoError asserts that a function returned no error (i.e. `nil`).
  337. //
  338. // actualObj, err := SomeFunction()
  339. // if assert.NoError(t, err) {
  340. // assert.Equal(t, actualObj, expectedObj)
  341. // }
  342. //
  343. // Returns whether the assertion was successful (true) or not (false).
  344. func NoError(t *testing.T, theError error, msgAndArgs ...interface{}) bool {
  345. message := messageFromMsgAndArgs(msgAndArgs...)
  346. return Nil(t, theError, "No error is expected but got %v %s", theError, message)
  347. }
  348. // Error asserts that a function returned an error (i.e. not `nil`).
  349. //
  350. // actualObj, err := SomeFunction()
  351. // if assert.Error(t, err, "An error was expected") {
  352. // assert.Equal(t, err, expectedError)
  353. // }
  354. //
  355. // Returns whether the assertion was successful (true) or not (false).
  356. func Error(t *testing.T, theError error, msgAndArgs ...interface{}) bool {
  357. message := messageFromMsgAndArgs(msgAndArgs...)
  358. return NotNil(t, theError, "An error is expected but got nil. %s", message)
  359. }