github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xnet/xhttp/xrequest/xrequest_test.go (about) 1 package xrequest 2 3 import ( 4 "context" 5 "io" 6 "net/http" 7 "net/http/httptest" 8 "net/url" 9 "testing" 10 11 "github.com/stretchr/testify/require" 12 ) 13 14 func TestRequest(t *testing.T) { 15 srv := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { 16 switch request.Method { 17 case http.MethodGet: 18 io.WriteString(writer, "Hello,GET") 19 case http.MethodPost: 20 io.Copy(writer, request.Body) 21 case http.MethodPut: 22 case http.MethodDelete: 23 case http.MethodOptions: 24 case http.MethodHead: 25 case http.MethodTrace: 26 case http.MethodPatch: 27 case http.MethodConnect: 28 29 } 30 })) 31 32 client := NewHttpClient(srv.Client(), "") 33 34 t.Run("GET", func(t *testing.T) { 35 response, err := client.Get(context.Background(), srv.URL) 36 require.Nil(t, err, "err must be nil") 37 body, err := response.String() 38 require.Nil(t, err, "err must be nil") 39 require.Equal(t, "Hello,GET", body) 40 }) 41 42 t.Run("POST", func(t *testing.T) { 43 reqBody, err := NewJsonBody(map[string]interface{}{"hello": "world", "age": 12}) 44 require.Nil(t, err, "err muse be nil") 45 response, err := client.Post(context.Background(), srv.URL, reqBody) 46 require.Nil(t, err, "err must be nil") 47 body, err := response.String() 48 require.Nil(t, err, "err must be nil") 49 require.Equal(t, `{"age":12,"hello":"world"}`, body) 50 }) 51 52 t.Run("PUT", func(t *testing.T) { 53 54 }) 55 56 t.Run("DELETE", func(t *testing.T) { 57 58 }) 59 60 t.Run("OPTIONS", func(t *testing.T) { 61 62 }) 63 64 t.Run("HEAD", func(t *testing.T) { 65 66 }) 67 68 t.Run("TRACE", func(t *testing.T) { 69 70 }) 71 72 t.Run("PATCH", func(t *testing.T) { 73 74 }) 75 76 t.Run("CONNECT", func(t *testing.T) { 77 78 }) 79 } 80 81 func TestInterceptor(t *testing.T) { 82 } 83 84 func TestBody(t *testing.T) { 85 t.Run("json", func(t *testing.T) { 86 87 }) 88 t.Run("xml", func(t *testing.T) { 89 b, err := NewXmlBody(map[string]interface{}{"page": 1, "token": "abcd1234"}) 90 require.Nilf(t, err, "err must be nil, but got %s", err) 91 require.Equal(t, "text/xml", b.ContentType()) 92 buf := make([]byte, 100) 93 n, err := b.Read(buf) 94 require.Nil(t, err, "err must be nil") 95 require.Equal(t, "page=1&token=abcd1234", string(buf[:n])) 96 }) 97 t.Run("url-encoded", func(t *testing.T) { 98 b, err := NewUrlEncodedBody(url.Values{"page": []string{"1"}, "token": []string{"abcd1234"}}) 99 require.Nil(t, err, "err must be nil") 100 require.Equal(t, "application/x-www-form-urlencoded", b.ContentType()) 101 buf := make([]byte, 100) 102 n, err := b.Read(buf) 103 require.Nil(t, err, "err must be nil") 104 require.Equal(t, "page=1&token=abcd1234", string(buf[:n])) 105 }) 106 }