template

package
v3.5.2 Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2025 License: BSD-3-Clause Imports: 15 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 Data. Attributes of this struct can be accessed using syntax like:

package {{.PkgName}}

import (
{{- range .Imports}}
	{{. | importStatement}}
{{- end}}
    mock "github.com/stretchr/testify/mock"
)

Further 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

Overview

Package template provides data and functionality for rendering templates using mockery. The data and methods herein are guaranteed to be backwards compatible, as they are used directly by user-defined Go templates. It is safe to import or use this package for any purpose.

Index

Constants

This section is empty.

Variables

View Source
var ErrTemplateDataSchemaValidation = errors.New("unable to verify template-data schema")

Functions

This section is empty.

Types

type Comment added in v3.1.0

type Comment string

Comment represents a single line of comments exactly as it appears in source. This includes the "//" or "/*" strings if present.

type CommentGroup added in v3.1.0

type CommentGroup struct {
	// List contains each individual line of the comments exactly as they appear
	// in source, including comment characters.
	List []Comment
	// Text contains the text of the comments without comment characters.
	Text string
}

func NewCommentGroupFromAST added in v3.1.0

func NewCommentGroupFromAST(comments *ast.CommentGroup) CommentGroup

type Comments added in v3.1.0

type Comments struct {
	/*
		GenDeclDoc represents the doc comments for a general declaration.
		For example, if you were to define an interface with the following comments:

		// Foo defines Bar
		type Foo interface {
			Bar() string
		}

		then GenDeclDoc will contain the "// Foo defines Bar" comment.
		Similarly, if you define your interface like:

		// hello world
		type (
			// Foo defines Bar
			Foo interface {
				Bar() string
			}
		)

		then GenDeclDoc will contain the "// hello world" comment.
	*/
	GenDeclDoc CommentGroup
	/*
		TypeSpecComment contains in-line comments for a type spec.
		For example:

		type Foo interface {
			Bar() string
		} // This is a line comment
	*/
	TypeSpecComment CommentGroup

	/*
		TypeSpecDoc contains the docs for a type spec.
		For example:

		type (
			// Foo defines Bar
			Foo interface {
				Bar() string
			}
		)

		TypeSpecDoc will _not_ contain the comments defined like this:

		// Foo defines Bar
		type Foo interface {
			Bar() string
		}

		The reason is because the Go AST defines this as a comment on an *ast.GenDecl, not an *ast.TypeSpec.
	*/
	TypeSpecDoc CommentGroup
}

func NewComments added in v3.1.0

func NewComments(typeSpec *ast.TypeSpec, genDecl *ast.GenDecl) Comments

type Data

type Data struct {
	// PkgName is the name of the package chosen for the template.
	PkgName string
	// Registry chiefly maintains the list of imports that are required in the
	// rendered template file.
	Registry *Registry
	// SrcPkgQualifier is the qualifier used for the source package, if any.
	// For example, if the source package is different from the package the template
	// is rendered into, this string will contain something like "foo.", where
	// "foo" is the alias or package name of the source package.
	SrcPkgQualifier string
	// Interfaces is the list of interfaces being rendered in the template.
	Interfaces Interfaces
	// TemplateData is a schemaless map containing parameters from configuration
	// you may consume in your template.
	TemplateData TemplateData
}

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

func NewData

func NewData(
	pkgName string,
	srcPkgQualifier string,
	imports Packages,
	interfaces Interfaces,
	templateData TemplateData,
	registry *Registry,
) Data

func (Data) Imports

func (d Data) Imports() Packages

type Interface

type Interface struct {
	Comments Comments
	Methods  []Method
	// Name is the name of the original interface.
	Name string
	// StructName is the chosen name for the struct that will implement the interface.
	StructName   string
	TemplateData TemplateData
	TypeParams   []TypeParam
}

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

func NewInterface added in v3.1.0

func NewInterface(
	name string,
	structName string,
	typeParams []TypeParam,
	methods []Method,
	templateData TemplateData,
	comments Comments,
) Interface

func (Interface) TypeConstraint

func (m Interface) TypeConstraint() string

func (Interface) TypeConstraintTest

func (m Interface) TypeConstraintTest() string

func (Interface) TypeInstantiation

func (m Interface) TypeInstantiation() string

type Interfaces

type Interfaces []Interface

func (Interfaces) ImplementsSomeMethod

func (m Interfaces) ImplementsSomeMethod() bool

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

type Method

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

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

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

	// 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
}

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

func (Method) AcceptsContext

func (m Method) AcceptsContext() bool

AcceptsContext returns whether or not the first argument of the method is a context.Context.

func (Method) ArgCallList

func (m Method) 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 (Method) ArgCallListNoEllipsis

