mock

package
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2024 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package mock provides the classes and tools of the advanced mock generator that nicely integrate with the testing framework.

Index

Constants

View Source
const (
	// Default mock file name.
	MockFileDefault = "mock_all_test.go"

	// Exit code for success.
	ExitSuccess = 0
	// Exit code for parse error.
	ExitParseError = 1
	// Exit code for write error.
	ExitWriteError = 2
)
View Source
const (
	// Default directory for package loading.
	DirDefault = "."
	// Magic constant defining packages read from file.
	ReadFromFile = "command-line-arguments"
	// Default value of mock interface name pattern.
	MockPatternDefault = "Mock*"
	// Default value of interface regex matching pattern.
	MatchPatternDefault = ".*"
)

Variables

View Source
var (
	ImportReflect = &Import{
		Alias: "reflect", Path: "reflect",
	}
	ImportGomock = &Import{
		Alias: "gomock", Path: "github.com/golang/mock/gomock",
	}
	ImportMock = &Import{
		Alias: "mock", Path: "github.com/tkrop/go-testing/mock",
	}
	ImportsTemplate = []*Import{
		ImportReflect, ImportGomock, ImportMock,
	}

	MockFileFuncMap = template.FuncMap{
		"ImportsList": importArgs,
		"ParamArgs":   paramArgs,
		"ResultArgs":  resultArgs,
		"CallArgs":    callArgs,
		"ConvertArgs": convertArgs,
	}

	MockFileTemplate = `` /* 2250-byte string literal not displayed */

)
View Source
var ErrAliasConflict = errors.New("alias conflict")
View Source
var ErrArgFailure = errors.New("argument failure")
View Source
var ErrArgInvalid = errors.New("argument invalid")
View Source
var ErrFileOpening = errors.New("file opening")
View Source
var ErrFileWriting = errors.New("file writing")
View Source
var ErrIllegalImport = errors.New("illegal import")
View Source
var ErrLoading = errors.New("loading")
View Source
var ErrMatcherInvalid = errors.New("matcher invalid")
View Source
var ErrNoIFace = errors.New("no interface")
View Source
var ErrNoNameType = errors.New("no name type")
View Source
var ErrNotFound = errors.New("not found")
View Source
var ErrPackageParsing = errors.New("package parsing")
View Source
var TargetDefault = &Type{File: MockFileDefault}

TargetDefault provides the default target setup for the parser.

Functions

func NewErrAliasConflict

func NewErrAliasConflict(imprt *Import, path string) error

func NewErrArgFailure

func NewErrArgFailure(pos int, arg string, err error) error

func NewErrArgInvalid

func NewErrArgInvalid(pos int, arg string) error

func NewErrArgNotFound

func NewErrArgNotFound(pos int, arg string) error

func NewErrFileOpening

func NewErrFileOpening(path string, err error) error

func NewErrFileWriting

func NewErrFileWriting(file *File, err error) error

func NewErrIllegalImport

func NewErrIllegalImport(imprt *Import) error

func NewErrLoading

func NewErrLoading(path string, err error) error

func NewErrMatcherInvalid

func NewErrMatcherInvalid(source *Type, err error) error

func NewErrNoIFace

func NewErrNoIFace(source *Type, name string) error

func NewErrNoNameType

func NewErrNoNameType(source *Type, name string) error

func NewErrNotFound

func NewErrNotFound(source *Type, name string) error

func NewErrPackageParsing

func NewErrPackageParsing(path string, pkgs []*packages.Package) error

func NewTemplate

func NewTemplate() (Template, []*Import, error)

NewTemplate creates a new mock template.

func ToAny

func ToAny(atype string) string

ToAny substitutes all `interfaces{}` types against the `any` type.

Types

type CachedLoader

type CachedLoader struct {
	// Configuration for package loading.
	Config *packages.Config
	// contains filtered or unexported fields
}

CachedLoader allows to efficient load, parse, and analyze packages as well as interfaces. The loaded packages are chached by request path for repeated access and analyzing. The loader is safe to be used concurrently.

