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

     1  package http_test
     2  
     3  import (
     4  	"context"
     5  	h "net/http"
     6  	"testing"
     7  
     8  	"github.com/jarcoal/httpmock"
     9  
    10  	"github.com/pkg/errors"
    11  
    12  	"github.com/MontFerret/ferret/pkg/runtime/values"
    13  	"github.com/MontFerret/ferret/pkg/runtime/values/types"
    14  
    15  	. "github.com/smartystreets/goconvey/convey"
    16  
    17  	"github.com/MontFerret/ferret/pkg/stdlib/io/net/http"
    18  )
    19  
    20  func TestGET(t *testing.T) {
    21  	url := "https://api.montferret.io/users"
    22  
    23  	Convey("Should successfully make request", t, func() {
    24  		httpmock.Activate()
    25  		defer httpmock.DeactivateAndReset()
    26  
    27  		httpmock.RegisterResponder("GET", url,
    28  			func(req *h.Request) (*h.Response, error) {
    29  				return httpmock.NewStringResponse(200, "OK"), nil
    30  			})
    31  
    32  		ctx := context.Background()
    33  
    34  		out, err := http.GET(ctx, values.NewString(url))
    35  
    36  		So(err, ShouldBeNil)
    37  		So(out.Type().ID(), ShouldEqual, types.Binary.ID())
    38  		So(out.String(), ShouldEqual, "OK")
    39  	})
    40  
    41  	Convey("Should add headers to a request", t, func() {
    42  		httpmock.Activate()
    43  		defer httpmock.DeactivateAndReset()
    44  
    45  		httpmock.RegisterResponder("GET", url,
    46  			func(req *h.Request) (*h.Response, error) {
    47  				if req.Header.Get("X-Token") != "Ferret" {
    48  					return nil, errors.Errorf("Expected X-Token to be Ferret, but got %s", req.Header.Get("X-Token"))
    49  				}
    50  
    51  				if req.Header.Get("X-From") != "localhost" {
    52  					return nil, errors.Errorf("Expected X-From to be localhost, but got %s", req.Header.Get("X-From"))
    53  				}
    54  
    55  				return httpmock.NewStringResponse(200, "OK"), nil
    56  			})
    57  
    58  		ctx := context.Background()
    59  
    60  		out, err := http.GET(ctx, values.NewObjectWith(
    61  			values.NewObjectProperty("url", values.NewString(url)),
    62  			values.NewObjectProperty("headers", values.NewObjectWith(
    63  				values.NewObjectProperty("X-Token", values.NewString("Ferret")),
    64  				values.NewObjectProperty("X-From", values.NewString("localhost")),
    65  			)),
    66  		))
    67  
    68  		So(err, ShouldBeNil)
    69  		So(out.Type().ID(), ShouldEqual, types.Binary.ID())
    70  		So(out.String(), ShouldEqual, "OK")
    71  	})
    72  }