added vendor example

This commit is contained in:
Mat Ryer
2017-07-11 20:02:46 +01:00
parent be1d7ca86c
commit df49857c18
11 changed files with 34 additions and 3 deletions

145
pkg/moq/importer.go Normal file
View File

@@ -0,0 +1,145 @@
package moq
// taken from https://github.com/ernesto-jimenez/gogen
// Copyright (c) 2015 Ernesto Jiménez
import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
)
type customImporter struct {
imported map[string]*types.Package
base types.Importer
skipTestFiles bool
}
func (i *customImporter) Import(path string) (*types.Package, error) {
var err error
if path == "" || path[0] == '.' {
path, err = filepath.Abs(filepath.Clean(path))
if err != nil {
return nil, err
}
path = stripGopath(path)
}
if pkg, ok := i.imported[path]; ok {
return pkg, nil
}
pkg, err := i.fsPkg(path)
if err != nil {
return nil, err
}
i.imported[path] = pkg
return pkg, nil
}
func gopathDir(pkg string) (string, error) {
for _, gopath := range strings.Split(os.Getenv("GOPATH"), ":") {
absPath, err := filepath.Abs(path.Join(gopath, "src", pkg))
if err != nil {
return "", err
}
if dir, err := os.Stat(absPath); err == nil && dir.IsDir() {
return absPath, nil
}
}
return "", fmt.Errorf("%s not in $GOPATH", pkg)
}
func removeGopath(p string) string {
for _, gopath := range strings.Split(os.Getenv("GOPATH"), ":") {
p = strings.Replace(p, path.Join(gopath, "src")+"/", "", 1)
}
return p
}
func (i *customImporter) fsPkg(pkg string) (*types.Package, error) {
dir, err := gopathDir(pkg)
if err != nil {
return importOrErr(i.base, pkg, err)
}
dirFiles, err := ioutil.ReadDir(dir)
if err != nil {
return importOrErr(i.base, pkg, err)
}
fset := token.NewFileSet()
var files []*ast.File
for _, fileInfo := range dirFiles {
if fileInfo.IsDir() {
continue
}
n := fileInfo.Name()
if path.Ext(fileInfo.Name()) != ".go" {
continue
}
if i.skipTestFiles && strings.Contains(fileInfo.Name(), "_test.go") {
continue
}
file := path.Join(dir, n)
src, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
f, err := parser.ParseFile(fset, file, src, 0)
if err != nil {
return nil, err
}
files = append(files, f)
}
conf := types.Config{
Importer: i,
}
p, err := conf.Check(pkg, fset, files, nil)
if err != nil {
return importOrErr(i.base, pkg, err)
}
return p, nil
}
func importOrErr(base types.Importer, pkg string, err error) (*types.Package, error) {
p, impErr := base.Import(pkg)
if impErr != nil {
return nil, err
}
return p, nil
}
// newImporter returns an importer that will try to import code from gopath before using go/importer.Default and skipping test files
func newImporter() types.Importer {
return &customImporter{
imported: make(map[string]*types.Package),
base: importer.Default(),
skipTestFiles: true,
}
}
// // DefaultWithTestFiles same as Default but it parses test files too
// func DefaultWithTestFiles() types.Importer {
// return &customImporter{
// imported: make(map[string]*types.Package),
// base: importer.Default(),
// skipTestFiles: false,
// }
// }
// stripGopath teks the directory to a package and remove the gopath to get the
// cannonical package name
func stripGopath(p string) string {
for _, gopath := range strings.Split(os.Getenv("GOPATH"), ":") {
p = strings.Replace(p, path.Join(gopath, "src")+"/", "", 1)
}
return p
}

304
pkg/moq/moq.go Normal file
View File

