github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/httptransport/transformer/z_tsfm_urlencoded_test.go (about)

     1  package transformer_test
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"net/http"
     7  	"reflect"
     8  	"testing"
     9  
    10  	. "github.com/onsi/gomega"
    11  
    12  	"github.com/machinefi/w3bstream/pkg/depends/kit/httptransport/httpx"
    13  	. "github.com/machinefi/w3bstream/pkg/depends/kit/httptransport/transformer"
    14  	"github.com/machinefi/w3bstream/pkg/depends/x/ptrx"
    15  	"github.com/machinefi/w3bstream/pkg/depends/x/typesx"
    16  )
    17  
    18  func TestURLEncoded(t *testing.T) {
    19  	queries := `Bool=true` +
    20  		`&Bytes=Ynl0ZXM%3D` +
    21  		`&PtrInt=1` +
    22  		`&StringArray=1&StringArray=&StringArray=3` +
    23  		`&StringSlice=1&StringSlice=2&StringSlice=3` +
    24  		`&Struct=%3CSub%3E%3CName%3E%3C%2FName%3E%3C%2FSub%3E` +
    25  		`&StructSlice=%7B%22Name%22%3A%22name%22%7D%0A` +
    26  		`&first_name=test`
    27  
    28  	type Sub struct{ Name string }
    29  
    30  	type TestData struct {
    31  		PtrBool     *bool `name:",omitempty"`
    32  		PtrInt      *int
    33  		Bool        bool
    34  		Bytes       []byte
    35  		FirstName   string `name:"first_name"`
    36  		StructSlice []Sub
    37  		StringSlice []string
    38  		StringArray [3]string
    39  		Struct      Sub `mime:"xml"`
    40  	}
    41  
    42  	data := TestData{}
    43  	data.FirstName = "test"
    44  	data.Bool = true
    45  	data.Bytes = []byte("bytes")
    46  	data.PtrInt = ptrx.Int(1)
    47  	data.StringSlice = []string{"1", "2", "3"}
    48  	data.StructSlice = []Sub{{Name: "name"}}
    49  	data.StringArray = [3]string{"1", "", "3"}
    50  
    51  	tsf, _ := DefaultFactory.NewTransformer(
    52  		bgctx,
    53  		typesx.FromReflectType(reflect.TypeOf(data)),
    54  		Option{MIME: "urlencoded"},
    55  	)
    56  
    57  	t.Run("EncodeTo", func(t *testing.T) {
    58  		b := bytes.NewBuffer(nil)
    59  		h := http.Header{}
    60  
    61  		err := tsf.EncodeTo(bgctx, WriterWithHeader(b, h), data)
    62  
    63  		NewWithT(t).Expect(err).To(BeNil())
    64  		NewWithT(t).Expect(h.Get(httpx.HeaderContentType)).
    65  			To(Equal("application/x-www-form-urlencoded; param=value"))
    66  		NewWithT(t).Expect(b.String()).To(Equal(queries))
    67  	})
    68  
    69  	t.Run("DecodeAndValidate", func(t *testing.T) {
    70  		b := bytes.NewBufferString(queries)
    71  		td := TestData{}
    72  
    73  		err := tsf.DecodeFrom(context.Background(), b, &td)
    74  		NewWithT(t).Expect(err).To(BeNil())
    75  		NewWithT(t).Expect(td).To(Equal(data))
    76  	})
    77  }