github.com/clubpay/ronykit/kit@v0.14.4-0.20240515065620-d0dace45cbc7/stub/stub_test.go (about)

     1  package stub_test
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  	"testing"
     7  
     8  	"github.com/clubpay/ronykit/kit"
     9  	"github.com/clubpay/ronykit/kit/stub"
    10  	. "github.com/onsi/ginkgo/v2"
    11  	. "github.com/onsi/gomega"
    12  )
    13  
    14  func TestStub(t *testing.T) {
    15  	RegisterFailHandler(Fail)
    16  	RunSpecs(t, "Stub Suite")
    17  }
    18  
    19  type ipInfoResponse struct {
    20  	IP       string `json:"ip"`
    21  	Hostname string `json:"hostname"`
    22  	City     string `json:"city"`
    23  	Readme   string `json:"readme"`
    24  	Timezone string `json:"timezone"`
    25  }
    26  
    27  var _ = Describe("Stub Basic Functionality", func() {
    28  	ctx := context.Background()
    29  
    30  	It("should unmarshal response from json", func() {
    31  		s := stub.New("ipinfo.io", stub.Secure())
    32  		httpCtx := s.REST().
    33  			SetMethod(http.MethodGet).
    34  			SetPath("/json").
    35  			SetQuery("someKey", "someValue").
    36  			DefaultResponseHandler(
    37  				func(_ context.Context, r stub.RESTResponse) *stub.Error {
    38  					switch r.StatusCode() {
    39  					case http.StatusOK:
    40  						v := &ipInfoResponse{}
    41  						Expect(kit.UnmarshalMessage(r.GetBody(), v)).To(Succeed())
    42  						Expect(v.Readme).To(Not(BeEmpty()))
    43  						Expect(v.IP).To(Not(BeEmpty()))
    44  					default:
    45  						Skip("we got error from ipinfo.io")
    46  					}
    47  
    48  					return nil
    49  				},
    50  			).
    51  			SetHeader("SomeKey", "SomeValue").
    52  			Run(ctx)
    53  		defer httpCtx.Release()
    54  
    55  		Expect(httpCtx.Err()).To(BeNil())
    56  	})
    57  })
    58  
    59  var _ = Describe("Stub from URL", func() {
    60  	ctx := context.Background()
    61  
    62  	It("should unmarshal response from json", func() {
    63  		httpCtx, err := stub.HTTP("https://ipinfo.io/json?someKey=someValue")
    64  		Expect(err).To(BeNil())
    65  		httpCtx.
    66  			SetMethod(http.MethodGet).
    67  			DefaultResponseHandler(
    68  				func(_ context.Context, r stub.RESTResponse) *stub.Error {
    69  					switch r.StatusCode() {
    70  					case http.StatusOK:
    71  						v := &ipInfoResponse{}
    72  						Expect(kit.UnmarshalMessage(r.GetBody(), v)).To(Succeed())
    73  						Expect(v.Readme).To(Not(BeEmpty()))
    74  						Expect(v.IP).To(Not(BeEmpty()))
    75  					default:
    76  						Skip("we got error from ipinfo.io")
    77  					}
    78  
    79  					return nil
    80  				},
    81  			).
    82  			SetHeader("SomeKey", "SomeValue").
    83  			Run(ctx)
    84  		defer httpCtx.Release()
    85  
    86  		Expect(httpCtx.Err()).To(BeNil())
    87  	})
    88  })