func (*CachedLoader) IFaces

func (loader *CachedLoader) IFaces(source *Type) ([]*IFace, error)

IFaces looks up the go-packages for the given source and extracts the interfaces matching the naming pattern and the file.

func (*CachedLoader) Load

func (loader *CachedLoader) Load(path string) *PkgResponse

Load loads the go-packages for the given path and caching them for repeated requests. The details provided by the package information depend on the configuration. By default only types and names are loaded.

func (*CachedLoader) Search

func (loader *CachedLoader) Search(source *Type) *PkgResponse

Search searches the go-packages with the given partial source type, either using the provided file path or the provided package path information. The file path is normalized assuming that any non-existing final part is a base file name that should be removed for package loading.

type File

type File struct {
	// Target file information.
	Target *Type
	// Common import data.
	Imports []*Import
	// Mock interface data.
	Mocks []*Mock
	// Writer used for file output.
	Writer *os.File
}

File information.

func NewFiles

func NewFiles(mocks []*Mock, imports ...*Import) []*File

NewFiles creates a list of new mock files from the given set of mocks and given set of default imports to consider for applying for the template using the mocks target information to collect all mocks that should be written to the same file.

func (*File) Close

func (file *File) Close() error

Close closes the file descriptor for writing.

func (*File) Open

func (file *File) Open(stdout *os.File) error

Open opens a file descriptor for writing.

func (*File) Write

func (file *File) Write(temp Template) error

Write writes the mocks using the given template to the file target.

type FileBuilder

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

FileBuilder is used to collect the mock file information used as input for the mock generator to create the mock source file using the template.

func NewFileBuilder

func NewFileBuilder(target *Type) *FileBuilder

NewFileBuilder creates a new file builder.

func (*FileBuilder) AddImports

func (b *FileBuilder) AddImports(imports ...*Import) *FileBuilder

AddImports adds a slice of imports to the file. If an import is matching the target import path, the alias is forcefully removed for this import.

func (*FileBuilder) AddMocks

func (b *FileBuilder) AddMocks(mock ...*Mock) *FileBuilder

AddMocks adds a slice of mocks to the file.

func (*FileBuilder) Build

func (b *FileBuilder) Build() *File

Build builds the actual file information.

type Generator

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

Generator for mocks.

func NewGenerator

func NewGenerator(dir string, target *Type) *Generator

NewGenerator creates a new mock generator with given default context directory and default target setup.

func (*Generator) Generate

func (gen *Generator) Generate(stdout, stderr *os.File, args ...string) int

Generate creates the mock files defined by the command line arguments.

type IFace

type IFace struct {
	// Source interface information.
	Source *Type
	// Methods of source/target interface.
	Methods []*Method
}

IFace contains interface information.

func NewIFace

func NewIFace(source *Type, iface *types.Interface) *IFace

NewIFace creats a new interface information using given definition.

type Import

type Import struct {
	// Alias name of import.
	Alias string
	// Path name of full import.
	Path string
}

Import information.

type Loader

type Loader interface {
	// Search searches the go-packages with the given partial source type,
	// either using the provided file path or the provided package path
	// information. The file path is normalized assuming that any non-existing
	// final part is a base file name that should be removed for package
	// loading.
	Search(source *Type) *PkgResponse
	// Load loads the go-packages for the given package path. The details
	// depend on the backing package loader and its configuration.
	Load(path string) *PkgResponse
	// IFaces looks up the go-packages for the given source and extracts
	// the interfaces matching the naming pattern and the file.
	IFaces(source *Type) ([]*IFace, error)
}

Loader is the generic interface of the package and interface loader.

func NewLoader

func NewLoader(dir string) Loader

NewLoader creates a new caching package loader, that allows efficient access to types from files and packages. By default it provides also access to the test packages and searches these for interfaces. To disable you need to set `loader.(*CachingLoader).Config.Tests` to `false`.

type Method

