github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/io/net/http/put_test.go (about)

     1  package http_test
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"io"
     7  	h "net/http"
     8  	"testing"
     9  
    10  	"github.com/jarcoal/httpmock"
    11  
    12  	"github.com/pkg/errors"
    13  	. "github.com/smartystreets/goconvey/convey"
    14  
    15  	"github.com/MontFerret/ferret/pkg/runtime/values"
    16  	"github.com/MontFerret/ferret/pkg/runtime/values/types"
    17  	"github.com/MontFerret/ferret/pkg/stdlib/io/net/http"
    18  )
    19  
    20  func TestPUT(t *testing.T) {
    21  	url := "https://api.montferret.io/users"
    22  
    23  	type User struct {
    24  		FirstName string `json:"first_name"`
    25  		LastName  string `json:"last_name"`
    26  	}
    27  
    28  	Convey("Should successfully make request", t, func() {
    29  		httpmock.Activate()
    30  		defer httpmock.DeactivateAndReset()
    31  
    32  		httpmock.RegisterResponder("PUT", url,
    33  			func(req *h.Request) (*h.Response, error) {
    34  				data, err := io.ReadAll(req.Body)
    35  
    36  				if err != nil {
    37  					return nil, err
    38  				}
    39  
    40  				user := User{}
    41  
    42  				err = json.Unmarshal(data, &user)
    43  
    44  				if err != nil {
    45  					return nil, err
    46  				}
    47  
    48  				if user.FirstName != "Rob" {
    49  					return nil, errors.Errorf("Expected FirstName to be Rob, but got %s", user.FirstName)
    50  				}
    51  
    52  				if user.LastName != "Pike" {
    53  					return nil, errors.Errorf("Expected LastName to be Pike, but got %s", user.LastName)
    54  				}
    55  
    56  				return httpmock.NewStringResponse(200, "OK"), nil
    57  			})
    58  
    59  		ctx := context.Background()
    60  
    61  		b, err := json.Marshal(User{
    62  			FirstName: "Rob",
    63  			LastName:  "Pike",
    64  		})
    65  
    66  		So(err, ShouldBeNil)
    67  
    68  		out, err := http.PUT(ctx, values.NewObjectWith(
    69  			values.NewObjectProperty("url", values.NewString(url)),
    70  			values.NewObjectProperty("body", values.NewBinary(b)),
    71  		))
    72  
    73  		So(err, ShouldBeNil)
    74  		So(out.Type().ID(), ShouldEqual, types.Binary.ID())
    75  		So(out.String(), ShouldEqual, "OK")
    76  	})
    77  }