gott_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. package gott
  2. import (
  3. "errors"
  4. "fmt"
  5. "testing"
  6. )
  7. func divide5(by interface{}) (interface{}, error) {
  8. if b := by.(int); b == 0 {
  9. return nil, errors.New("divideByZero")
  10. } else {
  11. return 5 / b, nil
  12. }
  13. }
  14. func TestBindOk(t *testing.T) {
  15. r := Result{5, nil}
  16. r = r.Bind(divide5)
  17. if r.e != nil {
  18. t.Errorf("Error returned: %s\n", r.e)
  19. } else if r.s != 1 {
  20. t.Errorf("5 / 5 = %d, want 1\n", r.s)
  21. }
  22. }
  23. func TestBindErr(t *testing.T) {
  24. r := Result{0, nil}
  25. r = r.Bind(divide5)
  26. if r.e == nil {
  27. t.Errorf("Error not returned\n")
  28. }
  29. }
  30. func add5(to interface{}) interface{} {
  31. return to.(int) + 5
  32. }
  33. func TestMap(t *testing.T) {
  34. r := Result{0, nil}
  35. r = r.Map(add5)
  36. if r.e != nil {
  37. t.Errorf("Error returned: %s\n", r.e)
  38. } else if r.s != 5 {
  39. t.Errorf("0 + 5 = %d, want 5\n", r.s)
  40. }
  41. }
  42. func sideEffectWithError(interface{}) error {
  43. fmt.Printf("side effect\n")
  44. return errors.New("Dummy error")
  45. }
  46. func sideEffect(interface{}) {
  47. fmt.Printf("side effect\n")
  48. }
  49. func TestTee(t *testing.T) {
  50. r := Result{0, nil}
  51. r = r.Tee(sideEffectWithError)
  52. if r.e == nil {
  53. t.Errorf("Error not returned\n")
  54. }
  55. }
  56. func TestSafeTee(t *testing.T) {
  57. r := Result{0, nil}
  58. r = r.SafeTee(sideEffect)
  59. if r.e != nil {
  60. t.Errorf("Error returned\n")
  61. } else if r.s != 0 {
  62. t.Errorf("nop 0 = %d, want 0\n", r.s)
  63. }
  64. }
  65. var s int
  66. var e error
  67. func onSuccess(param interface{}) {
  68. s = param.(int)
  69. }
  70. func onError(param error) {
  71. e = param
  72. }
  73. func TestHandle(t *testing.T) {
  74. r := Result{5, nil}
  75. r = r.Handle(onSuccess, onError)
  76. if r.e != nil {
  77. t.Errorf("Error returned\n")
  78. } else if r.s != 5 {
  79. t.Errorf("Success modified\n")
  80. } else if s != 5 {
  81. t.Errorf("onSuccess not run\n")
  82. } else if e != nil {
  83. t.Errorf("onError run\n")
  84. }
  85. }
  86. func histeric(interface{}) interface{} {
  87. panic(42)
  88. }
  89. func TestCatch(t *testing.T) {
  90. r := Result{0, nil}
  91. r = r.Catch(histeric)
  92. if r.s != nil {
  93. t.Errorf("success modifiedn")
  94. } else if r.e.(Exception).e != 42 {
  95. t.Errorf("%s, want 42", r.e)
  96. }
  97. }