8000 AssignableToTypeOf panics on an untyped nil argument · Issue #316 · uber-go/mock · GitHub
[go: up one dir, main page]

Skip to content

AssignableToTypeOf panics on an untyped nil argument #316

Open

Description

@lenamonj

Actual behavior An expectation built with gomock.AssignableToTypeOf crashes the test binary the first time the code under test passes an untyped nil for that parameter. assignableToTypeOfMatcher.Matches calls reflect.TypeOf(x).AssignableTo(...), and reflect.TypeOf(nil) is a nil reflect.Type, so the call is a nil pointer dereference. This happens whenever the mocked parameter is an interface type, context.Context being the common case, and the caller passes nil.

Expected behavior The matcher reports no match, the way every other matcher answers a value it does not accept, and the failure surfaces as an unexpected call rather than a panic.

To Reproduce Steps to reproduce the behavior

  1. gomock.AssignableToTypeOf(reflect.TypeOf((*context.Context)(nil)).Elem()).Matches(nil)
  2. The call panics with invalid memory address or nil pointer dereference.

Three cases appended to TestAssignableToTypeOfMatcher in the branch below cover an untyped nil against an interface target and against a pointer target, and a typed nil *Dog, which still carries its type and still matches. They fail on main at d8c3a2a.

Additional Information

  • gomock mode (reflect or source): both, the failure is in gomock/matchers.go
  • gomock version or git ref: main at d8c3a2a
  • golang version: go1.26.2

Triage Notes for the Maintainers

I have a fix with the tests ready at https://github.com/lenamonj/mock/commit/7998f38d9174a6c217b7183f8882079b19153d37: a nil check on the reflect.Type returning false, and two doc lines on AssignableToTypeOf pointing at AnyOf(Nil(), AssignableToTypeOf(x)) for callers that want to accept a nil. Returning false keeps both behaviours expressible; a matcher that accepted nil itself would leave no way to say assignable and not nil. go vet, go build, ci/test.sh, ci/check_panic_handling.sh and the module tests pass on it. CONTRIBUTING asks for an issue before a pull request, so I am opening this first and will open the pull request if you want the change.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0