fake

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Feb 29, 2024 License: MIT Imports: 14 Imported by: 0

README

Fake

Fake is a Go type-safe mocking library!

Automatically create type-safe mocks for any public interface.

Installation

Go install

Make sure $GO_PATH/bin is in your $PATH

go install github.com/sonalys/fake/entrypoints/fake@latest

Release download

Visit the Release Page and download the correct binary for your architecture/os.

Docker

You can safely run fake from a docker container using

docker run --rm -u $(id -u):$(id -g) -v .:/code ghcr.io/sonalys/fake:latest /fake -input /code -output /code/mocks

Usage


Usage:

  fake -input PATH -output mocks -ignore tests

The flags are:

  -input    STRING    Folder to scan for interfaces, can be invoked multiple times
  -output   STRING    Output folder, it will follow a tree structure repeating the package path
  -ignore   STRING    Folder to ignore, can be invoked multiple times
  

Example

Running against our weird interface

type StubInterface[T comparable] interface {
	WeirdFunc1(a any, b interface {
		A() int
	})
	WeirdFunc2(in *<-chan time.Time, outs ...chan int) error
	Empty()
	WeirdFunc3(map[T]func(in ...*chan<- time.Time)) T
}

Will generate the following mock:

type StubInterface[T comparable] struct {
	setupWeirdFunc1 mockSetup.Mock[func(a any, b interface {
		A() int
	})]
	setupWeirdFunc2 mockSetup.Mock[func(in *<-chan time.Time, outs ...chan int) error]
	setupEmpty      mockSetup.Mock[func()]
	setupWeirdFunc3 mockSetup.Mock[func(a0 map[T]func(in ...*chan<- time.Time)) T]
}

func (s *StubInterface[T]) OnWeirdFunc1(funcs ...func(a any, b interface { A() int })) Config
func (s *StubInterface[T]) WeirdFunc1(a any, b interface { A() int })
...

So you can use it like this


func Test_Stub(t *testing.T) {
  mock := mocks.NewStubInterface[int](t) // Setup call expectations
  mock.OnWeirdFunc1(func(a any, b interface { A() int }) {
    require.NotNil(t, a)
    ...
  })
  var Stub StubInterface[int] = mock
  Stub.WeirdFunc1(1, nil) // Will call the previous function.
}

You can pass more than one function or set repetition groups with

mock.OnWeirdFunc1(func(a any, b interface { A() int }) {
  require.NotNil(t, a)
  ...
}).Repeat(2)
// or
mock.OnWeirdFunc1(func(a any, b interface { A() int }) {
  require.NotNil(t, a)
  ...
}).Maybe()

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateFileAndFolders

func CreateFileAndFolders(filePath string) (*os.File, error)

CreateFileAndFolders creates a file and the necessary folders if they don't exist.

func FormatCode

func FormatCode(in []byte) []byte

func GetPackagePath

func GetPackagePath(fset *token.FileSet, filename string) (string, error)

GetPackagePath returns the full package path from a given *ast.File.

func ListGoFiles

func ListGoFiles(dirPath string, ignore []string) ([]string, error)

ListGoFiles lists all Go files under a directory.

func ParseImports

func ParseImports(imports []*ast.ImportSpec) map[string]*PackageInfo

func Run

func Run(inputs []string, output string, ignore []string)

func WriteHeader

func WriteHeader(w io.Writer, packageName string)

Types

type Generator

type Generator struct {
	FileSet *token.FileSet
	PkgName string
}

func NewGenerator

func NewGenerator(pkgName string) *Generator

func (*Generator) ListInterfaceFields

func (g *Generator) ListInterfaceFields(i *ParsedInterface, imports map[string]*PackageInfo) []*ParsedField

func (*Generator) ParseFile

func (g *Generator) ParseFile(input string) *ParsedFile

func (*Generator) ParseInterface

func (g *Generator) ParseInterface(ident *ast.SelectorExpr, usedImports map[string]struct{}, imports map[string]*PackageInfo) *ParsedInterface