@@ -0,0 +1,304 @@
package moq
import (
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"go/types"
"io"
"os"
"strings"
"text/template"
)
// Mocker can generate mock structs.
type Mocker struct {
src string
tmpl *template.Template
fset *token.FileSet
pkgs map[string]*ast.Package
pkgName string
imports map[string]bool
}
// New makes a new Mocker for the specified package directory.
func New(src, packageName string) (*Mocker, error) {
fset := token.NewFileSet()
noTestFiles := func(i os.FileInfo) bool {
return !strings.HasSuffix(i.Name(), "_test.go")
}
pkgs, err := parser.ParseDir(fset, src, noTestFiles, parser.SpuriousErrors)
if err != nil {
return nil, err
}
if len(packageName) == 0 {
for pkgName := range pkgs {
if strings.Contains(pkgName, "_test") {
continue
}
packageName = pkgName
break
}
}
if len(packageName) == 0 {
return nil, errors.New("failed to determine package name")
}
tmpl, err := template.New("moq").Funcs(templateFuncs).Parse(moqTemplate)
if err != nil {
return nil, err
}
return &Mocker{
src: src,
tmpl: tmpl,
fset: fset,
pkgs: pkgs,
pkgName: packageName,
imports: make(map[string]bool),
}, nil
}
// Mock generates a mock for the specified interface name.
func (m *Mocker) Mock(w io.Writer, name ...string) error {
if len(name) == 0 {
return errors.New("must specify one interface")
}
doc := doc{
PackageName: m.pkgName,
Imports: moqImports,
}
for _, pkg := range m.pkgs {
i := 0
files := make([]*ast.File, len(pkg.Files))
for _, file := range pkg.Files {
files[i] = file
i++
}
conf := types.Config{Importer: newImporter()}
tpkg, err := conf.Check(m.src, m.fset, files, nil)
if err != nil {
return err
}
for _, n := range name {
iface := tpkg.Scope().Lookup(n)
if iface == nil {
return fmt.Errorf("cannot find interface %s", n)
}
if !types.IsInterface(iface.Type()) {
return fmt.Errorf("%s (%s) not an interface", n, iface.Type().String())
}
iiface := iface.Type().Underlying().(*types.Interface).Complete()
obj := obj{
InterfaceName: n,
}
for i := 0; i < iiface.NumMethods(); i++ {
meth := iiface.Method(i)
sig := meth.Type().(*types.Signature)
method := &method{
Name: meth.Name(),
}
obj.Methods = append(obj.Methods, method)
method.Params = m.extractArgs(sig, sig.Params(), "in%d")
method.Returns = m.extractArgs(sig, sig.Results(), "out%d")
}
doc.Objects = append(doc.Objects, obj)
}
}
for pkgToImport := range m.imports {
doc.Imports = append(doc.Imports, pkgToImport)
}
err := m.tmpl.Execute(w, doc)
if err != nil {
return err
}
return nil
}
func (m *Mocker) packageQualifier(pkg *types.Package) string {
if m.pkgName == pkg.Name() {
return ""
}
m.imports[pkg.Path()] = true
return pkg.Name()
}
func (m *Mocker) extractArgs(sig *types.Signature, list *types.Tuple, nameFormat string) []*param {
var params []*param
listLen := list.Len()
for ii := 0; ii < listLen; ii++ {
p := list.At(ii)
name := p.Name()
if name == "" {
name = fmt.Sprintf(nameFormat, ii+1)
}
typename := types.TypeString(p.Type(), m.packageQualifier)
// check for final variadic argument
variadic := sig.Variadic() && ii == listLen-1 && typename[0:2] == "[]"
param := &param{
Name: name,
Type: typename,
Variadic: variadic,
}
params = append(params, param)
}
return params
}
type doc struct {
PackageName string
Objects []obj
Imports []string
}
type obj struct {
InterfaceName string
Methods []*method
}
type method struct {
Name string
Params []*param
Returns []*param
}
func (m *method) Arglist() string {
params := make([]string, len(m.Params))
for i, p := range m.Params {
params[i] = p.String()
}
return strings.Join(params, ", ")
}
func (m *method) ArgCallList() string {
params := make([]string, len(m.Params))
for i, p := range m.Params {
params[i] = p.CallName()
}
return strings.Join(params, ", ")
}
func (m *method) ReturnArglist() string {
params := make([]string, len(m.Returns))
for i, p := range m.Returns {
params[i] = p.TypeString()
}
if len(m.Returns) > 1 {
return fmt.Sprintf("(%s)", strings.Join(params, ", "))
}
return strings.Join(params, ", ")
}
type param struct {
Name string
Type string
Variadic bool
}
func (p param) String() string {
return fmt.Sprintf("%s %s", p.Name, p.TypeString())
}
func (p param) CallName() string {
if p.Variadic {
return p.Name + "..."
}
return p.Name
}
func (p param) TypeString() string {
if p.Variadic {
return "..." + p.Type[2:]
}
return p.Type
}
var templateFuncs = template.FuncMap{
"Exported": func(s string) string {
if s == "" {
return ""
}
return strings.ToUpper(s[0:1]) + s[1:]
},
}
// moqImports are the imports all moq files get.
var moqImports = []string{"sync"}
// moqTemplate is the template for mocked code.
var moqTemplate = `package {{.PackageName}}
// AUTOGENERATED BY MOQ
// github.com/matryer/moq
import (
{{- range .Imports }}
"{{.}}"
{{- end }}
)
{{ range $i, $obj := .Objects }}
// {{.InterfaceName}}Mock is a mock implementation of {{.InterfaceName}}.
//
// func TestSomethingThatUses{{.InterfaceName}}(t *testing.T) {
//
// // make and configure a mocked {{.InterfaceName}}
// mocked{{.InterfaceName}} := &{{.InterfaceName}}Mock{ {{ range .Methods }}
// {{.Name}}Func: func({{ .Arglist }}) {{.ReturnArglist}} {
// panic("TODO: mock out the {{.Name}} method")
// },{{- end }}
// }
//
// // TODO: use mocked{{.InterfaceName}} in code that requires {{.InterfaceName}}
// // and then make assertions.
// //
// // Use the CallsTo structure to access details about what calls were made:
// //
// // if len(mocked{{.InterfaceName}}.CallsTo.MethodFunc) != 1 {
// // t.Errorf("expected 1 call there were %d", len(mocked{{.InterfaceName}}.CallsTo.MethodFunc))
// // }
//
// }
type {{.InterfaceName}}Mock struct {
{{- range .Methods }}
// {{.Name}}Func mocks the {{.Name}} method.
{{.Name}}Func func({{ .Arglist }}) {{.ReturnArglist}}
{{ end }}
// CallsTo tracks calls to the methods.
CallsTo struct {
{{- range .Methods }}
lock{{.Name}} sync.Mutex // protects {{ .Name }}
// {{ .Name }} holds details about calls to the {{.Name}} method.
{{ .Name }} []struct {
{{- range .Params }}
// {{ .Name | Exported }} is the {{ .Name }} argument value.
{{ .Name | Exported }} {{ .Type }}
{{- end }}
}
{{- end }}
}
}
{{ range .Methods }}
// {{.Name}} calls {{.Name}}Func.
func (mock *{{$obj.InterfaceName}}Mock) {{.Name}}({{.Arglist}}) {{.ReturnArglist}} {
if mock.{{.Name}}Func == nil {
panic("moq: {{$obj.InterfaceName}}Mock.{{.Name}}Func is nil but was just called")
}
mock.CallsTo.lock{{.Name}}.Lock()
mock.CallsTo.{{.Name}} = append(mock.CallsTo.{{.Name}}, struct{
{{- range .Params }}
{{ .Name | Exported }} {{ .Type }}
{{- end }}
}{
{{- range .Params }}
{{ .Name | Exported }}: {{ .Name }},
{{- end }}
})
mock.CallsTo.lock{{.Name}}.Unlock()
{{- if .ReturnArglist }}
return mock.{{.Name}}Func({{.ArgCallList}})
{{- else }}
mock.{{.Name}}Func({{.ArgCallList}})
{{- end }}
}
{{ end -}}
{{ end -}}`

