Updated Deps

This commit is contained in:
Walter Antolini 2019-04-15 01:41:18 +02:00
parent db2c63a5f6
commit 75886c0f12
No known key found for this signature in database
GPG key ID: 9A8CB88B5717A49F
150 changed files with 9440 additions and 894 deletions

78
Gopkg.lock generated
View file

@ -2,50 +2,110 @@
[[projects]]
digest = "1:d7c5f0bac5337c5098b18d000ee24a9a58d10a6b98824cd1821af74d7219ebea"
name = "github.com/calmh/luhn"
packages = ["."]
pruneopts = ""
revision = "5b2abb343e70180dbf456397c5fd93f14471b08e"
version = "v2.0.0"
[[projects]]
digest = "1:59df7ab87ddca233bb586ff32c6feba12bf787260f6694dc45ceecea9d3e1a7e"
name = "github.com/cenkalti/backoff"
packages = ["."]
revision = "61153c768f31ee5f130071d08fc82b85208528de"
version = "v1.1.0"
pruneopts = ""
revision = "1e4cf3da559842a91afcb6ea6141451e6c30c618"
version = "v2.1.1"
[[projects]]
branch = "master"
digest = "1:50cf302cc52eb618cec25d4daf167ed5593145d43b447b906a9f0d24e271d48b"
name = "github.com/felixge/tcpkeepalive"
packages = ["."]
pruneopts = ""
revision = "5bb0b2dea91e0de550022159b9571aafc72c08ba"
[[projects]]
digest = "1:530233672f656641b365f8efb38ed9fba80e420baff2ce87633813ab3755ed6d"
name = "github.com/golang/mock"
packages = ["gomock"]
revision = "13f360950a79f5864a972c786a10a50e44b69541"
version = "v1.0.0"
pruneopts = ""
revision = "51421b967af1f557f93a59e0057aaf15ca02e29c"
version = "v1.2.0"
[[projects]]
digest = "1:3a86b4526cc15ca4caf041c7f6943b59b3eb3711a9bc832de27b0801b826e019"
name = "github.com/mmatczuk/go-http-tunnel"
packages = [
".",
"id",
"log",
"proto",
"tunnelmock",
]
pruneopts = ""
revision = "75a30abccc8db9d1149845e9985e80cca57758a2"
version = "2.1"
[[projects]]
branch = "master"
digest = "1:1285570ced192ee4703ca44573a4eaf19b5a0895af56f9db2210b171eefd2a41"
name = "golang.org/x/net"
packages = ["context","http2","http2/hpack","idna","lex/httplex"]
packages = [
"http2",
"http2/hpack",
"idna",
"lex/httplex",
]
pruneopts = ""
revision = "c7086645de248775cbf2373cf5ca4d2fa664b8c1"
[[projects]]
branch = "master"
digest = "1:39a1a71adca4b837a25dc6b5fcdd9d175e4597c6d3440f107dfeda31230218e4"
name = "golang.org/x/text"
packages = ["collate","collate/build","internal/colltab","internal/gen","internal/tag","internal/triegen","internal/ucd","language","secure/bidirule","transform","unicode/bidi","unicode/cldr","unicode/norm","unicode/rangetable"]
packages = [
"collate",
"collate/build",
"internal/colltab",
"internal/gen",
"internal/tag",
"internal/triegen",
"internal/ucd",
"language",
"secure/bidirule",
"transform",
"unicode/bidi",
"unicode/cldr",
"unicode/norm",
"unicode/rangetable",
]
pruneopts = ""
revision = "88f656faf3f37f690df1a32515b479415e1a6769"
[[projects]]
branch = "v2"
digest = "1:cedccf16b71e86db87a24f8d4c70b0a855872eb967cb906a66b95de56aefbd0d"
name = "gopkg.in/yaml.v2"
packages = ["."]
revision = "287cf08546ab5e7e37d55a84f7ed3fd1db036de5"
pruneopts = ""
revision = "51d6538a90f86fe93ac480b35f37b2be17fef232"
version = "v2.2.2"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "654fea302b8b5a71ce4f36f4097d0c0caa8150e46109cfbdd462adcd054a6768"
input-imports = [
"github.com/calmh/luhn",
"github.com/cenkalti/backoff",
"github.com/felixge/tcpkeepalive",
"github.com/golang/mock/gomock",
"github.com/mmatczuk/go-http-tunnel",
"github.com/mmatczuk/go-http-tunnel/id",
"github.com/mmatczuk/go-http-tunnel/log",
"github.com/mmatczuk/go-http-tunnel/proto",
"github.com/mmatczuk/go-http-tunnel/tunnelmock",
"golang.org/x/net/http2",
"gopkg.in/yaml.v2",
]
solver-name = "gps-cdcl"
solver-version = 1

View file

@ -27,23 +27,19 @@
[[constraint]]
name = "github.com/cenkalti/backoff"
version = "1.1.0"
version = "2.1.0"
[[constraint]]
name = "github.com/golang/mock"
version = "1.0.0"
[[constraint]]
name = "github.com/google/gops"
version = "0.3.2"
version = "1.2.0"
[[constraint]]
branch = "master"
name = "golang.org/x/net"
[[constraint]]
branch = "v2"
name = "gopkg.in/yaml.v2"
version = "2.2.2"
[[constraint]]
branch = "master"

View file

@ -1,6 +1,7 @@
language: go
go:
- 1.3.3
- 1.7
- 1.x
- tip
before_install:
- go get github.com/mattn/goveralls

View file

@ -24,7 +24,7 @@ See https://godoc.org/github.com/cenkalti/backoff#pkg-examples
[coveralls]: https://coveralls.io/github/cenkalti/backoff?branch=master
[coveralls image]: https://coveralls.io/repos/github/cenkalti/backoff/badge.svg?branch=master
[google-http-java-client]: https://github.com/google/google-http-java-client
[google-http-java-client]: https://github.com/google/google-http-java-client/blob/da1aa993e90285ec18579f1553339b00e19b3ab5/google-http-client/src/main/java/com/google/api/client/util/ExponentialBackOff.java
[exponential backoff wiki]: http://en.wikipedia.org/wiki/Exponential_backoff
[advanced example]: https://godoc.org/github.com/cenkalti/backoff#example_

View file

