assertions_test.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  1. package assert
  2. import (
  3. "errors"
  4. "io"
  5. "math"
  6. "os"
  7. "reflect"
  8. "regexp"
  9. "testing"
  10. "time"
  11. )
  12. var (
  13. i interface{}
  14. zeros = []interface{}{
  15. false,
  16. byte(0),
  17. complex64(0),
  18. complex128(0),
  19. float32(0),
  20. float64(0),
  21. int(0),
  22. int8(0),
  23. int16(0),
  24. int32(0),
  25. int64(0),
  26. rune(0),
  27. uint(0),
  28. uint8(0),
  29. uint16(0),
  30. uint32(0),
  31. uint64(0),
  32. uintptr(0),
  33. "",
  34. [0]interface{}{},
  35. []interface{}(nil),
  36. struct{ x int }{},
  37. (*interface{})(nil),
  38. (func())(nil),
  39. nil,
  40. interface{}(nil),
  41. map[interface{}]interface{}(nil),
  42. (chan interface{})(nil),
  43. (<-chan interface{})(nil),
  44. (chan<- interface{})(nil),
  45. }
  46. nonZeros = []interface{}{
  47. true,
  48. byte(1),
  49. complex64(1),
  50. complex128(1),
  51. float32(1),
  52. float64(1),
  53. int(1),
  54. int8(1),
  55. int16(1),
  56. int32(1),
  57. int64(1),
  58. rune(1),
  59. uint(1),
  60. uint8(1),
  61. uint16(1),
  62. uint32(1),
  63. uint64(1),
  64. uintptr(1),
  65. "s",
  66. [1]interface{}{1},
  67. []interface{}{},
  68. struct{ x int }{1},
  69. (*interface{})(&i),
  70. (func())(func() {}),
  71. interface{}(1),
  72. map[interface{}]interface{}{},
  73. (chan interface{})(make(chan interface{})),
  74. (<-chan interface{})(make(chan interface{})),
  75. (chan<- interface{})(make(chan interface{})),
  76. }
  77. )
  78. // AssertionTesterInterface defines an interface to be used for testing assertion methods
  79. type AssertionTesterInterface interface {
  80. TestMethod()
  81. }
  82. // AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface
  83. type AssertionTesterConformingObject struct {
  84. }
  85. func (a *AssertionTesterConformingObject) TestMethod() {
  86. }
  87. // AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface
  88. type AssertionTesterNonConformingObject struct {
  89. }
  90. func TestObjectsAreEqual(t *testing.T) {
  91. if !ObjectsAreEqual("Hello World", "Hello World") {
  92. t.Error("objectsAreEqual should return true")
  93. }
  94. if !ObjectsAreEqual(123, 123) {
  95. t.Error("objectsAreEqual should return true")
  96. }
  97. if !ObjectsAreEqual(123.5, 123.5) {
  98. t.Error("objectsAreEqual should return true")
  99. }
  100. if !ObjectsAreEqual([]byte("Hello World"), []byte("Hello World")) {
  101. t.Error("objectsAreEqual should return true")
  102. }
  103. if !ObjectsAreEqual(nil, nil) {
  104. t.Error("objectsAreEqual should return true")
  105. }
  106. if ObjectsAreEqual(map[int]int{5: 10}, map[int]int{10: 20}) {
  107. t.Error("objectsAreEqual should return false")
  108. }
  109. if ObjectsAreEqual('x', "x") {
  110. t.Error("objectsAreEqual should return false")
  111. }
  112. if ObjectsAreEqual("x", 'x') {
  113. t.Error("objectsAreEqual should return false")
  114. }
  115. if ObjectsAreEqual(0, 0.1) {
  116. t.Error("objectsAreEqual should return false")
  117. }
  118. if ObjectsAreEqual(0.1, 0) {
  119. t.Error("objectsAreEqual should return false")
  120. }
  121. if ObjectsAreEqual(uint32(10), int32(10)) {
  122. t.Error("objectsAreEqual should return false")
  123. }
  124. if !ObjectsAreEqualValues(uint32(10), int32(10)) {
  125. t.Error("ObjectsAreEqualValues should return true")
  126. }
  127. if ObjectsAreEqualValues(0, nil) {
  128. t.Fail()
  129. }
  130. if ObjectsAreEqualValues(nil, 0) {
  131. t.Fail()
  132. }
  133. }
  134. func TestImplements(t *testing.T) {
  135. mockT := new(testing.T)
  136. if !Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) {
  137. t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface")
  138. }
  139. if Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) {
  140. t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface")
  141. }
  142. }
  143. func TestIsType(t *testing.T) {
  144. mockT := new(testing.T)
  145. if !IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) {
  146. t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject")
  147. }
  148. if IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) {
  149. t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject")
  150. }
  151. }
  152. func TestEqual(t *testing.T) {
  153. mockT := new(testing.T)
  154. if !Equal(mockT, "Hello World", "Hello World") {
  155. t.Error("Equal should return true")
  156. }
  157. if !Equal(mockT, 123, 123) {
  158. t.Error("Equal should return true")
  159. }
  160. if !Equal(mockT, 123.5, 123.5) {
  161. t.Error("Equal should return true")
  162. }
  163. if !Equal(mockT, []byte("Hello World"), []byte("Hello World")) {
  164. t.Error("Equal should return true")
  165. }
  166. if !Equal(mockT, nil, nil) {
  167. t.Error("Equal should return true")
  168. }
  169. if !Equal(mockT, int32(123), int32(123)) {
  170. t.Error("Equal should return true")
  171. }
  172. if !Equal(mockT, uint64(123), uint64(123)) {
  173. t.Error("Equal should return true")
  174. }
  175. }
  176. func TestFormatUnequalValues(t *testing.T) {
  177. expected, actual := formatUnequalValues("foo", "bar")
  178. Equal(t, `"foo"`, expected, "value should not include type")
  179. Equal(t, `"bar"`, actual, "value should not include type")
  180. expected, actual = formatUnequalValues(123, 123)
  181. Equal(t, `123`, expected, "value should not include type")
  182. Equal(t, `123`, actual, "value should not include type")
  183. expected, actual = formatUnequalValues(int64(123), int32(123))
  184. Equal(t, `int64(123)`, expected, "value should include type")
  185. Equal(t, `int32(123)`, actual, "value should include type")
  186. type testStructType struct {
  187. Val string
  188. }
  189. expected, actual = formatUnequalValues(&testStructType{Val: "test"}, &testStructType{Val: "test"})
  190. Equal(t, `&assert.testStructType{Val:"test"}`, expected, "value should not include type annotation")
  191. Equal(t, `&assert.testStructType{Val:"test"}`, actual, "value should not include type annotation")
  192. }
  193. func TestNotNil(t *testing.T) {
  194. mockT := new(testing.T)
  195. if !NotNil(mockT, new(AssertionTesterConformingObject)) {
  196. t.Error("NotNil should return true: object is not nil")
  197. }
  198. if NotNil(mockT, nil) {
  199. t.Error("NotNil should return false: object is nil")
  200. }
  201. if NotNil(mockT, (*struct{})(nil)) {
  202. t.Error("NotNil should return false: object is (*struct{})(nil)")
  203. }
  204. }
  205. func TestNil(t *testing.T) {
  206. mockT := new(testing.T)
  207. if !Nil(mockT, nil) {
  208. t.Error("Nil should return true: object is nil")
  209. }
  210. if !Nil(mockT, (*struct{})(nil)) {
  211. t.Error("Nil should return true: object is (*struct{})(nil)")
  212. }
  213. if Nil(mockT, new(AssertionTesterConformingObject)) {
  214. t.Error("Nil should return false: object is not nil")
  215. }
  216. }
  217. func TestTrue(t *testing.T) {
  218. mockT := new(testing.T)
  219. if !True(mockT, true) {
  220. t.Error("True should return true")
  221. }
  222. if True(mockT, false) {
  223. t.Error("True should return false")
  224. }
  225. }
  226. func TestFalse(t *testing.T) {
  227. mockT := new(testing.T)
  228. if !False(mockT, false) {
  229. t.Error("False should return true")
  230. }
  231. if False(mockT, true) {
  232. t.Error("False should return false")
  233. }
  234. }
  235. func TestExactly(t *testing.T) {
  236. mockT := new(testing.T)
  237. a := float32(1)
  238. b := float64(1)
  239. c := float32(1)
  240. d := float32(2)
  241. if Exactly(mockT, a, b) {
  242. t.Error("Exactly should return false")
  243. }
  244. if Exactly(mockT, a, d) {
  245. t.Error("Exactly should return false")
  246. }
  247. if !Exactly(mockT, a, c) {
  248. t.Error("Exactly should return true")
  249. }
  250. if Exactly(mockT, nil, a) {
  251. t.Error("Exactly should return false")
  252. }
  253. if Exactly(mockT, a, nil) {
  254. t.Error("Exactly should return false")
  255. }
  256. }
  257. func TestNotEqual(t *testing.T) {
  258. mockT := new(testing.T)
  259. if !NotEqual(mockT, "Hello World", "Hello World!") {
  260. t.Error("NotEqual should return true")
  261. }
  262. if !NotEqual(mockT, 123, 1234) {
  263. t.Error("NotEqual should return true")
  264. }
  265. if !NotEqual(mockT, 123.5, 123.55) {
  266. t.Error("NotEqual should return true")
  267. }
  268. if !NotEqual(mockT, []byte("Hello World"), []byte("Hello World!")) {
  269. t.Error("NotEqual should return true")
  270. }
  271. if !NotEqual(mockT, nil, new(AssertionTesterConformingObject)) {
  272. t.Error("NotEqual should return true")
  273. }
  274. funcA := func() int { return 23 }
  275. funcB := func() int { return 42 }
  276. if !NotEqual(mockT, funcA, funcB) {
  277. t.Error("NotEqual should return true")
  278. }
  279. if NotEqual(mockT, "Hello World", "Hello World") {
  280. t.Error("NotEqual should return false")
  281. }
  282. if NotEqual(mockT, 123, 123) {
  283. t.Error("NotEqual should return false")
  284. }
  285. if NotEqual(mockT, 123.5, 123.5) {
  286. t.Error("NotEqual should return false")
  287. }
  288. if NotEqual(mockT, []byte("Hello World"), []byte("Hello World")) {
  289. t.Error("NotEqual should return false")
  290. }
  291. if NotEqual(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) {
  292. t.Error("NotEqual should return false")
  293. }
  294. }
  295. type A struct {
  296. Name, Value string
  297. }
  298. func TestContains(t *testing.T) {
  299. mockT := new(testing.T)
  300. list := []string{"Foo", "Bar"}
  301. complexList := []*A{
  302. {"b", "c"},
  303. {"d", "e"},
  304. {"g", "h"},
  305. {"j", "k"},
  306. }
  307. simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
  308. if !Contains(mockT, "Hello World", "Hello") {
  309. t.Error("Contains should return true: \"Hello World\" contains \"Hello\"")
  310. }
  311. if Contains(mockT, "Hello World", "Salut") {
  312. t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"")
  313. }
  314. if !Contains(mockT, list, "Bar") {
  315. t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Bar\"")
  316. }
  317. if Contains(mockT, list, "Salut") {
  318. t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"")
  319. }
  320. if !Contains(mockT, complexList, &A{"g", "h"}) {
  321. t.Error("Contains should return true: complexList contains {\"g\", \"h\"}")
  322. }
  323. if Contains(mockT, complexList, &A{"g", "e"}) {
  324. t.Error("Contains should return false: complexList contains {\"g\", \"e\"}")
  325. }
  326. if Contains(mockT, complexList, &A{"g", "e"}) {
  327. t.Error("Contains should return false: complexList contains {\"g\", \"e\"}")
  328. }
  329. if !Contains(mockT, simpleMap, "Foo") {
  330. t.Error("Contains should return true: \"{\"Foo\": \"Bar\"}\" contains \"Foo\"")
  331. }
  332. if Contains(mockT, simpleMap, "Bar") {
  333. t.Error("Contains should return false: \"{\"Foo\": \"Bar\"}\" does not contains \"Bar\"")
  334. }
  335. }
  336. func TestNotContains(t *testing.T) {
  337. mockT := new(testing.T)
  338. list := []string{"Foo", "Bar"}
  339. simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
  340. if !NotContains(mockT, "Hello World", "Hello!") {
  341. t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"")
  342. }
  343. if NotContains(mockT, "Hello World", "Hello") {
  344. t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"")
  345. }
  346. if !NotContains(mockT, list, "Foo!") {
  347. t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"")
  348. }
  349. if NotContains(mockT, list, "Foo") {
  350. t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"")
  351. }
  352. if NotContains(mockT, simpleMap, "Foo") {
  353. t.Error("Contains should return true: \"{\"Foo\": \"Bar\"}\" contains \"Foo\"")
  354. }
  355. if !NotContains(mockT, simpleMap, "Bar") {
  356. t.Error("Contains should return false: \"{\"Foo\": \"Bar\"}\" does not contains \"Bar\"")
  357. }
  358. }
  359. func Test_includeElement(t *testing.T) {
  360. list1 := []string{"Foo", "Bar"}
  361. list2 := []int{1, 2}
  362. simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
  363. ok, found := includeElement("Hello World", "World")
  364. True(t, ok)
  365. True(t, found)
  366. ok, found = includeElement(list1, "Foo")
  367. True(t, ok)
  368. True(t, found)
  369. ok, found = includeElement(list1, "Bar")
  370. True(t, ok)
  371. True(t, found)
  372. ok, found = includeElement(list2, 1)
  373. True(t, ok)
  374. True(t, found)
  375. ok, found = includeElement(list2, 2)
  376. True(t, ok)
  377. True(t, found)
  378. ok, found = includeElement(list1, "Foo!")
  379. True(t, ok)
  380. False(t, found)
  381. ok, found = includeElement(list2, 3)
  382. True(t, ok)
  383. False(t, found)
  384. ok, found = includeElement(list2, "1")
  385. True(t, ok)
  386. False(t, found)
  387. ok, found = includeElement(simpleMap, "Foo")
  388. True(t, ok)
  389. True(t, found)
  390. ok, found = includeElement(simpleMap, "Bar")
  391. True(t, ok)
  392. False(t, found)
  393. ok, found = includeElement(1433, "1")
  394. False(t, ok)
  395. False(t, found)
  396. }
  397. func TestCondition(t *testing.T) {
  398. mockT := new(testing.T)
  399. if !Condition(mockT, func() bool { return true }, "Truth") {
  400. t.Error("Condition should return true")
  401. }
  402. if Condition(mockT, func() bool { return false }, "Lie") {
  403. t.Error("Condition should return false")
  404. }
  405. }
  406. func TestDidPanic(t *testing.T) {
  407. if funcDidPanic, _ := didPanic(func() {
  408. panic("Panic!")
  409. }); !funcDidPanic {
  410. t.Error("didPanic should return true")
  411. }
  412. if funcDidPanic, _ := didPanic(func() {
  413. }); funcDidPanic {
  414. t.Error("didPanic should return false")
  415. }
  416. }
  417. func TestPanics(t *testing.T) {
  418. mockT := new(testing.T)
  419. if !Panics(mockT, func() {
  420. panic("Panic!")
  421. }) {
  422. t.Error("Panics should return true")
  423. }
  424. if Panics(mockT, func() {
  425. }) {
  426. t.Error("Panics should return false")
  427. }
  428. }
  429. func TestNotPanics(t *testing.T) {
  430. mockT := new(testing.T)
  431. if !NotPanics(mockT, func() {
  432. }) {
  433. t.Error("NotPanics should return true")
  434. }
  435. if NotPanics(mockT, func() {
  436. panic("Panic!")
  437. }) {
  438. t.Error("NotPanics should return false")
  439. }
  440. }
  441. func TestNoError(t *testing.T) {
  442. mockT := new(testing.T)
  443. // start with a nil error
  444. var err error
  445. True(t, NoError(mockT, err), "NoError should return True for nil arg")
  446. // now set an error
  447. err = errors.New("some error")
  448. False(t, NoError(mockT, err), "NoError with error should return False")
  449. // returning an empty error interface
  450. err = func() error {
  451. var err *customError
  452. if err != nil {
  453. t.Fatal("err should be nil here")
  454. }
  455. return err
  456. }()
  457. if err == nil { // err is not nil here!
  458. t.Errorf("Error should be nil due to empty interface", err)
  459. }
  460. False(t, NoError(mockT, err), "NoError should fail with empty error interface")
  461. }
  462. type customError struct{}
  463. func (*customError) Error() string { return "fail" }
  464. func TestError(t *testing.T) {
  465. mockT := new(testing.T)
  466. // start with a nil error
  467. var err error
  468. False(t, Error(mockT, err), "Error should return False for nil arg")
  469. // now set an error
  470. err = errors.New("some error")
  471. True(t, Error(mockT, err), "Error with error should return True")
  472. // returning an empty error interface
  473. err = func() error {
  474. var err *customError
  475. if err != nil {
  476. t.Fatal("err should be nil here")
  477. }
  478. return err
  479. }()
  480. if err == nil { // err is not nil here!
  481. t.Errorf("Error should be nil due to empty interface", err)
  482. }
  483. True(t, Error(mockT, err), "Error should pass with empty error interface")
  484. }
  485. func TestEqualError(t *testing.T) {
  486. mockT := new(testing.T)
  487. // start with a nil error
  488. var err error
  489. False(t, EqualError(mockT, err, ""),
  490. "EqualError should return false for nil arg")
  491. // now set an error
  492. err = errors.New("some error")
  493. False(t, EqualError(mockT, err, "Not some error"),
  494. "EqualError should return false for different error string")
  495. True(t, EqualError(mockT, err, "some error"),
  496. "EqualError should return true")
  497. }
  498. func Test_isEmpty(t *testing.T) {
  499. chWithValue := make(chan struct{}, 1)
  500. chWithValue <- struct{}{}
  501. True(t, isEmpty(""))
  502. True(t, isEmpty(nil))
  503. True(t, isEmpty([]string{}))
  504. True(t, isEmpty(0))
  505. True(t, isEmpty(int32(0)))
  506. True(t, isEmpty(int64(0)))
  507. True(t, isEmpty(false))
  508. True(t, isEmpty(map[string]string{}))
  509. True(t, isEmpty(new(time.Time)))
  510. True(t, isEmpty(time.Time{}))
  511. True(t, isEmpty(make(chan struct{})))
  512. False(t, isEmpty("something"))
  513. False(t, isEmpty(errors.New("something")))
  514. False(t, isEmpty([]string{"something"}))
  515. False(t, isEmpty(1))
  516. False(t, isEmpty(true))
  517. False(t, isEmpty(map[string]string{"Hello": "World"}))
  518. False(t, isEmpty(chWithValue))
  519. }
  520. func TestEmpty(t *testing.T) {
  521. mockT := new(testing.T)
  522. chWithValue := make(chan struct{}, 1)
  523. chWithValue <- struct{}{}
  524. var tiP *time.Time
  525. var tiNP time.Time
  526. var s *string
  527. var f *os.File
  528. True(t, Empty(mockT, ""), "Empty string is empty")
  529. True(t, Empty(mockT, nil), "Nil is empty")
  530. True(t, Empty(mockT, []string{}), "Empty string array is empty")
  531. True(t, Empty(mockT, 0), "Zero int value is empty")
  532. True(t, Empty(mockT, false), "False value is empty")
  533. True(t, Empty(mockT, make(chan struct{})), "Channel without values is empty")
  534. True(t, Empty(mockT, s), "Nil string pointer is empty")
  535. True(t, Empty(mockT, f), "Nil os.File pointer is empty")
  536. True(t, Empty(mockT, tiP), "Nil time.Time pointer is empty")
  537. True(t, Empty(mockT, tiNP), "time.Time is empty")
  538. False(t, Empty(mockT, "something"), "Non Empty string is not empty")
  539. False(t, Empty(mockT, errors.New("something")), "Non nil object is not empty")
  540. False(t, Empty(mockT, []string{"something"}), "Non empty string array is not empty")
  541. False(t, Empty(mockT, 1), "Non-zero int value is not empty")
  542. False(t, Empty(mockT, true), "True value is not empty")
  543. False(t, Empty(mockT, chWithValue), "Channel with values is not empty")
  544. }
  545. func TestNotEmpty(t *testing.T) {
  546. mockT := new(testing.T)
  547. chWithValue := make(chan struct{}, 1)
  548. chWithValue <- struct{}{}
  549. False(t, NotEmpty(mockT, ""), "Empty string is empty")
  550. False(t, NotEmpty(mockT, nil), "Nil is empty")
  551. False(t, NotEmpty(mockT, []string{}), "Empty string array is empty")
  552. False(t, NotEmpty(mockT, 0), "Zero int value is empty")
  553. False(t, NotEmpty(mockT, false), "False value is empty")
  554. False(t, NotEmpty(mockT, make(chan struct{})), "Channel without values is empty")
  555. True(t, NotEmpty(mockT, "something"), "Non Empty string is not empty")
  556. True(t, NotEmpty(mockT, errors.New("something")), "Non nil object is not empty")
  557. True(t, NotEmpty(mockT, []string{"something"}), "Non empty string array is not empty")
  558. True(t, NotEmpty(mockT, 1), "Non-zero int value is not empty")
  559. True(t, NotEmpty(mockT, true), "True value is not empty")
  560. True(t, NotEmpty(mockT, chWithValue), "Channel with values is not empty")
  561. }
  562. func Test_getLen(t *testing.T) {
  563. falseCases := []interface{}{
  564. nil,
  565. 0,
  566. true,
  567. false,
  568. 'A',
  569. struct{}{},
  570. }
  571. for _, v := range falseCases {
  572. ok, l := getLen(v)
  573. False(t, ok, "Expected getLen fail to get length of %#v", v)
  574. Equal(t, 0, l, "getLen should return 0 for %#v", v)
  575. }
  576. ch := make(chan int, 5)
  577. ch <- 1
  578. ch <- 2
  579. ch <- 3
  580. trueCases := []struct {
  581. v interface{}
  582. l int
  583. }{
  584. {[]int{1, 2, 3}, 3},
  585. {[...]int{1, 2, 3}, 3},
  586. {"ABC", 3},
  587. {map[int]int{1: 2, 2: 4, 3: 6}, 3},
  588. {ch, 3},
  589. {[]int{}, 0},
  590. {map[int]int{}, 0},
  591. {make(chan int), 0},
  592. {[]int(nil), 0},
  593. {map[int]int(nil), 0},
  594. {(chan int)(nil), 0},
  595. }
  596. for _, c := range trueCases {
  597. ok, l := getLen(c.v)
  598. True(t, ok, "Expected getLen success to get length of %#v", c.v)
  599. Equal(t, c.l, l)
  600. }
  601. }
  602. func TestLen(t *testing.T) {
  603. mockT := new(testing.T)
  604. False(t, Len(mockT, nil, 0), "nil does not have length")
  605. False(t, Len(mockT, 0, 0), "int does not have length")
  606. False(t, Len(mockT, true, 0), "true does not have length")
  607. False(t, Len(mockT, false, 0), "false does not have length")
  608. False(t, Len(mockT, 'A', 0), "Rune does not have length")
  609. False(t, Len(mockT, struct{}{}, 0), "Struct does not have length")
  610. ch := make(chan int, 5)
  611. ch <- 1
  612. ch <- 2
  613. ch <- 3
  614. cases := []struct {
  615. v interface{}
  616. l int
  617. }{
  618. {[]int{1, 2, 3}, 3},
  619. {[...]int{1, 2, 3}, 3},
  620. {"ABC", 3},
  621. {map[int]int{1: 2, 2: 4, 3: 6}, 3},
  622. {ch, 3},
  623. {[]int{}, 0},
  624. {map[int]int{}, 0},
  625. {make(chan int), 0},
  626. {[]int(nil), 0},
  627. {map[int]int(nil), 0},
  628. {(chan int)(nil), 0},
  629. }
  630. for _, c := range cases {
  631. True(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l)
  632. }
  633. cases = []struct {
  634. v interface{}
  635. l int
  636. }{
  637. {[]int{1, 2, 3}, 4},
  638. {[...]int{1, 2, 3}, 2},
  639. {"ABC", 2},
  640. {map[int]int{1: 2, 2: 4, 3: 6}, 4},
  641. {ch, 2},
  642. {[]int{}, 1},
  643. {map[int]int{}, 1},
  644. {make(chan int), 1},
  645. {[]int(nil), 1},
  646. {map[int]int(nil), 1},
  647. {(chan int)(nil), 1},
  648. }
  649. for _, c := range cases {
  650. False(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l)
  651. }
  652. }
  653. func TestWithinDuration(t *testing.T) {
  654. mockT := new(testing.T)
  655. a := time.Now()
  656. b := a.Add(10 * time.Second)
  657. True(t, WithinDuration(mockT, a, b, 10*time.Second), "A 10s difference is within a 10s time difference")
  658. True(t, WithinDuration(mockT, b, a, 10*time.Second), "A 10s difference is within a 10s time difference")
  659. False(t, WithinDuration(mockT, a, b, 9*time.Second), "A 10s difference is not within a 9s time difference")
  660. False(t, WithinDuration(mockT, b, a, 9*time.Second), "A 10s difference is not within a 9s time difference")
  661. False(t, WithinDuration(mockT, a, b, -9*time.Second), "A 10s difference is not within a 9s time difference")
  662. False(t, WithinDuration(mockT, b, a, -9*time.Second), "A 10s difference is not within a 9s time difference")
  663. False(t, WithinDuration(mockT, a, b, -11*time.Second), "A 10s difference is not within a 9s time difference")
  664. False(t, WithinDuration(mockT, b, a, -11*time.Second), "A 10s difference is not within a 9s time difference")
  665. }
  666. func TestInDelta(t *testing.T) {
  667. mockT := new(testing.T)
  668. True(t, InDelta(mockT, 1.001, 1, 0.01), "|1.001 - 1| <= 0.01")
  669. True(t, InDelta(mockT, 1, 1.001, 0.01), "|1 - 1.001| <= 0.01")
  670. True(t, InDelta(mockT, 1, 2, 1), "|1 - 2| <= 1")
  671. False(t, InDelta(mockT, 1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail")
  672. False(t, InDelta(mockT, 2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail")
  673. False(t, InDelta(mockT, "", nil, 1), "Expected non numerals to fail")
  674. False(t, InDelta(mockT, 42, math.NaN(), 0.01), "Expected NaN for actual to fail")
  675. False(t, InDelta(mockT, math.NaN(), 42, 0.01), "Expected NaN for expected to fail")
  676. cases := []struct {
  677. a, b interface{}
  678. delta float64
  679. }{
  680. {uint8(2), uint8(1), 1},
  681. {uint16(2), uint16(1), 1},
  682. {uint32(2), uint32(1), 1},
  683. {uint64(2), uint64(1), 1},
  684. {int(2), int(1), 1},
  685. {int8(2), int8(1), 1},
  686. {int16(2), int16(1), 1},
  687. {int32(2), int32(1), 1},
  688. {int64(2), int64(1), 1},
  689. {float32(2), float32(1), 1},
  690. {float64(2), float64(1), 1},
  691. }
  692. for _, tc := range cases {
  693. True(t, InDelta(mockT, tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta)
  694. }
  695. }
  696. func TestInDeltaSlice(t *testing.T) {
  697. mockT := new(testing.T)
  698. True(t, InDeltaSlice(mockT,
  699. []float64{1.001, 0.999},
  700. []float64{1, 1},
  701. 0.1), "{1.001, 0.009} is element-wise close to {1, 1} in delta=0.1")
  702. True(t, InDeltaSlice(mockT,
  703. []float64{1, 2},
  704. []float64{0, 3},
  705. 1), "{1, 2} is element-wise close to {0, 3} in delta=1")
  706. False(t, InDeltaSlice(mockT,
  707. []float64{1, 2},
  708. []float64{0, 3},
  709. 0.1), "{1, 2} is not element-wise close to {0, 3} in delta=0.1")
  710. False(t, InDeltaSlice(mockT, "", nil, 1), "Expected non numeral slices to fail")
  711. }
  712. func TestInEpsilon(t *testing.T) {
  713. mockT := new(testing.T)
  714. cases := []struct {
  715. a, b interface{}
  716. epsilon float64
  717. }{
  718. {uint8(2), uint16(2), .001},
  719. {2.1, 2.2, 0.1},
  720. {2.2, 2.1, 0.1},
  721. {-2.1, -2.2, 0.1},
  722. {-2.2, -2.1, 0.1},
  723. {uint64(100), uint8(101), 0.01},
  724. {0.1, -0.1, 2},
  725. {0.1, 0, 2},
  726. }
  727. for _, tc := range cases {
  728. True(t, InEpsilon(t, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon), "test: %q", tc)
  729. }
  730. cases = []struct {
  731. a, b interface{}
  732. epsilon float64
  733. }{
  734. {uint8(2), int16(-2), .001},
  735. {uint64(100), uint8(102), 0.01},
  736. {2.1, 2.2, 0.001},
  737. {2.2, 2.1, 0.001},
  738. {2.1, -2.2, 1},
  739. {2.1, "bla-bla", 0},
  740. {0.1, -0.1, 1.99},
  741. {0, 0.1, 2}, // expected must be different to zero
  742. }
  743. for _, tc := range cases {
  744. False(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon))
  745. }
  746. }
  747. func TestInEpsilonSlice(t *testing.T) {
  748. mockT := new(testing.T)
  749. True(t, InEpsilonSlice(mockT,
  750. []float64{2.2, 2.0},
  751. []float64{2.1, 2.1},
  752. 0.06), "{2.2, 2.0} is element-wise close to {2.1, 2.1} in espilon=0.06")
  753. False(t, InEpsilonSlice(mockT,
  754. []float64{2.2, 2.0},
  755. []float64{2.1, 2.1},
  756. 0.04), "{2.2, 2.0} is not element-wise close to {2.1, 2.1} in espilon=0.04")
  757. False(t, InEpsilonSlice(mockT, "", nil, 1), "Expected non numeral slices to fail")
  758. }
  759. func TestRegexp(t *testing.T) {
  760. mockT := new(testing.T)
  761. cases := []struct {
  762. rx, str string
  763. }{
  764. {"^start", "start of the line"},
  765. {"end$", "in the end"},
  766. {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"},
  767. }
  768. for _, tc := range cases {
  769. True(t, Regexp(mockT, tc.rx, tc.str))
  770. True(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
  771. False(t, NotRegexp(mockT, tc.rx, tc.str))
  772. False(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
  773. }
  774. cases = []struct {
  775. rx, str string
  776. }{
  777. {"^asdfastart", "Not the start of the line"},
  778. {"end$", "in the end."},
  779. {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"},
  780. }
  781. for _, tc := range cases {
  782. False(t, Regexp(mockT, tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str)
  783. False(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
  784. True(t, NotRegexp(mockT, tc.rx, tc.str))
  785. True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
  786. }
  787. }
  788. func testAutogeneratedFunction() {
  789. defer func() {
  790. if err := recover(); err == nil {
  791. panic("did not panic")
  792. }
  793. CallerInfo()
  794. }()
  795. t := struct {
  796. io.Closer
  797. }{}
  798. var c io.Closer
  799. c = t
  800. c.Close()
  801. }
  802. func TestCallerInfoWithAutogeneratedFunctions(t *testing.T) {
  803. NotPanics(t, func() {
  804. testAutogeneratedFunction()
  805. })
  806. }
  807. func TestZero(t *testing.T) {
  808. mockT := new(testing.T)
  809. for _, test := range zeros {
  810. True(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
  811. }
  812. for _, test := range nonZeros {
  813. False(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
  814. }
  815. }
  816. func TestNotZero(t *testing.T) {
  817. mockT := new(testing.T)
  818. for _, test := range zeros {
  819. False(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
  820. }
  821. for _, test := range nonZeros {
  822. True(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
  823. }
  824. }
  825. func TestJSONEq_EqualSONString(t *testing.T) {
  826. mockT := new(testing.T)
  827. True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`))
  828. }
  829. func TestJSONEq_EquivalentButNotEqual(t *testing.T) {
  830. mockT := new(testing.T)
  831. True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
  832. }
  833. func TestJSONEq_HashOfArraysAndHashes(t *testing.T) {
  834. mockT := new(testing.T)
  835. True(t, JSONEq(mockT, "{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}",
  836. "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}"))
  837. }
  838. func TestJSONEq_Array(t *testing.T) {
  839. mockT := new(testing.T)
  840. True(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`))
  841. }
  842. func TestJSONEq_HashAndArrayNotEquivalent(t *testing.T) {
  843. mockT := new(testing.T)
  844. False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`))
  845. }
  846. func TestJSONEq_HashesNotEquivalent(t *testing.T) {
  847. mockT := new(testing.T)
  848. False(t, JSONEq(mockT, `{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
  849. }
  850. func TestJSONEq_ActualIsNotJSON(t *testing.T) {
  851. mockT := new(testing.T)
  852. False(t, JSONEq(mockT, `{"foo": "bar"}`, "Not JSON"))
  853. }
  854. func TestJSONEq_ExpectedIsNotJSON(t *testing.T) {
  855. mockT := new(testing.T)
  856. False(t, JSONEq(mockT, "Not JSON", `{"foo": "bar", "hello": "world"}`))
  857. }
  858. func TestJSONEq_ExpectedAndActualNotJSON(t *testing.T) {
  859. mockT := new(testing.T)
  860. False(t, JSONEq(mockT, "Not JSON", "Not JSON"))
  861. }
  862. func TestJSONEq_ArraysOfDifferentOrder(t *testing.T) {
  863. mockT := new(testing.T)
  864. False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`))
  865. }
  866. func TestDiff(t *testing.T) {
  867. expected := `
  868. Diff:
  869. --- Expected
  870. +++ Actual
  871. @@ -1,3 +1,3 @@
  872. (struct { foo string }) {
  873. - foo: (string) (len=5) "hello"
  874. + foo: (string) (len=3) "bar"
  875. }
  876. `
  877. actual := diff(
  878. struct{ foo string }{"hello"},
  879. struct{ foo string }{"bar"},
  880. )
  881. Equal(t, expected, actual)
  882. expected = `
  883. Diff:
  884. --- Expected
  885. +++ Actual
  886. @@ -2,5 +2,5 @@
  887. (int) 1,
  888. - (int) 2,
  889. (int) 3,
  890. - (int) 4
  891. + (int) 5,
  892. + (int) 7
  893. }
  894. `
  895. actual = diff(
  896. []int{1, 2, 3, 4},
  897. []int{1, 3, 5, 7},
  898. )
  899. Equal(t, expected, actual)
  900. expected = `
  901. Diff:
  902. --- Expected
  903. +++ Actual
  904. @@ -2,4 +2,4 @@
  905. (int) 1,
  906. - (int) 2,
  907. - (int) 3
  908. + (int) 3,
  909. + (int) 5
  910. }
  911. `
  912. actual = diff(
  913. []int{1, 2, 3, 4}[0:3],
  914. []int{1, 3, 5, 7}[0:3],
  915. )
  916. Equal(t, expected, actual)
  917. expected = `
  918. Diff:
  919. --- Expected
  920. +++ Actual
  921. @@ -1,6 +1,6 @@
  922. (map[string]int) (len=4) {
  923. - (string) (len=4) "four": (int) 4,
  924. + (string) (len=4) "five": (int) 5,
  925. (string) (len=3) "one": (int) 1,
  926. - (string) (len=5) "three": (int) 3,
  927. - (string) (len=3) "two": (int) 2
  928. + (string) (len=5) "seven": (int) 7,
  929. + (string) (len=5) "three": (int) 3
  930. }
  931. `
  932. actual = diff(
  933. map[string]int{"one": 1, "two": 2, "three": 3, "four": 4},
  934. map[string]int{"one": 1, "three": 3, "five": 5, "seven": 7},
  935. )
  936. Equal(t, expected, actual)
  937. }
  938. func TestDiffEmptyCases(t *testing.T) {
  939. Equal(t, "", diff(nil, nil))
  940. Equal(t, "", diff(struct{ foo string }{}, nil))
  941. Equal(t, "", diff(nil, struct{ foo string }{}))
  942. Equal(t, "", diff(1, 2))
  943. Equal(t, "", diff(1, 2))
  944. Equal(t, "", diff([]int{1}, []bool{true}))
  945. }
  946. // Ensure there are no data races
  947. func TestDiffRace(t *testing.T) {
  948. t.Parallel()
  949. expected := map[string]string{
  950. "a": "A",
  951. "b": "B",
  952. "c": "C",
  953. }
  954. actual := map[string]string{
  955. "d": "D",
  956. "e": "E",
  957. "f": "F",
  958. }
  959. // run diffs in parallel simulating tests with t.Parallel()
  960. numRoutines := 10
  961. rChans := make([]chan string, numRoutines)
  962. for idx := range rChans {
  963. rChans[idx] = make(chan string)
  964. go func(ch chan string) {
  965. defer close(ch)
  966. ch <- diff(expected, actual)
  967. }(rChans[idx])
  968. }
  969. for _, ch := range rChans {
  970. for msg := range ch {
  971. NotZero(t, msg) // dummy assert
  972. }
  973. }
  974. }
  975. type mockTestingT struct {
  976. }
  977. func (m *mockTestingT) Errorf(format string, args ...interface{}) {}
  978. func TestFailNowWithPlainTestingT(t *testing.T) {
  979. mockT := &mockTestingT{}
  980. Panics(t, func() {
  981. FailNow(mockT, "failed")
  982. }, "should panic since mockT is missing FailNow()")
  983. }
  984. type mockFailNowTestingT struct {
  985. }
  986. func (m *mockFailNowTestingT) Errorf(format string, args ...interface{}) {}
  987. func (m *mockFailNowTestingT) FailNow() {}
  988. func TestFailNowWithFullTestingT(t *testing.T) {
  989. mockT := &mockFailNowTestingT{}
  990. NotPanics(t, func() {
  991. FailNow(mockT, "failed")
  992. }, "should call mockT.FailNow() rather than panicking")
  993. }