123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132 |
- package gott
- import (
- "errors"
- "fmt"
- "testing"
- )
- func divide5(by interface{}) (interface{}, error) {
- if b := by.(int); b == 0 {
- return nil, errors.New("divideByZero")
- } else {
- return 5 / b, nil
- }
- }
- func TestBindOk(t *testing.T) {
- r := Result{5, nil}
- r = r.Bind(divide5)
- if r.e != nil {
- t.Errorf("Error returned: %s\n", r.e)
- } else if r.s != 1 {
- t.Errorf("5 / 5 = %d, want 1\n", r.s)
- }
- }
- func TestBindErr(t *testing.T) {
- r := Result{0, nil}
- r = r.Bind(divide5)
- if r.e == nil {
- t.Errorf("Error not returned\n")
- }
- }
- func add5(to interface{}) interface{} {
- return to.(int) + 5
- }
- func TestMap(t *testing.T) {
- r := Result{0, nil}
- r = r.Map(add5)
- if r.e != nil {
- t.Errorf("Error returned: %s\n", r.e)
- } else if r.s != 5 {
- t.Errorf("0 + 5 = %d, want 5\n", r.s)
- }
- }
- func sideEffectWithError(interface{}) error {
- fmt.Printf("side effect\n")
- return errors.New("Dummy error")
- }
- func sideEffect(interface{}) {
- fmt.Printf("side effect\n")
- }
- func TestTee(t *testing.T) {
- r := Result{0, nil}
- r = r.Tee(sideEffectWithError)
- if r.e == nil {
- t.Errorf("Error not returned\n")
- }
- }
- func TestSafeTee(t *testing.T) {
- r := Result{0, nil}
- r = r.SafeTee(sideEffect)
- if r.e != nil {
- t.Errorf("Error returned\n")
- } else if r.s != 0 {
- t.Errorf("nop 0 = %d, want 0\n", r.s)
- }
- }
- var s int
- var e error
- func onSuccess(param interface{}) {
- s = param.(int)
- }
- func onError(param error) {
- e = param
- }
- func TestHandle(t *testing.T) {
- r := Result{5, nil}
- r = r.Handle(onSuccess, onError)
- if r.e != nil {
- t.Errorf("Error returned\n")
- } else if r.s != 5 {
- t.Errorf("Success modified\n")
- } else if s != 5 {
- t.Errorf("onSuccess not run\n")
- } else if e != nil {
- t.Errorf("onError run\n")
- }
- }
- func histeric(interface{}) interface{} {
- panic(42)
- }
- func TestCatch(t *testing.T) {
- r := Result{0, nil}
- r = r.Catch(histeric)
- if r.s != nil {
- t.Errorf("success modifiedn")
- } else if r.e.(Exception).e != 42 {
- t.Errorf("%s, want 42", r.e)
- }
- }
- func TestFinishOK(t *testing.T) {
- r := Result{5, nil}
- ok, err := r.Bind(divide5).Finish()
- if err != nil {
- t.Errorf("Error returned: %s\n", r.e)
- } else if ok != 1 {
- t.Errorf("5 / 5 = %d, want 1\n", r.s)
- }
- }
- func TestFinishErr(t *testing.T) {
- r := Result{0, nil}
- _, err := r.Bind(divide5).Finish()
- if err == nil {
- t.Errorf("Error not returned\n")
- }
- }
|