187
pkg/moq/moq_test.go Normal file
View File

@@ -0,0 +1,187 @@
package moq
import (
"bytes"
"log"
"strings"
"testing"
)
func TestMoq(t *testing.T) {
m, err := New("testdata/example", "")
if err != nil {
t.Fatalf("moq.New: %s", err)
}
var buf bytes.Buffer
err = m.Mock(&buf, "PersonStore")
if err != nil {
t.Errorf("m.Mock: %s", err)
}
s := buf.String()
// assertions of things that should be mentioned
var strs = []string{
"package example",
"type PersonStoreMock struct",
"CreateFunc func(ctx context.Context, person *Person, confirm bool) error",
"GetFunc func(ctx context.Context, id string) (*Person, error)",
"func (mock *PersonStoreMock) Create(ctx context.Context, person *Person, confirm bool) error",
"func (mock *PersonStoreMock) Get(ctx context.Context, id string) (*Person, error)",
"panic(\"moq: PersonStoreMock.CreateFunc is nil but was just called\")",
"panic(\"moq: PersonStoreMock.GetFunc is nil but was just called\")",
"mock.CallsTo.lockGet.Lock()",
"mock.CallsTo.Get = append(mock.CallsTo.Get, struct{",
"mock.CallsTo.lockGet.Unlock()",
}
for _, str := range strs {
if !strings.Contains(s, str) {
t.Errorf("expected but missing: \"%s\"", str)
}
}
}
func TestMoqExplicitPackage(t *testing.T) {
m, err := New("testdata/example", "different")
if err != nil {
t.Fatalf("moq.New: %s", err)
}
var buf bytes.Buffer
err = m.Mock(&buf, "PersonStore")
if err != nil {
t.Errorf("m.Mock: %s", err)
}
s := buf.String()
// assertions of things that should be mentioned
var strs = []string{
"package different",
"type PersonStoreMock struct",
"CreateFunc func(ctx context.Context, person *example.Person, confirm bool) error",
"GetFunc func(ctx context.Context, id string) (*example.Person, error)",
"func (mock *PersonStoreMock) Create(ctx context.Context, person *example.Person, confirm bool) error",
"func (mock *PersonStoreMock) Get(ctx context.Context, id string) (*example.Person, error)",
}
for _, str := range strs {
if !strings.Contains(s, str) {
t.Errorf("expected but missing: \"%s\"", str)
}
}
}
// TestVeradicArguments tests to ensure variadic work as
// expected.
// see https://github.com/matryer/moq/issues/5
func TestVariadicArguments(t *testing.T) {
m, err := New("testdata/variadic", "")
if err != nil {
t.Fatalf("moq.New: %s", err)
}
var buf bytes.Buffer
err = m.Mock(&buf, "Greeter")
if err != nil {
t.Errorf("m.Mock: %s", err)
}
s := buf.String()
// assertions of things that should be mentioned
var strs = []string{
"package variadic",
"type GreeterMock struct",
"GreetFunc func(ctx context.Context, names ...string) string",
"return mock.GreetFunc(ctx, names...)",
}
for _, str := range strs {
if !strings.Contains(s, str) {
t.Errorf("expected but missing: \"%s\"", str)
}
}
}
func TestNothingToReturn(t *testing.T) {
m, err := New("testdata/example", "")
if err != nil {
t.Fatalf("moq.New: %s", err)
}
var buf bytes.Buffer
err = m.Mock(&buf, "PersonStore")
if err != nil {
t.Errorf("m.Mock: %s", err)
}
s := buf.String()
if strings.Contains(s, `return mock.ClearCacheFunc(id)`) {
t.Errorf("should not have return for items that have no return arguments")
}
// assertions of things that should be mentioned
var strs = []string{
"mock.ClearCacheFunc(id)",
}
for _, str := range strs {
if !strings.Contains(s, str) {
t.Errorf("expected but missing: \"%s\"", str)
}
}
}
func TestChannelNames(t *testing.T) {
m, err := New("testdata/channels", "")
if err != nil {
t.Fatalf("moq.New: %s", err)
}
var buf bytes.Buffer
err = m.Mock(&buf, "Queuer")
if err != nil {
t.Errorf("m.Mock: %s", err)
}
s := buf.String()
var strs = []string{
"func (mock *QueuerMock) Sub(topic string) (<-chan Queue, error)",
}
for _, str := range strs {
if !strings.Contains(s, str) {
t.Errorf("expected but missing: \"%s\"", str)
}
}
}
func TestImports(t *testing.T) {
m, err := New("testdata/imports/two", "")
if err != nil {
t.Fatalf("moq.New: %s", err)
}
var buf bytes.Buffer
err = m.Mock(&buf, "DoSomething")
if err != nil {
t.Errorf("m.Mock: %s", err)
}
s := buf.String()
var strs = []string{
` "sync"`,
` "github.com/matryer/moq/pkg/moq/testdata/imports/one"`,
}
for _, str := range strs {
if !strings.Contains(s, str) {
t.Errorf("expected but missing: \"%s\"", str)
}
if len(strings.Split(s, str)) > 2 {
t.Errorf("more than one: \"%s\"", str)
}
}
}
func TestTemplateFuncs(t *testing.T) {
fn := templateFuncs["Exported"].(func(string) string)
if fn("var") != "Var" {
t.Errorf("exported didn't work: %s", fn("var"))
}
}
func TestVendoredPackages(t *testing.T) {
m, err := New("testdata/vendoring/user", "")
if err != nil {
t.Fatalf("moq.New: %s", err)
}
var buf bytes.Buffer
err = m.Mock(&buf, "Service")
if err != nil {
t.Errorf("mock error: %s", err)
}
log.Println(buf.String())
}

