diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1fed404e..054675ae 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -94,8 +94,8 @@ tests: ## Updating 3rd party packages -0. Update `Nut.toml`. -0. Run `script/vendor` to update the code in the `.vendor/src` directory. +0. Update `glide.yaml`. +0. Run `script/vendor` to update the code in the `vendor` directory. 0. Commit the change. Git LFS vendors the full source code in the repository. 0. Submit a pull request. diff --git a/Nut.toml b/Nut.toml deleted file mode 100644 index 7f8608ad..00000000 --- a/Nut.toml +++ /dev/null @@ -1,24 +0,0 @@ -[application] - -name = "git-lfs" -version = "1.2.0" -authors = [ - "Rick Olson ", - "Scott Barron ", -] - -[dependencies] - -"github.com/bgentry/go-netrc/netrc" = "9fd32a8b3d3d3f9d43c341bfe098430e07609480" -"github.com/cheggaaa/pb" = "bd14546a551971ae7f460e6d6e527c5b56cd38d7" -"github.com/kr/pretty" = "088c856450c08c03eb32f7a6c221e6eefaa10e6f" -"github.com/kr/pty" = "5cf931ef8f76dccd0910001d74a58a7fca84a83d" -"github.com/kr/text" = "6807e777504f54ad073ecef66747de158294b639" -"github.com/inconshreveable/mousetrap" = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75" -"github.com/olekukonko/ts" = "ecf753e7c962639ab5a1fb46f7da627d4c0a04b8" -"github.com/rubyist/tracerx" = "d7bcc0bc315bed2a841841bee5dbecc8d7d7582f" -"github.com/spf13/cobra" = "c55cdf33856a08e4822738728b41783292812889" -"github.com/spf13/pflag" = "580b9be06c33d8ba9dcc8757ea56b7642472c2f5" -"github.com/ThomsonReutersEikon/go-ntlm/ntlm" = "52b7efa603f1b809167b528b8bbaa467e36fdc02" -"github.com/technoweenie/assert" = "b25ea301d127043ffacf3b2545726e79b6632139" -"github.com/technoweenie/go-contentaddressable" = "38171def3cd15e3b76eb156219b3d48704643899" diff --git a/api/api.go b/api/api.go index 87f3d23c..676c3c3a 100644 --- a/api/api.go +++ b/api/api.go @@ -14,7 +14,7 @@ import ( "github.com/github/git-lfs/httputil" "github.com/github/git-lfs/tools" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" + "github.com/rubyist/tracerx" ) // BatchOrLegacy calls the Batch API and falls back on the Legacy API diff --git a/api/client.go b/api/client.go index 76d9ecfe..cfc06cc5 100644 --- a/api/client.go +++ b/api/client.go @@ -1,155 +1,75 @@ +// NOTE: Subject to change, do not rely on this package from outside git-lfs source package api -import ( - "net/http" - "net/url" - "path" +import "github.com/github/git-lfs/config" - "github.com/github/git-lfs/auth" - "github.com/github/git-lfs/config" - "github.com/github/git-lfs/errutil" - "github.com/github/git-lfs/httputil" - - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" -) +type Operation string const ( - MediaType = "application/vnd.git-lfs+json; charset=utf-8" + UploadOperation Operation = "upload" + DownloadOperation Operation = "download" ) -// doLegacyApiRequest runs the request to the LFS legacy API. -func DoLegacyRequest(req *http.Request) (*http.Response, *ObjectResource, error) { - via := make([]*http.Request, 0, 4) - res, err := httputil.DoHttpRequestWithRedirects(req, via, true) - if err != nil { - return res, nil, err - } +// Client exposes the LFS API to callers through a multitude of different +// services and transport mechanisms. Callers can make a *RequestSchema using +// any service that is attached to the Client, and then execute a request based +// on that schema using the `Do()` method. +// +// A prototypical example follows: +// ``` +// apiResponse, schema := client.Locks.Lock(request) +// resp, err := client.Do(schema) +// if err != nil { +// handleErr(err) +// } +// +// fmt.Println(apiResponse.Lock) +// ``` +type Client struct { + // Locks is the LockService used to interact with the Git LFS file- + // locking API. + Locks LockService - obj := &ObjectResource{} - err = httputil.DecodeResponse(res, obj) - - if err != nil { - httputil.SetErrorResponseContext(err, res) - return nil, nil, err - } - - return res, obj, nil + // lifecycle is the lifecycle used by all requests through this client. + lifecycle Lifecycle } -// doApiBatchRequest runs the request to the LFS batch API. If the API returns a -// 401, the repo will be marked as having private access and the request will be -// re-run. When the repo is marked as having private access, credentials will -// be retrieved. -func DoBatchRequest(req *http.Request) (*http.Response, []*ObjectResource, error) { - res, err := DoRequest(req, config.Config.PrivateAccess(auth.GetOperationForRequest(req))) - - if err != nil { - if res != nil && res.StatusCode == 401 { - return res, nil, errutil.NewAuthError(err) - } - return res, nil, err +// NewClient instantiates and returns a new instance of *Client, with the given +// lifecycle. +// +// If no lifecycle is given, a HttpLifecycle is used by default. +func NewClient(lifecycle Lifecycle) *Client { + if lifecycle == nil { + lifecycle = NewHttpLifecycle(config.Config) } - var objs map[string][]*ObjectResource - err = httputil.DecodeResponse(res, &objs) - - if err != nil { - httputil.SetErrorResponseContext(err, res) - } - - return res, objs["objects"], err + return &Client{lifecycle: lifecycle} } -// DoRequest runs a request to the LFS API, without parsing the response -// body. If the API returns a 401, the repo will be marked as having private -// access and the request will be re-run. When the repo is marked as having -// private access, credentials will be retrieved. -func DoRequest(req *http.Request, useCreds bool) (*http.Response, error) { - via := make([]*http.Request, 0, 4) - return httputil.DoHttpRequestWithRedirects(req, via, useCreds) -} - -func NewRequest(method, oid string) (*http.Request, error) { - objectOid := oid - operation := "download" - if method == "POST" { - if oid != "batch" { - objectOid = "" - operation = "upload" - } - } - endpoint := config.Config.Endpoint(operation) - - res, err := auth.SshAuthenticate(endpoint, operation, oid) - if err != nil { - tracerx.Printf("ssh: attempted with %s. Error: %s", - endpoint.SshUserAndHost, err.Error(), - ) - return nil, err - } - - if len(res.Href) > 0 { - endpoint.Url = res.Href - } - - u, err := ObjectUrl(endpoint, objectOid) - if err != nil { - return nil, err - } - - req, err := httputil.NewHttpRequest(method, u.String(), res.Header) - if err != nil { - return nil, err - } - - req.Header.Set("Accept", MediaType) - return req, nil -} - -func NewBatchRequest(operation string) (*http.Request, error) { - endpoint := config.Config.Endpoint(operation) - - res, err := auth.SshAuthenticate(endpoint, operation, "") - if err != nil { - tracerx.Printf("ssh: %s attempted with %s. Error: %s", - operation, endpoint.SshUserAndHost, err.Error(), - ) - return nil, err - } - - if len(res.Href) > 0 { - endpoint.Url = res.Href - } - - u, err := ObjectUrl(endpoint, "batch") - if err != nil { - return nil, err - } - - req, err := httputil.NewHttpRequest("POST", u.String(), nil) - if err != nil { - return nil, err - } - - req.Header.Set("Accept", MediaType) - if res.Header != nil { - for key, value := range res.Header { - req.Header.Set(key, value) - } - } - - return req, nil -} - -func ObjectUrl(endpoint config.Endpoint, oid string) (*url.URL, error) { - u, err := url.Parse(endpoint.Url) - if err != nil { - return nil, err - } - - u.Path = path.Join(u.Path, "objects") - if len(oid) > 0 { - u.Path = path.Join(u.Path, oid) - } - return u, nil +// Do preforms the request assosicated with the given *RequestSchema by +// delegating into the Lifecycle in use. +// +// If any error was encountered while either building, executing or cleaning up +// the request, then it will be returned immediately, and the request can be +// treated as invalid. +// +// If no error occured, an api.Response will be returned, along with a `nil` +// error. At this point, the body of the response has been serialized into +// `schema.Into`, and the body has been closed. +func (c *Client) Do(schema *RequestSchema) (Response, error) { + req, err := c.lifecycle.Build(schema) + if err != nil { + return nil, err + } + + resp, err := c.lifecycle.Execute(req, schema.Into) + if err != nil { + return nil, err + } + + if err = c.lifecycle.Cleanup(resp); err != nil { + return nil, err + } + + return resp, nil } diff --git a/api/client_test.go b/api/client_test.go new file mode 100644 index 00000000..d2005dba --- /dev/null +++ b/api/client_test.go @@ -0,0 +1,76 @@ +package api_test + +import ( + "errors" + "net/http" + "testing" + + "github.com/github/git-lfs/api" + "github.com/stretchr/testify/assert" +) + +func TestClientUsesLifecycleToExecuteSchemas(t *testing.T) { + schema := new(api.RequestSchema) + req := new(http.Request) + resp := new(api.HttpResponse) + + lifecycle := new(MockLifecycle) + lifecycle.On("Build", schema).Return(req, nil).Once() + lifecycle.On("Execute", req, schema.Into).Return(resp, nil).Once() + lifecycle.On("Cleanup", resp).Return(nil).Once() + + client := api.NewClient(lifecycle) + r1, err := client.Do(schema) + + assert.Equal(t, resp, r1) + assert.Nil(t, err) + lifecycle.AssertExpectations(t) +} + +func TestClientHaltsIfSchemaCannotBeBuilt(t *testing.T) { + schema := new(api.RequestSchema) + + lifecycle := new(MockLifecycle) + lifecycle.On("Build", schema).Return(nil, errors.New("uh-oh!")).Once() + + client := api.NewClient(lifecycle) + resp, err := client.Do(schema) + + lifecycle.AssertExpectations(t) + assert.Nil(t, resp) + assert.Equal(t, "uh-oh!", err.Error()) +} + +func TestClientHaltsIfSchemaCannotBeExecuted(t *testing.T) { + schema := new(api.RequestSchema) + req := new(http.Request) + + lifecycle := new(MockLifecycle) + lifecycle.On("Build", schema).Return(req, nil).Once() + lifecycle.On("Execute", req, schema.Into).Return(nil, errors.New("uh-oh!")).Once() + + client := api.NewClient(lifecycle) + resp, err := client.Do(schema) + + lifecycle.AssertExpectations(t) + assert.Nil(t, resp) + assert.Equal(t, "uh-oh!", err.Error()) +} + +func TestClientReturnsCleanupErrors(t *testing.T) { + schema := new(api.RequestSchema) + req := new(http.Request) + resp := new(api.HttpResponse) + + lifecycle := new(MockLifecycle) + lifecycle.On("Build", schema).Return(req, nil).Once() + lifecycle.On("Execute", req, schema.Into).Return(resp, nil).Once() + lifecycle.On("Cleanup", resp).Return(errors.New("uh-oh!")).Once() + + client := api.NewClient(lifecycle) + r1, err := client.Do(schema) + + lifecycle.AssertExpectations(t) + assert.Nil(t, r1) + assert.Equal(t, "uh-oh!", err.Error()) +} diff --git a/api/http_lifecycle.go b/api/http_lifecycle.go new file mode 100644 index 00000000..91c212ee --- /dev/null +++ b/api/http_lifecycle.go @@ -0,0 +1,181 @@ +// NOTE: Subject to change, do not rely on this package from outside git-lfs source +package api + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "io/ioutil" + "net/http" + "net/url" + + "github.com/github/git-lfs/auth" + "github.com/github/git-lfs/config" + "github.com/github/git-lfs/httputil" +) + +var ( + // ErrNoOperationGiven is an error which is returned when no operation + // is provided in a RequestSchema object. + ErrNoOperationGiven = errors.New("lfs/api: no operation provided in schema") +) + +// EndpointSource is an interface which encapsulates the behavior of returning +// `config.Endpoint`s based on a particular operation. +type EndpointSource interface { + // Endpoint returns the `config.Endpoint` assosciated with a given + // operation. + Endpoint(operation string) config.Endpoint +} + +// HttpLifecycle serves as the default implementation of the Lifecycle interface +// for HTTP requests. Internally, it leverages the *http.Client type to execute +// HTTP requests against a root *url.URL, as given in `NewHttpLifecycle`. +type HttpLifecycle struct { + endpoints EndpointSource +} + +var _ Lifecycle = new(HttpLifecycle) + +// NewHttpLifecycle initializes a new instance of the *HttpLifecycle type with a +// new *http.Client, and the given root (see above). +func NewHttpLifecycle(endpoints EndpointSource) *HttpLifecycle { + return &HttpLifecycle{ + endpoints: endpoints, + } +} + +// Build implements the Lifecycle.Build function. +// +// HttpLifecycle in particular, builds an absolute path by parsing and then +// relativizing the `schema.Path` with respsect to the `HttpLifecycle.root`. If +// there was an error in determining this URL, then that error will be returned, +// +// After this is complete, a body is attached to the request if the +// schema contained one. If a body was present, and there an error occurred while +// serializing it into JSON, then that error will be returned and the +// *http.Request will not be generated. +// +// In all cases, credentials are attached to the HTTP request as described in +// the `auth` package (see github.com/github/git-lfs/auth#GetCreds). +// +// Finally, all of these components are combined together and the resulting +// request is returned. +func (l *HttpLifecycle) Build(schema *RequestSchema) (*http.Request, error) { + path, err := l.absolutePath(schema.Operation, schema.Path) + if err != nil { + return nil, err + } + + body, err := l.body(schema) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(schema.Method, path.String(), body) + if err != nil { + return nil, err + } + + if _, err = auth.GetCreds(req); err != nil { + return nil, err + } + + req.URL.RawQuery = l.queryParameters(schema).Encode() + + return req, nil +} + +// Execute implements the Lifecycle.Execute function. +// +// Internally, the *http.Client is used to execute the underlying *http.Request. +// If the client returned an error corresponding to a failure to make the +// request, then that error will be returned immediately, and the response is +// guaranteed not to be serialized. +// +// Once the response has been gathered from the server, it is unmarshled into +// the given `into interface{}` which is identical to the one provided in the +// original RequestSchema. If an error occured while decoding, then that error +// is returned. +// +// Otherwise, the api.Response is returned, along with no error, signaling that +// the request completed successfully. +func (l *HttpLifecycle) Execute(req *http.Request, into interface{}) (Response, error) { + resp, err := httputil.DoHttpRequestWithRedirects(req, []*http.Request{}, true) + if err != nil { + return nil, err + } + + if into != nil { + decoder := json.NewDecoder(resp.Body) + if err = decoder.Decode(into); err != nil { + return nil, err + } + } + + return WrapHttpResponse(resp), nil +} + +// Cleanup implements the Lifecycle.Cleanup function by closing the Body +// attached to the response. +func (l *HttpLifecycle) Cleanup(resp Response) error { + return resp.Body().Close() +} + +// absolutePath returns the absolute path made by combining a given relative +// path with the root URL of the endpoint corresponding to the given operation. +// +// If there was an error in parsing the relative path, then that error will be +// returned. +func (l *HttpLifecycle) absolutePath(operation Operation, path string) (*url.URL, error) { + if len(operation) == 0 { + return nil, ErrNoOperationGiven + } + + root, err := url.Parse(l.endpoints.Endpoint(string(operation)).Url) + if err != nil { + return nil, err + } + + rel, err := url.Parse(path) + if err != nil { + return nil, err + + } + + return root.ResolveReference(rel), nil +} + +// body returns an io.Reader which reads out a JSON-encoded copy of the payload +// attached to a given *RequestSchema, if it is present. If no body is present +// in the request, then nil is returned instead. +// +// If an error was encountered while attempting to marshal the body, then that +// will be returned instead, along with a nil io.Reader. +func (l *HttpLifecycle) body(schema *RequestSchema) (io.ReadCloser, error) { + if schema.Body == nil { + return nil, nil + } + + body, err := json.Marshal(schema.Body) + if err != nil { + return nil, err + } + + return ioutil.NopCloser(bytes.NewReader(body)), nil +} + +// queryParameters returns a url.Values containing all of the provided query +// parameters as given in the *RequestSchema. If no query parameters were given, +// then an empty url.Values is returned instead. +func (l *HttpLifecycle) queryParameters(schema *RequestSchema) url.Values { + vals := url.Values{} + if schema.Query != nil { + for k, v := range schema.Query { + vals.Add(k, v) + } + } + + return vals +} diff --git a/api/http_lifecycle_test.go b/api/http_lifecycle_test.go new file mode 100644 index 00000000..154397c1 --- /dev/null +++ b/api/http_lifecycle_test.go @@ -0,0 +1,148 @@ +package api_test + +import ( + "io/ioutil" + "net/http" + "net/http/httptest" + "testing" + + "github.com/github/git-lfs/api" + "github.com/github/git-lfs/config" + "github.com/stretchr/testify/assert" +) + +type NopEndpointSource struct { + Root string +} + +func (e *NopEndpointSource) Endpoint(op string) config.Endpoint { + return config.Endpoint{Url: e.Root} +} + +var ( + source = &NopEndpointSource{"https://example.com"} +) + +func TestHttpLifecycleMakesRequestsAgainstAbsolutePath(t *testing.T) { + SetupTestCredentialsFunc() + defer RestoreCredentialsFunc() + + l := api.NewHttpLifecycle(source) + req, err := l.Build(&api.RequestSchema{ + Path: "/foo", + Operation: api.DownloadOperation, + }) + + assert.Nil(t, err) + assert.Equal(t, "https://example.com/foo", req.URL.String()) +} + +func TestHttpLifecycleAttachesQueryParameters(t *testing.T) { + SetupTestCredentialsFunc() + defer RestoreCredentialsFunc() + + l := api.NewHttpLifecycle(source) + req, err := l.Build(&api.RequestSchema{ + Path: "/foo", + Operation: api.DownloadOperation, + Query: map[string]string{ + "a": "b", + }, + }) + + assert.Nil(t, err) + assert.Equal(t, "https://example.com/foo?a=b", req.URL.String()) +} + +func TestHttpLifecycleAttachesBodyWhenPresent(t *testing.T) { + SetupTestCredentialsFunc() + defer RestoreCredentialsFunc() + + l := api.NewHttpLifecycle(source) + req, err := l.Build(&api.RequestSchema{ + Operation: api.DownloadOperation, + Body: struct { + Foo string `json:"foo"` + }{"bar"}, + }) + + assert.Nil(t, err) + + body, err := ioutil.ReadAll(req.Body) + assert.Nil(t, err) + assert.Equal(t, "{\"foo\":\"bar\"}", string(body)) +} + +func TestHttpLifecycleDoesNotAttachBodyWhenEmpty(t *testing.T) { + SetupTestCredentialsFunc() + defer RestoreCredentialsFunc() + + l := api.NewHttpLifecycle(source) + req, err := l.Build(&api.RequestSchema{ + Operation: api.DownloadOperation, + }) + + assert.Nil(t, err) + assert.Nil(t, req.Body) +} + +func TestHttpLifecycleErrsWithoutOperation(t *testing.T) { + SetupTestCredentialsFunc() + defer RestoreCredentialsFunc() + + l := api.NewHttpLifecycle(source) + req, err := l.Build(&api.RequestSchema{ + Path: "/foo", + }) + + assert.Equal(t, api.ErrNoOperationGiven, err) + assert.Nil(t, req) +} + +func TestHttpLifecycleExecutesRequestWithoutBody(t *testing.T) { + SetupTestCredentialsFunc() + defer RestoreCredentialsFunc() + + var called bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + called = true + + assert.Equal(t, "/path", r.URL.RequestURI()) + })) + defer server.Close() + + req, _ := http.NewRequest("GET", server.URL+"/path", nil) + + l := api.NewHttpLifecycle(source) + _, err := l.Execute(req, nil) + + assert.True(t, called) + assert.Nil(t, err) +} + +func TestHttpLifecycleExecutesRequestWithBody(t *testing.T) { + SetupTestCredentialsFunc() + defer RestoreCredentialsFunc() + + type Response struct { + Foo string `json:"foo"` + } + + var called bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + called = true + + w.Write([]byte("{\"foo\":\"bar\"}")) + })) + defer server.Close() + + req, _ := http.NewRequest("GET", server.URL+"/path", nil) + + l := api.NewHttpLifecycle(source) + resp := new(Response) + _, err := l.Execute(req, resp) + + assert.True(t, called) + assert.Nil(t, err) + assert.Equal(t, "bar", resp.Foo) +} diff --git a/api/http_response.go b/api/http_response.go new file mode 100644 index 00000000..5d923cff --- /dev/null +++ b/api/http_response.go @@ -0,0 +1,53 @@ +// NOTE: Subject to change, do not rely on this package from outside git-lfs source +package api + +import ( + "io" + "net/http" +) + +// HttpResponse is an implementation of the Response interface capable of +// handling HTTP responses. At its core, it works by wrapping an *http.Response. +type HttpResponse struct { + // r is the underlying *http.Response that is being wrapped. + r *http.Response +} + +// WrapHttpResponse returns a wrapped *HttpResponse implementing the Repsonse +// type by using the given *http.Response. +func WrapHttpResponse(r *http.Response) *HttpResponse { + return &HttpResponse{ + r: r, + } +} + +var _ Response = new(HttpResponse) + +// Status implements the Response.Status function, and returns the status given +// by the underlying *http.Response. +func (h *HttpResponse) Status() string { + return h.r.Status +} + +// StatusCode implements the Response.StatusCode function, and returns the +// status code given by the underlying *http.Response. +func (h *HttpResponse) StatusCode() int { + return h.r.StatusCode +} + +// Proto implements the Response.Proto function, and returns the proto given by +// the underlying *http.Response. +func (h *HttpResponse) Proto() string { + return h.r.Proto +} + +// Body implements the Response.Body function, and returns the body as given by +// the underlying *http.Response. +func (h *HttpResponse) Body() io.ReadCloser { + return h.r.Body +} + +// Header returns the underlying *http.Response's header. +func (h *HttpResponse) Header() http.Header { + return h.r.Header +} diff --git a/api/http_response_test.go b/api/http_response_test.go new file mode 100644 index 00000000..779a27fc --- /dev/null +++ b/api/http_response_test.go @@ -0,0 +1,27 @@ +package api_test + +import ( + "bytes" + "io/ioutil" + "net/http" + "testing" + + "github.com/github/git-lfs/api" + "github.com/stretchr/testify/assert" +) + +func TestWrappedHttpResponsesMatchInternal(t *testing.T) { + resp := &http.Response{ + Status: "200 OK", + StatusCode: 200, + Proto: "HTTP/1.1", + Body: ioutil.NopCloser(new(bytes.Buffer)), + } + wrapped := api.WrapHttpResponse(resp) + + assert.Equal(t, resp.Status, wrapped.Status()) + assert.Equal(t, resp.StatusCode, wrapped.StatusCode()) + assert.Equal(t, resp.Proto, wrapped.Proto()) + assert.Equal(t, resp.Body, wrapped.Body()) + assert.Equal(t, resp.Header, wrapped.Header()) +} diff --git a/api/lifecycle.go b/api/lifecycle.go new file mode 100644 index 00000000..d8737f58 --- /dev/null +++ b/api/lifecycle.go @@ -0,0 +1,32 @@ +// NOTE: Subject to change, do not rely on this package from outside git-lfs source +package api + +import "net/http" + +// TODO: extract interface for *http.Request; update methods. This will be in a +// later iteration of the API client. + +// A Lifecycle represents and encapsulates the behavior on an API request from +// inception to cleanup. +// +// At a high level, it turns an *api.RequestSchema into an +// api.Response (and optionally an error). Lifecycle does so by providing +// several more fine-grained methods that are used by the client to manage the +// lifecycle of a request in a platform-agnostic fashion. +type Lifecycle interface { + // Build creates a sendable request by using the given RequestSchema as + // a model. + Build(req *RequestSchema) (*http.Request, error) + + // Execute transforms generated request into a wrapped repsonse, (and + // optionally an error, if the request failed), and serializes the + // response into the `into interface{}`, if one was provided. + Execute(req *http.Request, into interface{}) (Response, error) + + // Cleanup is called after the request has been completed and its + // response has been processed. It is meant to preform any post-request + // actions necessary, like closing or resetting the connection. If an + // error was encountered in doing this operation, it should be returned + // from this method, otherwise nil. + Cleanup(resp Response) error +} diff --git a/api/lifecycle_test.go b/api/lifecycle_test.go new file mode 100644 index 00000000..e2260ecd --- /dev/null +++ b/api/lifecycle_test.go @@ -0,0 +1,39 @@ +package api_test + +import ( + "net/http" + + "github.com/github/git-lfs/api" + "github.com/stretchr/testify/mock" +) + +type MockLifecycle struct { + mock.Mock +} + +var _ api.Lifecycle = new(MockLifecycle) + +func (l *MockLifecycle) Build(req *api.RequestSchema) (*http.Request, error) { + args := l.Called(req) + + if args.Get(0) == nil { + return nil, args.Error(1) + } + + return args.Get(0).(*http.Request), args.Error(1) +} + +func (l *MockLifecycle) Execute(req *http.Request, into interface{}) (api.Response, error) { + args := l.Called(req, into) + + if args.Get(0) == nil { + return nil, args.Error(1) + } + + return args.Get(0).(api.Response), args.Error(1) +} + +func (l *MockLifecycle) Cleanup(resp api.Response) error { + args := l.Called(resp) + return args.Error(0) +} diff --git a/api/lock_api.go b/api/lock_api.go new file mode 100644 index 00000000..3e704533 --- /dev/null +++ b/api/lock_api.go @@ -0,0 +1,243 @@ +package api + +import ( + "fmt" + "strconv" + "time" +) + +// LockService is an API service which encapsulates the Git LFS Locking API. +type LockService struct{} + +// Lock generates a *RequestSchema that is used to preform the "attempt lock" +// API method. +// +// If a lock is already present, or if the server was unable to generate the +// lock, the Err field of the LockResponse type will be populated with a more +// detailed error describing the situation. +// +// If the caller does not have the minimum commit necessary to obtain the lock +// on that file, then the CommitNeeded field will be populated in the +// LockResponse, signaling that more commits are needed. +// +// In the successful case, a new Lock will be returned and granted to the +// caller. +func (s *LockService) Lock(req *LockRequest) (*RequestSchema, *LockResponse) { + var resp LockResponse + + return &RequestSchema{ + Method: "POST", + Path: "/locks", + Operation: UploadOperation, + Body: req, + Into: &resp, + }, &resp +} + +// Search generates a *RequestSchema that is used to preform the "search for +// locks" API method. +// +// Searches can be scoped to match specific parameters by using the Filters +// field in the given LockSearchRequest. If no matching Locks were found, then +// the Locks field of the response will be empty. +// +// If the client expects that the server will return many locks, then the client +// can choose to paginate that response. Pagination is preformed by limiting the +// amount of results per page, and the server will inform the client of the ID +// of the last returned lock. Since the server is guaranteed to return results +// in reverse chronological order, the client simply sends the last ID it +// processed along with the next request, and the server will continue where it +// left off. +// +// If the server was unable to process the lock search request, then the Error +// field will be populated in the response. +// +// In the successful case, one or more locks will be returned as a part of the +// response. +func (s *LockService) Search(req *LockSearchRequest) (*RequestSchema, *LockList) { + var resp LockList + + query := make(map[string]string) + for _, filter := range req.Filters { + query[filter.Property] = filter.Value + } + + if req.Cursor != "" { + query["cursor"] = req.Cursor + } + + if req.Limit != 0 { + query["limit"] = strconv.Itoa(req.Limit) + } + + return &RequestSchema{ + Method: "GET", + Path: "/locks", + Operation: UploadOperation, + Query: query, + Into: &resp, + }, &resp +} + +// Unlock generates a *RequestSchema that is used to preform the "unlock" API +// method, against a particular lock potentially with --force. +// +// This method's corresponding response type will either contain a reference to +// the lock that was unlocked, or an error that was experienced by the server in +// unlocking it. +func (s *LockService) Unlock(id string, force bool) (*RequestSchema, *UnlockResponse) { + var resp UnlockResponse + + return &RequestSchema{ + Method: "POST", + Path: fmt.Sprintf("/locks/%s/unlock", id), + Operation: UploadOperation, + Body: &UnlockRequest{id, force}, + Into: &resp, + }, &resp +} + +// Lock represents a single lock that against a particular path. +// +// Locks returned from the API may or may not be currently active, according to +// the Expired flag. +type Lock struct { + // Id is the unique identifier corresponding to this particular Lock. It + // must be consistent with the local copy, and the server's copy. + Id string `json:"id"` + // Path is an absolute path to the file that is locked as a part of this + // lock. + Path string `json:"path"` + // Committer is the author who initiated this lock. + Committer Committer `json:"committer"` + // CommitSHA is the commit that this Lock was created against. It is + // strictly equal to the SHA of the minimum commit negotiated in order + // to create this lock. + CommitSHA string `json:"commit_sha"` + // LockedAt is a required parameter that represents the instant in time + // that this lock was created. For most server implementations, this + // should be set to the instant at which the lock was initially + // received. + LockedAt time.Time `json:"locked_at"` + // ExpiresAt is an optional parameter that represents the instant in + // time that the lock stopped being active. If the lock is still active, + // the server can either a) not send this field, or b) send the + // zero-value of time.Time. + UnlockedAt time.Time `json:"unlocked_at,omitempty"` +} + +// Active returns whether or not the given lock is still active against the file +// that it is protecting. +func (l *Lock) Active() bool { + return l.UnlockedAt.IsZero() +} + +// Committer represents a "First Last " pair. +type Committer struct { + // Name is the name of the individual who would like to obtain the + // lock, for instance: "Rick Olson". + Name string `json:"name"` + // Email is the email assopsicated with the individual who would + // like to obtain the lock, for instance: "rick@github.com". + Email string `json:"email"` +} + +// LockRequest encapsulates the payload sent across the API when a client would +// like to obtain a lock against a particular path on a given remote. +type LockRequest struct { + // Path is the path that the client would like to obtain a lock against. + Path string `json:"path"` + // LatestRemoteCommit is the SHA of the last known commit from the + // remote that we are trying to create the lock against, as found in + // `.git/refs/origin/`. + LatestRemoteCommit string `json:"latest_remote_commit"` + // Committer is the individual that wishes to obtain the lock. + Committer Committer `json:"committer"` +} + +// LockResponse encapsulates the information sent over the API in response to +// a `LockRequest`. +type LockResponse struct { + // Lock is the Lock that was optionally created in response to the + // payload that was sent (see above). If the lock already exists, then + // the existing lock is sent in this field instead, and the author of + // that lock remains the same, meaning that the client failed to obtain + // that lock. An HTTP status of "409 - Conflict" is used here. + // + // If the lock was unable to be created, this field will hold the + // zero-value of Lock and the Err field will provide a more detailed set + // of information. + // + // If an error was experienced in creating this lock, then the + // zero-value of Lock should be sent here instead. + Lock *Lock `json:"lock"` + // CommitNeeded holds the minimum commit SHA that client must have to + // obtain the lock. + CommitNeeded string `json:"commit_needed,omitempty"` + // Err is the optional error that was encountered while trying to create + // the above lock. + Err string `json:"error,omitempty"` +} + +// UnlockRequest encapsulates the data sent in an API request to remove a lock. +type UnlockRequest struct { + // Id is the Id of the lock that the user wishes to unlock. + Id string `json:"id"` + // Force determines whether or not the lock should be "forcibly" + // unlocked; that is to say whether or not a given individual should be + // able to break a different individual's lock. + Force bool `json:"force"` +} + +// UnlockResponse is the result sent back from the API when asked to remove a +// lock. +type UnlockResponse struct { + // Lock is the lock corresponding to the asked-about lock in the + // `UnlockPayload` (see above). If no matching lock was found, this + // field will take the zero-value of Lock, and Err will be non-nil. + Lock *Lock `json:"lock"` + // Err is an optional field which holds any error that was experienced + // while removing the lock. + Err string `json:"error,omitempty"` +} + +// Filter represents a single qualifier to apply against a set of locks. +type Filter struct { + // Property is the property to search against. + // Value is the value that the property must take. + Property, Value string +} + +// LockSearchRequest encapsulates the request sent to the server when the client +// would like a list of locks that match the given criteria. +type LockSearchRequest struct { + // Filters is the set of filters to query against. If the client wishes + // to obtain a list of all locks, an empty array should be passed here. + Filters []Filter + // Cursor is an optional field used to tell the server which lock was + // seen last, if scanning through multiple pages of results. + // + // Servers must return a list of locks sorted in reverse chronological + // order, so the Cursor provides a consistent method of viewing all + // locks, even if more were created between two requests. + Cursor string + // Limit is the maximum number of locks to return in a single page. + Limit int +} + +// LockList encapsulates a set of Locks. +type LockList struct { + // Locks is the set of locks returned back, typically matching the query + // parameters sent in the LockListRequest call. If no locks were matched + // from a given query, then `Locks` will be represented as an empty + // array. + Locks []Lock `json:"locks"` + // NextCursor returns the Id of the Lock the client should update its + // cursor to, if there are multiple pages of results for a particular + // `LockListRequest`. + NextCursor string `json:"next_cursor,omitempty"` + // Err populates any error that was encountered during the search. If no + // error was encountered and the operation was succesful, then a value + // of nil will be passed here. + Err string `json:"error,omitempty"` +} diff --git a/api/lock_api_test.go b/api/lock_api_test.go new file mode 100644 index 00000000..d2cb5b01 --- /dev/null +++ b/api/lock_api_test.go @@ -0,0 +1,220 @@ +package api_test + +import ( + "testing" + "time" + + "github.com/github/git-lfs/api" + "github.com/github/git-lfs/api/schema" +) + +var LockService api.LockService + +func TestSuccessfullyObtainingALock(t *testing.T) { + got, body := LockService.Lock(new(api.LockRequest)) + + AssertRequestSchema(t, &api.RequestSchema{ + Method: "POST", + Path: "/locks", + Operation: api.UploadOperation, + Body: new(api.LockRequest), + Into: body, + }, got) +} + +func TestLockSearchWithFilters(t *testing.T) { + got, body := LockService.Search(&api.LockSearchRequest{ + Filters: []api.Filter{ + {"branch", "master"}, + {"path", "/path/to/file"}, + }, + }) + + AssertRequestSchema(t, &api.RequestSchema{ + Method: "GET", + Query: map[string]string{ + "branch": "master", + "path": "/path/to/file", + }, + Path: "/locks", + Operation: api.UploadOperation, + Into: body, + }, got) +} + +func TestLockSearchWithNextCursor(t *testing.T) { + got, body := LockService.Search(&api.LockSearchRequest{ + Cursor: "some-lock-id", + }) + + AssertRequestSchema(t, &api.RequestSchema{ + Method: "GET", + Query: map[string]string{ + "cursor": "some-lock-id", + }, + Path: "/locks", + Operation: api.UploadOperation, + Into: body, + }, got) +} + +func TestLockSearchWithLimit(t *testing.T) { + got, body := LockService.Search(&api.LockSearchRequest{ + Limit: 20, + }) + + AssertRequestSchema(t, &api.RequestSchema{ + Method: "GET", + Query: map[string]string{ + "limit": "20", + }, + Path: "/locks", + Operation: api.UploadOperation, + Into: body, + }, got) +} + +func TestUnlockingALock(t *testing.T) { + got, body := LockService.Unlock("some-lock-id", true) + + AssertRequestSchema(t, &api.RequestSchema{ + Method: "POST", + Path: "/locks/some-lock-id/unlock", + Operation: api.UploadOperation, + Body: &api.UnlockRequest{ + Id: "some-lock-id", + Force: true, + }, + Into: body, + }, got) +} + +func TestLockRequest(t *testing.T) { + schema.Validate(t, schema.LockRequestSchema, &api.LockRequest{ + Path: "/path/to/lock", + LatestRemoteCommit: "deadbeef", + Committer: api.Committer{ + Name: "Jane Doe", + Email: "jane@example.com", + }, + }) +} + +func TestLockResponseWithLockedLock(t *testing.T) { + schema.Validate(t, schema.LockResponseSchema, &api.LockResponse{ + Lock: &api.Lock{ + Id: "some-lock-id", + Path: "/lock/path", + Committer: api.Committer{ + Name: "Jane Doe", + Email: "jane@example.com", + }, + LockedAt: time.Now(), + }, + }) +} + +func TestLockResponseWithUnlockedLock(t *testing.T) { + schema.Validate(t, schema.LockResponseSchema, &api.LockResponse{ + Lock: &api.Lock{ + Id: "some-lock-id", + Path: "/lock/path", + Committer: api.Committer{ + Name: "Jane Doe", + Email: "jane@example.com", + }, + LockedAt: time.Now(), + UnlockedAt: time.Now(), + }, + }) +} + +func TestLockResponseWithError(t *testing.T) { + schema.Validate(t, schema.LockResponseSchema, &api.LockResponse{ + Err: "some error", + }) +} + +func TestLockResponseWithCommitNeeded(t *testing.T) { + schema.Validate(t, schema.LockResponseSchema, &api.LockResponse{ + CommitNeeded: "deadbeef", + }) +} + +func TestLockResponseInvalidWithCommitAndError(t *testing.T) { + schema.Refute(t, schema.LockResponseSchema, &api.LockResponse{ + Err: "some error", + CommitNeeded: "deadbeef", + }) +} + +func TestUnlockRequest(t *testing.T) { + schema.Validate(t, schema.UnlockRequestSchema, &api.UnlockRequest{ + Id: "some-lock-id", + Force: false, + }) +} + +func TestUnlockResponseWithLock(t *testing.T) { + schema.Validate(t, schema.UnlockResponseSchema, &api.UnlockResponse{ + Lock: &api.Lock{ + Id: "some-lock-id", + }, + }) +} + +func TestUnlockResponseWithError(t *testing.T) { + schema.Validate(t, schema.UnlockResponseSchema, &api.UnlockResponse{ + Err: "some-error", + }) +} + +func TestUnlockResponseDoesNotAllowLockAndError(t *testing.T) { + schema.Refute(t, schema.UnlockResponseSchema, &api.UnlockResponse{ + Lock: &api.Lock{ + Id: "some-lock-id", + }, + Err: "some-error", + }) +} + +func TestLockListWithLocks(t *testing.T) { + schema.Validate(t, schema.LockListSchema, &api.LockList{ + Locks: []api.Lock{ + api.Lock{Id: "foo"}, + api.Lock{Id: "bar"}, + }, + }) +} + +func TestLockListWithNoResults(t *testing.T) { + schema.Validate(t, schema.LockListSchema, &api.LockList{ + Locks: []api.Lock{}, + }) +} + +func TestLockListWithNextCursor(t *testing.T) { + schema.Validate(t, schema.LockListSchema, &api.LockList{ + Locks: []api.Lock{ + api.Lock{Id: "foo"}, + api.Lock{Id: "bar"}, + }, + NextCursor: "baz", + }) +} + +func TestLockListWithError(t *testing.T) { + schema.Validate(t, schema.LockListSchema, &api.LockList{ + Err: "some error", + }) +} + +func TestLockListWithErrorAndLocks(t *testing.T) { + schema.Refute(t, schema.LockListSchema, &api.LockList{ + Locks: []api.Lock{ + api.Lock{Id: "foo"}, + api.Lock{Id: "bar"}, + }, + Err: "this isn't possible!", + }) +} diff --git a/api/request_schema.go b/api/request_schema.go new file mode 100644 index 00000000..d26d01aa --- /dev/null +++ b/api/request_schema.go @@ -0,0 +1,21 @@ +// NOTE: Subject to change, do not rely on this package from outside git-lfs source +package api + +// RequestSchema provides a schema from which to generate sendable requests. +type RequestSchema struct { + // Method is the method that should be used when making a particular API + // call. + Method string + // Path is the relative path that this API call should be made against. + Path string + // Operation is the operation used to determine which endpoint to make + // the request against (see github.com/github/git-lfs/config). + Operation Operation + // Query is the query parameters used in the request URI. + Query map[string]string + // Body is the body of the request. + Body interface{} + // Into is an optional field used to represent the data structure into + // which a response should be serialized. + Into interface{} +} diff --git a/api/request_schema_test.go b/api/request_schema_test.go new file mode 100644 index 00000000..e5ae66be --- /dev/null +++ b/api/request_schema_test.go @@ -0,0 +1,23 @@ +package api_test + +import ( + "testing" + + "github.com/github/git-lfs/api" + "github.com/stretchr/testify/assert" +) + +// AssertRequestSchema encapsulates a single assertion of equality against two +// generated RequestSchema instances. +// +// This assertion is meant only to test that the request schema generated by an +// API service matches what we expect it to be. It does not make use of the +// *api.Client, any particular lifecycle, or spin up a test server. All of that +// behavior is tested at a higher strata in the client/lifecycle tests. +// +// - t is the *testing.T used to preform the assertion. +// - Expected is the *api.RequestSchema that we expected to be generated. +// - Got is the *api.RequestSchema that was generated by a service. +func AssertRequestSchema(t *testing.T, expected, got *api.RequestSchema) { + assert.Equal(t, expected, got) +} diff --git a/api/response.go b/api/response.go new file mode 100644 index 00000000..294cd2f2 --- /dev/null +++ b/api/response.go @@ -0,0 +1,24 @@ +// NOTE: Subject to change, do not rely on this package from outside git-lfs source +package api + +import "io" + +// Response is an interface that represents a response returned as a result of +// executing an API call. It is designed to represent itself across multiple +// response type, be it HTTP, SSH, or something else. +// +// The Response interface is meant to be small enough such that it can be +// sufficiently general, but is easily accessible if a caller needs more +// information specific to a particular protocol. +type Response interface { + // Status is a human-readable string representing the status the + // response was returned with. + Status() string + // StatusCode is the numeric code associated with a particular status. + StatusCode() int + // Proto is the protocol with which the response was delivered. + Proto() string + // Body returns an io.ReadCloser containg the contents of the response's + // body. + Body() io.ReadCloser +} diff --git a/api/schema/lock_list_schema.json b/api/schema/lock_list_schema.json new file mode 100644 index 00000000..e2fa6a36 --- /dev/null +++ b/api/schema/lock_list_schema.json @@ -0,0 +1,65 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + + "type": "object", + "oneOf": [ + { + "properties": { + "locks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "path": { + "type": "string" + }, + "committer": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "email": { + "type": "string" + } + }, + "required": ["name", "email"] + }, + "commit_sha": { + "type": "string" + }, + "locked_at": { + "type": "string" + }, + "unlocked_at": { + "type": "string" + } + }, + "required": ["id", "path", "commit_sha", "locked_at"], + "additionalItems": false + } + }, + "next_cursor": { + "type": "string" + } + }, + "additionalProperties": false, + "required": ["locks"] + }, + { + "properties": { + "locks": { + "type": "null" + }, + "error": { + "type": "string" + } + }, + "additionalProperties": false, + "required": ["error"] + } + ] +} diff --git a/api/schema/lock_request_schema.json b/api/schema/lock_request_schema.json new file mode 100644 index 00000000..10d5e2f2 --- /dev/null +++ b/api/schema/lock_request_schema.json @@ -0,0 +1,25 @@ +{ + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "latest_remote_commit": { + "type": "string" + }, + "committer": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "email": { + "type": "string" + } + }, + "required": ["name", "email"] + } + }, + "required": ["path", "latest_remote_commit", "committer"] + +} diff --git a/api/schema/lock_response_schema.json b/api/schema/lock_response_schema.json new file mode 100644 index 00000000..a5b458de --- /dev/null +++ b/api/schema/lock_response_schema.json @@ -0,0 +1,61 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + + "type": "object", + "oneOf": [ + { + "properties": { + "error": { + "type": "string" + } + }, + "required": ["error"] + }, + { + "properties": { + "commit_needed": { + "type": "string" + } + }, + "required": ["commit_needed"] + }, + { + "properties": { + "lock": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "path": { + "type": "string" + }, + "committer": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "email": { + "type": "string" + } + }, + "required": ["name", "email"] + }, + "commit_sha": { + "type": "string" + }, + "locked_at": { + "type": "string" + }, + "unlocked_at": { + "type": "string" + } + }, + "required": ["id", "path", "commit_sha", "locked_at"] + } + }, + "required": ["lock"] + } + ] +} diff --git a/api/schema/schema_validator.go b/api/schema/schema_validator.go new file mode 100644 index 00000000..5e1b7272 --- /dev/null +++ b/api/schema/schema_validator.go @@ -0,0 +1,82 @@ +package schema + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/xeipuuv/gojsonschema" +) + +// SchemaValidator uses the gojsonschema library to validate the JSON encoding +// of Go objects against a pre-defined JSON schema. +type SchemaValidator struct { + // Schema is the JSON schema to validate against. + // + // Subject is the instance of Go type that will be validated. + Schema, Subject gojsonschema.JSONLoader +} + +func NewSchemaValidator(t *testing.T, schemaName string, got interface{}) *SchemaValidator { + dir, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + + schema := gojsonschema.NewReferenceLoader(fmt.Sprintf( + "file:///%s", + filepath.Join(dir, "schema/", schemaName), + )) + + marshalled, err := json.Marshal(got) + if err != nil { + t.Fatal(err) + } + + subject := gojsonschema.NewStringLoader(string(marshalled)) + + return &SchemaValidator{ + Schema: schema, + Subject: subject, + } +} + +// Validate validates a Go object against JSON schema in a testing environment. +// If the validation fails, then the test will fail after logging all of the +// validation errors experienced by the validator. +func Validate(t *testing.T, schemaName string, got interface{}) { + NewSchemaValidator(t, schemaName, got).Assert(t) +} + +// Refute ensures that a particular Go object does not validate the JSON schema +// given. +// +// If validation against the schema is successful, then the test will fail after +// logging. +func Refute(t *testing.T, schemaName string, got interface{}) { + NewSchemaValidator(t, schemaName, got).Refute(t) +} + +// Assert preforms the validation assertion against the given *testing.T. +func (v *SchemaValidator) Assert(t *testing.T) { + if result, err := gojsonschema.Validate(v.Schema, v.Subject); err != nil { + t.Fatal(err) + } else if !result.Valid() { + for _, err := range result.Errors() { + t.Logf("Validation error: %s", err.Description()) + } + t.Fail() + } +} + +// Refute refutes that the given subject will validate against a particular +// schema. +func (v *SchemaValidator) Refute(t *testing.T) { + if result, err := gojsonschema.Validate(v.Schema, v.Subject); err != nil { + t.Fatal(err) + } else if result.Valid() { + t.Fatal("api/schema: expected validation to fail, succeeded") + } +} diff --git a/api/schema/schemas.go b/api/schema/schemas.go new file mode 100644 index 00000000..7d4c94d3 --- /dev/null +++ b/api/schema/schemas.go @@ -0,0 +1,24 @@ +// schema provides a testing utility for testing API types against a predefined +// JSON schema. +// +// The core philosophy for this package is as follows: when a new API is +// accepted, JSON Schema files should be added to document the types that are +// exchanged over this new API. Those files are placed in the `/api/schema` +// directory, and are used by the schema.Validate function to test that +// particular instances of these types as represented in Go match the predefined +// schema that was proposed as a part of the API. +// +// For ease of use, this file defines several constants, one for each schema +// file's name, to easily pass around during tests. +// +// As briefly described above, to validate that a Go type matches the schema for +// a particular API call, one should use the schema.Validate() function. +package schema + +const ( + LockListSchema = "lock_list_schema.json" + LockRequestSchema = "lock_request_schema.json" + LockResponseSchema = "lock_response_schema.json" + UnlockRequestSchema = "unlock_request_schema.json" + UnlockResponseSchema = "unlock_response_schema.json" +) diff --git a/api/schema/unlock_request_schema.json b/api/schema/unlock_request_schema.json new file mode 100644 index 00000000..c4362bb9 --- /dev/null +++ b/api/schema/unlock_request_schema.json @@ -0,0 +1,15 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "force": { + "type": "boolean" + } + }, + "required": ["id", "force"], + "additionalItems": false +} diff --git a/api/schema/unlock_response_schema.json b/api/schema/unlock_response_schema.json new file mode 100644 index 00000000..5ede9024 --- /dev/null +++ b/api/schema/unlock_response_schema.json @@ -0,0 +1,53 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + + "type": "object", + "oneOf": [ + { + "properties": { + "lock": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "path": { + "type": "string" + }, + "committer": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "email": { + "type": "string" + } + }, + "required": ["name", "email"] + }, + "commit_sha": { + "type": "string" + }, + "locked_at": { + "type": "string" + }, + "unlocked_at": { + "type": "string" + } + }, + "required": ["id", "path", "commit_sha", "locked_at"] + } + }, + "required": ["lock"] + }, + { + "properties": { + "error": { + "type": "string" + } + }, + "required": ["error"] + } + ] +} diff --git a/api/v1.go b/api/v1.go new file mode 100644 index 00000000..a5426879 --- /dev/null +++ b/api/v1.go @@ -0,0 +1,155 @@ +package api + +import ( + "net/http" + "net/url" + "path" + + "github.com/github/git-lfs/auth" + "github.com/github/git-lfs/config" + "github.com/github/git-lfs/errutil" + "github.com/github/git-lfs/httputil" + + "github.com/rubyist/tracerx" +) + +const ( + MediaType = "application/vnd.git-lfs+json; charset=utf-8" +) + +// doLegacyApiRequest runs the request to the LFS legacy API. +func DoLegacyRequest(req *http.Request) (*http.Response, *ObjectResource, error) { + via := make([]*http.Request, 0, 4) + res, err := httputil.DoHttpRequestWithRedirects(req, via, true) + if err != nil { + return res, nil, err + } + + obj := &ObjectResource{} + err = httputil.DecodeResponse(res, obj) + + if err != nil { + httputil.SetErrorResponseContext(err, res) + return nil, nil, err + } + + return res, obj, nil +} + +// doApiBatchRequest runs the request to the LFS batch API. If the API returns a +// 401, the repo will be marked as having private access and the request will be +// re-run. When the repo is marked as having private access, credentials will +// be retrieved. +func DoBatchRequest(req *http.Request) (*http.Response, []*ObjectResource, error) { + res, err := DoRequest(req, config.Config.PrivateAccess(auth.GetOperationForRequest(req))) + + if err != nil { + if res != nil && res.StatusCode == 401 { + return res, nil, errutil.NewAuthError(err) + } + return res, nil, err + } + + var objs map[string][]*ObjectResource + err = httputil.DecodeResponse(res, &objs) + + if err != nil { + httputil.SetErrorResponseContext(err, res) + } + + return res, objs["objects"], err +} + +// DoRequest runs a request to the LFS API, without parsing the response +// body. If the API returns a 401, the repo will be marked as having private +// access and the request will be re-run. When the repo is marked as having +// private access, credentials will be retrieved. +func DoRequest(req *http.Request, useCreds bool) (*http.Response, error) { + via := make([]*http.Request, 0, 4) + return httputil.DoHttpRequestWithRedirects(req, via, useCreds) +} + +func NewRequest(method, oid string) (*http.Request, error) { + objectOid := oid + operation := "download" + if method == "POST" { + if oid != "batch" { + objectOid = "" + operation = "upload" + } + } + endpoint := config.Config.Endpoint(operation) + + res, err := auth.SshAuthenticate(endpoint, operation, oid) + if err != nil { + tracerx.Printf("ssh: attempted with %s. Error: %s", + endpoint.SshUserAndHost, err.Error(), + ) + return nil, err + } + + if len(res.Href) > 0 { + endpoint.Url = res.Href + } + + u, err := ObjectUrl(endpoint, objectOid) + if err != nil { + return nil, err + } + + req, err := httputil.NewHttpRequest(method, u.String(), res.Header) + if err != nil { + return nil, err + } + + req.Header.Set("Accept", MediaType) + return req, nil +} + +func NewBatchRequest(operation string) (*http.Request, error) { + endpoint := config.Config.Endpoint(operation) + + res, err := auth.SshAuthenticate(endpoint, operation, "") + if err != nil { + tracerx.Printf("ssh: %s attempted with %s. Error: %s", + operation, endpoint.SshUserAndHost, err.Error(), + ) + return nil, err + } + + if len(res.Href) > 0 { + endpoint.Url = res.Href + } + + u, err := ObjectUrl(endpoint, "batch") + if err != nil { + return nil, err + } + + req, err := httputil.NewHttpRequest("POST", u.String(), nil) + if err != nil { + return nil, err + } + + req.Header.Set("Accept", MediaType) + if res.Header != nil { + for key, value := range res.Header { + req.Header.Set(key, value) + } + } + + return req, nil +} + +func ObjectUrl(endpoint config.Endpoint, oid string) (*url.URL, error) { + u, err := url.Parse(endpoint.Url) + if err != nil { + return nil, err + } + + u.Path = path.Join(u.Path, "objects") + if len(oid) > 0 { + u.Path = path.Join(u.Path, oid) + } + return u, nil +} diff --git a/auth/credentials.go b/auth/credentials.go index 39d40f1f..77410ae6 100644 --- a/auth/credentials.go +++ b/auth/credentials.go @@ -14,7 +14,7 @@ import ( "github.com/github/git-lfs/config" "github.com/github/git-lfs/errutil" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" + "github.com/rubyist/tracerx" ) // getCreds gets the credentials for a HTTP request and sets the given diff --git a/auth/credentials_test.go b/auth/credentials_test.go index 82cc0fc6..7663c259 100644 --- a/auth/credentials_test.go +++ b/auth/credentials_test.go @@ -8,8 +8,8 @@ import ( "strings" "testing" + "github.com/bgentry/go-netrc/netrc" "github.com/github/git-lfs/config" - "github.com/github/git-lfs/vendor/_nuts/github.com/bgentry/go-netrc/netrc" ) func TestGetCredentialsForApi(t *testing.T) { diff --git a/auth/ssh.go b/auth/ssh.go index 68ff3f18..d048c6fd 100644 --- a/auth/ssh.go +++ b/auth/ssh.go @@ -9,7 +9,7 @@ import ( "strings" "github.com/github/git-lfs/config" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" + "github.com/rubyist/tracerx" ) type SshAuthResponse struct { diff --git a/auth/ssh_test.go b/auth/ssh_test.go index 98ba2575..7f60c3a0 100644 --- a/auth/ssh_test.go +++ b/auth/ssh_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/github/git-lfs/config" - "github.com/github/git-lfs/vendor/_nuts/github.com/technoweenie/assert" + "github.com/stretchr/testify/assert" ) func TestSSHGetExeAndArgsSsh(t *testing.T) { diff --git a/commands/command_checkout.go b/commands/command_checkout.go index 8292d7f0..dfa9e445 100644 --- a/commands/command_checkout.go +++ b/commands/command_checkout.go @@ -11,8 +11,8 @@ import ( "github.com/github/git-lfs/git" "github.com/github/git-lfs/lfs" "github.com/github/git-lfs/progress" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/rubyist/tracerx" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_clean.go b/commands/command_clean.go index 94778f02..a0dea529 100644 --- a/commands/command_clean.go +++ b/commands/command_clean.go @@ -6,7 +6,7 @@ import ( "github.com/github/git-lfs/errutil" "github.com/github/git-lfs/lfs" "github.com/github/git-lfs/progress" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_clone.go b/commands/command_clone.go index 5d636a8f..2601a3e8 100644 --- a/commands/command_clone.go +++ b/commands/command_clone.go @@ -10,7 +10,7 @@ import ( "github.com/github/git-lfs/git" "github.com/github/git-lfs/localstorage" "github.com/github/git-lfs/tools" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_env.go b/commands/command_env.go index 69ebdb78..1d512ea2 100644 --- a/commands/command_env.go +++ b/commands/command_env.go @@ -4,7 +4,7 @@ import ( "github.com/github/git-lfs/config" "github.com/github/git-lfs/git" "github.com/github/git-lfs/lfs" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_ext.go b/commands/command_ext.go index b7c67bc0..da934eb5 100644 --- a/commands/command_ext.go +++ b/commands/command_ext.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/github/git-lfs/config" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_fetch.go b/commands/command_fetch.go index c698acf7..32363f04 100644 --- a/commands/command_fetch.go +++ b/commands/command_fetch.go @@ -8,8 +8,8 @@ import ( "github.com/github/git-lfs/git" "github.com/github/git-lfs/lfs" "github.com/github/git-lfs/progress" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/rubyist/tracerx" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_fsck.go b/commands/command_fsck.go index 5759aa2f..7f620f53 100644 --- a/commands/command_fsck.go +++ b/commands/command_fsck.go @@ -10,7 +10,7 @@ import ( "github.com/github/git-lfs/config" "github.com/github/git-lfs/git" "github.com/github/git-lfs/lfs" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_init.go b/commands/command_init.go index 5b53b24a..65caf8d2 100644 --- a/commands/command_init.go +++ b/commands/command_init.go @@ -4,7 +4,7 @@ import ( "fmt" "os" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) // TODO: Remove for Git LFS v2.0 https://github.com/github/git-lfs/issues/839 diff --git a/commands/command_install.go b/commands/command_install.go index 8144565d..692b7124 100644 --- a/commands/command_install.go +++ b/commands/command_install.go @@ -2,7 +2,7 @@ package commands import ( "github.com/github/git-lfs/lfs" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_logs.go b/commands/command_logs.go index 0912a6d2..8eb477e8 100644 --- a/commands/command_logs.go +++ b/commands/command_logs.go @@ -8,7 +8,7 @@ import ( "github.com/github/git-lfs/config" "github.com/github/git-lfs/errutil" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_ls_files.go b/commands/command_ls_files.go index b4b69510..935acf8f 100644 --- a/commands/command_ls_files.go +++ b/commands/command_ls_files.go @@ -5,7 +5,7 @@ import ( "github.com/github/git-lfs/git" "github.com/github/git-lfs/lfs" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_pointer.go b/commands/command_pointer.go index b8648af1..b7c35fd9 100644 --- a/commands/command_pointer.go +++ b/commands/command_pointer.go @@ -11,7 +11,7 @@ import ( "os/exec" "github.com/github/git-lfs/lfs" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_pre_push.go b/commands/command_pre_push.go index 27c3cbae..58809cf7 100644 --- a/commands/command_pre_push.go +++ b/commands/command_pre_push.go @@ -8,7 +8,7 @@ import ( "github.com/github/git-lfs/config" "github.com/github/git-lfs/git" "github.com/github/git-lfs/lfs" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_prune.go b/commands/command_prune.go index c0ad119c..9f95c2a2 100644 --- a/commands/command_prune.go +++ b/commands/command_prune.go @@ -12,8 +12,8 @@ import ( "github.com/github/git-lfs/lfs" "github.com/github/git-lfs/localstorage" "github.com/github/git-lfs/progress" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/rubyist/tracerx" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_pull.go b/commands/command_pull.go index 1a4e17f3..3f012ecf 100644 --- a/commands/command_pull.go +++ b/commands/command_pull.go @@ -5,7 +5,7 @@ import ( "github.com/github/git-lfs/config" "github.com/github/git-lfs/git" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_push.go b/commands/command_push.go index e3e1842d..2eeb6b22 100644 --- a/commands/command_push.go +++ b/commands/command_push.go @@ -7,8 +7,8 @@ import ( "github.com/github/git-lfs/config" "github.com/github/git-lfs/git" "github.com/github/git-lfs/lfs" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/rubyist/tracerx" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_smudge.go b/commands/command_smudge.go index 7312659c..309a57cb 100644 --- a/commands/command_smudge.go +++ b/commands/command_smudge.go @@ -9,7 +9,7 @@ import ( "github.com/github/git-lfs/config" "github.com/github/git-lfs/errutil" "github.com/github/git-lfs/lfs" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_status.go b/commands/command_status.go index 0c64e2f4..a262dc10 100644 --- a/commands/command_status.go +++ b/commands/command_status.go @@ -5,7 +5,7 @@ import ( "github.com/github/git-lfs/git" "github.com/github/git-lfs/lfs" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_track.go b/commands/command_track.go index 78f2266f..b66f643b 100644 --- a/commands/command_track.go +++ b/commands/command_track.go @@ -13,7 +13,7 @@ import ( "github.com/github/git-lfs/git" "github.com/github/git-lfs/lfs" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_uninit.go b/commands/command_uninit.go index bcb43116..08ee27e6 100644 --- a/commands/command_uninit.go +++ b/commands/command_uninit.go @@ -4,7 +4,7 @@ import ( "fmt" "os" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) // TODO: Remove for Git LFS v2.0 https://github.com/github/git-lfs/issues/839 diff --git a/commands/command_uninstall.go b/commands/command_uninstall.go index 9f2258bc..026bb99c 100644 --- a/commands/command_uninstall.go +++ b/commands/command_uninstall.go @@ -2,7 +2,7 @@ package commands import ( "github.com/github/git-lfs/lfs" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_untrack.go b/commands/command_untrack.go index ab01b63a..bd4127bc 100644 --- a/commands/command_untrack.go +++ b/commands/command_untrack.go @@ -8,7 +8,7 @@ import ( "github.com/github/git-lfs/config" "github.com/github/git-lfs/lfs" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_update.go b/commands/command_update.go index 9cafa113..5b5d8c34 100644 --- a/commands/command_update.go +++ b/commands/command_update.go @@ -6,7 +6,7 @@ import ( "github.com/github/git-lfs/config" "github.com/github/git-lfs/git" "github.com/github/git-lfs/lfs" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) var ( diff --git a/commands/command_version.go b/commands/command_version.go index 4b1f0435..3f584d5b 100644 --- a/commands/command_version.go +++ b/commands/command_version.go @@ -2,7 +2,7 @@ package commands import ( "github.com/github/git-lfs/httputil" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) var ( diff --git a/commands/commands.go b/commands/commands.go index 85d9c13a..93cc8a1c 100644 --- a/commands/commands.go +++ b/commands/commands.go @@ -15,7 +15,7 @@ import ( "github.com/github/git-lfs/errutil" "github.com/github/git-lfs/git" "github.com/github/git-lfs/lfs" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) // Populate man pages diff --git a/config/config.go b/config/config.go index b6e3aa6f..5b8a9d07 100644 --- a/config/config.go +++ b/config/config.go @@ -10,10 +10,10 @@ import ( "strings" "sync" + "github.com/ThomsonReutersEikon/go-ntlm/ntlm" + "github.com/bgentry/go-netrc/netrc" "github.com/github/git-lfs/git" - "github.com/github/git-lfs/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm" - "github.com/github/git-lfs/vendor/_nuts/github.com/bgentry/go-netrc/netrc" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" + "github.com/rubyist/tracerx" ) var ( diff --git a/config/config_netrc.go b/config/config_netrc.go index afc7c989..4c3ff19b 100644 --- a/config/config_netrc.go +++ b/config/config_netrc.go @@ -4,7 +4,7 @@ import ( "os" "path/filepath" - "github.com/github/git-lfs/vendor/_nuts/github.com/bgentry/go-netrc/netrc" + "github.com/bgentry/go-netrc/netrc" ) type netrcfinder interface { diff --git a/config/config_test.go b/config/config_test.go index e666fbe5..b13eebe1 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -3,7 +3,7 @@ package config import ( "testing" - "github.com/github/git-lfs/vendor/_nuts/github.com/technoweenie/assert" + "github.com/stretchr/testify/assert" ) func TestEndpointDefaultsToOrigin(t *testing.T) { @@ -363,7 +363,7 @@ func TestBatchAbsentIsTrue(t *testing.T) { config := &Configuration{} v := config.BatchTransfer() - assert.Equal(t, true, v) + assert.True(t, v) } func TestAccessConfig(t *testing.T) { @@ -438,8 +438,8 @@ func TestAccessAbsentConfig(t *testing.T) { config := &Configuration{} assert.Equal(t, "none", config.Access("download")) assert.Equal(t, "none", config.Access("upload")) - assert.Equal(t, false, config.PrivateAccess("download")) - assert.Equal(t, false, config.PrivateAccess("upload")) + assert.False(t, config.PrivateAccess("download")) + assert.False(t, config.PrivateAccess("upload")) } func TestLoadValidExtension(t *testing.T) { @@ -481,10 +481,10 @@ func TestFetchPruneConfigDefault(t *testing.T) { assert.Equal(t, 7, fp.FetchRecentRefsDays) assert.Equal(t, 0, fp.FetchRecentCommitsDays) assert.Equal(t, 3, fp.PruneOffsetDays) - assert.Equal(t, true, fp.FetchRecentRefsIncludeRemotes) + assert.True(t, fp.FetchRecentRefsIncludeRemotes) assert.Equal(t, 3, fp.PruneOffsetDays) assert.Equal(t, "origin", fp.PruneRemoteName) - assert.Equal(t, false, fp.PruneVerifyRemoteAlways) + assert.False(t, fp.PruneVerifyRemoteAlways) } func TestFetchPruneConfigCustom(t *testing.T) { @@ -502,8 +502,8 @@ func TestFetchPruneConfigCustom(t *testing.T) { assert.Equal(t, 12, fp.FetchRecentRefsDays) assert.Equal(t, 9, fp.FetchRecentCommitsDays) - assert.Equal(t, false, fp.FetchRecentRefsIncludeRemotes) + assert.False(t, fp.FetchRecentRefsIncludeRemotes) assert.Equal(t, 30, fp.PruneOffsetDays) assert.Equal(t, "upstream", fp.PruneRemoteName) - assert.Equal(t, true, fp.PruneVerifyRemoteAlways) + assert.True(t, fp.PruneVerifyRemoteAlways) } diff --git a/config/extension_test.go b/config/extension_test.go index bc8c5d25..56b3a03f 100644 --- a/config/extension_test.go +++ b/config/extension_test.go @@ -3,7 +3,7 @@ package config import ( "testing" - "github.com/github/git-lfs/vendor/_nuts/github.com/technoweenie/assert" + "github.com/stretchr/testify/assert" ) func TestSortExtensions(t *testing.T) { @@ -32,7 +32,7 @@ func TestSortExtensions(t *testing.T) { sorted, err := SortExtensions(m) - assert.Equal(t, err, nil) + assert.Nil(t, err) for i, ext := range sorted { name := names[i] @@ -61,6 +61,6 @@ func TestSortExtensionsDuplicatePriority(t *testing.T) { sorted, err := SortExtensions(m) - assert.NotEqual(t, err, nil) - assert.Equal(t, len(sorted), 0) + assert.NotNil(t, err) + assert.Empty(t, sorted) } diff --git a/config/filesystem.go b/config/filesystem.go index d40b2d6c..f89d5454 100644 --- a/config/filesystem.go +++ b/config/filesystem.go @@ -9,7 +9,7 @@ import ( "github.com/github/git-lfs/git" "github.com/github/git-lfs/tools" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" + "github.com/rubyist/tracerx" ) var ( diff --git a/debian/rules b/debian/rules index 85555c35..a1c8302c 100755 --- a/debian/rules +++ b/debian/rules @@ -1,7 +1,7 @@ #!/usr/bin/make -f export DH_OPTIONS -export GO15VENDOREXPERIMENT=0 +export GO15VENDOREXPERIMENT=1 #dh_golang doesn't do this for you ifeq ($(DEB_HOST_ARCH), i386) @@ -25,7 +25,7 @@ override_dh_clean: override_dh_auto_build: dh_auto_build - #dh_golang doesn't do anything here in deb 8, and it's needed in both + #dh_golang doesn't do anything here in deb 8, and it's needed in both if [ "$(DEB_HOST_GNU_TYPE)" != "$(DEB_BUILD_GNU_TYPE)" ]; then\ cp -rf $(BUILD_DIR)/bin/*/* $(BUILD_DIR)/bin/; \ cp -rf $(BUILD_DIR)/pkg/*/* $(BUILD_DIR)/pkg/; \ diff --git a/docs/proposals/locking.md b/docs/proposals/locking.md new file mode 100644 index 00000000..50575819 --- /dev/null +++ b/docs/proposals/locking.md @@ -0,0 +1,315 @@ +# Locking feature proposal + +We need the ability to lock files to discourage (we can never prevent) parallel +editing of binary files which will result in an unmergeable situation. This is +not a common theme in git (for obvious reasons, it conflicts with its +distributed, parallel nature), but is a requirement of any binary management +system, since files are very often completely unmergeable, and no-one likes +having to throw their work away & do it again. + +## What not to do: single branch model + +The simplest way to organise locking is to require that if binary files are only +ever edited on a single branch, and therefore editing this file can follow a +simple sequence: + +1. File starts out read-only locally +2. User locks the file, user is required to have the latest version locally from + the 'main' branch +3. User edits file & commits 1 or more times +4. User pushes these commits to the main branch +5. File is unlocked (and made read only locally again) + +## A more usable approach: multi-branch model + +In practice teams need to work on more than one branch, and sometimes that work +will have corresponding binary edits. + +It's important to remember that the core requirement is to prevent *unintended +parallel edits of an unmergeable file*. + +One way to address this would be to say that locking a file locks it across all +branches, and that lock is only released when the branch where the edit is is +merged back into a 'primary' branch. The problem is that although that allows +branching and also prevents merge conflicts, it forces merging of feature +branches before a further edit can be made by someone else. + +An alternative is that locking a file locks it across all branches, but when the +lock is released, further locks on that file can only be taken on a descendant +of the latest edit that has been made, whichever branch it is on. That means +a change to the rules of the lock sequence, namely: + +1. File starts out read-only locally +2. User tries to lock a file. This is only allowed if: + * The file is not already locked by anyone else, AND + * One of the following are true: + * The user has, or agrees to check out, a descendant of the latest commit + that was made for that file, whatever branch that was on, OR + * The user stays on their current commit but resets the locked file to the + state of the latest commit (making it modified locally, and + also cherry-picking changes for that file in practice). +3. User edits file & commits 1 or more times, on any branch they like +4. User pushes the commits +5. File is unlocked if: + * the latest commit to that file has been pushed (on any branch), and + * the file is not locally edited + +This means that long-running branches can be maintained but that editing of a +binary file must always incorporate the latest binary edits. This means that if +this system is always respected, there is only ever one linear stream of +development for this binary file, even though that 'thread' may wind its way +across many different branches in the process. + +This does mean that no-one's changes are accidentally lost, but it does mean +that we are either making new branches dependent on others, OR we're +cherry-picking changes to individual files across branches. This does change +the traditional git workflow, but importantly it achieves the core requirement +of never *accidentally* losing anyone's changes. How changes are threaded +across branches is always under the user's control. + +## Breaking the rules +We must allow the user to break the rules if they know what they are doing. +Locking is there to prevent unintended binary merge conflicts, but sometimes you +might want to intentionally create one, with the full knowledge that you're +going to have to manually merge the result (or more likely, pick one side and +discard the other) later down the line. There are 2 cases of rule breaking to +support: + +1. **Break someone else's lock** + People lock files and forget they've locked them, then go on holiday, or + worse, leave the company. You can't be stuck not being able to edit that file + so must be able to forcibly break someone else's lock. Ideally this should + result in some kind of notification to the original locker (might need to be a + special value-add on BB/Stash). This effectively removes the other person's + lock and is likely to cause them problems if they had edited and try to push + next time. + +2. **Allow a parallel lock** + Actually similar to breaking someone else's lock, except it lets you take + another lock on a file in parallel, leaving their lock in place too, and + knowing that you're going to have to resolve the merge problem later. You + could handle this just by manually making files read/write, then using 'force + push' to override hooks that prevent pushing when not locked. However by + explicitly registering a parallel lock (possible form: 'git lfs lock + --force') this could be recorded and communicated to anyone else with a lock, + letting them know about possible merge issues down the line. + +## Detailed feature points +|No | Feature | Notes +|---|---------|------------------ +|1 |Lock server must be available at same API URL| +|2 |Identify unmergeable files as subset of lfs files|`git lfs track -b` ? +|3 |Make unmergeable files read-only on checkout|Perform in smudge filter +|4 |Lock a file
  • Check with server which must atomically check/set
  • Check person requesting the lock is checked out on a commit which is a descendent of the last edit of that file (locally or on server, although last lock shouldn't have been released until push anyway), or allow --force to break rule
  • Record lock on server
  • Make file read/write locally if success
|`git lfs lock `? +|5 |Release a lock
  • Check if locally modified, if so must discard
  • Check if user has more recent commit of this file than server, if so must push first
  • Release lock on server atomically
  • Make local file read-only
|`git lfs unlock `? +|6 |Break a lock, ie override someone else's lock and take it yourself.
  • Release lock on server atomically
  • Proceed as per 'Lock a file'
  • Notify original lock holder HOW?
|`git lfs lock -break `? +|7 |Release lock on reset (maybe). Configurable option / prompt? May be resetting just to start editing again| +|8 |Release lock on push (maybe, if unmodified). See above| +|9 |Cater for read-only binary files when merging locally
  • Because files are read-only this might prevent merge from working when actually it's valid.
  • Always fine to merge the latest version of a binary file to anywhere else
  • Fine to merge the non-latest version if user is aware that this may cause merge problems (see Breaking the rules)
  • Therefore this feature is about dealing with the read-only flag and issuing a warning if not the latest
| +|10 |List current locks
  • That the current user has
  • That anyone has
  • Potentially scoped to folder
|`git lfs lock --list [paths...]` +|11 |Reject a push containing a binary file currently locked by someone else|pre-receive hook on server, allow --force to override (i.e. existing parameter to git push) + +## Implementation details +### Types +To make the implementing locking on the lfs-test-server as well as other servers +in the future easier, it makes sense to create a `lock` package that can be +depended upon from any server. This will go along with Steve's refactor which +touches the `lfs` package quite a bit. + +Below are enumerated some of the types that will presumably land in this +sub-package. + +```go +// Lock represents a single lock that against a particular path. +// +// Locks returned from the API may or may not be currently active, according to +// the Expired flag. +type Lock struct { + // Id is the unique identifier corresponding to this particular Lock. It + // must be consistent with the local copy, and the server's copy. + Id string `json:"id"` + // Path is an absolute path to the file that is locked as a part of this + // lock. + Path string `json:"path"` + // Committer is the author who initiated this lock. + Committer struct { + Name string `json:"name"` + Email string `json:"email"` + } `json:"creator"` + // CommitSHA is the commit that this Lock was created against. It is + // strictly equal to the SHA of the minimum commit negotiated in order + // to create this lock. + CommitSHA string `json:"commit_sha" + // LockedAt is a required parameter that represents the instant in time + // that this lock was created. For most server implementations, this + // should be set to the instant at which the lock was initially + // received. + LockedAt time.Time `json:"locked_at"` + // ExpiresAt is an optional parameter that represents the instant in + // time that the lock stopped being active. If the lock is still active, + // the server can either a) not send this field, or b) send the + // zero-value of time.Time. + UnlockedAt time.Time `json:"unlocked_at,omitempty"` +} + +// Active returns whether or not the given lock is still active against the file +// that it is protecting. +func (l *Lock) Active() bool { + return time.IsZero(l.UnlockedAt) +} +``` + +### Proposed Commands + +#### `git lfs lock ` + +The `lock` command will be used in accordance with the multi-branch flow as +proposed above to request that lock be granted to the specific path passed an +argument to the command. + +```go +// LockRequest encapsulates the payload sent across the API when a client would +// like to obtain a lock against a particular path on a given remote. +type LockRequest struct { + // Path is the path that the client would like to obtain a lock against. + Path string `json:"path"` + // LatestRemoteCommit is the SHA of the last known commit from the + // remote that we are trying to create the lock against, as found in + // `.git/refs/origin/`. + LatestRemoteCommit string `json:"latest_remote_commit"` + // Committer is the individual that wishes to obtain the lock. + Committer struct { + // Name is the name of the individual who would like to obtain the + // lock, for instance: "Rick Olson". + Name string `json:"name"` + // Email is the email assopsicated with the individual who would + // like to obtain the lock, for instance: "rick@github.com". + Email string `json:"email"` + } `json:"committer"` +} +``` + +```go +// LockResponse encapsulates the information sent over the API in response to +// a `LockRequest`. +type LockResponse struct { + // Lock is the Lock that was optionally created in response to the + // payload that was sent (see above). If the lock already exists, then + // the existing lock is sent in this field instead, and the author of + // that lock remains the same, meaning that the client failed to obtain + // that lock. An HTTP status of "409 - Conflict" is used here. + // + // If the lock was unable to be created, this field will hold the + // zero-value of Lock and the Err field will provide a more detailed set + // of information. + // + // If an error was experienced in creating this lock, then the + // zero-value of Lock should be sent here instead. + Lock Lock `json:"lock"` + // CommitNeeded holds the minimum commit SHA that client must have to + // obtain the lock. + CommitNeeded string `json:"commit_needed"` + // Err is the optional error that was encountered while trying to create + // the above lock. + Err error `json:"error,omitempty"` +} +``` + + +#### `git lfs unlock ` + +The `unlock` command is responsible for releasing the lock against a particular +file. The command takes a `` argument which the LFS client will have to +internally resolve into a Id to unlock. + +The API associated with this command can also be used on the server to remove +existing locks after a push. + +```go +// An UnlockRequest is sent by the client over the API when they wish to remove +// a lock associated with the given Id. +type UnlockRequest struct { + // Id is the identifier of the lock that the client wishes to remove. + Id string `json:"id"` +} +``` + +```go +// UnlockResult is the result sent back from the API when asked to remove a +// lock. +type UnlockResult struct { + // Lock is the lock corresponding to the asked-about lock in the + // `UnlockPayload` (see above). If no matching lock was found, this + // field will take the zero-value of Lock, and Err will be non-nil. + Lock Lock `json:"lock"` + // Err is an optional field which holds any error that was experienced + // while removing the lock. + Err error `json:"error,omitempty"` +} +``` + +Clients can determine whether or not their lock was removed by calling the +`Active()` method on the returned Lock, if `UnlockResult.Err` is nil. + +#### `git lfs locks (-r |-b )|(-i id)` + +For many operations, the LFS client will need to have knowledge of existing +locks on the server. Additionally, the client should not have to self-sort/index +this (potentially) large set. To remove this need, both the `locks` command and +corresponding API method take several filters. + +Clients should turn the flag-values that were passed during the command +invocation into `Filter`s as described below, and batched up into the `Filters` +field in the `LockListRequest`. + +```go +// Property is a constant-type that narrows fields pertaining to the server's +// Locks. +type Property string + +const ( + Branch Property = "branch" + Id Property = "id" + // (etc) ... +) + +// LockListRequest encapsulates the request sent to the server when the client +// would like a list of locks that match the given criteria. +type LockListRequest struct { + // Filters is the set of filters to query against. If the client wishes + // to obtain a list of all locks, an empty array should be passed here. + Filters []{ + // Prop is the property to search against. + Prop Property `json:"prop"` + // Value is the value that the property must take. + Value string `json:"value"` + } `json:"filters"` + // Cursor is an optional field used to tell the server which lock was + // seen last, if scanning through multiple pages of results. + // + // Servers must return a list of locks sorted in reverse chronological + // order, so the Cursor provides a consistent method of viewing all + // locks, even if more were created between two requests. + Cursor string `json:"cursor,omitempty"` + // Limit is the maximum number of locks to return in a single page. + Limit int `json:"limit"` +} +``` + +```go +// LockList encapsulates a set of Locks. +type LockList struct { + // Locks is the set of locks returned back, typically matching the query + // parameters sent in the LockListRequest call. If no locks were matched + // from a given query, then `Locks` will be represented as an empty + // array. + Locks []Lock `json:"locks"` + // NextCursor returns the Id of the Lock the client should update its + // cursor to, if there are multiple pages of results for a particular + // `LockListRequest`. + NextCursor string `json:"next_cursor,omitempty"` + // Err populates any error that was encountered during the search. If no + // error was encountered and the operation was succesful, then a value + // of nil will be passed here. + Err error `json:"error,omitempty"` +} diff --git a/docs/proposals/locking_api.md b/docs/proposals/locking_api.md new file mode 100644 index 00000000..ad469085 --- /dev/null +++ b/docs/proposals/locking_api.md @@ -0,0 +1,180 @@ +# Locking API proposal + +## POST /locks + +| Method | Accept | Content-Type | Authorization | +|---------|--------------------------------|--------------------------------|---------------| +| `POST` | `application/vnd.git-lfs+json` | `application/vnd.git-lfs+json` | Basic | + +### Request + +``` +> GET https://git-lfs-server.com/locks +> Accept: application/vnd.git-lfs+json +> Authorization: Basic +> Content-Type: application/vnd.git-lfs+json +> +> { +> path: "/path/to/file", +> remote: "origin", +> latest_remote_commit: "d3adbeef", +> committer: { +> name: "Jane Doe", +> email: "jane@example.com" +> } +> } +``` + +### Response + +* **Successful response** +``` +< HTTP/1.1 201 Created +< Content-Type: application/vnd.git-lfs+json +< +< { +< lock: { +< id: "some-uuid", +< path: "/path/to/file", +< committer: { +< name: "Jane Doe", +< email: "jane@example.com" +< }, +< commit_sha: "d3adbeef", +< locked_at: "2016-05-17T15:49:06+00:00" +< } +< } +``` + +* **Bad request: minimum commit not met** +``` +< HTTP/1.1 400 Bad request +< Content-Type: application/vnd.git-lfs+json +< +< { +< "commit_needed": "other_sha" +< } +``` + +* **Bad request: lock already present** +``` +< HTTP/1.1 409 Conflict +< Content-Type: application/vnd.git-lfs+json +< +< { +< lock: { +< /* the previously created lock */ +< }, +< error: "already created lock" +< } +``` + +* **Bad repsonse: server error** +``` +< HTTP/1.1 500 Internal server error +< Content-Type: application/vnd.git-lfs+json +< +< { +< error: "unable to create lock" +< } +``` + +## POST /locks/:id/unlock + +| Method | Accept | Content-Type | Authorization | +|---------|--------------------------------|--------------|---------------| +| `POST` | `application/vnd.git-lfs+json` | None | Basic | + +### Request + +``` +> POST https://git-lfs-server.com/locks/:id/unlock +> Accept: application/vnd.git-lfs+json +> Authorization: Basic +``` + +### Repsonse + +* **Success: unlocked** +``` +< HTTP/1.1 200 Ok +< Content-Type: application/vnd.git-lfs+json +< +< { +< lock: { +< id: "some-uuid", +< path: "/path/to/file", +< committer: { +< name: "Jane Doe", +< email: "jane@example.com" +< }, +< commit_sha: "d3adbeef", +< locked_at: "2016-05-17T15:49:06+00:00", +< unlocked_at: "2016-05-17T15:49:06+00:00" +< } +< } +} +``` + +* **Bad response: server error** +``` +< HTTP/1.1 500 Internal error +< Content-Type: application/vnd.git-lfs+json +< +< { +< error: "github/git-lfs: internal server error" +< } +``` + +## GET /locks + +| Method | Accept | Content-Type | Authorization | +|--------|-------------------------------|--------------|---------------| +| `GET` | `application/vnd.git-lfs+json | None | Basic | + +### Request + +``` +> GET https://git-lfs-server.com/locks?filters...&cursor=&limit= +> Accept: application/vnd.git-lfs+json +> Authorization: Basic +``` + +### Response + +* **Success: locks found** + +Note: no matching locks yields a payload of `locks: []`, and a status of 200. + +``` +< HTTP/1.1 200 Ok +< Content-Type: application/vnd.git-lfs+json +< +< { +< locks: [ +< { +< id: "some-uuid", +< path: "/path/to/file", +< committer": { +< name: "Jane Doe", +< email: "jane@example.com" +< }, +< commit_sha: "1ec245f", +< locked_at: "2016-05-17T15:49:06+00:00" +< } +< ], +< next_cursor: "optional-next-id", +< error: "optional error" +< } +``` + +* **Bad response: some locks may have matched, but the server encountered an error** +``` +< HTTP/1.1 500 Internal error +< Content-Type: application/vnd.git-lfs+json +< +< { +< locks: [], +< error: "github/git-lfs: internal server error" +< } +``` diff --git a/git/git.go b/git/git.go index 99c89741..1c0603fc 100644 --- a/git/git.go +++ b/git/git.go @@ -16,7 +16,7 @@ import ( "time" "github.com/github/git-lfs/subprocess" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" + "github.com/rubyist/tracerx" ) type RefType int @@ -116,7 +116,8 @@ func RemoteForCurrentBranch() (string, error) { return remote, nil } -// RemoteRefForCurrentBranch returns the full remote ref (remote/remotebranch) that the current branch is tracking +// RemoteRefForCurrentBranch returns the full remote ref (refs/remotes/{remote}/{remotebranch}) +// that the current branch is tracking. func RemoteRefNameForCurrentBranch() (string, error) { ref, err := CurrentRef() if err != nil { @@ -134,7 +135,7 @@ func RemoteRefNameForCurrentBranch() (string, error) { remotebranch := RemoteBranchForLocalBranch(ref.Name) - return remote + "/" + remotebranch, nil + return fmt.Sprintf("refs/remotes/%s/%s", remote, remotebranch), nil } // RemoteForBranch returns the remote name that a given local branch is tracking (blank if none) @@ -184,9 +185,13 @@ func LocalRefs() ([]*Ref, error) { if err != nil { return nil, fmt.Errorf("Failed to call git show-ref: %v", err) } - cmd.Start() var refs []*Ref + + if err := cmd.Start(); err != nil { + return refs, err + } + scanner := bufio.NewScanner(outp) for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) diff --git a/git/git_test.go b/git/git_test.go index 1306cb2c..7589ff2d 100644 --- a/git/git_test.go +++ b/git/git_test.go @@ -10,7 +10,7 @@ import ( . "github.com/github/git-lfs/git" "github.com/github/git-lfs/test" - "github.com/github/git-lfs/vendor/_nuts/github.com/technoweenie/assert" + "github.com/stretchr/testify/assert" ) func TestCurrentRefAndCurrentRemoteRef(t *testing.T) { @@ -51,25 +51,25 @@ func TestCurrentRefAndCurrentRemoteRef(t *testing.T) { outputs := repo.AddCommits(inputs) // last commit was on branch3 ref, err := CurrentRef() - assert.Equal(t, nil, err) + assert.Nil(t, err) assert.Equal(t, &Ref{"branch3", RefTypeLocalBranch, outputs[3].Sha}, ref) test.RunGitCommand(t, true, "checkout", "master") ref, err = CurrentRef() - assert.Equal(t, nil, err) + assert.Nil(t, err) assert.Equal(t, &Ref{"master", RefTypeLocalBranch, outputs[2].Sha}, ref) // Check remote repo.AddRemote("origin") test.RunGitCommand(t, true, "push", "-u", "origin", "master:someremotebranch") ref, err = CurrentRemoteRef() - assert.Equal(t, nil, err) + assert.Nil(t, err) assert.Equal(t, &Ref{"origin/someremotebranch", RefTypeRemoteBranch, outputs[2].Sha}, ref) refname, err := RemoteRefNameForCurrentBranch() - assert.Equal(t, nil, err) - assert.Equal(t, "origin/someremotebranch", refname) + assert.Nil(t, err) + assert.Equal(t, "refs/remotes/origin/someremotebranch", refname) remote, err := RemoteForCurrentBranch() - assert.Equal(t, nil, err) + assert.Nil(t, err) assert.Equal(t, "origin", remote) } @@ -262,19 +262,26 @@ func TestWorkTrees(t *testing.T) { } func TestVersionCompare(t *testing.T) { - assert.Equal(t, true, IsVersionAtLeast("2.6.0", "2.6.0")) - assert.Equal(t, true, IsVersionAtLeast("2.6.0", "2.6")) - assert.Equal(t, true, IsVersionAtLeast("2.6.0", "2")) - assert.Equal(t, true, IsVersionAtLeast("2.6.10", "2.6.5")) - assert.Equal(t, true, IsVersionAtLeast("2.8.1", "2.7.2")) + assert.True(t, IsVersionAtLeast("2.6.0", "2.6.0")) + assert.True(t, IsVersionAtLeast("2.6.0", "2.6")) + assert.True(t, IsVersionAtLeast("2.6.0", "2")) + assert.True(t, IsVersionAtLeast("2.6.10", "2.6.5")) + assert.True(t, IsVersionAtLeast("2.8.1", "2.7.2")) - assert.Equal(t, false, IsVersionAtLeast("1.6.0", "2")) - assert.Equal(t, false, IsVersionAtLeast("2.5.0", "2.6")) - assert.Equal(t, false, IsVersionAtLeast("2.5.0", "2.5.1")) - assert.Equal(t, false, IsVersionAtLeast("2.5.2", "2.5.10")) + assert.False(t, IsVersionAtLeast("1.6.0", "2")) + assert.False(t, IsVersionAtLeast("2.5.0", "2.6")) + assert.False(t, IsVersionAtLeast("2.5.0", "2.5.1")) + assert.False(t, IsVersionAtLeast("2.5.2", "2.5.10")) } func TestGitAndRootDirs(t *testing.T) { + repo := test.NewRepo(t) + repo.Pushd() + defer func() { + repo.Popd() + repo.Cleanup() + }() + git, root, err := GitAndRootDirs() if err != nil { t.Fatal(err) @@ -314,25 +321,25 @@ func TestGetTrackedFiles(t *testing.T) { repo.AddCommits(inputs) tracked, err := GetTrackedFiles("*.txt") - assert.Equal(t, nil, err) + assert.Nil(t, err) sort.Strings(tracked) // for direct comparison fulllist := []string{"file1.txt", "file2.txt", "file3.txt", "file4.txt", "folder1/anotherfile.txt", "folder1/file10.txt", "folder2/folder3/deep.txt", "folder2/something.txt"} assert.Equal(t, fulllist, tracked) tracked, err = GetTrackedFiles("*file*.txt") - assert.Equal(t, nil, err) + assert.Nil(t, err) sort.Strings(tracked) sublist := []string{"file1.txt", "file2.txt", "file3.txt", "file4.txt", "folder1/anotherfile.txt", "folder1/file10.txt"} assert.Equal(t, sublist, tracked) tracked, err = GetTrackedFiles("folder1/*") - assert.Equal(t, nil, err) + assert.Nil(t, err) sort.Strings(tracked) sublist = []string{"folder1/anotherfile.txt", "folder1/file10.txt"} assert.Equal(t, sublist, tracked) tracked, err = GetTrackedFiles("folder2/*") - assert.Equal(t, nil, err) + assert.Nil(t, err) sort.Strings(tracked) sublist = []string{"folder2/folder3/deep.txt", "folder2/something.txt"} assert.Equal(t, sublist, tracked) @@ -340,7 +347,7 @@ func TestGetTrackedFiles(t *testing.T) { // relative dir os.Chdir("folder1") tracked, err = GetTrackedFiles("*.txt") - assert.Equal(t, nil, err) + assert.Nil(t, err) sort.Strings(tracked) sublist = []string{"anotherfile.txt", "file10.txt"} assert.Equal(t, sublist, tracked) @@ -350,7 +357,7 @@ func TestGetTrackedFiles(t *testing.T) { ioutil.WriteFile("z_newfile.txt", []byte("Hello world"), 0644) test.RunGitCommand(t, true, "add", "z_newfile.txt") tracked, err = GetTrackedFiles("*.txt") - assert.Equal(t, nil, err) + assert.Nil(t, err) sort.Strings(tracked) fulllist = append(fulllist, "z_newfile.txt") assert.Equal(t, fulllist, tracked) @@ -358,21 +365,21 @@ func TestGetTrackedFiles(t *testing.T) { // Test includes modified files (not staged) ioutil.WriteFile("file1.txt", []byte("Modifications"), 0644) tracked, err = GetTrackedFiles("*.txt") - assert.Equal(t, nil, err) + assert.Nil(t, err) sort.Strings(tracked) assert.Equal(t, fulllist, tracked) // Test includes modified files (staged) test.RunGitCommand(t, true, "add", "file1.txt") tracked, err = GetTrackedFiles("*.txt") - assert.Equal(t, nil, err) + assert.Nil(t, err) sort.Strings(tracked) assert.Equal(t, fulllist, tracked) // Test excludes deleted files (not committed) test.RunGitCommand(t, true, "rm", "file2.txt") tracked, err = GetTrackedFiles("*.txt") - assert.Equal(t, nil, err) + assert.Nil(t, err) sort.Strings(tracked) deletedlist := []string{"file1.txt", "file3.txt", "file4.txt", "folder1/anotherfile.txt", "folder1/file10.txt", "folder2/folder3/deep.txt", "folder2/something.txt", "z_newfile.txt"} assert.Equal(t, deletedlist, tracked) @@ -380,12 +387,38 @@ func TestGetTrackedFiles(t *testing.T) { } func TestLocalRefs(t *testing.T) { + repo := test.NewRepo(t) + repo.Pushd() + defer func() { + repo.Popd() + repo.Cleanup() + }() + + repo.AddCommits([]*test.CommitInput{ + { + Files: []*test.FileInput{ + {Filename: "file1.txt", Size: 20}, + }, + }, + { + NewBranch: "branch", + ParentBranches: []string{"master"}, + Files: []*test.FileInput{ + {Filename: "file1.txt", Size: 20}, + }, + }, + }) + + test.RunGitCommand(t, true, "tag", "v1") + refs, err := LocalRefs() if err != nil { t.Fatal(err) } + actual := make(map[string]bool) for _, r := range refs { + t.Logf("REF: %s", r.Name) switch r.Type { case RefTypeHEAD: t.Errorf("Local HEAD ref: %v", r) @@ -393,6 +426,22 @@ func TestLocalRefs(t *testing.T) { t.Errorf("Stash or unknown ref: %v", r) case RefTypeRemoteBranch, RefTypeRemoteTag: t.Errorf("Remote ref: %v", r) + default: + actual[r.Name] = true } } + + expected := []string{"master", "branch", "v1"} + found := 0 + for _, refname := range expected { + if actual[refname] { + found += 1 + } else { + t.Errorf("could not find ref %q", refname) + } + } + + if found != len(expected) { + t.Errorf("Unexpected local refs: %v", actual) + } } diff --git a/glide.lock b/glide.lock new file mode 100644 index 00000000..4eaaa5a9 --- /dev/null +++ b/glide.lock @@ -0,0 +1,40 @@ +hash: 275cba8ff30fe108a79618e8ad803f600136572260dc78a7d879bd248b3bdbdb +updated: 2016-05-25T10:47:36.829238548-06:00 +imports: +- name: github.com/bgentry/go-netrc + version: 9fd32a8b3d3d3f9d43c341bfe098430e07609480 + subpackages: + - netrc +- name: github.com/cheggaaa/pb + version: bd14546a551971ae7f460e6d6e527c5b56cd38d7 +- name: github.com/inconshreveable/mousetrap + version: 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 +- name: github.com/kr/pretty + version: 088c856450c08c03eb32f7a6c221e6eefaa10e6f +- name: github.com/kr/pty + version: 5cf931ef8f76dccd0910001d74a58a7fca84a83d +- name: github.com/kr/text + version: 6807e777504f54ad073ecef66747de158294b639 +- name: github.com/olekukonko/ts + version: ecf753e7c962639ab5a1fb46f7da627d4c0a04b8 +- name: github.com/rubyist/tracerx + version: d7bcc0bc315bed2a841841bee5dbecc8d7d7582f +- name: github.com/spf13/cobra + version: c55cdf33856a08e4822738728b41783292812889 +- name: github.com/spf13/pflag + version: 580b9be06c33d8ba9dcc8757ea56b7642472c2f5 +- name: github.com/stretchr/testify + version: 6cb3b85ef5a0efef77caef88363ec4d4b5c0976d +- name: github.com/technoweenie/go-contentaddressable + version: 38171def3cd15e3b76eb156219b3d48704643899 +- name: github.com/ThomsonReutersEikon/go-ntlm + version: b00ec39bbdd04f845950f4dbb4fd0a2c3155e830 + subpackages: + - ntlm +- name: github.com/xeipuuv/gojsonpointer + version: e0fe6f68307607d540ed8eac07a342c33fa1b54a +- name: github.com/xeipuuv/gojsonreference + version: e02fc20de94c78484cd5ffb007f8af96be030a45 +- name: github.com/xeipuuv/gojsonschema + version: d5336c75940ef31c9ceeb0ae64cf92944bccb4ee +devImports: [] diff --git a/glide.yaml b/glide.yaml new file mode 100644 index 00000000..671f084c --- /dev/null +++ b/glide.yaml @@ -0,0 +1,39 @@ +package: github.com/github/git-lfs +import: +- package: github.com/bgentry/go-netrc + version: 9fd32a8b3d3d3f9d43c341bfe098430e07609480 + subpackages: + - netrc +- package: github.com/cheggaaa/pb + version: bd14546a551971ae7f460e6d6e527c5b56cd38d7 +- package: github.com/kr/pretty + version: 088c856450c08c03eb32f7a6c221e6eefaa10e6f +- package: github.com/kr/pty + version: 5cf931ef8f76dccd0910001d74a58a7fca84a83d +- package: github.com/kr/text + version: 6807e777504f54ad073ecef66747de158294b639 +- package: github.com/inconshreveable/mousetrap + version: 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 +- package: github.com/olekukonko/ts + version: ecf753e7c962639ab5a1fb46f7da627d4c0a04b8 +- package: github.com/rubyist/tracerx + version: d7bcc0bc315bed2a841841bee5dbecc8d7d7582f +- package: github.com/spf13/cobra + version: c55cdf33856a08e4822738728b41783292812889 +- package: github.com/spf13/pflag + version: 580b9be06c33d8ba9dcc8757ea56b7642472c2f5 +- package: github.com/stretchr/testify + version: 6cb3b85ef5a0efef77caef88363ec4d4b5c0976d +- package: github.com/ThomsonReutersEikon/go-ntlm + version: b00ec39bbdd04f845950f4dbb4fd0a2c3155e830 + # go-ntlm includes a util/ directory, which was removed + subpackages: + - ntlm +- package: github.com/technoweenie/go-contentaddressable + version: 38171def3cd15e3b76eb156219b3d48704643899 +- package: github.com/xeipuuv/gojsonpointer + version: e0fe6f68307607d540ed8eac07a342c33fa1b54a +- package: github.com/xeipuuv/gojsonreference + version: e02fc20de94c78484cd5ffb007f8af96be030a45 +- package: github.com/xeipuuv/gojsonschema + version: d5336c75940ef31c9ceeb0ae64cf92944bccb4ee diff --git a/httputil/certs.go b/httputil/certs.go index 760ea654..03b5cbb3 100644 --- a/httputil/certs.go +++ b/httputil/certs.go @@ -7,7 +7,7 @@ import ( "path/filepath" "github.com/github/git-lfs/config" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" + "github.com/rubyist/tracerx" ) // isCertVerificationDisabledForHost returns whether SSL certificate verification diff --git a/httputil/certs_darwin.go b/httputil/certs_darwin.go index 8f6dbaef..75eb88a6 100644 --- a/httputil/certs_darwin.go +++ b/httputil/certs_darwin.go @@ -6,7 +6,7 @@ import ( "strings" "github.com/github/git-lfs/subprocess" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" + "github.com/rubyist/tracerx" ) func appendRootCAsForHostFromPlatform(pool *x509.CertPool, host string) *x509.CertPool { diff --git a/httputil/certs_test.go b/httputil/certs_test.go index 1f5771d0..5d98af80 100644 --- a/httputil/certs_test.go +++ b/httputil/certs_test.go @@ -1,14 +1,13 @@ package httputil import ( - "crypto/x509" "io/ioutil" "os" "path/filepath" "testing" "github.com/github/git-lfs/config" - "github.com/github/git-lfs/vendor/_nuts/github.com/technoweenie/assert" + "github.com/stretchr/testify/assert" ) var testCert = `-----BEGIN CERTIFICATE----- @@ -39,11 +38,11 @@ func TestCertFromSSLCAInfoConfig(t *testing.T) { defer config.Config.ResetConfig() tempfile, err := ioutil.TempFile("", "testcert") - assert.Equal(t, nil, err, "Error creating temp cert file") + assert.Nil(t, err, "Error creating temp cert file") defer os.Remove(tempfile.Name()) _, err = tempfile.WriteString(testCert) - assert.Equal(t, nil, err, "Error writing temp cert file") + assert.Nil(t, err, "Error writing temp cert file") tempfile.Close() config.Config.ClearConfig() @@ -51,15 +50,15 @@ func TestCertFromSSLCAInfoConfig(t *testing.T) { // Should match pool := getRootCAsForHost("git-lfs.local") - assert.NotEqual(t, (*x509.CertPool)(nil), pool) + assert.NotNil(t, pool) // Shouldn't match pool = getRootCAsForHost("wronghost.com") - assert.Equal(t, (*x509.CertPool)(nil), pool) + assert.Nil(t, pool) // Ports have to match pool = getRootCAsForHost("git-lfs.local:8443") - assert.Equal(t, (*x509.CertPool)(nil), pool) + assert.Nil(t, pool) // Now use global sslcainfo config.Config.ClearConfig() @@ -67,22 +66,22 @@ func TestCertFromSSLCAInfoConfig(t *testing.T) { // Should match anything pool = getRootCAsForHost("git-lfs.local") - assert.NotEqual(t, (*x509.CertPool)(nil), pool) + assert.NotNil(t, pool) pool = getRootCAsForHost("wronghost.com") - assert.NotEqual(t, (*x509.CertPool)(nil), pool) + assert.NotNil(t, pool) pool = getRootCAsForHost("git-lfs.local:8443") - assert.NotEqual(t, (*x509.CertPool)(nil), pool) + assert.NotNil(t, pool) } func TestCertFromSSLCAInfoEnv(t *testing.T) { tempfile, err := ioutil.TempFile("", "testcert") - assert.Equal(t, nil, err, "Error creating temp cert file") + assert.Nil(t, err, "Error creating temp cert file") defer os.Remove(tempfile.Name()) _, err = tempfile.WriteString(testCert) - assert.Equal(t, nil, err, "Error writing temp cert file") + assert.Nil(t, err, "Error writing temp cert file") tempfile.Close() oldEnv := config.Config.GetAllEnv() @@ -93,11 +92,11 @@ func TestCertFromSSLCAInfoEnv(t *testing.T) { // Should match any host at all pool := getRootCAsForHost("git-lfs.local") - assert.NotEqual(t, (*x509.CertPool)(nil), pool) + assert.NotNil(t, pool) pool = getRootCAsForHost("wronghost.com") - assert.NotEqual(t, (*x509.CertPool)(nil), pool) + assert.NotNil(t, pool) pool = getRootCAsForHost("notthisone.com:8888") - assert.NotEqual(t, (*x509.CertPool)(nil), pool) + assert.NotNil(t, pool) } @@ -105,33 +104,33 @@ func TestCertFromSSLCAPathConfig(t *testing.T) { defer config.Config.ResetConfig() tempdir, err := ioutil.TempDir("", "testcertdir") - assert.Equal(t, nil, err, "Error creating temp cert dir") + assert.Nil(t, err, "Error creating temp cert dir") defer os.RemoveAll(tempdir) err = ioutil.WriteFile(filepath.Join(tempdir, "cert1.pem"), []byte(testCert), 0644) - assert.Equal(t, nil, err, "Error creating cert file") + assert.Nil(t, err, "Error creating cert file") config.Config.ClearConfig() config.Config.SetConfig("http.sslcapath", tempdir) // Should match any host at all pool := getRootCAsForHost("git-lfs.local") - assert.NotEqual(t, (*x509.CertPool)(nil), pool) + assert.NotNil(t, pool) pool = getRootCAsForHost("wronghost.com") - assert.NotEqual(t, (*x509.CertPool)(nil), pool) + assert.NotNil(t, pool) pool = getRootCAsForHost("notthisone.com:8888") - assert.NotEqual(t, (*x509.CertPool)(nil), pool) + assert.NotNil(t, pool) } func TestCertFromSSLCAPathEnv(t *testing.T) { tempdir, err := ioutil.TempDir("", "testcertdir") - assert.Equal(t, nil, err, "Error creating temp cert dir") + assert.Nil(t, err, "Error creating temp cert dir") defer os.RemoveAll(tempdir) err = ioutil.WriteFile(filepath.Join(tempdir, "cert1.pem"), []byte(testCert), 0644) - assert.Equal(t, nil, err, "Error creating cert file") + assert.Nil(t, err, "Error creating cert file") oldEnv := config.Config.GetAllEnv() defer func() { @@ -141,17 +140,17 @@ func TestCertFromSSLCAPathEnv(t *testing.T) { // Should match any host at all pool := getRootCAsForHost("git-lfs.local") - assert.NotEqual(t, (*x509.CertPool)(nil), pool) + assert.NotNil(t, pool) pool = getRootCAsForHost("wronghost.com") - assert.NotEqual(t, (*x509.CertPool)(nil), pool) + assert.NotNil(t, pool) pool = getRootCAsForHost("notthisone.com:8888") - assert.NotEqual(t, (*x509.CertPool)(nil), pool) + assert.NotNil(t, pool) } func TestCertVerifyDisabledGlobalEnv(t *testing.T) { - assert.Equal(t, false, isCertVerificationDisabledForHost("anyhost.com")) + assert.False(t, isCertVerificationDisabledForHost("anyhost.com")) oldEnv := config.Config.GetAllEnv() defer func() { @@ -159,29 +158,29 @@ func TestCertVerifyDisabledGlobalEnv(t *testing.T) { }() config.Config.SetAllEnv(map[string]string{"GIT_SSL_NO_VERIFY": "1"}) - assert.Equal(t, true, isCertVerificationDisabledForHost("anyhost.com")) + assert.True(t, isCertVerificationDisabledForHost("anyhost.com")) } func TestCertVerifyDisabledGlobalConfig(t *testing.T) { defer config.Config.ResetConfig() - assert.Equal(t, false, isCertVerificationDisabledForHost("anyhost.com")) + assert.False(t, isCertVerificationDisabledForHost("anyhost.com")) config.Config.ClearConfig() config.Config.SetConfig("http.sslverify", "false") - assert.Equal(t, true, isCertVerificationDisabledForHost("anyhost.com")) + assert.True(t, isCertVerificationDisabledForHost("anyhost.com")) } func TestCertVerifyDisabledHostConfig(t *testing.T) { defer config.Config.ResetConfig() - assert.Equal(t, false, isCertVerificationDisabledForHost("specifichost.com")) - assert.Equal(t, false, isCertVerificationDisabledForHost("otherhost.com")) + assert.False(t, isCertVerificationDisabledForHost("specifichost.com")) + assert.False(t, isCertVerificationDisabledForHost("otherhost.com")) config.Config.ClearConfig() config.Config.SetConfig("http.https://specifichost.com/.sslverify", "false") - assert.Equal(t, true, isCertVerificationDisabledForHost("specifichost.com")) - assert.Equal(t, false, isCertVerificationDisabledForHost("otherhost.com")) + assert.True(t, isCertVerificationDisabledForHost("specifichost.com")) + assert.False(t, isCertVerificationDisabledForHost("otherhost.com")) } diff --git a/httputil/http.go b/httputil/http.go index 54c896a9..26f894e4 100644 --- a/httputil/http.go +++ b/httputil/http.go @@ -19,7 +19,7 @@ import ( "time" "github.com/github/git-lfs/config" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" + "github.com/rubyist/tracerx" ) type httpTransferStats struct { diff --git a/httputil/ntlm.go b/httputil/ntlm.go index 8d081717..712b2638 100644 --- a/httputil/ntlm.go +++ b/httputil/ntlm.go @@ -12,9 +12,9 @@ import ( "strings" "sync/atomic" + "github.com/ThomsonReutersEikon/go-ntlm/ntlm" "github.com/github/git-lfs/auth" "github.com/github/git-lfs/config" - "github.com/github/git-lfs/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm" ) func ntlmClientSession(c *config.Configuration, creds auth.Creds) (ntlm.ClientSession, error) { diff --git a/httputil/ntlm_test.go b/httputil/ntlm_test.go index 1f4e51f9..dbb6468f 100644 --- a/httputil/ntlm_test.go +++ b/httputil/ntlm_test.go @@ -10,7 +10,7 @@ import ( "github.com/github/git-lfs/auth" "github.com/github/git-lfs/config" - "github.com/github/git-lfs/vendor/_nuts/github.com/technoweenie/assert" + "github.com/stretchr/testify/assert" ) func TestNtlmClientSession(t *testing.T) { @@ -20,12 +20,12 @@ func TestNtlmClientSession(t *testing.T) { creds := auth.Creds{"username": "MOOSEDOMAIN\\canadian", "password": "MooseAntlersYeah"} _, err := ntlmClientSession(config.Config, creds) - assert.Equal(t, err, nil) + assert.Nil(t, err) //The second call should ignore creds and give the session we just created. badCreds := auth.Creds{"username": "badusername", "password": "MooseAntlersYeah"} _, err = ntlmClientSession(config.Config, badCreds) - assert.Equal(t, err, nil) + assert.Nil(t, err) //clean up config.Config.NtlmSession = nil @@ -38,7 +38,7 @@ func TestNtlmClientSessionBadCreds(t *testing.T) { creds := auth.Creds{"username": "badusername", "password": "MooseAntlersYeah"} _, err := ntlmClientSession(config.Config, creds) - assert.NotEqual(t, err, nil) + assert.NotNil(t, err) //clean up config.Config.NtlmSession = nil @@ -47,12 +47,12 @@ func TestNtlmClientSessionBadCreds(t *testing.T) { func TestNtlmCloneRequest(t *testing.T) { req1, _ := http.NewRequest("Method", "url", nil) cloneOfReq1, err := cloneRequest(req1) - assert.Equal(t, err, nil) + assert.Nil(t, err) assertRequestsEqual(t, req1, cloneOfReq1) req2, _ := http.NewRequest("Method", "url", bytes.NewReader([]byte("Moose can be request bodies"))) cloneOfReq2, err := cloneRequest(req2) - assert.Equal(t, err, nil) + assert.Nil(t, err) assertRequestsEqual(t, req2, cloneOfReq2) } @@ -64,11 +64,11 @@ func assertRequestsEqual(t *testing.T, req1 *http.Request, req2 *http.Request) { } if req1.Body == nil { - assert.Equal(t, req2.Body, nil) + assert.Nil(t, req2.Body) } else { bytes1, _ := ioutil.ReadAll(req1.Body) bytes2, _ := ioutil.ReadAll(req2.Body) - assert.Equal(t, bytes.Compare(bytes1, bytes2), 0) + assert.Equal(t, bytes1, bytes2) } } @@ -77,8 +77,8 @@ func TestNtlmHeaderParseValid(t *testing.T) { res.Header = make(map[string][]string) res.Header.Add("Www-Authenticate", "NTLM "+base64.StdEncoding.EncodeToString([]byte("I am a moose"))) bytes, err := parseChallengeResponse(&res) - assert.Equal(t, err, nil) - assert.Equal(t, strings.HasPrefix(string(bytes), "NTLM"), false) + assert.Nil(t, err) + assert.False(t, strings.HasPrefix(string(bytes), "NTLM")) } func TestNtlmHeaderParseInvalidLength(t *testing.T) { @@ -100,7 +100,7 @@ func TestNtlmHeaderParseInvalid(t *testing.T) { res.Header = make(map[string][]string) res.Header.Add("Www-Authenticate", base64.StdEncoding.EncodeToString([]byte("NTLM I am a moose"))) _, err := parseChallengeResponse(&res) - assert.NotEqual(t, err, nil) + assert.NotNil(t, err) } func TestCloneSmallBody(t *testing.T) { diff --git a/httputil/request.go b/httputil/request.go index 9952c26d..1d9aa125 100644 --- a/httputil/request.go +++ b/httputil/request.go @@ -12,7 +12,7 @@ import ( "github.com/github/git-lfs/config" "github.com/github/git-lfs/errutil" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" + "github.com/rubyist/tracerx" ) type ClientError struct { diff --git a/lfs/batcher_test.go b/lfs/batcher_test.go index bac8fe3d..918732ea 100644 --- a/lfs/batcher_test.go +++ b/lfs/batcher_test.go @@ -3,7 +3,7 @@ package lfs import ( "testing" - "github.com/github/git-lfs/vendor/_nuts/github.com/technoweenie/assert" + "github.com/stretchr/testify/assert" ) func TestBatcherSizeMet(t *testing.T) { @@ -65,7 +65,7 @@ func runBatcherTests(cases []batcherTestCase, t *testing.T) { items := c.ItemCount for i := 0; i < c.Batches(); i++ { group := b.Next() - assert.Equal(t, c.BatchSize, len(group)) + assert.Len(t, group, c.BatchSize) items -= c.BatchSize } } diff --git a/lfs/lfs.go b/lfs/lfs.go index ca80d3df..530e8f30 100644 --- a/lfs/lfs.go +++ b/lfs/lfs.go @@ -11,7 +11,7 @@ import ( "github.com/github/git-lfs/config" "github.com/github/git-lfs/localstorage" "github.com/github/git-lfs/tools" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" + "github.com/rubyist/tracerx" ) var ( diff --git a/lfs/lfs_test.go b/lfs/lfs_test.go index 50463fb1..6f9f177e 100644 --- a/lfs/lfs_test.go +++ b/lfs/lfs_test.go @@ -7,7 +7,7 @@ import ( "github.com/github/git-lfs/lfs" "github.com/github/git-lfs/test" - "github.com/github/git-lfs/vendor/_nuts/github.com/technoweenie/assert" + "github.com/stretchr/testify/assert" ) func TestAllCurrentObjectsNone(t *testing.T) { diff --git a/lfs/pointer_smudge.go b/lfs/pointer_smudge.go index 1d7ca871..9ab047cd 100644 --- a/lfs/pointer_smudge.go +++ b/lfs/pointer_smudge.go @@ -6,15 +6,15 @@ import ( "os" "path/filepath" + "github.com/cheggaaa/pb" + "github.com/github/git-lfs/tools" "github.com/github/git-lfs/transfer" "github.com/github/git-lfs/api" "github.com/github/git-lfs/config" "github.com/github/git-lfs/errutil" "github.com/github/git-lfs/progress" - "github.com/github/git-lfs/tools" - "github.com/github/git-lfs/vendor/_nuts/github.com/cheggaaa/pb" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" + "github.com/rubyist/tracerx" ) func PointerSmudgeToFile(filename string, ptr *Pointer, download bool, cb progress.CopyCallback) error { diff --git a/lfs/pointer_test.go b/lfs/pointer_test.go index c01d5028..78585ff7 100644 --- a/lfs/pointer_test.go +++ b/lfs/pointer_test.go @@ -9,14 +9,14 @@ import ( "testing" "github.com/github/git-lfs/errutil" - "github.com/github/git-lfs/vendor/_nuts/github.com/technoweenie/assert" + "github.com/stretchr/testify/assert" ) func TestEncode(t *testing.T) { var buf bytes.Buffer pointer := NewPointer("booya", 12345, nil) _, err := EncodePointer(&buf, pointer) - assert.Equal(t, nil, err) + assert.Nil(t, err) bufReader := bufio.NewReader(&buf) assertLine(t, bufReader, "version https://git-lfs.github.com/spec/v1\n") @@ -51,7 +51,7 @@ func TestEncodeExtensions(t *testing.T) { } pointer := NewPointer("main_oid", 12345, exts) _, err := EncodePointer(&buf, pointer) - assert.Equal(t, nil, err) + assert.Nil(t, err) bufReader := bufio.NewReader(&buf) assertLine(t, bufReader, "version https://git-lfs.github.com/spec/v1\n") @@ -70,7 +70,7 @@ func TestEncodeExtensions(t *testing.T) { func assertLine(t *testing.T, r *bufio.Reader, expected string) { actual, err := r.ReadString('\n') - assert.Equal(t, nil, err) + assert.Nil(t, err) assert.Equal(t, expected, actual) } @@ -290,5 +290,5 @@ size 12345`, } func assertEqualWithExample(t *testing.T, example string, expected, actual interface{}) { - assert.Equalf(t, expected, actual, "Example:\n%s", strings.TrimSpace(example)) + assert.Equal(t, expected, actual, "Example:\n%s", strings.TrimSpace(example)) } diff --git a/lfs/scanner.go b/lfs/scanner.go index 17122e7f..ecc6967c 100644 --- a/lfs/scanner.go +++ b/lfs/scanner.go @@ -15,7 +15,7 @@ import ( "time" "github.com/github/git-lfs/git" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" + "github.com/rubyist/tracerx" ) const ( diff --git a/lfs/scanner_git_test.go b/lfs/scanner_git_test.go index 9832b371..de403aad 100644 --- a/lfs/scanner_git_test.go +++ b/lfs/scanner_git_test.go @@ -11,7 +11,7 @@ import ( . "github.com/github/git-lfs/lfs" "github.com/github/git-lfs/test" - "github.com/github/git-lfs/vendor/_nuts/github.com/technoweenie/assert" + "github.com/stretchr/testify/assert" ) func TestScanUnpushed(t *testing.T) { @@ -54,36 +54,36 @@ func TestScanUnpushed(t *testing.T) { repo.AddRemote("upstream") pointers, err := ScanUnpushed("") - assert.Equal(t, nil, err, "Should be no error calling ScanUnpushed") - assert.Equal(t, 4, len(pointers), "Should be 4 pointers because none pushed") + assert.Nil(t, err, "Should be no error calling ScanUnpushed") + assert.Len(t, pointers, 4, "Should be 4 pointers because none pushed") test.RunGitCommand(t, true, "push", "origin", "branch2") // Branch2 will have pushed 2 commits pointers, err = ScanUnpushed("") - assert.Equal(t, nil, err, "Should be no error calling ScanUnpushed") - assert.Equal(t, 2, len(pointers), "Should be 2 pointers") + assert.Nil(t, err, "Should be no error calling ScanUnpushed") + assert.Len(t, pointers, 2, "Should be 2 pointers") test.RunGitCommand(t, true, "push", "upstream", "master") // Master pushes 1 more commit pointers, err = ScanUnpushed("") - assert.Equal(t, nil, err, "Should be no error calling ScanUnpushed") - assert.Equal(t, 1, len(pointers), "Should be 1 pointer") + assert.Nil(t, err, "Should be no error calling ScanUnpushed") + assert.Len(t, pointers, 1, "Should be 1 pointer") test.RunGitCommand(t, true, "push", "origin", "branch3") // All pushed (somewhere) pointers, err = ScanUnpushed("") - assert.Equal(t, nil, err, "Should be no error calling ScanUnpushed") - assert.Equal(t, 0, len(pointers), "Should be 0 pointers unpushed") + assert.Nil(t, err, "Should be no error calling ScanUnpushed") + assert.Empty(t, pointers, "Should be 0 pointers unpushed") // Check origin pointers, err = ScanUnpushed("origin") - assert.Equal(t, nil, err, "Should be no error calling ScanUnpushed") - assert.Equal(t, 0, len(pointers), "Should be 0 pointers unpushed to origin") + assert.Nil(t, err, "Should be no error calling ScanUnpushed") + assert.Empty(t, pointers, "Should be 0 pointers unpushed to origin") // Check upstream pointers, err = ScanUnpushed("upstream") - assert.Equal(t, nil, err, "Should be no error calling ScanUnpushed") - assert.Equal(t, 2, len(pointers), "Should be 2 pointers unpushed to upstream") + assert.Nil(t, err, "Should be no error calling ScanUnpushed") + assert.Len(t, pointers, 2, "Should be 2 pointers unpushed to upstream") } func TestScanPreviousVersions(t *testing.T) { diff --git a/lfs/scanner_test.go b/lfs/scanner_test.go index 32ec4f7e..46db8834 100644 --- a/lfs/scanner_test.go +++ b/lfs/scanner_test.go @@ -4,7 +4,7 @@ import ( "strings" "testing" - "github.com/github/git-lfs/vendor/_nuts/github.com/technoweenie/assert" + "github.com/stretchr/testify/assert" ) var ( @@ -108,7 +108,7 @@ func TestParseLogOutputToPointersAdditions(t *testing.T) { for p := range pchan { pointers = append(pointers, p) } - assert.Equal(t, 5, len(pointers)) + assert.Len(t, pointers, 5) // modification, + side assert.Equal(t, "radial_1.png", pointers[0].Name) @@ -142,7 +142,7 @@ func TestParseLogOutputToPointersAdditions(t *testing.T) { for p := range pchan { pointers = append(pointers, p) } - assert.Equal(t, 1, len(pointers)) + assert.Len(t, pointers, 1) assert.Equal(t, "waveNM.png", pointers[0].Name) assert.Equal(t, "fe2c2f236b97bba4585d9909a227a8fa64897d9bbe297fa272f714302d86c908", pointers[0].Oid) assert.Equal(t, int64(125873), pointers[0].Size) @@ -158,7 +158,7 @@ func TestParseLogOutputToPointersAdditions(t *testing.T) { for p := range pchan { pointers = append(pointers, p) } - assert.Equal(t, 4, len(pointers)) + assert.Len(t, pointers, 4) assert.Equal(t, "radial_1.png", pointers[0].Name) assert.Equal(t, "3301b3da173d231f0f6b1f9bf075e573758cd79b3cfeff7623a953d708d6688b", pointers[0].Oid) assert.Equal(t, int64(3152388), pointers[0].Size) @@ -188,7 +188,7 @@ func TestParseLogOutputToPointersDeletion(t *testing.T) { pointers = append(pointers, p) } - assert.Equal(t, 4, len(pointers)) + assert.Len(t, pointers, 4) // deletion, - side assert.Equal(t, "smoke_1.png", pointers[0].Name) @@ -218,7 +218,7 @@ func TestParseLogOutputToPointersDeletion(t *testing.T) { for p := range pchan { pointers = append(pointers, p) } - assert.Equal(t, 1, len(pointers)) + assert.Len(t, pointers, 1) assert.Equal(t, "flare_1.png", pointers[0].Name) assert.Equal(t, "ea61c67cc5e8b3504d46de77212364045f31d9a023ad4448a1ace2a2fb4eed28", pointers[0].Oid) assert.Equal(t, int64(72982), pointers[0].Size) @@ -234,7 +234,7 @@ func TestParseLogOutputToPointersDeletion(t *testing.T) { for p := range pchan { pointers = append(pointers, p) } - assert.Equal(t, 3, len(pointers)) + assert.Len(t, pointers, 3) assert.Equal(t, "smoke_1.png", pointers[0].Name) assert.Equal(t, "8eb65d66303acc60062f44b44ef1f7360d7189db8acf3d066e59e2528f39514e", pointers[0].Oid) assert.Equal(t, int64(35022), pointers[0].Size) diff --git a/lfs/transfer_queue.go b/lfs/transfer_queue.go index 176ac819..47235e13 100644 --- a/lfs/transfer_queue.go +++ b/lfs/transfer_queue.go @@ -10,7 +10,7 @@ import ( "github.com/github/git-lfs/git" "github.com/github/git-lfs/progress" "github.com/github/git-lfs/transfer" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" + "github.com/rubyist/tracerx" ) const ( diff --git a/lfs/util_test.go b/lfs/util_test.go index 846e2d63..b2e776e4 100644 --- a/lfs/util_test.go +++ b/lfs/util_test.go @@ -6,7 +6,7 @@ import ( "testing" "github.com/github/git-lfs/progress" - "github.com/github/git-lfs/vendor/_nuts/github.com/technoweenie/assert" + "github.com/stretchr/testify/assert" ) func TestWriterWithCallback(t *testing.T) { @@ -26,15 +26,15 @@ func TestWriterWithCallback(t *testing.T) { readBuf := make([]byte, 3) n, err := reader.Read(readBuf) - assert.Equal(t, nil, err) + assert.Nil(t, err) assert.Equal(t, "BOO", string(readBuf[0:n])) n, err = reader.Read(readBuf) - assert.Equal(t, nil, err) + assert.Nil(t, err) assert.Equal(t, "YA", string(readBuf[0:n])) assert.Equal(t, 2, called) - assert.Equal(t, 2, len(calledRead)) + assert.Len(t, calledRead, 2) assert.Equal(t, 3, int(calledRead[0])) assert.Equal(t, 5, int(calledRead[1])) } diff --git a/localstorage/scan.go b/localstorage/scan.go index 2a97da97..8596fc0b 100644 --- a/localstorage/scan.go +++ b/localstorage/scan.go @@ -4,7 +4,7 @@ import ( "os" "path/filepath" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" + "github.com/rubyist/tracerx" ) // AllObjects returns a slice of the the objects stored in this LocalStorage diff --git a/localstorage/temp.go b/localstorage/temp.go index 2a0e2ea7..7b49613e 100644 --- a/localstorage/temp.go +++ b/localstorage/temp.go @@ -6,7 +6,7 @@ import ( "strings" "time" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" + "github.com/rubyist/tracerx" ) func (s *LocalStorage) ClearTempObjects() error { diff --git a/progress/meter.go b/progress/meter.go index 63cdd509..eb94188f 100644 --- a/progress/meter.go +++ b/progress/meter.go @@ -8,7 +8,7 @@ import ( "sync/atomic" "time" - "github.com/github/git-lfs/vendor/_nuts/github.com/olekukonko/ts" + "github.com/olekukonko/ts" ) // ProgressMeter provides a progress bar type output for the TransferQueue. It diff --git a/progress/spinner.go b/progress/spinner.go index 3af23095..02955eea 100644 --- a/progress/spinner.go +++ b/progress/spinner.go @@ -6,7 +6,7 @@ import ( "runtime" "strings" - "github.com/github/git-lfs/vendor/_nuts/github.com/olekukonko/ts" + "github.com/olekukonko/ts" ) // Indeterminate progress indicator 'spinner' diff --git a/script/bootstrap b/script/bootstrap index 3cf96be8..14ae3373 100755 --- a/script/bootstrap +++ b/script/bootstrap @@ -12,4 +12,4 @@ fi script/fmt rm -rf bin/* -GO15VENDOREXPERIMENT=0 go run script/*.go -cmd build "$@" +GO15VENDOREXPERIMENT=1 go run script/*.go -cmd build "$@" diff --git a/script/integration b/script/integration index 884dbd15..9d78d62b 100755 --- a/script/integration +++ b/script/integration @@ -46,4 +46,4 @@ parallel=${GIT_LFS_TEST_MAXPROCS:-4} echo "Running this maxprocs=$parallel" echo -GO15VENDOREXPERIMENT=0 GIT_LFS_TEST_MAXPROCS=$parallel GIT_LFS_TEST_DIR="$GIT_LFS_TEST_DIR" SHUTDOWN_LFS="no" go run script/*.go -cmd integration "$@" +GO15VENDOREXPERIMENT=1 GIT_LFS_TEST_MAXPROCS=$parallel GIT_LFS_TEST_DIR="$GIT_LFS_TEST_DIR" SHUTDOWN_LFS="no" go run script/*.go -cmd integration "$@" diff --git a/script/lint b/script/lint index 119f39f5..3ae8cd88 100755 --- a/script/lint +++ b/script/lint @@ -1,6 +1,6 @@ #!/usr/bin/env bash -deps=$(go list -f '{{join .Deps "\n"}}' . | xargs go list -f '{{if not .Standard}}{{.ImportPath}}{{end}}' | grep -v "github.com/github/git-lfs") +deps=$(GO15VENDOREXPERIMENT=1 go list -f '{{join .Deps "\n"}}' . | xargs go list -f '{{if not .Standard}}{{.ImportPath}}{{end}}' | grep -v "github.com/github/git-lfs") # exit 0 means non-vendored deps were found if [ $? -eq 0 ]; @@ -8,8 +8,8 @@ then echo "Non vendored dependencies found:" for d in $deps; do echo "\t$d"; done echo - echo "These dependencies should be tracked in 'Nut.toml', with an import prefix of:" - echo "\tgithub.com/github/git-lfs/vendor/_nuts" + echo "These dependencies should be tracked in 'glide.yaml'." + echo "Consider running "glide update" or "glide get" to vendor a new dependency." exit 1 else echo "Looks good!" diff --git a/script/release b/script/release index 5a7e6cd7..0efa6d21 100755 --- a/script/release +++ b/script/release @@ -1,3 +1,3 @@ #!/usr/bin/env bash script/fmt -GO15VENDOREXPERIMENT=0 go run script/*.go -cmd release "$@" +GO15VENDOREXPERIMENT=1 go run script/*.go -cmd release "$@" diff --git a/script/run b/script/run index 3f64f706..5348a17f 100755 --- a/script/run +++ b/script/run @@ -1,4 +1,4 @@ #!/usr/bin/env bash script/fmt commit=`git rev-parse --short HEAD` -GO15VENDOREXPERIMENT=0 go run -ldflags="-X github.com/github/git-lfs/config.GitCommit=$commit" ./git-lfs.go "$@" +GO15VENDOREXPERIMENT=1 go run -ldflags="-X github.com/github/git-lfs/config.GitCommit=$commit" ./git-lfs.go "$@" diff --git a/script/test b/script/test index 47fc65ce..72ab7259 100755 --- a/script/test +++ b/script/test @@ -1,10 +1,14 @@ #!/usr/bin/env bash -#/ Usage: script/test # run all tests +#/ Usage: script/test # run all non-vendored tests #/ script/test # run just a package's tests script/fmt if [ $# -gt 0 ]; then - GO15VENDOREXPERIMENT=0 go test "./$1" -else - GO15VENDOREXPERIMENT=0 go test ./... + GO15VENDOREXPERIMENT=1 go test "./$1" +else + GO15VENDOREXPERIMENT=1 go test \ + $(GO15VENDOREXPERIMENT=1 go list ./... \ + | grep -v "github.com/olekukonko/ts" \ + | grep -v "github.com/technoweenie/go-contentaddressable" \ + ) fi diff --git a/script/vendor b/script/vendor index 40ca9689..6c946802 100755 --- a/script/vendor +++ b/script/vendor @@ -1,2 +1,5 @@ #!/usr/bin/env bash -nut install +glide update -s -u +glide install -s -u + +rm -rf vendor/github.com/ThomsonReutersEikon/go-ntlm/utils diff --git a/subprocess/pty_nix.go b/subprocess/pty_nix.go index 217b23ff..9cd71c07 100644 --- a/subprocess/pty_nix.go +++ b/subprocess/pty_nix.go @@ -6,7 +6,7 @@ import ( "os/exec" "syscall" - "github.com/github/git-lfs/vendor/_nuts/github.com/kr/pty" + "github.com/kr/pty" ) // NewTty creates a pseudo-TTY for a command and modifies it appropriately so diff --git a/subprocess/subprocess.go b/subprocess/subprocess.go index 685e825c..826a3471 100644 --- a/subprocess/subprocess.go +++ b/subprocess/subprocess.go @@ -8,7 +8,7 @@ import ( "os/exec" "strings" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" + "github.com/rubyist/tracerx" ) // SimpleExec is a small wrapper around os/exec.Command. diff --git a/test/README.md b/test/README.md index fb48f28b..6bd9f6b8 100644 --- a/test/README.md +++ b/test/README.md @@ -67,7 +67,7 @@ There are a few environment variables that you can set to change the test suite behavior: * `GIT_LFS_TEST_DIR=path` - This sets the directory that is used as the current -working directory of the tests. By default, this will be in your temp dir. It's +working directory of the tests. By default, this will be in your temp dir. It's recommended that this is set to a directory outside of any Git repository. * `GIT_LFS_TEST_MAXPROCS=N` - This tells `script/integration` how many tests to run in parallel. Default: 4. diff --git a/test/git-lfs-test-server-api/main.go b/test/git-lfs-test-server-api/main.go index 2efcb9e4..8a466300 100644 --- a/test/git-lfs-test-server-api/main.go +++ b/test/git-lfs-test-server-api/main.go @@ -15,7 +15,7 @@ import ( "github.com/github/git-lfs/errutil" "github.com/github/git-lfs/lfs" "github.com/github/git-lfs/test" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/cobra" + "github.com/spf13/cobra" ) type TestObject struct { diff --git a/test/testhelpers.sh b/test/testhelpers.sh index 583daf6a..2524f097 100644 --- a/test/testhelpers.sh +++ b/test/testhelpers.sh @@ -197,7 +197,7 @@ clone_repo() { # clone_repo_ssl clones a repository from the test Git server to the subdirectory -# $dir under $TRASHDIR, using the SSL endpoint. +# $dir under $TRASHDIR, using the SSL endpoint. # setup_remote_repo() needs to be run first. Output is written to clone_ssl.log. clone_repo_ssl() { cd "$TRASHDIR" @@ -233,10 +233,10 @@ setup() { if [ -z "$SKIPCOMPILE" ]; then for go in test/cmd/*.go; do - GO15VENDOREXPERIMENT=0 go build -o "$BINPATH/$(basename $go .go)" "$go" + GO15VENDOREXPERIMENT=1 go build -o "$BINPATH/$(basename $go .go)" "$go" done # Ensure API test util is built during tests to ensure it stays in sync - GO15VENDOREXPERIMENT=0 go build -o "$BINPATH/git-lfs-test-server-api" "test/git-lfs-test-server-api/main.go" "test/git-lfs-test-server-api/testdownload.go" "test/git-lfs-test-server-api/testupload.go" + GO15VENDOREXPERIMENT=1 go build -o "$BINPATH/git-lfs-test-server-api" "test/git-lfs-test-server-api/main.go" "test/git-lfs-test-server-api/testdownload.go" "test/git-lfs-test-server-api/testupload.go" fi LFSTEST_URL="$LFS_URL_FILE" LFSTEST_SSL_URL="$LFS_SSL_URL_FILE" LFSTEST_DIR="$REMOTEDIR" LFSTEST_CERT="$LFS_CERT_FILE" lfstest-gitserver > "$REMOTEDIR/gitserver.log" 2>&1 & diff --git a/tools/util_test.go b/tools/util_test.go index 86f77e87..a467cb31 100644 --- a/tools/util_test.go +++ b/tools/util_test.go @@ -5,7 +5,7 @@ import ( "io/ioutil" "testing" - "github.com/bmizerany/assert" + "github.com/stretchr/testify/assert" ) func TestCopyWithCallback(t *testing.T) { @@ -20,10 +20,10 @@ func TestCopyWithCallback(t *testing.T) { assert.Equal(t, 5, int(total)) return nil }) - assert.Equal(t, nil, err) + assert.Nil(t, err) assert.Equal(t, 5, int(n)) assert.Equal(t, 1, called) - assert.Equal(t, 1, len(calledWritten)) + assert.Len(t, calledWritten, 1) assert.Equal(t, 5, int(calledWritten[0])) } diff --git a/transfer/basic.go b/transfer/basic.go index 57a2d301..faf25259 100644 --- a/transfer/basic.go +++ b/transfer/basic.go @@ -15,7 +15,7 @@ import ( "github.com/github/git-lfs/httputil" "github.com/github/git-lfs/progress" "github.com/github/git-lfs/tools" - "github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx" + "github.com/rubyist/tracerx" ) const ( diff --git a/vendor/_nuts/code.google.com/p/log4go/.hgtags b/vendor/_nuts/code.google.com/p/log4go/.hgtags deleted file mode 100644 index 72a2eea2..00000000 --- a/vendor/_nuts/code.google.com/p/log4go/.hgtags +++ /dev/null @@ -1,4 +0,0 @@ -4fbe6aadba231e838a449d340e43bdaab0bf85bd go.weekly.2012-02-07 -56168fd53249d639c25c74ced881fffb20d27be9 go.weekly.2012-02-22 -56168fd53249d639c25c74ced881fffb20d27be9 go.weekly.2012-02-22 -5c22fbd77d91f54d76cdbdee05318699754c44cc go.weekly.2012-02-22 diff --git a/vendor/_nuts/code.google.com/p/log4go/LICENSE b/vendor/_nuts/code.google.com/p/log4go/LICENSE deleted file mode 100644 index 7093402b..00000000 --- a/vendor/_nuts/code.google.com/p/log4go/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright (c) 2010, Kyle Lemons . All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/_nuts/code.google.com/p/log4go/README b/vendor/_nuts/code.google.com/p/log4go/README deleted file mode 100644 index 16d80ecb..00000000 --- a/vendor/_nuts/code.google.com/p/log4go/README +++ /dev/null @@ -1,12 +0,0 @@ -Please see http://log4go.googlecode.com/ - -Installation: -- Run `goinstall log4go.googlecode.com/hg` - -Usage: -- Add the following import: -import l4g "log4go.googlecode.com/hg" - -Acknowledgements: -- pomack - For providing awesome patches to bring log4go up to the latest Go spec diff --git a/vendor/_nuts/code.google.com/p/log4go/config.go b/vendor/_nuts/code.google.com/p/log4go/config.go deleted file mode 100644 index f048b69f..00000000 --- a/vendor/_nuts/code.google.com/p/log4go/config.go +++ /dev/null @@ -1,288 +0,0 @@ -// Copyright (C) 2010, Kyle Lemons . All rights reserved. - -package log4go - -import ( - "encoding/xml" - "fmt" - "io/ioutil" - "os" - "strconv" - "strings" -) - -type xmlProperty struct { - Name string `xml:"name,attr"` - Value string `xml:",chardata"` -} - -type xmlFilter struct { - Enabled string `xml:"enabled,attr"` - Tag string `xml:"tag"` - Level string `xml:"level"` - Type string `xml:"type"` - Property []xmlProperty `xml:"property"` -} - -type xmlLoggerConfig struct { - Filter []xmlFilter `xml:"filter"` -} - -// Load XML configuration; see examples/example.xml for documentation -func (log Logger) LoadConfiguration(filename string) { - log.Close() - - // Open the configuration file - fd, err := os.Open(filename) - if err != nil { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Could not open %q for reading: %s\n", filename, err) - os.Exit(1) - } - - contents, err := ioutil.ReadAll(fd) - if err != nil { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Could not read %q: %s\n", filename, err) - os.Exit(1) - } - - xc := new(xmlLoggerConfig) - if err := xml.Unmarshal(contents, xc); err != nil { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Could not parse XML configuration in %q: %s\n", filename, err) - os.Exit(1) - } - - for _, xmlfilt := range xc.Filter { - var filt LogWriter - var lvl level - bad, good, enabled := false, true, false - - // Check required children - if len(xmlfilt.Enabled) == 0 { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Required attribute %s for filter missing in %s\n", "enabled", filename) - bad = true - } else { - enabled = xmlfilt.Enabled != "false" - } - if len(xmlfilt.Tag) == 0 { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Required child <%s> for filter missing in %s\n", "tag", filename) - bad = true - } - if len(xmlfilt.Type) == 0 { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Required child <%s> for filter missing in %s\n", "type", filename) - bad = true - } - if len(xmlfilt.Level) == 0 { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Required child <%s> for filter missing in %s\n", "level", filename) - bad = true - } - - switch xmlfilt.Level { - case "FINEST": - lvl = FINEST - case "FINE": - lvl = FINE - case "DEBUG": - lvl = DEBUG - case "TRACE": - lvl = TRACE - case "INFO": - lvl = INFO - case "WARNING": - lvl = WARNING - case "ERROR": - lvl = ERROR - case "CRITICAL": - lvl = CRITICAL - default: - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Required child <%s> for filter has unknown value in %s: %s\n", "level", filename, xmlfilt.Level) - bad = true - } - - // Just so all of the required attributes are errored at the same time if missing - if bad { - os.Exit(1) - } - - switch xmlfilt.Type { - case "console": - filt, good = xmlToConsoleLogWriter(filename, xmlfilt.Property, enabled) - case "file": - filt, good = xmlToFileLogWriter(filename, xmlfilt.Property, enabled) - case "xml": - filt, good = xmlToXMLLogWriter(filename, xmlfilt.Property, enabled) - case "socket": - filt, good = xmlToSocketLogWriter(filename, xmlfilt.Property, enabled) - default: - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Could not load XML configuration in %s: unknown filter type \"%s\"\n", filename, xmlfilt.Type) - os.Exit(1) - } - - // Just so all of the required params are errored at the same time if wrong - if !good { - os.Exit(1) - } - - // If we're disabled (syntax and correctness checks only), don't add to logger - if !enabled { - continue - } - - log[xmlfilt.Tag] = &Filter{lvl, filt} - } -} - -func xmlToConsoleLogWriter(filename string, props []xmlProperty, enabled bool) (ConsoleLogWriter, bool) { - // Parse properties - for _, prop := range props { - switch prop.Name { - default: - fmt.Fprintf(os.Stderr, "LoadConfiguration: Warning: Unknown property \"%s\" for console filter in %s\n", prop.Name, filename) - } - } - - // If it's disabled, we're just checking syntax - if !enabled { - return nil, true - } - - return NewConsoleLogWriter(), true -} - -// Parse a number with K/M/G suffixes based on thousands (1000) or 2^10 (1024) -func strToNumSuffix(str string, mult int) int { - num := 1 - if len(str) > 1 { - switch str[len(str)-1] { - case 'G', 'g': - num *= mult - fallthrough - case 'M', 'm': - num *= mult - fallthrough - case 'K', 'k': - num *= mult - str = str[0 : len(str)-1] - } - } - parsed, _ := strconv.Atoi(str) - return parsed * num -} -func xmlToFileLogWriter(filename string, props []xmlProperty, enabled bool) (*FileLogWriter, bool) { - file := "" - format := "[%D %T] [%L] (%S) %M" - maxlines := 0 - maxsize := 0 - daily := false - rotate := false - - // Parse properties - for _, prop := range props { - switch prop.Name { - case "filename": - file = strings.Trim(prop.Value, " \r\n") - case "format": - format = strings.Trim(prop.Value, " \r\n") - case "maxlines": - maxlines = strToNumSuffix(strings.Trim(prop.Value, " \r\n"), 1000) - case "maxsize": - maxsize = strToNumSuffix(strings.Trim(prop.Value, " \r\n"), 1024) - case "daily": - daily = strings.Trim(prop.Value, " \r\n") != "false" - case "rotate": - rotate = strings.Trim(prop.Value, " \r\n") != "false" - default: - fmt.Fprintf(os.Stderr, "LoadConfiguration: Warning: Unknown property \"%s\" for file filter in %s\n", prop.Name, filename) - } - } - - // Check properties - if len(file) == 0 { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Required property \"%s\" for file filter missing in %s\n", "filename", filename) - return nil, false - } - - // If it's disabled, we're just checking syntax - if !enabled { - return nil, true - } - - flw := NewFileLogWriter(file, rotate) - flw.SetFormat(format) - flw.SetRotateLines(maxlines) - flw.SetRotateSize(maxsize) - flw.SetRotateDaily(daily) - return flw, true -} - -func xmlToXMLLogWriter(filename string, props []xmlProperty, enabled bool) (*FileLogWriter, bool) { - file := "" - maxrecords := 0 - maxsize := 0 - daily := false - rotate := false - - // Parse properties - for _, prop := range props { - switch prop.Name { - case "filename": - file = strings.Trim(prop.Value, " \r\n") - case "maxrecords": - maxrecords = strToNumSuffix(strings.Trim(prop.Value, " \r\n"), 1000) - case "maxsize": - maxsize = strToNumSuffix(strings.Trim(prop.Value, " \r\n"), 1024) - case "daily": - daily = strings.Trim(prop.Value, " \r\n") != "false" - case "rotate": - rotate = strings.Trim(prop.Value, " \r\n") != "false" - default: - fmt.Fprintf(os.Stderr, "LoadConfiguration: Warning: Unknown property \"%s\" for xml filter in %s\n", prop.Name, filename) - } - } - - // Check properties - if len(file) == 0 { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Required property \"%s\" for xml filter missing in %s\n", "filename", filename) - return nil, false - } - - // If it's disabled, we're just checking syntax - if !enabled { - return nil, true - } - - xlw := NewXMLLogWriter(file, rotate) - xlw.SetRotateLines(maxrecords) - xlw.SetRotateSize(maxsize) - xlw.SetRotateDaily(daily) - return xlw, true -} - -func xmlToSocketLogWriter(filename string, props []xmlProperty, enabled bool) (SocketLogWriter, bool) { - endpoint := "" - protocol := "udp" - - // Parse properties - for _, prop := range props { - switch prop.Name { - case "endpoint": - endpoint = strings.Trim(prop.Value, " \r\n") - case "protocol": - protocol = strings.Trim(prop.Value, " \r\n") - default: - fmt.Fprintf(os.Stderr, "LoadConfiguration: Warning: Unknown property \"%s\" for file filter in %s\n", prop.Name, filename) - } - } - - // Check properties - if len(endpoint) == 0 { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Required property \"%s\" for file filter missing in %s\n", "endpoint", filename) - return nil, false - } - - // If it's disabled, we're just checking syntax - if !enabled { - return nil, true - } - - return NewSocketLogWriter(protocol, endpoint), true -} diff --git a/vendor/_nuts/code.google.com/p/log4go/examples/ConsoleLogWriter_Manual.go b/vendor/_nuts/code.google.com/p/log4go/examples/ConsoleLogWriter_Manual.go deleted file mode 100644 index 7169ec97..00000000 --- a/vendor/_nuts/code.google.com/p/log4go/examples/ConsoleLogWriter_Manual.go +++ /dev/null @@ -1,13 +0,0 @@ -package main - -import ( - "time" -) - -import l4g "github.com/github/git-lfs/vendor/_nuts/code.google.com/p/log4go" - -func main() { - log := l4g.NewLogger() - log.AddFilter("stdout", l4g.DEBUG, l4g.NewConsoleLogWriter()) - log.Info("The time is now: %s", time.Now().Format("15:04:05 MST 2006/01/02")) -} diff --git a/vendor/_nuts/code.google.com/p/log4go/examples/FileLogWriter_Manual.go b/vendor/_nuts/code.google.com/p/log4go/examples/FileLogWriter_Manual.go deleted file mode 100644 index 872bb45b..00000000 --- a/vendor/_nuts/code.google.com/p/log4go/examples/FileLogWriter_Manual.go +++ /dev/null @@ -1,57 +0,0 @@ -package main - -import ( - "bufio" - "fmt" - "io" - "os" - "time" -) - -import l4g "github.com/github/git-lfs/vendor/_nuts/code.google.com/p/log4go" - -const ( - filename = "flw.log" -) - -func main() { - // Get a new logger instance - log := l4g.NewLogger() - - // Create a default logger that is logging messages of FINE or higher - log.AddFilter("file", l4g.FINE, l4g.NewFileLogWriter(filename, false)) - log.Close() - - /* Can also specify manually via the following: (these are the defaults) */ - flw := l4g.NewFileLogWriter(filename, false) - flw.SetFormat("[%D %T] [%L] (%S) %M") - flw.SetRotate(false) - flw.SetRotateSize(0) - flw.SetRotateLines(0) - flw.SetRotateDaily(false) - log.AddFilter("file", l4g.FINE, flw) - - // Log some experimental messages - log.Finest("Everything is created now (notice that I will not be printing to the file)") - log.Info("The time is now: %s", time.Now().Format("15:04:05 MST 2006/01/02")) - log.Critical("Time to close out!") - - // Close the log - log.Close() - - // Print what was logged to the file (yes, I know I'm skipping error checking) - fd, _ := os.Open(filename) - in := bufio.NewReader(fd) - fmt.Print("Messages logged to file were: (line numbers not included)\n") - for lineno := 1; ; lineno++ { - line, err := in.ReadString('\n') - if err == io.EOF { - break - } - fmt.Printf("%3d:\t%s", lineno, line) - } - fd.Close() - - // Remove the file so it's not lying around - os.Remove(filename) -} diff --git a/vendor/_nuts/code.google.com/p/log4go/examples/SimpleNetLogServer.go b/vendor/_nuts/code.google.com/p/log4go/examples/SimpleNetLogServer.go deleted file mode 100644 index 83c80ad1..00000000 --- a/vendor/_nuts/code.google.com/p/log4go/examples/SimpleNetLogServer.go +++ /dev/null @@ -1,42 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "net" - "os" -) - -var ( - port = flag.String("p", "12124", "Port number to listen on") -) - -func e(err error) { - if err != nil { - fmt.Printf("Erroring out: %s\n", err) - os.Exit(1) - } -} - -func main() { - flag.Parse() - - // Bind to the port - bind, err := net.ResolveUDPAddr("0.0.0.0:" + *port) - e(err) - - // Create listener - listener, err := net.ListenUDP("udp", bind) - e(err) - - fmt.Printf("Listening to port %s...\n", *port) - for { - // read into a new buffer - buffer := make([]byte, 1024) - _, _, err := listener.ReadFrom(buffer) - e(err) - - // log to standard output - fmt.Println(string(buffer)) - } -} diff --git a/vendor/_nuts/code.google.com/p/log4go/examples/SocketLogWriter_Manual.go b/vendor/_nuts/code.google.com/p/log4go/examples/SocketLogWriter_Manual.go deleted file mode 100644 index d553699f..00000000 --- a/vendor/_nuts/code.google.com/p/log4go/examples/SocketLogWriter_Manual.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "time" -) - -import l4g "github.com/github/git-lfs/vendor/_nuts/code.google.com/p/log4go" - -func main() { - log := l4g.NewLogger() - log.AddFilter("network", l4g.FINEST, l4g.NewSocketLogWriter("udp", "192.168.1.255:12124")) - - // Run `nc -u -l -p 12124` or similar before you run this to see the following message - log.Info("The time is now: %s", time.Now().Format("15:04:05 MST 2006/01/02")) - - // This makes sure the output stream buffer is written - log.Close() -} diff --git a/vendor/_nuts/code.google.com/p/log4go/examples/XMLConfigurationExample.go b/vendor/_nuts/code.google.com/p/log4go/examples/XMLConfigurationExample.go deleted file mode 100644 index d6485753..00000000 --- a/vendor/_nuts/code.google.com/p/log4go/examples/XMLConfigurationExample.go +++ /dev/null @@ -1,13 +0,0 @@ -package main - -import l4g "github.com/github/git-lfs/vendor/_nuts/code.google.com/p/log4go" - -func main() { - // Load the configuration (isn't this easy?) - l4g.LoadConfiguration("example.xml") - - // And now we're ready! - l4g.Finest("This will only go to those of you really cool UDP kids! If you change enabled=true.") - l4g.Debug("Oh no! %d + %d = %d!", 2, 2, 2+2) - l4g.Info("About that time, eh chaps?") -} diff --git a/vendor/_nuts/code.google.com/p/log4go/examples/example.xml b/vendor/_nuts/code.google.com/p/log4go/examples/example.xml deleted file mode 100644 index e791278c..00000000 --- a/vendor/_nuts/code.google.com/p/log4go/examples/example.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - stdout - console - - DEBUG - - - file - file - FINEST - test.log - - [%D %T] [%L] (%S) %M - false - 0M - 0K - true - - - xmllog - xml - TRACE - trace.xml - true - 100M - 6K - false - - - donotopen - socket - FINEST - 192.168.1.255:12124 - udp - - diff --git a/vendor/_nuts/code.google.com/p/log4go/filelog.go b/vendor/_nuts/code.google.com/p/log4go/filelog.go deleted file mode 100644 index 9cbd815d..00000000 --- a/vendor/_nuts/code.google.com/p/log4go/filelog.go +++ /dev/null @@ -1,239 +0,0 @@ -// Copyright (C) 2010, Kyle Lemons . All rights reserved. - -package log4go - -import ( - "os" - "fmt" - "time" -) - -// This log writer sends output to a file -type FileLogWriter struct { - rec chan *LogRecord - rot chan bool - - // The opened file - filename string - file *os.File - - // The logging format - format string - - // File header/trailer - header, trailer string - - // Rotate at linecount - maxlines int - maxlines_curlines int - - // Rotate at size - maxsize int - maxsize_cursize int - - // Rotate daily - daily bool - daily_opendate int - - // Keep old logfiles (.001, .002, etc) - rotate bool -} - -// This is the FileLogWriter's output method -func (w *FileLogWriter) LogWrite(rec *LogRecord) { - w.rec <- rec -} - -func (w *FileLogWriter) Close() { - close(w.rec) -} - -// NewFileLogWriter creates a new LogWriter which writes to the given file and -// has rotation enabled if rotate is true. -// -// If rotate is true, any time a new log file is opened, the old one is renamed -// with a .### extension to preserve it. The various Set* methods can be used -// to configure log rotation based on lines, size, and daily. -// -// The standard log-line format is: -// [%D %T] [%L] (%S) %M -func NewFileLogWriter(fname string, rotate bool) *FileLogWriter { - w := &FileLogWriter{ - rec: make(chan *LogRecord, LogBufferLength), - rot: make(chan bool), - filename: fname, - format: "[%D %T] [%L] (%S) %M", - rotate: rotate, - } - - // open the file for the first time - if err := w.intRotate(); err != nil { - fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.filename, err) - return nil - } - - go func() { - defer func() { - if w.file != nil { - fmt.Fprint(w.file, FormatLogRecord(w.trailer, &LogRecord{Created: time.Now()})) - w.file.Close() - } - }() - - for { - select { - case <-w.rot: - if err := w.intRotate(); err != nil { - fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.filename, err) - return - } - case rec, ok := <-w.rec: - if !ok { - return - } - now := time.Now() - if (w.maxlines > 0 && w.maxlines_curlines >= w.maxlines) || - (w.maxsize > 0 && w.maxsize_cursize >= w.maxsize) || - (w.daily && now.Day() != w.daily_opendate) { - if err := w.intRotate(); err != nil { - fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.filename, err) - return - } - } - - // Perform the write - n, err := fmt.Fprint(w.file, FormatLogRecord(w.format, rec)) - if err != nil { - fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.filename, err) - return - } - - // Update the counts - w.maxlines_curlines++ - w.maxsize_cursize += n - } - } - }() - - return w -} - -// Request that the logs rotate -func (w *FileLogWriter) Rotate() { - w.rot <- true -} - -// If this is called in a threaded context, it MUST be synchronized -func (w *FileLogWriter) intRotate() error { - // Close any log file that may be open - if w.file != nil { - fmt.Fprint(w.file, FormatLogRecord(w.trailer, &LogRecord{Created: time.Now()})) - w.file.Close() - } - - // If we are keeping log files, move it to the next available number - if w.rotate { - _, err := os.Lstat(w.filename) - if err == nil { // file exists - // Find the next available number - num := 1 - fname := "" - for ; err == nil && num <= 999; num++ { - fname = w.filename + fmt.Sprintf(".%03d", num) - _, err = os.Lstat(fname) - } - // return error if the last file checked still existed - if err == nil { - return fmt.Errorf("Rotate: Cannot find free log number to rename %s\n", w.filename) - } - - // Rename the file to its newfound home - err = os.Rename(w.filename, fname) - if err != nil { - return fmt.Errorf("Rotate: %s\n", err) - } - } - } - - // Open the log file - fd, err := os.OpenFile(w.filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660) - if err != nil { - return err - } - w.file = fd - - now := time.Now() - fmt.Fprint(w.file, FormatLogRecord(w.header, &LogRecord{Created: now})) - - // Set the daily open date to the current date - w.daily_opendate = now.Day() - - // initialize rotation values - w.maxlines_curlines = 0 - w.maxsize_cursize = 0 - - return nil -} - -// Set the logging format (chainable). Must be called before the first log -// message is written. -func (w *FileLogWriter) SetFormat(format string) *FileLogWriter { - w.format = format - return w -} - -// Set the logfile header and footer (chainable). Must be called before the first log -// message is written. These are formatted similar to the FormatLogRecord (e.g. -// you can use %D and %T in your header/footer for date and time). -func (w *FileLogWriter) SetHeadFoot(head, foot string) *FileLogWriter { - w.header, w.trailer = head, foot - if w.maxlines_curlines == 0 { - fmt.Fprint(w.file, FormatLogRecord(w.header, &LogRecord{Created: time.Now()})) - } - return w -} - -// Set rotate at linecount (chainable). Must be called before the first log -// message is written. -func (w *FileLogWriter) SetRotateLines(maxlines int) *FileLogWriter { - //fmt.Fprintf(os.Stderr, "FileLogWriter.SetRotateLines: %v\n", maxlines) - w.maxlines = maxlines - return w -} - -// Set rotate at size (chainable). Must be called before the first log message -// is written. -func (w *FileLogWriter) SetRotateSize(maxsize int) *FileLogWriter { - //fmt.Fprintf(os.Stderr, "FileLogWriter.SetRotateSize: %v\n", maxsize) - w.maxsize = maxsize - return w -} - -// Set rotate daily (chainable). Must be called before the first log message is -// written. -func (w *FileLogWriter) SetRotateDaily(daily bool) *FileLogWriter { - //fmt.Fprintf(os.Stderr, "FileLogWriter.SetRotateDaily: %v\n", daily) - w.daily = daily - return w -} - -// SetRotate changes whether or not the old logs are kept. (chainable) Must be -// called before the first log message is written. If rotate is false, the -// files are overwritten; otherwise, they are rotated to another file before the -// new log is opened. -func (w *FileLogWriter) SetRotate(rotate bool) *FileLogWriter { - //fmt.Fprintf(os.Stderr, "FileLogWriter.SetRotate: %v\n", rotate) - w.rotate = rotate - return w -} - -// NewXMLLogWriter is a utility method for creating a FileLogWriter set up to -// output XML record log messages instead of line-based ones. -func NewXMLLogWriter(fname string, rotate bool) *FileLogWriter { - return NewFileLogWriter(fname, rotate).SetFormat( - ` - %D %T - %S - %M - `).SetHeadFoot("", "") -} diff --git a/vendor/_nuts/code.google.com/p/log4go/log4go.go b/vendor/_nuts/code.google.com/p/log4go/log4go.go deleted file mode 100644 index ab4e857f..00000000 --- a/vendor/_nuts/code.google.com/p/log4go/log4go.go +++ /dev/null @@ -1,484 +0,0 @@ -// Copyright (C) 2010, Kyle Lemons . All rights reserved. - -// Package log4go provides level-based and highly configurable logging. -// -// Enhanced Logging -// -// This is inspired by the logging functionality in Java. Essentially, you create a Logger -// object and create output filters for it. You can send whatever you want to the Logger, -// and it will filter that based on your settings and send it to the outputs. This way, you -// can put as much debug code in your program as you want, and when you're done you can filter -// out the mundane messages so only the important ones show up. -// -// Utility functions are provided to make life easier. Here is some example code to get started: -// -// log := log4go.NewLogger() -// log.AddFilter("stdout", log4go.DEBUG, log4go.NewConsoleLogWriter()) -// log.AddFilter("log", log4go.FINE, log4go.NewFileLogWriter("example.log", true)) -// log.Info("The time is now: %s", time.LocalTime().Format("15:04:05 MST 2006/01/02")) -// -// The first two lines can be combined with the utility NewDefaultLogger: -// -// log := log4go.NewDefaultLogger(log4go.DEBUG) -// log.AddFilter("log", log4go.FINE, log4go.NewFileLogWriter("example.log", true)) -// log.Info("The time is now: %s", time.LocalTime().Format("15:04:05 MST 2006/01/02")) -// -// Usage notes: -// - The ConsoleLogWriter does not display the source of the message to standard -// output, but the FileLogWriter does. -// - The utility functions (Info, Debug, Warn, etc) derive their source from the -// calling function, and this incurs extra overhead. -// -// Changes from 2.0: -// - The external interface has remained mostly stable, but a lot of the -// internals have been changed, so if you depended on any of this or created -// your own LogWriter, then you will probably have to update your code. In -// particular, Logger is now a map and ConsoleLogWriter is now a channel -// behind-the-scenes, and the LogWrite method no longer has return values. -// -// Future work: (please let me know if you think I should work on any of these particularly) -// - Log file rotation -// - Logging configuration files ala log4j -// - Have the ability to remove filters? -// - Have GetInfoChannel, GetDebugChannel, etc return a chan string that allows -// for another method of logging -// - Add an XML filter type -package log4go - -import ( - "errors" - "os" - "fmt" - "time" - "strings" - "runtime" -) - -// Version information -const ( - L4G_VERSION = "log4go-v3.0.1" - L4G_MAJOR = 3 - L4G_MINOR = 0 - L4G_BUILD = 1 -) - -/****** Constants ******/ - -// These are the integer logging levels used by the logger -type level int - -const ( - FINEST level = iota - FINE - DEBUG - TRACE - INFO - WARNING - ERROR - CRITICAL -) - -// Logging level strings -var ( - levelStrings = [...]string{"FNST", "FINE", "DEBG", "TRAC", "INFO", "WARN", "EROR", "CRIT"} -) - -func (l level) String() string { - if l < 0 || int(l) > len(levelStrings) { - return "UNKNOWN" - } - return levelStrings[int(l)] -} - -/****** Variables ******/ -var ( - // LogBufferLength specifies how many log messages a particular log4go - // logger can buffer at a time before writing them. - LogBufferLength = 32 -) - -/****** LogRecord ******/ - -// A LogRecord contains all of the pertinent information for each message -type LogRecord struct { - Level level // The log level - Created time.Time // The time at which the log message was created (nanoseconds) - Source string // The message source - Message string // The log message -} - -/****** LogWriter ******/ - -// This is an interface for anything that should be able to write logs -type LogWriter interface { - // This will be called to log a LogRecord message. - LogWrite(rec *LogRecord) - - // This should clean up anything lingering about the LogWriter, as it is called before - // the LogWriter is removed. LogWrite should not be called after Close. - Close() -} - -/****** Logger ******/ - -// A Filter represents the log level below which no log records are written to -// the associated LogWriter. -type Filter struct { - Level level - LogWriter -} - -// A Logger represents a collection of Filters through which log messages are -// written. -type Logger map[string]*Filter - -// Create a new logger. -// -// DEPRECATED: Use make(Logger) instead. -func NewLogger() Logger { - os.Stderr.WriteString("warning: use of deprecated NewLogger\n") - return make(Logger) -} - -// Create a new logger with a "stdout" filter configured to send log messages at -// or above lvl to standard output. -// -// DEPRECATED: use NewDefaultLogger instead. -func NewConsoleLogger(lvl level) Logger { - os.Stderr.WriteString("warning: use of deprecated NewConsoleLogger\n") - return Logger{ - "stdout": &Filter{lvl, NewConsoleLogWriter()}, - } -} - -// Create a new logger with a "stdout" filter configured to send log messages at -// or above lvl to standard output. -func NewDefaultLogger(lvl level) Logger { - return Logger{ - "stdout": &Filter{lvl, NewConsoleLogWriter()}, - } -} - -// Closes all log writers in preparation for exiting the program or a -// reconfiguration of logging. Calling this is not really imperative, unless -// you want to guarantee that all log messages are written. Close removes -// all filters (and thus all LogWriters) from the logger. -func (log Logger) Close() { - // Close all open loggers - for name, filt := range log { - filt.Close() - delete(log, name) - } -} - -// Add a new LogWriter to the Logger which will only log messages at lvl or -// higher. This function should not be called from multiple goroutines. -// Returns the logger for chaining. -func (log Logger) AddFilter(name string, lvl level, writer LogWriter) Logger { - log[name] = &Filter{lvl, writer} - return log -} - -/******* Logging *******/ -// Send a formatted log message internally -func (log Logger) intLogf(lvl level, format string, args ...interface{}) { - skip := true - - // Determine if any logging will be done - for _, filt := range log { - if lvl >= filt.Level { - skip = false - break - } - } - if skip { - return - } - - // Determine caller func - pc, _, lineno, ok := runtime.Caller(2) - src := "" - if ok { - src = fmt.Sprintf("%s:%d", runtime.FuncForPC(pc).Name(), lineno) - } - - msg := format - if len(args) > 0 { - msg = fmt.Sprintf(format, args...) - } - - // Make the log record - rec := &LogRecord{ - Level: lvl, - Created: time.Now(), - Source: src, - Message: msg, - } - - // Dispatch the logs - for _, filt := range log { - if lvl < filt.Level { - continue - } - filt.LogWrite(rec) - } -} - -// Send a closure log message internally -func (log Logger) intLogc(lvl level, closure func() string) { - skip := true - - // Determine if any logging will be done - for _, filt := range log { - if lvl >= filt.Level { - skip = false - break - } - } - if skip { - return - } - - // Determine caller func - pc, _, lineno, ok := runtime.Caller(2) - src := "" - if ok { - src = fmt.Sprintf("%s:%d", runtime.FuncForPC(pc).Name(), lineno) - } - - // Make the log record - rec := &LogRecord{ - Level: lvl, - Created: time.Now(), - Source: src, - Message: closure(), - } - - // Dispatch the logs - for _, filt := range log { - if lvl < filt.Level { - continue - } - filt.LogWrite(rec) - } -} - -// Send a log message with manual level, source, and message. -func (log Logger) Log(lvl level, source, message string) { - skip := true - - // Determine if any logging will be done - for _, filt := range log { - if lvl >= filt.Level { - skip = false - break - } - } - if skip { - return - } - - // Make the log record - rec := &LogRecord{ - Level: lvl, - Created: time.Now(), - Source: source, - Message: message, - } - - // Dispatch the logs - for _, filt := range log { - if lvl < filt.Level { - continue - } - filt.LogWrite(rec) - } -} - -// Logf logs a formatted log message at the given log level, using the caller as -// its source. -func (log Logger) Logf(lvl level, format string, args ...interface{}) { - log.intLogf(lvl, format, args...) -} - -// Logc logs a string returned by the closure at the given log level, using the caller as -// its source. If no log message would be written, the closure is never called. -func (log Logger) Logc(lvl level, closure func() string) { - log.intLogc(lvl, closure) -} - -// Finest logs a message at the finest log level. -// See Debug for an explanation of the arguments. -func (log Logger) Finest(arg0 interface{}, args ...interface{}) { - const ( - lvl = FINEST - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - log.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - log.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - log.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Fine logs a message at the fine log level. -// See Debug for an explanation of the arguments. -func (log Logger) Fine(arg0 interface{}, args ...interface{}) { - const ( - lvl = FINE - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - log.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - log.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - log.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Debug is a utility method for debug log messages. -// The behavior of Debug depends on the first argument: -// - arg0 is a string -// When given a string as the first argument, this behaves like Logf but with -// the DEBUG log level: the first argument is interpreted as a format for the -// latter arguments. -// - arg0 is a func()string -// When given a closure of type func()string, this logs the string returned by -// the closure iff it will be logged. The closure runs at most one time. -// - arg0 is interface{} -// When given anything else, the log message will be each of the arguments -// formatted with %v and separated by spaces (ala Sprint). -func (log Logger) Debug(arg0 interface{}, args ...interface{}) { - const ( - lvl = DEBUG - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - log.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - log.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - log.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Trace logs a message at the trace log level. -// See Debug for an explanation of the arguments. -func (log Logger) Trace(arg0 interface{}, args ...interface{}) { - const ( - lvl = TRACE - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - log.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - log.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - log.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Info logs a message at the info log level. -// See Debug for an explanation of the arguments. -func (log Logger) Info(arg0 interface{}, args ...interface{}) { - const ( - lvl = INFO - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - log.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - log.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - log.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Warn logs a message at the warning log level and returns the formatted error. -// At the warning level and higher, there is no performance benefit if the -// message is not actually logged, because all formats are processed and all -// closures are executed to format the error message. -// See Debug for further explanation of the arguments. -func (log Logger) Warn(arg0 interface{}, args ...interface{}) error { - const ( - lvl = WARNING - ) - var msg string - switch first := arg0.(type) { - case string: - // Use the string as a format string - msg = fmt.Sprintf(first, args...) - case func() string: - // Log the closure (no other arguments used) - msg = first() - default: - // Build a format string so that it will be similar to Sprint - msg = fmt.Sprintf(fmt.Sprint(first)+strings.Repeat(" %v", len(args)), args...) - } - log.intLogf(lvl, msg) - return errors.New(msg) -} - -// Error logs a message at the error log level and returns the formatted error, -// See Warn for an explanation of the performance and Debug for an explanation -// of the parameters. -func (log Logger) Error(arg0 interface{}, args ...interface{}) error { - const ( - lvl = ERROR - ) - var msg string - switch first := arg0.(type) { - case string: - // Use the string as a format string - msg = fmt.Sprintf(first, args...) - case func() string: - // Log the closure (no other arguments used) - msg = first() - default: - // Build a format string so that it will be similar to Sprint - msg = fmt.Sprintf(fmt.Sprint(first)+strings.Repeat(" %v", len(args)), args...) - } - log.intLogf(lvl, msg) - return errors.New(msg) -} - -// Critical logs a message at the critical log level and returns the formatted error, -// See Warn for an explanation of the performance and Debug for an explanation -// of the parameters. -func (log Logger) Critical(arg0 interface{}, args ...interface{}) error { - const ( - lvl = CRITICAL - ) - var msg string - switch first := arg0.(type) { - case string: - // Use the string as a format string - msg = fmt.Sprintf(first, args...) - case func() string: - // Log the closure (no other arguments used) - msg = first() - default: - // Build a format string so that it will be similar to Sprint - msg = fmt.Sprintf(fmt.Sprint(first)+strings.Repeat(" %v", len(args)), args...) - } - log.intLogf(lvl, msg) - return errors.New(msg) -} diff --git a/vendor/_nuts/code.google.com/p/log4go/log4go_test.go b/vendor/_nuts/code.google.com/p/log4go/log4go_test.go deleted file mode 100644 index 90c62997..00000000 --- a/vendor/_nuts/code.google.com/p/log4go/log4go_test.go +++ /dev/null @@ -1,534 +0,0 @@ -// Copyright (C) 2010, Kyle Lemons . All rights reserved. - -package log4go - -import ( - "crypto/md5" - "encoding/hex" - "fmt" - "io" - "io/ioutil" - "os" - "runtime" - "testing" - "time" -) - -const testLogFile = "_logtest.log" - -var now time.Time = time.Unix(0, 1234567890123456789).In(time.UTC) - -func newLogRecord(lvl level, src string, msg string) *LogRecord { - return &LogRecord{ - Level: lvl, - Source: src, - Created: now, - Message: msg, - } -} - -func TestELog(t *testing.T) { - fmt.Printf("Testing %s\n", L4G_VERSION) - lr := newLogRecord(CRITICAL, "source", "message") - if lr.Level != CRITICAL { - t.Errorf("Incorrect level: %d should be %d", lr.Level, CRITICAL) - } - if lr.Source != "source" { - t.Errorf("Incorrect source: %s should be %s", lr.Source, "source") - } - if lr.Message != "message" { - t.Errorf("Incorrect message: %s should be %s", lr.Source, "message") - } -} - -var formatTests = []struct { - Test string - Record *LogRecord - Formats map[string]string -}{ - { - Test: "Standard formats", - Record: &LogRecord{ - Level: ERROR, - Source: "source", - Message: "message", - Created: now, - }, - Formats: map[string]string{ - // TODO(kevlar): How can I do this so it'll work outside of PST? - FORMAT_DEFAULT: "[2009/02/13 23:31:30 UTC] [EROR] (source) message\n", - FORMAT_SHORT: "[23:31 02/13/09] [EROR] message\n", - FORMAT_ABBREV: "[EROR] message\n", - }, - }, -} - -func TestFormatLogRecord(t *testing.T) { - for _, test := range formatTests { - name := test.Test - for fmt, want := range test.Formats { - if got := FormatLogRecord(fmt, test.Record); got != want { - t.Errorf("%s - %s:", name, fmt) - t.Errorf(" got %q", got) - t.Errorf(" want %q", want) - } - } - } -} - -var logRecordWriteTests = []struct { - Test string - Record *LogRecord - Console string -}{ - { - Test: "Normal message", - Record: &LogRecord{ - Level: CRITICAL, - Source: "source", - Message: "message", - Created: now, - }, - Console: "[02/13/09 23:31:30] [CRIT] message\n", - }, -} - -func TestConsoleLogWriter(t *testing.T) { - console := make(ConsoleLogWriter) - - r, w := io.Pipe() - go console.run(w) - defer console.Close() - - buf := make([]byte, 1024) - - for _, test := range logRecordWriteTests { - name := test.Test - - console.LogWrite(test.Record) - n, _ := r.Read(buf) - - if got, want := string(buf[:n]), test.Console; got != want { - t.Errorf("%s: got %q", name, got) - t.Errorf("%s: want %q", name, want) - } - } -} - -func TestFileLogWriter(t *testing.T) { - defer func(buflen int) { - LogBufferLength = buflen - }(LogBufferLength) - LogBufferLength = 0 - - w := NewFileLogWriter(testLogFile, false) - if w == nil { - t.Fatalf("Invalid return: w should not be nil") - } - defer os.Remove(testLogFile) - - w.LogWrite(newLogRecord(CRITICAL, "source", "message")) - w.Close() - runtime.Gosched() - - if contents, err := ioutil.ReadFile(testLogFile); err != nil { - t.Errorf("read(%q): %s", testLogFile, err) - } else if len(contents) != 50 { - t.Errorf("malformed filelog: %q (%d bytes)", string(contents), len(contents)) - } -} - -func TestXMLLogWriter(t *testing.T) { - defer func(buflen int) { - LogBufferLength = buflen - }(LogBufferLength) - LogBufferLength = 0 - - w := NewXMLLogWriter(testLogFile, false) - if w == nil { - t.Fatalf("Invalid return: w should not be nil") - } - defer os.Remove(testLogFile) - - w.LogWrite(newLogRecord(CRITICAL, "source", "message")) - w.Close() - runtime.Gosched() - - if contents, err := ioutil.ReadFile(testLogFile); err != nil { - t.Errorf("read(%q): %s", testLogFile, err) - } else if len(contents) != 185 { - t.Errorf("malformed xmllog: %q (%d bytes)", string(contents), len(contents)) - } -} - -func TestLogger(t *testing.T) { - sl := NewDefaultLogger(WARNING) - if sl == nil { - t.Fatalf("NewDefaultLogger should never return nil") - } - if lw, exist := sl["stdout"]; lw == nil || exist != true { - t.Fatalf("NewDefaultLogger produced invalid logger (DNE or nil)") - } - if sl["stdout"].Level != WARNING { - t.Fatalf("NewDefaultLogger produced invalid logger (incorrect level)") - } - if len(sl) != 1 { - t.Fatalf("NewDefaultLogger produced invalid logger (incorrect map count)") - } - - //func (l *Logger) AddFilter(name string, level int, writer LogWriter) {} - l := make(Logger) - l.AddFilter("stdout", DEBUG, NewConsoleLogWriter()) - if lw, exist := l["stdout"]; lw == nil || exist != true { - t.Fatalf("AddFilter produced invalid logger (DNE or nil)") - } - if l["stdout"].Level != DEBUG { - t.Fatalf("AddFilter produced invalid logger (incorrect level)") - } - if len(l) != 1 { - t.Fatalf("AddFilter produced invalid logger (incorrect map count)") - } - - //func (l *Logger) Warn(format string, args ...interface{}) error {} - if err := l.Warn("%s %d %#v", "Warning:", 1, []int{}); err.Error() != "Warning: 1 []int{}" { - t.Errorf("Warn returned invalid error: %s", err) - } - - //func (l *Logger) Error(format string, args ...interface{}) error {} - if err := l.Error("%s %d %#v", "Error:", 10, []string{}); err.Error() != "Error: 10 []string{}" { - t.Errorf("Error returned invalid error: %s", err) - } - - //func (l *Logger) Critical(format string, args ...interface{}) error {} - if err := l.Critical("%s %d %#v", "Critical:", 100, []int64{}); err.Error() != "Critical: 100 []int64{}" { - t.Errorf("Critical returned invalid error: %s", err) - } - - // Already tested or basically untestable - //func (l *Logger) Log(level int, source, message string) {} - //func (l *Logger) Logf(level int, format string, args ...interface{}) {} - //func (l *Logger) intLogf(level int, format string, args ...interface{}) string {} - //func (l *Logger) Finest(format string, args ...interface{}) {} - //func (l *Logger) Fine(format string, args ...interface{}) {} - //func (l *Logger) Debug(format string, args ...interface{}) {} - //func (l *Logger) Trace(format string, args ...interface{}) {} - //func (l *Logger) Info(format string, args ...interface{}) {} -} - -func TestLogOutput(t *testing.T) { - const ( - expected = "fdf3e51e444da56b4cb400f30bc47424" - ) - - // Unbuffered output - defer func(buflen int) { - LogBufferLength = buflen - }(LogBufferLength) - LogBufferLength = 0 - - l := make(Logger) - - // Delete and open the output log without a timestamp (for a constant md5sum) - l.AddFilter("file", FINEST, NewFileLogWriter(testLogFile, false).SetFormat("[%L] %M")) - defer os.Remove(testLogFile) - - // Send some log messages - l.Log(CRITICAL, "testsrc1", fmt.Sprintf("This message is level %d", int(CRITICAL))) - l.Logf(ERROR, "This message is level %v", ERROR) - l.Logf(WARNING, "This message is level %s", WARNING) - l.Logc(INFO, func() string { return "This message is level INFO" }) - l.Trace("This message is level %d", int(TRACE)) - l.Debug("This message is level %s", DEBUG) - l.Fine(func() string { return fmt.Sprintf("This message is level %v", FINE) }) - l.Finest("This message is level %v", FINEST) - l.Finest(FINEST, "is also this message's level") - - l.Close() - - contents, err := ioutil.ReadFile(testLogFile) - if err != nil { - t.Fatalf("Could not read output log: %s", err) - } - - sum := md5.New() - sum.Write(contents) - if sumstr := hex.EncodeToString(sum.Sum(nil)); sumstr != expected { - t.Errorf("--- Log Contents:\n%s---", string(contents)) - t.Fatalf("Checksum does not match: %s (expecting %s)", sumstr, expected) - } -} - -func TestCountMallocs(t *testing.T) { - const N = 1 - var m runtime.MemStats - getMallocs := func() uint64 { - runtime.ReadMemStats(&m) - return m.Mallocs - } - - // Console logger - sl := NewDefaultLogger(INFO) - mallocs := 0 - getMallocs() - for i := 0; i < N; i++ { - sl.Log(WARNING, "here", "This is a WARNING message") - } - mallocs += getMallocs() - fmt.Printf("mallocs per sl.Log((WARNING, \"here\", \"This is a log message\"): %d\n", mallocs/N) - - // Console logger formatted - mallocs = 0 - getMallocs() - for i := 0; i < N; i++ { - sl.Logf(WARNING, "%s is a log message with level %d", "This", WARNING) - } - mallocs += getMallocs() - fmt.Printf("mallocs per sl.Logf(WARNING, \"%%s is a log message with level %%d\", \"This\", WARNING): %d\n", mallocs/N) - - // Console logger (not logged) - sl = NewDefaultLogger(INFO) - mallocs = 0 - getMallocs() - for i := 0; i < N; i++ { - sl.Log(DEBUG, "here", "This is a DEBUG log message") - } - mallocs += getMallocs() - fmt.Printf("mallocs per unlogged sl.Log((WARNING, \"here\", \"This is a log message\"): %d\n", mallocs/N) - - // Console logger formatted (not logged) - mallocs = 0 - getMallocs() - for i := 0; i < N; i++ { - sl.Logf(DEBUG, "%s is a log message with level %d", "This", DEBUG) - } - mallocs += getMallocs() - fmt.Printf("mallocs per unlogged sl.Logf(WARNING, \"%%s is a log message with level %%d\", \"This\", WARNING): %d\n", mallocs/N) -} - -func TestXMLConfig(t *testing.T) { - const ( - configfile = "example.xml" - ) - - fd, err := os.Create(configfile) - if err != nil { - t.Fatalf("Could not open %s for writing: %s", configfile, err) - } - - fmt.Fprintln(fd, "") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, " stdout") - fmt.Fprintln(fd, " console") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, " DEBUG") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, " file") - fmt.Fprintln(fd, " file") - fmt.Fprintln(fd, " FINEST") - fmt.Fprintln(fd, " test.log") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, " [%D %T] [%L] (%S) %M") - fmt.Fprintln(fd, " false ") - fmt.Fprintln(fd, " 0M ") - fmt.Fprintln(fd, " 0K ") - fmt.Fprintln(fd, " true ") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, " xmllog") - fmt.Fprintln(fd, " xml") - fmt.Fprintln(fd, " TRACE") - fmt.Fprintln(fd, " trace.xml") - fmt.Fprintln(fd, " true ") - fmt.Fprintln(fd, " 100M ") - fmt.Fprintln(fd, " 6K ") - fmt.Fprintln(fd, " false ") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, " donotopen") - fmt.Fprintln(fd, " socket") - fmt.Fprintln(fd, " FINEST") - fmt.Fprintln(fd, " 192.168.1.255:12124 ") - fmt.Fprintln(fd, " udp ") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, "") - fd.Close() - - log := make(Logger) - log.LoadConfiguration(configfile) - defer os.Remove("trace.xml") - defer os.Remove("test.log") - defer log.Close() - - // Make sure we got all loggers - if len(log) != 3 { - t.Fatalf("XMLConfig: Expected 3 filters, found %d", len(log)) - } - - // Make sure they're the right keys - if _, ok := log["stdout"]; !ok { - t.Errorf("XMLConfig: Expected stdout logger") - } - if _, ok := log["file"]; !ok { - t.Fatalf("XMLConfig: Expected file logger") - } - if _, ok := log["xmllog"]; !ok { - t.Fatalf("XMLConfig: Expected xmllog logger") - } - - // Make sure they're the right type - if _, ok := log["stdout"].LogWriter.(ConsoleLogWriter); !ok { - t.Fatalf("XMLConfig: Expected stdout to be ConsoleLogWriter, found %T", log["stdout"].LogWriter) - } - if _, ok := log["file"].LogWriter.(*FileLogWriter); !ok { - t.Fatalf("XMLConfig: Expected file to be *FileLogWriter, found %T", log["file"].LogWriter) - } - if _, ok := log["xmllog"].LogWriter.(*FileLogWriter); !ok { - t.Fatalf("XMLConfig: Expected xmllog to be *FileLogWriter, found %T", log["xmllog"].LogWriter) - } - - // Make sure levels are set - if lvl := log["stdout"].Level; lvl != DEBUG { - t.Errorf("XMLConfig: Expected stdout to be set to level %d, found %d", DEBUG, lvl) - } - if lvl := log["file"].Level; lvl != FINEST { - t.Errorf("XMLConfig: Expected file to be set to level %d, found %d", FINEST, lvl) - } - if lvl := log["xmllog"].Level; lvl != TRACE { - t.Errorf("XMLConfig: Expected xmllog to be set to level %d, found %d", TRACE, lvl) - } - - // Make sure the w is open and points to the right file - if fname := log["file"].LogWriter.(*FileLogWriter).file.Name(); fname != "test.log" { - t.Errorf("XMLConfig: Expected file to have opened %s, found %s", "test.log", fname) - } - - // Make sure the XLW is open and points to the right file - if fname := log["xmllog"].LogWriter.(*FileLogWriter).file.Name(); fname != "trace.xml" { - t.Errorf("XMLConfig: Expected xmllog to have opened %s, found %s", "trace.xml", fname) - } - - // Move XML log file - os.Rename(configfile, "examples/"+configfile) // Keep this so that an example with the documentation is available -} - -func BenchmarkFormatLogRecord(b *testing.B) { - const updateEvery = 1 - rec := &LogRecord{ - Level: CRITICAL, - Created: now, - Source: "source", - Message: "message", - } - for i := 0; i < b.N; i++ { - rec.Created = rec.Created.Add(1 * time.Second / updateEvery) - if i%2 == 0 { - FormatLogRecord(FORMAT_DEFAULT, rec) - } else { - FormatLogRecord(FORMAT_SHORT, rec) - } - } -} - -func BenchmarkConsoleLog(b *testing.B) { - /* This doesn't seem to work on OS X - sink, err := os.Open(os.DevNull) - if err != nil { - panic(err) - } - if err := syscall.Dup2(int(sink.Fd()), syscall.Stdout); err != nil { - panic(err) - } - */ - - stdout = ioutil.Discard - sl := NewDefaultLogger(INFO) - for i := 0; i < b.N; i++ { - sl.Log(WARNING, "here", "This is a log message") - } -} - -func BenchmarkConsoleNotLogged(b *testing.B) { - sl := NewDefaultLogger(INFO) - for i := 0; i < b.N; i++ { - sl.Log(DEBUG, "here", "This is a log message") - } -} - -func BenchmarkConsoleUtilLog(b *testing.B) { - sl := NewDefaultLogger(INFO) - for i := 0; i < b.N; i++ { - sl.Info("%s is a log message", "This") - } -} - -func BenchmarkConsoleUtilNotLog(b *testing.B) { - sl := NewDefaultLogger(INFO) - for i := 0; i < b.N; i++ { - sl.Debug("%s is a log message", "This") - } -} - -func BenchmarkFileLog(b *testing.B) { - sl := make(Logger) - b.StopTimer() - sl.AddFilter("file", INFO, NewFileLogWriter("benchlog.log", false)) - b.StartTimer() - for i := 0; i < b.N; i++ { - sl.Log(WARNING, "here", "This is a log message") - } - b.StopTimer() - os.Remove("benchlog.log") -} - -func BenchmarkFileNotLogged(b *testing.B) { - sl := make(Logger) - b.StopTimer() - sl.AddFilter("file", INFO, NewFileLogWriter("benchlog.log", false)) - b.StartTimer() - for i := 0; i < b.N; i++ { - sl.Log(DEBUG, "here", "This is a log message") - } - b.StopTimer() - os.Remove("benchlog.log") -} - -func BenchmarkFileUtilLog(b *testing.B) { - sl := make(Logger) - b.StopTimer() - sl.AddFilter("file", INFO, NewFileLogWriter("benchlog.log", false)) - b.StartTimer() - for i := 0; i < b.N; i++ { - sl.Info("%s is a log message", "This") - } - b.StopTimer() - os.Remove("benchlog.log") -} - -func BenchmarkFileUtilNotLog(b *testing.B) { - sl := make(Logger) - b.StopTimer() - sl.AddFilter("file", INFO, NewFileLogWriter("benchlog.log", false)) - b.StartTimer() - for i := 0; i < b.N; i++ { - sl.Debug("%s is a log message", "This") - } - b.StopTimer() - os.Remove("benchlog.log") -} - -// Benchmark results (darwin amd64 6g) -//elog.BenchmarkConsoleLog 100000 22819 ns/op -//elog.BenchmarkConsoleNotLogged 2000000 879 ns/op -//elog.BenchmarkConsoleUtilLog 50000 34380 ns/op -//elog.BenchmarkConsoleUtilNotLog 1000000 1339 ns/op -//elog.BenchmarkFileLog 100000 26497 ns/op -//elog.BenchmarkFileNotLogged 2000000 821 ns/op -//elog.BenchmarkFileUtilLog 50000 33945 ns/op -//elog.BenchmarkFileUtilNotLog 1000000 1258 ns/op diff --git a/vendor/_nuts/code.google.com/p/log4go/pattlog.go b/vendor/_nuts/code.google.com/p/log4go/pattlog.go deleted file mode 100644 index 8224302b..00000000 --- a/vendor/_nuts/code.google.com/p/log4go/pattlog.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (C) 2010, Kyle Lemons . All rights reserved. - -package log4go - -import ( - "fmt" - "bytes" - "io" -) - -const ( - FORMAT_DEFAULT = "[%D %T] [%L] (%S) %M" - FORMAT_SHORT = "[%t %d] [%L] %M" - FORMAT_ABBREV = "[%L] %M" -) - -type formatCacheType struct { - LastUpdateSeconds int64 - shortTime, shortDate string - longTime, longDate string -} - -var formatCache = &formatCacheType{} - -// Known format codes: -// %T - Time (15:04:05 MST) -// %t - Time (15:04) -// %D - Date (2006/01/02) -// %d - Date (01/02/06) -// %L - Level (FNST, FINE, DEBG, TRAC, WARN, EROR, CRIT) -// %S - Source -// %M - Message -// Ignores unknown formats -// Recommended: "[%D %T] [%L] (%S) %M" -func FormatLogRecord(format string, rec *LogRecord) string { - if rec == nil { - return "" - } - if len(format) == 0 { - return "" - } - - out := bytes.NewBuffer(make([]byte, 0, 64)) - secs := rec.Created.UnixNano() / 1e9 - - cache := *formatCache - if cache.LastUpdateSeconds != secs { - month, day, year := rec.Created.Month(), rec.Created.Day(), rec.Created.Year() - hour, minute, second := rec.Created.Hour(), rec.Created.Minute(), rec.Created.Second() - zone, _ := rec.Created.Zone() - updated := &formatCacheType{ - LastUpdateSeconds: secs, - shortTime: fmt.Sprintf("%02d:%02d", hour, minute), - shortDate: fmt.Sprintf("%02d/%02d/%02d", month, day, year%100), - longTime: fmt.Sprintf("%02d:%02d:%02d %s", hour, minute, second, zone), - longDate: fmt.Sprintf("%04d/%02d/%02d", year, month, day), - } - cache = *updated - formatCache = updated - } - - // Split the string into pieces by % signs - pieces := bytes.Split([]byte(format), []byte{'%'}) - - // Iterate over the pieces, replacing known formats - for i, piece := range pieces { - if i > 0 && len(piece) > 0 { - switch piece[0] { - case 'T': - out.WriteString(cache.longTime) - case 't': - out.WriteString(cache.shortTime) - case 'D': - out.WriteString(cache.longDate) - case 'd': - out.WriteString(cache.shortDate) - case 'L': - out.WriteString(levelStrings[rec.Level]) - case 'S': - out.WriteString(rec.Source) - case 'M': - out.WriteString(rec.Message) - } - if len(piece) > 1 { - out.Write(piece[1:]) - } - } else if len(piece) > 0 { - out.Write(piece) - } - } - out.WriteByte('\n') - - return out.String() -} - -// This is the standard writer that prints to standard output. -type FormatLogWriter chan *LogRecord - -// This creates a new FormatLogWriter -func NewFormatLogWriter(out io.Writer, format string) FormatLogWriter { - records := make(FormatLogWriter, LogBufferLength) - go records.run(out, format) - return records -} - -func (w FormatLogWriter) run(out io.Writer, format string) { - for rec := range w { - fmt.Fprint(out, FormatLogRecord(format, rec)) - } -} - -// This is the FormatLogWriter's output method. This will block if the output -// buffer is full. -func (w FormatLogWriter) LogWrite(rec *LogRecord) { - w <- rec -} - -// Close stops the logger from sending messages to standard output. Attempts to -// send log messages to this logger after a Close have undefined behavior. -func (w FormatLogWriter) Close() { - close(w) -} diff --git a/vendor/_nuts/code.google.com/p/log4go/socklog.go b/vendor/_nuts/code.google.com/p/log4go/socklog.go deleted file mode 100644 index 1d224a99..00000000 --- a/vendor/_nuts/code.google.com/p/log4go/socklog.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (C) 2010, Kyle Lemons . All rights reserved. - -package log4go - -import ( - "encoding/json" - "fmt" - "net" - "os" -) - -// This log writer sends output to a socket -type SocketLogWriter chan *LogRecord - -// This is the SocketLogWriter's output method -func (w SocketLogWriter) LogWrite(rec *LogRecord) { - w <- rec -} - -func (w SocketLogWriter) Close() { - close(w) -} - -func NewSocketLogWriter(proto, hostport string) SocketLogWriter { - sock, err := net.Dial(proto, hostport) - if err != nil { - fmt.Fprintf(os.Stderr, "NewSocketLogWriter(%q): %s\n", hostport, err) - return nil - } - - w := SocketLogWriter(make(chan *LogRecord, LogBufferLength)) - - go func() { - defer func() { - if sock != nil && proto == "tcp" { - sock.Close() - } - }() - - for rec := range w { - // Marshall into JSON - js, err := json.Marshal(rec) - if err != nil { - fmt.Fprint(os.Stderr, "SocketLogWriter(%q): %s", hostport, err) - return - } - - _, err = sock.Write(js) - if err != nil { - fmt.Fprint(os.Stderr, "SocketLogWriter(%q): %s", hostport, err) - return - } - } - }() - - return w -} diff --git a/vendor/_nuts/code.google.com/p/log4go/termlog.go b/vendor/_nuts/code.google.com/p/log4go/termlog.go deleted file mode 100644 index 1ed2e4e0..00000000 --- a/vendor/_nuts/code.google.com/p/log4go/termlog.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (C) 2010, Kyle Lemons . All rights reserved. - -package log4go - -import ( - "io" - "os" - "fmt" -) - -var stdout io.Writer = os.Stdout - -// This is the standard writer that prints to standard output. -type ConsoleLogWriter chan *LogRecord - -// This creates a new ConsoleLogWriter -func NewConsoleLogWriter() ConsoleLogWriter { - records := make(ConsoleLogWriter, LogBufferLength) - go records.run(stdout) - return records -} - -func (w ConsoleLogWriter) run(out io.Writer) { - var timestr string - var timestrAt int64 - - for rec := range w { - if at := rec.Created.UnixNano() / 1e9; at != timestrAt { - timestr, timestrAt = rec.Created.Format("01/02/06 15:04:05"), at - } - fmt.Fprint(out, "[", timestr, "] [", levelStrings[rec.Level], "] ", rec.Message, "\n") - } -} - -// This is the ConsoleLogWriter's output method. This will block if the output -// buffer is full. -func (w ConsoleLogWriter) LogWrite(rec *LogRecord) { - w <- rec -} - -// Close stops the logger from sending messages to standard output. Attempts to -// send log messages to this logger after a Close have undefined behavior. -func (w ConsoleLogWriter) Close() { - close(w) -} diff --git a/vendor/_nuts/code.google.com/p/log4go/wrapper.go b/vendor/_nuts/code.google.com/p/log4go/wrapper.go deleted file mode 100644 index 10ecd88e..00000000 --- a/vendor/_nuts/code.google.com/p/log4go/wrapper.go +++ /dev/null @@ -1,278 +0,0 @@ -// Copyright (C) 2010, Kyle Lemons . All rights reserved. - -package log4go - -import ( - "errors" - "os" - "fmt" - "strings" -) - -var ( - Global Logger -) - -func init() { - Global = NewDefaultLogger(DEBUG) -} - -// Wrapper for (*Logger).LoadConfiguration -func LoadConfiguration(filename string) { - Global.LoadConfiguration(filename) -} - -// Wrapper for (*Logger).AddFilter -func AddFilter(name string, lvl level, writer LogWriter) { - Global.AddFilter(name, lvl, writer) -} - -// Wrapper for (*Logger).Close (closes and removes all logwriters) -func Close() { - Global.Close() -} - -func Crash(args ...interface{}) { - if len(args) > 0 { - Global.intLogf(CRITICAL, strings.Repeat(" %v", len(args))[1:], args...) - } - panic(args) -} - -// Logs the given message and crashes the program -func Crashf(format string, args ...interface{}) { - Global.intLogf(CRITICAL, format, args...) - Global.Close() // so that hopefully the messages get logged - panic(fmt.Sprintf(format, args...)) -} - -// Compatibility with `log` -func Exit(args ...interface{}) { - if len(args) > 0 { - Global.intLogf(ERROR, strings.Repeat(" %v", len(args))[1:], args...) - } - Global.Close() // so that hopefully the messages get logged - os.Exit(0) -} - -// Compatibility with `log` -func Exitf(format string, args ...interface{}) { - Global.intLogf(ERROR, format, args...) - Global.Close() // so that hopefully the messages get logged - os.Exit(0) -} - -// Compatibility with `log` -func Stderr(args ...interface{}) { - if len(args) > 0 { - Global.intLogf(ERROR, strings.Repeat(" %v", len(args))[1:], args...) - } -} - -// Compatibility with `log` -func Stderrf(format string, args ...interface{}) { - Global.intLogf(ERROR, format, args...) -} - -// Compatibility with `log` -func Stdout(args ...interface{}) { - if len(args) > 0 { - Global.intLogf(INFO, strings.Repeat(" %v", len(args))[1:], args...) - } -} - -// Compatibility with `log` -func Stdoutf(format string, args ...interface{}) { - Global.intLogf(INFO, format, args...) -} - -// Send a log message manually -// Wrapper for (*Logger).Log -func Log(lvl level, source, message string) { - Global.Log(lvl, source, message) -} - -// Send a formatted log message easily -// Wrapper for (*Logger).Logf -func Logf(lvl level, format string, args ...interface{}) { - Global.intLogf(lvl, format, args...) -} - -// Send a closure log message -// Wrapper for (*Logger).Logc -func Logc(lvl level, closure func() string) { - Global.intLogc(lvl, closure) -} - -// Utility for finest log messages (see Debug() for parameter explanation) -// Wrapper for (*Logger).Finest -func Finest(arg0 interface{}, args ...interface{}) { - const ( - lvl = FINEST - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - Global.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - Global.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - Global.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Utility for fine log messages (see Debug() for parameter explanation) -// Wrapper for (*Logger).Fine -func Fine(arg0 interface{}, args ...interface{}) { - const ( - lvl = FINE - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - Global.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - Global.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - Global.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Utility for debug log messages -// When given a string as the first argument, this behaves like Logf but with the DEBUG log level (e.g. the first argument is interpreted as a format for the latter arguments) -// When given a closure of type func()string, this logs the string returned by the closure iff it will be logged. The closure runs at most one time. -// When given anything else, the log message will be each of the arguments formatted with %v and separated by spaces (ala Sprint). -// Wrapper for (*Logger).Debug -func Debug(arg0 interface{}, args ...interface{}) { - const ( - lvl = DEBUG - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - Global.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - Global.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - Global.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Utility for trace log messages (see Debug() for parameter explanation) -// Wrapper for (*Logger).Trace -func Trace(arg0 interface{}, args ...interface{}) { - const ( - lvl = TRACE - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - Global.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - Global.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - Global.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Utility for info log messages (see Debug() for parameter explanation) -// Wrapper for (*Logger).Info -func Info(arg0 interface{}, args ...interface{}) { - const ( - lvl = INFO - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - Global.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - Global.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - Global.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Utility for warn log messages (returns an error for easy function returns) (see Debug() for parameter explanation) -// These functions will execute a closure exactly once, to build the error message for the return -// Wrapper for (*Logger).Warn -func Warn(arg0 interface{}, args ...interface{}) error { - const ( - lvl = WARNING - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - Global.intLogf(lvl, first, args...) - return errors.New(fmt.Sprintf(first, args...)) - case func() string: - // Log the closure (no other arguments used) - str := first() - Global.intLogf(lvl, "%s", str) - return errors.New(str) - default: - // Build a format string so that it will be similar to Sprint - Global.intLogf(lvl, fmt.Sprint(first)+strings.Repeat(" %v", len(args)), args...) - return errors.New(fmt.Sprint(first) + fmt.Sprintf(strings.Repeat(" %v", len(args)), args...)) - } - return nil -} - -// Utility for error log messages (returns an error for easy function returns) (see Debug() for parameter explanation) -// These functions will execute a closure exactly once, to build the error message for the return -// Wrapper for (*Logger).Error -func Error(arg0 interface{}, args ...interface{}) error { - const ( - lvl = ERROR - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - Global.intLogf(lvl, first, args...) - return errors.New(fmt.Sprintf(first, args...)) - case func() string: - // Log the closure (no other arguments used) - str := first() - Global.intLogf(lvl, "%s", str) - return errors.New(str) - default: - // Build a format string so that it will be similar to Sprint - Global.intLogf(lvl, fmt.Sprint(first)+strings.Repeat(" %v", len(args)), args...) - return errors.New(fmt.Sprint(first) + fmt.Sprintf(strings.Repeat(" %v", len(args)), args...)) - } - return nil -} - -// Utility for critical log messages (returns an error for easy function returns) (see Debug() for parameter explanation) -// These functions will execute a closure exactly once, to build the error message for the return -// Wrapper for (*Logger).Critical -func Critical(arg0 interface{}, args ...interface{}) error { - const ( - lvl = CRITICAL - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - Global.intLogf(lvl, first, args...) - return errors.New(fmt.Sprintf(first, args...)) - case func() string: - // Log the closure (no other arguments used) - str := first() - Global.intLogf(lvl, "%s", str) - return errors.New(str) - default: - // Build a format string so that it will be similar to Sprint - Global.intLogf(lvl, fmt.Sprint(first)+strings.Repeat(" %v", len(args)), args...) - return errors.New(fmt.Sprint(first) + fmt.Sprintf(strings.Repeat(" %v", len(args)), args...)) - } - return nil -} diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/utils/decode_auth.go b/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/utils/decode_auth.go deleted file mode 100644 index d2d1d1f5..00000000 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/utils/decode_auth.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "encoding/base64" - "flag" - "fmt" -) - -func main() { - var ntlmVersion = flag.Int("ntlm", 2, "NTLM version to try: 1 or 2") - flag.Parse() - var data string - fmt.Println("Paste the base64 encoded Authenticate message (with no line breaks):") - fmt.Scanf("%s", &data) - authenticateData, _ := base64.StdEncoding.DecodeString(data) - a, _ := ntlm.ParseAuthenticateMessage(authenticateData, *ntlmVersion) - fmt.Printf(a.String()) -} diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/utils/test_auth.go b/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/utils/test_auth.go deleted file mode 100644 index 2338ba10..00000000 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/utils/test_auth.go +++ /dev/null @@ -1,87 +0,0 @@ -package main - -import ( - "encoding/base64" - "fmt" - "github.com/ThomsonReutersEikon/go-ntlm/ntlm" -) - -func main() { - // ntlm v2 - // challengeMessage := "TlRMTVNTUAACAAAAAAAAADgAAABVgphiPXSy0E6+HrMAAAAAAAAAAKIAogA4AAAABQEoCgAAAA8CAA4AUgBFAFUAVABFAFIAUwABABwAVQBLAEIAUAAtAEMAQgBUAFIATQBGAEUAMAA2AAQAFgBSAGUAdQB0AGUAcgBzAC4AbgBlAHQAAwA0AHUAawBiAHAALQBjAGIAdAByAG0AZgBlADAANgAuAFIAZQB1AHQAZQByAHMALgBuAGUAdAAFABYAUgBlAHUAdABlAHIAcwAuAG4AZQB0AAAAAAA=" - // authenticateMessage := "TlRMTVNTUAADAAAAGAAYALYAAADSANIAzgAAADQANABIAAAAIAAgAHwAAAAaABoAnAAAABAAEACgAQAAVYKQQgUCzg4AAAAPYQByAHIAYQB5ADEAMgAuAG0AcwBnAHQAcwB0AC4AcgBlAHUAdABlAHIAcwAuAGMAbwBtAHUAcwBlAHIAcwB0AHIAZQBzAHMAMQAwADAAMAAwADgATgBZAEMAVgBBADEAMgBTADIAQwBNAFMAQQBPYrLjU4h0YlWZeEoNvTJtBQMnnJuAeUwsP+vGmAHNRBpgZ+4ChQLqAQEAAAAAAACPFEIFjx7OAQUDJ5ybgHlMAAAAAAIADgBSAEUAVQBUAEUAUgBTAAEAHABVAEsAQgBQAC0AQwBCAFQAUgBNAEYARQAwADYABAAWAFIAZQB1AHQAZQByAHMALgBuAGUAdAADADQAdQBrAGIAcAAtAGMAYgB0AHIAbQBmAGUAMAA2AC4AUgBlAHUAdABlAHIAcwAuAG4AZQB0AAUAFgBSAGUAdQB0AGUAcgBzAC4AbgBlAHQAAAAAAAAAAAANuvnqD3K88ZpjkLleL0NW" - - //LCS v1 - //challengeMessage := "TlRMTVNTUAACAAAAAAAAADgAAADzgpjid08w9p89DLUAAAAAAAAAAPAA8AA4AAAABQLODgAAAA8CAA4AQQBSAFIAQQBZADEAMgABABYATgBZAEMAUwBNAFMARwA5ADkAMQAyAAQANABhAHIAcgBhAHkAMQAyAC4AbQBzAGcAdABzAHQALgByAGUAdQB0AGUAcgBzAC4AYwBvAG0AAwBMAE4AWQBDAFMATQBTAEcAOQA5ADEAMgAuAGEAcgByAGEAeQAxADIALgBtAHMAZwB0AHMAdAAuAHIAZQB1AHQAZQByAHMALgBjAG8AbQAFADQAYQByAHIAYQB5ADEAMgAuAG0AcwBnAHQAcwB0AC4AcgBlAHUAdABlAHIAcwAuAGMAbwBtAAAAAAA=" - //authenticateMessage := "TlRMTVNTUAADAAAAGAAYAKwAAAAYABgAxAAAAAAAAABYAAAANgA2AFgAAAAeAB4AjgAAABAAEADcAAAAVYKQYgYBsR0AAAAPUJSCwwcYcGpE0Zp9GsD3RDAANQAwADAANAA1AC4AcgBtAHcAYQB0AGUAcwB0AEAAcgBlAHUAdABlAHIAcwAuAGMAbwBtAFcASQBOAC0AMABEAEQAQQBCAEsAQwAxAFUASQA4ALIsDLYZktr3YlJDLyVT6GHgwNA+DFdM87IsDLYZktr3YlJDLyVT6GHgwNA+DFdM851g+vaa4CHvomwyYmjbB1M=" - - //US - //challengeMessage := "TlRMTVNTUAACAAAAAAAAADgAAABVgphisF5WgZrWn4MAAAAAAAAAAKIAogA4AAAABQEoCgAAAA8CAA4AUgBFAFUAVABFAFIAUwABABwAVQBLAEIAUAAtAEMAQgBUAFIATQBGAEUAMAA2AAQAFgBSAGUAdQB0AGUAcgBzAC4AbgBlAHQAAwA0AHUAawBiAHAALQBjAGIAdAByAG0AZgBlADAANgAuAFIAZQB1AHQAZQByAHMALgBuAGUAdAAFABYAUgBlAHUAdABlAHIAcwAuAG4AZQB0AAAAAAA=" - //authenticateMessage := "TlRMTVNTUAADAAAAGAAYAKwAAAAYABgAxAAAAAAAAABYAAAANgA2AFgAAAAeAB4AjgAAABAAEADcAAAAVYKQYgYBsR0AAAAPJc+NGJ4qgACnkkGb9J8RezAANQAwADAANAA1AC4AcgBtAHcAYQB0AGUAcwB0AEAAcgBlAHUAdABlAHIAcwAuAGMAbwBtAFcASQBOAC0AMABEAEQAQQBCAEsAQwAxAFUASQA4AJLPhCq8UHZjb5sEjtoaJtWBY2ZwNZyujpLPhCq8UHZjb5sEjtoaJtWBY2ZwNZyujtW8TsZdZ6PMc1ipWbL7VgY=" - - //US again - challengeMessage := "TlRMTVNTUAACAAAAAAAAADgAAABVgphiMx43owKH33MAAAAAAAAAAKIAogA4AAAABQEoCgAAAA8CAA4AUgBFAFUAVABFAFIAUwABABwAVQBLAEIAUAAtAEMAQgBUAFIATQBGAEUAMAA2AAQAFgBSAGUAdQB0AGUAcgBzAC4AbgBlAHQAAwA0AHUAawBiAHAALQBjAGIAdAByAG0AZgBlADAANgAuAFIAZQB1AHQAZQByAHMALgBuAGUAdAAFABYAUgBlAHUAdABlAHIAcwAuAG4AZQB0AAAAAAA=" - authenticateMessage := "TlRMTVNTUAADAAAAGAAYAKwAAAAYABgAxAAAAAAAAABYAAAANgA2AFgAAAAeAB4AjgAAABAAEADcAAAAVYKQYgYBsR0AAAAPukU9WmBJLdSLU2NvXjNgUzAANQAwADAANAA1AC4AcgBtAHcAYQB0AGUAcwB0AEAAcgBlAHUAdABlAHIAcwAuAGMAbwBtAFcASQBOAC0AMABEAEQAQQBCAEsAQwAxAFUASQA4AOLIAEYvI6zgw2+MBf8xHSTZhIfVaKIIFuLIAEYvI6zgw2+MBf8xHSTZhIfVaKIIFroZDwl770tY/oFQk38nnuI=" - - server, err := ntlm.CreateServerSession(ntlm.Version2, ntlm.ConnectionlessMode) - server.SetUserInfo("050045.rmwatest@reuters.com", "Welcome1", "") - - challengeData, _ := base64.StdEncoding.DecodeString(challengeMessage) - c, _ := ntlm.ParseChallengeMessage(challengeData) - - fmt.Println("----- Challenge Message ----- ") - fmt.Println(c.String()) - fmt.Println("----- END Challenge Message ----- ") - - authenticateData, _ := base64.StdEncoding.DecodeString(authenticateMessage) - var context ntlm.ServerSession - - msg, err := ntlm.ParseAuthenticateMessage(authenticateData, 2) - if err != nil { - msg2, newErr := ntlm.ParseAuthenticateMessage(authenticateData, 1) - if newErr != nil { - fmt.Printf("Error ParseAuthenticateMessage , %s", err) - return - } - - // Message parsed correctly as NTLMv1 so assume the session is v1 and reset the server session - newContext, err := ntlm.CreateServerSession(ntlm.Version1, ntlm.ConnectionlessMode) - newContext.SetUserInfo(server.GetUserInfo()) - if err != nil { - fmt.Println("Could not create NTLMv1 session") - return - } - - // Need the originally generated server challenge so we can process the response - newContext.SetServerChallenge(c.ServerChallenge) - // err = server.ProcessAuthenticateMessage(msg) - err = newContext.ProcessAuthenticateMessage(msg2) - if err != nil { - fmt.Printf("Could not process authenticate v1 message: %s\n", err) - return - } - // Set the security context to now be NTLMv1 - context = newContext - fmt.Println("----- Authenticate Message ----- ") - fmt.Println(msg2.String()) - fmt.Println("----- END Authenticate Message ----- ") - - } else { - context = server - // Need the server challenge to be set - server.SetServerChallenge(c.ServerChallenge) - - // err = server.ProcessAuthenticateMessage(msg) - err = context.ProcessAuthenticateMessage(msg) - if err != nil { - fmt.Printf("Could not process authenticate message: %s\n", err) - return - } - fmt.Println("----- Authenticate Message ----- ") - fmt.Println(msg.String()) - fmt.Println("----- END Authenticate Message ----- ") - - } - - fmt.Println("success") -} diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/.gitignore b/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/.gitignore deleted file mode 100644 index 6e92f57d..00000000 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/.gitignore +++ /dev/null @@ -1 +0,0 @@ -tags diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/LICENSE b/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/LICENSE deleted file mode 100644 index 7093402b..00000000 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright (c) 2010, Kyle Lemons . All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/README b/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/README deleted file mode 100644 index 16d80ecb..00000000 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/README +++ /dev/null @@ -1,12 +0,0 @@ -Please see http://log4go.googlecode.com/ - -Installation: -- Run `goinstall log4go.googlecode.com/hg` - -Usage: -- Add the following import: -import l4g "log4go.googlecode.com/hg" - -Acknowledgements: -- pomack - For providing awesome patches to bring log4go up to the latest Go spec diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/config.go b/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/config.go deleted file mode 100644 index 324dc16f..00000000 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/config.go +++ /dev/null @@ -1,283 +0,0 @@ -// Copyright (C) 2010, Kyle Lemons . All rights reserved. - -package log4go - -import ( - "encoding/xml" - "fmt" - "io/ioutil" - "os" - "strconv" - "strings" -) - -type xmlProperty struct { - Name string `xml:"name,attr"` - Value string `xml:",chardata"` -} - -type xmlFilter struct { - Enabled string `xml:"enabled,attr"` - Tag string `xml:"tag"` - Level string `xml:"level"` - Type string `xml:"type"` - Property []xmlProperty `xml:"property"` -} - -type xmlLoggerConfig struct { - Filter []xmlFilter `xml:"filter"` -} - -// Load XML configuration; see examples/example.xml for documentation -func (log Logger) LoadConfiguration(filename string) { - log.Close() - - // Open the configuration file - fd, err := os.Open(filename) - if err != nil { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Could not open %q for reading: %s\n", filename, err) - os.Exit(1) - } - - contents, err := ioutil.ReadAll(fd) - if err != nil { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Could not read %q: %s\n", filename, err) - os.Exit(1) - } - - xc := new(xmlLoggerConfig) - if err := xml.Unmarshal(contents, xc); err != nil { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Could not parse XML configuration in %q: %s\n", filename, err) - os.Exit(1) - } - - for _, xmlfilt := range xc.Filter { - var filt LogWriter - var lvl level - bad, good, enabled := false, true, false - - // Check required children - if len(xmlfilt.Enabled) == 0 { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Required attribute %s for filter missing in %s\n", "enabled", filename) - bad = true - } else { - enabled = xmlfilt.Enabled != "false" - } - if len(xmlfilt.Tag) == 0 { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Required child <%s> for filter missing in %s\n", "tag", filename) - bad = true - } - if len(xmlfilt.Type) == 0 { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Required child <%s> for filter missing in %s\n", "type", filename) - bad = true - } - if len(xmlfilt.Level) == 0 { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Required child <%s> for filter missing in %s\n", "level", filename) - bad = true - } - - switch xmlfilt.Level { - case "FINEST": - lvl = FINEST - case "FINE": - lvl = FINE - case "DEBUG": - lvl = DEBUG - case "TRACE": - lvl = TRACE - case "INFO": - lvl = INFO - case "WARNING": - lvl = WARNING - case "ERROR": - lvl = ERROR - case "CRITICAL": - lvl = CRITICAL - default: - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Required child <%s> for filter has unknown value in %s: %s\n", "level", filename, xmlfilt.Level) - bad = true - } - - // Just so all of the required attributes are errored at the same time if missing - if bad { - os.Exit(1) - } - - switch xmlfilt.Type { - case "console": - filt, good = xmlToConsoleLogWriter(filename, xmlfilt.Property, enabled) - case "file": - filt, good = xmlToFileLogWriter(filename, xmlfilt.Property, enabled) - case "xml": - filt, good = xmlToXMLLogWriter(filename, xmlfilt.Property, enabled) - case "socket": - filt, good = xmlToSocketLogWriter(filename, xmlfilt.Property, enabled) - default: - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Could not load XML configuration in %s: unknown filter type \"%s\"\n", filename, xmlfilt.Type) - os.Exit(1) - } - - // Just so all of the required params are errored at the same time if wrong - if !good { - os.Exit(1) - } - - // If we're disabled (syntax and correctness checks only), don't add to logger - if !enabled { - continue - } - - log[xmlfilt.Tag] = &Filter{lvl, filt} - } -} - -func xmlToConsoleLogWriter(filename string, props []xmlProperty, enabled bool) (ConsoleLogWriter, bool) { - // Parse properties - for _, prop := range props { - switch prop.Name { - default: - fmt.Fprintf(os.Stderr, "LoadConfiguration: Warning: Unknown property \"%s\" for console filter in %s\n", prop.Name, filename) - } - } - - return NewConsoleLogWriter(), true -} - -// Parse a number with K/M/G suffixes based on thousands (1000) or 2^10 (1024) -func strToNumSuffix(str string, mult int) int { - num := 1 - if len(str) > 1 { - switch str[len(str)-1] { - case 'G', 'g': - num *= mult - fallthrough - case 'M', 'm': - num *= mult - fallthrough - case 'K', 'k': - num *= mult - str = str[0 : len(str)-1] - } - } - parsed, _ := strconv.Atoi(str) - return parsed * num -} -func xmlToFileLogWriter(filename string, props []xmlProperty, enabled bool) (*FileLogWriter, bool) { - file := "" - format := "[%D %T] [%L] (%S) %M" - maxlines := 0 - maxsize := 0 - daily := false - rotate := false - - // Parse properties - for _, prop := range props { - switch prop.Name { - case "filename": - file = strings.Trim(prop.Value, " \r\n") - case "format": - format = strings.Trim(prop.Value, " \r\n") - case "maxlines": - maxlines = strToNumSuffix(strings.Trim(prop.Value, " \r\n"), 1000) - case "maxsize": - maxsize = strToNumSuffix(strings.Trim(prop.Value, " \r\n"), 1024) - case "daily": - daily = strings.Trim(prop.Value, " \r\n") != "false" - case "rotate": - rotate = strings.Trim(prop.Value, " \r\n") != "false" - default: - fmt.Fprintf(os.Stderr, "LoadConfiguration: Warning: Unknown property \"%s\" for file filter in %s\n", prop.Name, filename) - } - } - - // Check properties - if len(file) == 0 { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Required property \"%s\" for file filter missing in %s\n", "filename", filename) - return nil, false - } - - // If it's disabled, we're just checking syntax - if !enabled { - return nil, true - } - - flw := NewFileLogWriter(file, rotate) - flw.SetFormat(format) - flw.SetRotateLines(maxlines) - flw.SetRotateSize(maxsize) - flw.SetRotateDaily(daily) - return flw, true -} - -func xmlToXMLLogWriter(filename string, props []xmlProperty, enabled bool) (*FileLogWriter, bool) { - file := "" - maxrecords := 0 - maxsize := 0 - daily := false - rotate := false - - // Parse properties - for _, prop := range props { - switch prop.Name { - case "filename": - file = strings.Trim(prop.Value, " \r\n") - case "maxrecords": - maxrecords = strToNumSuffix(strings.Trim(prop.Value, " \r\n"), 1000) - case "maxsize": - maxsize = strToNumSuffix(strings.Trim(prop.Value, " \r\n"), 1024) - case "daily": - daily = strings.Trim(prop.Value, " \r\n") != "false" - case "rotate": - rotate = strings.Trim(prop.Value, " \r\n") != "false" - default: - fmt.Fprintf(os.Stderr, "LoadConfiguration: Warning: Unknown property \"%s\" for xml filter in %s\n", prop.Name, filename) - } - } - - // Check properties - if len(file) == 0 { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Required property \"%s\" for xml filter missing in %s\n", "filename", filename) - return nil, false - } - - // If it's disabled, we're just checking syntax - if !enabled { - return nil, true - } - - xlw := NewXMLLogWriter(file, rotate) - xlw.SetRotateLines(maxrecords) - xlw.SetRotateSize(maxsize) - xlw.SetRotateDaily(daily) - return xlw, true -} - -func xmlToSocketLogWriter(filename string, props []xmlProperty, enabled bool) (SocketLogWriter, bool) { - endpoint := "" - protocol := "udp" - - // Parse properties - for _, prop := range props { - switch prop.Name { - case "endpoint": - endpoint = strings.Trim(prop.Value, " \r\n") - case "protocol": - protocol = strings.Trim(prop.Value, " \r\n") - default: - fmt.Fprintf(os.Stderr, "LoadConfiguration: Warning: Unknown property \"%s\" for file filter in %s\n", prop.Name, filename) - } - } - - // Check properties - if len(endpoint) == 0 { - fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Required property \"%s\" for file filter missing in %s\n", "endpoint", filename) - return nil, false - } - - // If it's disabled, we're just checking syntax - if !enabled { - return nil, true - } - - return NewSocketLogWriter(protocol, endpoint), true -} diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/examples/ConsoleLogWriter_Manual.go b/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/examples/ConsoleLogWriter_Manual.go deleted file mode 100644 index 7169ec97..00000000 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/examples/ConsoleLogWriter_Manual.go +++ /dev/null @@ -1,13 +0,0 @@ -package main - -import ( - "time" -) - -import l4g "github.com/github/git-lfs/vendor/_nuts/code.google.com/p/log4go" - -func main() { - log := l4g.NewLogger() - log.AddFilter("stdout", l4g.DEBUG, l4g.NewConsoleLogWriter()) - log.Info("The time is now: %s", time.Now().Format("15:04:05 MST 2006/01/02")) -} diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/examples/FileLogWriter_Manual.go b/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/examples/FileLogWriter_Manual.go deleted file mode 100644 index 872bb45b..00000000 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/examples/FileLogWriter_Manual.go +++ /dev/null @@ -1,57 +0,0 @@ -package main - -import ( - "bufio" - "fmt" - "io" - "os" - "time" -) - -import l4g "github.com/github/git-lfs/vendor/_nuts/code.google.com/p/log4go" - -const ( - filename = "flw.log" -) - -func main() { - // Get a new logger instance - log := l4g.NewLogger() - - // Create a default logger that is logging messages of FINE or higher - log.AddFilter("file", l4g.FINE, l4g.NewFileLogWriter(filename, false)) - log.Close() - - /* Can also specify manually via the following: (these are the defaults) */ - flw := l4g.NewFileLogWriter(filename, false) - flw.SetFormat("[%D %T] [%L] (%S) %M") - flw.SetRotate(false) - flw.SetRotateSize(0) - flw.SetRotateLines(0) - flw.SetRotateDaily(false) - log.AddFilter("file", l4g.FINE, flw) - - // Log some experimental messages - log.Finest("Everything is created now (notice that I will not be printing to the file)") - log.Info("The time is now: %s", time.Now().Format("15:04:05 MST 2006/01/02")) - log.Critical("Time to close out!") - - // Close the log - log.Close() - - // Print what was logged to the file (yes, I know I'm skipping error checking) - fd, _ := os.Open(filename) - in := bufio.NewReader(fd) - fmt.Print("Messages logged to file were: (line numbers not included)\n") - for lineno := 1; ; lineno++ { - line, err := in.ReadString('\n') - if err == io.EOF { - break - } - fmt.Printf("%3d:\t%s", lineno, line) - } - fd.Close() - - // Remove the file so it's not lying around - os.Remove(filename) -} diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/examples/SimpleNetLogServer.go b/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/examples/SimpleNetLogServer.go deleted file mode 100644 index 83c80ad1..00000000 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/examples/SimpleNetLogServer.go +++ /dev/null @@ -1,42 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "net" - "os" -) - -var ( - port = flag.String("p", "12124", "Port number to listen on") -) - -func e(err error) { - if err != nil { - fmt.Printf("Erroring out: %s\n", err) - os.Exit(1) - } -} - -func main() { - flag.Parse() - - // Bind to the port - bind, err := net.ResolveUDPAddr("0.0.0.0:" + *port) - e(err) - - // Create listener - listener, err := net.ListenUDP("udp", bind) - e(err) - - fmt.Printf("Listening to port %s...\n", *port) - for { - // read into a new buffer - buffer := make([]byte, 1024) - _, _, err := listener.ReadFrom(buffer) - e(err) - - // log to standard output - fmt.Println(string(buffer)) - } -} diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/examples/SocketLogWriter_Manual.go b/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/examples/SocketLogWriter_Manual.go deleted file mode 100644 index d553699f..00000000 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/examples/SocketLogWriter_Manual.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "time" -) - -import l4g "github.com/github/git-lfs/vendor/_nuts/code.google.com/p/log4go" - -func main() { - log := l4g.NewLogger() - log.AddFilter("network", l4g.FINEST, l4g.NewSocketLogWriter("udp", "192.168.1.255:12124")) - - // Run `nc -u -l -p 12124` or similar before you run this to see the following message - log.Info("The time is now: %s", time.Now().Format("15:04:05 MST 2006/01/02")) - - // This makes sure the output stream buffer is written - log.Close() -} diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/examples/XMLConfigurationExample.go b/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/examples/XMLConfigurationExample.go deleted file mode 100644 index d6485753..00000000 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/examples/XMLConfigurationExample.go +++ /dev/null @@ -1,13 +0,0 @@ -package main - -import l4g "github.com/github/git-lfs/vendor/_nuts/code.google.com/p/log4go" - -func main() { - // Load the configuration (isn't this easy?) - l4g.LoadConfiguration("example.xml") - - // And now we're ready! - l4g.Finest("This will only go to those of you really cool UDP kids! If you change enabled=true.") - l4g.Debug("Oh no! %d + %d = %d!", 2, 2, 2+2) - l4g.Info("About that time, eh chaps?") -} diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/examples/example.xml b/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/examples/example.xml deleted file mode 100644 index e791278c..00000000 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/examples/example.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - stdout - console - - DEBUG - - - file - file - FINEST - test.log - - [%D %T] [%L] (%S) %M - false - 0M - 0K - true - - - xmllog - xml - TRACE - trace.xml - true - 100M - 6K - false - - - donotopen - socket - FINEST - 192.168.1.255:12124 - udp - - diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/filelog.go b/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/filelog.go deleted file mode 100644 index 9cbd815d..00000000 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/filelog.go +++ /dev/null @@ -1,239 +0,0 @@ -// Copyright (C) 2010, Kyle Lemons . All rights reserved. - -package log4go - -import ( - "os" - "fmt" - "time" -) - -// This log writer sends output to a file -type FileLogWriter struct { - rec chan *LogRecord - rot chan bool - - // The opened file - filename string - file *os.File - - // The logging format - format string - - // File header/trailer - header, trailer string - - // Rotate at linecount - maxlines int - maxlines_curlines int - - // Rotate at size - maxsize int - maxsize_cursize int - - // Rotate daily - daily bool - daily_opendate int - - // Keep old logfiles (.001, .002, etc) - rotate bool -} - -// This is the FileLogWriter's output method -func (w *FileLogWriter) LogWrite(rec *LogRecord) { - w.rec <- rec -} - -func (w *FileLogWriter) Close() { - close(w.rec) -} - -// NewFileLogWriter creates a new LogWriter which writes to the given file and -// has rotation enabled if rotate is true. -// -// If rotate is true, any time a new log file is opened, the old one is renamed -// with a .### extension to preserve it. The various Set* methods can be used -// to configure log rotation based on lines, size, and daily. -// -// The standard log-line format is: -// [%D %T] [%L] (%S) %M -func NewFileLogWriter(fname string, rotate bool) *FileLogWriter { - w := &FileLogWriter{ - rec: make(chan *LogRecord, LogBufferLength), - rot: make(chan bool), - filename: fname, - format: "[%D %T] [%L] (%S) %M", - rotate: rotate, - } - - // open the file for the first time - if err := w.intRotate(); err != nil { - fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.filename, err) - return nil - } - - go func() { - defer func() { - if w.file != nil { - fmt.Fprint(w.file, FormatLogRecord(w.trailer, &LogRecord{Created: time.Now()})) - w.file.Close() - } - }() - - for { - select { - case <-w.rot: - if err := w.intRotate(); err != nil { - fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.filename, err) - return - } - case rec, ok := <-w.rec: - if !ok { - return - } - now := time.Now() - if (w.maxlines > 0 && w.maxlines_curlines >= w.maxlines) || - (w.maxsize > 0 && w.maxsize_cursize >= w.maxsize) || - (w.daily && now.Day() != w.daily_opendate) { - if err := w.intRotate(); err != nil { - fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.filename, err) - return - } - } - - // Perform the write - n, err := fmt.Fprint(w.file, FormatLogRecord(w.format, rec)) - if err != nil { - fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.filename, err) - return - } - - // Update the counts - w.maxlines_curlines++ - w.maxsize_cursize += n - } - } - }() - - return w -} - -// Request that the logs rotate -func (w *FileLogWriter) Rotate() { - w.rot <- true -} - -// If this is called in a threaded context, it MUST be synchronized -func (w *FileLogWriter) intRotate() error { - // Close any log file that may be open - if w.file != nil { - fmt.Fprint(w.file, FormatLogRecord(w.trailer, &LogRecord{Created: time.Now()})) - w.file.Close() - } - - // If we are keeping log files, move it to the next available number - if w.rotate { - _, err := os.Lstat(w.filename) - if err == nil { // file exists - // Find the next available number - num := 1 - fname := "" - for ; err == nil && num <= 999; num++ { - fname = w.filename + fmt.Sprintf(".%03d", num) - _, err = os.Lstat(fname) - } - // return error if the last file checked still existed - if err == nil { - return fmt.Errorf("Rotate: Cannot find free log number to rename %s\n", w.filename) - } - - // Rename the file to its newfound home - err = os.Rename(w.filename, fname) - if err != nil { - return fmt.Errorf("Rotate: %s\n", err) - } - } - } - - // Open the log file - fd, err := os.OpenFile(w.filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660) - if err != nil { - return err - } - w.file = fd - - now := time.Now() - fmt.Fprint(w.file, FormatLogRecord(w.header, &LogRecord{Created: now})) - - // Set the daily open date to the current date - w.daily_opendate = now.Day() - - // initialize rotation values - w.maxlines_curlines = 0 - w.maxsize_cursize = 0 - - return nil -} - -// Set the logging format (chainable). Must be called before the first log -// message is written. -func (w *FileLogWriter) SetFormat(format string) *FileLogWriter { - w.format = format - return w -} - -// Set the logfile header and footer (chainable). Must be called before the first log -// message is written. These are formatted similar to the FormatLogRecord (e.g. -// you can use %D and %T in your header/footer for date and time). -func (w *FileLogWriter) SetHeadFoot(head, foot string) *FileLogWriter { - w.header, w.trailer = head, foot - if w.maxlines_curlines == 0 { - fmt.Fprint(w.file, FormatLogRecord(w.header, &LogRecord{Created: time.Now()})) - } - return w -} - -// Set rotate at linecount (chainable). Must be called before the first log -// message is written. -func (w *FileLogWriter) SetRotateLines(maxlines int) *FileLogWriter { - //fmt.Fprintf(os.Stderr, "FileLogWriter.SetRotateLines: %v\n", maxlines) - w.maxlines = maxlines - return w -} - -// Set rotate at size (chainable). Must be called before the first log message -// is written. -func (w *FileLogWriter) SetRotateSize(maxsize int) *FileLogWriter { - //fmt.Fprintf(os.Stderr, "FileLogWriter.SetRotateSize: %v\n", maxsize) - w.maxsize = maxsize - return w -} - -// Set rotate daily (chainable). Must be called before the first log message is -// written. -func (w *FileLogWriter) SetRotateDaily(daily bool) *FileLogWriter { - //fmt.Fprintf(os.Stderr, "FileLogWriter.SetRotateDaily: %v\n", daily) - w.daily = daily - return w -} - -// SetRotate changes whether or not the old logs are kept. (chainable) Must be -// called before the first log message is written. If rotate is false, the -// files are overwritten; otherwise, they are rotated to another file before the -// new log is opened. -func (w *FileLogWriter) SetRotate(rotate bool) *FileLogWriter { - //fmt.Fprintf(os.Stderr, "FileLogWriter.SetRotate: %v\n", rotate) - w.rotate = rotate - return w -} - -// NewXMLLogWriter is a utility method for creating a FileLogWriter set up to -// output XML record log messages instead of line-based ones. -func NewXMLLogWriter(fname string, rotate bool) *FileLogWriter { - return NewFileLogWriter(fname, rotate).SetFormat( - ` - %D %T - %S - %M - `).SetHeadFoot("", "") -} diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/log4go.go b/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/log4go.go deleted file mode 100644 index ab4e857f..00000000 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/log4go.go +++ /dev/null @@ -1,484 +0,0 @@ -// Copyright (C) 2010, Kyle Lemons . All rights reserved. - -// Package log4go provides level-based and highly configurable logging. -// -// Enhanced Logging -// -// This is inspired by the logging functionality in Java. Essentially, you create a Logger -// object and create output filters for it. You can send whatever you want to the Logger, -// and it will filter that based on your settings and send it to the outputs. This way, you -// can put as much debug code in your program as you want, and when you're done you can filter -// out the mundane messages so only the important ones show up. -// -// Utility functions are provided to make life easier. Here is some example code to get started: -// -// log := log4go.NewLogger() -// log.AddFilter("stdout", log4go.DEBUG, log4go.NewConsoleLogWriter()) -// log.AddFilter("log", log4go.FINE, log4go.NewFileLogWriter("example.log", true)) -// log.Info("The time is now: %s", time.LocalTime().Format("15:04:05 MST 2006/01/02")) -// -// The first two lines can be combined with the utility NewDefaultLogger: -// -// log := log4go.NewDefaultLogger(log4go.DEBUG) -// log.AddFilter("log", log4go.FINE, log4go.NewFileLogWriter("example.log", true)) -// log.Info("The time is now: %s", time.LocalTime().Format("15:04:05 MST 2006/01/02")) -// -// Usage notes: -// - The ConsoleLogWriter does not display the source of the message to standard -// output, but the FileLogWriter does. -// - The utility functions (Info, Debug, Warn, etc) derive their source from the -// calling function, and this incurs extra overhead. -// -// Changes from 2.0: -// - The external interface has remained mostly stable, but a lot of the -// internals have been changed, so if you depended on any of this or created -// your own LogWriter, then you will probably have to update your code. In -// particular, Logger is now a map and ConsoleLogWriter is now a channel -// behind-the-scenes, and the LogWrite method no longer has return values. -// -// Future work: (please let me know if you think I should work on any of these particularly) -// - Log file rotation -// - Logging configuration files ala log4j -// - Have the ability to remove filters? -// - Have GetInfoChannel, GetDebugChannel, etc return a chan string that allows -// for another method of logging -// - Add an XML filter type -package log4go - -import ( - "errors" - "os" - "fmt" - "time" - "strings" - "runtime" -) - -// Version information -const ( - L4G_VERSION = "log4go-v3.0.1" - L4G_MAJOR = 3 - L4G_MINOR = 0 - L4G_BUILD = 1 -) - -/****** Constants ******/ - -// These are the integer logging levels used by the logger -type level int - -const ( - FINEST level = iota - FINE - DEBUG - TRACE - INFO - WARNING - ERROR - CRITICAL -) - -// Logging level strings -var ( - levelStrings = [...]string{"FNST", "FINE", "DEBG", "TRAC", "INFO", "WARN", "EROR", "CRIT"} -) - -func (l level) String() string { - if l < 0 || int(l) > len(levelStrings) { - return "UNKNOWN" - } - return levelStrings[int(l)] -} - -/****** Variables ******/ -var ( - // LogBufferLength specifies how many log messages a particular log4go - // logger can buffer at a time before writing them. - LogBufferLength = 32 -) - -/****** LogRecord ******/ - -// A LogRecord contains all of the pertinent information for each message -type LogRecord struct { - Level level // The log level - Created time.Time // The time at which the log message was created (nanoseconds) - Source string // The message source - Message string // The log message -} - -/****** LogWriter ******/ - -// This is an interface for anything that should be able to write logs -type LogWriter interface { - // This will be called to log a LogRecord message. - LogWrite(rec *LogRecord) - - // This should clean up anything lingering about the LogWriter, as it is called before - // the LogWriter is removed. LogWrite should not be called after Close. - Close() -} - -/****** Logger ******/ - -// A Filter represents the log level below which no log records are written to -// the associated LogWriter. -type Filter struct { - Level level - LogWriter -} - -// A Logger represents a collection of Filters through which log messages are -// written. -type Logger map[string]*Filter - -// Create a new logger. -// -// DEPRECATED: Use make(Logger) instead. -func NewLogger() Logger { - os.Stderr.WriteString("warning: use of deprecated NewLogger\n") - return make(Logger) -} - -// Create a new logger with a "stdout" filter configured to send log messages at -// or above lvl to standard output. -// -// DEPRECATED: use NewDefaultLogger instead. -func NewConsoleLogger(lvl level) Logger { - os.Stderr.WriteString("warning: use of deprecated NewConsoleLogger\n") - return Logger{ - "stdout": &Filter{lvl, NewConsoleLogWriter()}, - } -} - -// Create a new logger with a "stdout" filter configured to send log messages at -// or above lvl to standard output. -func NewDefaultLogger(lvl level) Logger { - return Logger{ - "stdout": &Filter{lvl, NewConsoleLogWriter()}, - } -} - -// Closes all log writers in preparation for exiting the program or a -// reconfiguration of logging. Calling this is not really imperative, unless -// you want to guarantee that all log messages are written. Close removes -// all filters (and thus all LogWriters) from the logger. -func (log Logger) Close() { - // Close all open loggers - for name, filt := range log { - filt.Close() - delete(log, name) - } -} - -// Add a new LogWriter to the Logger which will only log messages at lvl or -// higher. This function should not be called from multiple goroutines. -// Returns the logger for chaining. -func (log Logger) AddFilter(name string, lvl level, writer LogWriter) Logger { - log[name] = &Filter{lvl, writer} - return log -} - -/******* Logging *******/ -// Send a formatted log message internally -func (log Logger) intLogf(lvl level, format string, args ...interface{}) { - skip := true - - // Determine if any logging will be done - for _, filt := range log { - if lvl >= filt.Level { - skip = false - break - } - } - if skip { - return - } - - // Determine caller func - pc, _, lineno, ok := runtime.Caller(2) - src := "" - if ok { - src = fmt.Sprintf("%s:%d", runtime.FuncForPC(pc).Name(), lineno) - } - - msg := format - if len(args) > 0 { - msg = fmt.Sprintf(format, args...) - } - - // Make the log record - rec := &LogRecord{ - Level: lvl, - Created: time.Now(), - Source: src, - Message: msg, - } - - // Dispatch the logs - for _, filt := range log { - if lvl < filt.Level { - continue - } - filt.LogWrite(rec) - } -} - -// Send a closure log message internally -func (log Logger) intLogc(lvl level, closure func() string) { - skip := true - - // Determine if any logging will be done - for _, filt := range log { - if lvl >= filt.Level { - skip = false - break - } - } - if skip { - return - } - - // Determine caller func - pc, _, lineno, ok := runtime.Caller(2) - src := "" - if ok { - src = fmt.Sprintf("%s:%d", runtime.FuncForPC(pc).Name(), lineno) - } - - // Make the log record - rec := &LogRecord{ - Level: lvl, - Created: time.Now(), - Source: src, - Message: closure(), - } - - // Dispatch the logs - for _, filt := range log { - if lvl < filt.Level { - continue - } - filt.LogWrite(rec) - } -} - -// Send a log message with manual level, source, and message. -func (log Logger) Log(lvl level, source, message string) { - skip := true - - // Determine if any logging will be done - for _, filt := range log { - if lvl >= filt.Level { - skip = false - break - } - } - if skip { - return - } - - // Make the log record - rec := &LogRecord{ - Level: lvl, - Created: time.Now(), - Source: source, - Message: message, - } - - // Dispatch the logs - for _, filt := range log { - if lvl < filt.Level { - continue - } - filt.LogWrite(rec) - } -} - -// Logf logs a formatted log message at the given log level, using the caller as -// its source. -func (log Logger) Logf(lvl level, format string, args ...interface{}) { - log.intLogf(lvl, format, args...) -} - -// Logc logs a string returned by the closure at the given log level, using the caller as -// its source. If no log message would be written, the closure is never called. -func (log Logger) Logc(lvl level, closure func() string) { - log.intLogc(lvl, closure) -} - -// Finest logs a message at the finest log level. -// See Debug for an explanation of the arguments. -func (log Logger) Finest(arg0 interface{}, args ...interface{}) { - const ( - lvl = FINEST - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - log.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - log.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - log.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Fine logs a message at the fine log level. -// See Debug for an explanation of the arguments. -func (log Logger) Fine(arg0 interface{}, args ...interface{}) { - const ( - lvl = FINE - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - log.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - log.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - log.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Debug is a utility method for debug log messages. -// The behavior of Debug depends on the first argument: -// - arg0 is a string -// When given a string as the first argument, this behaves like Logf but with -// the DEBUG log level: the first argument is interpreted as a format for the -// latter arguments. -// - arg0 is a func()string -// When given a closure of type func()string, this logs the string returned by -// the closure iff it will be logged. The closure runs at most one time. -// - arg0 is interface{} -// When given anything else, the log message will be each of the arguments -// formatted with %v and separated by spaces (ala Sprint). -func (log Logger) Debug(arg0 interface{}, args ...interface{}) { - const ( - lvl = DEBUG - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - log.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - log.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - log.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Trace logs a message at the trace log level. -// See Debug for an explanation of the arguments. -func (log Logger) Trace(arg0 interface{}, args ...interface{}) { - const ( - lvl = TRACE - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - log.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - log.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - log.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Info logs a message at the info log level. -// See Debug for an explanation of the arguments. -func (log Logger) Info(arg0 interface{}, args ...interface{}) { - const ( - lvl = INFO - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - log.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - log.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - log.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Warn logs a message at the warning log level and returns the formatted error. -// At the warning level and higher, there is no performance benefit if the -// message is not actually logged, because all formats are processed and all -// closures are executed to format the error message. -// See Debug for further explanation of the arguments. -func (log Logger) Warn(arg0 interface{}, args ...interface{}) error { - const ( - lvl = WARNING - ) - var msg string - switch first := arg0.(type) { - case string: - // Use the string as a format string - msg = fmt.Sprintf(first, args...) - case func() string: - // Log the closure (no other arguments used) - msg = first() - default: - // Build a format string so that it will be similar to Sprint - msg = fmt.Sprintf(fmt.Sprint(first)+strings.Repeat(" %v", len(args)), args...) - } - log.intLogf(lvl, msg) - return errors.New(msg) -} - -// Error logs a message at the error log level and returns the formatted error, -// See Warn for an explanation of the performance and Debug for an explanation -// of the parameters. -func (log Logger) Error(arg0 interface{}, args ...interface{}) error { - const ( - lvl = ERROR - ) - var msg string - switch first := arg0.(type) { - case string: - // Use the string as a format string - msg = fmt.Sprintf(first, args...) - case func() string: - // Log the closure (no other arguments used) - msg = first() - default: - // Build a format string so that it will be similar to Sprint - msg = fmt.Sprintf(fmt.Sprint(first)+strings.Repeat(" %v", len(args)), args...) - } - log.intLogf(lvl, msg) - return errors.New(msg) -} - -// Critical logs a message at the critical log level and returns the formatted error, -// See Warn for an explanation of the performance and Debug for an explanation -// of the parameters. -func (log Logger) Critical(arg0 interface{}, args ...interface{}) error { - const ( - lvl = CRITICAL - ) - var msg string - switch first := arg0.(type) { - case string: - // Use the string as a format string - msg = fmt.Sprintf(first, args...) - case func() string: - // Log the closure (no other arguments used) - msg = first() - default: - // Build a format string so that it will be similar to Sprint - msg = fmt.Sprintf(fmt.Sprint(first)+strings.Repeat(" %v", len(args)), args...) - } - log.intLogf(lvl, msg) - return errors.New(msg) -} diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/log4go_test.go b/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/log4go_test.go deleted file mode 100644 index 6f550649..00000000 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/log4go_test.go +++ /dev/null @@ -1,537 +0,0 @@ -// Copyright (C) 2010, Kyle Lemons . All rights reserved. - -package log4go - -import ( - "crypto/md5" - "encoding/hex" - "fmt" - "io" - "io/ioutil" - "os" - "runtime" - "testing" - "time" -) - -const testLogFile = "_logtest.log" - -var now time.Time = time.Unix(0, 1234567890123456789).In(time.UTC) - -func newLogRecord(lvl level, src string, msg string) *LogRecord { - return &LogRecord{ - Level: lvl, - Source: src, - Created: now, - Message: msg, - } -} - -func TestELog(t *testing.T) { - fmt.Printf("Testing %s\n", L4G_VERSION) - lr := newLogRecord(CRITICAL, "source", "message") - if lr.Level != CRITICAL { - t.Errorf("Incorrect level: %d should be %d", lr.Level, CRITICAL) - } - if lr.Source != "source" { - t.Errorf("Incorrect source: %s should be %s", lr.Source, "source") - } - if lr.Message != "message" { - t.Errorf("Incorrect message: %s should be %s", lr.Source, "message") - } -} - -var formatTests = []struct { - Test string - Record *LogRecord - Formats map[string]string -}{ - { - Test: "Standard formats", - Record: &LogRecord{ - Level: ERROR, - Source: "source", - Message: "message", - Created: now, - }, - Formats: map[string]string{ - // TODO(kevlar): How can I do this so it'll work outside of PST? - FORMAT_DEFAULT: "[2009/02/13 23:31:30 UTC] [EROR] (source) message\n", - FORMAT_SHORT: "[23:31 02/13/09] [EROR] message\n", - FORMAT_ABBREV: "[EROR] message\n", - }, - }, -} - -func TestFormatLogRecord(t *testing.T) { - for _, test := range formatTests { - name := test.Test - for fmt, want := range test.Formats { - if got := FormatLogRecord(fmt, test.Record); got != want { - t.Errorf("%s - %s:", name, fmt) - t.Errorf(" got %q", got) - t.Errorf(" want %q", want) - } - } - } -} - -var logRecordWriteTests = []struct { - Test string - Record *LogRecord - Console string -}{ - { - Test: "Normal message", - Record: &LogRecord{ - Level: CRITICAL, - Source: "source", - Message: "message", - Created: now, - }, - Console: "[Feb 13 23:31:30.123456] [CRIT] message\n", - }, -} - -func TestConsoleLogWriter(t *testing.T) { - r, w := io.Pipe() - stdout = w - console := NewConsoleLogWriter() - - // Write - go func() { - for _, test := range logRecordWriteTests { - console.LogWrite(test.Record) - } - }() - // Read and verify - buf := make([]byte, 1024) - for _, test := range logRecordWriteTests { - name := test.Test - n, _ := r.Read(buf) - if got, want := string(buf[:n]), test.Console; got != want { - t.Errorf("%s: got %q", name, got) - t.Errorf("%s: want %q", name, want) - } - } - - stdout = os.Stdout -} - -func TestFileLogWriter(t *testing.T) { - defer func(buflen int) { - LogBufferLength = buflen - }(LogBufferLength) - LogBufferLength = 0 - - w := NewFileLogWriter(testLogFile, false) - if w == nil { - t.Fatalf("Invalid return: w should not be nil") - } - defer os.Remove(testLogFile) - - w.LogWrite(newLogRecord(CRITICAL, "source", "message")) - w.Close() - runtime.Gosched() - - if contents, err := ioutil.ReadFile(testLogFile); err != nil { - t.Errorf("read(%q): %s", testLogFile, err) - } else if len(contents) != 50 { - t.Errorf("malformed filelog: %q (%d bytes)", string(contents), len(contents)) - } -} - -func TestXMLLogWriter(t *testing.T) { - defer func(buflen int) { - LogBufferLength = buflen - }(LogBufferLength) - LogBufferLength = 0 - - w := NewXMLLogWriter(testLogFile, false) - if w == nil { - t.Fatalf("Invalid return: w should not be nil") - } - defer os.Remove(testLogFile) - - w.LogWrite(newLogRecord(CRITICAL, "source", "message")) - w.Close() - runtime.Gosched() - - if contents, err := ioutil.ReadFile(testLogFile); err != nil { - t.Errorf("read(%q): %s", testLogFile, err) - } else if len(contents) != 185 { - t.Errorf("malformed xmllog: %q (%d bytes)", string(contents), len(contents)) - } -} - -func TestLogger(t *testing.T) { - sl := NewDefaultLogger(WARNING) - if sl == nil { - t.Fatalf("NewDefaultLogger should never return nil") - } - if lw, exist := sl["stdout"]; lw == nil || exist != true { - t.Fatalf("NewDefaultLogger produced invalid logger (DNE or nil)") - } - if sl["stdout"].Level != WARNING { - t.Fatalf("NewDefaultLogger produced invalid logger (incorrect level)") - } - if len(sl) != 1 { - t.Fatalf("NewDefaultLogger produced invalid logger (incorrect map count)") - } - - //func (l *Logger) AddFilter(name string, level int, writer LogWriter) {} - l := make(Logger) - l.AddFilter("stdout", DEBUG, NewConsoleLogWriter()) - if lw, exist := l["stdout"]; lw == nil || exist != true { - t.Fatalf("AddFilter produced invalid logger (DNE or nil)") - } - if l["stdout"].Level != DEBUG { - t.Fatalf("AddFilter produced invalid logger (incorrect level)") - } - if len(l) != 1 { - t.Fatalf("AddFilter produced invalid logger (incorrect map count)") - } - - //func (l *Logger) Warn(format string, args ...interface{}) error {} - if err := l.Warn("%s %d %#v", "Warning:", 1, []int{}); err.Error() != "Warning: 1 []int{}" { - t.Errorf("Warn returned invalid error: %s", err) - } - - //func (l *Logger) Error(format string, args ...interface{}) error {} - if err := l.Error("%s %d %#v", "Error:", 10, []string{}); err.Error() != "Error: 10 []string{}" { - t.Errorf("Error returned invalid error: %s", err) - } - - //func (l *Logger) Critical(format string, args ...interface{}) error {} - if err := l.Critical("%s %d %#v", "Critical:", 100, []int64{}); err.Error() != "Critical: 100 []int64{}" { - t.Errorf("Critical returned invalid error: %s", err) - } - - // Already tested or basically untestable - //func (l *Logger) Log(level int, source, message string) {} - //func (l *Logger) Logf(level int, format string, args ...interface{}) {} - //func (l *Logger) intLogf(level int, format string, args ...interface{}) string {} - //func (l *Logger) Finest(format string, args ...interface{}) {} - //func (l *Logger) Fine(format string, args ...interface{}) {} - //func (l *Logger) Debug(format string, args ...interface{}) {} - //func (l *Logger) Trace(format string, args ...interface{}) {} - //func (l *Logger) Info(format string, args ...interface{}) {} -} - -func TestLogOutput(t *testing.T) { - const ( - expected = "fdf3e51e444da56b4cb400f30bc47424" - ) - - // Unbuffered output - defer func(buflen int) { - LogBufferLength = buflen - }(LogBufferLength) - LogBufferLength = 0 - - l := make(Logger) - - // Delete and open the output log without a timestamp (for a constant md5sum) - l.AddFilter("file", FINEST, NewFileLogWriter(testLogFile, false).SetFormat("[%L] %M")) - defer os.Remove(testLogFile) - - // Send some log messages - l.Log(CRITICAL, "testsrc1", fmt.Sprintf("This message is level %d", int(CRITICAL))) - l.Logf(ERROR, "This message is level %v", ERROR) - l.Logf(WARNING, "This message is level %s", WARNING) - l.Logc(INFO, func() string { return "This message is level INFO" }) - l.Trace("This message is level %d", int(TRACE)) - l.Debug("This message is level %s", DEBUG) - l.Fine(func() string { return fmt.Sprintf("This message is level %v", FINE) }) - l.Finest("This message is level %v", FINEST) - l.Finest(FINEST, "is also this message's level") - - l.Close() - - contents, err := ioutil.ReadFile(testLogFile) - if err != nil { - t.Fatalf("Could not read output log: %s", err) - } - - sum := md5.New() - sum.Write(contents) - if sumstr := hex.EncodeToString(sum.Sum(nil)); sumstr != expected { - t.Errorf("--- Log Contents:\n%s---", string(contents)) - t.Fatalf("Checksum does not match: %s (expecting %s)", sumstr, expected) - } -} - -func TestCountMallocs(t *testing.T) { - const N = 1 - var m runtime.MemStats - getMallocs := func() uint64 { - runtime.ReadMemStats(&m) - return m.Mallocs - } - - // Console logger - sl := NewDefaultLogger(INFO) - mallocs := 0 - getMallocs() - for i := 0; i < N; i++ { - sl.Log(WARNING, "here", "This is a WARNING message") - } - mallocs += getMallocs() - fmt.Printf("mallocs per sl.Log((WARNING, \"here\", \"This is a log message\"): %d\n", mallocs/N) - - // Console logger formatted - mallocs = 0 - getMallocs() - for i := 0; i < N; i++ { - sl.Logf(WARNING, "%s is a log message with level %d", "This", WARNING) - } - mallocs += getMallocs() - fmt.Printf("mallocs per sl.Logf(WARNING, \"%%s is a log message with level %%d\", \"This\", WARNING): %d\n", mallocs/N) - - // Console logger (not logged) - sl = NewDefaultLogger(INFO) - mallocs = 0 - getMallocs() - for i := 0; i < N; i++ { - sl.Log(DEBUG, "here", "This is a DEBUG log message") - } - mallocs += getMallocs() - fmt.Printf("mallocs per unlogged sl.Log((WARNING, \"here\", \"This is a log message\"): %d\n", mallocs/N) - - // Console logger formatted (not logged) - mallocs = 0 - getMallocs() - for i := 0; i < N; i++ { - sl.Logf(DEBUG, "%s is a log message with level %d", "This", DEBUG) - } - mallocs += getMallocs() - fmt.Printf("mallocs per unlogged sl.Logf(WARNING, \"%%s is a log message with level %%d\", \"This\", WARNING): %d\n", mallocs/N) -} - -func TestXMLConfig(t *testing.T) { - const ( - configfile = "example.xml" - ) - - fd, err := os.Create(configfile) - if err != nil { - t.Fatalf("Could not open %s for writing: %s", configfile, err) - } - - fmt.Fprintln(fd, "") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, " stdout") - fmt.Fprintln(fd, " console") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, " DEBUG") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, " file") - fmt.Fprintln(fd, " file") - fmt.Fprintln(fd, " FINEST") - fmt.Fprintln(fd, " test.log") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, " [%D %T] [%L] (%S) %M") - fmt.Fprintln(fd, " false ") - fmt.Fprintln(fd, " 0M ") - fmt.Fprintln(fd, " 0K ") - fmt.Fprintln(fd, " true ") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, " xmllog") - fmt.Fprintln(fd, " xml") - fmt.Fprintln(fd, " TRACE") - fmt.Fprintln(fd, " trace.xml") - fmt.Fprintln(fd, " true ") - fmt.Fprintln(fd, " 100M ") - fmt.Fprintln(fd, " 6K ") - fmt.Fprintln(fd, " false ") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, " donotopen") - fmt.Fprintln(fd, " socket") - fmt.Fprintln(fd, " FINEST") - fmt.Fprintln(fd, " 192.168.1.255:12124 ") - fmt.Fprintln(fd, " udp ") - fmt.Fprintln(fd, " ") - fmt.Fprintln(fd, "") - fd.Close() - - log := make(Logger) - log.LoadConfiguration(configfile) - defer os.Remove("trace.xml") - defer os.Remove("test.log") - defer log.Close() - - // Make sure we got all loggers - if len(log) != 3 { - t.Fatalf("XMLConfig: Expected 3 filters, found %d", len(log)) - } - - // Make sure they're the right keys - if _, ok := log["stdout"]; !ok { - t.Errorf("XMLConfig: Expected stdout logger") - } - if _, ok := log["file"]; !ok { - t.Fatalf("XMLConfig: Expected file logger") - } - if _, ok := log["xmllog"]; !ok { - t.Fatalf("XMLConfig: Expected xmllog logger") - } - - // Make sure they're the right type - if _, ok := log["stdout"].LogWriter.(ConsoleLogWriter); !ok { - t.Fatalf("XMLConfig: Expected stdout to be ConsoleLogWriter, found %T", log["stdout"].LogWriter) - } - if _, ok := log["file"].LogWriter.(*FileLogWriter); !ok { - t.Fatalf("XMLConfig: Expected file to be *FileLogWriter, found %T", log["file"].LogWriter) - } - if _, ok := log["xmllog"].LogWriter.(*FileLogWriter); !ok { - t.Fatalf("XMLConfig: Expected xmllog to be *FileLogWriter, found %T", log["xmllog"].LogWriter) - } - - // Make sure levels are set - if lvl := log["stdout"].Level; lvl != DEBUG { - t.Errorf("XMLConfig: Expected stdout to be set to level %d, found %d", DEBUG, lvl) - } - if lvl := log["file"].Level; lvl != FINEST { - t.Errorf("XMLConfig: Expected file to be set to level %d, found %d", FINEST, lvl) - } - if lvl := log["xmllog"].Level; lvl != TRACE { - t.Errorf("XMLConfig: Expected xmllog to be set to level %d, found %d", TRACE, lvl) - } - - // Make sure the w is open and points to the right file - if fname := log["file"].LogWriter.(*FileLogWriter).file.Name(); fname != "test.log" { - t.Errorf("XMLConfig: Expected file to have opened %s, found %s", "test.log", fname) - } - - // Make sure the XLW is open and points to the right file - if fname := log["xmllog"].LogWriter.(*FileLogWriter).file.Name(); fname != "trace.xml" { - t.Errorf("XMLConfig: Expected xmllog to have opened %s, found %s", "trace.xml", fname) - } - - // Move XML log file - os.Rename(configfile, "examples/"+configfile) // Keep this so that an example with the documentation is available -} - -func BenchmarkFormatLogRecord(b *testing.B) { - const updateEvery = 1 - rec := &LogRecord{ - Level: CRITICAL, - Created: now, - Source: "source", - Message: "message", - } - for i := 0; i < b.N; i++ { - rec.Created = rec.Created.Add(1 * time.Second / updateEvery) - if i%2 == 0 { - FormatLogRecord(FORMAT_DEFAULT, rec) - } else { - FormatLogRecord(FORMAT_SHORT, rec) - } - } -} - -func BenchmarkConsoleLog(b *testing.B) { - /* This doesn't seem to work on OS X - sink, err := os.Open(os.DevNull) - if err != nil { - panic(err) - } - if err := syscall.Dup2(int(sink.Fd()), syscall.Stdout); err != nil { - panic(err) - } - */ - - stdout = ioutil.Discard - sl := NewDefaultLogger(INFO) - for i := 0; i < b.N; i++ { - sl.Log(WARNING, "here", "This is a log message") - } -} - -func BenchmarkConsoleNotLogged(b *testing.B) { - sl := NewDefaultLogger(INFO) - for i := 0; i < b.N; i++ { - sl.Log(DEBUG, "here", "This is a log message") - } -} - -func BenchmarkConsoleUtilLog(b *testing.B) { - sl := NewDefaultLogger(INFO) - for i := 0; i < b.N; i++ { - sl.Info("%s is a log message", "This") - } -} - -func BenchmarkConsoleUtilNotLog(b *testing.B) { - sl := NewDefaultLogger(INFO) - for i := 0; i < b.N; i++ { - sl.Debug("%s is a log message", "This") - } -} - -func BenchmarkFileLog(b *testing.B) { - sl := make(Logger) - b.StopTimer() - sl.AddFilter("file", INFO, NewFileLogWriter("benchlog.log", false)) - b.StartTimer() - for i := 0; i < b.N; i++ { - sl.Log(WARNING, "here", "This is a log message") - } - b.StopTimer() - os.Remove("benchlog.log") -} - -func BenchmarkFileNotLogged(b *testing.B) { - sl := make(Logger) - b.StopTimer() - sl.AddFilter("file", INFO, NewFileLogWriter("benchlog.log", false)) - b.StartTimer() - for i := 0; i < b.N; i++ { - sl.Log(DEBUG, "here", "This is a log message") - } - b.StopTimer() - os.Remove("benchlog.log") -} - -func BenchmarkFileUtilLog(b *testing.B) { - sl := make(Logger) - b.StopTimer() - sl.AddFilter("file", INFO, NewFileLogWriter("benchlog.log", false)) - b.StartTimer() - for i := 0; i < b.N; i++ { - sl.Info("%s is a log message", "This") - } - b.StopTimer() - os.Remove("benchlog.log") -} - -func BenchmarkFileUtilNotLog(b *testing.B) { - sl := make(Logger) - b.StopTimer() - sl.AddFilter("file", INFO, NewFileLogWriter("benchlog.log", false)) - b.StartTimer() - for i := 0; i < b.N; i++ { - sl.Debug("%s is a log message", "This") - } - b.StopTimer() - os.Remove("benchlog.log") -} - -// Benchmark results (darwin amd64 6g) -//elog.BenchmarkConsoleLog 100000 22819 ns/op -//elog.BenchmarkConsoleNotLogged 2000000 879 ns/op -//elog.BenchmarkConsoleUtilLog 50000 34380 ns/op -//elog.BenchmarkConsoleUtilNotLog 1000000 1339 ns/op -//elog.BenchmarkFileLog 100000 26497 ns/op -//elog.BenchmarkFileNotLogged 2000000 821 ns/op -//elog.BenchmarkFileUtilLog 50000 33945 ns/op -//elog.BenchmarkFileUtilNotLog 1000000 1258 ns/op diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/pattlog.go b/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/pattlog.go deleted file mode 100644 index c655f93b..00000000 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/pattlog.go +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright (C) 2010, Kyle Lemons . All rights reserved. - -package log4go - -import ( - "bytes" - "fmt" - "io" - "os" - "strconv" - "sync/atomic" - "unsafe" -) - -const ( - FORMAT_DEFAULT = "[%D %T] [%L] (%S) %M" - FORMAT_SHORT = "[%t %d] [%L] %M" - FORMAT_ABBREV = "[%L] %M" -) - -type formatCacheType struct { - LastUpdateSeconds int64 - shortTime, shortDate string - longTime, longDate string -} - -var formatCache = unsafe.Pointer(&formatCacheType{}) -var pid = os.Getpid() - -// Known format codes: -// %T - Time (15:04:05 MST) -// %t - Time (15:04) -// %R - Real time (2006-01-02 15:04:05.999999) -// %D - Date (2006/01/02) -// %d - Date (01/02/06) -// %L - Level (FNST, FINE, DEBG, TRAC, WARN, EROR, CRIT) -// %S - Source -// %M - Message -// Ignores unknown formats -// Recommended: "[%D %T] [%L] (%S) %M" -func FormatLogRecord(format string, rec *LogRecord) string { - if rec == nil { - return "" - } - if len(format) == 0 { - return "" - } - - out := bytes.NewBuffer(make([]byte, 0, 64)) - secs := rec.Created.UnixNano() / 1e9 - - cache := *(*formatCacheType)(atomic.LoadPointer(&formatCache)) - if cache.LastUpdateSeconds != secs { - month, day, year := rec.Created.Month(), rec.Created.Day(), rec.Created.Year() - hour, minute, second := rec.Created.Hour(), rec.Created.Minute(), rec.Created.Second() - zone, _ := rec.Created.Zone() - cache = formatCacheType{ - LastUpdateSeconds: secs, - shortTime: fmt.Sprintf("%02d:%02d", hour, minute), - shortDate: fmt.Sprintf("%02d/%02d/%02d", month, day, year%100), - longTime: fmt.Sprintf("%02d:%02d:%02d %s", hour, minute, second, zone), - longDate: fmt.Sprintf("%04d/%02d/%02d", year, month, day), - } - atomic.StorePointer(&formatCache, unsafe.Pointer(&cache)) - } - - // Split the string into pieces by % signs - pieces := bytes.Split([]byte(format), []byte{'%'}) - - // Iterate over the pieces, replacing known formats - for i, piece := range pieces { - if i > 0 && len(piece) > 0 { - switch piece[0] { - case 'P': - out.WriteString(strconv.Itoa(pid)) - case 'T': - out.WriteString(cache.longTime) - case 't': - out.WriteString(cache.shortTime) - case 'D': - out.WriteString(cache.longDate) - case 'd': - out.WriteString(cache.shortDate) - case 'L': - out.WriteString(levelStrings[rec.Level]) - case 'S': - out.WriteString(rec.Source) - case 'M': - out.WriteString(rec.Message) - case 'R': - out.WriteString(rec.Created.Format("2006-01-02 15:04:05.999999")) - } - if len(piece) > 1 { - out.Write(piece[1:]) - } - } else if len(piece) > 0 { - out.Write(piece) - } - } - out.WriteByte('\n') - - return out.String() -} - -// This is the standard writer that prints to standard output. -type FormatLogWriter chan *LogRecord - -// This creates a new FormatLogWriter -func NewFormatLogWriter(out io.Writer, format string) FormatLogWriter { - records := make(FormatLogWriter, LogBufferLength) - go records.run(out, format) - return records -} - -func (w FormatLogWriter) run(out io.Writer, format string) { - for rec := range w { - fmt.Fprint(out, FormatLogRecord(format, rec)) - } -} - -// This is the FormatLogWriter's output method. This will block if the output -// buffer is full. -func (w FormatLogWriter) LogWrite(rec *LogRecord) { - w <- rec -} - -// Close stops the logger from sending messages to standard output. Attempts to -// send log messages to this logger after a Close have undefined behavior. -func (w FormatLogWriter) Close() { - close(w) -} diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/socklog.go b/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/socklog.go deleted file mode 100644 index 1d224a99..00000000 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/socklog.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (C) 2010, Kyle Lemons . All rights reserved. - -package log4go - -import ( - "encoding/json" - "fmt" - "net" - "os" -) - -// This log writer sends output to a socket -type SocketLogWriter chan *LogRecord - -// This is the SocketLogWriter's output method -func (w SocketLogWriter) LogWrite(rec *LogRecord) { - w <- rec -} - -func (w SocketLogWriter) Close() { - close(w) -} - -func NewSocketLogWriter(proto, hostport string) SocketLogWriter { - sock, err := net.Dial(proto, hostport) - if err != nil { - fmt.Fprintf(os.Stderr, "NewSocketLogWriter(%q): %s\n", hostport, err) - return nil - } - - w := SocketLogWriter(make(chan *LogRecord, LogBufferLength)) - - go func() { - defer func() { - if sock != nil && proto == "tcp" { - sock.Close() - } - }() - - for rec := range w { - // Marshall into JSON - js, err := json.Marshal(rec) - if err != nil { - fmt.Fprint(os.Stderr, "SocketLogWriter(%q): %s", hostport, err) - return - } - - _, err = sock.Write(js) - if err != nil { - fmt.Fprint(os.Stderr, "SocketLogWriter(%q): %s", hostport, err) - return - } - } - }() - - return w -} diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/termlog.go b/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/termlog.go deleted file mode 100644 index 39f60c0e..00000000 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/termlog.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2010, Kyle Lemons . All rights reserved. - -package log4go - -import ( - "fmt" - "io" - "os" - "time" -) - -var stdout io.Writer = os.Stdout - -// This is the standard writer that prints to standard output. -type ConsoleLogWriter struct{} - -// This creates a new ConsoleLogWriter -func NewConsoleLogWriter() ConsoleLogWriter { - return ConsoleLogWriter{} -} - -// This is the ConsoleLogWriter's output method. -func (w ConsoleLogWriter) LogWrite(rec *LogRecord) { - timestr := rec.Created.Format(time.StampMicro) - fmt.Fprint(stdout, "[", timestr, "] [", levelStrings[rec.Level], "] ", rec.Message, "\n") -} - -// Close flushes the log. Probably don't need this any more. -func (w ConsoleLogWriter) Close() { - os.Stdout.Sync() -} diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/wrapper.go b/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/wrapper.go deleted file mode 100644 index 10ecd88e..00000000 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/log4go/wrapper.go +++ /dev/null @@ -1,278 +0,0 @@ -// Copyright (C) 2010, Kyle Lemons . All rights reserved. - -package log4go - -import ( - "errors" - "os" - "fmt" - "strings" -) - -var ( - Global Logger -) - -func init() { - Global = NewDefaultLogger(DEBUG) -} - -// Wrapper for (*Logger).LoadConfiguration -func LoadConfiguration(filename string) { - Global.LoadConfiguration(filename) -} - -// Wrapper for (*Logger).AddFilter -func AddFilter(name string, lvl level, writer LogWriter) { - Global.AddFilter(name, lvl, writer) -} - -// Wrapper for (*Logger).Close (closes and removes all logwriters) -func Close() { - Global.Close() -} - -func Crash(args ...interface{}) { - if len(args) > 0 { - Global.intLogf(CRITICAL, strings.Repeat(" %v", len(args))[1:], args...) - } - panic(args) -} - -// Logs the given message and crashes the program -func Crashf(format string, args ...interface{}) { - Global.intLogf(CRITICAL, format, args...) - Global.Close() // so that hopefully the messages get logged - panic(fmt.Sprintf(format, args...)) -} - -// Compatibility with `log` -func Exit(args ...interface{}) { - if len(args) > 0 { - Global.intLogf(ERROR, strings.Repeat(" %v", len(args))[1:], args...) - } - Global.Close() // so that hopefully the messages get logged - os.Exit(0) -} - -// Compatibility with `log` -func Exitf(format string, args ...interface{}) { - Global.intLogf(ERROR, format, args...) - Global.Close() // so that hopefully the messages get logged - os.Exit(0) -} - -// Compatibility with `log` -func Stderr(args ...interface{}) { - if len(args) > 0 { - Global.intLogf(ERROR, strings.Repeat(" %v", len(args))[1:], args...) - } -} - -// Compatibility with `log` -func Stderrf(format string, args ...interface{}) { - Global.intLogf(ERROR, format, args...) -} - -// Compatibility with `log` -func Stdout(args ...interface{}) { - if len(args) > 0 { - Global.intLogf(INFO, strings.Repeat(" %v", len(args))[1:], args...) - } -} - -// Compatibility with `log` -func Stdoutf(format string, args ...interface{}) { - Global.intLogf(INFO, format, args...) -} - -// Send a log message manually -// Wrapper for (*Logger).Log -func Log(lvl level, source, message string) { - Global.Log(lvl, source, message) -} - -// Send a formatted log message easily -// Wrapper for (*Logger).Logf -func Logf(lvl level, format string, args ...interface{}) { - Global.intLogf(lvl, format, args...) -} - -// Send a closure log message -// Wrapper for (*Logger).Logc -func Logc(lvl level, closure func() string) { - Global.intLogc(lvl, closure) -} - -// Utility for finest log messages (see Debug() for parameter explanation) -// Wrapper for (*Logger).Finest -func Finest(arg0 interface{}, args ...interface{}) { - const ( - lvl = FINEST - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - Global.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - Global.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - Global.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Utility for fine log messages (see Debug() for parameter explanation) -// Wrapper for (*Logger).Fine -func Fine(arg0 interface{}, args ...interface{}) { - const ( - lvl = FINE - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - Global.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - Global.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - Global.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Utility for debug log messages -// When given a string as the first argument, this behaves like Logf but with the DEBUG log level (e.g. the first argument is interpreted as a format for the latter arguments) -// When given a closure of type func()string, this logs the string returned by the closure iff it will be logged. The closure runs at most one time. -// When given anything else, the log message will be each of the arguments formatted with %v and separated by spaces (ala Sprint). -// Wrapper for (*Logger).Debug -func Debug(arg0 interface{}, args ...interface{}) { - const ( - lvl = DEBUG - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - Global.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - Global.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - Global.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Utility for trace log messages (see Debug() for parameter explanation) -// Wrapper for (*Logger).Trace -func Trace(arg0 interface{}, args ...interface{}) { - const ( - lvl = TRACE - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - Global.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - Global.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - Global.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Utility for info log messages (see Debug() for parameter explanation) -// Wrapper for (*Logger).Info -func Info(arg0 interface{}, args ...interface{}) { - const ( - lvl = INFO - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - Global.intLogf(lvl, first, args...) - case func() string: - // Log the closure (no other arguments used) - Global.intLogc(lvl, first) - default: - // Build a format string so that it will be similar to Sprint - Global.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...) - } -} - -// Utility for warn log messages (returns an error for easy function returns) (see Debug() for parameter explanation) -// These functions will execute a closure exactly once, to build the error message for the return -// Wrapper for (*Logger).Warn -func Warn(arg0 interface{}, args ...interface{}) error { - const ( - lvl = WARNING - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - Global.intLogf(lvl, first, args...) - return errors.New(fmt.Sprintf(first, args...)) - case func() string: - // Log the closure (no other arguments used) - str := first() - Global.intLogf(lvl, "%s", str) - return errors.New(str) - default: - // Build a format string so that it will be similar to Sprint - Global.intLogf(lvl, fmt.Sprint(first)+strings.Repeat(" %v", len(args)), args...) - return errors.New(fmt.Sprint(first) + fmt.Sprintf(strings.Repeat(" %v", len(args)), args...)) - } - return nil -} - -// Utility for error log messages (returns an error for easy function returns) (see Debug() for parameter explanation) -// These functions will execute a closure exactly once, to build the error message for the return -// Wrapper for (*Logger).Error -func Error(arg0 interface{}, args ...interface{}) error { - const ( - lvl = ERROR - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - Global.intLogf(lvl, first, args...) - return errors.New(fmt.Sprintf(first, args...)) - case func() string: - // Log the closure (no other arguments used) - str := first() - Global.intLogf(lvl, "%s", str) - return errors.New(str) - default: - // Build a format string so that it will be similar to Sprint - Global.intLogf(lvl, fmt.Sprint(first)+strings.Repeat(" %v", len(args)), args...) - return errors.New(fmt.Sprint(first) + fmt.Sprintf(strings.Repeat(" %v", len(args)), args...)) - } - return nil -} - -// Utility for critical log messages (returns an error for easy function returns) (see Debug() for parameter explanation) -// These functions will execute a closure exactly once, to build the error message for the return -// Wrapper for (*Logger).Critical -func Critical(arg0 interface{}, args ...interface{}) error { - const ( - lvl = CRITICAL - ) - switch first := arg0.(type) { - case string: - // Use the string as a format string - Global.intLogf(lvl, first, args...) - return errors.New(fmt.Sprintf(first, args...)) - case func() string: - // Log the closure (no other arguments used) - str := first() - Global.intLogf(lvl, "%s", str) - return errors.New(str) - default: - // Build a format string so that it will be similar to Sprint - Global.intLogf(lvl, fmt.Sprint(first)+strings.Repeat(" %v", len(args)), args...) - return errors.New(fmt.Sprint(first) + fmt.Sprintf(strings.Repeat(" %v", len(args)), args...)) - } - return nil -} diff --git a/vendor/_nuts/github.com/technoweenie/assert/.gitignore b/vendor/_nuts/github.com/technoweenie/assert/.gitignore deleted file mode 100644 index b6fadf4e..00000000 --- a/vendor/_nuts/github.com/technoweenie/assert/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -_go_.* -_gotest_.* -_obj -_test -_testmain.go -*.out -*.[568] diff --git a/vendor/_nuts/github.com/technoweenie/assert/README.md b/vendor/_nuts/github.com/technoweenie/assert/README.md deleted file mode 100644 index 8b6b6fc4..00000000 --- a/vendor/_nuts/github.com/technoweenie/assert/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# Assert (c) Blake Mizerany and Keith Rarick -- MIT LICENCE - -## Assertions for Go tests - -## Install - - $ go get github.com/bmizerany/assert - -## Use - -**point.go** - - package point - - type Point struct { - x, y int - } - -**point_test.go** - - - package point - - import ( - "testing" - "github.com/bmizerany/assert" - ) - - func TestAsserts(t *testing.T) { - p1 := Point{1, 1} - p2 := Point{2, 1} - - assert.Equal(t, p1, p2) - } - -**output** - $ go test - --- FAIL: TestAsserts (0.00 seconds) - assert.go:15: /Users/flavio.barbosa/dev/stewie/src/point_test.go:12 - assert.go:24: ! X: 1 != 2 - FAIL - -## Docs - - http://github.com/bmizerany/assert diff --git a/vendor/_nuts/github.com/technoweenie/assert/assert.go b/vendor/_nuts/github.com/technoweenie/assert/assert.go deleted file mode 100644 index 038164c7..00000000 --- a/vendor/_nuts/github.com/technoweenie/assert/assert.go +++ /dev/null @@ -1,77 +0,0 @@ -package assert - -// Testing helpers for doozer. - -import ( - "github.com/github/git-lfs/vendor/_nuts/github.com/kr/pretty" - "reflect" - "testing" - "runtime" - "fmt" -) - -func assert(t *testing.T, result bool, f func(), cd int) { - if !result { - _, file, line, _ := runtime.Caller(cd + 1) - t.Errorf("%s:%d", file, line) - f() - t.FailNow() - } -} - -func equal(t *testing.T, exp, got interface{}, cd int, args ...interface{}) { - fn := func() { - for _, desc := range pretty.Diff(exp, got) { - t.Error("!", desc) - } - if len(args) > 0 { - t.Error("!", " -", fmt.Sprint(args...)) - } - } - result := reflect.DeepEqual(exp, got) - assert(t, result, fn, cd+1) -} - -func tt(t *testing.T, result bool, cd int, args ...interface{}) { - fn := func() { - t.Errorf("! Failure") - if len(args) > 0 { - t.Error("!", " -", fmt.Sprint(args...)) - } - } - assert(t, result, fn, cd+1) -} - -func T(t *testing.T, result bool, args ...interface{}) { - tt(t, result, 1, args...) -} - -func Tf(t *testing.T, result bool, format string, args ...interface{}) { - tt(t, result, 1, fmt.Sprintf(format, args...)) -} - -func Equal(t *testing.T, exp, got interface{}, args ...interface{}) { - equal(t, exp, got, 1, args...) -} - -func Equalf(t *testing.T, exp, got interface{}, format string, args ...interface{}) { - equal(t, exp, got, 1, fmt.Sprintf(format, args...)) -} - -func NotEqual(t *testing.T, exp, got interface{}, args ...interface{}) { - fn := func() { - t.Errorf("! Unexpected: <%#v>", exp) - if len(args) > 0 { - t.Error("!", " -", fmt.Sprint(args...)) - } - } - result := !reflect.DeepEqual(exp, got) - assert(t, result, fn, 1) -} - -func Panic(t *testing.T, err interface{}, fn func()) { - defer func() { - equal(t, err, recover(), 3) - }() - fn() -} diff --git a/vendor/_nuts/github.com/technoweenie/assert/assert_test.go b/vendor/_nuts/github.com/technoweenie/assert/assert_test.go deleted file mode 100644 index 162a590c..00000000 --- a/vendor/_nuts/github.com/technoweenie/assert/assert_test.go +++ /dev/null @@ -1,15 +0,0 @@ -package assert - -import ( - "testing" -) - -func TestLineNumbers(t *testing.T) { - Equal(t, "foo", "foo", "msg!") - //Equal(t, "foo", "bar", "this should blow up") -} - -func TestNotEqual(t *testing.T) { - NotEqual(t, "foo", "bar", "msg!") - //NotEqual(t, "foo", "foo", "this should blow up") -} diff --git a/vendor/_nuts/github.com/technoweenie/assert/example/point.go b/vendor/_nuts/github.com/technoweenie/assert/example/point.go deleted file mode 100644 index 15789fe1..00000000 --- a/vendor/_nuts/github.com/technoweenie/assert/example/point.go +++ /dev/null @@ -1,5 +0,0 @@ -package point - -type Point struct { - X, Y int -} diff --git a/vendor/_nuts/github.com/technoweenie/assert/example/point_test.go b/vendor/_nuts/github.com/technoweenie/assert/example/point_test.go deleted file mode 100644 index dcf74603..00000000 --- a/vendor/_nuts/github.com/technoweenie/assert/example/point_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package point - -import ( - "testing" - "github.com/github/git-lfs/vendor/_nuts/github.com/technoweenie/assert" -) - -func TestAsserts(t *testing.T) { - p1 := Point{1, 1} - p2 := Point{2, 1} - - assert.Equal(t, p1, p2) -} diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/.gitignore b/vendor/github.com/ThomsonReutersEikon/go-ntlm/.gitignore similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/.gitignore rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/.gitignore diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/License b/vendor/github.com/ThomsonReutersEikon/go-ntlm/License similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/License rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/License diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/README.md b/vendor/github.com/ThomsonReutersEikon/go-ntlm/README.md similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/README.md rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/README.md diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/av_pairs.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/av_pairs.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/av_pairs.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/av_pairs.go diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/challenge_responses.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/challenge_responses.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/challenge_responses.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/challenge_responses.go diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/crypto.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/crypto.go similarity index 97% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/crypto.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/crypto.go index 1f7c41ca..6e6774dd 100644 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/crypto.go +++ b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/crypto.go @@ -8,8 +8,9 @@ import ( md5P "crypto/md5" "crypto/rand" rc4P "crypto/rc4" - md4P "github.com/github/git-lfs/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/md4" crc32P "hash/crc32" + + md4P "github.com/ThomsonReutersEikon/go-ntlm/ntlm/md4" ) func md4(data []byte) []byte { diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/crypto_test.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/crypto_test.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/crypto_test.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/crypto_test.go diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/helpers.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/helpers.go similarity index 75% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/helpers.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/helpers.go index 1cc78d52..6b1a1ddb 100644 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/helpers.go +++ b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/helpers.go @@ -5,8 +5,8 @@ package ntlm import ( "bytes" "crypto/rand" - "unicode/utf16" "encoding/binary" + "unicode/utf16" ) // Concatenate two byte slices into a new slice @@ -67,23 +67,22 @@ func utf16FromString(s string) []byte { // Convert a UTF16 string to UTF8 string for Go usage func utf16ToString(bytes []byte) string { - var data []uint16 + var data []uint16 - // NOTE: This is definitely not the best way to do this, but when I tried using a buffer.Read I could not get it to work - for offset := 0; offset < len(bytes); offset = offset + 2 { - i := binary.LittleEndian.Uint16(bytes[offset : offset+2]) - data = append(data, i) - } + // NOTE: This is definitely not the best way to do this, but when I tried using a buffer.Read I could not get it to work + for offset := 0; offset < len(bytes); offset = offset + 2 { + i := binary.LittleEndian.Uint16(bytes[offset : offset+2]) + data = append(data, i) + } - return string(utf16.Decode(data)) + return string(utf16.Decode(data)) } func uint32ToBytes(v uint32) []byte { - bytes := make([]byte, 4) - bytes[0] = byte(v & 0xff) - bytes[1] = byte((v >> 8) & 0xff) - bytes[2] = byte((v >> 16) & 0xff) - bytes[3] = byte((v >> 24) & 0xff) - return bytes + bytes := make([]byte, 4) + bytes[0] = byte(v & 0xff) + bytes[1] = byte((v >> 8) & 0xff) + bytes[2] = byte((v >> 16) & 0xff) + bytes[3] = byte((v >> 24) & 0xff) + return bytes } - diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/helpers_test.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/helpers_test.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/helpers_test.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/helpers_test.go diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/keys.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/keys.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/keys.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/keys.go diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/md4/LICENSE b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/md4/LICENSE similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/md4/LICENSE rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/md4/LICENSE diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/md4/md4.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/md4/md4.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/md4/md4.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/md4/md4.go diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/md4/md4_test.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/md4/md4_test.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/md4/md4_test.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/md4/md4_test.go diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/md4/md4block.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/md4/md4block.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/md4/md4block.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/md4/md4block.go diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_authenticate.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_authenticate.go similarity index 99% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_authenticate.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_authenticate.go index 5c2448ef..1792f532 100644 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_authenticate.go +++ b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_authenticate.go @@ -38,7 +38,7 @@ type AuthenticateMessage struct { /// MS-NLMP 2.2.1.3 - In connectionless mode, a NEGOTIATE structure that contains a set of bit flags (section 2.2.2.5) and represents the // conclusion of negotiation—the choices the client has made from the options the server offered in the CHALLENGE_MESSAGE. // In connection-oriented mode, a NEGOTIATE structure that contains the set of bit flags (section 2.2.2.5) negotiated in - // the previous + // the previous NegotiateFlags uint32 // 4 bytes // Version (8 bytes): A VERSION structure (section 2.2.2.10) that is present only when the NTLMSSP_NEGOTIATE_VERSION diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_authenticate_test.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_authenticate_test.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_authenticate_test.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_authenticate_test.go diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_challenge.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_challenge.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_challenge.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_challenge.go diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_challenge_test.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_challenge_test.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_challenge_test.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_challenge_test.go diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_negotiate.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_negotiate.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_negotiate.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/message_negotiate.go diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/negotiate_flags.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/negotiate_flags.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/negotiate_flags.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/negotiate_flags.go diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/negotiate_flags_test.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/negotiate_flags_test.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/negotiate_flags_test.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/negotiate_flags_test.go diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlm.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlm.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlm.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlm.go diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv1.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv1.go similarity index 98% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv1.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv1.go index 4536f955..4ad2b84e 100644 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv1.go +++ b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv1.go @@ -6,7 +6,7 @@ import ( "bytes" rc4P "crypto/rc4" "errors" - l4g "github.com/github/git-lfs/vendor/_nuts/github.com/ThomsonReutersEikon/log4go" + "log" "strings" ) @@ -181,7 +181,7 @@ func (n *V1ServerSession) ProcessAuthenticateMessage(am *AuthenticateMessage) (e // They should always be correct (I hope) n.user = am.UserName.String() n.userDomain = am.DomainName.String() - l4g.Info("(ProcessAuthenticateMessage)NTLM v1 User %s Domain %s", n.user, n.userDomain) + log.Printf("(ProcessAuthenticateMessage)NTLM v1 User %s Domain %s", n.user, n.userDomain) err = n.fetchResponseKeys() if err != nil { @@ -225,7 +225,7 @@ func (n *V1ServerSession) ProcessAuthenticateMessage(am *AuthenticateMessage) (e //UGH not entirely sure how this could possibly happen, going to put this in for now //TODO investigate if this ever is really happening am.Version = &VersionStruct{ProductMajorVersion: uint8(5), ProductMinorVersion: uint8(1), ProductBuild: uint16(2600), NTLMRevisionCurrent: uint8(15)} - l4g.Error("Nil version in ntlmv1") + log.Printf("Nil version in ntlmv1") } err = n.calculateKeys(am.Version.NTLMRevisionCurrent) diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv1_test.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv1_test.go similarity index 93% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv1_test.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv1_test.go index 18e02cf4..e175557a 100644 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv1_test.go +++ b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv1_test.go @@ -42,14 +42,14 @@ func checkV1Value(t *testing.T, name string, value []byte, expected string, err // would authenticate. This was due to a bug in the MS-NLMP docs. This tests for that issue func TestNtlmV1ExtendedSessionSecurity(t *testing.T) { // NTLMv1 with extended session security - challengeMessage := "TlRMTVNTUAACAAAAAAAAADgAAABVgphiRy3oSZvn1I4AAAAAAAAAAKIAogA4AAAABQEoCgAAAA8CAA4AUgBFAFUAVABFAFIAUwABABwAVQBLAEIAUAAtAEMAQgBUAFIATQBGAEUAMAA2AAQAFgBSAGUAdQB0AGUAcgBzAC4AbgBlAHQAAwA0AHUAawBiAHAALQBjAGIAdAByAG0AZgBlADAANgAuAFIAZQB1AHQAZQByAHMALgBuAGUAdAAFABYAUgBlAHUAdABlAHIAcwAuAG4AZQB0AAAAAAA=" - authenticateMessage := "TlRMTVNTUAADAAAAGAAYAJgAAAAYABgAsAAAAAAAAABIAAAAOgA6AEgAAAAWABYAggAAABAAEADIAAAAVYKYYgUCzg4AAAAPMQAwADAAMAAwADEALgB3AGMAcABAAHQAaABvAG0AcwBvAG4AcgBlAHUAdABlAHIAcwAuAGMAbwBtAE4AWQBDAFMATQBTAEcAOQA5ADAAOQBRWAK3h/TIywAAAAAAAAAAAAAAAAAAAAA3tp89kZU1hs1XZp7KTyGm3XsFAT9stEDW9YXDaeYVBmBcBb//2FOu" + challengeMessage := "TlRMTVNTUAACAAAAAAAAADgAAABVgphiRy3oSZvn1I4AAAAAAAAAAKIAogA4AAAABQEoCgAAAA8CAA4AUgBFAFUAVABFAFIAUwABABwAVQBLAEIAUAAtAEMAQgBUAFIATQBGAEUAMAA2AAQAFgBSAGUAdQB0AGUAcgBzAC4AbgBlAHQAAwA0AHUAawBiAHAALQBjAGIAdAByAG0AZgBlADAANgAuAFIAZQB1AHQAZQByAHMALgBuAGUAdAAFABYAUgBlAHUAdABlAHIAcwAuAG4AZQB0AAAAAAA=" + authenticateMessage := "TlRMTVNTUAADAAAAGAAYAJgAAAAYABgAsAAAAAAAAABIAAAAOgA6AEgAAAAWABYAggAAABAAEADIAAAAVYKYYgUCzg4AAAAPMQAwADAAMAAwADEALgB3AGMAcABAAHQAaABvAG0AcwBvAG4AcgBlAHUAdABlAHIAcwAuAGMAbwBtAE4AWQBDAFMATQBTAEcAOQA5ADAAOQBRWAK3h/TIywAAAAAAAAAAAAAAAAAAAAA3tp89kZU1hs1XZp7KTyGm3XsFAT9stEDW9YXDaeYVBmBcBb//2FOu" challengeData, _ := base64.StdEncoding.DecodeString(challengeMessage) c, _ := ParseChallengeMessage(challengeData) - authenticateData, _ := base64.StdEncoding.DecodeString(authenticateMessage) - msg, err := ParseAuthenticateMessage(authenticateData, 1) + authenticateData, _ := base64.StdEncoding.DecodeString(authenticateMessage) + msg, err := ParseAuthenticateMessage(authenticateData, 1) if err != nil { t.Errorf("Could not process authenticate message: %s", err) } diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv2.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv2.go similarity index 98% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv2.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv2.go index cc319f3d..a511f89a 100644 --- a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv2.go +++ b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv2.go @@ -7,7 +7,7 @@ import ( rc4P "crypto/rc4" "encoding/binary" "errors" - l4g "github.com/github/git-lfs/vendor/_nuts/github.com/ThomsonReutersEikon/log4go" + "log" "strings" "time" ) @@ -204,7 +204,7 @@ func (n *V2ServerSession) ProcessAuthenticateMessage(am *AuthenticateMessage) (e // They should always be correct (I hope) n.user = am.UserName.String() n.userDomain = am.DomainName.String() - l4g.Info("(ProcessAuthenticateMessage)NTLM v2 User %s Domain %s", n.user, n.userDomain) + log.Printf("(ProcessAuthenticateMessage)NTLM v2 User %s Domain %s", n.user, n.userDomain) err = n.fetchResponseKeys() if err != nil { @@ -243,7 +243,7 @@ func (n *V2ServerSession) ProcessAuthenticateMessage(am *AuthenticateMessage) (e //TODO investigate if this ever is really happening am.Version = &VersionStruct{ProductMajorVersion: uint8(5), ProductMinorVersion: uint8(1), ProductBuild: uint16(2600), NTLMRevisionCurrent: uint8(15)} - l4g.Error("Nil version in ntlmv2") + log.Printf("Nil version in ntlmv2") } err = n.calculateKeys(am.Version.NTLMRevisionCurrent) diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv2_test.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv2_test.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv2_test.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/ntlmv2_test.go diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/payload.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/payload.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/payload.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/payload.go diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/signature.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/signature.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/signature.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/signature.go diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/signature_test.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/signature_test.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/signature_test.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/signature_test.go diff --git a/vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/version.go b/vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/version.go similarity index 100% rename from vendor/_nuts/github.com/ThomsonReutersEikon/go-ntlm/ntlm/version.go rename to vendor/github.com/ThomsonReutersEikon/go-ntlm/ntlm/version.go diff --git a/vendor/_nuts/github.com/bgentry/go-netrc/.hgignore b/vendor/github.com/bgentry/go-netrc/.hgignore similarity index 100% rename from vendor/_nuts/github.com/bgentry/go-netrc/.hgignore rename to vendor/github.com/bgentry/go-netrc/.hgignore diff --git a/vendor/_nuts/github.com/bgentry/go-netrc/LICENSE b/vendor/github.com/bgentry/go-netrc/LICENSE similarity index 100% rename from vendor/_nuts/github.com/bgentry/go-netrc/LICENSE rename to vendor/github.com/bgentry/go-netrc/LICENSE diff --git a/vendor/_nuts/github.com/bgentry/go-netrc/README.md b/vendor/github.com/bgentry/go-netrc/README.md similarity index 100% rename from vendor/_nuts/github.com/bgentry/go-netrc/README.md rename to vendor/github.com/bgentry/go-netrc/README.md diff --git a/vendor/_nuts/github.com/bgentry/go-netrc/netrc/examples/bad_default_order.netrc b/vendor/github.com/bgentry/go-netrc/netrc/examples/bad_default_order.netrc similarity index 100% rename from vendor/_nuts/github.com/bgentry/go-netrc/netrc/examples/bad_default_order.netrc rename to vendor/github.com/bgentry/go-netrc/netrc/examples/bad_default_order.netrc diff --git a/vendor/_nuts/github.com/bgentry/go-netrc/netrc/examples/good.netrc b/vendor/github.com/bgentry/go-netrc/netrc/examples/good.netrc similarity index 100% rename from vendor/_nuts/github.com/bgentry/go-netrc/netrc/examples/good.netrc rename to vendor/github.com/bgentry/go-netrc/netrc/examples/good.netrc diff --git a/vendor/_nuts/github.com/bgentry/go-netrc/netrc/netrc.go b/vendor/github.com/bgentry/go-netrc/netrc/netrc.go similarity index 100% rename from vendor/_nuts/github.com/bgentry/go-netrc/netrc/netrc.go rename to vendor/github.com/bgentry/go-netrc/netrc/netrc.go diff --git a/vendor/_nuts/github.com/bgentry/go-netrc/netrc/netrc_test.go b/vendor/github.com/bgentry/go-netrc/netrc/netrc_test.go similarity index 100% rename from vendor/_nuts/github.com/bgentry/go-netrc/netrc/netrc_test.go rename to vendor/github.com/bgentry/go-netrc/netrc/netrc_test.go diff --git a/vendor/_nuts/github.com/cheggaaa/pb/LICENSE b/vendor/github.com/cheggaaa/pb/LICENSE similarity index 100% rename from vendor/_nuts/github.com/cheggaaa/pb/LICENSE rename to vendor/github.com/cheggaaa/pb/LICENSE diff --git a/vendor/_nuts/github.com/cheggaaa/pb/README.md b/vendor/github.com/cheggaaa/pb/README.md similarity index 100% rename from vendor/_nuts/github.com/cheggaaa/pb/README.md rename to vendor/github.com/cheggaaa/pb/README.md diff --git a/vendor/_nuts/github.com/cheggaaa/pb/example/copy/copy.go b/vendor/github.com/cheggaaa/pb/example/copy/copy.go similarity index 95% rename from vendor/_nuts/github.com/cheggaaa/pb/example/copy/copy.go rename to vendor/github.com/cheggaaa/pb/example/copy/copy.go index 0fffd728..82b5329a 100644 --- a/vendor/_nuts/github.com/cheggaaa/pb/example/copy/copy.go +++ b/vendor/github.com/cheggaaa/pb/example/copy/copy.go @@ -2,7 +2,7 @@ package main import ( "fmt" - "github.com/github/git-lfs/vendor/_nuts/github.com/cheggaaa/pb" + "github.com/cheggaaa/pb" "io" "net/http" "os" diff --git a/vendor/_nuts/github.com/cheggaaa/pb/example/pb.go b/vendor/github.com/cheggaaa/pb/example/pb.go similarity index 86% rename from vendor/_nuts/github.com/cheggaaa/pb/example/pb.go rename to vendor/github.com/cheggaaa/pb/example/pb.go index eee92ff0..140ba039 100644 --- a/vendor/_nuts/github.com/cheggaaa/pb/example/pb.go +++ b/vendor/github.com/cheggaaa/pb/example/pb.go @@ -1,7 +1,7 @@ package main import ( - "github.com/github/git-lfs/vendor/_nuts/github.com/cheggaaa/pb" + "github.com/cheggaaa/pb" "time" ) diff --git a/vendor/_nuts/github.com/cheggaaa/pb/format.go b/vendor/github.com/cheggaaa/pb/format.go similarity index 100% rename from vendor/_nuts/github.com/cheggaaa/pb/format.go rename to vendor/github.com/cheggaaa/pb/format.go diff --git a/vendor/_nuts/github.com/cheggaaa/pb/format_test.go b/vendor/github.com/cheggaaa/pb/format_test.go similarity index 100% rename from vendor/_nuts/github.com/cheggaaa/pb/format_test.go rename to vendor/github.com/cheggaaa/pb/format_test.go diff --git a/vendor/_nuts/github.com/cheggaaa/pb/pb.go b/vendor/github.com/cheggaaa/pb/pb.go similarity index 100% rename from vendor/_nuts/github.com/cheggaaa/pb/pb.go rename to vendor/github.com/cheggaaa/pb/pb.go diff --git a/vendor/_nuts/github.com/cheggaaa/pb/pb_nix.go b/vendor/github.com/cheggaaa/pb/pb_nix.go similarity index 100% rename from vendor/_nuts/github.com/cheggaaa/pb/pb_nix.go rename to vendor/github.com/cheggaaa/pb/pb_nix.go diff --git a/vendor/_nuts/github.com/cheggaaa/pb/pb_solaris.go b/vendor/github.com/cheggaaa/pb/pb_solaris.go similarity index 100% rename from vendor/_nuts/github.com/cheggaaa/pb/pb_solaris.go rename to vendor/github.com/cheggaaa/pb/pb_solaris.go diff --git a/vendor/_nuts/github.com/cheggaaa/pb/pb_test.go b/vendor/github.com/cheggaaa/pb/pb_test.go similarity index 100% rename from vendor/_nuts/github.com/cheggaaa/pb/pb_test.go rename to vendor/github.com/cheggaaa/pb/pb_test.go diff --git a/vendor/_nuts/github.com/cheggaaa/pb/pb_win.go b/vendor/github.com/cheggaaa/pb/pb_win.go similarity index 72% rename from vendor/_nuts/github.com/cheggaaa/pb/pb_win.go rename to vendor/github.com/cheggaaa/pb/pb_win.go index c700a5aa..eb36190c 100644 --- a/vendor/_nuts/github.com/cheggaaa/pb/pb_win.go +++ b/vendor/github.com/cheggaaa/pb/pb_win.go @@ -3,7 +3,7 @@ package pb import ( - "github.com/github/git-lfs/vendor/_nuts/github.com/olekukonko/ts" + "github.com/olekukonko/ts" ) func bold(str string) string { diff --git a/vendor/_nuts/github.com/cheggaaa/pb/pb_x.go b/vendor/github.com/cheggaaa/pb/pb_x.go similarity index 100% rename from vendor/_nuts/github.com/cheggaaa/pb/pb_x.go rename to vendor/github.com/cheggaaa/pb/pb_x.go diff --git a/vendor/_nuts/github.com/cheggaaa/pb/reader.go b/vendor/github.com/cheggaaa/pb/reader.go similarity index 100% rename from vendor/_nuts/github.com/cheggaaa/pb/reader.go rename to vendor/github.com/cheggaaa/pb/reader.go diff --git a/vendor/_nuts/github.com/inconshreveable/mousetrap/LICENSE b/vendor/github.com/inconshreveable/mousetrap/LICENSE similarity index 100% rename from vendor/_nuts/github.com/inconshreveable/mousetrap/LICENSE rename to vendor/github.com/inconshreveable/mousetrap/LICENSE diff --git a/vendor/_nuts/github.com/inconshreveable/mousetrap/README.md b/vendor/github.com/inconshreveable/mousetrap/README.md similarity index 100% rename from vendor/_nuts/github.com/inconshreveable/mousetrap/README.md rename to vendor/github.com/inconshreveable/mousetrap/README.md diff --git a/vendor/_nuts/github.com/inconshreveable/mousetrap/trap_others.go b/vendor/github.com/inconshreveable/mousetrap/trap_others.go similarity index 100% rename from vendor/_nuts/github.com/inconshreveable/mousetrap/trap_others.go rename to vendor/github.com/inconshreveable/mousetrap/trap_others.go diff --git a/vendor/_nuts/github.com/inconshreveable/mousetrap/trap_windows.go b/vendor/github.com/inconshreveable/mousetrap/trap_windows.go similarity index 100% rename from vendor/_nuts/github.com/inconshreveable/mousetrap/trap_windows.go rename to vendor/github.com/inconshreveable/mousetrap/trap_windows.go diff --git a/vendor/_nuts/github.com/inconshreveable/mousetrap/trap_windows_1.4.go b/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go similarity index 100% rename from vendor/_nuts/github.com/inconshreveable/mousetrap/trap_windows_1.4.go rename to vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go diff --git a/vendor/_nuts/github.com/kr/pretty/.gitignore b/vendor/github.com/kr/pretty/.gitignore similarity index 100% rename from vendor/_nuts/github.com/kr/pretty/.gitignore rename to vendor/github.com/kr/pretty/.gitignore diff --git a/vendor/_nuts/github.com/kr/pretty/License b/vendor/github.com/kr/pretty/License similarity index 100% rename from vendor/_nuts/github.com/kr/pretty/License rename to vendor/github.com/kr/pretty/License diff --git a/vendor/_nuts/github.com/kr/pretty/Readme b/vendor/github.com/kr/pretty/Readme similarity index 100% rename from vendor/_nuts/github.com/kr/pretty/Readme rename to vendor/github.com/kr/pretty/Readme diff --git a/vendor/_nuts/github.com/kr/pretty/diff.go b/vendor/github.com/kr/pretty/diff.go similarity index 100% rename from vendor/_nuts/github.com/kr/pretty/diff.go rename to vendor/github.com/kr/pretty/diff.go diff --git a/vendor/_nuts/github.com/kr/pretty/diff_test.go b/vendor/github.com/kr/pretty/diff_test.go similarity index 100% rename from vendor/_nuts/github.com/kr/pretty/diff_test.go rename to vendor/github.com/kr/pretty/diff_test.go diff --git a/vendor/_nuts/github.com/kr/pretty/example_test.go b/vendor/github.com/kr/pretty/example_test.go similarity index 81% rename from vendor/_nuts/github.com/kr/pretty/example_test.go rename to vendor/github.com/kr/pretty/example_test.go index f192163c..ecf40f3f 100644 --- a/vendor/_nuts/github.com/kr/pretty/example_test.go +++ b/vendor/github.com/kr/pretty/example_test.go @@ -2,7 +2,7 @@ package pretty_test import ( "fmt" - "github.com/github/git-lfs/vendor/_nuts/github.com/kr/pretty" + "github.com/kr/pretty" ) func Example() { diff --git a/vendor/_nuts/github.com/kr/pretty/formatter.go b/vendor/github.com/kr/pretty/formatter.go similarity index 99% rename from vendor/_nuts/github.com/kr/pretty/formatter.go rename to vendor/github.com/kr/pretty/formatter.go index 07652978..c834d464 100644 --- a/vendor/_nuts/github.com/kr/pretty/formatter.go +++ b/vendor/github.com/kr/pretty/formatter.go @@ -7,7 +7,7 @@ import ( "strconv" "text/tabwriter" - "github.com/github/git-lfs/vendor/_nuts/github.com/kr/text" + "github.com/kr/text" ) const ( diff --git a/vendor/_nuts/github.com/kr/pretty/formatter_test.go b/vendor/github.com/kr/pretty/formatter_test.go similarity index 100% rename from vendor/_nuts/github.com/kr/pretty/formatter_test.go rename to vendor/github.com/kr/pretty/formatter_test.go diff --git a/vendor/_nuts/github.com/kr/pretty/pretty.go b/vendor/github.com/kr/pretty/pretty.go similarity index 100% rename from vendor/_nuts/github.com/kr/pretty/pretty.go rename to vendor/github.com/kr/pretty/pretty.go diff --git a/vendor/_nuts/github.com/kr/pretty/zero.go b/vendor/github.com/kr/pretty/zero.go similarity index 100% rename from vendor/_nuts/github.com/kr/pretty/zero.go rename to vendor/github.com/kr/pretty/zero.go diff --git a/vendor/_nuts/github.com/kr/pty/.gitignore b/vendor/github.com/kr/pty/.gitignore similarity index 100% rename from vendor/_nuts/github.com/kr/pty/.gitignore rename to vendor/github.com/kr/pty/.gitignore diff --git a/vendor/_nuts/github.com/kr/pty/License b/vendor/github.com/kr/pty/License similarity index 100% rename from vendor/_nuts/github.com/kr/pty/License rename to vendor/github.com/kr/pty/License diff --git a/vendor/_nuts/github.com/kr/pty/README.md b/vendor/github.com/kr/pty/README.md similarity index 100% rename from vendor/_nuts/github.com/kr/pty/README.md rename to vendor/github.com/kr/pty/README.md diff --git a/vendor/_nuts/github.com/kr/pty/doc.go b/vendor/github.com/kr/pty/doc.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/doc.go rename to vendor/github.com/kr/pty/doc.go diff --git a/vendor/_nuts/github.com/kr/pty/ioctl.go b/vendor/github.com/kr/pty/ioctl.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/ioctl.go rename to vendor/github.com/kr/pty/ioctl.go diff --git a/vendor/_nuts/github.com/kr/pty/ioctl_bsd.go b/vendor/github.com/kr/pty/ioctl_bsd.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/ioctl_bsd.go rename to vendor/github.com/kr/pty/ioctl_bsd.go diff --git a/vendor/_nuts/github.com/kr/pty/mktypes.bash b/vendor/github.com/kr/pty/mktypes.bash old mode 100644 new mode 100755 similarity index 100% rename from vendor/_nuts/github.com/kr/pty/mktypes.bash rename to vendor/github.com/kr/pty/mktypes.bash diff --git a/vendor/_nuts/github.com/kr/pty/pty_darwin.go b/vendor/github.com/kr/pty/pty_darwin.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/pty_darwin.go rename to vendor/github.com/kr/pty/pty_darwin.go diff --git a/vendor/_nuts/github.com/kr/pty/pty_freebsd.go b/vendor/github.com/kr/pty/pty_freebsd.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/pty_freebsd.go rename to vendor/github.com/kr/pty/pty_freebsd.go diff --git a/vendor/_nuts/github.com/kr/pty/pty_linux.go b/vendor/github.com/kr/pty/pty_linux.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/pty_linux.go rename to vendor/github.com/kr/pty/pty_linux.go diff --git a/vendor/_nuts/github.com/kr/pty/pty_unsupported.go b/vendor/github.com/kr/pty/pty_unsupported.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/pty_unsupported.go rename to vendor/github.com/kr/pty/pty_unsupported.go diff --git a/vendor/_nuts/github.com/kr/pty/run.go b/vendor/github.com/kr/pty/run.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/run.go rename to vendor/github.com/kr/pty/run.go diff --git a/vendor/_nuts/github.com/kr/pty/types.go b/vendor/github.com/kr/pty/types.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/types.go rename to vendor/github.com/kr/pty/types.go diff --git a/vendor/_nuts/github.com/kr/pty/types_freebsd.go b/vendor/github.com/kr/pty/types_freebsd.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/types_freebsd.go rename to vendor/github.com/kr/pty/types_freebsd.go diff --git a/vendor/_nuts/github.com/kr/pty/util.go b/vendor/github.com/kr/pty/util.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/util.go rename to vendor/github.com/kr/pty/util.go diff --git a/vendor/_nuts/github.com/kr/pty/ztypes_386.go b/vendor/github.com/kr/pty/ztypes_386.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/ztypes_386.go rename to vendor/github.com/kr/pty/ztypes_386.go diff --git a/vendor/_nuts/github.com/kr/pty/ztypes_amd64.go b/vendor/github.com/kr/pty/ztypes_amd64.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/ztypes_amd64.go rename to vendor/github.com/kr/pty/ztypes_amd64.go diff --git a/vendor/_nuts/github.com/kr/pty/ztypes_arm.go b/vendor/github.com/kr/pty/ztypes_arm.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/ztypes_arm.go rename to vendor/github.com/kr/pty/ztypes_arm.go diff --git a/vendor/_nuts/github.com/kr/pty/ztypes_arm64.go b/vendor/github.com/kr/pty/ztypes_arm64.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/ztypes_arm64.go rename to vendor/github.com/kr/pty/ztypes_arm64.go diff --git a/vendor/_nuts/github.com/kr/pty/ztypes_freebsd_386.go b/vendor/github.com/kr/pty/ztypes_freebsd_386.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/ztypes_freebsd_386.go rename to vendor/github.com/kr/pty/ztypes_freebsd_386.go diff --git a/vendor/_nuts/github.com/kr/pty/ztypes_freebsd_amd64.go b/vendor/github.com/kr/pty/ztypes_freebsd_amd64.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/ztypes_freebsd_amd64.go rename to vendor/github.com/kr/pty/ztypes_freebsd_amd64.go diff --git a/vendor/_nuts/github.com/kr/pty/ztypes_freebsd_arm.go b/vendor/github.com/kr/pty/ztypes_freebsd_arm.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/ztypes_freebsd_arm.go rename to vendor/github.com/kr/pty/ztypes_freebsd_arm.go diff --git a/vendor/_nuts/github.com/kr/pty/ztypes_ppc64.go b/vendor/github.com/kr/pty/ztypes_ppc64.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/ztypes_ppc64.go rename to vendor/github.com/kr/pty/ztypes_ppc64.go diff --git a/vendor/_nuts/github.com/kr/pty/ztypes_ppc64le.go b/vendor/github.com/kr/pty/ztypes_ppc64le.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/ztypes_ppc64le.go rename to vendor/github.com/kr/pty/ztypes_ppc64le.go diff --git a/vendor/_nuts/github.com/kr/pty/ztypes_s390x.go b/vendor/github.com/kr/pty/ztypes_s390x.go similarity index 100% rename from vendor/_nuts/github.com/kr/pty/ztypes_s390x.go rename to vendor/github.com/kr/pty/ztypes_s390x.go diff --git a/vendor/_nuts/github.com/kr/text/License b/vendor/github.com/kr/text/License similarity index 100% rename from vendor/_nuts/github.com/kr/text/License rename to vendor/github.com/kr/text/License diff --git a/vendor/_nuts/github.com/kr/text/Readme b/vendor/github.com/kr/text/Readme similarity index 100% rename from vendor/_nuts/github.com/kr/text/Readme rename to vendor/github.com/kr/text/Readme diff --git a/vendor/_nuts/github.com/kr/text/colwriter/Readme b/vendor/github.com/kr/text/colwriter/Readme similarity index 100% rename from vendor/_nuts/github.com/kr/text/colwriter/Readme rename to vendor/github.com/kr/text/colwriter/Readme diff --git a/vendor/_nuts/github.com/kr/text/colwriter/column.go b/vendor/github.com/kr/text/colwriter/column.go similarity index 100% rename from vendor/_nuts/github.com/kr/text/colwriter/column.go rename to vendor/github.com/kr/text/colwriter/column.go diff --git a/vendor/_nuts/github.com/kr/text/colwriter/column_test.go b/vendor/github.com/kr/text/colwriter/column_test.go similarity index 100% rename from vendor/_nuts/github.com/kr/text/colwriter/column_test.go rename to vendor/github.com/kr/text/colwriter/column_test.go diff --git a/vendor/_nuts/github.com/kr/text/doc.go b/vendor/github.com/kr/text/doc.go similarity index 100% rename from vendor/_nuts/github.com/kr/text/doc.go rename to vendor/github.com/kr/text/doc.go diff --git a/vendor/_nuts/github.com/kr/text/indent.go b/vendor/github.com/kr/text/indent.go similarity index 100% rename from vendor/_nuts/github.com/kr/text/indent.go rename to vendor/github.com/kr/text/indent.go diff --git a/vendor/_nuts/github.com/kr/text/indent_test.go b/vendor/github.com/kr/text/indent_test.go similarity index 100% rename from vendor/_nuts/github.com/kr/text/indent_test.go rename to vendor/github.com/kr/text/indent_test.go diff --git a/vendor/_nuts/github.com/kr/text/mc/Readme b/vendor/github.com/kr/text/mc/Readme similarity index 100% rename from vendor/_nuts/github.com/kr/text/mc/Readme rename to vendor/github.com/kr/text/mc/Readme diff --git a/vendor/_nuts/github.com/kr/text/mc/mc.go b/vendor/github.com/kr/text/mc/mc.go similarity index 90% rename from vendor/_nuts/github.com/kr/text/mc/mc.go rename to vendor/github.com/kr/text/mc/mc.go index 4c591aac..00169a30 100644 --- a/vendor/_nuts/github.com/kr/text/mc/mc.go +++ b/vendor/github.com/kr/text/mc/mc.go @@ -10,8 +10,8 @@ package main import ( - "github.com/github/git-lfs/vendor/_nuts/github.com/kr/pty" - "github.com/github/git-lfs/vendor/_nuts/github.com/kr/text/colwriter" + "github.com/kr/pty" + "github.com/kr/text/colwriter" "io" "log" "os" diff --git a/vendor/_nuts/github.com/kr/text/wrap.go b/vendor/github.com/kr/text/wrap.go old mode 100644 new mode 100755 similarity index 100% rename from vendor/_nuts/github.com/kr/text/wrap.go rename to vendor/github.com/kr/text/wrap.go diff --git a/vendor/_nuts/github.com/kr/text/wrap_test.go b/vendor/github.com/kr/text/wrap_test.go similarity index 100% rename from vendor/_nuts/github.com/kr/text/wrap_test.go rename to vendor/github.com/kr/text/wrap_test.go diff --git a/vendor/_nuts/github.com/olekukonko/ts/.travis.yml b/vendor/github.com/olekukonko/ts/.travis.yml similarity index 100% rename from vendor/_nuts/github.com/olekukonko/ts/.travis.yml rename to vendor/github.com/olekukonko/ts/.travis.yml diff --git a/vendor/_nuts/github.com/olekukonko/ts/LICENCE b/vendor/github.com/olekukonko/ts/LICENCE similarity index 100% rename from vendor/_nuts/github.com/olekukonko/ts/LICENCE rename to vendor/github.com/olekukonko/ts/LICENCE diff --git a/vendor/_nuts/github.com/olekukonko/ts/README.md b/vendor/github.com/olekukonko/ts/README.md similarity index 100% rename from vendor/_nuts/github.com/olekukonko/ts/README.md rename to vendor/github.com/olekukonko/ts/README.md diff --git a/vendor/_nuts/github.com/olekukonko/ts/doc.go b/vendor/github.com/olekukonko/ts/doc.go similarity index 100% rename from vendor/_nuts/github.com/olekukonko/ts/doc.go rename to vendor/github.com/olekukonko/ts/doc.go diff --git a/vendor/_nuts/github.com/olekukonko/ts/ts.go b/vendor/github.com/olekukonko/ts/ts.go similarity index 100% rename from vendor/_nuts/github.com/olekukonko/ts/ts.go rename to vendor/github.com/olekukonko/ts/ts.go diff --git a/vendor/_nuts/github.com/olekukonko/ts/ts_darwin.go b/vendor/github.com/olekukonko/ts/ts_darwin.go similarity index 100% rename from vendor/_nuts/github.com/olekukonko/ts/ts_darwin.go rename to vendor/github.com/olekukonko/ts/ts_darwin.go diff --git a/vendor/_nuts/github.com/olekukonko/ts/ts_linux.go b/vendor/github.com/olekukonko/ts/ts_linux.go similarity index 100% rename from vendor/_nuts/github.com/olekukonko/ts/ts_linux.go rename to vendor/github.com/olekukonko/ts/ts_linux.go diff --git a/vendor/_nuts/github.com/olekukonko/ts/ts_other.go b/vendor/github.com/olekukonko/ts/ts_other.go similarity index 100% rename from vendor/_nuts/github.com/olekukonko/ts/ts_other.go rename to vendor/github.com/olekukonko/ts/ts_other.go diff --git a/vendor/_nuts/github.com/olekukonko/ts/ts_test.go b/vendor/github.com/olekukonko/ts/ts_test.go similarity index 100% rename from vendor/_nuts/github.com/olekukonko/ts/ts_test.go rename to vendor/github.com/olekukonko/ts/ts_test.go diff --git a/vendor/_nuts/github.com/olekukonko/ts/ts_unix.go b/vendor/github.com/olekukonko/ts/ts_unix.go similarity index 100% rename from vendor/_nuts/github.com/olekukonko/ts/ts_unix.go rename to vendor/github.com/olekukonko/ts/ts_unix.go diff --git a/vendor/_nuts/github.com/olekukonko/ts/ts_windows.go b/vendor/github.com/olekukonko/ts/ts_windows.go similarity index 100% rename from vendor/_nuts/github.com/olekukonko/ts/ts_windows.go rename to vendor/github.com/olekukonko/ts/ts_windows.go diff --git a/vendor/_nuts/github.com/olekukonko/ts/ts_x.go b/vendor/github.com/olekukonko/ts/ts_x.go similarity index 100% rename from vendor/_nuts/github.com/olekukonko/ts/ts_x.go rename to vendor/github.com/olekukonko/ts/ts_x.go diff --git a/vendor/_nuts/github.com/rubyist/tracerx/LICENSE b/vendor/github.com/rubyist/tracerx/LICENSE similarity index 100% rename from vendor/_nuts/github.com/rubyist/tracerx/LICENSE rename to vendor/github.com/rubyist/tracerx/LICENSE diff --git a/vendor/_nuts/github.com/rubyist/tracerx/README.md b/vendor/github.com/rubyist/tracerx/README.md similarity index 100% rename from vendor/_nuts/github.com/rubyist/tracerx/README.md rename to vendor/github.com/rubyist/tracerx/README.md diff --git a/vendor/_nuts/github.com/rubyist/tracerx/tracerx.go b/vendor/github.com/rubyist/tracerx/tracerx.go similarity index 100% rename from vendor/_nuts/github.com/rubyist/tracerx/tracerx.go rename to vendor/github.com/rubyist/tracerx/tracerx.go diff --git a/vendor/_nuts/github.com/spf13/cobra/.gitignore b/vendor/github.com/spf13/cobra/.gitignore similarity index 100% rename from vendor/_nuts/github.com/spf13/cobra/.gitignore rename to vendor/github.com/spf13/cobra/.gitignore diff --git a/vendor/_nuts/github.com/spf13/cobra/.travis.yml b/vendor/github.com/spf13/cobra/.travis.yml similarity index 100% rename from vendor/_nuts/github.com/spf13/cobra/.travis.yml rename to vendor/github.com/spf13/cobra/.travis.yml diff --git a/vendor/_nuts/github.com/spf13/cobra/LICENSE.txt b/vendor/github.com/spf13/cobra/LICENSE.txt similarity index 100% rename from vendor/_nuts/github.com/spf13/cobra/LICENSE.txt rename to vendor/github.com/spf13/cobra/LICENSE.txt diff --git a/vendor/_nuts/github.com/spf13/cobra/README.md b/vendor/github.com/spf13/cobra/README.md similarity index 100% rename from vendor/_nuts/github.com/spf13/cobra/README.md rename to vendor/github.com/spf13/cobra/README.md diff --git a/vendor/_nuts/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go similarity index 99% rename from vendor/_nuts/github.com/spf13/cobra/bash_completions.go rename to vendor/github.com/spf13/cobra/bash_completions.go index 29ad2f91..82c4274a 100644 --- a/vendor/_nuts/github.com/spf13/cobra/bash_completions.go +++ b/vendor/github.com/spf13/cobra/bash_completions.go @@ -7,7 +7,7 @@ import ( "sort" "strings" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/pflag" + "github.com/spf13/pflag" ) const ( diff --git a/vendor/_nuts/github.com/spf13/cobra/bash_completions.md b/vendor/github.com/spf13/cobra/bash_completions.md similarity index 100% rename from vendor/_nuts/github.com/spf13/cobra/bash_completions.md rename to vendor/github.com/spf13/cobra/bash_completions.md diff --git a/vendor/_nuts/github.com/spf13/cobra/bash_completions_test.go b/vendor/github.com/spf13/cobra/bash_completions_test.go similarity index 100% rename from vendor/_nuts/github.com/spf13/cobra/bash_completions_test.go rename to vendor/github.com/spf13/cobra/bash_completions_test.go diff --git a/vendor/_nuts/github.com/spf13/cobra/cobra.go b/vendor/github.com/spf13/cobra/cobra.go similarity index 100% rename from vendor/_nuts/github.com/spf13/cobra/cobra.go rename to vendor/github.com/spf13/cobra/cobra.go diff --git a/vendor/_nuts/github.com/spf13/cobra/cobra_test.go b/vendor/github.com/spf13/cobra/cobra_test.go similarity index 99% rename from vendor/_nuts/github.com/spf13/cobra/cobra_test.go rename to vendor/github.com/spf13/cobra/cobra_test.go index c636692e..7cb4917d 100644 --- a/vendor/_nuts/github.com/spf13/cobra/cobra_test.go +++ b/vendor/github.com/spf13/cobra/cobra_test.go @@ -9,7 +9,7 @@ import ( "strings" "testing" - "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/pflag" + "github.com/spf13/pflag" ) var _ = fmt.Println diff --git a/vendor/_nuts/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go similarity index 99% rename from vendor/_nuts/github.com/spf13/cobra/command.go rename to vendor/github.com/spf13/cobra/command.go index aa1dcd46..74565c2b 100644 --- a/vendor/_nuts/github.com/spf13/cobra/command.go +++ b/vendor/github.com/spf13/cobra/command.go @@ -24,8 +24,8 @@ import ( "strings" "time" - "github.com/github/git-lfs/vendor/_nuts/github.com/inconshreveable/mousetrap" - flag "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/pflag" + "github.com/inconshreveable/mousetrap" + flag "github.com/spf13/pflag" ) // Command is just that, a command for your application. diff --git a/vendor/_nuts/github.com/spf13/cobra/command_test.go b/vendor/github.com/spf13/cobra/command_test.go similarity index 100% rename from vendor/_nuts/github.com/spf13/cobra/command_test.go rename to vendor/github.com/spf13/cobra/command_test.go diff --git a/vendor/_nuts/github.com/spf13/cobra/md_docs.go b/vendor/github.com/spf13/cobra/md_docs.go similarity index 100% rename from vendor/_nuts/github.com/spf13/cobra/md_docs.go rename to vendor/github.com/spf13/cobra/md_docs.go diff --git a/vendor/_nuts/github.com/spf13/cobra/md_docs.md b/vendor/github.com/spf13/cobra/md_docs.md similarity index 100% rename from vendor/_nuts/github.com/spf13/cobra/md_docs.md rename to vendor/github.com/spf13/cobra/md_docs.md diff --git a/vendor/_nuts/github.com/spf13/cobra/md_docs_test.go b/vendor/github.com/spf13/cobra/md_docs_test.go similarity index 100% rename from vendor/_nuts/github.com/spf13/cobra/md_docs_test.go rename to vendor/github.com/spf13/cobra/md_docs_test.go diff --git a/vendor/_nuts/github.com/spf13/pflag/.travis.yml b/vendor/github.com/spf13/pflag/.travis.yml similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/.travis.yml rename to vendor/github.com/spf13/pflag/.travis.yml diff --git a/vendor/_nuts/github.com/spf13/pflag/LICENSE b/vendor/github.com/spf13/pflag/LICENSE similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/LICENSE rename to vendor/github.com/spf13/pflag/LICENSE diff --git a/vendor/_nuts/github.com/spf13/pflag/README.md b/vendor/github.com/spf13/pflag/README.md similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/README.md rename to vendor/github.com/spf13/pflag/README.md diff --git a/vendor/_nuts/github.com/spf13/pflag/bool.go b/vendor/github.com/spf13/pflag/bool.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/bool.go rename to vendor/github.com/spf13/pflag/bool.go diff --git a/vendor/_nuts/github.com/spf13/pflag/bool_test.go b/vendor/github.com/spf13/pflag/bool_test.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/bool_test.go rename to vendor/github.com/spf13/pflag/bool_test.go diff --git a/vendor/_nuts/github.com/spf13/pflag/count.go b/vendor/github.com/spf13/pflag/count.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/count.go rename to vendor/github.com/spf13/pflag/count.go diff --git a/vendor/_nuts/github.com/spf13/pflag/count_test.go b/vendor/github.com/spf13/pflag/count_test.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/count_test.go rename to vendor/github.com/spf13/pflag/count_test.go diff --git a/vendor/_nuts/github.com/spf13/pflag/duration.go b/vendor/github.com/spf13/pflag/duration.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/duration.go rename to vendor/github.com/spf13/pflag/duration.go diff --git a/vendor/_nuts/github.com/spf13/pflag/example_test.go b/vendor/github.com/spf13/pflag/example_test.go similarity index 97% rename from vendor/_nuts/github.com/spf13/pflag/example_test.go rename to vendor/github.com/spf13/pflag/example_test.go index c5940394..9be7a49f 100644 --- a/vendor/_nuts/github.com/spf13/pflag/example_test.go +++ b/vendor/github.com/spf13/pflag/example_test.go @@ -11,7 +11,7 @@ import ( "strings" "time" - flag "github.com/github/git-lfs/vendor/_nuts/github.com/spf13/pflag" + flag "github.com/spf13/pflag" ) // Example 1: A single string flag called "species" with default value "gopher". diff --git a/vendor/_nuts/github.com/spf13/pflag/export_test.go b/vendor/github.com/spf13/pflag/export_test.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/export_test.go rename to vendor/github.com/spf13/pflag/export_test.go diff --git a/vendor/_nuts/github.com/spf13/pflag/flag.go b/vendor/github.com/spf13/pflag/flag.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/flag.go rename to vendor/github.com/spf13/pflag/flag.go diff --git a/vendor/_nuts/github.com/spf13/pflag/flag_test.go b/vendor/github.com/spf13/pflag/flag_test.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/flag_test.go rename to vendor/github.com/spf13/pflag/flag_test.go diff --git a/vendor/_nuts/github.com/spf13/pflag/float32.go b/vendor/github.com/spf13/pflag/float32.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/float32.go rename to vendor/github.com/spf13/pflag/float32.go diff --git a/vendor/_nuts/github.com/spf13/pflag/float64.go b/vendor/github.com/spf13/pflag/float64.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/float64.go rename to vendor/github.com/spf13/pflag/float64.go diff --git a/vendor/_nuts/github.com/spf13/pflag/int.go b/vendor/github.com/spf13/pflag/int.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/int.go rename to vendor/github.com/spf13/pflag/int.go diff --git a/vendor/_nuts/github.com/spf13/pflag/int32.go b/vendor/github.com/spf13/pflag/int32.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/int32.go rename to vendor/github.com/spf13/pflag/int32.go diff --git a/vendor/_nuts/github.com/spf13/pflag/int64.go b/vendor/github.com/spf13/pflag/int64.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/int64.go rename to vendor/github.com/spf13/pflag/int64.go diff --git a/vendor/_nuts/github.com/spf13/pflag/int8.go b/vendor/github.com/spf13/pflag/int8.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/int8.go rename to vendor/github.com/spf13/pflag/int8.go diff --git a/vendor/_nuts/github.com/spf13/pflag/int_slice.go b/vendor/github.com/spf13/pflag/int_slice.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/int_slice.go rename to vendor/github.com/spf13/pflag/int_slice.go diff --git a/vendor/_nuts/github.com/spf13/pflag/int_slice_test.go b/vendor/github.com/spf13/pflag/int_slice_test.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/int_slice_test.go rename to vendor/github.com/spf13/pflag/int_slice_test.go diff --git a/vendor/_nuts/github.com/spf13/pflag/ip.go b/vendor/github.com/spf13/pflag/ip.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/ip.go rename to vendor/github.com/spf13/pflag/ip.go diff --git a/vendor/_nuts/github.com/spf13/pflag/ip_test.go b/vendor/github.com/spf13/pflag/ip_test.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/ip_test.go rename to vendor/github.com/spf13/pflag/ip_test.go diff --git a/vendor/_nuts/github.com/spf13/pflag/ipmask.go b/vendor/github.com/spf13/pflag/ipmask.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/ipmask.go rename to vendor/github.com/spf13/pflag/ipmask.go diff --git a/vendor/_nuts/github.com/spf13/pflag/ipnet.go b/vendor/github.com/spf13/pflag/ipnet.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/ipnet.go rename to vendor/github.com/spf13/pflag/ipnet.go diff --git a/vendor/_nuts/github.com/spf13/pflag/ipnet_test.go b/vendor/github.com/spf13/pflag/ipnet_test.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/ipnet_test.go rename to vendor/github.com/spf13/pflag/ipnet_test.go diff --git a/vendor/_nuts/github.com/spf13/pflag/string.go b/vendor/github.com/spf13/pflag/string.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/string.go rename to vendor/github.com/spf13/pflag/string.go diff --git a/vendor/_nuts/github.com/spf13/pflag/string_slice.go b/vendor/github.com/spf13/pflag/string_slice.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/string_slice.go rename to vendor/github.com/spf13/pflag/string_slice.go diff --git a/vendor/_nuts/github.com/spf13/pflag/string_slice_test.go b/vendor/github.com/spf13/pflag/string_slice_test.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/string_slice_test.go rename to vendor/github.com/spf13/pflag/string_slice_test.go diff --git a/vendor/_nuts/github.com/spf13/pflag/uint.go b/vendor/github.com/spf13/pflag/uint.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/uint.go rename to vendor/github.com/spf13/pflag/uint.go diff --git a/vendor/_nuts/github.com/spf13/pflag/uint16.go b/vendor/github.com/spf13/pflag/uint16.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/uint16.go rename to vendor/github.com/spf13/pflag/uint16.go diff --git a/vendor/_nuts/github.com/spf13/pflag/uint32.go b/vendor/github.com/spf13/pflag/uint32.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/uint32.go rename to vendor/github.com/spf13/pflag/uint32.go diff --git a/vendor/_nuts/github.com/spf13/pflag/uint64.go b/vendor/github.com/spf13/pflag/uint64.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/uint64.go rename to vendor/github.com/spf13/pflag/uint64.go diff --git a/vendor/_nuts/github.com/spf13/pflag/uint8.go b/vendor/github.com/spf13/pflag/uint8.go similarity index 100% rename from vendor/_nuts/github.com/spf13/pflag/uint8.go rename to vendor/github.com/spf13/pflag/uint8.go diff --git a/vendor/github.com/stretchr/testify/.gitignore b/vendor/github.com/stretchr/testify/.gitignore new file mode 100644 index 00000000..5aacdb7c --- /dev/null +++ b/vendor/github.com/stretchr/testify/.gitignore @@ -0,0 +1,24 @@ +# 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 + +.DS_Store diff --git a/vendor/github.com/stretchr/testify/.travis.yml b/vendor/github.com/stretchr/testify/.travis.yml new file mode 100644 index 00000000..455923ec --- /dev/null +++ b/vendor/github.com/stretchr/testify/.travis.yml @@ -0,0 +1,15 @@ +language: go + +sudo: false + +go: + - 1.1 + - 1.2 + - 1.3 + - 1.4 + - 1.5 + - 1.6 + - tip + +script: + - go test -v ./... diff --git a/vendor/github.com/stretchr/testify/Godeps/Godeps.json b/vendor/github.com/stretchr/testify/Godeps/Godeps.json new file mode 100644 index 00000000..5069ce03 --- /dev/null +++ b/vendor/github.com/stretchr/testify/Godeps/Godeps.json @@ -0,0 +1,21 @@ +{ + "ImportPath": "github.com/stretchr/testify", + "GoVersion": "go1.5", + "Packages": [ + "./..." + ], + "Deps": [ + { + "ImportPath": "github.com/davecgh/go-spew/spew", + "Rev": "5215b55f46b2b919f50a1df0eaa5886afe4e3b3d" + }, + { + "ImportPath": "github.com/pmezard/go-difflib/difflib", + "Rev": "d8ed2627bdf02c080bf22230dbb337003b7aba2d" + }, + { + "ImportPath": "github.com/stretchr/objx", + "Rev": "cbeaeb16a013161a98496fad62933b1d21786672" + } + ] +} diff --git a/vendor/github.com/stretchr/testify/Godeps/Readme b/vendor/github.com/stretchr/testify/Godeps/Readme new file mode 100644 index 00000000..4cdaa53d --- /dev/null +++ b/vendor/github.com/stretchr/testify/Godeps/Readme @@ -0,0 +1,5 @@ +This directory tree is generated automatically by godep. + +Please do not edit. + +See https://github.com/tools/godep for more information. diff --git a/vendor/github.com/stretchr/testify/LICENCE.txt b/vendor/github.com/stretchr/testify/LICENCE.txt new file mode 100644 index 00000000..473b670a --- /dev/null +++ b/vendor/github.com/stretchr/testify/LICENCE.txt @@ -0,0 +1,22 @@ +Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell + +Please consider promoting this project if you find it useful. + +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. diff --git a/vendor/github.com/stretchr/testify/LICENSE b/vendor/github.com/stretchr/testify/LICENSE new file mode 100644 index 00000000..473b670a --- /dev/null +++ b/vendor/github.com/stretchr/testify/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell + +Please consider promoting this project if you find it useful. + +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. diff --git a/vendor/github.com/stretchr/testify/README.md b/vendor/github.com/stretchr/testify/README.md new file mode 100644 index 00000000..aaf2aa0a --- /dev/null +++ b/vendor/github.com/stretchr/testify/README.md @@ -0,0 +1,332 @@ +Testify - Thou Shalt Write Tests +================================ + +[![Build Status](https://travis-ci.org/stretchr/testify.svg)](https://travis-ci.org/stretchr/testify) + +Go code (golang) set of packages that provide many tools for testifying that your code will behave as you intend. + +Features include: + + * [Easy assertions](#assert-package) + * [Mocking](#mock-package) + * [HTTP response trapping](#http-package) + * [Testing suite interfaces and functions](#suite-package) + +Get started: + + * Install testify with [one line of code](#installation), or [update it with another](#staying-up-to-date) + * For an introduction to writing test code in Go, see http://golang.org/doc/code.html#Testing + * Check out the API Documentation http://godoc.org/github.com/stretchr/testify + * To make your testing life easier, check out our other project, [gorc](http://github.com/stretchr/gorc) + * A little about [Test-Driven Development (TDD)](http://en.wikipedia.org/wiki/Test-driven_development) + + + +[`assert`](http://godoc.org/github.com/stretchr/testify/assert "API documentation") package +------------------------------------------------------------------------------------------- + +The `assert` package provides some helpful methods that allow you to write better test code in Go. + + * Prints friendly, easy to read failure descriptions + * Allows for very readable code + * Optionally annotate each assertion with a message + +See it in action: + +```go +package yours + +import ( + "testing" + "github.com/stretchr/testify/assert" +) + +func TestSomething(t *testing.T) { + + // assert equality + assert.Equal(t, 123, 123, "they should be equal") + + // assert inequality + assert.NotEqual(t, 123, 456, "they should not be equal") + + // assert for nil (good for errors) + assert.Nil(t, object) + + // assert for not nil (good when you expect something) + if assert.NotNil(t, object) { + + // now we know that object isn't nil, we are safe to make + // further assertions without causing any errors + assert.Equal(t, "Something", object.Value) + + } + +} +``` + + * Every assert func takes the `testing.T` object as the first argument. This is how it writes the errors out through the normal `go test` capabilities. + * Every assert func returns a bool indicating whether the assertion was successful or not, this is useful for if you want to go on making further assertions under certain conditions. + +if you assert many times, use the below: + +```go +package yours + +import ( + "testing" + "github.com/stretchr/testify/assert" +) + +func TestSomething(t *testing.T) { + assert := assert.New(t) + + // assert equality + assert.Equal(123, 123, "they should be equal") + + // assert inequality + assert.NotEqual(123, 456, "they should not be equal") + + // assert for nil (good for errors) + assert.Nil(object) + + // assert for not nil (good when you expect something) + if assert.NotNil(object) { + + // now we know that object isn't nil, we are safe to make + // further assertions without causing any errors + assert.Equal("Something", object.Value) + } +} +``` + +[`require`](http://godoc.org/github.com/stretchr/testify/require "API documentation") package +--------------------------------------------------------------------------------------------- + +The `require` package provides same global functions as the `assert` package, but instead of returning a boolean result they terminate current test. + +See [t.FailNow](http://golang.org/pkg/testing/#T.FailNow) for details. + + +[`http`](http://godoc.org/github.com/stretchr/testify/http "API documentation") package +--------------------------------------------------------------------------------------- + +The `http` package contains test objects useful for testing code that relies on the `net/http` package. Check out the [(deprecated) API documentation for the `http` package](http://godoc.org/github.com/stretchr/testify/http). + +We recommend you use [httptest](http://golang.org/pkg/net/http/httptest) instead. + +[`mock`](http://godoc.org/github.com/stretchr/testify/mock "API documentation") package +---------------------------------------------------------------------------------------- + +The `mock` package provides a mechanism for easily writing mock objects that can be used in place of real objects when writing test code. + +An example test function that tests a piece of code that relies on an external object `testObj`, can setup expectations (testify) and assert that they indeed happened: + +```go +package yours + +import ( + "testing" + "github.com/stretchr/testify/mock" +) + +/* + Test objects +*/ + +// MyMockedObject is a mocked object that implements an interface +// that describes an object that the code I am testing relies on. +type MyMockedObject struct{ + mock.Mock +} + +// DoSomething is a method on MyMockedObject that implements some interface +// and just records the activity, and returns what the Mock object tells it to. +// +// In the real object, this method would do something useful, but since this +// is a mocked object - we're just going to stub it out. +// +// NOTE: This method is not being tested here, code that uses this object is. +func (m *MyMockedObject) DoSomething(number int) (bool, error) { + + args := m.Called(number) + return args.Bool(0), args.Error(1) + +} + +/* + Actual test functions +*/ + +// TestSomething is an example of how to use our test object to +// make assertions about some target code we are testing. +func TestSomething(t *testing.T) { + + // create an instance of our test object + testObj := new(MyMockedObject) + + // setup expectations + testObj.On("DoSomething", 123).Return(true, nil) + + // call the code we are testing + targetFuncThatDoesSomethingWithObj(testObj) + + // assert that the expectations were met + testObj.AssertExpectations(t) + +} +``` + +For more information on how to write mock code, check out the [API documentation for the `mock` package](http://godoc.org/github.com/stretchr/testify/mock). + +You can use the [mockery tool](http://github.com/vektra/mockery) to autogenerate the mock code against an interface as well, making using mocks much quicker. + +[`suite`](http://godoc.org/github.com/stretchr/testify/suite "API documentation") package +----------------------------------------------------------------------------------------- + +The `suite` package provides functionality that you might be used to from more common object oriented languages. With it, you can build a testing suite as a struct, build setup/teardown methods and testing methods on your struct, and run them with 'go test' as per normal. + +An example suite is shown below: + +```go +// Basic imports +import ( + "testing" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/suite" +) + +// Define the suite, and absorb the built-in basic suite +// functionality from testify - including a T() method which +// returns the current testing context +type ExampleTestSuite struct { + suite.Suite + VariableThatShouldStartAtFive int +} + +// Make sure that VariableThatShouldStartAtFive is set to five +// before each test +func (suite *ExampleTestSuite) SetupTest() { + suite.VariableThatShouldStartAtFive = 5 +} + +// All methods that begin with "Test" are run as tests within a +// suite. +func (suite *ExampleTestSuite) TestExample() { + assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) +} + +// In order for 'go test' to run this suite, we need to create +// a normal test function and pass our suite to suite.Run +func TestExampleTestSuite(t *testing.T) { + suite.Run(t, new(ExampleTestSuite)) +} +``` + +For a more complete example, using all of the functionality provided by the suite package, look at our [example testing suite](https://github.com/stretchr/testify/blob/master/suite/suite_test.go) + +For more information on writing suites, check out the [API documentation for the `suite` package](http://godoc.org/github.com/stretchr/testify/suite). + +`Suite` object has assertion methods: + +```go +// Basic imports +import ( + "testing" + "github.com/stretchr/testify/suite" +) + +// Define the suite, and absorb the built-in basic suite +// functionality from testify - including assertion methods. +type ExampleTestSuite struct { + suite.Suite + VariableThatShouldStartAtFive int +} + +// Make sure that VariableThatShouldStartAtFive is set to five +// before each test +func (suite *ExampleTestSuite) SetupTest() { + suite.VariableThatShouldStartAtFive = 5 +} + +// All methods that begin with "Test" are run as tests within a +// suite. +func (suite *ExampleTestSuite) TestExample() { + suite.Equal(suite.VariableThatShouldStartAtFive, 5) +} + +// In order for 'go test' to run this suite, we need to create +// a normal test function and pass our suite to suite.Run +func TestExampleTestSuite(t *testing.T) { + suite.Run(t, new(ExampleTestSuite)) +} +``` + +------ + +Installation +============ + +To install Testify, use `go get`: + + * Latest version: go get github.com/stretchr/testify + * Specific version: go get gopkg.in/stretchr/testify.v1 + +This will then make the following packages available to you: + + github.com/stretchr/testify/assert + github.com/stretchr/testify/mock + github.com/stretchr/testify/http + +Import the `testify/assert` package into your code using this template: + +```go +package yours + +import ( + "testing" + "github.com/stretchr/testify/assert" +) + +func TestSomething(t *testing.T) { + + assert.True(t, true, "True is true!") + +} +``` + +------ + +Staying up to date +================== + +To update Testify to the latest version, use `go get -u github.com/stretchr/testify`. + +------ + +Version History +=============== + + * 1.0 - New package versioning strategy adopted. + +------ + +Contributing +============ + +Please feel free to submit issues, fork the repository and send pull requests! + +When submitting an issue, we ask that you please include a complete test function that demonstrates the issue. Extra credit for those using Testify to write the test code that demonstrates it. + +------ + +Licence +======= +Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell + +Please consider promoting this project if you find it useful. + +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. diff --git a/vendor/github.com/stretchr/testify/_codegen/main.go b/vendor/github.com/stretchr/testify/_codegen/main.go new file mode 100644 index 00000000..328009f8 --- /dev/null +++ b/vendor/github.com/stretchr/testify/_codegen/main.go @@ -0,0 +1,287 @@ +// This program reads all assertion functions from the assert package and +// automatically generates the corersponding requires and forwarded assertions + +package main + +import ( + "bytes" + "flag" + "fmt" + "go/ast" + "go/build" + "go/doc" + "go/importer" + "go/parser" + "go/token" + "go/types" + "io" + "io/ioutil" + "log" + "os" + "path" + "strings" + "text/template" + + "github.com/ernesto-jimenez/gogen/imports" +) + +var ( + pkg = flag.String("assert-path", "github.com/stretchr/testify/assert", "Path to the assert package") + outputPkg = flag.String("output-package", "", "package for the resulting code") + tmplFile = flag.String("template", "", "What file to load the function template from") + out = flag.String("out", "", "What file to write the source code to") +) + +func main() { + flag.Parse() + + scope, docs, err := parsePackageSource(*pkg) + if err != nil { + log.Fatal(err) + } + + importer, funcs, err := analyzeCode(scope, docs) + if err != nil { + log.Fatal(err) + } + + if err := generateCode(importer, funcs); err != nil { + log.Fatal(err) + } +} + +func generateCode(importer imports.Importer, funcs []testFunc) error { + buff := bytes.NewBuffer(nil) + + tmplHead, tmplFunc, err := parseTemplates() + if err != nil { + return err + } + + // Generate header + if err := tmplHead.Execute(buff, struct { + Name string + Imports map[string]string + }{ + *outputPkg, + importer.Imports(), + }); err != nil { + return err + } + + // Generate funcs + for _, fn := range funcs { + buff.Write([]byte("\n\n")) + if err := tmplFunc.Execute(buff, &fn); err != nil { + return err + } + } + + // Write file + output, err := outputFile() + if err != nil { + return err + } + defer output.Close() + _, err = io.Copy(output, buff) + return err +} + +func parseTemplates() (*template.Template, *template.Template, error) { + tmplHead, err := template.New("header").Parse(headerTemplate) + if err != nil { + return nil, nil, err + } + if *tmplFile != "" { + f, err := ioutil.ReadFile(*tmplFile) + if err != nil { + return nil, nil, err + } + funcTemplate = string(f) + } + tmpl, err := template.New("function").Parse(funcTemplate) + if err != nil { + return nil, nil, err + } + return tmplHead, tmpl, nil +} + +func outputFile() (*os.File, error) { + filename := *out + if filename == "-" || (filename == "" && *tmplFile == "") { + return os.Stdout, nil + } + if filename == "" { + filename = strings.TrimSuffix(strings.TrimSuffix(*tmplFile, ".tmpl"), ".go") + ".go" + } + return os.Create(filename) +} + +// analyzeCode takes the types scope and the docs and returns the import +// information and information about all the assertion functions. +func analyzeCode(scope *types.Scope, docs *doc.Package) (imports.Importer, []testFunc, error) { + testingT := scope.Lookup("TestingT").Type().Underlying().(*types.Interface) + + importer := imports.New(*outputPkg) + var funcs []testFunc + // Go through all the top level functions + for _, fdocs := range docs.Funcs { + // Find the function + obj := scope.Lookup(fdocs.Name) + + fn, ok := obj.(*types.Func) + if !ok { + continue + } + // Check function signatuer has at least two arguments + sig := fn.Type().(*types.Signature) + if sig.Params().Len() < 2 { + continue + } + // Check first argument is of type testingT + first, ok := sig.Params().At(0).Type().(*types.Named) + if !ok { + continue + } + firstType, ok := first.Underlying().(*types.Interface) + if !ok { + continue + } + if !types.Implements(firstType, testingT) { + continue + } + + funcs = append(funcs, testFunc{*outputPkg, fdocs, fn}) + importer.AddImportsFrom(sig.Params()) + } + return importer, funcs, nil +} + +// parsePackageSource returns the types scope and the package documentation from the pa +func parsePackageSource(pkg string) (*types.Scope, *doc.Package, error) { + pd, err := build.Import(pkg, ".", 0) + if err != nil { + return nil, nil, err + } + + fset := token.NewFileSet() + files := make(map[string]*ast.File) + fileList := make([]*ast.File, len(pd.GoFiles)) + for i, fname := range pd.GoFiles { + src, err := ioutil.ReadFile(path.Join(pd.SrcRoot, pd.ImportPath, fname)) + if err != nil { + return nil, nil, err + } + f, err := parser.ParseFile(fset, fname, src, parser.ParseComments|parser.AllErrors) + if err != nil { + return nil, nil, err + } + files[fname] = f + fileList[i] = f + } + + cfg := types.Config{ + Importer: importer.Default(), + } + info := types.Info{ + Defs: make(map[*ast.Ident]types.Object), + } + tp, err := cfg.Check(pkg, fset, fileList, &info) + if err != nil { + return nil, nil, err + } + + scope := tp.Scope() + + ap, _ := ast.NewPackage(fset, files, nil, nil) + docs := doc.New(ap, pkg, 0) + + return scope, docs, nil +} + +type testFunc struct { + CurrentPkg string + DocInfo *doc.Func + TypeInfo *types.Func +} + +func (f *testFunc) Qualifier(p *types.Package) string { + if p == nil || p.Name() == f.CurrentPkg { + return "" + } + return p.Name() +} + +func (f *testFunc) Params() string { + sig := f.TypeInfo.Type().(*types.Signature) + params := sig.Params() + p := "" + comma := "" + to := params.Len() + var i int + + if sig.Variadic() { + to-- + } + for i = 1; i < to; i++ { + param := params.At(i) + p += fmt.Sprintf("%s%s %s", comma, param.Name(), types.TypeString(param.Type(), f.Qualifier)) + comma = ", " + } + if sig.Variadic() { + param := params.At(params.Len() - 1) + p += fmt.Sprintf("%s%s ...%s", comma, param.Name(), types.TypeString(param.Type().(*types.Slice).Elem(), f.Qualifier)) + } + return p +} + +func (f *testFunc) ForwardedParams() string { + sig := f.TypeInfo.Type().(*types.Signature) + params := sig.Params() + p := "" + comma := "" + to := params.Len() + var i int + + if sig.Variadic() { + to-- + } + for i = 1; i < to; i++ { + param := params.At(i) + p += fmt.Sprintf("%s%s", comma, param.Name()) + comma = ", " + } + if sig.Variadic() { + param := params.At(params.Len() - 1) + p += fmt.Sprintf("%s%s...", comma, param.Name()) + } + return p +} + +func (f *testFunc) Comment() string { + return "// " + strings.Replace(strings.TrimSpace(f.DocInfo.Doc), "\n", "\n// ", -1) +} + +func (f *testFunc) CommentWithoutT(receiver string) string { + search := fmt.Sprintf("assert.%s(t, ", f.DocInfo.Name) + replace := fmt.Sprintf("%s.%s(", receiver, f.DocInfo.Name) + return strings.Replace(f.Comment(), search, replace, -1) +} + +var headerTemplate = `/* +* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen +* THIS FILE MUST NOT BE EDITED BY HAND +*/ + +package {{.Name}} + +import ( +{{range $path, $name := .Imports}} + {{$name}} "{{$path}}"{{end}} +) +` + +var funcTemplate = `{{.Comment}} +func (fwd *AssertionsForwarder) {{.DocInfo.Name}}({{.Params}}) bool { + return assert.{{.DocInfo.Name}}({{.ForwardedParams}}) +}` diff --git a/vendor/github.com/stretchr/testify/assert/assertion_forward.go b/vendor/github.com/stretchr/testify/assert/assertion_forward.go new file mode 100644 index 00000000..e6a79604 --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/assertion_forward.go @@ -0,0 +1,387 @@ +/* +* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen +* THIS FILE MUST NOT BE EDITED BY HAND +*/ + +package assert + +import ( + + http "net/http" + url "net/url" + time "time" +) + + +// Condition uses a Comparison to assert a complex condition. +func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool { + return Condition(a.t, comp, msgAndArgs...) +} + + +// Contains asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// a.Contains("Hello World", "World", "But 'Hello World' does contain 'World'") +// a.Contains(["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") +// a.Contains({"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { + return Contains(a.t, s, contains, msgAndArgs...) +} + + +// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// a.Empty(obj) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool { + return Empty(a.t, object, msgAndArgs...) +} + + +// Equal asserts that two objects are equal. +// +// a.Equal(123, 123, "123 and 123 should be equal") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { + return Equal(a.t, expected, actual, msgAndArgs...) +} + + +// EqualError asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// if assert.Error(t, err, "An error was expected") { +// assert.Equal(t, err, expectedError) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool { + return EqualError(a.t, theError, errString, msgAndArgs...) +} + + +// EqualValues asserts that two objects are equal or convertable to the same types +// and equal. +// +// a.EqualValues(uint32(123), int32(123), "123 and 123 should be equal") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { + return EqualValues(a.t, expected, actual, msgAndArgs...) +} + + +// Error asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if a.Error(err, "An error was expected") { +// assert.Equal(t, err, expectedError) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Error(err error, msgAndArgs ...interface{}) bool { + return Error(a.t, err, msgAndArgs...) +} + + +// Exactly asserts that two objects are equal is value and type. +// +// a.Exactly(int32(123), int64(123), "123 and 123 should NOT be equal") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { + return Exactly(a.t, expected, actual, msgAndArgs...) +} + + +// Fail reports a failure through +func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool { + return Fail(a.t, failureMessage, msgAndArgs...) +} + + +// FailNow fails test +func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) bool { + return FailNow(a.t, failureMessage, msgAndArgs...) +} + + +// False asserts that the specified value is false. +// +// a.False(myBool, "myBool should be false") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool { + return False(a.t, value, msgAndArgs...) +} + + +// HTTPBodyContains asserts that a specified handler returns a +// body that contains a string. +// +// a.HTTPBodyContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { + return HTTPBodyContains(a.t, handler, method, url, values, str) +} + + +// HTTPBodyNotContains asserts that a specified handler returns a +// body that does not contain a string. +// +// a.HTTPBodyNotContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { + return HTTPBodyNotContains(a.t, handler, method, url, values, str) +} + + +// HTTPError asserts that a specified handler returns an error status code. +// +// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values) bool { + return HTTPError(a.t, handler, method, url, values) +} + + +// HTTPRedirect asserts that a specified handler returns a redirect status code. +// +// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values) bool { + return HTTPRedirect(a.t, handler, method, url, values) +} + + +// HTTPSuccess asserts that a specified handler returns a success status code. +// +// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values) bool { + return HTTPSuccess(a.t, handler, method, url, values) +} + + +// Implements asserts that an object is implemented by the specified interface. +// +// a.Implements((*MyInterface)(nil), new(MyObject), "MyObject") +func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { + return Implements(a.t, interfaceObject, object, msgAndArgs...) +} + + +// InDelta asserts that the two numerals are within delta of each other. +// +// a.InDelta(math.Pi, (22 / 7.0), 0.01) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { + return InDelta(a.t, expected, actual, delta, msgAndArgs...) +} + + +// InDeltaSlice is the same as InDelta, except it compares two slices. +func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { + return InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) +} + + +// InEpsilon asserts that expected and actual have a relative error less than epsilon +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { + return InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) +} + + +// InEpsilonSlice is the same as InEpsilon, except it compares two slices. +func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { + return InEpsilonSlice(a.t, expected, actual, delta, msgAndArgs...) +} + + +// IsType asserts that the specified objects are of the same type. +func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { + return IsType(a.t, expectedType, object, msgAndArgs...) +} + + +// JSONEq asserts that two JSON strings are equivalent. +// +// a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) bool { + return JSONEq(a.t, expected, actual, msgAndArgs...) +} + + +// Len asserts that the specified object has specific length. +// Len also fails if the object has a type that len() not accept. +// +// a.Len(mySlice, 3, "The size of slice is not 3") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool { + return Len(a.t, object, length, msgAndArgs...) +} + + +// Nil asserts that the specified object is nil. +// +// a.Nil(err, "err should be nothing") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool { + return Nil(a.t, object, msgAndArgs...) +} + + +// NoError asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if a.NoError(err) { +// assert.Equal(t, actualObj, expectedObj) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) bool { + return NoError(a.t, err, msgAndArgs...) +} + + +// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// a.NotContains("Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") +// a.NotContains(["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") +// a.NotContains({"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { + return NotContains(a.t, s, contains, msgAndArgs...) +} + + +// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if a.NotEmpty(obj) { +// assert.Equal(t, "two", obj[1]) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool { + return NotEmpty(a.t, object, msgAndArgs...) +} + + +// NotEqual asserts that the specified values are NOT equal. +// +// a.NotEqual(obj1, obj2, "two objects shouldn't be equal") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { + return NotEqual(a.t, expected, actual, msgAndArgs...) +} + + +// NotNil asserts that the specified object is not nil. +// +// a.NotNil(err, "err should be something") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool { + return NotNil(a.t, object, msgAndArgs...) +} + + +// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// a.NotPanics(func(){ +// RemainCalm() +// }, "Calling RemainCalm() should NOT panic") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool { + return NotPanics(a.t, f, msgAndArgs...) +} + + +// NotRegexp asserts that a specified regexp does not match a string. +// +// a.NotRegexp(regexp.MustCompile("starts"), "it's starting") +// a.NotRegexp("^start", "it's not starting") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { + return NotRegexp(a.t, rx, str, msgAndArgs...) +} + + +// NotZero asserts that i is not the zero value for its type and returns the truth. +func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) bool { + return NotZero(a.t, i, msgAndArgs...) +} + + +// Panics asserts that the code inside the specified PanicTestFunc panics. +// +// a.Panics(func(){ +// GoCrazy() +// }, "Calling GoCrazy() should panic") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool { + return Panics(a.t, f, msgAndArgs...) +} + + +// Regexp asserts that a specified regexp matches a string. +// +// a.Regexp(regexp.MustCompile("start"), "it's starting") +// a.Regexp("start...$", "it's not starting") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { + return Regexp(a.t, rx, str, msgAndArgs...) +} + + +// True asserts that the specified value is true. +// +// a.True(myBool, "myBool should be true") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool { + return True(a.t, value, msgAndArgs...) +} + + +// WithinDuration asserts that the two times are within duration delta of each other. +// +// a.WithinDuration(time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { + return WithinDuration(a.t, expected, actual, delta, msgAndArgs...) +} + + +// Zero asserts that i is the zero value for its type and returns the truth. +func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) bool { + return Zero(a.t, i, msgAndArgs...) +} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl b/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl new file mode 100644 index 00000000..99f9acfb --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl @@ -0,0 +1,4 @@ +{{.CommentWithoutT "a"}} +func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) bool { + return {{.DocInfo.Name}}(a.t, {{.ForwardedParams}}) +} diff --git a/vendor/github.com/stretchr/testify/assert/assertions.go b/vendor/github.com/stretchr/testify/assert/assertions.go new file mode 100644 index 00000000..d7c16c59 --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/assertions.go @@ -0,0 +1,1004 @@ +package assert + +import ( + "bufio" + "bytes" + "encoding/json" + "fmt" + "math" + "reflect" + "regexp" + "runtime" + "strings" + "time" + "unicode" + "unicode/utf8" + + "github.com/davecgh/go-spew/spew" + "github.com/pmezard/go-difflib/difflib" +) + +// TestingT is an interface wrapper around *testing.T +type TestingT interface { + Errorf(format string, args ...interface{}) +} + +// Comparison a custom function that returns true on success and false on failure +type Comparison func() (success bool) + +/* + Helper functions +*/ + +// ObjectsAreEqual determines if two objects are considered equal. +// +// This function does no assertion of any kind. +func ObjectsAreEqual(expected, actual interface{}) bool { + + if expected == nil || actual == nil { + return expected == actual + } + + return reflect.DeepEqual(expected, actual) + +} + +// ObjectsAreEqualValues gets whether two objects are equal, or if their +// values are equal. +func ObjectsAreEqualValues(expected, actual interface{}) bool { + if ObjectsAreEqual(expected, actual) { + return true + } + + actualType := reflect.TypeOf(actual) + if actualType == nil { + return false + } + expectedValue := reflect.ValueOf(expected) + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + // Attempt comparison after type conversion + return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + + return false +} + +/* CallerInfo is necessary because the assert functions use the testing object +internally, causing it to print the file:line of the assert method, rather than where +the problem actually occured in calling code.*/ + +// CallerInfo returns an array of strings containing the file and line number +// of each stack frame leading from the current test to the assert call that +// failed. +func CallerInfo() []string { + + pc := uintptr(0) + file := "" + line := 0 + ok := false + name := "" + + callers := []string{} + for i := 0; ; i++ { + pc, file, line, ok = runtime.Caller(i) + if !ok { + return nil + } + + // This is a huge edge case, but it will panic if this is the case, see #180 + if file == "" { + break + } + + parts := strings.Split(file, "/") + dir := parts[len(parts)-2] + file = parts[len(parts)-1] + if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" { + callers = append(callers, fmt.Sprintf("%s:%d", file, line)) + } + + f := runtime.FuncForPC(pc) + if f == nil { + break + } + name = f.Name() + // Drop the package + segments := strings.Split(name, ".") + name = segments[len(segments)-1] + if isTest(name, "Test") || + isTest(name, "Benchmark") || + isTest(name, "Example") { + break + } + } + + return callers +} + +// Stolen from the `go test` tool. +// isTest tells whether name looks like a test (or benchmark, according to prefix). +// It is a Test (say) if there is a character after Test that is not a lower-case letter. +// We don't want TesticularCancer. +func isTest(name, prefix string) bool { + if !strings.HasPrefix(name, prefix) { + return false + } + if len(name) == len(prefix) { // "Test" is ok + return true + } + rune, _ := utf8.DecodeRuneInString(name[len(prefix):]) + return !unicode.IsLower(rune) +} + +// getWhitespaceString returns a string that is long enough to overwrite the default +// output from the go testing framework. +func getWhitespaceString() string { + + _, file, line, ok := runtime.Caller(1) + if !ok { + return "" + } + parts := strings.Split(file, "/") + file = parts[len(parts)-1] + + return strings.Repeat(" ", len(fmt.Sprintf("%s:%d: ", file, line))) + +} + +func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { + if len(msgAndArgs) == 0 || msgAndArgs == nil { + return "" + } + if len(msgAndArgs) == 1 { + return msgAndArgs[0].(string) + } + if len(msgAndArgs) > 1 { + return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...) + } + return "" +} + +// Indents all lines of the message by appending a number of tabs to each line, in an output format compatible with Go's +// test printing (see inner comment for specifics) +func indentMessageLines(message string, tabs int) string { + outBuf := new(bytes.Buffer) + + for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ { + if i != 0 { + outBuf.WriteRune('\n') + } + for ii := 0; ii < tabs; ii++ { + outBuf.WriteRune('\t') + // Bizarrely, all lines except the first need one fewer tabs prepended, so deliberately advance the counter + // by 1 prematurely. + if ii == 0 && i > 0 { + ii++ + } + } + outBuf.WriteString(scanner.Text()) + } + + return outBuf.String() +} + +type failNower interface { + FailNow() +} + +// FailNow fails test +func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { + Fail(t, failureMessage, msgAndArgs...) + + // We cannot extend TestingT with FailNow() and + // maintain backwards compatibility, so we fallback + // to panicking when FailNow is not available in + // TestingT. + // See issue #263 + + if t, ok := t.(failNower); ok { + t.FailNow() + } else { + panic("test failed and t is missing `FailNow()`") + } + return false +} + +// Fail reports a failure through +func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { + + message := messageFromMsgAndArgs(msgAndArgs...) + + errorTrace := strings.Join(CallerInfo(), "\n\r\t\t\t") + if len(message) > 0 { + t.Errorf("\r%s\r\tError Trace:\t%s\n"+ + "\r\tError:%s\n"+ + "\r\tMessages:\t%s\n\r", + getWhitespaceString(), + errorTrace, + indentMessageLines(failureMessage, 2), + message) + } else { + t.Errorf("\r%s\r\tError Trace:\t%s\n"+ + "\r\tError:%s\n\r", + getWhitespaceString(), + errorTrace, + indentMessageLines(failureMessage, 2)) + } + + return false +} + +// Implements asserts that an object is implemented by the specified interface. +// +// assert.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject") +func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { + + interfaceType := reflect.TypeOf(interfaceObject).Elem() + + if !reflect.TypeOf(object).Implements(interfaceType) { + return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...) + } + + return true + +} + +// IsType asserts that the specified objects are of the same type. +func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { + + if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) { + return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...) + } + + return true +} + +// Equal asserts that two objects are equal. +// +// assert.Equal(t, 123, 123, "123 and 123 should be equal") +// +// Returns whether the assertion was successful (true) or not (false). +func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { + + if !ObjectsAreEqual(expected, actual) { + diff := diff(expected, actual) + return Fail(t, fmt.Sprintf("Not equal: %#v (expected)\n"+ + " != %#v (actual)%s", expected, actual, diff), msgAndArgs...) + } + + return true + +} + +// EqualValues asserts that two objects are equal or convertable to the same types +// and equal. +// +// assert.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal") +// +// Returns whether the assertion was successful (true) or not (false). +func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { + + if !ObjectsAreEqualValues(expected, actual) { + return Fail(t, fmt.Sprintf("Not equal: %#v (expected)\n"+ + " != %#v (actual)", expected, actual), msgAndArgs...) + } + + return true + +} + +// Exactly asserts that two objects are equal is value and type. +// +// assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal") +// +// Returns whether the assertion was successful (true) or not (false). +func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { + + aType := reflect.TypeOf(expected) + bType := reflect.TypeOf(actual) + + if aType != bType { + return Fail(t, fmt.Sprintf("Types expected to match exactly\n\r\t%v != %v", aType, bType), msgAndArgs...) + } + + return Equal(t, expected, actual, msgAndArgs...) + +} + +// NotNil asserts that the specified object is not nil. +// +// assert.NotNil(t, err, "err should be something") +// +// Returns whether the assertion was successful (true) or not (false). +func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { + if !isNil(object) { + return true + } + return Fail(t, "Expected value not to be nil.", msgAndArgs...) +} + +// isNil checks if a specified object is nil or not, without Failing. +func isNil(object interface{}) bool { + if object == nil { + return true + } + + value := reflect.ValueOf(object) + kind := value.Kind() + if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() { + return true + } + + return false +} + +// Nil asserts that the specified object is nil. +// +// assert.Nil(t, err, "err should be nothing") +// +// Returns whether the assertion was successful (true) or not (false). +func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { + if isNil(object) { + return true + } + return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...) +} + +var numericZeros = []interface{}{ + int(0), + int8(0), + int16(0), + int32(0), + int64(0), + uint(0), + uint8(0), + uint16(0), + uint32(0), + uint64(0), + float32(0), + float64(0), +} + +// isEmpty gets whether the specified object is considered empty or not. +func isEmpty(object interface{}) bool { + + if object == nil { + return true + } else if object == "" { + return true + } else if object == false { + return true + } + + for _, v := range numericZeros { + if object == v { + return true + } + } + + objValue := reflect.ValueOf(object) + + switch objValue.Kind() { + case reflect.Map: + fallthrough + case reflect.Slice, reflect.Chan: + { + return (objValue.Len() == 0) + } + case reflect.Struct: + switch object.(type) { + case time.Time: + return object.(time.Time).IsZero() + } + case reflect.Ptr: + { + if objValue.IsNil() { + return true + } + switch object.(type) { + case *time.Time: + return object.(*time.Time).IsZero() + default: + return false + } + } + } + return false +} + +// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// assert.Empty(t, obj) +// +// Returns whether the assertion was successful (true) or not (false). +func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { + + pass := isEmpty(object) + if !pass { + Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...) + } + + return pass + +} + +// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if assert.NotEmpty(t, obj) { +// assert.Equal(t, "two", obj[1]) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { + + pass := !isEmpty(object) + if !pass { + Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...) + } + + return pass + +} + +// getLen try to get length of object. +// return (false, 0) if impossible. +func getLen(x interface{}) (ok bool, length int) { + v := reflect.ValueOf(x) + defer func() { + if e := recover(); e != nil { + ok = false + } + }() + return true, v.Len() +} + +// Len asserts that the specified object has specific length. +// Len also fails if the object has a type that len() not accept. +// +// assert.Len(t, mySlice, 3, "The size of slice is not 3") +// +// Returns whether the assertion was successful (true) or not (false). +func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool { + ok, l := getLen(object) + if !ok { + return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...) + } + + if l != length { + return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) + } + return true +} + +// True asserts that the specified value is true. +// +// assert.True(t, myBool, "myBool should be true") +// +// Returns whether the assertion was successful (true) or not (false). +func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { + + if value != true { + return Fail(t, "Should be true", msgAndArgs...) + } + + return true + +} + +// False asserts that the specified value is false. +// +// assert.False(t, myBool, "myBool should be false") +// +// Returns whether the assertion was successful (true) or not (false). +func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { + + if value != false { + return Fail(t, "Should be false", msgAndArgs...) + } + + return true + +} + +// NotEqual asserts that the specified values are NOT equal. +// +// assert.NotEqual(t, obj1, obj2, "two objects shouldn't be equal") +// +// Returns whether the assertion was successful (true) or not (false). +func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { + + if ObjectsAreEqual(expected, actual) { + return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...) + } + + return true + +} + +// containsElement try loop over the list check if the list includes the element. +// return (false, false) if impossible. +// return (true, false) if element was not found. +// return (true, true) if element was found. +func includeElement(list interface{}, element interface{}) (ok, found bool) { + + listValue := reflect.ValueOf(list) + elementValue := reflect.ValueOf(element) + defer func() { + if e := recover(); e != nil { + ok = false + found = false + } + }() + + if reflect.TypeOf(list).Kind() == reflect.String { + return true, strings.Contains(listValue.String(), elementValue.String()) + } + + if reflect.TypeOf(list).Kind() == reflect.Map { + mapKeys := listValue.MapKeys() + for i := 0; i < len(mapKeys); i++ { + if ObjectsAreEqual(mapKeys[i].Interface(), element) { + return true, true + } + } + return true, false + } + + for i := 0; i < listValue.Len(); i++ { + if ObjectsAreEqual(listValue.Index(i).Interface(), element) { + return true, true + } + } + return true, false + +} + +// Contains asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'") +// assert.Contains(t, ["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") +// assert.Contains(t, {"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'") +// +// Returns whether the assertion was successful (true) or not (false). +func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { + + ok, found := includeElement(s, contains) + if !ok { + return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) + } + if !found { + return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...) + } + + return true + +} + +// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") +// assert.NotContains(t, ["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") +// assert.NotContains(t, {"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'") +// +// Returns whether the assertion was successful (true) or not (false). +func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { + + ok, found := includeElement(s, contains) + if !ok { + return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) + } + if found { + return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...) + } + + return true + +} + +// Condition uses a Comparison to assert a complex condition. +func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool { + result := comp() + if !result { + Fail(t, "Condition failed!", msgAndArgs...) + } + return result +} + +// PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics +// methods, and represents a simple func that takes no arguments, and returns nothing. +type PanicTestFunc func() + +// didPanic returns true if the function passed to it panics. Otherwise, it returns false. +func didPanic(f PanicTestFunc) (bool, interface{}) { + + didPanic := false + var message interface{} + func() { + + defer func() { + if message = recover(); message != nil { + didPanic = true + } + }() + + // call the target function + f() + + }() + + return didPanic, message + +} + +// Panics asserts that the code inside the specified PanicTestFunc panics. +// +// assert.Panics(t, func(){ +// GoCrazy() +// }, "Calling GoCrazy() should panic") +// +// Returns whether the assertion was successful (true) or not (false). +func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { + + if funcDidPanic, panicValue := didPanic(f); !funcDidPanic { + return Fail(t, fmt.Sprintf("func %#v should panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) + } + + return true +} + +// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// assert.NotPanics(t, func(){ +// RemainCalm() +// }, "Calling RemainCalm() should NOT panic") +// +// Returns whether the assertion was successful (true) or not (false). +func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { + + if funcDidPanic, panicValue := didPanic(f); funcDidPanic { + return Fail(t, fmt.Sprintf("func %#v should not panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) + } + + return true +} + +// WithinDuration asserts that the two times are within duration delta of each other. +// +// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") +// +// Returns whether the assertion was successful (true) or not (false). +func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { + + dt := expected.Sub(actual) + if dt < -delta || dt > delta { + return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) + } + + return true +} + +func toFloat(x interface{}) (float64, bool) { + var xf float64 + xok := true + + switch xn := x.(type) { + case uint8: + xf = float64(xn) + case uint16: + xf = float64(xn) + case uint32: + xf = float64(xn) + case uint64: + xf = float64(xn) + case int: + xf = float64(xn) + case int8: + xf = float64(xn) + case int16: + xf = float64(xn) + case int32: + xf = float64(xn) + case int64: + xf = float64(xn) + case float32: + xf = float64(xn) + case float64: + xf = float64(xn) + default: + xok = false + } + + return xf, xok +} + +// InDelta asserts that the two numerals are within delta of each other. +// +// assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) +// +// Returns whether the assertion was successful (true) or not (false). +func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { + + af, aok := toFloat(expected) + bf, bok := toFloat(actual) + + if !aok || !bok { + return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...) + } + + if math.IsNaN(af) { + return Fail(t, fmt.Sprintf("Actual must not be NaN"), msgAndArgs...) + } + + if math.IsNaN(bf) { + return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...) + } + + dt := af - bf + if dt < -delta || dt > delta { + return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) + } + + return true +} + +// InDeltaSlice is the same as InDelta, except it compares two slices. +func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { + if expected == nil || actual == nil || + reflect.TypeOf(actual).Kind() != reflect.Slice || + reflect.TypeOf(expected).Kind() != reflect.Slice { + return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) + } + + actualSlice := reflect.ValueOf(actual) + expectedSlice := reflect.ValueOf(expected) + + for i := 0; i < actualSlice.Len(); i++ { + result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta) + if !result { + return result + } + } + + return true +} + +func calcRelativeError(expected, actual interface{}) (float64, error) { + af, aok := toFloat(expected) + if !aok { + return 0, fmt.Errorf("expected value %q cannot be converted to float", expected) + } + if af == 0 { + return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error") + } + bf, bok := toFloat(actual) + if !bok { + return 0, fmt.Errorf("expected value %q cannot be converted to float", actual) + } + + return math.Abs(af-bf) / math.Abs(af), nil +} + +// InEpsilon asserts that expected and actual have a relative error less than epsilon +// +// Returns whether the assertion was successful (true) or not (false). +func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { + actualEpsilon, err := calcRelativeError(expected, actual) + if err != nil { + return Fail(t, err.Error(), msgAndArgs...) + } + if actualEpsilon > epsilon { + return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+ + " < %#v (actual)", actualEpsilon, epsilon), msgAndArgs...) + } + + return true +} + +// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. +func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { + if expected == nil || actual == nil || + reflect.TypeOf(actual).Kind() != reflect.Slice || + reflect.TypeOf(expected).Kind() != reflect.Slice { + return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) + } + + actualSlice := reflect.ValueOf(actual) + expectedSlice := reflect.ValueOf(expected) + + for i := 0; i < actualSlice.Len(); i++ { + result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon) + if !result { + return result + } + } + + return true +} + +/* + Errors +*/ + +// NoError asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if assert.NoError(t, err) { +// assert.Equal(t, actualObj, expectedObj) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool { + if isNil(err) { + return true + } + + return Fail(t, fmt.Sprintf("Received unexpected error %q", err), msgAndArgs...) +} + +// Error asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if assert.Error(t, err, "An error was expected") { +// assert.Equal(t, err, expectedError) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func Error(t TestingT, err error, msgAndArgs ...interface{}) bool { + + message := messageFromMsgAndArgs(msgAndArgs...) + return NotNil(t, err, "An error is expected but got nil. %s", message) + +} + +// EqualError asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// if assert.Error(t, err, "An error was expected") { +// assert.Equal(t, err, expectedError) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool { + + message := messageFromMsgAndArgs(msgAndArgs...) + if !NotNil(t, theError, "An error is expected but got nil. %s", message) { + return false + } + s := "An error with value \"%s\" is expected but got \"%s\". %s" + return Equal(t, errString, theError.Error(), + s, errString, theError.Error(), message) +} + +// matchRegexp return true if a specified regexp matches a string. +func matchRegexp(rx interface{}, str interface{}) bool { + + var r *regexp.Regexp + if rr, ok := rx.(*regexp.Regexp); ok { + r = rr + } else { + r = regexp.MustCompile(fmt.Sprint(rx)) + } + + return (r.FindStringIndex(fmt.Sprint(str)) != nil) + +} + +// Regexp asserts that a specified regexp matches a string. +// +// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") +// assert.Regexp(t, "start...$", "it's not starting") +// +// Returns whether the assertion was successful (true) or not (false). +func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { + + match := matchRegexp(rx, str) + + if !match { + Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...) + } + + return match +} + +// NotRegexp asserts that a specified regexp does not match a string. +// +// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") +// assert.NotRegexp(t, "^start", "it's not starting") +// +// Returns whether the assertion was successful (true) or not (false). +func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { + match := matchRegexp(rx, str) + + if match { + Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...) + } + + return !match + +} + +// Zero asserts that i is the zero value for its type and returns the truth. +func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { + if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { + return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...) + } + return true +} + +// NotZero asserts that i is not the zero value for its type and returns the truth. +func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { + if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { + return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...) + } + return true +} + +// JSONEq asserts that two JSON strings are equivalent. +// +// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) +// +// Returns whether the assertion was successful (true) or not (false). +func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool { + var expectedJSONAsInterface, actualJSONAsInterface interface{} + + if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil { + return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...) + } + + if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil { + return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...) + } + + return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...) +} + +func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) { + t := reflect.TypeOf(v) + k := t.Kind() + + if k == reflect.Ptr { + t = t.Elem() + k = t.Kind() + } + return t, k +} + +// diff returns a diff of both values as long as both are of the same type and +// are a struct, map, slice or array. Otherwise it returns an empty string. +func diff(expected interface{}, actual interface{}) string { + if expected == nil || actual == nil { + return "" + } + + et, ek := typeAndKind(expected) + at, _ := typeAndKind(actual) + + if et != at { + return "" + } + + if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array { + return "" + } + + spew.Config.SortKeys = true + e := spew.Sdump(expected) + a := spew.Sdump(actual) + + diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ + A: difflib.SplitLines(e), + B: difflib.SplitLines(a), + FromFile: "Expected", + FromDate: "", + ToFile: "Actual", + ToDate: "", + Context: 1, + }) + + return "\n\nDiff:\n" + diff +} diff --git a/vendor/github.com/stretchr/testify/assert/assertions_test.go b/vendor/github.com/stretchr/testify/assert/assertions_test.go new file mode 100644 index 00000000..15a04b8f --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/assertions_test.go @@ -0,0 +1,1122 @@ +package assert + +import ( + "errors" + "io" + "math" + "os" + "reflect" + "regexp" + "testing" + "time" +) + +var ( + i interface{} + zeros = []interface{}{ + false, + byte(0), + complex64(0), + complex128(0), + float32(0), + float64(0), + int(0), + int8(0), + int16(0), + int32(0), + int64(0), + rune(0), + uint(0), + uint8(0), + uint16(0), + uint32(0), + uint64(0), + uintptr(0), + "", + [0]interface{}{}, + []interface{}(nil), + struct{ x int }{}, + (*interface{})(nil), + (func())(nil), + nil, + interface{}(nil), + map[interface{}]interface{}(nil), + (chan interface{})(nil), + (<-chan interface{})(nil), + (chan<- interface{})(nil), + } + nonZeros = []interface{}{ + true, + byte(1), + complex64(1), + complex128(1), + float32(1), + float64(1), + int(1), + int8(1), + int16(1), + int32(1), + int64(1), + rune(1), + uint(1), + uint8(1), + uint16(1), + uint32(1), + uint64(1), + uintptr(1), + "s", + [1]interface{}{1}, + []interface{}{}, + struct{ x int }{1}, + (*interface{})(&i), + (func())(func() {}), + interface{}(1), + map[interface{}]interface{}{}, + (chan interface{})(make(chan interface{})), + (<-chan interface{})(make(chan interface{})), + (chan<- interface{})(make(chan interface{})), + } +) + +// AssertionTesterInterface defines an interface to be used for testing assertion methods +type AssertionTesterInterface interface { + TestMethod() +} + +// AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface +type AssertionTesterConformingObject struct { +} + +func (a *AssertionTesterConformingObject) TestMethod() { +} + +// AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface +type AssertionTesterNonConformingObject struct { +} + +func TestObjectsAreEqual(t *testing.T) { + + if !ObjectsAreEqual("Hello World", "Hello World") { + t.Error("objectsAreEqual should return true") + } + if !ObjectsAreEqual(123, 123) { + t.Error("objectsAreEqual should return true") + } + if !ObjectsAreEqual(123.5, 123.5) { + t.Error("objectsAreEqual should return true") + } + if !ObjectsAreEqual([]byte("Hello World"), []byte("Hello World")) { + t.Error("objectsAreEqual should return true") + } + if !ObjectsAreEqual(nil, nil) { + t.Error("objectsAreEqual should return true") + } + if ObjectsAreEqual(map[int]int{5: 10}, map[int]int{10: 20}) { + t.Error("objectsAreEqual should return false") + } + if ObjectsAreEqual('x', "x") { + t.Error("objectsAreEqual should return false") + } + if ObjectsAreEqual("x", 'x') { + t.Error("objectsAreEqual should return false") + } + if ObjectsAreEqual(0, 0.1) { + t.Error("objectsAreEqual should return false") + } + if ObjectsAreEqual(0.1, 0) { + t.Error("objectsAreEqual should return false") + } + if ObjectsAreEqual(uint32(10), int32(10)) { + t.Error("objectsAreEqual should return false") + } + if !ObjectsAreEqualValues(uint32(10), int32(10)) { + t.Error("ObjectsAreEqualValues should return true") + } + if ObjectsAreEqualValues(0, nil) { + t.Fail() + } + if ObjectsAreEqualValues(nil, 0) { + t.Fail() + } + +} + +func TestImplements(t *testing.T) { + + mockT := new(testing.T) + + if !Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) { + t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface") + } + if Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) { + t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface") + } + +} + +func TestIsType(t *testing.T) { + + mockT := new(testing.T) + + if !IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { + t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject") + } + if IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) { + t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject") + } + +} + +func TestEqual(t *testing.T) { + + mockT := new(testing.T) + + if !Equal(mockT, "Hello World", "Hello World") { + t.Error("Equal should return true") + } + if !Equal(mockT, 123, 123) { + t.Error("Equal should return true") + } + if !Equal(mockT, 123.5, 123.5) { + t.Error("Equal should return true") + } + if !Equal(mockT, []byte("Hello World"), []byte("Hello World")) { + t.Error("Equal should return true") + } + if !Equal(mockT, nil, nil) { + t.Error("Equal should return true") + } + if !Equal(mockT, int32(123), int32(123)) { + t.Error("Equal should return true") + } + if !Equal(mockT, uint64(123), uint64(123)) { + t.Error("Equal should return true") + } + +} + +func TestNotNil(t *testing.T) { + + mockT := new(testing.T) + + if !NotNil(mockT, new(AssertionTesterConformingObject)) { + t.Error("NotNil should return true: object is not nil") + } + if NotNil(mockT, nil) { + t.Error("NotNil should return false: object is nil") + } + if NotNil(mockT, (*struct{})(nil)) { + t.Error("NotNil should return false: object is (*struct{})(nil)") + } + +} + +func TestNil(t *testing.T) { + + mockT := new(testing.T) + + if !Nil(mockT, nil) { + t.Error("Nil should return true: object is nil") + } + if !Nil(mockT, (*struct{})(nil)) { + t.Error("Nil should return true: object is (*struct{})(nil)") + } + if Nil(mockT, new(AssertionTesterConformingObject)) { + t.Error("Nil should return false: object is not nil") + } + +} + +func TestTrue(t *testing.T) { + + mockT := new(testing.T) + + if !True(mockT, true) { + t.Error("True should return true") + } + if True(mockT, false) { + t.Error("True should return false") + } + +} + +func TestFalse(t *testing.T) { + + mockT := new(testing.T) + + if !False(mockT, false) { + t.Error("False should return true") + } + if False(mockT, true) { + t.Error("False should return false") + } + +} + +func TestExactly(t *testing.T) { + + mockT := new(testing.T) + + a := float32(1) + b := float64(1) + c := float32(1) + d := float32(2) + + if Exactly(mockT, a, b) { + t.Error("Exactly should return false") + } + if Exactly(mockT, a, d) { + t.Error("Exactly should return false") + } + if !Exactly(mockT, a, c) { + t.Error("Exactly should return true") + } + + if Exactly(mockT, nil, a) { + t.Error("Exactly should return false") + } + if Exactly(mockT, a, nil) { + t.Error("Exactly should return false") + } + +} + +func TestNotEqual(t *testing.T) { + + mockT := new(testing.T) + + if !NotEqual(mockT, "Hello World", "Hello World!") { + t.Error("NotEqual should return true") + } + if !NotEqual(mockT, 123, 1234) { + t.Error("NotEqual should return true") + } + if !NotEqual(mockT, 123.5, 123.55) { + t.Error("NotEqual should return true") + } + if !NotEqual(mockT, []byte("Hello World"), []byte("Hello World!")) { + t.Error("NotEqual should return true") + } + if !NotEqual(mockT, nil, new(AssertionTesterConformingObject)) { + t.Error("NotEqual should return true") + } + funcA := func() int { return 23 } + funcB := func() int { return 42 } + if !NotEqual(mockT, funcA, funcB) { + t.Error("NotEqual should return true") + } + + if NotEqual(mockT, "Hello World", "Hello World") { + t.Error("NotEqual should return false") + } + if NotEqual(mockT, 123, 123) { + t.Error("NotEqual should return false") + } + if NotEqual(mockT, 123.5, 123.5) { + t.Error("NotEqual should return false") + } + if NotEqual(mockT, []byte("Hello World"), []byte("Hello World")) { + t.Error("NotEqual should return false") + } + if NotEqual(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { + t.Error("NotEqual should return false") + } +} + +type A struct { + Name, Value string +} + +func TestContains(t *testing.T) { + + mockT := new(testing.T) + list := []string{"Foo", "Bar"} + complexList := []*A{ + {"b", "c"}, + {"d", "e"}, + {"g", "h"}, + {"j", "k"}, + } + simpleMap := map[interface{}]interface{}{"Foo": "Bar"} + + if !Contains(mockT, "Hello World", "Hello") { + t.Error("Contains should return true: \"Hello World\" contains \"Hello\"") + } + if Contains(mockT, "Hello World", "Salut") { + t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"") + } + + if !Contains(mockT, list, "Bar") { + t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Bar\"") + } + if Contains(mockT, list, "Salut") { + t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"") + } + if !Contains(mockT, complexList, &A{"g", "h"}) { + t.Error("Contains should return true: complexList contains {\"g\", \"h\"}") + } + if Contains(mockT, complexList, &A{"g", "e"}) { + t.Error("Contains should return false: complexList contains {\"g\", \"e\"}") + } + if Contains(mockT, complexList, &A{"g", "e"}) { + t.Error("Contains should return false: complexList contains {\"g\", \"e\"}") + } + if !Contains(mockT, simpleMap, "Foo") { + t.Error("Contains should return true: \"{\"Foo\": \"Bar\"}\" contains \"Foo\"") + } + if Contains(mockT, simpleMap, "Bar") { + t.Error("Contains should return false: \"{\"Foo\": \"Bar\"}\" does not contains \"Bar\"") + } +} + +func TestNotContains(t *testing.T) { + + mockT := new(testing.T) + list := []string{"Foo", "Bar"} + simpleMap := map[interface{}]interface{}{"Foo": "Bar"} + + if !NotContains(mockT, "Hello World", "Hello!") { + t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"") + } + if NotContains(mockT, "Hello World", "Hello") { + t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"") + } + + if !NotContains(mockT, list, "Foo!") { + t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"") + } + if NotContains(mockT, list, "Foo") { + t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") + } + if NotContains(mockT, simpleMap, "Foo") { + t.Error("Contains should return true: \"{\"Foo\": \"Bar\"}\" contains \"Foo\"") + } + if !NotContains(mockT, simpleMap, "Bar") { + t.Error("Contains should return false: \"{\"Foo\": \"Bar\"}\" does not contains \"Bar\"") + } +} + +func Test_includeElement(t *testing.T) { + + list1 := []string{"Foo", "Bar"} + list2 := []int{1, 2} + simpleMap := map[interface{}]interface{}{"Foo": "Bar"} + + ok, found := includeElement("Hello World", "World") + True(t, ok) + True(t, found) + + ok, found = includeElement(list1, "Foo") + True(t, ok) + True(t, found) + + ok, found = includeElement(list1, "Bar") + True(t, ok) + True(t, found) + + ok, found = includeElement(list2, 1) + True(t, ok) + True(t, found) + + ok, found = includeElement(list2, 2) + True(t, ok) + True(t, found) + + ok, found = includeElement(list1, "Foo!") + True(t, ok) + False(t, found) + + ok, found = includeElement(list2, 3) + True(t, ok) + False(t, found) + + ok, found = includeElement(list2, "1") + True(t, ok) + False(t, found) + + ok, found = includeElement(simpleMap, "Foo") + True(t, ok) + True(t, found) + + ok, found = includeElement(simpleMap, "Bar") + True(t, ok) + False(t, found) + + ok, found = includeElement(1433, "1") + False(t, ok) + False(t, found) +} + +func TestCondition(t *testing.T) { + mockT := new(testing.T) + + if !Condition(mockT, func() bool { return true }, "Truth") { + t.Error("Condition should return true") + } + + if Condition(mockT, func() bool { return false }, "Lie") { + t.Error("Condition should return false") + } + +} + +func TestDidPanic(t *testing.T) { + + if funcDidPanic, _ := didPanic(func() { + panic("Panic!") + }); !funcDidPanic { + t.Error("didPanic should return true") + } + + if funcDidPanic, _ := didPanic(func() { + }); funcDidPanic { + t.Error("didPanic should return false") + } + +} + +func TestPanics(t *testing.T) { + + mockT := new(testing.T) + + if !Panics(mockT, func() { + panic("Panic!") + }) { + t.Error("Panics should return true") + } + + if Panics(mockT, func() { + }) { + t.Error("Panics should return false") + } + +} + +func TestNotPanics(t *testing.T) { + + mockT := new(testing.T) + + if !NotPanics(mockT, func() { + }) { + t.Error("NotPanics should return true") + } + + if NotPanics(mockT, func() { + panic("Panic!") + }) { + t.Error("NotPanics should return false") + } + +} + +func TestNoError(t *testing.T) { + + mockT := new(testing.T) + + // start with a nil error + var err error + + True(t, NoError(mockT, err), "NoError should return True for nil arg") + + // now set an error + err = errors.New("some error") + + False(t, NoError(mockT, err), "NoError with error should return False") + +} + +func TestError(t *testing.T) { + + mockT := new(testing.T) + + // start with a nil error + var err error + + False(t, Error(mockT, err), "Error should return False for nil arg") + + // now set an error + err = errors.New("some error") + + True(t, Error(mockT, err), "Error with error should return True") + +} + +func TestEqualError(t *testing.T) { + mockT := new(testing.T) + + // start with a nil error + var err error + False(t, EqualError(mockT, err, ""), + "EqualError should return false for nil arg") + + // now set an error + err = errors.New("some error") + False(t, EqualError(mockT, err, "Not some error"), + "EqualError should return false for different error string") + True(t, EqualError(mockT, err, "some error"), + "EqualError should return true") +} + +func Test_isEmpty(t *testing.T) { + + chWithValue := make(chan struct{}, 1) + chWithValue <- struct{}{} + + True(t, isEmpty("")) + True(t, isEmpty(nil)) + True(t, isEmpty([]string{})) + True(t, isEmpty(0)) + True(t, isEmpty(int32(0))) + True(t, isEmpty(int64(0))) + True(t, isEmpty(false)) + True(t, isEmpty(map[string]string{})) + True(t, isEmpty(new(time.Time))) + True(t, isEmpty(time.Time{})) + True(t, isEmpty(make(chan struct{}))) + False(t, isEmpty("something")) + False(t, isEmpty(errors.New("something"))) + False(t, isEmpty([]string{"something"})) + False(t, isEmpty(1)) + False(t, isEmpty(true)) + False(t, isEmpty(map[string]string{"Hello": "World"})) + False(t, isEmpty(chWithValue)) + +} + +func TestEmpty(t *testing.T) { + + mockT := new(testing.T) + chWithValue := make(chan struct{}, 1) + chWithValue <- struct{}{} + var tiP *time.Time + var tiNP time.Time + var s *string + var f *os.File + + True(t, Empty(mockT, ""), "Empty string is empty") + True(t, Empty(mockT, nil), "Nil is empty") + True(t, Empty(mockT, []string{}), "Empty string array is empty") + True(t, Empty(mockT, 0), "Zero int value is empty") + True(t, Empty(mockT, false), "False value is empty") + True(t, Empty(mockT, make(chan struct{})), "Channel without values is empty") + True(t, Empty(mockT, s), "Nil string pointer is empty") + True(t, Empty(mockT, f), "Nil os.File pointer is empty") + True(t, Empty(mockT, tiP), "Nil time.Time pointer is empty") + True(t, Empty(mockT, tiNP), "time.Time is empty") + + False(t, Empty(mockT, "something"), "Non Empty string is not empty") + False(t, Empty(mockT, errors.New("something")), "Non nil object is not empty") + False(t, Empty(mockT, []string{"something"}), "Non empty string array is not empty") + False(t, Empty(mockT, 1), "Non-zero int value is not empty") + False(t, Empty(mockT, true), "True value is not empty") + False(t, Empty(mockT, chWithValue), "Channel with values is not empty") +} + +func TestNotEmpty(t *testing.T) { + + mockT := new(testing.T) + chWithValue := make(chan struct{}, 1) + chWithValue <- struct{}{} + + False(t, NotEmpty(mockT, ""), "Empty string is empty") + False(t, NotEmpty(mockT, nil), "Nil is empty") + False(t, NotEmpty(mockT, []string{}), "Empty string array is empty") + False(t, NotEmpty(mockT, 0), "Zero int value is empty") + False(t, NotEmpty(mockT, false), "False value is empty") + False(t, NotEmpty(mockT, make(chan struct{})), "Channel without values is empty") + + True(t, NotEmpty(mockT, "something"), "Non Empty string is not empty") + True(t, NotEmpty(mockT, errors.New("something")), "Non nil object is not empty") + True(t, NotEmpty(mockT, []string{"something"}), "Non empty string array is not empty") + True(t, NotEmpty(mockT, 1), "Non-zero int value is not empty") + True(t, NotEmpty(mockT, true), "True value is not empty") + True(t, NotEmpty(mockT, chWithValue), "Channel with values is not empty") +} + +func Test_getLen(t *testing.T) { + falseCases := []interface{}{ + nil, + 0, + true, + false, + 'A', + struct{}{}, + } + for _, v := range falseCases { + ok, l := getLen(v) + False(t, ok, "Expected getLen fail to get length of %#v", v) + Equal(t, 0, l, "getLen should return 0 for %#v", v) + } + + ch := make(chan int, 5) + ch <- 1 + ch <- 2 + ch <- 3 + trueCases := []struct { + v interface{} + l int + }{ + {[]int{1, 2, 3}, 3}, + {[...]int{1, 2, 3}, 3}, + {"ABC", 3}, + {map[int]int{1: 2, 2: 4, 3: 6}, 3}, + {ch, 3}, + + {[]int{}, 0}, + {map[int]int{}, 0}, + {make(chan int), 0}, + + {[]int(nil), 0}, + {map[int]int(nil), 0}, + {(chan int)(nil), 0}, + } + + for _, c := range trueCases { + ok, l := getLen(c.v) + True(t, ok, "Expected getLen success to get length of %#v", c.v) + Equal(t, c.l, l) + } +} + +func TestLen(t *testing.T) { + mockT := new(testing.T) + + False(t, Len(mockT, nil, 0), "nil does not have length") + False(t, Len(mockT, 0, 0), "int does not have length") + False(t, Len(mockT, true, 0), "true does not have length") + False(t, Len(mockT, false, 0), "false does not have length") + False(t, Len(mockT, 'A', 0), "Rune does not have length") + False(t, Len(mockT, struct{}{}, 0), "Struct does not have length") + + ch := make(chan int, 5) + ch <- 1 + ch <- 2 + ch <- 3 + + cases := []struct { + v interface{} + l int + }{ + {[]int{1, 2, 3}, 3}, + {[...]int{1, 2, 3}, 3}, + {"ABC", 3}, + {map[int]int{1: 2, 2: 4, 3: 6}, 3}, + {ch, 3}, + + {[]int{}, 0}, + {map[int]int{}, 0}, + {make(chan int), 0}, + + {[]int(nil), 0}, + {map[int]int(nil), 0}, + {(chan int)(nil), 0}, + } + + for _, c := range cases { + True(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l) + } + + cases = []struct { + v interface{} + l int + }{ + {[]int{1, 2, 3}, 4}, + {[...]int{1, 2, 3}, 2}, + {"ABC", 2}, + {map[int]int{1: 2, 2: 4, 3: 6}, 4}, + {ch, 2}, + + {[]int{}, 1}, + {map[int]int{}, 1}, + {make(chan int), 1}, + + {[]int(nil), 1}, + {map[int]int(nil), 1}, + {(chan int)(nil), 1}, + } + + for _, c := range cases { + False(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l) + } +} + +func TestWithinDuration(t *testing.T) { + + mockT := new(testing.T) + a := time.Now() + b := a.Add(10 * time.Second) + + True(t, WithinDuration(mockT, a, b, 10*time.Second), "A 10s difference is within a 10s time difference") + True(t, WithinDuration(mockT, b, a, 10*time.Second), "A 10s difference is within a 10s time difference") + + False(t, WithinDuration(mockT, a, b, 9*time.Second), "A 10s difference is not within a 9s time difference") + False(t, WithinDuration(mockT, b, a, 9*time.Second), "A 10s difference is not within a 9s time difference") + + False(t, WithinDuration(mockT, a, b, -9*time.Second), "A 10s difference is not within a 9s time difference") + False(t, WithinDuration(mockT, b, a, -9*time.Second), "A 10s difference is not within a 9s time difference") + + False(t, WithinDuration(mockT, a, b, -11*time.Second), "A 10s difference is not within a 9s time difference") + False(t, WithinDuration(mockT, b, a, -11*time.Second), "A 10s difference is not within a 9s time difference") +} + +func TestInDelta(t *testing.T) { + mockT := new(testing.T) + + True(t, InDelta(mockT, 1.001, 1, 0.01), "|1.001 - 1| <= 0.01") + True(t, InDelta(mockT, 1, 1.001, 0.01), "|1 - 1.001| <= 0.01") + True(t, InDelta(mockT, 1, 2, 1), "|1 - 2| <= 1") + False(t, InDelta(mockT, 1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail") + False(t, InDelta(mockT, 2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail") + False(t, InDelta(mockT, "", nil, 1), "Expected non numerals to fail") + False(t, InDelta(mockT, 42, math.NaN(), 0.01), "Expected NaN for actual to fail") + False(t, InDelta(mockT, math.NaN(), 42, 0.01), "Expected NaN for expected to fail") + + cases := []struct { + a, b interface{} + delta float64 + }{ + {uint8(2), uint8(1), 1}, + {uint16(2), uint16(1), 1}, + {uint32(2), uint32(1), 1}, + {uint64(2), uint64(1), 1}, + + {int(2), int(1), 1}, + {int8(2), int8(1), 1}, + {int16(2), int16(1), 1}, + {int32(2), int32(1), 1}, + {int64(2), int64(1), 1}, + + {float32(2), float32(1), 1}, + {float64(2), float64(1), 1}, + } + + for _, tc := range cases { + True(t, InDelta(mockT, tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta) + } +} + +func TestInDeltaSlice(t *testing.T) { + mockT := new(testing.T) + + True(t, InDeltaSlice(mockT, + []float64{1.001, 0.999}, + []float64{1, 1}, + 0.1), "{1.001, 0.009} is element-wise close to {1, 1} in delta=0.1") + + True(t, InDeltaSlice(mockT, + []float64{1, 2}, + []float64{0, 3}, + 1), "{1, 2} is element-wise close to {0, 3} in delta=1") + + False(t, InDeltaSlice(mockT, + []float64{1, 2}, + []float64{0, 3}, + 0.1), "{1, 2} is not element-wise close to {0, 3} in delta=0.1") + + False(t, InDeltaSlice(mockT, "", nil, 1), "Expected non numeral slices to fail") +} + +func TestInEpsilon(t *testing.T) { + mockT := new(testing.T) + + cases := []struct { + a, b interface{} + epsilon float64 + }{ + {uint8(2), uint16(2), .001}, + {2.1, 2.2, 0.1}, + {2.2, 2.1, 0.1}, + {-2.1, -2.2, 0.1}, + {-2.2, -2.1, 0.1}, + {uint64(100), uint8(101), 0.01}, + {0.1, -0.1, 2}, + {0.1, 0, 2}, + } + + for _, tc := range cases { + True(t, InEpsilon(t, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon), "test: %q", tc) + } + + cases = []struct { + a, b interface{} + epsilon float64 + }{ + {uint8(2), int16(-2), .001}, + {uint64(100), uint8(102), 0.01}, + {2.1, 2.2, 0.001}, + {2.2, 2.1, 0.001}, + {2.1, -2.2, 1}, + {2.1, "bla-bla", 0}, + {0.1, -0.1, 1.99}, + {0, 0.1, 2}, // expected must be different to zero + } + + for _, tc := range cases { + False(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) + } + +} + +func TestInEpsilonSlice(t *testing.T) { + mockT := new(testing.T) + + True(t, InEpsilonSlice(mockT, + []float64{2.2, 2.0}, + []float64{2.1, 2.1}, + 0.06), "{2.2, 2.0} is element-wise close to {2.1, 2.1} in espilon=0.06") + + False(t, InEpsilonSlice(mockT, + []float64{2.2, 2.0}, + []float64{2.1, 2.1}, + 0.04), "{2.2, 2.0} is not element-wise close to {2.1, 2.1} in espilon=0.04") + + False(t, InEpsilonSlice(mockT, "", nil, 1), "Expected non numeral slices to fail") +} + +func TestRegexp(t *testing.T) { + mockT := new(testing.T) + + cases := []struct { + rx, str string + }{ + {"^start", "start of the line"}, + {"end$", "in the end"}, + {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"}, + } + + for _, tc := range cases { + True(t, Regexp(mockT, tc.rx, tc.str)) + True(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str)) + False(t, NotRegexp(mockT, tc.rx, tc.str)) + False(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str)) + } + + cases = []struct { + rx, str string + }{ + {"^asdfastart", "Not the start of the line"}, + {"end$", "in the end."}, + {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"}, + } + + for _, tc := range cases { + False(t, Regexp(mockT, tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str) + False(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str)) + True(t, NotRegexp(mockT, tc.rx, tc.str)) + True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str)) + } +} + +func testAutogeneratedFunction() { + defer func() { + if err := recover(); err == nil { + panic("did not panic") + } + CallerInfo() + }() + t := struct { + io.Closer + }{} + var c io.Closer + c = t + c.Close() +} + +func TestCallerInfoWithAutogeneratedFunctions(t *testing.T) { + NotPanics(t, func() { + testAutogeneratedFunction() + }) +} + +func TestZero(t *testing.T) { + mockT := new(testing.T) + + for _, test := range zeros { + True(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) + } + + for _, test := range nonZeros { + False(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) + } +} + +func TestNotZero(t *testing.T) { + mockT := new(testing.T) + + for _, test := range zeros { + False(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) + } + + for _, test := range nonZeros { + True(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) + } +} + +func TestJSONEq_EqualSONString(t *testing.T) { + mockT := new(testing.T) + True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`)) +} + +func TestJSONEq_EquivalentButNotEqual(t *testing.T) { + mockT := new(testing.T) + True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)) +} + +func TestJSONEq_HashOfArraysAndHashes(t *testing.T) { + mockT := new(testing.T) + True(t, JSONEq(mockT, "{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}", + "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}")) +} + +func TestJSONEq_Array(t *testing.T) { + mockT := new(testing.T) + True(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`)) +} + +func TestJSONEq_HashAndArrayNotEquivalent(t *testing.T) { + mockT := new(testing.T) + False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`)) +} + +func TestJSONEq_HashesNotEquivalent(t *testing.T) { + mockT := new(testing.T) + False(t, JSONEq(mockT, `{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)) +} + +func TestJSONEq_ActualIsNotJSON(t *testing.T) { + mockT := new(testing.T) + False(t, JSONEq(mockT, `{"foo": "bar"}`, "Not JSON")) +} + +func TestJSONEq_ExpectedIsNotJSON(t *testing.T) { + mockT := new(testing.T) + False(t, JSONEq(mockT, "Not JSON", `{"foo": "bar", "hello": "world"}`)) +} + +func TestJSONEq_ExpectedAndActualNotJSON(t *testing.T) { + mockT := new(testing.T) + False(t, JSONEq(mockT, "Not JSON", "Not JSON")) +} + +func TestJSONEq_ArraysOfDifferentOrder(t *testing.T) { + mockT := new(testing.T) + False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`)) +} + +func TestDiff(t *testing.T) { + expected := ` + +Diff: +--- Expected ++++ Actual +@@ -1,3 +1,3 @@ + (struct { foo string }) { +- foo: (string) (len=5) "hello" ++ foo: (string) (len=3) "bar" + } +` + actual := diff( + struct{ foo string }{"hello"}, + struct{ foo string }{"bar"}, + ) + Equal(t, expected, actual) + + expected = ` + +Diff: +--- Expected ++++ Actual +@@ -2,5 +2,5 @@ + (int) 1, +- (int) 2, + (int) 3, +- (int) 4 ++ (int) 5, ++ (int) 7 + } +` + actual = diff( + []int{1, 2, 3, 4}, + []int{1, 3, 5, 7}, + ) + Equal(t, expected, actual) + + expected = ` + +Diff: +--- Expected ++++ Actual +@@ -2,4 +2,4 @@ + (int) 1, +- (int) 2, +- (int) 3 ++ (int) 3, ++ (int) 5 + } +` + actual = diff( + []int{1, 2, 3, 4}[0:3], + []int{1, 3, 5, 7}[0:3], + ) + Equal(t, expected, actual) + + expected = ` + +Diff: +--- Expected ++++ Actual +@@ -1,6 +1,6 @@ + (map[string]int) (len=4) { +- (string) (len=4) "four": (int) 4, ++ (string) (len=4) "five": (int) 5, + (string) (len=3) "one": (int) 1, +- (string) (len=5) "three": (int) 3, +- (string) (len=3) "two": (int) 2 ++ (string) (len=5) "seven": (int) 7, ++ (string) (len=5) "three": (int) 3 + } +` + + actual = diff( + map[string]int{"one": 1, "two": 2, "three": 3, "four": 4}, + map[string]int{"one": 1, "three": 3, "five": 5, "seven": 7}, + ) + Equal(t, expected, actual) +} + +func TestDiffEmptyCases(t *testing.T) { + Equal(t, "", diff(nil, nil)) + Equal(t, "", diff(struct{ foo string }{}, nil)) + Equal(t, "", diff(nil, struct{ foo string }{})) + Equal(t, "", diff(1, 2)) + Equal(t, "", diff(1, 2)) + Equal(t, "", diff([]int{1}, []bool{true})) +} + +type mockTestingT struct { +} + +func (m *mockTestingT) Errorf(format string, args ...interface{}) {} + +func TestFailNowWithPlainTestingT(t *testing.T) { + mockT := &mockTestingT{} + + Panics(t, func() { + FailNow(mockT, "failed") + }, "should panic since mockT is missing FailNow()") +} + +type mockFailNowTestingT struct { +} + +func (m *mockFailNowTestingT) Errorf(format string, args ...interface{}) {} + +func (m *mockFailNowTestingT) FailNow() {} + +func TestFailNowWithFullTestingT(t *testing.T) { + mockT := &mockFailNowTestingT{} + + NotPanics(t, func() { + FailNow(mockT, "failed") + }, "should call mockT.FailNow() rather than panicking") +} diff --git a/vendor/github.com/stretchr/testify/assert/doc.go b/vendor/github.com/stretchr/testify/assert/doc.go new file mode 100644 index 00000000..c9dccc4d --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/doc.go @@ -0,0 +1,45 @@ +// Package assert provides a set of comprehensive testing tools for use with the normal Go testing system. +// +// Example Usage +// +// The following is a complete example using assert in a standard test function: +// import ( +// "testing" +// "github.com/stretchr/testify/assert" +// ) +// +// func TestSomething(t *testing.T) { +// +// var a string = "Hello" +// var b string = "Hello" +// +// assert.Equal(t, a, b, "The two words should be the same.") +// +// } +// +// if you assert many times, use the format below: +// +// import ( +// "testing" +// "github.com/stretchr/testify/assert" +// ) +// +// func TestSomething(t *testing.T) { +// assert := assert.New(t) +// +// var a string = "Hello" +// var b string = "Hello" +// +// assert.Equal(a, b, "The two words should be the same.") +// } +// +// Assertions +// +// Assertions allow you to easily write test code, and are global funcs in the `assert` package. +// All assertion functions take, as the first argument, the `*testing.T` object provided by the +// testing framework. This allows the assertion funcs to write the failings and other details to +// the correct place. +// +// Every assertion function also takes an optional string message as the final argument, +// allowing custom error messages to be appended to the message the assertion method outputs. +package assert diff --git a/vendor/github.com/stretchr/testify/assert/errors.go b/vendor/github.com/stretchr/testify/assert/errors.go new file mode 100644 index 00000000..ac9dc9d1 --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/errors.go @@ -0,0 +1,10 @@ +package assert + +import ( + "errors" +) + +// AnError is an error instance useful for testing. If the code does not care +// about error specifics, and only needs to return the error for example, this +// error should be used to make the test code more readable. +var AnError = errors.New("assert.AnError general error for testing") diff --git a/vendor/github.com/stretchr/testify/assert/forward_assertions.go b/vendor/github.com/stretchr/testify/assert/forward_assertions.go new file mode 100644 index 00000000..b867e95e --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/forward_assertions.go @@ -0,0 +1,16 @@ +package assert + +// Assertions provides assertion methods around the +// TestingT interface. +type Assertions struct { + t TestingT +} + +// New makes a new Assertions object for the specified TestingT. +func New(t TestingT) *Assertions { + return &Assertions{ + t: t, + } +} + +//go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_forward.go.tmpl diff --git a/vendor/github.com/stretchr/testify/assert/forward_assertions_test.go b/vendor/github.com/stretchr/testify/assert/forward_assertions_test.go new file mode 100644 index 00000000..22e1df1d --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/forward_assertions_test.go @@ -0,0 +1,611 @@ +package assert + +import ( + "errors" + "regexp" + "testing" + "time" +) + +func TestImplementsWrapper(t *testing.T) { + assert := New(new(testing.T)) + + if !assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) { + t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface") + } + if assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) { + t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface") + } +} + +func TestIsTypeWrapper(t *testing.T) { + assert := New(new(testing.T)) + + if !assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { + t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject") + } + if assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) { + t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject") + } + +} + +func TestEqualWrapper(t *testing.T) { + assert := New(new(testing.T)) + + if !assert.Equal("Hello World", "Hello World") { + t.Error("Equal should return true") + } + if !assert.Equal(123, 123) { + t.Error("Equal should return true") + } + if !assert.Equal(123.5, 123.5) { + t.Error("Equal should return true") + } + if !assert.Equal([]byte("Hello World"), []byte("Hello World")) { + t.Error("Equal should return true") + } + if !assert.Equal(nil, nil) { + t.Error("Equal should return true") + } +} + +func TestEqualValuesWrapper(t *testing.T) { + assert := New(new(testing.T)) + + if !assert.EqualValues(uint32(10), int32(10)) { + t.Error("EqualValues should return true") + } +} + +func TestNotNilWrapper(t *testing.T) { + assert := New(new(testing.T)) + + if !assert.NotNil(new(AssertionTesterConformingObject)) { + t.Error("NotNil should return true: object is not nil") + } + if assert.NotNil(nil) { + t.Error("NotNil should return false: object is nil") + } + +} + +func TestNilWrapper(t *testing.T) { + assert := New(new(testing.T)) + + if !assert.Nil(nil) { + t.Error("Nil should return true: object is nil") + } + if assert.Nil(new(AssertionTesterConformingObject)) { + t.Error("Nil should return false: object is not nil") + } + +} + +func TestTrueWrapper(t *testing.T) { + assert := New(new(testing.T)) + + if !assert.True(true) { + t.Error("True should return true") + } + if assert.True(false) { + t.Error("True should return false") + } + +} + +func TestFalseWrapper(t *testing.T) { + assert := New(new(testing.T)) + + if !assert.False(false) { + t.Error("False should return true") + } + if assert.False(true) { + t.Error("False should return false") + } + +} + +func TestExactlyWrapper(t *testing.T) { + assert := New(new(testing.T)) + + a := float32(1) + b := float64(1) + c := float32(1) + d := float32(2) + + if assert.Exactly(a, b) { + t.Error("Exactly should return false") + } + if assert.Exactly(a, d) { + t.Error("Exactly should return false") + } + if !assert.Exactly(a, c) { + t.Error("Exactly should return true") + } + + if assert.Exactly(nil, a) { + t.Error("Exactly should return false") + } + if assert.Exactly(a, nil) { + t.Error("Exactly should return false") + } + +} + +func TestNotEqualWrapper(t *testing.T) { + + assert := New(new(testing.T)) + + if !assert.NotEqual("Hello World", "Hello World!") { + t.Error("NotEqual should return true") + } + if !assert.NotEqual(123, 1234) { + t.Error("NotEqual should return true") + } + if !assert.NotEqual(123.5, 123.55) { + t.Error("NotEqual should return true") + } + if !assert.NotEqual([]byte("Hello World"), []byte("Hello World!")) { + t.Error("NotEqual should return true") + } + if !assert.NotEqual(nil, new(AssertionTesterConformingObject)) { + t.Error("NotEqual should return true") + } +} + +func TestContainsWrapper(t *testing.T) { + + assert := New(new(testing.T)) + list := []string{"Foo", "Bar"} + + if !assert.Contains("Hello World", "Hello") { + t.Error("Contains should return true: \"Hello World\" contains \"Hello\"") + } + if assert.Contains("Hello World", "Salut") { + t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"") + } + + if !assert.Contains(list, "Foo") { + t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") + } + if assert.Contains(list, "Salut") { + t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"") + } + +} + +func TestNotContainsWrapper(t *testing.T) { + + assert := New(new(testing.T)) + list := []string{"Foo", "Bar"} + + if !assert.NotContains("Hello World", "Hello!") { + t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"") + } + if assert.NotContains("Hello World", "Hello") { + t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"") + } + + if !assert.NotContains(list, "Foo!") { + t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"") + } + if assert.NotContains(list, "Foo") { + t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") + } + +} + +func TestConditionWrapper(t *testing.T) { + + assert := New(new(testing.T)) + + if !assert.Condition(func() bool { return true }, "Truth") { + t.Error("Condition should return true") + } + + if assert.Condition(func() bool { return false }, "Lie") { + t.Error("Condition should return false") + } + +} + +func TestDidPanicWrapper(t *testing.T) { + + if funcDidPanic, _ := didPanic(func() { + panic("Panic!") + }); !funcDidPanic { + t.Error("didPanic should return true") + } + + if funcDidPanic, _ := didPanic(func() { + }); funcDidPanic { + t.Error("didPanic should return false") + } + +} + +func TestPanicsWrapper(t *testing.T) { + + assert := New(new(testing.T)) + + if !assert.Panics(func() { + panic("Panic!") + }) { + t.Error("Panics should return true") + } + + if assert.Panics(func() { + }) { + t.Error("Panics should return false") + } + +} + +func TestNotPanicsWrapper(t *testing.T) { + + assert := New(new(testing.T)) + + if !assert.NotPanics(func() { + }) { + t.Error("NotPanics should return true") + } + + if assert.NotPanics(func() { + panic("Panic!") + }) { + t.Error("NotPanics should return false") + } + +} + +func TestNoErrorWrapper(t *testing.T) { + assert := New(t) + mockAssert := New(new(testing.T)) + + // start with a nil error + var err error + + assert.True(mockAssert.NoError(err), "NoError should return True for nil arg") + + // now set an error + err = errors.New("Some error") + + assert.False(mockAssert.NoError(err), "NoError with error should return False") + +} + +func TestErrorWrapper(t *testing.T) { + assert := New(t) + mockAssert := New(new(testing.T)) + + // start with a nil error + var err error + + assert.False(mockAssert.Error(err), "Error should return False for nil arg") + + // now set an error + err = errors.New("Some error") + + assert.True(mockAssert.Error(err), "Error with error should return True") + +} + +func TestEqualErrorWrapper(t *testing.T) { + assert := New(t) + mockAssert := New(new(testing.T)) + + // start with a nil error + var err error + assert.False(mockAssert.EqualError(err, ""), + "EqualError should return false for nil arg") + + // now set an error + err = errors.New("some error") + assert.False(mockAssert.EqualError(err, "Not some error"), + "EqualError should return false for different error string") + assert.True(mockAssert.EqualError(err, "some error"), + "EqualError should return true") +} + +func TestEmptyWrapper(t *testing.T) { + assert := New(t) + mockAssert := New(new(testing.T)) + + assert.True(mockAssert.Empty(""), "Empty string is empty") + assert.True(mockAssert.Empty(nil), "Nil is empty") + assert.True(mockAssert.Empty([]string{}), "Empty string array is empty") + assert.True(mockAssert.Empty(0), "Zero int value is empty") + assert.True(mockAssert.Empty(false), "False value is empty") + + assert.False(mockAssert.Empty("something"), "Non Empty string is not empty") + assert.False(mockAssert.Empty(errors.New("something")), "Non nil object is not empty") + assert.False(mockAssert.Empty([]string{"something"}), "Non empty string array is not empty") + assert.False(mockAssert.Empty(1), "Non-zero int value is not empty") + assert.False(mockAssert.Empty(true), "True value is not empty") + +} + +func TestNotEmptyWrapper(t *testing.T) { + assert := New(t) + mockAssert := New(new(testing.T)) + + assert.False(mockAssert.NotEmpty(""), "Empty string is empty") + assert.False(mockAssert.NotEmpty(nil), "Nil is empty") + assert.False(mockAssert.NotEmpty([]string{}), "Empty string array is empty") + assert.False(mockAssert.NotEmpty(0), "Zero int value is empty") + assert.False(mockAssert.NotEmpty(false), "False value is empty") + + assert.True(mockAssert.NotEmpty("something"), "Non Empty string is not empty") + assert.True(mockAssert.NotEmpty(errors.New("something")), "Non nil object is not empty") + assert.True(mockAssert.NotEmpty([]string{"something"}), "Non empty string array is not empty") + assert.True(mockAssert.NotEmpty(1), "Non-zero int value is not empty") + assert.True(mockAssert.NotEmpty(true), "True value is not empty") + +} + +func TestLenWrapper(t *testing.T) { + assert := New(t) + mockAssert := New(new(testing.T)) + + assert.False(mockAssert.Len(nil, 0), "nil does not have length") + assert.False(mockAssert.Len(0, 0), "int does not have length") + assert.False(mockAssert.Len(true, 0), "true does not have length") + assert.False(mockAssert.Len(false, 0), "false does not have length") + assert.False(mockAssert.Len('A', 0), "Rune does not have length") + assert.False(mockAssert.Len(struct{}{}, 0), "Struct does not have length") + + ch := make(chan int, 5) + ch <- 1 + ch <- 2 + ch <- 3 + + cases := []struct { + v interface{} + l int + }{ + {[]int{1, 2, 3}, 3}, + {[...]int{1, 2, 3}, 3}, + {"ABC", 3}, + {map[int]int{1: 2, 2: 4, 3: 6}, 3}, + {ch, 3}, + + {[]int{}, 0}, + {map[int]int{}, 0}, + {make(chan int), 0}, + + {[]int(nil), 0}, + {map[int]int(nil), 0}, + {(chan int)(nil), 0}, + } + + for _, c := range cases { + assert.True(mockAssert.Len(c.v, c.l), "%#v have %d items", c.v, c.l) + } +} + +func TestWithinDurationWrapper(t *testing.T) { + assert := New(t) + mockAssert := New(new(testing.T)) + a := time.Now() + b := a.Add(10 * time.Second) + + assert.True(mockAssert.WithinDuration(a, b, 10*time.Second), "A 10s difference is within a 10s time difference") + assert.True(mockAssert.WithinDuration(b, a, 10*time.Second), "A 10s difference is within a 10s time difference") + + assert.False(mockAssert.WithinDuration(a, b, 9*time.Second), "A 10s difference is not within a 9s time difference") + assert.False(mockAssert.WithinDuration(b, a, 9*time.Second), "A 10s difference is not within a 9s time difference") + + assert.False(mockAssert.WithinDuration(a, b, -9*time.Second), "A 10s difference is not within a 9s time difference") + assert.False(mockAssert.WithinDuration(b, a, -9*time.Second), "A 10s difference is not within a 9s time difference") + + assert.False(mockAssert.WithinDuration(a, b, -11*time.Second), "A 10s difference is not within a 9s time difference") + assert.False(mockAssert.WithinDuration(b, a, -11*time.Second), "A 10s difference is not within a 9s time difference") +} + +func TestInDeltaWrapper(t *testing.T) { + assert := New(new(testing.T)) + + True(t, assert.InDelta(1.001, 1, 0.01), "|1.001 - 1| <= 0.01") + True(t, assert.InDelta(1, 1.001, 0.01), "|1 - 1.001| <= 0.01") + True(t, assert.InDelta(1, 2, 1), "|1 - 2| <= 1") + False(t, assert.InDelta(1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail") + False(t, assert.InDelta(2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail") + False(t, assert.InDelta("", nil, 1), "Expected non numerals to fail") + + cases := []struct { + a, b interface{} + delta float64 + }{ + {uint8(2), uint8(1), 1}, + {uint16(2), uint16(1), 1}, + {uint32(2), uint32(1), 1}, + {uint64(2), uint64(1), 1}, + + {int(2), int(1), 1}, + {int8(2), int8(1), 1}, + {int16(2), int16(1), 1}, + {int32(2), int32(1), 1}, + {int64(2), int64(1), 1}, + + {float32(2), float32(1), 1}, + {float64(2), float64(1), 1}, + } + + for _, tc := range cases { + True(t, assert.InDelta(tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta) + } +} + +func TestInEpsilonWrapper(t *testing.T) { + assert := New(new(testing.T)) + + cases := []struct { + a, b interface{} + epsilon float64 + }{ + {uint8(2), uint16(2), .001}, + {2.1, 2.2, 0.1}, + {2.2, 2.1, 0.1}, + {-2.1, -2.2, 0.1}, + {-2.2, -2.1, 0.1}, + {uint64(100), uint8(101), 0.01}, + {0.1, -0.1, 2}, + } + + for _, tc := range cases { + True(t, assert.InEpsilon(tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) + } + + cases = []struct { + a, b interface{} + epsilon float64 + }{ + {uint8(2), int16(-2), .001}, + {uint64(100), uint8(102), 0.01}, + {2.1, 2.2, 0.001}, + {2.2, 2.1, 0.001}, + {2.1, -2.2, 1}, + {2.1, "bla-bla", 0}, + {0.1, -0.1, 1.99}, + } + + for _, tc := range cases { + False(t, assert.InEpsilon(tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) + } +} + +func TestRegexpWrapper(t *testing.T) { + + assert := New(new(testing.T)) + + cases := []struct { + rx, str string + }{ + {"^start", "start of the line"}, + {"end$", "in the end"}, + {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"}, + } + + for _, tc := range cases { + True(t, assert.Regexp(tc.rx, tc.str)) + True(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str)) + False(t, assert.NotRegexp(tc.rx, tc.str)) + False(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str)) + } + + cases = []struct { + rx, str string + }{ + {"^asdfastart", "Not the start of the line"}, + {"end$", "in the end."}, + {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"}, + } + + for _, tc := range cases { + False(t, assert.Regexp(tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str) + False(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str)) + True(t, assert.NotRegexp(tc.rx, tc.str)) + True(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str)) + } +} + +func TestZeroWrapper(t *testing.T) { + assert := New(t) + mockAssert := New(new(testing.T)) + + for _, test := range zeros { + assert.True(mockAssert.Zero(test), "Zero should return true for %v", test) + } + + for _, test := range nonZeros { + assert.False(mockAssert.Zero(test), "Zero should return false for %v", test) + } +} + +func TestNotZeroWrapper(t *testing.T) { + assert := New(t) + mockAssert := New(new(testing.T)) + + for _, test := range zeros { + assert.False(mockAssert.NotZero(test), "Zero should return true for %v", test) + } + + for _, test := range nonZeros { + assert.True(mockAssert.NotZero(test), "Zero should return false for %v", test) + } +} + +func TestJSONEqWrapper_EqualSONString(t *testing.T) { + assert := New(new(testing.T)) + if !assert.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`) { + t.Error("JSONEq should return true") + } + +} + +func TestJSONEqWrapper_EquivalentButNotEqual(t *testing.T) { + assert := New(new(testing.T)) + if !assert.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) { + t.Error("JSONEq should return true") + } + +} + +func TestJSONEqWrapper_HashOfArraysAndHashes(t *testing.T) { + assert := New(new(testing.T)) + if !assert.JSONEq("{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}", + "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}") { + t.Error("JSONEq should return true") + } +} + +func TestJSONEqWrapper_Array(t *testing.T) { + assert := New(new(testing.T)) + if !assert.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`) { + t.Error("JSONEq should return true") + } + +} + +func TestJSONEqWrapper_HashAndArrayNotEquivalent(t *testing.T) { + assert := New(new(testing.T)) + if assert.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`) { + t.Error("JSONEq should return false") + } +} + +func TestJSONEqWrapper_HashesNotEquivalent(t *testing.T) { + assert := New(new(testing.T)) + if assert.JSONEq(`{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) { + t.Error("JSONEq should return false") + } +} + +func TestJSONEqWrapper_ActualIsNotJSON(t *testing.T) { + assert := New(new(testing.T)) + if assert.JSONEq(`{"foo": "bar"}`, "Not JSON") { + t.Error("JSONEq should return false") + } +} + +func TestJSONEqWrapper_ExpectedIsNotJSON(t *testing.T) { + assert := New(new(testing.T)) + if assert.JSONEq("Not JSON", `{"foo": "bar", "hello": "world"}`) { + t.Error("JSONEq should return false") + } +} + +func TestJSONEqWrapper_ExpectedAndActualNotJSON(t *testing.T) { + assert := New(new(testing.T)) + if assert.JSONEq("Not JSON", "Not JSON") { + t.Error("JSONEq should return false") + } +} + +func TestJSONEqWrapper_ArraysOfDifferentOrder(t *testing.T) { + assert := New(new(testing.T)) + if assert.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`) { + t.Error("JSONEq should return false") + } +} diff --git a/vendor/github.com/stretchr/testify/assert/http_assertions.go b/vendor/github.com/stretchr/testify/assert/http_assertions.go new file mode 100644 index 00000000..e1b9442b --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/http_assertions.go @@ -0,0 +1,106 @@ +package assert + +import ( + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "strings" +) + +// httpCode is a helper that returns HTTP code of the response. It returns -1 +// if building a new request fails. +func httpCode(handler http.HandlerFunc, method, url string, values url.Values) int { + w := httptest.NewRecorder() + req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) + if err != nil { + return -1 + } + handler(w, req) + return w.Code +} + +// HTTPSuccess asserts that a specified handler returns a success status code. +// +// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { + code := httpCode(handler, method, url, values) + if code == -1 { + return false + } + return code >= http.StatusOK && code <= http.StatusPartialContent +} + +// HTTPRedirect asserts that a specified handler returns a redirect status code. +// +// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { + code := httpCode(handler, method, url, values) + if code == -1 { + return false + } + return code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect +} + +// HTTPError asserts that a specified handler returns an error status code. +// +// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { + code := httpCode(handler, method, url, values) + if code == -1 { + return false + } + return code >= http.StatusBadRequest +} + +// HTTPBody is a helper that returns HTTP body of the response. It returns +// empty string if building a new request fails. +func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string { + w := httptest.NewRecorder() + req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) + if err != nil { + return "" + } + handler(w, req) + return w.Body.String() +} + +// HTTPBodyContains asserts that a specified handler returns a +// body that contains a string. +// +// assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool { + body := HTTPBody(handler, method, url, values) + + contains := strings.Contains(body, fmt.Sprint(str)) + if !contains { + Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) + } + + return contains +} + +// HTTPBodyNotContains asserts that a specified handler returns a +// body that does not contain a string. +// +// assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool { + body := HTTPBody(handler, method, url, values) + + contains := strings.Contains(body, fmt.Sprint(str)) + if contains { + Fail(t, "Expected response body for %s to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body) + } + + return !contains +} diff --git a/vendor/github.com/stretchr/testify/assert/http_assertions_test.go b/vendor/github.com/stretchr/testify/assert/http_assertions_test.go new file mode 100644 index 00000000..684c2d5d --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/http_assertions_test.go @@ -0,0 +1,86 @@ +package assert + +import ( + "fmt" + "net/http" + "net/url" + "testing" +) + +func httpOK(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) +} + +func httpRedirect(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusTemporaryRedirect) +} + +func httpError(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) +} + +func TestHTTPStatuses(t *testing.T) { + assert := New(t) + mockT := new(testing.T) + + assert.Equal(HTTPSuccess(mockT, httpOK, "GET", "/", nil), true) + assert.Equal(HTTPSuccess(mockT, httpRedirect, "GET", "/", nil), false) + assert.Equal(HTTPSuccess(mockT, httpError, "GET", "/", nil), false) + + assert.Equal(HTTPRedirect(mockT, httpOK, "GET", "/", nil), false) + assert.Equal(HTTPRedirect(mockT, httpRedirect, "GET", "/", nil), true) + assert.Equal(HTTPRedirect(mockT, httpError, "GET", "/", nil), false) + + assert.Equal(HTTPError(mockT, httpOK, "GET", "/", nil), false) + assert.Equal(HTTPError(mockT, httpRedirect, "GET", "/", nil), false) + assert.Equal(HTTPError(mockT, httpError, "GET", "/", nil), true) +} + +func TestHTTPStatusesWrapper(t *testing.T) { + assert := New(t) + mockAssert := New(new(testing.T)) + + assert.Equal(mockAssert.HTTPSuccess(httpOK, "GET", "/", nil), true) + assert.Equal(mockAssert.HTTPSuccess(httpRedirect, "GET", "/", nil), false) + assert.Equal(mockAssert.HTTPSuccess(httpError, "GET", "/", nil), false) + + assert.Equal(mockAssert.HTTPRedirect(httpOK, "GET", "/", nil), false) + assert.Equal(mockAssert.HTTPRedirect(httpRedirect, "GET", "/", nil), true) + assert.Equal(mockAssert.HTTPRedirect(httpError, "GET", "/", nil), false) + + assert.Equal(mockAssert.HTTPError(httpOK, "GET", "/", nil), false) + assert.Equal(mockAssert.HTTPError(httpRedirect, "GET", "/", nil), false) + assert.Equal(mockAssert.HTTPError(httpError, "GET", "/", nil), true) +} + +func httpHelloName(w http.ResponseWriter, r *http.Request) { + name := r.FormValue("name") + w.Write([]byte(fmt.Sprintf("Hello, %s!", name))) +} + +func TestHttpBody(t *testing.T) { + assert := New(t) + mockT := new(testing.T) + + assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) + assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) + assert.False(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) + + assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) + assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) + assert.True(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) +} + +func TestHttpBodyWrappers(t *testing.T) { + assert := New(t) + mockAssert := New(new(testing.T)) + + assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) + assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) + assert.False(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) + + assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) + assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) + assert.True(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) + +} diff --git a/vendor/github.com/stretchr/testify/doc.go b/vendor/github.com/stretchr/testify/doc.go new file mode 100644 index 00000000..377d5cc5 --- /dev/null +++ b/vendor/github.com/stretchr/testify/doc.go @@ -0,0 +1,22 @@ +// Package testify is a set of packages that provide many tools for testifying that your code will behave as you intend. +// +// testify contains the following packages: +// +// The assert package provides a comprehensive set of assertion functions that tie in to the Go testing system. +// +// The http package contains tools to make it easier to test http activity using the Go testing system. +// +// The mock package provides a system by which it is possible to mock your objects and verify calls are happening as expected. +// +// The suite package provides a basic structure for using structs as testing suites, and methods on those structs as tests. It includes setup/teardown functionality in the way of interfaces. +package testify + +// blank imports help docs. +import ( + // assert package + _ "github.com/stretchr/testify/assert" + // http package + _ "github.com/stretchr/testify/http" + // mock package + _ "github.com/stretchr/testify/mock" +) diff --git a/vendor/github.com/stretchr/testify/http/doc.go b/vendor/github.com/stretchr/testify/http/doc.go new file mode 100644 index 00000000..695167c6 --- /dev/null +++ b/vendor/github.com/stretchr/testify/http/doc.go @@ -0,0 +1,2 @@ +// Package http DEPRECATED USE net/http/httptest +package http diff --git a/vendor/github.com/stretchr/testify/http/test_response_writer.go b/vendor/github.com/stretchr/testify/http/test_response_writer.go new file mode 100644 index 00000000..5c3f813f --- /dev/null +++ b/vendor/github.com/stretchr/testify/http/test_response_writer.go @@ -0,0 +1,49 @@ +package http + +import ( + "net/http" +) + +// TestResponseWriter DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. +type TestResponseWriter struct { + + // StatusCode is the last int written by the call to WriteHeader(int) + StatusCode int + + // Output is a string containing the written bytes using the Write([]byte) func. + Output string + + // header is the internal storage of the http.Header object + header http.Header +} + +// Header DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. +func (rw *TestResponseWriter) Header() http.Header { + + if rw.header == nil { + rw.header = make(http.Header) + } + + return rw.header +} + +// Write DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. +func (rw *TestResponseWriter) Write(bytes []byte) (int, error) { + + // assume 200 success if no header has been set + if rw.StatusCode == 0 { + rw.WriteHeader(200) + } + + // add these bytes to the output string + rw.Output = rw.Output + string(bytes) + + // return normal values + return 0, nil + +} + +// WriteHeader DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. +func (rw *TestResponseWriter) WriteHeader(i int) { + rw.StatusCode = i +} diff --git a/vendor/github.com/stretchr/testify/http/test_round_tripper.go b/vendor/github.com/stretchr/testify/http/test_round_tripper.go new file mode 100644 index 00000000..b1e32f1d --- /dev/null +++ b/vendor/github.com/stretchr/testify/http/test_round_tripper.go @@ -0,0 +1,17 @@ +package http + +import ( + "github.com/stretchr/testify/mock" + "net/http" +) + +// TestRoundTripper DEPRECATED USE net/http/httptest +type TestRoundTripper struct { + mock.Mock +} + +// RoundTrip DEPRECATED USE net/http/httptest +func (t *TestRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + args := t.Called(req) + return args.Get(0).(*http.Response), args.Error(1) +} diff --git a/vendor/github.com/stretchr/testify/mock/doc.go b/vendor/github.com/stretchr/testify/mock/doc.go new file mode 100644 index 00000000..7324128e --- /dev/null +++ b/vendor/github.com/stretchr/testify/mock/doc.go @@ -0,0 +1,44 @@ +// Package mock provides a system by which it is possible to mock your objects +// and verify calls are happening as expected. +// +// Example Usage +// +// The mock package provides an object, Mock, that tracks activity on another object. It is usually +// embedded into a test object as shown below: +// +// type MyTestObject struct { +// // add a Mock object instance +// mock.Mock +// +// // other fields go here as normal +// } +// +// When implementing the methods of an interface, you wire your functions up +// to call the Mock.Called(args...) method, and return the appropriate values. +// +// For example, to mock a method that saves the name and age of a person and returns +// the year of their birth or an error, you might write this: +// +// func (o *MyTestObject) SavePersonDetails(firstname, lastname string, age int) (int, error) { +// args := o.Called(firstname, lastname, age) +// return args.Int(0), args.Error(1) +// } +// +// The Int, Error and Bool methods are examples of strongly typed getters that take the argument +// index position. Given this argument list: +// +// (12, true, "Something") +// +// You could read them out strongly typed like this: +// +// args.Int(0) +// args.Bool(1) +// args.String(2) +// +// For objects of your own type, use the generic Arguments.Get(index) method and make a type assertion: +// +// return args.Get(0).(*MyObject), args.Get(1).(*AnotherObjectOfMine) +// +// This may cause a panic if the object you are getting is nil (the type assertion will fail), in those +// cases you should check for nil first. +package mock diff --git a/vendor/github.com/stretchr/testify/mock/mock.go b/vendor/github.com/stretchr/testify/mock/mock.go new file mode 100644 index 00000000..cba9009a --- /dev/null +++ b/vendor/github.com/stretchr/testify/mock/mock.go @@ -0,0 +1,693 @@ +package mock + +import ( + "fmt" + "reflect" + "regexp" + "runtime" + "strings" + "sync" + "time" + + "github.com/stretchr/objx" + "github.com/stretchr/testify/assert" +) + +// TestingT is an interface wrapper around *testing.T +type TestingT interface { + Logf(format string, args ...interface{}) + Errorf(format string, args ...interface{}) + FailNow() +} + +/* + Call +*/ + +// Call represents a method call and is used for setting expectations, +// as well as recording activity. +type Call struct { + Parent *Mock + + // The name of the method that was or will be called. + Method string + + // Holds the arguments of the method. + Arguments Arguments + + // Holds the arguments that should be returned when + // this method is called. + ReturnArguments Arguments + + // The number of times to return the return arguments when setting + // expectations. 0 means to always return the value. + Repeatability int + + // Amount of times this call has been called + totalCalls int + + // Holds a channel that will be used to block the Return until it either + // recieves a message or is closed. nil means it returns immediately. + WaitFor <-chan time.Time + + // Holds a handler used to manipulate arguments content that are passed by + // reference. It's useful when mocking methods such as unmarshalers or + // decoders. + RunFn func(Arguments) +} + +func newCall(parent *Mock, methodName string, methodArguments ...interface{}) *Call { + return &Call{ + Parent: parent, + Method: methodName, + Arguments: methodArguments, + ReturnArguments: make([]interface{}, 0), + Repeatability: 0, + WaitFor: nil, + RunFn: nil, + } +} + +func (c *Call) lock() { + c.Parent.mutex.Lock() +} + +func (c *Call) unlock() { + c.Parent.mutex.Unlock() +} + +// Return specifies the return arguments for the expectation. +// +// Mock.On("DoSomething").Return(errors.New("failed")) +func (c *Call) Return(returnArguments ...interface{}) *Call { + c.lock() + defer c.unlock() + + c.ReturnArguments = returnArguments + + return c +} + +// Once indicates that that the mock should only return the value once. +// +// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Once() +func (c *Call) Once() *Call { + return c.Times(1) +} + +// Twice indicates that that the mock should only return the value twice. +// +// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Twice() +func (c *Call) Twice() *Call { + return c.Times(2) +} + +// Times indicates that that the mock should only return the indicated number +// of times. +// +// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Times(5) +func (c *Call) Times(i int) *Call { + c.lock() + defer c.unlock() + c.Repeatability = i + return c +} + +// WaitUntil sets the channel that will block the mock's return until its closed +// or a message is received. +// +// Mock.On("MyMethod", arg1, arg2).WaitUntil(time.After(time.Second)) +func (c *Call) WaitUntil(w <-chan time.Time) *Call { + c.lock() + defer c.unlock() + c.WaitFor = w + return c +} + +// After sets how long to block until the call returns +// +// Mock.On("MyMethod", arg1, arg2).After(time.Second) +func (c *Call) After(d time.Duration) *Call { + return c.WaitUntil(time.After(d)) +} + +// Run sets a handler to be called before returning. It can be used when +// mocking a method such as unmarshalers that takes a pointer to a struct and +// sets properties in such struct +// +// Mock.On("Unmarshal", AnythingOfType("*map[string]interface{}").Return().Run(func(args Arguments) { +// arg := args.Get(0).(*map[string]interface{}) +// arg["foo"] = "bar" +// }) +func (c *Call) Run(fn func(Arguments)) *Call { + c.lock() + defer c.unlock() + c.RunFn = fn + return c +} + +// On chains a new expectation description onto the mocked interface. This +// allows syntax like. +// +// Mock. +// On("MyMethod", 1).Return(nil). +// On("MyOtherMethod", 'a', 'b', 'c').Return(errors.New("Some Error")) +func (c *Call) On(methodName string, arguments ...interface{}) *Call { + return c.Parent.On(methodName, arguments...) +} + +// Mock is the workhorse used to track activity on another object. +// For an example of its usage, refer to the "Example Usage" section at the top +// of this document. +type Mock struct { + // Represents the calls that are expected of + // an object. + ExpectedCalls []*Call + + // Holds the calls that were made to this mocked object. + Calls []Call + + // TestData holds any data that might be useful for testing. Testify ignores + // this data completely allowing you to do whatever you like with it. + testData objx.Map + + mutex sync.Mutex +} + +// TestData holds any data that might be useful for testing. Testify ignores +// this data completely allowing you to do whatever you like with it. +func (m *Mock) TestData() objx.Map { + + if m.testData == nil { + m.testData = make(objx.Map) + } + + return m.testData +} + +/* + Setting expectations +*/ + +// On starts a description of an expectation of the specified method +// being called. +// +// Mock.On("MyMethod", arg1, arg2) +func (m *Mock) On(methodName string, arguments ...interface{}) *Call { + for _, arg := range arguments { + if v := reflect.ValueOf(arg); v.Kind() == reflect.Func { + panic(fmt.Sprintf("cannot use Func in expectations. Use mock.AnythingOfType(\"%T\")", arg)) + } + } + + m.mutex.Lock() + defer m.mutex.Unlock() + c := newCall(m, methodName, arguments...) + m.ExpectedCalls = append(m.ExpectedCalls, c) + return c +} + +// /* +// Recording and responding to activity +// */ + +func (m *Mock) findExpectedCall(method string, arguments ...interface{}) (int, *Call) { + m.mutex.Lock() + defer m.mutex.Unlock() + for i, call := range m.ExpectedCalls { + if call.Method == method && call.Repeatability > -1 { + + _, diffCount := call.Arguments.Diff(arguments) + if diffCount == 0 { + return i, call + } + + } + } + return -1, nil +} + +func (m *Mock) findClosestCall(method string, arguments ...interface{}) (bool, *Call) { + diffCount := 0 + var closestCall *Call + + for _, call := range m.expectedCalls() { + if call.Method == method { + + _, tempDiffCount := call.Arguments.Diff(arguments) + if tempDiffCount < diffCount || diffCount == 0 { + diffCount = tempDiffCount + closestCall = call + } + + } + } + + if closestCall == nil { + return false, nil + } + + return true, closestCall +} + +func callString(method string, arguments Arguments, includeArgumentValues bool) string { + + var argValsString string + if includeArgumentValues { + var argVals []string + for argIndex, arg := range arguments { + argVals = append(argVals, fmt.Sprintf("%d: %#v", argIndex, arg)) + } + argValsString = fmt.Sprintf("\n\t\t%s", strings.Join(argVals, "\n\t\t")) + } + + return fmt.Sprintf("%s(%s)%s", method, arguments.String(), argValsString) +} + +// Called tells the mock object that a method has been called, and gets an array +// of arguments to return. Panics if the call is unexpected (i.e. not preceded by +// appropriate .On .Return() calls) +// If Call.WaitFor is set, blocks until the channel is closed or receives a message. +func (m *Mock) Called(arguments ...interface{}) Arguments { + // get the calling function's name + pc, _, _, ok := runtime.Caller(1) + if !ok { + panic("Couldn't get the caller information") + } + functionPath := runtime.FuncForPC(pc).Name() + //Next four lines are required to use GCCGO function naming conventions. + //For Ex: github_com_docker_libkv_store_mock.WatchTree.pN39_github_com_docker_libkv_store_mock.Mock + //uses inteface information unlike golang github.com/docker/libkv/store/mock.(*Mock).WatchTree + //With GCCGO we need to remove interface information starting from pN
. + re := regexp.MustCompile("\\.pN\\d+_") + if re.MatchString(functionPath) { + functionPath = re.Split(functionPath, -1)[0] + } + parts := strings.Split(functionPath, ".") + functionName := parts[len(parts)-1] + + found, call := m.findExpectedCall(functionName, arguments...) + + if found < 0 { + // we have to fail here - because we don't know what to do + // as the return arguments. This is because: + // + // a) this is a totally unexpected call to this method, + // b) the arguments are not what was expected, or + // c) the developer has forgotten to add an accompanying On...Return pair. + + closestFound, closestCall := m.findClosestCall(functionName, arguments...) + + if closestFound { + panic(fmt.Sprintf("\n\nmock: Unexpected Method Call\n-----------------------------\n\n%s\n\nThe closest call I have is: \n\n%s\n", callString(functionName, arguments, true), callString(functionName, closestCall.Arguments, true))) + } else { + panic(fmt.Sprintf("\nassert: mock: I don't know what to return because the method call was unexpected.\n\tEither do Mock.On(\"%s\").Return(...) first, or remove the %s() call.\n\tThis method was unexpected:\n\t\t%s\n\tat: %s", functionName, functionName, callString(functionName, arguments, true), assert.CallerInfo())) + } + } else { + m.mutex.Lock() + switch { + case call.Repeatability == 1: + call.Repeatability = -1 + call.totalCalls++ + + case call.Repeatability > 1: + call.Repeatability-- + call.totalCalls++ + + case call.Repeatability == 0: + call.totalCalls++ + } + m.mutex.Unlock() + } + + // add the call + m.mutex.Lock() + m.Calls = append(m.Calls, *newCall(m, functionName, arguments...)) + m.mutex.Unlock() + + // block if specified + if call.WaitFor != nil { + <-call.WaitFor + } + + if call.RunFn != nil { + call.RunFn(arguments) + } + + return call.ReturnArguments +} + +/* + Assertions +*/ + +// AssertExpectationsForObjects asserts that everything specified with On and Return +// of the specified objects was in fact called as expected. +// +// Calls may have occurred in any order. +func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool { + var success = true + for _, obj := range testObjects { + mockObj := obj.(Mock) + success = success && mockObj.AssertExpectations(t) + } + return success +} + +// AssertExpectations asserts that everything specified with On and Return was +// in fact called as expected. Calls may have occurred in any order. +func (m *Mock) AssertExpectations(t TestingT) bool { + var somethingMissing bool + var failedExpectations int + + // iterate through each expectation + expectedCalls := m.expectedCalls() + for _, expectedCall := range expectedCalls { + if !m.methodWasCalled(expectedCall.Method, expectedCall.Arguments) && expectedCall.totalCalls == 0 { + somethingMissing = true + failedExpectations++ + t.Logf("\u274C\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String()) + } else { + m.mutex.Lock() + if expectedCall.Repeatability > 0 { + somethingMissing = true + failedExpectations++ + } else { + t.Logf("\u2705\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String()) + } + m.mutex.Unlock() + } + } + + if somethingMissing { + t.Errorf("FAIL: %d out of %d expectation(s) were met.\n\tThe code you are testing needs to make %d more call(s).\n\tat: %s", len(expectedCalls)-failedExpectations, len(expectedCalls), failedExpectations, assert.CallerInfo()) + } + + return !somethingMissing +} + +// AssertNumberOfCalls asserts that the method was called expectedCalls times. +func (m *Mock) AssertNumberOfCalls(t TestingT, methodName string, expectedCalls int) bool { + var actualCalls int + for _, call := range m.calls() { + if call.Method == methodName { + actualCalls++ + } + } + return assert.Equal(t, expectedCalls, actualCalls, fmt.Sprintf("Expected number of calls (%d) does not match the actual number of calls (%d).", expectedCalls, actualCalls)) +} + +// AssertCalled asserts that the method was called. +// It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method. +func (m *Mock) AssertCalled(t TestingT, methodName string, arguments ...interface{}) bool { + if !assert.True(t, m.methodWasCalled(methodName, arguments), fmt.Sprintf("The \"%s\" method should have been called with %d argument(s), but was not.", methodName, len(arguments))) { + t.Logf("%v", m.expectedCalls()) + return false + } + return true +} + +// AssertNotCalled asserts that the method was not called. +// It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method. +func (m *Mock) AssertNotCalled(t TestingT, methodName string, arguments ...interface{}) bool { + if !assert.False(t, m.methodWasCalled(methodName, arguments), fmt.Sprintf("The \"%s\" method was called with %d argument(s), but should NOT have been.", methodName, len(arguments))) { + t.Logf("%v", m.expectedCalls()) + return false + } + return true +} + +func (m *Mock) methodWasCalled(methodName string, expected []interface{}) bool { + for _, call := range m.calls() { + if call.Method == methodName { + + _, differences := Arguments(expected).Diff(call.Arguments) + + if differences == 0 { + // found the expected call + return true + } + + } + } + // we didn't find the expected call + return false +} + +func (m *Mock) expectedCalls() []*Call { + m.mutex.Lock() + defer m.mutex.Unlock() + return append([]*Call{}, m.ExpectedCalls...) +} + +func (m *Mock) calls() []Call { + m.mutex.Lock() + defer m.mutex.Unlock() + return append([]Call{}, m.Calls...) +} + +/* + Arguments +*/ + +// Arguments holds an array of method arguments or return values. +type Arguments []interface{} + +const ( + // Anything is used in Diff and Assert when the argument being tested + // shouldn't be taken into consideration. + Anything string = "mock.Anything" +) + +// AnythingOfTypeArgument is a string that contains the type of an argument +// for use when type checking. Used in Diff and Assert. +type AnythingOfTypeArgument string + +// AnythingOfType returns an AnythingOfTypeArgument object containing the +// name of the type to check for. Used in Diff and Assert. +// +// For example: +// Assert(t, AnythingOfType("string"), AnythingOfType("int")) +func AnythingOfType(t string) AnythingOfTypeArgument { + return AnythingOfTypeArgument(t) +} + +// argumentMatcher performs custom argument matching, returning whether or +// not the argument is matched by the expectation fixture function. +type argumentMatcher struct { + // fn is a function which accepts one argument, and returns a bool. + fn reflect.Value +} + +func (f argumentMatcher) Matches(argument interface{}) bool { + expectType := f.fn.Type().In(0) + + if reflect.TypeOf(argument).AssignableTo(expectType) { + result := f.fn.Call([]reflect.Value{reflect.ValueOf(argument)}) + return result[0].Bool() + } + return false +} + +func (f argumentMatcher) String() string { + return fmt.Sprintf("func(%s) bool", f.fn.Type().In(0).Name()) +} + +// MatchedBy can be used to match a mock call based on only certain properties +// from a complex struct or some calculation. It takes a function that will be +// evaluated with the called argument and will return true when there's a match +// and false otherwise. +// +// Example: +// m.On("Do", MatchedBy(func(req *http.Request) bool { return req.Host == "example.com" })) +// +// |fn|, must be a function accepting a single argument (of the expected type) +// which returns a bool. If |fn| doesn't match the required signature, +// MathedBy() panics. +func MatchedBy(fn interface{}) argumentMatcher { + fnType := reflect.TypeOf(fn) + + if fnType.Kind() != reflect.Func { + panic(fmt.Sprintf("assert: arguments: %s is not a func", fn)) + } + if fnType.NumIn() != 1 { + panic(fmt.Sprintf("assert: arguments: %s does not take exactly one argument", fn)) + } + if fnType.NumOut() != 1 || fnType.Out(0).Kind() != reflect.Bool { + panic(fmt.Sprintf("assert: arguments: %s does not return a bool", fn)) + } + + return argumentMatcher{fn: reflect.ValueOf(fn)} +} + +// Get Returns the argument at the specified index. +func (args Arguments) Get(index int) interface{} { + if index+1 > len(args) { + panic(fmt.Sprintf("assert: arguments: Cannot call Get(%d) because there are %d argument(s).", index, len(args))) + } + return args[index] +} + +// Is gets whether the objects match the arguments specified. +func (args Arguments) Is(objects ...interface{}) bool { + for i, obj := range args { + if obj != objects[i] { + return false + } + } + return true +} + +// Diff gets a string describing the differences between the arguments +// and the specified objects. +// +// Returns the diff string and number of differences found. +func (args Arguments) Diff(objects []interface{}) (string, int) { + + var output = "\n" + var differences int + + var maxArgCount = len(args) + if len(objects) > maxArgCount { + maxArgCount = len(objects) + } + + for i := 0; i < maxArgCount; i++ { + var actual, expected interface{} + + if len(objects) <= i { + actual = "(Missing)" + } else { + actual = objects[i] + } + + if len(args) <= i { + expected = "(Missing)" + } else { + expected = args[i] + } + + if matcher, ok := expected.(argumentMatcher); ok { + if matcher.Matches(actual) { + output = fmt.Sprintf("%s\t%d: \u2705 %s matched by %s\n", output, i, actual, matcher) + } else { + differences++ + output = fmt.Sprintf("%s\t%d: \u2705 %s not matched by %s\n", output, i, actual, matcher) + } + } else if reflect.TypeOf(expected) == reflect.TypeOf((*AnythingOfTypeArgument)(nil)).Elem() { + + // type checking + if reflect.TypeOf(actual).Name() != string(expected.(AnythingOfTypeArgument)) && reflect.TypeOf(actual).String() != string(expected.(AnythingOfTypeArgument)) { + // not match + differences++ + output = fmt.Sprintf("%s\t%d: \u274C type %s != type %s - %s\n", output, i, expected, reflect.TypeOf(actual).Name(), actual) + } + + } else { + + // normal checking + + if assert.ObjectsAreEqual(expected, Anything) || assert.ObjectsAreEqual(actual, Anything) || assert.ObjectsAreEqual(actual, expected) { + // match + output = fmt.Sprintf("%s\t%d: \u2705 %s == %s\n", output, i, actual, expected) + } else { + // not match + differences++ + output = fmt.Sprintf("%s\t%d: \u274C %s != %s\n", output, i, actual, expected) + } + } + + } + + if differences == 0 { + return "No differences.", differences + } + + return output, differences + +} + +// Assert compares the arguments with the specified objects and fails if +// they do not exactly match. +func (args Arguments) Assert(t TestingT, objects ...interface{}) bool { + + // get the differences + diff, diffCount := args.Diff(objects) + + if diffCount == 0 { + return true + } + + // there are differences... report them... + t.Logf(diff) + t.Errorf("%sArguments do not match.", assert.CallerInfo()) + + return false + +} + +// String gets the argument at the specified index. Panics if there is no argument, or +// if the argument is of the wrong type. +// +// If no index is provided, String() returns a complete string representation +// of the arguments. +func (args Arguments) String(indexOrNil ...int) string { + + if len(indexOrNil) == 0 { + // normal String() method - return a string representation of the args + var argsStr []string + for _, arg := range args { + argsStr = append(argsStr, fmt.Sprintf("%s", reflect.TypeOf(arg))) + } + return strings.Join(argsStr, ",") + } else if len(indexOrNil) == 1 { + // Index has been specified - get the argument at that index + var index = indexOrNil[0] + var s string + var ok bool + if s, ok = args.Get(index).(string); !ok { + panic(fmt.Sprintf("assert: arguments: String(%d) failed because object wasn't correct type: %s", index, args.Get(index))) + } + return s + } + + panic(fmt.Sprintf("assert: arguments: Wrong number of arguments passed to String. Must be 0 or 1, not %d", len(indexOrNil))) + +} + +// Int gets the argument at the specified index. Panics if there is no argument, or +// if the argument is of the wrong type. +func (args Arguments) Int(index int) int { + var s int + var ok bool + if s, ok = args.Get(index).(int); !ok { + panic(fmt.Sprintf("assert: arguments: Int(%d) failed because object wasn't correct type: %v", index, args.Get(index))) + } + return s +} + +// Error gets the argument at the specified index. Panics if there is no argument, or +// if the argument is of the wrong type. +func (args Arguments) Error(index int) error { + obj := args.Get(index) + var s error + var ok bool + if obj == nil { + return nil + } + if s, ok = obj.(error); !ok { + panic(fmt.Sprintf("assert: arguments: Error(%d) failed because object wasn't correct type: %v", index, args.Get(index))) + } + return s +} + +// Bool gets the argument at the specified index. Panics if there is no argument, or +// if the argument is of the wrong type. +func (args Arguments) Bool(index int) bool { + var s bool + var ok bool + if s, ok = args.Get(index).(bool); !ok { + panic(fmt.Sprintf("assert: arguments: Bool(%d) failed because object wasn't correct type: %v", index, args.Get(index))) + } + return s +} diff --git a/vendor/github.com/stretchr/testify/mock/mock_test.go b/vendor/github.com/stretchr/testify/mock/mock_test.go new file mode 100644 index 00000000..166c3246 --- /dev/null +++ b/vendor/github.com/stretchr/testify/mock/mock_test.go @@ -0,0 +1,1130 @@ +package mock + +import ( + "errors" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" + "time" +) + +/* + Test objects +*/ + +// ExampleInterface represents an example interface. +type ExampleInterface interface { + TheExampleMethod(a, b, c int) (int, error) +} + +// TestExampleImplementation is a test implementation of ExampleInterface +type TestExampleImplementation struct { + Mock +} + +func (i *TestExampleImplementation) TheExampleMethod(a, b, c int) (int, error) { + args := i.Called(a, b, c) + return args.Int(0), errors.New("Whoops") +} + +func (i *TestExampleImplementation) TheExampleMethod2(yesorno bool) { + i.Called(yesorno) +} + +type ExampleType struct { + ran bool +} + +func (i *TestExampleImplementation) TheExampleMethod3(et *ExampleType) error { + args := i.Called(et) + return args.Error(0) +} + +func (i *TestExampleImplementation) TheExampleMethodFunc(fn func(string) error) error { + args := i.Called(fn) + return args.Error(0) +} + +func (i *TestExampleImplementation) TheExampleMethodVariadic(a ...int) error { + args := i.Called(a) + return args.Error(0) +} + +func (i *TestExampleImplementation) TheExampleMethodVariadicInterface(a ...interface{}) error { + args := i.Called(a) + return args.Error(0) +} + +type ExampleFuncType func(string) error + +func (i *TestExampleImplementation) TheExampleMethodFuncType(fn ExampleFuncType) error { + args := i.Called(fn) + return args.Error(0) +} + +/* + Mock +*/ + +func Test_Mock_TestData(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + if assert.NotNil(t, mockedService.TestData()) { + + mockedService.TestData().Set("something", 123) + assert.Equal(t, 123, mockedService.TestData().Get("something").Data()) + } +} + +func Test_Mock_On(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService.On("TheExampleMethod") + assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + assert.Equal(t, "TheExampleMethod", c.Method) +} + +func Test_Mock_Chained_On(t *testing.T) { + // make a test impl object + var mockedService = new(TestExampleImplementation) + + mockedService. + On("TheExampleMethod", 1, 2, 3). + Return(0). + On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")). + Return(nil) + + expectedCalls := []*Call{ + &Call{ + Parent: &mockedService.Mock, + Method: "TheExampleMethod", + Arguments: []interface{}{1, 2, 3}, + ReturnArguments: []interface{}{0}, + }, + &Call{ + Parent: &mockedService.Mock, + Method: "TheExampleMethod3", + Arguments: []interface{}{AnythingOfType("*mock.ExampleType")}, + ReturnArguments: []interface{}{nil}, + }, + } + assert.Equal(t, expectedCalls, mockedService.ExpectedCalls) +} + +func Test_Mock_On_WithArgs(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService.On("TheExampleMethod", 1, 2, 3, 4) + + assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + assert.Equal(t, "TheExampleMethod", c.Method) + assert.Equal(t, Arguments{1, 2, 3, 4}, c.Arguments) +} + +func Test_Mock_On_WithFuncArg(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService. + On("TheExampleMethodFunc", AnythingOfType("func(string) error")). + Return(nil) + + assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + assert.Equal(t, "TheExampleMethodFunc", c.Method) + assert.Equal(t, 1, len(c.Arguments)) + assert.Equal(t, AnythingOfType("func(string) error"), c.Arguments[0]) + + fn := func(string) error { return nil } + + assert.NotPanics(t, func() { + mockedService.TheExampleMethodFunc(fn) + }) +} + +func Test_Mock_On_WithIntArgMatcher(t *testing.T) { + var mockedService TestExampleImplementation + + mockedService.On("TheExampleMethod", + MatchedBy(func(a int) bool { + return a == 1 + }), MatchedBy(func(b int) bool { + return b == 2 + }), MatchedBy(func(c int) bool { + return c == 3 + })).Return(0, nil) + + assert.Panics(t, func() { + mockedService.TheExampleMethod(1, 2, 4) + }) + assert.Panics(t, func() { + mockedService.TheExampleMethod(2, 2, 3) + }) + assert.NotPanics(t, func() { + mockedService.TheExampleMethod(1, 2, 3) + }) +} + +func Test_Mock_On_WithPtrArgMatcher(t *testing.T) { + var mockedService TestExampleImplementation + + mockedService.On("TheExampleMethod3", + MatchedBy(func(a *ExampleType) bool { return a.ran == true }), + ).Return(nil) + + mockedService.On("TheExampleMethod3", + MatchedBy(func(a *ExampleType) bool { return a.ran == false }), + ).Return(errors.New("error")) + + assert.Equal(t, mockedService.TheExampleMethod3(&ExampleType{true}), nil) + assert.EqualError(t, mockedService.TheExampleMethod3(&ExampleType{false}), "error") +} + +func Test_Mock_On_WithFuncArgMatcher(t *testing.T) { + var mockedService TestExampleImplementation + + fixture1, fixture2 := errors.New("fixture1"), errors.New("fixture2") + + mockedService.On("TheExampleMethodFunc", + MatchedBy(func(a func(string) error) bool { return a("string") == fixture1 }), + ).Return(errors.New("fixture1")) + + mockedService.On("TheExampleMethodFunc", + MatchedBy(func(a func(string) error) bool { return a("string") == fixture2 }), + ).Return(errors.New("fixture2")) + + assert.EqualError(t, mockedService.TheExampleMethodFunc( + func(string) error { return fixture1 }), "fixture1") + assert.EqualError(t, mockedService.TheExampleMethodFunc( + func(string) error { return fixture2 }), "fixture2") +} + +func Test_Mock_On_WithVariadicFunc(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService. + On("TheExampleMethodVariadic", []int{1, 2, 3}). + Return(nil) + + assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + assert.Equal(t, 1, len(c.Arguments)) + assert.Equal(t, []int{1, 2, 3}, c.Arguments[0]) + + assert.NotPanics(t, func() { + mockedService.TheExampleMethodVariadic(1, 2, 3) + }) + assert.Panics(t, func() { + mockedService.TheExampleMethodVariadic(1, 2) + }) + +} + +func Test_Mock_On_WithVariadicFuncWithInterface(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService.On("TheExampleMethodVariadicInterface", []interface{}{1, 2, 3}). + Return(nil) + + assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + assert.Equal(t, 1, len(c.Arguments)) + assert.Equal(t, []interface{}{1, 2, 3}, c.Arguments[0]) + + assert.NotPanics(t, func() { + mockedService.TheExampleMethodVariadicInterface(1, 2, 3) + }) + assert.Panics(t, func() { + mockedService.TheExampleMethodVariadicInterface(1, 2) + }) + +} + +func Test_Mock_On_WithVariadicFuncWithEmptyInterfaceArray(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + var expected []interface{} + c := mockedService. + On("TheExampleMethodVariadicInterface", expected). + Return(nil) + + assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + assert.Equal(t, 1, len(c.Arguments)) + assert.Equal(t, expected, c.Arguments[0]) + + assert.NotPanics(t, func() { + mockedService.TheExampleMethodVariadicInterface() + }) + assert.Panics(t, func() { + mockedService.TheExampleMethodVariadicInterface(1, 2) + }) + +} + +func Test_Mock_On_WithFuncPanics(t *testing.T) { + // make a test impl object + var mockedService = new(TestExampleImplementation) + + assert.Panics(t, func() { + mockedService.On("TheExampleMethodFunc", func(string) error { return nil }) + }) +} + +func Test_Mock_On_WithFuncTypeArg(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService. + On("TheExampleMethodFuncType", AnythingOfType("mock.ExampleFuncType")). + Return(nil) + + assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + assert.Equal(t, 1, len(c.Arguments)) + assert.Equal(t, AnythingOfType("mock.ExampleFuncType"), c.Arguments[0]) + + fn := func(string) error { return nil } + assert.NotPanics(t, func() { + mockedService.TheExampleMethodFuncType(fn) + }) +} + +func Test_Mock_Return(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService. + On("TheExampleMethod", "A", "B", true). + Return(1, "two", true) + + require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + + call := mockedService.ExpectedCalls[0] + + assert.Equal(t, "TheExampleMethod", call.Method) + assert.Equal(t, "A", call.Arguments[0]) + assert.Equal(t, "B", call.Arguments[1]) + assert.Equal(t, true, call.Arguments[2]) + assert.Equal(t, 1, call.ReturnArguments[0]) + assert.Equal(t, "two", call.ReturnArguments[1]) + assert.Equal(t, true, call.ReturnArguments[2]) + assert.Equal(t, 0, call.Repeatability) + assert.Nil(t, call.WaitFor) +} + +func Test_Mock_Return_WaitUntil(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + ch := time.After(time.Second) + + c := mockedService.Mock. + On("TheExampleMethod", "A", "B", true). + WaitUntil(ch). + Return(1, "two", true) + + // assert that the call was created + require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + + call := mockedService.ExpectedCalls[0] + + assert.Equal(t, "TheExampleMethod", call.Method) + assert.Equal(t, "A", call.Arguments[0]) + assert.Equal(t, "B", call.Arguments[1]) + assert.Equal(t, true, call.Arguments[2]) + assert.Equal(t, 1, call.ReturnArguments[0]) + assert.Equal(t, "two", call.ReturnArguments[1]) + assert.Equal(t, true, call.ReturnArguments[2]) + assert.Equal(t, 0, call.Repeatability) + assert.Equal(t, ch, call.WaitFor) +} + +func Test_Mock_Return_After(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService.Mock. + On("TheExampleMethod", "A", "B", true). + Return(1, "two", true). + After(time.Second) + + require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + + call := mockedService.Mock.ExpectedCalls[0] + + assert.Equal(t, "TheExampleMethod", call.Method) + assert.Equal(t, "A", call.Arguments[0]) + assert.Equal(t, "B", call.Arguments[1]) + assert.Equal(t, true, call.Arguments[2]) + assert.Equal(t, 1, call.ReturnArguments[0]) + assert.Equal(t, "two", call.ReturnArguments[1]) + assert.Equal(t, true, call.ReturnArguments[2]) + assert.Equal(t, 0, call.Repeatability) + assert.NotEqual(t, nil, call.WaitFor) + +} + +func Test_Mock_Return_Run(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + fn := func(args Arguments) { + arg := args.Get(0).(*ExampleType) + arg.ran = true + } + + c := mockedService.Mock. + On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")). + Return(nil). + Run(fn) + + require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + + call := mockedService.Mock.ExpectedCalls[0] + + assert.Equal(t, "TheExampleMethod3", call.Method) + assert.Equal(t, AnythingOfType("*mock.ExampleType"), call.Arguments[0]) + assert.Equal(t, nil, call.ReturnArguments[0]) + assert.Equal(t, 0, call.Repeatability) + assert.NotEqual(t, nil, call.WaitFor) + assert.NotNil(t, call.Run) + + et := ExampleType{} + assert.Equal(t, false, et.ran) + mockedService.TheExampleMethod3(&et) + assert.Equal(t, true, et.ran) +} + +func Test_Mock_Return_Run_Out_Of_Order(t *testing.T) { + // make a test impl object + var mockedService = new(TestExampleImplementation) + f := func(args Arguments) { + arg := args.Get(0).(*ExampleType) + arg.ran = true + } + + c := mockedService.Mock. + On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")). + Run(f). + Return(nil) + + require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + + call := mockedService.Mock.ExpectedCalls[0] + + assert.Equal(t, "TheExampleMethod3", call.Method) + assert.Equal(t, AnythingOfType("*mock.ExampleType"), call.Arguments[0]) + assert.Equal(t, nil, call.ReturnArguments[0]) + assert.Equal(t, 0, call.Repeatability) + assert.NotEqual(t, nil, call.WaitFor) + assert.NotNil(t, call.Run) +} + +func Test_Mock_Return_Once(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService.On("TheExampleMethod", "A", "B", true). + Return(1, "two", true). + Once() + + require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + + call := mockedService.ExpectedCalls[0] + + assert.Equal(t, "TheExampleMethod", call.Method) + assert.Equal(t, "A", call.Arguments[0]) + assert.Equal(t, "B", call.Arguments[1]) + assert.Equal(t, true, call.Arguments[2]) + assert.Equal(t, 1, call.ReturnArguments[0]) + assert.Equal(t, "two", call.ReturnArguments[1]) + assert.Equal(t, true, call.ReturnArguments[2]) + assert.Equal(t, 1, call.Repeatability) + assert.Nil(t, call.WaitFor) +} + +func Test_Mock_Return_Twice(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService. + On("TheExampleMethod", "A", "B", true). + Return(1, "two", true). + Twice() + + require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + + call := mockedService.ExpectedCalls[0] + + assert.Equal(t, "TheExampleMethod", call.Method) + assert.Equal(t, "A", call.Arguments[0]) + assert.Equal(t, "B", call.Arguments[1]) + assert.Equal(t, true, call.Arguments[2]) + assert.Equal(t, 1, call.ReturnArguments[0]) + assert.Equal(t, "two", call.ReturnArguments[1]) + assert.Equal(t, true, call.ReturnArguments[2]) + assert.Equal(t, 2, call.Repeatability) + assert.Nil(t, call.WaitFor) +} + +func Test_Mock_Return_Times(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService. + On("TheExampleMethod", "A", "B", true). + Return(1, "two", true). + Times(5) + + require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + + call := mockedService.ExpectedCalls[0] + + assert.Equal(t, "TheExampleMethod", call.Method) + assert.Equal(t, "A", call.Arguments[0]) + assert.Equal(t, "B", call.Arguments[1]) + assert.Equal(t, true, call.Arguments[2]) + assert.Equal(t, 1, call.ReturnArguments[0]) + assert.Equal(t, "two", call.ReturnArguments[1]) + assert.Equal(t, true, call.ReturnArguments[2]) + assert.Equal(t, 5, call.Repeatability) + assert.Nil(t, call.WaitFor) +} + +func Test_Mock_Return_Nothing(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService. + On("TheExampleMethod", "A", "B", true). + Return() + + require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + + call := mockedService.ExpectedCalls[0] + + assert.Equal(t, "TheExampleMethod", call.Method) + assert.Equal(t, "A", call.Arguments[0]) + assert.Equal(t, "B", call.Arguments[1]) + assert.Equal(t, true, call.Arguments[2]) + assert.Equal(t, 0, len(call.ReturnArguments)) +} + +func Test_Mock_findExpectedCall(t *testing.T) { + + m := new(Mock) + m.On("One", 1).Return("one") + m.On("Two", 2).Return("two") + m.On("Two", 3).Return("three") + + f, c := m.findExpectedCall("Two", 3) + + if assert.Equal(t, 2, f) { + if assert.NotNil(t, c) { + assert.Equal(t, "Two", c.Method) + assert.Equal(t, 3, c.Arguments[0]) + assert.Equal(t, "three", c.ReturnArguments[0]) + } + } + +} + +func Test_Mock_findExpectedCall_For_Unknown_Method(t *testing.T) { + + m := new(Mock) + m.On("One", 1).Return("one") + m.On("Two", 2).Return("two") + m.On("Two", 3).Return("three") + + f, _ := m.findExpectedCall("Two") + + assert.Equal(t, -1, f) + +} + +func Test_Mock_findExpectedCall_Respects_Repeatability(t *testing.T) { + + m := new(Mock) + m.On("One", 1).Return("one") + m.On("Two", 2).Return("two").Once() + m.On("Two", 3).Return("three").Twice() + m.On("Two", 3).Return("three").Times(8) + + f, c := m.findExpectedCall("Two", 3) + + if assert.Equal(t, 2, f) { + if assert.NotNil(t, c) { + assert.Equal(t, "Two", c.Method) + assert.Equal(t, 3, c.Arguments[0]) + assert.Equal(t, "three", c.ReturnArguments[0]) + } + } + +} + +func Test_callString(t *testing.T) { + + assert.Equal(t, `Method(int,bool,string)`, callString("Method", []interface{}{1, true, "something"}, false)) + +} + +func Test_Mock_Called(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_Called", 1, 2, 3).Return(5, "6", true) + + returnArguments := mockedService.Called(1, 2, 3) + + if assert.Equal(t, 1, len(mockedService.Calls)) { + assert.Equal(t, "Test_Mock_Called", mockedService.Calls[0].Method) + assert.Equal(t, 1, mockedService.Calls[0].Arguments[0]) + assert.Equal(t, 2, mockedService.Calls[0].Arguments[1]) + assert.Equal(t, 3, mockedService.Calls[0].Arguments[2]) + } + + if assert.Equal(t, 3, len(returnArguments)) { + assert.Equal(t, 5, returnArguments[0]) + assert.Equal(t, "6", returnArguments[1]) + assert.Equal(t, true, returnArguments[2]) + } + +} + +func asyncCall(m *Mock, ch chan Arguments) { + ch <- m.Called(1, 2, 3) +} + +func Test_Mock_Called_blocks(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.Mock.On("asyncCall", 1, 2, 3).Return(5, "6", true).After(2 * time.Millisecond) + + ch := make(chan Arguments) + + go asyncCall(&mockedService.Mock, ch) + + select { + case <-ch: + t.Fatal("should have waited") + case <-time.After(1 * time.Millisecond): + } + + returnArguments := <-ch + + if assert.Equal(t, 1, len(mockedService.Mock.Calls)) { + assert.Equal(t, "asyncCall", mockedService.Mock.Calls[0].Method) + assert.Equal(t, 1, mockedService.Mock.Calls[0].Arguments[0]) + assert.Equal(t, 2, mockedService.Mock.Calls[0].Arguments[1]) + assert.Equal(t, 3, mockedService.Mock.Calls[0].Arguments[2]) + } + + if assert.Equal(t, 3, len(returnArguments)) { + assert.Equal(t, 5, returnArguments[0]) + assert.Equal(t, "6", returnArguments[1]) + assert.Equal(t, true, returnArguments[2]) + } + +} + +func Test_Mock_Called_For_Bounded_Repeatability(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService. + On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3). + Return(5, "6", true). + Once() + mockedService. + On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3). + Return(-1, "hi", false) + + returnArguments1 := mockedService.Called(1, 2, 3) + returnArguments2 := mockedService.Called(1, 2, 3) + + if assert.Equal(t, 2, len(mockedService.Calls)) { + assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[0].Method) + assert.Equal(t, 1, mockedService.Calls[0].Arguments[0]) + assert.Equal(t, 2, mockedService.Calls[0].Arguments[1]) + assert.Equal(t, 3, mockedService.Calls[0].Arguments[2]) + + assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[1].Method) + assert.Equal(t, 1, mockedService.Calls[1].Arguments[0]) + assert.Equal(t, 2, mockedService.Calls[1].Arguments[1]) + assert.Equal(t, 3, mockedService.Calls[1].Arguments[2]) + } + + if assert.Equal(t, 3, len(returnArguments1)) { + assert.Equal(t, 5, returnArguments1[0]) + assert.Equal(t, "6", returnArguments1[1]) + assert.Equal(t, true, returnArguments1[2]) + } + + if assert.Equal(t, 3, len(returnArguments2)) { + assert.Equal(t, -1, returnArguments2[0]) + assert.Equal(t, "hi", returnArguments2[1]) + assert.Equal(t, false, returnArguments2[2]) + } + +} + +func Test_Mock_Called_For_SetTime_Expectation(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("TheExampleMethod", 1, 2, 3).Return(5, "6", true).Times(4) + + mockedService.TheExampleMethod(1, 2, 3) + mockedService.TheExampleMethod(1, 2, 3) + mockedService.TheExampleMethod(1, 2, 3) + mockedService.TheExampleMethod(1, 2, 3) + assert.Panics(t, func() { + mockedService.TheExampleMethod(1, 2, 3) + }) + +} + +func Test_Mock_Called_Unexpected(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + // make sure it panics if no expectation was made + assert.Panics(t, func() { + mockedService.Called(1, 2, 3) + }, "Calling unexpected method should panic") + +} + +func Test_AssertExpectationsForObjects_Helper(t *testing.T) { + + var mockedService1 = new(TestExampleImplementation) + var mockedService2 = new(TestExampleImplementation) + var mockedService3 = new(TestExampleImplementation) + + mockedService1.On("Test_AssertExpectationsForObjects_Helper", 1).Return() + mockedService2.On("Test_AssertExpectationsForObjects_Helper", 2).Return() + mockedService3.On("Test_AssertExpectationsForObjects_Helper", 3).Return() + + mockedService1.Called(1) + mockedService2.Called(2) + mockedService3.Called(3) + + assert.True(t, AssertExpectationsForObjects(t, mockedService1.Mock, mockedService2.Mock, mockedService3.Mock)) + +} + +func Test_AssertExpectationsForObjects_Helper_Failed(t *testing.T) { + + var mockedService1 = new(TestExampleImplementation) + var mockedService2 = new(TestExampleImplementation) + var mockedService3 = new(TestExampleImplementation) + + mockedService1.On("Test_AssertExpectationsForObjects_Helper_Failed", 1).Return() + mockedService2.On("Test_AssertExpectationsForObjects_Helper_Failed", 2).Return() + mockedService3.On("Test_AssertExpectationsForObjects_Helper_Failed", 3).Return() + + mockedService1.Called(1) + mockedService3.Called(3) + + tt := new(testing.T) + assert.False(t, AssertExpectationsForObjects(tt, mockedService1.Mock, mockedService2.Mock, mockedService3.Mock)) + +} + +func Test_Mock_AssertExpectations(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertExpectations", 1, 2, 3).Return(5, 6, 7) + + tt := new(testing.T) + assert.False(t, mockedService.AssertExpectations(tt)) + + // make the call now + mockedService.Called(1, 2, 3) + + // now assert expectations + assert.True(t, mockedService.AssertExpectations(tt)) + +} + +func Test_Mock_AssertExpectations_Placeholder_NoArgs(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertExpectations_Placeholder_NoArgs").Return(5, 6, 7).Once() + mockedService.On("Test_Mock_AssertExpectations_Placeholder_NoArgs").Return(7, 6, 5) + + tt := new(testing.T) + assert.False(t, mockedService.AssertExpectations(tt)) + + // make the call now + mockedService.Called() + + // now assert expectations + assert.True(t, mockedService.AssertExpectations(tt)) + +} + +func Test_Mock_AssertExpectations_Placeholder(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertExpectations_Placeholder", 1, 2, 3).Return(5, 6, 7).Once() + mockedService.On("Test_Mock_AssertExpectations_Placeholder", 3, 2, 1).Return(7, 6, 5) + + tt := new(testing.T) + assert.False(t, mockedService.AssertExpectations(tt)) + + // make the call now + mockedService.Called(1, 2, 3) + + // now assert expectations + assert.False(t, mockedService.AssertExpectations(tt)) + + // make call to the second expectation + mockedService.Called(3, 2, 1) + + // now assert expectations again + assert.True(t, mockedService.AssertExpectations(tt)) +} + +func Test_Mock_AssertExpectations_With_Pointers(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertExpectations_With_Pointers", &struct{ Foo int }{1}).Return(1) + mockedService.On("Test_Mock_AssertExpectations_With_Pointers", &struct{ Foo int }{2}).Return(2) + + tt := new(testing.T) + assert.False(t, mockedService.AssertExpectations(tt)) + + s := struct{ Foo int }{1} + // make the calls now + mockedService.Called(&s) + s.Foo = 2 + mockedService.Called(&s) + + // now assert expectations + assert.True(t, mockedService.AssertExpectations(tt)) + +} + +func Test_Mock_AssertExpectationsCustomType(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).Return(nil).Once() + + tt := new(testing.T) + assert.False(t, mockedService.AssertExpectations(tt)) + + // make the call now + mockedService.TheExampleMethod3(&ExampleType{}) + + // now assert expectations + assert.True(t, mockedService.AssertExpectations(tt)) + +} + +func Test_Mock_AssertExpectations_With_Repeatability(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertExpectations_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Twice() + + tt := new(testing.T) + assert.False(t, mockedService.AssertExpectations(tt)) + + // make the call now + mockedService.Called(1, 2, 3) + + assert.False(t, mockedService.AssertExpectations(tt)) + + mockedService.Called(1, 2, 3) + + // now assert expectations + assert.True(t, mockedService.AssertExpectations(tt)) + +} + +func Test_Mock_TwoCallsWithDifferentArguments(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_TwoCallsWithDifferentArguments", 1, 2, 3).Return(5, 6, 7) + mockedService.On("Test_Mock_TwoCallsWithDifferentArguments", 4, 5, 6).Return(5, 6, 7) + + args1 := mockedService.Called(1, 2, 3) + assert.Equal(t, 5, args1.Int(0)) + assert.Equal(t, 6, args1.Int(1)) + assert.Equal(t, 7, args1.Int(2)) + + args2 := mockedService.Called(4, 5, 6) + assert.Equal(t, 5, args2.Int(0)) + assert.Equal(t, 6, args2.Int(1)) + assert.Equal(t, 7, args2.Int(2)) + +} + +func Test_Mock_AssertNumberOfCalls(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertNumberOfCalls", 1, 2, 3).Return(5, 6, 7) + + mockedService.Called(1, 2, 3) + assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 1)) + + mockedService.Called(1, 2, 3) + assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 2)) + +} + +func Test_Mock_AssertCalled(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertCalled", 1, 2, 3).Return(5, 6, 7) + + mockedService.Called(1, 2, 3) + + assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled", 1, 2, 3)) + +} + +func Test_Mock_AssertCalled_WithAnythingOfTypeArgument(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService. + On("Test_Mock_AssertCalled_WithAnythingOfTypeArgument", Anything, Anything, Anything). + Return() + + mockedService.Called(1, "two", []uint8("three")) + + assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled_WithAnythingOfTypeArgument", AnythingOfType("int"), AnythingOfType("string"), AnythingOfType("[]uint8"))) + +} + +func Test_Mock_AssertCalled_WithArguments(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertCalled_WithArguments", 1, 2, 3).Return(5, 6, 7) + + mockedService.Called(1, 2, 3) + + tt := new(testing.T) + assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 1, 2, 3)) + assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 2, 3, 4)) + +} + +func Test_Mock_AssertCalled_WithArguments_With_Repeatability(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Once() + mockedService.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4).Return(5, 6, 7).Once() + + mockedService.Called(1, 2, 3) + mockedService.Called(2, 3, 4) + + tt := new(testing.T) + assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3)) + assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4)) + assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 3, 4, 5)) + +} + +func Test_Mock_AssertNotCalled(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertNotCalled", 1, 2, 3).Return(5, 6, 7) + + mockedService.Called(1, 2, 3) + + assert.True(t, mockedService.AssertNotCalled(t, "Test_Mock_NotCalled")) + +} + +/* + Arguments helper methods +*/ +func Test_Arguments_Get(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true}) + + assert.Equal(t, "string", args.Get(0).(string)) + assert.Equal(t, 123, args.Get(1).(int)) + assert.Equal(t, true, args.Get(2).(bool)) + +} + +func Test_Arguments_Is(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true}) + + assert.True(t, args.Is("string", 123, true)) + assert.False(t, args.Is("wrong", 456, false)) + +} + +func Test_Arguments_Diff(t *testing.T) { + + var args = Arguments([]interface{}{"Hello World", 123, true}) + var diff string + var count int + diff, count = args.Diff([]interface{}{"Hello World", 456, "false"}) + + assert.Equal(t, 2, count) + assert.Contains(t, diff, `%!s(int=456) != %!s(int=123)`) + assert.Contains(t, diff, `false != %!s(bool=true)`) + +} + +func Test_Arguments_Diff_DifferentNumberOfArgs(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true}) + var diff string + var count int + diff, count = args.Diff([]interface{}{"string", 456, "false", "extra"}) + + assert.Equal(t, 3, count) + assert.Contains(t, diff, `extra != (Missing)`) + +} + +func Test_Arguments_Diff_WithAnythingArgument(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true}) + var count int + _, count = args.Diff([]interface{}{"string", Anything, true}) + + assert.Equal(t, 0, count) + +} + +func Test_Arguments_Diff_WithAnythingArgument_InActualToo(t *testing.T) { + + var args = Arguments([]interface{}{"string", Anything, true}) + var count int + _, count = args.Diff([]interface{}{"string", 123, true}) + + assert.Equal(t, 0, count) + +} + +func Test_Arguments_Diff_WithAnythingOfTypeArgument(t *testing.T) { + + var args = Arguments([]interface{}{"string", AnythingOfType("int"), true}) + var count int + _, count = args.Diff([]interface{}{"string", 123, true}) + + assert.Equal(t, 0, count) + +} + +func Test_Arguments_Diff_WithAnythingOfTypeArgument_Failing(t *testing.T) { + + var args = Arguments([]interface{}{"string", AnythingOfType("string"), true}) + var count int + var diff string + diff, count = args.Diff([]interface{}{"string", 123, true}) + + assert.Equal(t, 1, count) + assert.Contains(t, diff, `string != type int - %!s(int=123)`) + +} + +func Test_Arguments_Diff_WithArgMatcher(t *testing.T) { + matchFn := func(a int) bool { + return a == 123 + } + var args = Arguments([]interface{}{"string", MatchedBy(matchFn), true}) + + diff, count := args.Diff([]interface{}{"string", 124, true}) + assert.Equal(t, 1, count) + assert.Contains(t, diff, `%!s(int=124) not matched by func(int) bool`) + + diff, count = args.Diff([]interface{}{"string", false, true}) + assert.Equal(t, 1, count) + assert.Contains(t, diff, `%!s(bool=false) not matched by func(int) bool`) + + diff, count = args.Diff([]interface{}{"string", 123, false}) + assert.Contains(t, diff, `%!s(int=123) matched by func(int) bool`) + + diff, count = args.Diff([]interface{}{"string", 123, true}) + assert.Equal(t, 0, count) + assert.Contains(t, diff, `No differences.`) +} + +func Test_Arguments_Assert(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true}) + + assert.True(t, args.Assert(t, "string", 123, true)) + +} + +func Test_Arguments_String_Representation(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true}) + assert.Equal(t, `string,int,bool`, args.String()) + +} + +func Test_Arguments_String(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true}) + assert.Equal(t, "string", args.String(0)) + +} + +func Test_Arguments_Error(t *testing.T) { + + var err = errors.New("An Error") + var args = Arguments([]interface{}{"string", 123, true, err}) + assert.Equal(t, err, args.Error(3)) + +} + +func Test_Arguments_Error_Nil(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true, nil}) + assert.Equal(t, nil, args.Error(3)) + +} + +func Test_Arguments_Int(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true}) + assert.Equal(t, 123, args.Int(1)) + +} + +func Test_Arguments_Bool(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true}) + assert.Equal(t, true, args.Bool(2)) + +} diff --git a/vendor/github.com/stretchr/testify/package_test.go b/vendor/github.com/stretchr/testify/package_test.go new file mode 100644 index 00000000..7ac5d6d8 --- /dev/null +++ b/vendor/github.com/stretchr/testify/package_test.go @@ -0,0 +1,12 @@ +package testify + +import ( + "github.com/stretchr/testify/assert" + "testing" +) + +func TestImports(t *testing.T) { + if assert.Equal(t, 1, 1) != true { + t.Error("Something is wrong.") + } +} diff --git a/vendor/github.com/stretchr/testify/require/doc.go b/vendor/github.com/stretchr/testify/require/doc.go new file mode 100644 index 00000000..169de392 --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/doc.go @@ -0,0 +1,28 @@ +// Package require implements the same assertions as the `assert` package but +// stops test execution when a test fails. +// +// Example Usage +// +// The following is a complete example using require in a standard test function: +// import ( +// "testing" +// "github.com/stretchr/testify/require" +// ) +// +// func TestSomething(t *testing.T) { +// +// var a string = "Hello" +// var b string = "Hello" +// +// require.Equal(t, a, b, "The two words should be the same.") +// +// } +// +// Assertions +// +// The `require` package have same global functions as in the `assert` package, +// but instead of returning a boolean result they call `t.FailNow()`. +// +// Every assertion function also takes an optional string message as the final argument, +// allowing custom error messages to be appended to the message the assertion method outputs. +package require diff --git a/vendor/github.com/stretchr/testify/require/forward_requirements.go b/vendor/github.com/stretchr/testify/require/forward_requirements.go new file mode 100644 index 00000000..d3c2ab9b --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/forward_requirements.go @@ -0,0 +1,16 @@ +package require + +// Assertions provides assertion methods around the +// TestingT interface. +type Assertions struct { + t TestingT +} + +// New makes a new Assertions object for the specified TestingT. +func New(t TestingT) *Assertions { + return &Assertions{ + t: t, + } +} + +//go:generate go run ../_codegen/main.go -output-package=require -template=require_forward.go.tmpl diff --git a/vendor/github.com/stretchr/testify/require/forward_requirements_test.go b/vendor/github.com/stretchr/testify/require/forward_requirements_test.go new file mode 100644 index 00000000..b120ae3b --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/forward_requirements_test.go @@ -0,0 +1,385 @@ +package require + +import ( + "errors" + "testing" + "time" +) + +func TestImplementsWrapper(t *testing.T) { + require := New(t) + + require.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestIsTypeWrapper(t *testing.T) { + require := New(t) + require.IsType(new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.IsType(new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestEqualWrapper(t *testing.T) { + require := New(t) + require.Equal(1, 1) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.Equal(1, 2) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotEqualWrapper(t *testing.T) { + require := New(t) + require.NotEqual(1, 2) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.NotEqual(2, 2) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestExactlyWrapper(t *testing.T) { + require := New(t) + + a := float32(1) + b := float32(1) + c := float64(1) + + require.Exactly(a, b) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.Exactly(a, c) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotNilWrapper(t *testing.T) { + require := New(t) + require.NotNil(t, new(AssertionTesterConformingObject)) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.NotNil(nil) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNilWrapper(t *testing.T) { + require := New(t) + require.Nil(nil) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.Nil(new(AssertionTesterConformingObject)) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestTrueWrapper(t *testing.T) { + require := New(t) + require.True(true) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.True(false) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestFalseWrapper(t *testing.T) { + require := New(t) + require.False(false) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.False(true) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestContainsWrapper(t *testing.T) { + require := New(t) + require.Contains("Hello World", "Hello") + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.Contains("Hello World", "Salut") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotContainsWrapper(t *testing.T) { + require := New(t) + require.NotContains("Hello World", "Hello!") + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.NotContains("Hello World", "Hello") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestPanicsWrapper(t *testing.T) { + require := New(t) + require.Panics(func() { + panic("Panic!") + }) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.Panics(func() {}) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotPanicsWrapper(t *testing.T) { + require := New(t) + require.NotPanics(func() {}) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.NotPanics(func() { + panic("Panic!") + }) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNoErrorWrapper(t *testing.T) { + require := New(t) + require.NoError(nil) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.NoError(errors.New("some error")) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestErrorWrapper(t *testing.T) { + require := New(t) + require.Error(errors.New("some error")) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.Error(nil) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestEqualErrorWrapper(t *testing.T) { + require := New(t) + require.EqualError(errors.New("some error"), "some error") + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.EqualError(errors.New("some error"), "Not some error") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestEmptyWrapper(t *testing.T) { + require := New(t) + require.Empty("") + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.Empty("x") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotEmptyWrapper(t *testing.T) { + require := New(t) + require.NotEmpty("x") + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.NotEmpty("") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestWithinDurationWrapper(t *testing.T) { + require := New(t) + a := time.Now() + b := a.Add(10 * time.Second) + + require.WithinDuration(a, b, 15*time.Second) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.WithinDuration(a, b, 5*time.Second) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestInDeltaWrapper(t *testing.T) { + require := New(t) + require.InDelta(1.001, 1, 0.01) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.InDelta(1, 2, 0.5) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestZeroWrapper(t *testing.T) { + require := New(t) + require.Zero(0) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.Zero(1) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotZeroWrapper(t *testing.T) { + require := New(t) + require.NotZero(1) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.NotZero(0) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEqWrapper_EqualSONString(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`) + if mockT.Failed { + t.Error("Check should pass") + } +} + +func TestJSONEqWrapper_EquivalentButNotEqual(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) + if mockT.Failed { + t.Error("Check should pass") + } +} + +func TestJSONEqWrapper_HashOfArraysAndHashes(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq("{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}", + "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}") + if mockT.Failed { + t.Error("Check should pass") + } +} + +func TestJSONEqWrapper_Array(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`) + if mockT.Failed { + t.Error("Check should pass") + } +} + +func TestJSONEqWrapper_HashAndArrayNotEquivalent(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEqWrapper_HashesNotEquivalent(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq(`{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEqWrapper_ActualIsNotJSON(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq(`{"foo": "bar"}`, "Not JSON") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEqWrapper_ExpectedIsNotJSON(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq("Not JSON", `{"foo": "bar", "hello": "world"}`) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEqWrapper_ExpectedAndActualNotJSON(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq("Not JSON", "Not JSON") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEqWrapper_ArraysOfDifferentOrder(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`) + if !mockT.Failed { + t.Error("Check should fail") + } +} diff --git a/vendor/github.com/stretchr/testify/require/require.go b/vendor/github.com/stretchr/testify/require/require.go new file mode 100644 index 00000000..1bcfcb0d --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/require.go @@ -0,0 +1,464 @@ +/* +* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen +* THIS FILE MUST NOT BE EDITED BY HAND +*/ + +package require + +import ( + + assert "github.com/stretchr/testify/assert" + http "net/http" + url "net/url" + time "time" +) + + +// Condition uses a Comparison to assert a complex condition. +func Condition(t TestingT, comp assert.Comparison, msgAndArgs ...interface{}) { + if !assert.Condition(t, comp, msgAndArgs...) { + t.FailNow() + } +} + + +// Contains asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'") +// assert.Contains(t, ["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") +// assert.Contains(t, {"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'") +// +// Returns whether the assertion was successful (true) or not (false). +func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { + if !assert.Contains(t, s, contains, msgAndArgs...) { + t.FailNow() + } +} + + +// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// assert.Empty(t, obj) +// +// Returns whether the assertion was successful (true) or not (false). +func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) { + if !assert.Empty(t, object, msgAndArgs...) { + t.FailNow() + } +} + + +// Equal asserts that two objects are equal. +// +// assert.Equal(t, 123, 123, "123 and 123 should be equal") +// +// Returns whether the assertion was successful (true) or not (false). +func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if !assert.Equal(t, expected, actual, msgAndArgs...) { + t.FailNow() + } +} + + +// EqualError asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// if assert.Error(t, err, "An error was expected") { +// assert.Equal(t, err, expectedError) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) { + if !assert.EqualError(t, theError, errString, msgAndArgs...) { + t.FailNow() + } +} + + +// EqualValues asserts that two objects are equal or convertable to the same types +// and equal. +// +// assert.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal") +// +// Returns whether the assertion was successful (true) or not (false). +func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if !assert.EqualValues(t, expected, actual, msgAndArgs...) { + t.FailNow() + } +} + + +// Error asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if assert.Error(t, err, "An error was expected") { +// assert.Equal(t, err, expectedError) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func Error(t TestingT, err error, msgAndArgs ...interface{}) { + if !assert.Error(t, err, msgAndArgs...) { + t.FailNow() + } +} + + +// Exactly asserts that two objects are equal is value and type. +// +// assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal") +// +// Returns whether the assertion was successful (true) or not (false). +func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if !assert.Exactly(t, expected, actual, msgAndArgs...) { + t.FailNow() + } +} + + +// Fail reports a failure through +func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) { + if !assert.Fail(t, failureMessage, msgAndArgs...) { + t.FailNow() + } +} + + +// FailNow fails test +func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) { + if !assert.FailNow(t, failureMessage, msgAndArgs...) { + t.FailNow() + } +} + + +// False asserts that the specified value is false. +// +// assert.False(t, myBool, "myBool should be false") +// +// Returns whether the assertion was successful (true) or not (false). +func False(t TestingT, value bool, msgAndArgs ...interface{}) { + if !assert.False(t, value, msgAndArgs...) { + t.FailNow() + } +} + + +// HTTPBodyContains asserts that a specified handler returns a +// body that contains a string. +// +// assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { + if !assert.HTTPBodyContains(t, handler, method, url, values, str) { + t.FailNow() + } +} + + +// HTTPBodyNotContains asserts that a specified handler returns a +// body that does not contain a string. +// +// assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { + if !assert.HTTPBodyNotContains(t, handler, method, url, values, str) { + t.FailNow() + } +} + + +// HTTPError asserts that a specified handler returns an error status code. +// +// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) { + if !assert.HTTPError(t, handler, method, url, values) { + t.FailNow() + } +} + + +// HTTPRedirect asserts that a specified handler returns a redirect status code. +// +// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) { + if !assert.HTTPRedirect(t, handler, method, url, values) { + t.FailNow() + } +} + + +// HTTPSuccess asserts that a specified handler returns a success status code. +// +// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) { + if !assert.HTTPSuccess(t, handler, method, url, values) { + t.FailNow() + } +} + + +// Implements asserts that an object is implemented by the specified interface. +// +// assert.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject") +func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { + if !assert.Implements(t, interfaceObject, object, msgAndArgs...) { + t.FailNow() + } +} + + +// InDelta asserts that the two numerals are within delta of each other. +// +// assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) +// +// Returns whether the assertion was successful (true) or not (false). +func InDelta(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { + if !assert.InDelta(t, expected, actual, delta, msgAndArgs...) { + t.FailNow() + } +} + + +// InDeltaSlice is the same as InDelta, except it compares two slices. +func InDeltaSlice(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { + if !assert.InDeltaSlice(t, expected, actual, delta, msgAndArgs...) { + t.FailNow() + } +} + + +// InEpsilon asserts that expected and actual have a relative error less than epsilon +// +// Returns whether the assertion was successful (true) or not (false). +func InEpsilon(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { + if !assert.InEpsilon(t, expected, actual, epsilon, msgAndArgs...) { + t.FailNow() + } +} + + +// InEpsilonSlice is the same as InEpsilon, except it compares two slices. +func InEpsilonSlice(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { + if !assert.InEpsilonSlice(t, expected, actual, delta, msgAndArgs...) { + t.FailNow() + } +} + + +// IsType asserts that the specified objects are of the same type. +func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { + if !assert.IsType(t, expectedType, object, msgAndArgs...) { + t.FailNow() + } +} + + +// JSONEq asserts that two JSON strings are equivalent. +// +// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) +// +// Returns whether the assertion was successful (true) or not (false). +func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) { + if !assert.JSONEq(t, expected, actual, msgAndArgs...) { + t.FailNow() + } +} + + +// Len asserts that the specified object has specific length. +// Len also fails if the object has a type that len() not accept. +// +// assert.Len(t, mySlice, 3, "The size of slice is not 3") +// +// Returns whether the assertion was successful (true) or not (false). +func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) { + if !assert.Len(t, object, length, msgAndArgs...) { + t.FailNow() + } +} + + +// Nil asserts that the specified object is nil. +// +// assert.Nil(t, err, "err should be nothing") +// +// Returns whether the assertion was successful (true) or not (false). +func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) { + if !assert.Nil(t, object, msgAndArgs...) { + t.FailNow() + } +} + + +// NoError asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if assert.NoError(t, err) { +// assert.Equal(t, actualObj, expectedObj) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func NoError(t TestingT, err error, msgAndArgs ...interface{}) { + if !assert.NoError(t, err, msgAndArgs...) { + t.FailNow() + } +} + + +// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") +// assert.NotContains(t, ["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") +// assert.NotContains(t, {"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'") +// +// Returns whether the assertion was successful (true) or not (false). +func NotContains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { + if !assert.NotContains(t, s, contains, msgAndArgs...) { + t.FailNow() + } +} + + +// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if assert.NotEmpty(t, obj) { +// assert.Equal(t, "two", obj[1]) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) { + if !assert.NotEmpty(t, object, msgAndArgs...) { + t.FailNow() + } +} + + +// NotEqual asserts that the specified values are NOT equal. +// +// assert.NotEqual(t, obj1, obj2, "two objects shouldn't be equal") +// +// Returns whether the assertion was successful (true) or not (false). +func NotEqual(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if !assert.NotEqual(t, expected, actual, msgAndArgs...) { + t.FailNow() + } +} + + +// NotNil asserts that the specified object is not nil. +// +// assert.NotNil(t, err, "err should be something") +// +// Returns whether the assertion was successful (true) or not (false). +func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) { + if !assert.NotNil(t, object, msgAndArgs...) { + t.FailNow() + } +} + + +// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// assert.NotPanics(t, func(){ +// RemainCalm() +// }, "Calling RemainCalm() should NOT panic") +// +// Returns whether the assertion was successful (true) or not (false). +func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { + if !assert.NotPanics(t, f, msgAndArgs...) { + t.FailNow() + } +} + + +// NotRegexp asserts that a specified regexp does not match a string. +// +// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") +// assert.NotRegexp(t, "^start", "it's not starting") +// +// Returns whether the assertion was successful (true) or not (false). +func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { + if !assert.NotRegexp(t, rx, str, msgAndArgs...) { + t.FailNow() + } +} + + +// NotZero asserts that i is not the zero value for its type and returns the truth. +func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) { + if !assert.NotZero(t, i, msgAndArgs...) { + t.FailNow() + } +} + + +// Panics asserts that the code inside the specified PanicTestFunc panics. +// +// assert.Panics(t, func(){ +// GoCrazy() +// }, "Calling GoCrazy() should panic") +// +// Returns whether the assertion was successful (true) or not (false). +func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { + if !assert.Panics(t, f, msgAndArgs...) { + t.FailNow() + } +} + + +// Regexp asserts that a specified regexp matches a string. +// +// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") +// assert.Regexp(t, "start...$", "it's not starting") +// +// Returns whether the assertion was successful (true) or not (false). +func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { + if !assert.Regexp(t, rx, str, msgAndArgs...) { + t.FailNow() + } +} + + +// True asserts that the specified value is true. +// +// assert.True(t, myBool, "myBool should be true") +// +// Returns whether the assertion was successful (true) or not (false). +func True(t TestingT, value bool, msgAndArgs ...interface{}) { + if !assert.True(t, value, msgAndArgs...) { + t.FailNow() + } +} + + +// WithinDuration asserts that the two times are within duration delta of each other. +// +// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") +// +// Returns whether the assertion was successful (true) or not (false). +func WithinDuration(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { + if !assert.WithinDuration(t, expected, actual, delta, msgAndArgs...) { + t.FailNow() + } +} + + +// Zero asserts that i is the zero value for its type and returns the truth. +func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) { + if !assert.Zero(t, i, msgAndArgs...) { + t.FailNow() + } +} diff --git a/vendor/github.com/stretchr/testify/require/require.go.tmpl b/vendor/github.com/stretchr/testify/require/require.go.tmpl new file mode 100644 index 00000000..ab1b1e9f --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/require.go.tmpl @@ -0,0 +1,6 @@ +{{.Comment}} +func {{.DocInfo.Name}}(t TestingT, {{.Params}}) { + if !assert.{{.DocInfo.Name}}(t, {{.ForwardedParams}}) { + t.FailNow() + } +} diff --git a/vendor/github.com/stretchr/testify/require/require_forward.go b/vendor/github.com/stretchr/testify/require/require_forward.go new file mode 100644 index 00000000..58324f10 --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/require_forward.go @@ -0,0 +1,388 @@ +/* +* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen +* THIS FILE MUST NOT BE EDITED BY HAND +*/ + +package require + +import ( + + assert "github.com/stretchr/testify/assert" + http "net/http" + url "net/url" + time "time" +) + + +// Condition uses a Comparison to assert a complex condition. +func (a *Assertions) Condition(comp assert.Comparison, msgAndArgs ...interface{}) { + Condition(a.t, comp, msgAndArgs...) +} + + +// Contains asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// a.Contains("Hello World", "World", "But 'Hello World' does contain 'World'") +// a.Contains(["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") +// a.Contains({"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { + Contains(a.t, s, contains, msgAndArgs...) +} + + +// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// a.Empty(obj) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) { + Empty(a.t, object, msgAndArgs...) +} + + +// Equal asserts that two objects are equal. +// +// a.Equal(123, 123, "123 and 123 should be equal") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + Equal(a.t, expected, actual, msgAndArgs...) +} + + +// EqualError asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// if assert.Error(t, err, "An error was expected") { +// assert.Equal(t, err, expectedError) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) { + EqualError(a.t, theError, errString, msgAndArgs...) +} + + +// EqualValues asserts that two objects are equal or convertable to the same types +// and equal. +// +// a.EqualValues(uint32(123), int32(123), "123 and 123 should be equal") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + EqualValues(a.t, expected, actual, msgAndArgs...) +} + + +// Error asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if a.Error(err, "An error was expected") { +// assert.Equal(t, err, expectedError) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Error(err error, msgAndArgs ...interface{}) { + Error(a.t, err, msgAndArgs...) +} + + +// Exactly asserts that two objects are equal is value and type. +// +// a.Exactly(int32(123), int64(123), "123 and 123 should NOT be equal") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + Exactly(a.t, expected, actual, msgAndArgs...) +} + + +// Fail reports a failure through +func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) { + Fail(a.t, failureMessage, msgAndArgs...) +} + + +// FailNow fails test +func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) { + FailNow(a.t, failureMessage, msgAndArgs...) +} + + +// False asserts that the specified value is false. +// +// a.False(myBool, "myBool should be false") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) False(value bool, msgAndArgs ...interface{}) { + False(a.t, value, msgAndArgs...) +} + + +// HTTPBodyContains asserts that a specified handler returns a +// body that contains a string. +// +// a.HTTPBodyContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { + HTTPBodyContains(a.t, handler, method, url, values, str) +} + + +// HTTPBodyNotContains asserts that a specified handler returns a +// body that does not contain a string. +// +// a.HTTPBodyNotContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { + HTTPBodyNotContains(a.t, handler, method, url, values, str) +} + + +// HTTPError asserts that a specified handler returns an error status code. +// +// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values) { + HTTPError(a.t, handler, method, url, values) +} + + +// HTTPRedirect asserts that a specified handler returns a redirect status code. +// +// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values) { + HTTPRedirect(a.t, handler, method, url, values) +} + + +// HTTPSuccess asserts that a specified handler returns a success status code. +// +// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values) { + HTTPSuccess(a.t, handler, method, url, values) +} + + +// Implements asserts that an object is implemented by the specified interface. +// +// a.Implements((*MyInterface)(nil), new(MyObject), "MyObject") +func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { + Implements(a.t, interfaceObject, object, msgAndArgs...) +} + + +// InDelta asserts that the two numerals are within delta of each other. +// +// a.InDelta(math.Pi, (22 / 7.0), 0.01) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { + InDelta(a.t, expected, actual, delta, msgAndArgs...) +} + + +// InDeltaSlice is the same as InDelta, except it compares two slices. +func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { + InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) +} + + +// InEpsilon asserts that expected and actual have a relative error less than epsilon +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { + InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) +} + + +// InEpsilonSlice is the same as InEpsilon, except it compares two slices. +func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { + InEpsilonSlice(a.t, expected, actual, delta, msgAndArgs...) +} + + +// IsType asserts that the specified objects are of the same type. +func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { + IsType(a.t, expectedType, object, msgAndArgs...) +} + + +// JSONEq asserts that two JSON strings are equivalent. +// +// a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) { + JSONEq(a.t, expected, actual, msgAndArgs...) +} + + +// Len asserts that the specified object has specific length. +// Len also fails if the object has a type that len() not accept. +// +// a.Len(mySlice, 3, "The size of slice is not 3") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) { + Len(a.t, object, length, msgAndArgs...) +} + + +// Nil asserts that the specified object is nil. +// +// a.Nil(err, "err should be nothing") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) { + Nil(a.t, object, msgAndArgs...) +} + + +// NoError asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if a.NoError(err) { +// assert.Equal(t, actualObj, expectedObj) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) { + NoError(a.t, err, msgAndArgs...) +} + + +// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// a.NotContains("Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") +// a.NotContains(["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") +// a.NotContains({"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { + NotContains(a.t, s, contains, msgAndArgs...) +} + + +// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if a.NotEmpty(obj) { +// assert.Equal(t, "two", obj[1]) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) { + NotEmpty(a.t, object, msgAndArgs...) +} + + +// NotEqual asserts that the specified values are NOT equal. +// +// a.NotEqual(obj1, obj2, "two objects shouldn't be equal") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + NotEqual(a.t, expected, actual, msgAndArgs...) +} + + +// NotNil asserts that the specified object is not nil. +// +// a.NotNil(err, "err should be something") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) { + NotNil(a.t, object, msgAndArgs...) +} + + +// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// a.NotPanics(func(){ +// RemainCalm() +// }, "Calling RemainCalm() should NOT panic") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotPanics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { + NotPanics(a.t, f, msgAndArgs...) +} + + +// NotRegexp asserts that a specified regexp does not match a string. +// +// a.NotRegexp(regexp.MustCompile("starts"), "it's starting") +// a.NotRegexp("^start", "it's not starting") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { + NotRegexp(a.t, rx, str, msgAndArgs...) +} + + +// NotZero asserts that i is not the zero value for its type and returns the truth. +func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) { + NotZero(a.t, i, msgAndArgs...) +} + + +// Panics asserts that the code inside the specified PanicTestFunc panics. +// +// a.Panics(func(){ +// GoCrazy() +// }, "Calling GoCrazy() should panic") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Panics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { + Panics(a.t, f, msgAndArgs...) +} + + +// Regexp asserts that a specified regexp matches a string. +// +// a.Regexp(regexp.MustCompile("start"), "it's starting") +// a.Regexp("start...$", "it's not starting") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { + Regexp(a.t, rx, str, msgAndArgs...) +} + + +// True asserts that the specified value is true. +// +// a.True(myBool, "myBool should be true") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) True(value bool, msgAndArgs ...interface{}) { + True(a.t, value, msgAndArgs...) +} + + +// WithinDuration asserts that the two times are within duration delta of each other. +// +// a.WithinDuration(time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { + WithinDuration(a.t, expected, actual, delta, msgAndArgs...) +} + + +// Zero asserts that i is the zero value for its type and returns the truth. +func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) { + Zero(a.t, i, msgAndArgs...) +} diff --git a/vendor/github.com/stretchr/testify/require/require_forward.go.tmpl b/vendor/github.com/stretchr/testify/require/require_forward.go.tmpl new file mode 100644 index 00000000..b93569e0 --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/require_forward.go.tmpl @@ -0,0 +1,4 @@ +{{.CommentWithoutT "a"}} +func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) { + {{.DocInfo.Name}}(a.t, {{.ForwardedParams}}) +} diff --git a/vendor/github.com/stretchr/testify/require/requirements.go b/vendor/github.com/stretchr/testify/require/requirements.go new file mode 100644 index 00000000..41147562 --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/requirements.go @@ -0,0 +1,9 @@ +package require + +// TestingT is an interface wrapper around *testing.T +type TestingT interface { + Errorf(format string, args ...interface{}) + FailNow() +} + +//go:generate go run ../_codegen/main.go -output-package=require -template=require.go.tmpl diff --git a/vendor/github.com/stretchr/testify/require/requirements_test.go b/vendor/github.com/stretchr/testify/require/requirements_test.go new file mode 100644 index 00000000..d2ccc99c --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/requirements_test.go @@ -0,0 +1,369 @@ +package require + +import ( + "errors" + "testing" + "time" +) + +// AssertionTesterInterface defines an interface to be used for testing assertion methods +type AssertionTesterInterface interface { + TestMethod() +} + +// AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface +type AssertionTesterConformingObject struct { +} + +func (a *AssertionTesterConformingObject) TestMethod() { +} + +// AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface +type AssertionTesterNonConformingObject struct { +} + +type MockT struct { + Failed bool +} + +func (t *MockT) FailNow() { + t.Failed = true +} + +func (t *MockT) Errorf(format string, args ...interface{}) { + _, _ = format, args +} + +func TestImplements(t *testing.T) { + + Implements(t, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) + + mockT := new(MockT) + Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestIsType(t *testing.T) { + + IsType(t, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) + + mockT := new(MockT) + IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestEqual(t *testing.T) { + + Equal(t, 1, 1) + + mockT := new(MockT) + Equal(mockT, 1, 2) + if !mockT.Failed { + t.Error("Check should fail") + } + +} + +func TestNotEqual(t *testing.T) { + + NotEqual(t, 1, 2) + mockT := new(MockT) + NotEqual(mockT, 2, 2) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestExactly(t *testing.T) { + + a := float32(1) + b := float32(1) + c := float64(1) + + Exactly(t, a, b) + + mockT := new(MockT) + Exactly(mockT, a, c) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotNil(t *testing.T) { + + NotNil(t, new(AssertionTesterConformingObject)) + + mockT := new(MockT) + NotNil(mockT, nil) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNil(t *testing.T) { + + Nil(t, nil) + + mockT := new(MockT) + Nil(mockT, new(AssertionTesterConformingObject)) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestTrue(t *testing.T) { + + True(t, true) + + mockT := new(MockT) + True(mockT, false) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestFalse(t *testing.T) { + + False(t, false) + + mockT := new(MockT) + False(mockT, true) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestContains(t *testing.T) { + + Contains(t, "Hello World", "Hello") + + mockT := new(MockT) + Contains(mockT, "Hello World", "Salut") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotContains(t *testing.T) { + + NotContains(t, "Hello World", "Hello!") + + mockT := new(MockT) + NotContains(mockT, "Hello World", "Hello") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestPanics(t *testing.T) { + + Panics(t, func() { + panic("Panic!") + }) + + mockT := new(MockT) + Panics(mockT, func() {}) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotPanics(t *testing.T) { + + NotPanics(t, func() {}) + + mockT := new(MockT) + NotPanics(mockT, func() { + panic("Panic!") + }) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNoError(t *testing.T) { + + NoError(t, nil) + + mockT := new(MockT) + NoError(mockT, errors.New("some error")) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestError(t *testing.T) { + + Error(t, errors.New("some error")) + + mockT := new(MockT) + Error(mockT, nil) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestEqualError(t *testing.T) { + + EqualError(t, errors.New("some error"), "some error") + + mockT := new(MockT) + EqualError(mockT, errors.New("some error"), "Not some error") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestEmpty(t *testing.T) { + + Empty(t, "") + + mockT := new(MockT) + Empty(mockT, "x") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotEmpty(t *testing.T) { + + NotEmpty(t, "x") + + mockT := new(MockT) + NotEmpty(mockT, "") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestWithinDuration(t *testing.T) { + + a := time.Now() + b := a.Add(10 * time.Second) + + WithinDuration(t, a, b, 15*time.Second) + + mockT := new(MockT) + WithinDuration(mockT, a, b, 5*time.Second) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestInDelta(t *testing.T) { + + InDelta(t, 1.001, 1, 0.01) + + mockT := new(MockT) + InDelta(mockT, 1, 2, 0.5) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestZero(t *testing.T) { + + Zero(t, "") + + mockT := new(MockT) + Zero(mockT, "x") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotZero(t *testing.T) { + + NotZero(t, "x") + + mockT := new(MockT) + NotZero(mockT, "") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEq_EqualSONString(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`) + if mockT.Failed { + t.Error("Check should pass") + } +} + +func TestJSONEq_EquivalentButNotEqual(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) + if mockT.Failed { + t.Error("Check should pass") + } +} + +func TestJSONEq_HashOfArraysAndHashes(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, "{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}", + "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}") + if mockT.Failed { + t.Error("Check should pass") + } +} + +func TestJSONEq_Array(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`) + if mockT.Failed { + t.Error("Check should pass") + } +} + +func TestJSONEq_HashAndArrayNotEquivalent(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEq_HashesNotEquivalent(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, `{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEq_ActualIsNotJSON(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, `{"foo": "bar"}`, "Not JSON") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEq_ExpectedIsNotJSON(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, "Not JSON", `{"foo": "bar", "hello": "world"}`) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEq_ExpectedAndActualNotJSON(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, "Not JSON", "Not JSON") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEq_ArraysOfDifferentOrder(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`) + if !mockT.Failed { + t.Error("Check should fail") + } +} diff --git a/vendor/github.com/stretchr/testify/suite/doc.go b/vendor/github.com/stretchr/testify/suite/doc.go new file mode 100644 index 00000000..f91a245d --- /dev/null +++ b/vendor/github.com/stretchr/testify/suite/doc.go @@ -0,0 +1,65 @@ +// Package suite contains logic for creating testing suite structs +// and running the methods on those structs as tests. The most useful +// piece of this package is that you can create setup/teardown methods +// on your testing suites, which will run before/after the whole suite +// or individual tests (depending on which interface(s) you +// implement). +// +// A testing suite is usually built by first extending the built-in +// suite functionality from suite.Suite in testify. Alternatively, +// you could reproduce that logic on your own if you wanted (you +// just need to implement the TestingSuite interface from +// suite/interfaces.go). +// +// After that, you can implement any of the interfaces in +// suite/interfaces.go to add setup/teardown functionality to your +// suite, and add any methods that start with "Test" to add tests. +// Methods that do not match any suite interfaces and do not begin +// with "Test" will not be run by testify, and can safely be used as +// helper methods. +// +// Once you've built your testing suite, you need to run the suite +// (using suite.Run from testify) inside any function that matches the +// identity that "go test" is already looking for (i.e. +// func(*testing.T)). +// +// Regular expression to select test suites specified command-line +// argument "-run". Regular expression to select the methods +// of test suites specified command-line argument "-m". +// Suite object has assertion methods. +// +// A crude example: +// // Basic imports +// import ( +// "testing" +// "github.com/stretchr/testify/assert" +// "github.com/stretchr/testify/suite" +// ) +// +// // Define the suite, and absorb the built-in basic suite +// // functionality from testify - including a T() method which +// // returns the current testing context +// type ExampleTestSuite struct { +// suite.Suite +// VariableThatShouldStartAtFive int +// } +// +// // Make sure that VariableThatShouldStartAtFive is set to five +// // before each test +// func (suite *ExampleTestSuite) SetupTest() { +// suite.VariableThatShouldStartAtFive = 5 +// } +// +// // All methods that begin with "Test" are run as tests within a +// // suite. +// func (suite *ExampleTestSuite) TestExample() { +// assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) +// suite.Equal(5, suite.VariableThatShouldStartAtFive) +// } +// +// // In order for 'go test' to run this suite, we need to create +// // a normal test function and pass our suite to suite.Run +// func TestExampleTestSuite(t *testing.T) { +// suite.Run(t, new(ExampleTestSuite)) +// } +package suite diff --git a/vendor/github.com/stretchr/testify/suite/interfaces.go b/vendor/github.com/stretchr/testify/suite/interfaces.go new file mode 100644 index 00000000..20969472 --- /dev/null +++ b/vendor/github.com/stretchr/testify/suite/interfaces.go @@ -0,0 +1,34 @@ +package suite + +import "testing" + +// TestingSuite can store and return the current *testing.T context +// generated by 'go test'. +type TestingSuite interface { + T() *testing.T + SetT(*testing.T) +} + +// SetupAllSuite has a SetupSuite method, which will run before the +// tests in the suite are run. +type SetupAllSuite interface { + SetupSuite() +} + +// SetupTestSuite has a SetupTest method, which will run before each +// test in the suite. +type SetupTestSuite interface { + SetupTest() +} + +// TearDownAllSuite has a TearDownSuite method, which will run after +// all the tests in the suite have been run. +type TearDownAllSuite interface { + TearDownSuite() +} + +// TearDownTestSuite has a TearDownTest method, which will run after +// each test in the suite. +type TearDownTestSuite interface { + TearDownTest() +} diff --git a/vendor/github.com/stretchr/testify/suite/suite.go b/vendor/github.com/stretchr/testify/suite/suite.go new file mode 100644 index 00000000..f831e251 --- /dev/null +++ b/vendor/github.com/stretchr/testify/suite/suite.go @@ -0,0 +1,115 @@ +package suite + +import ( + "flag" + "fmt" + "os" + "reflect" + "regexp" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var matchMethod = flag.String("m", "", "regular expression to select tests of the suite to run") + +// Suite is a basic testing suite with methods for storing and +// retrieving the current *testing.T context. +type Suite struct { + *assert.Assertions + require *require.Assertions + t *testing.T +} + +// T retrieves the current *testing.T context. +func (suite *Suite) T() *testing.T { + return suite.t +} + +// SetT sets the current *testing.T context. +func (suite *Suite) SetT(t *testing.T) { + suite.t = t + suite.Assertions = assert.New(t) + suite.require = require.New(t) +} + +// Require returns a require context for suite. +func (suite *Suite) Require() *require.Assertions { + if suite.require == nil { + suite.require = require.New(suite.T()) + } + return suite.require +} + +// Assert returns an assert context for suite. Normally, you can call +// `suite.NoError(expected, actual)`, but for situations where the embedded +// methods are overridden (for example, you might want to override +// assert.Assertions with require.Assertions), this method is provided so you +// can call `suite.Assert().NoError()`. +func (suite *Suite) Assert() *assert.Assertions { + if suite.Assertions == nil { + suite.Assertions = assert.New(suite.T()) + } + return suite.Assertions +} + +// Run takes a testing suite and runs all of the tests attached +// to it. +func Run(t *testing.T, suite TestingSuite) { + suite.SetT(t) + + if setupAllSuite, ok := suite.(SetupAllSuite); ok { + setupAllSuite.SetupSuite() + } + defer func() { + if tearDownAllSuite, ok := suite.(TearDownAllSuite); ok { + tearDownAllSuite.TearDownSuite() + } + }() + + methodFinder := reflect.TypeOf(suite) + tests := []testing.InternalTest{} + for index := 0; index < methodFinder.NumMethod(); index++ { + method := methodFinder.Method(index) + ok, err := methodFilter(method.Name) + if err != nil { + fmt.Fprintf(os.Stderr, "testify: invalid regexp for -m: %s\n", err) + os.Exit(1) + } + if ok { + test := testing.InternalTest{ + Name: method.Name, + F: func(t *testing.T) { + parentT := suite.T() + suite.SetT(t) + if setupTestSuite, ok := suite.(SetupTestSuite); ok { + setupTestSuite.SetupTest() + } + defer func() { + if tearDownTestSuite, ok := suite.(TearDownTestSuite); ok { + tearDownTestSuite.TearDownTest() + } + suite.SetT(parentT) + }() + method.Func.Call([]reflect.Value{reflect.ValueOf(suite)}) + }, + } + tests = append(tests, test) + } + } + + if !testing.RunTests(func(_, _ string) (bool, error) { return true, nil }, + tests) { + t.Fail() + } +} + +// Filtering method according to set regular expression +// specified command-line argument -m +func methodFilter(name string) (bool, error) { + if ok, _ := regexp.MatchString("^Test", name); !ok { + return false, nil + } + return regexp.MatchString(*matchMethod, name) +} diff --git a/vendor/github.com/stretchr/testify/suite/suite_test.go b/vendor/github.com/stretchr/testify/suite/suite_test.go new file mode 100644 index 00000000..c7c4e88f --- /dev/null +++ b/vendor/github.com/stretchr/testify/suite/suite_test.go @@ -0,0 +1,239 @@ +package suite + +import ( + "errors" + "io/ioutil" + "os" + "testing" + + "github.com/stretchr/testify/assert" +) + +// SuiteRequireTwice is intended to test the usage of suite.Require in two +// different tests +type SuiteRequireTwice struct{ Suite } + +// TestSuiteRequireTwice checks for regressions of issue #149 where +// suite.requirements was not initialised in suite.SetT() +// A regression would result on these tests panicking rather than failing. +func TestSuiteRequireTwice(t *testing.T) { + ok := testing.RunTests( + func(_, _ string) (bool, error) { return true, nil }, + []testing.InternalTest{{ + Name: "TestSuiteRequireTwice", + F: func(t *testing.T) { + suite := new(SuiteRequireTwice) + Run(t, suite) + }, + }}, + ) + assert.Equal(t, false, ok) +} + +func (s *SuiteRequireTwice) TestRequireOne() { + r := s.Require() + r.Equal(1, 2) +} + +func (s *SuiteRequireTwice) TestRequireTwo() { + r := s.Require() + r.Equal(1, 2) +} + +// This suite is intended to store values to make sure that only +// testing-suite-related methods are run. It's also a fully +// functional example of a testing suite, using setup/teardown methods +// and a helper method that is ignored by testify. To make this look +// more like a real world example, all tests in the suite perform some +// type of assertion. +type SuiteTester struct { + // Include our basic suite logic. + Suite + + // Keep counts of how many times each method is run. + SetupSuiteRunCount int + TearDownSuiteRunCount int + SetupTestRunCount int + TearDownTestRunCount int + TestOneRunCount int + TestTwoRunCount int + NonTestMethodRunCount int +} + +type SuiteSkipTester struct { + // Include our basic suite logic. + Suite + + // Keep counts of how many times each method is run. + SetupSuiteRunCount int + TearDownSuiteRunCount int +} + +// The SetupSuite method will be run by testify once, at the very +// start of the testing suite, before any tests are run. +func (suite *SuiteTester) SetupSuite() { + suite.SetupSuiteRunCount++ +} + +func (suite *SuiteSkipTester) SetupSuite() { + suite.SetupSuiteRunCount++ + suite.T().Skip() +} + +// The TearDownSuite method will be run by testify once, at the very +// end of the testing suite, after all tests have been run. +func (suite *SuiteTester) TearDownSuite() { + suite.TearDownSuiteRunCount++ +} + +func (suite *SuiteSkipTester) TearDownSuite() { + suite.TearDownSuiteRunCount++ +} + +// The SetupTest method will be run before every test in the suite. +func (suite *SuiteTester) SetupTest() { + suite.SetupTestRunCount++ +} + +// The TearDownTest method will be run after every test in the suite. +func (suite *SuiteTester) TearDownTest() { + suite.TearDownTestRunCount++ +} + +// Every method in a testing suite that begins with "Test" will be run +// as a test. TestOne is an example of a test. For the purposes of +// this example, we've included assertions in the tests, since most +// tests will issue assertions. +func (suite *SuiteTester) TestOne() { + beforeCount := suite.TestOneRunCount + suite.TestOneRunCount++ + assert.Equal(suite.T(), suite.TestOneRunCount, beforeCount+1) + suite.Equal(suite.TestOneRunCount, beforeCount+1) +} + +// TestTwo is another example of a test. +func (suite *SuiteTester) TestTwo() { + beforeCount := suite.TestTwoRunCount + suite.TestTwoRunCount++ + assert.NotEqual(suite.T(), suite.TestTwoRunCount, beforeCount) + suite.NotEqual(suite.TestTwoRunCount, beforeCount) +} + +func (suite *SuiteTester) TestSkip() { + suite.T().Skip() +} + +// NonTestMethod does not begin with "Test", so it will not be run by +// testify as a test in the suite. This is useful for creating helper +// methods for your tests. +func (suite *SuiteTester) NonTestMethod() { + suite.NonTestMethodRunCount++ +} + +// TestRunSuite will be run by the 'go test' command, so within it, we +// can run our suite using the Run(*testing.T, TestingSuite) function. +func TestRunSuite(t *testing.T) { + suiteTester := new(SuiteTester) + Run(t, suiteTester) + + // Normally, the test would end here. The following are simply + // some assertions to ensure that the Run function is working as + // intended - they are not part of the example. + + // The suite was only run once, so the SetupSuite and TearDownSuite + // methods should have each been run only once. + assert.Equal(t, suiteTester.SetupSuiteRunCount, 1) + assert.Equal(t, suiteTester.TearDownSuiteRunCount, 1) + + // There are three test methods (TestOne, TestTwo, and TestSkip), so + // the SetupTest and TearDownTest methods (which should be run once for + // each test) should have been run three times. + assert.Equal(t, suiteTester.SetupTestRunCount, 3) + assert.Equal(t, suiteTester.TearDownTestRunCount, 3) + + // Each test should have been run once. + assert.Equal(t, suiteTester.TestOneRunCount, 1) + assert.Equal(t, suiteTester.TestTwoRunCount, 1) + + // Methods that don't match the test method identifier shouldn't + // have been run at all. + assert.Equal(t, suiteTester.NonTestMethodRunCount, 0) + + suiteSkipTester := new(SuiteSkipTester) + Run(t, suiteSkipTester) + + // The suite was only run once, so the SetupSuite and TearDownSuite + // methods should have each been run only once, even though SetupSuite + // called Skip() + assert.Equal(t, suiteSkipTester.SetupSuiteRunCount, 1) + assert.Equal(t, suiteSkipTester.TearDownSuiteRunCount, 1) + +} + +func TestSuiteGetters(t *testing.T) { + suite := new(SuiteTester) + suite.SetT(t) + assert.NotNil(t, suite.Assert()) + assert.Equal(t, suite.Assertions, suite.Assert()) + assert.NotNil(t, suite.Require()) + assert.Equal(t, suite.require, suite.Require()) +} + +type SuiteLoggingTester struct { + Suite +} + +func (s *SuiteLoggingTester) TestLoggingPass() { + s.T().Log("TESTLOGPASS") +} + +func (s *SuiteLoggingTester) TestLoggingFail() { + s.T().Log("TESTLOGFAIL") + assert.NotNil(s.T(), nil) // expected to fail +} + +type StdoutCapture struct { + oldStdout *os.File + readPipe *os.File +} + +func (sc *StdoutCapture) StartCapture() { + sc.oldStdout = os.Stdout + sc.readPipe, os.Stdout, _ = os.Pipe() +} + +func (sc *StdoutCapture) StopCapture() (string, error) { + if sc.oldStdout == nil || sc.readPipe == nil { + return "", errors.New("StartCapture not called before StopCapture") + } + os.Stdout.Close() + os.Stdout = sc.oldStdout + bytes, err := ioutil.ReadAll(sc.readPipe) + if err != nil { + return "", err + } + return string(bytes), nil +} + +func TestSuiteLogging(t *testing.T) { + testT := testing.T{} + + suiteLoggingTester := new(SuiteLoggingTester) + + capture := StdoutCapture{} + capture.StartCapture() + Run(&testT, suiteLoggingTester) + output, err := capture.StopCapture() + + assert.Nil(t, err, "Got an error trying to capture stdout!") + + // Failed tests' output is always printed + assert.Contains(t, output, "TESTLOGFAIL") + + if testing.Verbose() { + // In verbose mode, output from successful tests is also printed + assert.Contains(t, output, "TESTLOGPASS") + } else { + assert.NotContains(t, output, "TESTLOGPASS") + } +} diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/LICENSE b/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/LICENSE new file mode 100644 index 00000000..2a7cfd2b --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2012-2013 Dave Collins + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/bypass.go b/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/bypass.go new file mode 100644 index 00000000..565bf589 --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/bypass.go @@ -0,0 +1,151 @@ +// Copyright (c) 2015 Dave Collins +// +// Permission to use, copy, modify, and distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// NOTE: Due to the following build constraints, this file will only be compiled +// when the code is not running on Google App Engine and "-tags disableunsafe" +// is not added to the go build command line. +// +build !appengine,!disableunsafe + +package spew + +import ( + "reflect" + "unsafe" +) + +const ( + // UnsafeDisabled is a build-time constant which specifies whether or + // not access to the unsafe package is available. + UnsafeDisabled = false + + // ptrSize is the size of a pointer on the current arch. + ptrSize = unsafe.Sizeof((*byte)(nil)) +) + +var ( + // offsetPtr, offsetScalar, and offsetFlag are the offsets for the + // internal reflect.Value fields. These values are valid before golang + // commit ecccf07e7f9d which changed the format. The are also valid + // after commit 82f48826c6c7 which changed the format again to mirror + // the original format. Code in the init function updates these offsets + // as necessary. + offsetPtr = uintptr(ptrSize) + offsetScalar = uintptr(0) + offsetFlag = uintptr(ptrSize * 2) + + // flagKindWidth and flagKindShift indicate various bits that the + // reflect package uses internally to track kind information. + // + // flagRO indicates whether or not the value field of a reflect.Value is + // read-only. + // + // flagIndir indicates whether the value field of a reflect.Value is + // the actual data or a pointer to the data. + // + // These values are valid before golang commit 90a7c3c86944 which + // changed their positions. Code in the init function updates these + // flags as necessary. + flagKindWidth = uintptr(5) + flagKindShift = uintptr(flagKindWidth - 1) + flagRO = uintptr(1 << 0) + flagIndir = uintptr(1 << 1) +) + +func init() { + // Older versions of reflect.Value stored small integers directly in the + // ptr field (which is named val in the older versions). Versions + // between commits ecccf07e7f9d and 82f48826c6c7 added a new field named + // scalar for this purpose which unfortunately came before the flag + // field, so the offset of the flag field is different for those + // versions. + // + // This code constructs a new reflect.Value from a known small integer + // and checks if the size of the reflect.Value struct indicates it has + // the scalar field. When it does, the offsets are updated accordingly. + vv := reflect.ValueOf(0xf00) + if unsafe.Sizeof(vv) == (ptrSize * 4) { + offsetScalar = ptrSize * 2 + offsetFlag = ptrSize * 3 + } + + // Commit 90a7c3c86944 changed the flag positions such that the low + // order bits are the kind. This code extracts the kind from the flags + // field and ensures it's the correct type. When it's not, the flag + // order has been changed to the newer format, so the flags are updated + // accordingly. + upf := unsafe.Pointer(uintptr(unsafe.Pointer(&vv)) + offsetFlag) + upfv := *(*uintptr)(upf) + flagKindMask := uintptr((1<>flagKindShift != uintptr(reflect.Int) { + flagKindShift = 0 + flagRO = 1 << 5 + flagIndir = 1 << 6 + + // Commit adf9b30e5594 modified the flags to separate the + // flagRO flag into two bits which specifies whether or not the + // field is embedded. This causes flagIndir to move over a bit + // and means that flagRO is the combination of either of the + // original flagRO bit and the new bit. + // + // This code detects the change by extracting what used to be + // the indirect bit to ensure it's set. When it's not, the flag + // order has been changed to the newer format, so the flags are + // updated accordingly. + if upfv&flagIndir == 0 { + flagRO = 3 << 5 + flagIndir = 1 << 7 + } + } +} + +// unsafeReflectValue converts the passed reflect.Value into a one that bypasses +// the typical safety restrictions preventing access to unaddressable and +// unexported data. It works by digging the raw pointer to the underlying +// value out of the protected value and generating a new unprotected (unsafe) +// reflect.Value to it. +// +// This allows us to check for implementations of the Stringer and error +// interfaces to be used for pretty printing ordinarily unaddressable and +// inaccessible values such as unexported struct fields. +func unsafeReflectValue(v reflect.Value) (rv reflect.Value) { + indirects := 1 + vt := v.Type() + upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr) + rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag)) + if rvf&flagIndir != 0 { + vt = reflect.PtrTo(v.Type()) + indirects++ + } else if offsetScalar != 0 { + // The value is in the scalar field when it's not one of the + // reference types. + switch vt.Kind() { + case reflect.Uintptr: + case reflect.Chan: + case reflect.Func: + case reflect.Map: + case reflect.Ptr: + case reflect.UnsafePointer: + default: + upv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + + offsetScalar) + } + } + + pv := reflect.NewAt(vt, upv) + rv = pv + for i := 0; i < indirects; i++ { + rv = rv.Elem() + } + return rv +} diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go b/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go new file mode 100644 index 00000000..457e4123 --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go @@ -0,0 +1,37 @@ +// Copyright (c) 2015 Dave Collins +// +// Permission to use, copy, modify, and distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// NOTE: Due to the following build constraints, this file will only be compiled +// when either the code is running on Google App Engine or "-tags disableunsafe" +// is added to the go build command line. +// +build appengine disableunsafe + +package spew + +import "reflect" + +const ( + // UnsafeDisabled is a build-time constant which specifies whether or + // not access to the unsafe package is available. + UnsafeDisabled = true +) + +// unsafeReflectValue typically converts the passed reflect.Value into a one +// that bypasses the typical safety restrictions preventing access to +// unaddressable and unexported data. However, doing this relies on access to +// the unsafe package. This is a stub version which simply returns the passed +// reflect.Value when the unsafe package is not available. +func unsafeReflectValue(v reflect.Value) reflect.Value { + return v +} diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/common.go b/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/common.go new file mode 100644 index 00000000..14f02dc1 --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/common.go @@ -0,0 +1,341 @@ +/* + * Copyright (c) 2013 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "bytes" + "fmt" + "io" + "reflect" + "sort" + "strconv" +) + +// Some constants in the form of bytes to avoid string overhead. This mirrors +// the technique used in the fmt package. +var ( + panicBytes = []byte("(PANIC=") + plusBytes = []byte("+") + iBytes = []byte("i") + trueBytes = []byte("true") + falseBytes = []byte("false") + interfaceBytes = []byte("(interface {})") + commaNewlineBytes = []byte(",\n") + newlineBytes = []byte("\n") + openBraceBytes = []byte("{") + openBraceNewlineBytes = []byte("{\n") + closeBraceBytes = []byte("}") + asteriskBytes = []byte("*") + colonBytes = []byte(":") + colonSpaceBytes = []byte(": ") + openParenBytes = []byte("(") + closeParenBytes = []byte(")") + spaceBytes = []byte(" ") + pointerChainBytes = []byte("->") + nilAngleBytes = []byte("") + maxNewlineBytes = []byte("\n") + maxShortBytes = []byte("") + circularBytes = []byte("") + circularShortBytes = []byte("") + invalidAngleBytes = []byte("") + openBracketBytes = []byte("[") + closeBracketBytes = []byte("]") + percentBytes = []byte("%") + precisionBytes = []byte(".") + openAngleBytes = []byte("<") + closeAngleBytes = []byte(">") + openMapBytes = []byte("map[") + closeMapBytes = []byte("]") + lenEqualsBytes = []byte("len=") + capEqualsBytes = []byte("cap=") +) + +// hexDigits is used to map a decimal value to a hex digit. +var hexDigits = "0123456789abcdef" + +// catchPanic handles any panics that might occur during the handleMethods +// calls. +func catchPanic(w io.Writer, v reflect.Value) { + if err := recover(); err != nil { + w.Write(panicBytes) + fmt.Fprintf(w, "%v", err) + w.Write(closeParenBytes) + } +} + +// handleMethods attempts to call the Error and String methods on the underlying +// type the passed reflect.Value represents and outputes the result to Writer w. +// +// It handles panics in any called methods by catching and displaying the error +// as the formatted value. +func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) { + // We need an interface to check if the type implements the error or + // Stringer interface. However, the reflect package won't give us an + // interface on certain things like unexported struct fields in order + // to enforce visibility rules. We use unsafe, when it's available, + // to bypass these restrictions since this package does not mutate the + // values. + if !v.CanInterface() { + if UnsafeDisabled { + return false + } + + v = unsafeReflectValue(v) + } + + // Choose whether or not to do error and Stringer interface lookups against + // the base type or a pointer to the base type depending on settings. + // Technically calling one of these methods with a pointer receiver can + // mutate the value, however, types which choose to satisify an error or + // Stringer interface with a pointer receiver should not be mutating their + // state inside these interface methods. + if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() { + v = unsafeReflectValue(v) + } + if v.CanAddr() { + v = v.Addr() + } + + // Is it an error or Stringer? + switch iface := v.Interface().(type) { + case error: + defer catchPanic(w, v) + if cs.ContinueOnMethod { + w.Write(openParenBytes) + w.Write([]byte(iface.Error())) + w.Write(closeParenBytes) + w.Write(spaceBytes) + return false + } + + w.Write([]byte(iface.Error())) + return true + + case fmt.Stringer: + defer catchPanic(w, v) + if cs.ContinueOnMethod { + w.Write(openParenBytes) + w.Write([]byte(iface.String())) + w.Write(closeParenBytes) + w.Write(spaceBytes) + return false + } + w.Write([]byte(iface.String())) + return true + } + return false +} + +// printBool outputs a boolean value as true or false to Writer w. +func printBool(w io.Writer, val bool) { + if val { + w.Write(trueBytes) + } else { + w.Write(falseBytes) + } +} + +// printInt outputs a signed integer value to Writer w. +func printInt(w io.Writer, val int64, base int) { + w.Write([]byte(strconv.FormatInt(val, base))) +} + +// printUint outputs an unsigned integer value to Writer w. +func printUint(w io.Writer, val uint64, base int) { + w.Write([]byte(strconv.FormatUint(val, base))) +} + +// printFloat outputs a floating point value using the specified precision, +// which is expected to be 32 or 64bit, to Writer w. +func printFloat(w io.Writer, val float64, precision int) { + w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision))) +} + +// printComplex outputs a complex value using the specified float precision +// for the real and imaginary parts to Writer w. +func printComplex(w io.Writer, c complex128, floatPrecision int) { + r := real(c) + w.Write(openParenBytes) + w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision))) + i := imag(c) + if i >= 0 { + w.Write(plusBytes) + } + w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision))) + w.Write(iBytes) + w.Write(closeParenBytes) +} + +// printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x' +// prefix to Writer w. +func printHexPtr(w io.Writer, p uintptr) { + // Null pointer. + num := uint64(p) + if num == 0 { + w.Write(nilAngleBytes) + return + } + + // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix + buf := make([]byte, 18) + + // It's simpler to construct the hex string right to left. + base := uint64(16) + i := len(buf) - 1 + for num >= base { + buf[i] = hexDigits[num%base] + num /= base + i-- + } + buf[i] = hexDigits[num] + + // Add '0x' prefix. + i-- + buf[i] = 'x' + i-- + buf[i] = '0' + + // Strip unused leading bytes. + buf = buf[i:] + w.Write(buf) +} + +// valuesSorter implements sort.Interface to allow a slice of reflect.Value +// elements to be sorted. +type valuesSorter struct { + values []reflect.Value + strings []string // either nil or same len and values + cs *ConfigState +} + +// newValuesSorter initializes a valuesSorter instance, which holds a set of +// surrogate keys on which the data should be sorted. It uses flags in +// ConfigState to decide if and how to populate those surrogate keys. +func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface { + vs := &valuesSorter{values: values, cs: cs} + if canSortSimply(vs.values[0].Kind()) { + return vs + } + if !cs.DisableMethods { + vs.strings = make([]string, len(values)) + for i := range vs.values { + b := bytes.Buffer{} + if !handleMethods(cs, &b, vs.values[i]) { + vs.strings = nil + break + } + vs.strings[i] = b.String() + } + } + if vs.strings == nil && cs.SpewKeys { + vs.strings = make([]string, len(values)) + for i := range vs.values { + vs.strings[i] = Sprintf("%#v", vs.values[i].Interface()) + } + } + return vs +} + +// canSortSimply tests whether a reflect.Kind is a primitive that can be sorted +// directly, or whether it should be considered for sorting by surrogate keys +// (if the ConfigState allows it). +func canSortSimply(kind reflect.Kind) bool { + // This switch parallels valueSortLess, except for the default case. + switch kind { + case reflect.Bool: + return true + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + return true + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + return true + case reflect.Float32, reflect.Float64: + return true + case reflect.String: + return true + case reflect.Uintptr: + return true + case reflect.Array: + return true + } + return false +} + +// Len returns the number of values in the slice. It is part of the +// sort.Interface implementation. +func (s *valuesSorter) Len() int { + return len(s.values) +} + +// Swap swaps the values at the passed indices. It is part of the +// sort.Interface implementation. +func (s *valuesSorter) Swap(i, j int) { + s.values[i], s.values[j] = s.values[j], s.values[i] + if s.strings != nil { + s.strings[i], s.strings[j] = s.strings[j], s.strings[i] + } +} + +// valueSortLess returns whether the first value should sort before the second +// value. It is used by valueSorter.Less as part of the sort.Interface +// implementation. +func valueSortLess(a, b reflect.Value) bool { + switch a.Kind() { + case reflect.Bool: + return !a.Bool() && b.Bool() + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + return a.Int() < b.Int() + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + return a.Uint() < b.Uint() + case reflect.Float32, reflect.Float64: + return a.Float() < b.Float() + case reflect.String: + return a.String() < b.String() + case reflect.Uintptr: + return a.Uint() < b.Uint() + case reflect.Array: + // Compare the contents of both arrays. + l := a.Len() + for i := 0; i < l; i++ { + av := a.Index(i) + bv := b.Index(i) + if av.Interface() == bv.Interface() { + continue + } + return valueSortLess(av, bv) + } + } + return a.String() < b.String() +} + +// Less returns whether the value at index i should sort before the +// value at index j. It is part of the sort.Interface implementation. +func (s *valuesSorter) Less(i, j int) bool { + if s.strings == nil { + return valueSortLess(s.values[i], s.values[j]) + } + return s.strings[i] < s.strings[j] +} + +// sortValues is a sort function that handles both native types and any type that +// can be converted to error or Stringer. Other inputs are sorted according to +// their Value.String() value to ensure display stability. +func sortValues(values []reflect.Value, cs *ConfigState) { + if len(values) == 0 { + return + } + sort.Sort(newValuesSorter(values, cs)) +} diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/config.go b/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/config.go new file mode 100644 index 00000000..ee1ab07b --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/config.go @@ -0,0 +1,297 @@ +/* + * Copyright (c) 2013 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "bytes" + "fmt" + "io" + "os" +) + +// ConfigState houses the configuration options used by spew to format and +// display values. There is a global instance, Config, that is used to control +// all top-level Formatter and Dump functionality. Each ConfigState instance +// provides methods equivalent to the top-level functions. +// +// The zero value for ConfigState provides no indentation. You would typically +// want to set it to a space or a tab. +// +// Alternatively, you can use NewDefaultConfig to get a ConfigState instance +// with default settings. See the documentation of NewDefaultConfig for default +// values. +type ConfigState struct { + // Indent specifies the string to use for each indentation level. The + // global config instance that all top-level functions use set this to a + // single space by default. If you would like more indentation, you might + // set this to a tab with "\t" or perhaps two spaces with " ". + Indent string + + // MaxDepth controls the maximum number of levels to descend into nested + // data structures. The default, 0, means there is no limit. + // + // NOTE: Circular data structures are properly detected, so it is not + // necessary to set this value unless you specifically want to limit deeply + // nested data structures. + MaxDepth int + + // DisableMethods specifies whether or not error and Stringer interfaces are + // invoked for types that implement them. + DisableMethods bool + + // DisablePointerMethods specifies whether or not to check for and invoke + // error and Stringer interfaces on types which only accept a pointer + // receiver when the current type is not a pointer. + // + // NOTE: This might be an unsafe action since calling one of these methods + // with a pointer receiver could technically mutate the value, however, + // in practice, types which choose to satisify an error or Stringer + // interface with a pointer receiver should not be mutating their state + // inside these interface methods. As a result, this option relies on + // access to the unsafe package, so it will not have any effect when + // running in environments without access to the unsafe package such as + // Google App Engine or with the "disableunsafe" build tag specified. + DisablePointerMethods bool + + // ContinueOnMethod specifies whether or not recursion should continue once + // a custom error or Stringer interface is invoked. The default, false, + // means it will print the results of invoking the custom error or Stringer + // interface and return immediately instead of continuing to recurse into + // the internals of the data type. + // + // NOTE: This flag does not have any effect if method invocation is disabled + // via the DisableMethods or DisablePointerMethods options. + ContinueOnMethod bool + + // SortKeys specifies map keys should be sorted before being printed. Use + // this to have a more deterministic, diffable output. Note that only + // native types (bool, int, uint, floats, uintptr and string) and types + // that support the error or Stringer interfaces (if methods are + // enabled) are supported, with other types sorted according to the + // reflect.Value.String() output which guarantees display stability. + SortKeys bool + + // SpewKeys specifies that, as a last resort attempt, map keys should + // be spewed to strings and sorted by those strings. This is only + // considered if SortKeys is true. + SpewKeys bool +} + +// Config is the active configuration of the top-level functions. +// The configuration can be changed by modifying the contents of spew.Config. +var Config = ConfigState{Indent: " "} + +// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the formatted string as a value that satisfies error. See NewFormatter +// for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) { + return fmt.Errorf(format, c.convertArgs(a)...) +} + +// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprint(w, c.convertArgs(a)...) +} + +// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { + return fmt.Fprintf(w, format, c.convertArgs(a)...) +} + +// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it +// passed with a Formatter interface returned by c.NewFormatter. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprintln(w, c.convertArgs(a)...) +} + +// Print is a wrapper for fmt.Print that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Print(c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Print(a ...interface{}) (n int, err error) { + return fmt.Print(c.convertArgs(a)...) +} + +// Printf is a wrapper for fmt.Printf that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) { + return fmt.Printf(format, c.convertArgs(a)...) +} + +// Println is a wrapper for fmt.Println that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Println(c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Println(a ...interface{}) (n int, err error) { + return fmt.Println(c.convertArgs(a)...) +} + +// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Sprint(a ...interface{}) string { + return fmt.Sprint(c.convertArgs(a)...) +} + +// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Sprintf(format string, a ...interface{}) string { + return fmt.Sprintf(format, c.convertArgs(a)...) +} + +// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it +// were passed with a Formatter interface returned by c.NewFormatter. It +// returns the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Sprintln(a ...interface{}) string { + return fmt.Sprintln(c.convertArgs(a)...) +} + +/* +NewFormatter returns a custom formatter that satisfies the fmt.Formatter +interface. As a result, it integrates cleanly with standard fmt package +printing functions. The formatter is useful for inline printing of smaller data +types similar to the standard %v format specifier. + +The custom formatter only responds to the %v (most compact), %+v (adds pointer +addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb +combinations. Any other verbs such as %x and %q will be sent to the the +standard fmt package for formatting. In addition, the custom formatter ignores +the width and precision arguments (however they will still work on the format +specifiers not handled by the custom formatter). + +Typically this function shouldn't be called directly. It is much easier to make +use of the custom formatter by calling one of the convenience functions such as +c.Printf, c.Println, or c.Printf. +*/ +func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter { + return newFormatter(c, v) +} + +// Fdump formats and displays the passed arguments to io.Writer w. It formats +// exactly the same as Dump. +func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) { + fdump(c, w, a...) +} + +/* +Dump displays the passed parameters to standard out with newlines, customizable +indentation, and additional debug information such as complete types and all +pointer addresses used to indirect to the final value. It provides the +following features over the built-in printing facilities provided by the fmt +package: + + * Pointers are dereferenced and followed + * Circular data structures are detected and handled properly + * Custom Stringer/error interfaces are optionally invoked, including + on unexported types + * Custom types which only implement the Stringer/error interfaces via + a pointer receiver are optionally invoked when passing non-pointer + variables + * Byte arrays and slices are dumped like the hexdump -C command which + includes offsets, byte values in hex, and ASCII output + +The configuration options are controlled by modifying the public members +of c. See ConfigState for options documentation. + +See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to +get the formatted result as a string. +*/ +func (c *ConfigState) Dump(a ...interface{}) { + fdump(c, os.Stdout, a...) +} + +// Sdump returns a string with the passed arguments formatted exactly the same +// as Dump. +func (c *ConfigState) Sdump(a ...interface{}) string { + var buf bytes.Buffer + fdump(c, &buf, a...) + return buf.String() +} + +// convertArgs accepts a slice of arguments and returns a slice of the same +// length with each argument converted to a spew Formatter interface using +// the ConfigState associated with s. +func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) { + formatters = make([]interface{}, len(args)) + for index, arg := range args { + formatters[index] = newFormatter(c, arg) + } + return formatters +} + +// NewDefaultConfig returns a ConfigState with the following default settings. +// +// Indent: " " +// MaxDepth: 0 +// DisableMethods: false +// DisablePointerMethods: false +// ContinueOnMethod: false +// SortKeys: false +func NewDefaultConfig() *ConfigState { + return &ConfigState{Indent: " "} +} diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/doc.go b/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/doc.go new file mode 100644 index 00000000..5be0c406 --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/doc.go @@ -0,0 +1,202 @@ +/* + * Copyright (c) 2013 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* +Package spew implements a deep pretty printer for Go data structures to aid in +debugging. + +A quick overview of the additional features spew provides over the built-in +printing facilities for Go data types are as follows: + + * Pointers are dereferenced and followed + * Circular data structures are detected and handled properly + * Custom Stringer/error interfaces are optionally invoked, including + on unexported types + * Custom types which only implement the Stringer/error interfaces via + a pointer receiver are optionally invoked when passing non-pointer + variables + * Byte arrays and slices are dumped like the hexdump -C command which + includes offsets, byte values in hex, and ASCII output (only when using + Dump style) + +There are two different approaches spew allows for dumping Go data structures: + + * Dump style which prints with newlines, customizable indentation, + and additional debug information such as types and all pointer addresses + used to indirect to the final value + * A custom Formatter interface that integrates cleanly with the standard fmt + package and replaces %v, %+v, %#v, and %#+v to provide inline printing + similar to the default %v while providing the additional functionality + outlined above and passing unsupported format verbs such as %x and %q + along to fmt + +Quick Start + +This section demonstrates how to quickly get started with spew. See the +sections below for further details on formatting and configuration options. + +To dump a variable with full newlines, indentation, type, and pointer +information use Dump, Fdump, or Sdump: + spew.Dump(myVar1, myVar2, ...) + spew.Fdump(someWriter, myVar1, myVar2, ...) + str := spew.Sdump(myVar1, myVar2, ...) + +Alternatively, if you would prefer to use format strings with a compacted inline +printing style, use the convenience wrappers Printf, Fprintf, etc with +%v (most compact), %+v (adds pointer addresses), %#v (adds types), or +%#+v (adds types and pointer addresses): + spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) + spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) + spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) + spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) + +Configuration Options + +Configuration of spew is handled by fields in the ConfigState type. For +convenience, all of the top-level functions use a global state available +via the spew.Config global. + +It is also possible to create a ConfigState instance that provides methods +equivalent to the top-level functions. This allows concurrent configuration +options. See the ConfigState documentation for more details. + +The following configuration options are available: + * Indent + String to use for each indentation level for Dump functions. + It is a single space by default. A popular alternative is "\t". + + * MaxDepth + Maximum number of levels to descend into nested data structures. + There is no limit by default. + + * DisableMethods + Disables invocation of error and Stringer interface methods. + Method invocation is enabled by default. + + * DisablePointerMethods + Disables invocation of error and Stringer interface methods on types + which only accept pointer receivers from non-pointer variables. + Pointer method invocation is enabled by default. + + * ContinueOnMethod + Enables recursion into types after invoking error and Stringer interface + methods. Recursion after method invocation is disabled by default. + + * SortKeys + Specifies map keys should be sorted before being printed. Use + this to have a more deterministic, diffable output. Note that + only native types (bool, int, uint, floats, uintptr and string) + and types which implement error or Stringer interfaces are + supported with other types sorted according to the + reflect.Value.String() output which guarantees display + stability. Natural map order is used by default. + + * SpewKeys + Specifies that, as a last resort attempt, map keys should be + spewed to strings and sorted by those strings. This is only + considered if SortKeys is true. + +Dump Usage + +Simply call spew.Dump with a list of variables you want to dump: + + spew.Dump(myVar1, myVar2, ...) + +You may also call spew.Fdump if you would prefer to output to an arbitrary +io.Writer. For example, to dump to standard error: + + spew.Fdump(os.Stderr, myVar1, myVar2, ...) + +A third option is to call spew.Sdump to get the formatted output as a string: + + str := spew.Sdump(myVar1, myVar2, ...) + +Sample Dump Output + +See the Dump example for details on the setup of the types and variables being +shown here. + + (main.Foo) { + unexportedField: (*main.Bar)(0xf84002e210)({ + flag: (main.Flag) flagTwo, + data: (uintptr) + }), + ExportedField: (map[interface {}]interface {}) (len=1) { + (string) (len=3) "one": (bool) true + } + } + +Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C +command as shown. + ([]uint8) (len=32 cap=32) { + 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | + 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| + 00000020 31 32 |12| + } + +Custom Formatter + +Spew provides a custom formatter that implements the fmt.Formatter interface +so that it integrates cleanly with standard fmt package printing functions. The +formatter is useful for inline printing of smaller data types similar to the +standard %v format specifier. + +The custom formatter only responds to the %v (most compact), %+v (adds pointer +addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb +combinations. Any other verbs such as %x and %q will be sent to the the +standard fmt package for formatting. In addition, the custom formatter ignores +the width and precision arguments (however they will still work on the format +specifiers not handled by the custom formatter). + +Custom Formatter Usage + +The simplest way to make use of the spew custom formatter is to call one of the +convenience functions such as spew.Printf, spew.Println, or spew.Printf. The +functions have syntax you are most likely already familiar with: + + spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) + spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) + spew.Println(myVar, myVar2) + spew.Fprintf(os.Stderr, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) + spew.Fprintf(os.Stderr, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) + +See the Index for the full list convenience functions. + +Sample Formatter Output + +Double pointer to a uint8: + %v: <**>5 + %+v: <**>(0xf8400420d0->0xf8400420c8)5 + %#v: (**uint8)5 + %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5 + +Pointer to circular struct with a uint8 field and a pointer to itself: + %v: <*>{1 <*>} + %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)} + %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)} + %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)} + +See the Printf example for details on the setup of variables being shown +here. + +Errors + +Since it is possible for custom Stringer/error interfaces to panic, spew +detects them and handles them internally by printing the panic information +inline with the output. Since spew is intended to provide deep pretty printing +capabilities on structures, it intentionally does not return any errors. +*/ +package spew diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/dump.go b/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/dump.go new file mode 100644 index 00000000..a0ff95e2 --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/dump.go @@ -0,0 +1,509 @@ +/* + * Copyright (c) 2013 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "bytes" + "encoding/hex" + "fmt" + "io" + "os" + "reflect" + "regexp" + "strconv" + "strings" +) + +var ( + // uint8Type is a reflect.Type representing a uint8. It is used to + // convert cgo types to uint8 slices for hexdumping. + uint8Type = reflect.TypeOf(uint8(0)) + + // cCharRE is a regular expression that matches a cgo char. + // It is used to detect character arrays to hexdump them. + cCharRE = regexp.MustCompile("^.*\\._Ctype_char$") + + // cUnsignedCharRE is a regular expression that matches a cgo unsigned + // char. It is used to detect unsigned character arrays to hexdump + // them. + cUnsignedCharRE = regexp.MustCompile("^.*\\._Ctype_unsignedchar$") + + // cUint8tCharRE is a regular expression that matches a cgo uint8_t. + // It is used to detect uint8_t arrays to hexdump them. + cUint8tCharRE = regexp.MustCompile("^.*\\._Ctype_uint8_t$") +) + +// dumpState contains information about the state of a dump operation. +type dumpState struct { + w io.Writer + depth int + pointers map[uintptr]int + ignoreNextType bool + ignoreNextIndent bool + cs *ConfigState +} + +// indent performs indentation according to the depth level and cs.Indent +// option. +func (d *dumpState) indent() { + if d.ignoreNextIndent { + d.ignoreNextIndent = false + return + } + d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth)) +} + +// unpackValue returns values inside of non-nil interfaces when possible. +// This is useful for data types like structs, arrays, slices, and maps which +// can contain varying types packed inside an interface. +func (d *dumpState) unpackValue(v reflect.Value) reflect.Value { + if v.Kind() == reflect.Interface && !v.IsNil() { + v = v.Elem() + } + return v +} + +// dumpPtr handles formatting of pointers by indirecting them as necessary. +func (d *dumpState) dumpPtr(v reflect.Value) { + // Remove pointers at or below the current depth from map used to detect + // circular refs. + for k, depth := range d.pointers { + if depth >= d.depth { + delete(d.pointers, k) + } + } + + // Keep list of all dereferenced pointers to show later. + pointerChain := make([]uintptr, 0) + + // Figure out how many levels of indirection there are by dereferencing + // pointers and unpacking interfaces down the chain while detecting circular + // references. + nilFound := false + cycleFound := false + indirects := 0 + ve := v + for ve.Kind() == reflect.Ptr { + if ve.IsNil() { + nilFound = true + break + } + indirects++ + addr := ve.Pointer() + pointerChain = append(pointerChain, addr) + if pd, ok := d.pointers[addr]; ok && pd < d.depth { + cycleFound = true + indirects-- + break + } + d.pointers[addr] = d.depth + + ve = ve.Elem() + if ve.Kind() == reflect.Interface { + if ve.IsNil() { + nilFound = true + break + } + ve = ve.Elem() + } + } + + // Display type information. + d.w.Write(openParenBytes) + d.w.Write(bytes.Repeat(asteriskBytes, indirects)) + d.w.Write([]byte(ve.Type().String())) + d.w.Write(closeParenBytes) + + // Display pointer information. + if len(pointerChain) > 0 { + d.w.Write(openParenBytes) + for i, addr := range pointerChain { + if i > 0 { + d.w.Write(pointerChainBytes) + } + printHexPtr(d.w, addr) + } + d.w.Write(closeParenBytes) + } + + // Display dereferenced value. + d.w.Write(openParenBytes) + switch { + case nilFound == true: + d.w.Write(nilAngleBytes) + + case cycleFound == true: + d.w.Write(circularBytes) + + default: + d.ignoreNextType = true + d.dump(ve) + } + d.w.Write(closeParenBytes) +} + +// dumpSlice handles formatting of arrays and slices. Byte (uint8 under +// reflection) arrays and slices are dumped in hexdump -C fashion. +func (d *dumpState) dumpSlice(v reflect.Value) { + // Determine whether this type should be hex dumped or not. Also, + // for types which should be hexdumped, try to use the underlying data + // first, then fall back to trying to convert them to a uint8 slice. + var buf []uint8 + doConvert := false + doHexDump := false + numEntries := v.Len() + if numEntries > 0 { + vt := v.Index(0).Type() + vts := vt.String() + switch { + // C types that need to be converted. + case cCharRE.MatchString(vts): + fallthrough + case cUnsignedCharRE.MatchString(vts): + fallthrough + case cUint8tCharRE.MatchString(vts): + doConvert = true + + // Try to use existing uint8 slices and fall back to converting + // and copying if that fails. + case vt.Kind() == reflect.Uint8: + // We need an addressable interface to convert the type + // to a byte slice. However, the reflect package won't + // give us an interface on certain things like + // unexported struct fields in order to enforce + // visibility rules. We use unsafe, when available, to + // bypass these restrictions since this package does not + // mutate the values. + vs := v + if !vs.CanInterface() || !vs.CanAddr() { + vs = unsafeReflectValue(vs) + } + if !UnsafeDisabled { + vs = vs.Slice(0, numEntries) + + // Use the existing uint8 slice if it can be + // type asserted. + iface := vs.Interface() + if slice, ok := iface.([]uint8); ok { + buf = slice + doHexDump = true + break + } + } + + // The underlying data needs to be converted if it can't + // be type asserted to a uint8 slice. + doConvert = true + } + + // Copy and convert the underlying type if needed. + if doConvert && vt.ConvertibleTo(uint8Type) { + // Convert and copy each element into a uint8 byte + // slice. + buf = make([]uint8, numEntries) + for i := 0; i < numEntries; i++ { + vv := v.Index(i) + buf[i] = uint8(vv.Convert(uint8Type).Uint()) + } + doHexDump = true + } + } + + // Hexdump the entire slice as needed. + if doHexDump { + indent := strings.Repeat(d.cs.Indent, d.depth) + str := indent + hex.Dump(buf) + str = strings.Replace(str, "\n", "\n"+indent, -1) + str = strings.TrimRight(str, d.cs.Indent) + d.w.Write([]byte(str)) + return + } + + // Recursively call dump for each item. + for i := 0; i < numEntries; i++ { + d.dump(d.unpackValue(v.Index(i))) + if i < (numEntries - 1) { + d.w.Write(commaNewlineBytes) + } else { + d.w.Write(newlineBytes) + } + } +} + +// dump is the main workhorse for dumping a value. It uses the passed reflect +// value to figure out what kind of object we are dealing with and formats it +// appropriately. It is a recursive function, however circular data structures +// are detected and handled properly. +func (d *dumpState) dump(v reflect.Value) { + // Handle invalid reflect values immediately. + kind := v.Kind() + if kind == reflect.Invalid { + d.w.Write(invalidAngleBytes) + return + } + + // Handle pointers specially. + if kind == reflect.Ptr { + d.indent() + d.dumpPtr(v) + return + } + + // Print type information unless already handled elsewhere. + if !d.ignoreNextType { + d.indent() + d.w.Write(openParenBytes) + d.w.Write([]byte(v.Type().String())) + d.w.Write(closeParenBytes) + d.w.Write(spaceBytes) + } + d.ignoreNextType = false + + // Display length and capacity if the built-in len and cap functions + // work with the value's kind and the len/cap itself is non-zero. + valueLen, valueCap := 0, 0 + switch v.Kind() { + case reflect.Array, reflect.Slice, reflect.Chan: + valueLen, valueCap = v.Len(), v.Cap() + case reflect.Map, reflect.String: + valueLen = v.Len() + } + if valueLen != 0 || valueCap != 0 { + d.w.Write(openParenBytes) + if valueLen != 0 { + d.w.Write(lenEqualsBytes) + printInt(d.w, int64(valueLen), 10) + } + if valueCap != 0 { + if valueLen != 0 { + d.w.Write(spaceBytes) + } + d.w.Write(capEqualsBytes) + printInt(d.w, int64(valueCap), 10) + } + d.w.Write(closeParenBytes) + d.w.Write(spaceBytes) + } + + // Call Stringer/error interfaces if they exist and the handle methods flag + // is enabled + if !d.cs.DisableMethods { + if (kind != reflect.Invalid) && (kind != reflect.Interface) { + if handled := handleMethods(d.cs, d.w, v); handled { + return + } + } + } + + switch kind { + case reflect.Invalid: + // Do nothing. We should never get here since invalid has already + // been handled above. + + case reflect.Bool: + printBool(d.w, v.Bool()) + + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + printInt(d.w, v.Int(), 10) + + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + printUint(d.w, v.Uint(), 10) + + case reflect.Float32: + printFloat(d.w, v.Float(), 32) + + case reflect.Float64: + printFloat(d.w, v.Float(), 64) + + case reflect.Complex64: + printComplex(d.w, v.Complex(), 32) + + case reflect.Complex128: + printComplex(d.w, v.Complex(), 64) + + case reflect.Slice: + if v.IsNil() { + d.w.Write(nilAngleBytes) + break + } + fallthrough + + case reflect.Array: + d.w.Write(openBraceNewlineBytes) + d.depth++ + if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { + d.indent() + d.w.Write(maxNewlineBytes) + } else { + d.dumpSlice(v) + } + d.depth-- + d.indent() + d.w.Write(closeBraceBytes) + + case reflect.String: + d.w.Write([]byte(strconv.Quote(v.String()))) + + case reflect.Interface: + // The only time we should get here is for nil interfaces due to + // unpackValue calls. + if v.IsNil() { + d.w.Write(nilAngleBytes) + } + + case reflect.Ptr: + // Do nothing. We should never get here since pointers have already + // been handled above. + + case reflect.Map: + // nil maps should be indicated as different than empty maps + if v.IsNil() { + d.w.Write(nilAngleBytes) + break + } + + d.w.Write(openBraceNewlineBytes) + d.depth++ + if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { + d.indent() + d.w.Write(maxNewlineBytes) + } else { + numEntries := v.Len() + keys := v.MapKeys() + if d.cs.SortKeys { + sortValues(keys, d.cs) + } + for i, key := range keys { + d.dump(d.unpackValue(key)) + d.w.Write(colonSpaceBytes) + d.ignoreNextIndent = true + d.dump(d.unpackValue(v.MapIndex(key))) + if i < (numEntries - 1) { + d.w.Write(commaNewlineBytes) + } else { + d.w.Write(newlineBytes) + } + } + } + d.depth-- + d.indent() + d.w.Write(closeBraceBytes) + + case reflect.Struct: + d.w.Write(openBraceNewlineBytes) + d.depth++ + if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { + d.indent() + d.w.Write(maxNewlineBytes) + } else { + vt := v.Type() + numFields := v.NumField() + for i := 0; i < numFields; i++ { + d.indent() + vtf := vt.Field(i) + d.w.Write([]byte(vtf.Name)) + d.w.Write(colonSpaceBytes) + d.ignoreNextIndent = true + d.dump(d.unpackValue(v.Field(i))) + if i < (numFields - 1) { + d.w.Write(commaNewlineBytes) + } else { + d.w.Write(newlineBytes) + } + } + } + d.depth-- + d.indent() + d.w.Write(closeBraceBytes) + + case reflect.Uintptr: + printHexPtr(d.w, uintptr(v.Uint())) + + case reflect.UnsafePointer, reflect.Chan, reflect.Func: + printHexPtr(d.w, v.Pointer()) + + // There were not any other types at the time this code was written, but + // fall back to letting the default fmt package handle it in case any new + // types are added. + default: + if v.CanInterface() { + fmt.Fprintf(d.w, "%v", v.Interface()) + } else { + fmt.Fprintf(d.w, "%v", v.String()) + } + } +} + +// fdump is a helper function to consolidate the logic from the various public +// methods which take varying writers and config states. +func fdump(cs *ConfigState, w io.Writer, a ...interface{}) { + for _, arg := range a { + if arg == nil { + w.Write(interfaceBytes) + w.Write(spaceBytes) + w.Write(nilAngleBytes) + w.Write(newlineBytes) + continue + } + + d := dumpState{w: w, cs: cs} + d.pointers = make(map[uintptr]int) + d.dump(reflect.ValueOf(arg)) + d.w.Write(newlineBytes) + } +} + +// Fdump formats and displays the passed arguments to io.Writer w. It formats +// exactly the same as Dump. +func Fdump(w io.Writer, a ...interface{}) { + fdump(&Config, w, a...) +} + +// Sdump returns a string with the passed arguments formatted exactly the same +// as Dump. +func Sdump(a ...interface{}) string { + var buf bytes.Buffer + fdump(&Config, &buf, a...) + return buf.String() +} + +/* +Dump displays the passed parameters to standard out with newlines, customizable +indentation, and additional debug information such as complete types and all +pointer addresses used to indirect to the final value. It provides the +following features over the built-in printing facilities provided by the fmt +package: + + * Pointers are dereferenced and followed + * Circular data structures are detected and handled properly + * Custom Stringer/error interfaces are optionally invoked, including + on unexported types + * Custom types which only implement the Stringer/error interfaces via + a pointer receiver are optionally invoked when passing non-pointer + variables + * Byte arrays and slices are dumped like the hexdump -C command which + includes offsets, byte values in hex, and ASCII output + +The configuration options are controlled by an exported package global, +spew.Config. See ConfigState for options documentation. + +See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to +get the formatted result as a string. +*/ +func Dump(a ...interface{}) { + fdump(&Config, os.Stdout, a...) +} diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/format.go b/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/format.go new file mode 100644 index 00000000..ecf3b80e --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/format.go @@ -0,0 +1,419 @@ +/* + * Copyright (c) 2013 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "bytes" + "fmt" + "reflect" + "strconv" + "strings" +) + +// supportedFlags is a list of all the character flags supported by fmt package. +const supportedFlags = "0-+# " + +// formatState implements the fmt.Formatter interface and contains information +// about the state of a formatting operation. The NewFormatter function can +// be used to get a new Formatter which can be used directly as arguments +// in standard fmt package printing calls. +type formatState struct { + value interface{} + fs fmt.State + depth int + pointers map[uintptr]int + ignoreNextType bool + cs *ConfigState +} + +// buildDefaultFormat recreates the original format string without precision +// and width information to pass in to fmt.Sprintf in the case of an +// unrecognized type. Unless new types are added to the language, this +// function won't ever be called. +func (f *formatState) buildDefaultFormat() (format string) { + buf := bytes.NewBuffer(percentBytes) + + for _, flag := range supportedFlags { + if f.fs.Flag(int(flag)) { + buf.WriteRune(flag) + } + } + + buf.WriteRune('v') + + format = buf.String() + return format +} + +// constructOrigFormat recreates the original format string including precision +// and width information to pass along to the standard fmt package. This allows +// automatic deferral of all format strings this package doesn't support. +func (f *formatState) constructOrigFormat(verb rune) (format string) { + buf := bytes.NewBuffer(percentBytes) + + for _, flag := range supportedFlags { + if f.fs.Flag(int(flag)) { + buf.WriteRune(flag) + } + } + + if width, ok := f.fs.Width(); ok { + buf.WriteString(strconv.Itoa(width)) + } + + if precision, ok := f.fs.Precision(); ok { + buf.Write(precisionBytes) + buf.WriteString(strconv.Itoa(precision)) + } + + buf.WriteRune(verb) + + format = buf.String() + return format +} + +// unpackValue returns values inside of non-nil interfaces when possible and +// ensures that types for values which have been unpacked from an interface +// are displayed when the show types flag is also set. +// This is useful for data types like structs, arrays, slices, and maps which +// can contain varying types packed inside an interface. +func (f *formatState) unpackValue(v reflect.Value) reflect.Value { + if v.Kind() == reflect.Interface { + f.ignoreNextType = false + if !v.IsNil() { + v = v.Elem() + } + } + return v +} + +// formatPtr handles formatting of pointers by indirecting them as necessary. +func (f *formatState) formatPtr(v reflect.Value) { + // Display nil if top level pointer is nil. + showTypes := f.fs.Flag('#') + if v.IsNil() && (!showTypes || f.ignoreNextType) { + f.fs.Write(nilAngleBytes) + return + } + + // Remove pointers at or below the current depth from map used to detect + // circular refs. + for k, depth := range f.pointers { + if depth >= f.depth { + delete(f.pointers, k) + } + } + + // Keep list of all dereferenced pointers to possibly show later. + pointerChain := make([]uintptr, 0) + + // Figure out how many levels of indirection there are by derferencing + // pointers and unpacking interfaces down the chain while detecting circular + // references. + nilFound := false + cycleFound := false + indirects := 0 + ve := v + for ve.Kind() == reflect.Ptr { + if ve.IsNil() { + nilFound = true + break + } + indirects++ + addr := ve.Pointer() + pointerChain = append(pointerChain, addr) + if pd, ok := f.pointers[addr]; ok && pd < f.depth { + cycleFound = true + indirects-- + break + } + f.pointers[addr] = f.depth + + ve = ve.Elem() + if ve.Kind() == reflect.Interface { + if ve.IsNil() { + nilFound = true + break + } + ve = ve.Elem() + } + } + + // Display type or indirection level depending on flags. + if showTypes && !f.ignoreNextType { + f.fs.Write(openParenBytes) + f.fs.Write(bytes.Repeat(asteriskBytes, indirects)) + f.fs.Write([]byte(ve.Type().String())) + f.fs.Write(closeParenBytes) + } else { + if nilFound || cycleFound { + indirects += strings.Count(ve.Type().String(), "*") + } + f.fs.Write(openAngleBytes) + f.fs.Write([]byte(strings.Repeat("*", indirects))) + f.fs.Write(closeAngleBytes) + } + + // Display pointer information depending on flags. + if f.fs.Flag('+') && (len(pointerChain) > 0) { + f.fs.Write(openParenBytes) + for i, addr := range pointerChain { + if i > 0 { + f.fs.Write(pointerChainBytes) + } + printHexPtr(f.fs, addr) + } + f.fs.Write(closeParenBytes) + } + + // Display dereferenced value. + switch { + case nilFound == true: + f.fs.Write(nilAngleBytes) + + case cycleFound == true: + f.fs.Write(circularShortBytes) + + default: + f.ignoreNextType = true + f.format(ve) + } +} + +// format is the main workhorse for providing the Formatter interface. It +// uses the passed reflect value to figure out what kind of object we are +// dealing with and formats it appropriately. It is a recursive function, +// however circular data structures are detected and handled properly. +func (f *formatState) format(v reflect.Value) { + // Handle invalid reflect values immediately. + kind := v.Kind() + if kind == reflect.Invalid { + f.fs.Write(invalidAngleBytes) + return + } + + // Handle pointers specially. + if kind == reflect.Ptr { + f.formatPtr(v) + return + } + + // Print type information unless already handled elsewhere. + if !f.ignoreNextType && f.fs.Flag('#') { + f.fs.Write(openParenBytes) + f.fs.Write([]byte(v.Type().String())) + f.fs.Write(closeParenBytes) + } + f.ignoreNextType = false + + // Call Stringer/error interfaces if they exist and the handle methods + // flag is enabled. + if !f.cs.DisableMethods { + if (kind != reflect.Invalid) && (kind != reflect.Interface) { + if handled := handleMethods(f.cs, f.fs, v); handled { + return + } + } + } + + switch kind { + case reflect.Invalid: + // Do nothing. We should never get here since invalid has already + // been handled above. + + case reflect.Bool: + printBool(f.fs, v.Bool()) + + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + printInt(f.fs, v.Int(), 10) + + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + printUint(f.fs, v.Uint(), 10) + + case reflect.Float32: + printFloat(f.fs, v.Float(), 32) + + case reflect.Float64: + printFloat(f.fs, v.Float(), 64) + + case reflect.Complex64: + printComplex(f.fs, v.Complex(), 32) + + case reflect.Complex128: + printComplex(f.fs, v.Complex(), 64) + + case reflect.Slice: + if v.IsNil() { + f.fs.Write(nilAngleBytes) + break + } + fallthrough + + case reflect.Array: + f.fs.Write(openBracketBytes) + f.depth++ + if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { + f.fs.Write(maxShortBytes) + } else { + numEntries := v.Len() + for i := 0; i < numEntries; i++ { + if i > 0 { + f.fs.Write(spaceBytes) + } + f.ignoreNextType = true + f.format(f.unpackValue(v.Index(i))) + } + } + f.depth-- + f.fs.Write(closeBracketBytes) + + case reflect.String: + f.fs.Write([]byte(v.String())) + + case reflect.Interface: + // The only time we should get here is for nil interfaces due to + // unpackValue calls. + if v.IsNil() { + f.fs.Write(nilAngleBytes) + } + + case reflect.Ptr: + // Do nothing. We should never get here since pointers have already + // been handled above. + + case reflect.Map: + // nil maps should be indicated as different than empty maps + if v.IsNil() { + f.fs.Write(nilAngleBytes) + break + } + + f.fs.Write(openMapBytes) + f.depth++ + if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { + f.fs.Write(maxShortBytes) + } else { + keys := v.MapKeys() + if f.cs.SortKeys { + sortValues(keys, f.cs) + } + for i, key := range keys { + if i > 0 { + f.fs.Write(spaceBytes) + } + f.ignoreNextType = true + f.format(f.unpackValue(key)) + f.fs.Write(colonBytes) + f.ignoreNextType = true + f.format(f.unpackValue(v.MapIndex(key))) + } + } + f.depth-- + f.fs.Write(closeMapBytes) + + case reflect.Struct: + numFields := v.NumField() + f.fs.Write(openBraceBytes) + f.depth++ + if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { + f.fs.Write(maxShortBytes) + } else { + vt := v.Type() + for i := 0; i < numFields; i++ { + if i > 0 { + f.fs.Write(spaceBytes) + } + vtf := vt.Field(i) + if f.fs.Flag('+') || f.fs.Flag('#') { + f.fs.Write([]byte(vtf.Name)) + f.fs.Write(colonBytes) + } + f.format(f.unpackValue(v.Field(i))) + } + } + f.depth-- + f.fs.Write(closeBraceBytes) + + case reflect.Uintptr: + printHexPtr(f.fs, uintptr(v.Uint())) + + case reflect.UnsafePointer, reflect.Chan, reflect.Func: + printHexPtr(f.fs, v.Pointer()) + + // There were not any other types at the time this code was written, but + // fall back to letting the default fmt package handle it if any get added. + default: + format := f.buildDefaultFormat() + if v.CanInterface() { + fmt.Fprintf(f.fs, format, v.Interface()) + } else { + fmt.Fprintf(f.fs, format, v.String()) + } + } +} + +// Format satisfies the fmt.Formatter interface. See NewFormatter for usage +// details. +func (f *formatState) Format(fs fmt.State, verb rune) { + f.fs = fs + + // Use standard formatting for verbs that are not v. + if verb != 'v' { + format := f.constructOrigFormat(verb) + fmt.Fprintf(fs, format, f.value) + return + } + + if f.value == nil { + if fs.Flag('#') { + fs.Write(interfaceBytes) + } + fs.Write(nilAngleBytes) + return + } + + f.format(reflect.ValueOf(f.value)) +} + +// newFormatter is a helper function to consolidate the logic from the various +// public methods which take varying config states. +func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter { + fs := &formatState{value: v, cs: cs} + fs.pointers = make(map[uintptr]int) + return fs +} + +/* +NewFormatter returns a custom formatter that satisfies the fmt.Formatter +interface. As a result, it integrates cleanly with standard fmt package +printing functions. The formatter is useful for inline printing of smaller data +types similar to the standard %v format specifier. + +The custom formatter only responds to the %v (most compact), %+v (adds pointer +addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb +combinations. Any other verbs such as %x and %q will be sent to the the +standard fmt package for formatting. In addition, the custom formatter ignores +the width and precision arguments (however they will still work on the format +specifiers not handled by the custom formatter). + +Typically this function shouldn't be called directly. It is much easier to make +use of the custom formatter by calling one of the convenience functions such as +Printf, Println, or Fprintf. +*/ +func NewFormatter(v interface{}) fmt.Formatter { + return newFormatter(&Config, v) +} diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/spew.go b/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/spew.go new file mode 100644 index 00000000..d8233f54 --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/spew.go @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2013 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "fmt" + "io" +) + +// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the formatted string as a value that satisfies error. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Errorf(format, spew.NewFormatter(a), spew.NewFormatter(b)) +func Errorf(format string, a ...interface{}) (err error) { + return fmt.Errorf(format, convertArgs(a)...) +} + +// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprint(w, spew.NewFormatter(a), spew.NewFormatter(b)) +func Fprint(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprint(w, convertArgs(a)...) +} + +// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprintf(w, format, spew.NewFormatter(a), spew.NewFormatter(b)) +func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { + return fmt.Fprintf(w, format, convertArgs(a)...) +} + +// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it +// passed with a default Formatter interface returned by NewFormatter. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprintln(w, spew.NewFormatter(a), spew.NewFormatter(b)) +func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprintln(w, convertArgs(a)...) +} + +// Print is a wrapper for fmt.Print that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Print(spew.NewFormatter(a), spew.NewFormatter(b)) +func Print(a ...interface{}) (n int, err error) { + return fmt.Print(convertArgs(a)...) +} + +// Printf is a wrapper for fmt.Printf that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Printf(format, spew.NewFormatter(a), spew.NewFormatter(b)) +func Printf(format string, a ...interface{}) (n int, err error) { + return fmt.Printf(format, convertArgs(a)...) +} + +// Println is a wrapper for fmt.Println that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Println(spew.NewFormatter(a), spew.NewFormatter(b)) +func Println(a ...interface{}) (n int, err error) { + return fmt.Println(convertArgs(a)...) +} + +// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprint(spew.NewFormatter(a), spew.NewFormatter(b)) +func Sprint(a ...interface{}) string { + return fmt.Sprint(convertArgs(a)...) +} + +// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprintf(format, spew.NewFormatter(a), spew.NewFormatter(b)) +func Sprintf(format string, a ...interface{}) string { + return fmt.Sprintf(format, convertArgs(a)...) +} + +// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it +// were passed with a default Formatter interface returned by NewFormatter. It +// returns the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprintln(spew.NewFormatter(a), spew.NewFormatter(b)) +func Sprintln(a ...interface{}) string { + return fmt.Sprintln(convertArgs(a)...) +} + +// convertArgs accepts a slice of arguments and returns a slice of the same +// length with each argument converted to a default spew Formatter interface. +func convertArgs(args []interface{}) (formatters []interface{}) { + formatters = make([]interface{}, len(args)) + for index, arg := range args { + formatters[index] = NewFormatter(arg) + } + return formatters +} diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/pmezard/go-difflib/LICENSE b/vendor/github.com/stretchr/testify/vendor/github.com/pmezard/go-difflib/LICENSE new file mode 100644 index 00000000..c67dad61 --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/pmezard/go-difflib/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2013, Patrick Mezard +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + The names of its contributors may not be used to endorse or promote +products derived from this software without specific prior written +permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/pmezard/go-difflib/difflib/difflib.go b/vendor/github.com/stretchr/testify/vendor/github.com/pmezard/go-difflib/difflib/difflib.go new file mode 100644 index 00000000..64cc40fe --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/pmezard/go-difflib/difflib/difflib.go @@ -0,0 +1,758 @@ +// Package difflib is a partial port of Python difflib module. +// +// It provides tools to compare sequences of strings and generate textual diffs. +// +// The following class and functions have been ported: +// +// - SequenceMatcher +// +// - unified_diff +// +// - context_diff +// +// Getting unified diffs was the main goal of the port. Keep in mind this code +// is mostly suitable to output text differences in a human friendly way, there +// are no guarantees generated diffs are consumable by patch(1). +package difflib + +import ( + "bufio" + "bytes" + "fmt" + "io" + "strings" +) + +func min(a, b int) int { + if a < b { + return a + } + return b +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func calculateRatio(matches, length int) float64 { + if length > 0 { + return 2.0 * float64(matches) / float64(length) + } + return 1.0 +} + +type Match struct { + A int + B int + Size int +} + +type OpCode struct { + Tag byte + I1 int + I2 int + J1 int + J2 int +} + +// SequenceMatcher compares sequence of strings. The basic +// algorithm predates, and is a little fancier than, an algorithm +// published in the late 1980's by Ratcliff and Obershelp under the +// hyperbolic name "gestalt pattern matching". The basic idea is to find +// the longest contiguous matching subsequence that contains no "junk" +// elements (R-O doesn't address junk). The same idea is then applied +// recursively to the pieces of the sequences to the left and to the right +// of the matching subsequence. This does not yield minimal edit +// sequences, but does tend to yield matches that "look right" to people. +// +// SequenceMatcher tries to compute a "human-friendly diff" between two +// sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the +// longest *contiguous* & junk-free matching subsequence. That's what +// catches peoples' eyes. The Windows(tm) windiff has another interesting +// notion, pairing up elements that appear uniquely in each sequence. +// That, and the method here, appear to yield more intuitive difference +// reports than does diff. This method appears to be the least vulnerable +// to synching up on blocks of "junk lines", though (like blank lines in +// ordinary text files, or maybe "

" lines in HTML files). That may be +// because this is the only method of the 3 that has a *concept* of +// "junk" . +// +// Timing: Basic R-O is cubic time worst case and quadratic time expected +// case. SequenceMatcher is quadratic time for the worst case and has +// expected-case behavior dependent in a complicated way on how many +// elements the sequences have in common; best case time is linear. +type SequenceMatcher struct { + a []string + b []string + b2j map[string][]int + IsJunk func(string) bool + autoJunk bool + bJunk map[string]struct{} + matchingBlocks []Match + fullBCount map[string]int + bPopular map[string]struct{} + opCodes []OpCode +} + +func NewMatcher(a, b []string) *SequenceMatcher { + m := SequenceMatcher{autoJunk: true} + m.SetSeqs(a, b) + return &m +} + +func NewMatcherWithJunk(a, b []string, autoJunk bool, + isJunk func(string) bool) *SequenceMatcher { + + m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk} + m.SetSeqs(a, b) + return &m +} + +// Set two sequences to be compared. +func (m *SequenceMatcher) SetSeqs(a, b []string) { + m.SetSeq1(a) + m.SetSeq2(b) +} + +// Set the first sequence to be compared. The second sequence to be compared is +// not changed. +// +// SequenceMatcher computes and caches detailed information about the second +// sequence, so if you want to compare one sequence S against many sequences, +// use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other +// sequences. +// +// See also SetSeqs() and SetSeq2(). +func (m *SequenceMatcher) SetSeq1(a []string) { + if &a == &m.a { + return + } + m.a = a + m.matchingBlocks = nil + m.opCodes = nil +} + +// Set the second sequence to be compared. The first sequence to be compared is +// not changed. +func (m *SequenceMatcher) SetSeq2(b []string) { + if &b == &m.b { + return + } + m.b = b + m.matchingBlocks = nil + m.opCodes = nil + m.fullBCount = nil + m.chainB() +} + +func (m *SequenceMatcher) chainB() { + // Populate line -> index mapping + b2j := map[string][]int{} + for i, s := range m.b { + indices := b2j[s] + indices = append(indices, i) + b2j[s] = indices + } + + // Purge junk elements + m.bJunk = map[string]struct{}{} + if m.IsJunk != nil { + junk := m.bJunk + for s, _ := range b2j { + if m.IsJunk(s) { + junk[s] = struct{}{} + } + } + for s, _ := range junk { + delete(b2j, s) + } + } + + // Purge remaining popular elements + popular := map[string]struct{}{} + n := len(m.b) + if m.autoJunk && n >= 200 { + ntest := n/100 + 1 + for s, indices := range b2j { + if len(indices) > ntest { + popular[s] = struct{}{} + } + } + for s, _ := range popular { + delete(b2j, s) + } + } + m.bPopular = popular + m.b2j = b2j +} + +func (m *SequenceMatcher) isBJunk(s string) bool { + _, ok := m.bJunk[s] + return ok +} + +// Find longest matching block in a[alo:ahi] and b[blo:bhi]. +// +// If IsJunk is not defined: +// +// Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where +// alo <= i <= i+k <= ahi +// blo <= j <= j+k <= bhi +// and for all (i',j',k') meeting those conditions, +// k >= k' +// i <= i' +// and if i == i', j <= j' +// +// In other words, of all maximal matching blocks, return one that +// starts earliest in a, and of all those maximal matching blocks that +// start earliest in a, return the one that starts earliest in b. +// +// If IsJunk is defined, first the longest matching block is +// determined as above, but with the additional restriction that no +// junk element appears in the block. Then that block is extended as +// far as possible by matching (only) junk elements on both sides. So +// the resulting block never matches on junk except as identical junk +// happens to be adjacent to an "interesting" match. +// +// If no blocks match, return (alo, blo, 0). +func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match { + // CAUTION: stripping common prefix or suffix would be incorrect. + // E.g., + // ab + // acab + // Longest matching block is "ab", but if common prefix is + // stripped, it's "a" (tied with "b"). UNIX(tm) diff does so + // strip, so ends up claiming that ab is changed to acab by + // inserting "ca" in the middle. That's minimal but unintuitive: + // "it's obvious" that someone inserted "ac" at the front. + // Windiff ends up at the same place as diff, but by pairing up + // the unique 'b's and then matching the first two 'a's. + besti, bestj, bestsize := alo, blo, 0 + + // find longest junk-free match + // during an iteration of the loop, j2len[j] = length of longest + // junk-free match ending with a[i-1] and b[j] + j2len := map[int]int{} + for i := alo; i != ahi; i++ { + // look at all instances of a[i] in b; note that because + // b2j has no junk keys, the loop is skipped if a[i] is junk + newj2len := map[int]int{} + for _, j := range m.b2j[m.a[i]] { + // a[i] matches b[j] + if j < blo { + continue + } + if j >= bhi { + break + } + k := j2len[j-1] + 1 + newj2len[j] = k + if k > bestsize { + besti, bestj, bestsize = i-k+1, j-k+1, k + } + } + j2len = newj2len + } + + // Extend the best by non-junk elements on each end. In particular, + // "popular" non-junk elements aren't in b2j, which greatly speeds + // the inner loop above, but also means "the best" match so far + // doesn't contain any junk *or* popular non-junk elements. + for besti > alo && bestj > blo && !m.isBJunk(m.b[bestj-1]) && + m.a[besti-1] == m.b[bestj-1] { + besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 + } + for besti+bestsize < ahi && bestj+bestsize < bhi && + !m.isBJunk(m.b[bestj+bestsize]) && + m.a[besti+bestsize] == m.b[bestj+bestsize] { + bestsize += 1 + } + + // Now that we have a wholly interesting match (albeit possibly + // empty!), we may as well suck up the matching junk on each + // side of it too. Can't think of a good reason not to, and it + // saves post-processing the (possibly considerable) expense of + // figuring out what to do with it. In the case of an empty + // interesting match, this is clearly the right thing to do, + // because no other kind of match is possible in the regions. + for besti > alo && bestj > blo && m.isBJunk(m.b[bestj-1]) && + m.a[besti-1] == m.b[bestj-1] { + besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 + } + for besti+bestsize < ahi && bestj+bestsize < bhi && + m.isBJunk(m.b[bestj+bestsize]) && + m.a[besti+bestsize] == m.b[bestj+bestsize] { + bestsize += 1 + } + + return Match{A: besti, B: bestj, Size: bestsize} +} + +// Return list of triples describing matching subsequences. +// +// Each triple is of the form (i, j, n), and means that +// a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in +// i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are +// adjacent triples in the list, and the second is not the last triple in the +// list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe +// adjacent equal blocks. +// +// The last triple is a dummy, (len(a), len(b), 0), and is the only +// triple with n==0. +func (m *SequenceMatcher) GetMatchingBlocks() []Match { + if m.matchingBlocks != nil { + return m.matchingBlocks + } + + var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match + matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match { + match := m.findLongestMatch(alo, ahi, blo, bhi) + i, j, k := match.A, match.B, match.Size + if match.Size > 0 { + if alo < i && blo < j { + matched = matchBlocks(alo, i, blo, j, matched) + } + matched = append(matched, match) + if i+k < ahi && j+k < bhi { + matched = matchBlocks(i+k, ahi, j+k, bhi, matched) + } + } + return matched + } + matched := matchBlocks(0, len(m.a), 0, len(m.b), nil) + + // It's possible that we have adjacent equal blocks in the + // matching_blocks list now. + nonAdjacent := []Match{} + i1, j1, k1 := 0, 0, 0 + for _, b := range matched { + // Is this block adjacent to i1, j1, k1? + i2, j2, k2 := b.A, b.B, b.Size + if i1+k1 == i2 && j1+k1 == j2 { + // Yes, so collapse them -- this just increases the length of + // the first block by the length of the second, and the first + // block so lengthened remains the block to compare against. + k1 += k2 + } else { + // Not adjacent. Remember the first block (k1==0 means it's + // the dummy we started with), and make the second block the + // new block to compare against. + if k1 > 0 { + nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) + } + i1, j1, k1 = i2, j2, k2 + } + } + if k1 > 0 { + nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) + } + + nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0}) + m.matchingBlocks = nonAdjacent + return m.matchingBlocks +} + +// Return list of 5-tuples describing how to turn a into b. +// +// Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple +// has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the +// tuple preceding it, and likewise for j1 == the previous j2. +// +// The tags are characters, with these meanings: +// +// 'r' (replace): a[i1:i2] should be replaced by b[j1:j2] +// +// 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case. +// +// 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case. +// +// 'e' (equal): a[i1:i2] == b[j1:j2] +func (m *SequenceMatcher) GetOpCodes() []OpCode { + if m.opCodes != nil { + return m.opCodes + } + i, j := 0, 0 + matching := m.GetMatchingBlocks() + opCodes := make([]OpCode, 0, len(matching)) + for _, m := range matching { + // invariant: we've pumped out correct diffs to change + // a[:i] into b[:j], and the next matching block is + // a[ai:ai+size] == b[bj:bj+size]. So we need to pump + // out a diff to change a[i:ai] into b[j:bj], pump out + // the matching block, and move (i,j) beyond the match + ai, bj, size := m.A, m.B, m.Size + tag := byte(0) + if i < ai && j < bj { + tag = 'r' + } else if i < ai { + tag = 'd' + } else if j < bj { + tag = 'i' + } + if tag > 0 { + opCodes = append(opCodes, OpCode{tag, i, ai, j, bj}) + } + i, j = ai+size, bj+size + // the list of matching blocks is terminated by a + // sentinel with size 0 + if size > 0 { + opCodes = append(opCodes, OpCode{'e', ai, i, bj, j}) + } + } + m.opCodes = opCodes + return m.opCodes +} + +// Isolate change clusters by eliminating ranges with no changes. +// +// Return a generator of groups with up to n lines of context. +// Each group is in the same format as returned by GetOpCodes(). +func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode { + if n < 0 { + n = 3 + } + codes := m.GetOpCodes() + if len(codes) == 0 { + codes = []OpCode{OpCode{'e', 0, 1, 0, 1}} + } + // Fixup leading and trailing groups if they show no changes. + if codes[0].Tag == 'e' { + c := codes[0] + i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 + codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2} + } + if codes[len(codes)-1].Tag == 'e' { + c := codes[len(codes)-1] + i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 + codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)} + } + nn := n + n + groups := [][]OpCode{} + group := []OpCode{} + for _, c := range codes { + i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 + // End the current group and start a new one whenever + // there is a large range with no changes. + if c.Tag == 'e' && i2-i1 > nn { + group = append(group, OpCode{c.Tag, i1, min(i2, i1+n), + j1, min(j2, j1+n)}) + groups = append(groups, group) + group = []OpCode{} + i1, j1 = max(i1, i2-n), max(j1, j2-n) + } + group = append(group, OpCode{c.Tag, i1, i2, j1, j2}) + } + if len(group) > 0 && !(len(group) == 1 && group[0].Tag == 'e') { + groups = append(groups, group) + } + return groups +} + +// Return a measure of the sequences' similarity (float in [0,1]). +// +// Where T is the total number of elements in both sequences, and +// M is the number of matches, this is 2.0*M / T. +// Note that this is 1 if the sequences are identical, and 0 if +// they have nothing in common. +// +// .Ratio() is expensive to compute if you haven't already computed +// .GetMatchingBlocks() or .GetOpCodes(), in which case you may +// want to try .QuickRatio() or .RealQuickRation() first to get an +// upper bound. +func (m *SequenceMatcher) Ratio() float64 { + matches := 0 + for _, m := range m.GetMatchingBlocks() { + matches += m.Size + } + return calculateRatio(matches, len(m.a)+len(m.b)) +} + +// Return an upper bound on ratio() relatively quickly. +// +// This isn't defined beyond that it is an upper bound on .Ratio(), and +// is faster to compute. +func (m *SequenceMatcher) QuickRatio() float64 { + // viewing a and b as multisets, set matches to the cardinality + // of their intersection; this counts the number of matches + // without regard to order, so is clearly an upper bound + if m.fullBCount == nil { + m.fullBCount = map[string]int{} + for _, s := range m.b { + m.fullBCount[s] = m.fullBCount[s] + 1 + } + } + + // avail[x] is the number of times x appears in 'b' less the + // number of times we've seen it in 'a' so far ... kinda + avail := map[string]int{} + matches := 0 + for _, s := range m.a { + n, ok := avail[s] + if !ok { + n = m.fullBCount[s] + } + avail[s] = n - 1 + if n > 0 { + matches += 1 + } + } + return calculateRatio(matches, len(m.a)+len(m.b)) +} + +// Return an upper bound on ratio() very quickly. +// +// This isn't defined beyond that it is an upper bound on .Ratio(), and +// is faster to compute than either .Ratio() or .QuickRatio(). +func (m *SequenceMatcher) RealQuickRatio() float64 { + la, lb := len(m.a), len(m.b) + return calculateRatio(min(la, lb), la+lb) +} + +// Convert range to the "ed" format +func formatRangeUnified(start, stop int) string { + // Per the diff spec at http://www.unix.org/single_unix_specification/ + beginning := start + 1 // lines start numbering with one + length := stop - start + if length == 1 { + return fmt.Sprintf("%d", beginning) + } + if length == 0 { + beginning -= 1 // empty ranges begin at line just before the range + } + return fmt.Sprintf("%d,%d", beginning, length) +} + +// Unified diff parameters +type UnifiedDiff struct { + A []string // First sequence lines + FromFile string // First file name + FromDate string // First file time + B []string // Second sequence lines + ToFile string // Second file name + ToDate string // Second file time + Eol string // Headers end of line, defaults to LF + Context int // Number of context lines +} + +// Compare two sequences of lines; generate the delta as a unified diff. +// +// Unified diffs are a compact way of showing line changes and a few +// lines of context. The number of context lines is set by 'n' which +// defaults to three. +// +// By default, the diff control lines (those with ---, +++, or @@) are +// created with a trailing newline. This is helpful so that inputs +// created from file.readlines() result in diffs that are suitable for +// file.writelines() since both the inputs and outputs have trailing +// newlines. +// +// For inputs that do not have trailing newlines, set the lineterm +// argument to "" so that the output will be uniformly newline free. +// +// The unidiff format normally has a header for filenames and modification +// times. Any or all of these may be specified using strings for +// 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. +// The modification times are normally expressed in the ISO 8601 format. +func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error { + buf := bufio.NewWriter(writer) + defer buf.Flush() + w := func(format string, args ...interface{}) error { + _, err := buf.WriteString(fmt.Sprintf(format, args...)) + return err + } + + if len(diff.Eol) == 0 { + diff.Eol = "\n" + } + + started := false + m := NewMatcher(diff.A, diff.B) + for _, g := range m.GetGroupedOpCodes(diff.Context) { + if !started { + started = true + fromDate := "" + if len(diff.FromDate) > 0 { + fromDate = "\t" + diff.FromDate + } + toDate := "" + if len(diff.ToDate) > 0 { + toDate = "\t" + diff.ToDate + } + err := w("--- %s%s%s", diff.FromFile, fromDate, diff.Eol) + if err != nil { + return err + } + err = w("+++ %s%s%s", diff.ToFile, toDate, diff.Eol) + if err != nil { + return err + } + } + first, last := g[0], g[len(g)-1] + range1 := formatRangeUnified(first.I1, last.I2) + range2 := formatRangeUnified(first.J1, last.J2) + if err := w("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil { + return err + } + for _, c := range g { + i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 + if c.Tag == 'e' { + for _, line := range diff.A[i1:i2] { + if err := w(" " + line); err != nil { + return err + } + } + continue + } + if c.Tag == 'r' || c.Tag == 'd' { + for _, line := range diff.A[i1:i2] { + if err := w("-" + line); err != nil { + return err + } + } + } + if c.Tag == 'r' || c.Tag == 'i' { + for _, line := range diff.B[j1:j2] { + if err := w("+" + line); err != nil { + return err + } + } + } + } + } + return nil +} + +// Like WriteUnifiedDiff but returns the diff a string. +func GetUnifiedDiffString(diff UnifiedDiff) (string, error) { + w := &bytes.Buffer{} + err := WriteUnifiedDiff(w, diff) + return string(w.Bytes()), err +} + +// Convert range to the "ed" format. +func formatRangeContext(start, stop int) string { + // Per the diff spec at http://www.unix.org/single_unix_specification/ + beginning := start + 1 // lines start numbering with one + length := stop - start + if length == 0 { + beginning -= 1 // empty ranges begin at line just before the range + } + if length <= 1 { + return fmt.Sprintf("%d", beginning) + } + return fmt.Sprintf("%d,%d", beginning, beginning+length-1) +} + +type ContextDiff UnifiedDiff + +// Compare two sequences of lines; generate the delta as a context diff. +// +// Context diffs are a compact way of showing line changes and a few +// lines of context. The number of context lines is set by diff.Context +// which defaults to three. +// +// By default, the diff control lines (those with *** or ---) are +// created with a trailing newline. +// +// For inputs that do not have trailing newlines, set the diff.Eol +// argument to "" so that the output will be uniformly newline free. +// +// The context diff format normally has a header for filenames and +// modification times. Any or all of these may be specified using +// strings for diff.FromFile, diff.ToFile, diff.FromDate, diff.ToDate. +// The modification times are normally expressed in the ISO 8601 format. +// If not specified, the strings default to blanks. +func WriteContextDiff(writer io.Writer, diff ContextDiff) error { + buf := bufio.NewWriter(writer) + defer buf.Flush() + var diffErr error + w := func(format string, args ...interface{}) { + _, err := buf.WriteString(fmt.Sprintf(format, args...)) + if diffErr == nil && err != nil { + diffErr = err + } + } + + if len(diff.Eol) == 0 { + diff.Eol = "\n" + } + + prefix := map[byte]string{ + 'i': "+ ", + 'd': "- ", + 'r': "! ", + 'e': " ", + } + + started := false + m := NewMatcher(diff.A, diff.B) + for _, g := range m.GetGroupedOpCodes(diff.Context) { + if !started { + started = true + fromDate := "" + if len(diff.FromDate) > 0 { + fromDate = "\t" + diff.FromDate + } + toDate := "" + if len(diff.ToDate) > 0 { + toDate = "\t" + diff.ToDate + } + w("*** %s%s%s", diff.FromFile, fromDate, diff.Eol) + w("--- %s%s%s", diff.ToFile, toDate, diff.Eol) + } + + first, last := g[0], g[len(g)-1] + w("***************" + diff.Eol) + + range1 := formatRangeContext(first.I1, last.I2) + w("*** %s ****%s", range1, diff.Eol) + for _, c := range g { + if c.Tag == 'r' || c.Tag == 'd' { + for _, cc := range g { + if cc.Tag == 'i' { + continue + } + for _, line := range diff.A[cc.I1:cc.I2] { + w(prefix[cc.Tag] + line) + } + } + break + } + } + + range2 := formatRangeContext(first.J1, last.J2) + w("--- %s ----%s", range2, diff.Eol) + for _, c := range g { + if c.Tag == 'r' || c.Tag == 'i' { + for _, cc := range g { + if cc.Tag == 'd' { + continue + } + for _, line := range diff.B[cc.J1:cc.J2] { + w(prefix[cc.Tag] + line) + } + } + break + } + } + } + return diffErr +} + +// Like WriteContextDiff but returns the diff a string. +func GetContextDiffString(diff ContextDiff) (string, error) { + w := &bytes.Buffer{} + err := WriteContextDiff(w, diff) + return string(w.Bytes()), err +} + +// Split a string on "\n" while preserving them. The output can be used +// as input for UnifiedDiff and ContextDiff structures. +func SplitLines(s string) []string { + lines := strings.SplitAfter(s, "\n") + lines[len(lines)-1] += "\n" + return lines +} diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/.gitignore b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/.gitignore new file mode 100644 index 00000000..00268614 --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/.gitignore @@ -0,0 +1,22 @@ +# 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 diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/LICENSE.md b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/LICENSE.md new file mode 100644 index 00000000..21999458 --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/LICENSE.md @@ -0,0 +1,23 @@ +objx - by Mat Ryer and Tyler Bunnell + +The MIT License (MIT) + +Copyright (c) 2014 Stretchr, Inc. + +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. diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/README.md b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/README.md new file mode 100644 index 00000000..4aa18068 --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/README.md @@ -0,0 +1,3 @@ +# objx + + * Jump into the [API Documentation](http://godoc.org/github.com/stretchr/objx) diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/accessors.go b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/accessors.go new file mode 100644 index 00000000..721bcac7 --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/accessors.go @@ -0,0 +1,179 @@ +package objx + +import ( + "fmt" + "regexp" + "strconv" + "strings" +) + +// arrayAccesRegexString is the regex used to extract the array number +// from the access path +const arrayAccesRegexString = `^(.+)\[([0-9]+)\]$` + +// arrayAccesRegex is the compiled arrayAccesRegexString +var arrayAccesRegex = regexp.MustCompile(arrayAccesRegexString) + +// Get gets the value using the specified selector and +// returns it inside a new Obj object. +// +// If it cannot find the value, Get will return a nil +// value inside an instance of Obj. +// +// Get can only operate directly on map[string]interface{} and []interface. +// +// Example +// +// To access the title of the third chapter of the second book, do: +// +// o.Get("books[1].chapters[2].title") +func (m Map) Get(selector string) *Value { + rawObj := access(m, selector, nil, false, false) + return &Value{data: rawObj} +} + +// Set sets the value using the specified selector and +// returns the object on which Set was called. +// +// Set can only operate directly on map[string]interface{} and []interface +// +// Example +// +// To set the title of the third chapter of the second book, do: +// +// o.Set("books[1].chapters[2].title","Time to Go") +func (m Map) Set(selector string, value interface{}) Map { + access(m, selector, value, true, false) + return m +} + +// access accesses the object using the selector and performs the +// appropriate action. +func access(current, selector, value interface{}, isSet, panics bool) interface{} { + + switch selector.(type) { + case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: + + if array, ok := current.([]interface{}); ok { + index := intFromInterface(selector) + + if index >= len(array) { + if panics { + panic(fmt.Sprintf("objx: Index %d is out of range. Slice only contains %d items.", index, len(array))) + } + return nil + } + + return array[index] + } + + return nil + + case string: + + selStr := selector.(string) + selSegs := strings.SplitN(selStr, PathSeparator, 2) + thisSel := selSegs[0] + index := -1 + var err error + + // https://github.com/stretchr/objx/issues/12 + if strings.Contains(thisSel, "[") { + + arrayMatches := arrayAccesRegex.FindStringSubmatch(thisSel) + + if len(arrayMatches) > 0 { + + // Get the key into the map + thisSel = arrayMatches[1] + + // Get the index into the array at the key + index, err = strconv.Atoi(arrayMatches[2]) + + if err != nil { + // This should never happen. If it does, something has gone + // seriously wrong. Panic. + panic("objx: Array index is not an integer. Must use array[int].") + } + + } + } + + if curMap, ok := current.(Map); ok { + current = map[string]interface{}(curMap) + } + + // get the object in question + switch current.(type) { + case map[string]interface{}: + curMSI := current.(map[string]interface{}) + if len(selSegs) <= 1 && isSet { + curMSI[thisSel] = value + return nil + } else { + current = curMSI[thisSel] + } + default: + current = nil + } + + if current == nil && panics { + panic(fmt.Sprintf("objx: '%v' invalid on object.", selector)) + } + + // do we need to access the item of an array? + if index > -1 { + if array, ok := current.([]interface{}); ok { + if index < len(array) { + current = array[index] + } else { + if panics { + panic(fmt.Sprintf("objx: Index %d is out of range. Slice only contains %d items.", index, len(array))) + } + current = nil + } + } + } + + if len(selSegs) > 1 { + current = access(current, selSegs[1], value, isSet, panics) + } + + } + + return current + +} + +// intFromInterface converts an interface object to the largest +// representation of an unsigned integer using a type switch and +// assertions +func intFromInterface(selector interface{}) int { + var value int + switch selector.(type) { + case int: + value = selector.(int) + case int8: + value = int(selector.(int8)) + case int16: + value = int(selector.(int16)) + case int32: + value = int(selector.(int32)) + case int64: + value = int(selector.(int64)) + case uint: + value = int(selector.(uint)) + case uint8: + value = int(selector.(uint8)) + case uint16: + value = int(selector.(uint16)) + case uint32: + value = int(selector.(uint32)) + case uint64: + value = int(selector.(uint64)) + default: + panic("objx: array access argument is not an integer type (this should never happen)") + } + + return value +} diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/codegen/array-access.txt b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/codegen/array-access.txt new file mode 100644 index 00000000..30602347 --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/codegen/array-access.txt @@ -0,0 +1,14 @@ + case []{1}: + a := object.([]{1}) + if isSet { + a[index] = value.({1}) + } else { + if index >= len(a) { + if panics { + panic(fmt.Sprintf("objx: Index %d is out of range because the []{1} only contains %d items.", index, len(a))) + } + return nil + } else { + return a[index] + } + } diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/codegen/index.html b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/codegen/index.html new file mode 100644 index 00000000..379ffc3c --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/codegen/index.html @@ -0,0 +1,86 @@ + + + + Codegen + + + + + +

+ Template +

+

+ Use {x} as a placeholder for each argument. +

+ + +

+ Arguments (comma separated) +

+

+ One block per line +

+ + +

+ Output +

+ + + + + + + + diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/codegen/template.txt b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/codegen/template.txt new file mode 100644 index 00000000..b396900b --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/codegen/template.txt @@ -0,0 +1,286 @@ +/* + {4} ({1} and []{1}) + -------------------------------------------------- +*/ + +// {4} gets the value as a {1}, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) {4}(optionalDefault ...{1}) {1} { + if s, ok := v.data.({1}); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return {3} +} + +// Must{4} gets the value as a {1}. +// +// Panics if the object is not a {1}. +func (v *Value) Must{4}() {1} { + return v.data.({1}) +} + +// {4}Slice gets the value as a []{1}, returns the optionalDefault +// value or nil if the value is not a []{1}. +func (v *Value) {4}Slice(optionalDefault ...[]{1}) []{1} { + if s, ok := v.data.([]{1}); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// Must{4}Slice gets the value as a []{1}. +// +// Panics if the object is not a []{1}. +func (v *Value) Must{4}Slice() []{1} { + return v.data.([]{1}) +} + +// Is{4} gets whether the object contained is a {1} or not. +func (v *Value) Is{4}() bool { + _, ok := v.data.({1}) + return ok +} + +// Is{4}Slice gets whether the object contained is a []{1} or not. +func (v *Value) Is{4}Slice() bool { + _, ok := v.data.([]{1}) + return ok +} + +// Each{4} calls the specified callback for each object +// in the []{1}. +// +// Panics if the object is the wrong type. +func (v *Value) Each{4}(callback func(int, {1}) bool) *Value { + + for index, val := range v.Must{4}Slice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// Where{4} uses the specified decider function to select items +// from the []{1}. The object contained in the result will contain +// only the selected items. +func (v *Value) Where{4}(decider func(int, {1}) bool) *Value { + + var selected []{1} + + v.Each{4}(func(index int, val {1}) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data:selected} + +} + +// Group{4} uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]{1}. +func (v *Value) Group{4}(grouper func(int, {1}) string) *Value { + + groups := make(map[string][]{1}) + + v.Each{4}(func(index int, val {1}) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]{1}, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data:groups} + +} + +// Replace{4} uses the specified function to replace each {1}s +// by iterating each item. The data in the returned result will be a +// []{1} containing the replaced items. +func (v *Value) Replace{4}(replacer func(int, {1}) {1}) *Value { + + arr := v.Must{4}Slice() + replaced := make([]{1}, len(arr)) + + v.Each{4}(func(index int, val {1}) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data:replaced} + +} + +// Collect{4} uses the specified collector function to collect a value +// for each of the {1}s in the slice. The data returned will be a +// []interface{}. +func (v *Value) Collect{4}(collector func(int, {1}) interface{}) *Value { + + arr := v.Must{4}Slice() + collected := make([]interface{}, len(arr)) + + v.Each{4}(func(index int, val {1}) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data:collected} +} + +// ************************************************************ +// TESTS +// ************************************************************ + +func Test{4}(t *testing.T) { + + val := {1}( {2} ) + m := map[string]interface{}{"value": val, "nothing": nil} + assert.Equal(t, val, New(m).Get("value").{4}()) + assert.Equal(t, val, New(m).Get("value").Must{4}()) + assert.Equal(t, {1}({3}), New(m).Get("nothing").{4}()) + assert.Equal(t, val, New(m).Get("nothing").{4}({2})) + + assert.Panics(t, func() { + New(m).Get("age").Must{4}() + }) + +} + +func Test{4}Slice(t *testing.T) { + + val := {1}( {2} ) + m := map[string]interface{}{"value": []{1}{ val }, "nothing": nil} + assert.Equal(t, val, New(m).Get("value").{4}Slice()[0]) + assert.Equal(t, val, New(m).Get("value").Must{4}Slice()[0]) + assert.Equal(t, []{1}(nil), New(m).Get("nothing").{4}Slice()) + assert.Equal(t, val, New(m).Get("nothing").{4}Slice( []{1}{ {1}({2}) } )[0]) + + assert.Panics(t, func() { + New(m).Get("nothing").Must{4}Slice() + }) + +} + +func TestIs{4}(t *testing.T) { + + var v *Value + + v = &Value{data: {1}({2})} + assert.True(t, v.Is{4}()) + + v = &Value{data: []{1}{ {1}({2}) }} + assert.True(t, v.Is{4}Slice()) + +} + +func TestEach{4}(t *testing.T) { + + v := &Value{data: []{1}{ {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}) }} + count := 0 + replacedVals := make([]{1}, 0) + assert.Equal(t, v, v.Each{4}(func(i int, val {1}) bool { + + count++ + replacedVals = append(replacedVals, val) + + // abort early + if i == 2 { + return false + } + + return true + + })) + + assert.Equal(t, count, 3) + assert.Equal(t, replacedVals[0], v.Must{4}Slice()[0]) + assert.Equal(t, replacedVals[1], v.Must{4}Slice()[1]) + assert.Equal(t, replacedVals[2], v.Must{4}Slice()[2]) + +} + +func TestWhere{4}(t *testing.T) { + + v := &Value{data: []{1}{ {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}) }} + + selected := v.Where{4}(func(i int, val {1}) bool { + return i%2==0 + }).Must{4}Slice() + + assert.Equal(t, 3, len(selected)) + +} + +func TestGroup{4}(t *testing.T) { + + v := &Value{data: []{1}{ {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}) }} + + grouped := v.Group{4}(func(i int, val {1}) string { + return fmt.Sprintf("%v", i%2==0) + }).data.(map[string][]{1}) + + assert.Equal(t, 2, len(grouped)) + assert.Equal(t, 3, len(grouped["true"])) + assert.Equal(t, 3, len(grouped["false"])) + +} + +func TestReplace{4}(t *testing.T) { + + v := &Value{data: []{1}{ {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}) }} + + rawArr := v.Must{4}Slice() + + replaced := v.Replace{4}(func(index int, val {1}) {1} { + if index < len(rawArr)-1 { + return rawArr[index+1] + } + return rawArr[0] + }) + + replacedArr := replaced.Must{4}Slice() + if assert.Equal(t, 6, len(replacedArr)) { + assert.Equal(t, replacedArr[0], rawArr[1]) + assert.Equal(t, replacedArr[1], rawArr[2]) + assert.Equal(t, replacedArr[2], rawArr[3]) + assert.Equal(t, replacedArr[3], rawArr[4]) + assert.Equal(t, replacedArr[4], rawArr[5]) + assert.Equal(t, replacedArr[5], rawArr[0]) + } + +} + +func TestCollect{4}(t *testing.T) { + + v := &Value{data: []{1}{ {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}) }} + + collected := v.Collect{4}(func(index int, val {1}) interface{} { + return index + }) + + collectedArr := collected.MustInterSlice() + if assert.Equal(t, 6, len(collectedArr)) { + assert.Equal(t, collectedArr[0], 0) + assert.Equal(t, collectedArr[1], 1) + assert.Equal(t, collectedArr[2], 2) + assert.Equal(t, collectedArr[3], 3) + assert.Equal(t, collectedArr[4], 4) + assert.Equal(t, collectedArr[5], 5) + } + +} diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/codegen/types_list.txt b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/codegen/types_list.txt new file mode 100644 index 00000000..069d43d8 --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/codegen/types_list.txt @@ -0,0 +1,20 @@ +Interface,interface{},"something",nil,Inter +Map,map[string]interface{},map[string]interface{}{"name":"Tyler"},nil,MSI +ObjxMap,(Map),New(1),New(nil),ObjxMap +Bool,bool,true,false,Bool +String,string,"hello","",Str +Int,int,1,0,Int +Int8,int8,1,0,Int8 +Int16,int16,1,0,Int16 +Int32,int32,1,0,Int32 +Int64,int64,1,0,Int64 +Uint,uint,1,0,Uint +Uint8,uint8,1,0,Uint8 +Uint16,uint16,1,0,Uint16 +Uint32,uint32,1,0,Uint32 +Uint64,uint64,1,0,Uint64 +Uintptr,uintptr,1,0,Uintptr +Float32,float32,1,0,Float32 +Float64,float64,1,0,Float64 +Complex64,complex64,1,0,Complex64 +Complex128,complex128,1,0,Complex128 diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/constants.go b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/constants.go new file mode 100644 index 00000000..f9eb42a2 --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/constants.go @@ -0,0 +1,13 @@ +package objx + +const ( + // PathSeparator is the character used to separate the elements + // of the keypath. + // + // For example, `location.address.city` + PathSeparator string = "." + + // SignatureSeparator is the character that is used to + // separate the Base64 string from the security signature. + SignatureSeparator = "_" +) diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/conversions.go b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/conversions.go new file mode 100644 index 00000000..9cdfa9f9 --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/conversions.go @@ -0,0 +1,117 @@ +package objx + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/url" +) + +// JSON converts the contained object to a JSON string +// representation +func (m Map) JSON() (string, error) { + + result, err := json.Marshal(m) + + if err != nil { + err = errors.New("objx: JSON encode failed with: " + err.Error()) + } + + return string(result), err + +} + +// MustJSON converts the contained object to a JSON string +// representation and panics if there is an error +func (m Map) MustJSON() string { + result, err := m.JSON() + if err != nil { + panic(err.Error()) + } + return result +} + +// Base64 converts the contained object to a Base64 string +// representation of the JSON string representation +func (m Map) Base64() (string, error) { + + var buf bytes.Buffer + + jsonData, err := m.JSON() + if err != nil { + return "", err + } + + encoder := base64.NewEncoder(base64.StdEncoding, &buf) + encoder.Write([]byte(jsonData)) + encoder.Close() + + return buf.String(), nil + +} + +// MustBase64 converts the contained object to a Base64 string +// representation of the JSON string representation and panics +// if there is an error +func (m Map) MustBase64() string { + result, err := m.Base64() + if err != nil { + panic(err.Error()) + } + return result +} + +// SignedBase64 converts the contained object to a Base64 string +// representation of the JSON string representation and signs it +// using the provided key. +func (m Map) SignedBase64(key string) (string, error) { + + base64, err := m.Base64() + if err != nil { + return "", err + } + + sig := HashWithKey(base64, key) + + return base64 + SignatureSeparator + sig, nil + +} + +// MustSignedBase64 converts the contained object to a Base64 string +// representation of the JSON string representation and signs it +// using the provided key and panics if there is an error +func (m Map) MustSignedBase64(key string) string { + result, err := m.SignedBase64(key) + if err != nil { + panic(err.Error()) + } + return result +} + +/* + URL Query + ------------------------------------------------ +*/ + +// URLValues creates a url.Values object from an Obj. This +// function requires that the wrapped object be a map[string]interface{} +func (m Map) URLValues() url.Values { + + vals := make(url.Values) + + for k, v := range m { + //TODO: can this be done without sprintf? + vals.Set(k, fmt.Sprintf("%v", v)) + } + + return vals +} + +// URLQuery gets an encoded URL query representing the given +// Obj. This function requires that the wrapped object be a +// map[string]interface{} +func (m Map) URLQuery() (string, error) { + return m.URLValues().Encode(), nil +} diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/doc.go b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/doc.go new file mode 100644 index 00000000..47bf85e4 --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/doc.go @@ -0,0 +1,72 @@ +// objx - Go package for dealing with maps, slices, JSON and other data. +// +// Overview +// +// Objx provides the `objx.Map` type, which is a `map[string]interface{}` that exposes +// a powerful `Get` method (among others) that allows you to easily and quickly get +// access to data within the map, without having to worry too much about type assertions, +// missing data, default values etc. +// +// Pattern +// +// Objx uses a preditable pattern to make access data from within `map[string]interface{}'s +// easy. +// +// Call one of the `objx.` functions to create your `objx.Map` to get going: +// +// m, err := objx.FromJSON(json) +// +// NOTE: Any methods or functions with the `Must` prefix will panic if something goes wrong, +// the rest will be optimistic and try to figure things out without panicking. +// +// Use `Get` to access the value you're interested in. You can use dot and array +// notation too: +// +// m.Get("places[0].latlng") +// +// Once you have saught the `Value` you're interested in, you can use the `Is*` methods +// to determine its type. +// +// if m.Get("code").IsStr() { /* ... */ } +// +// Or you can just assume the type, and use one of the strong type methods to +// extract the real value: +// +// m.Get("code").Int() +// +// If there's no value there (or if it's the wrong type) then a default value +// will be returned, or you can be explicit about the default value. +// +// Get("code").Int(-1) +// +// If you're dealing with a slice of data as a value, Objx provides many useful +// methods for iterating, manipulating and selecting that data. You can find out more +// by exploring the index below. +// +// Reading data +// +// A simple example of how to use Objx: +// +// // use MustFromJSON to make an objx.Map from some JSON +// m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`) +// +// // get the details +// name := m.Get("name").Str() +// age := m.Get("age").Int() +// +// // get their nickname (or use their name if they +// // don't have one) +// nickname := m.Get("nickname").Str(name) +// +// Ranging +// +// Since `objx.Map` is a `map[string]interface{}` you can treat it as such. For +// example, to `range` the data, do what you would expect: +// +// m := objx.MustFromJSON(json) +// for key, value := range m { +// +// /* ... do your magic ... */ +// +// } +package objx diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/map.go b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/map.go new file mode 100644 index 00000000..eb6ed8e2 --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/map.go @@ -0,0 +1,222 @@ +package objx + +import ( + "encoding/base64" + "encoding/json" + "errors" + "io/ioutil" + "net/url" + "strings" +) + +// MSIConvertable is an interface that defines methods for converting your +// custom types to a map[string]interface{} representation. +type MSIConvertable interface { + // MSI gets a map[string]interface{} (msi) representing the + // object. + MSI() map[string]interface{} +} + +// Map provides extended functionality for working with +// untyped data, in particular map[string]interface (msi). +type Map map[string]interface{} + +// Value returns the internal value instance +func (m Map) Value() *Value { + return &Value{data: m} +} + +// Nil represents a nil Map. +var Nil Map = New(nil) + +// New creates a new Map containing the map[string]interface{} in the data argument. +// If the data argument is not a map[string]interface, New attempts to call the +// MSI() method on the MSIConvertable interface to create one. +func New(data interface{}) Map { + if _, ok := data.(map[string]interface{}); !ok { + if converter, ok := data.(MSIConvertable); ok { + data = converter.MSI() + } else { + return nil + } + } + return Map(data.(map[string]interface{})) +} + +// MSI creates a map[string]interface{} and puts it inside a new Map. +// +// The arguments follow a key, value pattern. +// +// Panics +// +// Panics if any key arugment is non-string or if there are an odd number of arguments. +// +// Example +// +// To easily create Maps: +// +// m := objx.MSI("name", "Mat", "age", 29, "subobj", objx.MSI("active", true)) +// +// // creates an Map equivalent to +// m := objx.New(map[string]interface{}{"name": "Mat", "age": 29, "subobj": map[string]interface{}{"active": true}}) +func MSI(keyAndValuePairs ...interface{}) Map { + + newMap := make(map[string]interface{}) + keyAndValuePairsLen := len(keyAndValuePairs) + + if keyAndValuePairsLen%2 != 0 { + panic("objx: MSI must have an even number of arguments following the 'key, value' pattern.") + } + + for i := 0; i < keyAndValuePairsLen; i = i + 2 { + + key := keyAndValuePairs[i] + value := keyAndValuePairs[i+1] + + // make sure the key is a string + keyString, keyStringOK := key.(string) + if !keyStringOK { + panic("objx: MSI must follow 'string, interface{}' pattern. " + keyString + " is not a valid key.") + } + + newMap[keyString] = value + + } + + return New(newMap) +} + +// ****** Conversion Constructors + +// MustFromJSON creates a new Map containing the data specified in the +// jsonString. +// +// Panics if the JSON is invalid. +func MustFromJSON(jsonString string) Map { + o, err := FromJSON(jsonString) + + if err != nil { + panic("objx: MustFromJSON failed with error: " + err.Error()) + } + + return o +} + +// FromJSON creates a new Map containing the data specified in the +// jsonString. +// +// Returns an error if the JSON is invalid. +func FromJSON(jsonString string) (Map, error) { + + var data interface{} + err := json.Unmarshal([]byte(jsonString), &data) + + if err != nil { + return Nil, err + } + + return New(data), nil + +} + +// FromBase64 creates a new Obj containing the data specified +// in the Base64 string. +// +// The string is an encoded JSON string returned by Base64 +func FromBase64(base64String string) (Map, error) { + + decoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(base64String)) + + decoded, err := ioutil.ReadAll(decoder) + if err != nil { + return nil, err + } + + return FromJSON(string(decoded)) +} + +// MustFromBase64 creates a new Obj containing the data specified +// in the Base64 string and panics if there is an error. +// +// The string is an encoded JSON string returned by Base64 +func MustFromBase64(base64String string) Map { + + result, err := FromBase64(base64String) + + if err != nil { + panic("objx: MustFromBase64 failed with error: " + err.Error()) + } + + return result +} + +// FromSignedBase64 creates a new Obj containing the data specified +// in the Base64 string. +// +// The string is an encoded JSON string returned by SignedBase64 +func FromSignedBase64(base64String, key string) (Map, error) { + parts := strings.Split(base64String, SignatureSeparator) + if len(parts) != 2 { + return nil, errors.New("objx: Signed base64 string is malformed.") + } + + sig := HashWithKey(parts[0], key) + if parts[1] != sig { + return nil, errors.New("objx: Signature for base64 data does not match.") + } + + return FromBase64(parts[0]) +} + +// MustFromSignedBase64 creates a new Obj containing the data specified +// in the Base64 string and panics if there is an error. +// +// The string is an encoded JSON string returned by Base64 +func MustFromSignedBase64(base64String, key string) Map { + + result, err := FromSignedBase64(base64String, key) + + if err != nil { + panic("objx: MustFromSignedBase64 failed with error: " + err.Error()) + } + + return result +} + +// FromURLQuery generates a new Obj by parsing the specified +// query. +// +// For queries with multiple values, the first value is selected. +func FromURLQuery(query string) (Map, error) { + + vals, err := url.ParseQuery(query) + + if err != nil { + return nil, err + } + + m := make(map[string]interface{}) + for k, vals := range vals { + m[k] = vals[0] + } + + return New(m), nil +} + +// MustFromURLQuery generates a new Obj by parsing the specified +// query. +// +// For queries with multiple values, the first value is selected. +// +// Panics if it encounters an error +func MustFromURLQuery(query string) Map { + + o, err := FromURLQuery(query) + + if err != nil { + panic("objx: MustFromURLQuery failed with error: " + err.Error()) + } + + return o + +} diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/mutations.go b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/mutations.go new file mode 100644 index 00000000..b35c8639 --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/mutations.go @@ -0,0 +1,81 @@ +package objx + +// Exclude returns a new Map with the keys in the specified []string +// excluded. +func (d Map) Exclude(exclude []string) Map { + + excluded := make(Map) + for k, v := range d { + var shouldInclude bool = true + for _, toExclude := range exclude { + if k == toExclude { + shouldInclude = false + break + } + } + if shouldInclude { + excluded[k] = v + } + } + + return excluded +} + +// Copy creates a shallow copy of the Obj. +func (m Map) Copy() Map { + copied := make(map[string]interface{}) + for k, v := range m { + copied[k] = v + } + return New(copied) +} + +// Merge blends the specified map with a copy of this map and returns the result. +// +// Keys that appear in both will be selected from the specified map. +// This method requires that the wrapped object be a map[string]interface{} +func (m Map) Merge(merge Map) Map { + return m.Copy().MergeHere(merge) +} + +// Merge blends the specified map with this map and returns the current map. +// +// Keys that appear in both will be selected from the specified map. The original map +// will be modified. This method requires that +// the wrapped object be a map[string]interface{} +func (m Map) MergeHere(merge Map) Map { + + for k, v := range merge { + m[k] = v + } + + return m + +} + +// Transform builds a new Obj giving the transformer a chance +// to change the keys and values as it goes. This method requires that +// the wrapped object be a map[string]interface{} +func (m Map) Transform(transformer func(key string, value interface{}) (string, interface{})) Map { + newMap := make(map[string]interface{}) + for k, v := range m { + modifiedKey, modifiedVal := transformer(k, v) + newMap[modifiedKey] = modifiedVal + } + return New(newMap) +} + +// TransformKeys builds a new map using the specified key mapping. +// +// Unspecified keys will be unaltered. +// This method requires that the wrapped object be a map[string]interface{} +func (m Map) TransformKeys(mapping map[string]string) Map { + return m.Transform(func(key string, value interface{}) (string, interface{}) { + + if newKey, ok := mapping[key]; ok { + return newKey, value + } + + return key, value + }) +} diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/security.go b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/security.go new file mode 100644 index 00000000..fdd6be9c --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/security.go @@ -0,0 +1,14 @@ +package objx + +import ( + "crypto/sha1" + "encoding/hex" +) + +// HashWithKey hashes the specified string using the security +// key. +func HashWithKey(data, key string) string { + hash := sha1.New() + hash.Write([]byte(data + ":" + key)) + return hex.EncodeToString(hash.Sum(nil)) +} diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/tests.go b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/tests.go new file mode 100644 index 00000000..d9e0b479 --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/tests.go @@ -0,0 +1,17 @@ +package objx + +// Has gets whether there is something at the specified selector +// or not. +// +// If m is nil, Has will always return false. +func (m Map) Has(selector string) bool { + if m == nil { + return false + } + return !m.Get(selector).IsNil() +} + +// IsNil gets whether the data is nil or not. +func (v *Value) IsNil() bool { + return v == nil || v.data == nil +} diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/type_specific_codegen.go b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/type_specific_codegen.go new file mode 100644 index 00000000..f3ecb29b --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/type_specific_codegen.go @@ -0,0 +1,2881 @@ +package objx + +/* + Inter (interface{} and []interface{}) + -------------------------------------------------- +*/ + +// Inter gets the value as a interface{}, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Inter(optionalDefault ...interface{}) interface{} { + if s, ok := v.data.(interface{}); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustInter gets the value as a interface{}. +// +// Panics if the object is not a interface{}. +func (v *Value) MustInter() interface{} { + return v.data.(interface{}) +} + +// InterSlice gets the value as a []interface{}, returns the optionalDefault +// value or nil if the value is not a []interface{}. +func (v *Value) InterSlice(optionalDefault ...[]interface{}) []interface{} { + if s, ok := v.data.([]interface{}); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustInterSlice gets the value as a []interface{}. +// +// Panics if the object is not a []interface{}. +func (v *Value) MustInterSlice() []interface{} { + return v.data.([]interface{}) +} + +// IsInter gets whether the object contained is a interface{} or not. +func (v *Value) IsInter() bool { + _, ok := v.data.(interface{}) + return ok +} + +// IsInterSlice gets whether the object contained is a []interface{} or not. +func (v *Value) IsInterSlice() bool { + _, ok := v.data.([]interface{}) + return ok +} + +// EachInter calls the specified callback for each object +// in the []interface{}. +// +// Panics if the object is the wrong type. +func (v *Value) EachInter(callback func(int, interface{}) bool) *Value { + + for index, val := range v.MustInterSlice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereInter uses the specified decider function to select items +// from the []interface{}. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereInter(decider func(int, interface{}) bool) *Value { + + var selected []interface{} + + v.EachInter(func(index int, val interface{}) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupInter uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]interface{}. +func (v *Value) GroupInter(grouper func(int, interface{}) string) *Value { + + groups := make(map[string][]interface{}) + + v.EachInter(func(index int, val interface{}) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]interface{}, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceInter uses the specified function to replace each interface{}s +// by iterating each item. The data in the returned result will be a +// []interface{} containing the replaced items. +func (v *Value) ReplaceInter(replacer func(int, interface{}) interface{}) *Value { + + arr := v.MustInterSlice() + replaced := make([]interface{}, len(arr)) + + v.EachInter(func(index int, val interface{}) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectInter uses the specified collector function to collect a value +// for each of the interface{}s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectInter(collector func(int, interface{}) interface{}) *Value { + + arr := v.MustInterSlice() + collected := make([]interface{}, len(arr)) + + v.EachInter(func(index int, val interface{}) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} + +/* + MSI (map[string]interface{} and []map[string]interface{}) + -------------------------------------------------- +*/ + +// MSI gets the value as a map[string]interface{}, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) MSI(optionalDefault ...map[string]interface{}) map[string]interface{} { + if s, ok := v.data.(map[string]interface{}); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustMSI gets the value as a map[string]interface{}. +// +// Panics if the object is not a map[string]interface{}. +func (v *Value) MustMSI() map[string]interface{} { + return v.data.(map[string]interface{}) +} + +// MSISlice gets the value as a []map[string]interface{}, returns the optionalDefault +// value or nil if the value is not a []map[string]interface{}. +func (v *Value) MSISlice(optionalDefault ...[]map[string]interface{}) []map[string]interface{} { + if s, ok := v.data.([]map[string]interface{}); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustMSISlice gets the value as a []map[string]interface{}. +// +// Panics if the object is not a []map[string]interface{}. +func (v *Value) MustMSISlice() []map[string]interface{} { + return v.data.([]map[string]interface{}) +} + +// IsMSI gets whether the object contained is a map[string]interface{} or not. +func (v *Value) IsMSI() bool { + _, ok := v.data.(map[string]interface{}) + return ok +} + +// IsMSISlice gets whether the object contained is a []map[string]interface{} or not. +func (v *Value) IsMSISlice() bool { + _, ok := v.data.([]map[string]interface{}) + return ok +} + +// EachMSI calls the specified callback for each object +// in the []map[string]interface{}. +// +// Panics if the object is the wrong type. +func (v *Value) EachMSI(callback func(int, map[string]interface{}) bool) *Value { + + for index, val := range v.MustMSISlice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereMSI uses the specified decider function to select items +// from the []map[string]interface{}. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereMSI(decider func(int, map[string]interface{}) bool) *Value { + + var selected []map[string]interface{} + + v.EachMSI(func(index int, val map[string]interface{}) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupMSI uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]map[string]interface{}. +func (v *Value) GroupMSI(grouper func(int, map[string]interface{}) string) *Value { + + groups := make(map[string][]map[string]interface{}) + + v.EachMSI(func(index int, val map[string]interface{}) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]map[string]interface{}, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceMSI uses the specified function to replace each map[string]interface{}s +// by iterating each item. The data in the returned result will be a +// []map[string]interface{} containing the replaced items. +func (v *Value) ReplaceMSI(replacer func(int, map[string]interface{}) map[string]interface{}) *Value { + + arr := v.MustMSISlice() + replaced := make([]map[string]interface{}, len(arr)) + + v.EachMSI(func(index int, val map[string]interface{}) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectMSI uses the specified collector function to collect a value +// for each of the map[string]interface{}s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectMSI(collector func(int, map[string]interface{}) interface{}) *Value { + + arr := v.MustMSISlice() + collected := make([]interface{}, len(arr)) + + v.EachMSI(func(index int, val map[string]interface{}) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} + +/* + ObjxMap ((Map) and [](Map)) + -------------------------------------------------- +*/ + +// ObjxMap gets the value as a (Map), returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) ObjxMap(optionalDefault ...(Map)) Map { + if s, ok := v.data.((Map)); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return New(nil) +} + +// MustObjxMap gets the value as a (Map). +// +// Panics if the object is not a (Map). +func (v *Value) MustObjxMap() Map { + return v.data.((Map)) +} + +// ObjxMapSlice gets the value as a [](Map), returns the optionalDefault +// value or nil if the value is not a [](Map). +func (v *Value) ObjxMapSlice(optionalDefault ...[](Map)) [](Map) { + if s, ok := v.data.([](Map)); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustObjxMapSlice gets the value as a [](Map). +// +// Panics if the object is not a [](Map). +func (v *Value) MustObjxMapSlice() [](Map) { + return v.data.([](Map)) +} + +// IsObjxMap gets whether the object contained is a (Map) or not. +func (v *Value) IsObjxMap() bool { + _, ok := v.data.((Map)) + return ok +} + +// IsObjxMapSlice gets whether the object contained is a [](Map) or not. +func (v *Value) IsObjxMapSlice() bool { + _, ok := v.data.([](Map)) + return ok +} + +// EachObjxMap calls the specified callback for each object +// in the [](Map). +// +// Panics if the object is the wrong type. +func (v *Value) EachObjxMap(callback func(int, Map) bool) *Value { + + for index, val := range v.MustObjxMapSlice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereObjxMap uses the specified decider function to select items +// from the [](Map). The object contained in the result will contain +// only the selected items. +func (v *Value) WhereObjxMap(decider func(int, Map) bool) *Value { + + var selected [](Map) + + v.EachObjxMap(func(index int, val Map) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupObjxMap uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][](Map). +func (v *Value) GroupObjxMap(grouper func(int, Map) string) *Value { + + groups := make(map[string][](Map)) + + v.EachObjxMap(func(index int, val Map) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([](Map), 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceObjxMap uses the specified function to replace each (Map)s +// by iterating each item. The data in the returned result will be a +// [](Map) containing the replaced items. +func (v *Value) ReplaceObjxMap(replacer func(int, Map) Map) *Value { + + arr := v.MustObjxMapSlice() + replaced := make([](Map), len(arr)) + + v.EachObjxMap(func(index int, val Map) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectObjxMap uses the specified collector function to collect a value +// for each of the (Map)s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectObjxMap(collector func(int, Map) interface{}) *Value { + + arr := v.MustObjxMapSlice() + collected := make([]interface{}, len(arr)) + + v.EachObjxMap(func(index int, val Map) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} + +/* + Bool (bool and []bool) + -------------------------------------------------- +*/ + +// Bool gets the value as a bool, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Bool(optionalDefault ...bool) bool { + if s, ok := v.data.(bool); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return false +} + +// MustBool gets the value as a bool. +// +// Panics if the object is not a bool. +func (v *Value) MustBool() bool { + return v.data.(bool) +} + +// BoolSlice gets the value as a []bool, returns the optionalDefault +// value or nil if the value is not a []bool. +func (v *Value) BoolSlice(optionalDefault ...[]bool) []bool { + if s, ok := v.data.([]bool); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustBoolSlice gets the value as a []bool. +// +// Panics if the object is not a []bool. +func (v *Value) MustBoolSlice() []bool { + return v.data.([]bool) +} + +// IsBool gets whether the object contained is a bool or not. +func (v *Value) IsBool() bool { + _, ok := v.data.(bool) + return ok +} + +// IsBoolSlice gets whether the object contained is a []bool or not. +func (v *Value) IsBoolSlice() bool { + _, ok := v.data.([]bool) + return ok +} + +// EachBool calls the specified callback for each object +// in the []bool. +// +// Panics if the object is the wrong type. +func (v *Value) EachBool(callback func(int, bool) bool) *Value { + + for index, val := range v.MustBoolSlice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereBool uses the specified decider function to select items +// from the []bool. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereBool(decider func(int, bool) bool) *Value { + + var selected []bool + + v.EachBool(func(index int, val bool) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupBool uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]bool. +func (v *Value) GroupBool(grouper func(int, bool) string) *Value { + + groups := make(map[string][]bool) + + v.EachBool(func(index int, val bool) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]bool, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceBool uses the specified function to replace each bools +// by iterating each item. The data in the returned result will be a +// []bool containing the replaced items. +func (v *Value) ReplaceBool(replacer func(int, bool) bool) *Value { + + arr := v.MustBoolSlice() + replaced := make([]bool, len(arr)) + + v.EachBool(func(index int, val bool) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectBool uses the specified collector function to collect a value +// for each of the bools in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectBool(collector func(int, bool) interface{}) *Value { + + arr := v.MustBoolSlice() + collected := make([]interface{}, len(arr)) + + v.EachBool(func(index int, val bool) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} + +/* + Str (string and []string) + -------------------------------------------------- +*/ + +// Str gets the value as a string, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Str(optionalDefault ...string) string { + if s, ok := v.data.(string); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return "" +} + +// MustStr gets the value as a string. +// +// Panics if the object is not a string. +func (v *Value) MustStr() string { + return v.data.(string) +} + +// StrSlice gets the value as a []string, returns the optionalDefault +// value or nil if the value is not a []string. +func (v *Value) StrSlice(optionalDefault ...[]string) []string { + if s, ok := v.data.([]string); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustStrSlice gets the value as a []string. +// +// Panics if the object is not a []string. +func (v *Value) MustStrSlice() []string { + return v.data.([]string) +} + +// IsStr gets whether the object contained is a string or not. +func (v *Value) IsStr() bool { + _, ok := v.data.(string) + return ok +} + +// IsStrSlice gets whether the object contained is a []string or not. +func (v *Value) IsStrSlice() bool { + _, ok := v.data.([]string) + return ok +} + +// EachStr calls the specified callback for each object +// in the []string. +// +// Panics if the object is the wrong type. +func (v *Value) EachStr(callback func(int, string) bool) *Value { + + for index, val := range v.MustStrSlice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereStr uses the specified decider function to select items +// from the []string. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereStr(decider func(int, string) bool) *Value { + + var selected []string + + v.EachStr(func(index int, val string) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupStr uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]string. +func (v *Value) GroupStr(grouper func(int, string) string) *Value { + + groups := make(map[string][]string) + + v.EachStr(func(index int, val string) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]string, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceStr uses the specified function to replace each strings +// by iterating each item. The data in the returned result will be a +// []string containing the replaced items. +func (v *Value) ReplaceStr(replacer func(int, string) string) *Value { + + arr := v.MustStrSlice() + replaced := make([]string, len(arr)) + + v.EachStr(func(index int, val string) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectStr uses the specified collector function to collect a value +// for each of the strings in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectStr(collector func(int, string) interface{}) *Value { + + arr := v.MustStrSlice() + collected := make([]interface{}, len(arr)) + + v.EachStr(func(index int, val string) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} + +/* + Int (int and []int) + -------------------------------------------------- +*/ + +// Int gets the value as a int, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Int(optionalDefault ...int) int { + if s, ok := v.data.(int); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustInt gets the value as a int. +// +// Panics if the object is not a int. +func (v *Value) MustInt() int { + return v.data.(int) +} + +// IntSlice gets the value as a []int, returns the optionalDefault +// value or nil if the value is not a []int. +func (v *Value) IntSlice(optionalDefault ...[]int) []int { + if s, ok := v.data.([]int); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustIntSlice gets the value as a []int. +// +// Panics if the object is not a []int. +func (v *Value) MustIntSlice() []int { + return v.data.([]int) +} + +// IsInt gets whether the object contained is a int or not. +func (v *Value) IsInt() bool { + _, ok := v.data.(int) + return ok +} + +// IsIntSlice gets whether the object contained is a []int or not. +func (v *Value) IsIntSlice() bool { + _, ok := v.data.([]int) + return ok +} + +// EachInt calls the specified callback for each object +// in the []int. +// +// Panics if the object is the wrong type. +func (v *Value) EachInt(callback func(int, int) bool) *Value { + + for index, val := range v.MustIntSlice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereInt uses the specified decider function to select items +// from the []int. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereInt(decider func(int, int) bool) *Value { + + var selected []int + + v.EachInt(func(index int, val int) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupInt uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]int. +func (v *Value) GroupInt(grouper func(int, int) string) *Value { + + groups := make(map[string][]int) + + v.EachInt(func(index int, val int) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]int, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceInt uses the specified function to replace each ints +// by iterating each item. The data in the returned result will be a +// []int containing the replaced items. +func (v *Value) ReplaceInt(replacer func(int, int) int) *Value { + + arr := v.MustIntSlice() + replaced := make([]int, len(arr)) + + v.EachInt(func(index int, val int) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectInt uses the specified collector function to collect a value +// for each of the ints in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectInt(collector func(int, int) interface{}) *Value { + + arr := v.MustIntSlice() + collected := make([]interface{}, len(arr)) + + v.EachInt(func(index int, val int) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} + +/* + Int8 (int8 and []int8) + -------------------------------------------------- +*/ + +// Int8 gets the value as a int8, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Int8(optionalDefault ...int8) int8 { + if s, ok := v.data.(int8); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustInt8 gets the value as a int8. +// +// Panics if the object is not a int8. +func (v *Value) MustInt8() int8 { + return v.data.(int8) +} + +// Int8Slice gets the value as a []int8, returns the optionalDefault +// value or nil if the value is not a []int8. +func (v *Value) Int8Slice(optionalDefault ...[]int8) []int8 { + if s, ok := v.data.([]int8); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustInt8Slice gets the value as a []int8. +// +// Panics if the object is not a []int8. +func (v *Value) MustInt8Slice() []int8 { + return v.data.([]int8) +} + +// IsInt8 gets whether the object contained is a int8 or not. +func (v *Value) IsInt8() bool { + _, ok := v.data.(int8) + return ok +} + +// IsInt8Slice gets whether the object contained is a []int8 or not. +func (v *Value) IsInt8Slice() bool { + _, ok := v.data.([]int8) + return ok +} + +// EachInt8 calls the specified callback for each object +// in the []int8. +// +// Panics if the object is the wrong type. +func (v *Value) EachInt8(callback func(int, int8) bool) *Value { + + for index, val := range v.MustInt8Slice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereInt8 uses the specified decider function to select items +// from the []int8. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereInt8(decider func(int, int8) bool) *Value { + + var selected []int8 + + v.EachInt8(func(index int, val int8) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupInt8 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]int8. +func (v *Value) GroupInt8(grouper func(int, int8) string) *Value { + + groups := make(map[string][]int8) + + v.EachInt8(func(index int, val int8) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]int8, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceInt8 uses the specified function to replace each int8s +// by iterating each item. The data in the returned result will be a +// []int8 containing the replaced items. +func (v *Value) ReplaceInt8(replacer func(int, int8) int8) *Value { + + arr := v.MustInt8Slice() + replaced := make([]int8, len(arr)) + + v.EachInt8(func(index int, val int8) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectInt8 uses the specified collector function to collect a value +// for each of the int8s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectInt8(collector func(int, int8) interface{}) *Value { + + arr := v.MustInt8Slice() + collected := make([]interface{}, len(arr)) + + v.EachInt8(func(index int, val int8) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} + +/* + Int16 (int16 and []int16) + -------------------------------------------------- +*/ + +// Int16 gets the value as a int16, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Int16(optionalDefault ...int16) int16 { + if s, ok := v.data.(int16); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustInt16 gets the value as a int16. +// +// Panics if the object is not a int16. +func (v *Value) MustInt16() int16 { + return v.data.(int16) +} + +// Int16Slice gets the value as a []int16, returns the optionalDefault +// value or nil if the value is not a []int16. +func (v *Value) Int16Slice(optionalDefault ...[]int16) []int16 { + if s, ok := v.data.([]int16); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustInt16Slice gets the value as a []int16. +// +// Panics if the object is not a []int16. +func (v *Value) MustInt16Slice() []int16 { + return v.data.([]int16) +} + +// IsInt16 gets whether the object contained is a int16 or not. +func (v *Value) IsInt16() bool { + _, ok := v.data.(int16) + return ok +} + +// IsInt16Slice gets whether the object contained is a []int16 or not. +func (v *Value) IsInt16Slice() bool { + _, ok := v.data.([]int16) + return ok +} + +// EachInt16 calls the specified callback for each object +// in the []int16. +// +// Panics if the object is the wrong type. +func (v *Value) EachInt16(callback func(int, int16) bool) *Value { + + for index, val := range v.MustInt16Slice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereInt16 uses the specified decider function to select items +// from the []int16. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereInt16(decider func(int, int16) bool) *Value { + + var selected []int16 + + v.EachInt16(func(index int, val int16) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupInt16 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]int16. +func (v *Value) GroupInt16(grouper func(int, int16) string) *Value { + + groups := make(map[string][]int16) + + v.EachInt16(func(index int, val int16) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]int16, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceInt16 uses the specified function to replace each int16s +// by iterating each item. The data in the returned result will be a +// []int16 containing the replaced items. +func (v *Value) ReplaceInt16(replacer func(int, int16) int16) *Value { + + arr := v.MustInt16Slice() + replaced := make([]int16, len(arr)) + + v.EachInt16(func(index int, val int16) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectInt16 uses the specified collector function to collect a value +// for each of the int16s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectInt16(collector func(int, int16) interface{}) *Value { + + arr := v.MustInt16Slice() + collected := make([]interface{}, len(arr)) + + v.EachInt16(func(index int, val int16) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} + +/* + Int32 (int32 and []int32) + -------------------------------------------------- +*/ + +// Int32 gets the value as a int32, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Int32(optionalDefault ...int32) int32 { + if s, ok := v.data.(int32); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustInt32 gets the value as a int32. +// +// Panics if the object is not a int32. +func (v *Value) MustInt32() int32 { + return v.data.(int32) +} + +// Int32Slice gets the value as a []int32, returns the optionalDefault +// value or nil if the value is not a []int32. +func (v *Value) Int32Slice(optionalDefault ...[]int32) []int32 { + if s, ok := v.data.([]int32); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustInt32Slice gets the value as a []int32. +// +// Panics if the object is not a []int32. +func (v *Value) MustInt32Slice() []int32 { + return v.data.([]int32) +} + +// IsInt32 gets whether the object contained is a int32 or not. +func (v *Value) IsInt32() bool { + _, ok := v.data.(int32) + return ok +} + +// IsInt32Slice gets whether the object contained is a []int32 or not. +func (v *Value) IsInt32Slice() bool { + _, ok := v.data.([]int32) + return ok +} + +// EachInt32 calls the specified callback for each object +// in the []int32. +// +// Panics if the object is the wrong type. +func (v *Value) EachInt32(callback func(int, int32) bool) *Value { + + for index, val := range v.MustInt32Slice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereInt32 uses the specified decider function to select items +// from the []int32. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereInt32(decider func(int, int32) bool) *Value { + + var selected []int32 + + v.EachInt32(func(index int, val int32) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupInt32 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]int32. +func (v *Value) GroupInt32(grouper func(int, int32) string) *Value { + + groups := make(map[string][]int32) + + v.EachInt32(func(index int, val int32) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]int32, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceInt32 uses the specified function to replace each int32s +// by iterating each item. The data in the returned result will be a +// []int32 containing the replaced items. +func (v *Value) ReplaceInt32(replacer func(int, int32) int32) *Value { + + arr := v.MustInt32Slice() + replaced := make([]int32, len(arr)) + + v.EachInt32(func(index int, val int32) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectInt32 uses the specified collector function to collect a value +// for each of the int32s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectInt32(collector func(int, int32) interface{}) *Value { + + arr := v.MustInt32Slice() + collected := make([]interface{}, len(arr)) + + v.EachInt32(func(index int, val int32) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} + +/* + Int64 (int64 and []int64) + -------------------------------------------------- +*/ + +// Int64 gets the value as a int64, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Int64(optionalDefault ...int64) int64 { + if s, ok := v.data.(int64); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustInt64 gets the value as a int64. +// +// Panics if the object is not a int64. +func (v *Value) MustInt64() int64 { + return v.data.(int64) +} + +// Int64Slice gets the value as a []int64, returns the optionalDefault +// value or nil if the value is not a []int64. +func (v *Value) Int64Slice(optionalDefault ...[]int64) []int64 { + if s, ok := v.data.([]int64); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustInt64Slice gets the value as a []int64. +// +// Panics if the object is not a []int64. +func (v *Value) MustInt64Slice() []int64 { + return v.data.([]int64) +} + +// IsInt64 gets whether the object contained is a int64 or not. +func (v *Value) IsInt64() bool { + _, ok := v.data.(int64) + return ok +} + +// IsInt64Slice gets whether the object contained is a []int64 or not. +func (v *Value) IsInt64Slice() bool { + _, ok := v.data.([]int64) + return ok +} + +// EachInt64 calls the specified callback for each object +// in the []int64. +// +// Panics if the object is the wrong type. +func (v *Value) EachInt64(callback func(int, int64) bool) *Value { + + for index, val := range v.MustInt64Slice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereInt64 uses the specified decider function to select items +// from the []int64. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereInt64(decider func(int, int64) bool) *Value { + + var selected []int64 + + v.EachInt64(func(index int, val int64) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupInt64 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]int64. +func (v *Value) GroupInt64(grouper func(int, int64) string) *Value { + + groups := make(map[string][]int64) + + v.EachInt64(func(index int, val int64) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]int64, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceInt64 uses the specified function to replace each int64s +// by iterating each item. The data in the returned result will be a +// []int64 containing the replaced items. +func (v *Value) ReplaceInt64(replacer func(int, int64) int64) *Value { + + arr := v.MustInt64Slice() + replaced := make([]int64, len(arr)) + + v.EachInt64(func(index int, val int64) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectInt64 uses the specified collector function to collect a value +// for each of the int64s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectInt64(collector func(int, int64) interface{}) *Value { + + arr := v.MustInt64Slice() + collected := make([]interface{}, len(arr)) + + v.EachInt64(func(index int, val int64) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} + +/* + Uint (uint and []uint) + -------------------------------------------------- +*/ + +// Uint gets the value as a uint, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Uint(optionalDefault ...uint) uint { + if s, ok := v.data.(uint); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustUint gets the value as a uint. +// +// Panics if the object is not a uint. +func (v *Value) MustUint() uint { + return v.data.(uint) +} + +// UintSlice gets the value as a []uint, returns the optionalDefault +// value or nil if the value is not a []uint. +func (v *Value) UintSlice(optionalDefault ...[]uint) []uint { + if s, ok := v.data.([]uint); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustUintSlice gets the value as a []uint. +// +// Panics if the object is not a []uint. +func (v *Value) MustUintSlice() []uint { + return v.data.([]uint) +} + +// IsUint gets whether the object contained is a uint or not. +func (v *Value) IsUint() bool { + _, ok := v.data.(uint) + return ok +} + +// IsUintSlice gets whether the object contained is a []uint or not. +func (v *Value) IsUintSlice() bool { + _, ok := v.data.([]uint) + return ok +} + +// EachUint calls the specified callback for each object +// in the []uint. +// +// Panics if the object is the wrong type. +func (v *Value) EachUint(callback func(int, uint) bool) *Value { + + for index, val := range v.MustUintSlice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereUint uses the specified decider function to select items +// from the []uint. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereUint(decider func(int, uint) bool) *Value { + + var selected []uint + + v.EachUint(func(index int, val uint) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupUint uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]uint. +func (v *Value) GroupUint(grouper func(int, uint) string) *Value { + + groups := make(map[string][]uint) + + v.EachUint(func(index int, val uint) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]uint, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceUint uses the specified function to replace each uints +// by iterating each item. The data in the returned result will be a +// []uint containing the replaced items. +func (v *Value) ReplaceUint(replacer func(int, uint) uint) *Value { + + arr := v.MustUintSlice() + replaced := make([]uint, len(arr)) + + v.EachUint(func(index int, val uint) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectUint uses the specified collector function to collect a value +// for each of the uints in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectUint(collector func(int, uint) interface{}) *Value { + + arr := v.MustUintSlice() + collected := make([]interface{}, len(arr)) + + v.EachUint(func(index int, val uint) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} + +/* + Uint8 (uint8 and []uint8) + -------------------------------------------------- +*/ + +// Uint8 gets the value as a uint8, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Uint8(optionalDefault ...uint8) uint8 { + if s, ok := v.data.(uint8); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustUint8 gets the value as a uint8. +// +// Panics if the object is not a uint8. +func (v *Value) MustUint8() uint8 { + return v.data.(uint8) +} + +// Uint8Slice gets the value as a []uint8, returns the optionalDefault +// value or nil if the value is not a []uint8. +func (v *Value) Uint8Slice(optionalDefault ...[]uint8) []uint8 { + if s, ok := v.data.([]uint8); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustUint8Slice gets the value as a []uint8. +// +// Panics if the object is not a []uint8. +func (v *Value) MustUint8Slice() []uint8 { + return v.data.([]uint8) +} + +// IsUint8 gets whether the object contained is a uint8 or not. +func (v *Value) IsUint8() bool { + _, ok := v.data.(uint8) + return ok +} + +// IsUint8Slice gets whether the object contained is a []uint8 or not. +func (v *Value) IsUint8Slice() bool { + _, ok := v.data.([]uint8) + return ok +} + +// EachUint8 calls the specified callback for each object +// in the []uint8. +// +// Panics if the object is the wrong type. +func (v *Value) EachUint8(callback func(int, uint8) bool) *Value { + + for index, val := range v.MustUint8Slice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereUint8 uses the specified decider function to select items +// from the []uint8. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereUint8(decider func(int, uint8) bool) *Value { + + var selected []uint8 + + v.EachUint8(func(index int, val uint8) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupUint8 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]uint8. +func (v *Value) GroupUint8(grouper func(int, uint8) string) *Value { + + groups := make(map[string][]uint8) + + v.EachUint8(func(index int, val uint8) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]uint8, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceUint8 uses the specified function to replace each uint8s +// by iterating each item. The data in the returned result will be a +// []uint8 containing the replaced items. +func (v *Value) ReplaceUint8(replacer func(int, uint8) uint8) *Value { + + arr := v.MustUint8Slice() + replaced := make([]uint8, len(arr)) + + v.EachUint8(func(index int, val uint8) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectUint8 uses the specified collector function to collect a value +// for each of the uint8s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectUint8(collector func(int, uint8) interface{}) *Value { + + arr := v.MustUint8Slice() + collected := make([]interface{}, len(arr)) + + v.EachUint8(func(index int, val uint8) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} + +/* + Uint16 (uint16 and []uint16) + -------------------------------------------------- +*/ + +// Uint16 gets the value as a uint16, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Uint16(optionalDefault ...uint16) uint16 { + if s, ok := v.data.(uint16); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustUint16 gets the value as a uint16. +// +// Panics if the object is not a uint16. +func (v *Value) MustUint16() uint16 { + return v.data.(uint16) +} + +// Uint16Slice gets the value as a []uint16, returns the optionalDefault +// value or nil if the value is not a []uint16. +func (v *Value) Uint16Slice(optionalDefault ...[]uint16) []uint16 { + if s, ok := v.data.([]uint16); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustUint16Slice gets the value as a []uint16. +// +// Panics if the object is not a []uint16. +func (v *Value) MustUint16Slice() []uint16 { + return v.data.([]uint16) +} + +// IsUint16 gets whether the object contained is a uint16 or not. +func (v *Value) IsUint16() bool { + _, ok := v.data.(uint16) + return ok +} + +// IsUint16Slice gets whether the object contained is a []uint16 or not. +func (v *Value) IsUint16Slice() bool { + _, ok := v.data.([]uint16) + return ok +} + +// EachUint16 calls the specified callback for each object +// in the []uint16. +// +// Panics if the object is the wrong type. +func (v *Value) EachUint16(callback func(int, uint16) bool) *Value { + + for index, val := range v.MustUint16Slice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereUint16 uses the specified decider function to select items +// from the []uint16. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereUint16(decider func(int, uint16) bool) *Value { + + var selected []uint16 + + v.EachUint16(func(index int, val uint16) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupUint16 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]uint16. +func (v *Value) GroupUint16(grouper func(int, uint16) string) *Value { + + groups := make(map[string][]uint16) + + v.EachUint16(func(index int, val uint16) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]uint16, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceUint16 uses the specified function to replace each uint16s +// by iterating each item. The data in the returned result will be a +// []uint16 containing the replaced items. +func (v *Value) ReplaceUint16(replacer func(int, uint16) uint16) *Value { + + arr := v.MustUint16Slice() + replaced := make([]uint16, len(arr)) + + v.EachUint16(func(index int, val uint16) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectUint16 uses the specified collector function to collect a value +// for each of the uint16s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectUint16(collector func(int, uint16) interface{}) *Value { + + arr := v.MustUint16Slice() + collected := make([]interface{}, len(arr)) + + v.EachUint16(func(index int, val uint16) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} + +/* + Uint32 (uint32 and []uint32) + -------------------------------------------------- +*/ + +// Uint32 gets the value as a uint32, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Uint32(optionalDefault ...uint32) uint32 { + if s, ok := v.data.(uint32); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustUint32 gets the value as a uint32. +// +// Panics if the object is not a uint32. +func (v *Value) MustUint32() uint32 { + return v.data.(uint32) +} + +// Uint32Slice gets the value as a []uint32, returns the optionalDefault +// value or nil if the value is not a []uint32. +func (v *Value) Uint32Slice(optionalDefault ...[]uint32) []uint32 { + if s, ok := v.data.([]uint32); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustUint32Slice gets the value as a []uint32. +// +// Panics if the object is not a []uint32. +func (v *Value) MustUint32Slice() []uint32 { + return v.data.([]uint32) +} + +// IsUint32 gets whether the object contained is a uint32 or not. +func (v *Value) IsUint32() bool { + _, ok := v.data.(uint32) + return ok +} + +// IsUint32Slice gets whether the object contained is a []uint32 or not. +func (v *Value) IsUint32Slice() bool { + _, ok := v.data.([]uint32) + return ok +} + +// EachUint32 calls the specified callback for each object +// in the []uint32. +// +// Panics if the object is the wrong type. +func (v *Value) EachUint32(callback func(int, uint32) bool) *Value { + + for index, val := range v.MustUint32Slice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereUint32 uses the specified decider function to select items +// from the []uint32. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereUint32(decider func(int, uint32) bool) *Value { + + var selected []uint32 + + v.EachUint32(func(index int, val uint32) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupUint32 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]uint32. +func (v *Value) GroupUint32(grouper func(int, uint32) string) *Value { + + groups := make(map[string][]uint32) + + v.EachUint32(func(index int, val uint32) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]uint32, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceUint32 uses the specified function to replace each uint32s +// by iterating each item. The data in the returned result will be a +// []uint32 containing the replaced items. +func (v *Value) ReplaceUint32(replacer func(int, uint32) uint32) *Value { + + arr := v.MustUint32Slice() + replaced := make([]uint32, len(arr)) + + v.EachUint32(func(index int, val uint32) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectUint32 uses the specified collector function to collect a value +// for each of the uint32s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectUint32(collector func(int, uint32) interface{}) *Value { + + arr := v.MustUint32Slice() + collected := make([]interface{}, len(arr)) + + v.EachUint32(func(index int, val uint32) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} + +/* + Uint64 (uint64 and []uint64) + -------------------------------------------------- +*/ + +// Uint64 gets the value as a uint64, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Uint64(optionalDefault ...uint64) uint64 { + if s, ok := v.data.(uint64); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustUint64 gets the value as a uint64. +// +// Panics if the object is not a uint64. +func (v *Value) MustUint64() uint64 { + return v.data.(uint64) +} + +// Uint64Slice gets the value as a []uint64, returns the optionalDefault +// value or nil if the value is not a []uint64. +func (v *Value) Uint64Slice(optionalDefault ...[]uint64) []uint64 { + if s, ok := v.data.([]uint64); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustUint64Slice gets the value as a []uint64. +// +// Panics if the object is not a []uint64. +func (v *Value) MustUint64Slice() []uint64 { + return v.data.([]uint64) +} + +// IsUint64 gets whether the object contained is a uint64 or not. +func (v *Value) IsUint64() bool { + _, ok := v.data.(uint64) + return ok +} + +// IsUint64Slice gets whether the object contained is a []uint64 or not. +func (v *Value) IsUint64Slice() bool { + _, ok := v.data.([]uint64) + return ok +} + +// EachUint64 calls the specified callback for each object +// in the []uint64. +// +// Panics if the object is the wrong type. +func (v *Value) EachUint64(callback func(int, uint64) bool) *Value { + + for index, val := range v.MustUint64Slice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereUint64 uses the specified decider function to select items +// from the []uint64. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereUint64(decider func(int, uint64) bool) *Value { + + var selected []uint64 + + v.EachUint64(func(index int, val uint64) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupUint64 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]uint64. +func (v *Value) GroupUint64(grouper func(int, uint64) string) *Value { + + groups := make(map[string][]uint64) + + v.EachUint64(func(index int, val uint64) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]uint64, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceUint64 uses the specified function to replace each uint64s +// by iterating each item. The data in the returned result will be a +// []uint64 containing the replaced items. +func (v *Value) ReplaceUint64(replacer func(int, uint64) uint64) *Value { + + arr := v.MustUint64Slice() + replaced := make([]uint64, len(arr)) + + v.EachUint64(func(index int, val uint64) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectUint64 uses the specified collector function to collect a value +// for each of the uint64s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectUint64(collector func(int, uint64) interface{}) *Value { + + arr := v.MustUint64Slice() + collected := make([]interface{}, len(arr)) + + v.EachUint64(func(index int, val uint64) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} + +/* + Uintptr (uintptr and []uintptr) + -------------------------------------------------- +*/ + +// Uintptr gets the value as a uintptr, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Uintptr(optionalDefault ...uintptr) uintptr { + if s, ok := v.data.(uintptr); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustUintptr gets the value as a uintptr. +// +// Panics if the object is not a uintptr. +func (v *Value) MustUintptr() uintptr { + return v.data.(uintptr) +} + +// UintptrSlice gets the value as a []uintptr, returns the optionalDefault +// value or nil if the value is not a []uintptr. +func (v *Value) UintptrSlice(optionalDefault ...[]uintptr) []uintptr { + if s, ok := v.data.([]uintptr); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustUintptrSlice gets the value as a []uintptr. +// +// Panics if the object is not a []uintptr. +func (v *Value) MustUintptrSlice() []uintptr { + return v.data.([]uintptr) +} + +// IsUintptr gets whether the object contained is a uintptr or not. +func (v *Value) IsUintptr() bool { + _, ok := v.data.(uintptr) + return ok +} + +// IsUintptrSlice gets whether the object contained is a []uintptr or not. +func (v *Value) IsUintptrSlice() bool { + _, ok := v.data.([]uintptr) + return ok +} + +// EachUintptr calls the specified callback for each object +// in the []uintptr. +// +// Panics if the object is the wrong type. +func (v *Value) EachUintptr(callback func(int, uintptr) bool) *Value { + + for index, val := range v.MustUintptrSlice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereUintptr uses the specified decider function to select items +// from the []uintptr. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereUintptr(decider func(int, uintptr) bool) *Value { + + var selected []uintptr + + v.EachUintptr(func(index int, val uintptr) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupUintptr uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]uintptr. +func (v *Value) GroupUintptr(grouper func(int, uintptr) string) *Value { + + groups := make(map[string][]uintptr) + + v.EachUintptr(func(index int, val uintptr) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]uintptr, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceUintptr uses the specified function to replace each uintptrs +// by iterating each item. The data in the returned result will be a +// []uintptr containing the replaced items. +func (v *Value) ReplaceUintptr(replacer func(int, uintptr) uintptr) *Value { + + arr := v.MustUintptrSlice() + replaced := make([]uintptr, len(arr)) + + v.EachUintptr(func(index int, val uintptr) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectUintptr uses the specified collector function to collect a value +// for each of the uintptrs in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectUintptr(collector func(int, uintptr) interface{}) *Value { + + arr := v.MustUintptrSlice() + collected := make([]interface{}, len(arr)) + + v.EachUintptr(func(index int, val uintptr) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} + +/* + Float32 (float32 and []float32) + -------------------------------------------------- +*/ + +// Float32 gets the value as a float32, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Float32(optionalDefault ...float32) float32 { + if s, ok := v.data.(float32); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustFloat32 gets the value as a float32. +// +// Panics if the object is not a float32. +func (v *Value) MustFloat32() float32 { + return v.data.(float32) +} + +// Float32Slice gets the value as a []float32, returns the optionalDefault +// value or nil if the value is not a []float32. +func (v *Value) Float32Slice(optionalDefault ...[]float32) []float32 { + if s, ok := v.data.([]float32); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustFloat32Slice gets the value as a []float32. +// +// Panics if the object is not a []float32. +func (v *Value) MustFloat32Slice() []float32 { + return v.data.([]float32) +} + +// IsFloat32 gets whether the object contained is a float32 or not. +func (v *Value) IsFloat32() bool { + _, ok := v.data.(float32) + return ok +} + +// IsFloat32Slice gets whether the object contained is a []float32 or not. +func (v *Value) IsFloat32Slice() bool { + _, ok := v.data.([]float32) + return ok +} + +// EachFloat32 calls the specified callback for each object +// in the []float32. +// +// Panics if the object is the wrong type. +func (v *Value) EachFloat32(callback func(int, float32) bool) *Value { + + for index, val := range v.MustFloat32Slice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereFloat32 uses the specified decider function to select items +// from the []float32. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereFloat32(decider func(int, float32) bool) *Value { + + var selected []float32 + + v.EachFloat32(func(index int, val float32) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupFloat32 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]float32. +func (v *Value) GroupFloat32(grouper func(int, float32) string) *Value { + + groups := make(map[string][]float32) + + v.EachFloat32(func(index int, val float32) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]float32, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceFloat32 uses the specified function to replace each float32s +// by iterating each item. The data in the returned result will be a +// []float32 containing the replaced items. +func (v *Value) ReplaceFloat32(replacer func(int, float32) float32) *Value { + + arr := v.MustFloat32Slice() + replaced := make([]float32, len(arr)) + + v.EachFloat32(func(index int, val float32) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectFloat32 uses the specified collector function to collect a value +// for each of the float32s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectFloat32(collector func(int, float32) interface{}) *Value { + + arr := v.MustFloat32Slice() + collected := make([]interface{}, len(arr)) + + v.EachFloat32(func(index int, val float32) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} + +/* + Float64 (float64 and []float64) + -------------------------------------------------- +*/ + +// Float64 gets the value as a float64, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Float64(optionalDefault ...float64) float64 { + if s, ok := v.data.(float64); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustFloat64 gets the value as a float64. +// +// Panics if the object is not a float64. +func (v *Value) MustFloat64() float64 { + return v.data.(float64) +} + +// Float64Slice gets the value as a []float64, returns the optionalDefault +// value or nil if the value is not a []float64. +func (v *Value) Float64Slice(optionalDefault ...[]float64) []float64 { + if s, ok := v.data.([]float64); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustFloat64Slice gets the value as a []float64. +// +// Panics if the object is not a []float64. +func (v *Value) MustFloat64Slice() []float64 { + return v.data.([]float64) +} + +// IsFloat64 gets whether the object contained is a float64 or not. +func (v *Value) IsFloat64() bool { + _, ok := v.data.(float64) + return ok +} + +// IsFloat64Slice gets whether the object contained is a []float64 or not. +func (v *Value) IsFloat64Slice() bool { + _, ok := v.data.([]float64) + return ok +} + +// EachFloat64 calls the specified callback for each object +// in the []float64. +// +// Panics if the object is the wrong type. +func (v *Value) EachFloat64(callback func(int, float64) bool) *Value { + + for index, val := range v.MustFloat64Slice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereFloat64 uses the specified decider function to select items +// from the []float64. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereFloat64(decider func(int, float64) bool) *Value { + + var selected []float64 + + v.EachFloat64(func(index int, val float64) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupFloat64 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]float64. +func (v *Value) GroupFloat64(grouper func(int, float64) string) *Value { + + groups := make(map[string][]float64) + + v.EachFloat64(func(index int, val float64) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]float64, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceFloat64 uses the specified function to replace each float64s +// by iterating each item. The data in the returned result will be a +// []float64 containing the replaced items. +func (v *Value) ReplaceFloat64(replacer func(int, float64) float64) *Value { + + arr := v.MustFloat64Slice() + replaced := make([]float64, len(arr)) + + v.EachFloat64(func(index int, val float64) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectFloat64 uses the specified collector function to collect a value +// for each of the float64s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectFloat64(collector func(int, float64) interface{}) *Value { + + arr := v.MustFloat64Slice() + collected := make([]interface{}, len(arr)) + + v.EachFloat64(func(index int, val float64) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} + +/* + Complex64 (complex64 and []complex64) + -------------------------------------------------- +*/ + +// Complex64 gets the value as a complex64, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Complex64(optionalDefault ...complex64) complex64 { + if s, ok := v.data.(complex64); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustComplex64 gets the value as a complex64. +// +// Panics if the object is not a complex64. +func (v *Value) MustComplex64() complex64 { + return v.data.(complex64) +} + +// Complex64Slice gets the value as a []complex64, returns the optionalDefault +// value or nil if the value is not a []complex64. +func (v *Value) Complex64Slice(optionalDefault ...[]complex64) []complex64 { + if s, ok := v.data.([]complex64); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustComplex64Slice gets the value as a []complex64. +// +// Panics if the object is not a []complex64. +func (v *Value) MustComplex64Slice() []complex64 { + return v.data.([]complex64) +} + +// IsComplex64 gets whether the object contained is a complex64 or not. +func (v *Value) IsComplex64() bool { + _, ok := v.data.(complex64) + return ok +} + +// IsComplex64Slice gets whether the object contained is a []complex64 or not. +func (v *Value) IsComplex64Slice() bool { + _, ok := v.data.([]complex64) + return ok +} + +// EachComplex64 calls the specified callback for each object +// in the []complex64. +// +// Panics if the object is the wrong type. +func (v *Value) EachComplex64(callback func(int, complex64) bool) *Value { + + for index, val := range v.MustComplex64Slice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereComplex64 uses the specified decider function to select items +// from the []complex64. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereComplex64(decider func(int, complex64) bool) *Value { + + var selected []complex64 + + v.EachComplex64(func(index int, val complex64) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupComplex64 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]complex64. +func (v *Value) GroupComplex64(grouper func(int, complex64) string) *Value { + + groups := make(map[string][]complex64) + + v.EachComplex64(func(index int, val complex64) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]complex64, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceComplex64 uses the specified function to replace each complex64s +// by iterating each item. The data in the returned result will be a +// []complex64 containing the replaced items. +func (v *Value) ReplaceComplex64(replacer func(int, complex64) complex64) *Value { + + arr := v.MustComplex64Slice() + replaced := make([]complex64, len(arr)) + + v.EachComplex64(func(index int, val complex64) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectComplex64 uses the specified collector function to collect a value +// for each of the complex64s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectComplex64(collector func(int, complex64) interface{}) *Value { + + arr := v.MustComplex64Slice() + collected := make([]interface{}, len(arr)) + + v.EachComplex64(func(index int, val complex64) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} + +/* + Complex128 (complex128 and []complex128) + -------------------------------------------------- +*/ + +// Complex128 gets the value as a complex128, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Complex128(optionalDefault ...complex128) complex128 { + if s, ok := v.data.(complex128); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustComplex128 gets the value as a complex128. +// +// Panics if the object is not a complex128. +func (v *Value) MustComplex128() complex128 { + return v.data.(complex128) +} + +// Complex128Slice gets the value as a []complex128, returns the optionalDefault +// value or nil if the value is not a []complex128. +func (v *Value) Complex128Slice(optionalDefault ...[]complex128) []complex128 { + if s, ok := v.data.([]complex128); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustComplex128Slice gets the value as a []complex128. +// +// Panics if the object is not a []complex128. +func (v *Value) MustComplex128Slice() []complex128 { + return v.data.([]complex128) +} + +// IsComplex128 gets whether the object contained is a complex128 or not. +func (v *Value) IsComplex128() bool { + _, ok := v.data.(complex128) + return ok +} + +// IsComplex128Slice gets whether the object contained is a []complex128 or not. +func (v *Value) IsComplex128Slice() bool { + _, ok := v.data.([]complex128) + return ok +} + +// EachComplex128 calls the specified callback for each object +// in the []complex128. +// +// Panics if the object is the wrong type. +func (v *Value) EachComplex128(callback func(int, complex128) bool) *Value { + + for index, val := range v.MustComplex128Slice() { + carryon := callback(index, val) + if carryon == false { + break + } + } + + return v + +} + +// WhereComplex128 uses the specified decider function to select items +// from the []complex128. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereComplex128(decider func(int, complex128) bool) *Value { + + var selected []complex128 + + v.EachComplex128(func(index int, val complex128) bool { + shouldSelect := decider(index, val) + if shouldSelect == false { + selected = append(selected, val) + } + return true + }) + + return &Value{data: selected} + +} + +// GroupComplex128 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]complex128. +func (v *Value) GroupComplex128(grouper func(int, complex128) string) *Value { + + groups := make(map[string][]complex128) + + v.EachComplex128(func(index int, val complex128) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]complex128, 0) + } + groups[group] = append(groups[group], val) + return true + }) + + return &Value{data: groups} + +} + +// ReplaceComplex128 uses the specified function to replace each complex128s +// by iterating each item. The data in the returned result will be a +// []complex128 containing the replaced items. +func (v *Value) ReplaceComplex128(replacer func(int, complex128) complex128) *Value { + + arr := v.MustComplex128Slice() + replaced := make([]complex128, len(arr)) + + v.EachComplex128(func(index int, val complex128) bool { + replaced[index] = replacer(index, val) + return true + }) + + return &Value{data: replaced} + +} + +// CollectComplex128 uses the specified collector function to collect a value +// for each of the complex128s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectComplex128(collector func(int, complex128) interface{}) *Value { + + arr := v.MustComplex128Slice() + collected := make([]interface{}, len(arr)) + + v.EachComplex128(func(index int, val complex128) bool { + collected[index] = collector(index, val) + return true + }) + + return &Value{data: collected} +} diff --git a/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/value.go b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/value.go new file mode 100644 index 00000000..7aaef06b --- /dev/null +++ b/vendor/github.com/stretchr/testify/vendor/github.com/stretchr/objx/value.go @@ -0,0 +1,13 @@ +package objx + +// Value provides methods for extracting interface{} data in various +// types. +type Value struct { + // data contains the raw data being managed by this Value + data interface{} +} + +// Data returns the raw data contained by this Value +func (v *Value) Data() interface{} { + return v.data +} diff --git a/vendor/github.com/technoweenie/go-contentaddressable/LICENSE b/vendor/github.com/technoweenie/go-contentaddressable/LICENSE new file mode 100644 index 00000000..1bc5edff --- /dev/null +++ b/vendor/github.com/technoweenie/go-contentaddressable/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2014 rick olson + +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. diff --git a/vendor/github.com/technoweenie/go-contentaddressable/README.md b/vendor/github.com/technoweenie/go-contentaddressable/README.md new file mode 100644 index 00000000..1af73df4 --- /dev/null +++ b/vendor/github.com/technoweenie/go-contentaddressable/README.md @@ -0,0 +1,49 @@ +# Content Addressable + +Package contentaddressable contains tools for writing content addressable files. +Files are written to a temporary location, and only renamed to the final +location after the file's OID (Object ID) has been verified. + +```go +filename := "path/to/01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b" +file, err := contentaddressable.NewFile(filename) +if err != nil { + panic(err) +} +defer file.Close() + +file.Oid // 01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b + +written, err := io.Copy(file, someReader) + +if err == nil { +// Move file to final location if OID is verified. + err = file.Accept() +} + +if err != nil { + panic(err) +} +``` + +See the [godocs](http://godoc.org/github.com/technoweenie/go-contentaddressable) +for details. + +## Installation + + $ go get github.com/technoweenie/go-contentaddressable + +Then import it: + + import "github.com/technoweenie/go-contentaddressable" + +## Note on Patches/Pull Requests + +1. Fork the project on GitHub. +2. Make your feature addition or bug fix. +3. Add tests for it. This is important so I don't break it in a future version + unintentionally. +4. Commit, do not mess with version or history. (if you want to have + your own version, that is fine but bump version in a commit by itself I can + ignore when I pull) +5. Send me a pull request. Bonus points for topic branches. diff --git a/vendor/github.com/technoweenie/go-contentaddressable/contentaddressable.go b/vendor/github.com/technoweenie/go-contentaddressable/contentaddressable.go new file mode 100644 index 00000000..7c8c4d5a --- /dev/null +++ b/vendor/github.com/technoweenie/go-contentaddressable/contentaddressable.go @@ -0,0 +1,28 @@ +/* +Package contentaddressable contains tools for writing content addressable files. +Files are written to a temporary location, and only renamed to the final +location after the file's OID (Object ID) has been verified. + + filename := "path/to/01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b" + file, err := contentaddressable.NewFile(filename) + if err != nil { + panic(err) + } + defer file.Close() + + file.Oid // 01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b + + written, err := io.Copy(file, someReader) + + if err == nil { + // Move file to final location if OID is verified. + err = file.Accept() + } + + if err != nil { + panic(err) + } + +Currently SHA-256 is used for a file's OID. +*/ +package contentaddressable diff --git a/vendor/github.com/technoweenie/go-contentaddressable/file.go b/vendor/github.com/technoweenie/go-contentaddressable/file.go new file mode 100644 index 00000000..7909ec18 --- /dev/null +++ b/vendor/github.com/technoweenie/go-contentaddressable/file.go @@ -0,0 +1,131 @@ +package contentaddressable + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "hash" + "os" + "path/filepath" +) + +var ( + AlreadyClosed = errors.New("Already closed.") + HasData = errors.New("Destination file already has data.") +) + +// File handles the atomic writing of a content addressable file. It writes to +// a temp file, and then renames to the final location after Accept(). +type File struct { + Oid string + filename string + tempFilename string + file *os.File + tempFile *os.File + hasher hash.Hash +} + +// NewFile initializes a content addressable file for writing. It opens both +// the given filename, and a temp filename in exclusive mode. The *File OID +// is taken from the base name of the given filename. +func NewFile(filename string) (*File, error) { + oid := filepath.Base(filename) + dir := filepath.Dir(filename) + if err := os.MkdirAll(dir, 0755); err != nil { + return nil, err + } + + tempFilename := filename + "-temp" + tempFile, err := os.OpenFile(tempFilename, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644) + if err != nil { + return nil, err + } + + file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644) + if err != nil { + cleanupFile(tempFile) + return nil, err + } + + caw := &File{ + Oid: oid, + filename: filename, + tempFilename: tempFilename, + file: file, + tempFile: tempFile, + hasher: sha256.New(), + } + + return caw, nil +} + +// Write sends data to the temporary file. +func (w *File) Write(p []byte) (int, error) { + if w.Closed() { + return 0, AlreadyClosed + } + + w.hasher.Write(p) + return w.tempFile.Write(p) +} + +// Accept verifies the written content SHA-256 signature matches the given OID. +// If it matches, the temp file is renamed to the original filename. If not, +// an error is returned. +func (w *File) Accept() error { + if w.Closed() { + return AlreadyClosed + } + + sig := hex.EncodeToString(w.hasher.Sum(nil)) + if sig != w.Oid { + return fmt.Errorf("Content mismatch. Expected OID %s, got %s", w.Oid, sig) + } + + if err := cleanupFile(w.file); err != nil { + return err + } + w.file = nil + + w.tempFile.Close() + err := os.Rename(w.tempFilename, w.filename) + w.Close() + return err +} + +// Close cleans up the internal file objects. +func (w *File) Close() error { + if w.tempFile != nil { + if err := cleanupFile(w.tempFile); err != nil { + return err + } + w.tempFile = nil + } + + if w.file != nil { + if err := cleanupFile(w.file); err != nil { + return err + } + w.file = nil + } + + return nil +} + +// Closed reports whether this file object has been closed. +func (w *File) Closed() bool { + if w.tempFile == nil || w.file == nil { + return true + } + return false +} + +func cleanupFile(f *os.File) error { + err := f.Close() + if err := os.RemoveAll(f.Name()); err != nil { + return err + } + + return err +} diff --git a/vendor/github.com/technoweenie/go-contentaddressable/file_test.go b/vendor/github.com/technoweenie/go-contentaddressable/file_test.go new file mode 100644 index 00000000..b9dca47c --- /dev/null +++ b/vendor/github.com/technoweenie/go-contentaddressable/file_test.go @@ -0,0 +1,176 @@ +package contentaddressable + +import ( + "io/ioutil" + "os" + "path/filepath" + "strings" + "testing" + "reflect" + "runtime" +) + +var supOid = "a2b71d6ee8997eb87b25ab42d566c44f6a32871752c7c73eb5578cb1182f7be0" + +func TestFile(t *testing.T) { + test := SetupFile(t) + defer test.Teardown() + + filename := filepath.Join(test.Path, supOid) + aw, err := NewFile(filename) + assertEqual(t, nil, err) + + n, err := aw.Write([]byte("SUP")) + assertEqual(t, nil, err) + assertEqual(t, 3, n) + + by, err := ioutil.ReadFile(filename) + assertEqual(t, nil, err) + assertEqual(t, 0, len(by)) + + assertEqual(t, nil, aw.Accept()) + + by, err = ioutil.ReadFile(filename) + assertEqual(t, nil, err) + assertEqual(t, "SUP", string(by)) + + assertEqual(t, nil, aw.Close()) +} + +func TestFileMismatch(t *testing.T) { + test := SetupFile(t) + defer test.Teardown() + + filename := filepath.Join(test.Path, "b2b71d6ee8997eb87b25ab42d566c44f6a32871752c7c73eb5578cb1182f7be0") + aw, err := NewFile(filename) + assertEqual(t, nil, err) + + n, err := aw.Write([]byte("SUP")) + assertEqual(t, nil, err) + assertEqual(t, 3, n) + + by, err := ioutil.ReadFile(filename) + assertEqual(t, nil, err) + assertEqual(t, 0, len(by)) + + err = aw.Accept() + if err == nil || !strings.Contains(err.Error(), "Content mismatch") { + t.Errorf("Expected mismatch error: %s", err) + } + + by, err = ioutil.ReadFile(filename) + assertEqual(t, nil, err) + assertEqual(t, "", string(by)) + + assertEqual(t, nil, aw.Close()) + + _, err = ioutil.ReadFile(filename) + assertEqual(t, true, os.IsNotExist(err)) +} + +func TestFileCancel(t *testing.T) { + test := SetupFile(t) + defer test.Teardown() + + filename := filepath.Join(test.Path, supOid) + aw, err := NewFile(filename) + assertEqual(t, nil, err) + + n, err := aw.Write([]byte("SUP")) + assertEqual(t, nil, err) + assertEqual(t, 3, n) + + assertEqual(t, nil, aw.Close()) + + for _, name := range []string{aw.filename, aw.tempFilename} { + if _, err := os.Stat(name); err == nil { + t.Errorf("%s exists?", name) + } + } +} + +func TestFileLocks(t *testing.T) { + test := SetupFile(t) + defer test.Teardown() + + filename := filepath.Join(test.Path, supOid) + aw, err := NewFile(filename) + assertEqual(t, nil, err) + assertEqual(t, filename, aw.filename) + assertEqual(t, filename+"-temp", aw.tempFilename) + + files := []string{aw.filename, aw.tempFilename} + + for _, name := range files { + if _, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0665); err == nil { + t.Errorf("Able to open %s!", name) + } + } + + assertEqual(t, nil, aw.Close()) + + for _, name := range files { + f, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0665) + assertEqualf(t, nil, err, "unable to open %s: %s", name, err) + cleanupFile(f) + } +} + +func TestFileDuel(t *testing.T) { + test := SetupFile(t) + defer test.Teardown() + + filename := filepath.Join(test.Path, supOid) + aw, err := NewFile(filename) + assertEqual(t, nil, err) + defer aw.Close() + + if _, err := NewFile(filename); err == nil { + t.Errorf("Expected a file open conflict!") + } +} + +func SetupFile(t *testing.T) *FileTest { + wd, err := os.Getwd() + if err != nil { + t.Fatalf("Error getting wd: %s", err) + } + + return &FileTest{filepath.Join(wd, "File"), t} +} + +type FileTest struct { + Path string + *testing.T +} + +func (t *FileTest) Teardown() { + if err := os.RemoveAll(t.Path); err != nil { + t.Fatalf("Error removing %s: %s", t.Path, err) + } +} + +func assertEqual(t *testing.T, expected, actual interface{}) { + checkAssertion(t, expected, actual, "") +} + +func assertEqualf(t *testing.T, expected, actual interface{}, format string, args ...interface{}) { + checkAssertion(t, expected, actual, format, args...) +} + +func checkAssertion(t *testing.T, expected, actual interface{}, format string, args ...interface{}) { + if expected == nil { + if actual == nil { + return + } + } else if reflect.DeepEqual(expected, actual) { + return + } + + _, file, line, _ := runtime.Caller(2) // assertEqual + checkAssertion + t.Logf("%s:%d\nExpected: %v\nActual: %v", file, line, expected, actual) + if len(args) > 0 { + t.Logf("! - "+format, args...) + } + t.FailNow() +} diff --git a/vendor/github.com/xeipuuv/gojsonpointer/LICENSE-APACHE-2.0.txt b/vendor/github.com/xeipuuv/gojsonpointer/LICENSE-APACHE-2.0.txt new file mode 100644 index 00000000..55ede8a4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonpointer/LICENSE-APACHE-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2015 xeipuuv + + 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. diff --git a/vendor/github.com/xeipuuv/gojsonpointer/README.md b/vendor/github.com/xeipuuv/gojsonpointer/README.md new file mode 100644 index 00000000..dbe4d508 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonpointer/README.md @@ -0,0 +1,8 @@ +# gojsonpointer +An implementation of JSON Pointer - Go language + +## References +http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 + +### Note +The 4.Evaluation part of the previous reference, starting with 'If the currently referenced value is a JSON array, the reference token MUST contain either...' is not implemented. diff --git a/vendor/github.com/xeipuuv/gojsonpointer/pointer.go b/vendor/github.com/xeipuuv/gojsonpointer/pointer.go new file mode 100644 index 00000000..6ca317a4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonpointer/pointer.go @@ -0,0 +1,217 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// 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. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonpointer +// repository-desc An implementation of JSON Pointer - Go language +// +// description Main and unique file. +// +// created 25-02-2013 + +package gojsonpointer + +import ( + "errors" + "fmt" + "reflect" + "strconv" + "strings" +) + +const ( + const_empty_pointer = `` + const_pointer_separator = `/` + + const_invalid_start = `JSON pointer must be empty or start with a "` + const_pointer_separator + `"` +) + +type implStruct struct { + mode string // "SET" or "GET" + + inDocument interface{} + + setInValue interface{} + + getOutNode interface{} + getOutKind reflect.Kind + outError error +} + +func NewJsonPointer(jsonPointerString string) (JsonPointer, error) { + + var p JsonPointer + err := p.parse(jsonPointerString) + return p, err + +} + +type JsonPointer struct { + referenceTokens []string +} + +// "Constructor", parses the given string JSON pointer +func (p *JsonPointer) parse(jsonPointerString string) error { + + var err error + + if jsonPointerString != const_empty_pointer { + if !strings.HasPrefix(jsonPointerString, const_pointer_separator) { + err = errors.New(const_invalid_start) + } else { + referenceTokens := strings.Split(jsonPointerString, const_pointer_separator) + for _, referenceToken := range referenceTokens[1:] { + p.referenceTokens = append(p.referenceTokens, referenceToken) + } + } + } + + return err +} + +// Uses the pointer to retrieve a value from a JSON document +func (p *JsonPointer) Get(document interface{}) (interface{}, reflect.Kind, error) { + + is := &implStruct{mode: "GET", inDocument: document} + p.implementation(is) + return is.getOutNode, is.getOutKind, is.outError + +} + +// Uses the pointer to update a value from a JSON document +func (p *JsonPointer) Set(document interface{}, value interface{}) (interface{}, error) { + + is := &implStruct{mode: "SET", inDocument: document, setInValue: value} + p.implementation(is) + return document, is.outError + +} + +// Both Get and Set functions use the same implementation to avoid code duplication +func (p *JsonPointer) implementation(i *implStruct) { + + kind := reflect.Invalid + + // Full document when empty + if len(p.referenceTokens) == 0 { + i.getOutNode = i.inDocument + i.outError = nil + i.getOutKind = kind + i.outError = nil + return + } + + node := i.inDocument + + for ti, token := range p.referenceTokens { + + decodedToken := decodeReferenceToken(token) + isLastToken := ti == len(p.referenceTokens)-1 + + rValue := reflect.ValueOf(node) + kind = rValue.Kind() + + switch kind { + + case reflect.Map: + m := node.(map[string]interface{}) + if _, ok := m[decodedToken]; ok { + node = m[decodedToken] + if isLastToken && i.mode == "SET" { + m[decodedToken] = i.setInValue + } + } else { + i.outError = errors.New(fmt.Sprintf("Object has no key '%s'", token)) + i.getOutKind = kind + i.getOutNode = nil + return + } + + case reflect.Slice: + s := node.([]interface{}) + tokenIndex, err := strconv.Atoi(token) + if err != nil { + i.outError = errors.New(fmt.Sprintf("Invalid array index '%s'", token)) + i.getOutKind = kind + i.getOutNode = nil + return + } + sLength := len(s) + if tokenIndex < 0 || tokenIndex >= sLength { + i.outError = errors.New(fmt.Sprintf("Out of bound array[0,%d] index '%d'", sLength, tokenIndex)) + i.getOutKind = kind + i.getOutNode = nil + return + } + + node = s[tokenIndex] + if isLastToken && i.mode == "SET" { + s[tokenIndex] = i.setInValue + } + + default: + i.outError = errors.New(fmt.Sprintf("Invalid token reference '%s'", token)) + i.getOutKind = kind + i.getOutNode = nil + return + } + + } + + rValue := reflect.ValueOf(node) + kind = rValue.Kind() + + i.getOutNode = node + i.getOutKind = kind + i.outError = nil +} + +// Pointer to string representation function +func (p *JsonPointer) String() string { + + if len(p.referenceTokens) == 0 { + return const_empty_pointer + } + + pointerString := const_pointer_separator + strings.Join(p.referenceTokens, const_pointer_separator) + + return pointerString +} + +// Specific JSON pointer encoding here +// ~0 => ~ +// ~1 => / +// ... and vice versa + +const ( + const_encoded_reference_token_0 = `~0` + const_encoded_reference_token_1 = `~1` + const_decoded_reference_token_0 = `~` + const_decoded_reference_token_1 = `/` +) + +func decodeReferenceToken(token string) string { + step1 := strings.Replace(token, const_encoded_reference_token_1, const_decoded_reference_token_1, -1) + step2 := strings.Replace(step1, const_encoded_reference_token_0, const_decoded_reference_token_0, -1) + return step2 +} + +func encodeReferenceToken(token string) string { + step1 := strings.Replace(token, const_decoded_reference_token_1, const_encoded_reference_token_1, -1) + step2 := strings.Replace(step1, const_decoded_reference_token_0, const_encoded_reference_token_0, -1) + return step2 +} diff --git a/vendor/github.com/xeipuuv/gojsonpointer/pointer_test.go b/vendor/github.com/xeipuuv/gojsonpointer/pointer_test.go new file mode 100644 index 00000000..ddf3663d --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonpointer/pointer_test.go @@ -0,0 +1,205 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// 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. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonpointer +// repository-desc An implementation of JSON Pointer - Go language +// +// description Automated tests on package. +// +// created 03-03-2013 + +package gojsonpointer + +import ( + "encoding/json" + "testing" +) + +const ( + TEST_DOCUMENT_NB_ELEMENTS = 11 + TEST_NODE_OBJ_NB_ELEMENTS = 4 + TEST_DOCUMENT_STRING = `{ +"foo": ["bar", "baz"], +"obj": { "a":1, "b":2, "c":[3,4], "d":[ {"e":9}, {"f":[50,51]} ] }, +"": 0, +"a/b": 1, +"c%d": 2, +"e^f": 3, +"g|h": 4, +"i\\j": 5, +"k\"l": 6, +" ": 7, +"m~n": 8 +}` +) + +var testDocumentJson interface{} + +func init() { + json.Unmarshal([]byte(TEST_DOCUMENT_STRING), &testDocumentJson) +} + +func TestEscaping(t *testing.T) { + + ins := []string{`/`, `/`, `/a~1b`, `/a~1b`, `/c%d`, `/e^f`, `/g|h`, `/i\j`, `/k"l`, `/ `, `/m~0n`} + outs := []float64{0, 0, 1, 1, 2, 3, 4, 5, 6, 7, 8} + + for i := range ins { + + p, err := NewJsonPointer(ins[i]) + if err != nil { + t.Errorf("NewJsonPointer(%v) error %v", ins[i], err.Error()) + } + + result, _, err := p.Get(testDocumentJson) + if err != nil { + t.Errorf("Get(%v) error %v", ins[i], err.Error()) + } + + if result != outs[i] { + t.Errorf("Get(%v) = %v, expect %v", ins[i], result, outs[i]) + } + } + +} + +func TestFullDocument(t *testing.T) { + + in := `` + + p, err := NewJsonPointer(in) + if err != nil { + t.Errorf("NewJsonPointer(%v) error %v", in, err.Error()) + } + + result, _, err := p.Get(testDocumentJson) + if err != nil { + t.Errorf("Get(%v) error %v", in, err.Error()) + } + + if len(result.(map[string]interface{})) != TEST_DOCUMENT_NB_ELEMENTS { + t.Errorf("Get(%v) = %v, expect full document", in, result) + } +} + +func TestGetNode(t *testing.T) { + + in := `/obj` + + p, err := NewJsonPointer(in) + if err != nil { + t.Errorf("NewJsonPointer(%v) error %v", in, err.Error()) + } + + result, _, err := p.Get(testDocumentJson) + if err != nil { + t.Errorf("Get(%v) error %v", in, err.Error()) + } + + if len(result.(map[string]interface{})) != TEST_NODE_OBJ_NB_ELEMENTS { + t.Errorf("Get(%v) = %v, expect full document", in, result) + } +} + +func TestArray(t *testing.T) { + + ins := []string{`/foo/0`, `/foo/0`, `/foo/1`} + outs := []string{"bar", "bar", "baz"} + + for i := range ins { + + p, err := NewJsonPointer(ins[i]) + if err != nil { + t.Errorf("NewJsonPointer(%v) error %v", ins[i], err.Error()) + } + + result, _, err := p.Get(testDocumentJson) + if err != nil { + t.Errorf("Get(%v) error %v", ins[i], err.Error()) + } + + if result != outs[i] { + t.Errorf("Get(%v) = %v, expect %v", ins[i], result, outs[i]) + } + } + +} + +func TestObject(t *testing.T) { + + ins := []string{`/obj/a`, `/obj/b`, `/obj/c/0`, `/obj/c/1`, `/obj/c/1`, `/obj/d/1/f/0`} + outs := []float64{1, 2, 3, 4, 4, 50} + + for i := range ins { + + p, err := NewJsonPointer(ins[i]) + if err != nil { + t.Errorf("NewJsonPointer(%v) error %v", ins[i], err.Error()) + } + + result, _, err := p.Get(testDocumentJson) + if err != nil { + t.Errorf("Get(%v) error %v", ins[i], err.Error()) + } + + if result != outs[i] { + t.Errorf("Get(%v) = %v, expect %v", ins[i], result, outs[i]) + } + } + +} + +func TestSetNode(t *testing.T) { + + jsonText := `{"a":[{"b": 1, "c": 2}], "d": 3}` + + var jsonDocument interface{} + json.Unmarshal([]byte(jsonText), &jsonDocument) + + in := "/a/0/c" + + p, err := NewJsonPointer(in) + if err != nil { + t.Errorf("NewJsonPointer(%v) error %v", in, err.Error()) + } + + _, err = p.Set(jsonDocument, 999) + if err != nil { + t.Errorf("Set(%v) error %v", in, err.Error()) + } + + firstNode := jsonDocument.(map[string]interface{}) + if len(firstNode) != 2 { + t.Errorf("Set(%s) failed", in) + } + + sliceNode := firstNode["a"].([]interface{}) + if len(sliceNode) != 1 { + t.Errorf("Set(%s) failed", in) + } + + changedNode := sliceNode[0].(map[string]interface{}) + changedNodeValue := changedNode["c"].(int) + + if changedNodeValue != 999 { + if len(sliceNode) != 1 { + t.Errorf("Set(%s) failed", in) + } + } + +} diff --git a/vendor/github.com/xeipuuv/gojsonreference/LICENSE-APACHE-2.0.txt b/vendor/github.com/xeipuuv/gojsonreference/LICENSE-APACHE-2.0.txt new file mode 100644 index 00000000..55ede8a4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonreference/LICENSE-APACHE-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2015 xeipuuv + + 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. diff --git a/vendor/github.com/xeipuuv/gojsonreference/README.md b/vendor/github.com/xeipuuv/gojsonreference/README.md new file mode 100644 index 00000000..9ab6e1eb --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonreference/README.md @@ -0,0 +1,10 @@ +# gojsonreference +An implementation of JSON Reference - Go language + +## Dependencies +https://github.com/xeipuuv/gojsonpointer + +## References +http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 + +http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 diff --git a/vendor/github.com/xeipuuv/gojsonreference/reference.go b/vendor/github.com/xeipuuv/gojsonreference/reference.go new file mode 100644 index 00000000..d4d2eca0 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonreference/reference.go @@ -0,0 +1,141 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// 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. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonreference +// repository-desc An implementation of JSON Reference - Go language +// +// description Main and unique file. +// +// created 26-02-2013 + +package gojsonreference + +import ( + "errors" + "github.com/xeipuuv/gojsonpointer" + "net/url" + "path/filepath" + "runtime" + "strings" +) + +const ( + const_fragment_char = `#` +) + +func NewJsonReference(jsonReferenceString string) (JsonReference, error) { + + var r JsonReference + err := r.parse(jsonReferenceString) + return r, err + +} + +type JsonReference struct { + referenceUrl *url.URL + referencePointer gojsonpointer.JsonPointer + + HasFullUrl bool + HasUrlPathOnly bool + HasFragmentOnly bool + HasFileScheme bool + HasFullFilePath bool +} + +func (r *JsonReference) GetUrl() *url.URL { + return r.referenceUrl +} + +func (r *JsonReference) GetPointer() *gojsonpointer.JsonPointer { + return &r.referencePointer +} + +func (r *JsonReference) String() string { + + if r.referenceUrl != nil { + return r.referenceUrl.String() + } + + if r.HasFragmentOnly { + return const_fragment_char + r.referencePointer.String() + } + + return r.referencePointer.String() +} + +func (r *JsonReference) IsCanonical() bool { + return (r.HasFileScheme && r.HasFullFilePath) || (!r.HasFileScheme && r.HasFullUrl) +} + +// "Constructor", parses the given string JSON reference +func (r *JsonReference) parse(jsonReferenceString string) (err error) { + + r.referenceUrl, err = url.Parse(jsonReferenceString) + if err != nil { + return + } + refUrl := r.referenceUrl + + if refUrl.Scheme != "" && refUrl.Host != "" { + r.HasFullUrl = true + } else { + if refUrl.Path != "" { + r.HasUrlPathOnly = true + } else if refUrl.RawQuery == "" && refUrl.Fragment != "" { + r.HasFragmentOnly = true + } + } + + r.HasFileScheme = refUrl.Scheme == "file" + if runtime.GOOS == "windows" { + // on Windows, a file URL may have an extra leading slash, and if it + // doesn't then its first component will be treated as the host by the + // Go runtime + if refUrl.Host == "" && strings.HasPrefix(refUrl.Path, "/") { + r.HasFullFilePath = filepath.IsAbs(refUrl.Path[1:]) + } else { + r.HasFullFilePath = filepath.IsAbs(refUrl.Host + refUrl.Path) + } + } else { + r.HasFullFilePath = filepath.IsAbs(refUrl.Path) + } + + // invalid json-pointer error means url has no json-pointer fragment. simply ignore error + r.referencePointer, _ = gojsonpointer.NewJsonPointer(refUrl.Fragment) + + return +} + +// Creates a new reference from a parent and a child +// If the child cannot inherit from the parent, an error is returned +func (r *JsonReference) Inherits(child JsonReference) (*JsonReference, error) { + childUrl := child.GetUrl() + parentUrl := r.GetUrl() + if childUrl == nil { + return nil, errors.New("childUrl is nil!") + } + if parentUrl == nil { + return nil, errors.New("parentUrl is nil!") + } + + ref, err := NewJsonReference(parentUrl.ResolveReference(childUrl).String()) + if err != nil { + return nil, err + } + return &ref, err +} diff --git a/vendor/github.com/xeipuuv/gojsonreference/reference_test.go b/vendor/github.com/xeipuuv/gojsonreference/reference_test.go new file mode 100644 index 00000000..4f6e7735 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonreference/reference_test.go @@ -0,0 +1,378 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// 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. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonreference +// repository-desc An implementation of JSON Reference - Go language +// +// description Automated tests on package. +// +// created 03-03-2013 + +package gojsonreference + +import ( + "testing" +) + +func TestFull(t *testing.T) { + + in := "http://host/path/a/b/c#/f/a/b" + + r1, err := NewJsonReference(in) + if err != nil { + t.Errorf("NewJsonReference(%v) error %s", in, err.Error()) + } + + if in != r1.String() { + t.Errorf("NewJsonReference(%v) = %v, expect %v", in, r1.String(), in) + } + + if r1.HasFragmentOnly != false { + t.Errorf("NewJsonReference(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) + } + + if r1.HasFullUrl != true { + t.Errorf("NewJsonReference(%v)::HasFullUrl %v expect %v", in, r1.HasFullUrl, true) + } + + if r1.HasUrlPathOnly != false { + t.Errorf("NewJsonReference(%v)::HasUrlPathOnly %v expect %v", in, r1.HasUrlPathOnly, false) + } + + if r1.HasFileScheme != false { + t.Errorf("NewJsonReference(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) + } + + if r1.GetPointer().String() != "/f/a/b" { + t.Errorf("NewJsonReference(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "/f/a/b") + } +} + +func TestFullUrl(t *testing.T) { + + in := "http://host/path/a/b/c" + + r1, err := NewJsonReference(in) + if err != nil { + t.Errorf("NewJsonReference(%v) error %s", in, err.Error()) + } + + if in != r1.String() { + t.Errorf("NewJsonReference(%v) = %v, expect %v", in, r1.String(), in) + } + + if r1.HasFragmentOnly != false { + t.Errorf("NewJsonReference(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) + } + + if r1.HasFullUrl != true { + t.Errorf("NewJsonReference(%v)::HasFullUrl %v expect %v", in, r1.HasFullUrl, true) + } + + if r1.HasUrlPathOnly != false { + t.Errorf("NewJsonReference(%v)::HasUrlPathOnly %v expect %v", in, r1.HasUrlPathOnly, false) + } + + if r1.HasFileScheme != false { + t.Errorf("NewJsonReference(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) + } + + if r1.GetPointer().String() != "" { + t.Errorf("NewJsonReference(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "") + } +} + +func TestFragmentOnly(t *testing.T) { + + in := "#/fragment/only" + + r1, err := NewJsonReference(in) + if err != nil { + t.Errorf("NewJsonReference(%v) error %s", in, err.Error()) + } + + if in != r1.String() { + t.Errorf("NewJsonReference(%v) = %v, expect %v", in, r1.String(), in) + } + + if r1.HasFragmentOnly != true { + t.Errorf("NewJsonReference(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, true) + } + + if r1.HasFullUrl != false { + t.Errorf("NewJsonReference(%v)::HasFullUrl %v expect %v", in, r1.HasFullUrl, false) + } + + if r1.HasUrlPathOnly != false { + t.Errorf("NewJsonReference(%v)::HasUrlPathOnly %v expect %v", in, r1.HasUrlPathOnly, false) + } + + if r1.HasFileScheme != false { + t.Errorf("NewJsonReference(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) + } + + if r1.GetPointer().String() != "/fragment/only" { + t.Errorf("NewJsonReference(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "/fragment/only") + } +} + +func TestUrlPathOnly(t *testing.T) { + + in := "/documents/document.json" + + r1, err := NewJsonReference(in) + if err != nil { + t.Errorf("NewJsonReference(%v) error %s", in, err.Error()) + } + + if in != r1.String() { + t.Errorf("NewJsonReference(%v) = %v, expect %v", in, r1.String(), in) + } + + if r1.HasFragmentOnly != false { + t.Errorf("NewJsonReference(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) + } + + if r1.HasFullUrl != false { + t.Errorf("NewJsonReference(%v)::HasFullUrl %v expect %v", in, r1.HasFullUrl, false) + } + + if r1.HasUrlPathOnly != true { + t.Errorf("NewJsonReference(%v)::HasUrlPathOnly %v expect %v", in, r1.HasUrlPathOnly, true) + } + + if r1.HasFileScheme != false { + t.Errorf("NewJsonReference(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) + } + + if r1.GetPointer().String() != "" { + t.Errorf("NewJsonReference(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "") + } +} + +func TestUrlRelativePathOnly(t *testing.T) { + + in := "document.json" + + r1, err := NewJsonReference(in) + if err != nil { + t.Errorf("NewJsonReference(%v) error %s", in, err.Error()) + } + + if in != r1.String() { + t.Errorf("NewJsonReference(%v) = %v, expect %v", in, r1.String(), in) + } + + if r1.HasFragmentOnly != false { + t.Errorf("NewJsonReference(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) + } + + if r1.HasFullUrl != false { + t.Errorf("NewJsonReference(%v)::HasFullUrl %v expect %v", in, r1.HasFullUrl, false) + } + + if r1.HasUrlPathOnly != true { + t.Errorf("NewJsonReference(%v)::HasUrlPathOnly %v expect %v", in, r1.HasUrlPathOnly, true) + } + + if r1.HasFileScheme != false { + t.Errorf("NewJsonReference(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) + } + + if r1.GetPointer().String() != "" { + t.Errorf("NewJsonReference(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "") + } +} + +func TestInheritsValid(t *testing.T) { + + in1 := "http://www.test.com/doc.json" + in2 := "#/a/b" + out := in1 + in2 + + r1, _ := NewJsonReference(in1) + r2, _ := NewJsonReference(in2) + + result, err := r1.Inherits(r2) + if err != nil { + t.Errorf("Inherits(%s,%s) error %s", r1.String(), r2.String(), err.Error()) + } + + if result.String() != out { + t.Errorf("Inherits(%s,%s) = %s, expect %s", r1.String(), r2.String(), result.String(), out) + } + + if result.GetPointer().String() != "/a/b" { + t.Errorf("result(%v)::GetPointer() %v expect %v", result.String(), result.GetPointer().String(), "/a/b") + } +} + +func TestInheritsDifferentHost(t *testing.T) { + + in1 := "http://www.test.com/doc.json" + in2 := "http://www.test2.com/doc.json#bla" + + r1, _ := NewJsonReference(in1) + r2, _ := NewJsonReference(in2) + + result, err := r1.Inherits(r2) + + if err != nil { + t.Errorf("Inherits(%s,%s) should not fail. Error: %s", r1.String(), r2.String(), err.Error()) + } + + if result.String() != in2 { + t.Errorf("Inherits(%s,%s) should be %s but is %s", in1, in2, in2, result) + } + + if result.GetPointer().String() != "" { + t.Errorf("result(%v)::GetPointer() %v expect %v", result.String(), result.GetPointer().String(), "") + } +} + +func TestFileScheme(t *testing.T) { + + in1 := "file:///Users/mac/1.json#a" + in2 := "file:///Users/mac/2.json#b" + + r1, _ := NewJsonReference(in1) + r2, _ := NewJsonReference(in2) + + if r1.HasFragmentOnly != false { + t.Errorf("NewJsonReference(%v)::HasFragmentOnly %v expect %v", in1, r1.HasFragmentOnly, false) + } + + if r1.HasFileScheme != true { + t.Errorf("NewJsonReference(%v)::HasFileScheme %v expect %v", in1, r1.HasFileScheme, true) + } + + if r1.HasFullFilePath != true { + t.Errorf("NewJsonReference(%v)::HasFullFilePath %v expect %v", in1, r1.HasFullFilePath, true) + } + + if r1.IsCanonical() != true { + t.Errorf("NewJsonReference(%v)::IsCanonical %v expect %v", in1, r1.IsCanonical, true) + } + + result, err := r1.Inherits(r2) + if err != nil { + t.Errorf("Inherits(%s,%s) should not fail. Error: %s", r1.String(), r2.String(), err.Error()) + } + if result.String() != in2 { + t.Errorf("Inherits(%s,%s) should be %s but is %s", in1, in2, in2, result) + } + + if result.GetPointer().String() != "" { + t.Errorf("result(%v)::GetPointer() %v expect %v", result.String(), result.GetPointer().String(), "") + } +} + +func TestReferenceResolution(t *testing.T) { + + // 5.4. Reference Resolution Examples + // http://tools.ietf.org/html/rfc3986#section-5.4 + + base := "http://a/b/c/d;p?q" + baseRef, err := NewJsonReference(base) + + if err != nil { + t.Errorf("NewJsonReference(%s) failed error: %s", base, err.Error()) + } + if baseRef.String() != base { + t.Errorf("NewJsonReference(%s) %s expected %s", base, baseRef.String(), base) + } + + checks := []string{ + // 5.4.1. Normal Examples + // http://tools.ietf.org/html/rfc3986#section-5.4.1 + + "g:h", "g:h", + "g", "http://a/b/c/g", + "./g", "http://a/b/c/g", + "g/", "http://a/b/c/g/", + "/g", "http://a/g", + "//g", "http://g", + "?y", "http://a/b/c/d;p?y", + "g?y", "http://a/b/c/g?y", + "#s", "http://a/b/c/d;p?q#s", + "g#s", "http://a/b/c/g#s", + "g?y#s", "http://a/b/c/g?y#s", + ";x", "http://a/b/c/;x", + "g;x", "http://a/b/c/g;x", + "g;x?y#s", "http://a/b/c/g;x?y#s", + "", "http://a/b/c/d;p?q", + ".", "http://a/b/c/", + "./", "http://a/b/c/", + "..", "http://a/b/", + "../", "http://a/b/", + "../g", "http://a/b/g", + "../..", "http://a/", + "../../", "http://a/", + "../../g", "http://a/g", + + // 5.4.2. Abnormal Examples + // http://tools.ietf.org/html/rfc3986#section-5.4.2 + + "../../../g", "http://a/g", + "../../../../g", "http://a/g", + + "/./g", "http://a/g", + "/../g", "http://a/g", + "g.", "http://a/b/c/g.", + ".g", "http://a/b/c/.g", + "g..", "http://a/b/c/g..", + "..g", "http://a/b/c/..g", + + "./../g", "http://a/b/g", + "./g/.", "http://a/b/c/g/", + "g/./h", "http://a/b/c/g/h", + "g/../h", "http://a/b/c/h", + "g;x=1/./y", "http://a/b/c/g;x=1/y", + "g;x=1/../y", "http://a/b/c/y", + + "g?y/./x", "http://a/b/c/g?y/./x", + "g?y/../x", "http://a/b/c/g?y/../x", + "g#s/./x", "http://a/b/c/g#s/./x", + "g#s/../x", "http://a/b/c/g#s/../x", + + "http:g", "http:g", // for strict parsers + //"http:g", "http://a/b/c/g", // for backward compatibility + + } + for i := 0; i < len(checks); i += 2 { + child := checks[i] + expected := checks[i+1] + // fmt.Printf("%d: %v -> %v\n", i/2, child, expected) + + childRef, e := NewJsonReference(child) + if e != nil { + t.Errorf("%d: NewJsonReference(%s) failed error: %s", i/2, child, e.Error()) + } + + res, e := baseRef.Inherits(childRef) + if res == nil { + t.Errorf("%d: Inherits(%s, %s) nil not expected", i/2, base, child) + } + if e != nil { + t.Errorf("%d: Inherits(%s) failed error: %s", i/2, child, e.Error()) + } + if res.String() != expected { + t.Errorf("%d: Inherits(%s, %s) %s expected %s", i/2, base, child, res.String(), expected) + } + } +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/.gitignore b/vendor/github.com/xeipuuv/gojsonschema/.gitignore new file mode 100644 index 00000000..c1e0636f --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/.gitignore @@ -0,0 +1 @@ +*.sw[nop] diff --git a/vendor/github.com/xeipuuv/gojsonschema/.travis.yml b/vendor/github.com/xeipuuv/gojsonschema/.travis.yml new file mode 100644 index 00000000..9cc01e8a --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/.travis.yml @@ -0,0 +1,7 @@ +language: go +go: + - 1.3 +before_install: + - go get github.com/sigu-399/gojsonreference + - go get github.com/sigu-399/gojsonpointer + - go get github.com/stretchr/testify/assert diff --git a/vendor/github.com/xeipuuv/gojsonschema/LICENSE-APACHE-2.0.txt b/vendor/github.com/xeipuuv/gojsonschema/LICENSE-APACHE-2.0.txt new file mode 100644 index 00000000..55ede8a4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/LICENSE-APACHE-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2015 xeipuuv + + 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. diff --git a/vendor/github.com/xeipuuv/gojsonschema/README.md b/vendor/github.com/xeipuuv/gojsonschema/README.md new file mode 100644 index 00000000..187da61e --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/README.md @@ -0,0 +1,236 @@ +[![Build Status](https://travis-ci.org/xeipuuv/gojsonschema.svg)](https://travis-ci.org/xeipuuv/gojsonschema) + +# gojsonschema + +## Description + +An implementation of JSON Schema, based on IETF's draft v4 - Go language + +References : + +* http://json-schema.org +* http://json-schema.org/latest/json-schema-core.html +* http://json-schema.org/latest/json-schema-validation.html + +## Installation + +``` +go get github.com/xeipuuv/gojsonschema +``` + +Dependencies : +* [github.com/xeipuuv/gojsonpointer](https://github.com/xeipuuv/gojsonpointer) +* [github.com/xeipuuv/gojsonreference](https://github.com/xeipuuv/gojsonreference) +* [github.com/stretchr/testify/assert](https://github.com/stretchr/testify#assert-package) + +## Usage + +### Example + +```go + +package main + +import ( + "fmt" + "github.com/xeipuuv/gojsonschema" +) + +func main() { + + schemaLoader := gojsonschema.NewReferenceLoader("file:///home/me/schema.json") + documentLoader := gojsonschema.NewReferenceLoader("file:///home/me/document.json") + + result, err := gojsonschema.Validate(schemaLoader, documentLoader) + if err != nil { + panic(err.Error()) + } + + if result.Valid() { + fmt.Printf("The document is valid\n") + } else { + fmt.Printf("The document is not valid. see errors :\n") + for _, desc := range result.Errors() { + fmt.Printf("- %s\n", desc) + } + } + +} + + +``` + +#### Loaders + +There are various ways to load your JSON data. +In order to load your schemas and documents, +first declare an appropriate loader : + +* Web / HTTP, using a reference : + +```go +loader := gojsonschema.NewReferenceLoader("http://www.some_host.com/schema.json") +``` + +* Local file, using a reference : + +```go +loader := gojsonschema.NewReferenceLoader("file:///home/me/schema.json") +``` + +References use the URI scheme, the prefix (file://) and a full path to the file are required. + +* JSON strings : + +```go +loader := gojsonschema.NewStringLoader(`{"type": "string"}`) +``` + +* Custom Go types : + +```go +m := map[string]interface{}{"type": "string"} +loader := gojsonschema.NewGoLoader(m) +``` + +And + +```go +type Root struct { + Users []User `json:"users"` +} + +type User struct { + Name string `json:"name"` +} + +... + +data := Root{} +data.Users = append(data.Users, User{"John"}) +data.Users = append(data.Users, User{"Sophia"}) +data.Users = append(data.Users, User{"Bill"}) + +loader := gojsonschema.NewGoLoader(data) +``` + +#### Validation + +Once the loaders are set, validation is easy : + +```go +result, err := gojsonschema.Validate(schemaLoader, documentLoader) +``` + +Alternatively, you might want to load a schema only once and process to multiple validations : + +```go +schema, err := gojsonschema.NewSchema(schemaLoader) +... +result1, err := schema.Validate(documentLoader1) +... +result2, err := schema.Validate(documentLoader2) +... +// etc ... +``` + +To check the result : + +```go + if result.Valid() { + fmt.Printf("The document is valid\n") + } else { + fmt.Printf("The document is not valid. see errors :\n") + for _, err := range result.Errors() { + // Err implements the ResultError interface + fmt.Printf("- %s\n", err) + } + } +``` + +## Working with Errors + +The library handles string error codes which you can customize by creating your own gojsonschema.locale and setting it +```go +gojsonschema.Locale = YourCustomLocale{} +``` + +However, each error contains additional contextual information. + +**err.Type()**: *string* Returns the "type" of error that occurred. Note you can also type check. See below + +Note: An error of RequiredType has an err.Type() return value of "required" + + "required": RequiredError + "invalid_type": InvalidTypeError + "number_any_of": NumberAnyOfError + "number_one_of": NumberOneOfError + "number_all_of": NumberAllOfError + "number_not": NumberNotError + "missing_dependency": MissingDependencyError + "internal": InternalError + "enum": EnumError + "array_no_additional_items": ArrayNoAdditionalItemsError + "array_min_items": ArrayMinItemsError + "array_max_items": ArrayMaxItemsError + "unique": ItemsMustBeUniqueError + "array_min_properties": ArrayMinPropertiesError + "array_max_properties": ArrayMaxPropertiesError + "additional_property_not_allowed": AdditionalPropertyNotAllowedError + "invalid_property_pattern": InvalidPropertyPatternError + "string_gte": StringLengthGTEError + "string_lte": StringLengthLTEError + "pattern": DoesNotMatchPatternError + "multiple_of": MultipleOfError + "number_gte": NumberGTEError + "number_gt": NumberGTError + "number_lte": NumberLTEError + "number_lt": NumberLTError + +**err.Value()**: *interface{}* Returns the value given + +**err.Context()**: *gojsonschema.jsonContext* Returns the context. This has a String() method that will print something like this: (root).firstName + +**err.Field()**: *string* Returns the fieldname in the format firstName, or for embedded properties, person.firstName. This returns the same as the String() method on *err.Context()* but removes the (root). prefix. + +**err.Description()**: *string* The error description. This is based on the locale you are using. See the beginning of this section for overwriting the locale with a custom implementation. + +**err.Details()**: *gojsonschema.ErrorDetails* Returns a map[string]interface{} of additional error details specific to the error. For example, GTE errors will have a "min" value, LTE will have a "max" value. See errors.go for a full description of all the error details. Every error always contains a "field" key that holds the value of *err.Field()* + +Note in most cases, the err.Details() will be used to generate replacement strings in your locales. and not used directly i.e. +``` +%field% must be greater than or equal to %min% +``` + +## Formats +JSON Schema allows for optional "format" property to validate strings against well-known formats. gojsonschema ships with all of the formats defined in the spec that you can use like this: +````json +{"type": "string", "format": "email"} +```` +Available formats: date-time, hostname, email, ipv4, ipv6, uri. + +For repetitive or more complex formats, you can create custom format checkers and add them to gojsonschema like this: + +```go +// Define the format checker +type RoleFormatChecker struct {} + +// Ensure it meets the gojsonschema.FormatChecker interface +func (f RoleFormatChecker) IsFormat(input string) bool { + return strings.HasPrefix("ROLE_", input) +} + +// Add it to the library +gojsonschema.FormatCheckers.Add("role", RoleFormatChecker{}) +```` + +Now to use in your json schema: +````json +{"type": "string", "format": "role"} +```` + +## Uses + +gojsonschema uses the following test suite : + +https://github.com/json-schema/JSON-Schema-Test-Suite diff --git a/vendor/github.com/xeipuuv/gojsonschema/errors.go b/vendor/github.com/xeipuuv/gojsonschema/errors.go new file mode 100644 index 00000000..5146cbba --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/errors.go @@ -0,0 +1,242 @@ +package gojsonschema + +import ( + "fmt" + "strings" +) + +type ( + // RequiredError. ErrorDetails: property string + RequiredError struct { + ResultErrorFields + } + + // InvalidTypeError. ErrorDetails: expected, given + InvalidTypeError struct { + ResultErrorFields + } + + // NumberAnyOfError. ErrorDetails: - + NumberAnyOfError struct { + ResultErrorFields + } + + // NumberOneOfError. ErrorDetails: - + NumberOneOfError struct { + ResultErrorFields + } + + // NumberAllOfError. ErrorDetails: - + NumberAllOfError struct { + ResultErrorFields + } + + // NumberNotError. ErrorDetails: - + NumberNotError struct { + ResultErrorFields + } + + // MissingDependencyError. ErrorDetails: dependency + MissingDependencyError struct { + ResultErrorFields + } + + // InternalError. ErrorDetails: error + InternalError struct { + ResultErrorFields + } + + // EnumError. ErrorDetails: allowed + EnumError struct { + ResultErrorFields + } + + // ArrayNoAdditionalItemsError. ErrorDetails: - + ArrayNoAdditionalItemsError struct { + ResultErrorFields + } + + // ArrayMinItemsError. ErrorDetails: min + ArrayMinItemsError struct { + ResultErrorFields + } + + // ArrayMaxItemsError. ErrorDetails: max + ArrayMaxItemsError struct { + ResultErrorFields + } + + // ItemsMustBeUniqueError. ErrorDetails: type + ItemsMustBeUniqueError struct { + ResultErrorFields + } + + // ArrayMinPropertiesError. ErrorDetails: min + ArrayMinPropertiesError struct { + ResultErrorFields + } + + // ArrayMaxPropertiesError. ErrorDetails: max + ArrayMaxPropertiesError struct { + ResultErrorFields + } + + // AdditionalPropertyNotAllowedError. ErrorDetails: property + AdditionalPropertyNotAllowedError struct { + ResultErrorFields + } + + // InvalidPropertyPatternError. ErrorDetails: property, pattern + InvalidPropertyPatternError struct { + ResultErrorFields + } + + // StringLengthGTEError. ErrorDetails: min + StringLengthGTEError struct { + ResultErrorFields + } + + // StringLengthLTEError. ErrorDetails: max + StringLengthLTEError struct { + ResultErrorFields + } + + // DoesNotMatchPatternError. ErrorDetails: pattern + DoesNotMatchPatternError struct { + ResultErrorFields + } + + // DoesNotMatchFormatError. ErrorDetails: format + DoesNotMatchFormatError struct { + ResultErrorFields + } + + // MultipleOfError. ErrorDetails: multiple + MultipleOfError struct { + ResultErrorFields + } + + // NumberGTEError. ErrorDetails: min + NumberGTEError struct { + ResultErrorFields + } + + // NumberGTError. ErrorDetails: min + NumberGTError struct { + ResultErrorFields + } + + // NumberLTEError. ErrorDetails: max + NumberLTEError struct { + ResultErrorFields + } + + // NumberLTError. ErrorDetails: max + NumberLTError struct { + ResultErrorFields + } +) + +// newError takes a ResultError type and sets the type, context, description, details, value, and field +func newError(err ResultError, context *jsonContext, value interface{}, locale locale, details ErrorDetails) { + var t string + var d string + switch err.(type) { + case *RequiredError: + t = "required" + d = locale.Required() + case *InvalidTypeError: + t = "invalid_type" + d = locale.InvalidType() + case *NumberAnyOfError: + t = "number_any_of" + d = locale.NumberAnyOf() + case *NumberOneOfError: + t = "number_one_of" + d = locale.NumberOneOf() + case *NumberAllOfError: + t = "number_all_of" + d = locale.NumberAllOf() + case *NumberNotError: + t = "number_not" + d = locale.NumberNot() + case *MissingDependencyError: + t = "missing_dependency" + d = locale.MissingDependency() + case *InternalError: + t = "internal" + d = locale.Internal() + case *EnumError: + t = "enum" + d = locale.Enum() + case *ArrayNoAdditionalItemsError: + t = "array_no_additional_items" + d = locale.ArrayNoAdditionalItems() + case *ArrayMinItemsError: + t = "array_min_items" + d = locale.ArrayMinItems() + case *ArrayMaxItemsError: + t = "array_max_items" + d = locale.ArrayMaxItems() + case *ItemsMustBeUniqueError: + t = "unique" + d = locale.Unique() + case *ArrayMinPropertiesError: + t = "array_min_properties" + d = locale.ArrayMinProperties() + case *ArrayMaxPropertiesError: + t = "array_max_properties" + d = locale.ArrayMaxProperties() + case *AdditionalPropertyNotAllowedError: + t = "additional_property_not_allowed" + d = locale.AdditionalPropertyNotAllowed() + case *InvalidPropertyPatternError: + t = "invalid_property_pattern" + d = locale.InvalidPropertyPattern() + case *StringLengthGTEError: + t = "string_gte" + d = locale.StringGTE() + case *StringLengthLTEError: + t = "string_lte" + d = locale.StringLTE() + case *DoesNotMatchPatternError: + t = "pattern" + d = locale.DoesNotMatchPattern() + case *DoesNotMatchFormatError: + t = "format" + d = locale.DoesNotMatchFormat() + case *MultipleOfError: + t = "multiple_of" + d = locale.MultipleOf() + case *NumberGTEError: + t = "number_gte" + d = locale.NumberGTE() + case *NumberGTError: + t = "number_gt" + d = locale.NumberGT() + case *NumberLTEError: + t = "number_lte" + d = locale.NumberLTE() + case *NumberLTError: + t = "number_lt" + d = locale.NumberLT() + } + + err.SetType(t) + err.SetContext(context) + err.SetValue(value) + err.SetDetails(details) + details["field"] = err.Field() + err.SetDescription(formatErrorDescription(d, details)) +} + +// formatErrorDescription takes a string in this format: %field% is required +// and converts it to a string with replacements. The fields come from +// the ErrorDetails struct and vary for each type of error. +func formatErrorDescription(s string, details ErrorDetails) string { + for name, val := range details { + s = strings.Replace(s, "%"+strings.ToLower(name)+"%", fmt.Sprintf("%v", val), -1) + } + + return s +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/format_checkers.go b/vendor/github.com/xeipuuv/gojsonschema/format_checkers.go new file mode 100644 index 00000000..b91c360a --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/format_checkers.go @@ -0,0 +1,178 @@ +package gojsonschema + +import ( + "net" + "net/url" + "reflect" + "regexp" + "strings" + "time" +) + +type ( + // FormatChecker is the interface all formatters added to FormatCheckerChain must implement + FormatChecker interface { + IsFormat(input string) bool + } + + // FormatCheckerChain holds the formatters + FormatCheckerChain struct { + formatters map[string]FormatChecker + } + + // EmailFormatter verifies email address formats + EmailFormatChecker struct{} + + // IPV4FormatChecker verifies IP addresses in the ipv4 format + IPV4FormatChecker struct{} + + // IPV6FormatChecker verifies IP addresses in the ipv6 format + IPV6FormatChecker struct{} + + // DateTimeFormatChecker verifies date/time formats per RFC3339 5.6 + // + // Valid formats: + // Partial Time: HH:MM:SS + // Full Date: YYYY-MM-DD + // Full Time: HH:MM:SSZ-07:00 + // Date Time: YYYY-MM-DDTHH:MM:SSZ-0700 + // + // Where + // YYYY = 4DIGIT year + // MM = 2DIGIT month ; 01-12 + // DD = 2DIGIT day-month ; 01-28, 01-29, 01-30, 01-31 based on month/year + // HH = 2DIGIT hour ; 00-23 + // MM = 2DIGIT ; 00-59 + // SS = 2DIGIT ; 00-58, 00-60 based on leap second rules + // T = Literal + // Z = Literal + // + // Note: Nanoseconds are also suported in all formats + // + // http://tools.ietf.org/html/rfc3339#section-5.6 + DateTimeFormatChecker struct{} + + // URIFormatCheckers validates a URI with a valid Scheme per RFC3986 + URIFormatChecker struct{} + + // HostnameFormatChecker validates a hostname is in the correct format + HostnameFormatChecker struct{} + + // UUIDFormatChecker validates a UUID is in the correct format + UUIDFormatChecker struct{} +) + +var ( + // Formatters holds the valid formatters, and is a public variable + // so library users can add custom formatters + FormatCheckers = FormatCheckerChain{ + formatters: map[string]FormatChecker{ + "date-time": DateTimeFormatChecker{}, + "hostname": HostnameFormatChecker{}, + "email": EmailFormatChecker{}, + "ipv4": IPV4FormatChecker{}, + "ipv6": IPV6FormatChecker{}, + "uri": URIFormatChecker{}, + "uuid": UUIDFormatChecker{}, + }, + } + + // Regex credit: https://github.com/asaskevich/govalidator + rxEmail = regexp.MustCompile("^(((([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$") + + // Regex credit: https://www.socketloop.com/tutorials/golang-validate-hostname + rxHostname = regexp.MustCompile(`^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$`) + + rxUUID = regexp.MustCompile("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$") +) + +// Add adds a FormatChecker to the FormatCheckerChain +// The name used will be the value used for the format key in your json schema +func (c *FormatCheckerChain) Add(name string, f FormatChecker) *FormatCheckerChain { + c.formatters[name] = f + + return c +} + +// Remove deletes a FormatChecker from the FormatCheckerChain (if it exists) +func (c *FormatCheckerChain) Remove(name string) *FormatCheckerChain { + delete(c.formatters, name) + + return c +} + +// Has checks to see if the FormatCheckerChain holds a FormatChecker with the given name +func (c *FormatCheckerChain) Has(name string) bool { + _, ok := c.formatters[name] + + return ok +} + +// IsFormat will check an input against a FormatChecker with the given name +// to see if it is the correct format +func (c *FormatCheckerChain) IsFormat(name string, input interface{}) bool { + f, ok := c.formatters[name] + + if !ok { + return false + } + + if !isKind(input, reflect.String) { + return false + } + + inputString := input.(string) + + return f.IsFormat(inputString) +} + +func (f EmailFormatChecker) IsFormat(input string) bool { + return rxEmail.MatchString(input) +} + +// Credit: https://github.com/asaskevich/govalidator +func (f IPV4FormatChecker) IsFormat(input string) bool { + ip := net.ParseIP(input) + return ip != nil && strings.Contains(input, ".") +} + +// Credit: https://github.com/asaskevich/govalidator +func (f IPV6FormatChecker) IsFormat(input string) bool { + ip := net.ParseIP(input) + return ip != nil && strings.Contains(input, ":") +} + +func (f DateTimeFormatChecker) IsFormat(input string) bool { + formats := []string{ + "15:04:05", + "15:04:05Z07:00", + "2006-01-02", + time.RFC3339, + time.RFC3339Nano, + } + + for _, format := range formats { + if _, err := time.Parse(format, input); err == nil { + return true + } + } + + return false +} + +func (f URIFormatChecker) IsFormat(input string) bool { + u, err := url.Parse(input) + if err != nil || u.Scheme == "" { + return false + } + + return true +} + +func (f HostnameFormatChecker) IsFormat(input string) bool { + return rxHostname.MatchString(input) && len(input) < 256 +} + +func (f UUIDFormatChecker) IsFormat(input string) bool { + return rxUUID.MatchString(input) +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/format_checkers_test.go b/vendor/github.com/xeipuuv/gojsonschema/format_checkers_test.go new file mode 100644 index 00000000..04db0e7c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/format_checkers_test.go @@ -0,0 +1,16 @@ +package gojsonschema + +import ( + "github.com/stretchr/testify/assert" + "testing" +) + +func TestUUIDFormatCheckerIsFormat(t *testing.T) { + checker := UUIDFormatChecker{} + + assert.True(t, checker.IsFormat("01234567-89ab-cdef-0123-456789abcdef")) + assert.True(t, checker.IsFormat("f1234567-89ab-cdef-0123-456789abcdef")) + + assert.False(t, checker.IsFormat("not-a-uuid")) + assert.False(t, checker.IsFormat("g1234567-89ab-cdef-0123-456789abcdef")) +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/glide.yaml b/vendor/github.com/xeipuuv/gojsonschema/glide.yaml new file mode 100644 index 00000000..7aef8c09 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/glide.yaml @@ -0,0 +1,12 @@ +package: github.com/xeipuuv/gojsonschema +license: Apache 2.0 +import: +- package: github.com/xeipuuv/gojsonschema + +- package: github.com/xeipuuv/gojsonpointer + +- package: github.com/xeipuuv/gojsonreference + +- package: github.com/stretchr/testify/assert + version: ^1.1.3 + diff --git a/vendor/github.com/xeipuuv/gojsonschema/internalLog.go b/vendor/github.com/xeipuuv/gojsonschema/internalLog.go new file mode 100644 index 00000000..4ef7a8d0 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/internalLog.go @@ -0,0 +1,37 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// 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. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Very simple log wrapper. +// Used for debugging/testing purposes. +// +// created 01-01-2015 + +package gojsonschema + +import ( + "log" +) + +const internalLogEnabled = false + +func internalLog(format string, v ...interface{}) { + log.Printf(format, v...) +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/jsonContext.go b/vendor/github.com/xeipuuv/gojsonschema/jsonContext.go new file mode 100644 index 00000000..fcc8d9d6 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/jsonContext.go @@ -0,0 +1,72 @@ +// Copyright 2013 MongoDB, 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. + +// author tolsen +// author-github https://github.com/tolsen +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Implements a persistent (immutable w/ shared structure) singly-linked list of strings for the purpose of storing a json context +// +// created 04-09-2013 + +package gojsonschema + +import "bytes" + +// jsonContext implements a persistent linked-list of strings +type jsonContext struct { + head string + tail *jsonContext +} + +func newJsonContext(head string, tail *jsonContext) *jsonContext { + return &jsonContext{head, tail} +} + +// String displays the context in reverse. +// This plays well with the data structure's persistent nature with +// Cons and a json document's tree structure. +func (c *jsonContext) String(del ...string) string { + byteArr := make([]byte, 0, c.stringLen()) + buf := bytes.NewBuffer(byteArr) + c.writeStringToBuffer(buf, del) + + return buf.String() +} + +func (c *jsonContext) stringLen() int { + length := 0 + if c.tail != nil { + length = c.tail.stringLen() + 1 // add 1 for "." + } + + length += len(c.head) + return length +} + +func (c *jsonContext) writeStringToBuffer(buf *bytes.Buffer, del []string) { + if c.tail != nil { + c.tail.writeStringToBuffer(buf, del) + + if len(del) > 0 { + buf.WriteString(del[0]) + } else { + buf.WriteString(".") + } + } + + buf.WriteString(c.head) +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/jsonLoader.go b/vendor/github.com/xeipuuv/gojsonschema/jsonLoader.go new file mode 100644 index 00000000..0b405747 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/jsonLoader.go @@ -0,0 +1,314 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// 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. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Different strategies to load JSON files. +// Includes References (file and HTTP), JSON strings and Go types. +// +// created 01-02-2015 + +package gojsonschema + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "io/ioutil" + "net/http" + "os" + "path/filepath" + "runtime" + "strings" + + "github.com/xeipuuv/gojsonreference" +) + +var osFS = osFileSystem(os.Open) + +// JSON loader interface + +type JSONLoader interface { + jsonSource() interface{} + loadJSON() (interface{}, error) + loadSchema() (*Schema, error) +} + +// osFileSystem is a functional wrapper for os.Open that implements http.FileSystem. +type osFileSystem func(string) (*os.File, error) + +func (o osFileSystem) Open(name string) (http.File, error) { + return o(name) +} + +// JSON Reference loader +// references are used to load JSONs from files and HTTP + +type jsonReferenceLoader struct { + fs http.FileSystem + source string +} + +func (l *jsonReferenceLoader) jsonSource() interface{} { + return l.source +} + +// NewReferenceLoader returns a JSON reference loader using the given source and the local OS file system. +func NewReferenceLoader(source string) *jsonReferenceLoader { + return &jsonReferenceLoader{ + fs: osFS, + source: source, + } +} + +// NewReferenceLoaderFileSystem returns a JSON reference loader using the given source and file system. +func NewReferenceLoaderFileSystem(source string, fs http.FileSystem) *jsonReferenceLoader { + return &jsonReferenceLoader{ + fs: fs, + source: source, + } +} + +func (l *jsonReferenceLoader) loadJSON() (interface{}, error) { + + var err error + + reference, err := gojsonreference.NewJsonReference(l.jsonSource().(string)) + if err != nil { + return nil, err + } + + refToUrl := reference + refToUrl.GetUrl().Fragment = "" + + var document interface{} + + if reference.HasFileScheme { + + filename := strings.Replace(refToUrl.String(), "file://", "", -1) + if runtime.GOOS == "windows" { + // on Windows, a file URL may have an extra leading slash, use slashes + // instead of backslashes, and have spaces escaped + if strings.HasPrefix(filename, "/") { + filename = filename[1:] + } + filename = filepath.FromSlash(filename) + filename = strings.Replace(filename, "%20", " ", -1) + } + + document, err = l.loadFromFile(filename) + if err != nil { + return nil, err + } + + } else { + + document, err = l.loadFromHTTP(refToUrl.String()) + if err != nil { + return nil, err + } + + } + + return document, nil + +} + +func (l *jsonReferenceLoader) loadSchema() (*Schema, error) { + + var err error + + d := Schema{} + d.pool = newSchemaPool(l.fs) + d.referencePool = newSchemaReferencePool() + + d.documentReference, err = gojsonreference.NewJsonReference(l.jsonSource().(string)) + if err != nil { + return nil, err + } + + spd, err := d.pool.GetDocument(d.documentReference) + if err != nil { + return nil, err + } + + err = d.parse(spd.Document) + if err != nil { + return nil, err + } + + return &d, nil + +} + +func (l *jsonReferenceLoader) loadFromHTTP(address string) (interface{}, error) { + + resp, err := http.Get(address) + if err != nil { + return nil, err + } + + // must return HTTP Status 200 OK + if resp.StatusCode != http.StatusOK { + return nil, errors.New(formatErrorDescription(Locale.httpBadStatus(), ErrorDetails{"status": resp.Status})) + } + + bodyBuff, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + return decodeJsonUsingNumber(bytes.NewReader(bodyBuff)) + +} + +func (l *jsonReferenceLoader) loadFromFile(path string) (interface{}, error) { + f, err := l.fs.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + + bodyBuff, err := ioutil.ReadAll(f) + if err != nil { + return nil, err + } + + return decodeJsonUsingNumber(bytes.NewReader(bodyBuff)) + +} + +// JSON string loader + +type jsonStringLoader struct { + source string +} + +func (l *jsonStringLoader) jsonSource() interface{} { + return l.source +} + +func NewStringLoader(source string) *jsonStringLoader { + return &jsonStringLoader{source: source} +} + +func (l *jsonStringLoader) loadJSON() (interface{}, error) { + + return decodeJsonUsingNumber(strings.NewReader(l.jsonSource().(string))) + +} + +func (l *jsonStringLoader) loadSchema() (*Schema, error) { + + var err error + + document, err := l.loadJSON() + if err != nil { + return nil, err + } + + d := Schema{} + d.pool = newSchemaPool(osFS) + d.referencePool = newSchemaReferencePool() + d.documentReference, err = gojsonreference.NewJsonReference("#") + d.pool.SetStandaloneDocument(document) + if err != nil { + return nil, err + } + + err = d.parse(document) + if err != nil { + return nil, err + } + + return &d, nil + +} + +// JSON Go (types) loader +// used to load JSONs from the code as maps, interface{}, structs ... + +type jsonGoLoader struct { + source interface{} +} + +func (l *jsonGoLoader) jsonSource() interface{} { + return l.source +} + +func NewGoLoader(source interface{}) *jsonGoLoader { + return &jsonGoLoader{source: source} +} + +func (l *jsonGoLoader) loadJSON() (interface{}, error) { + + // convert it to a compliant JSON first to avoid types "mismatches" + + jsonBytes, err := json.Marshal(l.jsonSource()) + if err != nil { + return nil, err + } + + return decodeJsonUsingNumber(bytes.NewReader(jsonBytes)) + +} + +func (l *jsonGoLoader) loadSchema() (*Schema, error) { + + var err error + + document, err := l.loadJSON() + if err != nil { + return nil, err + } + + d := Schema{} + d.pool = newSchemaPool(osFS) + d.referencePool = newSchemaReferencePool() + d.documentReference, err = gojsonreference.NewJsonReference("#") + d.pool.SetStandaloneDocument(document) + if err != nil { + return nil, err + } + + err = d.parse(document) + if err != nil { + return nil, err + } + + return &d, nil + +} + +func decodeJsonUsingNumber(r io.Reader) (interface{}, error) { + + var document interface{} + + decoder := json.NewDecoder(r) + decoder.UseNumber() + + err := decoder.Decode(&document) + if err != nil { + return nil, err + } + + return document, nil + +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/LICENSE b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/LICENSE new file mode 100644 index 00000000..c28adbad --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2012 Julian Berman + +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. diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_00.json new file mode 100644 index 00000000..5cb29f91 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_00.json @@ -0,0 +1 @@ +[null,2,3,4] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_01.json new file mode 100644 index 00000000..4eb0d32f --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_01.json @@ -0,0 +1 @@ +[null,2,3,"foo"] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_10.json new file mode 100644 index 00000000..e77ca8d9 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_10.json @@ -0,0 +1 @@ +[1,2,3,4,5] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_20.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_20.json new file mode 100644 index 00000000..3a26a2e5 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_20.json @@ -0,0 +1 @@ +[1,2,3] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_21.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_21.json new file mode 100644 index 00000000..fde6c1d7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_21.json @@ -0,0 +1 @@ +[1,2,3,4] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_30.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_30.json new file mode 100644 index 00000000..e77ca8d9 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_30.json @@ -0,0 +1 @@ +[1,2,3,4,5] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_31.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_31.json new file mode 100644 index 00000000..9f5dd4e3 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_31.json @@ -0,0 +1 @@ +{"foo":"bar"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_40.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_40.json new file mode 100644 index 00000000..327fe850 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/data_40.json @@ -0,0 +1 @@ +[1,"foo",false] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/schema_0.json new file mode 100644 index 00000000..75a4b7e0 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/schema_0.json @@ -0,0 +1 @@ +{"additionalItems":{"type":"integer"},"items":[{}]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/schema_1.json new file mode 100644 index 00000000..d5046a9c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/schema_1.json @@ -0,0 +1 @@ +{"additionalItems":false,"items":{}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/schema_2.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/schema_2.json new file mode 100644 index 00000000..6ab20de2 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/schema_2.json @@ -0,0 +1 @@ +{"additionalItems":false,"items":[{},{},{}]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/schema_3.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/schema_3.json new file mode 100644 index 00000000..f04aaf84 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/schema_3.json @@ -0,0 +1 @@ +{"additionalItems":false} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/schema_4.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/schema_4.json new file mode 100644 index 00000000..fff26f85 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalItems/schema_4.json @@ -0,0 +1 @@ +{"items":[{"type":"integer"}]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_00.json new file mode 100644 index 00000000..2518e687 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_00.json @@ -0,0 +1 @@ +{"foo":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_01.json new file mode 100644 index 00000000..513d61fb --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_01.json @@ -0,0 +1 @@ +{"bar":2,"foo":1,"quux":"boom"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_02.json new file mode 100644 index 00000000..3a26a2e5 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_02.json @@ -0,0 +1 @@ +[1,2,3] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_03.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_03.json new file mode 100644 index 00000000..65a158df --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_03.json @@ -0,0 +1 @@ +{"foo":1, "vroom": 2} diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_10.json new file mode 100644 index 00000000..2518e687 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_10.json @@ -0,0 +1 @@ +{"foo":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_11.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_11.json new file mode 100644 index 00000000..2129e620 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_11.json @@ -0,0 +1 @@ +{"bar":2,"foo":1,"quux":true} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_12.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_12.json new file mode 100644 index 00000000..ce7708b1 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_12.json @@ -0,0 +1 @@ +{"bar":2,"foo":1,"quux":12} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_20.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_20.json new file mode 100644 index 00000000..2129e620 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/data_20.json @@ -0,0 +1 @@ +{"bar":2,"foo":1,"quux":true} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/schema_0.json new file mode 100644 index 00000000..99d0ef4f --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/schema_0.json @@ -0,0 +1 @@ +{"additionalProperties":false,"properties":{"bar":{},"foo":{}},"patternProperties": { "^v": {} }} diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/schema_1.json new file mode 100644 index 00000000..b55c0924 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/schema_1.json @@ -0,0 +1 @@ +{"additionalProperties":{"type":"boolean"},"properties":{"bar":{},"foo":{}}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/schema_2.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/schema_2.json new file mode 100644 index 00000000..4d0bc3a9 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/additionalProperties/schema_2.json @@ -0,0 +1 @@ +{"properties":{"bar":{},"foo":{}}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_00.json new file mode 100644 index 00000000..7973c0ac --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_00.json @@ -0,0 +1 @@ +{"bar":2,"foo":"baz"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_01.json new file mode 100644 index 00000000..62aa0a13 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_01.json @@ -0,0 +1 @@ +{"foo":"baz"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_02.json new file mode 100644 index 00000000..70eef88e --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_02.json @@ -0,0 +1 @@ +{"bar":2} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_03.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_03.json new file mode 100644 index 00000000..54c2b0b0 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_03.json @@ -0,0 +1 @@ +{"bar":"quux","foo":"baz"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_10.json new file mode 100644 index 00000000..fa13a378 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_10.json @@ -0,0 +1 @@ +{"bar":2,"baz":null,"foo":"quux"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_11.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_11.json new file mode 100644 index 00000000..366679e8 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_11.json @@ -0,0 +1 @@ +{"baz":null,"foo":"quux"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_12.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_12.json new file mode 100644 index 00000000..e8f534ad --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_12.json @@ -0,0 +1 @@ +{"bar":2,"baz":null} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_13.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_13.json new file mode 100644 index 00000000..6fbe1984 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_13.json @@ -0,0 +1 @@ +{"bar":2,"foo":"quux"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_14.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_14.json new file mode 100644 index 00000000..70eef88e --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_14.json @@ -0,0 +1 @@ +{"bar":2} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_20.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_20.json new file mode 100644 index 00000000..410b14d2 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_20.json @@ -0,0 +1 @@ +25 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_21.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_21.json new file mode 100644 index 00000000..597975b4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/data_21.json @@ -0,0 +1 @@ +35 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/schema_0.json new file mode 100644 index 00000000..13b607a4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/schema_0.json @@ -0,0 +1 @@ +{"allOf":[{"properties":{"bar":{"type":"integer"}},"required":["bar"]},{"properties":{"foo":{"type":"string"}},"required":["foo"]}]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/schema_1.json new file mode 100644 index 00000000..f618c0b2 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/schema_1.json @@ -0,0 +1 @@ +{"allOf":[{"properties":{"foo":{"type":"string"}},"required":["foo"]},{"properties":{"baz":{"type":"null"}},"required":["baz"]}],"properties":{"bar":{"type":"integer"}},"required":["bar"]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/schema_2.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/schema_2.json new file mode 100644 index 00000000..748ee7ef --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/allOf/schema_2.json @@ -0,0 +1 @@ +{"allOf":[{"maximum":30},{"minimum":20}]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_00.json new file mode 100644 index 00000000..56a6051c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_00.json @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_01.json new file mode 100644 index 00000000..68151b2e --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_01.json @@ -0,0 +1 @@ +2.5 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_02.json new file mode 100644 index 00000000..e440e5c8 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_02.json @@ -0,0 +1 @@ +3 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_03.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_03.json new file mode 100644 index 00000000..400122e6 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_03.json @@ -0,0 +1 @@ +1.5 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_10.json new file mode 100644 index 00000000..e440e5c8 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_10.json @@ -0,0 +1 @@ +3 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_11.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_11.json new file mode 100644 index 00000000..b2bb988b --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_11.json @@ -0,0 +1 @@ +"foobar" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_12.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_12.json new file mode 100644 index 00000000..7e9668e7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/data_12.json @@ -0,0 +1 @@ +"foo" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/schema_0.json new file mode 100644 index 00000000..5540cb8f --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/schema_0.json @@ -0,0 +1 @@ +{"anyOf":[{"type":"integer"},{"minimum":2}]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/schema_1.json new file mode 100644 index 00000000..cbe387a3 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/anyOf/schema_1.json @@ -0,0 +1 @@ +{"anyOf":[{"maxLength":2},{"minLength":4}],"type":"string"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/definitions/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/definitions/data_00.json new file mode 100644 index 00000000..fc7a98bf --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/definitions/data_00.json @@ -0,0 +1 @@ +{"definitions":{"foo":{"type":"integer"}}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/definitions/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/definitions/data_10.json new file mode 100644 index 00000000..5270defb --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/definitions/data_10.json @@ -0,0 +1 @@ +{"definitions":{"foo":{"type":1}}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/definitions/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/definitions/schema_0.json new file mode 100644 index 00000000..412c2163 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/definitions/schema_0.json @@ -0,0 +1 @@ +{"$ref":"http://json-schema.org/draft-04/schema#"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/definitions/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/definitions/schema_1.json new file mode 100644 index 00000000..412c2163 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/definitions/schema_1.json @@ -0,0 +1 @@ +{"$ref":"http://json-schema.org/draft-04/schema#"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_00.json new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_00.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_01.json new file mode 100644 index 00000000..2518e687 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_01.json @@ -0,0 +1 @@ +{"foo":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_02.json new file mode 100644 index 00000000..b0fcefdb --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_02.json @@ -0,0 +1 @@ +{"bar":2,"foo":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_03.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_03.json new file mode 100644 index 00000000..70eef88e --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_03.json @@ -0,0 +1 @@ +{"bar":2} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_04.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_04.json new file mode 100644 index 00000000..7e9668e7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_04.json @@ -0,0 +1 @@ +"foo" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_10.json new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_10.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_11.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_11.json new file mode 100644 index 00000000..b0fcefdb --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_11.json @@ -0,0 +1 @@ +{"bar":2,"foo":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_12.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_12.json new file mode 100644 index 00000000..2c48cfbe --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_12.json @@ -0,0 +1 @@ +{"bar":2,"foo":1,"quux":3} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_13.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_13.json new file mode 100644 index 00000000..6fe283b3 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_13.json @@ -0,0 +1 @@ +{"foo":1,"quux":2} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_14.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_14.json new file mode 100644 index 00000000..7bed583b --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_14.json @@ -0,0 +1 @@ +{"bar":1,"quux":2} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_15.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_15.json new file mode 100644 index 00000000..10d82bf9 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_15.json @@ -0,0 +1 @@ +{"quux":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_20.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_20.json new file mode 100644 index 00000000..b0fcefdb --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_20.json @@ -0,0 +1 @@ +{"bar":2,"foo":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_21.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_21.json new file mode 100644 index 00000000..707f7cec --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_21.json @@ -0,0 +1 @@ +{"foo":"quux"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_22.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_22.json new file mode 100644 index 00000000..6fbe1984 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_22.json @@ -0,0 +1 @@ +{"bar":2,"foo":"quux"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_23.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_23.json new file mode 100644 index 00000000..a1637389 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_23.json @@ -0,0 +1 @@ +{"bar":"quux","foo":2} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_24.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_24.json new file mode 100644 index 00000000..2fee1e31 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/data_24.json @@ -0,0 +1 @@ +{"bar":"quux","foo":"quux"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/schema_0.json new file mode 100644 index 00000000..445985c6 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/schema_0.json @@ -0,0 +1 @@ +{"dependencies":{"bar":["foo"]}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/schema_1.json new file mode 100644 index 00000000..1bb5a676 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/schema_1.json @@ -0,0 +1 @@ +{"dependencies":{"quux":["foo","bar"]}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/schema_2.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/schema_2.json new file mode 100644 index 00000000..27f97a43 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/dependencies/schema_2.json @@ -0,0 +1 @@ +{"dependencies":{"bar":{"properties":{"bar":{"type":"integer"},"foo":{"type":"integer"}}}}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/data_00.json new file mode 100644 index 00000000..56a6051c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/data_00.json @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/data_01.json new file mode 100644 index 00000000..bf0d87ab --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/data_01.json @@ -0,0 +1 @@ +4 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/data_10.json new file mode 100644 index 00000000..0637a088 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/data_10.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/data_11.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/data_11.json new file mode 100644 index 00000000..ec747fa4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/data_11.json @@ -0,0 +1 @@ +null \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/data_12.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/data_12.json new file mode 100644 index 00000000..1bfa80c1 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/data_12.json @@ -0,0 +1 @@ +{"foo":false} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/schema_0.json new file mode 100644 index 00000000..240e702e --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/schema_0.json @@ -0,0 +1 @@ +{"enum":[1,2,3]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/schema_1.json new file mode 100644 index 00000000..d6b8c5f6 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/enum/schema_1.json @@ -0,0 +1 @@ +{"enum":[6,"foo",[],true,{"foo":12}]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_00.json new file mode 100644 index 00000000..60bc259b --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_00.json @@ -0,0 +1 @@ +"test" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_01.json new file mode 100644 index 00000000..6d9ec401 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_01.json @@ -0,0 +1 @@ +"test@" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_02.json new file mode 100644 index 00000000..6b8674d0 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_02.json @@ -0,0 +1 @@ +"test@test.com" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_03.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_03.json new file mode 100644 index 00000000..970043c7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_03.json @@ -0,0 +1 @@ +"AB-10105" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_04.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_04.json new file mode 100644 index 00000000..140843fb --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_04.json @@ -0,0 +1 @@ +"ABC10105" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_05.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_05.json new file mode 100644 index 00000000..e87a8acd --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_05.json @@ -0,0 +1 @@ +"05:15:37" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_06.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_06.json new file mode 100644 index 00000000..17f91eb8 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_06.json @@ -0,0 +1 @@ +"2015-05-13" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_07.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_07.json new file mode 100644 index 00000000..f0218e9a --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_07.json @@ -0,0 +1 @@ +"2015-6-31" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_08.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_08.json new file mode 100644 index 00000000..bf9e258b --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_08.json @@ -0,0 +1 @@ +"2015-01-30 19:08:06" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_09.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_09.json new file mode 100644 index 00000000..1a57beb5 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_09.json @@ -0,0 +1 @@ +"18:31:24-05:00" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_10.json new file mode 100644 index 00000000..00ed4ee1 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_10.json @@ -0,0 +1 @@ +"2002-10-02T10:00:00-05:00" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_11.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_11.json new file mode 100644 index 00000000..a8f92d50 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_11.json @@ -0,0 +1 @@ +"2002-10-02T15:00:00Z" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_12.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_12.json new file mode 100644 index 00000000..0975607f --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_12.json @@ -0,0 +1 @@ +"2002-10-02T15:00:00.05Z" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_13.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_13.json new file mode 100644 index 00000000..9f9dacee --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_13.json @@ -0,0 +1 @@ +"example.com" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_14.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_14.json new file mode 100644 index 00000000..15a9a873 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_14.json @@ -0,0 +1 @@ +"sub.example.com" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_15.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_15.json new file mode 100644 index 00000000..5c8e9b7b --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_15.json @@ -0,0 +1 @@ +"hello.co.uk" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_16.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_16.json new file mode 100644 index 00000000..f5a11ec2 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_16.json @@ -0,0 +1 @@ +"http://example.com" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_17.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_17.json new file mode 100644 index 00000000..062bf8cb --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_17.json @@ -0,0 +1 @@ +"example_com" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_18.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_18.json new file mode 100644 index 00000000..fd444101 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_18.json @@ -0,0 +1 @@ +"4.2.2.4" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_19.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_19.json new file mode 100644 index 00000000..1e490c63 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_19.json @@ -0,0 +1 @@ +"4.1.1111.45" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_20.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_20.json new file mode 100644 index 00000000..28918103 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_20.json @@ -0,0 +1 @@ +"FE80:0000:0000:0000:0202:B3FF:FE1E:8329" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_21.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_21.json new file mode 100644 index 00000000..ad20ef3c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_21.json @@ -0,0 +1 @@ +"FE80::0202:B3FF:FE1E:8329" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_22.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_22.json new file mode 100644 index 00000000..97dae8fe --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_22.json @@ -0,0 +1 @@ +"1200::AB00:1234::2552:7777:1313" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_23.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_23.json new file mode 100644 index 00000000..ef38c10e --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_23.json @@ -0,0 +1 @@ +"1200:0000:AB00:1234:O000:2552:7777:1313" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_24.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_24.json new file mode 100644 index 00000000..4187b90a --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_24.json @@ -0,0 +1 @@ +"ftp://ftp.is.co.za/rfc/rfc1808.txt" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_25.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_25.json new file mode 100644 index 00000000..78168386 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_25.json @@ -0,0 +1 @@ +"mailto:john.doe@example.com" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_26.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_26.json new file mode 100644 index 00000000..df1cfae9 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_26.json @@ -0,0 +1 @@ +"tel:+1-816-555-1212" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_27.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_27.json new file mode 100644 index 00000000..28995ddd --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_27.json @@ -0,0 +1 @@ +"http://www.ietf.org/rfc/rfc2396.txt" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_28.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_28.json new file mode 100644 index 00000000..6b620edf --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/data_28.json @@ -0,0 +1 @@ +"example.com/path/to/file" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_0.json new file mode 100644 index 00000000..b54a202e --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_0.json @@ -0,0 +1 @@ +{"type": "string", "format": "email"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_1.json new file mode 100644 index 00000000..7df67118 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_1.json @@ -0,0 +1 @@ +{"type": "string", "format": "invoice"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_2.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_2.json new file mode 100644 index 00000000..0dc4b8ff --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_2.json @@ -0,0 +1 @@ +{"type": "string", "format": "date-time"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_3.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_3.json new file mode 100644 index 00000000..d1cf1a05 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_3.json @@ -0,0 +1 @@ +{"type": "string", "format": "hostname"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_4.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_4.json new file mode 100644 index 00000000..8468509f --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_4.json @@ -0,0 +1 @@ +{"type": "string", "format": "ipv4"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_5.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_5.json new file mode 100644 index 00000000..ddee8475 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_5.json @@ -0,0 +1 @@ +{"type": "string", "format": "ipv6"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_6.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_6.json new file mode 100644 index 00000000..493546d0 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/format/schema_6.json @@ -0,0 +1 @@ +{"type": "string", "format": "uri"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/data_00.json new file mode 100644 index 00000000..3a26a2e5 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/data_00.json @@ -0,0 +1 @@ +[1,2,3] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/data_01.json new file mode 100644 index 00000000..084da97d --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/data_01.json @@ -0,0 +1 @@ +[1,"x"] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/data_02.json new file mode 100644 index 00000000..9f5dd4e3 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/data_02.json @@ -0,0 +1 @@ +{"foo":"bar"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/data_10.json new file mode 100644 index 00000000..f4e52901 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/data_10.json @@ -0,0 +1 @@ +[1,"foo"] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/data_11.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/data_11.json new file mode 100644 index 00000000..d68c5004 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/data_11.json @@ -0,0 +1 @@ +["foo",1] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/schema_0.json new file mode 100644 index 00000000..e628c9f8 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/schema_0.json @@ -0,0 +1 @@ +{"items":{"type":"integer"}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/schema_1.json new file mode 100644 index 00000000..8b92516d --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/items/schema_1.json @@ -0,0 +1 @@ +{"items":[{"type":"integer"},{"type":"string"}]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxItems/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxItems/data_00.json new file mode 100644 index 00000000..bace2a0b --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxItems/data_00.json @@ -0,0 +1 @@ +[1] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxItems/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxItems/data_01.json new file mode 100644 index 00000000..3169929f --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxItems/data_01.json @@ -0,0 +1 @@ +[1,2] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxItems/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxItems/data_02.json new file mode 100644 index 00000000..3a26a2e5 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxItems/data_02.json @@ -0,0 +1 @@ +[1,2,3] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxItems/data_03.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxItems/data_03.json new file mode 100644 index 00000000..b2bb988b --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxItems/data_03.json @@ -0,0 +1 @@ +"foobar" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxItems/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxItems/schema_0.json new file mode 100644 index 00000000..81cfbcca --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxItems/schema_0.json @@ -0,0 +1 @@ +{"maxItems":2} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxLength/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxLength/data_00.json new file mode 100644 index 00000000..91d1e395 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxLength/data_00.json @@ -0,0 +1 @@ +"f" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxLength/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxLength/data_01.json new file mode 100644 index 00000000..67af23e2 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxLength/data_01.json @@ -0,0 +1 @@ +"fo" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxLength/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxLength/data_02.json new file mode 100644 index 00000000..7e9668e7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxLength/data_02.json @@ -0,0 +1 @@ +"foo" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxLength/data_03.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxLength/data_03.json new file mode 100644 index 00000000..9a037142 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxLength/data_03.json @@ -0,0 +1 @@ +10 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxLength/data_04.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxLength/data_04.json new file mode 100644 index 00000000..7d62b4d2 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxLength/data_04.json @@ -0,0 +1 @@ +"世界" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxLength/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxLength/schema_0.json new file mode 100644 index 00000000..30a07477 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxLength/schema_0.json @@ -0,0 +1 @@ +{"maxLength":2} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxProperties/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxProperties/data_00.json new file mode 100644 index 00000000..2518e687 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxProperties/data_00.json @@ -0,0 +1 @@ +{"foo":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxProperties/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxProperties/data_01.json new file mode 100644 index 00000000..b0fcefdb --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxProperties/data_01.json @@ -0,0 +1 @@ +{"bar":2,"foo":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxProperties/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxProperties/data_02.json new file mode 100644 index 00000000..bce2e6b6 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxProperties/data_02.json @@ -0,0 +1 @@ +{"bar":2,"baz":3,"foo":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxProperties/data_03.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxProperties/data_03.json new file mode 100644 index 00000000..b2bb988b --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxProperties/data_03.json @@ -0,0 +1 @@ +"foobar" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxProperties/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxProperties/schema_0.json new file mode 100644 index 00000000..a9d977b6 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maxProperties/schema_0.json @@ -0,0 +1 @@ +{"maxProperties":2} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/data_00.json new file mode 100644 index 00000000..c20c8ac5 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/data_00.json @@ -0,0 +1 @@ +2.6 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/data_01.json new file mode 100644 index 00000000..56e972a2 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/data_01.json @@ -0,0 +1 @@ +3.5 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/data_02.json new file mode 100644 index 00000000..3403a0c7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/data_02.json @@ -0,0 +1 @@ +"x" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/data_10.json new file mode 100644 index 00000000..61618788 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/data_10.json @@ -0,0 +1 @@ +2.2 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/data_11.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/data_11.json new file mode 100644 index 00000000..e440e5c8 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/data_11.json @@ -0,0 +1 @@ +3 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/schema_0.json new file mode 100644 index 00000000..e88aefdf --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/schema_0.json @@ -0,0 +1 @@ +{"maximum":3} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/schema_1.json new file mode 100644 index 00000000..b96954dc --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/maximum/schema_1.json @@ -0,0 +1 @@ +{"exclusiveMaximum":true,"maximum":3} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minItems/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minItems/data_00.json new file mode 100644 index 00000000..3169929f --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minItems/data_00.json @@ -0,0 +1 @@ +[1,2] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minItems/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minItems/data_01.json new file mode 100644 index 00000000..bace2a0b --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minItems/data_01.json @@ -0,0 +1 @@ +[1] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minItems/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minItems/data_02.json new file mode 100644 index 00000000..0637a088 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minItems/data_02.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minItems/data_03.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minItems/data_03.json new file mode 100644 index 00000000..3cc762b5 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minItems/data_03.json @@ -0,0 +1 @@ +"" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minItems/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minItems/schema_0.json new file mode 100644 index 00000000..dcfe1c90 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minItems/schema_0.json @@ -0,0 +1 @@ +{"minItems":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minLength/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minLength/data_00.json new file mode 100644 index 00000000..7e9668e7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minLength/data_00.json @@ -0,0 +1 @@ +"foo" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minLength/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minLength/data_01.json new file mode 100644 index 00000000..67af23e2 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minLength/data_01.json @@ -0,0 +1 @@ +"fo" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minLength/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minLength/data_02.json new file mode 100644 index 00000000..91d1e395 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minLength/data_02.json @@ -0,0 +1 @@ +"f" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minLength/data_03.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minLength/data_03.json new file mode 100644 index 00000000..56a6051c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minLength/data_03.json @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minLength/data_04.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minLength/data_04.json new file mode 100644 index 00000000..62db65a1 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minLength/data_04.json @@ -0,0 +1 @@ +"世" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minLength/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minLength/schema_0.json new file mode 100644 index 00000000..efc23046 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minLength/schema_0.json @@ -0,0 +1 @@ +{"minLength":2} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minProperties/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minProperties/data_00.json new file mode 100644 index 00000000..b0fcefdb --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minProperties/data_00.json @@ -0,0 +1 @@ +{"bar":2,"foo":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minProperties/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minProperties/data_01.json new file mode 100644 index 00000000..2518e687 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minProperties/data_01.json @@ -0,0 +1 @@ +{"foo":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minProperties/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minProperties/data_02.json new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minProperties/data_02.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minProperties/data_03.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minProperties/data_03.json new file mode 100644 index 00000000..3cc762b5 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minProperties/data_03.json @@ -0,0 +1 @@ +"" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minProperties/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minProperties/schema_0.json new file mode 100644 index 00000000..87b25c2b --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minProperties/schema_0.json @@ -0,0 +1 @@ +{"minProperties":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/data_00.json new file mode 100644 index 00000000..c20c8ac5 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/data_00.json @@ -0,0 +1 @@ +2.6 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/data_01.json new file mode 100644 index 00000000..490f510f --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/data_01.json @@ -0,0 +1 @@ +0.6 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/data_02.json new file mode 100644 index 00000000..3403a0c7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/data_02.json @@ -0,0 +1 @@ +"x" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/data_10.json new file mode 100644 index 00000000..ea710abb --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/data_10.json @@ -0,0 +1 @@ +1.2 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/data_11.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/data_11.json new file mode 100644 index 00000000..b123147e --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/data_11.json @@ -0,0 +1 @@ +1.1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/schema_0.json new file mode 100644 index 00000000..0acddfc1 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/schema_0.json @@ -0,0 +1 @@ +{"minimum":1.1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/schema_1.json new file mode 100644 index 00000000..e0945a43 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/minimum/schema_1.json @@ -0,0 +1 @@ +{"exclusiveMinimum":true,"minimum":1.1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_00.json new file mode 100644 index 00000000..9a037142 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_00.json @@ -0,0 +1 @@ +10 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_01.json new file mode 100644 index 00000000..c7930257 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_01.json @@ -0,0 +1 @@ +7 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_02.json new file mode 100644 index 00000000..7e9668e7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_02.json @@ -0,0 +1 @@ +"foo" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_10.json new file mode 100644 index 00000000..c2270834 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_10.json @@ -0,0 +1 @@ +0 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_11.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_11.json new file mode 100644 index 00000000..958d30d8 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_11.json @@ -0,0 +1 @@ +4.5 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_12.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_12.json new file mode 100644 index 00000000..597975b4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_12.json @@ -0,0 +1 @@ +35 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_20.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_20.json new file mode 100644 index 00000000..136664fd --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_20.json @@ -0,0 +1 @@ +0.0075 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_21.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_21.json new file mode 100644 index 00000000..77dfb807 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/data_21.json @@ -0,0 +1 @@ +0.00751 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/schema_0.json new file mode 100644 index 00000000..b51609f2 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/schema_0.json @@ -0,0 +1 @@ +{"multipleOf":2} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/schema_1.json new file mode 100644 index 00000000..2ee79665 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/schema_1.json @@ -0,0 +1 @@ +{"multipleOf":1.5} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/schema_2.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/schema_2.json new file mode 100644 index 00000000..de303ef6 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/multipleOf/schema_2.json @@ -0,0 +1 @@ +{"multipleOf":0.0001} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_00.json new file mode 100644 index 00000000..7e9668e7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_00.json @@ -0,0 +1 @@ +"foo" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_01.json new file mode 100644 index 00000000..56a6051c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_01.json @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_10.json new file mode 100644 index 00000000..7e9668e7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_10.json @@ -0,0 +1 @@ +"foo" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_11.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_11.json new file mode 100644 index 00000000..56a6051c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_11.json @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_12.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_12.json new file mode 100644 index 00000000..f32a5804 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_12.json @@ -0,0 +1 @@ +true \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_20.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_20.json new file mode 100644 index 00000000..56a6051c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_20.json @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_21.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_21.json new file mode 100644 index 00000000..2518e687 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_21.json @@ -0,0 +1 @@ +{"foo":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_22.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_22.json new file mode 100644 index 00000000..9f5dd4e3 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/data_22.json @@ -0,0 +1 @@ +{"foo":"bar"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/schema_0.json new file mode 100644 index 00000000..fc125d79 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/schema_0.json @@ -0,0 +1 @@ +{"not":{"type":"integer"}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/schema_1.json new file mode 100644 index 00000000..7f219476 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/schema_1.json @@ -0,0 +1 @@ +{"not":{"type":["integer","boolean"]}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/schema_2.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/schema_2.json new file mode 100644 index 00000000..a3f16808 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/not/schema_2.json @@ -0,0 +1 @@ +{"not":{"properties":{"foo":{"type":"string"}},"type":"object"}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_00.json new file mode 100644 index 00000000..56a6051c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_00.json @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_01.json new file mode 100644 index 00000000..68151b2e --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_01.json @@ -0,0 +1 @@ +2.5 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_02.json new file mode 100644 index 00000000..e440e5c8 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_02.json @@ -0,0 +1 @@ +3 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_03.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_03.json new file mode 100644 index 00000000..400122e6 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_03.json @@ -0,0 +1 @@ +1.5 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_10.json new file mode 100644 index 00000000..e440e5c8 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_10.json @@ -0,0 +1 @@ +3 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_11.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_11.json new file mode 100644 index 00000000..b2bb988b --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_11.json @@ -0,0 +1 @@ +"foobar" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_12.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_12.json new file mode 100644 index 00000000..7e9668e7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/data_12.json @@ -0,0 +1 @@ +"foo" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/schema_0.json new file mode 100644 index 00000000..217c51e6 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/schema_0.json @@ -0,0 +1 @@ +{"oneOf":[{"type":"integer"},{"minimum":2}]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/schema_1.json new file mode 100644 index 00000000..4dae78a5 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/oneOf/schema_1.json @@ -0,0 +1 @@ +{"oneOf":[{"minLength":2},{"maxLength":4}],"type":"string"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/pattern/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/pattern/data_00.json new file mode 100644 index 00000000..a9cf1d43 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/pattern/data_00.json @@ -0,0 +1 @@ +"aaa" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/pattern/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/pattern/data_01.json new file mode 100644 index 00000000..4f44a210 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/pattern/data_01.json @@ -0,0 +1 @@ +"abc" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/pattern/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/pattern/data_02.json new file mode 100644 index 00000000..f32a5804 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/pattern/data_02.json @@ -0,0 +1 @@ +true \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/pattern/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/pattern/schema_0.json new file mode 100644 index 00000000..47a0a0e2 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/pattern/schema_0.json @@ -0,0 +1 @@ +{"pattern":"^a*$"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_00.json new file mode 100644 index 00000000..2518e687 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_00.json @@ -0,0 +1 @@ +{"foo":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_01.json new file mode 100644 index 00000000..40129f47 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_01.json @@ -0,0 +1 @@ +{"foo":1,"foooooo":2} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_02.json new file mode 100644 index 00000000..7a2b52f4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_02.json @@ -0,0 +1 @@ +{"foo":"bar","fooooo":2} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_03.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_03.json new file mode 100644 index 00000000..e7e5b7c9 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_03.json @@ -0,0 +1 @@ +{"foo":"bar","foooooo":"baz"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_04.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_04.json new file mode 100644 index 00000000..3cacc0b9 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_04.json @@ -0,0 +1 @@ +12 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_10.json new file mode 100644 index 00000000..c7b8e693 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_10.json @@ -0,0 +1 @@ +{"a":21} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_11.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_11.json new file mode 100644 index 00000000..644136dd --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_11.json @@ -0,0 +1 @@ +{"aaaa":18} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_12.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_12.json new file mode 100644 index 00000000..4af39994 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_12.json @@ -0,0 +1 @@ +{"a":21,"aaaa":18} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_13.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_13.json new file mode 100644 index 00000000..5286d3b9 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_13.json @@ -0,0 +1 @@ +{"a":"bar"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_14.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_14.json new file mode 100644 index 00000000..b778e0fa --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_14.json @@ -0,0 +1 @@ +{"aaaa":31} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_15.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_15.json new file mode 100644 index 00000000..786f9cb1 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_15.json @@ -0,0 +1 @@ +{"aaa":"foo","aaaa":31} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_20.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_20.json new file mode 100644 index 00000000..b2ef65b7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_20.json @@ -0,0 +1 @@ +{"answer 1":"42"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_21.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_21.json new file mode 100644 index 00000000..f8f6268d --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_21.json @@ -0,0 +1 @@ +{"a31b":null} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_22.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_22.json new file mode 100644 index 00000000..bfc72fb3 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_22.json @@ -0,0 +1 @@ +{"a_x_3":3} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_23.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_23.json new file mode 100644 index 00000000..cd32d32f --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_23.json @@ -0,0 +1 @@ +{"a_X_3":3} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_24.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_24.json new file mode 100644 index 00000000..c578f690 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_24.json @@ -0,0 +1,4 @@ +{ + "a": "hello", + "aaaaaaaaaaaaaaaaaaa": null +} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_25.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_25.json new file mode 100644 index 00000000..dd415e02 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_25.json @@ -0,0 +1,3 @@ +{ + "aaaaaaaaaaaaaaaaaaa": null +} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_26.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_26.json new file mode 100644 index 00000000..1b44a9f6 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/data_26.json @@ -0,0 +1,6 @@ +{ + "dictionary": { + "aaaaaaaaaaaaaaaaaaaa": null, + "b": "hello" + } +} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/schema_0.json new file mode 100644 index 00000000..6f5a8199 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/schema_0.json @@ -0,0 +1 @@ +{"patternProperties":{"f.*o":{"type":"integer"}}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/schema_1.json new file mode 100644 index 00000000..8776f201 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/schema_1.json @@ -0,0 +1 @@ +{"patternProperties":{"a*":{"type":"integer"},"aaa*":{"maximum":20}}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/schema_2.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/schema_2.json new file mode 100644 index 00000000..04a4cbc8 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/schema_2.json @@ -0,0 +1 @@ +{"patternProperties":{"X_":{"type":"string"},"[0-9]{2,}":{"type":"boolean"}}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/schema_3.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/schema_3.json new file mode 100644 index 00000000..03a67b99 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/schema_3.json @@ -0,0 +1,8 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9]{1,10}$": { "type": "string" } + }, + "additionalProperties": false +} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/schema_4.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/schema_4.json new file mode 100644 index 00000000..4c35adb5 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/patternProperties/schema_4.json @@ -0,0 +1,14 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "type": "object", + "properties": { + "dictionary": { + "type": "object", + "patternProperties": { + "^[a-zA-Z0-9]{1,10}$": { "type": "string" } + }, + "additionalProperties": false + } + }, + "additionalProperties": false +} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_00.json new file mode 100644 index 00000000..022ce236 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_00.json @@ -0,0 +1 @@ +{"bar":"baz","foo":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_01.json new file mode 100644 index 00000000..9ed62200 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_01.json @@ -0,0 +1 @@ +{"bar":{},"foo":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_02.json new file mode 100644 index 00000000..00062ccb --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_02.json @@ -0,0 +1 @@ +{"bar":{},"foo":[]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_03.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_03.json new file mode 100644 index 00000000..81ebc367 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_03.json @@ -0,0 +1 @@ +{"quux":[]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_04.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_04.json new file mode 100644 index 00000000..0637a088 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_04.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_10.json new file mode 100644 index 00000000..a82c1531 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_10.json @@ -0,0 +1 @@ +{"foo":[1,2]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_11.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_11.json new file mode 100644 index 00000000..f08510eb --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_11.json @@ -0,0 +1 @@ +{"foo":[1,2,3,4]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_12.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_12.json new file mode 100644 index 00000000..2ad6a35a --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_12.json @@ -0,0 +1 @@ +{"foo":[]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_13.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_13.json new file mode 100644 index 00000000..13370fe0 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_13.json @@ -0,0 +1 @@ +{"fxo":[1,2]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_14.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_14.json new file mode 100644 index 00000000..f82be5d3 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_14.json @@ -0,0 +1 @@ +{"fxo":[]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_15.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_15.json new file mode 100644 index 00000000..2ed66803 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_15.json @@ -0,0 +1 @@ +{"bar":[]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_16.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_16.json new file mode 100644 index 00000000..935e5254 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_16.json @@ -0,0 +1 @@ +{"quux":3} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_17.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_17.json new file mode 100644 index 00000000..531bbc94 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/data_17.json @@ -0,0 +1 @@ +{"quux":"foo"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/schema_0.json new file mode 100644 index 00000000..2c73cd58 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/schema_0.json @@ -0,0 +1 @@ +{"properties":{"bar":{"type":"string"},"foo":{"type":"integer"}}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/schema_1.json new file mode 100644 index 00000000..144f96e3 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/properties/schema_1.json @@ -0,0 +1 @@ +{"additionalProperties":{"type":"integer"},"patternProperties":{"f.o":{"minItems":2}},"properties":{"bar":{"type":"array"},"foo":{"maxItems":3,"type":"array"}}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_00.json new file mode 100644 index 00000000..1bfa80c1 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_00.json @@ -0,0 +1 @@ +{"foo":false} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_01.json new file mode 100644 index 00000000..27768a40 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_01.json @@ -0,0 +1 @@ +{"foo":{"foo":false}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_02.json new file mode 100644 index 00000000..a2742720 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_02.json @@ -0,0 +1 @@ +{"bar":false} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_03.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_03.json new file mode 100644 index 00000000..1de66762 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_03.json @@ -0,0 +1 @@ +{"foo":{"bar":false}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_10.json new file mode 100644 index 00000000..cc6193bd --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_10.json @@ -0,0 +1 @@ +{"bar":3} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_11.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_11.json new file mode 100644 index 00000000..7716a931 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_11.json @@ -0,0 +1 @@ +{"bar":true} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_20.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_20.json new file mode 100644 index 00000000..3169929f --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_20.json @@ -0,0 +1 @@ +[1,2] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_21.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_21.json new file mode 100644 index 00000000..f4e52901 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_21.json @@ -0,0 +1 @@ +[1,"foo"] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_30.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_30.json new file mode 100644 index 00000000..1606db7f --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_30.json @@ -0,0 +1 @@ +{"slash":"aoeu"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_31.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_31.json new file mode 100644 index 00000000..51cdcbc4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_31.json @@ -0,0 +1 @@ +{"tilda":"aoeu"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_32.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_32.json new file mode 100644 index 00000000..1aa03c6a --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_32.json @@ -0,0 +1 @@ +{"percent":"aoeu"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_40.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_40.json new file mode 100644 index 00000000..7813681f --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_40.json @@ -0,0 +1 @@ +5 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_41.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_41.json new file mode 100644 index 00000000..075c842d --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_41.json @@ -0,0 +1 @@ +"a" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_50.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_50.json new file mode 100644 index 00000000..9d936d56 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_50.json @@ -0,0 +1 @@ +{"minLength":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_51.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_51.json new file mode 100644 index 00000000..64ba18b3 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/data_51.json @@ -0,0 +1 @@ +{"minLength":-1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/schema_0.json new file mode 100644 index 00000000..a243138b --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/schema_0.json @@ -0,0 +1 @@ +{"additionalProperties":false,"properties":{"foo":{"$ref":"#"}}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/schema_1.json new file mode 100644 index 00000000..5475b8ef --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/schema_1.json @@ -0,0 +1 @@ +{"properties":{"bar":{"$ref":"#/properties/foo"},"foo":{"type":"integer"}}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/schema_2.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/schema_2.json new file mode 100644 index 00000000..80f5a14a --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/schema_2.json @@ -0,0 +1 @@ +{"items":[{"type":"integer"},{"$ref":"#/items/0"}]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/schema_3.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/schema_3.json new file mode 100644 index 00000000..5f5c1e25 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/schema_3.json @@ -0,0 +1 @@ +{"percent%field":{"type":"integer"},"properties":{"percent":{"$ref":"#/percent%25field"},"slash":{"$ref":"#/slash~1field"},"tilda":{"$ref":"#/tilda~0field"}},"slash/field":{"type":"integer"},"tilda~field":{"type":"integer"}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/schema_4.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/schema_4.json new file mode 100644 index 00000000..ac40ec7a --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/schema_4.json @@ -0,0 +1 @@ +{"$ref":"#/definitions/c","definitions":{"a":{"type":"integer"},"b":{"$ref":"#/definitions/a"},"c":{"$ref":"#/definitions/b"}}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/schema_5.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/schema_5.json new file mode 100644 index 00000000..412c2163 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/ref/schema_5.json @@ -0,0 +1 @@ +{"$ref":"http://json-schema.org/draft-04/schema#"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_00.json new file mode 100644 index 00000000..56a6051c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_00.json @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_01.json new file mode 100644 index 00000000..075c842d --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_01.json @@ -0,0 +1 @@ +"a" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_10.json new file mode 100644 index 00000000..56a6051c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_10.json @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_11.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_11.json new file mode 100644 index 00000000..075c842d --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_11.json @@ -0,0 +1 @@ +"a" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_20.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_20.json new file mode 100644 index 00000000..56a6051c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_20.json @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_21.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_21.json new file mode 100644 index 00000000..075c842d --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_21.json @@ -0,0 +1 @@ +"a" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_30.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_30.json new file mode 100644 index 00000000..89d00ba2 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_30.json @@ -0,0 +1 @@ +[[1]] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_31.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_31.json new file mode 100644 index 00000000..294b06e0 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/data_31.json @@ -0,0 +1 @@ +[["a"]] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/remoteFiles/folder/folderInteger.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/remoteFiles/folder/folderInteger.json new file mode 100644 index 00000000..dbe5c758 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/remoteFiles/folder/folderInteger.json @@ -0,0 +1,3 @@ +{ + "type": "integer" +} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/remoteFiles/integer.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/remoteFiles/integer.json new file mode 100644 index 00000000..dbe5c758 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/remoteFiles/integer.json @@ -0,0 +1,3 @@ +{ + "type": "integer" +} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/remoteFiles/subSchemas.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/remoteFiles/subSchemas.json new file mode 100644 index 00000000..8b6d8f84 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/remoteFiles/subSchemas.json @@ -0,0 +1,8 @@ +{ + "integer": { + "type": "integer" + }, + "refToInteger": { + "$ref": "#/integer" + } +} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/schema_0.json new file mode 100644 index 00000000..c9d47df2 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/schema_0.json @@ -0,0 +1 @@ +{"$ref":"http://localhost:1234/integer.json"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/schema_1.json new file mode 100644 index 00000000..de9da7fe --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/schema_1.json @@ -0,0 +1 @@ +{"$ref":"http://localhost:1234/subSchemas.json#/integer"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/schema_2.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/schema_2.json new file mode 100644 index 00000000..40b5213d --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/schema_2.json @@ -0,0 +1 @@ +{"$ref":"http://localhost:1234/subSchemas.json#/refToInteger"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/schema_3.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/schema_3.json new file mode 100644 index 00000000..51bd33d7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/refRemote/schema_3.json @@ -0,0 +1 @@ +{"id":"http://localhost:1234","items":{"id":"folder/","items":{"$ref":"folderInteger.json"}}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/required/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/required/data_00.json new file mode 100644 index 00000000..2518e687 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/required/data_00.json @@ -0,0 +1 @@ +{"foo":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/required/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/required/data_01.json new file mode 100644 index 00000000..ba06f3f8 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/required/data_01.json @@ -0,0 +1 @@ +{"bar":1} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/required/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/required/data_10.json new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/required/data_10.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/required/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/required/schema_0.json new file mode 100644 index 00000000..237ecc42 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/required/schema_0.json @@ -0,0 +1 @@ +{"properties":{"bar":{},"foo":{}},"required":["foo"]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/required/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/required/schema_1.json new file mode 100644 index 00000000..5891a518 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/required/schema_1.json @@ -0,0 +1 @@ +{"properties":{"foo":{}}} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_00.json new file mode 100644 index 00000000..56a6051c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_00.json @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_01.json new file mode 100644 index 00000000..b123147e --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_01.json @@ -0,0 +1 @@ +1.1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_02.json new file mode 100644 index 00000000..7e9668e7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_02.json @@ -0,0 +1 @@ +"foo" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_03.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_03.json new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_03.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_04.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_04.json new file mode 100644 index 00000000..0637a088 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_04.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_05.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_05.json new file mode 100644 index 00000000..f32a5804 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_05.json @@ -0,0 +1 @@ +true \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_06.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_06.json new file mode 100644 index 00000000..ec747fa4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_06.json @@ -0,0 +1 @@ +null \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_10.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_10.json new file mode 100644 index 00000000..56a6051c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_10.json @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_11.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_11.json new file mode 100644 index 00000000..b123147e --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_11.json @@ -0,0 +1 @@ +1.1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_12.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_12.json new file mode 100644 index 00000000..7e9668e7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_12.json @@ -0,0 +1 @@ +"foo" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_13.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_13.json new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_13.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_14.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_14.json new file mode 100644 index 00000000..0637a088 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_14.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_15.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_15.json new file mode 100644 index 00000000..f32a5804 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_15.json @@ -0,0 +1 @@ +true \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_16.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_16.json new file mode 100644 index 00000000..ec747fa4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_16.json @@ -0,0 +1 @@ +null \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_20.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_20.json new file mode 100644 index 00000000..56a6051c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_20.json @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_21.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_21.json new file mode 100644 index 00000000..b123147e --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_21.json @@ -0,0 +1 @@ +1.1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_22.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_22.json new file mode 100644 index 00000000..7e9668e7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_22.json @@ -0,0 +1 @@ +"foo" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_23.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_23.json new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_23.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_24.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_24.json new file mode 100644 index 00000000..0637a088 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_24.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_25.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_25.json new file mode 100644 index 00000000..f32a5804 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_25.json @@ -0,0 +1 @@ +true \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_26.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_26.json new file mode 100644 index 00000000..ec747fa4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_26.json @@ -0,0 +1 @@ +null \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_30.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_30.json new file mode 100644 index 00000000..56a6051c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_30.json @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_31.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_31.json new file mode 100644 index 00000000..b123147e --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_31.json @@ -0,0 +1 @@ +1.1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_32.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_32.json new file mode 100644 index 00000000..7e9668e7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_32.json @@ -0,0 +1 @@ +"foo" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_33.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_33.json new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_33.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_34.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_34.json new file mode 100644 index 00000000..0637a088 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_34.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_35.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_35.json new file mode 100644 index 00000000..f32a5804 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_35.json @@ -0,0 +1 @@ +true \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_36.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_36.json new file mode 100644 index 00000000..ec747fa4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_36.json @@ -0,0 +1 @@ +null \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_40.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_40.json new file mode 100644 index 00000000..56a6051c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_40.json @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_41.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_41.json new file mode 100644 index 00000000..b123147e --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_41.json @@ -0,0 +1 @@ +1.1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_42.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_42.json new file mode 100644 index 00000000..7e9668e7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_42.json @@ -0,0 +1 @@ +"foo" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_43.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_43.json new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_43.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_44.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_44.json new file mode 100644 index 00000000..0637a088 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_44.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_45.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_45.json new file mode 100644 index 00000000..f32a5804 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_45.json @@ -0,0 +1 @@ +true \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_46.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_46.json new file mode 100644 index 00000000..ec747fa4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_46.json @@ -0,0 +1 @@ +null \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_50.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_50.json new file mode 100644 index 00000000..56a6051c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_50.json @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_51.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_51.json new file mode 100644 index 00000000..b123147e --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_51.json @@ -0,0 +1 @@ +1.1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_52.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_52.json new file mode 100644 index 00000000..7e9668e7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_52.json @@ -0,0 +1 @@ +"foo" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_53.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_53.json new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_53.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_54.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_54.json new file mode 100644 index 00000000..0637a088 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_54.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_55.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_55.json new file mode 100644 index 00000000..f32a5804 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_55.json @@ -0,0 +1 @@ +true \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_56.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_56.json new file mode 100644 index 00000000..ec747fa4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_56.json @@ -0,0 +1 @@ +null \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_60.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_60.json new file mode 100644 index 00000000..56a6051c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_60.json @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_61.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_61.json new file mode 100644 index 00000000..b123147e --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_61.json @@ -0,0 +1 @@ +1.1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_62.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_62.json new file mode 100644 index 00000000..7e9668e7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_62.json @@ -0,0 +1 @@ +"foo" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_63.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_63.json new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_63.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_64.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_64.json new file mode 100644 index 00000000..0637a088 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_64.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_65.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_65.json new file mode 100644 index 00000000..f32a5804 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_65.json @@ -0,0 +1 @@ +true \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_66.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_66.json new file mode 100644 index 00000000..ec747fa4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_66.json @@ -0,0 +1 @@ +null \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_70.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_70.json new file mode 100644 index 00000000..56a6051c --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_70.json @@ -0,0 +1 @@ +1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_71.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_71.json new file mode 100644 index 00000000..7e9668e7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_71.json @@ -0,0 +1 @@ +"foo" \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_72.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_72.json new file mode 100644 index 00000000..b123147e --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_72.json @@ -0,0 +1 @@ +1.1 \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_73.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_73.json new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_73.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_74.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_74.json new file mode 100644 index 00000000..0637a088 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_74.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_75.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_75.json new file mode 100644 index 00000000..f32a5804 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_75.json @@ -0,0 +1 @@ +true \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_76.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_76.json new file mode 100644 index 00000000..ec747fa4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/data_76.json @@ -0,0 +1 @@ +null \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_0.json new file mode 100644 index 00000000..2be72ba1 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_0.json @@ -0,0 +1 @@ +{"type":"integer"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_1.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_1.json new file mode 100644 index 00000000..da4eeec7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_1.json @@ -0,0 +1 @@ +{"type":"number"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_2.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_2.json new file mode 100644 index 00000000..4db187eb --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_2.json @@ -0,0 +1 @@ +{"type":"string"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_3.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_3.json new file mode 100644 index 00000000..ffa5c9f8 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_3.json @@ -0,0 +1 @@ +{"type":"object"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_4.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_4.json new file mode 100644 index 00000000..bc88ff4a --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_4.json @@ -0,0 +1 @@ +{"type":"array"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_5.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_5.json new file mode 100644 index 00000000..7763bc51 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_5.json @@ -0,0 +1 @@ +{"type":"boolean"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_6.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_6.json new file mode 100644 index 00000000..fedaf464 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_6.json @@ -0,0 +1 @@ +{"type":"null"} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_7.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_7.json new file mode 100644 index 00000000..c243f0b7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/type/schema_7.json @@ -0,0 +1 @@ +{"type":["integer","string"]} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_00.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_00.json new file mode 100644 index 00000000..3169929f --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_00.json @@ -0,0 +1 @@ +[1,2] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_01.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_01.json new file mode 100644 index 00000000..a7c0e4b1 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_01.json @@ -0,0 +1 @@ +[1,1] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_010.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_010.json new file mode 100644 index 00000000..7e6261e1 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_010.json @@ -0,0 +1 @@ +[0,false] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_011.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_011.json new file mode 100644 index 00000000..48006ce5 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_011.json @@ -0,0 +1 @@ +[{},[1],true,null,1] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_012.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_012.json new file mode 100644 index 00000000..067faf53 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_012.json @@ -0,0 +1 @@ +[{},[1],true,null,{},1] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_02.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_02.json new file mode 100644 index 00000000..22881161 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_02.json @@ -0,0 +1 @@ +[1,1,1] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_03.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_03.json new file mode 100644 index 00000000..b7734bb0 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_03.json @@ -0,0 +1 @@ +[{"foo":"bar"},{"foo":"baz"}] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_04.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_04.json new file mode 100644 index 00000000..67d501bc --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_04.json @@ -0,0 +1 @@ +[{"foo":"bar"},{"foo":"bar"}] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_05.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_05.json new file mode 100644 index 00000000..4e042c2f --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_05.json @@ -0,0 +1 @@ +[{"foo":{"bar":{"baz":true}}},{"foo":{"bar":{"baz":false}}}] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_06.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_06.json new file mode 100644 index 00000000..0f63748a --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_06.json @@ -0,0 +1 @@ +[{"foo":{"bar":{"baz":true}}},{"foo":{"bar":{"baz":true}}}] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_07.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_07.json new file mode 100644 index 00000000..8318b7d7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_07.json @@ -0,0 +1 @@ +[["foo"],["bar"]] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_08.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_08.json new file mode 100644 index 00000000..15caa6c0 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_08.json @@ -0,0 +1 @@ +[["foo"],["foo"]] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_09.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_09.json new file mode 100644 index 00000000..1083d092 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/data_09.json @@ -0,0 +1 @@ +[1,true] \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/schema_0.json b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/schema_0.json new file mode 100644 index 00000000..d598d705 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/json_schema_test_suite/uniqueItems/schema_0.json @@ -0,0 +1 @@ +{"uniqueItems":true} \ No newline at end of file diff --git a/vendor/github.com/xeipuuv/gojsonschema/locales.go b/vendor/github.com/xeipuuv/gojsonschema/locales.go new file mode 100644 index 00000000..de05d60d --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/locales.go @@ -0,0 +1,275 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// 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. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Contains const string and messages. +// +// created 01-01-2015 + +package gojsonschema + +type ( + // locale is an interface for definining custom error strings + locale interface { + Required() string + InvalidType() string + NumberAnyOf() string + NumberOneOf() string + NumberAllOf() string + NumberNot() string + MissingDependency() string + Internal() string + Enum() string + ArrayNoAdditionalItems() string + ArrayMinItems() string + ArrayMaxItems() string + Unique() string + ArrayMinProperties() string + ArrayMaxProperties() string + AdditionalPropertyNotAllowed() string + InvalidPropertyPattern() string + StringGTE() string + StringLTE() string + DoesNotMatchPattern() string + DoesNotMatchFormat() string + MultipleOf() string + NumberGTE() string + NumberGT() string + NumberLTE() string + NumberLT() string + + // Schema validations + RegexPattern() string + GreaterThanZero() string + MustBeOfA() string + MustBeOfAn() string + CannotBeUsedWithout() string + CannotBeGT() string + MustBeOfType() string + MustBeValidRegex() string + MustBeValidFormat() string + MustBeGTEZero() string + KeyCannotBeGreaterThan() string + KeyItemsMustBeOfType() string + KeyItemsMustBeUnique() string + ReferenceMustBeCanonical() string + NotAValidType() string + Duplicated() string + httpBadStatus() string + + // ErrorFormat + ErrorFormat() string + } + + // DefaultLocale is the default locale for this package + DefaultLocale struct{} +) + +func (l DefaultLocale) Required() string { + return `%property% is required` +} + +func (l DefaultLocale) InvalidType() string { + return `Invalid type. Expected: %expected%, given: %given%` +} + +func (l DefaultLocale) NumberAnyOf() string { + return `Must validate at least one schema (anyOf)` +} + +func (l DefaultLocale) NumberOneOf() string { + return `Must validate one and only one schema (oneOf)` +} + +func (l DefaultLocale) NumberAllOf() string { + return `Must validate all the schemas (allOf)` +} + +func (l DefaultLocale) NumberNot() string { + return `Must not validate the schema (not)` +} + +func (l DefaultLocale) MissingDependency() string { + return `Has a dependency on %dependency%` +} + +func (l DefaultLocale) Internal() string { + return `Internal Error %error%` +} + +func (l DefaultLocale) Enum() string { + return `%field% must be one of the following: %allowed%` +} + +func (l DefaultLocale) ArrayNoAdditionalItems() string { + return `No additional items allowed on array` +} + +func (l DefaultLocale) ArrayMinItems() string { + return `Array must have at least %min% items` +} + +func (l DefaultLocale) ArrayMaxItems() string { + return `Array must have at most %max% items` +} + +func (l DefaultLocale) Unique() string { + return `%type% items must be unique` +} + +func (l DefaultLocale) ArrayMinProperties() string { + return `Must have at least %min% properties` +} + +func (l DefaultLocale) ArrayMaxProperties() string { + return `Must have at most %max% properties` +} + +func (l DefaultLocale) AdditionalPropertyNotAllowed() string { + return `Additional property %property% is not allowed` +} + +func (l DefaultLocale) InvalidPropertyPattern() string { + return `Property "%property%" does not match pattern %pattern%` +} + +func (l DefaultLocale) StringGTE() string { + return `String length must be greater than or equal to %min%` +} + +func (l DefaultLocale) StringLTE() string { + return `String length must be less than or equal to %max%` +} + +func (l DefaultLocale) DoesNotMatchPattern() string { + return `Does not match pattern '%pattern%'` +} + +func (l DefaultLocale) DoesNotMatchFormat() string { + return `Does not match format '%format%'` +} + +func (l DefaultLocale) MultipleOf() string { + return `Must be a multiple of %multiple%` +} + +func (l DefaultLocale) NumberGTE() string { + return `Must be greater than or equal to %min%` +} + +func (l DefaultLocale) NumberGT() string { + return `Must be greater than %min%` +} + +func (l DefaultLocale) NumberLTE() string { + return `Must be less than or equal to %max%` +} + +func (l DefaultLocale) NumberLT() string { + return `Must be less than %max%` +} + +// Schema validators +func (l DefaultLocale) RegexPattern() string { + return `Invalid regex pattern '%pattern%'` +} + +func (l DefaultLocale) GreaterThanZero() string { + return `%number% must be strictly greater than 0` +} + +func (l DefaultLocale) MustBeOfA() string { + return `%x% must be of a %y%` +} + +func (l DefaultLocale) MustBeOfAn() string { + return `%x% must be of an %y%` +} + +func (l DefaultLocale) CannotBeUsedWithout() string { + return `%x% cannot be used without %y%` +} + +func (l DefaultLocale) CannotBeGT() string { + return `%x% cannot be greater than %y%` +} + +func (l DefaultLocale) MustBeOfType() string { + return `%key% must be of type %type%` +} + +func (l DefaultLocale) MustBeValidRegex() string { + return `%key% must be a valid regex` +} + +func (l DefaultLocale) MustBeValidFormat() string { + return `%key% must be a valid format %given%` +} + +func (l DefaultLocale) MustBeGTEZero() string { + return `%key% must be greater than or equal to 0` +} + +func (l DefaultLocale) KeyCannotBeGreaterThan() string { + return `%key% cannot be greater than %y%` +} + +func (l DefaultLocale) KeyItemsMustBeOfType() string { + return `%key% items must be %type%` +} + +func (l DefaultLocale) KeyItemsMustBeUnique() string { + return `%key% items must be unique` +} + +func (l DefaultLocale) ReferenceMustBeCanonical() string { + return `Reference %reference% must be canonical` +} + +func (l DefaultLocale) NotAValidType() string { + return `%type% is not a valid type -- ` +} + +func (l DefaultLocale) Duplicated() string { + return `%type% type is duplicated` +} + +func (l DefaultLocale) httpBadStatus() string { + return `Could not read schema from HTTP, response status is %status%` +} + +// Replacement options: field, description, context, value +func (l DefaultLocale) ErrorFormat() string { + return `%field%: %description%` +} + +const ( + STRING_NUMBER = "number" + STRING_ARRAY_OF_STRINGS = "array of strings" + STRING_ARRAY_OF_SCHEMAS = "array of schemas" + STRING_SCHEMA = "schema" + STRING_SCHEMA_OR_ARRAY_OF_STRINGS = "schema or array of strings" + STRING_PROPERTIES = "properties" + STRING_DEPENDENCY = "dependency" + STRING_PROPERTY = "property" + STRING_UNDEFINED = "undefined" + STRING_CONTEXT_ROOT = "(root)" + STRING_ROOT_SCHEMA_PROPERTY = "(root)" +) diff --git a/vendor/github.com/xeipuuv/gojsonschema/result.go b/vendor/github.com/xeipuuv/gojsonschema/result.go new file mode 100644 index 00000000..c6d33758 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/result.go @@ -0,0 +1,171 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// 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. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Result and ResultError implementations. +// +// created 01-01-2015 + +package gojsonschema + +import ( + "fmt" + "strings" +) + +type ( + // ErrorDetails is a map of details specific to each error. + // While the values will vary, every error will contain a "field" value + ErrorDetails map[string]interface{} + + // ResultError is the interface that library errors must implement + ResultError interface { + Field() string + SetType(string) + Type() string + SetContext(*jsonContext) + Context() *jsonContext + SetDescription(string) + Description() string + SetValue(interface{}) + Value() interface{} + SetDetails(ErrorDetails) + Details() ErrorDetails + } + + // ResultErrorFields holds the fields for each ResultError implementation. + // ResultErrorFields implements the ResultError interface, so custom errors + // can be defined by just embedding this type + ResultErrorFields struct { + errorType string // A string with the type of error (i.e. invalid_type) + context *jsonContext // Tree like notation of the part that failed the validation. ex (root).a.b ... + description string // A human readable error message + value interface{} // Value given by the JSON file that is the source of the error + details ErrorDetails + } + + Result struct { + errors []ResultError + // Scores how well the validation matched. Useful in generating + // better error messages for anyOf and oneOf. + score int + } +) + +// Field outputs the field name without the root context +// i.e. firstName or person.firstName instead of (root).firstName or (root).person.firstName +func (v *ResultErrorFields) Field() string { + if p, ok := v.Details()["property"]; ok { + if str, isString := p.(string); isString { + return str + } + } + + return strings.TrimPrefix(v.context.String(), STRING_ROOT_SCHEMA_PROPERTY+".") +} + +func (v *ResultErrorFields) SetType(errorType string) { + v.errorType = errorType +} + +func (v *ResultErrorFields) Type() string { + return v.errorType +} + +func (v *ResultErrorFields) SetContext(context *jsonContext) { + v.context = context +} + +func (v *ResultErrorFields) Context() *jsonContext { + return v.context +} + +func (v *ResultErrorFields) SetDescription(description string) { + v.description = description +} + +func (v *ResultErrorFields) Description() string { + return v.description +} + +func (v *ResultErrorFields) SetValue(value interface{}) { + v.value = value +} + +func (v *ResultErrorFields) Value() interface{} { + return v.value +} + +func (v *ResultErrorFields) SetDetails(details ErrorDetails) { + v.details = details +} + +func (v *ResultErrorFields) Details() ErrorDetails { + return v.details +} + +func (v ResultErrorFields) String() string { + // as a fallback, the value is displayed go style + valueString := fmt.Sprintf("%v", v.value) + + // marshal the go value value to json + if v.value == nil { + valueString = TYPE_NULL + } else { + if vs, err := marshalToJsonString(v.value); err == nil { + if vs == nil { + valueString = TYPE_NULL + } else { + valueString = *vs + } + } + } + + return formatErrorDescription(Locale.ErrorFormat(), ErrorDetails{ + "context": v.context.String(), + "description": v.description, + "value": valueString, + "field": v.Field(), + }) +} + +func (v *Result) Valid() bool { + return len(v.errors) == 0 +} + +func (v *Result) Errors() []ResultError { + return v.errors +} + +func (v *Result) addError(err ResultError, context *jsonContext, value interface{}, details ErrorDetails) { + newError(err, context, value, Locale, details) + v.errors = append(v.errors, err) + v.score -= 2 // results in a net -1 when added to the +1 we get at the end of the validation function +} + +// Used to copy errors from a sub-schema to the main one +func (v *Result) mergeErrors(otherResult *Result) { + v.errors = append(v.errors, otherResult.Errors()...) + v.score += otherResult.score +} + +func (v *Result) incrementScore() { + v.score++ +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/schema.go b/vendor/github.com/xeipuuv/gojsonschema/schema.go new file mode 100644 index 00000000..577c7863 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/schema.go @@ -0,0 +1,908 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// 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. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Defines Schema, the main entry to every subSchema. +// Contains the parsing logic and error checking. +// +// created 26-02-2013 + +package gojsonschema + +import ( + // "encoding/json" + "errors" + "reflect" + "regexp" + + "github.com/xeipuuv/gojsonreference" +) + +var ( + // Locale is the default locale to use + // Library users can overwrite with their own implementation + Locale locale = DefaultLocale{} +) + +func NewSchema(l JSONLoader) (*Schema, error) { + return l.loadSchema() +} + +type Schema struct { + documentReference gojsonreference.JsonReference + rootSchema *subSchema + pool *schemaPool + referencePool *schemaReferencePool +} + +func (d *Schema) parse(document interface{}) error { + d.rootSchema = &subSchema{property: STRING_ROOT_SCHEMA_PROPERTY} + return d.parseSchema(document, d.rootSchema) +} + +func (d *Schema) SetRootSchemaName(name string) { + d.rootSchema.property = name +} + +// Parses a subSchema +// +// Pretty long function ( sorry :) )... but pretty straight forward, repetitive and boring +// Not much magic involved here, most of the job is to validate the key names and their values, +// then the values are copied into subSchema struct +// +func (d *Schema) parseSchema(documentNode interface{}, currentSchema *subSchema) error { + + if !isKind(documentNode, reflect.Map) { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_OBJECT, + "given": STRING_SCHEMA, + }, + )) + } + + m := documentNode.(map[string]interface{}) + + if currentSchema == d.rootSchema { + currentSchema.ref = &d.documentReference + } + + // $subSchema + if existsMapKey(m, KEY_SCHEMA) { + if !isKind(m[KEY_SCHEMA], reflect.String) { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_STRING, + "given": KEY_SCHEMA, + }, + )) + } + schemaRef := m[KEY_SCHEMA].(string) + schemaReference, err := gojsonreference.NewJsonReference(schemaRef) + currentSchema.subSchema = &schemaReference + if err != nil { + return err + } + } + + // $ref + if existsMapKey(m, KEY_REF) && !isKind(m[KEY_REF], reflect.String) { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_STRING, + "given": KEY_REF, + }, + )) + } + if k, ok := m[KEY_REF].(string); ok { + + if sch, ok := d.referencePool.Get(currentSchema.ref.String() + k); ok { + + currentSchema.refSchema = sch + + } else { + + var err error + err = d.parseReference(documentNode, currentSchema, k) + if err != nil { + return err + } + + return nil + } + } + + // definitions + if existsMapKey(m, KEY_DEFINITIONS) { + if isKind(m[KEY_DEFINITIONS], reflect.Map) { + currentSchema.definitions = make(map[string]*subSchema) + for dk, dv := range m[KEY_DEFINITIONS].(map[string]interface{}) { + if isKind(dv, reflect.Map) { + newSchema := &subSchema{property: KEY_DEFINITIONS, parent: currentSchema, ref: currentSchema.ref} + currentSchema.definitions[dk] = newSchema + err := d.parseSchema(dv, newSchema) + if err != nil { + return errors.New(err.Error()) + } + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": STRING_ARRAY_OF_SCHEMAS, + "given": KEY_DEFINITIONS, + }, + )) + } + } + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": STRING_ARRAY_OF_SCHEMAS, + "given": KEY_DEFINITIONS, + }, + )) + } + + } + + // id + if existsMapKey(m, KEY_ID) && !isKind(m[KEY_ID], reflect.String) { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_STRING, + "given": KEY_ID, + }, + )) + } + if k, ok := m[KEY_ID].(string); ok { + currentSchema.id = &k + } + + // title + if existsMapKey(m, KEY_TITLE) && !isKind(m[KEY_TITLE], reflect.String) { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_STRING, + "given": KEY_TITLE, + }, + )) + } + if k, ok := m[KEY_TITLE].(string); ok { + currentSchema.title = &k + } + + // description + if existsMapKey(m, KEY_DESCRIPTION) && !isKind(m[KEY_DESCRIPTION], reflect.String) { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_STRING, + "given": KEY_DESCRIPTION, + }, + )) + } + if k, ok := m[KEY_DESCRIPTION].(string); ok { + currentSchema.description = &k + } + + // type + if existsMapKey(m, KEY_TYPE) { + if isKind(m[KEY_TYPE], reflect.String) { + if k, ok := m[KEY_TYPE].(string); ok { + err := currentSchema.types.Add(k) + if err != nil { + return err + } + } + } else { + if isKind(m[KEY_TYPE], reflect.Slice) { + arrayOfTypes := m[KEY_TYPE].([]interface{}) + for _, typeInArray := range arrayOfTypes { + if reflect.ValueOf(typeInArray).Kind() != reflect.String { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_STRING + "/" + STRING_ARRAY_OF_STRINGS, + "given": KEY_TYPE, + }, + )) + } else { + currentSchema.types.Add(typeInArray.(string)) + } + } + + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_STRING + "/" + STRING_ARRAY_OF_STRINGS, + "given": KEY_TYPE, + }, + )) + } + } + } + + // properties + if existsMapKey(m, KEY_PROPERTIES) { + err := d.parseProperties(m[KEY_PROPERTIES], currentSchema) + if err != nil { + return err + } + } + + // additionalProperties + if existsMapKey(m, KEY_ADDITIONAL_PROPERTIES) { + if isKind(m[KEY_ADDITIONAL_PROPERTIES], reflect.Bool) { + currentSchema.additionalProperties = m[KEY_ADDITIONAL_PROPERTIES].(bool) + } else if isKind(m[KEY_ADDITIONAL_PROPERTIES], reflect.Map) { + newSchema := &subSchema{property: KEY_ADDITIONAL_PROPERTIES, parent: currentSchema, ref: currentSchema.ref} + currentSchema.additionalProperties = newSchema + err := d.parseSchema(m[KEY_ADDITIONAL_PROPERTIES], newSchema) + if err != nil { + return errors.New(err.Error()) + } + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_BOOLEAN + "/" + STRING_SCHEMA, + "given": KEY_ADDITIONAL_PROPERTIES, + }, + )) + } + } + + // patternProperties + if existsMapKey(m, KEY_PATTERN_PROPERTIES) { + if isKind(m[KEY_PATTERN_PROPERTIES], reflect.Map) { + patternPropertiesMap := m[KEY_PATTERN_PROPERTIES].(map[string]interface{}) + if len(patternPropertiesMap) > 0 { + currentSchema.patternProperties = make(map[string]*subSchema) + for k, v := range patternPropertiesMap { + _, err := regexp.MatchString(k, "") + if err != nil { + return errors.New(formatErrorDescription( + Locale.RegexPattern(), + ErrorDetails{"pattern": k}, + )) + } + newSchema := &subSchema{property: k, parent: currentSchema, ref: currentSchema.ref} + err = d.parseSchema(v, newSchema) + if err != nil { + return errors.New(err.Error()) + } + currentSchema.patternProperties[k] = newSchema + } + } + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": STRING_SCHEMA, + "given": KEY_PATTERN_PROPERTIES, + }, + )) + } + } + + // dependencies + if existsMapKey(m, KEY_DEPENDENCIES) { + err := d.parseDependencies(m[KEY_DEPENDENCIES], currentSchema) + if err != nil { + return err + } + } + + // items + if existsMapKey(m, KEY_ITEMS) { + if isKind(m[KEY_ITEMS], reflect.Slice) { + for _, itemElement := range m[KEY_ITEMS].([]interface{}) { + if isKind(itemElement, reflect.Map) { + newSchema := &subSchema{parent: currentSchema, property: KEY_ITEMS} + newSchema.ref = currentSchema.ref + currentSchema.AddItemsChild(newSchema) + err := d.parseSchema(itemElement, newSchema) + if err != nil { + return err + } + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": STRING_SCHEMA + "/" + STRING_ARRAY_OF_SCHEMAS, + "given": KEY_ITEMS, + }, + )) + } + currentSchema.itemsChildrenIsSingleSchema = false + } + } else if isKind(m[KEY_ITEMS], reflect.Map) { + newSchema := &subSchema{parent: currentSchema, property: KEY_ITEMS} + newSchema.ref = currentSchema.ref + currentSchema.AddItemsChild(newSchema) + err := d.parseSchema(m[KEY_ITEMS], newSchema) + if err != nil { + return err + } + currentSchema.itemsChildrenIsSingleSchema = true + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": STRING_SCHEMA + "/" + STRING_ARRAY_OF_SCHEMAS, + "given": KEY_ITEMS, + }, + )) + } + } + + // additionalItems + if existsMapKey(m, KEY_ADDITIONAL_ITEMS) { + if isKind(m[KEY_ADDITIONAL_ITEMS], reflect.Bool) { + currentSchema.additionalItems = m[KEY_ADDITIONAL_ITEMS].(bool) + } else if isKind(m[KEY_ADDITIONAL_ITEMS], reflect.Map) { + newSchema := &subSchema{property: KEY_ADDITIONAL_ITEMS, parent: currentSchema, ref: currentSchema.ref} + currentSchema.additionalItems = newSchema + err := d.parseSchema(m[KEY_ADDITIONAL_ITEMS], newSchema) + if err != nil { + return errors.New(err.Error()) + } + } else { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": TYPE_BOOLEAN + "/" + STRING_SCHEMA, + "given": KEY_ADDITIONAL_ITEMS, + }, + )) + } + } + + // validation : number / integer + + if existsMapKey(m, KEY_MULTIPLE_OF) { + multipleOfValue := mustBeNumber(m[KEY_MULTIPLE_OF]) + if multipleOfValue == nil { + return errors.New(formatErrorDescription( + Locale.InvalidType(), + ErrorDetails{ + "expected": STRING_NUMBER, + "given": KEY_MULTIPLE_OF, + }, + )) + } + if *multipleOfValue <= 0 { + return errors.New(formatErrorDescription( + Locale.GreaterThanZero(), + ErrorDetails{"number": KEY_MULTIPLE_OF}, + )) + } + currentSchema.multipleOf = multipleOfValue + } + + if existsMapKey(m, KEY_MINIMUM) { + minimumValue := mustBeNumber(m[KEY_MINIMUM]) + if minimumValue == nil { + return errors.New(formatErrorDescription( + Locale.MustBeOfA(), + ErrorDetails{"x": KEY_MINIMUM, "y": STRING_NUMBER}, + )) + } + currentSchema.minimum = minimumValue + } + + if existsMapKey(m, KEY_EXCLUSIVE_MINIMUM) { + if isKind(m[KEY_EXCLUSIVE_MINIMUM], reflect.Bool) { + if currentSchema.minimum == nil { + return errors.New(formatErrorDescription( + Locale.CannotBeUsedWithout(), + ErrorDetails{"x": KEY_EXCLUSIVE_MINIMUM, "y": KEY_MINIMUM}, + )) + } + exclusiveMinimumValue := m[KEY_EXCLUSIVE_MINIMUM].(bool) + currentSchema.exclusiveMinimum = exclusiveMinimumValue + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfA(), + ErrorDetails{"x": KEY_EXCLUSIVE_MINIMUM, "y": TYPE_BOOLEAN}, + )) + } + } + + if existsMapKey(m, KEY_MAXIMUM) { + maximumValue := mustBeNumber(m[KEY_MAXIMUM]) + if maximumValue == nil { + return errors.New(formatErrorDescription( + Locale.MustBeOfA(), + ErrorDetails{"x": KEY_MAXIMUM, "y": STRING_NUMBER}, + )) + } + currentSchema.maximum = maximumValue + } + + if existsMapKey(m, KEY_EXCLUSIVE_MAXIMUM) { + if isKind(m[KEY_EXCLUSIVE_MAXIMUM], reflect.Bool) { + if currentSchema.maximum == nil { + return errors.New(formatErrorDescription( + Locale.CannotBeUsedWithout(), + ErrorDetails{"x": KEY_EXCLUSIVE_MAXIMUM, "y": KEY_MAXIMUM}, + )) + } + exclusiveMaximumValue := m[KEY_EXCLUSIVE_MAXIMUM].(bool) + currentSchema.exclusiveMaximum = exclusiveMaximumValue + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfA(), + ErrorDetails{"x": KEY_EXCLUSIVE_MAXIMUM, "y": STRING_NUMBER}, + )) + } + } + + if currentSchema.minimum != nil && currentSchema.maximum != nil { + if *currentSchema.minimum > *currentSchema.maximum { + return errors.New(formatErrorDescription( + Locale.CannotBeGT(), + ErrorDetails{"x": KEY_MINIMUM, "y": KEY_MAXIMUM}, + )) + } + } + + // validation : string + + if existsMapKey(m, KEY_MIN_LENGTH) { + minLengthIntegerValue := mustBeInteger(m[KEY_MIN_LENGTH]) + if minLengthIntegerValue == nil { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_MIN_LENGTH, "y": TYPE_INTEGER}, + )) + } + if *minLengthIntegerValue < 0 { + return errors.New(formatErrorDescription( + Locale.MustBeGTEZero(), + ErrorDetails{"key": KEY_MIN_LENGTH}, + )) + } + currentSchema.minLength = minLengthIntegerValue + } + + if existsMapKey(m, KEY_MAX_LENGTH) { + maxLengthIntegerValue := mustBeInteger(m[KEY_MAX_LENGTH]) + if maxLengthIntegerValue == nil { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_MAX_LENGTH, "y": TYPE_INTEGER}, + )) + } + if *maxLengthIntegerValue < 0 { + return errors.New(formatErrorDescription( + Locale.MustBeGTEZero(), + ErrorDetails{"key": KEY_MAX_LENGTH}, + )) + } + currentSchema.maxLength = maxLengthIntegerValue + } + + if currentSchema.minLength != nil && currentSchema.maxLength != nil { + if *currentSchema.minLength > *currentSchema.maxLength { + return errors.New(formatErrorDescription( + Locale.CannotBeGT(), + ErrorDetails{"x": KEY_MIN_LENGTH, "y": KEY_MAX_LENGTH}, + )) + } + } + + if existsMapKey(m, KEY_PATTERN) { + if isKind(m[KEY_PATTERN], reflect.String) { + regexpObject, err := regexp.Compile(m[KEY_PATTERN].(string)) + if err != nil { + return errors.New(formatErrorDescription( + Locale.MustBeValidRegex(), + ErrorDetails{"key": KEY_PATTERN}, + )) + } + currentSchema.pattern = regexpObject + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfA(), + ErrorDetails{"x": KEY_PATTERN, "y": TYPE_STRING}, + )) + } + } + + if existsMapKey(m, KEY_FORMAT) { + formatString, ok := m[KEY_FORMAT].(string) + if ok && FormatCheckers.Has(formatString) { + currentSchema.format = formatString + } else { + return errors.New(formatErrorDescription( + Locale.MustBeValidFormat(), + ErrorDetails{"key": KEY_FORMAT, "given": m[KEY_FORMAT]}, + )) + } + } + + // validation : object + + if existsMapKey(m, KEY_MIN_PROPERTIES) { + minPropertiesIntegerValue := mustBeInteger(m[KEY_MIN_PROPERTIES]) + if minPropertiesIntegerValue == nil { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_MIN_PROPERTIES, "y": TYPE_INTEGER}, + )) + } + if *minPropertiesIntegerValue < 0 { + return errors.New(formatErrorDescription( + Locale.MustBeGTEZero(), + ErrorDetails{"key": KEY_MIN_PROPERTIES}, + )) + } + currentSchema.minProperties = minPropertiesIntegerValue + } + + if existsMapKey(m, KEY_MAX_PROPERTIES) { + maxPropertiesIntegerValue := mustBeInteger(m[KEY_MAX_PROPERTIES]) + if maxPropertiesIntegerValue == nil { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_MAX_PROPERTIES, "y": TYPE_INTEGER}, + )) + } + if *maxPropertiesIntegerValue < 0 { + return errors.New(formatErrorDescription( + Locale.MustBeGTEZero(), + ErrorDetails{"key": KEY_MAX_PROPERTIES}, + )) + } + currentSchema.maxProperties = maxPropertiesIntegerValue + } + + if currentSchema.minProperties != nil && currentSchema.maxProperties != nil { + if *currentSchema.minProperties > *currentSchema.maxProperties { + return errors.New(formatErrorDescription( + Locale.KeyCannotBeGreaterThan(), + ErrorDetails{"key": KEY_MIN_PROPERTIES, "y": KEY_MAX_PROPERTIES}, + )) + } + } + + if existsMapKey(m, KEY_REQUIRED) { + if isKind(m[KEY_REQUIRED], reflect.Slice) { + requiredValues := m[KEY_REQUIRED].([]interface{}) + for _, requiredValue := range requiredValues { + if isKind(requiredValue, reflect.String) { + err := currentSchema.AddRequired(requiredValue.(string)) + if err != nil { + return err + } + } else { + return errors.New(formatErrorDescription( + Locale.KeyItemsMustBeOfType(), + ErrorDetails{"key": KEY_REQUIRED, "type": TYPE_STRING}, + )) + } + } + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_REQUIRED, "y": TYPE_ARRAY}, + )) + } + } + + // validation : array + + if existsMapKey(m, KEY_MIN_ITEMS) { + minItemsIntegerValue := mustBeInteger(m[KEY_MIN_ITEMS]) + if minItemsIntegerValue == nil { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_MIN_ITEMS, "y": TYPE_INTEGER}, + )) + } + if *minItemsIntegerValue < 0 { + return errors.New(formatErrorDescription( + Locale.MustBeGTEZero(), + ErrorDetails{"key": KEY_MIN_ITEMS}, + )) + } + currentSchema.minItems = minItemsIntegerValue + } + + if existsMapKey(m, KEY_MAX_ITEMS) { + maxItemsIntegerValue := mustBeInteger(m[KEY_MAX_ITEMS]) + if maxItemsIntegerValue == nil { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_MAX_ITEMS, "y": TYPE_INTEGER}, + )) + } + if *maxItemsIntegerValue < 0 { + return errors.New(formatErrorDescription( + Locale.MustBeGTEZero(), + ErrorDetails{"key": KEY_MAX_ITEMS}, + )) + } + currentSchema.maxItems = maxItemsIntegerValue + } + + if existsMapKey(m, KEY_UNIQUE_ITEMS) { + if isKind(m[KEY_UNIQUE_ITEMS], reflect.Bool) { + currentSchema.uniqueItems = m[KEY_UNIQUE_ITEMS].(bool) + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfA(), + ErrorDetails{"x": KEY_UNIQUE_ITEMS, "y": TYPE_BOOLEAN}, + )) + } + } + + // validation : all + + if existsMapKey(m, KEY_ENUM) { + if isKind(m[KEY_ENUM], reflect.Slice) { + for _, v := range m[KEY_ENUM].([]interface{}) { + err := currentSchema.AddEnum(v) + if err != nil { + return err + } + } + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_ENUM, "y": TYPE_ARRAY}, + )) + } + } + + // validation : subSchema + + if existsMapKey(m, KEY_ONE_OF) { + if isKind(m[KEY_ONE_OF], reflect.Slice) { + for _, v := range m[KEY_ONE_OF].([]interface{}) { + newSchema := &subSchema{property: KEY_ONE_OF, parent: currentSchema, ref: currentSchema.ref} + currentSchema.AddOneOf(newSchema) + err := d.parseSchema(v, newSchema) + if err != nil { + return err + } + } + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_ONE_OF, "y": TYPE_ARRAY}, + )) + } + } + + if existsMapKey(m, KEY_ANY_OF) { + if isKind(m[KEY_ANY_OF], reflect.Slice) { + for _, v := range m[KEY_ANY_OF].([]interface{}) { + newSchema := &subSchema{property: KEY_ANY_OF, parent: currentSchema, ref: currentSchema.ref} + currentSchema.AddAnyOf(newSchema) + err := d.parseSchema(v, newSchema) + if err != nil { + return err + } + } + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_ANY_OF, "y": TYPE_ARRAY}, + )) + } + } + + if existsMapKey(m, KEY_ALL_OF) { + if isKind(m[KEY_ALL_OF], reflect.Slice) { + for _, v := range m[KEY_ALL_OF].([]interface{}) { + newSchema := &subSchema{property: KEY_ALL_OF, parent: currentSchema, ref: currentSchema.ref} + currentSchema.AddAllOf(newSchema) + err := d.parseSchema(v, newSchema) + if err != nil { + return err + } + } + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_ANY_OF, "y": TYPE_ARRAY}, + )) + } + } + + if existsMapKey(m, KEY_NOT) { + if isKind(m[KEY_NOT], reflect.Map) { + newSchema := &subSchema{property: KEY_NOT, parent: currentSchema, ref: currentSchema.ref} + currentSchema.SetNot(newSchema) + err := d.parseSchema(m[KEY_NOT], newSchema) + if err != nil { + return err + } + } else { + return errors.New(formatErrorDescription( + Locale.MustBeOfAn(), + ErrorDetails{"x": KEY_NOT, "y": TYPE_OBJECT}, + )) + } + } + + return nil +} + +func (d *Schema) parseReference(documentNode interface{}, currentSchema *subSchema, reference string) (e error) { + + var err error + + jsonReference, err := gojsonreference.NewJsonReference(reference) + if err != nil { + return err + } + + standaloneDocument := d.pool.GetStandaloneDocument() + + if jsonReference.HasFullUrl { + currentSchema.ref = &jsonReference + } else { + inheritedReference, err := currentSchema.ref.Inherits(jsonReference) + if err != nil { + return err + } + currentSchema.ref = inheritedReference + } + + jsonPointer := currentSchema.ref.GetPointer() + + var refdDocumentNode interface{} + + if standaloneDocument != nil { + + var err error + refdDocumentNode, _, err = jsonPointer.Get(standaloneDocument) + if err != nil { + return err + } + + } else { + + var err error + dsp, err := d.pool.GetDocument(*currentSchema.ref) + if err != nil { + return err + } + + refdDocumentNode, _, err = jsonPointer.Get(dsp.Document) + if err != nil { + return err + } + + } + + if !isKind(refdDocumentNode, reflect.Map) { + return errors.New(formatErrorDescription( + Locale.MustBeOfType(), + ErrorDetails{"key": STRING_SCHEMA, "type": TYPE_OBJECT}, + )) + } + + // returns the loaded referenced subSchema for the caller to update its current subSchema + newSchemaDocument := refdDocumentNode.(map[string]interface{}) + + newSchema := &subSchema{property: KEY_REF, parent: currentSchema, ref: currentSchema.ref} + d.referencePool.Add(currentSchema.ref.String()+reference, newSchema) + + err = d.parseSchema(newSchemaDocument, newSchema) + if err != nil { + return err + } + + currentSchema.refSchema = newSchema + + return nil + +} + +func (d *Schema) parseProperties(documentNode interface{}, currentSchema *subSchema) error { + + if !isKind(documentNode, reflect.Map) { + return errors.New(formatErrorDescription( + Locale.MustBeOfType(), + ErrorDetails{"key": STRING_PROPERTIES, "type": TYPE_OBJECT}, + )) + } + + m := documentNode.(map[string]interface{}) + for k := range m { + schemaProperty := k + newSchema := &subSchema{property: schemaProperty, parent: currentSchema, ref: currentSchema.ref} + currentSchema.AddPropertiesChild(newSchema) + err := d.parseSchema(m[k], newSchema) + if err != nil { + return err + } + } + + return nil +} + +func (d *Schema) parseDependencies(documentNode interface{}, currentSchema *subSchema) error { + + if !isKind(documentNode, reflect.Map) { + return errors.New(formatErrorDescription( + Locale.MustBeOfType(), + ErrorDetails{"key": KEY_DEPENDENCIES, "type": TYPE_OBJECT}, + )) + } + + m := documentNode.(map[string]interface{}) + currentSchema.dependencies = make(map[string]interface{}) + + for k := range m { + switch reflect.ValueOf(m[k]).Kind() { + + case reflect.Slice: + values := m[k].([]interface{}) + var valuesToRegister []string + + for _, value := range values { + if !isKind(value, reflect.String) { + return errors.New(formatErrorDescription( + Locale.MustBeOfType(), + ErrorDetails{ + "key": STRING_DEPENDENCY, + "type": STRING_SCHEMA_OR_ARRAY_OF_STRINGS, + }, + )) + } else { + valuesToRegister = append(valuesToRegister, value.(string)) + } + currentSchema.dependencies[k] = valuesToRegister + } + + case reflect.Map: + depSchema := &subSchema{property: k, parent: currentSchema, ref: currentSchema.ref} + err := d.parseSchema(m[k], depSchema) + if err != nil { + return err + } + currentSchema.dependencies[k] = depSchema + + default: + return errors.New(formatErrorDescription( + Locale.MustBeOfType(), + ErrorDetails{ + "key": STRING_DEPENDENCY, + "type": STRING_SCHEMA_OR_ARRAY_OF_STRINGS, + }, + )) + } + + } + + return nil +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/schemaPool.go b/vendor/github.com/xeipuuv/gojsonschema/schemaPool.go new file mode 100644 index 00000000..70ae7318 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/schemaPool.go @@ -0,0 +1,110 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// 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. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Defines resources pooling. +// Eases referencing and avoids downloading the same resource twice. +// +// created 26-02-2013 + +package gojsonschema + +import ( + "errors" + "net/http" + + "github.com/xeipuuv/gojsonreference" +) + +type schemaPoolDocument struct { + Document interface{} +} + +type schemaPool struct { + schemaPoolDocuments map[string]*schemaPoolDocument + standaloneDocument interface{} + fs http.FileSystem +} + +func newSchemaPool(fs http.FileSystem) *schemaPool { + + p := &schemaPool{} + p.schemaPoolDocuments = make(map[string]*schemaPoolDocument) + p.standaloneDocument = nil + p.fs = fs + + return p +} + +func (p *schemaPool) SetStandaloneDocument(document interface{}) { + p.standaloneDocument = document +} + +func (p *schemaPool) GetStandaloneDocument() (document interface{}) { + return p.standaloneDocument +} + +func (p *schemaPool) GetDocument(reference gojsonreference.JsonReference) (*schemaPoolDocument, error) { + + if internalLogEnabled { + internalLog("Get Document ( %s )", reference.String()) + } + + var err error + + // It is not possible to load anything that is not canonical... + if !reference.IsCanonical() { + return nil, errors.New(formatErrorDescription( + Locale.ReferenceMustBeCanonical(), + ErrorDetails{"reference": reference}, + )) + } + + refToUrl := reference + refToUrl.GetUrl().Fragment = "" + + var spd *schemaPoolDocument + + // Try to find the requested document in the pool + for k := range p.schemaPoolDocuments { + if k == refToUrl.String() { + spd = p.schemaPoolDocuments[k] + } + } + + if spd != nil { + if internalLogEnabled { + internalLog(" From pool") + } + return spd, nil + } + + jsonReferenceLoader := NewReferenceLoaderFileSystem(reference.String(), p.fs) + document, err := jsonReferenceLoader.loadJSON() + if err != nil { + return nil, err + } + + spd = &schemaPoolDocument{Document: document} + // add the document to the pool for potential later use + p.schemaPoolDocuments[refToUrl.String()] = spd + + return spd, nil +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/schemaReferencePool.go b/vendor/github.com/xeipuuv/gojsonschema/schemaReferencePool.go new file mode 100644 index 00000000..294e36a7 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/schemaReferencePool.go @@ -0,0 +1,67 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// 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. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Pool of referenced schemas. +// +// created 25-06-2013 + +package gojsonschema + +import ( + "fmt" +) + +type schemaReferencePool struct { + documents map[string]*subSchema +} + +func newSchemaReferencePool() *schemaReferencePool { + + p := &schemaReferencePool{} + p.documents = make(map[string]*subSchema) + + return p +} + +func (p *schemaReferencePool) Get(ref string) (r *subSchema, o bool) { + + if internalLogEnabled { + internalLog(fmt.Sprintf("Schema Reference ( %s )", ref)) + } + + if sch, ok := p.documents[ref]; ok { + if internalLogEnabled { + internalLog(fmt.Sprintf(" From pool")) + } + return sch, true + } + + return nil, false +} + +func (p *schemaReferencePool) Add(ref string, sch *subSchema) { + + if internalLogEnabled { + internalLog(fmt.Sprintf("Add Schema Reference %s to pool", ref)) + } + + p.documents[ref] = sch +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/schemaType.go b/vendor/github.com/xeipuuv/gojsonschema/schemaType.go new file mode 100644 index 00000000..e13a0fb0 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/schemaType.go @@ -0,0 +1,83 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// 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. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Helper structure to handle schema types, and the combination of them. +// +// created 28-02-2013 + +package gojsonschema + +import ( + "errors" + "fmt" + "strings" +) + +type jsonSchemaType struct { + types []string +} + +// Is the schema typed ? that is containing at least one type +// When not typed, the schema does not need any type validation +func (t *jsonSchemaType) IsTyped() bool { + return len(t.types) > 0 +} + +func (t *jsonSchemaType) Add(etype string) error { + + if !isStringInSlice(JSON_TYPES, etype) { + return errors.New(formatErrorDescription(Locale.NotAValidType(), ErrorDetails{"type": etype})) + } + + if t.Contains(etype) { + return errors.New(formatErrorDescription(Locale.Duplicated(), ErrorDetails{"type": etype})) + } + + t.types = append(t.types, etype) + + return nil +} + +func (t *jsonSchemaType) Contains(etype string) bool { + + for _, v := range t.types { + if v == etype { + return true + } + } + + return false +} + +func (t *jsonSchemaType) String() string { + + if len(t.types) == 0 { + return STRING_UNDEFINED // should never happen + } + + // Displayed as a list [type1,type2,...] + if len(t.types) > 1 { + return fmt.Sprintf("[%s]", strings.Join(t.types, ",")) + } + + // Only one type: name only + return t.types[0] +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/schema_test.go b/vendor/github.com/xeipuuv/gojsonschema/schema_test.go new file mode 100644 index 00000000..2a1832c5 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/schema_test.go @@ -0,0 +1,416 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// 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. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description (Unit) Tests for schema validation. +// +// created 16-06-2013 + +package gojsonschema + +import ( + "fmt" + "net/http" + "os" + "reflect" + "regexp" + "sort" + "strconv" + "strings" + "testing" +) + +const displayErrorMessages = false + +var rxInvoice = regexp.MustCompile("^[A-Z]{2}-[0-9]{5}") +var rxSplitErrors = regexp.MustCompile(", ?") + +// Used for remote schema in ref/schema_5.json that defines "uri" and "regex" types +type alwaysTrueFormatChecker struct{} +type invoiceFormatChecker struct{} + +func (a alwaysTrueFormatChecker) IsFormat(input string) bool { + return true +} + +func (a invoiceFormatChecker) IsFormat(input string) bool { + return rxInvoice.MatchString(input) +} + +func TestJsonSchemaTestSuite(t *testing.T) { + + JsonSchemaTestSuiteMap := []map[string]string{ + + map[string]string{"phase": "integer type matches integers", "test": "an integer is an integer", "schema": "type/schema_0.json", "data": "type/data_00.json", "valid": "true"}, + map[string]string{"phase": "integer type matches integers", "test": "a float is not an integer", "schema": "type/schema_0.json", "data": "type/data_01.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "integer type matches integers", "test": "a string is not an integer", "schema": "type/schema_0.json", "data": "type/data_02.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "integer type matches integers", "test": "an object is not an integer", "schema": "type/schema_0.json", "data": "type/data_03.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "integer type matches integers", "test": "an array is not an integer", "schema": "type/schema_0.json", "data": "type/data_04.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "integer type matches integers", "test": "a boolean is not an integer", "schema": "type/schema_0.json", "data": "type/data_05.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "integer type matches integers", "test": "null is not an integer", "schema": "type/schema_0.json", "data": "type/data_06.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "number type matches numbers", "test": "an integer is a number", "schema": "type/schema_1.json", "data": "type/data_10.json", "valid": "true"}, + map[string]string{"phase": "number type matches numbers", "test": "a float is a number", "schema": "type/schema_1.json", "data": "type/data_11.json", "valid": "true"}, + map[string]string{"phase": "number type matches numbers", "test": "a string is not a number", "schema": "type/schema_1.json", "data": "type/data_12.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "number type matches numbers", "test": "an object is not a number", "schema": "type/schema_1.json", "data": "type/data_13.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "number type matches numbers", "test": "an array is not a number", "schema": "type/schema_1.json", "data": "type/data_14.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "number type matches numbers", "test": "a boolean is not a number", "schema": "type/schema_1.json", "data": "type/data_15.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "number type matches numbers", "test": "null is not a number", "schema": "type/schema_1.json", "data": "type/data_16.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "string type matches strings", "test": "1 is not a string", "schema": "type/schema_2.json", "data": "type/data_20.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "string type matches strings", "test": "a float is not a string", "schema": "type/schema_2.json", "data": "type/data_21.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "string type matches strings", "test": "a string is a string", "schema": "type/schema_2.json", "data": "type/data_22.json", "valid": "true"}, + map[string]string{"phase": "string type matches strings", "test": "an object is not a string", "schema": "type/schema_2.json", "data": "type/data_23.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "string type matches strings", "test": "an array is not a string", "schema": "type/schema_2.json", "data": "type/data_24.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "string type matches strings", "test": "a boolean is not a string", "schema": "type/schema_2.json", "data": "type/data_25.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "string type matches strings", "test": "null is not a string", "schema": "type/schema_2.json", "data": "type/data_26.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "object type matches objects", "test": "an integer is not an object", "schema": "type/schema_3.json", "data": "type/data_30.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "object type matches objects", "test": "a float is not an object", "schema": "type/schema_3.json", "data": "type/data_31.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "object type matches objects", "test": "a string is not an object", "schema": "type/schema_3.json", "data": "type/data_32.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "object type matches objects", "test": "an object is an object", "schema": "type/schema_3.json", "data": "type/data_33.json", "valid": "true"}, + map[string]string{"phase": "object type matches objects", "test": "an array is not an object", "schema": "type/schema_3.json", "data": "type/data_34.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "object type matches objects", "test": "a boolean is not an object", "schema": "type/schema_3.json", "data": "type/data_35.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "object type matches objects", "test": "null is not an object", "schema": "type/schema_3.json", "data": "type/data_36.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "array type matches arrays", "test": "an integer is not an array", "schema": "type/schema_4.json", "data": "type/data_40.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "array type matches arrays", "test": "a float is not an array", "schema": "type/schema_4.json", "data": "type/data_41.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "array type matches arrays", "test": "a string is not an array", "schema": "type/schema_4.json", "data": "type/data_42.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "array type matches arrays", "test": "an object is not an array", "schema": "type/schema_4.json", "data": "type/data_43.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "array type matches arrays", "test": "an array is not an array", "schema": "type/schema_4.json", "data": "type/data_44.json", "valid": "true"}, + map[string]string{"phase": "array type matches arrays", "test": "a boolean is not an array", "schema": "type/schema_4.json", "data": "type/data_45.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "array type matches arrays", "test": "null is not an array", "schema": "type/schema_4.json", "data": "type/data_46.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "boolean type matches booleans", "test": "an integer is not a boolean", "schema": "type/schema_5.json", "data": "type/data_50.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "boolean type matches booleans", "test": "a float is not a boolean", "schema": "type/schema_5.json", "data": "type/data_51.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "boolean type matches booleans", "test": "a string is not a boolean", "schema": "type/schema_5.json", "data": "type/data_52.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "boolean type matches booleans", "test": "an object is not a boolean", "schema": "type/schema_5.json", "data": "type/data_53.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "boolean type matches booleans", "test": "an array is not a boolean", "schema": "type/schema_5.json", "data": "type/data_54.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "boolean type matches booleans", "test": "a boolean is not a boolean", "schema": "type/schema_5.json", "data": "type/data_55.json", "valid": "true", "errors": "invalid_type"}, + map[string]string{"phase": "boolean type matches booleans", "test": "null is not a boolean", "schema": "type/schema_5.json", "data": "type/data_56.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "null type matches only the null object", "test": "an integer is not null", "schema": "type/schema_6.json", "data": "type/data_60.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "null type matches only the null object", "test": "a float is not null", "schema": "type/schema_6.json", "data": "type/data_61.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "null type matches only the null object", "test": "a string is not null", "schema": "type/schema_6.json", "data": "type/data_62.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "null type matches only the null object", "test": "an object is not null", "schema": "type/schema_6.json", "data": "type/data_63.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "null type matches only the null object", "test": "an array is not null", "schema": "type/schema_6.json", "data": "type/data_64.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "null type matches only the null object", "test": "a boolean is not null", "schema": "type/schema_6.json", "data": "type/data_65.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "null type matches only the null object", "test": "null is null", "schema": "type/schema_6.json", "data": "type/data_66.json", "valid": "true"}, + map[string]string{"phase": "multiple types can be specified in an array", "test": "an integer is valid", "schema": "type/schema_7.json", "data": "type/data_70.json", "valid": "true"}, + map[string]string{"phase": "multiple types can be specified in an array", "test": "a string is valid", "schema": "type/schema_7.json", "data": "type/data_71.json", "valid": "true"}, + map[string]string{"phase": "multiple types can be specified in an array", "test": "a float is invalid", "schema": "type/schema_7.json", "data": "type/data_72.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "multiple types can be specified in an array", "test": "an object is invalid", "schema": "type/schema_7.json", "data": "type/data_73.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "multiple types can be specified in an array", "test": "an array is invalid", "schema": "type/schema_7.json", "data": "type/data_74.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "multiple types can be specified in an array", "test": "a boolean is invalid", "schema": "type/schema_7.json", "data": "type/data_75.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "multiple types can be specified in an array", "test": "null is invalid", "schema": "type/schema_7.json", "data": "type/data_76.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "required validation", "test": "present required property is valid", "schema": "required/schema_0.json", "data": "required/data_00.json", "valid": "true"}, + map[string]string{"phase": "required validation", "test": "non-present required property is invalid", "schema": "required/schema_0.json", "data": "required/data_01.json", "valid": "false", "errors": "required"}, + map[string]string{"phase": "required default validation", "test": "not required by default", "schema": "required/schema_1.json", "data": "required/data_10.json", "valid": "true"}, + map[string]string{"phase": "uniqueItems validation", "test": "unique array of integers is valid", "schema": "uniqueItems/schema_0.json", "data": "uniqueItems/data_00.json", "valid": "true"}, + map[string]string{"phase": "uniqueItems validation", "test": "non-unique array of integers is invalid", "schema": "uniqueItems/schema_0.json", "data": "uniqueItems/data_01.json", "valid": "false", "errors": "unique"}, + map[string]string{"phase": "uniqueItems validation", "test": "numbers are unique if mathematically unequal", "schema": "uniqueItems/schema_0.json", "data": "uniqueItems/data_02.json", "valid": "false", "errors": "unique, unique"}, + map[string]string{"phase": "uniqueItems validation", "test": "unique array of objects is valid", "schema": "uniqueItems/schema_0.json", "data": "uniqueItems/data_03.json", "valid": "true"}, + map[string]string{"phase": "uniqueItems validation", "test": "non-unique array of objects is invalid", "schema": "uniqueItems/schema_0.json", "data": "uniqueItems/data_04.json", "valid": "false", "errors": "unique"}, + map[string]string{"phase": "uniqueItems validation", "test": "unique array of nested objects is valid", "schema": "uniqueItems/schema_0.json", "data": "uniqueItems/data_05.json", "valid": "true"}, + map[string]string{"phase": "uniqueItems validation", "test": "non-unique array of nested objects is invalid", "schema": "uniqueItems/schema_0.json", "data": "uniqueItems/data_06.json", "valid": "false", "errors": "unique"}, + map[string]string{"phase": "uniqueItems validation", "test": "unique array of arrays is valid", "schema": "uniqueItems/schema_0.json", "data": "uniqueItems/data_07.json", "valid": "true"}, + map[string]string{"phase": "uniqueItems validation", "test": "non-unique array of arrays is invalid", "schema": "uniqueItems/schema_0.json", "data": "uniqueItems/data_08.json", "valid": "false", "errors": "unique"}, + map[string]string{"phase": "uniqueItems validation", "test": "1 and true are unique", "schema": "uniqueItems/schema_0.json", "data": "uniqueItems/data_09.json", "valid": "true"}, + map[string]string{"phase": "uniqueItems validation", "test": "0 and false are unique", "schema": "uniqueItems/schema_0.json", "data": "uniqueItems/data_010.json", "valid": "true"}, + map[string]string{"phase": "uniqueItems validation", "test": "unique heterogeneous types are valid", "schema": "uniqueItems/schema_0.json", "data": "uniqueItems/data_011.json", "valid": "true"}, + map[string]string{"phase": "uniqueItems validation", "test": "non-unique heterogeneous types are invalid", "schema": "uniqueItems/schema_0.json", "data": "uniqueItems/data_012.json", "valid": "false", "errors": "unique"}, + map[string]string{"phase": "pattern validation", "test": "a matching pattern is valid", "schema": "pattern/schema_0.json", "data": "pattern/data_00.json", "valid": "true"}, + map[string]string{"phase": "pattern validation", "test": "a non-matching pattern is invalid", "schema": "pattern/schema_0.json", "data": "pattern/data_01.json", "valid": "false", "errors": "pattern"}, + map[string]string{"phase": "pattern validation", "test": "ignores non-strings", "schema": "pattern/schema_0.json", "data": "pattern/data_02.json", "valid": "true"}, + map[string]string{"phase": "simple enum validation", "test": "one of the enum is valid", "schema": "enum/schema_0.json", "data": "enum/data_00.json", "valid": "true"}, + map[string]string{"phase": "simple enum validation", "test": "something else is invalid", "schema": "enum/schema_0.json", "data": "enum/data_01.json", "valid": "false", "errors": "enum"}, + map[string]string{"phase": "heterogeneous enum validation", "test": "one of the enum is valid", "schema": "enum/schema_1.json", "data": "enum/data_10.json", "valid": "true"}, + map[string]string{"phase": "heterogeneous enum validation", "test": "something else is invalid", "schema": "enum/schema_1.json", "data": "enum/data_11.json", "valid": "false", "errors": "enum"}, + map[string]string{"phase": "heterogeneous enum validation", "test": "objects are deep compared", "schema": "enum/schema_1.json", "data": "enum/data_12.json", "valid": "false", "errors": "enum"}, + map[string]string{"phase": "minLength validation", "test": "longer is valid", "schema": "minLength/schema_0.json", "data": "minLength/data_00.json", "valid": "true"}, + map[string]string{"phase": "minLength validation", "test": "exact length is valid", "schema": "minLength/schema_0.json", "data": "minLength/data_01.json", "valid": "true"}, + map[string]string{"phase": "minLength validation", "test": "too short is invalid", "schema": "minLength/schema_0.json", "data": "minLength/data_02.json", "valid": "false", "errors": "string_gte"}, + map[string]string{"phase": "minLength validation", "test": "ignores non-strings", "schema": "minLength/schema_0.json", "data": "minLength/data_03.json", "valid": "true"}, + map[string]string{"phase": "minLength validation", "test": "counts utf8 length correctly", "schema": "minLength/schema_0.json", "data": "minLength/data_04.json", "valid": "false", "errors": "string_gte"}, + map[string]string{"phase": "maxLength validation", "test": "shorter is valid", "schema": "maxLength/schema_0.json", "data": "maxLength/data_00.json", "valid": "true"}, + map[string]string{"phase": "maxLength validation", "test": "exact length is valid", "schema": "maxLength/schema_0.json", "data": "maxLength/data_01.json", "valid": "true"}, + map[string]string{"phase": "maxLength validation", "test": "too long is invalid", "schema": "maxLength/schema_0.json", "data": "maxLength/data_02.json", "valid": "false", "errors": "string_lte"}, + map[string]string{"phase": "maxLength validation", "test": "ignores non-strings", "schema": "maxLength/schema_0.json", "data": "maxLength/data_03.json", "valid": "true"}, + map[string]string{"phase": "maxLength validation", "test": "counts utf8 length correctly", "schema": "maxLength/schema_0.json", "data": "maxLength/data_04.json", "valid": "true"}, + map[string]string{"phase": "minimum validation", "test": "above the minimum is valid", "schema": "minimum/schema_0.json", "data": "minimum/data_00.json", "valid": "true"}, + map[string]string{"phase": "minimum validation", "test": "below the minimum is invalid", "schema": "minimum/schema_0.json", "data": "minimum/data_01.json", "valid": "false", "errors": "number_gte"}, + map[string]string{"phase": "minimum validation", "test": "ignores non-numbers", "schema": "minimum/schema_0.json", "data": "minimum/data_02.json", "valid": "true"}, + map[string]string{"phase": "exclusiveMinimum validation", "test": "above the minimum is still valid", "schema": "minimum/schema_1.json", "data": "minimum/data_10.json", "valid": "true"}, + map[string]string{"phase": "exclusiveMinimum validation", "test": "boundary point is invalid", "schema": "minimum/schema_1.json", "data": "minimum/data_11.json", "valid": "false", "errors": "number_gt"}, + map[string]string{"phase": "maximum validation", "test": "below the maximum is valid", "schema": "maximum/schema_0.json", "data": "maximum/data_00.json", "valid": "true"}, + map[string]string{"phase": "maximum validation", "test": "above the maximum is invalid", "schema": "maximum/schema_0.json", "data": "maximum/data_01.json", "valid": "false", "errors": "number_lte"}, + map[string]string{"phase": "maximum validation", "test": "ignores non-numbers", "schema": "maximum/schema_0.json", "data": "maximum/data_02.json", "valid": "true"}, + map[string]string{"phase": "exclusiveMaximum validation", "test": "below the maximum is still valid", "schema": "maximum/schema_1.json", "data": "maximum/data_10.json", "valid": "true"}, + map[string]string{"phase": "exclusiveMaximum validation", "test": "boundary point is invalid", "schema": "maximum/schema_1.json", "data": "maximum/data_11.json", "valid": "false", "errors": "number_lt"}, + map[string]string{"phase": "allOf", "test": "allOf", "schema": "allOf/schema_0.json", "data": "allOf/data_00.json", "valid": "true"}, + map[string]string{"phase": "allOf", "test": "mismatch second", "schema": "allOf/schema_0.json", "data": "allOf/data_01.json", "valid": "false", "errors": "number_all_of, required"}, + map[string]string{"phase": "allOf", "test": "mismatch first", "schema": "allOf/schema_0.json", "data": "allOf/data_02.json", "valid": "false", "errors": "number_all_of, required"}, + map[string]string{"phase": "allOf", "test": "wrong type", "schema": "allOf/schema_0.json", "data": "allOf/data_03.json", "valid": "false", "errors": "number_all_of, invalid_type"}, + map[string]string{"phase": "allOf with base schema", "test": "valid", "schema": "allOf/schema_1.json", "data": "allOf/data_10.json", "valid": "true"}, + map[string]string{"phase": "allOf with base schema", "test": "mismatch base schema", "schema": "allOf/schema_1.json", "data": "allOf/data_11.json", "valid": "false", "errors": "required"}, + map[string]string{"phase": "allOf with base schema", "test": "mismatch first allOf", "schema": "allOf/schema_1.json", "data": "allOf/data_12.json", "valid": "false", "errors": "number_all_of, required"}, + map[string]string{"phase": "allOf with base schema", "test": "mismatch second allOf", "schema": "allOf/schema_1.json", "data": "allOf/data_13.json", "valid": "false", "errors": "number_all_of, required"}, + map[string]string{"phase": "allOf with base schema", "test": "mismatch both", "schema": "allOf/schema_1.json", "data": "allOf/data_14.json", "valid": "false", "errors": "number_all_of, required, required"}, + map[string]string{"phase": "allOf simple types", "test": "valid", "schema": "allOf/schema_2.json", "data": "allOf/data_20.json", "valid": "true"}, + map[string]string{"phase": "allOf simple types", "test": "mismatch one", "schema": "allOf/schema_2.json", "data": "allOf/data_21.json", "valid": "false", "errors": "number_all_of, number_lte"}, + map[string]string{"phase": "oneOf", "test": "first oneOf valid", "schema": "oneOf/schema_0.json", "data": "oneOf/data_00.json", "valid": "true"}, + map[string]string{"phase": "oneOf", "test": "second oneOf valid", "schema": "oneOf/schema_0.json", "data": "oneOf/data_01.json", "valid": "true"}, + map[string]string{"phase": "oneOf", "test": "both oneOf valid", "schema": "oneOf/schema_0.json", "data": "oneOf/data_02.json", "valid": "false", "errors": "number_one_of"}, + map[string]string{"phase": "oneOf", "test": "neither oneOf valid", "schema": "oneOf/schema_0.json", "data": "oneOf/data_03.json", "valid": "false"}, + map[string]string{"phase": "oneOf with base schema", "test": "mismatch base schema", "schema": "oneOf/schema_1.json", "data": "oneOf/data_10.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "oneOf with base schema", "test": "one oneOf valid", "schema": "oneOf/schema_1.json", "data": "oneOf/data_11.json", "valid": "true"}, + map[string]string{"phase": "oneOf with base schema", "test": "both oneOf valid", "schema": "oneOf/schema_1.json", "data": "oneOf/data_12.json", "valid": "false", "errors": "number_one_of"}, + map[string]string{"phase": "anyOf", "test": "first anyOf valid", "schema": "anyOf/schema_0.json", "data": "anyOf/data_00.json", "valid": "true"}, + map[string]string{"phase": "anyOf", "test": "second anyOf valid", "schema": "anyOf/schema_0.json", "data": "anyOf/data_01.json", "valid": "true"}, + map[string]string{"phase": "anyOf", "test": "both anyOf valid", "schema": "anyOf/schema_0.json", "data": "anyOf/data_02.json", "valid": "true"}, + map[string]string{"phase": "anyOf", "test": "neither anyOf valid", "schema": "anyOf/schema_0.json", "data": "anyOf/data_03.json", "valid": "false", "errors": "number_any_of, number_gte"}, + map[string]string{"phase": "anyOf with base schema", "test": "mismatch base schema", "schema": "anyOf/schema_1.json", "data": "anyOf/data_10.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "anyOf with base schema", "test": "one anyOf valid", "schema": "anyOf/schema_1.json", "data": "anyOf/data_11.json", "valid": "true"}, + map[string]string{"phase": "anyOf with base schema", "test": "both anyOf invalid", "schema": "anyOf/schema_1.json", "data": "anyOf/data_12.json", "valid": "false", "errors": "number_any_of, string_lte"}, + map[string]string{"phase": "not", "test": "allowed", "schema": "not/schema_0.json", "data": "not/data_00.json", "valid": "true"}, + map[string]string{"phase": "not", "test": "disallowed", "schema": "not/schema_0.json", "data": "not/data_01.json", "valid": "false", "errors": "number_not"}, + map[string]string{"phase": "not multiple types", "test": "valid", "schema": "not/schema_1.json", "data": "not/data_10.json", "valid": "true"}, + map[string]string{"phase": "not multiple types", "test": "mismatch", "schema": "not/schema_1.json", "data": "not/data_11.json", "valid": "false", "errors": "number_not"}, + map[string]string{"phase": "not multiple types", "test": "other mismatch", "schema": "not/schema_1.json", "data": "not/data_12.json", "valid": "false", "errors": "number_not"}, + map[string]string{"phase": "not more complex schema", "test": "match", "schema": "not/schema_2.json", "data": "not/data_20.json", "valid": "true"}, + map[string]string{"phase": "not more complex schema", "test": "other match", "schema": "not/schema_2.json", "data": "not/data_21.json", "valid": "true"}, + map[string]string{"phase": "not more complex schema", "test": "mismatch", "schema": "not/schema_2.json", "data": "not/data_22.json", "valid": "false", "errors": "number_not"}, + map[string]string{"phase": "minProperties validation", "test": "longer is valid", "schema": "minProperties/schema_0.json", "data": "minProperties/data_00.json", "valid": "true"}, + map[string]string{"phase": "minProperties validation", "test": "exact length is valid", "schema": "minProperties/schema_0.json", "data": "minProperties/data_01.json", "valid": "true"}, + map[string]string{"phase": "minProperties validation", "test": "too short is invalid", "schema": "minProperties/schema_0.json", "data": "minProperties/data_02.json", "valid": "false", "errors": "array_min_properties"}, + map[string]string{"phase": "minProperties validation", "test": "ignores non-objects", "schema": "minProperties/schema_0.json", "data": "minProperties/data_03.json", "valid": "true"}, + map[string]string{"phase": "maxProperties validation", "test": "shorter is valid", "schema": "maxProperties/schema_0.json", "data": "maxProperties/data_00.json", "valid": "true"}, + map[string]string{"phase": "maxProperties validation", "test": "exact length is valid", "schema": "maxProperties/schema_0.json", "data": "maxProperties/data_01.json", "valid": "true"}, + map[string]string{"phase": "maxProperties validation", "test": "too long is invalid", "schema": "maxProperties/schema_0.json", "data": "maxProperties/data_02.json", "valid": "false", "errors": "array_max_properties"}, + map[string]string{"phase": "maxProperties validation", "test": "ignores non-objects", "schema": "maxProperties/schema_0.json", "data": "maxProperties/data_03.json", "valid": "true"}, + map[string]string{"phase": "by int", "test": "int by int", "schema": "multipleOf/schema_0.json", "data": "multipleOf/data_00.json", "valid": "true"}, + map[string]string{"phase": "by int", "test": "int by int fail", "schema": "multipleOf/schema_0.json", "data": "multipleOf/data_01.json", "valid": "false", "errors": "multiple_of"}, + map[string]string{"phase": "by int", "test": "ignores non-numbers", "schema": "multipleOf/schema_0.json", "data": "multipleOf/data_02.json", "valid": "true"}, + map[string]string{"phase": "by number", "test": "zero is multiple of anything", "schema": "multipleOf/schema_1.json", "data": "multipleOf/data_10.json", "valid": "true"}, + map[string]string{"phase": "by number", "test": "4.5 is multiple of 1.5", "schema": "multipleOf/schema_1.json", "data": "multipleOf/data_11.json", "valid": "true"}, + map[string]string{"phase": "by number", "test": "35 is not multiple of 1.5", "schema": "multipleOf/schema_1.json", "data": "multipleOf/data_12.json", "valid": "false", "errors": "multiple_of"}, + map[string]string{"phase": "by small number", "test": "0.0075 is multiple of 0.0001", "schema": "multipleOf/schema_2.json", "data": "multipleOf/data_20.json", "valid": "true"}, + map[string]string{"phase": "by small number", "test": "0.00751 is not multiple of 0.0001", "schema": "multipleOf/schema_2.json", "data": "multipleOf/data_21.json", "valid": "false", "errors": "multiple_of"}, + map[string]string{"phase": "minItems validation", "test": "longer is valid", "schema": "minItems/schema_0.json", "data": "minItems/data_00.json", "valid": "true"}, + map[string]string{"phase": "minItems validation", "test": "exact length is valid", "schema": "minItems/schema_0.json", "data": "minItems/data_01.json", "valid": "true"}, + map[string]string{"phase": "minItems validation", "test": "too short is invalid", "schema": "minItems/schema_0.json", "data": "minItems/data_02.json", "valid": "false", "errors": "array_min_items"}, + map[string]string{"phase": "minItems validation", "test": "ignores non-arrays", "schema": "minItems/schema_0.json", "data": "minItems/data_03.json", "valid": "true"}, + map[string]string{"phase": "maxItems validation", "test": "shorter is valid", "schema": "maxItems/schema_0.json", "data": "maxItems/data_00.json", "valid": "true"}, + map[string]string{"phase": "maxItems validation", "test": "exact length is valid", "schema": "maxItems/schema_0.json", "data": "maxItems/data_01.json", "valid": "true"}, + map[string]string{"phase": "maxItems validation", "test": "too long is invalid", "schema": "maxItems/schema_0.json", "data": "maxItems/data_02.json", "valid": "false", "errors": "array_max_items"}, + map[string]string{"phase": "maxItems validation", "test": "ignores non-arrays", "schema": "maxItems/schema_0.json", "data": "maxItems/data_03.json", "valid": "true"}, + map[string]string{"phase": "object properties validation", "test": "both properties present and valid is valid", "schema": "properties/schema_0.json", "data": "properties/data_00.json", "valid": "true"}, + map[string]string{"phase": "object properties validation", "test": "one property invalid is invalid", "schema": "properties/schema_0.json", "data": "properties/data_01.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "object properties validation", "test": "both properties invalid is invalid", "schema": "properties/schema_0.json", "data": "properties/data_02.json", "valid": "false", "errors": "invalid_type, invalid_type"}, + map[string]string{"phase": "object properties validation", "test": "doesn't invalidate other properties", "schema": "properties/schema_0.json", "data": "properties/data_03.json", "valid": "true"}, + map[string]string{"phase": "object properties validation", "test": "ignores non-objects", "schema": "properties/schema_0.json", "data": "properties/data_04.json", "valid": "true"}, + map[string]string{"phase": "properties, patternProperties, additionalProperties interaction", "test": "property validates property", "schema": "properties/schema_1.json", "data": "properties/data_10.json", "valid": "true"}, + map[string]string{"phase": "properties, patternProperties, additionalProperties interaction", "test": "property invalidates property", "schema": "properties/schema_1.json", "data": "properties/data_11.json", "valid": "false", "errors": "array_max_items"}, + map[string]string{"phase": "properties, patternProperties, additionalProperties interaction", "test": "patternProperty invalidates property", "schema": "properties/schema_1.json", "data": "properties/data_12.json", "valid": "false", "errors": "array_min_items, invalid_type"}, + map[string]string{"phase": "properties, patternProperties, additionalProperties interaction", "test": "patternProperty validates nonproperty", "schema": "properties/schema_1.json", "data": "properties/data_13.json", "valid": "true"}, + map[string]string{"phase": "properties, patternProperties, additionalProperties interaction", "test": "patternProperty invalidates nonproperty", "schema": "properties/schema_1.json", "data": "properties/data_14.json", "valid": "false", "errors": "array_min_items, invalid_type"}, + map[string]string{"phase": "properties, patternProperties, additionalProperties interaction", "test": "additionalProperty ignores property", "schema": "properties/schema_1.json", "data": "properties/data_15.json", "valid": "true"}, + map[string]string{"phase": "properties, patternProperties, additionalProperties interaction", "test": "additionalProperty validates others", "schema": "properties/schema_1.json", "data": "properties/data_16.json", "valid": "true"}, + map[string]string{"phase": "properties, patternProperties, additionalProperties interaction", "test": "additionalProperty invalidates others", "schema": "properties/schema_1.json", "data": "properties/data_17.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "root pointer ref", "test": "match", "schema": "ref/schema_0.json", "data": "ref/data_00.json", "valid": "true"}, + map[string]string{"phase": "root pointer ref", "test": "recursive match", "schema": "ref/schema_0.json", "data": "ref/data_01.json", "valid": "true"}, + map[string]string{"phase": "root pointer ref", "test": "mismatch", "schema": "ref/schema_0.json", "data": "ref/data_02.json", "valid": "false", "errors": "additional_property_not_allowed"}, + map[string]string{"phase": "root pointer ref", "test": "recursive mismatch", "schema": "ref/schema_0.json", "data": "ref/data_03.json", "valid": "false", "errors": "additional_property_not_allowed"}, + map[string]string{"phase": "relative pointer ref to object", "test": "match", "schema": "ref/schema_1.json", "data": "ref/data_10.json", "valid": "true"}, + map[string]string{"phase": "relative pointer ref to object", "test": "mismatch", "schema": "ref/schema_1.json", "data": "ref/data_11.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "relative pointer ref to array", "test": "match array", "schema": "ref/schema_2.json", "data": "ref/data_20.json", "valid": "true"}, + map[string]string{"phase": "relative pointer ref to array", "test": "mismatch array", "schema": "ref/schema_2.json", "data": "ref/data_21.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "escaped pointer ref", "test": "slash", "schema": "ref/schema_3.json", "data": "ref/data_30.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "escaped pointer ref", "test": "tilda", "schema": "ref/schema_3.json", "data": "ref/data_31.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "escaped pointer ref", "test": "percent", "schema": "ref/schema_3.json", "data": "ref/data_32.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "nested refs", "test": "nested ref valid", "schema": "ref/schema_4.json", "data": "ref/data_40.json", "valid": "true"}, + map[string]string{"phase": "nested refs", "test": "nested ref invalid", "schema": "ref/schema_4.json", "data": "ref/data_41.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "remote ref, containing refs itself", "test": "remote ref valid", "schema": "ref/schema_5.json", "data": "ref/data_50.json", "valid": "true"}, + map[string]string{"phase": "remote ref, containing refs itself", "test": "remote ref invalid", "schema": "ref/schema_5.json", "data": "ref/data_51.json", "valid": "false", "errors": "number_all_of, number_gte"}, + map[string]string{"phase": "a schema given for items", "test": "valid items", "schema": "items/schema_0.json", "data": "items/data_00.json", "valid": "true"}, + map[string]string{"phase": "a schema given for items", "test": "wrong type of items", "schema": "items/schema_0.json", "data": "items/data_01.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "a schema given for items", "test": "ignores non-arrays", "schema": "items/schema_0.json", "data": "items/data_02.json", "valid": "true"}, + map[string]string{"phase": "an array of schemas for items", "test": "correct types", "schema": "items/schema_1.json", "data": "items/data_10.json", "valid": "true"}, + map[string]string{"phase": "an array of schemas for items", "test": "wrong types", "schema": "items/schema_1.json", "data": "items/data_11.json", "valid": "false", "errors": "invalid_type, invalid_type"}, + map[string]string{"phase": "valid definition", "test": "valid definition schema", "schema": "definitions/schema_0.json", "data": "definitions/data_00.json", "valid": "true"}, + map[string]string{"phase": "invalid definition", "test": "invalid definition schema", "schema": "definitions/schema_1.json", "data": "definitions/data_10.json", "valid": "false", "errors": "number_any_of, enum"}, + map[string]string{"phase": "additionalItems as schema", "test": "additional items match schema", "schema": "additionalItems/schema_0.json", "data": "additionalItems/data_00.json", "valid": "true"}, + map[string]string{"phase": "additionalItems as schema", "test": "additional items do not match schema", "schema": "additionalItems/schema_0.json", "data": "additionalItems/data_01.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "items is schema, no additionalItems", "test": "all items match schema", "schema": "additionalItems/schema_1.json", "data": "additionalItems/data_10.json", "valid": "true"}, + map[string]string{"phase": "array of items with no additionalItems", "test": "no additional items present", "schema": "additionalItems/schema_2.json", "data": "additionalItems/data_20.json", "valid": "true"}, + map[string]string{"phase": "array of items with no additionalItems", "test": "additional items are not permitted", "schema": "additionalItems/schema_2.json", "data": "additionalItems/data_21.json", "valid": "false", "errors": "array_no_additional_items"}, + map[string]string{"phase": "additionalItems as false without items", "test": "items defaults to empty schema so everything is valid", "schema": "additionalItems/schema_3.json", "data": "additionalItems/data_30.json", "valid": "true"}, + map[string]string{"phase": "additionalItems as false without items", "test": "ignores non-arrays", "schema": "additionalItems/schema_3.json", "data": "additionalItems/data_31.json", "valid": "true"}, + map[string]string{"phase": "additionalItems are allowed by default", "test": "only the first item is validated", "schema": "additionalItems/schema_4.json", "data": "additionalItems/data_40.json", "valid": "true"}, + map[string]string{"phase": "additionalProperties being false does not allow other properties", "test": "no additional properties is valid", "schema": "additionalProperties/schema_0.json", "data": "additionalProperties/data_00.json", "valid": "true"}, + map[string]string{"phase": "additionalProperties being false does not allow other properties", "test": "an additional property is invalid", "schema": "additionalProperties/schema_0.json", "data": "additionalProperties/data_01.json", "valid": "false", "errors": "additional_property_not_allowed"}, + map[string]string{"phase": "additionalProperties being false does not allow other properties", "test": "ignores non-objects", "schema": "additionalProperties/schema_0.json", "data": "additionalProperties/data_02.json", "valid": "true"}, + map[string]string{"phase": "additionalProperties being false does not allow other properties", "test": "patternProperties are not additional properties", "schema": "additionalProperties/schema_0.json", "data": "additionalProperties/data_03.json", "valid": "true"}, + map[string]string{"phase": "additionalProperties allows a schema which should validate", "test": "no additional properties is valid", "schema": "additionalProperties/schema_1.json", "data": "additionalProperties/data_10.json", "valid": "true"}, + map[string]string{"phase": "additionalProperties allows a schema which should validate", "test": "an additional valid property is valid", "schema": "additionalProperties/schema_1.json", "data": "additionalProperties/data_11.json", "valid": "true"}, + map[string]string{"phase": "additionalProperties allows a schema which should validate", "test": "an additional invalid property is invalid", "schema": "additionalProperties/schema_1.json", "data": "additionalProperties/data_12.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "additionalProperties are allowed by default", "test": "additional properties are allowed", "schema": "additionalProperties/schema_2.json", "data": "additionalProperties/data_20.json", "valid": "true"}, + map[string]string{"phase": "dependencies", "test": "neither", "schema": "dependencies/schema_0.json", "data": "dependencies/data_00.json", "valid": "true"}, + map[string]string{"phase": "dependencies", "test": "nondependant", "schema": "dependencies/schema_0.json", "data": "dependencies/data_01.json", "valid": "true"}, + map[string]string{"phase": "dependencies", "test": "with dependency", "schema": "dependencies/schema_0.json", "data": "dependencies/data_02.json", "valid": "true"}, + map[string]string{"phase": "dependencies", "test": "missing dependency", "schema": "dependencies/schema_0.json", "data": "dependencies/data_03.json", "valid": "false", "errors": "missing_dependency"}, + map[string]string{"phase": "dependencies", "test": "ignores non-objects", "schema": "dependencies/schema_0.json", "data": "dependencies/data_04.json", "valid": "true"}, + map[string]string{"phase": "multiple dependencies", "test": "neither", "schema": "dependencies/schema_1.json", "data": "dependencies/data_10.json", "valid": "true"}, + map[string]string{"phase": "multiple dependencies", "test": "nondependants", "schema": "dependencies/schema_1.json", "data": "dependencies/data_11.json", "valid": "true"}, + map[string]string{"phase": "multiple dependencies", "test": "with dependencies", "schema": "dependencies/schema_1.json", "data": "dependencies/data_12.json", "valid": "true"}, + map[string]string{"phase": "multiple dependencies", "test": "missing dependency", "schema": "dependencies/schema_1.json", "data": "dependencies/data_13.json", "valid": "false", "errors": "missing_dependency"}, + map[string]string{"phase": "multiple dependencies", "test": "missing other dependency", "schema": "dependencies/schema_1.json", "data": "dependencies/data_14.json", "valid": "false", "errors": "missing_dependency"}, + map[string]string{"phase": "multiple dependencies", "test": "missing both dependencies", "schema": "dependencies/schema_1.json", "data": "dependencies/data_15.json", "valid": "false", "errors": "missing_dependency, missing_dependency"}, + map[string]string{"phase": "multiple dependencies subschema", "test": "valid", "schema": "dependencies/schema_2.json", "data": "dependencies/data_20.json", "valid": "true"}, + map[string]string{"phase": "multiple dependencies subschema", "test": "no dependency", "schema": "dependencies/schema_2.json", "data": "dependencies/data_21.json", "valid": "true"}, + map[string]string{"phase": "multiple dependencies subschema", "test": "wrong type", "schema": "dependencies/schema_2.json", "data": "dependencies/data_22.json", "valid": "false"}, + map[string]string{"phase": "multiple dependencies subschema", "test": "wrong type other", "schema": "dependencies/schema_2.json", "data": "dependencies/data_23.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "multiple dependencies subschema", "test": "wrong type both", "schema": "dependencies/schema_2.json", "data": "dependencies/data_24.json", "valid": "false", "errors": "invalid_type, invalid_type"}, + map[string]string{"phase": "patternProperties validates properties matching a regex", "test": "a single valid match is valid", "schema": "patternProperties/schema_0.json", "data": "patternProperties/data_00.json", "valid": "true"}, + map[string]string{"phase": "patternProperties validates properties matching a regex", "test": "multiple valid matches is valid", "schema": "patternProperties/schema_0.json", "data": "patternProperties/data_01.json", "valid": "true"}, + map[string]string{"phase": "patternProperties validates properties matching a regex", "test": "a single invalid match is invalid", "schema": "patternProperties/schema_0.json", "data": "patternProperties/data_02.json", "valid": "false", "errors": "invalid_property_pattern, invalid_type"}, + map[string]string{"phase": "patternProperties validates properties matching a regex", "test": "multiple invalid matches is invalid", "schema": "patternProperties/schema_0.json", "data": "patternProperties/data_03.json", "valid": "false", "errors": "invalid_property_pattern, invalid_property_pattern, invalid_type, invalid_type"}, + map[string]string{"phase": "patternProperties validates properties matching a regex", "test": "ignores non-objects", "schema": "patternProperties/schema_0.json", "data": "patternProperties/data_04.json", "valid": "true"}, + map[string]string{"phase": "patternProperties validates properties matching a regex", "test": "with additionalProperties combination", "schema": "patternProperties/schema_3.json", "data": "patternProperties/data_24.json", "valid": "false", "errors": "additional_property_not_allowed"}, + map[string]string{"phase": "patternProperties validates properties matching a regex", "test": "with additionalProperties combination", "schema": "patternProperties/schema_3.json", "data": "patternProperties/data_25.json", "valid": "false", "errors": "additional_property_not_allowed"}, + map[string]string{"phase": "patternProperties validates properties matching a regex", "test": "with additionalProperties combination", "schema": "patternProperties/schema_4.json", "data": "patternProperties/data_26.json", "valid": "false", "errors": "additional_property_not_allowed"}, + map[string]string{"phase": "multiple simultaneous patternProperties are validated", "test": "a single valid match is valid", "schema": "patternProperties/schema_1.json", "data": "patternProperties/data_10.json", "valid": "true"}, + map[string]string{"phase": "multiple simultaneous patternProperties are validated", "test": "a simultaneous match is valid", "schema": "patternProperties/schema_1.json", "data": "patternProperties/data_11.json", "valid": "true"}, + map[string]string{"phase": "multiple simultaneous patternProperties are validated", "test": "multiple matches is valid", "schema": "patternProperties/schema_1.json", "data": "patternProperties/data_12.json", "valid": "true"}, + map[string]string{"phase": "multiple simultaneous patternProperties are validated", "test": "an invalid due to one is invalid", "schema": "patternProperties/schema_1.json", "data": "patternProperties/data_13.json", "valid": "false", "errors": "invalid_property_pattern, invalid_type"}, + map[string]string{"phase": "multiple simultaneous patternProperties are validated", "test": "an invalid due to the other is invalid", "schema": "patternProperties/schema_1.json", "data": "patternProperties/data_14.json", "valid": "false", "errors": "number_lte"}, + map[string]string{"phase": "multiple simultaneous patternProperties are validated", "test": "an invalid due to both is invalid", "schema": "patternProperties/schema_1.json", "data": "patternProperties/data_15.json", "valid": "false", "errors": "invalid_type, number_lte"}, + map[string]string{"phase": "regexes are not anchored by default and are case sensitive", "test": "non recognized members are ignored", "schema": "patternProperties/schema_2.json", "data": "patternProperties/data_20.json", "valid": "true"}, + map[string]string{"phase": "regexes are not anchored by default and are case sensitive", "test": "recognized members are accounted for", "schema": "patternProperties/schema_2.json", "data": "patternProperties/data_21.json", "valid": "false", "errors": "invalid_property_pattern, invalid_type"}, + map[string]string{"phase": "regexes are not anchored by default and are case sensitive", "test": "regexes are case sensitive", "schema": "patternProperties/schema_2.json", "data": "patternProperties/data_22.json", "valid": "true"}, + map[string]string{"phase": "regexes are not anchored by default and are case sensitive", "test": "regexes are case sensitive, 2", "schema": "patternProperties/schema_2.json", "data": "patternProperties/data_23.json", "valid": "false", "errors": "invalid_property_pattern, invalid_type"}, + map[string]string{"phase": "remote ref", "test": "remote ref valid", "schema": "refRemote/schema_0.json", "data": "refRemote/data_00.json", "valid": "true"}, + map[string]string{"phase": "remote ref", "test": "remote ref invalid", "schema": "refRemote/schema_0.json", "data": "refRemote/data_01.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "fragment within remote ref", "test": "remote fragment valid", "schema": "refRemote/schema_1.json", "data": "refRemote/data_10.json", "valid": "true"}, + map[string]string{"phase": "fragment within remote ref", "test": "remote fragment invalid", "schema": "refRemote/schema_1.json", "data": "refRemote/data_11.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "ref within remote ref", "test": "ref within ref valid", "schema": "refRemote/schema_2.json", "data": "refRemote/data_20.json", "valid": "true"}, + map[string]string{"phase": "ref within remote ref", "test": "ref within ref invalid", "schema": "refRemote/schema_2.json", "data": "refRemote/data_21.json", "valid": "false", "errors": "invalid_type"}, + map[string]string{"phase": "format validation", "test": "email format is invalid", "schema": "format/schema_0.json", "data": "format/data_00.json", "valid": "false", "errors": "format"}, + map[string]string{"phase": "format validation", "test": "email format is invalid", "schema": "format/schema_0.json", "data": "format/data_01.json", "valid": "false", "errors": "format"}, + map[string]string{"phase": "format validation", "test": "email format valid", "schema": "format/schema_0.json", "data": "format/data_02.json", "valid": "true"}, + map[string]string{"phase": "format validation", "test": "invoice format valid", "schema": "format/schema_1.json", "data": "format/data_03.json", "valid": "true"}, + map[string]string{"phase": "format validation", "test": "invoice format is invalid", "schema": "format/schema_1.json", "data": "format/data_04.json", "valid": "false", "errors": "format"}, + map[string]string{"phase": "format validation", "test": "date-time format is valid", "schema": "format/schema_2.json", "data": "format/data_05.json", "valid": "true"}, + map[string]string{"phase": "format validation", "test": "date-time format is valid", "schema": "format/schema_2.json", "data": "format/data_06.json", "valid": "true"}, + map[string]string{"phase": "format validation", "test": "date-time format is invalid", "schema": "format/schema_2.json", "data": "format/data_07.json", "valid": "false", "errors": "format"}, + map[string]string{"phase": "format validation", "test": "date-time format is valid", "schema": "format/schema_2.json", "data": "format/data_08.json", "valid": "false", "errors": "format"}, + map[string]string{"phase": "format validation", "test": "date-time format is valid", "schema": "format/schema_2.json", "data": "format/data_09.json", "valid": "true"}, + map[string]string{"phase": "format validation", "test": "date-time format is valid", "schema": "format/schema_2.json", "data": "format/data_10.json", "valid": "true"}, + map[string]string{"phase": "format validation", "test": "date-time format is valid", "schema": "format/schema_2.json", "data": "format/data_11.json", "valid": "true"}, + map[string]string{"phase": "format validation", "test": "date-time format is valid", "schema": "format/schema_2.json", "data": "format/data_12.json", "valid": "true"}, + map[string]string{"phase": "format validation", "test": "hostname format is valid", "schema": "format/schema_3.json", "data": "format/data_13.json", "valid": "true"}, + map[string]string{"phase": "format validation", "test": "hostname format is valid", "schema": "format/schema_3.json", "data": "format/data_14.json", "valid": "true"}, + map[string]string{"phase": "format validation", "test": "hostname format is valid", "schema": "format/schema_3.json", "data": "format/data_15.json", "valid": "true"}, + map[string]string{"phase": "format validation", "test": "hostname format is invalid", "schema": "format/schema_3.json", "data": "format/data_16.json", "valid": "false", "errors": "format"}, + map[string]string{"phase": "format validation", "test": "hostname format is invalid", "schema": "format/schema_3.json", "data": "format/data_17.json", "valid": "false", "errors": "format"}, + map[string]string{"phase": "format validation", "test": "ipv4 format is valid", "schema": "format/schema_4.json", "data": "format/data_18.json", "valid": "true"}, + map[string]string{"phase": "format validation", "test": "ipv4 format is invalid", "schema": "format/schema_4.json", "data": "format/data_19.json", "valid": "false", "errors": "format"}, + map[string]string{"phase": "format validation", "test": "ipv6 format is valid", "schema": "format/schema_5.json", "data": "format/data_20.json", "valid": "true"}, + map[string]string{"phase": "format validation", "test": "ipv6 format is valid", "schema": "format/schema_5.json", "data": "format/data_21.json", "valid": "true"}, + map[string]string{"phase": "format validation", "test": "ipv6 format is invalid", "schema": "format/schema_5.json", "data": "format/data_22.json", "valid": "false", "errors": "format"}, + map[string]string{"phase": "format validation", "test": "ipv6 format is invalid", "schema": "format/schema_5.json", "data": "format/data_23.json", "valid": "false", "errors": "format"}, + map[string]string{"phase": "format validation", "test": "uri format is valid", "schema": "format/schema_6.json", "data": "format/data_24.json", "valid": "true"}, + map[string]string{"phase": "format validation", "test": "uri format is valid", "schema": "format/schema_6.json", "data": "format/data_25.json", "valid": "true"}, + map[string]string{"phase": "format validation", "test": "uri format is valid", "schema": "format/schema_6.json", "data": "format/data_26.json", "valid": "true"}, + map[string]string{"phase": "format validation", "test": "uri format is valid", "schema": "format/schema_6.json", "data": "format/data_27.json", "valid": "true"}, + map[string]string{"phase": "format validation", "test": "uri format is invalid", "schema": "format/schema_6.json", "data": "format/data_28.json", "valid": "false", "errors": "format"}, + map[string]string{"phase": "format validation", "test": "uri format is invalid", "schema": "format/schema_6.json", "data": "format/data_13.json", "valid": "false", "errors": "format"}, + } + + //TODO Pass failed tests : id(s) as scope for references is not implemented yet + //map[string]string{"phase": "change resolution scope", "test": "changed scope ref valid", "schema": "refRemote/schema_3.json", "data": "refRemote/data_30.json", "valid": "true"}, + //map[string]string{"phase": "change resolution scope", "test": "changed scope ref invalid", "schema": "refRemote/schema_3.json", "data": "refRemote/data_31.json", "valid": "false"}} + + // Setup a small http server on localhost:1234 for testing purposes + + wd, err := os.Getwd() + if err != nil { + panic(err.Error()) + } + + testwd := wd + "/json_schema_test_suite" + + go func() { + err := http.ListenAndServe(":1234", http.FileServer(http.Dir(testwd+"/refRemote/remoteFiles"))) + if err != nil { + panic(err.Error()) + } + }() + + // Used for remote schema in ref/schema_5.json that defines "regex" type + FormatCheckers.Add("regex", alwaysTrueFormatChecker{}) + + // Custom Formatter + FormatCheckers.Add("invoice", invoiceFormatChecker{}) + + // Launch tests + + for testJsonIndex, testJson := range JsonSchemaTestSuiteMap { + + fmt.Printf("Test (%d) | %s :: %s\n", testJsonIndex, testJson["phase"], testJson["test"]) + + schemaLoader := NewReferenceLoader("file://" + testwd + "/" + testJson["schema"]) + documentLoader := NewReferenceLoader("file://" + testwd + "/" + testJson["data"]) + + // validate + result, err := Validate(schemaLoader, documentLoader) + if err != nil { + t.Errorf("Error (%s)\n", err.Error()) + } + givenValid := result.Valid() + + if displayErrorMessages { + for vErrI, vErr := range result.Errors() { + fmt.Printf(" Error (%d) | %s\n", vErrI, vErr) + } + } + + expectedValid, _ := strconv.ParseBool(testJson["valid"]) + if givenValid != expectedValid { + t.Errorf("Test failed : %s :: %s, expects %t, given %t\n", testJson["phase"], testJson["test"], expectedValid, givenValid) + } + + if !givenValid && testJson["errors"] != "" { + expectedErrors := rxSplitErrors.Split(testJson["errors"], -1) + errors := result.Errors() + if len(errors) != len(expectedErrors) { + t.Errorf("Test failed : %s :: %s, expects %d errors, given %d errors\n", testJson["phase"], testJson["test"], len(expectedErrors), len(errors)) + } + + actualErrors := make([]string, 0) + for _, e := range result.Errors() { + actualErrors = append(actualErrors, e.Type()) + } + + sort.Strings(actualErrors) + sort.Strings(expectedErrors) + if !reflect.DeepEqual(actualErrors, expectedErrors) { + t.Errorf("Test failed : %s :: %s, expected '%s' errors, given '%s' errors\n", testJson["phase"], testJson["test"], strings.Join(expectedErrors, ", "), strings.Join(actualErrors, ", ")) + } + } + + } + + fmt.Printf("\n%d tests performed / %d total tests to perform ( %.2f %% )\n", len(JsonSchemaTestSuiteMap), 248, float32(len(JsonSchemaTestSuiteMap))/248.0*100.0) +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/subSchema.go b/vendor/github.com/xeipuuv/gojsonschema/subSchema.go new file mode 100644 index 00000000..b249b7e5 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/subSchema.go @@ -0,0 +1,227 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// 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. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Defines the structure of a sub-subSchema. +// A sub-subSchema can contain other sub-schemas. +// +// created 27-02-2013 + +package gojsonschema + +import ( + "errors" + "regexp" + "strings" + + "github.com/xeipuuv/gojsonreference" +) + +const ( + KEY_SCHEMA = "$subSchema" + KEY_ID = "$id" + KEY_REF = "$ref" + KEY_TITLE = "title" + KEY_DESCRIPTION = "description" + KEY_TYPE = "type" + KEY_ITEMS = "items" + KEY_ADDITIONAL_ITEMS = "additionalItems" + KEY_PROPERTIES = "properties" + KEY_PATTERN_PROPERTIES = "patternProperties" + KEY_ADDITIONAL_PROPERTIES = "additionalProperties" + KEY_DEFINITIONS = "definitions" + KEY_MULTIPLE_OF = "multipleOf" + KEY_MINIMUM = "minimum" + KEY_MAXIMUM = "maximum" + KEY_EXCLUSIVE_MINIMUM = "exclusiveMinimum" + KEY_EXCLUSIVE_MAXIMUM = "exclusiveMaximum" + KEY_MIN_LENGTH = "minLength" + KEY_MAX_LENGTH = "maxLength" + KEY_PATTERN = "pattern" + KEY_FORMAT = "format" + KEY_MIN_PROPERTIES = "minProperties" + KEY_MAX_PROPERTIES = "maxProperties" + KEY_DEPENDENCIES = "dependencies" + KEY_REQUIRED = "required" + KEY_MIN_ITEMS = "minItems" + KEY_MAX_ITEMS = "maxItems" + KEY_UNIQUE_ITEMS = "uniqueItems" + KEY_ENUM = "enum" + KEY_ONE_OF = "oneOf" + KEY_ANY_OF = "anyOf" + KEY_ALL_OF = "allOf" + KEY_NOT = "not" +) + +type subSchema struct { + + // basic subSchema meta properties + id *string + title *string + description *string + + property string + + // Types associated with the subSchema + types jsonSchemaType + + // Reference url + ref *gojsonreference.JsonReference + // Schema referenced + refSchema *subSchema + // Json reference + subSchema *gojsonreference.JsonReference + + // hierarchy + parent *subSchema + definitions map[string]*subSchema + definitionsChildren []*subSchema + itemsChildren []*subSchema + itemsChildrenIsSingleSchema bool + propertiesChildren []*subSchema + + // validation : number / integer + multipleOf *float64 + maximum *float64 + exclusiveMaximum bool + minimum *float64 + exclusiveMinimum bool + + // validation : string + minLength *int + maxLength *int + pattern *regexp.Regexp + format string + + // validation : object + minProperties *int + maxProperties *int + required []string + + dependencies map[string]interface{} + additionalProperties interface{} + patternProperties map[string]*subSchema + + // validation : array + minItems *int + maxItems *int + uniqueItems bool + + additionalItems interface{} + + // validation : all + enum []string + + // validation : subSchema + oneOf []*subSchema + anyOf []*subSchema + allOf []*subSchema + not *subSchema +} + +func (s *subSchema) AddEnum(i interface{}) error { + + is, err := marshalToJsonString(i) + if err != nil { + return err + } + + if isStringInSlice(s.enum, *is) { + return errors.New(formatErrorDescription( + Locale.KeyItemsMustBeUnique(), + ErrorDetails{"key": KEY_ENUM}, + )) + } + + s.enum = append(s.enum, *is) + + return nil +} + +func (s *subSchema) ContainsEnum(i interface{}) (bool, error) { + + is, err := marshalToJsonString(i) + if err != nil { + return false, err + } + + return isStringInSlice(s.enum, *is), nil +} + +func (s *subSchema) AddOneOf(subSchema *subSchema) { + s.oneOf = append(s.oneOf, subSchema) +} + +func (s *subSchema) AddAllOf(subSchema *subSchema) { + s.allOf = append(s.allOf, subSchema) +} + +func (s *subSchema) AddAnyOf(subSchema *subSchema) { + s.anyOf = append(s.anyOf, subSchema) +} + +func (s *subSchema) SetNot(subSchema *subSchema) { + s.not = subSchema +} + +func (s *subSchema) AddRequired(value string) error { + + if isStringInSlice(s.required, value) { + return errors.New(formatErrorDescription( + Locale.KeyItemsMustBeUnique(), + ErrorDetails{"key": KEY_REQUIRED}, + )) + } + + s.required = append(s.required, value) + + return nil +} + +func (s *subSchema) AddDefinitionChild(child *subSchema) { + s.definitionsChildren = append(s.definitionsChildren, child) +} + +func (s *subSchema) AddItemsChild(child *subSchema) { + s.itemsChildren = append(s.itemsChildren, child) +} + +func (s *subSchema) AddPropertiesChild(child *subSchema) { + s.propertiesChildren = append(s.propertiesChildren, child) +} + +func (s *subSchema) PatternPropertiesString() string { + + if s.patternProperties == nil || len(s.patternProperties) == 0 { + return STRING_UNDEFINED // should never happen + } + + patternPropertiesKeySlice := []string{} + for pk, _ := range s.patternProperties { + patternPropertiesKeySlice = append(patternPropertiesKeySlice, `"`+pk+`"`) + } + + if len(patternPropertiesKeySlice) == 1 { + return patternPropertiesKeySlice[0] + } + + return "[" + strings.Join(patternPropertiesKeySlice, ",") + "]" + +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/types.go b/vendor/github.com/xeipuuv/gojsonschema/types.go new file mode 100644 index 00000000..952d22ef --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/types.go @@ -0,0 +1,58 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// 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. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Contains const types for schema and JSON. +// +// created 28-02-2013 + +package gojsonschema + +const ( + TYPE_ARRAY = `array` + TYPE_BOOLEAN = `boolean` + TYPE_INTEGER = `integer` + TYPE_NUMBER = `number` + TYPE_NULL = `null` + TYPE_OBJECT = `object` + TYPE_STRING = `string` +) + +var JSON_TYPES []string +var SCHEMA_TYPES []string + +func init() { + JSON_TYPES = []string{ + TYPE_ARRAY, + TYPE_BOOLEAN, + TYPE_INTEGER, + TYPE_NUMBER, + TYPE_NULL, + TYPE_OBJECT, + TYPE_STRING} + + SCHEMA_TYPES = []string{ + TYPE_ARRAY, + TYPE_BOOLEAN, + TYPE_INTEGER, + TYPE_NUMBER, + TYPE_OBJECT, + TYPE_STRING} +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/utils.go b/vendor/github.com/xeipuuv/gojsonschema/utils.go new file mode 100644 index 00000000..4cbe0dcc --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/utils.go @@ -0,0 +1,203 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// 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. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Various utility functions. +// +// created 26-02-2013 + +package gojsonschema + +import ( + "encoding/json" + "fmt" + "math" + "reflect" + "strconv" +) + +func isKind(what interface{}, kind reflect.Kind) bool { + return reflect.ValueOf(what).Kind() == kind +} + +func existsMapKey(m map[string]interface{}, k string) bool { + _, ok := m[k] + return ok +} + +func isStringInSlice(s []string, what string) bool { + for i := range s { + if s[i] == what { + return true + } + } + return false +} + +func marshalToJsonString(value interface{}) (*string, error) { + + mBytes, err := json.Marshal(value) + if err != nil { + return nil, err + } + + sBytes := string(mBytes) + return &sBytes, nil +} + +func isJsonNumber(what interface{}) bool { + + switch what.(type) { + + case json.Number: + return true + } + + return false +} + +func checkJsonNumber(what interface{}) (isValidFloat64 bool, isValidInt64 bool, isValidInt32 bool) { + + jsonNumber := what.(json.Number) + + f64, errFloat64 := jsonNumber.Float64() + s64 := strconv.FormatFloat(f64, 'f', -1, 64) + _, errInt64 := strconv.ParseInt(s64, 10, 64) + + isValidFloat64 = errFloat64 == nil + isValidInt64 = errInt64 == nil + + _, errInt32 := strconv.ParseInt(s64, 10, 32) + isValidInt32 = isValidInt64 && errInt32 == nil + + return + +} + +// same as ECMA Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER +const ( + max_json_float = float64(1<<53 - 1) // 9007199254740991.0 2^53 - 1 + min_json_float = -float64(1<<53 - 1) //-9007199254740991.0 -2^53 - 1 +) + +func isFloat64AnInteger(f float64) bool { + + if math.IsNaN(f) || math.IsInf(f, 0) || f < min_json_float || f > max_json_float { + return false + } + + return f == float64(int64(f)) || f == float64(uint64(f)) +} + +func mustBeInteger(what interface{}) *int { + + if isJsonNumber(what) { + + number := what.(json.Number) + + _, _, isValidInt32 := checkJsonNumber(number) + + if isValidInt32 { + + int64Value, err := number.Int64() + if err != nil { + return nil + } + + int32Value := int(int64Value) + return &int32Value + + } else { + return nil + } + + } + + return nil +} + +func mustBeNumber(what interface{}) *float64 { + + if isJsonNumber(what) { + + number := what.(json.Number) + float64Value, err := number.Float64() + + if err == nil { + return &float64Value + } else { + return nil + } + + } + + return nil + +} + +// formats a number so that it is displayed as the smallest string possible +func resultErrorFormatJsonNumber(n json.Number) string { + + if int64Value, err := n.Int64(); err == nil { + return fmt.Sprintf("%d", int64Value) + } + + float64Value, _ := n.Float64() + + return fmt.Sprintf("%g", float64Value) +} + +// formats a number so that it is displayed as the smallest string possible +func resultErrorFormatNumber(n float64) string { + + if isFloat64AnInteger(n) { + return fmt.Sprintf("%d", int64(n)) + } + + return fmt.Sprintf("%g", n) +} + +func convertDocumentNode(val interface{}) interface{} { + + if lval, ok := val.([]interface{}); ok { + + res := []interface{}{} + for _, v := range lval { + res = append(res, convertDocumentNode(v)) + } + + return res + + } + + if mval, ok := val.(map[interface{}]interface{}); ok { + + res := map[string]interface{}{} + + for k, v := range mval { + res[k.(string)] = convertDocumentNode(v) + } + + return res + + } + + return val +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/utils_test.go b/vendor/github.com/xeipuuv/gojsonschema/utils_test.go new file mode 100644 index 00000000..489577d4 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/utils_test.go @@ -0,0 +1,64 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// 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. + +// author janmentzel +// author-github https://github.com/janmentzel +// author-mail ? ( forward to xeipuuv@gmail.com ) +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description (Unit) Tests for utils ( Float / Integer conversion ). +// +// created 08-08-2013 + +package gojsonschema + +import ( + "github.com/stretchr/testify/assert" + "math" + "testing" +) + +func TestResultErrorFormatNumber(t *testing.T) { + + assert.Equal(t, "1", resultErrorFormatNumber(1)) + assert.Equal(t, "-1", resultErrorFormatNumber(-1)) + assert.Equal(t, "0", resultErrorFormatNumber(0)) + // unfortunately, can not be recognized as float + assert.Equal(t, "0", resultErrorFormatNumber(0.0)) + + assert.Equal(t, "1.001", resultErrorFormatNumber(1.001)) + assert.Equal(t, "-1.001", resultErrorFormatNumber(-1.001)) + assert.Equal(t, "0.0001", resultErrorFormatNumber(0.0001)) + + // casting math.MaxInt64 (1<<63 -1) to float back to int64 + // becomes negative. obviousely because of bit missinterpretation. + // so simply test a slightly smaller "large" integer here + assert.Equal(t, "4.611686018427388e+18", resultErrorFormatNumber(1<<62)) + // with negative int64 max works + assert.Equal(t, "-9.223372036854776e+18", resultErrorFormatNumber(math.MinInt64)) + assert.Equal(t, "-4.611686018427388e+18", resultErrorFormatNumber(-1<<62)) + + assert.Equal(t, "10000000000", resultErrorFormatNumber(1e10)) + assert.Equal(t, "-10000000000", resultErrorFormatNumber(-1e10)) + + assert.Equal(t, "1.000000000001", resultErrorFormatNumber(1.000000000001)) + assert.Equal(t, "-1.000000000001", resultErrorFormatNumber(-1.000000000001)) + assert.Equal(t, "1e-10", resultErrorFormatNumber(1e-10)) + assert.Equal(t, "-1e-10", resultErrorFormatNumber(-1e-10)) + assert.Equal(t, "4.6116860184273876e+07", resultErrorFormatNumber(4.611686018427387904e7)) + assert.Equal(t, "-4.6116860184273876e+07", resultErrorFormatNumber(-4.611686018427387904e7)) + +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/validation.go b/vendor/github.com/xeipuuv/gojsonschema/validation.go new file mode 100644 index 00000000..2dc0df22 --- /dev/null +++ b/vendor/github.com/xeipuuv/gojsonschema/validation.go @@ -0,0 +1,829 @@ +// Copyright 2015 xeipuuv ( https://github.com/xeipuuv ) +// +// 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. + +// author xeipuuv +// author-github https://github.com/xeipuuv +// author-mail xeipuuv@gmail.com +// +// repository-name gojsonschema +// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language. +// +// description Extends Schema and subSchema, implements the validation phase. +// +// created 28-02-2013 + +package gojsonschema + +import ( + "encoding/json" + "reflect" + "regexp" + "strconv" + "strings" + "unicode/utf8" +) + +func Validate(ls JSONLoader, ld JSONLoader) (*Result, error) { + + var err error + + // load schema + + schema, err := NewSchema(ls) + if err != nil { + return nil, err + } + + // begine validation + + return schema.Validate(ld) + +} + +func (v *Schema) Validate(l JSONLoader) (*Result, error) { + + // load document + + root, err := l.loadJSON() + if err != nil { + return nil, err + } + + // begin validation + + result := &Result{} + context := newJsonContext(STRING_CONTEXT_ROOT, nil) + v.rootSchema.validateRecursive(v.rootSchema, root, result, context) + + return result, nil + +} + +func (v *subSchema) subValidateWithContext(document interface{}, context *jsonContext) *Result { + result := &Result{} + v.validateRecursive(v, document, result, context) + return result +} + +// Walker function to validate the json recursively against the subSchema +func (v *subSchema) validateRecursive(currentSubSchema *subSchema, currentNode interface{}, result *Result, context *jsonContext) { + + if internalLogEnabled { + internalLog("validateRecursive %s", context.String()) + internalLog(" %v", currentNode) + } + + // Handle referenced schemas, returns directly when a $ref is found + if currentSubSchema.refSchema != nil { + v.validateRecursive(currentSubSchema.refSchema, currentNode, result, context) + return + } + + // Check for null value + if currentNode == nil { + if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_NULL) { + result.addError( + new(InvalidTypeError), + context, + currentNode, + ErrorDetails{ + "expected": currentSubSchema.types.String(), + "given": TYPE_NULL, + }, + ) + return + } + + currentSubSchema.validateSchema(currentSubSchema, currentNode, result, context) + v.validateCommon(currentSubSchema, currentNode, result, context) + + } else { // Not a null value + + if isJsonNumber(currentNode) { + + value := currentNode.(json.Number) + + _, isValidInt64, _ := checkJsonNumber(value) + + validType := currentSubSchema.types.Contains(TYPE_NUMBER) || (isValidInt64 && currentSubSchema.types.Contains(TYPE_INTEGER)) + + if currentSubSchema.types.IsTyped() && !validType { + + givenType := TYPE_INTEGER + if !isValidInt64 { + givenType = TYPE_NUMBER + } + + result.addError( + new(InvalidTypeError), + context, + currentNode, + ErrorDetails{ + "expected": currentSubSchema.types.String(), + "given": givenType, + }, + ) + return + } + + currentSubSchema.validateSchema(currentSubSchema, value, result, context) + v.validateNumber(currentSubSchema, value, result, context) + v.validateCommon(currentSubSchema, value, result, context) + v.validateString(currentSubSchema, value, result, context) + + } else { + + rValue := reflect.ValueOf(currentNode) + rKind := rValue.Kind() + + switch rKind { + + // Slice => JSON array + + case reflect.Slice: + + if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_ARRAY) { + result.addError( + new(InvalidTypeError), + context, + currentNode, + ErrorDetails{ + "expected": currentSubSchema.types.String(), + "given": TYPE_ARRAY, + }, + ) + return + } + + castCurrentNode := currentNode.([]interface{}) + + currentSubSchema.validateSchema(currentSubSchema, castCurrentNode, result, context) + + v.validateArray(currentSubSchema, castCurrentNode, result, context) + v.validateCommon(currentSubSchema, castCurrentNode, result, context) + + // Map => JSON object + + case reflect.Map: + if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_OBJECT) { + result.addError( + new(InvalidTypeError), + context, + currentNode, + ErrorDetails{ + "expected": currentSubSchema.types.String(), + "given": TYPE_OBJECT, + }, + ) + return + } + + castCurrentNode, ok := currentNode.(map[string]interface{}) + if !ok { + castCurrentNode = convertDocumentNode(currentNode).(map[string]interface{}) + } + + currentSubSchema.validateSchema(currentSubSchema, castCurrentNode, result, context) + + v.validateObject(currentSubSchema, castCurrentNode, result, context) + v.validateCommon(currentSubSchema, castCurrentNode, result, context) + + for _, pSchema := range currentSubSchema.propertiesChildren { + nextNode, ok := castCurrentNode[pSchema.property] + if ok { + subContext := newJsonContext(pSchema.property, context) + v.validateRecursive(pSchema, nextNode, result, subContext) + } + } + + // Simple JSON values : string, number, boolean + + case reflect.Bool: + + if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_BOOLEAN) { + result.addError( + new(InvalidTypeError), + context, + currentNode, + ErrorDetails{ + "expected": currentSubSchema.types.String(), + "given": TYPE_BOOLEAN, + }, + ) + return + } + + value := currentNode.(bool) + + currentSubSchema.validateSchema(currentSubSchema, value, result, context) + v.validateNumber(currentSubSchema, value, result, context) + v.validateCommon(currentSubSchema, value, result, context) + v.validateString(currentSubSchema, value, result, context) + + case reflect.String: + + if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_STRING) { + result.addError( + new(InvalidTypeError), + context, + currentNode, + ErrorDetails{ + "expected": currentSubSchema.types.String(), + "given": TYPE_STRING, + }, + ) + return + } + + value := currentNode.(string) + + currentSubSchema.validateSchema(currentSubSchema, value, result, context) + v.validateNumber(currentSubSchema, value, result, context) + v.validateCommon(currentSubSchema, value, result, context) + v.validateString(currentSubSchema, value, result, context) + + } + + } + + } + + result.incrementScore() +} + +// Different kinds of validation there, subSchema / common / array / object / string... +func (v *subSchema) validateSchema(currentSubSchema *subSchema, currentNode interface{}, result *Result, context *jsonContext) { + + if internalLogEnabled { + internalLog("validateSchema %s", context.String()) + internalLog(" %v", currentNode) + } + + if len(currentSubSchema.anyOf) > 0 { + + validatedAnyOf := false + var bestValidationResult *Result + + for _, anyOfSchema := range currentSubSchema.anyOf { + if !validatedAnyOf { + validationResult := anyOfSchema.subValidateWithContext(currentNode, context) + validatedAnyOf = validationResult.Valid() + + if !validatedAnyOf && (bestValidationResult == nil || validationResult.score > bestValidationResult.score) { + bestValidationResult = validationResult + } + } + } + if !validatedAnyOf { + + result.addError(new(NumberAnyOfError), context, currentNode, ErrorDetails{}) + + if bestValidationResult != nil { + // add error messages of closest matching subSchema as + // that's probably the one the user was trying to match + result.mergeErrors(bestValidationResult) + } + } + } + + if len(currentSubSchema.oneOf) > 0 { + + nbValidated := 0 + var bestValidationResult *Result + + for _, oneOfSchema := range currentSubSchema.oneOf { + validationResult := oneOfSchema.subValidateWithContext(currentNode, context) + if validationResult.Valid() { + nbValidated++ + } else if nbValidated == 0 && (bestValidationResult == nil || validationResult.score > bestValidationResult.score) { + bestValidationResult = validationResult + } + } + + if nbValidated != 1 { + + result.addError(new(NumberOneOfError), context, currentNode, ErrorDetails{}) + + if nbValidated == 0 { + // add error messages of closest matching subSchema as + // that's probably the one the user was trying to match + result.mergeErrors(bestValidationResult) + } + } + + } + + if len(currentSubSchema.allOf) > 0 { + nbValidated := 0 + + for _, allOfSchema := range currentSubSchema.allOf { + validationResult := allOfSchema.subValidateWithContext(currentNode, context) + if validationResult.Valid() { + nbValidated++ + } + result.mergeErrors(validationResult) + } + + if nbValidated != len(currentSubSchema.allOf) { + result.addError(new(NumberAllOfError), context, currentNode, ErrorDetails{}) + } + } + + if currentSubSchema.not != nil { + validationResult := currentSubSchema.not.subValidateWithContext(currentNode, context) + if validationResult.Valid() { + result.addError(new(NumberNotError), context, currentNode, ErrorDetails{}) + } + } + + if currentSubSchema.dependencies != nil && len(currentSubSchema.dependencies) > 0 { + if isKind(currentNode, reflect.Map) { + for elementKey := range currentNode.(map[string]interface{}) { + if dependency, ok := currentSubSchema.dependencies[elementKey]; ok { + switch dependency := dependency.(type) { + + case []string: + for _, dependOnKey := range dependency { + if _, dependencyResolved := currentNode.(map[string]interface{})[dependOnKey]; !dependencyResolved { + result.addError( + new(MissingDependencyError), + context, + currentNode, + ErrorDetails{"dependency": dependOnKey}, + ) + } + } + + case *subSchema: + dependency.validateRecursive(dependency, currentNode, result, context) + + } + } + } + } + } + + result.incrementScore() +} + +func (v *subSchema) validateCommon(currentSubSchema *subSchema, value interface{}, result *Result, context *jsonContext) { + + if internalLogEnabled { + internalLog("validateCommon %s", context.String()) + internalLog(" %v", value) + } + + // enum: + if len(currentSubSchema.enum) > 0 { + has, err := currentSubSchema.ContainsEnum(value) + if err != nil { + result.addError(new(InternalError), context, value, ErrorDetails{"error": err}) + } + if !has { + result.addError( + new(EnumError), + context, + value, + ErrorDetails{ + "allowed": strings.Join(currentSubSchema.enum, ", "), + }, + ) + } + } + + result.incrementScore() +} + +func (v *subSchema) validateArray(currentSubSchema *subSchema, value []interface{}, result *Result, context *jsonContext) { + + if internalLogEnabled { + internalLog("validateArray %s", context.String()) + internalLog(" %v", value) + } + + nbItems := len(value) + + // TODO explain + if currentSubSchema.itemsChildrenIsSingleSchema { + for i := range value { + subContext := newJsonContext(strconv.Itoa(i), context) + validationResult := currentSubSchema.itemsChildren[0].subValidateWithContext(value[i], subContext) + result.mergeErrors(validationResult) + } + } else { + if currentSubSchema.itemsChildren != nil && len(currentSubSchema.itemsChildren) > 0 { + + nbItems := len(currentSubSchema.itemsChildren) + nbValues := len(value) + + if nbItems == nbValues { + for i := 0; i != nbItems; i++ { + subContext := newJsonContext(strconv.Itoa(i), context) + validationResult := currentSubSchema.itemsChildren[i].subValidateWithContext(value[i], subContext) + result.mergeErrors(validationResult) + } + } else if nbItems < nbValues { + switch currentSubSchema.additionalItems.(type) { + case bool: + if !currentSubSchema.additionalItems.(bool) { + result.addError(new(ArrayNoAdditionalItemsError), context, value, ErrorDetails{}) + } + case *subSchema: + additionalItemSchema := currentSubSchema.additionalItems.(*subSchema) + for i := nbItems; i != nbValues; i++ { + subContext := newJsonContext(strconv.Itoa(i), context) + validationResult := additionalItemSchema.subValidateWithContext(value[i], subContext) + result.mergeErrors(validationResult) + } + } + } + } + } + + // minItems & maxItems + if currentSubSchema.minItems != nil { + if nbItems < int(*currentSubSchema.minItems) { + result.addError( + new(ArrayMinItemsError), + context, + value, + ErrorDetails{"min": *currentSubSchema.minItems}, + ) + } + } + if currentSubSchema.maxItems != nil { + if nbItems > int(*currentSubSchema.maxItems) { + result.addError( + new(ArrayMaxItemsError), + context, + value, + ErrorDetails{"max": *currentSubSchema.maxItems}, + ) + } + } + + // uniqueItems: + if currentSubSchema.uniqueItems { + var stringifiedItems []string + for _, v := range value { + vString, err := marshalToJsonString(v) + if err != nil { + result.addError(new(InternalError), context, value, ErrorDetails{"err": err}) + } + if isStringInSlice(stringifiedItems, *vString) { + result.addError( + new(ItemsMustBeUniqueError), + context, + value, + ErrorDetails{"type": TYPE_ARRAY}, + ) + } + stringifiedItems = append(stringifiedItems, *vString) + } + } + + result.incrementScore() +} + +func (v *subSchema) validateObject(currentSubSchema *subSchema, value map[string]interface{}, result *Result, context *jsonContext) { + + if internalLogEnabled { + internalLog("validateObject %s", context.String()) + internalLog(" %v", value) + } + + // minProperties & maxProperties: + if currentSubSchema.minProperties != nil { + if len(value) < int(*currentSubSchema.minProperties) { + result.addError( + new(ArrayMinPropertiesError), + context, + value, + ErrorDetails{"min": *currentSubSchema.minProperties}, + ) + } + } + if currentSubSchema.maxProperties != nil { + if len(value) > int(*currentSubSchema.maxProperties) { + result.addError( + new(ArrayMaxPropertiesError), + context, + value, + ErrorDetails{"max": *currentSubSchema.maxProperties}, + ) + } + } + + // required: + for _, requiredProperty := range currentSubSchema.required { + _, ok := value[requiredProperty] + if ok { + result.incrementScore() + } else { + result.addError( + new(RequiredError), + context, + value, + ErrorDetails{"property": requiredProperty}, + ) + } + } + + // additionalProperty & patternProperty: + if currentSubSchema.additionalProperties != nil { + + switch currentSubSchema.additionalProperties.(type) { + case bool: + + if !currentSubSchema.additionalProperties.(bool) { + + for pk := range value { + + found := false + for _, spValue := range currentSubSchema.propertiesChildren { + if pk == spValue.property { + found = true + } + } + + pp_has, pp_match := v.validatePatternProperty(currentSubSchema, pk, value[pk], result, context) + + if found { + + if pp_has && !pp_match { + result.addError( + new(AdditionalPropertyNotAllowedError), + context, + value, + ErrorDetails{"property": pk}, + ) + } + + } else { + + if !pp_has || !pp_match { + result.addError( + new(AdditionalPropertyNotAllowedError), + context, + value, + ErrorDetails{"property": pk}, + ) + } + + } + } + } + + case *subSchema: + + additionalPropertiesSchema := currentSubSchema.additionalProperties.(*subSchema) + for pk := range value { + + found := false + for _, spValue := range currentSubSchema.propertiesChildren { + if pk == spValue.property { + found = true + } + } + + pp_has, pp_match := v.validatePatternProperty(currentSubSchema, pk, value[pk], result, context) + + if found { + + if pp_has && !pp_match { + validationResult := additionalPropertiesSchema.subValidateWithContext(value[pk], context) + result.mergeErrors(validationResult) + } + + } else { + + if !pp_has || !pp_match { + validationResult := additionalPropertiesSchema.subValidateWithContext(value[pk], context) + result.mergeErrors(validationResult) + } + + } + + } + } + } else { + + for pk := range value { + + pp_has, pp_match := v.validatePatternProperty(currentSubSchema, pk, value[pk], result, context) + + if pp_has && !pp_match { + + result.addError( + new(InvalidPropertyPatternError), + context, + value, + ErrorDetails{ + "property": pk, + "pattern": currentSubSchema.PatternPropertiesString(), + }, + ) + } + + } + } + + result.incrementScore() +} + +func (v *subSchema) validatePatternProperty(currentSubSchema *subSchema, key string, value interface{}, result *Result, context *jsonContext) (has bool, matched bool) { + + if internalLogEnabled { + internalLog("validatePatternProperty %s", context.String()) + internalLog(" %s %v", key, value) + } + + has = false + + validatedkey := false + + for pk, pv := range currentSubSchema.patternProperties { + if matches, _ := regexp.MatchString(pk, key); matches { + has = true + subContext := newJsonContext(key, context) + validationResult := pv.subValidateWithContext(value, subContext) + result.mergeErrors(validationResult) + if validationResult.Valid() { + validatedkey = true + } + } + } + + if !validatedkey { + return has, false + } + + result.incrementScore() + + return has, true +} + +func (v *subSchema) validateString(currentSubSchema *subSchema, value interface{}, result *Result, context *jsonContext) { + + // Ignore JSON numbers + if isJsonNumber(value) { + return + } + + // Ignore non strings + if !isKind(value, reflect.String) { + return + } + + if internalLogEnabled { + internalLog("validateString %s", context.String()) + internalLog(" %v", value) + } + + stringValue := value.(string) + + // minLength & maxLength: + if currentSubSchema.minLength != nil { + if utf8.RuneCount([]byte(stringValue)) < int(*currentSubSchema.minLength) { + result.addError( + new(StringLengthGTEError), + context, + value, + ErrorDetails{"min": *currentSubSchema.minLength}, + ) + } + } + if currentSubSchema.maxLength != nil { + if utf8.RuneCount([]byte(stringValue)) > int(*currentSubSchema.maxLength) { + result.addError( + new(StringLengthLTEError), + context, + value, + ErrorDetails{"max": *currentSubSchema.maxLength}, + ) + } + } + + // pattern: + if currentSubSchema.pattern != nil { + if !currentSubSchema.pattern.MatchString(stringValue) { + result.addError( + new(DoesNotMatchPatternError), + context, + value, + ErrorDetails{"pattern": currentSubSchema.pattern}, + ) + + } + } + + // format + if currentSubSchema.format != "" { + if !FormatCheckers.IsFormat(currentSubSchema.format, stringValue) { + result.addError( + new(DoesNotMatchFormatError), + context, + value, + ErrorDetails{"format": currentSubSchema.format}, + ) + } + } + + result.incrementScore() +} + +func (v *subSchema) validateNumber(currentSubSchema *subSchema, value interface{}, result *Result, context *jsonContext) { + + // Ignore non numbers + if !isJsonNumber(value) { + return + } + + if internalLogEnabled { + internalLog("validateNumber %s", context.String()) + internalLog(" %v", value) + } + + number := value.(json.Number) + float64Value, _ := number.Float64() + + // multipleOf: + if currentSubSchema.multipleOf != nil { + + if !isFloat64AnInteger(float64Value / *currentSubSchema.multipleOf) { + result.addError( + new(MultipleOfError), + context, + resultErrorFormatJsonNumber(number), + ErrorDetails{"multiple": *currentSubSchema.multipleOf}, + ) + } + } + + //maximum & exclusiveMaximum: + if currentSubSchema.maximum != nil { + if currentSubSchema.exclusiveMaximum { + if float64Value >= *currentSubSchema.maximum { + result.addError( + new(NumberLTError), + context, + resultErrorFormatJsonNumber(number), + ErrorDetails{ + "max": resultErrorFormatNumber(*currentSubSchema.maximum), + }, + ) + } + } else { + if float64Value > *currentSubSchema.maximum { + result.addError( + new(NumberLTEError), + context, + resultErrorFormatJsonNumber(number), + ErrorDetails{ + "max": resultErrorFormatNumber(*currentSubSchema.maximum), + }, + ) + } + } + } + + //minimum & exclusiveMinimum: + if currentSubSchema.minimum != nil { + if currentSubSchema.exclusiveMinimum { + if float64Value <= *currentSubSchema.minimum { + result.addError( + new(NumberGTError), + context, + resultErrorFormatJsonNumber(number), + ErrorDetails{ + "min": resultErrorFormatNumber(*currentSubSchema.minimum), + }, + ) + } + } else { + if float64Value < *currentSubSchema.minimum { + result.addError( + new(NumberGTEError), + context, + resultErrorFormatJsonNumber(number), + ErrorDetails{ + "min": resultErrorFormatNumber(*currentSubSchema.minimum), + }, + ) + } + } + } + + result.incrementScore() +}