github.com/blend/go-sdk@v1.20220411.3/r2/opt_json_body_test.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package r2 9 10 import ( 11 "encoding/json" 12 "fmt" 13 "io" 14 "net/http" 15 "net/http/httptest" 16 "testing" 17 18 "github.com/blend/go-sdk/assert" 19 ) 20 21 func TestOptJSONBody(t *testing.T) { 22 assert := assert.New(t) 23 24 object := map[string]interface{}{"foo": "bar"} 25 26 opt := OptJSONBody(object) 27 28 req := New("https://foo.bar.local") 29 assert.Nil(opt(req)) 30 31 assert.NotNil(req.Request.Body) 32 33 contents, err := io.ReadAll(req.Request.Body) 34 assert.Nil(err) 35 assert.Equal(`{"foo":"bar"}`, string(contents)) 36 37 assert.Equal(ContentTypeApplicationJSON, req.Request.Header.Get("Content-Type")) 38 } 39 40 func TestOptJSONBodyRedirect(t *testing.T) { 41 assert := assert.New(t) 42 43 finalServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { 44 if r.ContentLength != 13 { 45 http.Error(rw, fmt.Sprintf("final; invalid content length: %d", r.ContentLength), http.StatusBadRequest) 46 return 47 } 48 var actualBody map[string]interface{} 49 if err := json.NewDecoder(r.Body).Decode(&actualBody); err != nil { 50 http.Error(rw, "final; invalid json body", http.StatusBadRequest) 51 return 52 } 53 if actualBody["foo"] != "bar" { 54 http.Error(rw, "final; invalid foo", http.StatusBadRequest) 55 return 56 } 57 rw.WriteHeader(http.StatusOK) 58 fmt.Fprintf(rw, "OK!") 59 })) 60 defer finalServer.Close() 61 62 // we test the redirect to assert that the .GetBody function works as intended 63 redirectServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { 64 if r.ContentLength != 13 { 65 http.Error(rw, fmt.Sprintf("redirect; invalid content length: %d", r.ContentLength), http.StatusBadRequest) 66 return 67 } 68 // http.StatusTemporaryRedirect necessary here so the body follows the redirect 69 http.Redirect(rw, r, finalServer.URL, http.StatusTemporaryRedirect) 70 })) 71 defer redirectServer.Close() 72 73 jsonObject := map[string]interface{}{"foo": "bar"} 74 75 r := New(redirectServer.URL, 76 OptJSONBody(jsonObject), 77 ) 78 assert.Equal(13, r.Request.ContentLength) 79 assert.NotNil(r.Request.Body) 80 assert.NotNil(r.Request.GetBody) 81 82 contents, meta, err := r.Bytes() 83 assert.Nil(err) 84 assert.Equal(http.StatusOK, meta.StatusCode, string(contents)) 85 }