Update to latest version of pegomock library

This commit is contained in:
Luke Kysow
2017-10-25 08:00:34 -07:00
parent d5f2fc0426
commit 41196a9f80
9 changed files with 268 additions and 64 deletions

2
Gopkg.lock generated
View File

@@ -149,7 +149,7 @@
branch = "master"
name = "github.com/petergtz/pegomock"
packages = [".","internal/verify"]
revision = "cc94f74ce20a9c2575a77736799f359ef247beef"
revision = "53d177bf13d74db3a7120c60f03d4f42bea4b608"
[[projects]]
name = "github.com/pkg/errors"

View File

@@ -1,4 +1,6 @@
mock_display_test.go
debug.test
.vscode
*.coverprofile
*.coverprofile
.idea
*.iml

View File

@@ -18,6 +18,7 @@ import (
"bytes"
"fmt"
"reflect"
"sort"
"testing"
"github.com/onsi/gomega/format"
@@ -107,19 +108,18 @@ func (genericMock *GenericMock) Verify(
}
}
if !invocationCountMatcher.Matches(len(methodInvocations)) {
if len(globalArgMatchers) == 0 {
GlobalFailHandler(fmt.Sprintf(
"Mock invocation count for method \"%s\" with params %v does not match expectation.\n\n\t%v",
methodName, params, invocationCountMatcher.FailureMessage()))
} else {
GlobalFailHandler(fmt.Sprintf(
"Mock invocation count for method \"%s\" with params %v does not match expectation.\n\n\t%v",
methodName, globalArgMatchers, invocationCountMatcher.FailureMessage()))
var paramsOrMatchers interface{} = params
if len(globalArgMatchers) != 0 {
paramsOrMatchers = globalArgMatchers
}
GlobalFailHandler(fmt.Sprintf(
"Mock invocation count for method \"%s\" with params %v does not match expectation.\n\n\t%v\n\n\t%v",
methodName, paramsOrMatchers, invocationCountMatcher.FailureMessage(), formatInteractions(genericMock.allInteractions())))
}
return methodInvocations
}
// TODO this doesn't need to be a method, can be a free function
func (genericMock *GenericMock) GetInvocationParams(methodInvocations []MethodInvocation) [][]Param {
if len(methodInvocations) == 0 {
return nil
@@ -150,6 +150,55 @@ func (genericMock *GenericMock) methodInvocations(methodName string, params []Pa
return invocations
}
func formatInteractions(interactions map[string][]MethodInvocation) string {
if len(interactions) == 0 {
return "There were no other interactions with this mock"
}
result := "But other interactions with this mock were:\n"
for _, methodName := range sortedMethodNames(interactions) {
result += formatInvocations(methodName, interactions[methodName])
}
return result
}
func formatInvocations(methodName string, invocations []MethodInvocation) (result string) {
for _, invocation := range invocations {
result += "\t" + methodName + "(" + formatParams(invocation.params) + ")\n"
}
return
}
func formatParams(params []Param) (result string) {
for i, param := range params {
if i > 0 {
result += ", "
}
result += fmt.Sprint(param)
}
return
}
func sortedMethodNames(interactions map[string][]MethodInvocation) []string {
methodNames := make([]string, len(interactions))
i := 0
for key := range interactions {
methodNames[i] = key
i++
}
sort.Strings(methodNames)
return methodNames
}
func (genericMock *GenericMock) allInteractions() map[string][]MethodInvocation {
interactions := make(map[string][]MethodInvocation)
for methodName := range genericMock.mockedMethods {
for _, invocation := range genericMock.mockedMethods[methodName].invocations {
interactions[methodName] = append(interactions[methodName], invocation)
}
}
return interactions
}
type mockedMethod struct {
name string
invocations []MethodInvocation

View File

@@ -70,10 +70,10 @@ var _ = Describe("MockDisplay", func() {
})
It("fails during verification when mock was not called", func() {
Expect(func() { display.VerifyWasCalledOnce().MultipleParamsAndReturnValue("Hello", 333) }).To(PanicWith(
Expect(func() { display.VerifyWasCalledOnce().MultipleParamsAndReturnValue("Hello", 333) }).To(PanicWithMessageTo(HavePrefix(
"Mock invocation count for method \"MultipleParamsAndReturnValue\" with params [Hello 333] " +
"does not match expectation.\n\n\tExpected: 1; but got: 0",
))
)))
})
It("succeeds verification when mock was called", func() {
@@ -82,10 +82,10 @@ var _ = Describe("MockDisplay", func() {
})
It("succeeds verification when verification and invocation are mixed", func() {
Expect(func() { display.VerifyWasCalledOnce().MultipleParamsAndReturnValue("Hello", 333) }).To(PanicWith(
Expect(func() { display.VerifyWasCalledOnce().MultipleParamsAndReturnValue("Hello", 333) }).To(PanicWithMessageTo(HavePrefix(
"Mock invocation count for method \"MultipleParamsAndReturnValue\" with params [Hello 333] " +
"does not match expectation.\n\n\tExpected: 1; but got: 0",
))
)))
display.MultipleParamsAndReturnValue("Hello", 333)
Expect(func() { display.VerifyWasCalledOnce().MultipleParamsAndReturnValue("Hello", 333) }).NotTo(Panic())
})
@@ -95,10 +95,10 @@ var _ = Describe("MockDisplay", func() {
It("succeeds all verifications that match", func() {
When(display.MultipleParamsAndReturnValue(AnyString(), EqInt(333))).ThenReturn("Bla")
Expect(func() { display.VerifyWasCalledOnce().MultipleParamsAndReturnValue("Hello", 333) }).To(PanicWith(
Expect(func() { display.VerifyWasCalledOnce().MultipleParamsAndReturnValue("Hello", 333) }).To(PanicWithMessageTo(HavePrefix(
"Mock invocation count for method \"MultipleParamsAndReturnValue\" with params [Hello 333] " +
"does not match expectation.\n\n\tExpected: 1; but got: 0",
))
)))
display.MultipleParamsAndReturnValue("Hello", 333)
display.MultipleParamsAndReturnValue("Hello again", 333)
@@ -108,17 +108,17 @@ var _ = Describe("MockDisplay", func() {
Expect(func() { display.VerifyWasCalledOnce().MultipleParamsAndReturnValue("Hello again", 333) }).NotTo(Panic())
Expect(func() { display.VerifyWasCalledOnce().MultipleParamsAndReturnValue("And again", 333) }).NotTo(Panic())
Expect(func() { display.VerifyWasCalledOnce().MultipleParamsAndReturnValue("And again", 444) }).To(PanicWith(
Expect(func() { display.VerifyWasCalledOnce().MultipleParamsAndReturnValue("And again", 444) }).To(PanicWithMessageTo(HavePrefix(
"Mock invocation count for method \"MultipleParamsAndReturnValue\" with params [And again 444] " +
"does not match expectation.\n\n\tExpected: 1; but got: 0",
))
)))
})
})
Context("Calling MultipleParamsAndReturnValue() only with matchers on some parameters", func() {
It("panics", func() {
Expect(func() { When(display.MultipleParamsAndReturnValue(EqString("Hello"), 333)) }).To(PanicWith(
Expect(func() { When(display.MultipleParamsAndReturnValue(EqString("Hello"), 333)) }).To(PanicWithMessageTo(HavePrefix(
"Invalid use of matchers!\n\n 2 matchers expected, 1 recorded.\n\n" +
"This error may occur if matchers are combined with raw values:\n" +
" //incorrect:\n" +
@@ -127,7 +127,7 @@ var _ = Describe("MockDisplay", func() {
"For example:\n" +
" //correct:\n" +
" someFunc(AnyInt(), EqString(\"String by matcher\"))",
))
)))
})
})
@@ -156,28 +156,28 @@ var _ = Describe("MockDisplay", func() {
})
It("fails if verify is called on mock that was not invoked.", func() {
Expect(func() { display.VerifyWasCalledOnce().Show("Some parameter") }).To(PanicWith(
Expect(func() { display.VerifyWasCalledOnce().Show("Some parameter") }).To(PanicWithMessageTo(HavePrefix(
"Mock invocation count for method \"Show\" with params [Some parameter] " +
"does not match expectation.\n\n\tExpected: 1; but got: 0",
))
)))
})
It("fails if verify is called on mock that was invoked more than once.", func() {
display.Show("param")
display.Show("param")
Expect(func() { display.VerifyWasCalledOnce().Show("param") }).To(PanicWith(
Expect(func() { display.VerifyWasCalledOnce().Show("param") }).To(PanicWithMessageTo(HavePrefix(
"Mock invocation count for method \"Show\" with params [param] " +
"does not match expectation.\n\n\tExpected: 1; but got: 2",
))
)))
})
})
Context("Stubbing with invalid return type", func() {
It("panics", func() {
Expect(func() { When(display.SomeValue()).ThenReturn("Hello").ThenReturn(0) }).To(PanicWith(
Expect(func() { When(display.SomeValue()).ThenReturn("Hello").ThenReturn(0) }).To(PanicWithMessageTo(HavePrefix(
"Return value of type int not assignable to return type string",
))
)))
})
})
@@ -210,9 +210,9 @@ var _ = Describe("MockDisplay", func() {
Context("Stubbing with value that does not implement error interface", func() {
It("panics", func() {
Expect(func() { When(display.ErrorReturnValue()).ThenReturn("Blub") }).To(PanicWith(
Expect(func() { When(display.ErrorReturnValue()).ThenReturn("Blub") }).To(PanicWithMessageTo(HavePrefix(
"Return value of type string not assignable to return type error",
))
)))
})
})
@@ -229,9 +229,9 @@ var _ = Describe("MockDisplay", func() {
Context("Stubbed method, but no invocation takes place", func() {
It("fails during verification", func() {
When(display.SomeValue()).ThenReturn("Hello")
Expect(func() { display.VerifyWasCalledOnce().SomeValue() }).To(PanicWith(
Expect(func() { display.VerifyWasCalledOnce().SomeValue() }).To(PanicWithMessageTo(HavePrefix(
"Mock invocation count for method \"SomeValue\" with params [] does not match expectation.\n\n\tExpected: 1; but got: 0",
))
)))
})
})
@@ -244,10 +244,10 @@ var _ = Describe("MockDisplay", func() {
})
It("fails during verification if values are not matching", func() {
Expect(func() { display.VerifyWasCalledOnce().Flash("Hello", 666) }).To(PanicWith(
Expect(func() { display.VerifyWasCalledOnce().Flash("Hello", 666) }).To(PanicWithMessageTo(HavePrefix(
"Mock invocation count for method \"Flash\" with params [Hello 666] " +
"does not match expectation.\n\n\tExpected: 1; but got: 0",
))
)))
})
It("succeeds during verification when using Any-matchers ", func() {
@@ -259,10 +259,10 @@ var _ = Describe("MockDisplay", func() {
})
It("fails during verification when using invalid Eq-matchers ", func() {
Expect(func() { display.VerifyWasCalledOnce().Flash(EqString("Invalid"), EqInt(-1)) }).To(PanicWith(
Expect(func() { display.VerifyWasCalledOnce().Flash(EqString("Invalid"), EqInt(-1)) }).To(PanicWithMessageTo(HavePrefix(
"Mock invocation count for method \"Flash\" with params [Eq(Invalid) Eq(-1)] " +
"does not match expectation.\n\n\tExpected: 1; but got: 0",
))
)))
})
It("fails when not using matchers for all params", func() {
@@ -293,17 +293,17 @@ var _ = Describe("MockDisplay", func() {
})
It("fails during verification if verifying with VerifyWasCalledOnce", func() {
Expect(func() { display.VerifyWasCalledOnce().Flash("Hello", 333) }).To(PanicWith(
Expect(func() { display.VerifyWasCalledOnce().Flash("Hello", 333) }).To(PanicWithMessageTo(HavePrefix(
"Mock invocation count for method \"Flash\" with params [Hello 333] " +
"does not match expectation.\n\n\tExpected: 1; but got: 2",
))
)))
})
It("fails during verification if verifying with Times(1)", func() {
Expect(func() { display.VerifyWasCalled(Times(1)).Flash("Hello", 333) }).To(PanicWith(
Expect(func() { display.VerifyWasCalled(Times(1)).Flash("Hello", 333) }).To(PanicWithMessageTo(HavePrefix(
"Mock invocation count for method \"Flash\" with params [Hello 333] " +
"does not match expectation.\n\n\tExpected: 1; but got: 2",
))
)))
})
It("succeeds during verification when using AtLeast(1)", func() {
@@ -315,10 +315,10 @@ var _ = Describe("MockDisplay", func() {
})
It("fails during verification when using AtLeast(3)", func() {
Expect(func() { display.VerifyWasCalled(AtLeast(3)).Flash("Hello", 333) }).To(PanicWith(
Expect(func() { display.VerifyWasCalled(AtLeast(3)).Flash("Hello", 333) }).To(PanicWithMessageTo(HavePrefix(
"Mock invocation count for method \"Flash\" with params [Hello 333] " +
"does not match expectation.\n\n\tExpected: at least 3; but got: 2",
))
)))
})
It("succeeds during verification when using Never()", func() {
@@ -326,10 +326,10 @@ var _ = Describe("MockDisplay", func() {
})
It("fails during verification when using Never()", func() {
Expect(func() { display.VerifyWasCalled(Never()).Flash("Hello", 333) }).To(PanicWith(
Expect(func() { display.VerifyWasCalled(Never()).Flash("Hello", 333) }).To(PanicWithMessageTo(HavePrefix(
"Mock invocation count for method \"Flash\" with params [Hello 333] " +
"does not match expectation.\n\n\tExpected: 0; but got: 2",
))
)))
})
})
@@ -395,9 +395,9 @@ var _ = Describe("MockDisplay", func() {
display.VerifyWasCalledInOrder(Once(), inOrder).Flash("again", 222)
display.VerifyWasCalledInOrder(Once(), inOrder).Flash("Hello", 111)
display.VerifyWasCalledInOrder(Once(), inOrder).Flash("and again", 333)
}).To(PanicWith(
}).To(PanicWithMessageTo(HavePrefix(
"Expected function call \"Flash\" with params [Hello 111] before function call \"Flash\" with params [again 222]",
))
)))
})
})
@@ -463,20 +463,20 @@ var _ = Describe("MockDisplay", func() {
Expect(func() {
display.InterfaceParam(3)
display.VerifyWasCalledOnce().InterfaceParam(AnyFloat32())
}).To(PanicWith(
}).To(PanicWithMessageTo(HavePrefix(
"Mock invocation count for method \"InterfaceParam\" with params [Any(float32)] " +
"does not match expectation.\n\n\tExpected: 1; but got: 0",
))
)))
})
It("Panics when interface{}-parameter is passed as float, but verified as int", func() {
Expect(func() {
display.InterfaceParam(3.141)
display.VerifyWasCalledOnce().InterfaceParam(AnyInt())
}).To(PanicWith(
}).To(PanicWithMessageTo(HavePrefix(
"Mock invocation count for method \"InterfaceParam\" with params [Any(int)] " +
"does not match expectation.\n\n\tExpected: 1; but got: 0",
))
)))
})
It("Succeeds when interface{}-parameter is passed as int and verified as int", func() {
@@ -493,10 +493,10 @@ var _ = Describe("MockDisplay", func() {
Expect(func() {
display.InterfaceParam(nil)
display.VerifyWasCalledOnce().InterfaceParam(AnyInt())
}).To(PanicWith(
}).To(PanicWithMessageTo(HavePrefix(
"Mock invocation count for method \"InterfaceParam\" with params [Any(int)] " +
"does not match expectation.\n\n\tExpected: 1; but got: 0",
))
)))
})
It("Succeeds when error-parameter is passed as nil and verified as any error", func() {
@@ -547,6 +547,42 @@ var _ = Describe("MockDisplay", func() {
})
})
Describe("Verifying gives hints about actual invocations in failure messages", func() {
It("shows actual interactions with same methods", func() {
display.Flash("Hello", 123)
display.Flash("Again", 456)
Expect(func() { display.VerifyWasCalledOnce().Flash("wrong string", -987) }).To(PanicWith(
"Mock invocation count for method \"Flash\" with params [wrong string -987] " +
"does not match expectation.\n\n\tExpected: 1; but got: 0\n\n" +
"\tBut other interactions with this mock were:\n" +
"\tFlash(Hello, 123)\n" +
"\tFlash(Again, 456)\n",
))
})
It("shows actual interactions with all methods", func() {
display.Show("Again")
display.Flash("Hello", 123)
Expect(func() { display.VerifyWasCalledOnce().Flash("wrong string", -987) }).To(PanicWith(
"Mock invocation count for method \"Flash\" with params [wrong string -987] " +
"does not match expectation.\n\n\tExpected: 1; but got: 0\n\n" +
"\tBut other interactions with this mock were:\n" +
"\tFlash(Hello, 123)\n" +
"\tShow(Again)\n"),
)
})
It("shows no interactions if there were none", func() {
Expect(func() { display.VerifyWasCalledOnce().Flash("wrong string", -987) }).To(PanicWith(
"Mock invocation count for method \"Flash\" with params [wrong string -987] " +
"does not match expectation.\n\n\tExpected: 1; but got: 0\n\n" +
"\tThere were no other interactions with this mock",
))
})
})
Describe("Stubbing methods that have no return value", func() {
It("Can be stubbed with Panic", func() {
When(func() { display.Show(AnyString()) }).ThenPanic("bla")

View File

@@ -36,7 +36,7 @@ import (
const mockFrameworkImportPath = "github.com/petergtz/pegomock"
func GenerateOutput(ast *model.Package, source string, packageOut string, selfPackage string) ([]byte, error) {
func GenerateOutput(ast *model.Package, source, packageOut, selfPackage string) ([]byte, error) {
g := new(generator)
g.generateCode(source, ast, packageOut, selfPackage)
return g.formattedOutput(), nil
@@ -47,20 +47,21 @@ type generator struct {
packageMap map[string]string // map from import path to package name
}
func (g *generator) generateCode(source string, pkg *model.Package, pkgName string, selfPackage string) {
func (g *generator) generateCode(source string, pkg *model.Package, pkgName, selfPackage string) {
g.p("// Automatically generated by pegomock. DO NOT EDIT!")
g.p("// Source: %v", source)
g.emptyLine()
importPaths := pkg.Imports()
importPaths[mockFrameworkImportPath] = true
g.packageMap = generateUniquePackageNamesFor(importPaths)
packageMap, nonVendorPackageMap := generateUniquePackageNamesFor(importPaths)
g.packageMap = packageMap
g.p("package %v", pkgName)
g.emptyLine()
g.p("import (")
g.p("\"reflect\"")
for packagePath, packageName := range g.packageMap {
for packagePath, packageName := range nonVendorPackageMap {
if packagePath != selfPackage {
g.p("%v %q", packageName, packagePath)
}
@@ -75,8 +76,9 @@ func (g *generator) generateCode(source string, pkg *model.Package, pkgName stri
}
}
func generateUniquePackageNamesFor(importPaths map[string]bool) (packageMap map[string]string) {
func generateUniquePackageNamesFor(importPaths map[string]bool) (packageMap, nonVendorPackageMap map[string]string) {
packageMap = make(map[string]string, len(importPaths))
nonVendorPackageMap = make(map[string]string, len(importPaths))
packageNamesAlreadyUsed := make(map[string]bool, len(importPaths))
for importPath := range importPaths {
sanitizedPackagePathBaseName := sanitize(path.Base(importPath))
@@ -90,8 +92,15 @@ func generateUniquePackageNamesFor(importPaths map[string]bool) (packageMap map[
for i := 0; packageNamesAlreadyUsed[packageName] || token.Lookup(packageName).IsKeyword(); i++ {
packageName = sanitizedPackagePathBaseName + strconv.Itoa(i)
}
packageMap[importPath] = packageName
packageNamesAlreadyUsed[packageName] = true
vendorParsedImportPath := importPath
if split := strings.Split(importPath, "/vendor/"); len(split) > 1 {
vendorParsedImportPath = split[1]
}
nonVendorPackageMap[vendorParsedImportPath] = packageName
}
return
}

View File

@@ -0,0 +1,66 @@
package pegomock_test
import (
"fmt"
"reflect"
"github.com/onsi/gomega/format"
"github.com/onsi/gomega/types"
"github.com/petergtz/pegomock/internal/verify"
)
type PanicWithMessageToMatcher struct {
expectedWith types.GomegaMatcher
actualWith interface{}
}
func PanicWithMessageTo(object types.GomegaMatcher) types.GomegaMatcher {
verify.Argument(object != nil, "You must provide a non-nil object to PanicWith")
return &PanicWithMessageToMatcher{expectedWith: object}
}
func (matcher *PanicWithMessageToMatcher) Match(actual interface{}) (success bool, err error) {
if actual == nil {
return false, fmt.Errorf("PanicWithMatcher expects a non-nil actual.")
}
actualType := reflect.TypeOf(actual)
if actualType.Kind() != reflect.Func {
return false, fmt.Errorf("PanicWithMatcher expects a function. Got:\n%s", format.Object(actual, 1))
}
if !(actualType.NumIn() == 0 && actualType.NumOut() == 0) {
return false, fmt.Errorf("PanicWithMatcher expects a function with no arguments and no return value. Got:\n%s", format.Object(actual, 1))
}
success = false
defer func() {
if object := recover(); object != nil {
var e error
success, e = matcher.expectedWith.Match(object)
if e != nil {
// TODO is there something needed here?
}
if !success {
matcher.actualWith = object
}
} else {
matcher.actualWith = object
}
}()
reflect.ValueOf(actual).Call([]reflect.Value{})
return
}
func (matcher *PanicWithMessageToMatcher) FailureMessage(actual interface{}) (message string) {
if matcher.actualWith == nil {
return format.Message(actual, "to panic")
} else {
return fmt.Sprintf("Panic message does not match.\n\n%v", matcher.expectedWith.FailureMessage(matcher.actualWith))
}
}
func (matcher *PanicWithMessageToMatcher) NegatedFailureMessage(actual interface{}) (message string) {
panic("Not implemented")
}

View File

@@ -17,6 +17,7 @@ package main_test
import (
"bytes"
"os"
"go/build"
"path/filepath"
"strings"
@@ -42,17 +43,19 @@ func TestPegomock(t *testing.T) {
var _ = Describe("CLI", func() {
var (
packageDir, subPackageDir string
app *kingpin.Application
origWorkingDir string
done chan bool = make(chan bool)
packageDir, subPackageDir, vendorPackageDir string
app *kingpin.Application
origWorkingDir string
done chan bool = make(chan bool)
)
BeforeEach(func() {
packageDir = joinPath(os.Getenv("GOPATH"), "src", "pegomocktest")
packageDir = joinPath(build.Default.GOPATH, "src", "pegomocktest")
Expect(os.MkdirAll(packageDir, 0755)).To(Succeed())
subPackageDir = joinPath(packageDir, "subpackage")
Expect(os.MkdirAll(subPackageDir, 0755)).To(Succeed())
vendorPackageDir = joinPath(packageDir, "vendor", "github.com", "petergtz", "vendored_package")
Expect(os.MkdirAll(vendorPackageDir, 0755)).To(Succeed())
var e error
origWorkingDir, e = os.Getwd()
@@ -63,6 +66,11 @@ var _ = Describe("CLI", func() {
"package pegomocktest; type MyDisplay interface { Show(something string) }")
WriteFile(joinPath(subPackageDir, "subdisplay.go"),
"package subpackage; type SubDisplay interface { ShowMe() }")
WriteFile(joinPath(vendorPackageDir, "iface.go"),
`package vendored_package; type Interface interface{ Foobar() }`)
WriteFile(joinPath(packageDir, "vendordisplay.go"), `package pegomocktest
import ( "github.com/petergtz/vendored_package" )
type VendorDisplay interface { Show(something vendored_package.Interface) }`)
app = kingpin.New("pegomock", "Generates mocks based on interfaces.")
app.Terminate(func(int) { panic("Unexpected terminate") })
@@ -92,6 +100,17 @@ var _ = Describe("CLI", func() {
})
})
Context(`with args "VendorDisplay""`, func() {
It(`generates a file mock_vendordisplay_test.go that contains 'import ( vendored_package "github.com/petergtz/vendored_package" )'`, func() {
main.Run(cmd("pegomock generate VendorDisplay"), os.Stdout, app, done)
Expect(joinPath(packageDir, "mock_vendordisplay_test.go")).To(SatisfyAll(
BeAnExistingFile(),
BeAFileContainingSubString(`vendored_package "github.com/petergtz/vendored_package"`)))
})
})
Context(`with args "pegomocktest/subpackage SubDisplay"`, func() {
It(`generates a file mock_subdisplay_test.go in "pegomocktest" that contains "package pegomocktest_test"`, func() {
main.Run(cmd("pegomock generate pegomocktest/subpackage SubDisplay"), os.Stdout, app, done)

View File

@@ -3,6 +3,7 @@ package util
import (
"errors"
"fmt"
"go/build"
"os"
"path/filepath"
"strings"
@@ -33,7 +34,7 @@ func SourceArgs(args []string) ([]string, error) {
if e != nil {
panic(e)
}
packagePath, err := packagePathFromDirectory(os.Getenv("GOPATH"), workingDir)
packagePath, err := packagePathFromDirectory(build.Default.GOPATH, workingDir)
if err != nil {
return nil, fmt.Errorf("Couldn't determine package path from directory: %v", err)
}

View File

@@ -15,6 +15,7 @@
package watch_test
import (
"go/build"
"os"
"path/filepath"
"testing"
@@ -36,15 +37,17 @@ func TestWatchCommand(t *testing.T) {
var _ = Describe("NewMockFileUpdater", func() {
var (
packageDir, subPackageDir string
origWorkingDir string
packageDir, subPackageDir, vendorPackageDir string
origWorkingDir string
)
BeforeEach(func() {
packageDir = joinPath(os.Getenv("GOPATH"), "src", "pegomocktest")
packageDir = joinPath(build.Default.GOPATH, "src", "pegomocktest")
Expect(os.MkdirAll(packageDir, 0755)).To(Succeed())
subPackageDir = joinPath(packageDir, "subpackage")
Expect(os.MkdirAll(subPackageDir, 0755)).To(Succeed())
vendorPackageDir = joinPath(packageDir, "vendor", "github.com", "petergtz", "vendored_package")
Expect(os.MkdirAll(vendorPackageDir, 0755)).To(Succeed())
var e error
origWorkingDir, e = os.Getwd()
@@ -55,6 +58,12 @@ var _ = Describe("NewMockFileUpdater", func() {
"package pegomocktest; type MyDisplay interface { Show() }")
WriteFile(joinPath(subPackageDir, "subdisplay.go"),
"package subpackage; type SubDisplay interface { ShowMe() }")
WriteFile(joinPath(vendorPackageDir, "iface.go"),
`package vendored_package; type Interface interface{ Foobar() }`)
WriteFile(joinPath(packageDir, "vendordisplay.go"), `package pegomocktest
import ( "github.com/petergtz/vendored_package" )
type VendorDisplay interface { Show(something vendored_package.Interface) }`)
})
AfterEach(func() {
@@ -97,6 +106,19 @@ var _ = Describe("NewMockFileUpdater", func() {
})
})
Context(`and specifying the vendor path`, func() {
It(`Eventually creates a file containing the import ( vendored_package "github.com/petergtz/vendored_package" )'`, func() {
WriteFile(joinPath(packageDir, "interfaces_to_mock"), "VendorDisplay")
watch.NewMockFileUpdater([]string{packageDir}, false).Update()
Expect(joinPath(packageDir, "mock_vendordisplay_test.go")).To(SatisfyAll(
BeAnExistingFile(),
BeAFileContainingSubString(`vendored_package "github.com/petergtz/vendored_package"`)))
})
})
Context("in multiple packages and providing those packages to watch", func() {
It(`Eventually creates correct files in respective directories`, func() {
os.Chdir("..")