@ -15,7 +15,7 @@ import "time"
// BackOff is a backoff policy for retrying an operation.
type BackOff interface {
// NextBackOff returns the duration to wait before retrying the operation,
// or backoff.Stop to indicate that no more retries should be made.
// or backoff. Stop to indicate that no more retries should be made.
//
// Example usage:
//

View file

@ -1,9 +1,8 @@
package backoff
import (
"context"
"time"
"golang.org/x/net/context"
)
// BackOffContext is a backoff policy that stops retrying after the context
@ -52,9 +51,13 @@ func (b *backOffContext) Context() context.Context {
func (b *backOffContext) NextBackOff() time.Duration {
select {
case <-b.Context().Done():
case <-b.ctx.Done():
return Stop
default:
return b.BackOff.NextBackOff()
}
next := b.BackOff.NextBackOff()
if deadline, ok := b.ctx.Deadline(); ok && deadline.Sub(time.Now()) < next {
return Stop
}
return next
}

View file

@ -1,10 +1,9 @@
package backoff
import (
"context"
"testing"
"time"
"golang.org/x/net/context"
)
func TestContext(t *testing.T) {

View file

@ -1,9 +1,8 @@
package backoff
import (
"context"
"log"
"golang.org/x/net/context"
)
func ExampleRetry() {

View file

@ -63,7 +63,6 @@ type ExponentialBackOff struct {
currentInterval time.Duration
startTime time.Time
random *rand.Rand
}
// Clock is an interface that returns current time for BackOff.
@ -89,7 +88,6 @@ func NewExponentialBackOff() *ExponentialBackOff {
MaxInterval: DefaultMaxInterval,
MaxElapsedTime: DefaultMaxElapsedTime,
Clock: SystemClock,
random: rand.New(rand.NewSource(time.Now().UnixNano())),
}
b.Reset()
return b
@ -118,16 +116,15 @@ func (b *ExponentialBackOff) NextBackOff() time.Duration {
return Stop
}
defer b.incrementCurrentInterval()
if b.random == nil {
b.random = rand.New(rand.NewSource(time.Now().UnixNano()))
}
return getRandomValueFromInterval(b.RandomizationFactor, b.random.Float64(), b.currentInterval)
return getRandomValueFromInterval(b.RandomizationFactor, rand.Float64(), b.currentInterval)
}
// GetElapsedTime returns the elapsed time since an ExponentialBackOff instance
// is created and is reset when Reset() is called.
//
// The elapsed time is computed using time.Now().UnixNano().
// The elapsed time is computed using time.Now().UnixNano(). It is
// safe to call even while the backoff policy is used by a running
// ticker.
func (b *ExponentialBackOff) GetElapsedTime() time.Duration {
return b.Clock.Now().Sub(b.startTime)
}

View file

@ -15,7 +15,6 @@ type Notify func(error, time.Duration)
// Retry the operation o until it does not return error or BackOff stops.
// o is guaranteed to be run at least once.
// It is the caller's responsibility to reset b after Retry returns.
//
// If o returns a *PermanentError, the operation is not retried, and the
// wrapped error is returned.
@ -29,6 +28,7 @@ func Retry(o Operation, b BackOff) error { return RetryNotify(o, b, nil) }
func RetryNotify(operation Operation, b BackOff, notify Notify) error {
var err error
var next time.Duration
var t *time.Timer
cb := ensureContext(b)
@ -42,7 +42,7 @@ func RetryNotify(operation Operation, b BackOff, notify Notify) error {
return permanent.Err
}
if next = b.NextBackOff(); next == Stop {
if next = cb.NextBackOff(); next == Stop {
return err
}
@ -50,11 +50,15 @@ func RetryNotify(operation Operation, b BackOff, notify Notify) error {
notify(err, next)
}
t := time.NewTimer(next)
if t == nil {
t = time.NewTimer(next)
defer t.Stop()
} else {
t.Reset(next)
}
select {
case <-cb.Context().Done():
t.Stop()
return err
case <-t.C:
}

View file

@ -1,13 +1,12 @@
package backoff
import (
"context"
"errors"
"fmt"
"log"
"testing"
"time"
"golang.org/x/net/context"
)
func TestRetry(t *testing.T) {

View file

@ -1,7 +1,6 @@
package backoff
import (
"runtime"
"sync"
"time"
)
@ -18,9 +17,12 @@ type Ticker struct {
stopOnce sync.Once
}
// NewTicker returns a new Ticker containing a channel that will send the time at times
// specified by the BackOff argument. Ticker is guaranteed to tick at least once.
// The channel is closed when Stop method is called or BackOff stops.
// NewTicker returns a new Ticker containing a channel that will send
// the time at times specified by the BackOff argument. Ticker is
// guaranteed to tick at least once. The channel is closed when Stop
// method is called or BackOff stops. It is not safe to manipulate the
// provided backoff policy (notably calling NextBackOff or Reset)
// while the ticker is running.
func NewTicker(b BackOff) *Ticker {
c := make(chan time.Time)
t := &Ticker{
@ -29,8 +31,8 @@ func NewTicker(b BackOff) *Ticker {
b: ensureContext(b),
stop: make(chan struct{}),
}
t.b.Reset()
go t.run()
runtime.SetFinalizer(t, (*Ticker).Stop)
return t
}
@ -42,7 +44,6 @@ func (t *Ticker) Stop() {
func (t *Ticker) run() {
c := t.c
defer close(c)
t.b.Reset()
// Ticker is guaranteed to tick at least once.
afterC := t.send(time.Now())

View file

@ -1,13 +1,12 @@
package backoff
import (
"context"
"errors"
"fmt"
"log"
"testing"
"time"
"golang.org/x/net/context"
)
func TestTicker(t *testing.T) {
@ -30,6 +29,10 @@ func TestTicker(t *testing.T) {
b := NewExponentialBackOff()
ticker := NewTicker(b)
elapsed := b.GetElapsedTime()
if elapsed > time.Second {
t.Errorf("elapsed time too large: %v", elapsed)
}
var err error
for _ = range ticker.C {

View file

@ -3,13 +3,13 @@ package backoff
import "time"
/*
WithMaxTries creates a wrapper around another BackOff, which will
WithMaxRetries creates a wrapper around another BackOff, which will
return Stop if NextBackOff() has been called too many times since
the last time Reset() was called
Note: Implementation is not thread-safe.
*/
func WithMaxTries(b BackOff, max uint64) BackOff {
func WithMaxRetries(b BackOff, max uint64) BackOff {
return &backOffTries{delegate: b, maxTries: max}
}

View file

@ -9,7 +9,7 @@ import (
func TestMaxTriesHappy(t *testing.T) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
max := 17 + r.Intn(13)
bo := WithMaxTries(&ZeroBackOff{}, uint64(max))
bo := WithMaxRetries(&ZeroBackOff{}, uint64(max))
// Load up the tries count, but reset should clear the record
for ix := 0; ix < max/2; ix++ {
@ -45,7 +45,7 @@ func TestMaxTriesHappy(t *testing.T) {
func TestMaxTriesZero(t *testing.T) {
// It might not make sense, but its okay to send a zero
bo := WithMaxTries(&ZeroBackOff{}, uint64(0))
bo := WithMaxRetries(&ZeroBackOff{}, uint64(0))
for ix := 0; ix < 11; ix++ {
d := bo.NextBackOff()
if d == Stop {

View file

@ -1,9 +1,9 @@
language: go
go:
# we intend to support only the latest version and perhaps the previous one
- 1.7
- 1.8
- 1.9.x
- 1.10.x
- 1.11.x
script:
- go build ./...

View file

@ -1,4 +1,4 @@
gomock [![Build Status](https://travis-ci.org/golang/mock.svg?branch=master)](https://travis-ci.org/golang/mock)
gomock [![Build Status][travis-ci-badge]][travis-ci] [![GoDoc][godoc-badge]][godoc]
======
GoMock is a mocking framework for the [Go programming language][golang]. It
@ -13,7 +13,7 @@ Once you have [installed Go][golang-install], run these commands
to install the `gomock` package and the `mockgen` tool:
go get github.com/golang/mock/gomock
go get github.com/golang/mock/mockgen
go install github.com/golang/mock/mockgen
Documentation
@ -74,13 +74,95 @@ It supports the following flags:
* `-build_flags`: (reflect mode only) Flags passed verbatim to `go build`.
* `-mock_names`: A list of custom names for generated mocks. This is specified
as a comma-separated list of elements of the form
`Repository=MockSensorRepository,Endpoint=MockSensorEndpoint`, where
`Repository` is the interface name and `MockSensorRepository` is the desired
mock name (mock factory method and mock recorder will be named after the mock).
If one of the interfaces has no custom name specified, then default naming
convention will be used.
For an example of the use of `mockgen`, see the `sample/` directory. In simple
cases, you will need only the `-source` flag.
TODO: Brief overview of how to create mock objects and set up expectations, and
an example.
Building Mocks
--------------
[golang]: http://golang.org/
[golang-install]: http://golang.org/doc/install.html#releases
[gomock-ref]: http://godoc.org/github.com/golang/mock/gomock
```go
type Foo interface {
Bar(x int) int
}
Func SUT(f Foo) {
// ...
}
```
```go
func TestFoo(t *testing.T) {
ctrl := gomock.NewController(t)
// Assert that Bar() is invoked.
defer ctrl.Finish()
m := NewMockFoo(ctrl)
// Asserts that the first and only call to Bar() is passed 99.
// Anything else will fail.
m.
EXPECT().
Bar(gomock.Eq(99)).
Return(101)
SUT(m)
}
```
Building Stubs
--------------
```go
type Foo interface {
Bar(x int) int
}
Func SUT(f Foo) {
// ...
}
```
```go
func TestFoo(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := NewMockFoo(ctrl)
// Does not make any assertions. Returns 101 when Bar is invoked with 99.
m.
EXPECT().
Bar(gomock.Eq(99)).
Return(101).
AnyTimes()
// Does not make any assertions. Returns 103 when Bar is invoked with 101.
m.
EXPECT().
Bar(gomock.Eq(101)).
Return(103).
AnyTimes()
SUT(m)
}
```
[golang]: http://golang.org/
[golang-install]: http://golang.org/doc/install.html#releases
[gomock-ref]: http://godoc.org/github.com/golang/mock/gomock
[travis-ci-badge]: https://travis-ci.org/golang/mock.svg?branch=master
[travis-ci]: https://travis-ci.org/golang/mock
[godoc-badge]: https://godoc.org/github.com/golang/mock/gomock?status.svg
[godoc]: https://godoc.org/github.com/golang/mock/gomock

View file

@ -17,18 +17,19 @@ package gomock
import (
"fmt"
"reflect"
"strconv"
"strings"
)
// Call represents an expected call to a mock.
type Call struct {
t TestReporter // for triggering test failures on invalid call setup
t TestHelper // for triggering test failures on invalid call setup
receiver interface{} // the receiver of the method call
method string // the name of the method
methodType reflect.Type // the type of the method
args []Matcher // the args
rets []interface{} // the return values (if any)
receiver interface{} // the receiver of the method call
method string // the name of the method
methodType reflect.Type // the type of the method
args []Matcher // the args
origin string // file and line number of call setup
preReqs []*Call // prerequisite calls
@ -37,9 +38,42 @@ type Call struct {
numCalls int // actual number made
// Actions
doFunc reflect.Value
setArgs map[int]reflect.Value
// actions are called when this Call is called. Each action gets the args and
// can set the return values by returning a non-nil slice. Actions run in the
// order they are created.
actions []func([]interface{}) []interface{}
}
// newCall creates a *Call. It requires the method type in order to support
// unexported methods.
func newCall(t TestHelper, receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call {
t.Helper()
// TODO: check arity, types.
margs := make([]Matcher, len(args))
for i, arg := range args {
if m, ok := arg.(Matcher); ok {
margs[i] = m
} else if arg == nil {
// Handle nil specially so that passing a nil interface value
// will match the typed nils of concrete args.
margs[i] = Nil()
} else {
margs[i] = Eq(arg)
}
}
origin := callerInfo(3)
actions := []func([]interface{}) []interface{}{func([]interface{}) []interface{} {
// Synthesize the zero value for each of the return args' types.
rets := make([]interface{}, methodType.NumOut())
for i := 0; i < methodType.NumOut(); i++ {
rets[i] = reflect.Zero(methodType.Out(i)).Interface()
}
return rets
}}
return &Call{t: t, receiver: receiver, method: method, methodType: methodType,
args: margs, origin: origin, minCalls: 1, maxCalls: 1, actions: actions}
}
// AnyTimes allows the expectation to be called 0 or more times
@ -68,19 +102,67 @@ func (c *Call) MaxTimes(n int) *Call {
return c
}
// Do declares the action to run when the call is matched.
// DoAndReturn declares the action to run when the call is matched.
// The return values from this function are returned by the mocked function.
// It takes an interface{} argument to support n-arity functions.
func (c *Call) Do(f interface{}) *Call {
func (c *Call) DoAndReturn(f interface{}) *Call {
// TODO: Check arity and types here, rather than dying badly elsewhere.
c.doFunc = reflect.ValueOf(f)
v := reflect.ValueOf(f)
c.addAction(func(args []interface{}) []interface{} {
vargs := make([]reflect.Value, len(args))
ft := v.Type()
for i := 0; i < len(args); i++ {
if args[i] != nil {
vargs[i] = reflect.ValueOf(args[i])
} else {
// Use the zero value for the arg.
vargs[i] = reflect.Zero(ft.In(i))
}
}
vrets := v.Call(vargs)
rets := make([]interface{}, len(vrets))
for i, ret := range vrets {
rets[i] = ret.Interface()
}
return rets
})
return c
}
// Do declares the action to run when the call is matched. The function's
// return values are ignored to retain backward compatibility. To use the
// return values call DoAndReturn.
// It takes an interface{} argument to support n-arity functions.
func (c *Call) Do(f interface{}) *Call {
// TODO: Check arity and types here, rather than dying badly elsewhere.
v := reflect.ValueOf(f)
c.addAction(func(args []interface{}) []interface{} {
vargs := make([]reflect.Value, len(args))
ft := v.Type()
for i := 0; i < len(args); i++ {
if args[i] != nil {
vargs[i] = reflect.ValueOf(args[i])
} else {
// Use the zero value for the arg.
vargs[i] = reflect.Zero(ft.In(i))
}
}
v.Call(vargs)
return nil
})
return c
}
// Return declares the values to be returned by the mocked function call.
func (c *Call) Return(rets ...interface{}) *Call {
c.t.Helper()
mt := c.methodType
if len(rets) != mt.NumOut() {
c.t.Fatalf("wrong number of arguments to Return for %T.%v: got %d, want %d",
c.receiver, c.method, len(rets), mt.NumOut())
c.t.Fatalf("wrong number of arguments to Return for %T.%v: got %d, want %d [%s]",
c.receiver, c.method, len(rets), mt.NumOut(), c.origin)
}
for i, ret := range rets {
if got, want := reflect.TypeOf(ret), mt.Out(i); got == want {
@ -91,8 +173,8 @@ func (c *Call) Return(rets ...interface{}) *Call {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
// ok
default:
c.t.Fatalf("argument %d to Return for %T.%v is nil, but %v is not nillable",
i, c.receiver, c.method, want)
c.t.Fatalf("argument %d to Return for %T.%v is nil, but %v is not nillable [%s]",
i, c.receiver, c.method, want, c.origin)
}
} else if got.AssignableTo(want) {
// Assignable type relation. Make the assignment now so that the generated code
@ -101,31 +183,36 @@ func (c *Call) Return(rets ...interface{}) *Call {
v.Set(reflect.ValueOf(ret))
rets[i] = v.Interface()
} else {
c.t.Fatalf("wrong type of argument %d to Return for %T.%v: %v is not assignable to %v",
i, c.receiver, c.method, got, want)
c.t.Fatalf("wrong type of argument %d to Return for %T.%v: %v is not assignable to %v [%s]",
i, c.receiver, c.method, got, want, c.origin)
}
}
c.rets = rets
c.addAction(func([]interface{}) []interface{} {
return rets
})
return c
}
// Times declares the exact number of times a function call is expected to be executed.
func (c *Call) Times(n int) *Call {
c.minCalls, c.maxCalls = n, n
return c
}
// SetArg declares an action that will set the nth argument's value,
// indirected through a pointer.
// indirected through a pointer. Or, in the case of a slice, SetArg
// will copy value's elements into the nth argument.
func (c *Call) SetArg(n int, value interface{}) *Call {
if c.setArgs == nil {
c.setArgs = make(map[int]reflect.Value)
}
c.t.Helper()
mt := c.methodType
// TODO: This will break on variadic methods.
// We will need to check those at invocation time.
if n < 0 || n >= mt.NumIn() {
c.t.Fatalf("SetArg(%d, ...) called for a method with %d args", n, mt.NumIn())
c.t.Fatalf("SetArg(%d, ...) called for a method with %d args [%s]",
n, mt.NumIn(), c.origin)
}
// Permit setting argument through an interface.
// In the interface case, we don't (nay, can't) check the type here.
@ -134,14 +221,28 @@ func (c *Call) SetArg(n int, value interface{}) *Call {
case reflect.Ptr:
dt := at.Elem()
if vt := reflect.TypeOf(value); !vt.AssignableTo(dt) {
c.t.Fatalf("SetArg(%d, ...) argument is a %v, not assignable to %v", n, vt, dt)
c.t.Fatalf("SetArg(%d, ...) argument is a %v, not assignable to %v [%s]",
n, vt, dt, c.origin)
}
case reflect.Interface:
// nothing to do
case reflect.Slice:
// nothing to do
default:
c.t.Fatalf("SetArg(%d, ...) referring to argument of non-pointer non-interface type %v", n, at)
c.t.Fatalf("SetArg(%d, ...) referring to argument of non-pointer non-interface non-slice type %v [%s]",
n, at, c.origin)
}
c.setArgs[n] = reflect.ValueOf(value)
c.addAction(func(args []interface{}) []interface{} {
v := reflect.ValueOf(value)
switch reflect.TypeOf(args[n]).Kind() {
case reflect.Slice:
setSlice(args[n], v)
default:
reflect.ValueOf(args[n]).Elem().Set(v)
}
return nil
})
return c
}
@ -157,8 +258,10 @@ func (c *Call) isPreReq(other *Call) bool {
// After declares that the call may only match after preReq has been exhausted.
func (c *Call) After(preReq *Call) *Call {
c.t.Helper()
if c == preReq {
c.t.Fatalf("A call isn't allowed to be it's own prerequisite")
c.t.Fatalf("A call isn't allowed to be its own prerequisite")
}
if preReq.isPreReq(c) {
c.t.Fatalf("Loop in call order: %v is a prerequisite to %v (possibly indirectly).", c, preReq)
@ -168,7 +271,7 @@ func (c *Call) After(preReq *Call) *Call {
return c
}
// Returns true iff the minimum number of calls have been made.
// Returns true if the minimum number of calls have been made.
func (c *Call) satisfied() bool {
return c.numCalls >= c.minCalls
}
@ -184,31 +287,108 @@ func (c *Call) String() string {
args[i] = arg.String()
}
arguments := strings.Join(args, ", ")
return fmt.Sprintf("%T.%v(%s)", c.receiver, c.method, arguments)
return fmt.Sprintf("%T.%v(%s) %s", c.receiver, c.method, arguments, c.origin)
}
// Tests if the given call matches the expected call.
func (c *Call) matches(args []interface{}) bool {
if len(args) != len(c.args) {
return false
}
for i, m := range c.args {
if !m.Matches(args[i]) {
return false
// If yes, returns nil. If no, returns error with message explaining why it does not match.
func (c *Call) matches(args []interface{}) error {
if !c.methodType.IsVariadic() {
if len(args) != len(c.args) {
return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d",
c.origin, len(args), len(c.args))
}
for i, m := range c.args {
if !m.Matches(args[i]) {
return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
c.origin, strconv.Itoa(i), args[i], m)
}
}
} else {
if len(c.args) < c.methodType.NumIn()-1 {
return fmt.Errorf("Expected call at %s has the wrong number of matchers. Got: %d, want: %d",
c.origin, len(c.args), c.methodType.NumIn()-1)
}
if len(c.args) != c.methodType.NumIn() && len(args) != len(c.args) {
return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d",
c.origin, len(args), len(c.args))
}
if len(args) < len(c.args)-1 {
return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: greater than or equal to %d",
c.origin, len(args), len(c.args)-1)
}
for i, m := range c.args {
if i < c.methodType.NumIn()-1 {
// Non-variadic args
if !m.Matches(args[i]) {
return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
c.origin, strconv.Itoa(i), args[i], m)
}
continue
}
// The last arg has a possibility of a variadic argument, so let it branch
// sample: Foo(a int, b int, c ...int)
if i < len(c.args) && i < len(args) {
if m.Matches(args[i]) {
// Got Foo(a, b, c) want Foo(matcherA, matcherB, gomock.Any())
// Got Foo(a, b, c) want Foo(matcherA, matcherB, someSliceMatcher)
// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC)
// Got Foo(a, b) want Foo(matcherA, matcherB)
// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD)
continue
}
}
// The number of actual args don't match the number of matchers,
// or the last matcher is a slice and the last arg is not.
// If this function still matches it is because the last matcher
// matches all the remaining arguments or the lack of any.
// Convert the remaining arguments, if any, into a slice of the
// expected type.
vargsType := c.methodType.In(c.methodType.NumIn() - 1)
vargs := reflect.MakeSlice(vargsType, 0, len(args)-i)
for _, arg := range args[i:] {
vargs = reflect.Append(vargs, reflect.ValueOf(arg))
}
if m.Matches(vargs.Interface()) {
// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, gomock.Any())
// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, someSliceMatcher)
// Got Foo(a, b) want Foo(matcherA, matcherB, gomock.Any())
// Got Foo(a, b) want Foo(matcherA, matcherB, someEmptySliceMatcher)
break
}
// Wrong number of matchers or not match. Fail.
// Got Foo(a, b) want Foo(matcherA, matcherB, matcherC, matcherD)
// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC, matcherD)
// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD, matcherE)
// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, matcherC, matcherD)
// Got Foo(a, b, c) want Foo(matcherA, matcherB)
return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
c.origin, strconv.Itoa(i), args[i:], c.args[i])
}
}
// Check that all prerequisite calls have been satisfied.
for _, preReqCall := range c.preReqs {
if !preReqCall.satisfied() {
return false
return fmt.Errorf("Expected call at %s doesn't have a prerequisite call satisfied:\n%v\nshould be called before:\n%v",
c.origin, preReqCall, c)
}
}
return true
// Check that the call is not exhausted.
if c.exhausted() {
return fmt.Errorf("Expected call at %s has already been called the max number of times.", c.origin)
}
return nil
}
// dropPrereqs tells the expected Call to not re-check prerequite calls any
// dropPrereqs tells the expected Call to not re-check prerequisite calls any
// longer, and to return its current set.
func (c *Call) dropPrereqs() (preReqs []*Call) {
preReqs = c.preReqs
@ -216,38 +396,9 @@ func (c *Call) dropPrereqs() (preReqs []*Call) {
return
}
func (c *Call) call(args []interface{}) (rets []interface{}, action func()) {
func (c *Call) call(args []interface{}) []func([]interface{}) []interface{} {
c.numCalls++
// Actions
if c.doFunc.IsValid() {
doArgs := make([]reflect.Value, len(args))
ft := c.doFunc.Type()
for i := 0; i < len(args); i++ {
if args[i] != nil {
doArgs[i] = reflect.ValueOf(args[i])
} else {
// Use the zero value for the arg.
doArgs[i] = reflect.Zero(ft.In(i))
}
}
action = func() { c.doFunc.Call(doArgs) }
}
for n, v := range c.setArgs {
reflect.ValueOf(args[n]).Elem().Set(v)
}
rets = c.rets
if rets == nil {
// Synthesize the zero value for each of the return args' types.
mt := c.methodType
rets = make([]interface{}, mt.NumOut())
for i := 0; i < mt.NumOut(); i++ {
rets[i] = reflect.Zero(mt.Out(i)).Interface()
}
}
return
return c.actions
}
// InOrder declares that the given calls should occur in order.
@ -256,3 +407,14 @@ func InOrder(calls ...*Call) {
calls[i].After(calls[i-1])
}
}
func setSlice(arg interface{}, v reflect.Value) {
va := reflect.ValueOf(arg)
for i := 0; i < v.Len(); i++ {
va.Index(i).Set(v.Index(i))
}
}
func (c *Call) addAction(action func([]interface{}) []interface{}) {
c.actions = append(c.actions, action)
}

View file

@ -1,6 +1,8 @@
package gomock
import "testing"
import (
"testing"
)
type mockTestReporter struct {
errorCalls int
@ -15,6 +17,8 @@ func (o *mockTestReporter) Fatalf(format string, args ...interface{}) {
o.fatalCalls++
}
func (o *mockTestReporter) Helper() {}
func TestCall_After(t *testing.T) {
t.Run("SelfPrereqCallsFatalf", func(t *testing.T) {
tr1 := &mockTestReporter{}

View file

@ -14,63 +14,95 @@
package gomock
import (
"bytes"
"fmt"
)
// callSet represents a set of expected calls, indexed by receiver and method
// name.
type callSet map[interface{}]map[string][]*Call
type callSet struct {
// Calls that are still expected.
expected map[callSetKey][]*Call
// Calls that have been exhausted.
exhausted map[callSetKey][]*Call
}
// callSetKey is the key in the maps in callSet
type callSetKey struct {
receiver interface{}
fname string
}
func newCallSet() *callSet {
return &callSet{make(map[callSetKey][]*Call), make(map[callSetKey][]*Call)}
}
// Add adds a new expected call.
func (cs callSet) Add(call *Call) {
methodMap, ok := cs[call.receiver]
if !ok {
methodMap = make(map[string][]*Call)
cs[call.receiver] = methodMap
key := callSetKey{call.receiver, call.method}
m := cs.expected
if call.exhausted() {
m = cs.exhausted
}
methodMap[call.method] = append(methodMap[call.method], call)
m[key] = append(m[key], call)
}
// Remove removes an expected call.
func (cs callSet) Remove(call *Call) {
methodMap, ok := cs[call.receiver]
if !ok {
return
}
sl := methodMap[call.method]
for i, c := range sl {
key := callSetKey{call.receiver, call.method}
calls := cs.expected[key]
for i, c := range calls {
if c == call {
// quick removal; we don't need to maintain call order
if len(sl) > 1 {
sl[i] = sl[len(sl)-1]
}
methodMap[call.method] = sl[:len(sl)-1]
// maintain order for remaining calls
cs.expected[key] = append(calls[:i], calls[i+1:]...)
cs.exhausted[key] = append(cs.exhausted[key], call)
break
}
}
}
// FindMatch searches for a matching call. Returns nil if no call matched.
func (cs callSet) FindMatch(receiver interface{}, method string, args []interface{}) *Call {
methodMap, ok := cs[receiver]
if !ok {
return nil
}
calls, ok := methodMap[method]
if !ok {
return nil
}
// FindMatch searches for a matching call. Returns error with explanation message if no call matched.
func (cs callSet) FindMatch(receiver interface{}, method string, args []interface{}) (*Call, error) {
key := callSetKey{receiver, method}
// Search through the unordered set of calls expected on a method on a
// receiver.
for _, call := range calls {
// A call should not normally still be here if exhausted,
// but it can happen if, for instance, .Times(0) was used.
// Pretend the call doesn't match.
if call.exhausted() {
continue
}
if call.matches(args) {
return call
// Search through the expected calls.
expected := cs.expected[key]
var callsErrors bytes.Buffer
for _, call := range expected {
err := call.matches(args)
if err != nil {
fmt.Fprintf(&callsErrors, "\n%v", err)
} else {
return call, nil
}
}
return nil
// If we haven't found a match then search through the exhausted calls so we
// get useful error messages.
exhausted := cs.exhausted[key]
for _, call := range exhausted {
if err := call.matches(args); err != nil {
fmt.Fprintf(&callsErrors, "\n%v", err)
}
}
if len(expected)+len(exhausted) == 0 {
fmt.Fprintf(&callsErrors, "there are no expected calls of the method %q for that receiver", method)
}
return nil, fmt.Errorf(callsErrors.String())
}
// Failures returns the calls that are not satisfied.
func (cs callSet) Failures() []*Call {
failures := make([]*Call, 0, len(cs.expected))
for _, calls := range cs.expected {
for _, call := range calls {
if !call.satisfied() {
failures = append(failures, call)
}
}
}
return failures
}

76
vendor/github.com/golang/mock/gomock/callset_test.go generated vendored Normal file
View file

@ -0,0 +1,76 @@
// Copyright 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gomock
import (
"reflect"
"testing"
)
type receiverType struct{}
func (receiverType) Func() {}
func TestCallSetAdd(t *testing.T) {
method := "TestMethod"
var receiver interface{} = "TestReceiver"
cs := newCallSet()
numCalls := 10
for i := 0; i < numCalls; i++ {
cs.Add(newCall(t, receiver, method, reflect.TypeOf(receiverType{}.Func)))
}
call, err := cs.FindMatch(receiver, method, []interface{}{})
if err != nil {
t.Fatalf("FindMatch: %v", err)
}
if call == nil {
t.Fatalf("FindMatch: Got nil, want non-nil *Call")
}
}
func TestCallSetRemove(t *testing.T) {
method := "TestMethod"
var receiver interface{} = "TestReceiver"
cs := newCallSet()
ourCalls := []*Call{}
numCalls := 10
for i := 0; i < numCalls; i++ {
// NOTE: abuse the `numCalls` value to convey initial ordering of mocked calls
generatedCall := &Call{receiver: receiver, method: method, numCalls: i}
cs.Add(generatedCall)
ourCalls = append(ourCalls, generatedCall)
}
// validateOrder validates that the calls in the array are ordered as they were added
validateOrder := func(calls []*Call) {
// lastNum tracks the last `numCalls` (call order) value seen
lastNum := -1
for _, c := range calls {
if lastNum >= c.numCalls {
t.Errorf("found call %d after call %d", c.numCalls, lastNum)
}
lastNum = c.numCalls
}
}
for _, c := range ourCalls {
validateOrder(cs.expected[callSetKey{receiver, method}])
cs.Remove(c)
}
}

View file

@ -56,8 +56,10 @@
package gomock
import (
"context"
"fmt"
"reflect"
"runtime"
"sync"
)
@ -68,97 +70,147 @@ type TestReporter interface {
Fatalf(format string, args ...interface{})
}
// TestHelper is a TestReporter that has the Helper method. It is satisfied
// by the standard library's *testing.T.
type TestHelper interface {
TestReporter
Helper()
}
// A Controller represents the top-level control of a mock ecosystem.
// It defines the scope and lifetime of mock objects, as well as their expectations.
// It is safe to call Controller's methods from multiple goroutines.
type Controller struct {
// T should only be called within a generated mock. It is not intended to
// be used in user code and may be changed in future versions. T is the
// TestReporter passed in when creating the Controller via NewController.
// If the TestReporter does not implment a TestHelper it will be wrapped
// with a nopTestHelper.
T TestHelper
mu sync.Mutex
t TestReporter
expectedCalls callSet
expectedCalls *callSet
finished bool
}
func NewController(t TestReporter) *Controller {
h, ok := t.(TestHelper)
if !ok {
h = nopTestHelper{t}
}
return &Controller{
t: t,
expectedCalls: make(callSet),
T: h,
expectedCalls: newCallSet(),
}
}
type cancelReporter struct {
TestHelper
cancel func()
}
func (r *cancelReporter) Errorf(format string, args ...interface{}) {
r.TestHelper.Errorf(format, args...)
}
func (r *cancelReporter) Fatalf(format string, args ...interface{}) {
defer r.cancel()
r.TestHelper.Fatalf(format, args...)
}
// WithContext returns a new Controller and a Context, which is cancelled on any
// fatal failure.
func WithContext(ctx context.Context, t TestReporter) (*Controller, context.Context) {
h, ok := t.(TestHelper)
if !ok {
h = nopTestHelper{t}
}
ctx, cancel := context.WithCancel(ctx)
return NewController(&cancelReporter{h, cancel}), ctx
}
type nopTestHelper struct {
TestReporter
}
func (h nopTestHelper) Helper() {}
func (ctrl *Controller) RecordCall(receiver interface{}, method string, args ...interface{}) *Call {
ctrl.T.Helper()
recv := reflect.ValueOf(receiver)
for i := 0; i < recv.Type().NumMethod(); i++ {
if recv.Type().Method(i).Name == method {
return ctrl.RecordCallWithMethodType(receiver, method, recv.Method(i).Type(), args...)
}
}
ctrl.t.Fatalf("gomock: failed finding method %s on %T", method, receiver)
// In case t.Fatalf does not panic.
panic(fmt.Sprintf("gomock: failed finding method %s on %T", method, receiver))
ctrl.T.Fatalf("gomock: failed finding method %s on %T", method, receiver)
panic("unreachable")
}
func (ctrl *Controller) RecordCallWithMethodType(receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call {
// TODO: check arity, types.
margs := make([]Matcher, len(args))
for i, arg := range args {
if m, ok := arg.(Matcher); ok {
margs[i] = m
} else if arg == nil {
// Handle nil specially so that passing a nil interface value
// will match the typed nils of concrete args.
margs[i] = Nil()
} else {
margs[i] = Eq(arg)
}
}
ctrl.T.Helper()
call := newCall(ctrl.T, receiver, method, methodType, args...)
ctrl.mu.Lock()
defer ctrl.mu.Unlock()
call := &Call{t: ctrl.t, receiver: receiver, method: method, methodType: methodType, args: margs, minCalls: 1, maxCalls: 1}
ctrl.expectedCalls.Add(call)
return call
}
func (ctrl *Controller) Call(receiver interface{}, method string, args ...interface{}) []interface{} {
ctrl.mu.Lock()
defer ctrl.mu.Unlock()
ctrl.T.Helper()
expected := ctrl.expectedCalls.FindMatch(receiver, method, args)
if expected == nil {
ctrl.t.Fatalf("no matching expected call: %T.%v(%v)", receiver, method, args)
}
// Nest this code so we can use defer to make sure the lock is released.
actions := func() []func([]interface{}) []interface{} {
ctrl.T.Helper()
ctrl.mu.Lock()
defer ctrl.mu.Unlock()
// Two things happen here:
// * the matching call no longer needs to check prerequite calls,
// * and the prerequite calls are no longer expected, so remove them.
preReqCalls := expected.dropPrereqs()
for _, preReqCall := range preReqCalls {
ctrl.expectedCalls.Remove(preReqCall)
}
expected, err := ctrl.expectedCalls.FindMatch(receiver, method, args)
if err != nil {
origin := callerInfo(2)
ctrl.T.Fatalf("Unexpected call to %T.%v(%v) at %s because: %s", receiver, method, args, origin, err)
}
rets, action := expected.call(args)
if expected.exhausted() {
ctrl.expectedCalls.Remove(expected)
}
// Two things happen here:
// * the matching call no longer needs to check prerequite calls,
// * and the prerequite calls are no longer expected, so remove them.
preReqCalls := expected.dropPrereqs()
for _, preReqCall := range preReqCalls {
ctrl.expectedCalls.Remove(preReqCall)
}
// Don't hold the lock while doing the call's action (if any)
// so that actions may execute concurrently.
// We use the deferred Unlock to capture any panics that happen above;
// here we add a deferred Lock to balance it.
ctrl.mu.Unlock()
defer ctrl.mu.Lock()
if action != nil {
action()
actions := expected.call(args)
if expected.exhausted() {
ctrl.expectedCalls.Remove(expected)
}
return actions
}()
var rets []interface{}
for _, action := range actions {
if r := action(args); r != nil {
rets = r
}
}
return rets
}
func (ctrl *Controller) Finish() {
ctrl.T.Helper()
ctrl.mu.Lock()
defer ctrl.mu.Unlock()
if ctrl.finished {
ctrl.T.Fatalf("Controller.Finish was called more than once. It has to be called exactly once.")
}
ctrl.finished = true
// If we're currently panicking, probably because this is a deferred call,
// pass through the panic.
if err := recover(); err != nil {
@ -166,18 +218,18 @@ func (ctrl *Controller) Finish() {
}
// Check that all remaining expected calls are satisfied.
failures := false
for _, methodMap := range ctrl.expectedCalls {
for _, calls := range methodMap {
for _, call := range calls {
if !call.satisfied() {
ctrl.t.Errorf("missing call(s) to %v", call)
failures = true
}
}
}
failures := ctrl.expectedCalls.Failures()
for _, call := range failures {
ctrl.T.Errorf("missing call(s) to %v", call)
}
if failures {
ctrl.t.Fatalf("aborting test due to missing call(s)")
if len(failures) != 0 {
ctrl.T.Fatalf("aborting test due to missing call(s)")
}
}
func callerInfo(skip int) string {
if _, file, line, ok := runtime.Caller(skip + 1); ok {
return fmt.Sprintf("%s:%d", file, line)
}
return "unknown file"
}

View file

@ -19,6 +19,8 @@ import (
"reflect"
"testing"
"strings"
"github.com/golang/mock/gomock"
)
@ -53,7 +55,7 @@ func (e *ErrorReporter) assertFail(msg string) {
}
// Use to check that code triggers a fatal test failure.
func (e *ErrorReporter) assertFatal(fn func()) {
func (e *ErrorReporter) assertFatal(fn func(), expectedErrMsgs ...string) {
defer func() {
err := recover()
if err == nil {
@ -66,6 +68,18 @@ func (e *ErrorReporter) assertFatal(fn func()) {
e.t.Error("Expected fatal failure, but got a", actual)
} else if token, ok := err.(*struct{}); ok && token == &e.fatalToken {
// This is okay - the panic is from Fatalf().
if expectedErrMsgs != nil {
// assert that the actual error message
// contains expectedErrMsgs
// check the last actualErrMsg, because the previous messages come from previous errors
actualErrMsg := e.log[len(e.log)-1]
for _, expectedErrMsg := range expectedErrMsgs {
if !strings.Contains(actualErrMsg, expectedErrMsg) {
e.t.Errorf("Error message:\ngot: %q\nwant to contain: %q\n", actualErrMsg, expectedErrMsg)
}
}
}
return
} else {
// Some other panic.
@ -108,6 +122,15 @@ func (e *ErrorReporter) Fatalf(format string, args ...interface{}) {
panic(&e.fatalToken)
}
type HelperReporter struct {
gomock.TestReporter
helper int
}
func (h *HelperReporter) Helper() {
h.helper++
}
// A type purely for use as a receiver in testing the Controller.
type Subject struct{}
@ -119,6 +142,20 @@ func (s *Subject) BarMethod(arg string) int {
return 0
}
func (s *Subject) VariadicMethod(arg int, vararg ...string) {}
// A type purely for ActOnTestStructMethod
type TestStruct struct {
Number int
Message string
}
func (s *Subject) ActOnTestStructMethod(arg TestStruct, arg1 int) int {
return 0
}
func (s *Subject) SetArgMethod(sliceArg []byte, ptrArg *int) {}
func assertEqual(t *testing.T, expected interface{}, actual interface{}) {
if !reflect.DeepEqual(expected, actual) {
t.Errorf("Expected %+v, but got %+v", expected, actual)
@ -140,6 +177,31 @@ func TestNoCalls(t *testing.T) {
reporter.assertPass("No calls expected or made.")
}
func TestNoRecordedCallsForAReceiver(t *testing.T) {
reporter, ctrl := createFixtures(t)
subject := new(Subject)
reporter.assertFatal(func() {
ctrl.Call(subject, "NotRecordedMethod", "argument")
}, "Unexpected call to", "there are no expected calls of the method \"NotRecordedMethod\" for that receiver")
ctrl.Finish()
}
func TestNoRecordedMatchingMethodNameForAReceiver(t *testing.T) {
reporter, ctrl := createFixtures(t)
subject := new(Subject)
ctrl.RecordCall(subject, "FooMethod", "argument")
reporter.assertFatal(func() {
ctrl.Call(subject, "NotRecordedMethod", "argument")
}, "Unexpected call to", "there are no expected calls of the method \"NotRecordedMethod\" for that receiver")
reporter.assertFatal(func() {
// The expected call wasn't made.
ctrl.Finish()
})
}
// This tests that a call with an arguments of some primitive type matches a recorded call.
func TestExpectedMethodCall(t *testing.T) {
reporter, ctrl := createFixtures(t)
subject := new(Subject)
@ -187,11 +249,68 @@ func TestUnexpectedArgCount(t *testing.T) {
reporter.assertFatal(func() {
// This call is made with the wrong number of arguments...
ctrl.Call(subject, "FooMethod", "argument", "extra_argument")
})
}, "Unexpected call to", "wrong number of arguments", "Got: 2, want: 1")
reporter.assertFatal(func() {
// ... so is this.
ctrl.Call(subject, "FooMethod")
}, "Unexpected call to", "wrong number of arguments", "Got: 0, want: 1")
reporter.assertFatal(func() {
// The expected call wasn't made.
ctrl.Finish()
})
}
// This tests that a call with complex arguments (a struct and some primitive type) matches a recorded call.
func TestExpectedMethodCall_CustomStruct(t *testing.T) {
reporter, ctrl := createFixtures(t)
subject := new(Subject)
expectedArg0 := TestStruct{Number: 123, Message: "hello"}
ctrl.RecordCall(subject, "ActOnTestStructMethod", expectedArg0, 15)
ctrl.Call(subject, "ActOnTestStructMethod", expectedArg0, 15)
reporter.assertPass("Expected method call made.")
}
func TestUnexpectedArgValue_FirstArg(t *testing.T) {
reporter, ctrl := createFixtures(t)
defer reporter.recoverUnexpectedFatal()
subject := new(Subject)
expectedArg0 := TestStruct{Number: 123, Message: "hello"}
ctrl.RecordCall(subject, "ActOnTestStructMethod", expectedArg0, 15)
reporter.assertFatal(func() {
// the method argument (of TestStruct type) has 1 unexpected value (for the Message field)
ctrl.Call(subject, "ActOnTestStructMethod", TestStruct{Number: 123, Message: "no message"}, 15)
}, "Unexpected call to", "doesn't match the argument at index 0",
"Got: {123 no message}\nWant: is equal to {123 hello}")
reporter.assertFatal(func() {
// the method argument (of TestStruct type) has 2 unexpected values (for both fields)
ctrl.Call(subject, "ActOnTestStructMethod", TestStruct{Number: 11, Message: "no message"}, 15)
}, "Unexpected call to", "doesn't match the argument at index 0",
"Got: {11 no message}\nWant: is equal to {123 hello}")
reporter.assertFatal(func() {
// The expected call wasn't made.
ctrl.Finish()
})
}
func TestUnexpectedArgValue_SecondtArg(t *testing.T) {
reporter, ctrl := createFixtures(t)
defer reporter.recoverUnexpectedFatal()
subject := new(Subject)
expectedArg0 := TestStruct{Number: 123, Message: "hello"}
ctrl.RecordCall(subject, "ActOnTestStructMethod", expectedArg0, 15)
reporter.assertFatal(func() {
ctrl.Call(subject, "ActOnTestStructMethod", TestStruct{Number: 123, Message: "hello"}, 3)
}, "Unexpected call to", "doesn't match the argument at index 1",
"Got: 3\nWant: is equal to 15")
reporter.assertFatal(func() {
// The expected call wasn't made.
ctrl.Finish()
@ -317,6 +436,74 @@ func TestDo(t *testing.T) {
ctrl.Finish()
}
func TestDoAndReturn(t *testing.T) {
_, ctrl := createFixtures(t)
subject := new(Subject)
doCalled := false
var argument string
ctrl.RecordCall(subject, "FooMethod", "argument").DoAndReturn(
func(arg string) int {
doCalled = true
argument = arg
return 5
})
if doCalled {
t.Error("Do() callback called too early.")
}
rets := ctrl.Call(subject, "FooMethod", "argument")
if !doCalled {
t.Error("Do() callback not called.")
}
if "argument" != argument {
t.Error("Do callback received wrong argument.")
}
if len(rets) != 1 {
t.Fatalf("Return values from Call: got %d, want 1", len(rets))
}
if ret, ok := rets[0].(int); !ok {
t.Fatalf("Return value is not an int")
} else if ret != 5 {
t.Errorf("DoAndReturn return value: got %d, want 5", ret)
}
ctrl.Finish()
}
func TestSetArgSlice(t *testing.T) {
_, ctrl := createFixtures(t)
subject := new(Subject)
var in = []byte{4, 5, 6}
var set = []byte{1, 2, 3}
ctrl.RecordCall(subject, "SetArgMethod", in, nil).SetArg(0, set)
ctrl.Call(subject, "SetArgMethod", in, nil)
if !reflect.DeepEqual(in, set) {
t.Error("Expected SetArg() to modify input slice argument")
}
ctrl.Finish()
}
func TestSetArgPtr(t *testing.T) {
_, ctrl := createFixtures(t)
subject := new(Subject)
var in int = 43
const set = 42
ctrl.RecordCall(subject, "SetArgMethod", nil, &in).SetArg(1, set)
ctrl.Call(subject, "SetArgMethod", nil, &in)
if in != set {
t.Error("Expected SetArg() to modify value pointed to by argument")
}
ctrl.Finish()
}
func TestReturn(t *testing.T) {
_, ctrl := createFixtures(t)
subject := new(Subject)
@ -393,11 +580,12 @@ func TestOrderedCallsInCorrect(t *testing.T) {
ctrl.Call(subjectOne, "FooMethod", "1")
reporter.assertFatal(func() {
// FooMethod(2) should be called before BarMethod(3)
ctrl.Call(subjectTwo, "BarMethod", "3")
})
}, "Unexpected call to", "Subject.BarMethod([3])", "doesn't have a prerequisite call satisfied")
}
// Test that calls that are prerequites to other calls but have maxCalls >
// Test that calls that are prerequisites to other calls but have maxCalls >
// minCalls are removed from the expected call set.
func TestOrderedCallsWithPreReqMaxUnbounded(t *testing.T) {
reporter, ctrl, subjectOne, subjectTwo := commonTestOrderedCalls(t)
@ -473,3 +661,79 @@ func TestTimes0(t *testing.T) {
ctrl.Call(s, "FooMethod", "arg")
})
}
func TestVariadicMatching(t *testing.T) {
rep, ctrl := createFixtures(t)
defer rep.recoverUnexpectedFatal()
s := new(Subject)
ctrl.RecordCall(s, "VariadicMethod", 0, "1", "2")
ctrl.Call(s, "VariadicMethod", 0, "1", "2")
ctrl.Finish()
rep.assertPass("variadic matching works")
}
func TestVariadicNoMatch(t *testing.T) {
rep, ctrl := createFixtures(t)
defer rep.recoverUnexpectedFatal()
s := new(Subject)
ctrl.RecordCall(s, "VariadicMethod", 0)
rep.assertFatal(func() {
ctrl.Call(s, "VariadicMethod", 1)
}, "Expected call at", "doesn't match the argument at index 0",
"Got: 1\nWant: is equal to 0")
ctrl.Call(s, "VariadicMethod", 0)
ctrl.Finish()
}
func TestVariadicMatchingWithSlice(t *testing.T) {
testCases := [][]string{
{"1"},
{"1", "2"},
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("%d arguments", len(tc)), func(t *testing.T) {
rep, ctrl := createFixtures(t)
defer rep.recoverUnexpectedFatal()
s := new(Subject)
ctrl.RecordCall(s, "VariadicMethod", 1, tc)
args := make([]interface{}, len(tc)+1)
args[0] = 1
for i, arg := range tc {
args[i+1] = arg
}
ctrl.Call(s, "VariadicMethod", args...)
ctrl.Finish()
rep.assertPass("slices can be used as matchers for variadic arguments")
})
}
}
func TestDuplicateFinishCallFails(t *testing.T) {
rep, ctrl := createFixtures(t)
ctrl.Finish()
rep.assertPass("the first Finish call should succeed")
rep.assertFatal(ctrl.Finish, "Controller.Finish was called more than once. It has to be called exactly once.")
}
func TestTestNoHelper(t *testing.T) {
ctrlNoHelper := gomock.NewController(NewErrorReporter(t))
// doesn't panic
ctrlNoHelper.T.Helper()
}
func TestTestWithHelper(t *testing.T) {
withHelper := &HelperReporter{TestReporter: NewErrorReporter(t)}
ctrlWithHelper := gomock.NewController(withHelper)
ctrlWithHelper.T.Helper()
if withHelper.helper == 0 {
t.Fatal("expected Helper to be invoked")
}
}

View file

@ -1,6 +1,7 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: github.com/golang/mock/gomock (interfaces: Matcher)
// Package mock_gomock is a generated GoMock package.
package mock_gomock
import (
@ -27,30 +28,34 @@ func NewMockMatcher(ctrl *gomock.Controller) *MockMatcher {
}
// EXPECT returns an object that allows the caller to indicate expected use
func (_m *MockMatcher) EXPECT() *MockMatcherMockRecorder {
return _m.recorder
func (m *MockMatcher) EXPECT() *MockMatcherMockRecorder {
return m.recorder
}
// Matches mocks base method
func (_m *MockMatcher) Matches(_param0 interface{}) bool {
ret := _m.ctrl.Call(_m, "Matches", _param0)
func (m *MockMatcher) Matches(arg0 interface{}) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Matches", arg0)
ret0, _ := ret[0].(bool)
return ret0
}
// Matches indicates an expected call of Matches
func (_mr *MockMatcherMockRecorder) Matches(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "Matches", reflect.TypeOf((*MockMatcher)(nil).Matches), arg0)
func (mr *MockMatcherMockRecorder) Matches(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Matches", reflect.TypeOf((*MockMatcher)(nil).Matches), arg0)
}
// String mocks base method
func (_m *MockMatcher) String() string {
ret := _m.ctrl.Call(_m, "String")
func (m *MockMatcher) String() string {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "String")
ret0, _ := ret[0].(string)
return ret0
}
// String indicates an expected call of String
func (_mr *MockMatcherMockRecorder) String() *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "String", reflect.TypeOf((*MockMatcher)(nil).String))
func (mr *MockMatcherMockRecorder) String() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "String", reflect.TypeOf((*MockMatcher)(nil).String))
}

View file

@ -1,5 +1,3 @@
//go:generate mockgen -destination mock_matcher/mock_matcher.go github.com/golang/mock/gomock Matcher
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
@ -87,6 +85,18 @@ func (n notMatcher) String() string {
return "not(" + n.m.String() + ")"
}
type assignableToTypeOfMatcher struct {
targetType reflect.Type
}
func (m assignableToTypeOfMatcher) Matches(x interface{}) bool {
return reflect.TypeOf(x).AssignableTo(m.targetType)
}
func (m assignableToTypeOfMatcher) String() string {
return "is assignable to " + m.targetType.Name()
}
// Constructors
func Any() Matcher { return anyMatcher{} }
func Eq(x interface{}) Matcher { return eqMatcher{x} }
@ -97,3 +107,16 @@ func Not(x interface{}) Matcher {
}
return notMatcher{Eq(x)}
}
// AssignableToTypeOf is a Matcher that matches if the parameter to the mock
// function is assignable to the type of the parameter to this function.
//
// Example usage:
//
// dbMock.EXPECT().
// Insert(gomock.AssignableToTypeOf(&EmployeeRecord{})).
// Return(errors.New("DB error"))
//
func AssignableToTypeOf(x interface{}) Matcher {
return assignableToTypeOfMatcher{reflect.TypeOf(x)}
}

View file

@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//go:generate mockgen -destination internal/mock_matcher/mock_matcher.go github.com/golang/mock/gomock Matcher
package gomock_test
import (
@ -19,7 +21,7 @@ import (
"testing"
"github.com/golang/mock/gomock"
mock_matcher "github.com/golang/mock/gomock/mock_matcher"
mock_matcher "github.com/golang/mock/gomock/internal/mock_matcher"
)
func TestMatchers(t *testing.T) {
@ -29,12 +31,12 @@ func TestMatchers(t *testing.T) {
yes, no []e
}
tests := []testCase{
testCase{gomock.Any(), []e{3, nil, "foo"}, nil},
testCase{gomock.Eq(4), []e{4}, []e{3, "blah", nil, int64(4)}},
testCase{gomock.Nil(),
{gomock.Any(), []e{3, nil, "foo"}, nil},
{gomock.Eq(4), []e{4}, []e{3, "blah", nil, int64(4)}},
{gomock.Nil(),
[]e{nil, (error)(nil), (chan bool)(nil), (*int)(nil)},
[]e{"", 0, make(chan bool), errors.New("err"), new(int)}},
testCase{gomock.Not(gomock.Eq(4)), []e{3, "blah", nil, int64(4)}, []e{4}},
{gomock.Not(gomock.Eq(4)), []e{3, "blah", nil, int64(4)}, []e{4}},
}
for i, test := range tests {
for _, x := range test.yes {
@ -68,3 +70,50 @@ func TestNotMatcher(t *testing.T) {
t.Errorf("notMatcher should match 5")
}
}
type Dog struct {
Breed, Name string
}
// A thorough test of assignableToTypeOfMatcher
func TestAssignableToTypeOfMatcher(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
aStr := "def"
anotherStr := "ghi"
if match := gomock.AssignableToTypeOf("abc").Matches(4); match {
t.Errorf(`AssignableToTypeOf("abc") should not match 4`)
}
if match := gomock.AssignableToTypeOf("abc").Matches(&aStr); match {
t.Errorf(`AssignableToTypeOf("abc") should not match &aStr (*string)`)
}
if match := gomock.AssignableToTypeOf("abc").Matches("def"); !match {
t.Errorf(`AssignableToTypeOf("abc") should match "def"`)
}
if match := gomock.AssignableToTypeOf(&aStr).Matches("abc"); match {
t.Errorf(`AssignableToTypeOf(&aStr) should not match "abc"`)
}
if match := gomock.AssignableToTypeOf(&aStr).Matches(&anotherStr); !match {
t.Errorf(`AssignableToTypeOf(&aStr) should match &anotherStr`)
}
if match := gomock.AssignableToTypeOf(0).Matches(4); !match {
t.Errorf(`AssignableToTypeOf(0) should match 4`)
}
if match := gomock.AssignableToTypeOf(0).Matches("def"); match {
t.Errorf(`AssignableToTypeOf(0) should not match "def"`)
}
if match := gomock.AssignableToTypeOf(Dog{}).Matches(&Dog{}); match {
t.Errorf(`AssignableToTypeOf(Dog{}) should not match &Dog{}`)
}
if match := gomock.AssignableToTypeOf(Dog{}).Matches(Dog{Breed: "pug", Name: "Fido"}); !match {
t.Errorf(`AssignableToTypeOf(Dog{}) should match Dog{Breed: "pug", Name: "Fido"}`)
}
if match := gomock.AssignableToTypeOf(&Dog{}).Matches(Dog{}); match {
t.Errorf(`AssignableToTypeOf(&Dog{}) should not match Dog{}`)
}
if match := gomock.AssignableToTypeOf(&Dog{}).Matches(&Dog{Breed: "pug", Name: "Fido"}); !match {
t.Errorf(`AssignableToTypeOf(&Dog{}) should match &Dog{Breed: "pug", Name: "Fido"}`)
}
}

View file

@ -0,0 +1,36 @@
Embedded interfaces in `aux_files` generate `unknown embedded interface XXX` errors.
See below for example of the problem:
```
// source
import (
alias "some.org/package/imported"
)
type Source interface {
alias.Foreign
}
```
```
// some.org/package/imported
type Foreign interface {
Embedded
}
type Embedded interface {}
```
Attempting to generate a mock will result in an `unknown embedded interface Embedded`.
The issue is that the `fileParser` stores `auxInterfaces` underneath the package name
explicitly specified in the `aux_files` flag.
In the `parseInterface` method, there is an incorrect assumption about an embedded interface
always being in the source file.
```
case *ast.Ident:
// Embedded interface in this package.
ei := p.auxInterfaces[""][v.String()]
if ei == nil {
return nil, p.errorf(v.Pos(), "unknown embedded interface %s", v.String())
}
```

View file

@ -0,0 +1,18 @@
//go:generate mockgen -aux_files faux=faux/faux.go -destination bugreport_mock.go -package bugreport -source=bugreport.go Example
package bugreport
import (
"log"
"github.com/golang/mock/mockgen/internal/tests/aux_imports_embedded_interface/faux"
)
// Source is an interface w/ an embedded foreign interface
type Source interface {
faux.Foreign
}
func CallForeignMethod(s Source) {
log.Println(s.Method())
}

View file

@ -0,0 +1,48 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: bugreport.go
// Package bugreport is a generated GoMock package.
package bugreport
import (
gomock "github.com/golang/mock/gomock"
faux "github.com/golang/mock/mockgen/internal/tests/aux_imports_embedded_interface/faux"
reflect "reflect"
)
// MockSource is a mock of Source interface
type MockSource struct {
ctrl *gomock.Controller
recorder *MockSourceMockRecorder
}
// MockSourceMockRecorder is the mock recorder for MockSource
type MockSourceMockRecorder struct {
mock *MockSource
}
// NewMockSource creates a new mock instance
func NewMockSource(ctrl *gomock.Controller) *MockSource {
mock := &MockSource{ctrl: ctrl}
mock.recorder = &MockSourceMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockSource) EXPECT() *MockSourceMockRecorder {
return m.recorder
}
// Method mocks base method
func (m *MockSource) Method() faux.Return {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Method")
ret0, _ := ret[0].(faux.Return)
return ret0
}
// Method indicates an expected call of Method
func (mr *MockSourceMockRecorder) Method() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Method", reflect.TypeOf((*MockSource)(nil).Method))
}

View file

@ -0,0 +1,18 @@
package bugreport
import (
"testing"
"github.com/golang/mock/gomock"
)
// TestValidInterface assesses whether or not the generated mock is valid
func TestValidInterface(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
s := NewMockSource(ctrl)
s.EXPECT().Method().Return("")
CallForeignMethod(s)
}

View file

@ -0,0 +1,10 @@
package faux
type Foreign interface {
Method() Return
Embedded
}
type Embedded interface{}
type Return interface{}

View file

@ -0,0 +1,22 @@
# Tests for custom package names
This directory contains test for mockgen generating mocks when imported package
name does not match import path suffix. For example, package with name "client"
is located under import path "github.com/golang/mock/mockgen/internal/tests/custom_package_name/client/v1".
Prior to this patch:
$ go generate greeter/greeter.go
2018/03/05 22:44:52 Loading input failed: greeter.go:17:11: failed parsing returns: greeter.go:17:14: unknown package "client"
greeter/greeter.go:1: running "mockgen": exit status 1
This can be fixed by manually providing `-imports` flag, like `-imports client=github.com/golang/mock/mockgen/internal/tests/custom_package_name/client/v1`.
But, mockgen should be able to automatically resolve package names in such situations.
With this patch applied:
$ go generate greeter/greeter.go
$ echo $?
0
Mockgen runs successfully, produced output is equal to [greeter_mock_test.go](greeter/greeter_mock_test.go) content.

View file

@ -0,0 +1,13 @@
package client
import "fmt"
type Client struct{}
func (c *Client) Greet(in GreetInput) string {
return fmt.Sprintf("Hello, %s!", in.Name)
}
type GreetInput struct {
Name string
}

View file

@ -0,0 +1,31 @@
//go:generate mockgen -source greeter.go -destination greeter_mock_test.go -package greeter
package greeter
import (
// stdlib import
"fmt"
// non-matching import suffix and package name
"github.com/golang/mock/mockgen/internal/tests/custom_package_name/client/v1"
// matching import suffix and package name
"github.com/golang/mock/mockgen/internal/tests/custom_package_name/validator"
)
type InputMaker interface {
MakeInput() client.GreetInput
}
type Greeter struct {
InputMaker InputMaker
Client *client.Client
}
func (g *Greeter) Greet() (string, error) {
in := g.InputMaker.MakeInput()
if err := validator.Validate(in.Name); err != nil {
return "", fmt.Errorf("validation failed: %v", err)
}
return g.Client.Greet(in), nil
}

View file

@ -0,0 +1,48 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: greeter.go
// Package greeter is a generated GoMock package.
package greeter
import (
gomock "github.com/golang/mock/gomock"
v1 "github.com/golang/mock/mockgen/internal/tests/custom_package_name/client/v1"
reflect "reflect"
)
// MockInputMaker is a mock of InputMaker interface
type MockInputMaker struct {
ctrl *gomock.Controller
recorder *MockInputMakerMockRecorder
}
// MockInputMakerMockRecorder is the mock recorder for MockInputMaker
type MockInputMakerMockRecorder struct {
mock *MockInputMaker
}
// NewMockInputMaker creates a new mock instance
func NewMockInputMaker(ctrl *gomock.Controller) *MockInputMaker {
mock := &MockInputMaker{ctrl: ctrl}
mock.recorder = &MockInputMakerMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockInputMaker) EXPECT() *MockInputMakerMockRecorder {
return m.recorder
}
// MakeInput mocks base method
func (m *MockInputMaker) MakeInput() v1.GreetInput {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "MakeInput")
ret0, _ := ret[0].(v1.GreetInput)
return ret0
}
// MakeInput indicates an expected call of MakeInput
func (mr *MockInputMakerMockRecorder) MakeInput() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MakeInput", reflect.TypeOf((*MockInputMaker)(nil).MakeInput))
}

View file

@ -0,0 +1,37 @@
package greeter
import (
"testing"
"github.com/golang/mock/gomock"
"github.com/golang/mock/mockgen/internal/tests/custom_package_name/client/v1"
)
func TestGreeter_Greet(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
input := client.GreetInput{
Name: "Foo",
}
inputMaker := NewMockInputMaker(ctrl)
inputMaker.EXPECT().
MakeInput().
Return(input)
g := &Greeter{
InputMaker: inputMaker,
Client: &client.Client{},
}
greeting, err := g.Greet()
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
expected := "Hello, Foo!"
if greeting != expected {
t.Fatalf("Expected greeting to be %v but got %v", expected, greeting)
}
}

View file

@ -0,0 +1,5 @@
package validator
func Validate(s string) error {
return nil
}

View file

@ -0,0 +1,14 @@
//go:generate mockgen -package dot_imports -destination mock.go -source input.go
package dot_imports
import (
"bytes"
. "context"
. "net/http"
)
type WithDotImports interface {
Method1() Request
Method2() *bytes.Buffer
Method3() Context
}

View file

@ -0,0 +1,78 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: input.go
// Package dot_imports is a generated GoMock package.
package dot_imports
import (
bytes "bytes"
. "context"
gomock "github.com/golang/mock/gomock"
. "net/http"
reflect "reflect"
)
// MockWithDotImports is a mock of WithDotImports interface
type MockWithDotImports struct {
ctrl *gomock.Controller
recorder *MockWithDotImportsMockRecorder
}
// MockWithDotImportsMockRecorder is the mock recorder for MockWithDotImports
type MockWithDotImportsMockRecorder struct {
mock *MockWithDotImports
}
// NewMockWithDotImports creates a new mock instance
func NewMockWithDotImports(ctrl *gomock.Controller) *MockWithDotImports {
mock := &MockWithDotImports{ctrl: ctrl}
mock.recorder = &MockWithDotImportsMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockWithDotImports) EXPECT() *MockWithDotImportsMockRecorder {
return m.recorder
}
// Method1 mocks base method
func (m *MockWithDotImports) Method1() Request {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Method1")
ret0, _ := ret[0].(Request)
return ret0
}
// Method1 indicates an expected call of Method1
func (mr *MockWithDotImportsMockRecorder) Method1() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Method1", reflect.TypeOf((*MockWithDotImports)(nil).Method1))
}
// Method2 mocks base method
func (m *MockWithDotImports) Method2() *bytes.Buffer {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Method2")
ret0, _ := ret[0].(*bytes.Buffer)
return ret0
}
// Method2 indicates an expected call of Method2
func (mr *MockWithDotImportsMockRecorder) Method2() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Method2", reflect.TypeOf((*MockWithDotImports)(nil).Method2))
}
// Method3 mocks base method
func (m *MockWithDotImports) Method3() Context {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Method3")
ret0, _ := ret[0].(Context)
return ret0
}
// Method3 indicates an expected call of Method3
func (mr *MockWithDotImportsMockRecorder) Method3() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Method3", reflect.TypeOf((*MockWithDotImports)(nil).Method3))
}

View file

@ -0,0 +1,4 @@
//go:generate mockgen -package empty_interface -destination mock.go -source input.go
package empty_interface
type Empty interface{}

View file

@ -0,0 +1,32 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: input.go
// Package empty_interface is a generated GoMock package.
package empty_interface
import (
gomock "github.com/golang/mock/gomock"
)
// MockEmpty is a mock of Empty interface
type MockEmpty struct {
ctrl *gomock.Controller
recorder *MockEmptyMockRecorder
}
// MockEmptyMockRecorder is the mock recorder for MockEmpty
type MockEmptyMockRecorder struct {
mock *MockEmpty
}
// NewMockEmpty creates a new mock instance
func NewMockEmpty(ctrl *gomock.Controller) *MockEmpty {
mock := &MockEmpty{ctrl: ctrl}
mock.recorder = &MockEmptyMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockEmpty) EXPECT() *MockEmptyMockRecorder {
return m.recorder
}

View file

@ -0,0 +1,26 @@
The generated mock methods use some hardcoded variable/receiver names that can
have conflicts with the argument names that are defined by the code for which
the mock is generated when using the source generation method.
Example:
```go
type Example interface {
Method(_m, _mr, m, mr int)
}
```
```go
// Method mocks base method
func (_m *MockExample) Method(_m int, _mr int, m int, mr int) {
_m.ctrl.Call(_m, "Method", _m, _mr, m, mr)
}
```
In the above example one of the interface method parameters is called `_m`
but unfortunately the generated receiver name is also called `_m` so the
mock code won't compile.
The generator has to make sure that generated identifiers (e.g.: the receiver
names) are always different from the arg names that might come from external
sources.

View file

@ -0,0 +1,16 @@
//go:generate mockgen -destination bugreport_mock.go -package bugreport -source=bugreport.go
package bugreport
type Example interface {
// _m and _mr were used by the buggy code: the '_' prefix was there hoping
// that no one will use method argument names starting with '_' reducing
// the chance of collision with generated identifiers.
// m and mr are used by the bugfixed new code, the '_' prefix has been
// removed because the new code generator changes the names of the
// generated identifiers in case they would collide with identifiers
// coming from argument names.
Method(_m, _mr, m, mr int)
VarargMethod(_s, _x, a, ret int, varargs ...int)
}

View file

@ -0,0 +1,62 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: bugreport.go
// Package bugreport is a generated GoMock package.
package bugreport
import (
gomock "github.com/golang/mock/gomock"
reflect "reflect"
)
// MockExample is a mock of Example interface
type MockExample struct {
ctrl *gomock.Controller
recorder *MockExampleMockRecorder
}
// MockExampleMockRecorder is the mock recorder for MockExample
type MockExampleMockRecorder struct {
mock *MockExample
}
// NewMockExample creates a new mock instance
func NewMockExample(ctrl *gomock.Controller) *MockExample {
mock := &MockExample{ctrl: ctrl}
mock.recorder = &MockExampleMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockExample) EXPECT() *MockExampleMockRecorder {
return m.recorder
}
// Method mocks base method
func (m_2 *MockExample) Method(_m, _mr, m, mr int) {
m_2.ctrl.T.Helper()
m_2.ctrl.Call(m_2, "Method", _m, _mr, m, mr)
}
// Method indicates an expected call of Method
func (mr_2 *MockExampleMockRecorder) Method(_m, _mr, m, mr interface{}) *gomock.Call {
mr_2.mock.ctrl.T.Helper()
return mr_2.mock.ctrl.RecordCallWithMethodType(mr_2.mock, "Method", reflect.TypeOf((*MockExample)(nil).Method), _m, _mr, m, mr)
}
// VarargMethod mocks base method
func (m *MockExample) VarargMethod(_s, _x, a, ret int, varargs ...int) {
m.ctrl.T.Helper()
varargs_2 := []interface{}{_s, _x, a, ret}
for _, a_2 := range varargs {
varargs_2 = append(varargs_2, a_2)
}
m.ctrl.Call(m, "VarargMethod", varargs_2...)
}
// VarargMethod indicates an expected call of VarargMethod
func (mr *MockExampleMockRecorder) VarargMethod(_s, _x, a, ret interface{}, varargs ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs_2 := append([]interface{}{_s, _x, a, ret}, varargs...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VarargMethod", reflect.TypeOf((*MockExample)(nil).VarargMethod), varargs_2...)
}

View file

@ -0,0 +1,26 @@
package bugreport
import (
"github.com/golang/mock/gomock"
"testing"
)
func TestExample_Method(t *testing.T) {
ctrl := gomock.NewController(t)
m := NewMockExample(ctrl)
m.EXPECT().Method(1, 2, 3, 4)
m.Method(1, 2, 3, 4)
ctrl.Finish()
}
func TestExample_VarargMethod(t *testing.T) {
ctrl := gomock.NewController(t)
m := NewMockExample(ctrl)
m.EXPECT().VarargMethod(1, 2, 3, 4, 6, 7)
m.VarargMethod(1, 2, 3, 4, 6, 7)
ctrl.Finish()
}

View file

@ -0,0 +1,3 @@
Test the case where the generated code uses a type defined in the source package (in source mode). There are two test cases:
- the output is in a new package
- the output is in the same package as the input

View file

@ -0,0 +1,9 @@
//go:generate mockgen -destination ../source_mock.go -source=source.go
//go:generate mockgen -package source -destination source_mock.go -source=source.go
package source
type X struct{}
type S interface {
F(X)
}

View file

@ -0,0 +1,45 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: source.go
// Package source is a generated GoMock package.
package source
import (
gomock "github.com/golang/mock/gomock"
reflect "reflect"
)
// MockS is a mock of S interface
type MockS struct {
ctrl *gomock.Controller
recorder *MockSMockRecorder
}
// MockSMockRecorder is the mock recorder for MockS
type MockSMockRecorder struct {
mock *MockS
}
// NewMockS creates a new mock instance
func NewMockS(ctrl *gomock.Controller) *MockS {
mock := &MockS{ctrl: ctrl}
mock.recorder = &MockSMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockS) EXPECT() *MockSMockRecorder {
return m.recorder
}
// F mocks base method
func (m *MockS) F(arg0 X) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "F", arg0)
}
// F indicates an expected call of F
func (mr *MockSMockRecorder) F(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "F", reflect.TypeOf((*MockS)(nil).F), arg0)
}

View file

@ -0,0 +1,46 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: source.go
// Package mock_source is a generated GoMock package.
package mock_source
import (
gomock "github.com/golang/mock/gomock"
definition "github.com/golang/mock/mockgen/internal/tests/import_source/definition"
reflect "reflect"
)
// MockS is a mock of S interface
type MockS struct {
ctrl *gomock.Controller
recorder *MockSMockRecorder
}
// MockSMockRecorder is the mock recorder for MockS
type MockSMockRecorder struct {
mock *MockS
}
// NewMockS creates a new mock instance
func NewMockS(ctrl *gomock.Controller) *MockS {
mock := &MockS{ctrl: ctrl}
mock.recorder = &MockSMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockS) EXPECT() *MockSMockRecorder {
return m.recorder
}
// F mocks base method
func (m *MockS) F(arg0 definition.X) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "F", arg0)
}
// F indicates an expected call of F
func (mr *MockSMockRecorder) F(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "F", reflect.TypeOf((*MockS)(nil).F), arg0)
}

View file

@ -0,0 +1,3 @@
//go:generate mockgen -destination subdir/internal/pkg/reflect_output/mock.go github.com/golang/mock/mockgen/internal/tests/internal_pkg/subdir/internal/pkg Intf
//go:generate mockgen -source subdir/internal/pkg/input.go -destination subdir/internal/pkg/source_output/mock.go
package test

View file

@ -0,0 +1,9 @@
package pkg
type Arg interface {
Foo() int
}
type Intf interface {
F() Arg
}

View file

@ -0,0 +1,48 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: github.com/golang/mock/mockgen/internal/tests/internal_pkg/subdir/internal/pkg (interfaces: Intf)
// Package mock_pkg is a generated GoMock package.
package mock_pkg
import (
gomock "github.com/golang/mock/gomock"
pkg "github.com/golang/mock/mockgen/internal/tests/internal_pkg/subdir/internal/pkg"
reflect "reflect"
)
// MockIntf is a mock of Intf interface
type MockIntf struct {
ctrl *gomock.Controller
recorder *MockIntfMockRecorder
}
// MockIntfMockRecorder is the mock recorder for MockIntf
type MockIntfMockRecorder struct {
mock *MockIntf
}
// NewMockIntf creates a new mock instance
func NewMockIntf(ctrl *gomock.Controller) *MockIntf {
mock := &MockIntf{ctrl: ctrl}
mock.recorder = &MockIntfMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockIntf) EXPECT() *MockIntfMockRecorder {
return m.recorder
}
// F mocks base method
func (m *MockIntf) F() pkg.Arg {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "F")
ret0, _ := ret[0].(pkg.Arg)
return ret0
}
// F indicates an expected call of F
func (mr *MockIntfMockRecorder) F() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "F", reflect.TypeOf((*MockIntf)(nil).F))
}

View file

@ -0,0 +1,85 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: subdir/internal/pkg/input.go
// Package mock_pkg is a generated GoMock package.
package mock_pkg
import (
gomock "github.com/golang/mock/gomock"
pkg "github.com/golang/mock/mockgen/internal/tests/internal_pkg/subdir/internal/pkg"
reflect "reflect"
)
// MockArg is a mock of Arg interface
type MockArg struct {
ctrl *gomock.Controller
recorder *MockArgMockRecorder
}
// MockArgMockRecorder is the mock recorder for MockArg
type MockArgMockRecorder struct {
mock *MockArg
}
// NewMockArg creates a new mock instance
func NewMockArg(ctrl *gomock.Controller) *MockArg {
mock := &MockArg{ctrl: ctrl}
mock.recorder = &MockArgMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockArg) EXPECT() *MockArgMockRecorder {
return m.recorder
}
// Foo mocks base method
func (m *MockArg) Foo() int {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Foo")
ret0, _ := ret[0].(int)
return ret0
}
// Foo indicates an expected call of Foo
func (mr *MockArgMockRecorder) Foo() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Foo", reflect.TypeOf((*MockArg)(nil).Foo))
}
// MockIntf is a mock of Intf interface
type MockIntf struct {
ctrl *gomock.Controller
recorder *MockIntfMockRecorder
}
// MockIntfMockRecorder is the mock recorder for MockIntf
type MockIntfMockRecorder struct {
mock *MockIntf
}
// NewMockIntf creates a new mock instance
func NewMockIntf(ctrl *gomock.Controller) *MockIntf {
mock := &MockIntf{ctrl: ctrl}
mock.recorder = &MockIntfMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockIntf) EXPECT() *MockIntfMockRecorder {
return m.recorder
}
// F mocks base method
func (m *MockIntf) F() pkg.Arg {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "F")
ret0, _ := ret[0].(pkg.Arg)
return ret0
}
// F indicates an expected call of F
func (mr *MockIntfMockRecorder) F() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "F", reflect.TypeOf((*MockIntf)(nil).F))
}

View file

@ -1,6 +1,7 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: bugreport.go
// Package bugreport is a generated GoMock package.
package bugreport
import (
@ -27,18 +28,20 @@ func NewMockExample(ctrl *gomock.Controller) *MockExample {
}
// EXPECT returns an object that allows the caller to indicate expected use
func (_m *MockExample) EXPECT() *MockExampleMockRecorder {
return _m.recorder
func (m *MockExample) EXPECT() *MockExampleMockRecorder {
return m.recorder
}
// someMethod mocks base method
func (_m *MockExample) someMethod(_param0 string) string {
ret := _m.ctrl.Call(_m, "someMethod", _param0)
func (m *MockExample) someMethod(arg0 string) string {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "someMethod", arg0)
ret0, _ := ret[0].(string)
return ret0
}
// someMethod indicates an expected call of someMethod
func (_mr *MockExampleMockRecorder) someMethod(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "someMethod", reflect.TypeOf((*MockExample)(nil).someMethod), arg0)
func (mr *MockExampleMockRecorder) someMethod(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "someMethod", reflect.TypeOf((*MockExample)(nil).someMethod), arg0)
}

View file

@ -0,0 +1,2 @@
Test for [Issue#4](https://github.com/golang/mock/issues/4).
Also see discussion on [#28](https://github.com/golang/mock/pull/28).

View file

@ -0,0 +1,4 @@
package vendor_dep
//go:generate mockgen -package vendor_dep -destination mock.go github.com/golang/mock/mockgen/internal/tests/vendor_dep VendorsDep
//go:generate mockgen -destination source_mock_package/mock.go -source=vendor_dep.go

View file

@ -0,0 +1,48 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: github.com/golang/mock/mockgen/internal/tests/vendor_dep (interfaces: VendorsDep)
// Package vendor_dep is a generated GoMock package.
package vendor_dep
import (
a "a"
gomock "github.com/golang/mock/gomock"
reflect "reflect"
)
// MockVendorsDep is a mock of VendorsDep interface
type MockVendorsDep struct {
ctrl *gomock.Controller
recorder *MockVendorsDepMockRecorder
}
// MockVendorsDepMockRecorder is the mock recorder for MockVendorsDep
type MockVendorsDepMockRecorder struct {
mock *MockVendorsDep
}
// NewMockVendorsDep creates a new mock instance
func NewMockVendorsDep(ctrl *gomock.Controller) *MockVendorsDep {
mock := &MockVendorsDep{ctrl: ctrl}
mock.recorder = &MockVendorsDepMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockVendorsDep) EXPECT() *MockVendorsDepMockRecorder {
return m.recorder
}
// Foo mocks base method
func (m *MockVendorsDep) Foo() a.Ifc {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Foo")
ret0, _ := ret[0].(a.Ifc)
return ret0
}
// Foo indicates an expected call of Foo
func (mr *MockVendorsDepMockRecorder) Foo() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Foo", reflect.TypeOf((*MockVendorsDep)(nil).Foo))
}

View file

@ -0,0 +1,48 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: vendor_dep.go
// Package mock_vendor_dep is a generated GoMock package.
package mock_vendor_dep
import (
a "a"
gomock "github.com/golang/mock/gomock"
reflect "reflect"
)
// MockVendorsDep is a mock of VendorsDep interface
type MockVendorsDep struct {
ctrl *gomock.Controller
recorder *MockVendorsDepMockRecorder
}
// MockVendorsDepMockRecorder is the mock recorder for MockVendorsDep
type MockVendorsDepMockRecorder struct {
mock *MockVendorsDep
}
// NewMockVendorsDep creates a new mock instance
func NewMockVendorsDep(ctrl *gomock.Controller) *MockVendorsDep {
mock := &MockVendorsDep{ctrl: ctrl}
mock.recorder = &MockVendorsDepMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockVendorsDep) EXPECT() *MockVendorsDepMockRecorder {
return m.recorder
}
// Foo mocks base method
func (m *MockVendorsDep) Foo() a.Ifc {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Foo")
ret0, _ := ret[0].(a.Ifc)
return ret0
}
// Foo indicates an expected call of Foo
func (mr *MockVendorsDepMockRecorder) Foo() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Foo", reflect.TypeOf((*MockVendorsDep)(nil).Foo))
}

View file

@ -0,0 +1,7 @@
package vendor_dep
import "a"
type VendorsDep interface {
Foo() a.Ifc
}

View file

@ -0,0 +1 @@
Test for [Issue#4](https://github.com/golang/mock/issues/4).

View file

@ -0,0 +1,3 @@
package vendor_pkg
//go:generate mockgen -destination mock.go -package vendor_pkg a Ifc

View file

@ -0,0 +1,111 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: a (interfaces: Ifc)
// Package vendor_pkg is a generated GoMock package.
package vendor_pkg
import (
gomock "github.com/golang/mock/gomock"
reflect "reflect"
)
// MockIfc is a mock of Ifc interface
type MockIfc struct {
ctrl *gomock.Controller
recorder *MockIfcMockRecorder
}
// MockIfcMockRecorder is the mock recorder for MockIfc
type MockIfcMockRecorder struct {
mock *MockIfc
}
// NewMockIfc creates a new mock instance
func NewMockIfc(ctrl *gomock.Controller) *MockIfc {
mock := &MockIfc{ctrl: ctrl}
mock.recorder = &MockIfcMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockIfc) EXPECT() *MockIfcMockRecorder {
return m.recorder
}
// A mocks base method
func (m *MockIfc) A(arg0 string) string {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "A", arg0)
ret0, _ := ret[0].(string)
return ret0
}
// A indicates an expected call of A
func (mr *MockIfcMockRecorder) A(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "A", reflect.TypeOf((*MockIfc)(nil).A), arg0)
}
// B mocks base method
func (m *MockIfc) B(arg0 int) int {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "B", arg0)
ret0, _ := ret[0].(int)
return ret0
}
// B indicates an expected call of B
func (mr *MockIfcMockRecorder) B(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "B", reflect.TypeOf((*MockIfc)(nil).B), arg0)
}
// C mocks base method
func (m *MockIfc) C(arg0 chan int) chan int {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "C", arg0)
ret0, _ := ret[0].(chan int)
return ret0
}
// C indicates an expected call of C
func (mr *MockIfcMockRecorder) C(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "C", reflect.TypeOf((*MockIfc)(nil).C), arg0)
}
// D mocks base method
func (m *MockIfc) D(arg0 interface{}) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "D", arg0)
}
// D indicates an expected call of D
func (mr *MockIfcMockRecorder) D(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "D", reflect.TypeOf((*MockIfc)(nil).D), arg0)
}
// E mocks base method
func (m *MockIfc) E(arg0 map[string]interface{}) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "E", arg0)
}
// E indicates an expected call of E
func (mr *MockIfcMockRecorder) E(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "E", reflect.TypeOf((*MockIfc)(nil).E), arg0)
}
// F mocks base method
func (m *MockIfc) F(arg0 []float64) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "F", arg0)
}
// F indicates an expected call of F
func (mr *MockIfcMockRecorder) F(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "F", reflect.TypeOf((*MockIfc)(nil).F), arg0)
}

View file

@ -22,12 +22,14 @@ import (
"bytes"
"flag"
"fmt"
"go/build"
"go/format"
"go/token"
"io"
"log"
"os"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
@ -41,10 +43,12 @@ const (
)
var (
source = flag.String("source", "", "(source mode) Input Go source file; enables source mode.")
destination = flag.String("destination", "", "Output file; defaults to stdout.")
packageOut = flag.String("package", "", "Package of the generated code; defaults to the package of the input with a 'mock_' prefix.")
selfPackage = flag.String("self_package", "", "If set, the package this mock will be part of.")
source = flag.String("source", "", "(source mode) Input Go source file; enables source mode.")
destination = flag.String("destination", "", "Output file; defaults to stdout.")
mockNames = flag.String("mock_names", "", "Comma-separated interfaceName=mockName pairs of explicit mock names to use. Mock names default to 'Mock'+ interfaceName suffix.")
packageOut = flag.String("package", "", "Package of the generated code; defaults to the package of the input with a 'mock_' prefix.")
selfPackage = flag.String("self_package", "", "The full package import path for the generated code. The purpose of this flag is to prevent import cycles in the generated code by trying to include its own package. This can happen if the mock's package is set to one of its inputs (usually the main one) and the output is stdio so mockgen cannot detect the final output package. Setting this flag will then tell mockgen which import to exclude.")
writePkgComment = flag.Bool("write_package_comment", true, "Writes package documentation comment (godoc) if true.")
debugParser = flag.Bool("debug_parser", false, "Print out parser results only.")
)
@ -75,6 +79,9 @@ func main() {
dst := os.Stdout
if len(*destination) > 0 {
if err := os.MkdirAll(filepath.Dir(*destination), os.ModePerm); err != nil {
log.Fatalf("Unable to create directory: %v", err)
}
f, err := os.Create(*destination)
if err != nil {
log.Fatalf("Failed opening destination file: %v", err)
@ -90,6 +97,25 @@ func main() {
packageName = "mock_" + sanitize(pkg.Name)
}
// outputPackagePath represents the fully qualified name of the package of
// the generated code. Its purposes are to prevent the module from importing
// itself and to prevent qualifying type names that come from its own
// package (i.e. if there is a type called X then we want to print "X" not
// "package.X" since "package" is this package). This can happen if the mock
// is output into an already existing package.
outputPackagePath := *selfPackage
if len(outputPackagePath) == 0 && len(*destination) > 0 {
dst, _ := filepath.Abs(filepath.Dir(*destination))
for _, prefix := range build.Default.SrcDirs() {
if strings.HasPrefix(dst, prefix) {
if rel, err := filepath.Rel(prefix, dst); err == nil {
outputPackagePath = rel
break
}
}
}
}
g := new(generator)
if *source != "" {
g.filename = *source
@ -97,13 +123,28 @@ func main() {
g.srcPackage = flag.Arg(0)
g.srcInterfaces = flag.Arg(1)
}
if err := g.Generate(pkg, packageName); err != nil {
if *mockNames != "" {
g.mockNames = parseMockNames(*mockNames)
}
if err := g.Generate(pkg, packageName, outputPackagePath); err != nil {
log.Fatalf("Failed generating mock: %v", err)
}
if _, err := dst.Write(g.Output()); err != nil {
log.Fatalf("Failed writing to destination: %v", err)
}
}
func parseMockNames(names string) map[string]string {
mocksMap := make(map[string]string)
for _, kv := range strings.Split(names, ",") {
parts := strings.SplitN(kv, "=", 2)
if len(parts) != 2 || parts[1] == "" {
log.Fatalf("bad mock names spec: %v", kv)
}
mocksMap[parts[0]] = parts[1]
}
return mocksMap
}
func usage() {
io.WriteString(os.Stderr, usageText)
@ -128,11 +169,11 @@ Example:
`
type generator struct {
buf bytes.Buffer
indent string
filename string // may be empty
srcPackage, srcInterfaces string // may be empty
buf bytes.Buffer
indent string
mockNames map[string]string //may be empty
filename string // may be empty
srcPackage, srcInterfaces string // may be empty
packageMap map[string]string // map from import path to package name
}
@ -181,7 +222,7 @@ func sanitize(s string) string {
return t
}
func (g *generator) Generate(pkg *model.Package, pkgName string) error {
func (g *generator) Generate(pkg *model.Package, pkgName string, outputPackagePath string) error {
g.p("// Code generated by MockGen. DO NOT EDIT.")
if g.filename != "" {
g.p("// Source: %v", g.filename)
@ -193,7 +234,15 @@ func (g *generator) Generate(pkg *model.Package, pkgName string) error {
// Get all required imports, and generate unique names for them all.
im := pkg.Imports()
im[gomockImportPath] = true
im["reflect"] = true
// Only import reflect if it's used. We only use reflect in mocked methods
// so only import if any of the mocked interfaces have methods.
for _, intf := range pkg.Interfaces {
if len(intf.Methods) > 0 {
im["reflect"] = true
break
}
}
// Sort keys to make import alias generation predictable
sorted_paths := make([]string, len(im), len(im))
@ -225,12 +274,15 @@ func (g *generator) Generate(pkg *model.Package, pkgName string) error {
localNames[pkgName] = true
}
if *writePkgComment {
g.p("// Package %v is a generated GoMock package.", pkgName)
}
g.p("package %v", pkgName)
g.p("")
g.p("import (")
g.in()
for path, pkg := range g.packageMap {
if path == *selfPackage {
if path == outputPackagePath {
continue
}
g.p("%v %q", pkg, path)
@ -242,7 +294,7 @@ func (g *generator) Generate(pkg *model.Package, pkgName string) error {
g.p(")")
for _, intf := range pkg.Interfaces {
if err := g.GenerateMockInterface(intf); err != nil {
if err := g.GenerateMockInterface(intf, outputPackagePath); err != nil {
return err
}
}
@ -251,12 +303,16 @@ func (g *generator) Generate(pkg *model.Package, pkgName string) error {
}
// The name of the mock type to use for the given interface identifier.
func mockName(typeName string) string {
func (g *generator) mockName(typeName string) string {
if mockName, ok := g.mockNames[typeName]; ok {
return mockName
}
return "Mock" + typeName
}
func (g *generator) GenerateMockInterface(intf *model.Interface) error {
mockType := mockName(intf.Name)
func (g *generator) GenerateMockInterface(intf *model.Interface, outputPackagePath string) error {
mockType := g.mockName(intf.Name)
g.p("")
g.p("// %v is a mock of %v interface", mockType, intf.Name)
@ -293,13 +349,13 @@ func (g *generator) GenerateMockInterface(intf *model.Interface) error {
// XXX: possible name collision here if someone has EXPECT in their interface.
g.p("// EXPECT returns an object that allows the caller to indicate expected use")
g.p("func (_m *%v) EXPECT() *%vMockRecorder {", mockType, mockType)
g.p("func (m *%v) EXPECT() *%vMockRecorder {", mockType, mockType)
g.in()
g.p("return _m.recorder")
g.p("return m.recorder")
g.out()
g.p("}")
g.GenerateMockMethods(mockType, intf, *selfPackage)
g.GenerateMockMethods(mockType, intf, outputPackagePath)
return nil
}
@ -313,30 +369,25 @@ func (g *generator) GenerateMockMethods(mockType string, intf *model.Interface,
}
}
func makeArgString(argNames, argTypes []string) string {
args := make([]string, len(argNames))
for i, name := range argNames {
// specify the type only once for consecutive args of the same type
if i+1 < len(argTypes) && argTypes[i] == argTypes[i+1] {
args[i] = name
} else {
args[i] = name + " " + argTypes[i]
}
}
return strings.Join(args, ", ")
}
// GenerateMockMethod generates a mock method implementation.
// If non-empty, pkgOverride is the package in which unqualified types reside.
func (g *generator) GenerateMockMethod(mockType string, m *model.Method, pkgOverride string) error {
args := make([]string, len(m.In))
argNames := make([]string, len(m.In))
for i, p := range m.In {
name := p.Name
if name == "" {
name = fmt.Sprintf("_param%d", i)
}
ts := p.Type.String(g.packageMap, pkgOverride)
args[i] = name + " " + ts
argNames[i] = name
}
if m.Variadic != nil {
name := m.Variadic.Name
if name == "" {
name = fmt.Sprintf("_param%d", len(m.In))
}
ts := m.Variadic.Type.String(g.packageMap, pkgOverride)
args = append(args, name+" ..."+ts)
argNames = append(argNames, name)
}
argString := strings.Join(args, ", ")
argNames := g.getArgNames(m)
argTypes := g.getArgTypes(m, pkgOverride)
argString := makeArgString(argNames, argTypes)
rets := make([]string, len(m.Out))
for i, p := range m.Out {
@ -350,37 +401,45 @@ func (g *generator) GenerateMockMethod(mockType string, m *model.Method, pkgOver
retString = " " + retString
}
g.p("// %v mocks base method", m.Name)
g.p("func (_m *%v) %v(%v)%v {", mockType, m.Name, argString, retString)
g.in()
ia := newIdentifierAllocator(argNames)
idRecv := ia.allocateIdentifier("m")
callArgs := strings.Join(argNames, ", ")
if callArgs != "" {
callArgs = ", " + callArgs
}
if m.Variadic != nil {
g.p("// %v mocks base method", m.Name)
g.p("func (%v *%v) %v(%v)%v {", idRecv, mockType, m.Name, argString, retString)
g.in()
g.p("%s.ctrl.T.Helper()", idRecv)
var callArgs string
if m.Variadic == nil {
if len(argNames) > 0 {
callArgs = ", " + strings.Join(argNames, ", ")
}
} else {
// Non-trivial. The generated code must build a []interface{},
// but the variadic argument may be any type.
g.p("_s := []interface{}{%s}", strings.Join(argNames[:len(argNames)-1], ", "))
g.p("for _, _x := range %s {", argNames[len(argNames)-1])
idVarArgs := ia.allocateIdentifier("varargs")
idVArg := ia.allocateIdentifier("a")
g.p("%s := []interface{}{%s}", idVarArgs, strings.Join(argNames[:len(argNames)-1], ", "))
g.p("for _, %s := range %s {", idVArg, argNames[len(argNames)-1])
g.in()
g.p("_s = append(_s, _x)")
g.p("%s = append(%s, %s)", idVarArgs, idVarArgs, idVArg)
g.out()
g.p("}")
callArgs = ", _s..."
callArgs = ", " + idVarArgs + "..."
}
if len(m.Out) == 0 {
g.p(`_m.ctrl.Call(_m, "%v"%v)`, m.Name, callArgs)
g.p(`%v.ctrl.Call(%v, %q%v)`, idRecv, idRecv, m.Name, callArgs)
} else {
g.p(`ret := _m.ctrl.Call(_m, "%v"%v)`, m.Name, callArgs)
idRet := ia.allocateIdentifier("ret")
g.p(`%v := %v.ctrl.Call(%v, %q%v)`, idRet, idRecv, idRecv, m.Name, callArgs)
// Go does not allow "naked" type assertions on nil values, so we use the two-value form here.
// The value of that is either (x.(T), true) or (Z, false), where Z is the zero value for T.
// Happily, this coincides with the semantics we want here.
retNames := make([]string, len(rets))
for i, t := range rets {
retNames[i] = fmt.Sprintf("ret%d", i)
g.p("%s, _ := ret[%d].(%s)", retNames[i], i, t)
retNames[i] = ia.allocateIdentifier(fmt.Sprintf("ret%d", i))
g.p("%s, _ := %s[%d].(%s)", retNames[i], idRet, i, t)
}
g.p("return " + strings.Join(retNames, ", "))
}
@ -391,47 +450,110 @@ func (g *generator) GenerateMockMethod(mockType string, m *model.Method, pkgOver
}
func (g *generator) GenerateMockRecorderMethod(mockType string, m *model.Method) error {
nargs := len(m.In)
args := make([]string, nargs)
for i := 0; i < nargs; i++ {
args[i] = "arg" + strconv.Itoa(i)
argNames := g.getArgNames(m)
var argString string
if m.Variadic == nil {
argString = strings.Join(argNames, ", ")
} else {
argString = strings.Join(argNames[:len(argNames)-1], ", ")
}
argString := strings.Join(args, ", ")
if nargs > 0 {
if argString != "" {
argString += " interface{}"
}
if m.Variadic != nil {
if nargs > 0 {
if argString != "" {
argString += ", "
}
argString += fmt.Sprintf("arg%d ...interface{}", nargs)
argString += fmt.Sprintf("%s ...interface{}", argNames[len(argNames)-1])
}
ia := newIdentifierAllocator(argNames)
idRecv := ia.allocateIdentifier("mr")
g.p("// %v indicates an expected call of %v", m.Name, m.Name)
g.p("func (_mr *%vMockRecorder) %v(%v) *gomock.Call {", mockType, m.Name, argString)
g.p("func (%s *%vMockRecorder) %v(%v) *gomock.Call {", idRecv, mockType, m.Name, argString)
g.in()
g.p("%s.mock.ctrl.T.Helper()", idRecv)
callArgs := strings.Join(args, ", ")
if nargs > 0 {
callArgs = ", " + callArgs
}
if m.Variadic != nil {
if nargs == 0 {
var callArgs string
if m.Variadic == nil {
if len(argNames) > 0 {
callArgs = ", " + strings.Join(argNames, ", ")
}
} else {
if len(argNames) == 1 {
// Easy: just use ... to push the arguments through.
callArgs = ", arg0..."
callArgs = ", " + argNames[0] + "..."
} else {
// Hard: create a temporary slice.
g.p("_s := append([]interface{}{%s}, arg%d...)", strings.Join(args, ", "), nargs)
callArgs = ", _s..."
idVarArgs := ia.allocateIdentifier("varargs")
g.p("%s := append([]interface{}{%s}, %s...)",
idVarArgs,
strings.Join(argNames[:len(argNames)-1], ", "),
argNames[len(argNames)-1])
callArgs = ", " + idVarArgs + "..."
}
}
g.p(`return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "%s", reflect.TypeOf((*%s)(nil).%s)%s)`, m.Name, mockType, m.Name, callArgs)
g.p(`return %s.mock.ctrl.RecordCallWithMethodType(%s.mock, "%s", reflect.TypeOf((*%s)(nil).%s)%s)`, idRecv, idRecv, m.Name, mockType, m.Name, callArgs)
g.out()
g.p("}")
return nil
}
func (g *generator) getArgNames(m *model.Method) []string {
argNames := make([]string, len(m.In))
for i, p := range m.In {
name := p.Name
if name == "" {
name = fmt.Sprintf("arg%d", i)
}
argNames[i] = name
}
if m.Variadic != nil {
name := m.Variadic.Name
if name == "" {
name = fmt.Sprintf("arg%d", len(m.In))
}
argNames = append(argNames, name)
}
return argNames
}
func (g *generator) getArgTypes(m *model.Method, pkgOverride string) []string {
argTypes := make([]string, len(m.In))
for i, p := range m.In {
argTypes[i] = p.Type.String(g.packageMap, pkgOverride)
}
if m.Variadic != nil {
argTypes = append(argTypes, "..."+m.Variadic.Type.String(g.packageMap, pkgOverride))
}
return argTypes
}
type identifierAllocator map[string]struct{}
func newIdentifierAllocator(taken []string) identifierAllocator {
a := make(identifierAllocator, len(taken))
for _, s := range taken {
a[s] = struct{}{}
}
return a
}
func (o identifierAllocator) allocateIdentifier(want string) string {
id := want
for i := 2; ; i++ {
if _, ok := o[id]; !ok {
o[id] = struct{}{}
return id
}
id = want + "_" + strconv.Itoa(i)
}
}
// Output returns the generator's output, formatted in the standard Go style.
func (g *generator) Output() []byte {
src, err := format.Source(g.buf.Bytes())

269
vendor/github.com/golang/mock/mockgen/mockgen_test.go generated vendored Normal file
View file

@ -0,0 +1,269 @@
package main
import (
"fmt"
"regexp"
"strings"
"testing"
"github.com/golang/mock/mockgen/model"
)
func TestMakeArgString(t *testing.T) {
testCases := []struct {
argNames []string
argTypes []string
argString string
}{
{
argNames: nil,
argTypes: nil,
argString: "",
},
{
argNames: []string{"arg0"},
argTypes: []string{"int"},
argString: "arg0 int",
},
{
argNames: []string{"arg0", "arg1"},
argTypes: []string{"int", "bool"},
argString: "arg0 int, arg1 bool",
},
{
argNames: []string{"arg0", "arg1"},
argTypes: []string{"int", "int"},
argString: "arg0, arg1 int",
},
{
argNames: []string{"arg0", "arg1", "arg2"},
argTypes: []string{"bool", "int", "int"},
argString: "arg0 bool, arg1, arg2 int",
},
{
argNames: []string{"arg0", "arg1", "arg2"},
argTypes: []string{"int", "bool", "int"},
argString: "arg0 int, arg1 bool, arg2 int",
},
{
argNames: []string{"arg0", "arg1", "arg2"},
argTypes: []string{"int", "int", "bool"},
argString: "arg0, arg1 int, arg2 bool",
},
{
argNames: []string{"arg0", "arg1", "arg2"},
argTypes: []string{"int", "int", "int"},
argString: "arg0, arg1, arg2 int",
},
{
argNames: []string{"arg0", "arg1", "arg2", "arg3"},
argTypes: []string{"bool", "int", "int", "int"},
argString: "arg0 bool, arg1, arg2, arg3 int",
},
{
argNames: []string{"arg0", "arg1", "arg2", "arg3"},
argTypes: []string{"int", "bool", "int", "int"},
argString: "arg0 int, arg1 bool, arg2, arg3 int",
},
{
argNames: []string{"arg0", "arg1", "arg2", "arg3"},
argTypes: []string{"int", "int", "bool", "int"},
argString: "arg0, arg1 int, arg2 bool, arg3 int",
},
{
argNames: []string{"arg0", "arg1", "arg2", "arg3"},
argTypes: []string{"int", "int", "int", "bool"},
argString: "arg0, arg1, arg2 int, arg3 bool",
},
{
argNames: []string{"arg0", "arg1", "arg2", "arg3", "arg4"},
argTypes: []string{"bool", "int", "int", "int", "bool"},
argString: "arg0 bool, arg1, arg2, arg3 int, arg4 bool",
},
{
argNames: []string{"arg0", "arg1", "arg2", "arg3", "arg4"},
argTypes: []string{"int", "bool", "int", "int", "bool"},
argString: "arg0 int, arg1 bool, arg2, arg3 int, arg4 bool",
},
{
argNames: []string{"arg0", "arg1", "arg2", "arg3", "arg4"},
argTypes: []string{"int", "int", "bool", "int", "bool"},
argString: "arg0, arg1 int, arg2 bool, arg3 int, arg4 bool",
},
{
argNames: []string{"arg0", "arg1", "arg2", "arg3", "arg4"},
argTypes: []string{"int", "int", "int", "bool", "bool"},
argString: "arg0, arg1, arg2 int, arg3, arg4 bool",
},
{
argNames: []string{"arg0", "arg1", "arg2", "arg3", "arg4"},
argTypes: []string{"int", "int", "bool", "bool", "int"},
argString: "arg0, arg1 int, arg2, arg3 bool, arg4 int",
},
}
for i, tc := range testCases {
t.Run(fmt.Sprintf("#%d", i), func(t *testing.T) {
s := makeArgString(tc.argNames, tc.argTypes)
if s != tc.argString {
t.Errorf("result == %q, want %q", s, tc.argString)
}
})
}
}
func TestNewIdentifierAllocator(t *testing.T) {
a := newIdentifierAllocator([]string{"taken1", "taken2"})
if len(a) != 2 {
t.Fatalf("expected 2 items, got %v", len(a))
}
_, ok := a["taken1"]
if !ok {
t.Errorf("allocator doesn't contain 'taken1': %#v", a)
}
_, ok = a["taken2"]
if !ok {
t.Errorf("allocator doesn't contain 'taken2': %#v", a)
}
}
func allocatorContainsIdentifiers(a identifierAllocator, ids []string) bool {
if len(a) != len(ids) {
return false
}
for _, id := range ids {
_, ok := a[id]
if !ok {
return false
}
}
return true
}
func TestIdentifierAllocator_allocateIdentifier(t *testing.T) {
a := newIdentifierAllocator([]string{"taken"})
t2 := a.allocateIdentifier("taken_2")
if t2 != "taken_2" {
t.Fatalf("expected 'taken_2', got %q", t2)
}
expected := []string{"taken", "taken_2"}
if !allocatorContainsIdentifiers(a, expected) {
t.Fatalf("allocator doesn't contain the expected items - allocator: %#v, expected items: %#v", a, expected)
}
t3 := a.allocateIdentifier("taken")
if t3 != "taken_3" {
t.Fatalf("expected 'taken_3', got %q", t3)
}
expected = []string{"taken", "taken_2", "taken_3"}
if !allocatorContainsIdentifiers(a, expected) {
t.Fatalf("allocator doesn't contain the expected items - allocator: %#v, expected items: %#v", a, expected)
}
t4 := a.allocateIdentifier("taken")
if t4 != "taken_4" {
t.Fatalf("expected 'taken_4', got %q", t4)
}
expected = []string{"taken", "taken_2", "taken_3", "taken_4"}
if !allocatorContainsIdentifiers(a, expected) {
t.Fatalf("allocator doesn't contain the expected items - allocator: %#v, expected items: %#v", a, expected)
}
id := a.allocateIdentifier("id")
if id != "id" {
t.Fatalf("expected 'id', got %q", id)
}
expected = []string{"taken", "taken_2", "taken_3", "taken_4", "id"}
if !allocatorContainsIdentifiers(a, expected) {
t.Fatalf("allocator doesn't contain the expected items - allocator: %#v, expected items: %#v", a, expected)
}
}
func TestGenerateMockInterface_Helper(t *testing.T) {
for _, test := range []struct {
Name string
Identifier string
HelperLine string
Methods []*model.Method
}{
{Name: "mock", Identifier: "MockSomename", HelperLine: "m.ctrl.T.Helper()"},
{Name: "recorder", Identifier: "MockSomenameMockRecorder", HelperLine: "mr.mock.ctrl.T.Helper()"},
{
Name: "mock identifier conflict",
Identifier: "MockSomename",
HelperLine: "m_2.ctrl.T.Helper()",
Methods: []*model.Method{
{
Name: "MethodA",
In: []*model.Parameter{
{
Name: "m",
Type: &model.NamedType{Type: "int"},
},
},
},
},
},
{
Name: "recorder identifier conflict",
Identifier: "MockSomenameMockRecorder",
HelperLine: "mr_2.mock.ctrl.T.Helper()",
Methods: []*model.Method{
{
Name: "MethodA",
In: []*model.Parameter{
{
Name: "mr",
Type: &model.NamedType{Type: "int"},
},
},
},
},
},
} {
t.Run(test.Name, func(t *testing.T) {
g := generator{}
if len(test.Methods) == 0 {
test.Methods = []*model.Method{
{Name: "MethodA"},
{Name: "MethodB"},
}
}
if err := g.GenerateMockInterface(&model.Interface{
Name: "Somename",
Methods: test.Methods,
}, "somepackage"); err != nil {
t.Fatal(err)
}
lines := strings.Split(g.buf.String(), "\n")
// T.Helper() should be the first line
for _, method := range test.Methods {
if strings.TrimSpace(lines[findMethod(t, test.Identifier, method.Name, lines)+1]) != test.HelperLine {
t.Fatalf("method %s.%s did not declare itself a Helper method", test.Identifier, method.Name)
}
}
})
}
}
func findMethod(t *testing.T, identifier, methodName string, lines []string) int {
t.Helper()
r := regexp.MustCompile(fmt.Sprintf(`func\s+\(.+%s\)\s*%s`, identifier, methodName))
for i, line := range lines {
if r.MatchString(line) {
return i
}
}
t.Fatalf("unable to find 'func (m %s) %s'", identifier, methodName)
panic("unreachable")
}

View file

@ -23,6 +23,9 @@ import (
"strings"
)
// pkgPath is the importable path for package model
const pkgPath = "github.com/golang/mock/mockgen/model"
// Package is a Go package. It may be a subset.
type Package struct {
Name string
@ -131,7 +134,15 @@ func init() {
gob.Register(&MapType{})
gob.Register(&NamedType{})
gob.Register(&PointerType{})
gob.Register(PredeclaredType(""))
// Call gob.RegisterName to make sure it has the consistent name registered
// for both gob decoder and encoder.
//
// For a non-pointer type, gob.Register will try to get package full path by
// calling rt.PkgPath() for a name to register. If your project has vendor
// directory, it is possible that PkgPath will get a path like this:
// ../../../vendor/github.com/golang/mock/mockgen/model
gob.RegisterName(pkgPath+".PredeclaredType", PredeclaredType(""))
}
// ArrayType is an array or slice type.
@ -241,7 +252,12 @@ func (nt *NamedType) String(pm map[string]string, pkgOverride string) string {
if pkgOverride == nt.Package {
return nt.Type
}
return pm[nt.Package] + "." + nt.Type
prefix := pm[nt.Package]
if prefix != "" {
return prefix + "." + nt.Type
} else {
return nt.Type
}
}
func (nt *NamedType) addImports(im map[string]bool) {
if nt.Package != "" {
@ -343,6 +359,13 @@ func typeFromType(t reflect.Type) (Type, error) {
}
if imp := t.PkgPath(); imp != "" {
// PkgPath might return a path that includes "vendor"
// These paths do not compile, so we need to remove everything
// up to and including "/vendor/"
// see https://github.com/golang/go/issues/12019
if i := strings.LastIndex(imp, "/vendor/"); i != -1 {
imp = imp[i+len("/vendor/"):]
}
return &NamedType{
Package: imp,
Type: t.Name(),

View file

@ -20,10 +20,12 @@ import (
"flag"
"fmt"
"go/ast"
"go/build"
"go/parser"
"go/token"
"log"
"path"
"path/filepath"
"strconv"
"strings"
@ -38,6 +40,16 @@ var (
// TODO: simplify error reporting
func ParseFile(source string) (*model.Package, error) {
srcDir, err := filepath.Abs(filepath.Dir(source))
if err != nil {
return nil, fmt.Errorf("failed getting source directory: %v", err)
}
var packageImport string
if p, err := build.ImportDir(srcDir, 0); err == nil {
packageImport = p.ImportPath
} // TODO: should we fail if this returns an error?
fs := token.NewFileSet()
file, err := parser.ParseFile(fs, source, nil, 0)
if err != nil {
@ -45,9 +57,11 @@ func ParseFile(source string) (*model.Package, error) {
}
p := &fileParser{
fileSet: fs,
imports: make(map[string]string),
auxInterfaces: make(map[string]map[string]*ast.InterfaceType),
fileSet: fs,
imports: make(map[string]string),
importedInterfaces: make(map[string]map[string]*ast.InterfaceType),
auxInterfaces: make(map[string]map[string]*ast.InterfaceType),
srcDir: srcDir,
}
// Handle -imports.
@ -70,13 +84,12 @@ func ParseFile(source string) (*model.Package, error) {
if err := p.parseAuxFiles(*auxFiles); err != nil {
return nil, err
}
p.addAuxInterfacesFromFile("", file) // this file
p.addAuxInterfacesFromFile(packageImport, file) // this file
pkg, err := p.parseFile(file)
pkg, err := p.parseFile(packageImport, file)
if err != nil {
return nil, err
}
pkg.DotImports = make([]string, 0, len(dotImports))
for path := range dotImports {
pkg.DotImports = append(pkg.DotImports, path)
}
@ -84,11 +97,14 @@ func ParseFile(source string) (*model.Package, error) {
}
type fileParser struct {
fileSet *token.FileSet
imports map[string]string // package name => import path
fileSet *token.FileSet
imports map[string]string // package name => import path
importedInterfaces map[string]map[string]*ast.InterfaceType // package (or "") => name => interface
auxFiles []*ast.File
auxInterfaces map[string]map[string]*ast.InterfaceType // package (or "") => name => interface
srcDir string
}
func (p *fileParser) errorf(pos token.Pos, format string, args ...interface{}) error {
@ -108,12 +124,14 @@ func (p *fileParser) parseAuxFiles(auxFiles string) error {
if len(parts) != 2 {
return fmt.Errorf("bad aux file spec: %v", kv)
}
file, err := parser.ParseFile(p.fileSet, parts[1], nil, 0)
pkg, fpath := parts[0], parts[1]
file, err := parser.ParseFile(p.fileSet, fpath, nil, 0)
if err != nil {
return err
}
p.auxFiles = append(p.auxFiles, file)
p.addAuxInterfacesFromFile(parts[0], file)
p.addAuxInterfacesFromFile(pkg, file)
}
return nil
}
@ -127,8 +145,10 @@ func (p *fileParser) addAuxInterfacesFromFile(pkg string, file *ast.File) {
}
}
func (p *fileParser) parseFile(file *ast.File) (*model.Package, error) {
allImports := importsOfFile(file)
// parseFile loads all file imports and auxiliary files import into the
// fileParser, parses all file interfaces and returns package model.
func (p *fileParser) parseFile(importPath string, file *ast.File) (*model.Package, error) {
allImports, dotImports := importsOfFile(file)
// Don't stomp imports provided by -imports. Those should take precedence.
for pkg, path := range allImports {
if _, ok := p.imports[pkg]; !ok {
@ -138,7 +158,8 @@ func (p *fileParser) parseFile(file *ast.File) (*model.Package, error) {
// Add imports from auxiliary files, which might be needed for embedded interfaces.
// Don't stomp any other imports.
for _, f := range p.auxFiles {
for pkg, path := range importsOfFile(f) {
auxImports, _ := importsOfFile(f)
for pkg, path := range auxImports {
if _, ok := p.imports[pkg]; !ok {
p.imports[pkg] = path
}
@ -147,7 +168,7 @@ func (p *fileParser) parseFile(file *ast.File) (*model.Package, error) {
var is []*model.Interface
for ni := range iterInterfaces(file) {
i, err := p.parseInterface(ni.name.String(), "", ni.it)
i, err := p.parseInterface(ni.name.String(), importPath, ni.it)
if err != nil {
return nil, err
}
@ -156,9 +177,37 @@ func (p *fileParser) parseFile(file *ast.File) (*model.Package, error) {
return &model.Package{
Name: file.Name.String(),
Interfaces: is,
DotImports: dotImports,
}, nil
}
// parsePackage loads package specified by path, parses it and populates
// corresponding imports and importedInterfaces into the fileParser.
func (p *fileParser) parsePackage(path string) error {
var pkgs map[string]*ast.Package
if imp, err := build.Import(path, p.srcDir, build.FindOnly); err != nil {
return err
} else if pkgs, err = parser.ParseDir(p.fileSet, imp.Dir, nil, 0); err != nil {
return err
}
for _, pkg := range pkgs {
file := ast.MergePackageFiles(pkg, ast.FilterFuncDuplicates|ast.FilterUnassociatedComments|ast.FilterImportDuplicates)
if _, ok := p.importedInterfaces[path]; !ok {
p.importedInterfaces[path] = make(map[string]*ast.InterfaceType)
}
for ni := range iterInterfaces(file) {
p.importedInterfaces[path][ni.name.Name] = ni.it
}
imports, _ := importsOfFile(file)
for pkgName, pkgPath := range imports {
if _, ok := p.imports[pkgName]; !ok {
p.imports[pkgName] = pkgPath
}
}
}
return nil
}
func (p *fileParser) parseInterface(name, pkg string, it *ast.InterfaceType) (*model.Interface, error) {
intf := &model.Interface{Name: name}
for _, field := range it.Methods.List {
@ -178,9 +227,11 @@ func (p *fileParser) parseInterface(name, pkg string, it *ast.InterfaceType) (*m
intf.Methods = append(intf.Methods, m)
case *ast.Ident:
// Embedded interface in this package.
ei := p.auxInterfaces[""][v.String()]
ei := p.auxInterfaces[pkg][v.String()]
if ei == nil {
return nil, p.errorf(v.Pos(), "unknown embedded interface %s", v.String())
if ei = p.importedInterfaces[pkg][v.String()]; ei == nil {
return nil, p.errorf(v.Pos(), "unknown embedded interface %s", v.String())
}
}
eintf, err := p.parseInterface(v.String(), pkg, ei)
if err != nil {
@ -194,15 +245,23 @@ func (p *fileParser) parseInterface(name, pkg string, it *ast.InterfaceType) (*m
case *ast.SelectorExpr:
// Embedded interface in another package.
fpkg, sel := v.X.(*ast.Ident).String(), v.Sel.String()
ei := p.auxInterfaces[fpkg][sel]
if ei == nil {
return nil, p.errorf(v.Pos(), "unknown embedded interface %s.%s", fpkg, sel)
}
epkg, ok := p.imports[fpkg]
if !ok {
return nil, p.errorf(v.X.Pos(), "unknown package %s", fpkg)
}
eintf, err := p.parseInterface(sel, epkg, ei)
ei := p.auxInterfaces[fpkg][sel]
if ei == nil {
fpkg = epkg
if _, ok = p.importedInterfaces[epkg]; !ok {
if err := p.parsePackage(epkg); err != nil {
return nil, p.errorf(v.Pos(), "could not parse package %s: %v", fpkg, err)
}
}
if ei = p.importedInterfaces[epkg][sel]; ei == nil {
return nil, p.errorf(v.Pos(), "unknown embedded interface %s.%s", fpkg, sel)
}
}
eintf, err := p.parseInterface(sel, fpkg, ei)
if err != nil {
return nil, err
}
@ -319,6 +378,12 @@ func (p *fileParser) parseType(pkg string, typ ast.Expr) (model.Type, error) {
return &model.FuncType{In: in, Out: out, Variadic: variadic}, nil
case *ast.Ident:
if v.IsExported() {
// `pkg` may be an aliased imported pkg
// if so, patch the import w/ the fully qualified import
maybeImportedPkg, ok := p.imports[pkg]
if ok {
pkg = maybeImportedPkg
}
// assume type in this package
return &model.NamedType{Package: pkg, Type: v.Name}, nil
} else {
@ -365,43 +430,43 @@ func (p *fileParser) parseType(pkg string, typ ast.Expr) (model.Type, error) {
// importsOfFile returns a map of package name to import path
// of the imports in file.
func importsOfFile(file *ast.File) map[string]string {
/* We have to make guesses about some imports, because imports are not required
* to have names. Named imports are always certain. Unnamed imports are guessed
* to have a name of the last path component; if the last path component has dots,
* the first dot-delimited field is used as the name.
*/
func importsOfFile(file *ast.File) (normalImports map[string]string, dotImports []string) {
normalImports = make(map[string]string)
dotImports = make([]string, 0)
for _, is := range file.Imports {
var pkgName string
importPath := is.Path.Value[1 : len(is.Path.Value)-1] // remove quotes
m := make(map[string]string)
for _, decl := range file.Decls {
gd, ok := decl.(*ast.GenDecl)
if !ok || gd.Tok != token.IMPORT {
continue
}
for _, spec := range gd.Specs {
is, ok := spec.(*ast.ImportSpec)
if !ok {
if is.Name != nil {
// Named imports are always certain.
if is.Name.Name == "_" {
continue
}
pkg, importPath := "", string(is.Path.Value)
importPath = importPath[1 : len(importPath)-1] // remove quotes
if is.Name != nil {
if is.Name.Name == "_" {
continue
}
pkg = removeDot(is.Name.Name)
} else {
pkgName = is.Name.Name
} else {
pkg, err := build.Import(importPath, "", 0)
if err != nil {
// Fallback to import path suffix. Note that this is uncertain.
_, last := path.Split(importPath)
pkg = strings.SplitN(last, ".", 2)[0]
// If the last path component has dots, the first dot-delimited
// field is used as the name.
pkgName = strings.SplitN(last, ".", 2)[0]
} else {
pkgName = pkg.Name
}
if _, ok := m[pkg]; ok {
log.Fatalf("imported package collision: %q imported twice", pkg)
}
if pkgName == "." {
dotImports = append(dotImports, importPath)
} else {
if _, ok := normalImports[pkgName]; ok {
log.Fatalf("imported package collision: %q imported twice", pkgName)
}
m[pkg] = importPath
normalImports[pkgName] = importPath
}
}
return m
return
}
type namedInterface struct {

108
vendor/github.com/golang/mock/mockgen/parse_test.go generated vendored Normal file
View file

@ -0,0 +1,108 @@
package main
import (
"go/ast"
"go/parser"
"go/token"
"testing"
)
func TestFileParser_ParseFile(t *testing.T) {
fs := token.NewFileSet()
file, err := parser.ParseFile(fs, "internal/tests/custom_package_name/greeter/greeter.go", nil, 0)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
p := fileParser{
fileSet: fs,
imports: make(map[string]string),
importedInterfaces: make(map[string]map[string]*ast.InterfaceType),
}
pkg, err := p.parseFile("", file)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
checkGreeterImports(t, p.imports)
expectedName := "greeter"
if pkg.Name != expectedName {
t.Fatalf("Expected name to be %v but got %v", expectedName, pkg.Name)
}
expectedInterfaceName := "InputMaker"
if pkg.Interfaces[0].Name != expectedInterfaceName {
t.Fatalf("Expected interface name to be %v but got %v", expectedInterfaceName, pkg.Interfaces[0].Name)
}
}
func TestFileParser_ParsePackage(t *testing.T) {
fs := token.NewFileSet()
_, err := parser.ParseFile(fs, "internal/tests/custom_package_name/greeter/greeter.go", nil, 0)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
p := fileParser{
fileSet: fs,
imports: make(map[string]string),
importedInterfaces: make(map[string]map[string]*ast.InterfaceType),
}
err = p.parsePackage("github.com/golang/mock/mockgen/internal/tests/custom_package_name/greeter")
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
checkGreeterImports(t, p.imports)
}
func TestImportsOfFile(t *testing.T) {
fs := token.NewFileSet()
file, err := parser.ParseFile(fs, "internal/tests/custom_package_name/greeter/greeter.go", nil, 0)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
imports, _ := importsOfFile(file)
checkGreeterImports(t, imports)
}
func checkGreeterImports(t *testing.T, imports map[string]string) {
// check that imports have stdlib package "fmt"
if fmtPackage, ok := imports["fmt"]; !ok {
t.Errorf("Expected imports to have key \"fmt\"")
} else {
expectedFmtPackage := "fmt"
if fmtPackage != expectedFmtPackage {
t.Errorf("Expected fmt key to have value %s but got %s", expectedFmtPackage, fmtPackage)
}
}
// check that imports have package named "validator"
if validatorPackage, ok := imports["validator"]; !ok {
t.Errorf("Expected imports to have key \"fmt\"")
} else {
expectedValidatorPackage := "github.com/golang/mock/mockgen/internal/tests/custom_package_name/validator"
if validatorPackage != expectedValidatorPackage {
t.Errorf("Expected validator key to have value %s but got %s", expectedValidatorPackage, validatorPackage)
}
}
// check that imports have package named "client"
if clientPackage, ok := imports["client"]; !ok {
t.Errorf("Expected imports to have key \"client\"")
} else {
expectedClientPackage := "github.com/golang/mock/mockgen/internal/tests/custom_package_name/client/v1"
if clientPackage != expectedClientPackage {
t.Errorf("Expected client key to have value %s but got %s", expectedClientPackage, clientPackage)
}
}
// check that imports don't have package named "v1"
if _, ok := imports["v1"]; ok {
t.Errorf("Expected import not to have key \"v1\"")
}
}

View file

@ -20,7 +20,7 @@ import (
"bytes"
"encoding/gob"
"flag"
"io"
"go/build"
"io/ioutil"
"os"
"os/exec"
@ -32,81 +32,131 @@ import (
)
var (
progOnly = flag.Bool("prog_only", false, "(reflect mode) Only generate the reflection program; write it to stdout.")
progOnly = flag.Bool("prog_only", false, "(reflect mode) Only generate the reflection program; write it to stdout and exit.")
execOnly = flag.String("exec_only", "", "(reflect mode) If set, execute this reflection program.")
buildFlags = flag.String("build_flags", "", "(reflect mode) Additional flags for go build.")
)
func Reflect(importPath string, symbols []string) (*model.Package, error) {
// TODO: sanity check arguments
func writeProgram(importPath string, symbols []string) ([]byte, error) {
var program bytes.Buffer
data := reflectData{
ImportPath: importPath,
Symbols: symbols,
}
if err := reflectProgram.Execute(&program, &data); err != nil {
return nil, err
}
return program.Bytes(), nil
}
progPath := *execOnly
if *execOnly == "" {
// We use TempDir instead of TempFile so we can control the filename.
tmpDir, err := ioutil.TempDir("", "gomock_reflect_")
if err != nil {
return nil, err
}
defer func() { os.RemoveAll(tmpDir) }()
const progSource = "prog.go"
var progBinary = "prog.bin"
if runtime.GOOS == "windows" {
// Windows won't execute a program unless it has a ".exe" suffix.
progBinary += ".exe"
}
// Generate program.
var program bytes.Buffer
data := reflectData{
ImportPath: importPath,
Symbols: symbols,
}
if err := reflectProgram.Execute(&program, &data); err != nil {
return nil, err
}
if *progOnly {
io.Copy(os.Stdout, &program)
os.Exit(0)
}
if err := ioutil.WriteFile(filepath.Join(tmpDir, progSource), program.Bytes(), 0600); err != nil {
return nil, err
}
cmdArgs := []string{}
cmdArgs = append(cmdArgs, "build")
if *buildFlags != "" {
cmdArgs = append(cmdArgs, *buildFlags)
}
cmdArgs = append(cmdArgs, "-o", progBinary, progSource)
// Build the program.
cmd := exec.Command("go", cmdArgs...)
cmd.Dir = tmpDir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return nil, err
}
progPath = filepath.Join(tmpDir, progBinary)
// run the given program and parse the output as a model.Package.
func run(program string) (*model.Package, error) {
f, err := ioutil.TempFile("", "")
filename := f.Name()
defer os.Remove(filename)
if err := f.Close(); err != nil {
return nil, err
}
// Run it.
cmd := exec.Command(progPath)
var stdout bytes.Buffer
cmd.Stdout = &stdout
// Run the program.
cmd := exec.Command(program, "-output", filename)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return nil, err
}
// Process output.
var pkg model.Package
if err := gob.NewDecoder(&stdout).Decode(&pkg); err != nil {
f, err = os.Open(filename)
if err != nil {
return nil, err
}
// Process output.
var pkg model.Package
if err := gob.NewDecoder(f).Decode(&pkg); err != nil {
return nil, err
}
if err := f.Close(); err != nil {
return nil, err
}
return &pkg, nil
}
// runInDir writes the given program into the given dir, runs it there, and
// parses the output as a model.Package.
func runInDir(program []byte, dir string) (*model.Package, error) {
// We use TempDir instead of TempFile so we can control the filename.
tmpDir, err := ioutil.TempDir(dir, "gomock_reflect_")
if err != nil {
return nil, err
}
defer func() { os.RemoveAll(tmpDir) }()
const progSource = "prog.go"
var progBinary = "prog.bin"
if runtime.GOOS == "windows" {
// Windows won't execute a program unless it has a ".exe" suffix.
progBinary += ".exe"
}
if err := ioutil.WriteFile(filepath.Join(tmpDir, progSource), program, 0600); err != nil {
return nil, err
}
cmdArgs := []string{}
cmdArgs = append(cmdArgs, "build")
if *buildFlags != "" {
cmdArgs = append(cmdArgs, *buildFlags)
}
cmdArgs = append(cmdArgs, "-o", progBinary, progSource)
// Build the program.
cmd := exec.Command("go", cmdArgs...)
cmd.Dir = tmpDir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return nil, err
}
return run(filepath.Join(tmpDir, progBinary))
}
func Reflect(importPath string, symbols []string) (*model.Package, error) {
// TODO: sanity check arguments
if *execOnly != "" {
return run(*execOnly)
}
program, err := writeProgram(importPath, symbols)
if err != nil {
return nil, err
}
if *progOnly {
os.Stdout.Write(program)
os.Exit(0)
}
wd, _ := os.Getwd()
// Try to run the program in the same directory as the input package.
if p, err := build.Import(importPath, wd, build.FindOnly); err == nil {
dir := p.Dir
if p, err := runInDir(program, dir); err == nil {
return p, nil
}
}
// Since that didn't work, try to run it in the current working directory.
if p, err := runInDir(program, wd); err == nil {
return p, nil
}
// Since that didn't work, try to run it in a standard temp directory.
return runInDir(program, "")
}
type reflectData struct {
ImportPath string
Symbols []string
@ -120,6 +170,7 @@ package main
import (
"encoding/gob"
"flag"
"fmt"
"os"
"path"
@ -130,7 +181,11 @@ import (
pkg_ {{printf "%q" .ImportPath}}
)
var output = flag.String("output", "", "The output file name, or empty to use stdout.")
func main() {
flag.Parse()
its := []struct{
sym string
typ reflect.Type
@ -155,7 +210,23 @@ func main() {
intf.Name = it.sym
pkg.Interfaces = append(pkg.Interfaces, intf)
}
if err := gob.NewEncoder(os.Stdout).Encode(pkg); err != nil {
outfile := os.Stdout
if len(*output) != 0 {
var err error
outfile, err = os.Create(*output)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to open output file %q", *output)
}
defer func() {
if err := outfile.Close(); err != nil {
fmt.Fprintf(os.Stderr, "failed to close output file %q", *output)
os.Exit(1)
}
}()
}
if err := gob.NewEncoder(outfile).Encode(pkg); err != nil {
fmt.Fprintf(os.Stderr, "gob encode: %v\n", err)
os.Exit(1)
}

View file

@ -8,8 +8,8 @@ interface that can be mocked with GoMock. The interesting files are:
interfaces from `user.go` are used. This demonstrates how to create mock
objects, set up expectations, and so on.
* `mock_user/mock_user.go`: The generated mock code. See ../update_mocks.sh
for the command used to generate it.
* `mock_user/mock_user.go`: The generated mock code. See ../gomock/matchers.go
for the `go:generate` command used to generate it.
To run the test,

View file

@ -0,0 +1,8 @@
//go:generate mockgen -destination mock/concurrent_mock.go github.com/golang/mock/sample/concurrent Math
// Package concurrent demonstrates how to use gomock with goroutines.
package concurrent
type Math interface {
Sum(a, b int) int
}

View file

@ -0,0 +1,46 @@
package concurrent
import (
"testing"
"context"
"github.com/golang/mock/gomock"
mock "github.com/golang/mock/sample/concurrent/mock"
)
func call(ctx context.Context, m Math) (int, error) {
result := make(chan int)
go func() {
result <- m.Sum(1, 2)
close(result)
}()
select {
case r := <-result:
return r, nil
case <-ctx.Done():
return 0, ctx.Err()
}
}
// testConcurrentFails is expected to fail (and is disabled). It
// demonstrates how to use gomock.WithContext to interrupt the test
// from a different goroutine.
func testConcurrentFails(t *testing.T) {
ctrl, ctx := gomock.WithContext(context.Background(), t)
defer ctrl.Finish()
m := mock.NewMockMath(ctrl)
if _, err := call(ctx, m); err != nil {
t.Error("call failed:", err)
}
}
func TestConcurrentWorks(t *testing.T) {
ctrl, ctx := gomock.WithContext(context.Background(), t)
defer ctrl.Finish()
m := mock.NewMockMath(ctrl)
m.EXPECT().Sum(1, 2).Return(3)
if _, err := call(ctx, m); err != nil {
t.Error("call failed:", err)
}
}

View file

@ -0,0 +1,47 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: github.com/golang/mock/sample/concurrent (interfaces: Math)
// Package mock_concurrent is a generated GoMock package.
package mock_concurrent
import (
gomock "github.com/golang/mock/gomock"
reflect "reflect"
)
// MockMath is a mock of Math interface
type MockMath struct {
ctrl *gomock.Controller
recorder *MockMathMockRecorder
}
// MockMathMockRecorder is the mock recorder for MockMath
type MockMathMockRecorder struct {
mock *MockMath
}
// NewMockMath creates a new mock instance
func NewMockMath(ctrl *gomock.Controller) *MockMath {
mock := &MockMath{ctrl: ctrl}
mock.recorder = &MockMathMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockMath) EXPECT() *MockMathMockRecorder {
return m.recorder
}
// Sum mocks base method
func (m *MockMath) Sum(arg0, arg1 int) int {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Sum", arg0, arg1)
ret0, _ := ret[0].(int)
return ret0
}
// Sum indicates an expected call of Sum
func (mr *MockMathMockRecorder) Sum(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sum", reflect.TypeOf((*MockMath)(nil).Sum), arg0, arg1)
}

View file

@ -1,6 +1,7 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: github.com/golang/mock/sample (interfaces: Index,Embed,Embedded)
// Package mock_sample is a generated GoMock package.
package mock_sample
import (
@ -38,250 +39,294 @@ func NewMockIndex(ctrl *gomock.Controller) *MockIndex {
}
// EXPECT returns an object that allows the caller to indicate expected use
func (_m *MockIndex) EXPECT() *MockIndexMockRecorder {
return _m.recorder
func (m *MockIndex) EXPECT() *MockIndexMockRecorder {
return m.recorder
}
// Anon mocks base method
func (_m *MockIndex) Anon(_param0 string) {
_m.ctrl.Call(_m, "Anon", _param0)
func (m *MockIndex) Anon(arg0 string) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "Anon", arg0)
}
// Anon indicates an expected call of Anon
func (_mr *MockIndexMockRecorder) Anon(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "Anon", reflect.TypeOf((*MockIndex)(nil).Anon), arg0)
func (mr *MockIndexMockRecorder) Anon(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Anon", reflect.TypeOf((*MockIndex)(nil).Anon), arg0)
}
// Chan mocks base method
func (_m *MockIndex) Chan(_param0 chan int, _param1 chan<- hash.Hash) {
_m.ctrl.Call(_m, "Chan", _param0, _param1)
func (m *MockIndex) Chan(arg0 chan int, arg1 chan<- hash.Hash) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "Chan", arg0, arg1)
}
// Chan indicates an expected call of Chan
func (_mr *MockIndexMockRecorder) Chan(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "Chan", reflect.TypeOf((*MockIndex)(nil).Chan), arg0, arg1)
func (mr *MockIndexMockRecorder) Chan(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Chan", reflect.TypeOf((*MockIndex)(nil).Chan), arg0, arg1)
}
// ConcreteRet mocks base method
func (_m *MockIndex) ConcreteRet() chan<- bool {
ret := _m.ctrl.Call(_m, "ConcreteRet")
func (m *MockIndex) ConcreteRet() chan<- bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ConcreteRet")
ret0, _ := ret[0].(chan<- bool)
return ret0
}
// ConcreteRet indicates an expected call of ConcreteRet
func (_mr *MockIndexMockRecorder) ConcreteRet() *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "ConcreteRet", reflect.TypeOf((*MockIndex)(nil).ConcreteRet))
func (mr *MockIndexMockRecorder) ConcreteRet() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConcreteRet", reflect.TypeOf((*MockIndex)(nil).ConcreteRet))
}
// Ellip mocks base method
func (_m *MockIndex) Ellip(_param0 string, _param1 ...interface{}) {
_s := []interface{}{_param0}
for _, _x := range _param1 {
_s = append(_s, _x)
func (m *MockIndex) Ellip(arg0 string, arg1 ...interface{}) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0}
for _, a := range arg1 {
varargs = append(varargs, a)
}
_m.ctrl.Call(_m, "Ellip", _s...)
m.ctrl.Call(m, "Ellip", varargs...)
}
// Ellip indicates an expected call of Ellip
func (_mr *MockIndexMockRecorder) Ellip(arg0 interface{}, arg1 ...interface{}) *gomock.Call {
_s := append([]interface{}{arg0}, arg1...)
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "Ellip", reflect.TypeOf((*MockIndex)(nil).Ellip), _s...)
func (mr *MockIndexMockRecorder) Ellip(arg0 interface{}, arg1 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0}, arg1...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ellip", reflect.TypeOf((*MockIndex)(nil).Ellip), varargs...)
}
// EllipOnly mocks base method
func (_m *MockIndex) EllipOnly(_param0 ...string) {
_s := []interface{}{}
for _, _x := range _param0 {
_s = append(_s, _x)
func (m *MockIndex) EllipOnly(arg0 ...string) {
m.ctrl.T.Helper()
varargs := []interface{}{}
for _, a := range arg0 {
varargs = append(varargs, a)
}
_m.ctrl.Call(_m, "EllipOnly", _s...)
m.ctrl.Call(m, "EllipOnly", varargs...)
}
// EllipOnly indicates an expected call of EllipOnly
func (_mr *MockIndexMockRecorder) EllipOnly(arg0 ...interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "EllipOnly", reflect.TypeOf((*MockIndex)(nil).EllipOnly), arg0...)
func (mr *MockIndexMockRecorder) EllipOnly(arg0 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EllipOnly", reflect.TypeOf((*MockIndex)(nil).EllipOnly), arg0...)
}
// ForeignFour mocks base method
func (_m *MockIndex) ForeignFour(_param0 imp4.Imp4) {
_m.ctrl.Call(_m, "ForeignFour", _param0)
func (m *MockIndex) ForeignFour(arg0 imp4.Imp4) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "ForeignFour", arg0)
}
// ForeignFour indicates an expected call of ForeignFour
func (_mr *MockIndexMockRecorder) ForeignFour(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "ForeignFour", reflect.TypeOf((*MockIndex)(nil).ForeignFour), arg0)
func (mr *MockIndexMockRecorder) ForeignFour(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ForeignFour", reflect.TypeOf((*MockIndex)(nil).ForeignFour), arg0)
}
// ForeignOne mocks base method
func (_m *MockIndex) ForeignOne(_param0 imp1.Imp1) {
_m.ctrl.Call(_m, "ForeignOne", _param0)
func (m *MockIndex) ForeignOne(arg0 imp1.Imp1) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "ForeignOne", arg0)
}
// ForeignOne indicates an expected call of ForeignOne
func (_mr *MockIndexMockRecorder) ForeignOne(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "ForeignOne", reflect.TypeOf((*MockIndex)(nil).ForeignOne), arg0)
func (mr *MockIndexMockRecorder) ForeignOne(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ForeignOne", reflect.TypeOf((*MockIndex)(nil).ForeignOne), arg0)
}
// ForeignThree mocks base method
func (_m *MockIndex) ForeignThree(_param0 imp3.Imp3) {
_m.ctrl.Call(_m, "ForeignThree", _param0)
func (m *MockIndex) ForeignThree(arg0 imp3.Imp3) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "ForeignThree", arg0)
}
// ForeignThree indicates an expected call of ForeignThree
func (_mr *MockIndexMockRecorder) ForeignThree(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "ForeignThree", reflect.TypeOf((*MockIndex)(nil).ForeignThree), arg0)
func (mr *MockIndexMockRecorder) ForeignThree(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ForeignThree", reflect.TypeOf((*MockIndex)(nil).ForeignThree), arg0)
}
// ForeignTwo mocks base method
func (_m *MockIndex) ForeignTwo(_param0 imp2.Imp2) {
_m.ctrl.Call(_m, "ForeignTwo", _param0)
func (m *MockIndex) ForeignTwo(arg0 imp2.Imp2) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "ForeignTwo", arg0)
}
// ForeignTwo indicates an expected call of ForeignTwo
func (_mr *MockIndexMockRecorder) ForeignTwo(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "ForeignTwo", reflect.TypeOf((*MockIndex)(nil).ForeignTwo), arg0)
func (mr *MockIndexMockRecorder) ForeignTwo(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ForeignTwo", reflect.TypeOf((*MockIndex)(nil).ForeignTwo), arg0)
}
// Func mocks base method
func (_m *MockIndex) Func(_param0 func(http.Request) (int, bool)) {
_m.ctrl.Call(_m, "Func", _param0)
func (m *MockIndex) Func(arg0 func(http.Request) (int, bool)) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "Func", arg0)
}
// Func indicates an expected call of Func
func (_mr *MockIndexMockRecorder) Func(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "Func", reflect.TypeOf((*MockIndex)(nil).Func), arg0)
func (mr *MockIndexMockRecorder) Func(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Func", reflect.TypeOf((*MockIndex)(nil).Func), arg0)
}
// Get mocks base method
func (_m *MockIndex) Get(_param0 string) interface{} {
ret := _m.ctrl.Call(_m, "Get", _param0)
func (m *MockIndex) Get(arg0 string) interface{} {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Get", arg0)
ret0, _ := ret[0].(interface{})
return ret0
}
// Get indicates an expected call of Get
func (_mr *MockIndexMockRecorder) Get(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "Get", reflect.TypeOf((*MockIndex)(nil).Get), arg0)
func (mr *MockIndexMockRecorder) Get(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockIndex)(nil).Get), arg0)
}
// GetTwo mocks base method
func (_m *MockIndex) GetTwo(_param0 string, _param1 string) (interface{}, interface{}) {
ret := _m.ctrl.Call(_m, "GetTwo", _param0, _param1)
func (m *MockIndex) GetTwo(arg0, arg1 string) (interface{}, interface{}) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetTwo", arg0, arg1)
ret0, _ := ret[0].(interface{})
ret1, _ := ret[1].(interface{})
return ret0, ret1
}
// GetTwo indicates an expected call of GetTwo
func (_mr *MockIndexMockRecorder) GetTwo(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "GetTwo", reflect.TypeOf((*MockIndex)(nil).GetTwo), arg0, arg1)
func (mr *MockIndexMockRecorder) GetTwo(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTwo", reflect.TypeOf((*MockIndex)(nil).GetTwo), arg0, arg1)
}
// Map mocks base method
func (_m *MockIndex) Map(_param0 map[int]hash.Hash) {
_m.ctrl.Call(_m, "Map", _param0)
func (m *MockIndex) Map(arg0 map[int]hash.Hash) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "Map", arg0)
}
// Map indicates an expected call of Map
func (_mr *MockIndexMockRecorder) Map(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "Map", reflect.TypeOf((*MockIndex)(nil).Map), arg0)
func (mr *MockIndexMockRecorder) Map(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Map", reflect.TypeOf((*MockIndex)(nil).Map), arg0)
}
// NillableRet mocks base method
func (_m *MockIndex) NillableRet() error {
ret := _m.ctrl.Call(_m, "NillableRet")
func (m *MockIndex) NillableRet() error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "NillableRet")
ret0, _ := ret[0].(error)
return ret0
}
// NillableRet indicates an expected call of NillableRet
func (_mr *MockIndexMockRecorder) NillableRet() *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "NillableRet", reflect.TypeOf((*MockIndex)(nil).NillableRet))
func (mr *MockIndexMockRecorder) NillableRet() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NillableRet", reflect.TypeOf((*MockIndex)(nil).NillableRet))
}
// Other mocks base method
func (_m *MockIndex) Other() hash.Hash {
ret := _m.ctrl.Call(_m, "Other")
func (m *MockIndex) Other() hash.Hash {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Other")
ret0, _ := ret[0].(hash.Hash)
return ret0
}
// Other indicates an expected call of Other
func (_mr *MockIndexMockRecorder) Other() *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "Other", reflect.TypeOf((*MockIndex)(nil).Other))
func (mr *MockIndexMockRecorder) Other() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Other", reflect.TypeOf((*MockIndex)(nil).Other))
}
// Ptr mocks base method
func (_m *MockIndex) Ptr(_param0 *int) {
_m.ctrl.Call(_m, "Ptr", _param0)
func (m *MockIndex) Ptr(arg0 *int) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "Ptr", arg0)
}
// Ptr indicates an expected call of Ptr
func (_mr *MockIndexMockRecorder) Ptr(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "Ptr", reflect.TypeOf((*MockIndex)(nil).Ptr), arg0)
func (mr *MockIndexMockRecorder) Ptr(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ptr", reflect.TypeOf((*MockIndex)(nil).Ptr), arg0)
}
// Put mocks base method
func (_m *MockIndex) Put(_param0 string, _param1 interface{}) {
_m.ctrl.Call(_m, "Put", _param0, _param1)
func (m *MockIndex) Put(arg0 string, arg1 interface{}) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "Put", arg0, arg1)
}
// Put indicates an expected call of Put
func (_mr *MockIndexMockRecorder) Put(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "Put", reflect.TypeOf((*MockIndex)(nil).Put), arg0, arg1)
func (mr *MockIndexMockRecorder) Put(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Put", reflect.TypeOf((*MockIndex)(nil).Put), arg0, arg1)
}
// Slice mocks base method
func (_m *MockIndex) Slice(_param0 []int, _param1 []byte) [3]int {
ret := _m.ctrl.Call(_m, "Slice", _param0, _param1)
func (m *MockIndex) Slice(arg0 []int, arg1 []byte) [3]int {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Slice", arg0, arg1)
ret0, _ := ret[0].([3]int)
return ret0
}
// Slice indicates an expected call of Slice
func (_mr *MockIndexMockRecorder) Slice(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "Slice", reflect.TypeOf((*MockIndex)(nil).Slice), arg0, arg1)
func (mr *MockIndexMockRecorder) Slice(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Slice", reflect.TypeOf((*MockIndex)(nil).Slice), arg0, arg1)
}
// Struct mocks base method
func (_m *MockIndex) Struct(_param0 struct{}) {
_m.ctrl.Call(_m, "Struct", _param0)
func (m *MockIndex) Struct(arg0 struct{}) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "Struct", arg0)
}
// Struct indicates an expected call of Struct
func (_mr *MockIndexMockRecorder) Struct(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "Struct", reflect.TypeOf((*MockIndex)(nil).Struct), arg0)
func (mr *MockIndexMockRecorder) Struct(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Struct", reflect.TypeOf((*MockIndex)(nil).Struct), arg0)
}
// StructChan mocks base method
func (_m *MockIndex) StructChan(_param0 chan struct{}) {
_m.ctrl.Call(_m, "StructChan", _param0)
func (m *MockIndex) StructChan(arg0 chan struct{}) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "StructChan", arg0)
}
// StructChan indicates an expected call of StructChan
func (_mr *MockIndexMockRecorder) StructChan(arg0 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "StructChan", reflect.TypeOf((*MockIndex)(nil).StructChan), arg0)
func (mr *MockIndexMockRecorder) StructChan(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StructChan", reflect.TypeOf((*MockIndex)(nil).StructChan), arg0)
}
// Summary mocks base method
func (_m *MockIndex) Summary(_param0 *bytes.Buffer, _param1 io.Writer) {
_m.ctrl.Call(_m, "Summary", _param0, _param1)
func (m *MockIndex) Summary(arg0 *bytes.Buffer, arg1 io.Writer) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "Summary", arg0, arg1)
}
// Summary indicates an expected call of Summary
func (_mr *MockIndexMockRecorder) Summary(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "Summary", reflect.TypeOf((*MockIndex)(nil).Summary), arg0, arg1)
func (mr *MockIndexMockRecorder) Summary(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Summary", reflect.TypeOf((*MockIndex)(nil).Summary), arg0, arg1)
}
// Templates mocks base method
func (_m *MockIndex) Templates(_param0 template.CSS, _param1 template0.FuncMap) {
_m.ctrl.Call(_m, "Templates", _param0, _param1)
func (m *MockIndex) Templates(arg0 template.CSS, arg1 template0.FuncMap) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "Templates", arg0, arg1)
}
// Templates indicates an expected call of Templates
func (_mr *MockIndexMockRecorder) Templates(arg0, arg1 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "Templates", reflect.TypeOf((*MockIndex)(nil).Templates), arg0, arg1)
func (mr *MockIndexMockRecorder) Templates(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Templates", reflect.TypeOf((*MockIndex)(nil).Templates), arg0, arg1)
}
// MockEmbed is a mock of Embed interface
@ -303,50 +348,58 @@ func NewMockEmbed(ctrl *gomock.Controller) *MockEmbed {
}
// EXPECT returns an object that allows the caller to indicate expected use
func (_m *MockEmbed) EXPECT() *MockEmbedMockRecorder {
return _m.recorder
func (m *MockEmbed) EXPECT() *MockEmbedMockRecorder {
return m.recorder
}
// EmbeddedMethod mocks base method
func (_m *MockEmbed) EmbeddedMethod() {
_m.ctrl.Call(_m, "EmbeddedMethod")
func (m *MockEmbed) EmbeddedMethod() {
m.ctrl.T.Helper()
m.ctrl.Call(m, "EmbeddedMethod")
}
// EmbeddedMethod indicates an expected call of EmbeddedMethod
func (_mr *MockEmbedMockRecorder) EmbeddedMethod() *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "EmbeddedMethod", reflect.TypeOf((*MockEmbed)(nil).EmbeddedMethod))
func (mr *MockEmbedMockRecorder) EmbeddedMethod() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EmbeddedMethod", reflect.TypeOf((*MockEmbed)(nil).EmbeddedMethod))
}
// ForeignEmbeddedMethod mocks base method
func (_m *MockEmbed) ForeignEmbeddedMethod() *bufio.Reader {
ret := _m.ctrl.Call(_m, "ForeignEmbeddedMethod")
func (m *MockEmbed) ForeignEmbeddedMethod() *bufio.Reader {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ForeignEmbeddedMethod")
ret0, _ := ret[0].(*bufio.Reader)
return ret0
}
// ForeignEmbeddedMethod indicates an expected call of ForeignEmbeddedMethod
func (_mr *MockEmbedMockRecorder) ForeignEmbeddedMethod() *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "ForeignEmbeddedMethod", reflect.TypeOf((*MockEmbed)(nil).ForeignEmbeddedMethod))
func (mr *MockEmbedMockRecorder) ForeignEmbeddedMethod() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ForeignEmbeddedMethod", reflect.TypeOf((*MockEmbed)(nil).ForeignEmbeddedMethod))
}
// ImplicitPackage mocks base method
func (_m *MockEmbed) ImplicitPackage(_param0 string, _param1 imp1.ImpT, _param2 []imp1.ImpT, _param3 *imp1.ImpT, _param4 chan imp1.ImpT) {
_m.ctrl.Call(_m, "ImplicitPackage", _param0, _param1, _param2, _param3, _param4)
func (m *MockEmbed) ImplicitPackage(arg0 string, arg1 imp1.ImpT, arg2 []imp1.ImpT, arg3 *imp1.ImpT, arg4 chan imp1.ImpT) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "ImplicitPackage", arg0, arg1, arg2, arg3, arg4)
}
// ImplicitPackage indicates an expected call of ImplicitPackage
func (_mr *MockEmbedMockRecorder) ImplicitPackage(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "ImplicitPackage", reflect.TypeOf((*MockEmbed)(nil).ImplicitPackage), arg0, arg1, arg2, arg3, arg4)
func (mr *MockEmbedMockRecorder) ImplicitPackage(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ImplicitPackage", reflect.TypeOf((*MockEmbed)(nil).ImplicitPackage), arg0, arg1, arg2, arg3, arg4)
}
// RegularMethod mocks base method
func (_m *MockEmbed) RegularMethod() {
_m.ctrl.Call(_m, "RegularMethod")
func (m *MockEmbed) RegularMethod() {
m.ctrl.T.Helper()
m.ctrl.Call(m, "RegularMethod")
}
// RegularMethod indicates an expected call of RegularMethod
func (_mr *MockEmbedMockRecorder) RegularMethod() *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "RegularMethod", reflect.TypeOf((*MockEmbed)(nil).RegularMethod))
func (mr *MockEmbedMockRecorder) RegularMethod() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegularMethod", reflect.TypeOf((*MockEmbed)(nil).RegularMethod))
}
// MockEmbedded is a mock of Embedded interface
@ -368,16 +421,18 @@ func NewMockEmbedded(ctrl *gomock.Controller) *MockEmbedded {
}
// EXPECT returns an object that allows the caller to indicate expected use
func (_m *MockEmbedded) EXPECT() *MockEmbeddedMockRecorder {
return _m.recorder
func (m *MockEmbedded) EXPECT() *MockEmbeddedMockRecorder {
return m.recorder
}
// EmbeddedMethod mocks base method
func (_m *MockEmbedded) EmbeddedMethod() {
_m.ctrl.Call(_m, "EmbeddedMethod")
func (m *MockEmbedded) EmbeddedMethod() {
m.ctrl.T.Helper()
m.ctrl.Call(m, "EmbeddedMethod")
}
// EmbeddedMethod indicates an expected call of EmbeddedMethod
func (_mr *MockEmbeddedMockRecorder) EmbeddedMethod() *gomock.Call {
return _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, "EmbeddedMethod", reflect.TypeOf((*MockEmbedded)(nil).EmbeddedMethod))
func (mr *MockEmbeddedMockRecorder) EmbeddedMethod() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EmbeddedMethod", reflect.TypeOf((*MockEmbedded)(nil).EmbeddedMethod))
}

View file

@ -68,18 +68,57 @@ func TestVariadicFunction(t *testing.T) {
defer ctrl.Finish()
mockIndex := mock_user.NewMockIndex(ctrl)
m := mockIndex.EXPECT().Ellip("%d", 0, 1, 1, 2, 3)
m.Do(func(format string, nums ...int) {
mockIndex.EXPECT().Ellip("%d", 5, 6, 7, 8).Do(func(format string, nums ...int) {
sum := 0
for _, value := range nums {
sum += value
}
if sum != 7 {
if sum != 26 {
t.Errorf("Expected 7, got %d", sum)
}
})
mockIndex.EXPECT().Ellip("%d", gomock.Any()).Do(func(format string, nums ...int) {
sum := 0
for _, value := range nums {
sum += value
}
if sum != 10 {
t.Errorf("Expected 7, got %d", sum)
}
})
mockIndex.EXPECT().Ellip("%d", gomock.Any()).Do(func(format string, nums ...int) {
sum := 0
for _, value := range nums {
sum += value
}
if sum != 0 {
t.Errorf("Expected 0, got %d", sum)
}
})
mockIndex.EXPECT().Ellip("%d", gomock.Any()).Do(func(format string, nums ...int) {
sum := 0
for _, value := range nums {
sum += value
}
if sum != 0 {
t.Errorf("Expected 0, got %d", sum)
}
})
mockIndex.EXPECT().Ellip("%d").Do(func(format string, nums ...int) {
sum := 0
for _, value := range nums {
sum += value
}
if sum != 0 {
t.Errorf("Expected 0, got %d", sum)
}
})
mockIndex.Ellip("%d", 0, 1, 1, 2, 3)
mockIndex.Ellip("%d", 1, 2, 3, 4) // Match second matcher.
mockIndex.Ellip("%d", 5, 6, 7, 8) // Match first matcher.
mockIndex.Ellip("%d", 0)
mockIndex.Ellip("%d")
mockIndex.Ellip("%d")
}
func TestGrabPointer(t *testing.T) {

View file

@ -0,0 +1,14 @@
; http://editorconfig.org/
root = true
[*]
end_of_line = lf
insert_final_newline = true
charset = utf-8
trim_trailing_whitespace = true
[*.go]
indent_style = tab
indent_size = 8

24
vendor/github.com/mmatczuk/go-http-tunnel/.gitignore generated vendored Normal file
View file

@ -0,0 +1,24 @@
### Tunnel
.tunnel/
build/
### Go
*.cov
*.prof
*.mprof
### IntelliJ
.idea/
*.iml
### Vim
# swap
[._]*.s[a-w][a-z]
[._]s[a-w][a-z]
# session
Session.vim
# temporary
.netrwhist
*~
# auto-generated tag files
tags

15
vendor/github.com/mmatczuk/go-http-tunnel/.travis.yml generated vendored Normal file
View file

@ -0,0 +1,15 @@
language: go
go:
- 1.x
addons:
apt:
packages:
- moreutils
install:
- make get-tools
- make get-deps
script:
- make

51
vendor/github.com/mmatczuk/go-http-tunnel/Gopkg.lock generated vendored Normal file
View file

@ -0,0 +1,51 @@
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
[[projects]]
name = "github.com/calmh/luhn"
packages = ["."]
revision = "5b2abb343e70180dbf456397c5fd93f14471b08e"
version = "v2.0.0"
[[projects]]
name = "github.com/cenkalti/backoff"
packages = ["."]
revision = "61153c768f31ee5f130071d08fc82b85208528de"
version = "v1.1.0"
[[projects]]
branch = "master"
name = "github.com/felixge/tcpkeepalive"
packages = ["."]
revision = "5bb0b2dea91e0de550022159b9571aafc72c08ba"
[[projects]]
name = "github.com/golang/mock"
packages = ["gomock"]
revision = "13f360950a79f5864a972c786a10a50e44b69541"
version = "v1.0.0"
[[projects]]
branch = "master"
name = "golang.org/x/net"
packages = ["context","http2","http2/hpack","idna","lex/httplex"]
revision = "c7086645de248775cbf2373cf5ca4d2fa664b8c1"
[[projects]]
branch = "master"
name = "golang.org/x/text"
packages = ["collate","collate/build","internal/colltab","internal/gen","internal/tag","internal/triegen","internal/ucd","language","secure/bidirule","transform","unicode/bidi","unicode/cldr","unicode/norm","unicode/rangetable"]
revision = "88f656faf3f37f690df1a32515b479415e1a6769"
[[projects]]
branch = "v2"
name = "gopkg.in/yaml.v2"
packages = ["."]
revision = "287cf08546ab5e7e37d55a84f7ed3fd1db036de5"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "654fea302b8b5a71ce4f36f4097d0c0caa8150e46109cfbdd462adcd054a6768"
solver-name = "gps-cdcl"
solver-version = 1

50
vendor/github.com/mmatczuk/go-http-tunnel/Gopkg.toml generated vendored Normal file
View file

@ -0,0 +1,50 @@
# Gopkg.toml example
#
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
# for detailed Gopkg.toml documentation.
#
# required = ["github.com/user/thing/cmd/thing"]
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
#
# [[constraint]]
# name = "github.com/user/project"
# version = "1.0.0"
#
# [[constraint]]
# name = "github.com/user/project2"
# branch = "dev"
# source = "github.com/myfork/project2"
#
# [[override]]
# name = "github.com/x/y"
# version = "2.4.0"
[[constraint]]
name = "github.com/calmh/luhn"
version = "2.0.0"
[[constraint]]
name = "github.com/cenkalti/backoff"
version = "1.1.0"
[[constraint]]
name = "github.com/golang/mock"
version = "1.0.0"
[[constraint]]
name = "github.com/google/gops"
version = "0.3.2"
[[constraint]]
branch = "master"
name = "golang.org/x/net"
[[constraint]]
branch = "v2"
name = "gopkg.in/yaml.v2"
[[constraint]]
branch = "master"
name = "github.com/felixge/tcpkeepalive"

661
vendor/github.com/mmatczuk/go-http-tunnel/LICENSE generated vendored Normal file
View file

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.

92
vendor/github.com/mmatczuk/go-http-tunnel/Makefile generated vendored Normal file
View file

@ -0,0 +1,92 @@
all: clean check test
.PHONY: clean
clean:
@go clean -r
.PHONY: fmt
fmt:
@go fmt ./...
.PHONY: check
check: .check-fmt .check-vet .check-lint .check-ineffassign .check-mega .check-misspell .check-vendor
.PHONY: .check-fmt
.check-fmt:
@go fmt ./... | tee /dev/stderr | ifne false
.PHONY: .check-vet
.check-vet:
@go vet ./...
.PHONY: .check-lint
.check-lint:
@golint `go list ./...` \
| grep -v /id/ \
| grep -v /tunnelmock/ \
| tee /dev/stderr | ifne false
.PHONY: .check-ineffassign
.check-ineffassign:
@ineffassign ./
.PHONY: .check-misspell
.check-misspell:
@misspell ./...
.PHONY: .check-mega
.check-mega:
@megacheck ./...
.PHONY: .check-vendor
.check-vendor:
@dep ensure -no-vendor -dry-run
.PHONY: test
test:
@echo "==> Running tests (race)..."
@go test -cover -race ./...
.PHONY: get-deps
get-deps:
@echo "==> Installing dependencies..."
@dep ensure
.PHONY: get-tools
get-tools:
@echo "==> Installing tools..."
@go get -u github.com/golang/dep/cmd/dep
@go get -u github.com/golang/lint/golint
@go get -u github.com/golang/mock/gomock
@go get -u github.com/client9/misspell/cmd/misspell
@go get -u github.com/gordonklaus/ineffassign
@go get -u github.com/mitchellh/gox
@go get -u github.com/tcnksm/ghr
@go get -u honnef.co/go/tools/cmd/megacheck
#OUTPUT_DIR = build
#OS = "darwin freebsd linux windows"
#ARCH = "386 amd64 arm"
#OSARCH = "!darwin/386 !darwin/arm !windows/arm"
#GIT_COMMIT = $(shell git describe --always)
#
#.PHONY: release
#release: check test clean build package
#
#.PHONY: build
#build:
# mkdir ${OUTPUT_DIR}
# CGO_ENABLED=0 GOARM=5 gox -ldflags "-w -X main.version=$(GIT_COMMIT)" \
# -os=${OS} -arch=${ARCH} -osarch=${OSARCH} -output "${OUTPUT_DIR}/pkg/{{.OS}}_{{.Arch}}/{{.Dir}}" \
# ./cmd/tunnel ./cmd/tunneld
#
#.PHONY: package
#package:
# mkdir ${OUTPUT_DIR}/dist
# cd ${OUTPUT_DIR}/pkg/; for osarch in *; do (cd $$osarch; tar zcvf ../../dist/tunnel_$$osarch.tar.gz ./*); done;
# cd ${OUTPUT_DIR}/dist; sha256sum * > ./SHA256SUMS
#
#.PHONY: publish
#publish:
# ghr -recreate -u mmatczuk -t ${GITHUB_TOKEN} -r go-http-tunnel pre-release ${OUTPUT_DIR}/dist

130
vendor/github.com/mmatczuk/go-http-tunnel/README.md generated vendored Normal file
View file

@ -0,0 +1,130 @@
# Go HTTP tunnel [![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg)](http://godoc.org/github.com/mmatczuk/go-http-tunnel) [![Go Report Card](https://goreportcard.com/badge/github.com/mmatczuk/go-http-tunnel)](https://goreportcard.com/report/github.com/mmatczuk/go-http-tunnel) [![Build Status](http://img.shields.io/travis/mmatczuk/go-http-tunnel.svg?branch=master)](https://travis-ci.org/mmatczuk/go-http-tunnel) [![Github All Releases](https://img.shields.io/github/downloads/mmatczuk/go-http-tunnel/total.svg)](https://github.com/mmatczuk/go-http-tunnel/releases)
Go HTTP tunnel is a reverse tunnel based on HTTP/2. It enables you to share your localhost when you don't have a public IP.
Features:
* HTTP proxy with [basic authentication](https://en.wikipedia.org/wiki/Basic_access_authentication)
* TCP proxy
* Client auto reconnect
* Client management and eviction
* Easy to use CLI
Common use cases:
* Hosting a game server from home
* Developing webhook integrations
* Managing IoT devices
## Installation
Build the latest version.
```bash
$ go get -u github.com/mmatczuk/go-http-tunnel/cmd/...
```
Alternatively [download the latest release](https://github.com/mmatczuk/go-http-tunnel/releases/latest).
## Running
There are two executables:
* `tunneld` - the tunnel server, to be run on publicly available host like AWS or GCE
* `tunnel` - the tunnel client, to be run on your local machine or in your private network
To get help on the command parameters run `tunneld -h` or `tunnel -h`.
Tunnel requires TLS certificates for both client and server.
```bash
$ openssl req -x509 -nodes -newkey rsa:2048 -sha256 -keyout client.key -out client.crt
$ openssl req -x509 -nodes -newkey rsa:2048 -sha256 -keyout server.key -out server.crt
```
Run client:
* Install `tunnel` binary
* Make `.tunnel` directory in your project directory
* Copy `client.key`, `client.crt` to `.tunnel`
* Create configuration file `tunnel.yml` in `.tunnel`
* Start all tunnels
```bash
$ tunnel -config ./tunnel/tunnel.yml start-all
```
Run server:
* Install `tunneld` binary
* Make `.tunneld` directory
* Copy `server.key`, `server.crt` to `.tunneld`
* Start tunnel server
```bash
$ tunneld -tlsCrt .tunneld/server.crt -tlsKey .tunneld/server.key
```
This will run HTTP server on port `80` and HTTPS (HTTP/2) server on port `443`. If you want to use HTTPS it's recommended to get a properly signed certificate to avoid security warnings.
## Configuration
The tunnel client `tunnel` requires configuration file, by default it will try reading `tunnel.yml` in your current working directory. If you want to specify other file use `-config` flag.
Sample configuration that exposes:
* `localhost:8080` as `webui.my-tunnel-host.com`
* host in private network for ssh connections
looks like this
```yaml
server_addr: SERVER_IP:5223
tunnels:
webui:
proto: http
addr: localhost:8080
auth: user:password
host: webui.my-tunnel-host.com
ssh:
proto: tcp
addr: 192.168.0.5:22
remote_addr: 0.0.0.0:22
```
Configuration options:
* `server_addr`: server TCP address, i.e. `54.12.12.45:5223`
* `tls_crt`: path to client TLS certificate, *default:* `client.crt` *in the config file directory*
* `tls_key`: path to client TLS certificate key, *default:* `client.key` *in the config file directory*
* `root_ca`: path to trusted root certificate authority pool file, if empty any server certificate is accepted
* `tunnels / [name]`
* `proto`: tunnel protocol, `http` or `tcp`
* `addr`: forward traffic to this local port number or network address, for `proto=http` this can be full URL i.e. `https://machine/sub/path/?plus=params`, supports URL schemes `http` and `https`
* `auth`: (`proto=http`) (optional) basic authentication credentials to enforce on tunneled requests, format `user:password`
* `host`: (`proto=http`) hostname to request (requires reserved name and DNS CNAME)
* `remote_addr`: (`proto=tcp`) bind the remote TCP address
* `backoff`
* `interval`: how long client would wait before redialing the server if connection was lost, exponential backoff initial interval, *default:* `500ms`
* `multiplier`: interval multiplier if reconnect failed, *default:* `1.5`
* `max_interval`: maximal time client would wait before redialing the server, *default:* `1m`
* `max_time`: maximal time client would try to reconnect to the server if connection was lost, set `0` to never stop trying, *default:* `15m`
## How it works
Client opens a TLS connection to a server. Server accepts connections from known clients only, client is recognised by it's TLS certificate ID. The server is publicly available and proxies incoming connections to the client. Then the connection is further proxied in the client's network.
Tunnel is based HTTP/2 for speed and security. There is a single TCP connection between client and server and all the proxied connections are multiplexed using HTTP/2.
## Donation
If this project help you reduce time to develop, you can give me a cup of coffee.
[![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=RMM46NAEY7YZ6&lc=US&item_name=go%2dhttp%2dtunnel&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted)
A GitHub star is always appreciated!
## License
Copyright (C) 2017 Michał Matczuk
This project is distributed under the AGPL-3 license. See the [LICENSE](https://github.com/mmatczuk/go-http-tunnel/blob/master/LICENSE) file for details. If you need an enterprice license contact me directly.

30
vendor/github.com/mmatczuk/go-http-tunnel/auth.go generated vendored Normal file
View file

@ -0,0 +1,30 @@
// Copyright (C) 2017 Michał Matczuk
// Use of this source code is governed by an AGPL-style
// license that can be found in the LICENSE file.
package tunnel
import "strings"
// Auth holds user and password.
type Auth struct {
User string
Password string
}
// NewAuth creates new auth from string representation "user:password".
func NewAuth(auth string) *Auth {
if auth == "" {
return nil
}
s := strings.SplitN(auth, ":", 2)
a := &Auth{
User: s[0],
}
if len(s) > 1 {
a.Password = s[1]
}
return a
}

28
vendor/github.com/mmatczuk/go-http-tunnel/auth_test.go generated vendored Normal file
View file

@ -0,0 +1,28 @@
// Copyright (C) 2017 Michał Matczuk
// Use of this source code is governed by an AGPL-style
// license that can be found in the LICENSE file.
package tunnel
import (
"reflect"
"testing"
)
func TestNewAuth(t *testing.T) {
tests := []struct {
actual string
expected *Auth
}{
{"", nil},
{"user", &Auth{User: "user"}},
{"user:password", &Auth{User: "user", Password: "password"}},
{"user:pass:word", &Auth{User: "user", Password: "pass:word"}},
}
for _, tt := range tests {
if !reflect.DeepEqual(NewAuth(tt.actual), tt.expected) {
t.Errorf("Invalid auth for %s", tt.actual)
}
}
}

19
vendor/github.com/mmatczuk/go-http-tunnel/backoff.go generated vendored Normal file
View file

@ -0,0 +1,19 @@
// Copyright (C) 2017 Michał Matczuk
// Use of this source code is governed by an AGPL-style
// license that can be found in the LICENSE file.
package tunnel
import "time"
// Backoff defines behavior of staggering reconnection retries.
type Backoff interface {
// Next returns the duration to sleep before retrying to reconnect.
// If the returned value is negative, the retry is aborted.
NextBackOff() time.Duration
// Reset is used to signal a reconnection was successful and next
// call to Next should return desired time duration for 1st reconnection
// attempt.
Reset()
}

View file

@ -0,0 +1,50 @@
# Benchmark report
The benchmark compares [tunnel](https://github.com/mmatczuk/go-http-tunnel) to [koding tunnel](https://github.com/koding/tunnel) on serving 184 midsized files that were gathered by saving `amazon.com` for offline view. The data set consists of images and text data (js, css, html). On start client loads the files into memory and act as a file server.
The diagrams were rendered using [hdrhistogram](http://hdrhistogram.github.io/HdrHistogram/plotFiles.html) and the input files were generated with help of [github.com/codahale/hdrhistogram](https://github.com/codahale/hdrhistogram) library. The vegeta raw results were corrected for stalls using [hdr correction method](https://godoc.org/github.com/codahale/hdrhistogram#Histogram.RecordCorrectedValue).
## Environment
Tests were done on four AWS `t2.micro` instances. An instance for client, an instance for server and two instances for load generator. For load generation we used [vegeta](https://github.com/tsenart/vegeta) in distributed mode. On all machines open files limit (`ulimit -n`) was increased to `20000`.
## Load spike
This test compares performance on two minute load spikes. tunnel handles 900 req/sec without dropping a message while preserving good latency. At 1000 req/sec tunnel still works but drops 0,20% requests and latency is much worse. Koding tunnel is faster at 800 req/sec, but at higher request rates latency degrades giving maximum values of 1.65s at 900 req/sec and 23.50s at 1000 req/sec (with 5% error rate).
![](spike.png)
Detailed results of load spike test.
| Impl. | Req/sec | Success rate | P99 (corrected)| Max |
|-------:| -------:|-------------:| --------------:| --------------:|
| tunnel | 600 | 100% | 40.079103ms | 147.310766ms |
| tunnel | 800 | 100% | 161.093631ms | 308.993573ms |
| tunnel | 900 | 100% | 172.114943ms | 376.924512ms |
| tunnel | 1000 | 99.90% | 793.423871ms | 1228.133135ms |
| koding | 600 | 100% | 43.161855ms | 173.871604ms |
| koding | 800 | 100% | 53.311743ms | 180.344454ms |
| koding | 900 | 100% | 1003.495423ms | 1648.814589ms |
| koding | 1000 | 94.95% | 16081.551359ms | 23494.866864ms |
## Constant pressure
This test compares performance on twenty minutes constant pressure runs. tunnel shows ability to trade latency for throughput. It runs fine at 300 req/sec but at higher request rates we observe poor latency and some message drops. Koding tunnel has acceptable performance at 300 req/sec, however, with increased load it just breaks.
Both implementations have a connection (or memory) leak when dealing with too high loads. This results in process (or machine) crash as machine runs out of memory. It's 100% reproducible, when process crashes it has few hundred thousands go routines waiting on select in a connection and memory full of connection buffers.
![](constload.png)
Detailed results of constant pressure test.
| Impl. | Req/sec | Success rate | P99 (corrected)| Max |
|-------:| -------:|-------------:| --------------:| --------------:|
| tunnel | 300 | 100% | 16.614527ms | 199.479958ms |
| tunnel | 400 | 99.98% | 1175.904255 | 1568.012326ms |
| tunnel | 500 | 99.96% | 1457.364991ms | 1917.406792ms |
| koding | 300 | 100% | 66.436607ms | 354.531247ms |
| koding | 400 | 82.66% | - | - |
| koding | 500 | 63.16% | - | - |

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 KiB

326
vendor/github.com/mmatczuk/go-http-tunnel/client.go generated vendored Normal file
View file

@ -0,0 +1,326 @@
// Copyright (C) 2017 Michał Matczuk
// Use of this source code is governed by an AGPL-style
// license that can be found in the LICENSE file.
package tunnel
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"sync"
"time"
"golang.org/x/net/http2"
"github.com/mmatczuk/go-http-tunnel/log"
"github.com/mmatczuk/go-http-tunnel/proto"
)
// ClientConfig is configuration of the Client.
type ClientConfig struct {
// ServerAddr specifies TCP address of the tunnel server.
ServerAddr string
// TLSClientConfig specifies the tls configuration to use with
// tls.Client.
TLSClientConfig *tls.Config
// DialTLS specifies an optional dial function that creates a tls
// connection to the server. If DialTLS is nil, tls.Dial is used.
DialTLS func(network, addr string, config *tls.Config) (net.Conn, error)
// Backoff specifies backoff policy on server connection retry. If nil
// when dial fails it will not be retried.
Backoff Backoff
// Tunnels specifies the tunnels client requests to be opened on server.
Tunnels map[string]*proto.Tunnel
// Proxy is ProxyFunc responsible for transferring data between server
// and local services.
Proxy ProxyFunc
// Logger is optional logger. If nil logging is disabled.
Logger log.Logger
}
// Client is responsible for creating connection to the server, handling control
// messages. It uses ProxyFunc for transferring data between server and local
// services.
type Client struct {
config *ClientConfig
conn net.Conn
connMu sync.Mutex
httpServer *http2.Server
serverErr error
lastDisconnect time.Time
logger log.Logger
}
// NewClient creates a new unconnected Client based on configuration. Caller
// must invoke Start() on returned instance in order to connect server.
func NewClient(config *ClientConfig) (*Client, error) {
if config.ServerAddr == "" {
return nil, errors.New("missing ServerAddr")
}
if config.TLSClientConfig == nil {
return nil, errors.New("missing TLSClientConfig")
}
if len(config.Tunnels) == 0 {
return nil, errors.New("missing Tunnels")
}
if config.Proxy == nil {
return nil, errors.New("missing Proxy")
}
logger := config.Logger
if logger == nil {
logger = log.NewNopLogger()
}
c := &Client{
config: config,
httpServer: &http2.Server{},
logger: logger,
}
return c, nil
}
// Start connects client to the server, it returns error if there is a
// connection error, or server cannot open requested tunnels. On connection
// error a backoff policy is used to reestablish the connection. When connected
// HTTP/2 server is started to handle ControlMessages.
func (c *Client) Start() error {
c.logger.Log(
"level", 1,
"action", "start",
)
for {
conn, err := c.connect()
if err != nil {
return err
}
c.httpServer.ServeConn(conn, &http2.ServeConnOpts{
Handler: http.HandlerFunc(c.serveHTTP),
})
c.logger.Log(
"level", 1,
"action", "disconnected",
)
c.connMu.Lock()
now := time.Now()
err = c.serverErr
// detect disconnect hiccup
if err == nil && now.Sub(c.lastDisconnect).Seconds() < 5 {
err = fmt.Errorf("connection is being cut")
}
c.conn = nil
c.serverErr = nil
c.lastDisconnect = now
c.connMu.Unlock()
if err != nil {
return err
}
}
}
func (c *Client) connect() (net.Conn, error) {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.conn != nil {
return nil, fmt.Errorf("already connected")
}
conn, err := c.dial()
if err != nil {
return nil, fmt.Errorf("failed to connect to server: %s", err)
}
c.conn = conn
return conn, nil
}
func (c *Client) dial() (net.Conn, error) {
var (
network = "tcp"
addr = c.config.ServerAddr
tlsConfig = c.config.TLSClientConfig
)
doDial := func() (conn net.Conn, err error) {
c.logger.Log(
"level", 1,
"action", "dial",
"network", network,
"addr", addr,
)
if c.config.DialTLS != nil {
conn, err = c.config.DialTLS(network, addr, tlsConfig)
} else {
d := &net.Dialer{
Timeout: DefaultTimeout,
}
conn, err = d.Dial(network, addr)
if err == nil {
err = keepAlive(conn)
}
if err == nil {
conn = tls.Client(conn, tlsConfig)
}
if err == nil {
err = conn.(*tls.Conn).Handshake()
}
}
if err != nil {
if conn != nil {
conn.Close()
conn = nil
}
c.logger.Log(
"level", 0,
"msg", "dial failed",
"network", network,
"addr", addr,
"err", err,
)
}
return
}
b := c.config.Backoff
if b == nil {
return doDial()
}
for {
conn, err := doDial()
// success
if err == nil {
b.Reset()
return conn, err
}
// failure
d := b.NextBackOff()
if d < 0 {
return conn, fmt.Errorf("backoff limit exeded: %s", err)
}
// backoff
c.logger.Log(
"level", 1,
"action", "backoff",
"sleep", d,
)
time.Sleep(d)
}
}
func (c *Client) serveHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodConnect {
if r.Header.Get(proto.HeaderError) != "" {
c.handleHandshakeError(w, r)
} else {
c.handleHandshake(w, r)
}
return
}
msg, err := proto.ReadControlMessage(r)
if err != nil {
c.logger.Log(
"level", 1,
"err", err,
)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
c.logger.Log(
"level", 2,
"action", "handle",
"ctrlMsg", msg,
)
switch msg.Action {
case proto.ActionProxy:
c.config.Proxy(w, r.Body, msg)
default:
c.logger.Log(
"level", 0,
"msg", "unknown action",
"ctrlMsg", msg,
)
http.Error(w, err.Error(), http.StatusBadRequest)
}
c.logger.Log(
"level", 2,
"action", "done",
"ctrlMsg", msg,
)
}
func (c *Client) handleHandshakeError(w http.ResponseWriter, r *http.Request) {
err := fmt.Errorf(r.Header.Get(proto.HeaderError))
c.logger.Log(
"level", 1,
"action", "handshake error",
"addr", r.RemoteAddr,
"err", err,
)
c.connMu.Lock()
c.serverErr = fmt.Errorf("server error: %s", err)
c.connMu.Unlock()
}
func (c *Client) handleHandshake(w http.ResponseWriter, r *http.Request) {
c.logger.Log(
"level", 1,
"action", "handshake",
"addr", r.RemoteAddr,
)
w.WriteHeader(http.StatusOK)
b, err := json.Marshal(c.config.Tunnels)
if err != nil {
c.logger.Log(
"level", 0,
"msg", "handshake failed",
"err", err,
)
return
}
w.Write(b)
}
// Stop disconnects client from server.
func (c *Client) Stop() {
c.connMu.Lock()
defer c.connMu.Unlock()
c.logger.Log(
"level", 1,
"action", "stop",
)
if c.conn != nil {
c.conn.Close()
}
c.conn = nil
}

View file

@ -0,0 +1,86 @@
// Copyright (C) 2017 Michał Matczuk
// Use of this source code is governed by an AGPL-style
// license that can be found in the LICENSE file.
package tunnel
import (
"crypto/tls"
"errors"
"net"
"net/http/httptest"
"testing"
"time"
"github.com/golang/mock/gomock"
"github.com/mmatczuk/go-http-tunnel/proto"
"github.com/mmatczuk/go-http-tunnel/tunnelmock"
)
func TestClient_Dial(t *testing.T) {
t.Parallel()
s := httptest.NewTLSServer(nil)
defer s.Close()
c, err := NewClient(&ClientConfig{
ServerAddr: s.Listener.Addr().String(),
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
Tunnels: map[string]*proto.Tunnel{"test": {}},
Proxy: Proxy(ProxyFuncs{}),
})
if err != nil {
t.Fatal(err)
}
conn, err := c.dial()
if err != nil {
t.Fatal("Dial error", err)
}
if conn == nil {
t.Fatal("Expected connection", err)
}
conn.Close()
}
func TestClient_DialBackoff(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
defer ctrl.Finish()
b := tunnelmock.NewMockBackoff(ctrl)
gomock.InOrder(
b.EXPECT().NextBackOff().Return(50*time.Millisecond).Times(2),
b.EXPECT().NextBackOff().Return(-time.Millisecond),
)
d := func(network, addr string, config *tls.Config) (net.Conn, error) {
return nil, errors.New("foobar")
}
c, err := NewClient(&ClientConfig{
ServerAddr: "8.8.8.8",
TLSClientConfig: &tls.Config{},
DialTLS: d,
Backoff: b,
Tunnels: map[string]*proto.Tunnel{"test": {}},
Proxy: Proxy(ProxyFuncs{}),
})
if err != nil {
t.Fatal(err)
}
start := time.Now()
_, err = c.dial()
if time.Since(start) < 100*time.Millisecond {
t.Fatal("Wait mismatch", err)
}
if err.Error() != "backoff limit exeded: foobar" {
t.Fatal("Error mismatch", err)
}
}

View file

@ -0,0 +1,142 @@
// Copyright (C) 2017 Michał Matczuk
// Use of this source code is governed by an AGPL-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"io/ioutil"
"path/filepath"
"time"
"gopkg.in/yaml.v2"
"github.com/mmatczuk/go-http-tunnel/proto"
)
// Default backoff configuration.
const (
DefaultBackoffInterval = 500 * time.Millisecond
DefaultBackoffMultiplier = 1.5
DefaultBackoffMaxInterval = 60 * time.Second
DefaultBackoffMaxTime = 15 * time.Minute
)
// BackoffConfig defines behavior of staggering reconnection retries.
type BackoffConfig struct {
Interval time.Duration `yaml:"interval"`
Multiplier float64 `yaml:"multiplier"`
MaxInterval time.Duration `yaml:"max_interval"`
MaxTime time.Duration `yaml:"max_time"`
}
// Tunnel defines a tunnel.
type Tunnel struct {
Protocol string `yaml:"proto,omitempty"`
Addr string `yaml:"addr,omitempty"`
Auth string `yaml:"auth,omitempty"`
Host string `yaml:"host,omitempty"`
RemoteAddr string `yaml:"remote_addr,omitempty"`
}
// ClientConfig is a tunnel client configuration.
type ClientConfig struct {
ServerAddr string `yaml:"server_addr"`
TLSCrt string `yaml:"tls_crt"`
TLSKey string `yaml:"tls_key"`
RootCA string `yaml:"root_ca"`
Backoff BackoffConfig `yaml:"backoff"`
Tunnels map[string]*Tunnel `yaml:"tunnels"`
}
func loadClientConfigFromFile(file string) (*ClientConfig, error) {
buf, err := ioutil.ReadFile(file)
if err != nil {
return nil, fmt.Errorf("failed to read file %q: %s", file, err)
}
c := ClientConfig{
TLSCrt: filepath.Join(filepath.Dir(file), "client.crt"),
TLSKey: filepath.Join(filepath.Dir(file), "client.key"),
Backoff: BackoffConfig{
Interval: DefaultBackoffInterval,
Multiplier: DefaultBackoffMultiplier,
MaxInterval: DefaultBackoffMaxInterval,
MaxTime: DefaultBackoffMaxTime,
},
}
if err = yaml.Unmarshal(buf, &c); err != nil {
return nil, fmt.Errorf("failed to parse file %q: %s", file, err)
}
if c.ServerAddr == "" {
return nil, fmt.Errorf("server_addr: missing")
}
if c.ServerAddr, err = normalizeAddress(c.ServerAddr); err != nil {
return nil, fmt.Errorf("server_addr: %s", err)
}
for name, t := range c.Tunnels {
switch t.Protocol {
case proto.HTTP:
if err := validateHTTP(t); err != nil {
return nil, fmt.Errorf("%s %s", name, err)
}
case proto.TCP, proto.TCP4, proto.TCP6:
if err := validateTCP(t); err != nil {
return nil, fmt.Errorf("%s %s", name, err)
}
default:
return nil, fmt.Errorf("%s invalid protocol %q", name, t.Protocol)
}
}
return &c, nil
}
func validateHTTP(t *Tunnel) error {
var err error
if t.Host == "" {
return fmt.Errorf("host: missing")
}
if t.Addr == "" {
return fmt.Errorf("addr: missing")
}
if t.Addr, err = normalizeURL(t.Addr); err != nil {
return fmt.Errorf("addr: %s", err)
}
// unexpected
if t.RemoteAddr != "" {
return fmt.Errorf("remote_addr: unexpected")
}
return nil
}
func validateTCP(t *Tunnel) error {
var err error
if t.RemoteAddr, err = normalizeAddress(t.RemoteAddr); err != nil {
return fmt.Errorf("remote_addr: %s", err)
}
if t.Addr == "" {
return fmt.Errorf("addr: missing")
}
if t.Addr, err = normalizeAddress(t.Addr); err != nil {
return fmt.Errorf("addr: %s", err)
}
// unexpected
if t.Host != "" {
return fmt.Errorf("host: unexpected")
}
if t.Auth != "" {
return fmt.Errorf("auth: unexpected")
}
return nil
}

View file

@ -0,0 +1,56 @@
// Copyright (C) 2017 Michał Matczuk
// Use of this source code is governed by an AGPL-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"net"
"net/url"
"strconv"
"strings"
)
func normalizeAddress(addr string) (string, error) {
// normalize port to addr
if _, err := strconv.Atoi(addr); err == nil {
addr = ":" + addr
}
host, port, err := net.SplitHostPort(addr)
if err != nil {
return "", err
}
if host == "" {
host = "127.0.0.1"
}
return fmt.Sprintf("%s:%s", host, port), nil
}
func normalizeURL(rawurl string) (string, error) {
// check scheme
s := strings.SplitN(rawurl, "://", 2)
if len(s) > 1 {
switch s[0] {
case "http", "https":
default:
return "", fmt.Errorf("unsupported url schema, choose 'http' or 'https'")
}
} else {
rawurl = fmt.Sprint("http://", rawurl)
}
u, err := url.Parse(rawurl)
if err != nil {
return "", err
}
if u.Path != "" && !strings.HasSuffix(u.Path, "/") {
return "", fmt.Errorf("url must end with '/'")
}
return rawurl, nil
}

View file

@ -0,0 +1,115 @@
// Copyright (C) 2017 Michał Matczuk
// Use of this source code is governed by an AGPL-style
// license that can be found in the LICENSE file.
package main
import (
"strings"
"testing"
)
func TestNormalizeAddress(t *testing.T) {
t.Parallel()
tests := []struct {
addr string
expected string
error string
}{
{
addr: "22",
expected: "127.0.0.1:22",
},
{
addr: ":22",
expected: "127.0.0.1:22",
},
{
addr: "0.0.0.0:22",
expected: "0.0.0.0:22",
},
{
addr: "0.0.0.0",
error: "missing port",
},
{
addr: "",
error: "missing port",
},
}
for i, tt := range tests {
actual, err := normalizeAddress(tt.addr)
if actual != tt.expected {
t.Errorf("[%d] expected %q got %q err: %s", i, tt.expected, actual, err)
}
if tt.error != "" && err == nil {
t.Errorf("[%d] expected error", i)
}
if err != nil && (tt.error == "" || !strings.Contains(err.Error(), tt.error)) {
t.Errorf("[%d] expected error contains %q, got %q", i, tt.error, err)
}
}
}
func TestNormalizeURL(t *testing.T) {
t.Parallel()
tests := []struct {
rawurl string
expected string
error string
}{
{
rawurl: "localhost",
expected: "http://localhost",
},
{
rawurl: "localhost:80",
expected: "http://localhost:80",
},
{
rawurl: "localhost:80/path/",
expected: "http://localhost:80/path/",
},
{
rawurl: "localhost:80/path",
error: "/",
},
{
rawurl: "https://localhost",
expected: "https://localhost",
},
{
rawurl: "https://localhost:443",
expected: "https://localhost:443",
},
{
rawurl: "https://localhost:443/path/",
expected: "https://localhost:443/path/",
},
{
rawurl: "https://localhost:443/path",
error: "/",
},
{
rawurl: "ftp://localhost",
error: "unsupported url schema",
},
}
for i, tt := range tests {
actual, err := normalizeURL(tt.rawurl)
if actual != tt.expected {
t.Errorf("[%d] expected %q got %q, err: %s", i, tt.expected, actual, err)
}
if tt.error != "" && err == nil {
t.Errorf("[%d] expected error", i)
}
if err != nil && (tt.error == "" || !strings.Contains(err.Error(), tt.error)) {
t.Errorf("[%d] expected error contains %q, got %q", i, tt.error, err)
}
}
}

View file

@ -0,0 +1,106 @@
// Copyright (C) 2017 Michał Matczuk
// Use of this source code is governed by an AGPL-style
// license that can be found in the LICENSE file.
package main
import (
"flag"
"fmt"
"os"
)
const usage1 string = `Usage: tunnel [OPTIONS] <command> [command args] [...]
options:
`
const usage2 string = `
Commands:
tunnel id Show client identifier
tunnel list List tunnel names from config file
tunnel start [tunnel] [...] Start tunnels by name from config file
tunnel start-all Start all tunnels defined in config file
Examples:
tunnel start www ssh
tunnel -config config.yaml -log-level 2 start ssh
tunnel start-all
config.yaml:
server_addr: SERVER_IP:5223
tunnels:
webui:
proto: http
addr: localhost:8080
auth: user:password
host: webui.my-tunnel-host.com
ssh:
proto: tcp
addr: 192.168.0.5:22
remote_addr: 0.0.0.0:22
Author:
Written by M. Matczuk (mmatczuk@gmail.com)
Bugs:
Submit bugs to https://github.com/mmatczuk/go-http-tunnel/issues
`
func init() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, usage1)
flag.PrintDefaults()
fmt.Fprintf(os.Stderr, usage2)
}
}
type options struct {
config string
logLevel int
version bool
command string
args []string
}
func parseArgs() (*options, error) {
config := flag.String("config", "tunnel.yml", "Path to tunnel configuration file")
logLevel := flag.Int("log-level", 1, "Level of messages to log, 0-3")
version := flag.Bool("version", false, "Prints tunnel version")
flag.Parse()
opts := &options{
config: *config,
logLevel: *logLevel,
version: *version,
command: flag.Arg(0),
}
if opts.version {
return opts, nil
}
switch opts.command {
case "":
flag.Usage()
os.Exit(2)
case "id", "list":
opts.args = flag.Args()[1:]
if len(opts.args) > 0 {
return nil, fmt.Errorf("list takes no arguments")
}
case "start":
opts.args = flag.Args()[1:]
if len(opts.args) == 0 {
return nil, fmt.Errorf("you must specify at least one tunnel to start")
}
case "start-all":
opts.args = flag.Args()[1:]
if len(opts.args) > 0 {
return nil, fmt.Errorf("start-all takes no arguments")
}
default:
return nil, fmt.Errorf("unknown command %q", opts.command)
}
return opts, nil
}

View file

@ -0,0 +1,198 @@
// Copyright (C) 2017 Michał Matczuk
// Use of this source code is governed by an AGPL-style
// license that can be found in the LICENSE file.
package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net"
"net/url"
"os"
"sort"
"gopkg.in/yaml.v2"
"github.com/cenkalti/backoff"
"github.com/mmatczuk/go-http-tunnel"
"github.com/mmatczuk/go-http-tunnel/id"
"github.com/mmatczuk/go-http-tunnel/log"
"github.com/mmatczuk/go-http-tunnel/proto"
)
func main() {
opts, err := parseArgs()
if err != nil {
fatal(err.Error())
}
if opts.version {
fmt.Println(version)
return
}
logger := log.NewFilterLogger(log.NewStdLogger(), opts.logLevel)
// read configuration file
config, err := loadClientConfigFromFile(opts.config)
if err != nil {
fatal("configuration error: %s", err)
}
switch opts.command {
case "id":
cert, err := tls.LoadX509KeyPair(config.TLSCrt, config.TLSKey)
if err != nil {
fatal("failed to load key pair: %s", err)
}
x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
if err != nil {
fatal("failed to parse certificate: %s", err)
}
fmt.Println(id.New(x509Cert.Raw))
return
case "list":
var names []string
for n := range config.Tunnels {
names = append(names, n)
}
sort.Strings(names)
for _, n := range names {
fmt.Println(n)
}
return
case "start":
tunnels := make(map[string]*Tunnel)
for _, arg := range opts.args {
t, ok := config.Tunnels[arg]
if !ok {
fatal("no such tunnel %q", arg)
}
tunnels[arg] = t
}
config.Tunnels = tunnels
}
if len(config.Tunnels) == 0 {
fatal("no tunnels")
}
tlsconf, err := tlsConfig(config)
if err != nil {
fatal("failed to configure tls: %s", err)
}
b, err := yaml.Marshal(config)
if err != nil {
fatal("failed to dump config: %s", err)
}
logger.Log("config", string(b))
client, err := tunnel.NewClient(&tunnel.ClientConfig{
ServerAddr: config.ServerAddr,
TLSClientConfig: tlsconf,
Backoff: expBackoff(config.Backoff),
Tunnels: tunnels(config.Tunnels),
Proxy: proxy(config.Tunnels, logger),
Logger: logger,
})
if err != nil {
fatal("failed to create client: %s", err)
}
if err := client.Start(); err != nil {
fatal("failed to start tunnels: %s", err)
}
}
func tlsConfig(config *ClientConfig) (*tls.Config, error) {
cert, err := tls.LoadX509KeyPair(config.TLSCrt, config.TLSKey)
if err != nil {
return nil, err
}
var roots *x509.CertPool
if config.RootCA != "" {
roots = x509.NewCertPool()
rootPEM, err := ioutil.ReadFile(config.RootCA)
if err != nil {
return nil, err
}
if ok := roots.AppendCertsFromPEM(rootPEM); !ok {
return nil, err
}
}
host, _, err := net.SplitHostPort(config.ServerAddr)
if err != nil {
return nil, err
}
return &tls.Config{
ServerName: host,
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: roots == nil,
RootCAs: roots,
}, nil
}
func expBackoff(c BackoffConfig) *backoff.ExponentialBackOff {
b := backoff.NewExponentialBackOff()
b.InitialInterval = c.Interval
b.Multiplier = c.Multiplier
b.MaxInterval = c.MaxInterval
b.MaxElapsedTime = c.MaxTime
return b
}
func tunnels(m map[string]*Tunnel) map[string]*proto.Tunnel {
p := make(map[string]*proto.Tunnel)
for name, t := range m {
p[name] = &proto.Tunnel{
Protocol: t.Protocol,
Host: t.Host,
Auth: t.Auth,
Addr: t.RemoteAddr,
}
}
return p
}
func proxy(m map[string]*Tunnel, logger log.Logger) tunnel.ProxyFunc {
httpURL := make(map[string]*url.URL)
tcpAddr := make(map[string]string)
for _, t := range m {
switch t.Protocol {
case proto.HTTP:
u, err := url.Parse(t.Addr)
if err != nil {
fatal("invalid tunnel address: %s", err)
}
httpURL[t.Host] = u
case proto.TCP, proto.TCP4, proto.TCP6:
tcpAddr[t.RemoteAddr] = t.Addr
}
}
return tunnel.Proxy(tunnel.ProxyFuncs{
HTTP: tunnel.NewMultiHTTPProxy(httpURL, log.NewContext(logger).WithPrefix("proxy", "HTTP")).Proxy,
TCP: tunnel.NewMultiTCPProxy(tcpAddr, log.NewContext(logger).WithPrefix("proxy", "TCP")).Proxy,
})
}
func fatal(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, format, a...)
fmt.Fprint(os.Stderr, "\n")
os.Exit(1)
}

View file

@ -0,0 +1,7 @@
// Copyright (C) 2017 Michał Matczuk
// Use of this source code is governed by an AGPL-style
// license that can be found in the LICENSE file.
package main
var version = "snapshot"

View file

@ -0,0 +1,14 @@
// Copyright (C) 2017 Michał Matczuk
// Use of this source code is governed by an AGPL-style
// license that can be found in the LICENSE file.
package main
const banner = `
______ __ __________________ __ __
/ ____/___ / / / /_ __/_ __/ __ \ / /___ ______ ____ ___ / /
/ / __/ __ \ / /_/ / / / / / / /_/ / / __/ / / / __ \/ __ \/ _ \/ /
/ /_/ / /_/ / / __ / / / / / / ____/ / /_/ /_/ / / / / / / / __/ /
\____/\____/ /_/ /_/ /_/ /_/ /_/ \__/\__,_/_/ /_/_/ /_/\___/_/
github.com/mmatczuk/go-http-tunnel
`

Some files were not shown because too many files have changed in this diff Show more