template

package
v3.0.0-alpha.21 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 20, 2025 License: BSD-3-Clause Imports: 13 Imported by: 0

README

Template

This package contains all of the data passed to mockery templates. The top-most variable provided to the templates is MockData. Examples of how to use the data provided to mockery templates can be found in the pre-curated mocks, such as:

Full documentation is provided at: https://vektra.github.io/mockery/v3/

Documentation

Index

Constants

This section is empty.

Variables

View Source
var TemplateMockFuncs = template.FuncMap{
	"importStatement": func(imprt *Package) string {
		if imprt.Alias == "" {
			return `"` + imprt.Path() + `"`
		}
		return imprt.Alias + ` "` + imprt.Path() + `"`
	},
	"syncPkgQualifier": func(imports []*Package) string {
		for _, imprt := range imports {
			if imprt.Path() == "sync" {
				return imprt.Qualifier()
			}
		}

		return "sync"
	},
	"exported": exported,

	"mocksSomeMethod": func(mocks []MockData) bool {
		for _, m := range mocks {
			if len(m.Methods) > 0 {
				return true
			}
		}

		return false
	},
	"typeConstraintTest": func(m MockData) string {
		if len(m.TypeParams) == 0 {
			return ""
		}
		s := "["
		for idx, param := range m.TypeParams {
			if idx != 0 {
				s += ", "
			}
			s += exported(param.Name())
			s += " "
			s += param.TypeString()
		}
		s += "]"
		return s
	},
	"readFile": func(path string) string {
		if path == "" {
			return ""
		}
		fileBytes, err := os.ReadFile(path)
		if err != nil {
			panic(err.Error())
		}
		return string(fileBytes)
	},
}

Functions

This section is empty.

Types

type Data

type Data struct {
	PkgName         string
	SrcPkgQualifier string
	Imports         []*Package
	Mocks           []MockData
	TemplateData    map[string]any
}

Data is the template data used to render the mock template.

func (Data) MocksSomeMethod

func (d Data) MocksSomeMethod() bool

MocksSomeMethod returns true of any one of the Mocks has at least 1 method.

type MethodData

type MethodData struct {
	// Name is the method's name.
	Name string

	// Params represents all the arguments to the method.
	Params []ParamData

	// Returns represents all the return parameters of the method.
	Returns []ParamData

	// Scope represents the lexical scope of the method. Its primary function
	// is keeping track of all names visible in the current scope, which allows
	// the creation of new variables with guaranteed non-conflicting names.
	Scope *MethodScope
}

MethodData is the data which represents a method on some interface.

func (MethodData) ArgCallList

func (m MethodData) ArgCallList() string

ArgCallList is the string representation of method call parameters, ex: 's, n, foo'. In case of a last variadic parameter, it will be of the format 's, n, foos...'.

func (MethodData) ArgCallListNoEllipsis

func (m MethodData) ArgCallListNoEllipsis() string

ArgCallListNoEllipsis is the same as ArgCallList, except the last parameter, if variadic, will not contain an ellipsis.

func (MethodData) ArgCallListSlice

func (m MethodData) ArgCallListSlice(start, end int) string

argCallListSlice is similar to ArgCallList, but it allows specification of a slice range to use for the parameter lists. Specifying an integer less than 1 for end indicates to slice to the end of the parameters. As with regular Go slicing semantics, the end value is a non-inclusive index.

func (MethodData) ArgCallListSliceNoEllipsis

func (m MethodData) ArgCallListSliceNoEllipsis(start, end int) string

func (MethodData) ArgList

func (m MethodData) ArgList() string

ArgList is the string representation of method parameters, ex: 's string, n int, foo bar.Baz'.

func (MethodData) ArgTypeList

func (m MethodData) ArgTypeList() string

ArgTypeList returns the argument types in a comma-separated string, ex: `string, int, bar.Baz`

func (MethodData) ArgTypeListEllipsis

func (m MethodData) ArgTypeListEllipsis() string

ArgTypeListEllipsis returns the argument types in a comma-separated string, ex: `string, int, bar.Baz`. If the last argument is variadic, it will contain an ellipsis as would be expected in a variadic function definition.

func (MethodData) IsVariadic

func (m MethodData) IsVariadic() bool

func (MethodData) ReturnArgList

func (m MethodData) ReturnArgList() string

ReturnArgList returns the name and types of the return values. For example: "foo int, bar string, err error"

func (MethodData) ReturnArgNameList

func (m MethodData) ReturnArgNameList() string

ReturnArgNameList is the string representation of values being returned from the method, ex: 'foo', 's, err'.

func (MethodData) ReturnArgTypeList

func (m MethodData) ReturnArgTypeList() string

ReturnArgTypeList is the string representation of method return types, ex: 'bar.Baz', '(string, error)'.

type MethodScope

type MethodScope struct {
	// contains filtered or unexported fields
}

MethodScope is the sub-registry for allocating variables present in the method scope.

It should be created using a registry instance.

func NewMethodScope

func NewMethodScope(r *Registry) *MethodScope

func (*MethodScope) AddName

func (m *MethodScope) AddName(name string)

AddName records name as visible in the current scope. This may be useful in cases where a template statically adds its own name that needs to be registered with the scope to prevent future naming collisions.

func (*MethodScope) AddVar

