Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mocks for interfaces which return named nillable types do not have nil checks #22

Closed
spaowi opened this issue May 16, 2015 · 3 comments
Closed

Comments

@spaowi
Copy link

spaowi commented May 16, 2015

Example:

package main
type B interface {
  Bar()
}
type A interface {
  Get() B
}

Running mockery -name A -print on this does not yield a mock which checks for nil! The problem is that the B return type is parsed to an *ast.Ident, not an *ast.InterfaceType (and therefore isNillable returns false).

You can use the type of the identifier to handle this case, e.g.:

func (g *Generator) isNillable(typ ast.Expr) bool {
        switch t := typ.(type) {
        case *ast.StarExpr, *ast.ArrayType, *ast.MapType, *ast.InterfaceType, *ast.FuncType, *ast.ChanType:
                return true
        case *ast.Ident:
                switch d := t.Obj.Decl.(type) {
                case *ast.TypeSpec:
                        switch d.Type.(type) {
                        case *ast.StarExpr, *ast.ArrayType, *ast.MapType, *ast.InterfaceType, *ast.FuncType, *ast.ChanType:
                                return true
                        }
                }
        }
        return false
}
@dakiva
Copy link
Contributor

dakiva commented May 17, 2015

@spaowi Your example works for the case where the interface return type is in the same package as the interface being mocked. However, when the interface is an exported type, the returned interface is incorrectly parsed as a *ast.SelectorExpr. With the code above, generating a mock for bar.A will not yield a mock that checks for nil:

package foo

type B interface {
MyFunc()
}

package bar

import "foo"

type A interface {
Get() foo.B
}

@spaowi
Copy link
Author

spaowi commented May 17, 2015

Good point. I assume handling that case will require parsing imported packages.

@evanphx
Copy link
Member

evanphx commented May 18, 2015

There is another feature that requires parsing other imported packages, so perhaps mockery should parse them to pull in other interfaces...

@evanphx evanphx closed this as completed in 1011ca1 Apr 7, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants