github.com/agiledragon/gomonkey/v2@v2.11.1-0.20240427155748-d56c6823ec17/dsl/patch_builder.go (about) 1 package dsl 2 3 import ( 4 "fmt" 5 "reflect" 6 7 . "github.com/agiledragon/gomonkey/v2" 8 ) 9 10 type FuncPara struct { 11 target interface{} 12 constraints []Constraint 13 behaviors []Behavior 14 } 15 16 type PatchBuilder struct { 17 patches *Patches 18 funcPara FuncPara 19 } 20 21 func NewPatchBuilder(patches *Patches) *PatchBuilder { 22 funcPara := FuncPara{target: nil, constraints: make([]Constraint, 0), 23 behaviors: make([]Behavior, 0)} 24 return &PatchBuilder{patches: patches, funcPara: funcPara} 25 } 26 27 func (this *PatchBuilder) Func(target interface{}) *PatchBuilder { 28 this.funcPara.target = target 29 return this 30 } 31 32 func (this *PatchBuilder) Stubs() *PatchBuilder { 33 return this 34 } 35 36 func (this *PatchBuilder) With(matcher ...Constraint) *PatchBuilder { 37 this.funcPara.constraints = append(this.funcPara.constraints, matcher...) 38 return this 39 } 40 41 func (this *PatchBuilder) Will(behavior Behavior) *PatchBuilder { 42 this.funcPara.behaviors = append(this.funcPara.behaviors, behavior) 43 return this 44 } 45 46 func (this *PatchBuilder) Then(behavior Behavior) *PatchBuilder { 47 this.funcPara.behaviors = append(this.funcPara.behaviors, behavior) 48 return this 49 } 50 51 func (this *PatchBuilder) End() { 52 funcType := reflect.TypeOf(this.funcPara.target) 53 t := reflect.ValueOf(this.funcPara.target) 54 d := reflect.MakeFunc(funcType, func(inputs []reflect.Value) []reflect.Value { 55 matchers := this.funcPara.constraints 56 for i, input := range inputs { 57 if !matchers[i].Eval(input.Interface()) { 58 info := fmt.Sprintf("input paras %v is not matched", input.Interface()) 59 panic(info) 60 } 61 } 62 return GetResultValues(funcType, this.funcPara.behaviors[0].Apply()[0]...) 63 }) 64 this.patches.ApplyCore(t, d) 65 }