7
pkg/moq/testdata/channels/example.go vendored Normal file
View File

@@ -0,0 +1,7 @@
package channels
type Queue []string
type Queuer interface {
Sub(topic string) (<-chan Queue, error)
}

16
pkg/moq/testdata/example/example.go vendored Normal file
View File

@@ -0,0 +1,16 @@
package example
import "context"
type Person struct {
ID string
Name string
Company string
Website string
}
type PersonStore interface {
Get(ctx context.Context, id string) (*Person, error)
Create(ctx context.Context, person *Person, confirm bool) error
ClearCache(id string)
}

4
pkg/moq/testdata/imports/one/one.go vendored Normal file
View File

@@ -0,0 +1,4 @@
package one
// Thing is just a thing.
type Thing struct{}

11
pkg/moq/testdata/imports/two/two.go vendored Normal file
View File

@@ -0,0 +1,11 @@
package two
import (
"github.com/matryer/moq/pkg/moq/testdata/imports/one"
)
// DoSomething does something.
type DoSomething interface {
Do(thing one.Thing) error
Another(thing one.Thing) error
}

8
pkg/moq/testdata/variadic/greeter.go vendored Normal file
View File

@@ -0,0 +1,8 @@
package variadic
import "context"
// Greeter greets people.
type Greeter interface {
Greet(ctx context.Context, names ...string) string
}

View File

@@ -0,0 +1,8 @@
package user
import "github.com/matryer/somerepo"
// Service does something good with computers.
type Service interface {
DoSomething(somerepo.SomeType) error
}

View File

@@ -0,0 +1,9 @@
// Package somerepo is a vendored package to test how moq deals with
// packages in the vendor package.
package somerepo
// SomeType is just some old type.
type SomeType struct {
// Truth indicates whether true is true or not. Computers.
Truth bool
}