monads

Monads, For Golang, Using Generics
git clone git://git.lair.cx/monads
Log | Files | Refs | README | LICENSE

option_test.go (1310B)


      1 package options
      2 
      3 import (
      4 	"reflect"
      5 	"strconv"
      6 	"testing"
      7 )
      8 
      9 func TestMap(t *testing.T) {
     10 	action := func(s string) int {
     11 		n, err := strconv.ParseInt(s, 10, 64)
     12 		if err != nil {
     13 			panic(err)
     14 		}
     15 		return int(n)
     16 	}
     17 	tests := []struct {
     18 		name  string
     19 		value Option[string]
     20 		want  Option[int]
     21 	}{
     22 		{
     23 			"with non-empty value",
     24 			Wrap("1"),
     25 			Wrap(1),
     26 		},
     27 		{
     28 			"with empty value",
     29 			Empty[string](),
     30 			Empty[int](),
     31 		},
     32 	}
     33 	for _, tt := range tests {
     34 		t.Run(tt.name, func(t *testing.T) {
     35 			if got := Map(tt.value, action); !reflect.DeepEqual(got, tt.want) {
     36 				t.Errorf("Map() = %v, want %v", got, tt.want)
     37 			}
     38 		})
     39 	}
     40 }
     41 
     42 func TestFlatMap(t *testing.T) {
     43 	action := func(s string) Option[int] {
     44 		n, err := strconv.ParseInt(s, 10, 64)
     45 		if err != nil {
     46 			return Empty[int]()
     47 		}
     48 		return Wrap(int(n))
     49 	}
     50 	tests := []struct {
     51 		name  string
     52 		value Option[string]
     53 		want  Option[int]
     54 	}{
     55 		{
     56 			"with non-empty value",
     57 			Wrap("1"),
     58 			Wrap(1),
     59 		},
     60 		{
     61 			"with empty value",
     62 			Empty[string](),
     63 			Empty[int](),
     64 		},
     65 		{
     66 			"with invalid value",
     67 			Wrap("??"),
     68 			Empty[int](),
     69 		},
     70 	}
     71 	for _, tt := range tests {
     72 		t.Run(tt.name, func(t *testing.T) {
     73 			if got := FlatMap(tt.value, action); !reflect.DeepEqual(got, tt.want) {
     74 				t.Errorf("Map() = %v, want %v", got, tt.want)
     75 			}
     76 		})
     77 	}
     78 }