petergtz / pegomock

Pegomock is a powerful, yet simple mocking framework for the Go programming language
Apache License 2.0
252 stars 28 forks source link

Using `GetCapturedArguments()` on a variadic function with no variadic args causes a panic #87

Closed jpopadak closed 4 years ago

jpopadak commented 5 years ago

Yes, those arguments make zero sense, but it works to cause the issue we are seeing in real code. Source:

type InterfaceName interface {
    DoSomething(context.Context, ...context.Context)
}

Test:

//go:generate pegomock generate -m github.com/package/path InterfaceName

func TestInterfaceName(t *testing.T) {
    var interfaceMock health.InterfaceName = NewMockInterfaceName()
    interfaceMock.DoSomething(context.Background()) // Called with only one param

    mockInterfaceName := interfaceMock.(*MockInterfaceName)
    mockInterfaceName.VerifyWasCalledOnce().DoSomething(matchers.AnyContextContext()).GetCapturedArguments()
}

Turns out this is due to these generated lines always expecting at least 1 value passed into the variadic function: _param1 = make([][]context.Context, len(params[1])) The code does a length check, but does not check to see if the data inside the params > the number of arguments minus the number of variadic.

Generated code:

func (c *MockInterfaceName_DoSomething_OngoingVerification) GetAllCapturedArguments() (_param0 []context.Context, _param1 [][]context.Context) {
    params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations)
    if len(params) > 0 {
        _param0 = make([]context.Context, len(params[0]))
        for u, param := range params[0] {
            _param0[u] = param.(context.Context)
        }
        _param1 = make([][]context.Context, len(params[1]))
        for u := range params[0] {
            _param1[u] = make([]context.Context, len(params)-1)
            for x := 1; x < len(params); x++ {
                if params[x][u] != nil {
                    _param1[u][x-1] = params[x][u].(context.Context)
                }
            }
        }
    }
    return
}
petergtz commented 5 years ago

@jpopadak You're absolutely right, that's a bug. Thanks for troubleshooting this already. I'll see if I can fix this within the next days.

petergtz commented 5 years ago

@jpopadak Just pushed a change on develop. Could you have a look please? If it works, I'll merge it into master and make a new release.

petergtz commented 4 years ago

@jpopadak Please let me know in case you still have trouble with this. Otherwise, I'll consider this fixed and will release it to master sometime next week.

jpopadak commented 4 years ago

Looks like this was fixed with 2.7.0. Thanks! :)