1
0
mirror of https://github.com/rancher/norman.git synced 2025-09-11 12:13:19 +00:00

Vendor changes

This commit is contained in:
Dan Ramich
2019-04-03 10:28:08 -07:00
parent 67bb53a805
commit be2ec71987
57 changed files with 22141 additions and 10215 deletions

25
vendor/github.com/matryer/moq/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,25 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof
.vscode

19
vendor/github.com/matryer/moq/.travis.yml generated vendored Normal file
View File

@@ -0,0 +1,19 @@
language: go
sudo: false
go:
- 1.9.x
- 1.10.x
- 1.11.x
- tip
before_install:
- go get golang.org/x/lint/golint
before_script:
- go vet ./...
- golint ./...
script:
- go test -v ./...

21
vendor/github.com/matryer/moq/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2016 Mat Ryer and David Hernandez
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

108
vendor/github.com/matryer/moq/README.md generated vendored Normal file
View File

@@ -0,0 +1,108 @@
![moq logo](moq-logo-small.png) [![Build Status](https://travis-ci.org/matryer/moq.svg?branch=master)](https://travis-ci.org/matryer/moq) [![Go Report Card](https://goreportcard.com/badge/github.com/matryer/moq)](https://goreportcard.com/report/github.com/matryer/moq)
Interface mocking tool for go generate.
By [Mat Ryer](https://twitter.com/matryer) and [David Hernandez](https://github.com/dahernan), with ideas lovingly stolen from [Ernesto Jimenez](https://github.com/ernesto-jimenez).
### What is Moq?
Moq is a tool that generates a struct from any interface. The struct can be used in test code as a mock of the interface.
![Preview](preview.png)
above: Moq generates the code on the right.
You can read more in the [Meet Moq blog post](http://bit.ly/meetmoq).
### Installing
To start using Moq, just run go get:
```
$ go get github.com/matryer/moq
```
### Usage
```
moq [flags] destination interface [interface2 [interface3 [...]]]
-out string
output file (default stdout)
-pkg string
package name (default will infer)
```
In a command line:
```
$ moq -out mocks_test.go . MyInterface
```
In code (for go generate):
```go
package my
//go:generate moq -out myinterface_moq_test.go . MyInterface
type MyInterface interface {
Method1() error
Method2(i int)
}
```
Then run `go generate` for your package.
### How to use it
Mocking interfaces is a nice way to write unit tests where you can easily control the behaviour of the mocked object.
Moq creates a struct that has a function field for each method, which you can declare in your test code.
This this example, Moq generated the `EmailSenderMock` type:
```go
func TestCompleteSignup(t *testing.T) {
var sentTo string
mockedEmailSender = &EmailSenderMock{
SendFunc: func(to, subject, body string) error {
sentTo = to
return nil
},
}
CompleteSignUp("me@email.com", mockedEmailSender)
callsToSend := len(mockedEmailSender.SendCalls())
if callsToSend != 1 {
t.Errorf("Send was called %d times", callsToSend)
}
if sentTo != "me@email.com" {
t.Errorf("unexpected recipient: %s", sentTo)
}
}
func CompleteSignUp(to string, sender EmailSender) {
// TODO: this
}
```
The mocked structure implements the interface, where each method calls the associated function field.
## Tips
* Keep mocked logic inside the test that is using it
* Only mock the fields you need
* It will panic if a nil function gets called
* Name arguments in the interface for a better experience
* Use closured variables inside your test function to capture details about the calls to the methods
* Use `.MethodCalls()` to track the calls
* Use `go:generate` to invoke the `moq` command
## License
The Moq project (and all code) is licensed under the [MIT License](LICENSE).
The Moq logo was created by [Chris Ryer](http://chrisryer.co.uk) and is licensed under the [Creative Commons Attribution 3.0 License](https://creativecommons.org/licenses/by/3.0/).

BIN
vendor/github.com/matryer/moq/moq-logo-small.png generated vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

BIN
vendor/github.com/matryer/moq/moq-logo.png generated vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

379
vendor/github.com/matryer/moq/pkg/moq/moq.go generated vendored Normal file
View File

@@ -0,0 +1,379 @@
package moq
import (
"bytes"
"errors"
"fmt"
"go/format"
"go/types"
"io"
"os"
"path"
"path/filepath"
"strings"
"text/template"
"golang.org/x/tools/go/packages"
)
// This list comes from the golint codebase. Golint will complain about any of
// these being mixed-case, like "Id" instead of "ID".
var golintInitialisms = []string{
"ACL",
"API",
"ASCII",
"CPU",
"CSS",
"DNS",
"EOF",
"GUID",
"HTML",
"HTTP",
"HTTPS",
"ID",
"IP",
"JSON",
"LHS",
"QPS",
"RAM",
"RHS",
"RPC",
"SLA",
"SMTP",
"SQL",
"SSH",
"TCP",
"TLS",
"TTL",
"UDP",
"UI",
"UID",
"UUID",
"URI",
"URL",
"UTF8",
"VM",
"XML",
"XMPP",
"XSRF",
"XSS",
}
// Mocker can generate mock structs.
type Mocker struct {
srcPkg *packages.Package
tmpl *template.Template
pkgName string
pkgPath string
// importByPath of the format key:path value:alias
importByPath map[string]string
// importByAlias of the format key:alias value:path
importByAlias map[string]string
}
// New makes a new Mocker for the specified package directory.
func New(src, packageName string) (*Mocker, error) {
srcPkg, err := pkgInfoFromPath(src, packages.LoadSyntax)
if err != nil {
return nil, fmt.Errorf("Couldn't load source package: %s", err)
}
pkgPath := srcPkg.PkgPath
if len(packageName) == 0 {
packageName = srcPkg.Name
} else {
mockPkgPath := filepath.Join(src, packageName)
if _, err := os.Stat(mockPkgPath); os.IsNotExist(err) {
os.Mkdir(mockPkgPath, os.ModePerm)
}
mockPkg, err := pkgInfoFromPath(mockPkgPath, packages.LoadFiles)
if err != nil {
return nil, fmt.Errorf("Couldn't load mock package: %s", err)
}
pkgPath = mockPkg.PkgPath
}
tmpl, err := template.New("moq").Funcs(templateFuncs).Parse(moqTemplate)
if err != nil {
return nil, err
}
return &Mocker{
tmpl: tmpl,
srcPkg: srcPkg,
pkgName: packageName,
pkgPath: pkgPath,
importByPath: make(map[string]string),
importByAlias: make(map[string]string),
}, nil
}
// Mock generates a mock for the specified interface name.
func (m *Mocker) Mock(w io.Writer, name ...string) error {
if len(name) == 0 {
return errors.New("must specify one interface")
}
doc := doc{
PackageName: m.pkgName,
Imports: moqImports,
}
// Add sync first to ensure it doesn't get an alias which will break the template
m.addSyncImport()
var syncNeeded bool
tpkg := m.srcPkg.Types
for _, n := range name {
iface := tpkg.Scope().Lookup(n)
if iface == nil {
return fmt.Errorf("cannot find interface %s", n)
}
if !types.IsInterface(iface.Type()) {
return fmt.Errorf("%s (%s) not an interface", n, iface.Type().String())
}
iiface := iface.Type().Underlying().(*types.Interface).Complete()
obj := obj{
InterfaceName: n,
}
for i := 0; i < iiface.NumMethods(); i++ {
syncNeeded = true
meth := iiface.Method(i)
sig := meth.Type().(*types.Signature)
method := &method{
Name: meth.Name(),
}
obj.Methods = append(obj.Methods, method)
method.Params = m.extractArgs(sig, sig.Params(), "in%d")
method.Returns = m.extractArgs(sig, sig.Results(), "out%d")
}
doc.Objects = append(doc.Objects, obj)
}
if !syncNeeded {
delete(m.importByAlias, "sync")
delete(m.importByPath, "sync")
}
if tpkg.Name() != m.pkgName {
if _, ok := m.importByPath[tpkg.Path()]; !ok {
alias := m.getUniqueAlias(tpkg.Name())
m.importByAlias[alias] = tpkg.Path()
m.importByPath[tpkg.Path()] = alias
}
doc.SourcePackagePrefix = m.importByPath[tpkg.Path()] + "."
}
for alias, path := range m.importByAlias {
aliasImport := fmt.Sprintf(`%s "%s"`, alias, stripVendorPath(path))
doc.Imports = append(doc.Imports, aliasImport)
}
var buf bytes.Buffer
err := m.tmpl.Execute(&buf, doc)
if err != nil {
return err
}
formatted, err := format.Source(buf.Bytes())
if err != nil {
return fmt.Errorf("go/format: %s", err)
}
if _, err := w.Write(formatted); err != nil {
return err
}
return nil
}
func (m *Mocker) addSyncImport() {
if _, ok := m.importByPath["sync"]; !ok {
m.importByAlias["sync"] = "sync"
m.importByPath["sync"] = "sync"
}
}
func (m *Mocker) packageQualifier(pkg *types.Package) string {
if m.pkgPath == pkg.Path() {
return ""
}
path := pkg.Path()
if pkg.Path() == "." {
wd, err := os.Getwd()
if err == nil {
path = stripGopath(wd)
}
}
if alias, ok := m.importByPath[path]; ok {
return alias
}
alias := pkg.Name()
if _, ok := m.importByAlias[alias]; ok {
alias = m.getUniqueAlias(alias)
}
m.importByAlias[alias] = path
m.importByPath[path] = alias
return alias
}
func (m *Mocker) getUniqueAlias(alias string) string {
for i := 0; ; i++ {
newAlias := alias + string('a'+byte(i))
if _, exists := m.importByAlias[newAlias]; !exists {
return newAlias
}
}
}
func (m *Mocker) extractArgs(sig *types.Signature, list *types.Tuple, nameFormat string) []*param {
var params []*param
listLen := list.Len()
for ii := 0; ii < listLen; ii++ {
p := list.At(ii)
name := p.Name()
if name == "" {
name = fmt.Sprintf(nameFormat, ii+1)
}
typename := types.TypeString(p.Type(), m.packageQualifier)
// check for final variadic argument
variadic := sig.Variadic() && ii == listLen-1 && typename[0:2] == "[]"
param := &param{
Name: name,
Type: typename,
Variadic: variadic,
}
params = append(params, param)
}
return params
}
func pkgInfoFromPath(src string, mode packages.LoadMode) (*packages.Package, error) {
conf := packages.Config{
Mode: mode,
Dir: src,
}
pkgs, err := packages.Load(&conf)
if err != nil {
return nil, err
}
if len(pkgs) == 0 {
return nil, errors.New("No packages found")
}
if len(pkgs) > 1 {
return nil, errors.New("More than one package was found")
}
return pkgs[0], nil
}
type doc struct {
PackageName string
SourcePackagePrefix string
Objects []obj
Imports []string
}
type obj struct {
InterfaceName string
Methods []*method
}
type method struct {
Name string
Params []*param
Returns []*param
}
func (m *method) Arglist() string {
params := make([]string, len(m.Params))
for i, p := range m.Params {
params[i] = p.String()
}
return strings.Join(params, ", ")
}
func (m *method) ArgCallList() string {
params := make([]string, len(m.Params))
for i, p := range m.Params {
params[i] = p.CallName()
}
return strings.Join(params, ", ")
}
func (m *method) ReturnArglist() string {
params := make([]string, len(m.Returns))
for i, p := range m.Returns {
params[i] = p.TypeString()
}
if len(m.Returns) > 1 {
return fmt.Sprintf("(%s)", strings.Join(params, ", "))
}
return strings.Join(params, ", ")
}
type param struct {
Name string
Type string
Variadic bool
}
func (p param) String() string {
return fmt.Sprintf("%s %s", p.Name, p.TypeString())
}
func (p param) CallName() string {
if p.Variadic {
return p.Name + "..."
}
return p.Name
}
func (p param) TypeString() string {
if p.Variadic {
return "..." + p.Type[2:]
}
return p.Type
}
var templateFuncs = template.FuncMap{
"Exported": func(s string) string {
if s == "" {
return ""
}
for _, initialism := range golintInitialisms {
if strings.ToUpper(s) == initialism {
return initialism
}
}
return strings.ToUpper(s[0:1]) + s[1:]
},
}
// stripVendorPath strips the vendor dir prefix from a package path.
// For example we might encounter an absolute path like
// github.com/foo/bar/vendor/github.com/pkg/errors which is resolved
// to github.com/pkg/errors.
func stripVendorPath(p string) string {
parts := strings.Split(p, "/vendor/")
if len(parts) == 1 {
return p
}
return strings.TrimLeft(path.Join(parts[1:]...), "/")
}
// stripGopath takes the directory to a package and remove the gopath to get the
// canonical package name.
//
// taken from https://github.com/ernesto-jimenez/gogen
// Copyright (c) 2015 Ernesto Jiménez
func stripGopath(p string) string {
for _, gopath := range gopaths() {
p = strings.TrimPrefix(p, path.Join(gopath, "src")+"/")
}
return p
}
func gopaths() []string {
return strings.Split(os.Getenv("GOPATH"), string(filepath.ListSeparator))
}

107
vendor/github.com/matryer/moq/pkg/moq/template.go generated vendored Normal file
View File

@@ -0,0 +1,107 @@
package moq
// moqImports are the imports all moq files get.
var moqImports = []string{}
// moqTemplate is the template for mocked code.
var moqTemplate = `// Code generated by moq; DO NOT EDIT.
// github.com/matryer/moq
package {{.PackageName}}
{{- $sourcePackagePrefix := .SourcePackagePrefix}}
import (
{{- range .Imports }}
{{.}}
{{- end }}
)
{{ range $i, $obj := .Objects -}}
var (
{{- range .Methods }}
lock{{$obj.InterfaceName}}Mock{{.Name}} sync.RWMutex
{{- end }}
)
// Ensure, that {{.InterfaceName}}Mock does implement {{.InterfaceName}}.
// If this is not the case, regenerate this file with moq.
var _ {{$sourcePackagePrefix}}{{.InterfaceName}} = &{{.InterfaceName}}Mock{}
// {{.InterfaceName}}Mock is a mock implementation of {{.InterfaceName}}.
//
// func TestSomethingThatUses{{.InterfaceName}}(t *testing.T) {
//
// // make and configure a mocked {{.InterfaceName}}
// mocked{{.InterfaceName}} := &{{.InterfaceName}}Mock{ {{ range .Methods }}
// {{.Name}}Func: func({{ .Arglist }}) {{.ReturnArglist}} {
// panic("mock out the {{.Name}} method")
// },{{- end }}
// }
//
// // use mocked{{.InterfaceName}} in code that requires {{.InterfaceName}}
// // and then make assertions.
//
// }
type {{.InterfaceName}}Mock struct {
{{- range .Methods }}
// {{.Name}}Func mocks the {{.Name}} method.
{{.Name}}Func func({{ .Arglist }}) {{.ReturnArglist}}
{{ end }}
// calls tracks calls to the methods.
calls struct {
{{- range .Methods }}
// {{ .Name }} holds details about calls to the {{.Name}} method.
{{ .Name }} []struct {
{{- range .Params }}
// {{ .Name | Exported }} is the {{ .Name }} argument value.
{{ .Name | Exported }} {{ .Type }}
{{- end }}
}
{{- end }}
}
}
{{ range .Methods }}
// {{.Name}} calls {{.Name}}Func.
func (mock *{{$obj.InterfaceName}}Mock) {{.Name}}({{.Arglist}}) {{.ReturnArglist}} {
if mock.{{.Name}}Func == nil {
panic("{{$obj.InterfaceName}}Mock.{{.Name}}Func: method is nil but {{$obj.InterfaceName}}.{{.Name}} was just called")
}
callInfo := struct {
{{- range .Params }}
{{ .Name | Exported }} {{ .Type }}
{{- end }}
}{
{{- range .Params }}
{{ .Name | Exported }}: {{ .Name }},
{{- end }}
}
lock{{$obj.InterfaceName}}Mock{{.Name}}.Lock()
mock.calls.{{.Name}} = append(mock.calls.{{.Name}}, callInfo)
lock{{$obj.InterfaceName}}Mock{{.Name}}.Unlock()
{{- if .ReturnArglist }}
return mock.{{.Name}}Func({{.ArgCallList}})
{{- else }}
mock.{{.Name}}Func({{.ArgCallList}})
{{- end }}
}
// {{.Name}}Calls gets all the calls that were made to {{.Name}}.
// Check the length with:
// len(mocked{{$obj.InterfaceName}}.{{.Name}}Calls())
func (mock *{{$obj.InterfaceName}}Mock) {{.Name}}Calls() []struct {
{{- range .Params }}
{{ .Name | Exported }} {{ .Type }}
{{- end }}
} {
var calls []struct {
{{- range .Params }}
{{ .Name | Exported }} {{ .Type }}
{{- end }}
}
lock{{$obj.InterfaceName}}Mock{{.Name}}.RLock()
calls = mock.calls.{{.Name}}
lock{{$obj.InterfaceName}}Mock{{.Name}}.RUnlock()
return calls
}
{{ end -}}
{{ end -}}`

BIN
vendor/github.com/matryer/moq/preview.png generated vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 726 KiB