From 06b0d32a8fdb1f16e4279a61f3ffa36e79b96861 Mon Sep 17 00:00:00 2001 From: Jon Chen Date: Thu, 29 Jun 2017 14:56:59 -0700 Subject: [PATCH] updates dependencies for goji --- .travis.yml | 2 +- Godeps/Godeps.json | 53 +- _vendor/github.com/gopherjs/gopherjs/LICENSE | 24 + _vendor/github.com/gopherjs/gopherjs/js/js.go | 168 ++++++ .../smartystreets/assertions/.gitignore | 3 + .../smartystreets/assertions/.travis.yml | 11 +- .../smartystreets/assertions/CONTRIBUTING.md | 12 + .../smartystreets/assertions/LICENSE.md | 2 +- .../smartystreets/assertions/README.md | 74 ++- .../assertions/assertions.goconvey | 3 - .../smartystreets/assertions/collections.go | 104 ++++ .../smartystreets/assertions/doc.go | 33 +- .../smartystreets/assertions/equality.go | 36 +- .../smartystreets/assertions/filter.go | 8 + .../assertions/internal/Makefile | 21 - .../internal/go-render/render/render.go | 477 +++++++++++++++++ .../internal/oglematchers/.travis.yml | 4 + .../internal/oglematchers/all_of.go | 70 --- .../assertions/internal/oglematchers/any.go | 32 -- .../internal/oglematchers/contains.go | 2 +- .../internal/oglematchers/elements_are.go | 91 ---- .../internal/oglematchers/equals.go | 18 +- .../assertions/internal/oglematchers/error.go | 51 -- .../internal/oglematchers/has_same_type_as.go | 37 -- .../internal/oglematchers/has_substr.go | 46 -- .../internal/oglematchers/identical_to.go | 134 ----- .../internal/oglematchers/matches_regexp.go | 69 --- .../internal/oglematchers/new_matcher.go | 43 -- .../internal/oglematchers/panics.go | 74 --- .../internal/oglematchers/pointee.go | 65 --- .../oglematchers/transform_description.go | 2 +- .../assertions/internal/oglemock/.gitignore | 5 - .../assertions/internal/oglemock/LICENSE | 202 -------- .../assertions/internal/oglemock/README.md | 103 ---- .../assertions/internal/oglemock/action.go | 36 -- .../internal/oglemock/controller.go | 480 ------------------ .../oglemock/createmock/createmock.go | 226 --------- .../test_cases/golden.no_interfaces | 1 - .../createmock/test_cases/golden.no_package | 1 - .../test_cases/golden.unknown_interface | 1 - .../test_cases/golden.unknown_package | 1 - .../assertions/internal/oglemock/do_all.go | 53 -- .../internal/oglemock/error_reporter.go | 29 -- .../internal/oglemock/expectation.go | 59 --- .../internal/oglemock/generate/generate.go | 329 ------------ .../complicated_pkg/complicated_pkg.go | 40 -- .../test_cases/golden.complicated_pkg.go | 311 ------------ .../generate/test_cases/golden.image.go | 238 --------- .../test_cases/golden.io_reader_writer.go | 127 ----- .../generate/test_cases/golden.renamed_pkg.go | 66 --- .../test_cases/renamed_pkg/renamed_pkg.go | 24 - .../internal/oglemock/internal_expectation.go | 180 ------- .../assertions/internal/oglemock/invoke.go | 73 --- .../internal/oglemock/mock_object.go | 30 -- .../assertions/internal/oglemock/return.go | 251 --------- .../internal/oglemock/sample/README.markdown | 6 - .../oglemock/sample/mock_io/mock_io.go | 71 --- .../assertions/internal/oglemock/save_arg.go | 83 --- .../assertions/internal/ogletest/.gitignore | 5 - .../assertions/internal/ogletest/LICENSE | 202 -------- .../assertions/internal/ogletest/README.md | 151 ------ .../internal/ogletest/assert_aliases.go | 70 --- .../internal/ogletest/assert_that.go | 46 -- .../assertions/internal/ogletest/doc.go | 51 -- .../internal/ogletest/expect_aliases.go | 64 --- .../internal/ogletest/expect_call.go | 59 --- .../internal/ogletest/expect_that.go | 100 ---- .../assertions/internal/ogletest/failure.go | 90 ---- .../assertions/internal/ogletest/register.go | 86 ---- .../internal/ogletest/register_test_suite.go | 193 ------- .../assertions/internal/ogletest/run_tests.go | 354 ------------- .../internal/ogletest/srcutil/docs.go | 5 - .../internal/ogletest/srcutil/methods.go | 65 --- .../ogletest/test_cases/failing.test.go | 252 --------- .../ogletest/test_cases/filtered.test.go | 79 --- .../ogletest/test_cases/golden.failing_test | 278 ---------- .../ogletest/test_cases/golden.filtered_test | 24 - .../ogletest/test_cases/golden.mock_test | 25 - .../ogletest/test_cases/golden.no_cases_test | 6 - .../ogletest/test_cases/golden.panicking_test | 90 ---- .../ogletest/test_cases/golden.passing_test | 22 - .../ogletest/test_cases/golden.run_twice_test | 14 - .../ogletest/test_cases/golden.stop_test | 13 - .../test_cases/golden.unexported_test | 12 - .../internal/ogletest/test_cases/mock.test.go | 82 --- .../test_cases/mock_image/mock_image.go | 115 ----- .../ogletest/test_cases/no_cases.test.go | 41 -- .../ogletest/test_cases/panicking.test.go | 99 ---- .../ogletest/test_cases/passing.test.go | 120 ----- .../ogletest/test_cases/run_twice.test.go | 47 -- .../internal/ogletest/test_cases/stop.test.go | 61 --- .../ogletest/test_cases/unexported.test.go | 43 -- .../assertions/internal/ogletest/test_info.go | 91 ---- .../assertions/internal/reqtrace/.gitignore | 24 - .../assertions/internal/reqtrace/LICENSE | 202 -------- .../assertions/internal/reqtrace/README.md | 53 -- .../assertions/internal/reqtrace/reqtrace.go | 132 ----- .../internal/reqtrace/trace_state.go | 175 ------- .../smartystreets/assertions/messages.go | 14 +- .../smartystreets/assertions/quantity.go | 2 +- .../smartystreets/assertions/serializer.go | 42 +- .../smartystreets/assertions/should/should.go | 67 --- .../smartystreets/assertions/strings.go | 44 ++ .../smartystreets/assertions/type.go | 29 +- .../smartystreets/goconvey/LICENSE.md | 26 +- .../goconvey/convey/assertions.go | 17 +- .../goconvey/convey/gotest/utils.go | 9 - .../smartystreets/goconvey/convey/init.go | 17 +- .../goconvey/convey/reporting/init.go | 11 +- .../goconvey/convey/reporting/problems.go | 16 +- .../goconvey/convey/reporting/reports.go | 8 +- .../goconvey/convey/reporting/statistics.go | 39 +- _vendor/goji.io/.travis.yml | 2 +- _vendor/goji.io/LICENSE | 2 +- _vendor/goji.io/README.md | 40 +- _vendor/goji.io/dispatch.go | 6 +- _vendor/goji.io/goji.go | 87 ++-- _vendor/goji.io/handle.go | 45 +- _vendor/goji.io/internal/context.go | 8 +- _vendor/goji.io/internal/http.go | 19 - _vendor/goji.io/middleware.go | 86 +--- _vendor/goji.io/middleware/middleware.go | 79 --- _vendor/goji.io/mux.go | 53 +- _vendor/goji.io/pat/match.go | 2 +- _vendor/goji.io/pat/pat.go | 16 +- _vendor/goji.io/pattern/pattern.go | 3 +- _vendor/goji.io/router.go | 6 +- _vendor/goji.io/router_simple.go | 22 +- _vendor/goji.io/router_trie.go | 52 +- _vendor/golang.org/x/net/context/context.go | 447 ---------------- .../x/net/context/ctxhttp/cancelreq.go | 18 - .../x/net/context/ctxhttp/cancelreq_go14.go | 23 - .../x/net/context/ctxhttp/ctxhttp.go | 79 --- client/client_test.go | 3 +- goji2-logger/logger.go | 18 +- jsh-api/api.go | 8 +- jsh-api/mock_storage.go | 2 +- jsh-api/resource.go | 126 +++-- jsh-api/resource_test.go | 2 +- jsh-api/sender.go | 5 +- jsh-api/store/store.go | 3 +- 141 files changed, 1406 insertions(+), 8633 deletions(-) create mode 100644 _vendor/github.com/gopherjs/gopherjs/LICENSE create mode 100644 _vendor/github.com/gopherjs/gopherjs/js/js.go create mode 100644 _vendor/github.com/smartystreets/assertions/CONTRIBUTING.md delete mode 100644 _vendor/github.com/smartystreets/assertions/assertions.goconvey delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/Makefile create mode 100644 _vendor/github.com/smartystreets/assertions/internal/go-render/render/render.go create mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglematchers/.travis.yml delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglematchers/all_of.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglematchers/any.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglematchers/elements_are.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglematchers/error.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglematchers/has_same_type_as.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglematchers/has_substr.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglematchers/identical_to.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglematchers/matches_regexp.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglematchers/new_matcher.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglematchers/panics.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglematchers/pointee.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/.gitignore delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/LICENSE delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/README.md delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/action.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/controller.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/createmock.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.no_interfaces delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.no_package delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.unknown_interface delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.unknown_package delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/do_all.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/error_reporter.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/expectation.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/generate/generate.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/complicated_pkg/complicated_pkg.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.complicated_pkg.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.image.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.io_reader_writer.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.renamed_pkg.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/renamed_pkg/renamed_pkg.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/internal_expectation.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/invoke.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/mock_object.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/return.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/sample/README.markdown delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/sample/mock_io/mock_io.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/oglemock/save_arg.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/.gitignore delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/LICENSE delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/README.md delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/assert_aliases.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/assert_that.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/doc.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/expect_aliases.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/expect_call.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/expect_that.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/failure.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/register.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/register_test_suite.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/run_tests.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/srcutil/docs.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/srcutil/methods.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/failing.test.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/filtered.test.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.failing_test delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.filtered_test delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.mock_test delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.no_cases_test delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.panicking_test delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.passing_test delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.run_twice_test delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.stop_test delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.unexported_test delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/mock.test.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/mock_image/mock_image.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/no_cases.test.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/panicking.test.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/passing.test.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/run_twice.test.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/stop.test.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/unexported.test.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/ogletest/test_info.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/reqtrace/.gitignore delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/reqtrace/LICENSE delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/reqtrace/README.md delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/reqtrace/reqtrace.go delete mode 100644 _vendor/github.com/smartystreets/assertions/internal/reqtrace/trace_state.go delete mode 100644 _vendor/github.com/smartystreets/assertions/should/should.go delete mode 100644 _vendor/goji.io/internal/http.go delete mode 100644 _vendor/goji.io/middleware/middleware.go delete mode 100644 _vendor/golang.org/x/net/context/context.go delete mode 100644 _vendor/golang.org/x/net/context/ctxhttp/cancelreq.go delete mode 100644 _vendor/golang.org/x/net/context/ctxhttp/cancelreq_go14.go delete mode 100644 _vendor/golang.org/x/net/context/ctxhttp/ctxhttp.go diff --git a/.travis.yml b/.travis.yml index 917cdf7..a5b7e5d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ language: go go: - tip - - 1.6 + - 1.8 install: - go get github.com/smartystreets/goconvey diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index 98ae2b4..36465b8 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -1,6 +1,7 @@ { "ImportPath": "github.com/derekdowling/go-json-spec-handler", - "GoVersion": "go1.6.2", + "GoVersion": "go1.8", + "GodepVersion": "v79", "Packages": [ "./..." ], @@ -14,19 +15,43 @@ "ImportPath": "github.com/derekdowling/go-stdlogger", "Rev": "cfa80b78b82f8d241ceece0b733b1161bb6a885c" }, + { + "ImportPath": "github.com/gopherjs/gopherjs/js", + "Rev": "dc374d32704510cb387457180ca9d5193978b555" + }, { "ImportPath": "github.com/jtolds/gls", "Rev": "9a4a02dbe491bef4bab3c24fd9f3087d6c4c6690" }, { "ImportPath": "github.com/smartystreets/assertions", - "Comment": "1.5.0-389-g507a61a", - "Rev": "507a61adbdc8674907f6e491b559d600a4127dc0" + "Comment": "1.6.0-27-g4ea54c1", + "Rev": "4ea54c1f28ad3ae597e76607dea3871fa177e263" + }, + { + "ImportPath": "github.com/smartystreets/assertions/internal/go-render/render", + "Comment": "1.6.0-27-g4ea54c1", + "Rev": "4ea54c1f28ad3ae597e76607dea3871fa177e263" + }, + { + "ImportPath": "github.com/smartystreets/assertions/internal/oglematchers", + "Comment": "1.6.0-27-g4ea54c1", + "Rev": "4ea54c1f28ad3ae597e76607dea3871fa177e263" }, { "ImportPath": "github.com/smartystreets/goconvey/convey", - "Comment": "1.5.0-398-gab7641a", - "Rev": "ab7641a0db76b0e88765294b1377b026ec01f26b" + "Comment": "1.6.2-21-g9e8dc3f", + "Rev": "9e8dc3f972df6c8fcc0375ef492c24d0bb204857" + }, + { + "ImportPath": "github.com/smartystreets/goconvey/convey/gotest", + "Comment": "1.6.2-21-g9e8dc3f", + "Rev": "9e8dc3f972df6c8fcc0375ef492c24d0bb204857" + }, + { + "ImportPath": "github.com/smartystreets/goconvey/convey/reporting", + "Comment": "1.6.2-21-g9e8dc3f", + "Rev": "9e8dc3f972df6c8fcc0375ef492c24d0bb204857" }, { "ImportPath": "github.com/zenazn/goji/web/mutil", @@ -35,11 +60,23 @@ }, { "ImportPath": "goji.io", - "Rev": "8110ccbc05240c40d43ccb004e0542b3bcbf27da" + "Comment": "v2.0", + "Rev": "0d89ff54b2c18c9c4ba530e32496aef902d3c6cd" + }, + { + "ImportPath": "goji.io/internal", + "Comment": "v2.0", + "Rev": "0d89ff54b2c18c9c4ba530e32496aef902d3c6cd" + }, + { + "ImportPath": "goji.io/pat", + "Comment": "v2.0", + "Rev": "0d89ff54b2c18c9c4ba530e32496aef902d3c6cd" }, { - "ImportPath": "golang.org/x/net/context", - "Rev": "28273ec927bee3bea305f112fc28ceee575ea893" + "ImportPath": "goji.io/pattern", + "Comment": "v2.0", + "Rev": "0d89ff54b2c18c9c4ba530e32496aef902d3c6cd" } ] } diff --git a/_vendor/github.com/gopherjs/gopherjs/LICENSE b/_vendor/github.com/gopherjs/gopherjs/LICENSE new file mode 100644 index 0000000..d496fef --- /dev/null +++ b/_vendor/github.com/gopherjs/gopherjs/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2013 Richard Musiol. 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 +OWNER 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/gopherjs/gopherjs/js/js.go b/_vendor/github.com/gopherjs/gopherjs/js/js.go new file mode 100644 index 0000000..3fbf1d8 --- /dev/null +++ b/_vendor/github.com/gopherjs/gopherjs/js/js.go @@ -0,0 +1,168 @@ +// Package js provides functions for interacting with native JavaScript APIs. Calls to these functions are treated specially by GopherJS and translated directly to their corresponding JavaScript syntax. +// +// Use MakeWrapper to expose methods to JavaScript. When passing values directly, the following type conversions are performed: +// +// | Go type | JavaScript type | Conversions back to interface{} | +// | --------------------- | --------------------- | ------------------------------- | +// | bool | Boolean | bool | +// | integers and floats | Number | float64 | +// | string | String | string | +// | []int8 | Int8Array | []int8 | +// | []int16 | Int16Array | []int16 | +// | []int32, []int | Int32Array | []int | +// | []uint8 | Uint8Array | []uint8 | +// | []uint16 | Uint16Array | []uint16 | +// | []uint32, []uint | Uint32Array | []uint | +// | []float32 | Float32Array | []float32 | +// | []float64 | Float64Array | []float64 | +// | all other slices | Array | []interface{} | +// | arrays | see slice type | see slice type | +// | functions | Function | func(...interface{}) *js.Object | +// | time.Time | Date | time.Time | +// | - | instanceof Node | *js.Object | +// | maps, structs | instanceof Object | map[string]interface{} | +// +// Additionally, for a struct containing a *js.Object field, only the content of the field will be passed to JavaScript and vice versa. +package js + +// Object is a container for a native JavaScript object. Calls to its methods are treated specially by GopherJS and translated directly to their JavaScript syntax. A nil pointer to Object is equal to JavaScript's "null". Object can not be used as a map key. +type Object struct{ object *Object } + +// Get returns the object's property with the given key. +func (o *Object) Get(key string) *Object { return o.object.Get(key) } + +// Set assigns the value to the object's property with the given key. +func (o *Object) Set(key string, value interface{}) { o.object.Set(key, value) } + +// Delete removes the object's property with the given key. +func (o *Object) Delete(key string) { o.object.Delete(key) } + +// Length returns the object's "length" property, converted to int. +func (o *Object) Length() int { return o.object.Length() } + +// Index returns the i'th element of an array. +func (o *Object) Index(i int) *Object { return o.object.Index(i) } + +// SetIndex sets the i'th element of an array. +func (o *Object) SetIndex(i int, value interface{}) { o.object.SetIndex(i, value) } + +// Call calls the object's method with the given name. +func (o *Object) Call(name string, args ...interface{}) *Object { return o.object.Call(name, args...) } + +// Invoke calls the object itself. This will fail if it is not a function. +func (o *Object) Invoke(args ...interface{}) *Object { return o.object.Invoke(args...) } + +// New creates a new instance of this type object. This will fail if it not a function (constructor). +func (o *Object) New(args ...interface{}) *Object { return o.object.New(args...) } + +// Bool returns the object converted to bool according to JavaScript type conversions. +func (o *Object) Bool() bool { return o.object.Bool() } + +// String returns the object converted to string according to JavaScript type conversions. +func (o *Object) String() string { return o.object.String() } + +// Int returns the object converted to int according to JavaScript type conversions (parseInt). +func (o *Object) Int() int { return o.object.Int() } + +// Int64 returns the object converted to int64 according to JavaScript type conversions (parseInt). +func (o *Object) Int64() int64 { return o.object.Int64() } + +// Uint64 returns the object converted to uint64 according to JavaScript type conversions (parseInt). +func (o *Object) Uint64() uint64 { return o.object.Uint64() } + +// Float returns the object converted to float64 according to JavaScript type conversions (parseFloat). +func (o *Object) Float() float64 { return o.object.Float() } + +// Interface returns the object converted to interface{}. See table in package comment for details. +func (o *Object) Interface() interface{} { return o.object.Interface() } + +// Unsafe returns the object as an uintptr, which can be converted via unsafe.Pointer. Not intended for public use. +func (o *Object) Unsafe() uintptr { return o.object.Unsafe() } + +// Error encapsulates JavaScript errors. Those are turned into a Go panic and may be recovered, giving an *Error that holds the JavaScript error object. +type Error struct { + *Object +} + +// Error returns the message of the encapsulated JavaScript error object. +func (err *Error) Error() string { + return "JavaScript error: " + err.Get("message").String() +} + +// Stack returns the stack property of the encapsulated JavaScript error object. +func (err *Error) Stack() string { + return err.Get("stack").String() +} + +// Global gives JavaScript's global object ("window" for browsers and "GLOBAL" for Node.js). +var Global *Object + +// Module gives the value of the "module" variable set by Node.js. Hint: Set a module export with 'js.Module.Get("exports").Set("exportName", ...)'. +var Module *Object + +// Undefined gives the JavaScript value "undefined". +var Undefined *Object + +// Debugger gets compiled to JavaScript's "debugger;" statement. +func Debugger() {} + +// InternalObject returns the internal JavaScript object that represents i. Not intended for public use. +func InternalObject(i interface{}) *Object { + return nil +} + +// MakeFunc wraps a function and gives access to the values of JavaScript's "this" and "arguments" keywords. +func MakeFunc(fn func(this *Object, arguments []*Object) interface{}) *Object { + return Global.Call("$makeFunc", InternalObject(fn)) +} + +// Keys returns the keys of the given JavaScript object. +func Keys(o *Object) []string { + if o == nil || o == Undefined { + return nil + } + a := Global.Get("Object").Call("keys", o) + s := make([]string, a.Length()) + for i := 0; i < a.Length(); i++ { + s[i] = a.Index(i).String() + } + return s +} + +// MakeWrapper creates a JavaScript object which has wrappers for the exported methods of i. Use explicit getter and setter methods to expose struct fields to JavaScript. +func MakeWrapper(i interface{}) *Object { + v := InternalObject(i) + o := Global.Get("Object").New() + o.Set("__internal_object__", v) + methods := v.Get("constructor").Get("methods") + for i := 0; i < methods.Length(); i++ { + m := methods.Index(i) + if m.Get("pkg").String() != "" { // not exported + continue + } + o.Set(m.Get("name").String(), func(args ...*Object) *Object { + return Global.Call("$externalizeFunction", v.Get(m.Get("prop").String()), m.Get("typ"), true).Call("apply", v, args) + }) + } + return o +} + +// NewArrayBuffer creates a JavaScript ArrayBuffer from a byte slice. +func NewArrayBuffer(b []byte) *Object { + slice := InternalObject(b) + offset := slice.Get("$offset").Int() + length := slice.Get("$length").Int() + return slice.Get("$array").Get("buffer").Call("slice", offset, offset+length) +} + +// M is a simple map type. It is intended as a shorthand for JavaScript objects (before conversion). +type M map[string]interface{} + +// S is a simple slice type. It is intended as a shorthand for JavaScript arrays (before conversion). +type S []interface{} + +func init() { + // avoid dead code elimination + e := Error{} + _ = e +} diff --git a/_vendor/github.com/smartystreets/assertions/.gitignore b/_vendor/github.com/smartystreets/assertions/.gitignore index fafff2e..07d3c71 100644 --- a/_vendor/github.com/smartystreets/assertions/.gitignore +++ b/_vendor/github.com/smartystreets/assertions/.gitignore @@ -1,2 +1,5 @@ .DS_Store Thumbs.db +*.iml +/.idea +coverage.out diff --git a/_vendor/github.com/smartystreets/assertions/.travis.yml b/_vendor/github.com/smartystreets/assertions/.travis.yml index 4aa2c6d..1065ceb 100644 --- a/_vendor/github.com/smartystreets/assertions/.travis.yml +++ b/_vendor/github.com/smartystreets/assertions/.travis.yml @@ -1,9 +1,12 @@ language: go go: - - 1.2 - - 1.3 - - 1.4 + - 1.x + - master install: - - go get golang.org/x/tools/cover + - go get -t ./... + +script: go test -v + +sudo: false diff --git a/_vendor/github.com/smartystreets/assertions/CONTRIBUTING.md b/_vendor/github.com/smartystreets/assertions/CONTRIBUTING.md new file mode 100644 index 0000000..1820ecb --- /dev/null +++ b/_vendor/github.com/smartystreets/assertions/CONTRIBUTING.md @@ -0,0 +1,12 @@ +# Contributing + +In general, the code posted to the [SmartyStreets github organization](https://github.com/smartystreets) is created to solve specific problems at SmartyStreets that are ancillary to our core products in the address verification industry and may or may not be useful to other organizations or developers. Our reason for posting said code isn't necessarily to solicit feedback or contributions from the community but more as a showcase of some of the approaches to solving problems we have adopted. + +Having stated that, we do consider issues raised by other githubbers as well as contributions submitted via pull requests. When submitting such a pull request, please follow these guidelines: + +- _Look before you leap:_ If the changes you plan to make are significant, it's in everyone's best interest for you to discuss them with a SmartyStreets team member prior to opening a pull request. +- _License and ownership:_ If modifying the `LICENSE.md` file, limit your changes to fixing typographical mistakes. Do NOT modify the actual terms in the license or the copyright by **SmartyStreets, LLC**. Code submitted to SmartyStreets projects becomes property of SmartyStreets and must be compatible with the associated license. +- _Testing:_ If the code you are submitting resides in packages/modules covered by automated tests, be sure to add passing tests that cover your changes and assert expected behavior and state. Submit the additional test cases as part of your change set. +- _Style:_ Match your approach to **naming** and **formatting** with the surrounding code. Basically, the code you submit shouldn't stand out. + - "Naming" refers to such constructs as variables, methods, functions, classes, structs, interfaces, packages, modules, directories, files, etc... + - "Formatting" refers to such constructs as whitespace, horizontal line length, vertical function length, vertical file length, indentation, curly braces, etc... diff --git a/_vendor/github.com/smartystreets/assertions/LICENSE.md b/_vendor/github.com/smartystreets/assertions/LICENSE.md index 48a3731..8ea6f94 100644 --- a/_vendor/github.com/smartystreets/assertions/LICENSE.md +++ b/_vendor/github.com/smartystreets/assertions/LICENSE.md @@ -1,4 +1,4 @@ -Copyright (c) 2015 SmartyStreets, LLC +Copyright (c) 2016 SmartyStreets, LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/_vendor/github.com/smartystreets/assertions/README.md b/_vendor/github.com/smartystreets/assertions/README.md index f337d38..58383bb 100644 --- a/_vendor/github.com/smartystreets/assertions/README.md +++ b/_vendor/github.com/smartystreets/assertions/README.md @@ -4,8 +4,14 @@ Package assertions contains the implementations for all assertions which are referenced in goconvey's `convey` package -(github.com/smartystreets/goconvey/convey) for use with the So(...) method. They -can also be used in traditional Go test functions and even in applicaitons. +(github.com/smartystreets/goconvey/convey) and gunit +(github.com/smartystreets/gunit) for use with the So(...) method. They can also +be used in traditional Go test functions and even in applications. + +Many of the assertions lean heavily on work done by Aaron Jacobs in his +excellent oglematchers library. (https://github.com/jacobsa/oglematchers) The +ShouldResemble assertion leans heavily on work done by Daniel Jacques in his +very helpful go-render library. (https://github.com/luci/go-render) ## Usage @@ -152,6 +158,14 @@ func ShouldContain(actual interface{}, expected ...interface{}) string ShouldContain receives exactly two parameters. The first is a slice and the second is a proposed member. Membership is determined using ShouldEqual. +#### func ShouldContainKey + +```go +func ShouldContainKey(actual interface{}, expected ...interface{}) string +``` +ShouldContainKey receives exactly two parameters. The first is a map and the +second is a proposed key. Keys are compared with a simple '=='. + #### func ShouldContainSubstring ```go @@ -175,6 +189,24 @@ func ShouldEqual(actual interface{}, expected ...interface{}) string ``` ShouldEqual receives exactly two parameters and does an equality check. +#### func ShouldEqualTrimSpace + +```go +func ShouldEqualTrimSpace(actual interface{}, expected ...interface{}) string +``` +ShouldEqualTrimSpace receives exactly 2 string parameters and ensures that the +first is equal to the second after removing all leading and trailing whitespace +using strings.TrimSpace(first). + +#### func ShouldEqualWithout + +```go +func ShouldEqualWithout(actual interface{}, expected ...interface{}) string +``` +ShouldEqualWithout receives exactly 3 string parameters and ensures that the +first is equal to the second after removing all instances of the third from the +first using strings.Replace(first, third, "", -1). + #### func ShouldHappenAfter ```go @@ -232,6 +264,15 @@ ShouldHappenWithin receives a time.Time, a time.Duration, and a time.Time (3 arguments) and asserts that the first time.Time happens within or on the duration specified relative to the other time.Time. +#### func ShouldHaveLength + +```go +func ShouldHaveLength(actual interface{}, expected ...interface{}) string +``` +ShouldHaveLength receives 2 parameters. The first is a collection to check the +length of, the second being the expected length. It obeys the rules specified by +the len function for determining length: http://golang.org/pkg/builtin/#len + #### func ShouldHaveSameTypeAs ```go @@ -316,6 +357,14 @@ func ShouldNotContain(actual interface{}, expected ...interface{}) string ShouldNotContain receives exactly two parameters. The first is a slice and the second is a proposed member. Membership is determinied using ShouldEqual. +#### func ShouldNotContainKey + +```go +func ShouldNotContainKey(actual interface{}, expected ...interface{}) string +``` +ShouldNotContainKey receives exactly two parameters. The first is a map and the +second is a proposed absent key. Keys are compared with a simple '=='. + #### func ShouldNotContainSubstring ```go @@ -488,6 +537,13 @@ func New(t testingT) *Assertion New swallows the *testing.T struct and prints failed assertions using t.Error. Example: assertions.New(t).So(1, should.Equal, 1) +#### func (*Assertion) Failed + +```go +func (this *Assertion) Failed() bool +``` +Failed reports whether any calls to So (on this Assertion instance) have failed. + #### func (*Assertion) So ```go @@ -496,6 +552,20 @@ func (this *Assertion) So(actual interface{}, assert assertion, expected ...inte So calls the standalone So function and additionally, calls t.Error in failure scenarios. +#### type FailureView + +```go +type FailureView struct { + Message string `json:"Message"` + Expected string `json:"Expected"` + Actual string `json:"Actual"` +} +``` + +This struct is also declared in +github.com/smartystreets/goconvey/convey/reporting. The json struct tags should +be equal in both declarations. + #### type Serializer ```go diff --git a/_vendor/github.com/smartystreets/assertions/assertions.goconvey b/_vendor/github.com/smartystreets/assertions/assertions.goconvey deleted file mode 100644 index e76cf27..0000000 --- a/_vendor/github.com/smartystreets/assertions/assertions.goconvey +++ /dev/null @@ -1,3 +0,0 @@ -#ignore --timeout=1s --coverpkg=github.com/smartystreets/assertions,github.com/smartystreets/assertions/internal/oglematchers \ No newline at end of file diff --git a/_vendor/github.com/smartystreets/assertions/collections.go b/_vendor/github.com/smartystreets/assertions/collections.go index d54745e..d7f407e 100644 --- a/_vendor/github.com/smartystreets/assertions/collections.go +++ b/_vendor/github.com/smartystreets/assertions/collections.go @@ -42,6 +42,61 @@ func ShouldNotContain(actual interface{}, expected ...interface{}) string { return fmt.Sprintf(shouldNotHaveContained, typeName, expected[0]) } +// ShouldContainKey receives exactly two parameters. The first is a map and the +// second is a proposed key. Keys are compared with a simple '=='. +func ShouldContainKey(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + + keys, isMap := mapKeys(actual) + if !isMap { + return fmt.Sprintf(shouldHaveBeenAValidMap, reflect.TypeOf(actual)) + } + + if !keyFound(keys, expected[0]) { + return fmt.Sprintf(shouldHaveContainedKey, reflect.TypeOf(actual), expected) + } + + return "" +} + +// ShouldNotContainKey receives exactly two parameters. The first is a map and the +// second is a proposed absent key. Keys are compared with a simple '=='. +func ShouldNotContainKey(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + + keys, isMap := mapKeys(actual) + if !isMap { + return fmt.Sprintf(shouldHaveBeenAValidMap, reflect.TypeOf(actual)) + } + + if keyFound(keys, expected[0]) { + return fmt.Sprintf(shouldNotHaveContainedKey, reflect.TypeOf(actual), expected) + } + + return "" +} + +func mapKeys(m interface{}) ([]reflect.Value, bool) { + value := reflect.ValueOf(m) + if value.Kind() != reflect.Map { + return nil, false + } + return value.MapKeys(), true +} +func keyFound(keys []reflect.Value, expectedKey interface{}) bool { + found := false + for _, key := range keys { + if key.Interface() == expectedKey { + found = true + } + } + return found +} + // ShouldBeIn receives at least 2 parameters. The first is a proposed member of the collection // that is passed in either as the second parameter, or of the collection that is comprised // of all the remaining parameters. This assertion ensures that the proposed member is in @@ -138,3 +193,52 @@ func ShouldNotBeEmpty(actual interface{}, expected ...interface{}) string { } return fmt.Sprintf(shouldNotHaveBeenEmpty, actual) } + +// ShouldHaveLength receives 2 parameters. The first is a collection to check +// the length of, the second being the expected length. It obeys the rules +// specified by the len function for determining length: +// http://golang.org/pkg/builtin/#len +func ShouldHaveLength(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + + var expectedLen int64 + lenValue := reflect.ValueOf(expected[0]) + switch lenValue.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + expectedLen = lenValue.Int() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + expectedLen = int64(lenValue.Uint()) + default: + return fmt.Sprintf(shouldHaveBeenAValidInteger, reflect.TypeOf(expected[0])) + } + + if expectedLen < 0 { + return fmt.Sprintf(shouldHaveBeenAValidLength, expected[0]) + } + + value := reflect.ValueOf(actual) + switch value.Kind() { + case reflect.Slice, + reflect.Chan, + reflect.Map, + reflect.String: + if int64(value.Len()) == expectedLen { + return success + } else { + return fmt.Sprintf(shouldHaveHadLength, actual, value.Len(), expectedLen) + } + case reflect.Ptr: + elem := value.Elem() + kind := elem.Kind() + if kind == reflect.Slice || kind == reflect.Array { + if int64(elem.Len()) == expectedLen { + return success + } else { + return fmt.Sprintf(shouldHaveHadLength, actual, elem.Len(), expectedLen) + } + } + } + return fmt.Sprintf(shouldHaveBeenAValidCollection, reflect.TypeOf(actual)) +} diff --git a/_vendor/github.com/smartystreets/assertions/doc.go b/_vendor/github.com/smartystreets/assertions/doc.go index 7439f13..43ceb6e 100644 --- a/_vendor/github.com/smartystreets/assertions/doc.go +++ b/_vendor/github.com/smartystreets/assertions/doc.go @@ -1,10 +1,21 @@ // Package assertions contains the implementations for all assertions which // are referenced in goconvey's `convey` package -// (github.com/smartystreets/goconvey/convey) for use with the So(...) method. +// (github.com/smartystreets/goconvey/convey) and gunit (github.com/smartystreets/gunit) +// for use with the So(...) method. // They can also be used in traditional Go test functions and even in -// applicaitons. +// applications. +// +// Many of the assertions lean heavily on work done by Aaron Jacobs in his excellent oglematchers library. +// (https://github.com/jacobsa/oglematchers) +// The ShouldResemble assertion leans heavily on work done by Daniel Jacques in his very helpful go-render library. +// (https://github.com/luci/go-render) package assertions +import ( + "fmt" + "runtime" +) + // By default we use a no-op serializer. The actual Serializer provides a JSON // representation of failure results on selected assertions so the goconvey // web UI can display a convenient diff. @@ -15,7 +26,7 @@ var serializer Serializer = new(noopSerializer) // are very helpful and can be rendered in a DIFF view. In that case, this function // will be called with a true value to enable the JSON serialization. By default, // the assertions in this package will not serializer a JSON result, making -// standalone ussage more convenient. +// standalone usage more convenient. func GoConveyMode(yes bool) { if yes { serializer = newSerializer() @@ -28,19 +39,29 @@ type testingT interface { Error(args ...interface{}) } -type Assertion struct{ t testingT } +type Assertion struct { + t testingT + failed bool +} // New swallows the *testing.T struct and prints failed assertions using t.Error. // Example: assertions.New(t).So(1, should.Equal, 1) func New(t testingT) *Assertion { - return &Assertion{t} + return &Assertion{t: t} +} + +// Failed reports whether any calls to So (on this Assertion instance) have failed. +func (this *Assertion) Failed() bool { + return this.failed } // So calls the standalone So function and additionally, calls t.Error in failure scenarios. func (this *Assertion) So(actual interface{}, assert assertion, expected ...interface{}) bool { ok, result := So(actual, assert, expected...) if !ok { - this.t.Error("\n" + result) + this.failed = true + _, file, line, _ := runtime.Caller(1) + this.t.Error(fmt.Sprintf("\n%s:%d\n%s", file, line, result)) } return ok } diff --git a/_vendor/github.com/smartystreets/assertions/equality.go b/_vendor/github.com/smartystreets/assertions/equality.go index 15127b3..1e5957e 100644 --- a/_vendor/github.com/smartystreets/assertions/equality.go +++ b/_vendor/github.com/smartystreets/assertions/equality.go @@ -7,12 +7,10 @@ import ( "reflect" "strings" + "github.com/smartystreets/assertions/internal/go-render/render" "github.com/smartystreets/assertions/internal/oglematchers" ) -// default acceptable delta for ShouldAlmostEqual -const defaultDelta = 0.0000000001 - // ShouldEqual receives exactly two parameters and does an equality check. func ShouldEqual(actual interface{}, expected ...interface{}) string { if message := need(1, expected); message != success { @@ -29,7 +27,14 @@ func shouldEqual(actual, expected interface{}) (message string) { }() if matchError := oglematchers.Equals(expected).Matches(actual); matchError != nil { - message = serializer.serialize(expected, actual, fmt.Sprintf(shouldHaveBeenEqual, expected, actual)) + expectedSyntax := fmt.Sprintf("%v", expected) + actualSyntax := fmt.Sprintf("%v", actual) + if expectedSyntax == actualSyntax && reflect.TypeOf(expected) != reflect.TypeOf(actual) { + message = fmt.Sprintf(shouldHaveBeenEqualTypeMismatch, expected, expected, actual, actual) + } else { + message = fmt.Sprintf(shouldHaveBeenEqual, expected, actual) + } + message = serializer.serialize(expected, actual, message) return } @@ -87,7 +92,7 @@ func cleanAlmostEqualInput(actual interface{}, expected ...interface{}) (float64 delta, err := getFloat(expected[1]) if err != nil { - return 0.0, 0.0, 0.0, "delta must be a numerical type" + return 0.0, 0.0, 0.0, "The delta value " + err.Error() } deltaFloat = delta @@ -96,15 +101,13 @@ func cleanAlmostEqualInput(actual interface{}, expected ...interface{}) (float64 } actualFloat, err := getFloat(actual) - if err != nil { - return 0.0, 0.0, 0.0, err.Error() + return 0.0, 0.0, 0.0, "The actual value " + err.Error() } expectedFloat, err := getFloat(expected[0]) - if err != nil { - return 0.0, 0.0, 0.0, err.Error() + return 0.0, 0.0, 0.0, "The comparison value " + err.Error() } return actualFloat, expectedFloat, deltaFloat, "" @@ -131,7 +134,7 @@ func getFloat(num interface{}) (float64, error) { numKind == reflect.Float64 { return numValue.Float(), nil } else { - return 0.0, errors.New("must be a numerical type, but was " + numKind.String()) + return 0.0, errors.New("must be a numerical type, but was: " + numKind.String()) } } @@ -142,15 +145,8 @@ func ShouldResemble(actual interface{}, expected ...interface{}) string { } if matchError := oglematchers.DeepEquals(expected[0]).Matches(actual); matchError != nil { - expectedSyntax := fmt.Sprintf("%#v", expected[0]) - actualSyntax := fmt.Sprintf("%#v", actual) - var message string - if expectedSyntax == actualSyntax { - message = fmt.Sprintf(shouldHaveResembledTypeMismatch, expected[0], actual, expected[0], actual) - } else { - message = fmt.Sprintf(shouldHaveResembled, expected[0], actual) - } - return serializer.serializeDetailed(expected[0], actual, message) + return serializer.serializeDetailed(expected[0], actual, + fmt.Sprintf(shouldHaveResembled, render.Render(expected[0]), render.Render(actual))) } return success @@ -161,7 +157,7 @@ func ShouldNotResemble(actual interface{}, expected ...interface{}) string { if message := need(1, expected); message != success { return message } else if ShouldResemble(actual, expected[0]) == success { - return fmt.Sprintf(shouldNotHaveResembled, actual, expected[0]) + return fmt.Sprintf(shouldNotHaveResembled, render.Render(actual), render.Render(expected[0])) } return success } diff --git a/_vendor/github.com/smartystreets/assertions/filter.go b/_vendor/github.com/smartystreets/assertions/filter.go index ee368a9..7c46ab8 100644 --- a/_vendor/github.com/smartystreets/assertions/filter.go +++ b/_vendor/github.com/smartystreets/assertions/filter.go @@ -6,6 +6,7 @@ const ( success = "" needExactValues = "This assertion requires exactly %d comparison values (you provided %d)." needNonEmptyCollection = "This assertion requires at least 1 comparison value (you provided 0)." + needFewerValues = "This assertion allows %d or fewer comparison values (you provided %d)." ) func need(needed int, expected []interface{}) string { @@ -21,3 +22,10 @@ func atLeast(minimum int, expected []interface{}) string { } return success } + +func atMost(max int, expected []interface{}) string { + if len(expected) > max { + return fmt.Sprintf(needFewerValues, max, len(expected)) + } + return success +} diff --git a/_vendor/github.com/smartystreets/assertions/internal/Makefile b/_vendor/github.com/smartystreets/assertions/internal/Makefile deleted file mode 100644 index 7147680..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -# This Makefile pulls the latest oglematchers (with dependencies), -# rewrites the imports to match this location, -# and ensures that all the tests pass. - -go: clean clone rewrite test - -clean: - rm -rf ogle* - rm -rf reqtrace - -clone: - git clone https://github.com/jacobsa/ogletest.git && rm -rf ogletest/.git - git clone https://github.com/jacobsa/oglemock.git && rm -rf oglemock/.git - git clone https://github.com/jacobsa/oglematchers.git && rm -rf oglematchers/.git - git clone https://github.com/jacobsa/reqtrace.git && rm -rf reqtrace/.git - -rewrite: - grep -rl --exclude Makefile 'github.com/jacobsa' . | xargs sed -i '' 's#github.com/jacobsa#github.com/smartystreets/assertions/internal#g' - -test: - go test github.com/smartystreets/assertions/... diff --git a/_vendor/github.com/smartystreets/assertions/internal/go-render/render/render.go b/_vendor/github.com/smartystreets/assertions/internal/go-render/render/render.go new file mode 100644 index 0000000..23b7a58 --- /dev/null +++ b/_vendor/github.com/smartystreets/assertions/internal/go-render/render/render.go @@ -0,0 +1,477 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package render + +import ( + "bytes" + "fmt" + "reflect" + "sort" + "strconv" +) + +var builtinTypeMap = map[reflect.Kind]string{ + reflect.Bool: "bool", + reflect.Complex128: "complex128", + reflect.Complex64: "complex64", + reflect.Float32: "float32", + reflect.Float64: "float64", + reflect.Int16: "int16", + reflect.Int32: "int32", + reflect.Int64: "int64", + reflect.Int8: "int8", + reflect.Int: "int", + reflect.String: "string", + reflect.Uint16: "uint16", + reflect.Uint32: "uint32", + reflect.Uint64: "uint64", + reflect.Uint8: "uint8", + reflect.Uint: "uint", + reflect.Uintptr: "uintptr", +} + +var builtinTypeSet = map[string]struct{}{} + +func init() { + for _, v := range builtinTypeMap { + builtinTypeSet[v] = struct{}{} + } +} + +var typeOfString = reflect.TypeOf("") +var typeOfInt = reflect.TypeOf(int(1)) +var typeOfUint = reflect.TypeOf(uint(1)) +var typeOfFloat = reflect.TypeOf(10.1) + +// Render converts a structure to a string representation. Unline the "%#v" +// format string, this resolves pointer types' contents in structs, maps, and +// slices/arrays and prints their field values. +func Render(v interface{}) string { + buf := bytes.Buffer{} + s := (*traverseState)(nil) + s.render(&buf, 0, reflect.ValueOf(v), false) + return buf.String() +} + +// renderPointer is called to render a pointer value. +// +// This is overridable so that the test suite can have deterministic pointer +// values in its expectations. +var renderPointer = func(buf *bytes.Buffer, p uintptr) { + fmt.Fprintf(buf, "0x%016x", p) +} + +// traverseState is used to note and avoid recursion as struct members are being +// traversed. +// +// traverseState is allowed to be nil. Specifically, the root state is nil. +type traverseState struct { + parent *traverseState + ptr uintptr +} + +func (s *traverseState) forkFor(ptr uintptr) *traverseState { + for cur := s; cur != nil; cur = cur.parent { + if ptr == cur.ptr { + return nil + } + } + + fs := &traverseState{ + parent: s, + ptr: ptr, + } + return fs +} + +func (s *traverseState) render(buf *bytes.Buffer, ptrs int, v reflect.Value, implicit bool) { + if v.Kind() == reflect.Invalid { + buf.WriteString("nil") + return + } + vt := v.Type() + + // If the type being rendered is a potentially recursive type (a type that + // can contain itself as a member), we need to avoid recursion. + // + // If we've already seen this type before, mark that this is the case and + // write a recursion placeholder instead of actually rendering it. + // + // If we haven't seen it before, fork our `seen` tracking so any higher-up + // renderers will also render it at least once, then mark that we've seen it + // to avoid recursing on lower layers. + pe := uintptr(0) + vk := vt.Kind() + switch vk { + case reflect.Ptr: + // Since structs and arrays aren't pointers, they can't directly be + // recursed, but they can contain pointers to themselves. Record their + // pointer to avoid this. + switch v.Elem().Kind() { + case reflect.Struct, reflect.Array: + pe = v.Pointer() + } + + case reflect.Slice, reflect.Map: + pe = v.Pointer() + } + if pe != 0 { + s = s.forkFor(pe) + if s == nil { + buf.WriteString("") + return + } + } + + isAnon := func(t reflect.Type) bool { + if t.Name() != "" { + if _, ok := builtinTypeSet[t.Name()]; !ok { + return false + } + } + return t.Kind() != reflect.Interface + } + + switch vk { + case reflect.Struct: + if !implicit { + writeType(buf, ptrs, vt) + } + structAnon := vt.Name() == "" + buf.WriteRune('{') + for i := 0; i < vt.NumField(); i++ { + if i > 0 { + buf.WriteString(", ") + } + anon := structAnon && isAnon(vt.Field(i).Type) + + if !anon { + buf.WriteString(vt.Field(i).Name) + buf.WriteRune(':') + } + + s.render(buf, 0, v.Field(i), anon) + } + buf.WriteRune('}') + + case reflect.Slice: + if v.IsNil() { + if !implicit { + writeType(buf, ptrs, vt) + buf.WriteString("(nil)") + } else { + buf.WriteString("nil") + } + return + } + fallthrough + + case reflect.Array: + if !implicit { + writeType(buf, ptrs, vt) + } + anon := vt.Name() == "" && isAnon(vt.Elem()) + buf.WriteString("{") + for i := 0; i < v.Len(); i++ { + if i > 0 { + buf.WriteString(", ") + } + + s.render(buf, 0, v.Index(i), anon) + } + buf.WriteRune('}') + + case reflect.Map: + if !implicit { + writeType(buf, ptrs, vt) + } + if v.IsNil() { + buf.WriteString("(nil)") + } else { + buf.WriteString("{") + + mkeys := v.MapKeys() + tryAndSortMapKeys(vt, mkeys) + + kt := vt.Key() + keyAnon := typeOfString.ConvertibleTo(kt) || typeOfInt.ConvertibleTo(kt) || typeOfUint.ConvertibleTo(kt) || typeOfFloat.ConvertibleTo(kt) + valAnon := vt.Name() == "" && isAnon(vt.Elem()) + for i, mk := range mkeys { + if i > 0 { + buf.WriteString(", ") + } + + s.render(buf, 0, mk, keyAnon) + buf.WriteString(":") + s.render(buf, 0, v.MapIndex(mk), valAnon) + } + buf.WriteRune('}') + } + + case reflect.Ptr: + ptrs++ + fallthrough + case reflect.Interface: + if v.IsNil() { + writeType(buf, ptrs, v.Type()) + buf.WriteString("(nil)") + } else { + s.render(buf, ptrs, v.Elem(), false) + } + + case reflect.Chan, reflect.Func, reflect.UnsafePointer: + writeType(buf, ptrs, vt) + buf.WriteRune('(') + renderPointer(buf, v.Pointer()) + buf.WriteRune(')') + + default: + tstr := vt.String() + implicit = implicit || (ptrs == 0 && builtinTypeMap[vk] == tstr) + if !implicit { + writeType(buf, ptrs, vt) + buf.WriteRune('(') + } + + switch vk { + case reflect.String: + fmt.Fprintf(buf, "%q", v.String()) + case reflect.Bool: + fmt.Fprintf(buf, "%v", v.Bool()) + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + fmt.Fprintf(buf, "%d", v.Int()) + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + fmt.Fprintf(buf, "%d", v.Uint()) + + case reflect.Float32, reflect.Float64: + fmt.Fprintf(buf, "%g", v.Float()) + + case reflect.Complex64, reflect.Complex128: + fmt.Fprintf(buf, "%g", v.Complex()) + } + + if !implicit { + buf.WriteRune(')') + } + } +} + +func writeType(buf *bytes.Buffer, ptrs int, t reflect.Type) { + parens := ptrs > 0 + switch t.Kind() { + case reflect.Chan, reflect.Func, reflect.UnsafePointer: + parens = true + } + + if parens { + buf.WriteRune('(') + for i := 0; i < ptrs; i++ { + buf.WriteRune('*') + } + } + + switch t.Kind() { + case reflect.Ptr: + if ptrs == 0 { + // This pointer was referenced from within writeType (e.g., as part of + // rendering a list), and so hasn't had its pointer asterisk accounted + // for. + buf.WriteRune('*') + } + writeType(buf, 0, t.Elem()) + + case reflect.Interface: + if n := t.Name(); n != "" { + buf.WriteString(t.String()) + } else { + buf.WriteString("interface{}") + } + + case reflect.Array: + buf.WriteRune('[') + buf.WriteString(strconv.FormatInt(int64(t.Len()), 10)) + buf.WriteRune(']') + writeType(buf, 0, t.Elem()) + + case reflect.Slice: + if t == reflect.SliceOf(t.Elem()) { + buf.WriteString("[]") + writeType(buf, 0, t.Elem()) + } else { + // Custom slice type, use type name. + buf.WriteString(t.String()) + } + + case reflect.Map: + if t == reflect.MapOf(t.Key(), t.Elem()) { + buf.WriteString("map[") + writeType(buf, 0, t.Key()) + buf.WriteRune(']') + writeType(buf, 0, t.Elem()) + } else { + // Custom map type, use type name. + buf.WriteString(t.String()) + } + + default: + buf.WriteString(t.String()) + } + + if parens { + buf.WriteRune(')') + } +} + +type cmpFn func(a, b reflect.Value) int + +type sortableValueSlice struct { + cmp cmpFn + elements []reflect.Value +} + +func (s sortableValueSlice) Len() int { + return len(s.elements) +} + +func (s sortableValueSlice) Less(i, j int) bool { + return s.cmp(s.elements[i], s.elements[j]) < 0 +} + +func (s sortableValueSlice) Swap(i, j int) { + s.elements[i], s.elements[j] = s.elements[j], s.elements[i] +} + +// cmpForType returns a cmpFn which sorts the data for some type t in the same +// order that a go-native map key is compared for equality. +func cmpForType(t reflect.Type) cmpFn { + switch t.Kind() { + case reflect.String: + return func(av, bv reflect.Value) int { + a, b := av.String(), bv.String() + if a < b { + return -1 + } else if a > b { + return 1 + } + return 0 + } + + case reflect.Bool: + return func(av, bv reflect.Value) int { + a, b := av.Bool(), bv.Bool() + if !a && b { + return -1 + } else if a && !b { + return 1 + } + return 0 + } + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return func(av, bv reflect.Value) int { + a, b := av.Int(), bv.Int() + if a < b { + return -1 + } else if a > b { + return 1 + } + return 0 + } + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, + reflect.Uint64, reflect.Uintptr, reflect.UnsafePointer: + return func(av, bv reflect.Value) int { + a, b := av.Uint(), bv.Uint() + if a < b { + return -1 + } else if a > b { + return 1 + } + return 0 + } + + case reflect.Float32, reflect.Float64: + return func(av, bv reflect.Value) int { + a, b := av.Float(), bv.Float() + if a < b { + return -1 + } else if a > b { + return 1 + } + return 0 + } + + case reflect.Interface: + return func(av, bv reflect.Value) int { + a, b := av.InterfaceData(), bv.InterfaceData() + if a[0] < b[0] { + return -1 + } else if a[0] > b[0] { + return 1 + } + if a[1] < b[1] { + return -1 + } else if a[1] > b[1] { + return 1 + } + return 0 + } + + case reflect.Complex64, reflect.Complex128: + return func(av, bv reflect.Value) int { + a, b := av.Complex(), bv.Complex() + if real(a) < real(b) { + return -1 + } else if real(a) > real(b) { + return 1 + } + if imag(a) < imag(b) { + return -1 + } else if imag(a) > imag(b) { + return 1 + } + return 0 + } + + case reflect.Ptr, reflect.Chan: + return func(av, bv reflect.Value) int { + a, b := av.Pointer(), bv.Pointer() + if a < b { + return -1 + } else if a > b { + return 1 + } + return 0 + } + + case reflect.Struct: + cmpLst := make([]cmpFn, t.NumField()) + for i := range cmpLst { + cmpLst[i] = cmpForType(t.Field(i).Type) + } + return func(a, b reflect.Value) int { + for i, cmp := range cmpLst { + if rslt := cmp(a.Field(i), b.Field(i)); rslt != 0 { + return rslt + } + } + return 0 + } + } + + return nil +} + +func tryAndSortMapKeys(mt reflect.Type, k []reflect.Value) { + if cmp := cmpForType(mt.Key()); cmp != nil { + sort.Sort(sortableValueSlice{cmp, k}) + } +} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/.travis.yml b/_vendor/github.com/smartystreets/assertions/internal/oglematchers/.travis.yml new file mode 100644 index 0000000..b972119 --- /dev/null +++ b/_vendor/github.com/smartystreets/assertions/internal/oglematchers/.travis.yml @@ -0,0 +1,4 @@ +# Cf. http://docs.travis-ci.com/user/getting-started/ +# Cf. http://docs.travis-ci.com/user/languages/go/ + +language: go diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/all_of.go b/_vendor/github.com/smartystreets/assertions/internal/oglematchers/all_of.go deleted file mode 100644 index d93a974..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/all_of.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "strings" -) - -// AllOf accepts a set of matchers S and returns a matcher that follows the -// algorithm below when considering a candidate c: -// -// 1. Return true if for every Matcher m in S, m matches c. -// -// 2. Otherwise, if there is a matcher m in S such that m returns a fatal -// error for c, return that matcher's error message. -// -// 3. Otherwise, return false with the error from some wrapped matcher. -// -// This is akin to a logical AND operation for matchers. -func AllOf(matchers ...Matcher) Matcher { - return &allOfMatcher{matchers} -} - -type allOfMatcher struct { - wrappedMatchers []Matcher -} - -func (m *allOfMatcher) Description() string { - // Special case: the empty set. - if len(m.wrappedMatchers) == 0 { - return "is anything" - } - - // Join the descriptions for the wrapped matchers. - wrappedDescs := make([]string, len(m.wrappedMatchers)) - for i, wrappedMatcher := range m.wrappedMatchers { - wrappedDescs[i] = wrappedMatcher.Description() - } - - return strings.Join(wrappedDescs, ", and ") -} - -func (m *allOfMatcher) Matches(c interface{}) (err error) { - for _, wrappedMatcher := range m.wrappedMatchers { - if wrappedErr := wrappedMatcher.Matches(c); wrappedErr != nil { - err = wrappedErr - - // If the error is fatal, return immediately with this error. - _, ok := wrappedErr.(*FatalError) - if ok { - return - } - } - } - - return -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/any.go b/_vendor/github.com/smartystreets/assertions/internal/oglematchers/any.go deleted file mode 100644 index f6991ec..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/any.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -// Any returns a matcher that matches any value. -func Any() Matcher { - return &anyMatcher{} -} - -type anyMatcher struct { -} - -func (m *anyMatcher) Description() string { - return "is anything" -} - -func (m *anyMatcher) Matches(c interface{}) error { - return nil -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/contains.go b/_vendor/github.com/smartystreets/assertions/internal/oglematchers/contains.go index 2f326db..87f107d 100644 --- a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/contains.go +++ b/_vendor/github.com/smartystreets/assertions/internal/oglematchers/contains.go @@ -28,7 +28,7 @@ func Contains(x interface{}) Matcher { var ok bool if result.elementMatcher, ok = x.(Matcher); !ok { - result.elementMatcher = Equals(x) + result.elementMatcher = DeepEquals(x) } return &result diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/elements_are.go b/_vendor/github.com/smartystreets/assertions/internal/oglematchers/elements_are.go deleted file mode 100644 index 2941847..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/elements_are.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" - "reflect" - "strings" -) - -// Given a list of arguments M, ElementsAre returns a matcher that matches -// arrays and slices A where all of the following hold: -// -// * A is the same length as M. -// -// * For each i < len(A) where M[i] is a matcher, A[i] matches M[i]. -// -// * For each i < len(A) where M[i] is not a matcher, A[i] matches -// Equals(M[i]). -// -func ElementsAre(M ...interface{}) Matcher { - // Copy over matchers, or convert to Equals(x) for non-matcher x. - subMatchers := make([]Matcher, len(M)) - for i, x := range M { - if matcher, ok := x.(Matcher); ok { - subMatchers[i] = matcher - continue - } - - subMatchers[i] = Equals(x) - } - - return &elementsAreMatcher{subMatchers} -} - -type elementsAreMatcher struct { - subMatchers []Matcher -} - -func (m *elementsAreMatcher) Description() string { - subDescs := make([]string, len(m.subMatchers)) - for i, sm := range m.subMatchers { - subDescs[i] = sm.Description() - } - - return fmt.Sprintf("elements are: [%s]", strings.Join(subDescs, ", ")) -} - -func (m *elementsAreMatcher) Matches(candidates interface{}) error { - // The candidate must be a slice or an array. - v := reflect.ValueOf(candidates) - if v.Kind() != reflect.Slice && v.Kind() != reflect.Array { - return NewFatalError("which is not a slice or array") - } - - // The length must be correct. - if v.Len() != len(m.subMatchers) { - return errors.New(fmt.Sprintf("which is of length %d", v.Len())) - } - - // Check each element. - for i, subMatcher := range m.subMatchers { - c := v.Index(i) - if matchErr := subMatcher.Matches(c.Interface()); matchErr != nil { - // Return an errors indicating which element doesn't match. If the - // matcher error was fatal, make this one fatal too. - err := errors.New(fmt.Sprintf("whose element %d doesn't match", i)) - if _, isFatal := matchErr.(*FatalError); isFatal { - err = NewFatalError(err.Error()) - } - - return err - } - } - - return nil -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/equals.go b/_vendor/github.com/smartystreets/assertions/internal/oglematchers/equals.go index 26280c5..a510707 100644 --- a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/equals.go +++ b/_vendor/github.com/smartystreets/assertions/internal/oglematchers/equals.go @@ -86,7 +86,7 @@ func isSignedInteger(v reflect.Value) bool { func isUnsignedInteger(v reflect.Value) bool { k := v.Kind() - return k >= reflect.Uint && k <= reflect.Uint64 + return k >= reflect.Uint && k <= reflect.Uintptr } func isInteger(v reflect.Value) bool { @@ -313,19 +313,6 @@ func checkAgainstBool(e bool, c reflect.Value) (err error) { return } -func checkAgainstUintptr(e uintptr, c reflect.Value) (err error) { - if c.Kind() != reflect.Uintptr { - err = NewFatalError("which is not a uintptr") - return - } - - err = errors.New("") - if uintptr(c.Uint()) == e { - err = nil - } - return -} - func checkAgainstChan(e reflect.Value, c reflect.Value) (err error) { // Create a description of e's type, e.g. "chan int". typeStr := fmt.Sprintf("%s %s", e.Type().ChanDir(), e.Type().Elem()) @@ -501,9 +488,6 @@ func (m *equalsMatcher) Matches(candidate interface{}) error { case isUnsignedInteger(e): return checkAgainstUint64(e.Uint(), c) - case ek == reflect.Uintptr: - return checkAgainstUintptr(uintptr(e.Uint()), c) - case ek == reflect.Float32: return checkAgainstFloat32(float32(e.Float()), c) diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/error.go b/_vendor/github.com/smartystreets/assertions/internal/oglematchers/error.go deleted file mode 100644 index 8a078e3..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/error.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -// Error returns a matcher that matches non-nil values implementing the -// built-in error interface for whom the return value of Error() matches the -// supplied matcher. -// -// For example: -// -// err := errors.New("taco burrito") -// -// Error(Equals("taco burrito")) // matches err -// Error(HasSubstr("taco")) // matches err -// Error(HasSubstr("enchilada")) // doesn't match err -// -func Error(m Matcher) Matcher { - return &errorMatcher{m} -} - -type errorMatcher struct { - wrappedMatcher Matcher -} - -func (m *errorMatcher) Description() string { - return "error " + m.wrappedMatcher.Description() -} - -func (m *errorMatcher) Matches(c interface{}) error { - // Make sure that c is an error. - e, ok := c.(error) - if !ok { - return NewFatalError("which is not an error") - } - - // Pass on the error text to the wrapped matcher. - return m.wrappedMatcher.Matches(e.Error()) -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/has_same_type_as.go b/_vendor/github.com/smartystreets/assertions/internal/oglematchers/has_same_type_as.go deleted file mode 100644 index 3b286f7..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/has_same_type_as.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2015 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "fmt" - "reflect" -) - -// HasSameTypeAs returns a matcher that matches values with exactly the same -// type as the supplied prototype. -func HasSameTypeAs(p interface{}) Matcher { - expected := reflect.TypeOf(p) - pred := func(c interface{}) error { - actual := reflect.TypeOf(c) - if actual != expected { - return fmt.Errorf("which has type %v", actual) - } - - return nil - } - - return NewMatcher(pred, fmt.Sprintf("has type %v", expected)) -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/has_substr.go b/_vendor/github.com/smartystreets/assertions/internal/oglematchers/has_substr.go deleted file mode 100644 index bf5bd6a..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/has_substr.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" - "reflect" - "strings" -) - -// HasSubstr returns a matcher that matches strings containing s as a -// substring. -func HasSubstr(s string) Matcher { - return NewMatcher( - func(c interface{}) error { return hasSubstr(s, c) }, - fmt.Sprintf("has substring \"%s\"", s)) -} - -func hasSubstr(needle string, c interface{}) error { - v := reflect.ValueOf(c) - if v.Kind() != reflect.String { - return NewFatalError("which is not a string") - } - - // Perform the substring search. - haystack := v.String() - if strings.Contains(haystack, needle) { - return nil - } - - return errors.New("") -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/identical_to.go b/_vendor/github.com/smartystreets/assertions/internal/oglematchers/identical_to.go deleted file mode 100644 index ae6460e..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/identical_to.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" - "reflect" -) - -// Is the type comparable according to the definition here? -// -// http://weekly.golang.org/doc/go_spec.html#Comparison_operators -// -func isComparable(t reflect.Type) bool { - switch t.Kind() { - case reflect.Array: - return isComparable(t.Elem()) - - case reflect.Struct: - for i := 0; i < t.NumField(); i++ { - if !isComparable(t.Field(i).Type) { - return false - } - } - - return true - - case reflect.Slice, reflect.Map, reflect.Func: - return false - } - - return true -} - -// Should the supplied type be allowed as an argument to IdenticalTo? -func isLegalForIdenticalTo(t reflect.Type) (bool, error) { - // Allow the zero type. - if t == nil { - return true, nil - } - - // Reference types are always okay; we compare pointers. - switch t.Kind() { - case reflect.Slice, reflect.Map, reflect.Func, reflect.Chan: - return true, nil - } - - // Reject other non-comparable types. - if !isComparable(t) { - return false, errors.New(fmt.Sprintf("%v is not comparable", t)) - } - - return true, nil -} - -// IdenticalTo(x) returns a matcher that matches values v with type identical -// to x such that: -// -// 1. If v and x are of a reference type (slice, map, function, channel), then -// they are either both nil or are references to the same object. -// -// 2. Otherwise, if v and x are not of a reference type but have a valid type, -// then v == x. -// -// If v and x are both the invalid type (which results from the predeclared nil -// value, or from nil interface variables), then the matcher is satisfied. -// -// This function will panic if x is of a value type that is not comparable. For -// example, x cannot be an array of functions. -func IdenticalTo(x interface{}) Matcher { - t := reflect.TypeOf(x) - - // Reject illegal arguments. - if ok, err := isLegalForIdenticalTo(t); !ok { - panic("IdenticalTo: " + err.Error()) - } - - return &identicalToMatcher{x} -} - -type identicalToMatcher struct { - x interface{} -} - -func (m *identicalToMatcher) Description() string { - t := reflect.TypeOf(m.x) - return fmt.Sprintf("identical to <%v> %v", t, m.x) -} - -func (m *identicalToMatcher) Matches(c interface{}) error { - // Make sure the candidate's type is correct. - t := reflect.TypeOf(m.x) - if ct := reflect.TypeOf(c); t != ct { - return NewFatalError(fmt.Sprintf("which is of type %v", ct)) - } - - // Special case: two values of the invalid type are always identical. - if t == nil { - return nil - } - - // Handle reference types. - switch t.Kind() { - case reflect.Slice, reflect.Map, reflect.Func, reflect.Chan: - xv := reflect.ValueOf(m.x) - cv := reflect.ValueOf(c) - if xv.Pointer() == cv.Pointer() { - return nil - } - - return errors.New("which is not an identical reference") - } - - // Are the values equal? - if m.x == c { - return nil - } - - return errors.New("") -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/matches_regexp.go b/_vendor/github.com/smartystreets/assertions/internal/oglematchers/matches_regexp.go deleted file mode 100644 index 1ed63f3..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/matches_regexp.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" - "reflect" - "regexp" -) - -// MatchesRegexp returns a matcher that matches strings and byte slices whose -// contents match the supplied regular expression. The semantics are those of -// regexp.Match. In particular, that means the match is not implicitly anchored -// to the ends of the string: MatchesRegexp("bar") will match "foo bar baz". -func MatchesRegexp(pattern string) Matcher { - re, err := regexp.Compile(pattern) - if err != nil { - panic("MatchesRegexp: " + err.Error()) - } - - return &matchesRegexpMatcher{re} -} - -type matchesRegexpMatcher struct { - re *regexp.Regexp -} - -func (m *matchesRegexpMatcher) Description() string { - return fmt.Sprintf("matches regexp \"%s\"", m.re.String()) -} - -func (m *matchesRegexpMatcher) Matches(c interface{}) (err error) { - v := reflect.ValueOf(c) - isString := v.Kind() == reflect.String - isByteSlice := v.Kind() == reflect.Slice && v.Elem().Kind() == reflect.Uint8 - - err = errors.New("") - - switch { - case isString: - if m.re.MatchString(v.String()) { - err = nil - } - - case isByteSlice: - if m.re.Match(v.Bytes()) { - err = nil - } - - default: - err = NewFatalError("which is not a string or []byte") - } - - return -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/new_matcher.go b/_vendor/github.com/smartystreets/assertions/internal/oglematchers/new_matcher.go deleted file mode 100644 index c9d8398..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/new_matcher.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2015 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -// Create a matcher with the given description and predicate function, which -// will be invoked to handle calls to Matchers. -// -// Using this constructor may be a convenience over defining your own type that -// implements Matcher if you do not need any logic in your Description method. -func NewMatcher( - predicate func(interface{}) error, - description string) Matcher { - return &predicateMatcher{ - predicate: predicate, - description: description, - } -} - -type predicateMatcher struct { - predicate func(interface{}) error - description string -} - -func (pm *predicateMatcher) Matches(c interface{}) error { - return pm.predicate(c) -} - -func (pm *predicateMatcher) Description() string { - return pm.description -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/panics.go b/_vendor/github.com/smartystreets/assertions/internal/oglematchers/panics.go deleted file mode 100644 index d2cfc97..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/panics.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" - "reflect" -) - -// Panics matches zero-arg functions which, when invoked, panic with an error -// that matches the supplied matcher. -// -// NOTE(jacobsa): This matcher cannot detect the case where the function panics -// using panic(nil), by design of the language. See here for more info: -// -// http://goo.gl/9aIQL -// -func Panics(m Matcher) Matcher { - return &panicsMatcher{m} -} - -type panicsMatcher struct { - wrappedMatcher Matcher -} - -func (m *panicsMatcher) Description() string { - return "panics with: " + m.wrappedMatcher.Description() -} - -func (m *panicsMatcher) Matches(c interface{}) (err error) { - // Make sure c is a zero-arg function. - v := reflect.ValueOf(c) - if v.Kind() != reflect.Func || v.Type().NumIn() != 0 { - err = NewFatalError("which is not a zero-arg function") - return - } - - // Call the function and check its panic error. - defer func() { - if e := recover(); e != nil { - err = m.wrappedMatcher.Matches(e) - - // Set a clearer error message if the matcher said no. - if err != nil { - wrappedClause := "" - if err.Error() != "" { - wrappedClause = ", " + err.Error() - } - - err = errors.New(fmt.Sprintf("which panicked with: %v%s", e, wrappedClause)) - } - } - }() - - v.Call([]reflect.Value{}) - - // If we get here, the function didn't panic. - err = errors.New("which didn't panic") - return -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/pointee.go b/_vendor/github.com/smartystreets/assertions/internal/oglematchers/pointee.go deleted file mode 100644 index c5383f2..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/pointee.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" - "reflect" -) - -// Return a matcher that matches non-nil pointers whose pointee matches the -// wrapped matcher. -func Pointee(m Matcher) Matcher { - return &pointeeMatcher{m} -} - -type pointeeMatcher struct { - wrapped Matcher -} - -func (m *pointeeMatcher) Matches(c interface{}) (err error) { - // Make sure the candidate is of the appropriate type. - cv := reflect.ValueOf(c) - if !cv.IsValid() || cv.Kind() != reflect.Ptr { - return NewFatalError("which is not a pointer") - } - - // Make sure the candidate is non-nil. - if cv.IsNil() { - return NewFatalError("") - } - - // Defer to the wrapped matcher. Fix up empty errors so that failure messages - // are more helpful than just printing a pointer for "Actual". - pointee := cv.Elem().Interface() - err = m.wrapped.Matches(pointee) - if err != nil && err.Error() == "" { - s := fmt.Sprintf("whose pointee is %v", pointee) - - if _, ok := err.(*FatalError); ok { - err = NewFatalError(s) - } else { - err = errors.New(s) - } - } - - return err -} - -func (m *pointeeMatcher) Description() string { - return fmt.Sprintf("pointee(%s)", m.wrapped.Description()) -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/transform_description.go b/_vendor/github.com/smartystreets/assertions/internal/oglematchers/transform_description.go index f79d0c0..8ea2807 100644 --- a/_vendor/github.com/smartystreets/assertions/internal/oglematchers/transform_description.go +++ b/_vendor/github.com/smartystreets/assertions/internal/oglematchers/transform_description.go @@ -23,7 +23,7 @@ func transformDescription(m Matcher, newDesc string) Matcher { } type transformDescriptionMatcher struct { - desc string + desc string wrappedMatcher Matcher } diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/.gitignore b/_vendor/github.com/smartystreets/assertions/internal/oglemock/.gitignore deleted file mode 100644 index dd8fc74..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -*.6 -6.out -_obj/ -_test/ -_testmain.go diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/LICENSE b/_vendor/github.com/smartystreets/assertions/internal/oglemock/LICENSE deleted file mode 100644 index d645695..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - 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 [yyyy] [name of copyright owner] - - 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/smartystreets/assertions/internal/oglemock/README.md b/_vendor/github.com/smartystreets/assertions/internal/oglemock/README.md deleted file mode 100644 index c5cb5c0..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/README.md +++ /dev/null @@ -1,103 +0,0 @@ -[![GoDoc](https://godoc.org/github.com/smartystreets/assertions/internal/oglemock?status.svg)](https://godoc.org/github.com/smartystreets/assertions/internal/oglemock) - -`oglemock` is a mocking framework for the Go programming language with the -following features: - - * An extensive and extensible set of matchers for expressing call - expectations (provided by the [oglematchers][] package). - - * Clean, readable output that tells you exactly what you need to know. - - * Style and semantics similar to [Google Mock][googlemock] and - [Google JS Test][google-js-test]. - - * Seamless integration with the [ogletest][] unit testing framework. - -It can be integrated into any testing framework (including Go's `testing` -package), but out of the box support is built in to [ogletest][] and that is the -easiest place to use it. - - -Installation ------------- - -First, make sure you have installed Go 1.0.2 or newer. See -[here][golang-install] for instructions. - -Use the following command to install `oglemock` and its dependencies, and to -keep them up to date: - - go get -u github.com/smartystreets/assertions/internal/oglemock - go get -u github.com/smartystreets/assertions/internal/oglemock/createmock - -Those commands will install the `oglemock` package itself, along with the -`createmock` tool that is used to auto-generate mock types. - - -Generating and using mock types -------------------------------- - -Automatically generating a mock implementation of an interface is easy. If you -want to mock interfaces `Bar` and `Baz` from package `foo`, simply run the -following: - - createmock foo Bar Baz - -That will print source code that can be saved to a file and used in your tests. -For example, to create a `mock_io` package containing mock implementations of -`io.Reader` and `io.Writer`: - - mkdir mock_io - createmock io Reader Writer > mock_io/mock_io.go - -The new package will be named `mock_io`, and contain types called `MockReader` -and `MockWriter`, which implement `io.Reader` and `io.Writer` respectively. - -For each generated mock type, there is a corresponding function for creating an -instance of that type given a `Controller` object (see below). For example, to -create a mock reader: - -```go -someController := [...] // See next section. -someReader := mock_io.NewMockReader(someController, "Mock file reader") -``` - -The snippet above creates a mock `io.Reader` that reports failures to -`someController`. The reader can subsequently have expectations set up and be -passed to your code under test that uses an `io.Reader`. - - -Getting ahold of a controller ------------------------------ - -[oglemock.Controller][controller-ref] is used to create mock objects, and to set -up and verify expectations for them. You can create one by calling -`NewController` with an `ErrorReporter`, which is the basic type used to -interface between `oglemock` and the testing framework within which it is being -used. - -If you are using [ogletest][] you don't need to worry about any of this, since -the `TestInfo` struct provided to your test's `SetUp` function already contains -a working `Controller` that you can use to create mock object, and you can use -the built-in `ExpectCall` function for setting expectations. (See the -[ogletest documentation][ogletest-docs] for more info.) Otherwise, you will need -to implement the simple [ErrorReporter interface][reporter-ref] for your test -environment. - - -Documentation -------------- - -For thorough documentation, including information on how to set up expectations, -see [here][oglemock-docs]. - - -[controller-ref]: http://godoc.org/github.com/smartystreets/assertions/internal/oglemock#Controller -[reporter-ref]: http://godoc.org/github.com/smartystreets/assertions/internal/oglemock#ErrorReporter -[golang-install]: http://golang.org/doc/install.html -[google-js-test]: http://code.google.com/p/google-js-test/ -[googlemock]: http://code.google.com/p/googlemock/ -[oglematchers]: https://github.com/smartystreets/assertions/internal/oglematchers -[oglemock-docs]: http://godoc.org/github.com/smartystreets/assertions/internal/oglemock -[ogletest]: https://github.com/smartystreets/assertions/internal/ogletest -[ogletest-docs]: http://godoc.org/github.com/smartystreets/assertions/internal/ogletest diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/action.go b/_vendor/github.com/smartystreets/assertions/internal/oglemock/action.go deleted file mode 100644 index 9fd40d8..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/action.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglemock - -import ( - "reflect" -) - -// Action represents an action to be taken in response to a call to a mock -// method. -type Action interface { - // Set the signature of the function with which this action is being used. - // This must be called before Invoke is called. - SetSignature(signature reflect.Type) error - - // Invoke runs the specified action, given the arguments to the mock method. - // It returns zero or more values that may be treated as the return values of - // the method. If the action doesn't return any values, it may return the nil - // slice. - // - // You must call SetSignature before calling Invoke. - Invoke(methodArgs []interface{}) []interface{} -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/controller.go b/_vendor/github.com/smartystreets/assertions/internal/oglemock/controller.go deleted file mode 100644 index 93a1d62..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/controller.go +++ /dev/null @@ -1,480 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglemock - -import ( - "errors" - "fmt" - "log" - "math" - "reflect" - "sync" -) - -// PartialExpecation is a function that should be called exactly once with -// expected arguments or matchers in order to set up an expected method call. -// See Controller.ExpectMethodCall below. It returns an expectation that can be -// further modified (e.g. by calling WillOnce). -// -// If the arguments are of the wrong type, the function reports a fatal error -// and returns nil. -type PartialExpecation func(...interface{}) Expectation - -// Controller represents an object that implements the central logic of -// oglemock: recording and verifying expectations, responding to mock method -// calls, and so on. -type Controller interface { - // ExpectCall expresses an expectation that the method of the given name - // should be called on the supplied mock object. It returns a function that - // should be called with the expected arguments, matchers for the arguments, - // or a mix of both. - // - // fileName and lineNumber should indicate the line on which the expectation - // was made, if known. - // - // For example: - // - // mockWriter := [...] - // controller.ExpectCall(mockWriter, "Write", "foo.go", 17)(ElementsAre(0x1)) - // .WillOnce(Return(1, nil)) - // - // If the mock object doesn't have a method of the supplied name, the - // function reports a fatal error and returns nil. - ExpectCall( - o MockObject, - methodName string, - fileName string, - lineNumber int) PartialExpecation - - // Finish causes the controller to check for any unsatisfied expectations, - // and report them as errors if they exist. - // - // The controller may panic if any of its methods (including this one) are - // called after Finish is called. - Finish() - - // HandleMethodCall looks for a registered expectation matching the call of - // the given method on mock object o, invokes the appropriate action (if - // any), and returns the values returned by that action (if any). - // - // If the action returns nothing, the controller returns zero values. If - // there is no matching expectation, the controller reports an error and - // returns zero values. - // - // If the mock object doesn't have a method of the supplied name, the - // arguments are of the wrong type, or the action returns the wrong types, - // the function reports a fatal error. - // - // HandleMethodCall is exported for the sake of mock implementations, and - // should not be used directly. - HandleMethodCall( - o MockObject, - methodName string, - fileName string, - lineNumber int, - args []interface{}) []interface{} -} - -// methodMap represents a map from method name to set of expectations for that -// method. -type methodMap map[string][]*InternalExpectation - -// objectMap represents a map from mock object ID to a methodMap for that object. -type objectMap map[uintptr]methodMap - -// NewController sets up a fresh controller, without any expectations set, and -// configures the controller to use the supplied error reporter. -func NewController(reporter ErrorReporter) Controller { - return &controllerImpl{reporter, sync.RWMutex{}, objectMap{}} -} - -type controllerImpl struct { - reporter ErrorReporter - - mutex sync.RWMutex - expectationsByObject objectMap // Protected by mutex -} - -// Return the list of registered expectations for the named method of the -// supplied object, or an empty slice if none have been registered. When this -// method returns, it is guaranteed that c.expectationsByObject has an entry -// for the object. -// -// c.mutex must be held for reading. -func (c *controllerImpl) getExpectationsLocked( - o MockObject, - methodName string) []*InternalExpectation { - id := o.Oglemock_Id() - - // Look up the mock object. - expectationsByMethod, ok := c.expectationsByObject[id] - if !ok { - expectationsByMethod = methodMap{} - c.expectationsByObject[id] = expectationsByMethod - } - - result, ok := expectationsByMethod[methodName] - if !ok { - return []*InternalExpectation{} - } - - return result -} - -// Add an expectation to the list registered for the named method of the -// supplied mock object. -// -// c.mutex must be held for writing. -func (c *controllerImpl) addExpectationLocked( - o MockObject, - methodName string, - exp *InternalExpectation) { - // Get the existing list. - existing := c.getExpectationsLocked(o, methodName) - - // Store a modified list. - id := o.Oglemock_Id() - c.expectationsByObject[id][methodName] = append(existing, exp) -} - -func (c *controllerImpl) ExpectCall( - o MockObject, - methodName string, - fileName string, - lineNumber int) PartialExpecation { - // Find the signature for the requested method. - ov := reflect.ValueOf(o) - method := ov.MethodByName(methodName) - if method.Kind() == reflect.Invalid { - c.reporter.ReportFatalError( - fileName, - lineNumber, - errors.New("Unknown method: "+methodName)) - return nil - } - - partialAlreadyCalled := false // Protected by c.mutex - return func(args ...interface{}) Expectation { - c.mutex.Lock() - defer c.mutex.Unlock() - - // This function should only be called once. - if partialAlreadyCalled { - c.reporter.ReportFatalError( - fileName, - lineNumber, - errors.New("Partial expectation called more than once.")) - return nil - } - - partialAlreadyCalled = true - - // Make sure that the number of args is legal. Keep in mind that the - // method's type has an extra receiver arg. - if len(args) != method.Type().NumIn() { - c.reporter.ReportFatalError( - fileName, - lineNumber, - errors.New( - fmt.Sprintf( - "Expectation for %s given wrong number of arguments: "+ - "expected %d, got %d.", - methodName, - method.Type().NumIn(), - len(args)))) - return nil - } - - // Create an expectation and insert it into the controller's map. - exp := InternalNewExpectation( - c.reporter, - method.Type(), - args, - fileName, - lineNumber) - - c.addExpectationLocked(o, methodName, exp) - - // Return the expectation to the user. - return exp - } -} - -func (c *controllerImpl) Finish() { - c.mutex.Lock() - defer c.mutex.Unlock() - - // Check whether the minimum cardinality for each registered expectation has - // been satisfied. - for _, expectationsByMethod := range c.expectationsByObject { - for methodName, expectations := range expectationsByMethod { - for _, exp := range expectations { - exp.mutex.Lock() - defer exp.mutex.Unlock() - - minCardinality, _ := computeCardinalityLocked(exp) - if exp.NumMatches < minCardinality { - c.reporter.ReportError( - exp.FileName, - exp.LineNumber, - errors.New( - fmt.Sprintf( - "Unsatisfied expectation; expected %s to be called "+ - "at least %d times; called %d times.", - methodName, - minCardinality, - exp.NumMatches))) - } - } - } - } -} - -// expectationMatches checks the matchers for the expectation against the -// supplied arguments. -func expectationMatches(exp *InternalExpectation, args []interface{}) bool { - matchers := exp.ArgMatchers - if len(args) != len(matchers) { - panic("expectationMatches: len(args)") - } - - // Check each matcher. - for i, matcher := range matchers { - if err := matcher.Matches(args[i]); err != nil { - return false - } - } - - return true -} - -// Return the expectation that matches the supplied arguments. If there is more -// than one such expectation, the one furthest along in the list for the method -// is returned. If there is no such expectation, nil is returned. -// -// c.mutex must be held for reading. -func (c *controllerImpl) chooseExpectationLocked( - o MockObject, - methodName string, - args []interface{}) *InternalExpectation { - // Do we have any expectations for this method? - expectations := c.getExpectationsLocked(o, methodName) - if len(expectations) == 0 { - return nil - } - - for i := len(expectations) - 1; i >= 0; i-- { - if expectationMatches(expectations[i], args) { - return expectations[i] - } - } - - return nil -} - -// makeZeroReturnValues creates a []interface{} containing appropriate zero -// values for returning from the supplied method type. -func makeZeroReturnValues(signature reflect.Type) []interface{} { - result := make([]interface{}, signature.NumOut()) - - for i, _ := range result { - outType := signature.Out(i) - zeroVal := reflect.Zero(outType) - result[i] = zeroVal.Interface() - } - - return result -} - -// computeCardinality decides on the [min, max] range of the number of expected -// matches for the supplied expectations, according to the rules documented in -// expectation.go. -// -// exp.mutex must be held for reading. -func computeCardinalityLocked(exp *InternalExpectation) (min, max uint) { - // Explicit cardinality. - if exp.ExpectedNumMatches >= 0 { - min = uint(exp.ExpectedNumMatches) - max = min - return - } - - // Implicit count based on one-time actions. - if len(exp.OneTimeActions) != 0 { - min = uint(len(exp.OneTimeActions)) - max = min - - // If there is a fallback action, this is only a lower bound. - if exp.FallbackAction != nil { - max = math.MaxUint32 - } - - return - } - - // Implicit lack of restriction based on a fallback action being configured. - if exp.FallbackAction != nil { - min = 0 - max = math.MaxUint32 - return - } - - // Implicit cardinality of one. - min = 1 - max = 1 - return -} - -// chooseAction returns the action that should be invoked for the i'th match to -// the supplied expectation (counting from zero). If the implicit "return zero -// values" action should be used, it returns nil. -// -// exp.mutex must be held for reading. -func chooseActionLocked(i uint, exp *InternalExpectation) Action { - // Exhaust one-time actions first. - if i < uint(len(exp.OneTimeActions)) { - return exp.OneTimeActions[i] - } - - // Fallback action (or nil if none is configured). - return exp.FallbackAction -} - -// Find an action for the method call, updating expectation match state in the -// process. Return either an action that should be invoked or a set of zero -// values to return immediately. -// -// This is split out from HandleMethodCall in order to more easily avoid -// invoking the action with locks held. -func (c *controllerImpl) chooseActionAndUpdateExpectations( - o MockObject, - methodName string, - fileName string, - lineNumber int, - args []interface{}, -) (action Action, zeroVals []interface{}) { - c.mutex.Lock() - defer c.mutex.Unlock() - - // Find the signature for the requested method. - ov := reflect.ValueOf(o) - method := ov.MethodByName(methodName) - if method.Kind() == reflect.Invalid { - c.reporter.ReportFatalError( - fileName, - lineNumber, - errors.New("Unknown method: "+methodName), - ) - - // Should never get here in real code. - log.Println("ReportFatalError unexpectedly returned.") - return - } - - // HACK(jacobsa): Make sure we got the correct number of arguments. This will - // need to be refined when issue #5 (variadic methods) is handled. - if len(args) != method.Type().NumIn() { - c.reporter.ReportFatalError( - fileName, - lineNumber, - errors.New( - fmt.Sprintf( - "Wrong number of arguments: expected %d; got %d", - method.Type().NumIn(), - len(args), - ), - ), - ) - - // Should never get here in real code. - log.Println("ReportFatalError unexpectedly returned.") - return - } - - // Find an expectation matching this call. - expectation := c.chooseExpectationLocked(o, methodName, args) - if expectation == nil { - c.reporter.ReportError( - fileName, - lineNumber, - errors.New( - fmt.Sprintf("Unexpected call to %s with args: %v", methodName, args), - ), - ) - - zeroVals = makeZeroReturnValues(method.Type()) - return - } - - expectation.mutex.Lock() - defer expectation.mutex.Unlock() - - // Increase the number of matches recorded, and check whether we're over the - // number expected. - expectation.NumMatches++ - _, maxCardinality := computeCardinalityLocked(expectation) - if expectation.NumMatches > maxCardinality { - c.reporter.ReportError( - expectation.FileName, - expectation.LineNumber, - errors.New( - fmt.Sprintf( - "Unexpected call to %s: "+ - "expected to be called at most %d times; called %d times.", - methodName, - maxCardinality, - expectation.NumMatches, - ), - ), - ) - - zeroVals = makeZeroReturnValues(method.Type()) - return - } - - // Choose an action to invoke. If there is none, just return zero values. - action = chooseActionLocked(expectation.NumMatches-1, expectation) - if action == nil { - zeroVals = makeZeroReturnValues(method.Type()) - return - } - - // Let the action take over. - return -} - -func (c *controllerImpl) HandleMethodCall( - o MockObject, - methodName string, - fileName string, - lineNumber int, - args []interface{}, -) []interface{} { - // Figure out whether to invoke an action or return zero values. - action, zeroVals := c.chooseActionAndUpdateExpectations( - o, - methodName, - fileName, - lineNumber, - args, - ) - - if action != nil { - return action.Invoke(args) - } - - return zeroVals -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/createmock.go b/_vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/createmock.go deleted file mode 100644 index b9243a7..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/createmock.go +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// 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. - -// createmock is used to generate source code for mock versions of interfaces -// from installed packages. -package main - -import ( - "errors" - "flag" - "fmt" - "go/build" - "io/ioutil" - "log" - "os" - "os/exec" - "path" - "regexp" - "text/template" - - // Ensure that the generate package, which is used by the generated code, is - // installed by goinstall. - _ "github.com/smartystreets/assertions/internal/oglemock/generate" -) - -// A template for generated code that is used to print the result. -const tmplStr = ` -{{$inputPkg := .InputPkg}} -{{$outputPkg := .OutputPkg}} - -package main - -import ( - {{range $identifier, $import := .Imports}} - {{$identifier}} "{{$import}}" - {{end}} -) - -func getTypeForPtr(ptr interface{}) reflect.Type { - return reflect.TypeOf(ptr).Elem() -} - -func main() { - // Reduce noise in logging output. - log.SetFlags(0) - - interfaces := []reflect.Type{ - {{range $typeName := .TypeNames}} - getTypeForPtr((*{{base $inputPkg}}.{{$typeName}})(nil)), - {{end}} - } - - err := generate.GenerateMockSource(os.Stdout, "{{$outputPkg}}", interfaces) - if err != nil { - log.Fatalf("Error generating mock source: %v", err) - } -} -` - -// A map from import identifier to package to use that identifier for, -// containing elements for each import needed by the generated code. -type importMap map[string]string - -type tmplArg struct { - InputPkg string - OutputPkg string - - // Imports needed by the generated code. - Imports importMap - - // Types to be mocked, relative to their package's name. - TypeNames []string -} - -var unknownPackageRegexp = regexp.MustCompile( - `tool\.go:\d+:\d+: cannot find package "([^"]+)"`) - -var undefinedInterfaceRegexp = regexp.MustCompile(`tool\.go:\d+: undefined: [\pL_0-9]+\.([\pL_0-9]+)`) - -// Does the 'go build' output indicate that a package wasn't found? If so, -// return the name of the package. -func findUnknownPackage(output []byte) *string { - if match := unknownPackageRegexp.FindSubmatch(output); match != nil { - res := string(match[1]) - return &res - } - - return nil -} - -// Does the 'go build' output indicate that an interface wasn't found? If so, -// return the name of the interface. -func findUndefinedInterface(output []byte) *string { - if match := undefinedInterfaceRegexp.FindSubmatch(output); match != nil { - res := string(match[1]) - return &res - } - - return nil -} - -// Split out from main so that deferred calls are executed even in the event of -// an error. -func run() error { - // Reduce noise in logging output. - log.SetFlags(0) - - // Check the command-line arguments. - flag.Parse() - - cmdLineArgs := flag.Args() - if len(cmdLineArgs) < 2 { - return errors.New("Usage: createmock [package] [interface ...]") - } - - // Create a temporary directory inside of $GOPATH to hold generated code. - buildPkg, err := build.Import("github.com/smartystreets/assertions/internal/oglemock", "", build.FindOnly) - if err != nil { - return errors.New(fmt.Sprintf("Couldn't find oglemock in $GOPATH: %v", err)) - } - - tmpDir, err := ioutil.TempDir(buildPkg.SrcRoot, "tmp-createmock-") - if err != nil { - return errors.New(fmt.Sprintf("Creating temp dir: %v", err)) - } - - defer os.RemoveAll(tmpDir) - - // Create a file to hold generated code. - codeFile, err := os.Create(path.Join(tmpDir, "tool.go")) - if err != nil { - return errors.New(fmt.Sprintf("Couldn't create a file to hold code: %v", err)) - } - - // Create an appropriate path for the built binary. - binaryPath := path.Join(tmpDir, "tool") - - // Create an appropriate template argument. - var arg tmplArg - arg.InputPkg = cmdLineArgs[0] - arg.OutputPkg = "mock_" + path.Base(arg.InputPkg) - arg.TypeNames = cmdLineArgs[1:] - - arg.Imports = make(importMap) - arg.Imports[path.Base(arg.InputPkg)] = arg.InputPkg - arg.Imports["generate"] = "github.com/smartystreets/assertions/internal/oglemock/generate" - arg.Imports["log"] = "log" - arg.Imports["os"] = "os" - arg.Imports["reflect"] = "reflect" - - // Execute the template to generate code that will itself generate the mock - // code. Write the code to the temp file. - tmpl := template.Must( - template.New("code").Funcs( - template.FuncMap{ - "base": path.Base, - }).Parse(tmplStr)) - if err := tmpl.Execute(codeFile, arg); err != nil { - return errors.New(fmt.Sprintf("Error executing template: %v", err)) - } - - codeFile.Close() - - // Attempt to build the code. - cmd := exec.Command("go", "build", "-o", binaryPath) - cmd.Dir = tmpDir - buildOutput, err := cmd.CombinedOutput() - - if err != nil { - // Did the compilation fail due to the user-specified package not being found? - if pkg := findUnknownPackage(buildOutput); pkg != nil && *pkg == arg.InputPkg { - return errors.New(fmt.Sprintf("Unknown package: %s", *pkg)) - } - - // Did the compilation fail due to an unknown interface? - if in := findUndefinedInterface(buildOutput); in != nil { - return errors.New(fmt.Sprintf("Unknown interface: %s", *in)) - } - - // Otherwise return a generic error. - return errors.New(fmt.Sprintf( - "%s\n\nError building generated code:\n\n"+ - " %v\n\nPlease report this oglemock bug.", - buildOutput, - err)) - } - - // Run the binary. - cmd = exec.Command(binaryPath) - binaryOutput, err := cmd.CombinedOutput() - - if err != nil { - return errors.New(fmt.Sprintf( - "%s\n\nError running generated code:\n\n"+ - " %v\n\n Please report this oglemock bug.", - binaryOutput, - err)) - } - - // Copy its output. - _, err = os.Stdout.Write(binaryOutput) - if err != nil { - return errors.New(fmt.Sprintf("Error copying binary output: %v", err)) - } - - return nil -} - -func main() { - if err := run(); err != nil { - fmt.Println(err.Error()) - os.Exit(1) - } -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.no_interfaces b/_vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.no_interfaces deleted file mode 100644 index b70535f..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.no_interfaces +++ /dev/null @@ -1 +0,0 @@ -Usage: createmock [package] [interface ...] diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.no_package b/_vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.no_package deleted file mode 100644 index b70535f..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.no_package +++ /dev/null @@ -1 +0,0 @@ -Usage: createmock [package] [interface ...] diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.unknown_interface b/_vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.unknown_interface deleted file mode 100644 index c32950a..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.unknown_interface +++ /dev/null @@ -1 +0,0 @@ -Unknown interface: Frobnicator diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.unknown_package b/_vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.unknown_package deleted file mode 100644 index d07e915..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/createmock/test_cases/golden.unknown_package +++ /dev/null @@ -1 +0,0 @@ -Unknown package: foo/bar diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/do_all.go b/_vendor/github.com/smartystreets/assertions/internal/oglemock/do_all.go deleted file mode 100644 index c0cd3ff..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/do_all.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2015 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglemock - -import ( - "fmt" - "reflect" -) - -// Create an Action that invokes the supplied actions one after another. The -// return values from the final action are used; others are ignored. -func DoAll(first Action, others ...Action) Action { - return &doAll{ - wrapped: append([]Action{first}, others...), - } -} - -type doAll struct { - wrapped []Action -} - -func (a *doAll) SetSignature(signature reflect.Type) (err error) { - for i, w := range a.wrapped { - err = w.SetSignature(signature) - if err != nil { - err = fmt.Errorf("Action %v: %v", i, err) - return - } - } - - return -} - -func (a *doAll) Invoke(methodArgs []interface{}) (rets []interface{}) { - for _, w := range a.wrapped { - rets = w.Invoke(methodArgs) - } - - return -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/error_reporter.go b/_vendor/github.com/smartystreets/assertions/internal/oglemock/error_reporter.go deleted file mode 100644 index 0c3a65e..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/error_reporter.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglemock - -// ErrorReporter is an interface that wraps methods for reporting errors that -// should cause test failures. -type ErrorReporter interface { - // Report that some failure (e.g. an unsatisfied expectation) occurred. If - // known, fileName and lineNumber should contain information about where it - // occurred. The test may continue if the test framework supports it. - ReportError(fileName string, lineNumber int, err error) - - // Like ReportError, but the test should be halted immediately. It is assumed - // that this method does not return. - ReportFatalError(fileName string, lineNumber int, err error) -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/expectation.go b/_vendor/github.com/smartystreets/assertions/internal/oglemock/expectation.go deleted file mode 100644 index d18bfb8..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/expectation.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglemock - -// Expectation is an expectation for zero or more calls to a mock method with -// particular arguments or sets of arguments. -type Expectation interface { - // Times expresses that a matching method call should happen exactly N times. - // Times must not be called more than once, and must not be called after - // WillOnce or WillRepeatedly. - // - // The full rules for the cardinality of an expectation are as follows: - // - // 1. If an explicit cardinality is set with Times(N), then anything other - // than exactly N matching calls will cause a test failure. - // - // 2. Otherwise, if there are any one-time actions set up, then it is - // expected there will be at least that many matching calls. If there is - // not also a fallback action, then it is expected that there will be - // exactly that many. - // - // 3. Otherwise, if there is a fallback action configured, any number of - // matching calls (including zero) is allowed. - // - // 4. Otherwise, the implicit cardinality is one. - // - Times(n uint) Expectation - - // WillOnce configures a "one-time action". WillOnce can be called zero or - // more times, but must be called after any call to Times and before any call - // to WillRepeatedly. - // - // When matching method calls are made on the mock object, one-time actions - // are invoked one per matching call in the order that they were set up until - // they are exhausted. Afterward the fallback action, if any, will be used. - WillOnce(a Action) Expectation - - // WillRepeatedly configures a "fallback action". WillRepeatedly can be - // called zero or one times, and must not be called before Times or WillOnce. - // - // Once all one-time actions are exhausted (see above), the fallback action - // will be invoked for any further method calls. If WillRepeatedly is not - // called, the fallback action is implicitly an action that returns zero - // values for the method's return values. - WillRepeatedly(a Action) Expectation -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/generate.go b/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/generate.go deleted file mode 100644 index 387367e..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/generate.go +++ /dev/null @@ -1,329 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package generate implements code generation for mock classes. This is an -// implementation detail of the createmock command, which you probably want to -// use directly instead. -package generate - -import ( - "bytes" - "errors" - "go/ast" - "go/parser" - "go/printer" - "go/token" - "io" - "reflect" - "regexp" - "text/template" -) - -const tmplStr = ` -// This file was auto-generated using createmock. See the following page for -// more information: -// -// https://github.com/smartystreets/assertions/internal/oglemock -// - -package {{.Pkg}} - -import ( - {{range $identifier, $import := .Imports}}{{$identifier}} "{{$import}}" - {{end}} -) - -{{range .Interfaces}} - {{$interfaceName := printf "Mock%s" .Name}} - {{$structName := printf "mock%s" .Name}} - - type {{$interfaceName}} interface { - {{getTypeString .}} - oglemock.MockObject - } - - type {{$structName}} struct { - controller oglemock.Controller - description string - } - - func New{{printf "Mock%s" .Name}}( - c oglemock.Controller, - desc string) {{$interfaceName}} { - return &{{$structName}}{ - controller: c, - description: desc, - } - } - - func (m *{{$structName}}) Oglemock_Id() uintptr { - return uintptr(unsafe.Pointer(m)) - } - - func (m *{{$structName}}) Oglemock_Description() string { - return m.description - } - - {{range getMethods .}} - {{$funcType := .Type}} - {{$inputTypes := getInputs $funcType}} - {{$outputTypes := getOutputs $funcType}} - - func (m *{{$structName}}) {{.Name}}({{range $i, $type := $inputTypes}}p{{$i}} {{getInputTypeString $i $funcType}}, {{end}}) ({{range $i, $type := $outputTypes}}o{{$i}} {{getTypeString $type}}, {{end}}) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "{{.Name}}", - file, - line, - []interface{}{ {{range $i, $type := $inputTypes}}p{{$i}}, {{end}} }) - - if len(retVals) != {{len $outputTypes}} { - panic(fmt.Sprintf("{{$structName}}.{{.Name}}: invalid return values: %v", retVals)) - } - - {{range $i, $type := $outputTypes}} - // o{{$i}} {{getTypeString $type}} - if retVals[{{$i}}] != nil { - o{{$i}} = retVals[{{$i}}].({{getTypeString $type}}) - } - {{end}} - - return - } - {{end}} -{{end}} -` - -type tmplArg struct { - // The package of the generated code. - Pkg string - - // Imports needed by the interfaces. - Imports importMap - - // The set of interfaces to mock. - Interfaces []reflect.Type -} - -var tmpl *template.Template - -func init() { - extraFuncs := make(template.FuncMap) - extraFuncs["getMethods"] = getMethods - extraFuncs["getInputs"] = getInputs - extraFuncs["getOutputs"] = getOutputs - extraFuncs["getInputTypeString"] = getInputTypeString - extraFuncs["getTypeString"] = getTypeString - - tmpl = template.New("code") - tmpl.Funcs(extraFuncs) - tmpl.Parse(tmplStr) -} - -func getInputTypeString(i int, ft reflect.Type) string { - numInputs := ft.NumIn() - if i == numInputs-1 && ft.IsVariadic() { - return "..." + getTypeString(ft.In(i).Elem()) - } - - return getTypeString(ft.In(i)) -} - -func getTypeString(t reflect.Type) string { - return t.String() -} - -func getMethods(it reflect.Type) []reflect.Method { - numMethods := it.NumMethod() - methods := make([]reflect.Method, numMethods) - - for i := 0; i < numMethods; i++ { - methods[i] = it.Method(i) - } - - return methods -} - -func getInputs(ft reflect.Type) []reflect.Type { - numIn := ft.NumIn() - inputs := make([]reflect.Type, numIn) - - for i := 0; i < numIn; i++ { - inputs[i] = ft.In(i) - } - - return inputs -} - -func getOutputs(ft reflect.Type) []reflect.Type { - numOut := ft.NumOut() - outputs := make([]reflect.Type, numOut) - - for i := 0; i < numOut; i++ { - outputs[i] = ft.Out(i) - } - - return outputs -} - -// A map from import identifier to package to use that identifier for, -// containing elements for each import needed by a set of mocked interfaces. -type importMap map[string]string - -var typePackageIdentifierRegexp = regexp.MustCompile(`^([\pL_0-9]+)\.[\pL_0-9]+$`) - -// Add an import for the supplied type, without recursing. -func addImportForType(imports importMap, t reflect.Type) { - // If there is no package path, this is a built-in type and we don't need an - // import. - pkgPath := t.PkgPath() - if pkgPath == "" { - return - } - - // Work around a bug in Go: - // - // http://code.google.com/p/go/issues/detail?id=2660 - // - var errorPtr *error - if t == reflect.TypeOf(errorPtr).Elem() { - return - } - - // Use the identifier that's part of the type's string representation as the - // import identifier. This means that we'll do the right thing for package - // "foo/bar" with declaration "package baz". - match := typePackageIdentifierRegexp.FindStringSubmatch(t.String()) - if match == nil { - return - } - - imports[match[1]] = pkgPath -} - -// Add all necessary imports for the type, recursing as appropriate. -func addImportsForType(imports importMap, t reflect.Type) { - // Add any import needed for the type itself. - addImportForType(imports, t) - - // Handle special cases where recursion is needed. - switch t.Kind() { - case reflect.Array, reflect.Chan, reflect.Ptr, reflect.Slice: - addImportsForType(imports, t.Elem()) - - case reflect.Func: - // Input parameters. - for i := 0; i < t.NumIn(); i++ { - addImportsForType(imports, t.In(i)) - } - - // Return values. - for i := 0; i < t.NumOut(); i++ { - addImportsForType(imports, t.Out(i)) - } - - case reflect.Map: - addImportsForType(imports, t.Key()) - addImportsForType(imports, t.Elem()) - } -} - -// Add imports for each of the methods of the interface, but not the interface -// itself. -func addImportsForInterfaceMethods(imports importMap, it reflect.Type) { - // Handle each method. - for i := 0; i < it.NumMethod(); i++ { - m := it.Method(i) - addImportsForType(imports, m.Type) - } -} - -// Given a set of interfaces, return a map from import identifier to package to -// use that identifier for, containing elements for each import needed by the -// mock versions of those interfaces. -func getImports(interfaces []reflect.Type) importMap { - imports := make(importMap) - for _, it := range interfaces { - addImportForType(imports, it) - addImportsForInterfaceMethods(imports, it) - } - - // Make sure there are imports for other types used by the generated code - // itself. - imports["fmt"] = "fmt" - imports["oglemock"] = "github.com/smartystreets/assertions/internal/oglemock" - imports["runtime"] = "runtime" - imports["unsafe"] = "unsafe" - - return imports -} - -// Given a set of interfaces to mock, write out source code for a package named -// `pkg` that contains mock implementations of those interfaces. -func GenerateMockSource(w io.Writer, pkg string, interfaces []reflect.Type) error { - // Sanity-check arguments. - if pkg == "" { - return errors.New("Package name must be non-empty.") - } - - if len(interfaces) == 0 { - return errors.New("List of interfaces must be non-empty.") - } - - // Make sure each type is indeed an interface. - for _, it := range interfaces { - if it.Kind() != reflect.Interface { - return errors.New("Invalid type: " + it.String()) - } - } - - // Create an appropriate template arg, then execute the template. Write the - // raw output into a buffer. - var arg tmplArg - arg.Pkg = pkg - arg.Imports = getImports(interfaces) - arg.Interfaces = interfaces - - buf := new(bytes.Buffer) - if err := tmpl.Execute(buf, arg); err != nil { - return err - } - - // Parse the output. - fset := token.NewFileSet() - astFile, err := parser.ParseFile(fset, pkg+".go", buf, parser.ParseComments) - if err != nil { - return errors.New("Error parsing generated code: " + err.Error()) - } - - // Sort the import lines in the AST in the same way that gofmt does. - ast.SortImports(fset, astFile) - - // Pretty-print the AST, using the same options that gofmt does by default. - cfg := &printer.Config{ - Mode: printer.UseSpaces | printer.TabIndent, - Tabwidth: 8, - } - - if err = cfg.Fprint(w, fset, astFile); err != nil { - return errors.New("Error pretty printing: " + err.Error()) - } - - return nil -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/complicated_pkg/complicated_pkg.go b/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/complicated_pkg/complicated_pkg.go deleted file mode 100644 index 08844fe..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/complicated_pkg/complicated_pkg.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package complicated_pkg contains an interface with lots of interesting -// cases, for use in integration testing. -package complicated_pkg - -import ( - "github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/renamed_pkg" - "image" - "io" - "net" -) - -type Byte uint8 - -type ComplicatedThing interface { - Channels(a chan chan<- <-chan net.Conn) chan int - Pointers(a *int, b *net.Conn, c **io.Reader) (*int, error) - Functions(a func(int, image.Image) int) func(string, int) net.Conn - Maps(a map[string]*int) (map[int]*string, error) - Arrays(a [3]string) ([3]int, error) - Slices(a []string) ([]int, error) - NamedScalarType(a Byte) ([]Byte, error) - EmptyInterface(a interface{}) (interface{}, error) - RenamedPackage(a tony.SomeUint8Alias) - Variadic(a int, b ...net.Conn) int -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.complicated_pkg.go b/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.complicated_pkg.go deleted file mode 100644 index c8c9f79..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.complicated_pkg.go +++ /dev/null @@ -1,311 +0,0 @@ -// This file was auto-generated using createmock. See the following page for -// more information: -// -// https://github.com/smartystreets/assertions/internal/oglemock -// - -package some_pkg - -import ( - fmt "fmt" - oglemock "github.com/smartystreets/assertions/internal/oglemock" - complicated_pkg "github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/complicated_pkg" - tony "github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/renamed_pkg" - image "image" - io "io" - net "net" - runtime "runtime" - unsafe "unsafe" -) - -type MockComplicatedThing interface { - complicated_pkg.ComplicatedThing - oglemock.MockObject -} - -type mockComplicatedThing struct { - controller oglemock.Controller - description string -} - -func NewMockComplicatedThing( - c oglemock.Controller, - desc string) MockComplicatedThing { - return &mockComplicatedThing{ - controller: c, - description: desc, - } -} - -func (m *mockComplicatedThing) Oglemock_Id() uintptr { - return uintptr(unsafe.Pointer(m)) -} - -func (m *mockComplicatedThing) Oglemock_Description() string { - return m.description -} - -func (m *mockComplicatedThing) Arrays(p0 [3]string) (o0 [3]int, o1 error) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Arrays", - file, - line, - []interface{}{p0}) - - if len(retVals) != 2 { - panic(fmt.Sprintf("mockComplicatedThing.Arrays: invalid return values: %v", retVals)) - } - - // o0 [3]int - if retVals[0] != nil { - o0 = retVals[0].([3]int) - } - - // o1 error - if retVals[1] != nil { - o1 = retVals[1].(error) - } - - return -} - -func (m *mockComplicatedThing) Channels(p0 chan chan<- <-chan net.Conn) (o0 chan int) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Channels", - file, - line, - []interface{}{p0}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockComplicatedThing.Channels: invalid return values: %v", retVals)) - } - - // o0 chan int - if retVals[0] != nil { - o0 = retVals[0].(chan int) - } - - return -} - -func (m *mockComplicatedThing) EmptyInterface(p0 interface{}) (o0 interface{}, o1 error) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "EmptyInterface", - file, - line, - []interface{}{p0}) - - if len(retVals) != 2 { - panic(fmt.Sprintf("mockComplicatedThing.EmptyInterface: invalid return values: %v", retVals)) - } - - // o0 interface {} - if retVals[0] != nil { - o0 = retVals[0].(interface{}) - } - - // o1 error - if retVals[1] != nil { - o1 = retVals[1].(error) - } - - return -} - -func (m *mockComplicatedThing) Functions(p0 func(int, image.Image) int) (o0 func(string, int) net.Conn) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Functions", - file, - line, - []interface{}{p0}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockComplicatedThing.Functions: invalid return values: %v", retVals)) - } - - // o0 func(string, int) net.Conn - if retVals[0] != nil { - o0 = retVals[0].(func(string, int) net.Conn) - } - - return -} - -func (m *mockComplicatedThing) Maps(p0 map[string]*int) (o0 map[int]*string, o1 error) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Maps", - file, - line, - []interface{}{p0}) - - if len(retVals) != 2 { - panic(fmt.Sprintf("mockComplicatedThing.Maps: invalid return values: %v", retVals)) - } - - // o0 map[int]*string - if retVals[0] != nil { - o0 = retVals[0].(map[int]*string) - } - - // o1 error - if retVals[1] != nil { - o1 = retVals[1].(error) - } - - return -} - -func (m *mockComplicatedThing) NamedScalarType(p0 complicated_pkg.Byte) (o0 []complicated_pkg.Byte, o1 error) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "NamedScalarType", - file, - line, - []interface{}{p0}) - - if len(retVals) != 2 { - panic(fmt.Sprintf("mockComplicatedThing.NamedScalarType: invalid return values: %v", retVals)) - } - - // o0 []complicated_pkg.Byte - if retVals[0] != nil { - o0 = retVals[0].([]complicated_pkg.Byte) - } - - // o1 error - if retVals[1] != nil { - o1 = retVals[1].(error) - } - - return -} - -func (m *mockComplicatedThing) Pointers(p0 *int, p1 *net.Conn, p2 **io.Reader) (o0 *int, o1 error) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Pointers", - file, - line, - []interface{}{p0, p1, p2}) - - if len(retVals) != 2 { - panic(fmt.Sprintf("mockComplicatedThing.Pointers: invalid return values: %v", retVals)) - } - - // o0 *int - if retVals[0] != nil { - o0 = retVals[0].(*int) - } - - // o1 error - if retVals[1] != nil { - o1 = retVals[1].(error) - } - - return -} - -func (m *mockComplicatedThing) RenamedPackage(p0 tony.SomeUint8Alias) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "RenamedPackage", - file, - line, - []interface{}{p0}) - - if len(retVals) != 0 { - panic(fmt.Sprintf("mockComplicatedThing.RenamedPackage: invalid return values: %v", retVals)) - } - - return -} - -func (m *mockComplicatedThing) Slices(p0 []string) (o0 []int, o1 error) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Slices", - file, - line, - []interface{}{p0}) - - if len(retVals) != 2 { - panic(fmt.Sprintf("mockComplicatedThing.Slices: invalid return values: %v", retVals)) - } - - // o0 []int - if retVals[0] != nil { - o0 = retVals[0].([]int) - } - - // o1 error - if retVals[1] != nil { - o1 = retVals[1].(error) - } - - return -} - -func (m *mockComplicatedThing) Variadic(p0 int, p1 ...net.Conn) (o0 int) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Variadic", - file, - line, - []interface{}{p0, p1}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockComplicatedThing.Variadic: invalid return values: %v", retVals)) - } - - // o0 int - if retVals[0] != nil { - o0 = retVals[0].(int) - } - - return -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.image.go b/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.image.go deleted file mode 100644 index 957186d..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.image.go +++ /dev/null @@ -1,238 +0,0 @@ -// This file was auto-generated using createmock. See the following page for -// more information: -// -// https://github.com/smartystreets/assertions/internal/oglemock -// - -package some_pkg - -import ( - fmt "fmt" - oglemock "github.com/smartystreets/assertions/internal/oglemock" - image "image" - color "image/color" - runtime "runtime" - unsafe "unsafe" -) - -type MockImage interface { - image.Image - oglemock.MockObject -} - -type mockImage struct { - controller oglemock.Controller - description string -} - -func NewMockImage( - c oglemock.Controller, - desc string) MockImage { - return &mockImage{ - controller: c, - description: desc, - } -} - -func (m *mockImage) Oglemock_Id() uintptr { - return uintptr(unsafe.Pointer(m)) -} - -func (m *mockImage) Oglemock_Description() string { - return m.description -} - -func (m *mockImage) At(p0 int, p1 int) (o0 color.Color) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "At", - file, - line, - []interface{}{p0, p1}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockImage.At: invalid return values: %v", retVals)) - } - - // o0 color.Color - if retVals[0] != nil { - o0 = retVals[0].(color.Color) - } - - return -} - -func (m *mockImage) Bounds() (o0 image.Rectangle) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Bounds", - file, - line, - []interface{}{}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockImage.Bounds: invalid return values: %v", retVals)) - } - - // o0 image.Rectangle - if retVals[0] != nil { - o0 = retVals[0].(image.Rectangle) - } - - return -} - -func (m *mockImage) ColorModel() (o0 color.Model) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "ColorModel", - file, - line, - []interface{}{}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockImage.ColorModel: invalid return values: %v", retVals)) - } - - // o0 color.Model - if retVals[0] != nil { - o0 = retVals[0].(color.Model) - } - - return -} - -type MockPalettedImage interface { - image.PalettedImage - oglemock.MockObject -} - -type mockPalettedImage struct { - controller oglemock.Controller - description string -} - -func NewMockPalettedImage( - c oglemock.Controller, - desc string) MockPalettedImage { - return &mockPalettedImage{ - controller: c, - description: desc, - } -} - -func (m *mockPalettedImage) Oglemock_Id() uintptr { - return uintptr(unsafe.Pointer(m)) -} - -func (m *mockPalettedImage) Oglemock_Description() string { - return m.description -} - -func (m *mockPalettedImage) At(p0 int, p1 int) (o0 color.Color) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "At", - file, - line, - []interface{}{p0, p1}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockPalettedImage.At: invalid return values: %v", retVals)) - } - - // o0 color.Color - if retVals[0] != nil { - o0 = retVals[0].(color.Color) - } - - return -} - -func (m *mockPalettedImage) Bounds() (o0 image.Rectangle) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Bounds", - file, - line, - []interface{}{}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockPalettedImage.Bounds: invalid return values: %v", retVals)) - } - - // o0 image.Rectangle - if retVals[0] != nil { - o0 = retVals[0].(image.Rectangle) - } - - return -} - -func (m *mockPalettedImage) ColorIndexAt(p0 int, p1 int) (o0 uint8) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "ColorIndexAt", - file, - line, - []interface{}{p0, p1}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockPalettedImage.ColorIndexAt: invalid return values: %v", retVals)) - } - - // o0 uint8 - if retVals[0] != nil { - o0 = retVals[0].(uint8) - } - - return -} - -func (m *mockPalettedImage) ColorModel() (o0 color.Model) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "ColorModel", - file, - line, - []interface{}{}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockPalettedImage.ColorModel: invalid return values: %v", retVals)) - } - - // o0 color.Model - if retVals[0] != nil { - o0 = retVals[0].(color.Model) - } - - return -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.io_reader_writer.go b/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.io_reader_writer.go deleted file mode 100644 index 59cba86..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.io_reader_writer.go +++ /dev/null @@ -1,127 +0,0 @@ -// This file was auto-generated using createmock. See the following page for -// more information: -// -// https://github.com/smartystreets/assertions/internal/oglemock -// - -package some_pkg - -import ( - fmt "fmt" - oglemock "github.com/smartystreets/assertions/internal/oglemock" - io "io" - runtime "runtime" - unsafe "unsafe" -) - -type MockReader interface { - io.Reader - oglemock.MockObject -} - -type mockReader struct { - controller oglemock.Controller - description string -} - -func NewMockReader( - c oglemock.Controller, - desc string) MockReader { - return &mockReader{ - controller: c, - description: desc, - } -} - -func (m *mockReader) Oglemock_Id() uintptr { - return uintptr(unsafe.Pointer(m)) -} - -func (m *mockReader) Oglemock_Description() string { - return m.description -} - -func (m *mockReader) Read(p0 []uint8) (o0 int, o1 error) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Read", - file, - line, - []interface{}{p0}) - - if len(retVals) != 2 { - panic(fmt.Sprintf("mockReader.Read: invalid return values: %v", retVals)) - } - - // o0 int - if retVals[0] != nil { - o0 = retVals[0].(int) - } - - // o1 error - if retVals[1] != nil { - o1 = retVals[1].(error) - } - - return -} - -type MockWriter interface { - io.Writer - oglemock.MockObject -} - -type mockWriter struct { - controller oglemock.Controller - description string -} - -func NewMockWriter( - c oglemock.Controller, - desc string) MockWriter { - return &mockWriter{ - controller: c, - description: desc, - } -} - -func (m *mockWriter) Oglemock_Id() uintptr { - return uintptr(unsafe.Pointer(m)) -} - -func (m *mockWriter) Oglemock_Description() string { - return m.description -} - -func (m *mockWriter) Write(p0 []uint8) (o0 int, o1 error) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Write", - file, - line, - []interface{}{p0}) - - if len(retVals) != 2 { - panic(fmt.Sprintf("mockWriter.Write: invalid return values: %v", retVals)) - } - - // o0 int - if retVals[0] != nil { - o0 = retVals[0].(int) - } - - // o1 error - if retVals[1] != nil { - o1 = retVals[1].(error) - } - - return -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.renamed_pkg.go b/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.renamed_pkg.go deleted file mode 100644 index 9b4158f..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/golden.renamed_pkg.go +++ /dev/null @@ -1,66 +0,0 @@ -// This file was auto-generated using createmock. See the following page for -// more information: -// -// https://github.com/smartystreets/assertions/internal/oglemock -// - -package some_pkg - -import ( - fmt "fmt" - oglemock "github.com/smartystreets/assertions/internal/oglemock" - tony "github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/renamed_pkg" - runtime "runtime" - unsafe "unsafe" -) - -type MockSomeInterface interface { - tony.SomeInterface - oglemock.MockObject -} - -type mockSomeInterface struct { - controller oglemock.Controller - description string -} - -func NewMockSomeInterface( - c oglemock.Controller, - desc string) MockSomeInterface { - return &mockSomeInterface{ - controller: c, - description: desc, - } -} - -func (m *mockSomeInterface) Oglemock_Id() uintptr { - return uintptr(unsafe.Pointer(m)) -} - -func (m *mockSomeInterface) Oglemock_Description() string { - return m.description -} - -func (m *mockSomeInterface) DoFoo(p0 int) (o0 int) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "DoFoo", - file, - line, - []interface{}{p0}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockSomeInterface.DoFoo: invalid return values: %v", retVals)) - } - - // o0 int - if retVals[0] != nil { - o0 = retVals[0].(int) - } - - return -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/renamed_pkg/renamed_pkg.go b/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/renamed_pkg/renamed_pkg.go deleted file mode 100644 index 1461cd6..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/generate/test_cases/renamed_pkg/renamed_pkg.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// 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. - -// A package that calls itself something different than its package path would -// have you believe. -package tony - -type SomeUint8Alias uint8 - -type SomeInterface interface { - DoFoo(a int) int -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/internal_expectation.go b/_vendor/github.com/smartystreets/assertions/internal/oglemock/internal_expectation.go deleted file mode 100644 index 8fa8aea..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/internal_expectation.go +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglemock - -import ( - "errors" - "fmt" - "github.com/smartystreets/assertions/internal/oglematchers" - "reflect" - "sync" -) - -// InternalExpectation is exported for purposes of testing only. You should not -// touch it. -// -// InternalExpectation represents an expectation for zero or more calls to a -// mock method, and a set of actions to be taken when those calls are received. -type InternalExpectation struct { - // The signature of the method to which this expectation is bound, for - // checking action types. - methodSignature reflect.Type - - // An error reporter to use for reporting errors in the way that expectations - // are set. - errorReporter ErrorReporter - - // A mutex protecting mutable fields of the struct. - mutex sync.Mutex - - // Matchers that the arguments to the mock method must satisfy in order to - // match this expectation. - ArgMatchers []oglematchers.Matcher - - // The name of the file in which this expectation was expressed. - FileName string - - // The line number at which this expectation was expressed. - LineNumber int - - // The number of times this expectation should be matched, as explicitly - // listed by the user. If there was no explicit number expressed, this is -1. - ExpectedNumMatches int - - // Actions to be taken for the first N calls, one per call in order, where N - // is the length of this slice. - OneTimeActions []Action - - // An action to be taken when the one-time actions have expired, or nil if - // there is no such action. - FallbackAction Action - - // The number of times this expectation has been matched so far. - NumMatches uint -} - -// InternalNewExpectation is exported for purposes of testing only. You should -// not touch it. -func InternalNewExpectation( - reporter ErrorReporter, - methodSignature reflect.Type, - args []interface{}, - fileName string, - lineNumber int) *InternalExpectation { - result := &InternalExpectation{} - - // Store fields that can be stored directly. - result.methodSignature = methodSignature - result.errorReporter = reporter - result.FileName = fileName - result.LineNumber = lineNumber - - // Set up defaults. - result.ExpectedNumMatches = -1 - result.OneTimeActions = make([]Action, 0) - - // Set up the ArgMatchers slice, using Equals(x) for each x that is not a - // matcher itself. - result.ArgMatchers = make([]oglematchers.Matcher, len(args)) - for i, x := range args { - if matcher, ok := x.(oglematchers.Matcher); ok { - result.ArgMatchers[i] = matcher - } else { - result.ArgMatchers[i] = oglematchers.Equals(x) - } - } - - return result -} - -func (e *InternalExpectation) Times(n uint) Expectation { - e.mutex.Lock() - defer e.mutex.Unlock() - - // It is illegal to call this more than once. - if e.ExpectedNumMatches != -1 { - e.reportFatalError("Times called more than once.") - return nil - } - - // It is illegal to call this after any actions are configured. - if len(e.OneTimeActions) != 0 { - e.reportFatalError("Times called after WillOnce.") - return nil - } - - if e.FallbackAction != nil { - e.reportFatalError("Times called after WillRepeatedly.") - return nil - } - - // Make sure the number is reasonable (and will fit in an int). - if n > 1000 { - e.reportFatalError("Expectation.Times: N must be at most 1000") - return nil - } - - e.ExpectedNumMatches = int(n) - return e -} - -func (e *InternalExpectation) WillOnce(a Action) Expectation { - e.mutex.Lock() - defer e.mutex.Unlock() - - // It is illegal to call this after WillRepeatedly. - if e.FallbackAction != nil { - e.reportFatalError("WillOnce called after WillRepeatedly.") - return nil - } - - // Tell the action about the method's signature. - if err := a.SetSignature(e.methodSignature); err != nil { - e.reportFatalError(fmt.Sprintf("WillOnce given invalid action: %v", err)) - return nil - } - - // Store the action. - e.OneTimeActions = append(e.OneTimeActions, a) - - return e -} - -func (e *InternalExpectation) WillRepeatedly(a Action) Expectation { - e.mutex.Lock() - defer e.mutex.Unlock() - - // It is illegal to call this twice. - if e.FallbackAction != nil { - e.reportFatalError("WillRepeatedly called more than once.") - return nil - } - - // Tell the action about the method's signature. - if err := a.SetSignature(e.methodSignature); err != nil { - e.reportFatalError(fmt.Sprintf("WillRepeatedly given invalid action: %v", err)) - return nil - } - - // Store the action. - e.FallbackAction = a - - return e -} - -func (e *InternalExpectation) reportFatalError(errorText string) { - e.errorReporter.ReportFatalError(e.FileName, e.LineNumber, errors.New(errorText)) -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/invoke.go b/_vendor/github.com/smartystreets/assertions/internal/oglemock/invoke.go deleted file mode 100644 index 07630cb..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/invoke.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglemock - -import ( - "errors" - "fmt" - "reflect" -) - -// Create an Action that invokes the supplied function, returning whatever it -// returns. The signature of the function must match that of the mocked method -// exactly. -func Invoke(f interface{}) Action { - // Make sure f is a function. - fv := reflect.ValueOf(f) - fk := fv.Kind() - - if fk != reflect.Func { - desc := "" - if fk != reflect.Invalid { - desc = fv.Type().String() - } - - panic(fmt.Sprintf("Invoke: expected function, got %s", desc)) - } - - return &invokeAction{fv} -} - -type invokeAction struct { - f reflect.Value -} - -func (a *invokeAction) SetSignature(signature reflect.Type) error { - // The signature must match exactly. - ft := a.f.Type() - if ft != signature { - return errors.New(fmt.Sprintf("Invoke: expected %v, got %v", signature, ft)) - } - - return nil -} - -func (a *invokeAction) Invoke(vals []interface{}) []interface{} { - // Create a slice of args for the function. - in := make([]reflect.Value, len(vals)) - for i, x := range vals { - in[i] = reflect.ValueOf(x) - } - - // Call the function and return its return values. - out := a.f.Call(in) - result := make([]interface{}, len(out)) - for i, v := range out { - result[i] = v.Interface() - } - - return result -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/mock_object.go b/_vendor/github.com/smartystreets/assertions/internal/oglemock/mock_object.go deleted file mode 100644 index de995ef..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/mock_object.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglemock - -// MockObject is an interface that mock object implementations must conform to -// in order to register expectations with and hand off calls to a -// MockController. Users should not interact with this interface directly. -type MockObject interface { - // Oglemock_Id returns an identifier for the mock object that is guaranteed - // to be unique within the process at least until the mock object is garbage - // collected. - Oglemock_Id() uintptr - - // Oglemock_Description returns a description of the mock object that may be - // helpful in test failure messages. - Oglemock_Description() string -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/return.go b/_vendor/github.com/smartystreets/assertions/internal/oglemock/return.go deleted file mode 100644 index c66d248..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/return.go +++ /dev/null @@ -1,251 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglemock - -import ( - "errors" - "fmt" - "math" - "reflect" -) - -var intType = reflect.TypeOf(int(0)) -var float64Type = reflect.TypeOf(float64(0)) -var complex128Type = reflect.TypeOf(complex128(0)) - -// Return creates an Action that returns the values passed to Return as -// arguments, after suitable legal type conversions. The following rules apply. -// Given an argument x to Return and a corresponding type T in the method's -// signature, at least one of the following must hold: -// -// * x is assignable to T. (See "Assignability" in the language spec.) Note -// that this in particular applies that x may be a type that implements an -// interface T. It also implies that the nil literal can be used if T is a -// pointer, function, interface, slice, channel, or map type. -// -// * T is any numeric type, and x is an int that is in-range for that type. -// This facilities using raw integer constants: Return(17). -// -// * T is a floating-point or complex number type, and x is a float64. This -// facilities using raw floating-point constants: Return(17.5). -// -// * T is a complex number type, and x is a complex128. This facilities using -// raw complex constants: Return(17+2i). -// -func Return(vals ...interface{}) Action { - return &returnAction{vals, nil} -} - -type returnAction struct { - returnVals []interface{} - signature reflect.Type -} - -func (a *returnAction) Invoke(vals []interface{}) []interface{} { - if a.signature == nil { - panic("You must first call SetSignature with a valid signature.") - } - - res, err := a.buildInvokeResult(a.signature) - if err != nil { - panic(err) - } - - return res -} - -func (a *returnAction) SetSignature(signature reflect.Type) error { - if _, err := a.buildInvokeResult(signature); err != nil { - return err - } - - a.signature = signature - return nil -} - -// A version of Invoke that does error checking, used by both public methods. -func (a *returnAction) buildInvokeResult( - sig reflect.Type) (res []interface{}, err error) { - // Check the length of the return value. - numOut := sig.NumOut() - numVals := len(a.returnVals) - - if numOut != numVals { - err = errors.New( - fmt.Sprintf("Return given %d vals; expected %d.", numVals, numOut)) - return - } - - // Attempt to coerce each return value. - res = make([]interface{}, numOut) - - for i, val := range a.returnVals { - resType := sig.Out(i) - res[i], err = a.coerce(val, resType) - - if err != nil { - res = nil - err = errors.New(fmt.Sprintf("Return: arg %d: %v", i, err)) - return - } - } - - return -} - -func (a *returnAction) coerce(x interface{}, t reflect.Type) (interface{}, error) { - xv := reflect.ValueOf(x) - rv := reflect.New(t).Elem() - - // Special case: the language spec says that the predeclared identifier nil - // is assignable to pointers, functions, interface, slices, channels, and map - // types. However, reflect.ValueOf(nil) returns an invalid value that will - // not cooperate below. So handle invalid values here, assuming that they - // resulted from Return(nil). - if !xv.IsValid() { - switch t.Kind() { - case reflect.Ptr, reflect.Func, reflect.Interface, reflect.Chan, reflect.Slice, reflect.Map, reflect.UnsafePointer: - return rv.Interface(), nil - } - - return nil, errors.New(fmt.Sprintf("expected %v, given ", t)) - } - - // If x is assignable to type t, let the reflect package do the heavy - // lifting. - if reflect.TypeOf(x).AssignableTo(t) { - rv.Set(xv) - return rv.Interface(), nil - } - - // Handle numeric types as described in the documentation on Return. - switch { - case xv.Type() == intType && a.isNumeric(t): - return a.coerceInt(xv.Int(), t) - - case xv.Type() == float64Type && (a.isFloatingPoint(t) || a.isComplex(t)): - return a.coerceFloat(xv.Float(), t) - - case xv.Type() == complex128Type && a.isComplex(t): - return a.coerceComplex(xv.Complex(), t) - } - - // The value wasn't of a legal type. - return nil, errors.New(fmt.Sprintf("expected %v, given %v", t, xv.Type())) -} - -func (a *returnAction) isNumeric(t reflect.Type) bool { - return (t.Kind() >= reflect.Int && t.Kind() <= reflect.Uint64) || - a.isFloatingPoint(t) || - a.isComplex(t) -} - -func (a *returnAction) isFloatingPoint(t reflect.Type) bool { - return t.Kind() == reflect.Float32 || t.Kind() == reflect.Float64 -} - -func (a *returnAction) isComplex(t reflect.Type) bool { - return t.Kind() == reflect.Complex64 || t.Kind() == reflect.Complex128 -} - -func (a *returnAction) coerceInt(x int64, t reflect.Type) (interface{}, error) { - k := t.Kind() - - // Floating point and complex numbers: promote appropriately. - if a.isFloatingPoint(t) || a.isComplex(t) { - return a.coerceFloat(float64(x), t) - } - - // Integers: range check. - var min, max int64 - unsigned := false - - switch k { - case reflect.Int8: - min = math.MinInt8 - max = math.MaxInt8 - - case reflect.Int16: - min = math.MinInt16 - max = math.MaxInt16 - - case reflect.Int32: - min = math.MinInt32 - max = math.MaxInt32 - - case reflect.Int64: - min = math.MinInt64 - max = math.MaxInt64 - - case reflect.Uint: - unsigned = true - min = 0 - max = math.MaxUint32 - - case reflect.Uint8: - unsigned = true - min = 0 - max = math.MaxUint8 - - case reflect.Uint16: - unsigned = true - min = 0 - max = math.MaxUint16 - - case reflect.Uint32: - unsigned = true - min = 0 - max = math.MaxUint32 - - case reflect.Uint64: - unsigned = true - min = 0 - max = math.MaxInt64 - - default: - panic(fmt.Sprintf("Unexpected type: %v", t)) - } - - if x < min || x > max { - return nil, errors.New("int value out of range") - } - - rv := reflect.New(t).Elem() - if unsigned { - rv.SetUint(uint64(x)) - } else { - rv.SetInt(x) - } - - return rv.Interface(), nil -} - -func (a *returnAction) coerceFloat(x float64, t reflect.Type) (interface{}, error) { - // Promote complex numbers. - if a.isComplex(t) { - return a.coerceComplex(complex(x, 0), t) - } - - rv := reflect.New(t).Elem() - rv.SetFloat(x) - return rv.Interface(), nil -} - -func (a *returnAction) coerceComplex(x complex128, t reflect.Type) (interface{}, error) { - rv := reflect.New(t).Elem() - rv.SetComplex(x) - return rv.Interface(), nil -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/sample/README.markdown b/_vendor/github.com/smartystreets/assertions/internal/oglemock/sample/README.markdown deleted file mode 100644 index 60d5d2c..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/sample/README.markdown +++ /dev/null @@ -1,6 +0,0 @@ -This directory contains sample code generated with the `createmock` command. For -example, the file `mock_io.go` can be regenerated with: - - createmock io Reader > sample/mock_io/mock_io.go - -The files are also used by `integration_test.go`. diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/sample/mock_io/mock_io.go b/_vendor/github.com/smartystreets/assertions/internal/oglemock/sample/mock_io/mock_io.go deleted file mode 100644 index 76e8f00..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/sample/mock_io/mock_io.go +++ /dev/null @@ -1,71 +0,0 @@ -// This file was auto-generated using createmock. See the following page for -// more information: -// -// https://github.com/smartystreets/assertions/internal/oglemock -// - -package mock_io - -import ( - fmt "fmt" - oglemock "github.com/smartystreets/assertions/internal/oglemock" - io "io" - runtime "runtime" - unsafe "unsafe" -) - -type MockReader interface { - io.Reader - oglemock.MockObject -} - -type mockReader struct { - controller oglemock.Controller - description string -} - -func NewMockReader( - c oglemock.Controller, - desc string) MockReader { - return &mockReader{ - controller: c, - description: desc, - } -} - -func (m *mockReader) Oglemock_Id() uintptr { - return uintptr(unsafe.Pointer(m)) -} - -func (m *mockReader) Oglemock_Description() string { - return m.description -} - -func (m *mockReader) Read(p0 []uint8) (o0 int, o1 error) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Read", - file, - line, - []interface{}{p0}) - - if len(retVals) != 2 { - panic(fmt.Sprintf("mockReader.Read: invalid return values: %v", retVals)) - } - - // o0 int - if retVals[0] != nil { - o0 = retVals[0].(int) - } - - // o1 error - if retVals[1] != nil { - o1 = retVals[1].(error) - } - - return -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/oglemock/save_arg.go b/_vendor/github.com/smartystreets/assertions/internal/oglemock/save_arg.go deleted file mode 100644 index 27cfcf6..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/oglemock/save_arg.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2015 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglemock - -import ( - "fmt" - "reflect" -) - -// Create an Action that saves the argument at the given zero-based index to -// the supplied destination, which must be a pointer to a type that is -// assignable from the argument type. -func SaveArg(index int, dst interface{}) Action { - return &saveArg{ - index: index, - dstPointer: dst, - } -} - -type saveArg struct { - index int - dstPointer interface{} - - // Set by SetSignature. - dstValue reflect.Value -} - -func (a *saveArg) SetSignature(signature reflect.Type) (err error) { - // Extract the source type. - if a.index >= signature.NumIn() { - err = fmt.Errorf( - "Out of range argument index %v for function type %v", - a.index, - signature) - return - } - - srcType := signature.In(a.index) - - // The destination must be a pointer. - v := reflect.ValueOf(a.dstPointer) - if v.Kind() != reflect.Ptr { - err = fmt.Errorf("Destination is %v, not a pointer", v.Kind()) - return - } - - // Dereference the pointer. - if v.IsNil() { - err = fmt.Errorf("Destination pointer must be non-nil") - return - } - - a.dstValue = v.Elem() - - // The destination must be assignable from the source. - if !srcType.AssignableTo(a.dstValue.Type()) { - err = fmt.Errorf( - "%v is not assignable to %v", - srcType, - a.dstValue.Type()) - return - } - - return -} - -func (a *saveArg) Invoke(methodArgs []interface{}) (rets []interface{}) { - a.dstValue.Set(reflect.ValueOf(methodArgs[a.index])) - return -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/.gitignore b/_vendor/github.com/smartystreets/assertions/internal/ogletest/.gitignore deleted file mode 100644 index dd8fc74..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -*.6 -6.out -_obj/ -_test/ -_testmain.go diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/LICENSE b/_vendor/github.com/smartystreets/assertions/internal/ogletest/LICENSE deleted file mode 100644 index d645695..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - 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 [yyyy] [name of copyright owner] - - 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/smartystreets/assertions/internal/ogletest/README.md b/_vendor/github.com/smartystreets/assertions/internal/ogletest/README.md deleted file mode 100644 index 8e54862..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/README.md +++ /dev/null @@ -1,151 +0,0 @@ -[![GoDoc](https://godoc.org/github.com/smartystreets/assertions/internal/ogletest?status.svg)](https://godoc.org/github.com/smartystreets/assertions/internal/ogletest) - -`ogletest` is a unit testing framework for Go with the following features: - - * An extensive and extensible set of matchers for expressing expectations. - * Automatic failure messages; no need to say `t.Errorf("Expected %v, got - %v"...)`. - * Clean, readable output that tells you exactly what you need to know. - * Built-in support for mocking through the [oglemock][] package. - * Style and semantics similar to [Google Test][googletest] and - [Google JS Test][google-js-test]. - -It integrates with Go's built-in `testing` package, so it works with the -`go test` command, and even with other types of test within your package. Unlike -the `testing` package which offers only basic capabilities for signalling -failures, it offers ways to express expectations and get nice failure messages -automatically. - - -Installation ------------- - -First, make sure you have installed Go 1.0.2 or newer. See -[here][golang-install] for instructions. - -Use the following command to install `ogletest` and its dependencies, and to -keep them up to date: - - go get -u github.com/smartystreets/assertions/internal/ogletest - - -Documentation -------------- - -See [here][reference] for package documentation containing an exhaustive list of -exported symbols. Alternatively, you can install the package and then use -`godoc`: - - godoc github.com/smartystreets/assertions/internal/ogletest - -An important part of `ogletest` is its use of matchers provided by the -[oglematchers][matcher-reference] package. See that package's documentation -for information on the built-in matchers available, and check out the -`oglematchers.Matcher` interface if you want to define your own. - - -Example -------- - -Let's say you have a function in your package `people` with the following -signature: - -```go -// GetRandomPerson returns the name and phone number of Tony, Dennis, or Scott. -func GetRandomPerson() (name, phone string) { - [...] -} -``` - -A silly function, but it will do for an example. You can write a couple of tests -for it as follows: - -```go -package people - -import ( - "github.com/smartystreets/assertions/internal/oglematchers" - "github.com/smartystreets/assertions/internal/ogletest" - "testing" -) - -// Give ogletest a chance to run your tests when invoked by 'go test'. -func TestOgletest(t *testing.T) { ogletest.RunTests(t) } - -// Create a test suite, which groups together logically related test methods -// (defined below). You can share common setup and teardown code here; see the -// package docs for more info. -type PeopleTest struct {} -func init() { ogletest.RegisterTestSuite(&PeopleTest{}) } - -func (t *PeopleTest) ReturnsCorrectNames() { - // Call the function a few times, and make sure it never strays from the set - // of expected names. - for i := 0; i < 25; i++ { - name, _ := GetRandomPerson() - ogletest.ExpectThat(name, oglematchers.AnyOf("Tony", "Dennis", "Scott")) - } -} - -func (t *PeopleTest) FormatsPhoneNumbersCorrectly() { - // Call the function a few times, and make sure it returns phone numbers in a - // standard US format. - for i := 0; i < 25; i++ { - _, phone := GetRandomPerson() - ogletest.ExpectThat(phone, oglematchers.MatchesRegexp(`^\(\d{3}\) \d{3}-\d{4}$`)) -} -``` - -Note that test control functions (`RunTests`, `ExpectThat`, and so on) are part -of the `ogletest` package, whereas built-in matchers (`AnyOf`, `MatchesRegexp`, -and more) are part of the [oglematchers][matcher-reference] library. You can of -course use dot imports so that you don't need to prefix each function with its -package name: - -```go -import ( - . "github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/smartystreets/assertions/internal/ogletest" -) -``` - -If you save the test in a file whose name ends in `_test.go`, you can run your -tests by simply invoking the following in your package directory: - - go test - -Here's what the failure output of ogletest looks like, if your function's -implementation is bad. - - [----------] Running tests from PeopleTest - [ RUN ] PeopleTest.FormatsPhoneNumbersCorrectly - people_test.go:32: - Expected: matches regexp "^\(\d{3}\) \d{3}-\d{4}$" - Actual: +1 800 555 5555 - - [ FAILED ] PeopleTest.FormatsPhoneNumbersCorrectly - [ RUN ] PeopleTest.ReturnsCorrectNames - people_test.go:23: - Expected: or(Tony, Dennis, Scott) - Actual: Bart - - [ FAILED ] PeopleTest.ReturnsCorrectNames - [----------] Finished with tests from PeopleTest - -And if the test passes: - - [----------] Running tests from PeopleTest - [ RUN ] PeopleTest.FormatsPhoneNumbersCorrectly - [ OK ] PeopleTest.FormatsPhoneNumbersCorrectly - [ RUN ] PeopleTest.ReturnsCorrectNames - [ OK ] PeopleTest.ReturnsCorrectNames - [----------] Finished with tests from PeopleTest - - -[reference]: http://godoc.org/github.com/smartystreets/assertions/internal/ogletest -[matcher-reference]: http://godoc.org/github.com/smartystreets/assertions/internal/oglematchers -[golang-install]: http://golang.org/doc/install.html -[googletest]: http://code.google.com/p/googletest/ -[google-js-test]: http://code.google.com/p/google-js-test/ -[howtowrite]: http://golang.org/doc/code.html -[oglemock]: https://github.com/smartystreets/assertions/internal/oglemock diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/assert_aliases.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/assert_aliases.go deleted file mode 100644 index 70fa25c..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/assert_aliases.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ogletest - -import ( - "github.com/smartystreets/assertions/internal/oglematchers" -) - -// AssertEq(e, a) is equivalent to AssertThat(a, oglematchers.Equals(e)). -func AssertEq(expected, actual interface{}, errorParts ...interface{}) { - assertThat( - actual, - oglematchers.Equals(expected), - 1, - errorParts) -} - -// AssertNe(e, a) is equivalent to -// AssertThat(a, oglematchers.Not(oglematchers.Equals(e))). -func AssertNe(expected, actual interface{}, errorParts ...interface{}) { - assertThat( - actual, - oglematchers.Not(oglematchers.Equals(expected)), - 1, - errorParts) -} - -// AssertLt(x, y) is equivalent to AssertThat(x, oglematchers.LessThan(y)). -func AssertLt(x, y interface{}, errorParts ...interface{}) { - assertThat(x, oglematchers.LessThan(y), 1, errorParts) -} - -// AssertLe(x, y) is equivalent to AssertThat(x, oglematchers.LessOrEqual(y)). -func AssertLe(x, y interface{}, errorParts ...interface{}) { - assertThat(x, oglematchers.LessOrEqual(y), 1, errorParts) -} - -// AssertGt(x, y) is equivalent to AssertThat(x, oglematchers.GreaterThan(y)). -func AssertGt(x, y interface{}, errorParts ...interface{}) { - assertThat(x, oglematchers.GreaterThan(y), 1, errorParts) -} - -// AssertGe(x, y) is equivalent to -// AssertThat(x, oglematchers.GreaterOrEqual(y)). -func AssertGe(x, y interface{}, errorParts ...interface{}) { - assertThat(x, oglematchers.GreaterOrEqual(y), 1, errorParts) -} - -// AssertTrue(b) is equivalent to AssertThat(b, oglematchers.Equals(true)). -func AssertTrue(b interface{}, errorParts ...interface{}) { - assertThat(b, oglematchers.Equals(true), 1, errorParts) -} - -// AssertFalse(b) is equivalent to AssertThat(b, oglematchers.Equals(false)). -func AssertFalse(b interface{}, errorParts ...interface{}) { - assertThat(b, oglematchers.Equals(false), 1, errorParts) -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/assert_that.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/assert_that.go deleted file mode 100644 index 65c8fbc..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/assert_that.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ogletest - -import ( - "github.com/smartystreets/assertions/internal/oglematchers" -) - -func assertThat( - x interface{}, - m oglematchers.Matcher, - depth int, - errorParts []interface{}) { - passed := expectThat(x, m, depth+1, errorParts) - if !passed { - AbortTest() - } -} - -// AssertThat is identical to ExpectThat, except that in the event of failure -// it halts the currently running test immediately. It is thus useful for -// things like bounds checking: -// -// someSlice := [...] -// AssertEq(1, len(someSlice)) // Protects next line from panicking. -// ExpectEq("taco", someSlice[0]) -// -func AssertThat( - x interface{}, - m oglematchers.Matcher, - errorParts ...interface{}) { - assertThat(x, m, 1, errorParts) -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/doc.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/doc.go deleted file mode 100644 index bf6507f..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/doc.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package ogletest provides a framework for writing expressive unit tests. It -// integrates with the builtin testing package, so it works with the gotest -// command. Unlike the testing package which offers only basic capabilities for -// signalling failures, it offers ways to express expectations and get nice -// failure messages automatically. -// -// For example: -// -// //////////////////////////////////////////////////////////////////////// -// // testing package test -// //////////////////////////////////////////////////////////////////////// -// -// someStr, err := ComputeSomeString() -// if err != nil { -// t.Errorf("ComputeSomeString: expected nil error, got %v", err) -// } -// -// !strings.Contains(someStr, "foo") { -// t.Errorf("ComputeSomeString: expected substring foo, got %v", someStr) -// } -// -// //////////////////////////////////////////////////////////////////////// -// // ogletest test -// //////////////////////////////////////////////////////////////////////// -// -// someStr, err := ComputeSomeString() -// ExpectEq(nil, err) -// ExpectThat(someStr, HasSubstr("foo") -// -// Failure messages require no work from the user, and look like the following: -// -// foo_test.go:103: -// Expected: has substring "foo" -// Actual: "bar baz" -// -package ogletest diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/expect_aliases.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/expect_aliases.go deleted file mode 100644 index 5bc1dc1..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/expect_aliases.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ogletest - -import "github.com/smartystreets/assertions/internal/oglematchers" - -// ExpectEq(e, a) is equivalent to ExpectThat(a, oglematchers.Equals(e)). -func ExpectEq(expected, actual interface{}, errorParts ...interface{}) { - expectThat(actual, oglematchers.Equals(expected), 1, errorParts) -} - -// ExpectNe(e, a) is equivalent to -// ExpectThat(a, oglematchers.Not(oglematchers.Equals(e))). -func ExpectNe(expected, actual interface{}, errorParts ...interface{}) { - expectThat( - actual, - oglematchers.Not(oglematchers.Equals(expected)), - 1, - errorParts) -} - -// ExpectLt(x, y) is equivalent to ExpectThat(x, oglematchers.LessThan(y)). -func ExpectLt(x, y interface{}, errorParts ...interface{}) { - expectThat(x, oglematchers.LessThan(y), 1, errorParts) -} - -// ExpectLe(x, y) is equivalent to ExpectThat(x, oglematchers.LessOrEqual(y)). -func ExpectLe(x, y interface{}, errorParts ...interface{}) { - expectThat(x, oglematchers.LessOrEqual(y), 1, errorParts) -} - -// ExpectGt(x, y) is equivalent to ExpectThat(x, oglematchers.GreaterThan(y)). -func ExpectGt(x, y interface{}, errorParts ...interface{}) { - expectThat(x, oglematchers.GreaterThan(y), 1, errorParts) -} - -// ExpectGe(x, y) is equivalent to -// ExpectThat(x, oglematchers.GreaterOrEqual(y)). -func ExpectGe(x, y interface{}, errorParts ...interface{}) { - expectThat(x, oglematchers.GreaterOrEqual(y), 1, errorParts) -} - -// ExpectTrue(b) is equivalent to ExpectThat(b, oglematchers.Equals(true)). -func ExpectTrue(b interface{}, errorParts ...interface{}) { - expectThat(b, oglematchers.Equals(true), 1, errorParts) -} - -// ExpectFalse(b) is equivalent to ExpectThat(b, oglematchers.Equals(false)). -func ExpectFalse(b interface{}, errorParts ...interface{}) { - expectThat(b, oglematchers.Equals(false), 1, errorParts) -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/expect_call.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/expect_call.go deleted file mode 100644 index b8bf542..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/expect_call.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ogletest - -import ( - "github.com/smartystreets/assertions/internal/oglemock" - "runtime" -) - -// ExpectCall expresses an expectation that the method of the given name -// should be called on the supplied mock object. It returns a function that -// should be called with the expected arguments, matchers for the arguments, -// or a mix of both. -// -// For example: -// -// mockWriter := [...] -// ogletest.ExpectCall(mockWriter, "Write")(oglematchers.ElementsAre(0x1)) -// .WillOnce(oglemock.Return(1, nil)) -// -// This is a shortcut for calling i.MockController.ExpectCall, where i is the -// TestInfo struct for the currently-running test. Unlike that direct approach, -// this function automatically sets the correct file name and line number for -// the expectation. -func ExpectCall(o oglemock.MockObject, method string) oglemock.PartialExpecation { - // Get information about the call site. - _, file, lineNumber, ok := runtime.Caller(1) - if !ok { - panic("ExpectCall: runtime.Caller") - } - - // Grab the current test info. - info := currentlyRunningTest - if info == nil { - panic("ExpectCall: no test info.") - } - - // Grab the mock controller. - controller := currentlyRunningTest.MockController - if controller == nil { - panic("ExpectCall: no mock controller.") - } - - // Report the expectation. - return controller.ExpectCall(o, method, file, lineNumber) -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/expect_that.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/expect_that.go deleted file mode 100644 index 69fc669..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/expect_that.go +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ogletest - -import ( - "fmt" - "path" - "reflect" - "runtime" - - "github.com/smartystreets/assertions/internal/oglematchers" -) - -// ExpectThat confirms that the supplied matcher matches the value x, adding a -// failure record to the currently running test if it does not. If additional -// parameters are supplied, the first will be used as a format string for the -// later ones, and the user-supplied error message will be added to the test -// output in the event of a failure. -// -// For example: -// -// ExpectThat(userName, Equals("jacobsa")) -// ExpectThat(users[i], Equals("jacobsa"), "while processing user %d", i) -// -func ExpectThat( - x interface{}, - m oglematchers.Matcher, - errorParts ...interface{}) { - expectThat(x, m, 1, errorParts) -} - -// The generalized form of ExpectThat. depth is the distance on the stack -// between the caller's frame and the user's frame. Returns passed iff the -// match succeeded. -func expectThat( - x interface{}, - m oglematchers.Matcher, - depth int, - errorParts []interface{}) (passed bool) { - // Check whether the value matches. If it does, we are finished. - matcherErr := m.Matches(x) - if matcherErr == nil { - passed = true - return - } - - var r FailureRecord - - // Get information about the call site. - var ok bool - if _, r.FileName, r.LineNumber, ok = runtime.Caller(depth + 1); !ok { - panic("expectThat: runtime.Caller") - } - - r.FileName = path.Base(r.FileName) - - // Create an appropriate failure message. Make sure that the expected and - // actual values align properly. - relativeClause := "" - if matcherErr.Error() != "" { - relativeClause = fmt.Sprintf(", %s", matcherErr.Error()) - } - - r.Error = fmt.Sprintf( - "Expected: %s\nActual: %v%s", - m.Description(), - x, - relativeClause) - - // Add the user error, if any. - if len(errorParts) != 0 { - v := reflect.ValueOf(errorParts[0]) - if v.Kind() != reflect.String { - panic(fmt.Sprintf("ExpectThat: invalid format string type %v", v.Kind())) - } - - r.Error = fmt.Sprintf( - "%s\n%s", - r.Error, - fmt.Sprintf(v.String(), errorParts[1:]...)) - } - - // Report the failure. - AddFailureRecord(r) - - return -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/failure.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/failure.go deleted file mode 100644 index 95be2cf..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/failure.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2015 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ogletest - -import ( - "fmt" - "path" - "runtime" -) - -// FailureRecord represents a single failed expectation or assertion for a -// test. Most users don't want to interact with these directly; they are -// generated implicitly using ExpectThat, AssertThat, ExpectLt, etc. -type FailureRecord struct { - // The file name within which the expectation failed, e.g. "foo_test.go". - FileName string - - // The line number at which the expectation failed. - LineNumber int - - // The error associated with the file:line pair above. For example, the - // following expectation: - // - // ExpectEq(17, "taco")" - // - // May cause this error: - // - // Expected: 17 - // Actual: "taco", which is not numeric - // - Error string -} - -// Record a failure for the currently running test (and continue running it). -// Most users will want to use ExpectThat, ExpectEq, etc. instead of this -// function. Those that do want to report arbitrary errors will probably be -// satisfied with AddFailure, which is easier to use. -func AddFailureRecord(r FailureRecord) { - currentlyRunningTest.mu.Lock() - defer currentlyRunningTest.mu.Unlock() - - currentlyRunningTest.failureRecords = append( - currentlyRunningTest.failureRecords, - r) -} - -// Call AddFailureRecord with a record whose file name and line number come -// from the caller of this function, and whose error string is created by -// calling fmt.Sprintf using the arguments to this function. -func AddFailure(format string, a ...interface{}) { - r := FailureRecord{ - Error: fmt.Sprintf(format, a...), - } - - // Get information about the call site. - var ok bool - if _, r.FileName, r.LineNumber, ok = runtime.Caller(1); !ok { - panic("Can't find caller") - } - - r.FileName = path.Base(r.FileName) - - AddFailureRecord(r) -} - -// A sentinel type that is used in a conspiracy between AbortTest and runTests. -// If runTests sees an abortError as the value given to a panic() call, it will -// avoid printing the panic error. -type abortError struct { -} - -// Immediately stop executing the running test, causing it to fail with the -// failures previously recorded. Behavior is undefined if no failures have been -// recorded. -func AbortTest() { - panic(abortError{}) -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/register.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/register.go deleted file mode 100644 index 756f2aa..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/register.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2015 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ogletest - -// The input to ogletest.Register. Most users will want to use -// ogletest.RegisterTestSuite. -// -// A test suite is the basic unit of registration in ogletest. It consists of -// zero or more named test functions which will be run in sequence, along with -// optional setup and tear-down functions. -type TestSuite struct { - // The name of the overall suite, e.g. "MyPackageTest". - Name string - - // If non-nil, a function that will be run exactly once, before any of the - // test functions are run. - SetUp func() - - // The test functions comprising this suite. - TestFunctions []TestFunction - - // If non-nil, a function that will be run exactly once, after all of the - // test functions have run. - TearDown func() -} - -type TestFunction struct { - // The name of this test function, relative to the suite in which it resides. - // If the name is "TweaksFrobnicator", then the function might be presented - // in the ogletest UI as "FooTest.TweaksFrobnicator". - Name string - - // If non-nil, a function that is run before Run, passed a pointer to a - // struct containing information about the test run. - SetUp func(*TestInfo) - - // The function to invoke for the test body. Must be non-nil. Will not be run - // if SetUp panics. - Run func() - - // If non-nil, a function that is run after Run. - TearDown func() -} - -// Register a test suite for execution by RunTests. -// -// This is the most general registration mechanism. Most users will want -// RegisterTestSuite, which is a wrapper around this function that requires -// less boilerplate. -// -// Panics on invalid input. -func Register(suite TestSuite) { - // Make sure the suite is legal. - if suite.Name == "" { - panic("Test suites must have names.") - } - - for _, tf := range suite.TestFunctions { - if tf.Name == "" { - panic("Test functions must have names.") - } - - if tf.Run == nil { - panic("Test functions must have non-nil run fields.") - } - } - - // Save the suite for later. - registeredSuites = append(registeredSuites, suite) -} - -// The list of test suites previously registered. -var registeredSuites []TestSuite diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/register_test_suite.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/register_test_suite.go deleted file mode 100644 index 7303dfa..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/register_test_suite.go +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ogletest - -import ( - "fmt" - "reflect" - - "github.com/smartystreets/assertions/internal/ogletest/srcutil" -) - -// Test suites that implement this interface have special meaning to -// RegisterTestSuite. -type SetUpTestSuiteInterface interface { - // This method will be called exactly once, before the first test method is - // run. The receiver of this method will be a zero value of the test suite - // type, and is not shared with any other methods. Use this method to set up - // any necessary global state shared by all of the test methods. - SetUpTestSuite() -} - -// Test suites that implement this interface have special meaning to -// RegisterTestSuite. -type TearDownTestSuiteInterface interface { - // This method will be called exactly once, after the last test method is - // run. The receiver of this method will be a zero value of the test suite - // type, and is not shared with any other methods. Use this method to clean - // up after any necessary global state shared by all of the test methods. - TearDownTestSuite() -} - -// Test suites that implement this interface have special meaning to -// Register. -type SetUpInterface interface { - // This method is called before each test method is invoked, with the same - // receiver as that test method. At the time this method is invoked, the - // receiver is a zero value for the test suite type. Use this method for - // common setup code that works on data not shared across tests. - SetUp(*TestInfo) -} - -// Test suites that implement this interface have special meaning to -// Register. -type TearDownInterface interface { - // This method is called after each test method is invoked, with the same - // receiver as that test method. Use this method for common cleanup code that - // works on data not shared across tests. - TearDown() -} - -// RegisterTestSuite tells ogletest about a test suite containing tests that it -// should run. Any exported method on the type pointed to by the supplied -// prototype value will be treated as test methods, with the exception of the -// methods defined by the following interfaces, which when present are treated -// as described in the documentation for those interfaces: -// -// * SetUpTestSuiteInterface -// * SetUpInterface -// * TearDownInterface -// * TearDownTestSuiteInterface -// -// Each test method is invoked on a different receiver, which is initially a -// zero value of the test suite type. -// -// Example: -// -// // Some value that is needed by the tests but is expensive to compute. -// var someExpensiveThing uint -// -// type FooTest struct { -// // Path to a temporary file used by the tests. Each test gets a -// // different temporary file. -// tempFile string -// } -// func init() { ogletest.RegisterTestSuite(&FooTest{}) } -// -// func (t *FooTest) SetUpTestSuite() { -// someExpensiveThing = ComputeSomeExpensiveThing() -// } -// -// func (t *FooTest) SetUp(ti *ogletest.TestInfo) { -// t.tempFile = CreateTempFile() -// } -// -// func (t *FooTest) TearDown() { -// DeleteTempFile(t.tempFile) -// } -// -// func (t *FooTest) FrobinicatorIsSuccessfullyTweaked() { -// res := DoSomethingWithExpensiveThing(someExpensiveThing, t.tempFile) -// ExpectThat(res, Equals(true)) -// } -// -func RegisterTestSuite(p interface{}) { - if p == nil { - panic("RegisterTestSuite called with nil suite.") - } - - val := reflect.ValueOf(p) - typ := val.Type() - var zeroInstance reflect.Value - - // We will transform to a TestSuite struct. - suite := TestSuite{} - suite.Name = typ.Elem().Name() - - zeroInstance = reflect.New(typ.Elem()) - if i, ok := zeroInstance.Interface().(SetUpTestSuiteInterface); ok { - suite.SetUp = func() { i.SetUpTestSuite() } - } - - zeroInstance = reflect.New(typ.Elem()) - if i, ok := zeroInstance.Interface().(TearDownTestSuiteInterface); ok { - suite.TearDown = func() { i.TearDownTestSuite() } - } - - // Transform a list of test methods for the suite, filtering them to just the - // ones that we don't need to skip. - for _, method := range filterMethods(suite.Name, srcutil.GetMethodsInSourceOrder(typ)) { - var tf TestFunction - tf.Name = method.Name - - // Create an instance to be operated on by all of the TestFunction's - // internal functions. - instance := reflect.New(typ.Elem()) - - // Bind the functions to the instance. - if i, ok := instance.Interface().(SetUpInterface); ok { - tf.SetUp = func(ti *TestInfo) { i.SetUp(ti) } - } - - methodCopy := method - tf.Run = func() { runTestMethod(instance, methodCopy) } - - if i, ok := instance.Interface().(TearDownInterface); ok { - tf.TearDown = func() { i.TearDown() } - } - - // Save the TestFunction. - suite.TestFunctions = append(suite.TestFunctions, tf) - } - - // Register the suite. - Register(suite) -} - -func runTestMethod(suite reflect.Value, method reflect.Method) { - if method.Func.Type().NumIn() != 1 { - panic(fmt.Sprintf( - "%s: expected 1 args, actually %d.", - method.Name, - method.Func.Type().NumIn())) - } - - method.Func.Call([]reflect.Value{suite}) -} - -func filterMethods(suiteName string, in []reflect.Method) (out []reflect.Method) { - for _, m := range in { - // Skip set up, tear down, and unexported methods. - if isSpecialMethod(m.Name) || !isExportedMethod(m.Name) { - continue - } - - out = append(out, m) - } - - return -} - -func isSpecialMethod(name string) bool { - return (name == "SetUpTestSuite") || - (name == "TearDownTestSuite") || - (name == "SetUp") || - (name == "TearDown") -} - -func isExportedMethod(name string) bool { - return len(name) > 0 && name[0] >= 'A' && name[0] <= 'Z' -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/run_tests.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/run_tests.go deleted file mode 100644 index 003aeb0..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/run_tests.go +++ /dev/null @@ -1,354 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ogletest - -import ( - "bytes" - "flag" - "fmt" - "os" - "path" - "regexp" - "runtime" - "sync" - "sync/atomic" - "testing" - "time" - - "github.com/smartystreets/assertions/internal/reqtrace" -) - -var fTestFilter = flag.String( - "ogletest.run", - "", - "Regexp for matching tests to run.") - -var fStopEarly = flag.Bool( - "ogletest.stop_early", - false, - "If true, stop after the first failure.") - -// runTestsOnce protects RunTests from executing multiple times. -var runTestsOnce sync.Once - -func isAbortError(x interface{}) bool { - _, ok := x.(abortError) - return ok -} - -// Run a single test function, returning a slice of failure records. -func runTestFunction(tf TestFunction) (failures []FailureRecord) { - // Set up a clean slate for this test. Make sure to reset it after everything - // below is finished, so we don't accidentally use it elsewhere. - currentlyRunningTest = newTestInfo() - defer func() { - currentlyRunningTest = nil - }() - - ti := currentlyRunningTest - - // Start a trace. - var reportOutcome reqtrace.ReportFunc - ti.Ctx, reportOutcome = reqtrace.Trace(ti.Ctx, tf.Name) - - // Run the SetUp function, if any, paying attention to whether it panics. - setUpPanicked := false - if tf.SetUp != nil { - setUpPanicked = runWithProtection(func() { tf.SetUp(ti) }) - } - - // Run the test function itself, but only if the SetUp function didn't panic. - // (This includes AssertThat errors.) - if !setUpPanicked { - runWithProtection(tf.Run) - } - - // Run the TearDown function, if any. - if tf.TearDown != nil { - runWithProtection(tf.TearDown) - } - - // Tell the mock controller for the tests to report any errors it's sitting - // on. - ti.MockController.Finish() - - // Report the outcome to reqtrace. - if len(ti.failureRecords) == 0 { - reportOutcome(nil) - } else { - reportOutcome(fmt.Errorf("%v failure records", len(ti.failureRecords))) - } - - return ti.failureRecords -} - -// Run everything registered with Register (including via the wrapper -// RegisterTestSuite). -// -// Failures are communicated to the supplied testing.T object. This is the -// bridge between ogletest and the testing package (and `go test`); you should -// ensure that it's called at least once by creating a test function compatible -// with `go test` and calling it there. -// -// For example: -// -// import ( -// "github.com/smartystreets/assertions/internal/ogletest" -// "testing" -// ) -// -// func TestOgletest(t *testing.T) { -// ogletest.RunTests(t) -// } -// -func RunTests(t *testing.T) { - runTestsOnce.Do(func() { runTestsInternal(t) }) -} - -// Signalling between RunTests and StopRunningTests. -var gStopRunning uint64 - -// Request that RunTests stop what it's doing. After the currently running test -// is finished, including tear-down, the program will exit with an error code. -func StopRunningTests() { - atomic.StoreUint64(&gStopRunning, 1) -} - -// runTestsInternal does the real work of RunTests, which simply wraps it in a -// sync.Once. -func runTestsInternal(t *testing.T) { - // Process each registered suite. - for _, suite := range registeredSuites { - // Stop now if we've already seen a failure and we've been told to stop - // early. - if t.Failed() && *fStopEarly { - break - } - - // Print a banner. - fmt.Printf("[----------] Running tests from %s\n", suite.Name) - - // Run the SetUp function, if any. - if suite.SetUp != nil { - suite.SetUp() - } - - // Run each test function that the user has not told us to skip. - stoppedEarly := false - for _, tf := range filterTestFunctions(suite) { - // Did the user request that we stop running tests? If so, skip the rest - // of this suite (and exit after tearing it down). - if atomic.LoadUint64(&gStopRunning) != 0 { - stoppedEarly = true - break - } - - // Print a banner for the start of this test function. - fmt.Printf("[ RUN ] %s.%s\n", suite.Name, tf.Name) - - // Run the test function. - startTime := time.Now() - failures := runTestFunction(tf) - runDuration := time.Since(startTime) - - // Print any failures, and mark the test as having failed if there are any. - for _, record := range failures { - t.Fail() - fmt.Printf( - "%s:%d:\n%s\n\n", - record.FileName, - record.LineNumber, - record.Error) - } - - // Print a banner for the end of the test. - bannerMessage := "[ OK ]" - if len(failures) != 0 { - bannerMessage = "[ FAILED ]" - } - - // Print a summary of the time taken, if long enough. - var timeMessage string - if runDuration >= 25*time.Millisecond { - timeMessage = fmt.Sprintf(" (%s)", runDuration.String()) - } - - fmt.Printf( - "%s %s.%s%s\n", - bannerMessage, - suite.Name, - tf.Name, - timeMessage) - - // Stop running tests from this suite if we've been told to stop early - // and this test failed. - if t.Failed() && *fStopEarly { - break - } - } - - // Run the suite's TearDown function, if any. - if suite.TearDown != nil { - suite.TearDown() - } - - // Were we told to exit early? - if stoppedEarly { - fmt.Println("Exiting early due to user request.") - os.Exit(1) - } - - fmt.Printf("[----------] Finished with tests from %s\n", suite.Name) - } -} - -// Return true iff the supplied program counter appears to lie within panic(). -func isPanic(pc uintptr) bool { - f := runtime.FuncForPC(pc) - if f == nil { - return false - } - - return f.Name() == "runtime.gopanic" || f.Name() == "runtime.sigpanic" -} - -// Find the deepest stack frame containing something that appears to be a -// panic. Return the 'skip' value that a caller to this function would need -// to supply to runtime.Caller for that frame, or a negative number if not found. -func findPanic() int { - localSkip := -1 - for i := 0; ; i++ { - // Stop if we've passed the base of the stack. - pc, _, _, ok := runtime.Caller(i) - if !ok { - break - } - - // Is this a panic? - if isPanic(pc) { - localSkip = i - } - } - - return localSkip - 1 -} - -// Attempt to find the file base name and line number for the ultimate source -// of a panic, on the panicking stack. Return a human-readable sentinel if -// unsuccessful. -func findPanicFileLine() (string, int) { - panicSkip := findPanic() - if panicSkip < 0 { - return "(unknown)", 0 - } - - // Find the trigger of the panic. - _, file, line, ok := runtime.Caller(panicSkip + 1) - if !ok { - return "(unknown)", 0 - } - - return path.Base(file), line -} - -// Run the supplied function, catching panics (including AssertThat errors) and -// reporting them to the currently-running test as appropriate. Return true iff -// the function panicked. -func runWithProtection(f func()) (panicked bool) { - defer func() { - // If the test didn't panic, we're done. - r := recover() - if r == nil { - return - } - - panicked = true - - // We modify the currently running test below. - currentlyRunningTest.mu.Lock() - defer currentlyRunningTest.mu.Unlock() - - // If the function panicked (and the panic was not due to an AssertThat - // failure), add a failure for the panic. - if !isAbortError(r) { - var panicRecord FailureRecord - panicRecord.FileName, panicRecord.LineNumber = findPanicFileLine() - panicRecord.Error = fmt.Sprintf( - "panic: %v\n\n%s", r, formatPanicStack()) - - currentlyRunningTest.failureRecords = append( - currentlyRunningTest.failureRecords, - panicRecord) - } - }() - - f() - return -} - -func formatPanicStack() string { - buf := new(bytes.Buffer) - - // Find the panic. If successful, we'll skip to below it. Otherwise, we'll - // format everything. - var initialSkip int - if panicSkip := findPanic(); panicSkip >= 0 { - initialSkip = panicSkip + 1 - } - - for i := initialSkip; ; i++ { - pc, file, line, ok := runtime.Caller(i) - if !ok { - break - } - - // Choose a function name to display. - funcName := "(unknown)" - if f := runtime.FuncForPC(pc); f != nil { - funcName = f.Name() - } - - // Stop if we've gotten as far as the test runner code. - if funcName == "github.com/smartystreets/assertions/internal/ogletest.runTestMethod" || - funcName == "github.com/smartystreets/assertions/internal/ogletest.runWithProtection" { - break - } - - // Add an entry for this frame. - fmt.Fprintf(buf, "%s\n\t%s:%d\n", funcName, file, line) - } - - return buf.String() -} - -// Filter test functions according to the user-supplied filter flag. -func filterTestFunctions(suite TestSuite) (out []TestFunction) { - re, err := regexp.Compile(*fTestFilter) - if err != nil { - panic("Invalid value for --ogletest.run: " + err.Error()) - } - - for _, tf := range suite.TestFunctions { - fullName := fmt.Sprintf("%s.%s", suite.Name, tf.Name) - if !re.MatchString(fullName) { - continue - } - - out = append(out, tf) - } - - return -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/srcutil/docs.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/srcutil/docs.go deleted file mode 100644 index d9b9bc8..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/srcutil/docs.go +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright 2015 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) - -// Functions for working with source code. -package srcutil diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/srcutil/methods.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/srcutil/methods.go deleted file mode 100644 index a8c5828..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/srcutil/methods.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package srcutil - -import ( - "fmt" - "reflect" - "runtime" - "sort" -) - -func getLine(m reflect.Method) int { - pc := m.Func.Pointer() - - f := runtime.FuncForPC(pc) - if f == nil { - panic(fmt.Sprintf("Couldn't get runtime func for method (pc=%d): %v", pc, m)) - } - - _, line := f.FileLine(pc) - return line -} - -type sortableMethodSet []reflect.Method - -func (s sortableMethodSet) Len() int { - return len(s) -} - -func (s sortableMethodSet) Less(i, j int) bool { - return getLine(s[i]) < getLine(s[j]) -} - -func (s sortableMethodSet) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} - -// Given a type t, return all of the methods of t sorted such that source file -// order is preserved. Order across files is undefined. Order within lines is -// undefined. -func GetMethodsInSourceOrder(t reflect.Type) []reflect.Method { - // Build the list of methods. - methods := sortableMethodSet{} - for i := 0; i < t.NumMethod(); i++ { - methods = append(methods, t.Method(i)) - } - - // Sort it. - sort.Sort(methods) - - return methods -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/failing.test.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/failing.test.go deleted file mode 100644 index 17c50e1..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/failing.test.go +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "fmt" - "testing" - - . "github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/smartystreets/assertions/internal/ogletest" -) - -func TestFailingTest(t *testing.T) { RunTests(t) } - -//////////////////////////////////////////////////////////////////////// -// Usual failures -//////////////////////////////////////////////////////////////////////// - -type FailingTest struct { -} - -var _ TearDownInterface = &FailingTest{} -var _ TearDownTestSuiteInterface = &FailingTest{} - -func init() { RegisterTestSuite(&FailingTest{}) } - -func (t *FailingTest) TearDown() { - fmt.Println("TearDown running.") -} - -func (t *FailingTest) TearDownTestSuite() { - fmt.Println("TearDownTestSuite running.") -} - -func (t *FailingTest) PassingMethod() { -} - -func (t *FailingTest) Equals() { - ExpectThat(17, Equals(17.5)) - ExpectThat(17, Equals("taco")) -} - -func (t *FailingTest) LessThan() { - ExpectThat(18, LessThan(17)) - ExpectThat(18, LessThan("taco")) -} - -func (t *FailingTest) HasSubstr() { - ExpectThat("taco", HasSubstr("ac")) - ExpectThat(17, HasSubstr("ac")) -} - -func (t *FailingTest) ExpectWithUserErrorMessages() { - ExpectThat(17, Equals(19), "foo bar: %d", 112) - ExpectEq(17, 17.5, "foo bar: %d", 112) - ExpectLe(17, 16.9, "foo bar: %d", 112) - ExpectLt(17, 16.9, "foo bar: %d", 112) - ExpectGe(17, 17.1, "foo bar: %d", 112) - ExpectGt(17, "taco", "foo bar: %d", 112) - ExpectNe(17, 17.0, "foo bar: %d", 112) - ExpectFalse(true, "foo bar: %d", 112) - ExpectTrue(false, "foo bar: %d", 112) -} - -func (t *FailingTest) AssertWithUserErrorMessages() { - AssertThat(17, Equals(19), "foo bar: %d", 112) -} - -func (t *FailingTest) ExpectationAliases() { - ExpectEq(17, 17.5) - ExpectEq("taco", 17.5) - - ExpectLe(17, 16.9) - ExpectLt(17, 16.9) - ExpectLt(17, "taco") - - ExpectGe(17, 17.1) - ExpectGt(17, 17.1) - ExpectGt(17, "taco") - - ExpectNe(17, 17.0) - ExpectNe(17, "taco") - - ExpectFalse(true) - ExpectFalse("taco") - - ExpectTrue(false) - ExpectTrue("taco") -} - -func (t *FailingTest) AssertThatFailure() { - AssertThat(17, Equals(19)) - panic("Shouldn't get here.") -} - -func (t *FailingTest) AssertEqFailure() { - AssertEq(19, 17) - panic("Shouldn't get here.") -} - -func (t *FailingTest) AssertNeFailure() { - AssertNe(19, 19) - panic("Shouldn't get here.") -} - -func (t *FailingTest) AssertLeFailure() { - AssertLe(19, 17) - panic("Shouldn't get here.") -} - -func (t *FailingTest) AssertLtFailure() { - AssertLt(19, 17) - panic("Shouldn't get here.") -} - -func (t *FailingTest) AssertGeFailure() { - AssertGe(17, 19) - panic("Shouldn't get here.") -} - -func (t *FailingTest) AssertGtFailure() { - AssertGt(17, 19) - panic("Shouldn't get here.") -} - -func (t *FailingTest) AssertTrueFailure() { - AssertTrue("taco") - panic("Shouldn't get here.") -} - -func (t *FailingTest) AssertFalseFailure() { - AssertFalse("taco") - panic("Shouldn't get here.") -} - -func (t *FailingTest) AddFailureRecord() { - r := FailureRecord{ - FileName: "foo.go", - LineNumber: 17, - Error: "taco\nburrito", - } - - AddFailureRecord(r) -} - -func (t *FailingTest) AddFailure() { - AddFailure("taco") - AddFailure("burrito: %d", 17) -} - -func (t *FailingTest) AddFailureThenAbortTest() { - AddFailure("enchilada") - AbortTest() - fmt.Println("Shouldn't get here.") -} - -//////////////////////////////////////////////////////////////////////// -// Expectation failure during SetUp -//////////////////////////////////////////////////////////////////////// - -type ExpectFailDuringSetUpTest struct { -} - -func init() { RegisterTestSuite(&ExpectFailDuringSetUpTest{}) } - -func (t *ExpectFailDuringSetUpTest) SetUp(i *TestInfo) { - ExpectFalse(true) -} - -func (t *ExpectFailDuringSetUpTest) TearDown() { - fmt.Println("TearDown running.") -} - -func (t *ExpectFailDuringSetUpTest) PassingMethod() { - fmt.Println("Method running.") -} - -//////////////////////////////////////////////////////////////////////// -// Assertion failure during SetUp -//////////////////////////////////////////////////////////////////////// - -type AssertFailDuringSetUpTest struct { -} - -func init() { RegisterTestSuite(&AssertFailDuringSetUpTest{}) } - -func (t *AssertFailDuringSetUpTest) SetUp(i *TestInfo) { - AssertFalse(true) -} - -func (t *AssertFailDuringSetUpTest) TearDown() { - fmt.Println("TearDown running.") -} - -func (t *AssertFailDuringSetUpTest) PassingMethod() { - fmt.Println("Method running.") -} - -//////////////////////////////////////////////////////////////////////// -// Expectation failure during TearDown -//////////////////////////////////////////////////////////////////////// - -type ExpectFailDuringTearDownTest struct { -} - -func init() { RegisterTestSuite(&ExpectFailDuringTearDownTest{}) } - -func (t *ExpectFailDuringTearDownTest) SetUp(i *TestInfo) { - fmt.Println("SetUp running.") -} - -func (t *ExpectFailDuringTearDownTest) TearDown() { - ExpectFalse(true) -} - -func (t *ExpectFailDuringTearDownTest) PassingMethod() { - fmt.Println("Method running.") -} - -//////////////////////////////////////////////////////////////////////// -// Assertion failure during TearDown -//////////////////////////////////////////////////////////////////////// - -type AssertFailDuringTearDownTest struct { -} - -func init() { RegisterTestSuite(&AssertFailDuringTearDownTest{}) } - -func (t *AssertFailDuringTearDownTest) SetUp(i *TestInfo) { - fmt.Println("SetUp running.") -} - -func (t *AssertFailDuringTearDownTest) TearDown() { - AssertFalse(true) -} - -func (t *AssertFailDuringTearDownTest) PassingMethod() { - fmt.Println("Method running.") -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/filtered.test.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/filtered.test.go deleted file mode 100644 index e559c5f..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/filtered.test.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "fmt" - . "github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/smartystreets/assertions/internal/ogletest" - "testing" -) - -func TestFiltered(t *testing.T) { RunTests(t) } - -//////////////////////////////////////////////////////////////////////// -// Partially filtered out -//////////////////////////////////////////////////////////////////////// - -type PartiallyFilteredTest struct { -} - -func init() { RegisterTestSuite(&PartiallyFilteredTest{}) } - -func (t *PartiallyFilteredTest) PassingTestFoo() { - ExpectThat(19, Equals(19)) -} - -func (t *PartiallyFilteredTest) PassingTestBar() { - ExpectThat(17, Equals(17)) -} - -func (t *PartiallyFilteredTest) PartiallyFilteredTestFoo() { - ExpectThat(18, LessThan(17)) -} - -func (t *PartiallyFilteredTest) PartiallyFilteredTestBar() { - ExpectThat("taco", HasSubstr("blah")) -} - -func (t *PartiallyFilteredTest) PartiallyFilteredTestBaz() { - ExpectThat(18, LessThan(17)) -} - -//////////////////////////////////////////////////////////////////////// -// Completely filtered out -//////////////////////////////////////////////////////////////////////// - -type CompletelyFilteredTest struct { -} - -func init() { RegisterTestSuite(&CompletelyFilteredTest{}) } - -func (t *CompletelyFilteredTest) SetUpTestSuite() { - fmt.Println("SetUpTestSuite run!") -} - -func (t *CompletelyFilteredTest) TearDownTestSuite() { - fmt.Println("TearDownTestSuite run!") -} - -func (t *PartiallyFilteredTest) SomePassingTest() { - ExpectThat(19, Equals(19)) -} - -func (t *PartiallyFilteredTest) SomeFailingTest() { - ExpectThat(19, Equals(17)) -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.failing_test b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.failing_test deleted file mode 100644 index f0cd76a..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.failing_test +++ /dev/null @@ -1,278 +0,0 @@ -[----------] Running tests from FailingTest -[ RUN ] FailingTest.PassingMethod -TearDown running. -[ OK ] FailingTest.PassingMethod -[ RUN ] FailingTest.Equals -TearDown running. -failing_test.go:52: -Expected: 17.5 -Actual: 17 - -failing_test.go:53: -Expected: taco -Actual: 17, which is not a string - -[ FAILED ] FailingTest.Equals -[ RUN ] FailingTest.LessThan -TearDown running. -failing_test.go:57: -Expected: less than 17 -Actual: 18 - -failing_test.go:58: -Expected: less than "taco" -Actual: 18, which is not comparable - -[ FAILED ] FailingTest.LessThan -[ RUN ] FailingTest.HasSubstr -TearDown running. -failing_test.go:63: -Expected: has substring "ac" -Actual: 17, which is not a string - -[ FAILED ] FailingTest.HasSubstr -[ RUN ] FailingTest.ExpectWithUserErrorMessages -TearDown running. -failing_test.go:67: -Expected: 19 -Actual: 17 -foo bar: 112 - -failing_test.go:68: -Expected: 17 -Actual: 17.5 -foo bar: 112 - -failing_test.go:69: -Expected: less than or equal to 16.9 -Actual: 17 -foo bar: 112 - -failing_test.go:70: -Expected: less than 16.9 -Actual: 17 -foo bar: 112 - -failing_test.go:71: -Expected: greater than or equal to 17.1 -Actual: 17 -foo bar: 112 - -failing_test.go:72: -Expected: greater than "taco" -Actual: 17, which is not comparable -foo bar: 112 - -failing_test.go:73: -Expected: not(17) -Actual: 17 -foo bar: 112 - -failing_test.go:74: -Expected: false -Actual: true -foo bar: 112 - -failing_test.go:75: -Expected: true -Actual: false -foo bar: 112 - -[ FAILED ] FailingTest.ExpectWithUserErrorMessages -[ RUN ] FailingTest.AssertWithUserErrorMessages -TearDown running. -failing_test.go:79: -Expected: 19 -Actual: 17 -foo bar: 112 - -[ FAILED ] FailingTest.AssertWithUserErrorMessages -[ RUN ] FailingTest.ExpectationAliases -TearDown running. -failing_test.go:83: -Expected: 17 -Actual: 17.5 - -failing_test.go:84: -Expected: taco -Actual: 17.5, which is not a string - -failing_test.go:86: -Expected: less than or equal to 16.9 -Actual: 17 - -failing_test.go:87: -Expected: less than 16.9 -Actual: 17 - -failing_test.go:88: -Expected: less than "taco" -Actual: 17, which is not comparable - -failing_test.go:90: -Expected: greater than or equal to 17.1 -Actual: 17 - -failing_test.go:91: -Expected: greater than 17.1 -Actual: 17 - -failing_test.go:92: -Expected: greater than "taco" -Actual: 17, which is not comparable - -failing_test.go:94: -Expected: not(17) -Actual: 17 - -failing_test.go:95: -Expected: not(17) -Actual: taco, which is not numeric - -failing_test.go:97: -Expected: false -Actual: true - -failing_test.go:98: -Expected: false -Actual: taco, which is not a bool - -failing_test.go:100: -Expected: true -Actual: false - -failing_test.go:101: -Expected: true -Actual: taco, which is not a bool - -[ FAILED ] FailingTest.ExpectationAliases -[ RUN ] FailingTest.AssertThatFailure -TearDown running. -failing_test.go:105: -Expected: 19 -Actual: 17 - -[ FAILED ] FailingTest.AssertThatFailure -[ RUN ] FailingTest.AssertEqFailure -TearDown running. -failing_test.go:110: -Expected: 19 -Actual: 17 - -[ FAILED ] FailingTest.AssertEqFailure -[ RUN ] FailingTest.AssertNeFailure -TearDown running. -failing_test.go:115: -Expected: not(19) -Actual: 19 - -[ FAILED ] FailingTest.AssertNeFailure -[ RUN ] FailingTest.AssertLeFailure -TearDown running. -failing_test.go:120: -Expected: less than or equal to 17 -Actual: 19 - -[ FAILED ] FailingTest.AssertLeFailure -[ RUN ] FailingTest.AssertLtFailure -TearDown running. -failing_test.go:125: -Expected: less than 17 -Actual: 19 - -[ FAILED ] FailingTest.AssertLtFailure -[ RUN ] FailingTest.AssertGeFailure -TearDown running. -failing_test.go:130: -Expected: greater than or equal to 19 -Actual: 17 - -[ FAILED ] FailingTest.AssertGeFailure -[ RUN ] FailingTest.AssertGtFailure -TearDown running. -failing_test.go:135: -Expected: greater than 19 -Actual: 17 - -[ FAILED ] FailingTest.AssertGtFailure -[ RUN ] FailingTest.AssertTrueFailure -TearDown running. -failing_test.go:140: -Expected: true -Actual: taco, which is not a bool - -[ FAILED ] FailingTest.AssertTrueFailure -[ RUN ] FailingTest.AssertFalseFailure -TearDown running. -failing_test.go:145: -Expected: false -Actual: taco, which is not a bool - -[ FAILED ] FailingTest.AssertFalseFailure -[ RUN ] FailingTest.AddFailureRecord -TearDown running. -foo.go:17: -taco -burrito - -[ FAILED ] FailingTest.AddFailureRecord -[ RUN ] FailingTest.AddFailure -TearDown running. -failing_test.go:160: -taco - -failing_test.go:161: -burrito: 17 - -[ FAILED ] FailingTest.AddFailure -[ RUN ] FailingTest.AddFailureThenAbortTest -TearDown running. -failing_test.go:165: -enchilada - -[ FAILED ] FailingTest.AddFailureThenAbortTest -TearDownTestSuite running. -[----------] Finished with tests from FailingTest -[----------] Running tests from ExpectFailDuringSetUpTest -[ RUN ] ExpectFailDuringSetUpTest.PassingMethod -Method running. -TearDown running. -failing_test.go:180: -Expected: false -Actual: true - -[ FAILED ] ExpectFailDuringSetUpTest.PassingMethod -[----------] Finished with tests from ExpectFailDuringSetUpTest -[----------] Running tests from AssertFailDuringSetUpTest -[ RUN ] AssertFailDuringSetUpTest.PassingMethod -TearDown running. -failing_test.go:201: -Expected: false -Actual: true - -[ FAILED ] AssertFailDuringSetUpTest.PassingMethod -[----------] Finished with tests from AssertFailDuringSetUpTest -[----------] Running tests from ExpectFailDuringTearDownTest -[ RUN ] ExpectFailDuringTearDownTest.PassingMethod -SetUp running. -Method running. -failing_test.go:226: -Expected: false -Actual: true - -[ FAILED ] ExpectFailDuringTearDownTest.PassingMethod -[----------] Finished with tests from ExpectFailDuringTearDownTest -[----------] Running tests from AssertFailDuringTearDownTest -[ RUN ] AssertFailDuringTearDownTest.PassingMethod -SetUp running. -Method running. -failing_test.go:247: -Expected: false -Actual: true - -[ FAILED ] AssertFailDuringTearDownTest.PassingMethod -[----------] Finished with tests from AssertFailDuringTearDownTest ---- FAIL: TestSomething (1.23s) -FAIL -exit status 1 -FAIL somepkg 1.234s diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.filtered_test b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.filtered_test deleted file mode 100644 index 39fa697..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.filtered_test +++ /dev/null @@ -1,24 +0,0 @@ -[----------] Running tests from PartiallyFilteredTest -[ RUN ] PartiallyFilteredTest.PassingTestBar -[ OK ] PartiallyFilteredTest.PassingTestBar -[ RUN ] PartiallyFilteredTest.PartiallyFilteredTestBar -filtered_test.go:49: -Expected: has substring "blah" -Actual: taco - -[ FAILED ] PartiallyFilteredTest.PartiallyFilteredTestBar -[ RUN ] PartiallyFilteredTest.PartiallyFilteredTestBaz -filtered_test.go:53: -Expected: less than 17 -Actual: 18 - -[ FAILED ] PartiallyFilteredTest.PartiallyFilteredTestBaz -[----------] Finished with tests from PartiallyFilteredTest -[----------] Running tests from CompletelyFilteredTest -SetUpTestSuite run! -TearDownTestSuite run! -[----------] Finished with tests from CompletelyFilteredTest ---- FAIL: TestSomething (1.23s) -FAIL -exit status 1 -FAIL somepkg 1.234s diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.mock_test b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.mock_test deleted file mode 100644 index 4ca2979..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.mock_test +++ /dev/null @@ -1,25 +0,0 @@ -[----------] Running tests from MockTest -[ RUN ] MockTest.ExpectationSatisfied -[ OK ] MockTest.ExpectationSatisfied -[ RUN ] MockTest.MockExpectationNotSatisfied -/some/path/mock_test.go:56: -Unsatisfied expectation; expected At to be called at least 1 times; called 0 times. - -[ FAILED ] MockTest.MockExpectationNotSatisfied -[ RUN ] MockTest.ExpectCallForUnknownMethod -/some/path/mock_test.go:61: -Unknown method: FooBar - -[ FAILED ] MockTest.ExpectCallForUnknownMethod -[ RUN ] MockTest.UnexpectedCall -/some/path/mock_test.go:65: -Unexpected call to At with args: [11 23] - -[ FAILED ] MockTest.UnexpectedCall -[ RUN ] MockTest.InvokeFunction -[ OK ] MockTest.InvokeFunction -[----------] Finished with tests from MockTest ---- FAIL: TestSomething (1.23s) -FAIL -exit status 1 -FAIL somepkg 1.234s diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.no_cases_test b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.no_cases_test deleted file mode 100644 index 8631385..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.no_cases_test +++ /dev/null @@ -1,6 +0,0 @@ -[----------] Running tests from NoCasesTest -SetUpTestSuite run! -TearDownTestSuite run! -[----------] Finished with tests from NoCasesTest -PASS -ok somepkg 1.234s diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.panicking_test b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.panicking_test deleted file mode 100644 index 32eac65..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.panicking_test +++ /dev/null @@ -1,90 +0,0 @@ -[----------] Running tests from PanickingTest -[ RUN ] PanickingTest.ExplicitPanic -TearDown running. -panicking_test.go:47: -panic: Panic in ExplicitPanic - -github.com/smartystreets/assertions/internal/ogletest/somepkg_test.(*PanickingTest).ExplicitPanic - some_file.txt:0 -runtime.call16 - /some/path/asm_amd64.s:401 -reflect.Value.call - some_file.txt:0 -reflect.Value.Call - some_file.txt:0 - - -[ FAILED ] PanickingTest.ExplicitPanic -[ RUN ] PanickingTest.ExplicitPanicInHelperFunction -TearDown running. -panicking_test.go:34: -panic: Panic in someFuncThatPanics - -github.com/smartystreets/assertions/internal/ogletest/somepkg_test.someFuncThatPanics - some_file.txt:0 -github.com/smartystreets/assertions/internal/ogletest/somepkg_test.(*PanickingTest).ExplicitPanicInHelperFunction - some_file.txt:0 -runtime.call16 - /some/path/asm_amd64.s:401 -reflect.Value.call - some_file.txt:0 -reflect.Value.Call - some_file.txt:0 - - -[ FAILED ] PanickingTest.ExplicitPanicInHelperFunction -[ RUN ] PanickingTest.NilPointerDerefence -TearDown running. -panicking_test.go:56: -panic: runtime error: invalid memory address or nil pointer dereference - -github.com/smartystreets/assertions/internal/ogletest/somepkg_test.(*PanickingTest).NilPointerDerefence - some_file.txt:0 -runtime.call16 - /some/path/asm_amd64.s:401 -reflect.Value.call - some_file.txt:0 -reflect.Value.Call - some_file.txt:0 - - -[ FAILED ] PanickingTest.NilPointerDerefence -[ RUN ] PanickingTest.ZzzSomeOtherTest -TearDown running. -[ OK ] PanickingTest.ZzzSomeOtherTest -[----------] Finished with tests from PanickingTest -[----------] Running tests from SetUpPanicTest -[ RUN ] SetUpPanicTest.SomeTestCase -SetUp about to panic. -TearDown running. -panicking_test.go:74: -panic: Panic in SetUp - -github.com/smartystreets/assertions/internal/ogletest/somepkg_test.(*SetUpPanicTest).SetUp - some_file.txt:0 -github.com/smartystreets/assertions/internal/ogletest.func·003 - some_file.txt:0 -github.com/smartystreets/assertions/internal/ogletest.func·007 - some_file.txt:0 - - -[ FAILED ] SetUpPanicTest.SomeTestCase -[----------] Finished with tests from SetUpPanicTest -[----------] Running tests from TearDownPanicTest -[ RUN ] TearDownPanicTest.SomeTestCase -TearDown about to panic. -panicking_test.go:95: -panic: Panic in TearDown - -github.com/smartystreets/assertions/internal/ogletest/somepkg_test.(*TearDownPanicTest).TearDown - some_file.txt:0 -github.com/smartystreets/assertions/internal/ogletest.func·005 - some_file.txt:0 - - -[ FAILED ] TearDownPanicTest.SomeTestCase -[----------] Finished with tests from TearDownPanicTest ---- FAIL: TestSomething (1.23s) -FAIL -exit status 1 -FAIL somepkg 1.234s diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.passing_test b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.passing_test deleted file mode 100644 index 0311288..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.passing_test +++ /dev/null @@ -1,22 +0,0 @@ -[----------] Running tests from PassingTest -[ RUN ] PassingTest.EmptyTestMethod -[ OK ] PassingTest.EmptyTestMethod -[ RUN ] PassingTest.SuccessfullMatches -[ OK ] PassingTest.SuccessfullMatches -[ RUN ] PassingTest.ExpectAliases -[ OK ] PassingTest.ExpectAliases -[ RUN ] PassingTest.AssertAliases -[ OK ] PassingTest.AssertAliases -[ RUN ] PassingTest.SlowTest -[ OK ] PassingTest.SlowTest (1234ms) -[----------] Finished with tests from PassingTest -[----------] Running tests from PassingTestWithHelpers -SetUpTestSuite ran. -[ RUN ] PassingTestWithHelpers.EmptyTestMethod -SetUp ran. -TearDown ran. -[ OK ] PassingTestWithHelpers.EmptyTestMethod -TearDownTestSuite ran. -[----------] Finished with tests from PassingTestWithHelpers -PASS -ok somepkg 1.234s diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.run_twice_test b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.run_twice_test deleted file mode 100644 index 0749f91..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.run_twice_test +++ /dev/null @@ -1,14 +0,0 @@ -[----------] Running tests from RunTwiceTest -[ RUN ] RunTwiceTest.PassingMethod -[ OK ] RunTwiceTest.PassingMethod -[ RUN ] RunTwiceTest.FailingMethod -run_twice_test.go:46: -Expected: 17.5 -Actual: 17 - -[ FAILED ] RunTwiceTest.FailingMethod -[----------] Finished with tests from RunTwiceTest ---- FAIL: TestSomething (1.23s) -FAIL -exit status 1 -FAIL somepkg 1.234s diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.stop_test b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.stop_test deleted file mode 100644 index e7d42c7..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.stop_test +++ /dev/null @@ -1,13 +0,0 @@ -[----------] Running tests from StopTest -[ RUN ] StopTest.First -TearDown running. -[ OK ] StopTest.First -[ RUN ] StopTest.Second -About to call StopRunningTests. -Called StopRunningTests. -TearDown running. -[ OK ] StopTest.Second -TearDownTestSuite running. -Exiting early due to user request. -exit status 1 -FAIL somepkg 1.234s diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.unexported_test b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.unexported_test deleted file mode 100644 index 6221e65..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/golden.unexported_test +++ /dev/null @@ -1,12 +0,0 @@ -[----------] Running tests from UnexportedTest -[ RUN ] UnexportedTest.SomeTest -unexported_test.go:42: -Expected: 4 -Actual: 3 - -[ FAILED ] UnexportedTest.SomeTest -[----------] Finished with tests from UnexportedTest ---- FAIL: TestSomething (1.23s) -FAIL -exit status 1 -FAIL somepkg 1.234s diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/mock.test.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/mock.test.go deleted file mode 100644 index 8e0fca9..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/mock.test.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - . "github.com/smartystreets/assertions/internal/oglematchers" - "github.com/smartystreets/assertions/internal/oglemock" - . "github.com/smartystreets/assertions/internal/ogletest" - "github.com/smartystreets/assertions/internal/ogletest/test_cases/mock_image" - "image/color" - "testing" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type MockTest struct { - controller oglemock.Controller - image mock_image.MockImage -} - -func init() { RegisterTestSuite(&MockTest{}) } -func TestMockTest(t *testing.T) { RunTests(t) } - -func (t *MockTest) SetUp(i *TestInfo) { - t.controller = i.MockController - t.image = mock_image.NewMockImage(t.controller, "some mock image") -} - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *MockTest) ExpectationSatisfied() { - ExpectCall(t.image, "At")(11, GreaterThan(19)). - WillOnce(oglemock.Return(color.Gray{0})) - - ExpectThat(t.image.At(11, 23), IdenticalTo(color.Gray{0})) -} - -func (t *MockTest) MockExpectationNotSatisfied() { - ExpectCall(t.image, "At")(11, GreaterThan(19)). - WillOnce(oglemock.Return(color.Gray{0})) -} - -func (t *MockTest) ExpectCallForUnknownMethod() { - ExpectCall(t.image, "FooBar")(11) -} - -func (t *MockTest) UnexpectedCall() { - t.image.At(11, 23) -} - -func (t *MockTest) InvokeFunction() { - var suppliedX, suppliedY int - f := func(x, y int) color.Color { - suppliedX = x - suppliedY = y - return color.Gray{17} - } - - ExpectCall(t.image, "At")(Any(), Any()). - WillOnce(oglemock.Invoke(f)) - - ExpectThat(t.image.At(-1, 12), IdenticalTo(color.Gray{17})) - ExpectEq(-1, suppliedX) - ExpectEq(12, suppliedY) -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/mock_image/mock_image.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/mock_image/mock_image.go deleted file mode 100644 index a8d55bc..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/mock_image/mock_image.go +++ /dev/null @@ -1,115 +0,0 @@ -// This file was auto-generated using createmock. See the following page for -// more information: -// -// https://github.com/smartystreets/assertions/internal/oglemock -// - -package mock_image - -import ( - fmt "fmt" - oglemock "github.com/smartystreets/assertions/internal/oglemock" - image "image" - color "image/color" - runtime "runtime" - unsafe "unsafe" -) - -type MockImage interface { - image.Image - oglemock.MockObject -} - -type mockImage struct { - controller oglemock.Controller - description string -} - -func NewMockImage( - c oglemock.Controller, - desc string) MockImage { - return &mockImage{ - controller: c, - description: desc, - } -} - -func (m *mockImage) Oglemock_Id() uintptr { - return uintptr(unsafe.Pointer(m)) -} - -func (m *mockImage) Oglemock_Description() string { - return m.description -} - -func (m *mockImage) At(p0 int, p1 int) (o0 color.Color) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "At", - file, - line, - []interface{}{p0, p1}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockImage.At: invalid return values: %v", retVals)) - } - - // o0 color.Color - if retVals[0] != nil { - o0 = retVals[0].(color.Color) - } - - return -} - -func (m *mockImage) Bounds() (o0 image.Rectangle) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "Bounds", - file, - line, - []interface{}{}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockImage.Bounds: invalid return values: %v", retVals)) - } - - // o0 image.Rectangle - if retVals[0] != nil { - o0 = retVals[0].(image.Rectangle) - } - - return -} - -func (m *mockImage) ColorModel() (o0 color.Model) { - // Get a file name and line number for the caller. - _, file, line, _ := runtime.Caller(1) - - // Hand the call off to the controller, which does most of the work. - retVals := m.controller.HandleMethodCall( - m, - "ColorModel", - file, - line, - []interface{}{}) - - if len(retVals) != 1 { - panic(fmt.Sprintf("mockImage.ColorModel: invalid return values: %v", retVals)) - } - - // o0 color.Model - if retVals[0] != nil { - o0 = retVals[0].(color.Model) - } - - return -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/no_cases.test.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/no_cases.test.go deleted file mode 100644 index ad204e0..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/no_cases.test.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "fmt" - . "github.com/smartystreets/assertions/internal/ogletest" - "testing" -) - -func TestNoCases(t *testing.T) { RunTests(t) } - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type NoCasesTest struct { -} - -func init() { RegisterTestSuite(&NoCasesTest{}) } - -func (t *NoCasesTest) SetUpTestSuite() { - fmt.Println("SetUpTestSuite run!") -} - -func (t *NoCasesTest) TearDownTestSuite() { - fmt.Println("TearDownTestSuite run!") -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/panicking.test.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/panicking.test.go deleted file mode 100644 index 59d1fe3..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/panicking.test.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "fmt" - "log" - "testing" - - . "github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/smartystreets/assertions/internal/ogletest" -) - -func TestPanickingTest(t *testing.T) { RunTests(t) } - -//////////////////////////////////////////////////////////////////////// -// PanickingTest -//////////////////////////////////////////////////////////////////////// - -func someFuncThatPanics() { - panic("Panic in someFuncThatPanics") -} - -type PanickingTest struct { -} - -func init() { RegisterTestSuite(&PanickingTest{}) } - -func (t *PanickingTest) TearDown() { - fmt.Println("TearDown running.") -} - -func (t *PanickingTest) ExplicitPanic() { - panic("Panic in ExplicitPanic") -} - -func (t *PanickingTest) ExplicitPanicInHelperFunction() { - someFuncThatPanics() -} - -func (t *PanickingTest) NilPointerDerefence() { - var p *int - log.Println(*p) -} - -func (t *PanickingTest) ZzzSomeOtherTest() { - ExpectThat(17, Equals(17.0)) -} - -//////////////////////////////////////////////////////////////////////// -// SetUpPanicTest -//////////////////////////////////////////////////////////////////////// - -type SetUpPanicTest struct { -} - -func init() { RegisterTestSuite(&SetUpPanicTest{}) } - -func (t *SetUpPanicTest) SetUp(ti *TestInfo) { - fmt.Println("SetUp about to panic.") - panic("Panic in SetUp") -} - -func (t *SetUpPanicTest) TearDown() { - fmt.Println("TearDown running.") -} - -func (t *SetUpPanicTest) SomeTestCase() { -} - -//////////////////////////////////////////////////////////////////////// -// TearDownPanicTest -//////////////////////////////////////////////////////////////////////// - -type TearDownPanicTest struct { -} - -func init() { RegisterTestSuite(&TearDownPanicTest{}) } - -func (t *TearDownPanicTest) TearDown() { - fmt.Println("TearDown about to panic.") - panic("Panic in TearDown") -} - -func (t *TearDownPanicTest) SomeTestCase() { -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/passing.test.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/passing.test.go deleted file mode 100644 index 01d8e63..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/passing.test.go +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "fmt" - "testing" - "time" - - . "github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/smartystreets/assertions/internal/ogletest" -) - -func TestPassingTest(t *testing.T) { RunTests(t) } - -//////////////////////////////////////////////////////////////////////// -// PassingTest -//////////////////////////////////////////////////////////////////////// - -type PassingTest struct { -} - -func init() { RegisterTestSuite(&PassingTest{}) } - -func (t *PassingTest) EmptyTestMethod() { -} - -func (t *PassingTest) SuccessfullMatches() { - ExpectThat(17, Equals(17.0)) - ExpectThat(16.9, LessThan(17)) - ExpectThat("taco", HasSubstr("ac")) - - AssertThat(17, Equals(17.0)) - AssertThat(16.9, LessThan(17)) - AssertThat("taco", HasSubstr("ac")) -} - -func (t *PassingTest) ExpectAliases() { - ExpectEq(17, 17.0) - - ExpectLe(17, 17.0) - ExpectLe(17, 18.0) - ExpectLt(17, 18.0) - - ExpectGe(17, 17.0) - ExpectGe(17, 16.0) - ExpectGt(17, 16.0) - - ExpectNe(17, 18.0) - - ExpectTrue(true) - ExpectFalse(false) -} - -func (t *PassingTest) AssertAliases() { - AssertEq(17, 17.0) - - AssertLe(17, 17.0) - AssertLe(17, 18.0) - AssertLt(17, 18.0) - - AssertGe(17, 17.0) - AssertGe(17, 16.0) - AssertGt(17, 16.0) - - AssertNe(17, 18.0) - - AssertTrue(true) - AssertFalse(false) -} - -func (t *PassingTest) SlowTest() { - time.Sleep(37 * time.Millisecond) -} - -//////////////////////////////////////////////////////////////////////// -// PassingTestWithHelpers -//////////////////////////////////////////////////////////////////////// - -type PassingTestWithHelpers struct { -} - -var _ SetUpTestSuiteInterface = &PassingTestWithHelpers{} -var _ SetUpInterface = &PassingTestWithHelpers{} -var _ TearDownInterface = &PassingTestWithHelpers{} -var _ TearDownTestSuiteInterface = &PassingTestWithHelpers{} - -func init() { RegisterTestSuite(&PassingTestWithHelpers{}) } - -func (t *PassingTestWithHelpers) SetUpTestSuite() { - fmt.Println("SetUpTestSuite ran.") -} - -func (t *PassingTestWithHelpers) SetUp(ti *TestInfo) { - fmt.Println("SetUp ran.") -} - -func (t *PassingTestWithHelpers) TearDown() { - fmt.Println("TearDown ran.") -} - -func (t *PassingTestWithHelpers) TearDownTestSuite() { - fmt.Println("TearDownTestSuite ran.") -} - -func (t *PassingTestWithHelpers) EmptyTestMethod() { -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/run_twice.test.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/run_twice.test.go deleted file mode 100644 index a3a36c1..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/run_twice.test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - . "github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/smartystreets/assertions/internal/ogletest" - "testing" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type RunTwiceTest struct { -} - -func init() { RegisterTestSuite(&RunTwiceTest{}) } - -// Set up two helpers that call RunTests. The test should still only be run -// once. -func TestOgletest(t *testing.T) { RunTests(t) } -func TestOgletest2(t *testing.T) { RunTests(t) } - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *RunTwiceTest) PassingMethod() { -} - -func (t *RunTwiceTest) FailingMethod() { - ExpectThat(17, Equals(17.5)) -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/stop.test.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/stop.test.go deleted file mode 100644 index a008c08..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/stop.test.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2015 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - "fmt" - "testing" - - . "github.com/smartystreets/assertions/internal/ogletest" -) - -func TestStop(t *testing.T) { RunTests(t) } - -//////////////////////////////////////////////////////////////////////// -// Boilerplate -//////////////////////////////////////////////////////////////////////// - -type StopTest struct { -} - -var _ TearDownInterface = &StopTest{} -var _ TearDownTestSuiteInterface = &StopTest{} - -func init() { RegisterTestSuite(&StopTest{}) } - -func (t *StopTest) TearDown() { - fmt.Println("TearDown running.") -} - -func (t *StopTest) TearDownTestSuite() { - fmt.Println("TearDownTestSuite running.") -} - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *StopTest) First() { -} - -func (t *StopTest) Second() { - fmt.Println("About to call StopRunningTests.") - StopRunningTests() - fmt.Println("Called StopRunningTests.") -} - -func (t *StopTest) Third() { -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/unexported.test.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/unexported.test.go deleted file mode 100644 index a425e78..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_cases/unexported.test.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers_test - -import ( - . "github.com/smartystreets/assertions/internal/oglematchers" - . "github.com/smartystreets/assertions/internal/ogletest" - "testing" -) - -//////////////////////////////////////////////////////////////////////// -// Helpers -//////////////////////////////////////////////////////////////////////// - -type UnexportedTest struct { -} - -func init() { RegisterTestSuite(&UnexportedTest{}) } -func TestUnexportedTest(t *testing.T) { RunTests(t) } - -func (t *UnexportedTest) someUnexportedMethod() { -} - -//////////////////////////////////////////////////////////////////////// -// Tests -//////////////////////////////////////////////////////////////////////// - -func (t *UnexportedTest) SomeTest() { - ExpectThat(3, Equals(4)) -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_info.go b/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_info.go deleted file mode 100644 index 3ae1252..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/ogletest/test_info.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ogletest - -import ( - "sync" - - "golang.org/x/net/context" - - "github.com/smartystreets/assertions/internal/oglemock" -) - -// TestInfo represents information about a currently running or previously-run -// test. -type TestInfo struct { - // A mock controller that is set up to report errors to the ogletest test - // runner. This can be used for setting up mock expectations and handling - // mock calls. The Finish method should not be run by the user; ogletest will - // do that automatically after the test's TearDown method is run. - // - // Note that this feature is still experimental, and is subject to change. - MockController oglemock.Controller - - // A context that can be used by tests for long-running operations. In - // particular, this enables conveniently tracing the execution of a test - // function with reqtrace. - Ctx context.Context - - // A mutex protecting shared state. - mu sync.RWMutex - - // A set of failure records that the test has produced. - // - // GUARDED_BY(mu) - failureRecords []FailureRecord -} - -// currentlyRunningTest is the state for the currently running test, if any. -var currentlyRunningTest *TestInfo - -// newTestInfo creates a valid but empty TestInfo struct. -func newTestInfo() (info *TestInfo) { - info = &TestInfo{} - info.MockController = oglemock.NewController(&testInfoErrorReporter{info}) - info.Ctx = context.Background() - - return -} - -// testInfoErrorReporter is an oglemock.ErrorReporter that writes failure -// records into a test info struct. -type testInfoErrorReporter struct { - testInfo *TestInfo -} - -func (r *testInfoErrorReporter) ReportError( - fileName string, - lineNumber int, - err error) { - r.testInfo.mu.Lock() - defer r.testInfo.mu.Unlock() - - record := FailureRecord{ - FileName: fileName, - LineNumber: lineNumber, - Error: err.Error(), - } - - r.testInfo.failureRecords = append(r.testInfo.failureRecords, record) -} - -func (r *testInfoErrorReporter) ReportFatalError( - fileName string, - lineNumber int, - err error) { - r.ReportError(fileName, lineNumber, err) - AbortTest() -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/reqtrace/.gitignore b/_vendor/github.com/smartystreets/assertions/internal/reqtrace/.gitignore deleted file mode 100644 index daf913b..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/reqtrace/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/_vendor/github.com/smartystreets/assertions/internal/reqtrace/LICENSE b/_vendor/github.com/smartystreets/assertions/internal/reqtrace/LICENSE deleted file mode 100644 index 8f71f43..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/reqtrace/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - 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 {yyyy} {name of copyright owner} - - 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/smartystreets/assertions/internal/reqtrace/README.md b/_vendor/github.com/smartystreets/assertions/internal/reqtrace/README.md deleted file mode 100644 index 4392452..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/reqtrace/README.md +++ /dev/null @@ -1,53 +0,0 @@ -[![GoDoc](https://godoc.org/github.com/smartystreets/assertions/internal/reqtrace?status.svg)](https://godoc.org/github.com/smartystreets/assertions/internal/reqtrace) - -reqtrace is a package for simple request tracing. It requires nothing of its -user except: - - * They must use [golang.org/x/net/context][context]. - * They must add a single line to each function they want to be visible in - traces. - -[context]: http://godoc.org/golang.org/x/net/context - -In particular, reqtrace is console-based and doesn't require an HTTP server. - -**Warning**: This package is still barebones and in its early days. I reserve -the right to make backwards-incompatible changes to its API. But if it's useful -to you in your current form, have at it. - -## Use - -Call reqtrace.Trace anywhere you want to start a new root trace. (This is -probably where you create your root context.) This returns a new context that -you should pass to child operations, and a reporting function that you must use -to inform reqtrace when the trace is complete. - -For example: - -```Go -func HandleRequest(r *someRequest) (err error) { - ctx, report := reqtrace.Trace(context.Background(), "HandleRequest") - defer func() { report(err) }() - - // Do two things for this request. - DoSomething(ctx, r) - DoSomethingElse(ctx, r) -} -``` - -Within other functions that you want to show up in the trace, you -reqtrace.StartSpan (or its more convenient sibling reqtrace.StartSpanWithError): - -```Go -func DoSomething(ctx context.Context, r *someRequest) (err error) { - defer reqtrace.StartSpanWithError(&ctx, &err, "DoSomething")() - - // Process the request somehow using ctx. If downstream code also annotes - // using reqtrace, reqtrace will know that its spans are descendants of - // this one. - CallAnotherLibrary(ctx, r.Param) -} -``` - -When `--reqtrace.enable` is set, the completion of a trace will cause helpful -ASCII art to be spit out. diff --git a/_vendor/github.com/smartystreets/assertions/internal/reqtrace/reqtrace.go b/_vendor/github.com/smartystreets/assertions/internal/reqtrace/reqtrace.go deleted file mode 100644 index 853c024..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/reqtrace/reqtrace.go +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package reqtrace contains a very simple request tracing framework. -package reqtrace - -import ( - "flag" - - "golang.org/x/net/context" -) - -type contextKey int - -var fEnabled = flag.Bool("reqtrace.enable", false, "Collect and print traces.") - -// The key used to associate a *traceState with a context. -const traceStateKey contextKey = 0 - -// A function that must be called exactly once to report the outcome of an -// operation represented by a span. -type ReportFunc func(error) - -// Return false only if traces are disabled, i.e. Trace will never cause a -// trace to be initiated. -// -// REQUIRES: flag.Parsed() -func Enabled() (enabled bool) { - enabled = *fEnabled - return -} - -// Begin a span within the current trace. Return a new context that should be -// used for operations that logically occur within the span, and a report -// function that must be called with the outcome of the logical operation -// represented by the span. -// -// If no trace is active, no span will be created but ctx and report will still -// be valid. -func StartSpan( - parent context.Context, - desc string) (ctx context.Context, report ReportFunc) { - // Look for the trace state. - val := parent.Value(traceStateKey) - if val == nil { - // Nothing to do. - ctx = parent - report = func(err error) {} - return - } - - ts := val.(*traceState) - - // Set up the report function. - report = ts.CreateSpan(desc) - - // For now we don't do anything interesting with the context. In the future, - // we may use it to record span hierarchy. - ctx = parent - - return -} - -// A wrapper around StartSpan that can be more convenient to use when the -// lifetime of a span matches the lifetime of a function. Intended to be used -// in a defer statement within a function using a named error return parameter. -// -// Equivalent to calling StartSpan with *ctx, replacing *ctx with the resulting -// new context, then setting f to a function that will invoke the report -// function with the contents of *error at the time that it is called. -// -// Example: -// -// func DoSomething(ctx context.Context) (err error) { -// defer reqtrace.StartSpanWithError(&ctx, &err, "DoSomething")() -// [...] -// } -// -func StartSpanWithError( - ctx *context.Context, - err *error, - desc string) (f func()) { - var report ReportFunc - *ctx, report = StartSpan(*ctx, desc) - f = func() { report(*err) } - return -} - -// Like StartSpan, but begins a root span for a new trace if no trace is active -// in the supplied context and tracing is enabled for the process. -func Trace( - parent context.Context, - desc string) (ctx context.Context, report ReportFunc) { - // If tracing is disabled, this is a no-op. - if !*fEnabled { - ctx = parent - report = func(err error) {} - return - } - - // Is this context already being traced? If so, simply add a span. - if parent.Value(traceStateKey) != nil { - ctx, report = StartSpan(parent, desc) - return - } - - // Set up a new trace state. - ts := new(traceState) - baseReport := ts.CreateSpan(desc) - - // Log when finished. - report = func(err error) { - baseReport(err) - ts.Log() - } - - // Set up the context. - ctx = context.WithValue(parent, traceStateKey, ts) - - return -} diff --git a/_vendor/github.com/smartystreets/assertions/internal/reqtrace/trace_state.go b/_vendor/github.com/smartystreets/assertions/internal/reqtrace/trace_state.go deleted file mode 100644 index 614ef90..0000000 --- a/_vendor/github.com/smartystreets/assertions/internal/reqtrace/trace_state.go +++ /dev/null @@ -1,175 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package reqtrace - -import ( - "log" - "math" - "os" - "strings" - "sync" - "time" -) - -const logFlags = 0 - -var gLogger = log.New(os.Stderr, "reqtrace: ", logFlags) - -type span struct { - // Fixed at creation. - desc string - start time.Time - - // Updated by report functions. - finished bool - end time.Time - err error -} - -// All of the state for a particular trace root. The zero value is usable. -type traceState struct { - mu sync.Mutex - - // The list of spans associated with this state. Append-only. - // - // GUARDED_BY(mu) - spans []*span -} - -func (ts *traceState) report(spanIndex int, err error) { - ts.mu.Lock() - defer ts.mu.Unlock() - - s := ts.spans[spanIndex] - s.finished = true - s.end = time.Now() - s.err = err -} - -// Associate a new span with the trace. Return a function that will report its -// completion. -func (ts *traceState) CreateSpan(desc string) (report ReportFunc) { - ts.mu.Lock() - defer ts.mu.Unlock() - - index := len(ts.spans) - ts.spans = append(ts.spans, &span{desc: desc, start: time.Now()}) - - report = func(err error) { ts.report(index, err) } - return -} - -func round(x float64) float64 { - if x < 0 { - return math.Ceil(x - 0.5) - } - - return math.Floor(x + 0.5) -} - -// Log information about the spans in this trace. -func (ts *traceState) Log() { - ts.mu.Lock() - defer ts.mu.Unlock() - gLogger.Println() - - // Special case: we require at least one span. - if len(ts.spans) == 0 { - return - } - - // Print a banner for this trace. - const bannerHalfLength = 45 - - gLogger.Println() - gLogger.Printf( - "%s %s %s", - strings.Repeat("=", bannerHalfLength), - ts.spans[0].desc, - strings.Repeat("=", bannerHalfLength)) - gLogger.Printf("Start time: %v", ts.spans[0].start.Format(time.RFC3339Nano)) - gLogger.Println() - - // Find the minimum start time and maximum end time of all durations. - var minStart time.Time - var maxEnd time.Time - for _, s := range ts.spans { - if !s.finished { - continue - } - - if minStart.IsZero() || s.start.Before(minStart) { - minStart = s.start - } - - if maxEnd.Before(s.end) { - maxEnd = s.end - } - } - - // Bail out if something weird happened. - // - // TODO(jacobsa): Be more graceful. - totalDuration := maxEnd.Sub(minStart) - if minStart.IsZero() || maxEnd.IsZero() || totalDuration <= 0 { - gLogger.Println("(Weird trace)") - return - } - - // Calculate the number of nanoseconds elapsed, as a floating point number. - totalNs := float64(totalDuration / time.Nanosecond) - - // Log each span with some ASCII art showing its length relative to the - // total. - const totalNumCols float64 = 120 - for _, s := range ts.spans { - if !s.finished { - gLogger.Printf("(Unfinished: %s)", s.desc) - gLogger.Println() - continue - } - - // Calculate the duration of the span, and its width relative to the - // longest span. - d := s.end.Sub(s.start) - if d <= 0 { - gLogger.Println("(Weird duration)") - gLogger.Println() - continue - } - - durationRatio := float64(d/time.Nanosecond) / totalNs - - // We will offset the label and banner proportional to the time since the - // start of the earliest span. - offsetRatio := float64(s.start.Sub(minStart)/time.Nanosecond) / totalNs - offsetChars := int(round(offsetRatio * totalNumCols)) - offsetStr := strings.Repeat(" ", offsetChars) - - // Print the description and duration. - gLogger.Printf("%s%v", offsetStr, s.desc) - gLogger.Printf("%s%v", offsetStr, d) - - // Print a banner showing the duration graphically. - bannerChars := int(round(durationRatio * totalNumCols)) - var dashes string - if bannerChars > 2 { - dashes = strings.Repeat("-", bannerChars-2) - } - - gLogger.Printf("%s|%s|", offsetStr, dashes) - gLogger.Println() - } -} diff --git a/_vendor/github.com/smartystreets/assertions/messages.go b/_vendor/github.com/smartystreets/assertions/messages.go index e97b23b..2756fb0 100644 --- a/_vendor/github.com/smartystreets/assertions/messages.go +++ b/_vendor/github.com/smartystreets/assertions/messages.go @@ -3,10 +3,10 @@ package assertions const ( // equality shouldHaveBeenEqual = "Expected: '%v'\nActual: '%v'\n(Should be equal)" shouldNotHaveBeenEqual = "Expected '%v'\nto NOT equal '%v'\n(but it did)!" + shouldHaveBeenEqualTypeMismatch = "Expected: '%v' (%T)\nActual: '%v' (%T)\n(Should be equal, type mismatch)" shouldHaveBeenAlmostEqual = "Expected '%v' to almost equal '%v' (but it didn't)!" shouldHaveNotBeenAlmostEqual = "Expected '%v' to NOT almost equal '%v' (but it did)!" - shouldHaveResembled = "Expected: '%#v'\nActual: '%#v'\n(Should resemble)!" - shouldHaveResembledTypeMismatch = "Expected: '%#v'\nActual: '%#v'\n(Type mismatch: '%T' vs '%T')!" + shouldHaveResembled = "Expected: '%s'\nActual: '%s'\n(Should resemble)!" shouldNotHaveResembled = "Expected '%#v'\nto NOT resemble '%#v'\n(but it did)!" shouldBePointers = "Both arguments should be pointers " shouldHaveBeenNonNilPointer = shouldBePointers + "(the %s was %s)!" @@ -34,11 +34,17 @@ const ( // quantity comparisons const ( // collections shouldHaveContained = "Expected the container (%v) to contain: '%v' (but it didn't)!" shouldNotHaveContained = "Expected the container (%v) NOT to contain: '%v' (but it did)!" + shouldHaveContainedKey = "Expected the %v to contain the key: %v (but it didn't)!" + shouldNotHaveContainedKey = "Expected the %v NOT to contain the key: %v (but it did)!" shouldHaveBeenIn = "Expected '%v' to be in the container (%v), but it wasn't!" shouldNotHaveBeenIn = "Expected '%v' NOT to be in the container (%v), but it was!" shouldHaveBeenAValidCollection = "You must provide a valid container (was %v)!" + shouldHaveBeenAValidMap = "You must provide a valid map type (was %v)!" shouldHaveBeenEmpty = "Expected %+v to be empty (but it wasn't)!" shouldNotHaveBeenEmpty = "Expected %+v to NOT be empty (but it was)!" + shouldHaveBeenAValidInteger = "You must provide a valid integer (was %v)!" + shouldHaveBeenAValidLength = "You must provide a valid positive integer (was %v)!" + shouldHaveHadLength = "Expected %+v (length: %v) to have length equal to '%v', but it wasn't!" ) const ( // strings @@ -46,6 +52,7 @@ const ( // strings shouldNotHaveStartedWith = "Expected '%v'\nNOT to start with '%v'\n(but it did)!" shouldHaveEndedWith = "Expected '%v'\nto end with '%v'\n(but it didn't)!" shouldNotHaveEndedWith = "Expected '%v'\nNOT to end with '%v'\n(but it did)!" + shouldAllBeStrings = "All arguments to this assertion must be strings (you provided: %v)." shouldBothBeStrings = "Both arguments to this assertion must be strings (you provided %v and %v)." shouldBeString = "The argument to this assertion must be a string (you provided %v)." shouldHaveContainedSubstring = "Expected '%s' to contain substring '%s' (but it didn't)!" @@ -70,6 +77,9 @@ const ( // type checking shouldNotHaveImplemented = "Expected '%v'\nto NOT implement '%v'\n(but it did)!" shouldCompareWithInterfacePointer = "The expected value must be a pointer to an interface type (eg. *fmt.Stringer)" shouldNotBeNilActual = "The actual value was 'nil' and should be a value or a pointer to a value!" + + shouldBeError = "Expected an error value (but was '%v' instead)!" + shouldBeErrorInvalidComparisonValue = "The final argument to this assertion must be a string or an error value (you provided: '%v')." ) const ( // time comparisons diff --git a/_vendor/github.com/smartystreets/assertions/quantity.go b/_vendor/github.com/smartystreets/assertions/quantity.go index 80789f0..f28b0a0 100644 --- a/_vendor/github.com/smartystreets/assertions/quantity.go +++ b/_vendor/github.com/smartystreets/assertions/quantity.go @@ -43,7 +43,7 @@ func ShouldBeLessThanOrEqualTo(actual interface{}, expected ...interface{}) stri if fail := need(1, expected); fail != success { return fail } else if matchError := oglematchers.LessOrEqual(expected[0]).Matches(actual); matchError != nil { - return fmt.Sprintf(shouldHaveBeenLess, actual, expected[0]) + return fmt.Sprintf(shouldHaveBeenLessOrEqual, actual, expected[0]) } return success } diff --git a/_vendor/github.com/smartystreets/assertions/serializer.go b/_vendor/github.com/smartystreets/assertions/serializer.go index 90c4ae3..fa32f94 100644 --- a/_vendor/github.com/smartystreets/assertions/serializer.go +++ b/_vendor/github.com/smartystreets/assertions/serializer.go @@ -4,7 +4,7 @@ import ( "encoding/json" "fmt" - "github.com/smartystreets/goconvey/convey/reporting" + "github.com/smartystreets/assertions/internal/go-render/render" ) type Serializer interface { @@ -15,40 +15,44 @@ type Serializer interface { type failureSerializer struct{} func (self *failureSerializer) serializeDetailed(expected, actual interface{}, message string) string { - view := self.format(expected, actual, message, "%#v") - serialized, err := json.Marshal(view) - if err != nil { - return message + view := FailureView{ + Message: message, + Expected: render.Render(expected), + Actual: render.Render(actual), } + serialized, _ := json.Marshal(view) return string(serialized) } func (self *failureSerializer) serialize(expected, actual interface{}, message string) string { - view := self.format(expected, actual, message, "%+v") - serialized, err := json.Marshal(view) - if err != nil { - return message - } - return string(serialized) -} - -func (self *failureSerializer) format(expected, actual interface{}, message string, format string) reporting.FailureView { - return reporting.FailureView{ + view := FailureView{ Message: message, - Expected: fmt.Sprintf(format, expected), - Actual: fmt.Sprintf(format, actual), + Expected: fmt.Sprintf("%+v", expected), + Actual: fmt.Sprintf("%+v", actual), } + serialized, _ := json.Marshal(view) + return string(serialized) } func newSerializer() *failureSerializer { return &failureSerializer{} } +/////////////////////////////////////////////////////////////////////////////// + +// This struct is also declared in github.com/smartystreets/goconvey/convey/reporting. +// The json struct tags should be equal in both declarations. +type FailureView struct { + Message string `json:"Message"` + Expected string `json:"Expected"` + Actual string `json:"Actual"` +} + /////////////////////////////////////////////////////// // noopSerializer just gives back the original message. This is useful when we are using -// the assertions from a context other than the web UI, that requires the JSON structure -// provided by the failureSerializer. +// the assertions from a context other than the GoConvey Web UI, that requires the JSON +// structure provided by the failureSerializer. type noopSerializer struct{} func (self *noopSerializer) serialize(expected, actual interface{}, message string) string { diff --git a/_vendor/github.com/smartystreets/assertions/should/should.go b/_vendor/github.com/smartystreets/assertions/should/should.go deleted file mode 100644 index e153be3..0000000 --- a/_vendor/github.com/smartystreets/assertions/should/should.go +++ /dev/null @@ -1,67 +0,0 @@ -// package should is simply a rewording of the assertion -// functions in the assertions package. -package should - -import "github.com/smartystreets/assertions" - -var ( - Equal = assertions.ShouldEqual - NotEqual = assertions.ShouldNotEqual - AlmostEqual = assertions.ShouldAlmostEqual - NotAlmostEqual = assertions.ShouldNotAlmostEqual - Resemble = assertions.ShouldResemble - NotResemble = assertions.ShouldNotResemble - PointTo = assertions.ShouldPointTo - NotPointTo = assertions.ShouldNotPointTo - BeNil = assertions.ShouldBeNil - NotBeNil = assertions.ShouldNotBeNil - BeTrue = assertions.ShouldBeTrue - BeFalse = assertions.ShouldBeFalse - BeZeroValue = assertions.ShouldBeZeroValue - - BeGreaterThan = assertions.ShouldBeGreaterThan - BeGreaterThanOrEqualTo = assertions.ShouldBeGreaterThanOrEqualTo - BeLessThan = assertions.ShouldBeLessThan - BeLessThanOrEqualTo = assertions.ShouldBeLessThanOrEqualTo - BeBetween = assertions.ShouldBeBetween - NotBeBetween = assertions.ShouldNotBeBetween - BeBetweenOrEqual = assertions.ShouldBeBetweenOrEqual - NotBeBetweenOrEqual = assertions.ShouldNotBeBetweenOrEqual - - Contain = assertions.ShouldContain - NotContain = assertions.ShouldNotContain - BeIn = assertions.ShouldBeIn - NotBeIn = assertions.ShouldNotBeIn - BeEmpty = assertions.ShouldBeEmpty - NotBeEmpty = assertions.ShouldNotBeEmpty - - StartWith = assertions.ShouldStartWith - NotStartWith = assertions.ShouldNotStartWith - EndWith = assertions.ShouldEndWith - NotEndWith = assertions.ShouldNotEndWith - BeBlank = assertions.ShouldBeBlank - NotBeBlank = assertions.ShouldNotBeBlank - ContainSubstring = assertions.ShouldContainSubstring - NotContainSubstring = assertions.ShouldNotContainSubstring - - Panic = assertions.ShouldPanic - NotPanic = assertions.ShouldNotPanic - PanicWith = assertions.ShouldPanicWith - NotPanicWith = assertions.ShouldNotPanicWith - - HaveSameTypeAs = assertions.ShouldHaveSameTypeAs - NotHaveSameTypeAs = assertions.ShouldNotHaveSameTypeAs - Implement = assertions.ShouldImplement - NotImplement = assertions.ShouldNotImplement - - HappenBefore = assertions.ShouldHappenBefore - HappenOnOrBefore = assertions.ShouldHappenOnOrBefore - HappenAfter = assertions.ShouldHappenAfter - HappenOnOrAfter = assertions.ShouldHappenOnOrAfter - HappenBetween = assertions.ShouldHappenBetween - HappenOnOrBetween = assertions.ShouldHappenOnOrBetween - NotHappenOnOrBetween = assertions.ShouldNotHappenOnOrBetween - HappenWithin = assertions.ShouldHappenWithin - NotHappenWithin = assertions.ShouldNotHappenWithin - BeChronological = assertions.ShouldBeChronological -) diff --git a/_vendor/github.com/smartystreets/assertions/strings.go b/_vendor/github.com/smartystreets/assertions/strings.go index 1b887b1..dbc3f04 100644 --- a/_vendor/github.com/smartystreets/assertions/strings.go +++ b/_vendor/github.com/smartystreets/assertions/strings.go @@ -181,3 +181,47 @@ func ShouldNotBeBlank(actual interface{}, expected ...interface{}) string { } return success } + +// ShouldEqualWithout receives exactly 3 string parameters and ensures that the first is equal to the second +// after removing all instances of the third from the first using strings.Replace(first, third, "", -1). +func ShouldEqualWithout(actual interface{}, expected ...interface{}) string { + if fail := need(2, expected); fail != success { + return fail + } + actualString, ok1 := actual.(string) + expectedString, ok2 := expected[0].(string) + replace, ok3 := expected[1].(string) + + if !ok1 || !ok2 || !ok3 { + return fmt.Sprintf(shouldAllBeStrings, []reflect.Type{ + reflect.TypeOf(actual), + reflect.TypeOf(expected[0]), + reflect.TypeOf(expected[1]), + }) + } + + replaced := strings.Replace(actualString, replace, "", -1) + if replaced == expectedString { + return "" + } + + return fmt.Sprintf("Expected '%s' to equal '%s' but without any '%s' (but it didn't).", actualString, expectedString, replace) +} + +// ShouldEqualTrimSpace receives exactly 2 string parameters and ensures that the first is equal to the second +// after removing all leading and trailing whitespace using strings.TrimSpace(first). +func ShouldEqualTrimSpace(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + + actualString, valueIsString := actual.(string) + _, value2IsString := expected[0].(string) + + if !valueIsString || !value2IsString { + return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) + } + + actualString = strings.TrimSpace(actualString) + return ShouldEqual(actualString, expected[0]) +} diff --git a/_vendor/github.com/smartystreets/assertions/type.go b/_vendor/github.com/smartystreets/assertions/type.go index 3fc00f6..25e0ed0 100644 --- a/_vendor/github.com/smartystreets/assertions/type.go +++ b/_vendor/github.com/smartystreets/assertions/type.go @@ -65,10 +65,6 @@ func ShouldImplement(actual interface{}, expectedList ...interface{}) string { expectedInterface := expectedType.Elem() - if actualType == nil { - return fmt.Sprintf(shouldHaveImplemented, expectedInterface, actual) - } - if !actualType.Implements(expectedInterface) { return fmt.Sprintf(shouldHaveImplemented, expectedInterface, actualType) } @@ -110,3 +106,28 @@ func ShouldNotImplement(actual interface{}, expectedList ...interface{}) string } return success } + +// ShouldBeError asserts that the first argument implements the error interface. +// It also compares the first argument against the second argument if provided +// (which must be an error message string or another error value). +func ShouldBeError(actual interface{}, expected ...interface{}) string { + if fail := atMost(1, expected); fail != success { + return fail + } + + if !isError(actual) { + return fmt.Sprintf(shouldBeError, reflect.TypeOf(actual)) + } + + if len(expected) == 0 { + return success + } + + if expected := expected[0]; !isString(expected) && !isError(expected) { + return fmt.Sprintf(shouldBeErrorInvalidComparisonValue, reflect.TypeOf(expected)) + } + return ShouldEqual(fmt.Sprint(actual), fmt.Sprint(expected[0])) +} + +func isString(value interface{}) bool { _, ok := value.(string); return ok } +func isError(value interface{}) bool { _, ok := value.(error); return ok } diff --git a/_vendor/github.com/smartystreets/goconvey/LICENSE.md b/_vendor/github.com/smartystreets/goconvey/LICENSE.md index 55b7700..3f87a40 100644 --- a/_vendor/github.com/smartystreets/goconvey/LICENSE.md +++ b/_vendor/github.com/smartystreets/goconvey/LICENSE.md @@ -1,21 +1,21 @@ -Copyright (c) 2014 SmartyStreets, LLC +Copyright (c) 2016 SmartyStreets, LLC -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 +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 +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 +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. NOTE: Various optional and subordinate components carry their own licensing diff --git a/_vendor/github.com/smartystreets/goconvey/convey/assertions.go b/_vendor/github.com/smartystreets/goconvey/convey/assertions.go index 52d90ee..b37f6b4 100644 --- a/_vendor/github.com/smartystreets/goconvey/convey/assertions.go +++ b/_vendor/github.com/smartystreets/goconvey/convey/assertions.go @@ -26,12 +26,15 @@ var ( ShouldBeBetweenOrEqual = assertions.ShouldBeBetweenOrEqual ShouldNotBeBetweenOrEqual = assertions.ShouldNotBeBetweenOrEqual - ShouldContain = assertions.ShouldContain - ShouldNotContain = assertions.ShouldNotContain - ShouldBeIn = assertions.ShouldBeIn - ShouldNotBeIn = assertions.ShouldNotBeIn - ShouldBeEmpty = assertions.ShouldBeEmpty - ShouldNotBeEmpty = assertions.ShouldNotBeEmpty + ShouldContain = assertions.ShouldContain + ShouldNotContain = assertions.ShouldNotContain + ShouldContainKey = assertions.ShouldContainKey + ShouldNotContainKey = assertions.ShouldNotContainKey + ShouldBeIn = assertions.ShouldBeIn + ShouldNotBeIn = assertions.ShouldNotBeIn + ShouldBeEmpty = assertions.ShouldBeEmpty + ShouldNotBeEmpty = assertions.ShouldNotBeEmpty + ShouldHaveLength = assertions.ShouldHaveLength ShouldStartWith = assertions.ShouldStartWith ShouldNotStartWith = assertions.ShouldNotStartWith @@ -62,4 +65,6 @@ var ( ShouldHappenWithin = assertions.ShouldHappenWithin ShouldNotHappenWithin = assertions.ShouldNotHappenWithin ShouldBeChronological = assertions.ShouldBeChronological + + ShouldBeError = assertions.ShouldBeError ) diff --git a/_vendor/github.com/smartystreets/goconvey/convey/gotest/utils.go b/_vendor/github.com/smartystreets/goconvey/convey/gotest/utils.go index 2855761..3a5c848 100644 --- a/_vendor/github.com/smartystreets/goconvey/convey/gotest/utils.go +++ b/_vendor/github.com/smartystreets/goconvey/convey/gotest/utils.go @@ -4,19 +4,10 @@ package gotest import ( - "fmt" "runtime" "strings" ) -func FormatExternalFileAndLine() string { - file, line, _ := ResolveExternalCaller() - if line == -1 { - return "" // panic? - } - return fmt.Sprintf("%s:%d", file, line) -} - func ResolveExternalCaller() (file string, line int, name string) { var caller_id uintptr callers := runtime.Callers(0, callStack) diff --git a/_vendor/github.com/smartystreets/goconvey/convey/init.go b/_vendor/github.com/smartystreets/goconvey/convey/init.go index 9f6ff81..1d77ff3 100644 --- a/_vendor/github.com/smartystreets/goconvey/convey/init.go +++ b/_vendor/github.com/smartystreets/goconvey/convey/init.go @@ -18,9 +18,9 @@ func init() { } func declareFlags() { - flag.BoolVar(&json, "json", false, "When true, emits results in JSON blocks. Default: 'false'") - flag.BoolVar(&silent, "silent", false, "When true, all output from GoConvey is suppressed.") - flag.BoolVar(&story, "story", false, "When true, emits story output, otherwise emits dot output. When not provided, this flag mirros the value of the '-test.v' flag") + flag.BoolVar(&json, "convey-json", false, "When true, emits results in JSON blocks. Default: 'false'") + flag.BoolVar(&silent, "convey-silent", false, "When true, all output from GoConvey is suppressed.") + flag.BoolVar(&story, "convey-story", false, "When true, emits story output, otherwise emits dot output. When not provided, this flag mirros the value of the '-test.v' flag") if noStoryFlagProvided() { story = verboseEnabled @@ -34,14 +34,19 @@ func noStoryFlagProvided() bool { } func buildReporter() reporting.Reporter { + selectReporter := os.Getenv("GOCONVEY_REPORTER") + switch { case testReporter != nil: return testReporter - case json: + case json || selectReporter == "json": return reporting.BuildJsonReporter() - case silent: + case silent || selectReporter == "silent": return reporting.BuildSilentReporter() - case story: + case selectReporter == "dot": + // Story is turned on when verbose is set, so we need to check for dot reporter first. + return reporting.BuildDotReporter() + case story || selectReporter == "story": return reporting.BuildStoryReporter() default: return reporting.BuildDotReporter() diff --git a/_vendor/github.com/smartystreets/goconvey/convey/reporting/init.go b/_vendor/github.com/smartystreets/goconvey/convey/reporting/init.go index 44a1332..44d080e 100644 --- a/_vendor/github.com/smartystreets/goconvey/convey/reporting/init.go +++ b/_vendor/github.com/smartystreets/goconvey/convey/reporting/init.go @@ -1,14 +1,13 @@ package reporting import ( - "fmt" "os" "runtime" "strings" ) func init() { - if !isXterm() { + if !isColorableTerminal() { monochrome() } @@ -43,7 +42,7 @@ func BuildSilentReporter() Reporter { out := NewPrinter(NewConsole()) return NewReporters( NewGoTestReporter(), - NewProblemReporter(out)) + NewSilentProblemReporter(out)) } var ( @@ -83,10 +82,8 @@ func monochrome() { greenColor, yellowColor, redColor, resetColor = "", "", "", "" } -func isXterm() bool { - env := fmt.Sprintf("%v", os.Environ()) - return strings.Contains(env, " TERM=isXterm") || - strings.Contains(env, " TERM=xterm") +func isColorableTerminal() bool { + return strings.Contains(os.Getenv("TERM"), "color") } // This interface allows us to pass the *testing.T struct diff --git a/_vendor/github.com/smartystreets/goconvey/convey/reporting/problems.go b/_vendor/github.com/smartystreets/goconvey/convey/reporting/problems.go index c610ba8..9ae493a 100644 --- a/_vendor/github.com/smartystreets/goconvey/convey/reporting/problems.go +++ b/_vendor/github.com/smartystreets/goconvey/convey/reporting/problems.go @@ -3,6 +3,7 @@ package reporting import "fmt" type problem struct { + silent bool out *Printer errors []*AssertionResult failures []*AssertionResult @@ -28,9 +29,13 @@ func (self *problem) EndStory() { self.prepareForNextStory() } func (self *problem) show(display func(), color string) { - fmt.Print(color) + if !self.silent { + fmt.Print(color) + } display() - fmt.Print(resetColor) + if !self.silent { + fmt.Print(resetColor) + } self.out.Dedent() } func (self *problem) showErrors() { @@ -62,6 +67,13 @@ func NewProblemReporter(out *Printer) *problem { self.prepareForNextStory() return self } + +func NewSilentProblemReporter(out *Printer) *problem { + self := NewProblemReporter(out) + self.silent = true + return self +} + func (self *problem) prepareForNextStory() { self.errors = []*AssertionResult{} self.failures = []*AssertionResult{} diff --git a/_vendor/github.com/smartystreets/goconvey/convey/reporting/reports.go b/_vendor/github.com/smartystreets/goconvey/convey/reporting/reports.go index 659a0ec..712e6ad 100644 --- a/_vendor/github.com/smartystreets/goconvey/convey/reporting/reports.go +++ b/_vendor/github.com/smartystreets/goconvey/convey/reporting/reports.go @@ -76,10 +76,12 @@ func removePackagePath(name string) string { /////////////////// FailureView //////////////////////// +// This struct is also declared in github.com/smartystreets/assertions. +// The json struct tags should be equal in both declarations. type FailureView struct { - Message string - Expected string - Actual string + Message string `json:"Message"` + Expected string `json:"Expected"` + Actual string `json:"Actual"` } ////////////////////AssertionResult ////////////////////// diff --git a/_vendor/github.com/smartystreets/goconvey/convey/reporting/statistics.go b/_vendor/github.com/smartystreets/goconvey/convey/reporting/statistics.go index 28e1d20..c3ccd05 100644 --- a/_vendor/github.com/smartystreets/goconvey/convey/reporting/statistics.go +++ b/_vendor/github.com/smartystreets/goconvey/convey/reporting/statistics.go @@ -1,12 +1,18 @@ package reporting -import "fmt" +import ( + "fmt" + "sync" +) func (self *statistics) BeginStory(story *StoryReport) {} func (self *statistics) Enter(scope *ScopeReport) {} func (self *statistics) Report(report *AssertionResult) { + self.Lock() + defer self.Unlock() + if !self.failing && report.Failure != "" { self.failing = true } @@ -23,25 +29,36 @@ func (self *statistics) Report(report *AssertionResult) { func (self *statistics) Exit() {} func (self *statistics) EndStory() { + self.Lock() + defer self.Unlock() + if !self.suppressed { - self.PrintSummary() + self.printSummaryLocked() } } func (self *statistics) Suppress() { + self.Lock() + defer self.Unlock() self.suppressed = true } func (self *statistics) PrintSummary() { - self.reportAssertions() - self.reportSkippedSections() - self.completeReport() + self.Lock() + defer self.Unlock() + self.printSummaryLocked() } -func (self *statistics) reportAssertions() { - self.decideColor() + +func (self *statistics) printSummaryLocked() { + self.reportAssertionsLocked() + self.reportSkippedSectionsLocked() + self.completeReportLocked() +} +func (self *statistics) reportAssertionsLocked() { + self.decideColorLocked() self.out.Print("\n%d total %s", self.total, plural("assertion", self.total)) } -func (self *statistics) decideColor() { +func (self *statistics) decideColorLocked() { if self.failing && !self.erroring { fmt.Print(yellowColor) } else if self.erroring { @@ -50,13 +67,13 @@ func (self *statistics) decideColor() { fmt.Print(greenColor) } } -func (self *statistics) reportSkippedSections() { +func (self *statistics) reportSkippedSectionsLocked() { if self.skipped > 0 { fmt.Print(yellowColor) self.out.Print(" (one or more sections skipped)") } } -func (self *statistics) completeReport() { +func (self *statistics) completeReportLocked() { fmt.Print(resetColor) self.out.Print("\n") self.out.Print("\n") @@ -73,6 +90,8 @@ func NewStatisticsReporter(out *Printer) *statistics { } type statistics struct { + sync.Mutex + out *Printer total int failing bool diff --git a/_vendor/goji.io/.travis.yml b/_vendor/goji.io/.travis.yml index 73353f5..8ca23fa 100644 --- a/_vendor/goji.io/.travis.yml +++ b/_vendor/goji.io/.travis.yml @@ -4,7 +4,7 @@ sudo: false matrix: include: - - go: 1.5 + - go: 1.7 - go: tip script: diff --git a/_vendor/goji.io/LICENSE b/_vendor/goji.io/LICENSE index 3f93ca1..38bc735 100644 --- a/_vendor/goji.io/LICENSE +++ b/_vendor/goji.io/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2015 Carl Jackson (carl@avtok.com) +Copyright (c) 2015, 2016 Carl Jackson (carl@avtok.com) MIT License diff --git a/_vendor/goji.io/README.md b/_vendor/goji.io/README.md index 9949855..7592be9 100644 --- a/_vendor/goji.io/README.md +++ b/_vendor/goji.io/README.md @@ -1,18 +1,20 @@ Goji ==== +[![GoDoc](https://godoc.org/goji.io?status.svg)](https://godoc.org/goji.io) [![Build Status](https://travis-ci.org/goji/goji.svg?branch=master)](https://travis-ci.org/goji/goji) + Goji is a HTTP request multiplexer, similar to [`net/http.ServeMux`][servemux]. It compares incoming requests to a list of registered [Patterns][pattern], and -dispatches to the [Handler][handler] that corresponds to the first matching +dispatches to the [http.Handler][handler] that corresponds to the first matching Pattern. Goji also supports [Middleware][middleware] (composable shared -functionality applied to every request) and uses the de facto standard -[`x/net/context`][context] to store request-scoped values. +functionality applied to every request) and uses the standard +[`context`][context] package to store request-scoped values. [servemux]: https://golang.org/pkg/net/http/#ServeMux [pattern]: https://godoc.org/goji.io#Pattern -[handler]: https://godoc.org/goji.io#Handler +[handler]: https://golang.org/pkg/net/http/#Handler [middleware]: https://godoc.org/goji.io#Mux.Use -[context]: https://godoc.org/golang.org/x/net/context +[context]: https://golang.org/pkg/context Quick Start @@ -27,17 +29,16 @@ import ( "goji.io" "goji.io/pat" - "golang.org/x/net/context" ) -func hello(ctx context.Context, w http.ResponseWriter, r *http.Request) { - name := pat.Param(ctx, "name") +func hello(w http.ResponseWriter, r *http.Request) { + name := pat.Param(r, "name") fmt.Fprintf(w, "Hello, %s!", name) } func main() { mux := goji.NewMux() - mux.HandleFuncC(pat.Get("/hello/:name"), hello) + mux.HandleFunc(pat.Get("/hello/:name"), hello) http.ListenAndServe("localhost:8000", mux) } @@ -51,17 +52,20 @@ Please refer to [Goji's GoDoc Documentation][godoc] for a full API reference. Stability --------- -As of this writing (late November 2015), this version of Goji is still very new, -and during this initial experimental stage it offers no API stability -guarantees. After the API has had a little time to bake, Goji expects to adhere -strictly to the Go project's [compatibility guidelines][compat], guaranteeing to -never break compatibility with existing code. +Goji's API was recently updated to use the new `net/http` and `context` +integration, and is therefore some of its interfaces are in a state of flux. We +don't expect any further changes to the API, and expect to be able to announce +API stability soon. Goji is suitable for use in production. -We expect to be able to make such a guarantee by early 2016. Although we reserve -the right to do so, there are no breaking API changes planned until that point, -and we are unlikely to accept any such breaking changes. +Prior to Go 1.7, Goji promised API stability with a different API to the one +that is offered today. The author broke this promise, and does not take this +breach of trust lightly. While stability is obviously extremely important, the +author and community have decided to follow the broader Go community in +standardizing on the standard library copy of the `context` package. -[compat]: https://golang.org/doc/go1compat +Users of the old API can find that familiar API on the `net-context` branch. The +author promises to maintain both the `net-context` branch and `master` for the +forseeable future. Community / Contributing diff --git a/_vendor/goji.io/dispatch.go b/_vendor/goji.io/dispatch.go index fdaa491..1fef86d 100644 --- a/_vendor/goji.io/dispatch.go +++ b/_vendor/goji.io/dispatch.go @@ -4,16 +4,16 @@ import ( "net/http" "goji.io/internal" - "golang.org/x/net/context" ) type dispatch struct{} -func (d dispatch) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) { +func (d dispatch) ServeHTTP(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() h := ctx.Value(internal.Handler) if h == nil { http.NotFound(w, r) } else { - h.(Handler).ServeHTTPC(ctx, w, r) + h.(http.Handler).ServeHTTP(w, r) } } diff --git a/_vendor/goji.io/goji.go b/_vendor/goji.io/goji.go index ce97be7..4b4a084 100644 --- a/_vendor/goji.io/goji.go +++ b/_vendor/goji.io/goji.go @@ -9,84 +9,55 @@ their own, especially if their needs are unusual. */ package goji -import ( - "net/http" - - "golang.org/x/net/context" -) +import "net/http" /* -Pattern determines whether or not a given request matches some criteria. Goji -users looking for a concrete type that implements this interface should consider +Pattern determines whether a given request matches some criteria. Goji users +looking for a concrete type that implements this interface should consider Goji's "pat" sub-package, which implements a small domain specific language for HTTP routing. -Most patterns match on a relatively small portion of incoming requests, most +Patterns typically only examine a small portion of incoming requests, most commonly the HTTP method and the URL's RawPath. As an optimization, Goji can elide calls to your Pattern for requests it knows cannot match. Pattern authors who wish to take advantage of this functionality (and in some cases an asymptotic performance improvement) can augment their Pattern implementations -with methods with any of the following signatures: +with any of the following methods: - // HTTPMethods returns a set of HTTP methods that all requests that this - // Pattern matches must be in, or nil if it's not possible to determine - // which HTTP methods might be matched. + // HTTPMethods returns a set of HTTP methods that this Pattern matches, + // or nil if it's not possible to determine which HTTP methods might be + // matched. Put another way, requests with HTTP methods not in the + // returned set are guaranteed to never match this Pattern. HTTPMethods() map[string]struct{} // PathPrefix returns a string which all RawPaths that match this - // Pattern must contain as a prefix. + // Pattern must have as a prefix. Put another way, requests with + // RawPaths that do not contain the returned string as a prefix are + // guaranteed to never match this Pattern. PathPrefix() string The presence or lack of these performance improvements should be viewed as an -implementation detail and are not part of Goji's API compatibility guarantee. -It is the responsibility of Pattern authors to ensure that their Match function -(which is part of the API compatibility guarantee) always returns correct -results, even if optimizations are not performed. +implementation detail and are not part of Goji's API compatibility guarantee. It +is the responsibility of Pattern authors to ensure that their Match function +always returns correct results, even if these optimizations are not performed. All operations on Patterns must be safe for concurrent use by multiple goroutines. */ type Pattern interface { - // Match examines the request and request context to determine if the - // request is a match. If so, it returns a non-nil context.Context - // derived from the input Context (or perhaps the input Context - // unchanged). The returned context may be used to store request-scoped - // data, such as variables extracted from the URL. + // Match examines the input Request to determine if it matches some + // criteria, and if so returns a non-nil output Request. This returned + // Request will be passed to the middleware stack and the final Handler. // - // Match must not mutate the passed request. - Match(context.Context, *http.Request) context.Context -} - -/* -Handler is a context-aware variant of net/http.Handler. It has the same -semantics as http.Handler, except that a request-scoped context is additionally -passed to the handler function. -*/ -type Handler interface { - ServeHTTPC(context.Context, http.ResponseWriter, *http.Request) -} - -/* -HandlerFunc is a context-aware variant of net/http.HandlerFunc. It has the same -semantics as http.Handler, except that a request-scoped context is additionally -passed to the function. - -HandlerFunc implements both the Handler and http.Handler interfaces. -*/ -type HandlerFunc func(context.Context, http.ResponseWriter, *http.Request) - -/* -ServeHTTP implements net/http.Handler. It calls the underlying function with a -context of context.TODO in order to ease the conversion of non-context-aware -Handlers to context-aware ones using static analysis. -*/ -func (h HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) { - h(context.TODO(), w, r) -} - -/* -ServeHTTPC implements Handler. -*/ -func (h HandlerFunc) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) { - h(ctx, w, r) + // Patterns often extract variables from the Request, for instance from + // the URL or from HTTP headers. In this case, it is common for the + // Request returned from the Match function to be derived from the input + // Request using the WithContext function, with a Context that contains + // those variable bindings. If no variable bindings are necessary, + // another common choice is to return the input Request unchanged. + // + // Match must not mutate the passed request if it returns nil. + // Implementers are also strongly discouraged from mutating the input + // Request even in the event of a match; instead, prefer making a copy. + Match(*http.Request) *http.Request } diff --git a/_vendor/goji.io/handle.go b/_vendor/goji.io/handle.go index 2dfb476..ec76d9b 100644 --- a/_vendor/goji.io/handle.go +++ b/_vendor/goji.io/handle.go @@ -1,17 +1,10 @@ package goji -import ( - "net/http" - - "golang.org/x/net/context" - - "goji.io/internal" -) +import "net/http" /* Handle adds a new route to the Mux. Requests that match the given Pattern will -be dispatched to the given http.Handler. If the http.Handler also supports -Handler, that interface will be used instead. +be dispatched to the given http.Handler. Routing is performed in the order in which routes are added: the first route with a matching Pattern will be used. In particular, Goji guarantees that @@ -19,23 +12,20 @@ routing is performed in a manner that is indistinguishable from the following algorithm: // Assume routes is a slice that every call to Handle appends to - for route := range routes { + for _, route := range routes { // For performance, Patterns can opt out of this call to Match. // See the documentation for Pattern for more. - if ctx2 := route.pattern.Match(ctx, r); ctx2 != nil { - route.handler.ServeHTTPC(ctx2, w, r) + if r2 := route.pattern.Match(r); r2 != nil { + route.handler.ServeHTTP(w, r2) break } } -It is not safe to concurrently register routes from multiple goroutines. +It is not safe to concurrently register routes from multiple goroutines, or to +register routes concurrently with requests. */ func (m *Mux) Handle(p Pattern, h http.Handler) { - gh, ok := h.(Handler) - if !ok { - gh = internal.ContextWrapper{Handler: h} - } - m.router.add(p, gh) + m.router.add(p, h) } /* @@ -45,22 +35,3 @@ handler wrapped with http.HandlerFunc, and is provided only for convenience. func (m *Mux) HandleFunc(p Pattern, h func(http.ResponseWriter, *http.Request)) { m.Handle(p, http.HandlerFunc(h)) } - -/* -HandleC adds a new context-aware route to the Mux. See the documentation for -Handle for more information about the semantics of routing. - -It is not safe to concurrently register routes from multiple goroutines. -*/ -func (m *Mux) HandleC(p Pattern, h Handler) { - m.router.add(p, h) -} - -/* -HandleFuncC adds a new context-aware route to the Mux. It is equivalent to -calling HandleC on a handler wrapped with HandlerFunc, and is provided for -convenience. -*/ -func (m *Mux) HandleFuncC(p Pattern, h func(context.Context, http.ResponseWriter, *http.Request)) { - m.HandleC(p, HandlerFunc(h)) -} diff --git a/_vendor/goji.io/internal/context.go b/_vendor/goji.io/internal/context.go index 47ea076..343ecb9 100644 --- a/_vendor/goji.io/internal/context.go +++ b/_vendor/goji.io/internal/context.go @@ -3,15 +3,15 @@ package internal // ContextKey is a type used for Goji's context.Context keys. type ContextKey int -const ( +var ( // Path is the context key used to store the path Goji uses for its // PathPrefix optimization. - Path ContextKey = iota + Path interface{} = ContextKey(0) // Pattern is the context key used to store the Pattern that Goji last // matched. - Pattern + Pattern interface{} = ContextKey(1) // Handler is the context key used to store the Handler that Goji last // mached (and will therefore dispatch to at the end of the middleware // stack). - Handler + Handler interface{} = ContextKey(2) ) diff --git a/_vendor/goji.io/internal/http.go b/_vendor/goji.io/internal/http.go deleted file mode 100644 index 79b8bdf..0000000 --- a/_vendor/goji.io/internal/http.go +++ /dev/null @@ -1,19 +0,0 @@ -package internal - -import ( - "net/http" - - "golang.org/x/net/context" -) - -// ContextWrapper is a standard bridge type from http.Handlers to context-aware -// Handlers. It is included here so that the middleware subpackage can use it to -// unwrap Handlers. -type ContextWrapper struct { - http.Handler -} - -// ServeHTTPC implements goji.Handler. -func (c ContextWrapper) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) { - c.Handler.ServeHTTP(w, r) -} diff --git a/_vendor/goji.io/middleware.go b/_vendor/goji.io/middleware.go index 759e17e..bd71175 100644 --- a/_vendor/goji.io/middleware.go +++ b/_vendor/goji.io/middleware.go @@ -1,38 +1,34 @@ package goji -import ( - "net/http" - - "golang.org/x/net/context" -) +import "net/http" /* Use appends a middleware to the Mux's middleware stack. -Middleware are composable pieces of functionality that augment Handlers. Common -examples of middleware include request loggers, authentication checkers, and -metrics gatherers. +Middleware are composable pieces of functionality that augment http.Handlers. +Common examples of middleware include request loggers, authentication checkers, +and metrics gatherers. Middleware are evaluated in the reverse order in which they were added, but the -resulting Handlers execute in "normal" order (i.e., the Handler returned by the -first Middleware to be added gets called first). +resulting http.Handlers execute in "normal" order (i.e., the http.Handler +returned by the first Middleware to be added gets called first). -For instance, given middleware A, B, and C, added in that order, Goji's behavior -will look something like this: +For instance, given middleware A, B, and C, added in that order, Goji will +behave similarly to this snippet: augmentedHandler := A(B(C(yourHandler))) - augmentedHandler.ServeHTTPC(ctx, w, r) + augmentedHandler.ServeHTTP(w, r) Assuming each of A, B, and C look something like this: - func A(inner goji.Handler) goji.Handler { + func A(inner http.Handler) http.Handler { log.Print("A: called") - mw := func(ctx context.Context, w http.ResponseWriter, r *http.Request) { + mw := func(w http.ResponseWriter, r *http.Request) { log.Print("A: before") - inner.ServeHTTPC(ctx, w, r) + inner.ServeHTTP(w, r) log.Print("A: after") } - return goji.HandlerFunc(mw) + return http.HandlerFunc(mw) } we'd expect to see the following in the log: @@ -49,65 +45,31 @@ we'd expect to see the following in the log: B: after A: after -Note that augmentedHandler may be called many times. Put another way, you will -see many invocations of the portion of the log below the divider, and perhaps -only see the portion above the divider a single time. Also note that as an -implementation detail, net/http-style middleware will be called once per -request, even though the Goji-style middleware around them might only ever be -called a single time. +Note that augmentedHandler will called many times, producing the log output +below the divider, while the outer middleware functions (the log output above +the divider) will only be called a handful of times at application boot. Middleware in Goji is called after routing has been performed. Therefore it is -possible to examine any routing information placed into the context by Patterns, -or to view or modify the Handler that will be routed to. +possible to examine any routing information placed into the Request context by +Patterns, or to view or modify the http.Handler that will be routed to. +Middleware authors should read the documentation for the "middleware" subpackage +for more information about how this is done. The http.Handler returned by the given middleware must be safe for concurrent use by multiple goroutines. It is not safe to concurrently register middleware -from multiple goroutines. +from multiple goroutines, or to register middleware concurrently with requests. */ func (m *Mux) Use(middleware func(http.Handler) http.Handler) { - m.middleware = append(m.middleware, func(h Handler) Handler { - return outerBridge{middleware, h} - }) - m.buildChain() -} - -/* -UseC appends a context-aware middleware to the Mux's middleware stack. See the -documentation for Use for more information about the semantics of middleware. - -The Handler returned by the given middleware must be safe for concurrent use by -multiple goroutines. It is not safe to concurrently register middleware from -multiple goroutines. -*/ -func (m *Mux) UseC(middleware func(Handler) Handler) { m.middleware = append(m.middleware, middleware) m.buildChain() } -// Pre-compile a Handler for us to use during dispatch. Yes, this means that -// adding middleware is quadratic, but it (a) happens during configuration time, -// not at "runtime", and (b) n should ~always be small. +// Pre-compile a http.Handler for us to use during dispatch. Yes, this means +// that adding middleware is quadratic, but it (a) happens during configuration +// time, not at "runtime", and (b) n should ~always be small. func (m *Mux) buildChain() { m.handler = dispatch{} for i := len(m.middleware) - 1; i >= 0; i-- { m.handler = m.middleware[i](m.handler) } } - -type innerBridge struct { - inner Handler - ctx context.Context -} - -func (b innerBridge) ServeHTTP(w http.ResponseWriter, r *http.Request) { - b.inner.ServeHTTPC(b.ctx, w, r) -} - -type outerBridge struct { - mware func(http.Handler) http.Handler - inner Handler -} - -func (b outerBridge) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) { - b.mware(innerBridge{b.inner, ctx}).ServeHTTP(w, r) -} diff --git a/_vendor/goji.io/middleware/middleware.go b/_vendor/goji.io/middleware/middleware.go deleted file mode 100644 index acfe948..0000000 --- a/_vendor/goji.io/middleware/middleware.go +++ /dev/null @@ -1,79 +0,0 @@ -/* -Package middleware contains utilities for Goji Middleware authors. - -Unless you are writing middleware for your application, you should avoid -importing this package. Instead, use the abstractions provided by your -middleware package. -*/ -package middleware - -import ( - "net/http" - - "goji.io" - "goji.io/internal" - "golang.org/x/net/context" -) - -/* -Pattern returns the most recently matched Pattern, or nil if no pattern was -matched. -*/ -func Pattern(ctx context.Context) goji.Pattern { - p := ctx.Value(internal.Pattern) - if p == nil { - return nil - } - return p.(goji.Pattern) -} - -/* -SetPattern returns a new context in which the given Pattern is used as the most -recently matched pattern. -*/ -func SetPattern(ctx context.Context, p goji.Pattern) context.Context { - return context.WithValue(ctx, internal.Pattern, p) -} - -/* -Handler returns the handler corresponding to the most recently matched Pattern, -or nil if no pattern was matched. - -Internally, Goji converts net/http.Handlers into goji.Handlers using a wrapper -object. Users who wish to retrieve the original http.Handler they passed to Goji -may call UnwrapHandler. - -The handler returned by this function is the one that will be dispatched to at -the end of the middleware stack. If the returned Handler is nil, http.NotFound -will be used instead. -*/ -func Handler(ctx context.Context) goji.Handler { - h := ctx.Value(internal.Handler) - if h == nil { - return nil - } - return h.(goji.Handler) -} - -/* -SetHandler returns a new context in which the given Handler was most recently -matched and which consequently will be dispatched to. -*/ -func SetHandler(ctx context.Context, h goji.Handler) context.Context { - return context.WithValue(ctx, internal.Handler, h) -} - -/* -UnwrapHandler extracts the original http.Handler from a Goji-wrapped Handler -object, or returns nil if the given Handler has not been wrapped in this way. - -This function is necessary because Goji uses goji.Handler as its native data -type internally, and uses a wrapper struct to convert all http.Handlers it is -passed into goji.Handlers. -*/ -func UnwrapHandler(h goji.Handler) http.Handler { - if cw, ok := h.(internal.ContextWrapper); ok { - return cw.Handler - } - return nil -} diff --git a/_vendor/goji.io/mux.go b/_vendor/goji.io/mux.go index b251602..9ecf75a 100644 --- a/_vendor/goji.io/mux.go +++ b/_vendor/goji.io/mux.go @@ -1,29 +1,28 @@ package goji import ( + "context" "net/http" "goji.io/internal" - - "golang.org/x/net/context" ) /* Mux is a HTTP multiplexer / router similar to net/http.ServeMux. -Muxes multiplex traffic between many Handlers by selecting the first applicable -Pattern. They then call a common middleware stack, finally passing control to -the selected Handler. See the documentation on the Handle function for more -information about how routing is performed, the documentation on the Pattern -type for more information about request matching, and the documentation for the -Use method for more about middleware. +Muxes multiplex traffic between many http.Handlers by selecting the first +applicable Pattern. They then call a common middleware stack, finally passing +control to the selected http.Handler. See the documentation on the Handle +function for more information about how routing is performed, the documentation +on the Pattern type for more information about request matching, and the +documentation for the Use method for more about middleware. Muxes cannot be configured concurrently from multiple goroutines, nor can they be configured concurrently with requests. */ type Mux struct { - handler Handler - middleware []func(Handler) Handler + handler http.Handler + middleware []func(http.Handler) http.Handler router router root bool } @@ -40,7 +39,7 @@ func NewMux() *Mux { /* SubMux returns a new Mux with no configured middleware or routes, and which inherits routing information from the passed context. This is especially useful -when using one Mux as a Handler registered to another "parent" Mux. +when using one Mux as a http.Handler registered to another "parent" Mux. For example, a common pattern is to organize applications in a way that mirrors the structure of its URLs: a photo-sharing site might have URLs that start with @@ -49,14 +48,14 @@ three Muxes: root := NewMux() users := SubMux() - root.HandleC(pat.New("/users/*", users) + root.Handle(pat.New("/users/*"), users) albums := SubMux() - root.HandleC(pat.New("/albums/*", albums) + root.Handle(pat.New("/albums/*"), albums) // e.g., GET /users/carl - users.HandleC(pat.Get("/:name"), renderProfile) + users.Handle(pat.Get("/:name"), renderProfile) // e.g., POST /albums/ - albums.HandleC(pat.Post("/"), newAlbum) + albums.Handle(pat.Post("/"), newAlbum) */ func SubMux() *Mux { m := &Mux{} @@ -64,29 +63,15 @@ func SubMux() *Mux { return m } -/* -ServeHTTP implements net/http.Handler. It uses context.TODO as the root context -in order to ease the conversion of non-context-aware Handlers to context-aware -ones using static analysis. - -Users who know that their mux sits at the top of the request hierarchy should -consider creating a small helper http.Handler that calls this Mux's ServeHTTPC -function with context.Background. -*/ +// ServeHTTP implements net/http.Handler. func (m *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) { - m.ServeHTTPC(context.TODO(), w, r) -} - -/* -ServeHTTPC implements Handler. -*/ -func (m *Mux) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) { if m.root { + ctx := r.Context() ctx = context.WithValue(ctx, internal.Path, r.URL.EscapedPath()) + r = r.WithContext(ctx) } - ctx = m.router.route(ctx, r) - m.handler.ServeHTTPC(ctx, w, r) + r = m.router.route(r) + m.handler.ServeHTTP(w, r) } var _ http.Handler = &Mux{} -var _ Handler = &Mux{} diff --git a/_vendor/goji.io/pat/match.go b/_vendor/goji.io/pat/match.go index b6321a4..fea04a4 100644 --- a/_vendor/goji.io/pat/match.go +++ b/_vendor/goji.io/pat/match.go @@ -1,11 +1,11 @@ package pat import ( + "context" "sort" "goji.io/internal" "goji.io/pattern" - "golang.org/x/net/context" ) type match struct { diff --git a/_vendor/goji.io/pat/pat.go b/_vendor/goji.io/pat/pat.go index 9d2259d..1d4d34d 100644 --- a/_vendor/goji.io/pat/pat.go +++ b/_vendor/goji.io/pat/pat.go @@ -87,7 +87,6 @@ import ( "strings" "goji.io/pattern" - "golang.org/x/net/context" ) type patNames []struct { @@ -184,12 +183,12 @@ func newWithMethods(pat string, methods ...string) *Pattern { } /* -Match runs the Pat pattern on the given request, returning a non-nil context if -the request matches the request. +Match runs the Pat pattern on the given request, returning a non-nil output +request if the input request matches the pattern. This function satisfies goji.Pattern. */ -func (p *Pattern) Match(ctx context.Context, r *http.Request) context.Context { +func (p *Pattern) Match(r *http.Request) *http.Request { if p.methods != nil { if _, ok := p.methods[r.Method]; !ok { return nil @@ -197,6 +196,7 @@ func (p *Pattern) Match(ctx context.Context, r *http.Request) context.Context { } // Check Path + ctx := r.Context() path := pattern.Path(ctx) var scratch []string if p.wildcard { @@ -251,7 +251,7 @@ func (p *Pattern) Match(ctx context.Context, r *http.Request) context.Context { } } - return &match{ctx, p, scratch} + return r.WithContext(&match{ctx, p, scratch}) } /* @@ -292,11 +292,11 @@ and the URL Path: /user/carl -a call to Param(ctx, "name") would return the string "carl". It is the caller's +a call to Param(r, "name") would return the string "carl". It is the caller's responsibility to ensure that the variable has been bound. Attempts to access variables that have not been set (or which have been invalidly set) are considered programmer errors and will trigger a panic. */ -func Param(ctx context.Context, name string) string { - return ctx.Value(pattern.Variable(name)).(string) +func Param(r *http.Request, name string) string { + return r.Context().Value(pattern.Variable(name)).(string) } diff --git a/_vendor/goji.io/pattern/pattern.go b/_vendor/goji.io/pattern/pattern.go index 6f5a99c..19ad0ef 100644 --- a/_vendor/goji.io/pattern/pattern.go +++ b/_vendor/goji.io/pattern/pattern.go @@ -13,8 +13,9 @@ to standardize on a few common interfaces may find this package useful. package pattern import ( + "context" + "goji.io/internal" - "golang.org/x/net/context" ) /* diff --git a/_vendor/goji.io/router.go b/_vendor/goji.io/router.go index 99a6fcd..d5e10e0 100644 --- a/_vendor/goji.io/router.go +++ b/_vendor/goji.io/router.go @@ -1,14 +1,16 @@ package goji import ( + "context" + "net/http" + "goji.io/internal" - "golang.org/x/net/context" ) type match struct { context.Context p Pattern - h Handler + h http.Handler } func (m match) Value(key interface{}) interface{} { diff --git a/_vendor/goji.io/router_simple.go b/_vendor/goji.io/router_simple.go index 719779a..e0be395 100644 --- a/_vendor/goji.io/router_simple.go +++ b/_vendor/goji.io/router_simple.go @@ -2,11 +2,7 @@ package goji -import ( - "net/http" - - "golang.org/x/net/context" -) +import "net/http" /* This is the simplest correct router implementation for Goji. @@ -16,18 +12,22 @@ type router []route type route struct { Pattern - Handler + http.Handler } -func (rt *router) add(p Pattern, h Handler) { +func (rt *router) add(p Pattern, h http.Handler) { *rt = append(*rt, route{p, h}) } -func (rt *router) route(ctx context.Context, r *http.Request) context.Context { +func (rt *router) route(r *http.Request) *http.Request { for _, route := range *rt { - if ctx := route.Match(ctx, r); ctx != nil { - return &match{ctx, route.Pattern, route.Handler} + if r2 := route.Match(r); r2 != nil { + return r2.WithContext(&match{ + Context: r2.Context(), + p: route.Pattern, + h: route.Handler, + }) } } - return &match{Context: ctx} + return r.WithContext(&match{Context: r.Context()}) } diff --git a/_vendor/goji.io/router_trie.go b/_vendor/goji.io/router_trie.go index db3b93e..ec9f28d 100644 --- a/_vendor/goji.io/router_trie.go +++ b/_vendor/goji.io/router_trie.go @@ -8,7 +8,6 @@ import ( "strings" "goji.io/internal" - "golang.org/x/net/context" ) type router struct { @@ -19,7 +18,7 @@ type router struct { type route struct { Pattern - Handler + http.Handler } type child struct { @@ -32,7 +31,7 @@ type trieNode struct { children []child } -func (rt *router) add(p Pattern, h Handler) { +func (rt *router) add(p Pattern, h http.Handler) { i := len(rt.routes) rt.routes = append(rt.routes, route{p, h}) @@ -64,21 +63,17 @@ func (rt *router) add(p Pattern, h Handler) { } } -func (rt *router) route(ctx context.Context, r *http.Request) context.Context { +func (rt *router) route(r *http.Request) *http.Request { tn := &rt.wildcard if tn2, ok := rt.methods[r.Method]; ok { tn = tn2 } + ctx := r.Context() path := ctx.Value(internal.Path).(string) - - var routes []int - for { - routes = append(routes, tn.routes...) - + for path != "" { i := sort.Search(len(tn.children), func(i int) bool { - p := tn.children[i].prefix - return path < p || strings.HasPrefix(path, p) + return path[0] <= tn.children[i].prefix[0] }) if i == len(tn.children) || !strings.HasPrefix(path, tn.children[i].prefix) { break @@ -87,13 +82,16 @@ func (rt *router) route(ctx context.Context, r *http.Request) context.Context { path = path[len(tn.children[i].prefix):] tn = tn.children[i].node } - sort.Ints(routes) - for _, i := range routes { - if ctx := rt.routes[i].Match(ctx, r); ctx != nil { - return &match{ctx, rt.routes[i].Pattern, rt.routes[i].Handler} + for _, i := range tn.routes { + if r2 := rt.routes[i].Match(r); r2 != nil { + return r2.WithContext(&match{ + Context: r2.Context(), + p: rt.routes[i].Pattern, + h: rt.routes[i].Handler, + }) } } - return &match{Context: ctx} + return r.WithContext(&match{Context: ctx}) } // We can be a teensy bit more efficient here: we're maintaining a sorted list, @@ -128,6 +126,9 @@ func longestPrefix(a, b string) string { func (tn *trieNode) add(prefix string, idx int) { if len(prefix) == 0 { tn.routes = append(tn.routes, idx) + for i := range tn.children { + tn.children[i].node.add(prefix, idx) + } return } @@ -136,11 +137,13 @@ func (tn *trieNode) add(prefix string, idx int) { return ch <= tn.children[i].prefix[0] }) - for ; i < len(tn.children); i++ { - if tn.children[i].prefix[0] > ch { - break - } - + if i == len(tn.children) || ch != tn.children[i].prefix[0] { + routes := append([]int(nil), tn.routes...) + tn.children = append(tn.children, child{ + prefix: prefix, + node: &trieNode{routes: append(routes, idx)}, + }) + } else { lp := longestPrefix(prefix, tn.children[i].prefix) if tn.children[i].prefix == lp { @@ -152,18 +155,13 @@ func (tn *trieNode) add(prefix string, idx int) { split.children = []child{ {tn.children[i].prefix[len(lp):], tn.children[i].node}, } + split.routes = append([]int(nil), tn.routes...) split.add(prefix[len(lp):], idx) tn.children[i].prefix = lp tn.children[i].node = split - sort.Sort(byPrefix(tn.children)) - return } - tn.children = append(tn.children, child{ - prefix: prefix, - node: &trieNode{routes: []int{idx}}, - }) sort.Sort(byPrefix(tn.children)) } diff --git a/_vendor/golang.org/x/net/context/context.go b/_vendor/golang.org/x/net/context/context.go deleted file mode 100644 index 11bd8d3..0000000 --- a/_vendor/golang.org/x/net/context/context.go +++ /dev/null @@ -1,447 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package context defines the Context type, which carries deadlines, -// cancelation signals, and other request-scoped values across API boundaries -// and between processes. -// -// Incoming requests to a server should create a Context, and outgoing calls to -// servers should accept a Context. The chain of function calls between must -// propagate the Context, optionally replacing it with a modified copy created -// using WithDeadline, WithTimeout, WithCancel, or WithValue. -// -// Programs that use Contexts should follow these rules to keep interfaces -// consistent across packages and enable static analysis tools to check context -// propagation: -// -// Do not store Contexts inside a struct type; instead, pass a Context -// explicitly to each function that needs it. The Context should be the first -// parameter, typically named ctx: -// -// func DoSomething(ctx context.Context, arg Arg) error { -// // ... use ctx ... -// } -// -// Do not pass a nil Context, even if a function permits it. Pass context.TODO -// if you are unsure about which Context to use. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -// -// The same Context may be passed to functions running in different goroutines; -// Contexts are safe for simultaneous use by multiple goroutines. -// -// See http://blog.golang.org/context for example code for a server that uses -// Contexts. -package context - -import ( - "errors" - "fmt" - "sync" - "time" -) - -// A Context carries a deadline, a cancelation signal, and other values across -// API boundaries. -// -// Context's methods may be called by multiple goroutines simultaneously. -type Context interface { - // Deadline returns the time when work done on behalf of this context - // should be canceled. Deadline returns ok==false when no deadline is - // set. Successive calls to Deadline return the same results. - Deadline() (deadline time.Time, ok bool) - - // Done returns a channel that's closed when work done on behalf of this - // context should be canceled. Done may return nil if this context can - // never be canceled. Successive calls to Done return the same value. - // - // WithCancel arranges for Done to be closed when cancel is called; - // WithDeadline arranges for Done to be closed when the deadline - // expires; WithTimeout arranges for Done to be closed when the timeout - // elapses. - // - // Done is provided for use in select statements: - // - // // Stream generates values with DoSomething and sends them to out - // // until DoSomething returns an error or ctx.Done is closed. - // func Stream(ctx context.Context, out <-chan Value) error { - // for { - // v, err := DoSomething(ctx) - // if err != nil { - // return err - // } - // select { - // case <-ctx.Done(): - // return ctx.Err() - // case out <- v: - // } - // } - // } - // - // See http://blog.golang.org/pipelines for more examples of how to use - // a Done channel for cancelation. - Done() <-chan struct{} - - // Err returns a non-nil error value after Done is closed. Err returns - // Canceled if the context was canceled or DeadlineExceeded if the - // context's deadline passed. No other values for Err are defined. - // After Done is closed, successive calls to Err return the same value. - Err() error - - // Value returns the value associated with this context for key, or nil - // if no value is associated with key. Successive calls to Value with - // the same key returns the same result. - // - // Use context values only for request-scoped data that transits - // processes and API boundaries, not for passing optional parameters to - // functions. - // - // A key identifies a specific value in a Context. Functions that wish - // to store values in Context typically allocate a key in a global - // variable then use that key as the argument to context.WithValue and - // Context.Value. A key can be any type that supports equality; - // packages should define keys as an unexported type to avoid - // collisions. - // - // Packages that define a Context key should provide type-safe accessors - // for the values stores using that key: - // - // // Package user defines a User type that's stored in Contexts. - // package user - // - // import "golang.org/x/net/context" - // - // // User is the type of value stored in the Contexts. - // type User struct {...} - // - // // key is an unexported type for keys defined in this package. - // // This prevents collisions with keys defined in other packages. - // type key int - // - // // userKey is the key for user.User values in Contexts. It is - // // unexported; clients use user.NewContext and user.FromContext - // // instead of using this key directly. - // var userKey key = 0 - // - // // NewContext returns a new Context that carries value u. - // func NewContext(ctx context.Context, u *User) context.Context { - // return context.WithValue(ctx, userKey, u) - // } - // - // // FromContext returns the User value stored in ctx, if any. - // func FromContext(ctx context.Context) (*User, bool) { - // u, ok := ctx.Value(userKey).(*User) - // return u, ok - // } - Value(key interface{}) interface{} -} - -// Canceled is the error returned by Context.Err when the context is canceled. -var Canceled = errors.New("context canceled") - -// DeadlineExceeded is the error returned by Context.Err when the context's -// deadline passes. -var DeadlineExceeded = errors.New("context deadline exceeded") - -// An emptyCtx is never canceled, has no values, and has no deadline. It is not -// struct{}, since vars of this type must have distinct addresses. -type emptyCtx int - -func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { - return -} - -func (*emptyCtx) Done() <-chan struct{} { - return nil -} - -func (*emptyCtx) Err() error { - return nil -} - -func (*emptyCtx) Value(key interface{}) interface{} { - return nil -} - -func (e *emptyCtx) String() string { - switch e { - case background: - return "context.Background" - case todo: - return "context.TODO" - } - return "unknown empty Context" -} - -var ( - background = new(emptyCtx) - todo = new(emptyCtx) -) - -// Background returns a non-nil, empty Context. It is never canceled, has no -// values, and has no deadline. It is typically used by the main function, -// initialization, and tests, and as the top-level Context for incoming -// requests. -func Background() Context { - return background -} - -// TODO returns a non-nil, empty Context. Code should use context.TODO when -// it's unclear which Context to use or it is not yet available (because the -// surrounding function has not yet been extended to accept a Context -// parameter). TODO is recognized by static analysis tools that determine -// whether Contexts are propagated correctly in a program. -func TODO() Context { - return todo -} - -// A CancelFunc tells an operation to abandon its work. -// A CancelFunc does not wait for the work to stop. -// After the first call, subsequent calls to a CancelFunc do nothing. -type CancelFunc func() - -// WithCancel returns a copy of parent with a new Done channel. The returned -// context's Done channel is closed when the returned cancel function is called -// or when the parent context's Done channel is closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { - c := newCancelCtx(parent) - propagateCancel(parent, &c) - return &c, func() { c.cancel(true, Canceled) } -} - -// newCancelCtx returns an initialized cancelCtx. -func newCancelCtx(parent Context) cancelCtx { - return cancelCtx{ - Context: parent, - done: make(chan struct{}), - } -} - -// propagateCancel arranges for child to be canceled when parent is. -func propagateCancel(parent Context, child canceler) { - if parent.Done() == nil { - return // parent is never canceled - } - if p, ok := parentCancelCtx(parent); ok { - p.mu.Lock() - if p.err != nil { - // parent has already been canceled - child.cancel(false, p.err) - } else { - if p.children == nil { - p.children = make(map[canceler]bool) - } - p.children[child] = true - } - p.mu.Unlock() - } else { - go func() { - select { - case <-parent.Done(): - child.cancel(false, parent.Err()) - case <-child.Done(): - } - }() - } -} - -// parentCancelCtx follows a chain of parent references until it finds a -// *cancelCtx. This function understands how each of the concrete types in this -// package represents its parent. -func parentCancelCtx(parent Context) (*cancelCtx, bool) { - for { - switch c := parent.(type) { - case *cancelCtx: - return c, true - case *timerCtx: - return &c.cancelCtx, true - case *valueCtx: - parent = c.Context - default: - return nil, false - } - } -} - -// removeChild removes a context from its parent. -func removeChild(parent Context, child canceler) { - p, ok := parentCancelCtx(parent) - if !ok { - return - } - p.mu.Lock() - if p.children != nil { - delete(p.children, child) - } - p.mu.Unlock() -} - -// A canceler is a context type that can be canceled directly. The -// implementations are *cancelCtx and *timerCtx. -type canceler interface { - cancel(removeFromParent bool, err error) - Done() <-chan struct{} -} - -// A cancelCtx can be canceled. When canceled, it also cancels any children -// that implement canceler. -type cancelCtx struct { - Context - - done chan struct{} // closed by the first cancel call. - - mu sync.Mutex - children map[canceler]bool // set to nil by the first cancel call - err error // set to non-nil by the first cancel call -} - -func (c *cancelCtx) Done() <-chan struct{} { - return c.done -} - -func (c *cancelCtx) Err() error { - c.mu.Lock() - defer c.mu.Unlock() - return c.err -} - -func (c *cancelCtx) String() string { - return fmt.Sprintf("%v.WithCancel", c.Context) -} - -// cancel closes c.done, cancels each of c's children, and, if -// removeFromParent is true, removes c from its parent's children. -func (c *cancelCtx) cancel(removeFromParent bool, err error) { - if err == nil { - panic("context: internal error: missing cancel error") - } - c.mu.Lock() - if c.err != nil { - c.mu.Unlock() - return // already canceled - } - c.err = err - close(c.done) - for child := range c.children { - // NOTE: acquiring the child's lock while holding parent's lock. - child.cancel(false, err) - } - c.children = nil - c.mu.Unlock() - - if removeFromParent { - removeChild(c.Context, c) - } -} - -// WithDeadline returns a copy of the parent context with the deadline adjusted -// to be no later than d. If the parent's deadline is already earlier than d, -// WithDeadline(parent, d) is semantically equivalent to parent. The returned -// context's Done channel is closed when the deadline expires, when the returned -// cancel function is called, or when the parent context's Done channel is -// closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { - if cur, ok := parent.Deadline(); ok && cur.Before(deadline) { - // The current deadline is already sooner than the new one. - return WithCancel(parent) - } - c := &timerCtx{ - cancelCtx: newCancelCtx(parent), - deadline: deadline, - } - propagateCancel(parent, c) - d := deadline.Sub(time.Now()) - if d <= 0 { - c.cancel(true, DeadlineExceeded) // deadline has already passed - return c, func() { c.cancel(true, Canceled) } - } - c.mu.Lock() - defer c.mu.Unlock() - if c.err == nil { - c.timer = time.AfterFunc(d, func() { - c.cancel(true, DeadlineExceeded) - }) - } - return c, func() { c.cancel(true, Canceled) } -} - -// A timerCtx carries a timer and a deadline. It embeds a cancelCtx to -// implement Done and Err. It implements cancel by stopping its timer then -// delegating to cancelCtx.cancel. -type timerCtx struct { - cancelCtx - timer *time.Timer // Under cancelCtx.mu. - - deadline time.Time -} - -func (c *timerCtx) Deadline() (deadline time.Time, ok bool) { - return c.deadline, true -} - -func (c *timerCtx) String() string { - return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now())) -} - -func (c *timerCtx) cancel(removeFromParent bool, err error) { - c.cancelCtx.cancel(false, err) - if removeFromParent { - // Remove this timerCtx from its parent cancelCtx's children. - removeChild(c.cancelCtx.Context, c) - } - c.mu.Lock() - if c.timer != nil { - c.timer.Stop() - c.timer = nil - } - c.mu.Unlock() -} - -// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete: -// -// func slowOperationWithTimeout(ctx context.Context) (Result, error) { -// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) -// defer cancel() // releases resources if slowOperation completes before timeout elapses -// return slowOperation(ctx) -// } -func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { - return WithDeadline(parent, time.Now().Add(timeout)) -} - -// WithValue returns a copy of parent in which the value associated with key is -// val. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -func WithValue(parent Context, key interface{}, val interface{}) Context { - return &valueCtx{parent, key, val} -} - -// A valueCtx carries a key-value pair. It implements Value for that key and -// delegates all other calls to the embedded Context. -type valueCtx struct { - Context - key, val interface{} -} - -func (c *valueCtx) String() string { - return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val) -} - -func (c *valueCtx) Value(key interface{}) interface{} { - if c.key == key { - return c.val - } - return c.Context.Value(key) -} diff --git a/_vendor/golang.org/x/net/context/ctxhttp/cancelreq.go b/_vendor/golang.org/x/net/context/ctxhttp/cancelreq.go deleted file mode 100644 index 48610e3..0000000 --- a/_vendor/golang.org/x/net/context/ctxhttp/cancelreq.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.5 - -package ctxhttp - -import "net/http" - -func canceler(client *http.Client, req *http.Request) func() { - ch := make(chan struct{}) - req.Cancel = ch - - return func() { - close(ch) - } -} diff --git a/_vendor/golang.org/x/net/context/ctxhttp/cancelreq_go14.go b/_vendor/golang.org/x/net/context/ctxhttp/cancelreq_go14.go deleted file mode 100644 index 56bcbad..0000000 --- a/_vendor/golang.org/x/net/context/ctxhttp/cancelreq_go14.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.5 - -package ctxhttp - -import "net/http" - -type requestCanceler interface { - CancelRequest(*http.Request) -} - -func canceler(client *http.Client, req *http.Request) func() { - rc, ok := client.Transport.(requestCanceler) - if !ok { - return func() {} - } - return func() { - rc.CancelRequest(req) - } -} diff --git a/_vendor/golang.org/x/net/context/ctxhttp/ctxhttp.go b/_vendor/golang.org/x/net/context/ctxhttp/ctxhttp.go deleted file mode 100644 index 9f34888..0000000 --- a/_vendor/golang.org/x/net/context/ctxhttp/ctxhttp.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package ctxhttp provides helper functions for performing context-aware HTTP requests. -package ctxhttp - -import ( - "io" - "net/http" - "net/url" - "strings" - - "golang.org/x/net/context" -) - -// Do sends an HTTP request with the provided http.Client and returns an HTTP response. -// If the client is nil, http.DefaultClient is used. -// If the context is canceled or times out, ctx.Err() will be returned. -func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { - if client == nil { - client = http.DefaultClient - } - - // Request cancelation changed in Go 1.5, see cancelreq.go and cancelreq_go14.go. - cancel := canceler(client, req) - - type responseAndError struct { - resp *http.Response - err error - } - result := make(chan responseAndError, 1) - - go func() { - resp, err := client.Do(req) - result <- responseAndError{resp, err} - }() - - select { - case <-ctx.Done(): - cancel() - return nil, ctx.Err() - case r := <-result: - return r.resp, r.err - } -} - -// Get issues a GET request via the Do function. -func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) { - req, err := http.NewRequest("GET", url, nil) - if err != nil { - return nil, err - } - return Do(ctx, client, req) -} - -// Head issues a HEAD request via the Do function. -func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) { - req, err := http.NewRequest("HEAD", url, nil) - if err != nil { - return nil, err - } - return Do(ctx, client, req) -} - -// Post issues a POST request via the Do function. -func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) { - req, err := http.NewRequest("POST", url, body) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", bodyType) - return Do(ctx, client, req) -} - -// PostForm issues a POST request via the Do function. -func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) { - return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) -} diff --git a/client/client_test.go b/client/client_test.go index cbe6d40..b220123 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -1,13 +1,12 @@ package jsc import ( + "context" "log" "net/http" "net/url" "testing" - "golang.org/x/net/context" - "github.com/derekdowling/go-json-spec-handler" "github.com/derekdowling/go-json-spec-handler/jsh-api" . "github.com/smartystreets/goconvey/convey" diff --git a/goji2-logger/logger.go b/goji2-logger/logger.go index d6956cf..799e6de 100644 --- a/goji2-logger/logger.go +++ b/goji2-logger/logger.go @@ -11,10 +11,6 @@ import ( "goji.io/pattern" - "goji.io" - - "golang.org/x/net/context" - "github.com/derekdowling/go-stdlogger" "github.com/zenazn/goji/web/mutil" ) @@ -59,15 +55,15 @@ func New(logger std.Logger, debug bool) *Logger { // Use like so with Goji2: // gLogger := gojilogger.New(nil, false) // yourGoji.UseC(gLogger.Middleware) -func (l *Logger) Middleware(next goji.Handler) goji.Handler { - middleware := func(ctx context.Context, w http.ResponseWriter, r *http.Request) { - l.printRequest(ctx, r) +func (l *Logger) Middleware(next http.Handler) http.Handler { + middleware := func(w http.ResponseWriter, r *http.Request) { + l.printRequest(r) // WrapWriter lets us peek at ResponseWriter outputs lw := mutil.WrapWriter(w) startTime := time.Now() - next.ServeHTTPC(ctx, lw, r) + next.ServeHTTP(lw, r) if lw.Status() == 0 { lw.WriteHeader(http.StatusOK) @@ -78,10 +74,10 @@ func (l *Logger) Middleware(next goji.Handler) goji.Handler { l.printResponse(lw, finishTime.Sub(startTime)) } - return goji.HandlerFunc(middleware) + return http.HandlerFunc(middleware) } -func (l *Logger) printRequest(ctx context.Context, r *http.Request) { +func (l *Logger) printRequest(r *http.Request) { var buf bytes.Buffer if l.Debug { @@ -91,7 +87,7 @@ func (l *Logger) printRequest(ctx context.Context, r *http.Request) { buf.WriteString("Serving route: ") // Goji routing details - colorWrite(&buf, bGreen, "%s", pattern.Path(ctx)) + colorWrite(&buf, bGreen, "%s", pattern.Path(r.Context())) // Server details buf.WriteString(fmt.Sprintf(" from %s ", r.RemoteAddr)) diff --git a/jsh-api/api.go b/jsh-api/api.go index 8559d3e..4c9d8bb 100644 --- a/jsh-api/api.go +++ b/jsh-api/api.go @@ -10,7 +10,7 @@ import ( "goji.io" "goji.io/pat" - "github.com/derekdowling/go-json-spec-handler/goji2-logger" + gojilogger "github.com/derekdowling/go-json-spec-handler/goji2-logger" "github.com/derekdowling/go-stdlogger" ) @@ -69,7 +69,7 @@ func Default(prefix string, debug bool, logger std.Logger) *API { // register logger middleware gojilogger := gojilogger.New(logger, debug) - api.UseC(gojilogger.Middleware) + api.Use(gojilogger.Middleware) return api } @@ -86,12 +86,12 @@ func (a *API) Add(resource *Resource) { // We need two separate routes, // /(prefix/)resources matcher := path.Join(a.prefix, resource.Type) - a.Mux.HandleC(pat.New(matcher), resource) + a.Mux.Handle(pat.New(matcher), resource) // And: // /(prefix/)resources/* idMatcher := path.Join(a.prefix, resource.Type, "*") - a.Mux.HandleC(pat.New(idMatcher), resource) + a.Mux.Handle(pat.New(idMatcher), resource) } // RouteTree prints out all accepted routes for the API that use jshapi implemented diff --git a/jsh-api/mock_storage.go b/jsh-api/mock_storage.go index 1d8a930..044c961 100644 --- a/jsh-api/mock_storage.go +++ b/jsh-api/mock_storage.go @@ -1,11 +1,11 @@ package jshapi import ( + "context" "log" "strconv" "github.com/derekdowling/go-json-spec-handler" - "golang.org/x/net/context" ) // MockStorage allows you to mock out APIs really easily, and is also used internally diff --git a/jsh-api/resource.go b/jsh-api/resource.go index b161e06..ea7bbe2 100644 --- a/jsh-api/resource.go +++ b/jsh-api/resource.go @@ -10,8 +10,6 @@ import ( "goji.io" "goji.io/pat" - "golang.org/x/net/context" - "github.com/derekdowling/go-json-spec-handler" "github.com/derekdowling/go-json-spec-handler/jsh-api/store" ) @@ -38,8 +36,8 @@ registering storage handlers via .Post(), .Get(), .List(), .Patch(), and .Delete Besides the built in registration helpers, it isn't recommended, but you can add your own routes using the goji.Mux API: - func searchHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) { - name := pat.Param(ctx, "name") + func searchHandler(w http.ResponseWriter, r *http.Request) { + name := pat.Param("name") fmt.Fprintf(w, "Hello, %s!", name) } @@ -104,10 +102,10 @@ func (res *Resource) CRUD(storage store.CRUD) { // Post registers a `POST /resource` handler with the resource func (res *Resource) Post(storage store.Save) { - res.HandleFuncC( + res.HandleFunc( pat.Post(patRoot), - func(ctx context.Context, w http.ResponseWriter, r *http.Request) { - res.postHandler(ctx, w, r, storage) + func(w http.ResponseWriter, r *http.Request) { + res.postHandler(w, r, storage) }, ) @@ -116,10 +114,10 @@ func (res *Resource) Post(storage store.Save) { // Get registers a `GET /resource/:id` handler for the resource func (res *Resource) Get(storage store.Get) { - res.HandleFuncC( + res.HandleFunc( pat.Get(patID), - func(ctx context.Context, w http.ResponseWriter, r *http.Request) { - res.getHandler(ctx, w, r, storage) + func(w http.ResponseWriter, r *http.Request) { + res.getHandler(w, r, storage) }, ) @@ -128,10 +126,10 @@ func (res *Resource) Get(storage store.Get) { // List registers a `GET /resource` handler for the resource func (res *Resource) List(storage store.List) { - res.HandleFuncC( + res.HandleFunc( pat.Get(patRoot), - func(ctx context.Context, w http.ResponseWriter, r *http.Request) { - res.listHandler(ctx, w, r, storage) + func(w http.ResponseWriter, r *http.Request) { + res.listHandler(w, r, storage) }, ) @@ -140,10 +138,10 @@ func (res *Resource) List(storage store.List) { // Delete registers a `DELETE /resource/:id` handler for the resource func (res *Resource) Delete(storage store.Delete) { - res.HandleFuncC( + res.HandleFunc( pat.Delete(patID), - func(ctx context.Context, w http.ResponseWriter, r *http.Request) { - res.deleteHandler(ctx, w, r, storage) + func(w http.ResponseWriter, r *http.Request) { + res.deleteHandler(w, r, storage) }, ) @@ -152,10 +150,10 @@ func (res *Resource) Delete(storage store.Delete) { // Patch registers a `PATCH /resource/:id` handler for the resource func (res *Resource) Patch(storage store.Update) { - res.HandleFuncC( + res.HandleFunc( pat.Patch(patID), - func(ctx context.Context, w http.ResponseWriter, r *http.Request) { - res.patchHandler(ctx, w, r, storage) + func(w http.ResponseWriter, r *http.Request) { + res.patchHandler(w, r, storage) }, ) @@ -177,8 +175,8 @@ func (res *Resource) ToOne( res.relationshipHandler( resourceType, - func(ctx context.Context, w http.ResponseWriter, r *http.Request) { - res.getHandler(ctx, w, r, storage) + func(w http.ResponseWriter, r *http.Request) { + res.getHandler(w, r, storage) }, ) @@ -201,8 +199,8 @@ func (res *Resource) ToMany( res.relationshipHandler( resourceType, - func(ctx context.Context, w http.ResponseWriter, r *http.Request) { - res.toManyHandler(ctx, w, r, storage) + func(w http.ResponseWriter, r *http.Request) { + res.toManyHandler(w, r, storage) }, ) @@ -213,12 +211,12 @@ func (res *Resource) ToMany( // relationship func (res *Resource) relationshipHandler( resourceType string, - handler goji.HandlerFunc, + handler http.HandlerFunc, ) { // handle /.../:id/ matcher := fmt.Sprintf("%s/%s", patID, resourceType) - res.HandleFuncC( + res.HandleFunc( pat.Get(matcher), handler, ) @@ -226,7 +224,7 @@ func (res *Resource) relationshipHandler( // handle /.../:id/relationships/ relationshipMatcher := fmt.Sprintf("%s/relationships/%s", patID, resourceType) - res.HandleFuncC( + res.HandleFunc( pat.Get(relationshipMatcher), handler, ) @@ -238,10 +236,10 @@ func (res *Resource) relationshipHandler( func (res *Resource) Action(actionName string, storage store.Get) { matcher := path.Join(patID, actionName) - res.HandleFuncC( + res.HandleFunc( pat.Get(matcher), - func(ctx context.Context, w http.ResponseWriter, r *http.Request) { - res.actionHandler(ctx, w, r, storage) + func(w http.ResponseWriter, r *http.Request) { + res.actionHandler(w, r, storage) }, ) @@ -249,53 +247,53 @@ func (res *Resource) Action(actionName string, storage store.Get) { } // POST /resources -func (res *Resource) postHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, storage store.Save) { +func (res *Resource) postHandler(w http.ResponseWriter, r *http.Request, storage store.Save) { parsedObject, parseErr := jsh.ParseObject(r) if parseErr != nil && reflect.ValueOf(parseErr).IsNil() == false { - SendHandler(ctx, w, r, parseErr) + SendHandler(w, r, parseErr) return } - object, err := storage(ctx, parsedObject) + object, err := storage(r.Context(), parsedObject) if err != nil && reflect.ValueOf(err).IsNil() == false { - SendHandler(ctx, w, r, err) + SendHandler(w, r, err) return } - SendHandler(ctx, w, r, object) + SendHandler(w, r, object) } // GET /resources/:id -func (res *Resource) getHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, storage store.Get) { - id := pat.Param(ctx, "id") +func (res *Resource) getHandler(w http.ResponseWriter, r *http.Request, storage store.Get) { + id := pat.Param(r, "id") - object, err := storage(ctx, id) + object, err := storage(r.Context(), id) if err != nil && reflect.ValueOf(err).IsNil() == false { - SendHandler(ctx, w, r, err) + SendHandler(w, r, err) return } - SendHandler(ctx, w, r, object) + SendHandler(w, r, object) } // GET /resources -func (res *Resource) listHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, storage store.List) { - list, err := storage(ctx) +func (res *Resource) listHandler(w http.ResponseWriter, r *http.Request, storage store.List) { + list, err := storage(r.Context()) if err != nil && reflect.ValueOf(err).IsNil() == false { - SendHandler(ctx, w, r, err) + SendHandler(w, r, err) return } - SendHandler(ctx, w, r, list) + SendHandler(w, r, list) } // DELETE /resources/:id -func (res *Resource) deleteHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, storage store.Delete) { - id := pat.Param(ctx, "id") +func (res *Resource) deleteHandler(w http.ResponseWriter, r *http.Request, storage store.Delete) { + id := pat.Param(r, "id") - err := storage(ctx, id) + err := storage(r.Context(), id) if err != nil && reflect.ValueOf(err).IsNil() == false { - SendHandler(ctx, w, r, err) + SendHandler(w, r, err) return } @@ -303,52 +301,52 @@ func (res *Resource) deleteHandler(ctx context.Context, w http.ResponseWriter, r } // PATCH /resources/:id -func (res *Resource) patchHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, storage store.Update) { +func (res *Resource) patchHandler(w http.ResponseWriter, r *http.Request, storage store.Update) { parsedObject, parseErr := jsh.ParseObject(r) if parseErr != nil && reflect.ValueOf(parseErr).IsNil() == false { - SendHandler(ctx, w, r, parseErr) + SendHandler(w, r, parseErr) return } - id := pat.Param(ctx, "id") + id := pat.Param(r, "id") if id != parsedObject.ID { - SendHandler(ctx, w, r, jsh.InputError("Request ID does not match URL's", "id")) + SendHandler(w, r, jsh.InputError("Request ID does not match URL's", "id")) return } - object, err := storage(ctx, parsedObject) + object, err := storage(r.Context(), parsedObject) if err != nil && reflect.ValueOf(err).IsNil() == false { - SendHandler(ctx, w, r, err) + SendHandler(w, r, err) return } - SendHandler(ctx, w, r, object) + SendHandler(w, r, object) } // GET /resources/:id/(relationships/)s -func (res *Resource) toManyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, storage store.ToMany) { - id := pat.Param(ctx, "id") +func (res *Resource) toManyHandler(w http.ResponseWriter, r *http.Request, storage store.ToMany) { + id := pat.Param(r, "id") - list, err := storage(ctx, id) + list, err := storage(r.Context(), id) if err != nil && reflect.ValueOf(err).IsNil() == false { - SendHandler(ctx, w, r, err) + SendHandler(w, r, err) return } - SendHandler(ctx, w, r, list) + SendHandler(w, r, list) } // All HTTP Methods for /resources/:id/ -func (res *Resource) actionHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, storage store.Get) { - id := pat.Param(ctx, "id") +func (res *Resource) actionHandler(w http.ResponseWriter, r *http.Request, storage store.Get) { + id := pat.Param(r, "id") - response, err := storage(ctx, id) + response, err := storage(r.Context(), id) if err != nil && reflect.ValueOf(err).IsNil() == false { - SendHandler(ctx, w, r, err) + SendHandler(w, r, err) return } - SendHandler(ctx, w, r, response) + SendHandler(w, r, response) } // addRoute adds the new method and route to a route Tree for debugging and diff --git a/jsh-api/resource_test.go b/jsh-api/resource_test.go index 6c47b55..9d4aba8 100644 --- a/jsh-api/resource_test.go +++ b/jsh-api/resource_test.go @@ -1,6 +1,7 @@ package jshapi import ( + "context" "log" "net/http" "net/http/httptest" @@ -10,7 +11,6 @@ import ( "github.com/derekdowling/go-json-spec-handler" "github.com/derekdowling/go-json-spec-handler/client" . "github.com/smartystreets/goconvey/convey" - "golang.org/x/net/context" ) func TestResource(t *testing.T) { diff --git a/jsh-api/sender.go b/jsh-api/sender.go index 3c1e743..f731099 100644 --- a/jsh-api/sender.go +++ b/jsh-api/sender.go @@ -5,21 +5,20 @@ import ( "github.com/derekdowling/go-json-spec-handler" "github.com/derekdowling/go-stdlogger" - "golang.org/x/net/context" ) /* Sender is a function type definition that allows consumers to customize how they send and log API responses. */ -type Sender func(context.Context, http.ResponseWriter, *http.Request, jsh.Sendable) +type Sender func(http.ResponseWriter, *http.Request, jsh.Sendable) /* DefaultSender is the default sender that will log 5XX errors that it encounters in the process of sending a response. */ func DefaultSender(logger std.Logger) Sender { - return func(ctx context.Context, w http.ResponseWriter, r *http.Request, sendable jsh.Sendable) { + return func(w http.ResponseWriter, r *http.Request, sendable jsh.Sendable) { sendableError, isType := sendable.(jsh.ErrorType) if isType && sendableError.StatusCode() >= 500 { logger.Printf("Returning ISE: %s\n", sendableError.Error()) diff --git a/jsh-api/store/store.go b/jsh-api/store/store.go index 5a6c8fb..29bad82 100644 --- a/jsh-api/store/store.go +++ b/jsh-api/store/store.go @@ -3,8 +3,9 @@ package store import ( + "context" + "github.com/derekdowling/go-json-spec-handler" - "golang.org/x/net/context" ) // CRUD implements all sub-storage functions