github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/httptransport/transformer/z_tsfm_xml_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/typesx" 15 ) 16 17 func TestXML(t *testing.T) { 18 type TestData struct { 19 Data struct { 20 Bool bool 21 FirstName string `xml:"name>first"` 22 StructSlice []struct { 23 Name string 24 } 25 StringSlice []string 26 StringAttrSlice []string `xml:"StringAttrSlice,attr"` 27 NestedSlice []struct { 28 Names []string 29 } 30 } 31 } 32 33 data := TestData{} 34 data.Data.FirstName = "test" 35 data.Data.StringSlice = []string{"1", "2", "3"} 36 data.Data.StringAttrSlice = []string{"1", "2", "3"} 37 38 ct, _ := DefaultFactory.NewTransformer( 39 bgctx, 40 typesx.FromReflectType(reflect.TypeOf(data)), 41 Option{MIME: "xml"}, 42 ) 43 44 t.Run("EncodeTo", func(t *testing.T) { 45 t.Run("RawValue", func(t *testing.T) { 46 b := bytes.NewBuffer(nil) 47 h := http.Header{} 48 err := ct.EncodeTo(bgctx, WriterWithHeader(b, h), data) 49 NewWithT(t).Expect(err).To(BeNil()) 50 NewWithT(t).Expect(h.Get(httpx.HeaderContentType)). 51 To(Equal("application/xml; charset=utf-8")) 52 }) 53 54 t.Run("ReflectValue", func(t *testing.T) { 55 b := bytes.NewBuffer(nil) 56 h := http.Header{} 57 err := ct.EncodeTo(bgctx, WriterWithHeader(b, h), reflect.ValueOf(data)) 58 NewWithT(t).Expect(err).To(BeNil()) 59 NewWithT(t).Expect(h.Get(httpx.HeaderContentType)). 60 To(Equal("application/xml; charset=utf-8")) 61 }) 62 }) 63 64 t.Run("DecodeAndValidate", func(t *testing.T) { 65 t.Run("FAILED", func(t *testing.T) { 66 b := bytes.NewBufferString("<") 67 err := ct.DecodeFrom(context.Background(), b, &data) 68 NewWithT(t).Expect(err).NotTo(BeNil()) 69 }) 70 71 t.Run("SUCCEED", func(t *testing.T) { 72 b := bytes.NewBufferString("<TestData></TestData>") 73 err := ct.DecodeFrom(context.Background(), b, reflect.ValueOf(&data)) 74 NewWithT(t).Expect(err).To(BeNil()) 75 }) 76 77 t.Run("FailedWithWrongType", func(t *testing.T) { 78 b := bytes.NewBufferString("<TestData><Data><Bool>bool</Bool></Data></TestData>") 79 err := ct.DecodeFrom(context.Background(), b, &data) 80 NewWithT(t).Expect(err).NotTo(BeNil()) 81 }) 82 }) 83 }