func (*Generator) WriteFile

func (g *Generator) WriteFile(input, output string) bool

type PackageInfo

type PackageInfo struct {
	Ref        *ast.ImportSpec
	Name       string
	ImportPath string
}

func ParsePackageInfo

func ParsePackageInfo(importPath string) (*PackageInfo, bool)

ParsePackageInfo parses the specified package and returns its package name and import path.

type ParsedField

type ParsedField struct {
	Interface *ParsedInterface
	Ref       *ast.Field
	Name      string
	Type      string
}

func (*ParsedField) UpdateImports

func (f *ParsedField) UpdateImports()

type ParsedFile

type ParsedFile struct {
	Generator   *Generator
	Ref         *ast.File
	PkgPath     string
	PkgName     string
	Imports     map[string]*PackageInfo
	UsedImports map[string]struct{}
}

func (*ParsedFile) FindInterfaceByName

func (f *ParsedFile) FindInterfaceByName(name string) (*ParsedInterface, map[string]*PackageInfo)

func (*ParsedFile) ListInterfaces

func (f *ParsedFile) ListInterfaces() []*ParsedInterface

func (*ParsedFile) WriteImports

func (f *ParsedFile) WriteImports(w io.Writer)

type ParsedInterface

type ParsedInterface struct {
	ParsedFile    *ParsedFile
	Type          *ast.TypeSpec
	Ref           *ast.InterfaceType
	Name          string
	GenericsTypes []string
	GenericsNames []string
	// TranslateGenericNames translates generic type names from any imported interfaces.
	// Example:
	//	type A[T any] interface{ B[T] }
	//	type B[J any] interface{ Method() J }
	// it should have method Method() T when implementing A mock.
	TranslateGenericNames []string
}

func (*ParsedInterface) GetGenericsInfo

func (i *ParsedInterface) GetGenericsInfo() ([]string, []string)

func (*ParsedInterface) ListFields

func (i *ParsedInterface) ListFields() []*ParsedField

func (*ParsedInterface) PrintAstField

func (f *ParsedInterface) PrintAstField(i int, field *ast.Field, printName bool) string

func (*ParsedInterface) PrintAstFields

func (f *ParsedInterface) PrintAstFields(implFile io.Writer, fields []*ast.Field, printName bool)

func (*ParsedInterface) PrintMethodHeader

func (f *ParsedInterface) PrintMethodHeader(file io.Writer, methodName string, field *ParsedField)

func (*ParsedInterface) WriteAssertExpectations

func (i *ParsedInterface) WriteAssertExpectations(w io.Writer)

func (*ParsedInterface) WriteGenericsHeader

func (i *ParsedInterface) WriteGenericsHeader() string

func (*ParsedInterface) WriteGenericsNameHeader

func (i *ParsedInterface) WriteGenericsNameHeader() string

func (*ParsedInterface) WriteInitializer

func (i *ParsedInterface) WriteInitializer(w io.Writer)

func (*ParsedInterface) WriteMethod

func (i *ParsedInterface) WriteMethod(w io.Writer, methodName string, f *ParsedField)

func (*ParsedInterface) WriteMethodParams

func (f *ParsedInterface) WriteMethodParams(implFile io.Writer, params []*ast.Field)

func (*ParsedInterface) WriteMethodResults

func (f *ParsedInterface) WriteMethodResults(implFile io.Writer, results []*ast.Field)

func (*ParsedInterface) WriteMock

func (i *ParsedInterface) WriteMock(w io.Writer)

func (*ParsedInterface) WriteOnMethod

func (i *ParsedInterface) WriteOnMethod(w io.Writer, methodName string, f *ParsedField)

func (*ParsedInterface) WriteStruct

func (i *ParsedInterface) WriteStruct(w io.Writer)

func (*ParsedInterface) WriteStructMethods

func (i *ParsedInterface) WriteStructMethods(file io.Writer)

Directories

Path Synopsis
entrypoint

Jump to

Keyboard shortcuts

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