type Method struct {
	// Name of method.
	Name string
	// Method arguments.
	Params []*Param
	// Method results.
	Results []*Param
	// Flag whether last argument is variadic.
	Variadic bool
}

Method provides the method information.

func NewMethods

func NewMethods(iface *types.Interface) []*Method

NewMethods creates a new method slice containing all methods of the given interface type.

type Mock

type Mock struct {
	// Source interface information.
	Source *Type
	// Target interface information.
	Target *Type
	// Methods of source/target interface.
	Methods []*Method
}

Mock interface information.

type Param

type Param struct {
	// Method parameter.
	Name string
	// Method type.
	Type string
}

Param provides method parameters.

func NewParams

func NewParams(tuple *types.Tuple) []*Param

NewParams creates a new parameter slice based on the given tuple providing the argument or return parameter list.

type ParseState

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

ParseState is keeping the state during the parsing process.

type Parser

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

Parser is a mock setup command line argument parser.

func NewParser

func NewParser(loader Loader, target *Type) *Parser

NewParser creates a new mock setup command line argument parser with loading of test packages enabled or disabled.

func (*Parser) Parse

func (parser *Parser) Parse(args ...string) ([]*Mock, []error)

Parse parses the command line arguments provided and returns a list of mock stubs containing the necessary source and target information without method data.

type PkgResponse

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

PkgResponse provides a cachable package loader response.

func NewPkgResponse

func NewPkgResponse(
	_ string, pkgs []*packages.Package, err error,
) *PkgResponse

NewPkgResponse calculates a new package response using given path, package list and error information. The method also derives the package path and package names using this information.

func (*PkgResponse) Get

func (r *PkgResponse) Get() ([]*packages.Package, error)

Get expands the package loader response result.

func (*PkgResponse) Path

func (r *PkgResponse) Path() string

Path resolves the package path if available.

type Template

type Template interface {
	Execute(writer io.Writer, file any) error
}

Template minimal mock template abstraction.

func MustTemplate

func MustTemplate() Template

MustTemplate crates a new mock template panicing in case of errors.

type Type

type Type struct {
	// Package of the interface.
	Package string
	// Path of the interface.
	Path string
	// File name of the interface.
	File string
	// Name of the interface.
	Name string
}

Type is a generic type information.

func NewType

func NewType(name *types.TypeName, fset *token.FileSet) *Type

NewType creates a new type information based on the given named type.

func (*Type) Copy

func (t *Type) Copy() *Type

func (*Type) IsPackageMatch

func (t *Type) IsPackageMatch(pkgs []*packages.Package) bool

IsPackageMatch chechs whether on of the provided package names matches the package name of the type. If the package has no name, the default name is computed and compared.

func (*Type) IsPartial

func (t *Type) IsPartial() bool

IsPartial states whether the type is prepared and needs to be processed before parsing can be finihed.

func (*Type) Matcher

func (t *Type) Matcher() (*TypeMatcher, error)

Matcher create a matcher from the given type using the file path and the name pattern.

func (*Type) Update

func (t *Type) Update(loader Loader)

Update updates the type with the information provided by given packages using the package path and the package name. If a previous package name is compared with names of the provided packages and only replaced against the name of the first package, if it does not match any package.

func (*Type) With

func (t *Type) With(etype *Type) *Type

With extends a type information with the given type information in all places that are not empty.

type TypeMatcher

type TypeMatcher struct {
	// Base file name.
	File string
	// Name pattern matcher.
	Name *regexp.Regexp
}

TypeMatcher contains type matcher information.

func (*TypeMatcher) Matches

func (tm *TypeMatcher) Matches(t *Type) bool

Matches checks whether the matcher matches the given type file and name.

Directories

Path Synopsis
Package test contains an interface and types for testing the mock package loading and mock file generating from template.
Package test contains an interface and types for testing the mock package loading and mock file generating from template.
Package test_test contains an interface and types for testing the mock package loading and mock file generating from template.
Package test_test contains an interface and types for testing the mock package loading and mock file generating from template.

Jump to

Keyboard shortcuts

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