func (m *MethodScope) AddVar(ctx context.Context, vr *types.Var, prefix string, replacement *config.ReplaceType) (*Var, error)

AddVar allocates a variable instance and adds it to the method scope.

Variables names are generated if required and are ensured to be without conflict with other variables and imported packages. It also adds the relevant imports to the registry for each added variable.

func (*MethodScope) AllocateName

func (m *MethodScope) AllocateName(prefix string) string

AllocateName creates a new variable name in the lexical scope of the method. It ensures the returned name does not conflict with any other name visible to the scope. It registers the returned name in the lexical scope such that its exact value can never be allocated again.

func (*MethodScope) NameExists

func (m *MethodScope) NameExists(name string) bool

NameExists returns whether or not the name is currently visible in the scope.

func (*MethodScope) ResolveVariableNameCollisions

func (m *MethodScope) ResolveVariableNameCollisions(ctx context.Context)

type MockData

type MockData struct {
	InterfaceName string
	MockName      string
	TypeParams    []TypeParamData
	Methods       []MethodData
	TemplateData  map[string]any
}

MockData is the data used to generate a mock for some interface.

func (MockData) TypeConstraint

func (m MockData) TypeConstraint() string

func (MockData) TypeInstantiation

func (m MockData) TypeInstantiation() string

type Package

type Package struct {
	Alias string
	// contains filtered or unexported fields
}

Package represents an imported package.

func NewPackage

func NewPackage(pkg TypesPackage) *Package

NewPackage creates a new instance of Package.

func (*Package) Path

func (p *Package) Path() string

Path is the full package import path (without vendor).

func (*Package) Qualifier

func (p *Package) Qualifier() string

Qualifier returns the qualifier which must be used to refer to types declared in the package.

type ParamData

type ParamData struct {
	Var      *Var
	Variadic bool
}

ParamData is the data which represents a parameter to some method of an interface.

func (ParamData) CallName

func (p ParamData) CallName(ellipsis bool) string

CallName returns the string representation of the parameter to be used for a method call. For a variadic paramter, it will be of the format 'foos...' if ellipsis is true.

func (ParamData) MethodArg

func (p ParamData) MethodArg() string

MethodArg is the representation of the parameter in the function signature, ex: 'name a.Type'.

func (ParamData) Name

func (p ParamData) Name() string

Name returns the name of the parameter.

func (ParamData) TypeString

func (p ParamData) TypeString() string

TypeString returns the string representation of the type of the parameter.

func (ParamData) TypeStringEllipsis

func (p ParamData) TypeStringEllipsis() string

TypeStringEllipsis returns the string representation of the type of the parameter. If it is a variadic parameter, it will be represented as a variadic parameter instead of a slice. For example instead of `[]string`, it will return `...string`.

func (ParamData) TypeStringVariadicUnderlying

func (p ParamData) TypeStringVariadicUnderlying() string

TypeStringVariadicUnderlying returns the underlying type of a variadic parameter. For instance, if a function has a parameter defined as `foo ...int`, this function will return "int". If the parameter is not variadic, this will behave the same as `TypeString`.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry encapsulates types information for the source and mock destination package. For the mock package, it tracks the list of imports and ensures there are no conflicts in the imported package qualifiers.

func NewRegistry

func NewRegistry(srcPkg *packages.Package, dstPkgPath string, inPackage bool) (*Registry, error)

New loads the source package info and returns a new instance of Registry.

func (*Registry) AddImport

func (r *Registry) AddImport(ctx context.Context, pkg TypesPackage) *Package

AddImport adds the given package to the set of imports. It generates a suitable alias if there are any conflicts with previously imported packages.

func (Registry) Imports

func (r Registry) Imports() []*Package

Imports returns the list of imported packages. The list is sorted by path.

func (Registry) LookupInterface

func (r Registry) LookupInterface(name string) (*types.Interface, *types.TypeParamList, error)

LookupInterface returns the underlying interface definition of the given interface name.

func (*Registry) MethodScope

func (r *Registry) MethodScope() *MethodScope

MethodScope returns a new MethodScope.

func (Registry) SrcPkg

func (r Registry) SrcPkg() *packages.Package

func (Registry) SrcPkgName

func (r Registry) SrcPkgName() string

SrcPkgName returns the name of the source package.

type Template

type Template struct {
	// contains filtered or unexported fields
}

Template is the Moq template. It is capable of generating the Moq implementation for the given template.Data.

func New

func New(templateString string, name string) (Template, error)

New returns a new instance of Template.

func (Template) Execute

func (t Template) Execute(w io.Writer, data Data) error

Execute generates and writes the Moq implementation for the given data.

type TypeParamData

type TypeParamData struct {
	ParamData
	Constraint types.Type
}

type TypesPackage

type TypesPackage interface {
	Name() string
	Path() string
}

type Var

type Var struct {
	Name string
	// contains filtered or unexported fields
}

Var represents a method variable/parameter.

It should be created using a method scope instance.

func (Var) IsSlice

func (v Var) IsSlice() bool

IsSlice returns whether the type (or the underlying type) is a slice.

func (Var) Nillable

func (v Var) Nillable() bool

func (Var) Type

func (v Var) Type() types.Type

func (Var) TypeString

func (v Var) TypeString() string

TypeString returns the variable type with the package qualifier in the format 'pkg.Type'.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL