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

     1  package transformer_test
     2  
     3  import (
     4  	"reflect"
     5  	"testing"
     6  
     7  	. "github.com/onsi/gomega"
     8  
     9  	. "github.com/machinefi/w3bstream/pkg/depends/kit/httptransport/transformer"
    10  	"github.com/machinefi/w3bstream/pkg/depends/x/ptrx"
    11  	"github.com/machinefi/w3bstream/pkg/depends/x/typesx"
    12  )
    13  
    14  type Sub struct {
    15  	A string `name:"a" in:"query"`
    16  }
    17  
    18  type PtrSub struct {
    19  	B []string `name:"b" in:"query"`
    20  }
    21  
    22  type P struct {
    23  	Sub
    24  	*PtrSub
    25  	C *string `name:"c" in:"query"`
    26  }
    27  
    28  func TestParameters(t *testing.T) {
    29  	params := make([]*Param, 0)
    30  
    31  	p := P{}
    32  	p.A = "a"
    33  	p.PtrSub = &PtrSub{B: []string{"b"}}
    34  	p.C = ptrx.String("c")
    35  
    36  	EachParameter(bgctx, typesx.FromReflectType(reflect.TypeOf(p)),
    37  		func(p *Param) bool {
    38  			params = append(params, p)
    39  			return true
    40  		},
    41  	)
    42  
    43  	rv := reflect.ValueOf(&p)
    44  
    45  	NewWithT(t).Expect(params).To(HaveLen(3))
    46  	NewWithT(t).Expect(params[0].FieldValue(rv).Interface()).To(Equal(p.A))
    47  	NewWithT(t).Expect(params[1].FieldValue(rv).Interface()).To(Equal(p.B))
    48  	NewWithT(t).Expect(params[2].FieldValue(rv).Interface()).To(Equal(p.C))
    49  }
    50  
    51  func BenchmarkParameter_FieldValue(b *testing.B) {
    52  	p := P{}
    53  	p.A = "a"
    54  	p.PtrSub = &PtrSub{
    55  		B: []string{"b"},
    56  	}
    57  	p.C = ptrx.String("c")
    58  
    59  	rv := reflect.ValueOf(&p).Elem()
    60  
    61  	params := make([]*Param, 0)
    62  
    63  	EachParameter(bgctx, typesx.FromReflectType(reflect.TypeOf(p)),
    64  		func(p *Param) bool {
    65  			params = append(params, p)
    66  			return true
    67  		},
    68  	)
    69  
    70  	b.Run("useCache", func(b *testing.B) {
    71  		for i := 0; i < b.N; i++ {
    72  			for i := range params {
    73  				_ = params[i].FieldValue(rv).Addr()
    74  			}
    75  		}
    76  	})
    77  
    78  	b.Run("WalkDirect", func(b *testing.B) {
    79  		var walk func(rv reflect.Value)
    80  
    81  		walk = func(rv reflect.Value) {
    82  			tpe := rv.Type()
    83  
    84  			for i := 0; i < rv.NumField(); i++ {
    85  				ft := tpe.Field(i)
    86  				f := rv.Field(i)
    87  
    88  				if ft.Anonymous && ft.Type.Kind() == reflect.Struct {
    89  					walk(f)
    90  				}
    91  			}
    92  		}
    93  
    94  		for i := 0; i < b.N; i++ {
    95  			walk(rv)
    96  		}
    97  	})
    98  }