github.com/blend/go-sdk@v1.20220411.3/r2/opt_xml_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/xml"
    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 TestOptXMLBody(t *testing.T) {
    22  	assert := assert.New(t)
    23  
    24  	r := New(TestURL, OptXMLBody(xmlTestCase{Status: "OK!"}))
    25  	assert.NotNil(r.Request.Body)
    26  
    27  	contents, err := io.ReadAll(r.Request.Body)
    28  	assert.Nil(err)
    29  	assert.Equal(47, r.Request.ContentLength)
    30  	assert.NotNil(r.Request.GetBody)
    31  	assert.Equal("<xmlTestCase><status>OK!</status></xmlTestCase>", string(contents))
    32  }
    33  
    34  func TestOptXMLBodyRedirect(t *testing.T) {
    35  	assert := assert.New(t)
    36  
    37  	finalServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
    38  		if r.ContentLength != 47 {
    39  			http.Error(rw, fmt.Sprintf("final; invalid content length: %d", r.ContentLength), http.StatusBadRequest)
    40  			return
    41  		}
    42  		var actualBody xmlTestCase
    43  		if err := xml.NewDecoder(r.Body).Decode(&actualBody); err != nil {
    44  			http.Error(rw, "final; invalid xml body", http.StatusBadRequest)
    45  			return
    46  		}
    47  		if actualBody.Status != "OK!" {
    48  			http.Error(rw, "final; invalid status", http.StatusBadRequest)
    49  			return
    50  		}
    51  		rw.WriteHeader(http.StatusOK)
    52  		fmt.Fprintf(rw, "OK!")
    53  	}))
    54  	defer finalServer.Close()
    55  
    56  	// we test the redirect to assert that the .GetBody function works as intended
    57  	redirectServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
    58  		if r.ContentLength != 47 {
    59  			http.Error(rw, fmt.Sprintf("redirect; invalid content length: %d", r.ContentLength), http.StatusBadRequest)
    60  			return
    61  		}
    62  		// http.StatusTemporaryRedirect necessary here so the body follows the redirect
    63  		http.Redirect(rw, r, finalServer.URL, http.StatusTemporaryRedirect)
    64  	}))
    65  	defer redirectServer.Close()
    66  
    67  	r := New(redirectServer.URL,
    68  		OptXMLBody(xmlTestCase{Status: "OK!"}),
    69  	)
    70  	assert.Equal(47, r.Request.ContentLength)
    71  	assert.NotNil(r.Request.Body)
    72  	assert.NotNil(r.Request.GetBody)
    73  
    74  	contents, meta, err := r.Bytes()
    75  	assert.Nil(err)
    76  	assert.Equal(http.StatusOK, meta.StatusCode, string(contents))
    77  }