github.com/pubgo/xprocess@v0.1.11/xprocess_future/future_test.go (about) 1 package xprocess_future 2 3 import ( 4 "fmt" 5 "net/http" 6 "testing" 7 8 "github.com/pubgo/xprocess/xprocess_abc" 9 "github.com/stretchr/testify/assert" 10 ) 11 12 type a1 struct { 13 a int 14 } 15 16 func a1Test() *a1 { 17 return &a1{} 18 } 19 20 func a2Test() *a1 { 21 return nil 22 } 23 24 func a3Test() a1 { 25 return a1{} 26 } 27 28 func TestAsync(t *testing.T) { 29 val := Async(http.Get, "https://www.cnblogs.com") 30 assert.Nil(t, val.Err()) 31 assert.NotNil(t, val.Get()) 32 assert.Nil(t, val.Value(func(resp *http.Response, err error) { 33 assert.Nil(t, err) 34 assert.NotNil(t, resp) 35 })) 36 37 val = Async(func(i int) {}, 1) 38 assert.Nil(t, val.Err()) 39 assert.Nil(t, val.Get()) 40 assert.Nil(t, val.Value(func() {})) 41 42 a1Val := Await(Async(a1Test), func(a *a1) *a1 { a.a = 1; return a }) 43 assert.Nil(t, a1Val.Err()) 44 assert.NotNil(t, a1Val.Get().(*a1)) 45 assert.Equal(t, a1Val.Get().(*a1).a, 1) 46 47 a1Val = Await(Async(a1Test), func(a *a1) *a1 { a.a = 1; return nil }) 48 assert.Nil(t, a1Val.Err()) 49 assert.Nil(t, a1Val.Get()) 50 assert.Nil(t, a1Val.Value(func(a *a1) { 51 fmt.Println("a", a, a == nil) 52 })) 53 54 a2Val := Await(Async(a2Test), func(a *a1) *a1 { 55 if a == nil { 56 return nil 57 } 58 59 a.a = 1 60 return a 61 }) 62 assert.Nil(t, a2Val.Err()) 63 assert.Nil(t, a2Val.Get()) 64 65 a3Val := Await(Async(a3Test), func(a a1) a1 { 66 a.a = 1 67 return a 68 }) 69 assert.Nil(t, a3Val.Err()) 70 assert.Equal(t, a3Val.Get().(a1).a, 1) 71 } 72 73 func TestAwait(t *testing.T) { 74 val := Async(http.Get, "https://www.cnblogs.com") 75 head := Await(val, func(resp *http.Response, err error) http.Header { 76 assert.Nil(t, err) 77 resp.Header.Add("aa", "11") 78 return resp.Header 79 }) 80 assert.Nil(t, head.Err()) 81 assert.NotNil(t, head.Get()) 82 assert.Equal(t, head.Get().(http.Header).Get("aa"), "11") 83 } 84 85 func promise1() xprocess_abc.IPromise { 86 return Promise(func(g xprocess_abc.Future) { 87 for i := 0; i < 10; i++ { 88 val := Async(http.Get, "https://www.cnblogs.com") 89 g.Yield(val) 90 91 val = Async(http.Get, "https://www.cnblogs.com") 92 val = Await(val, func(resp *http.Response, err error) (*http.Response, error) { 93 resp.Header.Set("a", "b") 94 return resp, err 95 }) 96 97 g.YieldFn(val, func(resp *http.Response, err error) (*http.Response, error) { 98 resp.Header.Set("b", "c") 99 return resp, err 100 }) 101 } 102 }) 103 } 104 105 func TestPromise(t *testing.T) { 106 p := promise1() 107 heads := p.Map(func(resp *http.Response, err error) http.Header { return resp.Header }) 108 assert.Nil(t, heads.Err()) 109 110 for _, h := range heads.Value().([]http.Header) { 111 fmt.Println(h) 112 } 113 }