func (m Method) ArgCallListNoEllipsis() string

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

func (Method) ArgCallListSlice

func (m Method) 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 (Method) ArgCallListSliceNoEllipsis

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

func (Method) ArgList

func (m Method) ArgList() string

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

func (Method) ArgListNoName added in v3.2.0

func (m Method) ArgListNoName() string

ArgListNoName is the same as ArgList except the argument names are not included.

func (Method) ArgTypeList

func (m Method) ArgTypeList() string

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

func (Method) ArgTypeListEllipsis

func (m Method) 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 (Method) Call

func (m Method) Call() string

Call returns a string containing the method call. This will usually need to be prefixed with a selector to specify which actual method to call. For example, if the method has a signature of "func Foo(s string) error", this method will return the string "Foo(s)". The name of each argument variable will be the same as what was generated post collision-resolution. Meaning, the argument variable name might be slightly altered from the original function if a naming collision was found.

func (Method) Declaration

func (m Method) Declaration() string

Declaration returns the method name followed by its signature. For example, if a method was declared as "func (b Bar) Foo(s string) error", this method will return "Foo(s string) error"

func (Method) HasParams

func (m Method) HasParams() bool

func (Method) HasReturns

func (m Method) HasReturns() bool

func (Method) IsVariadic

func (m Method) IsVariadic() bool

func (Method) ReturnArgList

func (m Method) ReturnArgList() string

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

func (Method) ReturnArgListNoName added in v3.2.0

func (m Method) ReturnArgListNoName() string

ReturnArgListNoName is the same as ReturnArgList except the return argument names are not included.

func (Method) ReturnArgNameList

func (m Method) ReturnArgNameList() string

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

func (Method) ReturnArgTypeList

func (m Method) ReturnArgTypeList() string

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

func (Method) ReturnStatement

func (m Method) ReturnStatement() string

ReturnStatement returns the string "return" if a method has return values. Otherwise, it returns an empty string.

func (Method) ReturnsError

func (m Method) ReturnsError() bool

func (Method) Signature

func (m Method) Signature() string

Signature returns the string representation of the method's signature. For example, if a method was declared as "func (b Bar) Foo(s string) error", this method will return "(s string) error"

func (Method) SignatureNoName added in v3.2.0

func (m Method) SignatureNoName() string

SignatureNoName is the same as Signature except the argument and return parameter names are not included.

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 method does not check for naming collisions, and consequently will not modify the given name in any way. It's recommended that you first check MethodScope.NameExists to determine if the name has any collisions, or use MethodScope.AllocateName.

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.

This method is not meant to be used directly by templates.

func (*MethodScope) AllocateName

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

AllocateName creates a new variable name in the lexical scope of the method. The name is guaranteed to not collide with any other existing names at the time of the call. It automatically allocates the name to the current scope. Returned is the name post collision resolution.

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)

ResolveVariableNameCollisions modifies argument names if they are found to collide with any other names visible to the scope.

This method is not meant to be used directly by templates.

func (*MethodScope) SuggestName

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

SuggestName 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. This method does _not_ register the returned name suggestion in the scope, which must separately be done by `MethodScope.AddName`.

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) ImportStatement

func (p *Package) ImportStatement() string

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 Packages

type Packages []*Package

func (Packages) PkgQualifier

func (p Packages) PkgQualifier(pkgPath string) (string, error)

PkgQualifier returns the qualifier for the given pkgPath. If the pkgPath does not exist in the container, an error is returned.

type Param

type Param struct {
	Var      *Var
	Variadic bool
}

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

func (Param) CallName

func (p Param) 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 (Param) MethodArg

func (p Param) MethodArg() string

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

func (Param) MethodArgNoName added in v3.2.0

func (p Param) MethodArgNoName() string

MethodArgNoName is the same as MethodArg except the argument name is not included.

func (Param) Name

func (p Param) Name() string

Name returns the name of the parameter.

func (Param) TypeString

func (p Param) TypeString() string

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

func (Param) TypeStringEllipsis

func (p Param) 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 (Param) TypeStringVariadicUnderlying

func (p Param) 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(pkgName string, pkgPath string) *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. pkgName must be set to the unaliased package name.

func (Registry) Imports

func (r Registry) Imports() Packages

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 represents the template requested for rendering.

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 TemplateData

type TemplateData map[string]any

func (TemplateData) VerifyJSONSchema

func (t TemplateData) VerifyJSONSchema(ctx context.Context, schema *gojsonschema.Schema) error

VerifyJSONSchema verifies that the contents of the type adhere to the schema defined by the schema argument.

This method is not meant to be used directly by templates.

type TypeParam

type TypeParam struct {
	Param
	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