Skip to content

Commit

Permalink
Merge pull request #90 from punchio/bug_apply_variadic_method
Browse files Browse the repository at this point in the history
Bug apply variadic method
  • Loading branch information
agiledragon authored May 19, 2022
2 parents 92b9f21 + 0ee58aa commit 27d638f
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
9 changes: 7 additions & 2 deletions patch.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ package gomonkey

import (
"fmt"
"github.com/agiledragon/gomonkey/v2/creflect"
"reflect"
"syscall"
"unsafe"

"github.com/agiledragon/gomonkey/v2/creflect"
)

type Patches struct {
Expand Down Expand Up @@ -335,7 +336,11 @@ func funcToMethod(funcType reflect.Type, doubleFunc interface{}) reflect.Value {
}
vf := reflect.ValueOf(doubleFunc)
return reflect.MakeFunc(funcType, func(in []reflect.Value) []reflect.Value {
return vf.Call(in[1:])
if funcType.IsVariadic() {
return vf.CallSlice(in[1:])
} else {
return vf.Call(in[1:])
}
})
}

Expand Down
13 changes: 13 additions & 0 deletions test/apply_method_func_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,5 +82,18 @@ func TestApplyMethodFunc(t *testing.T) {
So(len(slice), ShouldEqual, 1)
So(slice[0], ShouldEqual, 4)
})

Convey("for variadic method", func() {
slice = fake.NewSlice()
count := slice.Append(1, 2, 3)
So(count, ShouldEqual, 3)
patches := ApplyMethodFunc(s, "Append", func(_ ...int) int {
return 0
})
defer patches.Reset()
count = slice.Append(4, 5, 6)
So(count, ShouldEqual, 0)
So(len(slice), ShouldEqual, 3)
})
})
}
6 changes: 6 additions & 0 deletions test/fake/fake.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,12 @@ func (this* Slice) Remove(elem int) error {
return nil
}

func (this *Slice) Append(elems ...int) int {
*this = append(*this, elems...)
fmt.Printf("Slice: Append elem: %v succ\n", elems)
return len(elems)
}

func ReadLeaf(url string) (string, error) {
output := fmt.Sprintf("%s, %s!", "Hello", "World")
return output, nil
Expand Down

0 comments on commit 27d638f

Please sign in to comment.