diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json deleted file mode 100644 index a4e2e52c..00000000 --- a/Godeps/Godeps.json +++ /dev/null @@ -1,290 +0,0 @@ -{ - "ImportPath": "github.com/cloudfoundry-incubator/notifications", - "GoVersion": "go1.9", - "GodepVersion": "v80", - "Packages": [ - "./..." - ], - "Deps": [ - { - "ImportPath": "bitbucket.org/chrj/smtpd", - "Comment": "null-24", - "Rev": "10bcb042194e344946fc7d9a6dad3cd87c05ec04" - }, - { - "ImportPath": "github.com/DATA-DOG/go-sqlmock", - "Comment": "v1.3.0-7-ga6b4b16", - "Rev": "a6b4b164c6d1a917f8ec028b795e2429fe048619" - }, - { - "ImportPath": "github.com/PuerkitoBio/goquery", - "Comment": "v0.3.2-72-g269246d", - "Rev": "269246d9e7d42d74e1cf929336d128d2ef53e7a5" - }, - { - "ImportPath": "github.com/andybalholm/cascadia", - "Rev": "54abbbf07a45a3ef346ebe903e0715d9a3c19352" - }, - { - "ImportPath": "github.com/dgrijalva/jwt-go", - "Comment": "v2.2.0-2-g47b263f", - "Rev": "47b263f020574c14765ecc3ea88f0e9447046632" - }, - { - "ImportPath": "github.com/go-sql-driver/mysql", - "Comment": "v1.2", - "Rev": "a732e14c62dde3285440047bba97581bc472ae18" - }, - { - "ImportPath": "github.com/gorilla/context", - "Rev": "1be7a086a5fd6440ef16fe96baeda0c78282b980" - }, - { - "ImportPath": "github.com/gorilla/mux", - "Rev": "9ede152210fa25c1377d33e867cb828c19316445" - }, - { - "ImportPath": "github.com/onsi/ginkgo", - "Comment": "v1.1.0-32-g291f28e", - "Rev": "291f28e66dd277f35d3635990a7448759645c7e7" - }, - { - "ImportPath": "github.com/onsi/ginkgo/config", - "Comment": "v1.1.0-32-g291f28e", - "Rev": "291f28e66dd277f35d3635990a7448759645c7e7" - }, - { - "ImportPath": "github.com/onsi/ginkgo/internal/codelocation", - "Comment": "v1.1.0-32-g291f28e", - "Rev": "291f28e66dd277f35d3635990a7448759645c7e7" - }, - { - "ImportPath": "github.com/onsi/ginkgo/internal/containernode", - "Comment": "v1.1.0-32-g291f28e", - "Rev": "291f28e66dd277f35d3635990a7448759645c7e7" - }, - { - "ImportPath": "github.com/onsi/ginkgo/internal/failer", - "Comment": "v1.1.0-32-g291f28e", - "Rev": "291f28e66dd277f35d3635990a7448759645c7e7" - }, - { - "ImportPath": "github.com/onsi/ginkgo/internal/leafnodes", - "Comment": "v1.1.0-32-g291f28e", - "Rev": "291f28e66dd277f35d3635990a7448759645c7e7" - }, - { - "ImportPath": "github.com/onsi/ginkgo/internal/remote", - "Comment": "v1.1.0-32-g291f28e", - "Rev": "291f28e66dd277f35d3635990a7448759645c7e7" - }, - { - "ImportPath": "github.com/onsi/ginkgo/internal/spec", - "Comment": "v1.1.0-32-g291f28e", - "Rev": "291f28e66dd277f35d3635990a7448759645c7e7" - }, - { - "ImportPath": "github.com/onsi/ginkgo/internal/specrunner", - "Comment": "v1.1.0-32-g291f28e", - "Rev": "291f28e66dd277f35d3635990a7448759645c7e7" - }, - { - "ImportPath": "github.com/onsi/ginkgo/internal/suite", - "Comment": "v1.1.0-32-g291f28e", - "Rev": "291f28e66dd277f35d3635990a7448759645c7e7" - }, - { - "ImportPath": "github.com/onsi/ginkgo/internal/testingtproxy", - "Comment": "v1.1.0-32-g291f28e", - "Rev": "291f28e66dd277f35d3635990a7448759645c7e7" - }, - { - "ImportPath": "github.com/onsi/ginkgo/internal/writer", - "Comment": "v1.1.0-32-g291f28e", - "Rev": "291f28e66dd277f35d3635990a7448759645c7e7" - }, - { - "ImportPath": "github.com/onsi/ginkgo/reporters", - "Comment": "v1.1.0-32-g291f28e", - "Rev": "291f28e66dd277f35d3635990a7448759645c7e7" - }, - { - "ImportPath": "github.com/onsi/ginkgo/reporters/stenographer", - "Comment": "v1.1.0-32-g291f28e", - "Rev": "291f28e66dd277f35d3635990a7448759645c7e7" - }, - { - "ImportPath": "github.com/onsi/ginkgo/types", - "Comment": "v1.1.0-32-g291f28e", - "Rev": "291f28e66dd277f35d3635990a7448759645c7e7" - }, - { - "ImportPath": "github.com/onsi/gomega", - "Comment": "v1.0-50-gd6c945f", - "Rev": "d6c945f9fdbf6cad99e85b0feff591caa268e0db" - }, - { - "ImportPath": "github.com/onsi/gomega/format", - "Comment": "v1.0-50-gd6c945f", - "Rev": "d6c945f9fdbf6cad99e85b0feff591caa268e0db" - }, - { - "ImportPath": "github.com/onsi/gomega/internal/assertion", - "Comment": "v1.0-50-gd6c945f", - "Rev": "d6c945f9fdbf6cad99e85b0feff591caa268e0db" - }, - { - "ImportPath": "github.com/onsi/gomega/internal/asyncassertion", - "Comment": "v1.0-50-gd6c945f", - "Rev": "d6c945f9fdbf6cad99e85b0feff591caa268e0db" - }, - { - "ImportPath": "github.com/onsi/gomega/internal/testingtsupport", - "Comment": "v1.0-50-gd6c945f", - "Rev": "d6c945f9fdbf6cad99e85b0feff591caa268e0db" - }, - { - "ImportPath": "github.com/onsi/gomega/matchers", - "Comment": "v1.0-50-gd6c945f", - "Rev": "d6c945f9fdbf6cad99e85b0feff591caa268e0db" - }, - { - "ImportPath": "github.com/onsi/gomega/matchers/support/goraph/bipartitegraph", - "Comment": "v1.0-50-gd6c945f", - "Rev": "d6c945f9fdbf6cad99e85b0feff591caa268e0db" - }, - { - "ImportPath": "github.com/onsi/gomega/matchers/support/goraph/edge", - "Comment": "v1.0-50-gd6c945f", - "Rev": "d6c945f9fdbf6cad99e85b0feff591caa268e0db" - }, - { - "ImportPath": "github.com/onsi/gomega/matchers/support/goraph/node", - "Comment": "v1.0-50-gd6c945f", - "Rev": "d6c945f9fdbf6cad99e85b0feff591caa268e0db" - }, - { - "ImportPath": "github.com/onsi/gomega/matchers/support/goraph/util", - "Comment": "v1.0-50-gd6c945f", - "Rev": "d6c945f9fdbf6cad99e85b0feff591caa268e0db" - }, - { - "ImportPath": "github.com/onsi/gomega/types", - "Comment": "v1.0-50-gd6c945f", - "Rev": "d6c945f9fdbf6cad99e85b0feff591caa268e0db" - }, - { - "ImportPath": "github.com/pivotal-cf-experimental/rainmaker", - "Rev": "d533d01b7c52e51433fe565276ca570c2a0753fc" - }, - { - "ImportPath": "github.com/pivotal-cf-experimental/rainmaker/internal/documents", - "Rev": "d533d01b7c52e51433fe565276ca570c2a0753fc" - }, - { - "ImportPath": "github.com/pivotal-cf-experimental/rainmaker/internal/network", - "Rev": "d533d01b7c52e51433fe565276ca570c2a0753fc" - }, - { - "ImportPath": "github.com/pivotal-cf-experimental/warrant", - "Rev": "e3c3c7f4dbd0e97d4459ed67375f9b420fb4c4e9" - }, - { - "ImportPath": "github.com/pivotal-cf-experimental/warrant/internal/documents", - "Rev": "e3c3c7f4dbd0e97d4459ed67375f9b420fb4c4e9" - }, - { - "ImportPath": "github.com/pivotal-cf-experimental/warrant/internal/network", - "Rev": "e3c3c7f4dbd0e97d4459ed67375f9b420fb4c4e9" - }, - { - "ImportPath": "github.com/pivotal-cf-experimental/warrant/internal/server/clients", - "Rev": "e3c3c7f4dbd0e97d4459ed67375f9b420fb4c4e9" - }, - { - "ImportPath": "github.com/pivotal-cf-experimental/warrant/internal/server/common", - "Rev": "e3c3c7f4dbd0e97d4459ed67375f9b420fb4c4e9" - }, - { - "ImportPath": "github.com/pivotal-cf-experimental/warrant/internal/server/domain", - "Rev": "e3c3c7f4dbd0e97d4459ed67375f9b420fb4c4e9" - }, - { - "ImportPath": "github.com/pivotal-cf-experimental/warrant/internal/server/groups", - "Rev": "e3c3c7f4dbd0e97d4459ed67375f9b420fb4c4e9" - }, - { - "ImportPath": "github.com/pivotal-cf-experimental/warrant/internal/server/tokens", - "Rev": "e3c3c7f4dbd0e97d4459ed67375f9b420fb4c4e9" - }, - { - "ImportPath": "github.com/pivotal-cf-experimental/warrant/internal/server/users", - "Rev": "e3c3c7f4dbd0e97d4459ed67375f9b420fb4c4e9" - }, - { - "ImportPath": "github.com/pivotal-cf-experimental/warrant/testserver", - "Rev": "e3c3c7f4dbd0e97d4459ed67375f9b420fb4c4e9" - }, - { - "ImportPath": "github.com/pivotal-cf/uaa-sso-golang/uaa", - "Rev": "0b91e8ad4bb6b9e71a6316e1bb6de7414c0e01b2" - }, - { - "ImportPath": "github.com/pivotal-golang/conceal", - "Rev": "31656578115c62eb24f14f2a2946b018807cb6d2" - }, - { - "ImportPath": "github.com/pivotal-golang/lager", - "Rev": "c88fa6d6c4d2f8a21a4599785211e41777750d34" - }, - { - "ImportPath": "github.com/rcrowley/go-metrics", - "Rev": "8732c616f52954686704c8645fe1a9d59e9df7c1" - }, - { - "ImportPath": "github.com/rcrowley/go-metrics/exp", - "Rev": "8732c616f52954686704c8645fe1a9d59e9df7c1" - }, - { - "ImportPath": "github.com/rubenv/sql-migrate", - "Rev": "53184e1edfb4f9655b0fa8dd2c23e7763f452bda" - }, - { - "ImportPath": "github.com/rubenv/sql-migrate/sqlparse", - "Rev": "53184e1edfb4f9655b0fa8dd2c23e7763f452bda" - }, - { - "ImportPath": "github.com/ryanmoran/stack", - "Rev": "3debe7a5953ad63d7429bd22b186134c6dea6f73" - }, - { - "ImportPath": "github.com/ryanmoran/viron", - "Rev": "f3865b4826c87b16d3a67e308336b319b3b6859a" - }, - { - "ImportPath": "golang.org/x/net/html", - "Rev": "7dbad50ab5b31073856416cdcfeb2796d682f844" - }, - { - "ImportPath": "golang.org/x/net/html/atom", - "Rev": "7dbad50ab5b31073856416cdcfeb2796d682f844" - }, - { - "ImportPath": "gopkg.in/alexcesaro/quotedprintable.v1", - "Rev": "dacd4576c5aafefb89134351dfcf4fbe213cd998" - }, - { - "ImportPath": "gopkg.in/alexcesaro/quotedprintable.v1/internal", - "Rev": "dacd4576c5aafefb89134351dfcf4fbe213cd998" - }, - { - "ImportPath": "gopkg.in/gomail.v1", - "Rev": "d7294067b867578fbea56a07541dcd0c851e5c41" - }, - { - "ImportPath": "gopkg.in/gorp.v1", - "Comment": "v1.7.1", - "Rev": "c87af80f3cc5036b55b83d77171e156791085e2e" - } - ] -} diff --git a/Godeps/Readme b/Godeps/Readme deleted file mode 100644 index 4cdaa53d..00000000 --- a/Godeps/Readme +++ /dev/null @@ -1,5 +0,0 @@ -This directory tree is generated automatically by godep. - -Please do not edit. - -See https://github.com/tools/godep for more information. diff --git a/application/environment_test.go b/application/environment_test.go index c5819768..9a282724 100644 --- a/application/environment_test.go +++ b/application/environment_test.go @@ -56,7 +56,7 @@ var _ = Describe("Environment", func() { Context("when an environment error occurs", func() { It("adds a helpful message about using the bosh release to the error message", func() { - err := application.EnvironmentError{errors.New("something is misconfigured")} + err := application.EnvironmentError{Err: errors.New("something is misconfigured")} Expect(err.Error()).To(Equal("something is misconfigured (Please see https://github.com/cloudfoundry-incubator/notifications-release to find a packaged version of notifications and see the required configuration)")) }) }) @@ -83,14 +83,14 @@ var _ = Describe("Environment", func() { os.Setenv("DATABASE_URL", "") _, err := application.NewEnvironment() - Expect(err).To(MatchError(application.EnvironmentError{viron.RequiredFieldError{"DATABASE_URL"}})) + Expect(err).To(MatchError(application.EnvironmentError{Err: viron.RequiredFieldError{Name: "DATABASE_URL"}})) }) It("errors when the url is not properly formatted", func() { os.Setenv("DATABASE_URL", "s%%oe\\mthing!!") _, err := application.NewEnvironment() - Expect(err).To(MatchError(application.EnvironmentError{errors.New("Could not parse DATABASE_URL \"s%%oe\\\\mthing!!\", it does not fit format \"tcp://user:pass@host/dname\"")})) + Expect(err).To(MatchError(application.EnvironmentError{Err: errors.New("Could not parse DATABASE_URL \"s%%oe\\\\mthing!!\", it does not fit format \"tcp://user:pass@host/dname\"")})) }) }) }) @@ -165,21 +165,21 @@ var _ = Describe("Environment", func() { os.Setenv("UAA_CLIENT_SECRET", "uaa-client-secret") _, err := application.NewEnvironment() - Expect(err).To(MatchError(application.EnvironmentError{viron.RequiredFieldError{"UAA_HOST"}})) + Expect(err).To(MatchError(application.EnvironmentError{Err: viron.RequiredFieldError{Name: "UAA_HOST"}})) os.Setenv("UAA_HOST", "https://uaa.example.com") os.Setenv("UAA_CLIENT_ID", "") os.Setenv("UAA_CLIENT_SECRET", "uaa-client-secret") _, err = application.NewEnvironment() - Expect(err).To(MatchError(application.EnvironmentError{viron.RequiredFieldError{"UAA_CLIENT_ID"}})) + Expect(err).To(MatchError(application.EnvironmentError{Err: viron.RequiredFieldError{Name: "UAA_CLIENT_ID"}})) os.Setenv("UAA_HOST", "https://uaa.example.com") os.Setenv("UAA_CLIENT_ID", "uaa-client-id") os.Setenv("UAA_CLIENT_SECRET", "") _, err = application.NewEnvironment() - Expect(err).To(MatchError(application.EnvironmentError{viron.RequiredFieldError{"UAA_CLIENT_SECRET"}})) + Expect(err).To(MatchError(application.EnvironmentError{Err: viron.RequiredFieldError{Name: "UAA_CLIENT_SECRET"}})) }) }) @@ -236,7 +236,7 @@ var _ = Describe("Environment", func() { os.Setenv("SMTP_AUTH_MECHANISM", "banana") _, err = application.NewEnvironment() - Expect(err).To(MatchError(application.EnvironmentError{errors.New("Could not parse SMTP_AUTH_MECHANISM \"banana\", it is not one of the allowed values: [none plain cram-md5]")})) + Expect(err).To(MatchError(application.EnvironmentError{Err: errors.New("Could not parse SMTP_AUTH_MECHANISM \"banana\", it is not one of the allowed values: [none plain cram-md5]")})) }) It("errors when the values are missing", func() { @@ -250,19 +250,19 @@ var _ = Describe("Environment", func() { os.Setenv("SMTP_HOST", "") _, err = application.NewEnvironment() - Expect(err).To(MatchError(application.EnvironmentError{viron.RequiredFieldError{"SMTP_HOST"}})) + Expect(err).To(MatchError(application.EnvironmentError{Err: viron.RequiredFieldError{Name: "SMTP_HOST"}})) os.Setenv("SMTP_HOST", "smtp.example.com") os.Setenv("SMTP_PORT", "") _, err = application.NewEnvironment() - Expect(err).To(MatchError(application.EnvironmentError{viron.RequiredFieldError{"SMTP_PORT"}})) + Expect(err).To(MatchError(application.EnvironmentError{Err: viron.RequiredFieldError{Name: "SMTP_PORT"}})) os.Setenv("SMTP_AUTH_MECHANISM", "") os.Setenv("SMTP_PORT", "567") _, err = application.NewEnvironment() - Expect(err).To(MatchError(application.EnvironmentError{viron.RequiredFieldError{"SMTP_AUTH_MECHANISM"}})) + Expect(err).To(MatchError(application.EnvironmentError{Err: viron.RequiredFieldError{Name: "SMTP_AUTH_MECHANISM"}})) }) }) @@ -297,7 +297,7 @@ var _ = Describe("Environment", func() { os.Setenv("SENDER", "") _, err := application.NewEnvironment() - Expect(err).To(MatchError(application.EnvironmentError{viron.RequiredFieldError{"SENDER"}})) + Expect(err).To(MatchError(application.EnvironmentError{Err: viron.RequiredFieldError{Name: "SENDER"}})) }) }) @@ -314,7 +314,7 @@ var _ = Describe("Environment", func() { os.Setenv("CC_HOST", "") _, err := application.NewEnvironment() - Expect(err).To(MatchError(application.EnvironmentError{viron.RequiredFieldError{"CC_HOST"}})) + Expect(err).To(MatchError(application.EnvironmentError{Err: viron.RequiredFieldError{Name: "CC_HOST"}})) }) }) @@ -402,7 +402,7 @@ var _ = Describe("Environment", func() { os.Setenv("VCAP_APPLICATION", "") _, err := application.NewEnvironment() - Expect(err).To(MatchError(application.EnvironmentError{viron.RequiredFieldError{"VCAP_APPLICATION"}})) + Expect(err).To(MatchError(application.EnvironmentError{Err: viron.RequiredFieldError{Name: "VCAP_APPLICATION"}})) }) }) @@ -454,7 +454,7 @@ var _ = Describe("Environment", func() { os.Setenv("ENCRYPTION_KEY", "") _, err := application.NewEnvironment() - Expect(err).To(MatchError(application.EnvironmentError{viron.RequiredFieldError{"ENCRYPTION_KEY"}})) + Expect(err).To(MatchError(application.EnvironmentError{Err: viron.RequiredFieldError{Name: "ENCRYPTION_KEY"}})) }) }) @@ -504,7 +504,7 @@ var _ = Describe("Environment", func() { os.Setenv("DOMAIN", "") _, err := application.NewEnvironment() - Expect(err).To(MatchError(application.EnvironmentError{viron.RequiredFieldError{"DOMAIN"}})) + Expect(err).To(MatchError(application.EnvironmentError{Err: viron.RequiredFieldError{Name: "DOMAIN"}})) }) }) }) diff --git a/bin/test b/bin/test index 93e5a928..b4d7dbb0 100755 --- a/bin/test +++ b/bin/test @@ -33,7 +33,7 @@ if [[ $EXIT_CODE = 0 ]]; then echo pushd $DIR/.. > /dev/null 2>&1 set +e - find . -path ./vendor -prune -o -type f -print | grep "\.go$" | xargs go tool vet -composites=false + go vet ./... EXIT_CODE=$? set -e popd > /dev/null 2>&1 diff --git a/ci/pipelines/pull-request.yml b/ci/pipelines/pull-request.yml index 54df0507..75f6b0a4 100644 --- a/ci/pipelines/pull-request.yml +++ b/ci/pipelines/pull-request.yml @@ -15,7 +15,7 @@ resources: type: registry-image-dev source: repository: golang - tag: 1.9-stretch + tag: 1.11-stretch - name: pull-request type: pull-request @@ -53,13 +53,16 @@ jobs: export GOPATH=`pwd`/go export PATH=$PATH:$GOPATH/bin - cd go/src/github.com/cloudfoundry-incubator/notifications - - go get github.com/tools/godep + export GO111MODULE=off go get github.com/onsi/ginkgo/ginkgo + export GO111MODULE=on + export GOFLAGS=-mod=vendor + cd go/src/github.com/cloudfoundry-incubator/notifications go version + export GOFLAGS=-mod=vendor + echo "=== Setting up MySQL ===" apt-get -qqy update apt-get install -qqy mysql-server diff --git a/ci/pipelines/release.yml b/ci/pipelines/release.yml index 3d355490..300e88d3 100644 --- a/ci/pipelines/release.yml +++ b/ci/pipelines/release.yml @@ -10,7 +10,7 @@ resources: type: registry-image-dev source: repository: golang - tag: 1.9-stretch + tag: 1.11-stretch - name: master type: git @@ -67,13 +67,16 @@ jobs: export GOPATH=`pwd`/go export PATH=$PATH:$GOPATH/bin - cd go/src/github.com/cloudfoundry-incubator/notifications - - go get github.com/tools/godep + export GO111MODULE=off go get github.com/onsi/ginkgo/ginkgo + export GO111MODULE=on + export GOFLAGS=-mod=vendor + cd go/src/github.com/cloudfoundry-incubator/notifications go version + export GOFLAGS=-mod=vendor + echo "=== Running Tests ===" ./bin/unit @@ -116,13 +119,16 @@ jobs: export GOPATH=`pwd`/go export PATH=$PATH:$GOPATH/bin - cd go/src/github.com/cloudfoundry-incubator/notifications - - go get github.com/tools/godep + export GO111MODULE=off go get github.com/onsi/ginkgo/ginkgo + export GO111MODULE=on + export GOFLAGS=-mod=vendor + cd go/src/github.com/cloudfoundry-incubator/notifications go version + export GOFLAGS=-mod=vendor + echo "=== Setting up MySQL ===" apt-get -qqy update apt-get install -qqy mysql-server @@ -181,13 +187,16 @@ jobs: export GOPATH=`pwd`/go export PATH=$PATH:$GOPATH/bin - cd go/src/github.com/cloudfoundry-incubator/notifications - - go get github.com/tools/godep + export GO111MODULE=off go get github.com/onsi/ginkgo/ginkgo + export GO111MODULE=on + export GOFLAGS=-mod=vendor + cd go/src/github.com/cloudfoundry-incubator/notifications go version + export GOFLAGS=-mod=vendor + echo "=== Setting up MySQL ===" apt-get -qqy update apt-get install -qqy mysql-server diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..86a379a3 --- /dev/null +++ b/go.mod @@ -0,0 +1,29 @@ +module github.com/cloudfoundry-incubator/notifications + +go 1.12 + +require ( + github.com/DATA-DOG/go-sqlmock v0.0.0-20180221072120-a6b4b164c6d1 + github.com/PuerkitoBio/goquery v0.0.0-20150328133056-269246d9e7d4 + github.com/andybalholm/cascadia v0.0.0-20150328005534-54abbbf07a45 // indirect + github.com/chrj/smtpd v0.0.0-20140720195347-c6fe39d4dcdd + github.com/dgrijalva/jwt-go v0.0.0-20141103211122-47b263f02057 + github.com/go-sql-driver/mysql v1.2.0 + github.com/gorilla/context v0.0.0-20140306180640-1be7a086a5fd // indirect + github.com/gorilla/mux v0.0.0-20131205071822-9ede152210fa + github.com/onsi/ginkgo v0.0.0-20141213001613-291f28e66dd2 + github.com/onsi/gomega v0.0.0-20150530211311-d6c945f9fdbf + github.com/pivotal-cf-experimental/rainmaker v0.0.0-20160401052143-d533d01b7c52 + github.com/pivotal-cf-experimental/warrant v0.0.0-20170119140040-e3c3c7f4dbd0 + github.com/pivotal-cf/uaa-sso-golang v0.0.0-20141119184546-0b91e8ad4bb6 + github.com/pivotal-golang/conceal v0.0.0-20141120010127-31656578115c + github.com/pivotal-golang/lager v0.0.0-20150428205713-c88fa6d6c4d2 + github.com/rcrowley/go-metrics v0.0.0-20180125231941-8732c616f529 + github.com/rubenv/sql-migrate v0.0.0-20150713140751-53184e1edfb4 + github.com/ryanmoran/stack v0.0.0-20140916210556-3debe7a5953a + github.com/ryanmoran/viron v0.0.0-20150922192335-f3865b4826c8 + golang.org/x/net v0.0.0-20150320034621-7dbad50ab5b3 // indirect + gopkg.in/alexcesaro/quotedprintable.v1 v1.0.0-20141111223934-dacd4576c5aa // indirect + gopkg.in/gomail.v1 v1.0.0-20150120141108-d7294067b867 + gopkg.in/gorp.v1 v1.7.1 +) diff --git a/go.sum b/go.sum new file mode 100644 index 00000000..d2192280 --- /dev/null +++ b/go.sum @@ -0,0 +1,46 @@ +github.com/DATA-DOG/go-sqlmock v0.0.0-20180221072120-a6b4b164c6d1 h1:VCMK4Ry+CJWJeKkda76Nmffpwe5ECtkcpqN0TsRSQxM= +github.com/DATA-DOG/go-sqlmock v0.0.0-20180221072120-a6b4b164c6d1/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= +github.com/PuerkitoBio/goquery v0.0.0-20150328133056-269246d9e7d4 h1:Ill2Bt/QBs24daCeDtKBWG1hqLEIht1BrwHwBEshJ3U= +github.com/PuerkitoBio/goquery v0.0.0-20150328133056-269246d9e7d4/go.mod h1:T9ezsOHcCrDCgA8aF1Cqr3sSYbO/xgdy8/R/XiIMAhA= +github.com/andybalholm/cascadia v0.0.0-20150328005534-54abbbf07a45 h1:pIeKyS8OuZGGhM5rQNx9YC6juDR1QVc0GB8TxdOfrTg= +github.com/andybalholm/cascadia v0.0.0-20150328005534-54abbbf07a45/go.mod h1:3I+3V7B6gTBYfdpYgIG2ymALS9H+5VDKUl3lHH7ToM4= +github.com/chrj/smtpd v0.0.0-20140720195347-c6fe39d4dcdd h1:/f/SW/WhVIXuS3c2Eq9w2g0sfvzIAJ+g23YPuNSkKtg= +github.com/chrj/smtpd v0.0.0-20140720195347-c6fe39d4dcdd/go.mod h1:CCN2w0A/V4Mt1XKsMBYtLCUSkPCfanfGjsZbnaJ+13g= +github.com/dgrijalva/jwt-go v0.0.0-20141103211122-47b263f02057 h1:9+f7nOqKMfeJrPaWlOO6OAuSHtg0MkTZQDMwUN7W6Tk= +github.com/dgrijalva/jwt-go v0.0.0-20141103211122-47b263f02057/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/go-sql-driver/mysql v1.2.0 h1:C5cl8DzJiobQuZhND5+a3cOrrRhyaJBPHxZjLgdN8kk= +github.com/go-sql-driver/mysql v1.2.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= +github.com/gorilla/context v0.0.0-20140306180640-1be7a086a5fd h1:SZ5v0Oh0SwT8C2HQN2iQU7mW4TYCk9F93EvTSPcIYyo= +github.com/gorilla/context v0.0.0-20140306180640-1be7a086a5fd/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= +github.com/gorilla/mux v0.0.0-20131205071822-9ede152210fa h1:KxnFLqfI0rxX8qmbu8IfsWnB4yBZRDioqQsvc63PfS4= +github.com/gorilla/mux v0.0.0-20131205071822-9ede152210fa/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= +github.com/onsi/ginkgo v0.0.0-20141213001613-291f28e66dd2 h1:5tq+jOM9z5cHDLKEMFRFGyVk0cCii3jziYgQU0PjM5w= +github.com/onsi/ginkgo v0.0.0-20141213001613-291f28e66dd2/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/gomega v0.0.0-20150530211311-d6c945f9fdbf h1:NA0/kP9lOc4MwgtOE+H5KxRwPQVumngNvobaO4j1PQk= +github.com/onsi/gomega v0.0.0-20150530211311-d6c945f9fdbf/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= +github.com/pivotal-cf-experimental/rainmaker v0.0.0-20160401052143-d533d01b7c52 h1:YaPgxzuENXlCMHe/JVQICTIVtWdXbBodzNnQM/A8+rY= +github.com/pivotal-cf-experimental/rainmaker v0.0.0-20160401052143-d533d01b7c52/go.mod h1:NkPUxSBmoagsX+nu++zlZZKxjFJ1E8VQnduId7VdfFY= +github.com/pivotal-cf-experimental/warrant v0.0.0-20170119140040-e3c3c7f4dbd0 h1:U9Fa2qhp4PWBEbEBge2aBHamIV5g/8hixeYSq2rvJt8= +github.com/pivotal-cf-experimental/warrant v0.0.0-20170119140040-e3c3c7f4dbd0/go.mod h1:gX/qKr3kt6aLynrg2DaPFxicaLeVzJr15gxvqaI6t3Q= +github.com/pivotal-cf/uaa-sso-golang v0.0.0-20141119184546-0b91e8ad4bb6 h1:VIZLjNljVeBKRSGpAIElubnS3Aq1iuqAS7KpWYZayKA= +github.com/pivotal-cf/uaa-sso-golang v0.0.0-20141119184546-0b91e8ad4bb6/go.mod h1:x46WK+FVJdMtvVKBfTAt3fY2EZg/KLS3XXSzx1SAF+I= +github.com/pivotal-golang/conceal v0.0.0-20141120010127-31656578115c h1:reyrySYbaC7Gqj8x2Ko7pjglufeYH0UjxBbimAGVsDM= +github.com/pivotal-golang/conceal v0.0.0-20141120010127-31656578115c/go.mod h1:Kw/kMv1fNuHwfszQT6ZI0ClXyVdezduXsKd/70TUSjc= +github.com/pivotal-golang/lager v0.0.0-20150428205713-c88fa6d6c4d2 h1:5mfs0yZ4ijQYZr5DDwhwbzjAEqdbvFOoePnDg3w+erU= +github.com/pivotal-golang/lager v0.0.0-20150428205713-c88fa6d6c4d2/go.mod h1:EJZBAWMz/TvxVfLaBRwCv+gszrSByWbqQBRwfVbUhvM= +github.com/rcrowley/go-metrics v0.0.0-20180125231941-8732c616f529 h1:QdrarV+Ze3cQpiZZ410O4mpB0WUdOgMc3Rwu8zOmLVg= +github.com/rcrowley/go-metrics v0.0.0-20180125231941-8732c616f529/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/rubenv/sql-migrate v0.0.0-20150713140751-53184e1edfb4 h1:0V/8cK9e1VQ9zXGMoIscgkhYpDlAtUKy8DJp7MEO2NU= +github.com/rubenv/sql-migrate v0.0.0-20150713140751-53184e1edfb4/go.mod h1:WS0rl9eEliYI8DPnr3TOwz4439pay+qNgzJoVya/DmY= +github.com/ryanmoran/stack v0.0.0-20140916210556-3debe7a5953a h1:q7sqzOM/aAKYJcLG4p2UaZCL37SX3RIcFy5/1x4MFbM= +github.com/ryanmoran/stack v0.0.0-20140916210556-3debe7a5953a/go.mod h1:HspNMheDCl20Vj6UJJ0l6IOx8o41FHSGfqF2SoiuMY8= +github.com/ryanmoran/viron v0.0.0-20150922192335-f3865b4826c8 h1:z650GyMn4afbTu3BbYBG9YBZAmHm9TICO/g88raupu8= +github.com/ryanmoran/viron v0.0.0-20150922192335-f3865b4826c8/go.mod h1:m+4a5LnIWQUVuIJxdAcXMo+izXLXrGsTzafWta4gOE0= +golang.org/x/net v0.0.0-20150320034621-7dbad50ab5b3 h1:yvuqj4ruHcpURPG1eeixVVBgX3ku/QgBT92yRIJa1k4= +golang.org/x/net v0.0.0-20150320034621-7dbad50ab5b3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +gopkg.in/alexcesaro/quotedprintable.v1 v1.0.0-20141111223934-dacd4576c5aa h1:PIw+BbGtpLQs+259v7qLUVaaW8/kVZG7aSpg/1gvEUQ= +gopkg.in/alexcesaro/quotedprintable.v1 v1.0.0-20141111223934-dacd4576c5aa/go.mod h1:RSgkUXQnzRspquWaPU1S/IsLs35TDymLZCYZYCtXOoI= +gopkg.in/gomail.v1 v1.0.0-20150120141108-d7294067b867 h1:tBtvVni9Ig6tD3LNyd/MRSBKFTX0DBRzwQWgfII5w8k= +gopkg.in/gomail.v1 v1.0.0-20150120141108-d7294067b867/go.mod h1:mrkmGIvaT7iUJO0pgw8OzjwN1tHmFcMHYtBizddG/ZU= +gopkg.in/gorp.v1 v1.7.1 h1:GBB9KrWRATQZh95HJyVGUZrWwOPswitEYEyqlK8JbAA= +gopkg.in/gorp.v1 v1.7.1/go.mod h1:Wo3h+DBQZIxATwftsglhdD/62zRFPhGhTiu5jUJmCaw= diff --git a/gobble/queue_test.go b/gobble/queue_test.go index 8d560817..bfd525dd 100644 --- a/gobble/queue_test.go +++ b/gobble/queue_test.go @@ -56,7 +56,7 @@ var _ = Describe("Queue", func() { "testing": true, }) - transaction := db.NewTransaction(&db.Connection{database.Connection}) + transaction := db.NewTransaction(&db.Connection{DbMap: database.Connection}) transaction.Begin() job, err := queue.Enqueue(job, transaction) diff --git a/manifest.yml b/manifest.yml index d401eee6..9c375b71 100644 --- a/manifest.yml +++ b/manifest.yml @@ -4,3 +4,6 @@ applications: command: bin/notifications memory: 64M buildpack: go_buildpack + env: + GOVERSION: go1.11 + GOPACKAGENAME: github.com/cloudfoundry-incubator/notifications diff --git a/testing/servers/smtp.go b/testing/servers/smtp.go index 6b043691..75ecf0c7 100644 --- a/testing/servers/smtp.go +++ b/testing/servers/smtp.go @@ -4,7 +4,7 @@ import ( "net" "os" - "bitbucket.org/chrj/smtpd" + "github.com/chrj/smtpd" ) type SMTP struct { diff --git a/v1/collections/templates_test.go b/v1/collections/templates_test.go index 8ff6af43..c7d4cc31 100644 --- a/v1/collections/templates_test.go +++ b/v1/collections/templates_test.go @@ -54,17 +54,17 @@ var _ = Describe("TemplatesCollection", func() { Context("when the request includes a non-existant id", func() { It("reports that the client cannot be found", func() { - clientsRepo.FindCall.Returns.Error = models.NotFoundError{errors.New("not found")} + clientsRepo.FindCall.Returns.Error = models.NotFoundError{Err: errors.New("not found")} err := collection.AssignToClient(conn, "missing-client", "my-template") - Expect(err).To(MatchError(models.NotFoundError{errors.New("not found")})) + Expect(err).To(MatchError(models.NotFoundError{Err: errors.New("not found")})) }) It("reports that the template cannot be found", func() { - templatesRepo.FindByIDCall.Returns.Error = models.NotFoundError{errors.New("not found")} + templatesRepo.FindByIDCall.Returns.Error = models.NotFoundError{Err: errors.New("not found")} err := collection.AssignToClient(conn, "my-client", "non-existant-template") - Expect(err).To(MatchError(collections.TemplateAssignmentError{errors.New("No template with id \"non-existant-template\"")})) + Expect(err).To(MatchError(collections.TemplateAssignmentError{Err: errors.New("No template with id \"non-existant-template\"")})) }) }) @@ -167,25 +167,25 @@ var _ = Describe("TemplatesCollection", func() { Context("when the request includes a non-existant id", func() { It("reports that the client cannot be found", func() { - kindsRepo.FindCall.Returns.Error = models.NotFoundError{errors.New("not found")} + kindsRepo.FindCall.Returns.Error = models.NotFoundError{Err: errors.New("not found")} err := collection.AssignToNotification(conn, "bad-client", "my-kind", "my-template") - Expect(err).To(MatchError(models.NotFoundError{errors.New("not found")})) + Expect(err).To(MatchError(models.NotFoundError{Err: errors.New("not found")})) }) It("reports that the kind cannot be found", func() { - kindsRepo.FindCall.Returns.Error = models.NotFoundError{errors.New("not found")} + kindsRepo.FindCall.Returns.Error = models.NotFoundError{Err: errors.New("not found")} err := collection.AssignToNotification(conn, "my-client", "bad-kind", "my-template") Expect(err).To(HaveOccurred()) - Expect(err).To(BeAssignableToTypeOf(models.NotFoundError{errors.New("not found")})) + Expect(err).To(BeAssignableToTypeOf(models.NotFoundError{Err: errors.New("not found")})) }) It("reports that the template cannot be found", func() { - templatesRepo.FindByIDCall.Returns.Error = models.NotFoundError{errors.New("not found")} + templatesRepo.FindByIDCall.Returns.Error = models.NotFoundError{Err: errors.New("not found")} err := collection.AssignToNotification(conn, "my-client", "my-kind", "non-existant-template") - Expect(err).To(MatchError(collections.TemplateAssignmentError{errors.New("No template with id \"non-existant-template\"")})) + Expect(err).To(MatchError(collections.TemplateAssignmentError{Err: errors.New("No template with id \"non-existant-template\"")})) }) }) diff --git a/v1/models/clients_repo_test.go b/v1/models/clients_repo_test.go index 2952a76b..a5890b7d 100644 --- a/v1/models/clients_repo_test.go +++ b/v1/models/clients_repo_test.go @@ -95,7 +95,7 @@ var _ = Describe("ClientsRepo", func() { } _, err := repo.Update(conn, client) - Expect(err).To(MatchError(models.NotFoundError{errors.New("Client with ID \"my-client\" could not be found")})) + Expect(err).To(MatchError(models.NotFoundError{Err: errors.New("Client with ID \"my-client\" could not be found")})) }) }) @@ -134,7 +134,7 @@ var _ = Describe("ClientsRepo", func() { } _, err := repo.Update(conn, client) - Expect(err).To(MatchError(models.NotFoundError{errors.New("Client with ID \"my-client\" could not be found")})) + Expect(err).To(MatchError(models.NotFoundError{Err: errors.New("Client with ID \"my-client\" could not be found")})) }) }) }) diff --git a/v1/models/database_migrator_test.go b/v1/models/database_migrator_test.go index 1831f8c7..9be3dfeb 100644 --- a/v1/models/database_migrator_test.go +++ b/v1/models/database_migrator_test.go @@ -75,7 +75,7 @@ var _ = Describe("DatabaseMigrator", func() { It("has the default template pre-seeded", func() { _, err := repo.FindByID(connection, models.DefaultTemplateID) - Expect(err).To(MatchError(models.NotFoundError{errors.New("Template with ID \"default\" could not be found")})) + Expect(err).To(MatchError(models.NotFoundError{Err: errors.New("Template with ID \"default\" could not be found")})) dbMigrator.Seed(database, defaultTemplatePath) template, err := repo.FindByID(connection, models.DefaultTemplateID) diff --git a/v1/models/kinds_repo_test.go b/v1/models/kinds_repo_test.go index a86388d9..46cd9c51 100644 --- a/v1/models/kinds_repo_test.go +++ b/v1/models/kinds_repo_test.go @@ -77,7 +77,7 @@ var _ = Describe("KindsRepo", func() { TemplateID: "my-template", } _, err := repo.Update(conn, kind) - Expect(err).To(MatchError(models.NotFoundError{errors.New("Notification with ID \"my-kind\" belonging to client \"my-client\" could not be found")})) + Expect(err).To(MatchError(models.NotFoundError{Err: errors.New("Notification with ID \"my-kind\" belonging to client \"my-client\" could not be found")})) }) }) @@ -129,7 +129,7 @@ var _ = Describe("KindsRepo", func() { ClientID: "my-client", } _, err := repo.Update(conn, kind) - Expect(err).To(MatchError(models.NotFoundError{errors.New("Notification with ID \"my-kind\" belonging to client \"my-client\" could not be found")})) + Expect(err).To(MatchError(models.NotFoundError{Err: errors.New("Notification with ID \"my-kind\" belonging to client \"my-client\" could not be found")})) }) }) }) @@ -318,7 +318,7 @@ var _ = Describe("KindsRepo", func() { Expect(count).To(Equal(1)) _, err = repo.Find(conn, "my-kind", "the-client-id") - Expect(err).To(MatchError(models.NotFoundError{errors.New("Notification with ID \"my-kind\" belonging to client \"the-client-id\" could not be found")})) + Expect(err).To(MatchError(models.NotFoundError{Err: errors.New("Notification with ID \"my-kind\" belonging to client \"the-client-id\" could not be found")})) _, err = repo.Find(conn, "ignored-kind", "other-client-id") if err != nil { diff --git a/v1/models/messages_repo_test.go b/v1/models/messages_repo_test.go index 5c2e17e2..ae6a6770 100644 --- a/v1/models/messages_repo_test.go +++ b/v1/models/messages_repo_test.go @@ -28,7 +28,7 @@ var _ = Describe("MessagesRepo", func() { helpers.TruncateTables(database) conn = database.Connection() message = models.Message{ - Status: common.StatusDelivered, + Status: common.StatusDelivered, } guidGenerator = mocks.NewIDGenerator() @@ -69,7 +69,7 @@ var _ = Describe("MessagesRepo", func() { Context("When the message does not exists", func() { It("FindByID returns a models.RecordNotFoundError", func() { _, err := repo.FindByID(conn, "missing-id") - Expect(err).To(MatchError(models.NotFoundError{errors.New("Message with ID \"missing-id\" could not be found")})) + Expect(err).To(MatchError(models.NotFoundError{Err: errors.New("Message with ID \"missing-id\" could not be found")})) }) }) }) @@ -122,7 +122,7 @@ var _ = Describe("MessagesRepo", func() { Expect(itemsDeleted).To(Equal(1)) _, err = repo.FindByID(conn, message.ID) - Expect(err).To(MatchError(models.NotFoundError{fmt.Errorf("Message with ID %q could not be found", message.ID)})) + Expect(err).To(MatchError(models.NotFoundError{Err: fmt.Errorf("Message with ID %q could not be found", message.ID)})) }) diff --git a/v1/models/templates_repo_test.go b/v1/models/templates_repo_test.go index 0c1ea641..b3234c85 100644 --- a/v1/models/templates_repo_test.go +++ b/v1/models/templates_repo_test.go @@ -55,7 +55,7 @@ var _ = Describe("TemplatesRepo", func() { sillyTemplate, err := repo.FindByID(conn, "silly_template") Expect(sillyTemplate).To(Equal(models.Template{})) - Expect(err).To(MatchError(models.NotFoundError{errors.New("Template with ID \"silly_template\" could not be found")})) + Expect(err).To(MatchError(models.NotFoundError{Err: errors.New("Template with ID \"silly_template\" could not be found")})) }) }) }) @@ -127,7 +127,7 @@ var _ = Describe("TemplatesRepo", func() { Context("the template does not exist in the database", func() { It("bubbles up the error", func() { _, err := repo.Update(conn, "a-bad-id", aNewTemplate) - Expect(err).To(MatchError(models.NotFoundError{errors.New("Template with ID \"a-bad-id\" could not be found")})) + Expect(err).To(MatchError(models.NotFoundError{Err: errors.New("Template with ID \"a-bad-id\" could not be found")})) }) }) }) @@ -178,14 +178,14 @@ var _ = Describe("TemplatesRepo", func() { Expect(err).ToNot(HaveOccurred()) _, err = repo.FindByID(conn, template.ID) - Expect(err).To(MatchError(models.NotFoundError{fmt.Errorf("Template with ID %q could not be found", template.ID)})) + Expect(err).To(MatchError(models.NotFoundError{Err: fmt.Errorf("Template with ID %q could not be found", template.ID)})) }) }) Context("the template does not exist in the database", func() { It("returns an RecordNotFoundError", func() { err := repo.Destroy(conn, "knockknock") - Expect(err).To(MatchError(models.NotFoundError{errors.New("Template with ID \"knockknock\" could not be found")})) + Expect(err).To(MatchError(models.NotFoundError{Err: errors.New("Template with ID \"knockknock\" could not be found")})) }) }) }) diff --git a/v1/services/notifications_finder_test.go b/v1/services/notifications_finder_test.go index b94f77c0..f18e9e6e 100644 --- a/v1/services/notifications_finder_test.go +++ b/v1/services/notifications_finder_test.go @@ -55,7 +55,7 @@ var _ = Describe("NotificationsFinder", func() { Context("when the client cannot be found", func() { It("returns an empty models.Client", func() { - clientsRepo.FindCall.Returns.Error = models.NotFoundError{errors.New("not found")} + clientsRepo.FindCall.Returns.Error = models.NotFoundError{Err: errors.New("not found")} client, _, err := finder.ClientAndKind(database, "missing-client-id", "perimeter_breach") Expect(err).NotTo(HaveOccurred()) @@ -67,7 +67,7 @@ var _ = Describe("NotificationsFinder", func() { Context("when the kind cannot be found", func() { It("returns an empty models.Kind", func() { - kindsRepo.FindCall.Returns.Error = models.NotFoundError{errors.New("not found")} + kindsRepo.FindCall.Returns.Error = models.NotFoundError{Err: errors.New("not found")} client, kind, err := finder.ClientAndKind(database, "some-client-id", "bad-kind-id") Expect(err).NotTo(HaveOccurred()) diff --git a/v1/services/organization_loader_test.go b/v1/services/organization_loader_test.go index b1e1761a..eb1ac0cd 100644 --- a/v1/services/organization_loader_test.go +++ b/v1/services/organization_loader_test.go @@ -46,7 +46,7 @@ var _ = Describe("OrganizationLoader", func() { cc.LoadOrganizationCall.Returns.Error = cf.NewFailure(404, "BOOM!") _, err := loader.Load("missing-org", "some-token") - Expect(err).To(MatchError(services.CCNotFoundError{cf.NewFailure(404, "BOOM!")})) + Expect(err).To(MatchError(services.CCNotFoundError{Err: cf.NewFailure(404, "BOOM!")})) }) }) @@ -55,7 +55,7 @@ var _ = Describe("OrganizationLoader", func() { cc.LoadOrganizationCall.Returns.Error = cf.NewFailure(401, "BOOM!") _, err := loader.Load("org-001", "some-token") - Expect(err).To(Equal(services.CCDownError{cf.NewFailure(401, "BOOM!")})) + Expect(err).To(Equal(services.CCDownError{Err: cf.NewFailure(401, "BOOM!")})) }) It("returns the same error for all other cases", func() { diff --git a/v1/services/preference_updater_test.go b/v1/services/preference_updater_test.go index abcc2a2e..fff53599 100644 --- a/v1/services/preference_updater_test.go +++ b/v1/services/preference_updater_test.go @@ -141,7 +141,7 @@ var _ = Describe("PreferenceUpdater", func() { kindsRepo.FindCall.Returns.Error = errors.New("something bad happened") err := updater.Update(conn, preferences, false, "the-user") - Expect(err).To(MatchError(services.MissingKindOrClientError{errors.New("The kind 'boo' cannot be found for client 'ghosts'")})) + Expect(err).To(MatchError(services.MissingKindOrClientError{Err: errors.New("The kind 'boo' cannot be found for client 'ghosts'")})) }) }) @@ -169,7 +169,7 @@ var _ = Describe("PreferenceUpdater", func() { kindsRepo.FindCall.Returns.Error = errors.New("something bad happened") err := updater.Update(conn, preferences, false, "the-user") - Expect(err).To(Equal(services.MissingKindOrClientError{errors.New("The kind 'dead' cannot be found for client 'raptors'")})) + Expect(err).To(Equal(services.MissingKindOrClientError{Err: errors.New("The kind 'dead' cannot be found for client 'raptors'")})) }) }) @@ -201,7 +201,7 @@ var _ = Describe("PreferenceUpdater", func() { } err := updater.Update(conn, preferences, false, "the-user") - Expect(err).To(Equal(services.CriticalKindError{errors.New("The kind 'hungry' for the 'raptors' client is critical and cannot be unsubscribed from")})) + Expect(err).To(Equal(services.CriticalKindError{Err: errors.New("The kind 'hungry' for the 'raptors' client is critical and cannot be unsubscribed from")})) }) }) }) diff --git a/v1/services/space_loader_test.go b/v1/services/space_loader_test.go index 78e71e74..c8ec1b84 100644 --- a/v1/services/space_loader_test.go +++ b/v1/services/space_loader_test.go @@ -47,7 +47,7 @@ var _ = Describe("SpaceLoader", func() { cc.LoadSpaceCall.Returns.Error = cf.NewFailure(404, "not found") _, err := loader.Load("missing-space", "some-token") - Expect(err).To(MatchError(services.CCNotFoundError{cf.NewFailure(404, "not found")})) + Expect(err).To(MatchError(services.CCNotFoundError{Err: cf.NewFailure(404, "not found")})) }) }) @@ -56,7 +56,7 @@ var _ = Describe("SpaceLoader", func() { cc.LoadSpaceCall.Returns.Error = cf.NewFailure(401, "BOOM!") _, err := loader.Load("space-001", "some-token") - Expect(err).To(MatchError(services.CCDownError{cf.NewFailure(401, "BOOM!")})) + Expect(err).To(MatchError(services.CCDownError{Err: cf.NewFailure(401, "BOOM!")})) }) It("returns the same error for all other cases", func() { diff --git a/v1/web/notifications/client_registration_params.go b/v1/web/notifications/client_registration_params.go index cdc884d7..376306c9 100644 --- a/v1/web/notifications/client_registration_params.go +++ b/v1/web/notifications/client_registration_params.go @@ -58,24 +58,24 @@ func strictValidateJSON(bytes []byte) error { continue } else if key == "notifications" { if untypedClientRegistration[key] == nil { - return webutil.SchemaError{errors.New("only include \"notifications\" key when adding a notification")} + return webutil.SchemaError{Err: errors.New("only include \"notifications\" key when adding a notification")} } notifications := untypedClientRegistration[key].(map[string]interface{}) for _, notificationData := range notifications { if notificationData == nil { - return webutil.SchemaError{errors.New("notification must not be null")} + return webutil.SchemaError{Err: errors.New("notification must not be null")} } notificationMap := notificationData.(map[string]interface{}) for propertyName := range notificationMap { if propertyName == "description" || propertyName == "critical" { continue } else { - return webutil.SchemaError{fmt.Errorf("%q is not a valid property", propertyName)} + return webutil.SchemaError{Err: fmt.Errorf("%q is not a valid property", propertyName)} } } } } else { - return webutil.SchemaError{fmt.Errorf("%q is not a valid property", key)} + return webutil.SchemaError{Err: fmt.Errorf("%q is not a valid property", key)} } } return nil @@ -100,7 +100,7 @@ func (clientRegistration ClientRegistrationParams) Validate() error { } if len(errs) > 0 { - return webutil.ValidationError{errors.New(strings.Join(errs, ", "))} + return webutil.ValidationError{Err: errors.New(strings.Join(errs, ", "))} } return nil diff --git a/v1/web/notifications/client_registration_params_test.go b/v1/web/notifications/client_registration_params_test.go index a9ea3e01..0d6198fe 100644 --- a/v1/web/notifications/client_registration_params_test.go +++ b/v1/web/notifications/client_registration_params_test.go @@ -63,14 +63,14 @@ var _ = Describe("ClientRegistrationParams", func() { someJson := `{ "source_name" : "Raptor Containment Unit", "invalid_property" : 5 }` _, err := notifications.NewClientRegistrationParams(strings.NewReader(someJson)) - Expect(err).To(MatchError(webutil.SchemaError{errors.New("\"invalid_property\" is not a valid property")})) + Expect(err).To(MatchError(webutil.SchemaError{Err: errors.New("\"invalid_property\" is not a valid property")})) }) It("returns an error for invalid nested keys", func() { someJson := `{ "source_name" : "Raptor", "notifications": { "some_id": {"description" : "ok", "invalid_property" : 5 } } }` _, err := notifications.NewClientRegistrationParams(strings.NewReader(someJson)) - Expect(err).To(MatchError(webutil.SchemaError{errors.New("\"invalid_property\" is not a valid property")})) + Expect(err).To(MatchError(webutil.SchemaError{Err: errors.New("\"invalid_property\" is not a valid property")})) }) }) @@ -79,13 +79,13 @@ var _ = Describe("ClientRegistrationParams", func() { someJson := `{ "source_name" : "Something something raptor", "notifications": null }` _, err := notifications.NewClientRegistrationParams(strings.NewReader(someJson)) - Expect(err).To(MatchError(webutil.SchemaError{errors.New("only include \"notifications\" key when adding a notification")})) + Expect(err).To(MatchError(webutil.SchemaError{Err: errors.New("only include \"notifications\" key when adding a notification")})) }) It("returns an error if an individual notification is null ", func() { someJson := `{ "source_name" : "Raptor", "notifications": { "some_id": null } }` _, err := notifications.NewClientRegistrationParams(strings.NewReader(someJson)) - Expect(err).To(MatchError(webutil.SchemaError{errors.New("notification must not be null")})) + Expect(err).To(MatchError(webutil.SchemaError{Err: errors.New("notification must not be null")})) }) }) }) @@ -102,7 +102,7 @@ var _ = Describe("ClientRegistrationParams", func() { cr := notifications.ClientRegistrationParams{} err := cr.Validate() - Expect(err).To(MatchError(webutil.ValidationError{errors.New("\"source_name\" is a required field")})) + Expect(err).To(MatchError(webutil.ValidationError{Err: errors.New("\"source_name\" is a required field")})) }) It("returns an error if notification is missing a required field", func() { diff --git a/v1/web/notifications/put_handler.go b/v1/web/notifications/put_handler.go index 57c7b23d..c9a60897 100644 --- a/v1/web/notifications/put_handler.go +++ b/v1/web/notifications/put_handler.go @@ -108,7 +108,7 @@ func (h PutHandler) ValidateCriticalScopes(scopes interface{}, kinds []models.Ki validatedKinds := []models.Kind{} for _, kind := range kinds { if kind.Critical && !hasCriticalWrite { - return []models.Kind{}, webutil.UAAScopesError{errors.New("UAA Scopes Error: Client does not have authority to register critical notifications.")} + return []models.Kind{}, webutil.UAAScopesError{Err: errors.New("UAA Scopes Error: Client does not have authority to register critical notifications.")} } kind.ClientID = client.ID validatedKinds = append(validatedKinds, kind) diff --git a/v1/web/notifications/put_handler_test.go b/v1/web/notifications/put_handler_test.go index a3856815..52094a11 100644 --- a/v1/web/notifications/put_handler_test.go +++ b/v1/web/notifications/put_handler_test.go @@ -187,7 +187,7 @@ var _ = Describe("PutHandler", func() { context.Set("token", token) handler.ServeHTTP(writer, request, context) - Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.UAAScopesError{errors.New("UAA Scopes Error: Client does not have authority to register critical notifications.")})) + Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.UAAScopesError{Err: errors.New("UAA Scopes Error: Client does not have authority to register critical notifications.")})) Expect(transaction.BeginCall.WasCalled).To(BeFalse()) Expect(transaction.CommitCall.WasCalled).To(BeFalse()) diff --git a/v1/web/notifications/registration_handler.go b/v1/web/notifications/registration_handler.go index 22c14814..8ade2f5a 100644 --- a/v1/web/notifications/registration_handler.go +++ b/v1/web/notifications/registration_handler.go @@ -90,7 +90,7 @@ func (h RegistrationHandler) ValidateCriticalScopes(scopes interface{}, kinds [] validatedKinds := []models.Kind{} for _, kind := range kinds { if kind.Critical && !hasCriticalWrite { - return []models.Kind{}, webutil.UAAScopesError{errors.New("UAA Scopes Error: Client does not have authority to register critical notifications.")} + return []models.Kind{}, webutil.UAAScopesError{Err: errors.New("UAA Scopes Error: Client does not have authority to register critical notifications.")} } kind.ClientID = client.ID validatedKinds = append(validatedKinds, kind) diff --git a/v1/web/notifications/registration_handler_test.go b/v1/web/notifications/registration_handler_test.go index 33e58720..ef93c510 100644 --- a/v1/web/notifications/registration_handler_test.go +++ b/v1/web/notifications/registration_handler_test.go @@ -188,7 +188,7 @@ var _ = Describe("RegistrationHandler", func() { handler.ServeHTTP(writer, request, context) - Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.UAAScopesError{errors.New("UAA Scopes Error: Client does not have authority to register critical notifications.")})) + Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.UAAScopesError{Err: errors.New("UAA Scopes Error: Client does not have authority to register critical notifications.")})) Expect(transaction.BeginCall.WasCalled).To(BeFalse()) Expect(transaction.CommitCall.WasCalled).To(BeFalse()) diff --git a/v1/web/notifications/registration_params.go b/v1/web/notifications/registration_params.go index 1546061e..31d73f29 100644 --- a/v1/web/notifications/registration_params.go +++ b/v1/web/notifications/registration_params.go @@ -73,7 +73,7 @@ func (registration RegistrationParams) Validate() error { errs = append(errs, kindErrors...) if len(errs) > 0 { - return webutil.ValidationError{errors.New(strings.Join(errs, ", "))} + return webutil.ValidationError{Err: errors.New(strings.Join(errs, ", "))} } return nil } diff --git a/v1/web/notifications/registration_params_test.go b/v1/web/notifications/registration_params_test.go index be8c6394..92528d46 100644 --- a/v1/web/notifications/registration_params_test.go +++ b/v1/web/notifications/registration_params_test.go @@ -117,7 +117,7 @@ var _ = Describe("RegistrationParams", func() { Expect(err).NotTo(HaveOccurred()) err = parameters.Validate() - Expect(err).To(MatchError(webutil.ValidationError{errors.New("\"source_description\" is a required field, \"kind.id\" is a required field, \"kind.description\" is a required field")})) + Expect(err).To(MatchError(webutil.ValidationError{Err: errors.New("\"source_description\" is a required field, \"kind.id\" is a required field, \"kind.description\" is a required field")})) }) It("validates the format of kind.ID's", func() { @@ -136,7 +136,7 @@ var _ = Describe("RegistrationParams", func() { Expect(err).NotTo(HaveOccurred()) err = parameters.Validate() - Expect(err).To(MatchError(webutil.ValidationError{errors.New("\"kind.id\" is improperly formatted")})) + Expect(err).To(MatchError(webutil.ValidationError{Err: errors.New("\"kind.id\" is improperly formatted")})) }) }) diff --git a/v1/web/notifications/update_params.go b/v1/web/notifications/update_params.go index 64c863a6..a4728c87 100644 --- a/v1/web/notifications/update_params.go +++ b/v1/web/notifications/update_params.go @@ -22,7 +22,7 @@ func NewNotificationParams(body io.Reader) (NotificationUpdateParams, error) { if err != nil { switch err.(type) { case valiant.RequiredFieldError: - return params, webutil.ValidationError{err} + return params, webutil.ValidationError{Err: err} default: return params, webutil.ParseError{} } diff --git a/v1/web/notify/notify.go b/v1/web/notify/notify.go index 0e2696b4..ee4dad63 100644 --- a/v1/web/notify/notify.go +++ b/v1/web/notify/notify.go @@ -49,7 +49,7 @@ func (h Notify) Execute(connection ConnectionInterface, req *http.Request, conte } if !validator.Validate(¶meters) { - return []byte{}, webutil.ValidationError{errors.New(strings.Join(parameters.Errors, ","))} + return []byte{}, webutil.ValidationError{Err: errors.New(strings.Join(parameters.Errors, ","))} } requestReceivedTime, ok := context.Get(RequestReceivedTime).(time.Time) diff --git a/v1/web/notify/notify_test.go b/v1/web/notify/notify_test.go index dc034a52..40f90808 100644 --- a/v1/web/notify/notify_test.go +++ b/v1/web/notify/notify_test.go @@ -179,7 +179,7 @@ var _ = Describe("Notify", func() { request.Header.Set("Authorization", "Bearer "+rawToken) _, err = handler.Execute(conn, request, context, "space-001", strategy, validator, vcapRequestID) - Expect(err).To(MatchError(webutil.ValidationError{errors.New("boom")})) + Expect(err).To(MatchError(webutil.ValidationError{Err: errors.New("boom")})) }) It("returns a error response when params cannot be parsed", func() { diff --git a/v1/web/preferences/get_preferences_handler.go b/v1/web/preferences/get_preferences_handler.go index 13778dff..3c49d2dd 100644 --- a/v1/web/preferences/get_preferences_handler.go +++ b/v1/web/preferences/get_preferences_handler.go @@ -34,7 +34,7 @@ func (h GetPreferencesHandler) ServeHTTP(w http.ResponseWriter, req *http.Reques token := context.Get("token").(*jwt.Token) if _, ok := token.Claims["user_id"]; !ok { - h.errorWriter.Write(w, webutil.MissingUserTokenError{errors.New("Missing user_id from token claims.")}) + h.errorWriter.Write(w, webutil.MissingUserTokenError{Err: errors.New("Missing user_id from token claims.")}) return } diff --git a/v1/web/preferences/get_preferences_handler_test.go b/v1/web/preferences/get_preferences_handler_test.go index 74908e75..de09a7d3 100644 --- a/v1/web/preferences/get_preferences_handler_test.go +++ b/v1/web/preferences/get_preferences_handler_test.go @@ -141,7 +141,7 @@ var _ = Describe("GetPreferencesHandler", func() { context.Set("token", token) handler.ServeHTTP(writer, request, context) - Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.MissingUserTokenError{errors.New("Missing user_id from token claims.")})) + Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.MissingUserTokenError{Err: errors.New("Missing user_id from token claims.")})) }) }) }) diff --git a/v1/web/preferences/update_preferences_handler.go b/v1/web/preferences/update_preferences_handler.go index 3415862a..59b369b8 100644 --- a/v1/web/preferences/update_preferences_handler.go +++ b/v1/web/preferences/update_preferences_handler.go @@ -31,7 +31,7 @@ func (h UpdatePreferencesHandler) ServeHTTP(w http.ResponseWriter, req *http.Req token := context.Get("token").(*jwt.Token) if _, ok := token.Claims["user_id"]; !ok { - h.errorWriter.Write(w, webutil.MissingUserTokenError{errors.New("Missing user_id from token claims.")}) + h.errorWriter.Write(w, webutil.MissingUserTokenError{Err: errors.New("Missing user_id from token claims.")}) return } @@ -41,13 +41,13 @@ func (h UpdatePreferencesHandler) ServeHTTP(w http.ResponseWriter, req *http.Req validator := valiant.NewValidator(req.Body) err := validator.Validate(&builder) if err != nil { - h.errorWriter.Write(w, webutil.ValidationError{err}) + h.errorWriter.Write(w, webutil.ValidationError{Err: err}) return } preferences, err := builder.ToPreferences() if err != nil { - h.errorWriter.Write(w, webutil.ValidationError{err}) + h.errorWriter.Write(w, webutil.ValidationError{Err: err}) return } @@ -59,7 +59,7 @@ func (h UpdatePreferencesHandler) ServeHTTP(w http.ResponseWriter, req *http.Req switch err.(type) { case services.MissingKindOrClientError, services.CriticalKindError: - h.errorWriter.Write(w, webutil.ValidationError{err}) + h.errorWriter.Write(w, webutil.ValidationError{Err: err}) default: h.errorWriter.Write(w, err) } @@ -68,7 +68,7 @@ func (h UpdatePreferencesHandler) ServeHTTP(w http.ResponseWriter, req *http.Req err = transaction.Commit() if err != nil { - h.errorWriter.Write(w, models.TransactionCommitError{err}) + h.errorWriter.Write(w, models.TransactionCommitError{Err: err}) return } diff --git a/v1/web/preferences/update_preferences_handler_test.go b/v1/web/preferences/update_preferences_handler_test.go index b5d01efb..a898394b 100644 --- a/v1/web/preferences/update_preferences_handler_test.go +++ b/v1/web/preferences/update_preferences_handler_test.go @@ -175,7 +175,7 @@ var _ = Describe("UpdatePreferencesHandler", func() { context.Set("token", token) handler.ServeHTTP(writer, request, context) - Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.MissingUserTokenError{errors.New("Missing user_id from token claims.")})) + Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.MissingUserTokenError{Err: errors.New("Missing user_id from token claims.")})) Expect(transaction.BeginCall.WasCalled).To(BeFalse()) Expect(transaction.CommitCall.WasCalled).To(BeFalse()) Expect(transaction.RollbackCall.WasCalled).To(BeFalse()) @@ -183,12 +183,12 @@ var _ = Describe("UpdatePreferencesHandler", func() { }) It("delegates MissingKindOrClientErrors as webutil.ValidationError to the ErrorWriter", func() { - updateError := services.MissingKindOrClientError{errors.New("BOOM!")} + updateError := services.MissingKindOrClientError{Err: errors.New("BOOM!")} updater.UpdateCall.Returns.Error = updateError handler.ServeHTTP(writer, request, context) - Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.ValidationError{updateError})) + Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.ValidationError{Err: updateError})) Expect(transaction.BeginCall.WasCalled).To(BeTrue()) Expect(transaction.CommitCall.WasCalled).To(BeFalse()) @@ -196,12 +196,12 @@ var _ = Describe("UpdatePreferencesHandler", func() { }) It("delegates CriticalKindErrors as webutil.ValidationError to the ErrorWriter", func() { - updateError := services.CriticalKindError{errors.New("BOOM!")} + updateError := services.CriticalKindError{Err: errors.New("BOOM!")} updater.UpdateCall.Returns.Error = updateError handler.ServeHTTP(writer, request, context) - Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.ValidationError{updateError})) + Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.ValidationError{Err: updateError})) Expect(transaction.BeginCall.WasCalled).To(BeTrue()) Expect(transaction.CommitCall.WasCalled).To(BeFalse()) @@ -265,7 +265,7 @@ var _ = Describe("UpdatePreferencesHandler", func() { transaction.CommitCall.Returns.Error = errors.New("transaction error, oh no") handler.ServeHTTP(writer, request, context) - Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(models.TransactionCommitError{errors.New("transaction error, oh no")})) + Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(models.TransactionCommitError{Err: errors.New("transaction error, oh no")})) Expect(transaction.BeginCall.WasCalled).To(BeTrue()) Expect(transaction.CommitCall.WasCalled).To(BeTrue()) diff --git a/v1/web/preferences/update_user_preferences_handler.go b/v1/web/preferences/update_user_preferences_handler.go index e76e6d92..ef72504b 100644 --- a/v1/web/preferences/update_user_preferences_handler.go +++ b/v1/web/preferences/update_user_preferences_handler.go @@ -34,7 +34,7 @@ func (h UpdateUserPreferencesHandler) ServeHTTP(w http.ResponseWriter, req *http validator := valiant.NewValidator(req.Body) err := validator.Validate(&builder) if err != nil { - h.errorWriter.Write(w, webutil.ValidationError{err}) + h.errorWriter.Write(w, webutil.ValidationError{Err: err}) return } @@ -52,7 +52,7 @@ func (h UpdateUserPreferencesHandler) ServeHTTP(w http.ResponseWriter, req *http switch err.(type) { case services.MissingKindOrClientError, services.CriticalKindError: - h.errorWriter.Write(w, webutil.ValidationError{err}) + h.errorWriter.Write(w, webutil.ValidationError{Err: err}) default: h.errorWriter.Write(w, err) } @@ -61,7 +61,7 @@ func (h UpdateUserPreferencesHandler) ServeHTTP(w http.ResponseWriter, req *http err = transaction.Commit() if err != nil { - h.errorWriter.Write(w, models.TransactionCommitError{err}) + h.errorWriter.Write(w, models.TransactionCommitError{Err: err}) return } diff --git a/v1/web/preferences/update_user_preferences_handler_test.go b/v1/web/preferences/update_user_preferences_handler_test.go index 992609d4..34dea33a 100644 --- a/v1/web/preferences/update_user_preferences_handler_test.go +++ b/v1/web/preferences/update_user_preferences_handler_test.go @@ -157,12 +157,12 @@ var _ = Describe("UpdateUserPreferencesHandler", func() { }) It("delegates MissingKindOrClientErrors as webutil.ValidationError to the ErrorWriter", func() { - updateError := services.MissingKindOrClientError{errors.New("BOOM!")} + updateError := services.MissingKindOrClientError{Err: errors.New("BOOM!")} updater.UpdateCall.Returns.Error = updateError handler.ServeHTTP(writer, request, context) - Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.ValidationError{updateError})) + Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.ValidationError{Err: updateError})) Expect(transaction.BeginCall.WasCalled).To(BeTrue()) Expect(transaction.CommitCall.WasCalled).To(BeFalse()) @@ -170,12 +170,12 @@ var _ = Describe("UpdateUserPreferencesHandler", func() { }) It("delegates CriticalKindErrors as webutil.ValidationError to the ErrorWriter", func() { - updateError := services.CriticalKindError{errors.New("BOOM!")} + updateError := services.CriticalKindError{Err: errors.New("BOOM!")} updater.UpdateCall.Returns.Error = updateError handler.ServeHTTP(writer, request, context) - Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.ValidationError{updateError})) + Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.ValidationError{Err: updateError})) Expect(transaction.BeginCall.WasCalled).To(BeTrue()) Expect(transaction.CommitCall.WasCalled).To(BeFalse()) @@ -199,7 +199,7 @@ var _ = Describe("UpdateUserPreferencesHandler", func() { handler.ServeHTTP(writer, request, context) - Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(models.TransactionCommitError{errors.New("transaction error!!!")})) + Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(models.TransactionCommitError{Err: errors.New("transaction error!!!")})) Expect(transaction.BeginCall.WasCalled).To(BeTrue()) Expect(transaction.CommitCall.WasCalled).To(BeTrue()) diff --git a/v1/web/templates/create_handler_test.go b/v1/web/templates/create_handler_test.go index 2ad44cf3..b77052a3 100644 --- a/v1/web/templates/create_handler_test.go +++ b/v1/web/templates/create_handler_test.go @@ -88,7 +88,7 @@ var _ = Describe("CreateHandler", func() { Expect(err).NotTo(HaveOccurred()) handler.ServeHTTP(writer, request, context) - Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.ValidationError{valiant.RequiredFieldError{"Missing required field 'name'"}})) + Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.ValidationError{Err: valiant.RequiredFieldError{ErrorMessage: "Missing required field 'name'"}})) }) It("Writes a validation error to the errorwriter when the request is missing the html field", func() { @@ -96,7 +96,7 @@ var _ = Describe("CreateHandler", func() { Expect(err).NotTo(HaveOccurred()) handler.ServeHTTP(writer, request, context) - Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.ValidationError{valiant.RequiredFieldError{"Missing required field 'html'"}})) + Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.ValidationError{Err: valiant.RequiredFieldError{ErrorMessage: "Missing required field 'html'"}})) }) It("writes a parse error for an invalid request", func() { diff --git a/v1/web/templates/template_params.go b/v1/web/templates/template_params.go index 0c088d13..fda7c850 100644 --- a/v1/web/templates/template_params.go +++ b/v1/web/templates/template_params.go @@ -29,7 +29,7 @@ func NewTemplateParams(body io.ReadCloser) (TemplateParams, error) { if err != nil { switch err.(type) { case valiant.RequiredFieldError: - return template, webutil.ValidationError{err} + return template, webutil.ValidationError{Err: err} default: return template, webutil.ParseError{} } @@ -59,7 +59,7 @@ func (t TemplateParams) validateSyntax() error { for field, contents := range toValidate { _, err := template.New("test").Parse(contents) if err != nil { - return webutil.ValidationError{fmt.Errorf("%s syntax is malformed please check your braces", field)} + return webutil.ValidationError{Err: fmt.Errorf("%s syntax is malformed please check your braces", field)} } } diff --git a/v1/web/templates/template_params_test.go b/v1/web/templates/template_params_test.go index 6b0fb5e8..d76d19d9 100644 --- a/v1/web/templates/template_params_test.go +++ b/v1/web/templates/template_params_test.go @@ -72,7 +72,7 @@ var _ = Describe("TemplateParams", func() { Subject: "{{.bad}", }) _, err := templates.NewTemplateParams(ioutil.NopCloser(body)) - Expect(err).To(MatchError(webutil.ValidationError{errors.New("Subject syntax is malformed please check your braces")})) + Expect(err).To(MatchError(webutil.ValidationError{Err: errors.New("Subject syntax is malformed please check your braces")})) }) }) @@ -85,7 +85,7 @@ var _ = Describe("TemplateParams", func() { Subject: "Great Subject", }) _, err := templates.NewTemplateParams(ioutil.NopCloser(body)) - Expect(err).To(MatchError(webutil.ValidationError{errors.New("Text syntax is malformed please check your braces")})) + Expect(err).To(MatchError(webutil.ValidationError{Err: errors.New("Text syntax is malformed please check your braces")})) }) }) @@ -98,7 +98,7 @@ var _ = Describe("TemplateParams", func() { Subject: "Great Subject", }) _, err := templates.NewTemplateParams(ioutil.NopCloser(body)) - Expect(err).To(MatchError(webutil.ValidationError{errors.New("HTML syntax is malformed please check your braces")})) + Expect(err).To(MatchError(webutil.ValidationError{Err: errors.New("HTML syntax is malformed please check your braces")})) }) }) }) diff --git a/v1/web/templates/update_default_handler_test.go b/v1/web/templates/update_default_handler_test.go index 8ad4ceac..b778227c 100644 --- a/v1/web/templates/update_default_handler_test.go +++ b/v1/web/templates/update_default_handler_test.go @@ -76,7 +76,7 @@ var _ = Describe("UpdateDefaultHandler", func() { handler.ServeHTTP(writer, request, context) - Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.ValidationError{valiant.RequiredFieldError{"Missing required field 'html'"}})) + Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.ValidationError{Err: valiant.RequiredFieldError{ErrorMessage: "Missing required field 'html'"}})) }) }) diff --git a/v1/web/templates/update_handler_test.go b/v1/web/templates/update_handler_test.go index 10459563..3f73b25a 100644 --- a/v1/web/templates/update_handler_test.go +++ b/v1/web/templates/update_handler_test.go @@ -86,7 +86,7 @@ var _ = Describe("UpdateHandler", func() { Expect(err).NotTo(HaveOccurred()) handler.ServeHTTP(writer, request, context) - Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.ValidationError{valiant.RequiredFieldError{"Missing required field 'name'"}})) + Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.ValidationError{Err: valiant.RequiredFieldError{ErrorMessage: "Missing required field 'name'"}})) }) }) @@ -97,19 +97,19 @@ var _ = Describe("UpdateHandler", func() { Expect(err).NotTo(HaveOccurred()) handler.ServeHTTP(writer, request, context) - Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.ValidationError{valiant.RequiredFieldError{"Missing required field 'html'"}})) + Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(webutil.ValidationError{Err: valiant.RequiredFieldError{ErrorMessage: "Missing required field 'html'"}})) }) }) Describe("when the update returns an error", func() { It("returns the error", func() { - updater.UpdateCall.Returns.Error = models.TemplateUpdateError{errors.New("some error")} + updater.UpdateCall.Returns.Error = models.TemplateUpdateError{Err: errors.New("some error")} body := []byte(`{"name": "a temlate name", "html": "

my html

"}`) request, err = http.NewRequest("PUT", "/templates/a-template-id", bytes.NewBuffer(body)) Expect(err).NotTo(HaveOccurred()) handler.ServeHTTP(writer, request, context) - Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(models.TemplateUpdateError{errors.New("some error")})) + Expect(errorWriter.WriteCall.Receives.Error).To(MatchError(models.TemplateUpdateError{Err: errors.New("some error")})) }) }) }) diff --git a/v1/web/webutil/error_writer_test.go b/v1/web/webutil/error_writer_test.go index 082c65e7..511d58fe 100644 --- a/v1/web/webutil/error_writer_test.go +++ b/v1/web/webutil/error_writer_test.go @@ -27,15 +27,15 @@ var _ = Describe("ErrorWriter", func() { }) It("returns a 422 when a client tries to register a critical notification without critical_notifications.write scope", func() { - writer.Write(recorder, webutil.UAAScopesError{errors.New("UAA Scopes Error: Client does not have authority to register critical notifications.")}) + writer.Write(recorder, webutil.UAAScopesError{Err: errors.New("UAA Scopes Error: Client does not have authority to register critical notifications.")}) Expect(recorder.Code).To(Equal(422)) Expect(recorder.Body).To(MatchJSON(`{ - "errors": ["UAA Scopes Error: Client does not have authority to register critical notifications."] + "errors": ["UAA Scopes Error: Client does not have authority to register critical notifications."] }`)) }) It("returns a 502 when CloudController fails to respond", func() { - writer.Write(recorder, services.CCDownError{errors.New("Bad things happened!")}) + writer.Write(recorder, services.CCDownError{Err: errors.New("Bad things happened!")}) Expect(recorder.Code).To(Equal(http.StatusBadGateway)) Expect(recorder.Body).To(MatchJSON(`{ "errors": ["Bad things happened!"] @@ -46,23 +46,23 @@ var _ = Describe("ErrorWriter", func() { writer.Write(recorder, webutil.TemplateCreateError{}) Expect(recorder.Code).To(Equal(http.StatusInternalServerError)) Expect(recorder.Body).To(MatchJSON(`{ - "errors": ["Failed to create Template in the database"] + "errors": ["Failed to create Template in the database"] }`)) }) It("returns a 500 when there is a template update error", func() { - writer.Write(recorder, models.TemplateUpdateError{errors.New("Failed to update Template in the database")}) + writer.Write(recorder, models.TemplateUpdateError{Err: errors.New("Failed to update Template in the database")}) Expect(recorder.Code).To(Equal(http.StatusInternalServerError)) Expect(recorder.Body).To(MatchJSON(`{ - "errors": ["Failed to update Template in the database"] + "errors": ["Failed to update Template in the database"] }`)) }) It("returns a 404 when the space cannot be found", func() { - writer.Write(recorder, services.CCNotFoundError{errors.New("Space could not be found")}) + writer.Write(recorder, services.CCNotFoundError{Err: errors.New("Space could not be found")}) Expect(recorder.Code).To(Equal(http.StatusNotFound)) Expect(recorder.Body).To(MatchJSON(`{ - "errors": ["Space could not be found"] + "errors": ["Space could not be found"] }`)) }) @@ -70,7 +70,7 @@ var _ = Describe("ErrorWriter", func() { writer.Write(recorder, cf.NotFoundError{Message: "Space could not be found"}) Expect(recorder.Code).To(Equal(http.StatusNotFound)) Expect(recorder.Body).To(MatchJSON(`{ - "errors": ["CloudController Failure: Space could not be found"] + "errors": ["CloudController Failure: Space could not be found"] }`)) }) @@ -78,15 +78,15 @@ var _ = Describe("ErrorWriter", func() { writer.Write(recorder, webutil.ParseError{}) Expect(recorder.Code).To(Equal(400)) Expect(recorder.Body).To(MatchJSON(`{ - "errors": ["Request body could not be parsed"] + "errors": ["Request body could not be parsed"] }`)) }) It("returns a 422 when the requests are not valid due to semantically invalid JSON", func() { - writer.Write(recorder, webutil.ValidationError{errors.New("invalid json")}) + writer.Write(recorder, webutil.ValidationError{Err: errors.New("invalid json")}) Expect(recorder.Code).To(Equal(422)) Expect(recorder.Body).To(MatchJSON(`{ - "errors": ["invalid json"] + "errors": ["invalid json"] }`)) }) @@ -94,23 +94,23 @@ var _ = Describe("ErrorWriter", func() { writer.Write(recorder, webutil.NewCriticalNotificationError("raptors")) Expect(recorder.Code).To(Equal(422)) Expect(recorder.Body).To(MatchJSON(`{ - "errors": ["Insufficient privileges to send notification raptors"] + "errors": ["Insufficient privileges to send notification raptors"] }`)) }) It("returns a 409 when there is a duplicate record", func() { - writer.Write(recorder, models.DuplicateError{errors.New("duplicate record")}) + writer.Write(recorder, models.DuplicateError{Err: errors.New("duplicate record")}) Expect(recorder.Code).To(Equal(409)) Expect(recorder.Body).To(MatchJSON(`{ - "errors": ["duplicate record"] + "errors": ["duplicate record"] }`)) }) It("returns a 404 when a record cannot be found", func() { - writer.Write(recorder, models.NotFoundError{errors.New("not found")}) + writer.Write(recorder, models.NotFoundError{Err: errors.New("not found")}) Expect(recorder.Code).To(Equal(404)) Expect(recorder.Body).To(MatchJSON(`{ - "errors": ["not found"] + "errors": ["not found"] }`)) }) @@ -118,20 +118,20 @@ var _ = Describe("ErrorWriter", func() { writer.Write(recorder, services.DefaultScopeError{}) Expect(recorder.Code).To(Equal(406)) Expect(recorder.Body).To(MatchJSON(`{ - "errors": ["You cannot send a notification to a default scope"] + "errors": ["You cannot send a notification to a default scope"] }`)) }) It("returns a 422 when a template cannot be assigned", func() { - writer.Write(recorder, collections.TemplateAssignmentError{errors.New("The template could not be assigned")}) + writer.Write(recorder, collections.TemplateAssignmentError{Err: errors.New("The template could not be assigned")}) Expect(recorder.Code).To(Equal(422)) Expect(recorder.Body).To(MatchJSON(`{ - "errors": ["The template could not be assigned"] + "errors": ["The template could not be assigned"] }`)) }) It("returns a 422 when a user token was expected but is not present", func() { - writer.Write(recorder, webutil.MissingUserTokenError{errors.New("Missing user_id from token claims.")}) + writer.Write(recorder, webutil.MissingUserTokenError{Err: errors.New("Missing user_id from token claims.")}) Expect(recorder.Code).To(Equal(422)) Expect(recorder.Body).To(MatchJSON(`{ "errors": ["Missing user_id from token claims."] diff --git a/vendor/bitbucket.org/chrj/smtpd/example_test.go b/vendor/bitbucket.org/chrj/smtpd/example_test.go deleted file mode 100644 index 611a79b3..00000000 --- a/vendor/bitbucket.org/chrj/smtpd/example_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package smtpd_test - -import ( - "bitbucket.org/chrj/smtpd" - "errors" - "net/smtp" - "strings" -) - -func ExampleServer() { - var server *smtpd.Server - - // No-op server. Accepts and discards - server = &smtpd.Server{} - server.ListenAndServe() - - // Relay server. Accepts only from single IP address and forwards using the Gmail smtp - server = &smtpd.Server{ - - Addr: "0.0.0.0:10025", - - HeloChecker: func(peer smtpd.Peer, name string) error { - if !strings.HasPrefix(peer.Addr.String(), "42.42.42.42:") { - return errors.New("Denied") - } - return nil - }, - - Handler: func(peer smtpd.Peer, env smtpd.Envelope) error { - - return smtp.SendMail( - "smtp.gmail.com:587", - smtp.PlainAuth( - "", - "username@gmail.com", - "password", - "smtp.gmail.com", - ), - env.Sender, - env.Recipients, - env.Data, - ) - - }, - } - - server.ListenAndServe() -} diff --git a/vendor/bitbucket.org/chrj/smtpd/smtpd_test.go b/vendor/bitbucket.org/chrj/smtpd/smtpd_test.go deleted file mode 100644 index 3770744b..00000000 --- a/vendor/bitbucket.org/chrj/smtpd/smtpd_test.go +++ /dev/null @@ -1,1147 +0,0 @@ -package smtpd_test - -import ( - "bitbucket.org/chrj/smtpd" - "crypto/tls" - "errors" - "fmt" - "net" - "net/smtp" - "strings" - "testing" - "time" -) - -var localhostCert = []byte(`-----BEGIN CERTIFICATE----- -MIIBkzCCAT+gAwIBAgIQf4LO8+QzcbXRHJUo6MvX7zALBgkqhkiG9w0BAQswEjEQ -MA4GA1UEChMHQWNtZSBDbzAeFw03MDAxMDEwMDAwMDBaFw04MTA1MjkxNjAwMDBa -MBIxEDAOBgNVBAoTB0FjbWUgQ28wXDANBgkqhkiG9w0BAQEFAANLADBIAkEAx2Uj -2nl0ESnMMrdUOwQnpnIPQzQBX9MIYT87VxhHzImOukWcq5DrmN1ZB//diyrgiCLv -D0udX3YXNHMn1Ki8awIDAQABo3MwcTAOBgNVHQ8BAf8EBAMCAKQwEwYDVR0lBAww -CgYIKwYBBQUHAwEwDwYDVR0TAQH/BAUwAwEB/zA5BgNVHREEMjAwggtleGFtcGxl -LmNvbYIJbG9jYWxob3N0hwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMAsGCSqGSIb3 -DQEBCwNBAGcaB2Il0TIXFcJOdOLGPa6F8qZH1ZHBtVlCBnaJn4vZJGzID+V36Gn0 -hA1AYfGAaF0c43oQofvv+XqQlTe4a+M= ------END CERTIFICATE-----`) - -var localhostKey = []byte(`-----BEGIN RSA PRIVATE KEY----- -MIIBPAIBAAJBAMdlI9p5dBEpzDK3VDsEJ6ZyD0M0AV/TCGE/O1cYR8yJjrpFnKuQ -65jdWQf/3Ysq4Igi7w9LnV92FzRzJ9SovGsCAwEAAQJAVaFw2VWJbAmIQUuMJ+Ar -6wZW2aSO5okpsyHFqSyrQQIcAj/QOq8P83F8J10IreFWNlBlywJU9c7IlJtn/lqq -AQIhAOxHXOxrKPxqTIdIcNnWye/HRQ+5VD54QQr1+M77+bEBAiEA2AmsNNqj2fKj -j2xk+4vnBSY0vrb4q/O3WZ46oorawWsCIQDWdpfzx/i11E6OZMR6FinJSNh4w0Gi -SkjPiCBE0BX+AQIhAI/TiLk7YmBkQG3ovSYW0vvDntPlXpKj08ovJFw4U0D3AiEA -lGjGna4oaauI0CWI6pG0wg4zklTnrDWK7w9h/S/T4e0= ------END RSA PRIVATE KEY-----`) - -func TestSMTP(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{} - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c.Hello("localhost"); err != nil { - t.Fatalf("HELO failed: %v", err) - } - - if supported, _ := c.Extension("AUTH"); supported { - t.Fatal("AUTH supported before TLS") - } - - if supported, _ := c.Extension("8BITMIME"); !supported { - t.Fatal("8BITMIME not supported") - } - - if supported, _ := c.Extension("STARTTLS"); supported { - t.Fatal("STARTTLS supported") - } - - if err := c.Mail("sender@example.org"); err != nil { - t.Fatalf("Mail failed: %v", err) - } - - if err := c.Rcpt("recipient@example.net"); err != nil { - t.Fatalf("Rcpt failed: %v", err) - } - - if err := c.Rcpt("recipient2@example.net"); err != nil { - t.Fatalf("Rcpt2 failed: %v", err) - } - - wc, err := c.Data() - if err != nil { - t.Fatalf("Data failed: %v", err) - } - - _, err = fmt.Fprintf(wc, "This is the email body") - if err != nil { - t.Fatalf("Data body failed: %v", err) - } - - err = wc.Close() - if err != nil { - t.Fatalf("Data close failed: %v", err) - } - - if err := c.Reset(); err != nil { - t.Fatalf("Reset failed: %v", err) - } - - if err := c.Verify("foobar@example.net"); err == nil { - t.Fatal("Unexpected support for VRFY") - } - - if err := c.Quit(); err != nil { - t.Fatalf("Quit failed: %v", err) - } -} - -func TestListenAndServe(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - addr := ln.Addr().String() - - ln.Close() - - server := &smtpd.Server{Addr: addr} - - go func() { - server.ListenAndServe() - }() - - time.Sleep(100 * time.Millisecond) - - c, err := smtp.Dial(addr) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c.Quit(); err != nil { - t.Fatalf("Quit failed: %v", err) - } - -} - -func TestSTARTTLS(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - cert, err := tls.X509KeyPair(localhostCert, localhostKey) - if err != nil { - t.Fatalf("Cert load failed: %v", err) - } - - server := &smtpd.Server{ - Authenticator: func(peer smtpd.Peer, username, password string) error { return nil }, - TLSConfig: &tls.Config{ - Certificates: []tls.Certificate{cert}, - }, - ForceTLS: true, - } - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if supported, _ := c.Extension("AUTH"); supported { - t.Fatal("AUTH supported before TLS") - } - - if err := c.Mail("sender@example.org"); err == nil { - t.Fatal("Mail workded before TLS with ForceTLS") - } - - if err := c.StartTLS(&tls.Config{InsecureSkipVerify: true}); err != nil { - t.Fatalf("STARTTLS failed: %v", err) - } - - if err := c.StartTLS(&tls.Config{InsecureSkipVerify: true}); err == nil { - t.Fatal("STARTTLS worked twice") - } - - if supported, _ := c.Extension("AUTH"); !supported { - t.Fatal("AUTH not supported after TLS") - } - - if _, mechs := c.Extension("AUTH"); !strings.Contains(mechs, "PLAIN") { - t.Fatal("PLAIN AUTH not supported after TLS") - } - - if _, mechs := c.Extension("AUTH"); !strings.Contains(mechs, "LOGIN") { - t.Fatal("LOGIN AUTH not supported after TLS") - } - - if err := c.Auth(smtp.PlainAuth("foo", "foo", "bar", "127.0.0.1")); err != nil { - t.Fatalf("Auth failed: %v", err) - } - - if err := c.Mail("sender@example.org"); err != nil { - t.Fatalf("Mail failed: %v", err) - } - - if err := c.Rcpt("recipient@example.net"); err != nil { - t.Fatalf("Rcpt failed: %v", err) - } - - if err := c.Rcpt("recipient2@example.net"); err != nil { - t.Fatalf("Rcpt2 failed: %v", err) - } - - wc, err := c.Data() - if err != nil { - t.Fatalf("Data failed: %v", err) - } - - _, err = fmt.Fprintf(wc, "This is the email body") - if err != nil { - t.Fatalf("Data body failed: %v", err) - } - - err = wc.Close() - if err != nil { - t.Fatalf("Data close failed: %v", err) - } - - if err := c.Quit(); err != nil { - t.Fatalf("Quit failed: %v", err) - } -} - -func TestAuthRejection(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - cert, err := tls.X509KeyPair(localhostCert, localhostKey) - if err != nil { - t.Fatalf("Cert load failed: %v", err) - } - - server := &smtpd.Server{ - Authenticator: func(peer smtpd.Peer, username, password string) error { - return smtpd.Error{Code: 550, Message: "Denied"} - }, - TLSConfig: &tls.Config{ - Certificates: []tls.Certificate{cert}, - }, - ForceTLS: true, - } - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c.StartTLS(&tls.Config{InsecureSkipVerify: true}); err != nil { - t.Fatalf("STARTTLS failed: %v", err) - } - - if err := c.Auth(smtp.PlainAuth("foo", "foo", "bar", "127.0.0.1")); err == nil { - t.Fatal("Auth worked despite rejection") - } - -} - -func TestAuthNotSupported(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - cert, err := tls.X509KeyPair(localhostCert, localhostKey) - if err != nil { - t.Fatalf("Cert load failed: %v", err) - } - - server := &smtpd.Server{ - TLSConfig: &tls.Config{ - Certificates: []tls.Certificate{cert}, - }, - ForceTLS: true, - } - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c.StartTLS(&tls.Config{InsecureSkipVerify: true}); err != nil { - t.Fatalf("STARTTLS failed: %v", err) - } - - if err := c.Auth(smtp.PlainAuth("foo", "foo", "bar", "127.0.0.1")); err == nil { - t.Fatal("Auth worked despite no authenticator") - } - -} - -func TestConnectionCheck(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{ - ConnectionChecker: func(peer smtpd.Peer) error { - return smtpd.Error{Code: 552, Message: "Denied"} - }, - } - - go func() { - server.Serve(ln) - }() - - if _, err := smtp.Dial(ln.Addr().String()); err == nil { - t.Fatal("Dial succeeded despite ConnectionCheck") - } - -} - -func TestConnectionCheckSimpleError(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{ - ConnectionChecker: func(peer smtpd.Peer) error { - return errors.New("Denied") - }, - } - - go func() { - server.Serve(ln) - }() - - if _, err := smtp.Dial(ln.Addr().String()); err == nil { - t.Fatal("Dial succeeded despite ConnectionCheck") - } - -} - -func TestHELOCheck(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{ - HeloChecker: func(peer smtpd.Peer, name string) error { - if name != "foobar.local" { - t.Fatal("Wrong HELO name") - } - return smtpd.Error{Code: 552, Message: "Denied"} - }, - } - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c.Hello("foobar.local"); err == nil { - t.Fatal("Unexpected HELO success") - } - -} - -func TestSenderCheck(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{ - SenderChecker: func(peer smtpd.Peer, addr string) error { - return smtpd.Error{Code: 552, Message: "Denied"} - }, - } - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c.Mail("sender@example.org"); err == nil { - t.Fatal("Unexpected MAIL success") - } - -} - -func TestRecipientCheck(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{ - RecipientChecker: func(peer smtpd.Peer, addr string) error { - return smtpd.Error{Code: 552, Message: "Denied"} - }, - } - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c.Mail("sender@example.org"); err != nil { - t.Fatalf("Mail failed: %v", err) - } - - if err := c.Rcpt("recipient@example.net"); err == nil { - t.Fatal("Unexpected RCPT success") - } - -} - -func TestMaxMessageSize(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{ - MaxMessageSize: 5, - } - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c.Mail("sender@example.org"); err != nil { - t.Fatalf("MAIL failed: %v", err) - } - - if err := c.Rcpt("recipient@example.net"); err != nil { - t.Fatalf("RCPT failed: %v", err) - } - - wc, err := c.Data() - if err != nil { - t.Fatalf("Data failed: %v", err) - } - - _, err = fmt.Fprintf(wc, "This is the email body") - if err != nil { - t.Fatalf("Data body failed: %v", err) - } - - err = wc.Close() - if err == nil { - t.Fatal("Allowed message larger than 5 bytes to pass.") - } - - if err := c.Quit(); err != nil { - t.Fatalf("QUIT failed: %v", err) - } - -} - -func TestHandler(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{ - Handler: func(peer smtpd.Peer, env smtpd.Envelope) error { - if env.Sender != "sender@example.org" { - t.Fatalf("Unknown sender: %v", env.Sender) - } - if len(env.Recipients) != 1 { - t.Fatalf("Too many recipients: %d", len(env.Recipients)) - } - if env.Recipients[0] != "recipient@example.net" { - t.Fatalf("Unknown recipient: %v", env.Recipients[0]) - } - if string(env.Data) != "This is the email body\n" { - t.Fatalf("Wrong message body: %v", string(env.Data)) - } - return nil - }, - } - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c.Mail("sender@example.org"); err != nil { - t.Fatalf("MAIL failed: %v", err) - } - - if err := c.Rcpt("recipient@example.net"); err != nil { - t.Fatalf("RCPT failed: %v", err) - } - - wc, err := c.Data() - if err != nil { - t.Fatalf("Data failed: %v", err) - } - - _, err = fmt.Fprintf(wc, "This is the email body") - if err != nil { - t.Fatalf("Data body failed: %v", err) - } - - err = wc.Close() - if err != nil { - t.Fatalf("Data close failed: %v", err) - } - - if err := c.Quit(); err != nil { - t.Fatalf("QUIT failed: %v", err) - } - -} - -func TestRejectHandler(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{ - Handler: func(peer smtpd.Peer, env smtpd.Envelope) error { - return smtpd.Error{Code: 550, Message: "Rejected"} - }, - } - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c.Mail("sender@example.org"); err != nil { - t.Fatalf("MAIL failed: %v", err) - } - - if err := c.Rcpt("recipient@example.net"); err != nil { - t.Fatalf("RCPT failed: %v", err) - } - - wc, err := c.Data() - if err != nil { - t.Fatalf("Data failed: %v", err) - } - - _, err = fmt.Fprintf(wc, "This is the email body") - if err != nil { - t.Fatalf("Data body failed: %v", err) - } - - err = wc.Close() - if err == nil { - t.Fatal("Unexpected accept of data") - } - - if err := c.Quit(); err != nil { - t.Fatalf("QUIT failed: %v", err) - } - -} - -func TestMaxConnections(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{ - MaxConnections: 1, - } - - go func() { - server.Serve(ln) - }() - - c1, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - _, err = smtp.Dial(ln.Addr().String()) - if err == nil { - t.Fatal("Dial succeeded despite MaxConnections = 1") - } - - c1.Close() -} - -func TestNoMaxConnections(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{ - MaxConnections: -1, - } - - go func() { - server.Serve(ln) - }() - - c1, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - c1.Close() -} - -func TestMaxRecipients(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{ - MaxRecipients: 1, - } - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c.Mail("sender@example.org"); err != nil { - t.Fatalf("MAIL failed: %v", err) - } - - if err := c.Rcpt("recipient@example.net"); err != nil { - t.Fatalf("RCPT failed: %v", err) - } - - if err := c.Rcpt("recipient@example.net"); err == nil { - t.Fatal("RCPT succeeded despite MaxRecipients = 1") - } - - if err := c.Quit(); err != nil { - t.Fatalf("QUIT failed: %v", err) - } - -} - -func TestInvalidHelo(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{} - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c.Hello(""); err == nil { - t.Fatal("Unexpected HELO success") - } - -} - -func TestInvalidSender(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{} - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c.Mail("invalid@@example.org"); err == nil { - t.Fatal("Unexpected MAIL success") - } - -} - -func TestInvalidRecipient(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{} - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c.Mail("sender@example.org"); err != nil { - t.Fatalf("Mail failed: %v", err) - } - - if err := c.Rcpt("invalid@@example.org"); err == nil { - t.Fatal("Unexpected RCPT success") - } - -} - -func TestRCPTbeforeMAIL(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{} - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c.Rcpt("recipient@example.net"); err == nil { - t.Fatal("Unexpected RCPT success") - } - -} - -func TestDATAbeforeRCPT(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{ - Handler: func(peer smtpd.Peer, env smtpd.Envelope) error { - return smtpd.Error{Code: 550, Message: "Rejected"} - }, - } - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c.Mail("sender@example.org"); err != nil { - t.Fatalf("MAIL failed: %v", err) - } - - if _, err := c.Data(); err == nil { - t.Fatal("Data accepted despite no recipients") - } - - if err := c.Quit(); err != nil { - t.Fatalf("QUIT failed: %v", err) - } - -} - -func TestInterruptedDATA(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{ - Handler: func(peer smtpd.Peer, env smtpd.Envelope) error { - t.Fatal("Accepted DATA despite disconnection") - return nil - }, - } - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c.Mail("sender@example.org"); err != nil { - t.Fatalf("MAIL failed: %v", err) - } - - if err := c.Rcpt("recipient@example.net"); err != nil { - t.Fatalf("RCPT failed: %v", err) - } - - wc, err := c.Data() - if err != nil { - t.Fatalf("Data failed: %v", err) - } - - _, err = fmt.Fprintf(wc, "This is the email body") - if err != nil { - t.Fatalf("Data body failed: %v", err) - } - - c.Close() - -} - -func TestTimeoutClose(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{ - MaxConnections: 1, - ReadTimeout: time.Second, - WriteTimeout: time.Second, - } - - go func() { - server.Serve(ln) - }() - - c1, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - time.Sleep(time.Second * 2) - - c2, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c1.Mail("sender@example.org"); err == nil { - t.Fatal("MAIL succeeded despite being timed out.") - } - - if err := c2.Mail("sender@example.org"); err != nil { - t.Fatalf("MAIL failed: %v", err) - } - - if err := c2.Quit(); err != nil { - t.Fatalf("Quit failed: %v", err) - } - - c2.Close() -} - -func TestTLSTimeout(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - cert, err := tls.X509KeyPair(localhostCert, localhostKey) - if err != nil { - t.Fatalf("Cert load failed: %v", err) - } - - server := &smtpd.Server{ - TLSConfig: &tls.Config{ - Certificates: []tls.Certificate{cert}, - }, - ReadTimeout: time.Second * 2, - WriteTimeout: time.Second * 2, - } - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c.StartTLS(&tls.Config{InsecureSkipVerify: true}); err != nil { - t.Fatalf("STARTTLS failed: %v", err) - } - - time.Sleep(time.Second) - - if err := c.Mail("sender@example.org"); err != nil { - t.Fatalf("MAIL failed: %v", err) - } - - time.Sleep(time.Second) - - if err := c.Rcpt("recipient@example.net"); err != nil { - t.Fatalf("RCPT failed: %v", err) - } - - time.Sleep(time.Second) - - if err := c.Rcpt("recipient@example.net"); err != nil { - t.Fatalf("RCPT failed: %v", err) - } - - time.Sleep(time.Second) - - if err := c.Quit(); err != nil { - t.Fatalf("Quit failed: %v", err) - } - -} - -func TestLongLine(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{} - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if err := c.Mail(fmt.Sprintf("%s@example.org", strings.Repeat("x", 65*1024))); err == nil { - t.Fatalf("MAIL failed: %v", err) - } - - if err := c.Quit(); err != nil { - t.Fatalf("Quit failed: %v", err) - } - -} - -func TestXCLIENT(t *testing.T) { - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen failed: %v", err) - } - - defer ln.Close() - - server := &smtpd.Server{ - EnableXCLIENT: true, - SenderChecker: func(peer smtpd.Peer, addr string) error { - if peer.HeloName != "new.example.net" { - t.Fatalf("Didn't override HELO name: %v", peer.HeloName) - } - if peer.Addr.String() != "42.42.42.42:4242" { - t.Fatalf("Didn't override IP/Port: %v", peer.Addr) - } - if peer.Username != "newusername" { - t.Fatalf("Didn't override username: %v", peer.Username) - } - if peer.Protocol != smtpd.SMTP { - t.Fatalf("Didn't override protocol: %v", peer.Protocol) - } - return nil - }, - } - - go func() { - server.Serve(ln) - }() - - c, err := smtp.Dial(ln.Addr().String()) - if err != nil { - t.Fatalf("Dial failed: %v", err) - } - - if supported, _ := c.Extension("XCLIENT"); !supported { - t.Fatal("XCLIENT not supported") - } - - id, err := c.Text.Cmd("XCLIENT NAME=ignored ADDR=42.42.42.42 PORT=4242 PROTO=SMTP HELO=new.example.net LOGIN=newusername") - if err != nil { - t.Fatalf("Cmd failed: %v", err) - } - - c.Text.StartResponse(id) - _, _, err = c.Text.ReadResponse(220) - c.Text.EndResponse(id) - - if err != nil { - t.Fatalf("XCLIENT failed: %v", err) - } - - if err := c.Mail("sender@example.org"); err != nil { - t.Fatalf("Mail failed: %v", err) - } - - if err := c.Rcpt("recipient@example.net"); err != nil { - t.Fatalf("Rcpt failed: %v", err) - } - - if err := c.Rcpt("recipient2@example.net"); err != nil { - t.Fatalf("Rcpt2 failed: %v", err) - } - - wc, err := c.Data() - if err != nil { - t.Fatalf("Data failed: %v", err) - } - - _, err = fmt.Fprintf(wc, "This is the email body") - if err != nil { - t.Fatalf("Data body failed: %v", err) - } - - err = wc.Close() - if err != nil { - t.Fatalf("Data close failed: %v", err) - } - - if err := c.Quit(); err != nil { - t.Fatalf("Quit failed: %v", err) - } - -} diff --git a/vendor/github.com/DATA-DOG/go-sqlmock/argument_test.go b/vendor/github.com/DATA-DOG/go-sqlmock/argument_test.go deleted file mode 100644 index 0e0d13b2..00000000 --- a/vendor/github.com/DATA-DOG/go-sqlmock/argument_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package sqlmock - -import ( - "database/sql/driver" - "testing" - "time" -) - -type AnyTime struct{} - -// Match satisfies sqlmock.Argument interface -func (a AnyTime) Match(v driver.Value) bool { - _, ok := v.(time.Time) - return ok -} - -func TestAnyTimeArgument(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - mock.ExpectExec("INSERT INTO users"). - WithArgs("john", AnyTime{}). - WillReturnResult(NewResult(1, 1)) - - _, err = db.Exec("INSERT INTO users(name, created_at) VALUES (?, ?)", "john", time.Now()) - if err != nil { - t.Errorf("error '%s' was not expected, while inserting a row", err) - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestByteSliceArgument(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - username := []byte("user") - mock.ExpectExec("INSERT INTO users").WithArgs(username).WillReturnResult(NewResult(1, 1)) - - _, err = db.Exec("INSERT INTO users(username) VALUES (?)", username) - if err != nil { - t.Errorf("error '%s' was not expected, while inserting a row", err) - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} diff --git a/vendor/github.com/DATA-DOG/go-sqlmock/driver_test.go b/vendor/github.com/DATA-DOG/go-sqlmock/driver_test.go deleted file mode 100644 index 4f805ba3..00000000 --- a/vendor/github.com/DATA-DOG/go-sqlmock/driver_test.go +++ /dev/null @@ -1,112 +0,0 @@ -package sqlmock - -import ( - "fmt" - "testing" -) - -type void struct{} - -func (void) Print(...interface{}) {} - -func ExampleNew() { - db, mock, err := New() - if err != nil { - fmt.Println("expected no error, but got:", err) - return - } - defer db.Close() - // now we can expect operations performed on db - mock.ExpectBegin().WillReturnError(fmt.Errorf("an error will occur on db.Begin() call")) -} - -func TestShouldOpenConnectionIssue15(t *testing.T) { - db, mock, err := New() - if err != nil { - t.Errorf("expected no error, but got: %s", err) - } - if len(pool.conns) != 1 { - t.Errorf("expected 1 connection in pool, but there is: %d", len(pool.conns)) - } - - smock, _ := mock.(*sqlmock) - if smock.opened != 1 { - t.Errorf("expected 1 connection on mock to be opened, but there is: %d", smock.opened) - } - - // defer so the rows gets closed first - defer func() { - if smock.opened != 0 { - t.Errorf("expected no connections on mock to be opened, but there is: %d", smock.opened) - } - }() - - mock.ExpectQuery("SELECT").WillReturnRows(NewRows([]string{"one", "two"}).AddRow("val1", "val2")) - rows, err := db.Query("SELECT") - if err != nil { - t.Errorf("unexpected error: %s", err) - } - defer rows.Close() - - mock.ExpectExec("UPDATE").WillReturnResult(NewResult(1, 1)) - if _, err = db.Exec("UPDATE"); err != nil { - t.Errorf("unexpected error: %s", err) - } - - // now there should be two connections open - if smock.opened != 2 { - t.Errorf("expected 2 connection on mock to be opened, but there is: %d", smock.opened) - } - - mock.ExpectClose() - if err = db.Close(); err != nil { - t.Errorf("expected no error on close, but got: %s", err) - } - - // one is still reserved for rows - if smock.opened != 1 { - t.Errorf("expected 1 connection on mock to be still reserved for rows, but there is: %d", smock.opened) - } -} - -func TestTwoOpenConnectionsOnTheSameDSN(t *testing.T) { - db, mock, err := New() - if err != nil { - t.Errorf("expected no error, but got: %s", err) - } - db2, mock2, err := New() - if err != nil { - t.Errorf("expected no error, but got: %s", err) - } - if len(pool.conns) != 2 { - t.Errorf("expected 2 connection in pool, but there is: %d", len(pool.conns)) - } - - if db == db2 { - t.Errorf("expected not the same database instance, but it is the same") - } - if mock == mock2 { - t.Errorf("expected not the same mock instance, but it is the same") - } -} - -func TestWrongDSN(t *testing.T) { - t.Parallel() - db, _, _ := New() - defer db.Close() - if _, err := db.Driver().Open("wrong_dsn"); err == nil { - t.Error("expected error on Open") - } -} - -func TestNewDSN(t *testing.T) { - if _, _, err := NewWithDSN("sqlmock_db_99"); err != nil { - t.Errorf("expected no error on NewWithDSN, but got: %s", err) - } -} - -func TestDuplicateNewDSN(t *testing.T) { - if _, _, err := NewWithDSN("sqlmock_db_1"); err == nil { - t.Error("expected error on NewWithDSN") - } -} diff --git a/vendor/github.com/DATA-DOG/go-sqlmock/expectations_go18_test.go b/vendor/github.com/DATA-DOG/go-sqlmock/expectations_go18_test.go deleted file mode 100644 index 5f30d2ff..00000000 --- a/vendor/github.com/DATA-DOG/go-sqlmock/expectations_go18_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// +build go1.8 - -package sqlmock - -import ( - "database/sql" - "database/sql/driver" - "testing" -) - -func TestQueryExpectationNamedArgComparison(t *testing.T) { - e := &queryBasedExpectation{} - against := []namedValue{{Value: int64(5), Name: "id"}} - if err := e.argsMatches(against); err != nil { - t.Errorf("arguments should match, since the no expectation was set, but got err: %s", err) - } - - e.args = []driver.Value{ - sql.Named("id", 5), - sql.Named("s", "str"), - } - - if err := e.argsMatches(against); err == nil { - t.Error("arguments should not match, since the size is not the same") - } - - against = []namedValue{ - {Value: int64(5), Name: "id"}, - {Value: "str", Name: "s"}, - } - - if err := e.argsMatches(against); err != nil { - t.Errorf("arguments should have matched, but it did not: %v", err) - } - - against = []namedValue{ - {Value: int64(5), Name: "id"}, - {Value: "str", Name: "username"}, - } - - if err := e.argsMatches(against); err == nil { - t.Error("arguments matched, but it should have not due to Name") - } - - e.args = []driver.Value{int64(5), "str"} - - against = []namedValue{ - {Value: int64(5), Ordinal: 0}, - {Value: "str", Ordinal: 1}, - } - - if err := e.argsMatches(against); err == nil { - t.Error("arguments matched, but it should have not due to wrong Ordinal position") - } - - against = []namedValue{ - {Value: int64(5), Ordinal: 1}, - {Value: "str", Ordinal: 2}, - } - - if err := e.argsMatches(against); err != nil { - t.Errorf("arguments should have matched, but it did not: %v", err) - } -} diff --git a/vendor/github.com/DATA-DOG/go-sqlmock/expectations_test.go b/vendor/github.com/DATA-DOG/go-sqlmock/expectations_test.go deleted file mode 100644 index 2e3c097b..00000000 --- a/vendor/github.com/DATA-DOG/go-sqlmock/expectations_test.go +++ /dev/null @@ -1,154 +0,0 @@ -package sqlmock - -import ( - "database/sql/driver" - "fmt" - "regexp" - "testing" - "time" -) - -func TestQueryExpectationArgComparison(t *testing.T) { - e := &queryBasedExpectation{} - against := []namedValue{{Value: int64(5), Ordinal: 1}} - if err := e.argsMatches(against); err != nil { - t.Errorf("arguments should match, since the no expectation was set, but got err: %s", err) - } - - e.args = []driver.Value{5, "str"} - - against = []namedValue{{Value: int64(5), Ordinal: 1}} - if err := e.argsMatches(against); err == nil { - t.Error("arguments should not match, since the size is not the same") - } - - against = []namedValue{ - {Value: int64(3), Ordinal: 1}, - {Value: "str", Ordinal: 2}, - } - if err := e.argsMatches(against); err == nil { - t.Error("arguments should not match, since the first argument (int value) is different") - } - - against = []namedValue{ - {Value: int64(5), Ordinal: 1}, - {Value: "st", Ordinal: 2}, - } - if err := e.argsMatches(against); err == nil { - t.Error("arguments should not match, since the second argument (string value) is different") - } - - against = []namedValue{ - {Value: int64(5), Ordinal: 1}, - {Value: "str", Ordinal: 2}, - } - if err := e.argsMatches(against); err != nil { - t.Errorf("arguments should match, but it did not: %s", err) - } - - const longForm = "Jan 2, 2006 at 3:04pm (MST)" - tm, _ := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)") - e.args = []driver.Value{5, tm} - - against = []namedValue{ - {Value: int64(5), Ordinal: 1}, - {Value: tm, Ordinal: 2}, - } - if err := e.argsMatches(against); err != nil { - t.Error("arguments should match, but it did not") - } - - e.args = []driver.Value{5, AnyArg()} - if err := e.argsMatches(against); err != nil { - t.Errorf("arguments should match, but it did not: %s", err) - } -} - -func TestQueryExpectationArgComparisonBool(t *testing.T) { - var e *queryBasedExpectation - - e = &queryBasedExpectation{args: []driver.Value{true}} - against := []namedValue{ - {Value: true, Ordinal: 1}, - } - if err := e.argsMatches(against); err != nil { - t.Error("arguments should match, since arguments are the same") - } - - e = &queryBasedExpectation{args: []driver.Value{false}} - against = []namedValue{ - {Value: false, Ordinal: 1}, - } - if err := e.argsMatches(against); err != nil { - t.Error("arguments should match, since argument are the same") - } - - e = &queryBasedExpectation{args: []driver.Value{true}} - against = []namedValue{ - {Value: false, Ordinal: 1}, - } - if err := e.argsMatches(against); err == nil { - t.Error("arguments should not match, since argument is different") - } - - e = &queryBasedExpectation{args: []driver.Value{false}} - against = []namedValue{ - {Value: true, Ordinal: 1}, - } - if err := e.argsMatches(against); err == nil { - t.Error("arguments should not match, since argument is different") - } -} - -func TestQueryExpectationSqlMatch(t *testing.T) { - e := &ExpectedExec{} - - e.sqlRegex = regexp.MustCompile("SELECT x FROM") - if !e.queryMatches("SELECT x FROM someting") { - t.Errorf("Sql must have matched the query") - } - - e.sqlRegex = regexp.MustCompile("SELECT COUNT\\(x\\) FROM") - if !e.queryMatches("SELECT COUNT(x) FROM someting") { - t.Errorf("Sql must have matched the query") - } -} - -func ExampleExpectedExec() { - db, mock, _ := New() - result := NewErrorResult(fmt.Errorf("some error")) - mock.ExpectExec("^INSERT (.+)").WillReturnResult(result) - res, _ := db.Exec("INSERT something") - _, err := res.LastInsertId() - fmt.Println(err) - // Output: some error -} - -func TestBuildQuery(t *testing.T) { - db, mock, _ := New() - query := ` - SELECT - name, - email, - address, - anotherfield - FROM user - where - name = 'John' - and - address = 'Jakarta' - - ` - - mock.ExpectQuery(query) - mock.ExpectExec(query) - mock.ExpectPrepare(query) - - db.QueryRow(query) - db.Exec(query) - db.Prepare(query) - - if err := mock.ExpectationsWereMet(); err != nil { - t.Error(err) - } -} diff --git a/vendor/github.com/DATA-DOG/go-sqlmock/result_test.go b/vendor/github.com/DATA-DOG/go-sqlmock/result_test.go deleted file mode 100644 index e0214c51..00000000 --- a/vendor/github.com/DATA-DOG/go-sqlmock/result_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package sqlmock - -import ( - "fmt" - "testing" -) - -// used for examples -var mock = &sqlmock{} - -func ExampleNewErrorResult() { - db, mock, _ := New() - result := NewErrorResult(fmt.Errorf("some error")) - mock.ExpectExec("^INSERT (.+)").WillReturnResult(result) - res, _ := db.Exec("INSERT something") - _, err := res.LastInsertId() - fmt.Println(err) - // Output: some error -} - -func ExampleNewResult() { - var lastInsertID, affected int64 - result := NewResult(lastInsertID, affected) - mock.ExpectExec("^INSERT (.+)").WillReturnResult(result) - fmt.Println(mock.ExpectationsWereMet()) - // Output: there is a remaining expectation which was not matched: ExpectedExec => expecting Exec or ExecContext which: - // - matches sql: '^INSERT (.+)' - // - is without arguments - // - should return Result having: - // LastInsertId: 0 - // RowsAffected: 0 -} - -func TestShouldReturnValidSqlDriverResult(t *testing.T) { - result := NewResult(1, 2) - id, err := result.LastInsertId() - if 1 != id { - t.Errorf("Expected last insert id to be 1, but got: %d", id) - } - if err != nil { - t.Errorf("expected no error, but got: %s", err) - } - affected, err := result.RowsAffected() - if 2 != affected { - t.Errorf("Expected affected rows to be 2, but got: %d", affected) - } - if err != nil { - t.Errorf("expected no error, but got: %s", err) - } -} - -func TestShouldReturnErroeSqlDriverResult(t *testing.T) { - result := NewErrorResult(fmt.Errorf("some error")) - _, err := result.LastInsertId() - if err == nil { - t.Error("expected error, but got none") - } - _, err = result.RowsAffected() - if err == nil { - t.Error("expected error, but got none") - } -} diff --git a/vendor/github.com/DATA-DOG/go-sqlmock/rows_go18_test.go b/vendor/github.com/DATA-DOG/go-sqlmock/rows_go18_test.go deleted file mode 100644 index c776defe..00000000 --- a/vendor/github.com/DATA-DOG/go-sqlmock/rows_go18_test.go +++ /dev/null @@ -1,92 +0,0 @@ -// +build go1.8 - -package sqlmock - -import ( - "fmt" - "testing" -) - -func TestQueryMultiRows(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - rs1 := NewRows([]string{"id", "title"}).AddRow(5, "hello world") - rs2 := NewRows([]string{"name"}).AddRow("gopher").AddRow("john").AddRow("jane").RowError(2, fmt.Errorf("error")) - - mock.ExpectQuery("SELECT (.+) FROM articles WHERE id = \\?;SELECT name FROM users"). - WithArgs(5). - WillReturnRows(rs1, rs2) - - rows, err := db.Query("SELECT id, title FROM articles WHERE id = ?;SELECT name FROM users", 5) - if err != nil { - t.Errorf("error was not expected, but got: %v", err) - } - defer rows.Close() - - if !rows.Next() { - t.Error("expected a row to be available in first result set") - } - - var id int - var name string - - err = rows.Scan(&id, &name) - if err != nil { - t.Errorf("error was not expected, but got: %v", err) - } - - if id != 5 || name != "hello world" { - t.Errorf("unexpected row values id: %v name: %v", id, name) - } - - if rows.Next() { - t.Error("was not expecting next row in first result set") - } - - if !rows.NextResultSet() { - t.Error("had to have next result set") - } - - if !rows.Next() { - t.Error("expected a row to be available in second result set") - } - - err = rows.Scan(&name) - if err != nil { - t.Errorf("error was not expected, but got: %v", err) - } - - if name != "gopher" { - t.Errorf("unexpected row name: %v", name) - } - - if !rows.Next() { - t.Error("expected a row to be available in second result set") - } - - err = rows.Scan(&name) - if err != nil { - t.Errorf("error was not expected, but got: %v", err) - } - - if name != "john" { - t.Errorf("unexpected row name: %v", name) - } - - if rows.Next() { - t.Error("expected next row to produce error") - } - - if rows.Err() == nil { - t.Error("expected an error, but there was none") - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} diff --git a/vendor/github.com/DATA-DOG/go-sqlmock/rows_test.go b/vendor/github.com/DATA-DOG/go-sqlmock/rows_test.go deleted file mode 100644 index a508a0bf..00000000 --- a/vendor/github.com/DATA-DOG/go-sqlmock/rows_test.go +++ /dev/null @@ -1,285 +0,0 @@ -package sqlmock - -import ( - "database/sql" - "fmt" - "testing" -) - -func ExampleRows() { - db, mock, err := New() - if err != nil { - fmt.Println("failed to open sqlmock database:", err) - } - defer db.Close() - - rows := NewRows([]string{"id", "title"}). - AddRow(1, "one"). - AddRow(2, "two") - - mock.ExpectQuery("SELECT").WillReturnRows(rows) - - rs, _ := db.Query("SELECT") - defer rs.Close() - - for rs.Next() { - var id int - var title string - rs.Scan(&id, &title) - fmt.Println("scanned id:", id, "and title:", title) - } - - if rs.Err() != nil { - fmt.Println("got rows error:", rs.Err()) - } - // Output: scanned id: 1 and title: one - // scanned id: 2 and title: two -} - -func ExampleRows_rowError() { - db, mock, err := New() - if err != nil { - fmt.Println("failed to open sqlmock database:", err) - } - defer db.Close() - - rows := NewRows([]string{"id", "title"}). - AddRow(0, "one"). - AddRow(1, "two"). - RowError(1, fmt.Errorf("row error")) - mock.ExpectQuery("SELECT").WillReturnRows(rows) - - rs, _ := db.Query("SELECT") - defer rs.Close() - - for rs.Next() { - var id int - var title string - rs.Scan(&id, &title) - fmt.Println("scanned id:", id, "and title:", title) - } - - if rs.Err() != nil { - fmt.Println("got rows error:", rs.Err()) - } - // Output: scanned id: 0 and title: one - // got rows error: row error -} - -func ExampleRows_closeError() { - db, mock, err := New() - if err != nil { - fmt.Println("failed to open sqlmock database:", err) - } - defer db.Close() - - rows := NewRows([]string{"id", "title"}).CloseError(fmt.Errorf("close error")) - mock.ExpectQuery("SELECT").WillReturnRows(rows) - - rs, _ := db.Query("SELECT") - - // Note: that close will return error only before rows EOF - // that is a default sql package behavior. If you run rs.Next() - // it will handle the error internally and return nil bellow - if err := rs.Close(); err != nil { - fmt.Println("got error:", err) - } - - // Output: got error: close error -} - -func TestAllowsToSetRowsErrors(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - rows := NewRows([]string{"id", "title"}). - AddRow(0, "one"). - AddRow(1, "two"). - RowError(1, fmt.Errorf("error")) - mock.ExpectQuery("SELECT").WillReturnRows(rows) - - rs, err := db.Query("SELECT") - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - defer rs.Close() - - if !rs.Next() { - t.Fatal("expected the first row to be available") - } - if rs.Err() != nil { - t.Fatalf("unexpected error: %s", rs.Err()) - } - - if rs.Next() { - t.Fatal("was not expecting the second row, since there should be an error") - } - if rs.Err() == nil { - t.Fatal("expected an error, but got none") - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Fatal(err) - } -} - -func TestRowsCloseError(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - rows := NewRows([]string{"id"}).CloseError(fmt.Errorf("close error")) - mock.ExpectQuery("SELECT").WillReturnRows(rows) - - rs, err := db.Query("SELECT") - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - - if err := rs.Close(); err == nil { - t.Fatal("expected a close error") - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Fatal(err) - } -} - -func TestQuerySingleRow(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - rows := NewRows([]string{"id"}). - AddRow(1). - AddRow(2) - mock.ExpectQuery("SELECT").WillReturnRows(rows) - - var id int - if err := db.QueryRow("SELECT").Scan(&id); err != nil { - t.Fatalf("unexpected error: %s", err) - } - - mock.ExpectQuery("SELECT").WillReturnRows(NewRows([]string{"id"})) - if err := db.QueryRow("SELECT").Scan(&id); err != sql.ErrNoRows { - t.Fatal("expected sql no rows error") - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Fatal(err) - } -} - -func TestRowsScanError(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - r := NewRows([]string{"col1", "col2"}).AddRow("one", "two").AddRow("one", nil) - mock.ExpectQuery("SELECT").WillReturnRows(r) - - rs, err := db.Query("SELECT") - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - defer rs.Close() - - var one, two string - if !rs.Next() || rs.Err() != nil || rs.Scan(&one, &two) != nil { - t.Fatal("unexpected error on first row scan") - } - - if !rs.Next() || rs.Err() != nil { - t.Fatal("unexpected error on second row read") - } - - err = rs.Scan(&one, &two) - if err == nil { - t.Fatal("expected an error for scan, but got none") - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Fatal(err) - } -} - -func TestCSVRowParser(t *testing.T) { - t.Parallel() - rs := NewRows([]string{"col1", "col2"}).FromCSVString("a,NULL") - db, mock, err := New() - if err != nil { - t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - mock.ExpectQuery("SELECT").WillReturnRows(rs) - - rw, err := db.Query("SELECT") - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - defer rw.Close() - var col1 string - var col2 []byte - - rw.Next() - if err = rw.Scan(&col1, &col2); err != nil { - t.Fatalf("unexpected error: %s", err) - } - if col1 != "a" { - t.Fatalf("expected col1 to be 'a', but got [%T]:%+v", col1, col1) - } - if col2 != nil { - t.Fatalf("expected col2 to be nil, but got [%T]:%+v", col2, col2) - } -} - -func TestWrongNumberOfValues(t *testing.T) { - // Open new mock database - db, mock, err := New() - if err != nil { - fmt.Println("error creating mock database") - return - } - defer db.Close() - defer func() { - recover() - }() - mock.ExpectQuery("SELECT ID FROM TABLE").WithArgs(101).WillReturnRows(NewRows([]string{"ID"}).AddRow(101, "Hello")) - db.Query("SELECT ID FROM TABLE", 101) - // shouldn't reach here - t.Error("expected panic from query") -} - -func TestEmptyRowSets(t *testing.T) { - rs1 := NewRows([]string{"a"}).AddRow("a") - rs2 := NewRows([]string{"b"}) - rs3 := NewRows([]string{"c"}) - - set1 := &rowSets{sets: []*Rows{rs1, rs2}} - set2 := &rowSets{sets: []*Rows{rs3, rs2}} - set3 := &rowSets{sets: []*Rows{rs2}} - - if set1.empty() { - t.Fatalf("expected rowset 1, not to be empty, but it was") - } - if !set2.empty() { - t.Fatalf("expected rowset 2, to be empty, but it was not") - } - if !set3.empty() { - t.Fatalf("expected rowset 3, to be empty, but it was not") - } -} diff --git a/vendor/github.com/DATA-DOG/go-sqlmock/sqlmock_go18_test.go b/vendor/github.com/DATA-DOG/go-sqlmock/sqlmock_go18_test.go deleted file mode 100644 index e53d9c74..00000000 --- a/vendor/github.com/DATA-DOG/go-sqlmock/sqlmock_go18_test.go +++ /dev/null @@ -1,476 +0,0 @@ -// +build go1.8 - -package sqlmock - -import ( - "context" - "database/sql" - "errors" - "testing" - "time" -) - -func TestContextExecCancel(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - mock.ExpectExec("DELETE FROM users"). - WillDelayFor(time.Second). - WillReturnResult(NewResult(1, 1)) - - ctx, cancel := context.WithCancel(context.Background()) - - go func() { - time.Sleep(time.Millisecond * 10) - cancel() - }() - - _, err = db.ExecContext(ctx, "DELETE FROM users") - if err == nil { - t.Error("error was expected, but there was none") - } - - if err != ErrCancelled { - t.Errorf("was expecting cancel error, but got: %v", err) - } - - _, err = db.ExecContext(ctx, "DELETE FROM users") - if err != context.Canceled { - t.Error("error was expected since context was already done, but there was none") - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestPreparedStatementContextExecCancel(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - mock.ExpectPrepare("DELETE FROM users"). - ExpectExec(). - WillDelayFor(time.Second). - WillReturnResult(NewResult(1, 1)) - - ctx, cancel := context.WithCancel(context.Background()) - - go func() { - time.Sleep(time.Millisecond * 10) - cancel() - }() - - stmt, err := db.Prepare("DELETE FROM users") - if err != nil { - t.Errorf("error was not expected, but got: %v", err) - } - - _, err = stmt.ExecContext(ctx) - if err == nil { - t.Error("error was expected, but there was none") - } - - if err != ErrCancelled { - t.Errorf("was expecting cancel error, but got: %v", err) - } - - _, err = stmt.ExecContext(ctx) - if err != context.Canceled { - t.Error("error was expected since context was already done, but there was none") - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestContextExecWithNamedArg(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - mock.ExpectExec("DELETE FROM users"). - WithArgs(sql.Named("id", 5)). - WillDelayFor(time.Second). - WillReturnResult(NewResult(1, 1)) - - ctx, cancel := context.WithCancel(context.Background()) - - go func() { - time.Sleep(time.Millisecond * 10) - cancel() - }() - - _, err = db.ExecContext(ctx, "DELETE FROM users WHERE id = :id", sql.Named("id", 5)) - if err == nil { - t.Error("error was expected, but there was none") - } - - if err != ErrCancelled { - t.Errorf("was expecting cancel error, but got: %v", err) - } - - _, err = db.ExecContext(ctx, "DELETE FROM users WHERE id = :id", sql.Named("id", 5)) - if err != context.Canceled { - t.Error("error was expected since context was already done, but there was none") - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestContextExec(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - mock.ExpectExec("DELETE FROM users"). - WillReturnResult(NewResult(1, 1)) - - ctx, cancel := context.WithCancel(context.Background()) - - go func() { - time.Sleep(time.Millisecond * 10) - cancel() - }() - - res, err := db.ExecContext(ctx, "DELETE FROM users") - if err != nil { - t.Errorf("error was not expected, but got: %v", err) - } - - affected, err := res.RowsAffected() - if affected != 1 { - t.Errorf("expected affected rows 1, but got %v", affected) - } - - if err != nil { - t.Errorf("error was not expected, but got: %v", err) - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestContextQueryCancel(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - rs := NewRows([]string{"id", "title"}).AddRow(5, "hello world") - - mock.ExpectQuery("SELECT (.+) FROM articles WHERE id = ?"). - WithArgs(5). - WillDelayFor(time.Second). - WillReturnRows(rs) - - ctx, cancel := context.WithCancel(context.Background()) - - go func() { - time.Sleep(time.Millisecond * 10) - cancel() - }() - - _, err = db.QueryContext(ctx, "SELECT id, title FROM articles WHERE id = ?", 5) - if err == nil { - t.Error("error was expected, but there was none") - } - - if err != ErrCancelled { - t.Errorf("was expecting cancel error, but got: %v", err) - } - - _, err = db.QueryContext(ctx, "SELECT id, title FROM articles WHERE id = ?", 5) - if err != context.Canceled { - t.Error("error was expected since context was already done, but there was none") - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestPreparedStatementContextQueryCancel(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - rs := NewRows([]string{"id", "title"}).AddRow(5, "hello world") - - mock.ExpectPrepare("SELECT (.+) FROM articles WHERE id = ?"). - ExpectQuery(). - WithArgs(5). - WillDelayFor(time.Second). - WillReturnRows(rs) - - ctx, cancel := context.WithCancel(context.Background()) - - go func() { - time.Sleep(time.Millisecond * 10) - cancel() - }() - - stmt, err := db.Prepare("SELECT id, title FROM articles WHERE id = ?") - if err != nil { - t.Errorf("error was not expected, but got: %v", err) - } - - _, err = stmt.QueryContext(ctx, 5) - if err == nil { - t.Error("error was expected, but there was none") - } - - if err != ErrCancelled { - t.Errorf("was expecting cancel error, but got: %v", err) - } - - _, err = stmt.QueryContext(ctx, 5) - if err != context.Canceled { - t.Error("error was expected since context was already done, but there was none") - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestContextQuery(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - rs := NewRows([]string{"id", "title"}).AddRow(5, "hello world") - - mock.ExpectQuery("SELECT (.+) FROM articles WHERE id ="). - WithArgs(sql.Named("id", 5)). - WillDelayFor(time.Millisecond * 3). - WillReturnRows(rs) - - ctx, cancel := context.WithCancel(context.Background()) - - go func() { - time.Sleep(time.Millisecond * 10) - cancel() - }() - - rows, err := db.QueryContext(ctx, "SELECT id, title FROM articles WHERE id = :id", sql.Named("id", 5)) - if err != nil { - t.Errorf("error was not expected, but got: %v", err) - } - - if !rows.Next() { - t.Error("expected one row, but there was none") - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestContextBeginCancel(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - mock.ExpectBegin().WillDelayFor(time.Second) - - ctx, cancel := context.WithCancel(context.Background()) - - go func() { - time.Sleep(time.Millisecond * 10) - cancel() - }() - - _, err = db.BeginTx(ctx, nil) - if err == nil { - t.Error("error was expected, but there was none") - } - - if err != ErrCancelled { - t.Errorf("was expecting cancel error, but got: %v", err) - } - - _, err = db.BeginTx(ctx, nil) - if err != context.Canceled { - t.Error("error was expected since context was already done, but there was none") - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestContextBegin(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - mock.ExpectBegin().WillDelayFor(time.Millisecond * 3) - - ctx, cancel := context.WithCancel(context.Background()) - - go func() { - time.Sleep(time.Millisecond * 10) - cancel() - }() - - tx, err := db.BeginTx(ctx, nil) - if err != nil { - t.Errorf("error was not expected, but got: %v", err) - } - - if tx == nil { - t.Error("expected tx, but there was nil") - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestContextPrepareCancel(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - mock.ExpectPrepare("SELECT").WillDelayFor(time.Second) - - ctx, cancel := context.WithCancel(context.Background()) - - go func() { - time.Sleep(time.Millisecond * 10) - cancel() - }() - - _, err = db.PrepareContext(ctx, "SELECT") - if err == nil { - t.Error("error was expected, but there was none") - } - - if err != ErrCancelled { - t.Errorf("was expecting cancel error, but got: %v", err) - } - - _, err = db.PrepareContext(ctx, "SELECT") - if err != context.Canceled { - t.Error("error was expected since context was already done, but there was none") - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestContextPrepare(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - mock.ExpectPrepare("SELECT").WillDelayFor(time.Millisecond * 3) - - ctx, cancel := context.WithCancel(context.Background()) - - go func() { - time.Sleep(time.Millisecond * 10) - cancel() - }() - - stmt, err := db.PrepareContext(ctx, "SELECT") - if err != nil { - t.Errorf("error was not expected, but got: %v", err) - } - - if stmt == nil { - t.Error("expected stmt, but there was nil") - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestContextExecErrorDelay(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - // test that return of error is delayed - var delay time.Duration - delay = 100 * time.Millisecond - mock.ExpectExec("^INSERT INTO articles"). - WillReturnError(errors.New("slow fail")). - WillDelayFor(delay) - - start := time.Now() - res, err := db.ExecContext(context.Background(), "INSERT INTO articles (title) VALUES (?)", "hello") - stop := time.Now() - - if res != nil { - t.Errorf("result was not expected, was expecting nil") - } - - if err == nil { - t.Errorf("error was expected, was not expecting nil") - } - - if err.Error() != "slow fail" { - t.Errorf("error '%s' was not expected, was expecting '%s'", err.Error(), "slow fail") - } - - elapsed := stop.Sub(start) - if elapsed < delay { - t.Errorf("expecting a delay of %v before error, actual delay was %v", delay, elapsed) - } - - // also test that return of error is not delayed - mock.ExpectExec("^INSERT INTO articles").WillReturnError(errors.New("fast fail")) - - start = time.Now() - db.ExecContext(context.Background(), "INSERT INTO articles (title) VALUES (?)", "hello") - stop = time.Now() - - elapsed = stop.Sub(start) - if elapsed > delay { - t.Errorf("expecting a delay of less than %v before error, actual delay was %v", delay, elapsed) - } -} diff --git a/vendor/github.com/DATA-DOG/go-sqlmock/sqlmock_test.go b/vendor/github.com/DATA-DOG/go-sqlmock/sqlmock_test.go deleted file mode 100644 index f43a3e77..00000000 --- a/vendor/github.com/DATA-DOG/go-sqlmock/sqlmock_test.go +++ /dev/null @@ -1,1115 +0,0 @@ -package sqlmock - -import ( - "database/sql" - "errors" - "fmt" - "strconv" - "sync" - "testing" - "time" -) - -func cancelOrder(db *sql.DB, orderID int) error { - tx, _ := db.Begin() - _, _ = tx.Query("SELECT * FROM orders {0} FOR UPDATE", orderID) - err := tx.Rollback() - if err != nil { - return err - } - return nil -} - -func Example() { - // Open new mock database - db, mock, err := New() - if err != nil { - fmt.Println("error creating mock database") - return - } - // columns to be used for result - columns := []string{"id", "status"} - // expect transaction begin - mock.ExpectBegin() - // expect query to fetch order, match it with regexp - mock.ExpectQuery("SELECT (.+) FROM orders (.+) FOR UPDATE"). - WithArgs(1). - WillReturnRows(NewRows(columns).AddRow(1, 1)) - // expect transaction rollback, since order status is "cancelled" - mock.ExpectRollback() - - // run the cancel order function - someOrderID := 1 - // call a function which executes expected database operations - err = cancelOrder(db, someOrderID) - if err != nil { - fmt.Printf("unexpected error: %s", err) - return - } - - // ensure all expectations have been met - if err = mock.ExpectationsWereMet(); err != nil { - fmt.Printf("unmet expectation error: %s", err) - } - // Output: -} - -func TestIssue14EscapeSQL(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - mock.ExpectExec("INSERT INTO mytable\\(a, b\\)"). - WithArgs("A", "B"). - WillReturnResult(NewResult(1, 1)) - - _, err = db.Exec("INSERT INTO mytable(a, b) VALUES (?, ?)", "A", "B") - if err != nil { - t.Errorf("error '%s' was not expected, while inserting a row", err) - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -// test the case when db is not triggered and expectations -// are not asserted on close -func TestIssue4(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - mock.ExpectQuery("some sql query which will not be called"). - WillReturnRows(NewRows([]string{"id"})) - - if err := mock.ExpectationsWereMet(); err == nil { - t.Errorf("was expecting an error since query was not triggered") - } -} - -func TestMockQuery(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - rs := NewRows([]string{"id", "title"}).FromCSVString("5,hello world") - - mock.ExpectQuery("SELECT (.+) FROM articles WHERE id = ?"). - WithArgs(5). - WillReturnRows(rs) - - rows, err := db.Query("SELECT (.+) FROM articles WHERE id = ?", 5) - if err != nil { - t.Errorf("error '%s' was not expected while retrieving mock rows", err) - } - - defer func() { - if er := rows.Close(); er != nil { - t.Error("Unexpected error while trying to close rows") - } - }() - - if !rows.Next() { - t.Error("it must have had one row as result, but got empty result set instead") - } - - var id int - var title string - - err = rows.Scan(&id, &title) - if err != nil { - t.Errorf("error '%s' was not expected while trying to scan row", err) - } - - if id != 5 { - t.Errorf("expected mocked id to be 5, but got %d instead", id) - } - - if title != "hello world" { - t.Errorf("expected mocked title to be 'hello world', but got '%s' instead", title) - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestMockQueryTypes(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - columns := []string{"id", "timestamp", "sold"} - - timestamp := time.Now() - rs := NewRows(columns) - rs.AddRow(5, timestamp, true) - - mock.ExpectQuery("SELECT (.+) FROM sales WHERE id = ?"). - WithArgs(5). - WillReturnRows(rs) - - rows, err := db.Query("SELECT (.+) FROM sales WHERE id = ?", 5) - if err != nil { - t.Errorf("error '%s' was not expected while retrieving mock rows", err) - } - defer func() { - if er := rows.Close(); er != nil { - t.Error("Unexpected error while trying to close rows") - } - }() - if !rows.Next() { - t.Error("it must have had one row as result, but got empty result set instead") - } - - var id int - var time time.Time - var sold bool - - err = rows.Scan(&id, &time, &sold) - if err != nil { - t.Errorf("error '%s' was not expected while trying to scan row", err) - } - - if id != 5 { - t.Errorf("expected mocked id to be 5, but got %d instead", id) - } - - if time != timestamp { - t.Errorf("expected mocked time to be %s, but got '%s' instead", timestamp, time) - } - - if sold != true { - t.Errorf("expected mocked boolean to be true, but got %v instead", sold) - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestTransactionExpectations(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - // begin and commit - mock.ExpectBegin() - mock.ExpectCommit() - - tx, err := db.Begin() - if err != nil { - t.Errorf("an error '%s' was not expected when beginning a transaction", err) - } - - err = tx.Commit() - if err != nil { - t.Errorf("an error '%s' was not expected when committing a transaction", err) - } - - // begin and rollback - mock.ExpectBegin() - mock.ExpectRollback() - - tx, err = db.Begin() - if err != nil { - t.Errorf("an error '%s' was not expected when beginning a transaction", err) - } - - err = tx.Rollback() - if err != nil { - t.Errorf("an error '%s' was not expected when rolling back a transaction", err) - } - - // begin with an error - mock.ExpectBegin().WillReturnError(fmt.Errorf("some err")) - - tx, err = db.Begin() - if err == nil { - t.Error("an error was expected when beginning a transaction, but got none") - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestPrepareExpectations(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - mock.ExpectPrepare("SELECT (.+) FROM articles WHERE id = ?") - - stmt, err := db.Prepare("SELECT (.+) FROM articles WHERE id = ?") - if err != nil { - t.Errorf("error '%s' was not expected while creating a prepared statement", err) - } - if stmt == nil { - t.Errorf("stmt was expected while creating a prepared statement") - } - - // expect something else, w/o ExpectPrepare() - var id int - var title string - rs := NewRows([]string{"id", "title"}).FromCSVString("5,hello world") - - mock.ExpectQuery("SELECT (.+) FROM articles WHERE id = ?"). - WithArgs(5). - WillReturnRows(rs) - - err = stmt.QueryRow(5).Scan(&id, &title) - if err != nil { - t.Errorf("error '%s' was not expected while retrieving mock rows", err) - } - - mock.ExpectPrepare("SELECT (.+) FROM articles WHERE id = ?"). - WillReturnError(fmt.Errorf("Some DB error occurred")) - - stmt, err = db.Prepare("SELECT id FROM articles WHERE id = ?") - if err == nil { - t.Error("error was expected while creating a prepared statement") - } - if stmt != nil { - t.Errorf("stmt was not expected while creating a prepared statement returning error") - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestPreparedQueryExecutions(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - mock.ExpectPrepare("SELECT (.+) FROM articles WHERE id = ?") - - rs1 := NewRows([]string{"id", "title"}).FromCSVString("5,hello world") - mock.ExpectQuery("SELECT (.+) FROM articles WHERE id = ?"). - WithArgs(5). - WillReturnRows(rs1) - - rs2 := NewRows([]string{"id", "title"}).FromCSVString("2,whoop") - mock.ExpectQuery("SELECT (.+) FROM articles WHERE id = ?"). - WithArgs(2). - WillReturnRows(rs2) - - stmt, err := db.Prepare("SELECT id, title FROM articles WHERE id = ?") - if err != nil { - t.Errorf("error '%s' was not expected while creating a prepared statement", err) - } - - var id int - var title string - err = stmt.QueryRow(5).Scan(&id, &title) - if err != nil { - t.Errorf("error '%s' was not expected querying row from statement and scanning", err) - } - - if id != 5 { - t.Errorf("expected mocked id to be 5, but got %d instead", id) - } - - if title != "hello world" { - t.Errorf("expected mocked title to be 'hello world', but got '%s' instead", title) - } - - err = stmt.QueryRow(2).Scan(&id, &title) - if err != nil { - t.Errorf("error '%s' was not expected querying row from statement and scanning", err) - } - - if id != 2 { - t.Errorf("expected mocked id to be 2, but got %d instead", id) - } - - if title != "whoop" { - t.Errorf("expected mocked title to be 'whoop', but got '%s' instead", title) - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestUnorderedPreparedQueryExecutions(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - mock.MatchExpectationsInOrder(false) - - mock.ExpectPrepare("SELECT (.+) FROM articles WHERE id = ?"). - ExpectQuery(). - WithArgs(5). - WillReturnRows(NewRows([]string{"id", "title"}).FromCSVString("5,The quick brown fox")) - mock.ExpectPrepare("SELECT (.+) FROM authors WHERE id = ?"). - ExpectQuery(). - WithArgs(1). - WillReturnRows(NewRows([]string{"id", "title"}).FromCSVString("1,Betty B.")) - - var id int - var name string - - stmt, err := db.Prepare("SELECT id, name FROM authors WHERE id = ?") - if err != nil { - t.Errorf("error '%s' was not expected while creating a prepared statement", err) - } - - err = stmt.QueryRow(1).Scan(&id, &name) - if err != nil { - t.Errorf("error '%s' was not expected querying row from statement and scanning", err) - } - - if name != "Betty B." { - t.Errorf("expected mocked name to be 'Betty B.', but got '%s' instead", name) - } -} - -func TestUnexpectedOperations(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - mock.ExpectPrepare("SELECT (.+) FROM articles WHERE id = ?") - stmt, err := db.Prepare("SELECT id, title FROM articles WHERE id = ?") - if err != nil { - t.Errorf("error '%s' was not expected while creating a prepared statement", err) - } - - var id int - var title string - - err = stmt.QueryRow(5).Scan(&id, &title) - if err == nil { - t.Error("error was expected querying row, since there was no such expectation") - } - - mock.ExpectRollback() - - if err := mock.ExpectationsWereMet(); err == nil { - t.Errorf("was expecting an error since query was not triggered") - } -} - -func TestWrongExpectations(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - mock.ExpectBegin() - - rs1 := NewRows([]string{"id", "title"}).FromCSVString("5,hello world") - mock.ExpectQuery("SELECT (.+) FROM articles WHERE id = ?"). - WithArgs(5). - WillReturnRows(rs1) - - mock.ExpectCommit().WillReturnError(fmt.Errorf("deadlock occurred")) - mock.ExpectRollback() // won't be triggered - - var id int - var title string - - err = db.QueryRow("SELECT id, title FROM articles WHERE id = ? FOR UPDATE", 5).Scan(&id, &title) - if err == nil { - t.Error("error was expected while querying row, since there begin transaction expectation is not fulfilled") - } - - // lets go around and start transaction - tx, err := db.Begin() - if err != nil { - t.Errorf("an error '%s' was not expected when beginning a transaction", err) - } - - err = db.QueryRow("SELECT id, title FROM articles WHERE id = ? FOR UPDATE", 5).Scan(&id, &title) - if err != nil { - t.Errorf("error '%s' was not expected while querying row, since transaction was started", err) - } - - err = tx.Commit() - if err == nil { - t.Error("a deadlock error was expected when committing a transaction", err) - } - - if err := mock.ExpectationsWereMet(); err == nil { - t.Errorf("was expecting an error since query was not triggered") - } -} - -func TestExecExpectations(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - result := NewResult(1, 1) - mock.ExpectExec("^INSERT INTO articles"). - WithArgs("hello"). - WillReturnResult(result) - - res, err := db.Exec("INSERT INTO articles (title) VALUES (?)", "hello") - if err != nil { - t.Errorf("error '%s' was not expected, while inserting a row", err) - } - - id, err := res.LastInsertId() - if err != nil { - t.Errorf("error '%s' was not expected, while getting a last insert id", err) - } - - affected, err := res.RowsAffected() - if err != nil { - t.Errorf("error '%s' was not expected, while getting affected rows", err) - } - - if id != 1 { - t.Errorf("expected last insert id to be 1, but got %d instead", id) - } - - if affected != 1 { - t.Errorf("expected affected rows to be 1, but got %d instead", affected) - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestRowBuilderAndNilTypes(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - rs := NewRows([]string{"id", "active", "created", "status"}). - AddRow(1, true, time.Now(), 5). - AddRow(2, false, nil, nil) - - mock.ExpectQuery("SELECT (.+) FROM sales").WillReturnRows(rs) - - rows, err := db.Query("SELECT * FROM sales") - if err != nil { - t.Errorf("error '%s' was not expected while retrieving mock rows", err) - } - defer func() { - if er := rows.Close(); er != nil { - t.Error("Unexpected error while trying to close rows") - } - }() - - // NullTime and NullInt are used from stubs_test.go - var ( - id int - active bool - created NullTime - status NullInt - ) - - if !rows.Next() { - t.Error("it must have had row in rows, but got empty result set instead") - } - - err = rows.Scan(&id, &active, &created, &status) - if err != nil { - t.Errorf("error '%s' was not expected while trying to scan row", err) - } - - if id != 1 { - t.Errorf("expected mocked id to be 1, but got %d instead", id) - } - - if !active { - t.Errorf("expected 'active' to be 'true', but got '%v' instead", active) - } - - if !created.Valid { - t.Errorf("expected 'created' to be valid, but it %+v is not", created) - } - - if !status.Valid { - t.Errorf("expected 'status' to be valid, but it %+v is not", status) - } - - if status.Integer != 5 { - t.Errorf("expected 'status' to be '5', but got '%d'", status.Integer) - } - - // test second row - if !rows.Next() { - t.Error("it must have had row in rows, but got empty result set instead") - } - - err = rows.Scan(&id, &active, &created, &status) - if err != nil { - t.Errorf("error '%s' was not expected while trying to scan row", err) - } - - if id != 2 { - t.Errorf("expected mocked id to be 2, but got %d instead", id) - } - - if active { - t.Errorf("expected 'active' to be 'false', but got '%v' instead", active) - } - - if created.Valid { - t.Errorf("expected 'created' to be invalid, but it %+v is not", created) - } - - if status.Valid { - t.Errorf("expected 'status' to be invalid, but it %+v is not", status) - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestArgumentReflectValueTypeError(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - rs := NewRows([]string{"id"}).AddRow(1) - - mock.ExpectQuery("SELECT (.+) FROM sales").WithArgs(5.5).WillReturnRows(rs) - - _, err = db.Query("SELECT * FROM sales WHERE x = ?", 5) - if err == nil { - t.Error("Expected error, but got none") - } -} - -func TestGoroutineExecutionWithUnorderedExpectationMatching(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - // note this line is important for unordered expectation matching - mock.MatchExpectationsInOrder(false) - - result := NewResult(1, 1) - - mock.ExpectExec("^UPDATE one").WithArgs("one").WillReturnResult(result) - mock.ExpectExec("^UPDATE two").WithArgs("one", "two").WillReturnResult(result) - mock.ExpectExec("^UPDATE three").WithArgs("one", "two", "three").WillReturnResult(result) - - var wg sync.WaitGroup - queries := map[string][]interface{}{ - "one": []interface{}{"one"}, - "two": []interface{}{"one", "two"}, - "three": []interface{}{"one", "two", "three"}, - } - - wg.Add(len(queries)) - for table, args := range queries { - go func(tbl string, a []interface{}) { - if _, err := db.Exec("UPDATE "+tbl, a...); err != nil { - t.Errorf("error was not expected: %s", err) - } - wg.Done() - }(table, args) - } - - wg.Wait() - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func ExampleSqlmock_goroutines() { - db, mock, err := New() - if err != nil { - fmt.Println("failed to open sqlmock database:", err) - } - defer db.Close() - - // note this line is important for unordered expectation matching - mock.MatchExpectationsInOrder(false) - - result := NewResult(1, 1) - - mock.ExpectExec("^UPDATE one").WithArgs("one").WillReturnResult(result) - mock.ExpectExec("^UPDATE two").WithArgs("one", "two").WillReturnResult(result) - mock.ExpectExec("^UPDATE three").WithArgs("one", "two", "three").WillReturnResult(result) - - var wg sync.WaitGroup - queries := map[string][]interface{}{ - "one": []interface{}{"one"}, - "two": []interface{}{"one", "two"}, - "three": []interface{}{"one", "two", "three"}, - } - - wg.Add(len(queries)) - for table, args := range queries { - go func(tbl string, a []interface{}) { - if _, err := db.Exec("UPDATE "+tbl, a...); err != nil { - fmt.Println("error was not expected:", err) - } - wg.Done() - }(table, args) - } - - wg.Wait() - - if err := mock.ExpectationsWereMet(); err != nil { - fmt.Println("there were unfulfilled expectations:", err) - } - // Output: -} - -// False Positive - passes despite mismatched Exec -// see #37 issue -func TestRunExecsWithOrderedShouldNotMeetAllExpectations(t *testing.T) { - db, dbmock, _ := New() - dbmock.ExpectExec("THE FIRST EXEC") - dbmock.ExpectExec("THE SECOND EXEC") - - _, _ = db.Exec("THE FIRST EXEC") - _, _ = db.Exec("THE WRONG EXEC") - - err := dbmock.ExpectationsWereMet() - if err == nil { - t.Fatal("was expecting an error, but there wasn't any") - } -} - -// False Positive - passes despite mismatched Exec -// see #37 issue -func TestRunQueriesWithOrderedShouldNotMeetAllExpectations(t *testing.T) { - db, dbmock, _ := New() - dbmock.ExpectQuery("THE FIRST QUERY") - dbmock.ExpectQuery("THE SECOND QUERY") - - _, _ = db.Query("THE FIRST QUERY") - _, _ = db.Query("THE WRONG QUERY") - - err := dbmock.ExpectationsWereMet() - if err == nil { - t.Fatal("was expecting an error, but there wasn't any") - } -} - -func TestRunExecsWithExpectedErrorMeetsExpectations(t *testing.T) { - db, dbmock, _ := New() - dbmock.ExpectExec("THE FIRST EXEC").WillReturnError(fmt.Errorf("big bad bug")) - dbmock.ExpectExec("THE SECOND EXEC").WillReturnResult(NewResult(0, 0)) - - _, _ = db.Exec("THE FIRST EXEC") - _, _ = db.Exec("THE SECOND EXEC") - - err := dbmock.ExpectationsWereMet() - if err != nil { - t.Fatalf("all expectations should be met: %s", err) - } -} - -func TestRunQueryWithExpectedErrorMeetsExpectations(t *testing.T) { - db, dbmock, _ := New() - dbmock.ExpectQuery("THE FIRST QUERY").WillReturnError(fmt.Errorf("big bad bug")) - dbmock.ExpectQuery("THE SECOND QUERY").WillReturnRows(NewRows([]string{"col"}).AddRow(1)) - - _, _ = db.Query("THE FIRST QUERY") - _, _ = db.Query("THE SECOND QUERY") - - err := dbmock.ExpectationsWereMet() - if err != nil { - t.Fatalf("all expectations should be met: %s", err) - } -} - -func TestEmptyRowSet(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - rs := NewRows([]string{"id", "title"}) - - mock.ExpectQuery("SELECT (.+) FROM articles WHERE id = ?"). - WithArgs(5). - WillReturnRows(rs) - - rows, err := db.Query("SELECT (.+) FROM articles WHERE id = ?", 5) - if err != nil { - t.Errorf("error '%s' was not expected while retrieving mock rows", err) - } - - defer func() { - if er := rows.Close(); er != nil { - t.Error("Unexpected error while trying to close rows") - } - }() - - if rows.Next() { - t.Error("expected no rows but got one") - } - - err = mock.ExpectationsWereMet() - if err != nil { - t.Fatalf("all expectations should be met: %s", err) - } -} - -// Based on issue #50 -func TestPrepareExpectationNotFulfilled(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - mock.ExpectPrepare("^BADSELECT$") - - if _, err := db.Prepare("SELECT"); err == nil { - t.Fatal("prepare should not match expected query string") - } - - if err := mock.ExpectationsWereMet(); err == nil { - t.Errorf("was expecting an error, since prepared statement query does not match, but there was none") - } -} - -func TestRollbackThrow(t *testing.T) { - // Open new mock database - db, mock, err := New() - if err != nil { - fmt.Println("error creating mock database") - return - } - // columns to be used for result - columns := []string{"id", "status"} - // expect transaction begin - mock.ExpectBegin() - // expect query to fetch order, match it with regexp - mock.ExpectQuery("SELECT (.+) FROM orders (.+) FOR UPDATE"). - WithArgs(1). - WillReturnRows(NewRows(columns).AddRow(1, 1)) - // expect transaction rollback, since order status is "cancelled" - mock.ExpectRollback().WillReturnError(fmt.Errorf("rollback failed")) - - // run the cancel order function - someOrderID := 1 - // call a function which executes expected database operations - err = cancelOrder(db, someOrderID) - if err == nil { - t.Error("an error was expected when rolling back transaction, but got none") - } - - // ensure all expectations have been met - if err = mock.ExpectationsWereMet(); err != nil { - t.Errorf("unmet expectation error: %s", err) - } - // Output: -} - -func TestUnexpectedCommit(t *testing.T) { - // Open new mock database - db, mock, err := New() - if err != nil { - fmt.Println("error creating mock database") - return - } - mock.ExpectBegin() - tx, _ := db.Begin() - if err := tx.Commit(); err == nil { - t.Error("an error was expected when calling commit, but got none") - } -} - -func TestUnexpectedCommitOrder(t *testing.T) { - // Open new mock database - db, mock, err := New() - if err != nil { - fmt.Println("error creating mock database") - return - } - mock.ExpectBegin() - mock.ExpectRollback().WillReturnError(fmt.Errorf("Rollback failed")) - tx, _ := db.Begin() - if err := tx.Commit(); err == nil { - t.Error("an error was expected when calling commit, but got none") - } -} - -func TestExpectedCommitOrder(t *testing.T) { - // Open new mock database - db, mock, err := New() - if err != nil { - fmt.Println("error creating mock database") - return - } - mock.ExpectCommit().WillReturnError(fmt.Errorf("Commit failed")) - if _, err := db.Begin(); err == nil { - t.Error("an error was expected when calling begin, but got none") - } -} - -func TestUnexpectedRollback(t *testing.T) { - // Open new mock database - db, mock, err := New() - if err != nil { - fmt.Println("error creating mock database") - return - } - mock.ExpectBegin() - tx, _ := db.Begin() - if err := tx.Rollback(); err == nil { - t.Error("an error was expected when calling rollback, but got none") - } -} - -func TestUnexpectedRollbackOrder(t *testing.T) { - // Open new mock database - db, mock, err := New() - if err != nil { - fmt.Println("error creating mock database") - return - } - mock.ExpectBegin() - - tx, _ := db.Begin() - if err := tx.Rollback(); err == nil { - t.Error("an error was expected when calling rollback, but got none") - } -} - -func TestPrepareExec(t *testing.T) { - // Open new mock database - db, mock, err := New() - if err != nil { - fmt.Println("error creating mock database") - return - } - defer db.Close() - mock.ExpectBegin() - ep := mock.ExpectPrepare("INSERT INTO ORDERS\\(ID, STATUS\\) VALUES \\(\\?, \\?\\)") - for i := 0; i < 3; i++ { - ep.ExpectExec().WillReturnResult(NewResult(1, 1)) - } - mock.ExpectCommit() - tx, _ := db.Begin() - stmt, err := tx.Prepare("INSERT INTO ORDERS(ID, STATUS) VALUES (?, ?)") - if err != nil { - t.Fatal(err) - } - defer stmt.Close() - for i := 0; i < 3; i++ { - _, err := stmt.Exec(i, "Hello"+strconv.Itoa(i)) - if err != nil { - t.Fatal(err) - } - } - tx.Commit() - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestPrepareQuery(t *testing.T) { - // Open new mock database - db, mock, err := New() - if err != nil { - fmt.Println("error creating mock database") - return - } - defer db.Close() - mock.ExpectBegin() - ep := mock.ExpectPrepare("SELECT ID, STATUS FROM ORDERS WHERE ID = \\?") - ep.ExpectQuery().WithArgs(101).WillReturnRows(NewRows([]string{"ID", "STATUS"}).AddRow(101, "Hello")) - mock.ExpectCommit() - tx, _ := db.Begin() - stmt, err := tx.Prepare("SELECT ID, STATUS FROM ORDERS WHERE ID = ?") - if err != nil { - t.Fatal(err) - } - defer stmt.Close() - rows, err := stmt.Query(101) - if err != nil { - t.Fatal(err) - } - defer rows.Close() - for rows.Next() { - var ( - id int - status string - ) - if rows.Scan(&id, &status); id != 101 || status != "Hello" { - t.Fatal("wrong query results") - } - - } - tx.Commit() - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestExpectedCloseError(t *testing.T) { - // Open new mock database - db, mock, err := New() - if err != nil { - fmt.Println("error creating mock database") - return - } - mock.ExpectClose().WillReturnError(fmt.Errorf("Close failed")) - if err := db.Close(); err == nil { - t.Error("an error was expected when calling close, but got none") - } - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestExpectedCloseOrder(t *testing.T) { - // Open new mock database - db, mock, err := New() - if err != nil { - fmt.Println("error creating mock database") - return - } - defer db.Close() - mock.ExpectClose().WillReturnError(fmt.Errorf("Close failed")) - db.Begin() - if err := mock.ExpectationsWereMet(); err == nil { - t.Error("expected error on ExpectationsWereMet") - } -} - -func TestExpectedBeginOrder(t *testing.T) { - // Open new mock database - db, mock, err := New() - if err != nil { - fmt.Println("error creating mock database") - return - } - mock.ExpectBegin().WillReturnError(fmt.Errorf("Begin failed")) - if err := db.Close(); err == nil { - t.Error("an error was expected when calling close, but got none") - } -} - -func TestPreparedStatementCloseExpectation(t *testing.T) { - // Open new mock database - db, mock, err := New() - if err != nil { - fmt.Println("error creating mock database") - return - } - defer db.Close() - - ep := mock.ExpectPrepare("INSERT INTO ORDERS").WillBeClosed() - ep.ExpectExec().WillReturnResult(NewResult(1, 1)) - - stmt, err := db.Prepare("INSERT INTO ORDERS(ID, STATUS) VALUES (?, ?)") - if err != nil { - t.Fatal(err) - } - - if _, err := stmt.Exec(1, "Hello"); err != nil { - t.Fatal(err) - } - - if err := stmt.Close(); err != nil { - t.Fatal(err) - } - - if err := mock.ExpectationsWereMet(); err != nil { - t.Errorf("there were unfulfilled expectations: %s", err) - } -} - -func TestExecExpectationErrorDelay(t *testing.T) { - t.Parallel() - db, mock, err := New() - if err != nil { - t.Errorf("an error '%s' was not expected when opening a stub database connection", err) - } - defer db.Close() - - // test that return of error is delayed - var delay time.Duration - delay = 100 * time.Millisecond - mock.ExpectExec("^INSERT INTO articles"). - WillReturnError(errors.New("slow fail")). - WillDelayFor(delay) - - start := time.Now() - res, err := db.Exec("INSERT INTO articles (title) VALUES (?)", "hello") - stop := time.Now() - - if res != nil { - t.Errorf("result was not expected, was expecting nil") - } - - if err == nil { - t.Errorf("error was expected, was not expecting nil") - } - - if err.Error() != "slow fail" { - t.Errorf("error '%s' was not expected, was expecting '%s'", err.Error(), "slow fail") - } - - elapsed := stop.Sub(start) - if elapsed < delay { - t.Errorf("expecting a delay of %v before error, actual delay was %v", delay, elapsed) - } - - // also test that return of error is not delayed - mock.ExpectExec("^INSERT INTO articles").WillReturnError(errors.New("fast fail")) - - start = time.Now() - db.Exec("INSERT INTO articles (title) VALUES (?)", "hello") - stop = time.Now() - - elapsed = stop.Sub(start) - if elapsed > delay { - t.Errorf("expecting a delay of less than %v before error, actual delay was %v", delay, elapsed) - } -} diff --git a/vendor/github.com/DATA-DOG/go-sqlmock/statement_test.go b/vendor/github.com/DATA-DOG/go-sqlmock/statement_test.go deleted file mode 100644 index f951f631..00000000 --- a/vendor/github.com/DATA-DOG/go-sqlmock/statement_test.go +++ /dev/null @@ -1,33 +0,0 @@ -// +build go1.6 - -package sqlmock - -import ( - "errors" - "testing" -) - -func TestExpectedPreparedStatemtCloseError(t *testing.T) { - conn, mock, err := New() - if err != nil { - t.Fatal("failed to open sqlmock database:", err) - } - - mock.ExpectBegin() - want := errors.New("STMT ERROR") - mock.ExpectPrepare("SELECT").WillReturnCloseError(want) - - txn, err := conn.Begin() - if err != nil { - t.Fatal("unexpected error while opening transaction:", err) - } - - stmt, err := txn.Prepare("SELECT") - if err != nil { - t.Fatal("unexpected error while preparing a statement:", err) - } - - if err := stmt.Close(); err != want { - t.Fatalf("Got = %v, want = %v", err, want) - } -} diff --git a/vendor/github.com/DATA-DOG/go-sqlmock/stubs_test.go b/vendor/github.com/DATA-DOG/go-sqlmock/stubs_test.go deleted file mode 100644 index d3c6003f..00000000 --- a/vendor/github.com/DATA-DOG/go-sqlmock/stubs_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package sqlmock - -import ( - "database/sql/driver" - "fmt" - "strconv" - "time" -) - -type NullTime struct { - Time time.Time - Valid bool // Valid is true if Time is not NULL -} - -type NullInt struct { - Integer int - Valid bool -} - -// Satisfy sql.Scanner interface -func (ni *NullInt) Scan(value interface{}) (err error) { - if value == nil { - ni.Integer, ni.Valid = 0, false - return - } - - switch v := value.(type) { - case int, int8, int16, int32, int64: - ni.Integer, ni.Valid = v.(int), true - return - case []byte: - ni.Integer, err = strconv.Atoi(string(v)) - ni.Valid = (err == nil) - return - case string: - ni.Integer, err = strconv.Atoi(v) - ni.Valid = (err == nil) - return - } - - ni.Valid = false - return fmt.Errorf("Can't convert %T to integer", value) -} - -// Satisfy sql.Valuer interface. -func (ni NullInt) Value() (driver.Value, error) { - if !ni.Valid { - return nil, nil - } - return ni.Integer, nil -} - -// Satisfy sql.Scanner interface -func (nt *NullTime) Scan(value interface{}) (err error) { - if value == nil { - nt.Time, nt.Valid = time.Time{}, false - return - } - - switch v := value.(type) { - case time.Time: - nt.Time, nt.Valid = v, true - return - } - - nt.Valid = false - return fmt.Errorf("Can't convert %T to time.Time", value) -} - -// Satisfy sql.Valuer interface. -func (nt NullTime) Value() (driver.Value, error) { - if !nt.Valid { - return nil, nil - } - return nt.Time, nil -} diff --git a/vendor/github.com/DATA-DOG/go-sqlmock/util_test.go b/vendor/github.com/DATA-DOG/go-sqlmock/util_test.go deleted file mode 100644 index c4b3974e..00000000 --- a/vendor/github.com/DATA-DOG/go-sqlmock/util_test.go +++ /dev/null @@ -1,21 +0,0 @@ -package sqlmock - -import ( - "testing" -) - -func TestQueryStringStripping(t *testing.T) { - assert := func(actual, expected string) { - if res := stripQuery(actual); res != expected { - t.Errorf("Expected '%s' to be '%s', but got '%s'", actual, expected, res) - } - } - - assert(" SELECT 1", "SELECT 1") - assert("SELECT 1 FROM d", "SELECT 1 FROM d") - assert(` - SELECT c - FROM D -`, "SELECT c FROM D") - assert("UPDATE (.+) SET ", "UPDATE (.+) SET") -} diff --git a/vendor/github.com/andybalholm/cascadia/LICENSE b/vendor/github.com/andybalholm/cascadia/LICENSE old mode 100755 new mode 100644 diff --git a/vendor/bitbucket.org/chrj/smtpd/.hgignore b/vendor/github.com/chrj/smtpd/.hgignore similarity index 100% rename from vendor/bitbucket.org/chrj/smtpd/.hgignore rename to vendor/github.com/chrj/smtpd/.hgignore diff --git a/vendor/bitbucket.org/chrj/smtpd/LICENSE b/vendor/github.com/chrj/smtpd/LICENSE similarity index 100% rename from vendor/bitbucket.org/chrj/smtpd/LICENSE rename to vendor/github.com/chrj/smtpd/LICENSE diff --git a/vendor/bitbucket.org/chrj/smtpd/README.md b/vendor/github.com/chrj/smtpd/README.md similarity index 100% rename from vendor/bitbucket.org/chrj/smtpd/README.md rename to vendor/github.com/chrj/smtpd/README.md diff --git a/vendor/bitbucket.org/chrj/smtpd/address.go b/vendor/github.com/chrj/smtpd/address.go similarity index 100% rename from vendor/bitbucket.org/chrj/smtpd/address.go rename to vendor/github.com/chrj/smtpd/address.go diff --git a/vendor/bitbucket.org/chrj/smtpd/protocol.go b/vendor/github.com/chrj/smtpd/protocol.go similarity index 100% rename from vendor/bitbucket.org/chrj/smtpd/protocol.go rename to vendor/github.com/chrj/smtpd/protocol.go diff --git a/vendor/bitbucket.org/chrj/smtpd/smtpd.go b/vendor/github.com/chrj/smtpd/smtpd.go similarity index 100% rename from vendor/bitbucket.org/chrj/smtpd/smtpd.go rename to vendor/github.com/chrj/smtpd/smtpd.go diff --git a/vendor/github.com/onsi/ginkgo/internal/codelocation/code_location_suite_test.go b/vendor/github.com/onsi/ginkgo/internal/codelocation/code_location_suite_test.go deleted file mode 100644 index f06abf3c..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/codelocation/code_location_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package codelocation_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestCodelocation(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "CodeLocation Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/internal/codelocation/code_location_test.go b/vendor/github.com/onsi/ginkgo/internal/codelocation/code_location_test.go deleted file mode 100644 index 9f63f735..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/codelocation/code_location_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package codelocation_test - -import ( - "runtime" - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" -) - -var _ = Describe("CodeLocation", func() { - var ( - codeLocation types.CodeLocation - expectedFileName string - expectedLineNumber int - ) - - caller0 := func() { - codeLocation = codelocation.New(1) - } - - caller1 := func() { - _, expectedFileName, expectedLineNumber, _ = runtime.Caller(0) - expectedLineNumber += 2 - caller0() - } - - BeforeEach(func() { - caller1() - }) - - It("should use the passed in skip parameter to pick out the correct file & line number", func() { - Ω(codeLocation.FileName).Should(Equal(expectedFileName)) - Ω(codeLocation.LineNumber).Should(Equal(expectedLineNumber)) - }) - - Describe("stringer behavior", func() { - It("should stringify nicely", func() { - Ω(codeLocation.String()).Should(ContainSubstring("code_location_test.go:%d", expectedLineNumber)) - }) - }) - - //There's no better way than to test this private method as it - //goes out of its way to prune out ginkgo related code in the stack trace - Describe("PruneStack", func() { - It("should remove any references to ginkgo and pkg/testing and pkg/runtime", func() { - input := `/Skip/me -Skip: skip() -/Skip/me -Skip: skip() -/Users/whoever/gospace/src/github.com/onsi/ginkgo/whatever.go:10 (0x12314) -Something: Func() -/Users/whoever/gospace/src/github.com/onsi/ginkgo/whatever_else.go:10 (0x12314) -SomethingInternalToGinkgo: Func() -/usr/goroot/pkg/strings/oops.go:10 (0x12341) -Oops: BlowUp() -/Users/whoever/gospace/src/mycode/code.go:10 (0x12341) -MyCode: Func() -/Users/whoever/gospace/src/mycode/code_test.go:10 (0x12341) -MyCodeTest: Func() -/Users/whoever/gospace/src/mycode/code_suite_test.go:12 (0x37f08) -TestFoo: RunSpecs(t, "Foo Suite") -/usr/goroot/pkg/testing/testing.go:12 (0x37f08) -TestingT: Blah() -/usr/goroot/pkg/runtime/runtime.go:12 (0x37f08) -Something: Func() -` - prunedStack := codelocation.PruneStack(input, 1) - Ω(prunedStack).Should(Equal(`/usr/goroot/pkg/strings/oops.go:10 (0x12341) -Oops: BlowUp() -/Users/whoever/gospace/src/mycode/code.go:10 (0x12341) -MyCode: Func() -/Users/whoever/gospace/src/mycode/code_test.go:10 (0x12341) -MyCodeTest: Func() -/Users/whoever/gospace/src/mycode/code_suite_test.go:12 (0x37f08) -TestFoo: RunSpecs(t, "Foo Suite")`)) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/containernode/container_node_suite_test.go b/vendor/github.com/onsi/ginkgo/internal/containernode/container_node_suite_test.go deleted file mode 100644 index c6fc314f..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/containernode/container_node_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package containernode_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestContainernode(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Containernode Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/internal/containernode/container_node_test.go b/vendor/github.com/onsi/ginkgo/internal/containernode/container_node_test.go deleted file mode 100644 index b83844ac..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/containernode/container_node_test.go +++ /dev/null @@ -1,212 +0,0 @@ -package containernode_test - -import ( - "math/rand" - "github.com/onsi/ginkgo/internal/leafnodes" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/internal/codelocation" - . "github.com/onsi/ginkgo/internal/containernode" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("Container Node", func() { - var ( - codeLocation types.CodeLocation - container *ContainerNode - ) - - BeforeEach(func() { - codeLocation = codelocation.New(0) - container = New("description text", types.FlagTypeFocused, codeLocation) - }) - - Describe("creating a container node", func() { - It("can answer questions about itself", func() { - Ω(container.Text()).Should(Equal("description text")) - Ω(container.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(container.CodeLocation()).Should(Equal(codeLocation)) - }) - }) - - Describe("pushing setup nodes", func() { - It("can append setup nodes of various types and fetch them by type", func() { - befA := leafnodes.NewBeforeEachNode(func() {}, codelocation.New(0), 0, nil, 0) - befB := leafnodes.NewBeforeEachNode(func() {}, codelocation.New(0), 0, nil, 0) - aftA := leafnodes.NewAfterEachNode(func() {}, codelocation.New(0), 0, nil, 0) - aftB := leafnodes.NewAfterEachNode(func() {}, codelocation.New(0), 0, nil, 0) - jusBefA := leafnodes.NewJustBeforeEachNode(func() {}, codelocation.New(0), 0, nil, 0) - jusBefB := leafnodes.NewJustBeforeEachNode(func() {}, codelocation.New(0), 0, nil, 0) - - container.PushSetupNode(befA) - container.PushSetupNode(befB) - container.PushSetupNode(aftA) - container.PushSetupNode(aftB) - container.PushSetupNode(jusBefA) - container.PushSetupNode(jusBefB) - - subject := leafnodes.NewItNode("subject", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - container.PushSubjectNode(subject) - - Ω(container.SetupNodesOfType(types.SpecComponentTypeBeforeEach)).Should(Equal([]leafnodes.BasicNode{befA, befB})) - Ω(container.SetupNodesOfType(types.SpecComponentTypeAfterEach)).Should(Equal([]leafnodes.BasicNode{aftA, aftB})) - Ω(container.SetupNodesOfType(types.SpecComponentTypeJustBeforeEach)).Should(Equal([]leafnodes.BasicNode{jusBefA, jusBefB})) - Ω(container.SetupNodesOfType(types.SpecComponentTypeIt)).Should(BeEmpty()) //subjects are not setup nodes - }) - }) - - Context("With appended containers and subject nodes", func() { - var ( - itA, itB, innerItA, innerItB leafnodes.SubjectNode - innerContainer *ContainerNode - ) - - BeforeEach(func() { - itA = leafnodes.NewItNode("Banana", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - itB = leafnodes.NewItNode("Apple", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - - innerItA = leafnodes.NewItNode("inner A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - innerItB = leafnodes.NewItNode("inner B", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - - innerContainer = New("Orange", types.FlagTypeNone, codelocation.New(0)) - - container.PushSubjectNode(itA) - container.PushContainerNode(innerContainer) - innerContainer.PushSubjectNode(innerItA) - innerContainer.PushSubjectNode(innerItB) - container.PushSubjectNode(itB) - }) - - Describe("Collating", func() { - It("should return a collated set of containers and subject nodes in the correct order", func() { - collated := container.Collate() - Ω(collated).Should(HaveLen(4)) - - Ω(collated[0]).Should(Equal(CollatedNodes{ - Containers: []*ContainerNode{container}, - Subject: itA, - })) - - Ω(collated[1]).Should(Equal(CollatedNodes{ - Containers: []*ContainerNode{container, innerContainer}, - Subject: innerItA, - })) - - Ω(collated[2]).Should(Equal(CollatedNodes{ - Containers: []*ContainerNode{container, innerContainer}, - Subject: innerItB, - })) - - Ω(collated[3]).Should(Equal(CollatedNodes{ - Containers: []*ContainerNode{container}, - Subject: itB, - })) - }) - }) - - Describe("Backpropagating Programmatic Focus", func() { - //This allows inner focused specs to override the focus of outer focussed - //specs and more closely maps to what a developer wants to happen - //when debugging a test suite - - Context("when a parent is focused *and* an inner subject is focused", func() { - BeforeEach(func() { - container = New("description text", types.FlagTypeFocused, codeLocation) - itA = leafnodes.NewItNode("A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - container.PushSubjectNode(itA) - - innerContainer = New("Orange", types.FlagTypeNone, codelocation.New(0)) - container.PushContainerNode(innerContainer) - innerItA = leafnodes.NewItNode("inner A", func() {}, types.FlagTypeFocused, codelocation.New(0), 0, nil, 0) - innerContainer.PushSubjectNode(innerItA) - }) - - It("should unfocus the parent", func() { - container.BackPropagateProgrammaticFocus() - - Ω(container.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(itA.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(innerContainer.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(innerItA.Flag()).Should(Equal(types.FlagTypeFocused)) - }) - }) - - Context("when a parent is focused *and* an inner container is focused", func() { - BeforeEach(func() { - container = New("description text", types.FlagTypeFocused, codeLocation) - itA = leafnodes.NewItNode("A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - container.PushSubjectNode(itA) - - innerContainer = New("Orange", types.FlagTypeFocused, codelocation.New(0)) - container.PushContainerNode(innerContainer) - innerItA = leafnodes.NewItNode("inner A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - innerContainer.PushSubjectNode(innerItA) - }) - - It("should unfocus the parent", func() { - container.BackPropagateProgrammaticFocus() - - Ω(container.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(itA.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(innerContainer.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(innerItA.Flag()).Should(Equal(types.FlagTypeNone)) - }) - }) - - Context("when a parent is pending and a child is focused", func() { - BeforeEach(func() { - container = New("description text", types.FlagTypeFocused, codeLocation) - itA = leafnodes.NewItNode("A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - container.PushSubjectNode(itA) - - innerContainer = New("Orange", types.FlagTypePending, codelocation.New(0)) - container.PushContainerNode(innerContainer) - innerItA = leafnodes.NewItNode("inner A", func() {}, types.FlagTypeFocused, codelocation.New(0), 0, nil, 0) - innerContainer.PushSubjectNode(innerItA) - }) - - It("should not do anything", func() { - container.BackPropagateProgrammaticFocus() - - Ω(container.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(itA.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(innerContainer.Flag()).Should(Equal(types.FlagTypePending)) - Ω(innerItA.Flag()).Should(Equal(types.FlagTypeFocused)) - }) - }) - }) - - Describe("Shuffling", func() { - var unshuffledCollation []CollatedNodes - BeforeEach(func() { - unshuffledCollation = container.Collate() - - r := rand.New(rand.NewSource(17)) - container.Shuffle(r) - }) - - It("should sort, and then shuffle, the top level contents of the container", func() { - shuffledCollation := container.Collate() - Ω(shuffledCollation).Should(HaveLen(len(unshuffledCollation))) - Ω(shuffledCollation).ShouldNot(Equal(unshuffledCollation)) - - for _, entry := range unshuffledCollation { - Ω(shuffledCollation).Should(ContainElement(entry)) - } - - innerAIndex, innerBIndex := 0, 0 - for i, entry := range shuffledCollation { - if entry.Subject == innerItA { - innerAIndex = i - } else if entry.Subject == innerItB { - innerBIndex = i - } - } - - Ω(innerAIndex).Should(Equal(innerBIndex - 1)) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/failer/failer_suite_test.go b/vendor/github.com/onsi/ginkgo/internal/failer/failer_suite_test.go deleted file mode 100644 index 8dce7be9..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/failer/failer_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package failer_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestFailer(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Failer Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/internal/failer/failer_test.go b/vendor/github.com/onsi/ginkgo/internal/failer/failer_test.go deleted file mode 100644 index 3da62db6..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/failer/failer_test.go +++ /dev/null @@ -1,125 +0,0 @@ -package failer_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/failer" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("Failer", func() { - var ( - failer *Failer - codeLocationA types.CodeLocation - codeLocationB types.CodeLocation - ) - - BeforeEach(func() { - codeLocationA = codelocation.New(0) - codeLocationB = codelocation.New(0) - failer = New() - }) - - Context("with no failures", func() { - It("should return success when drained", func() { - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(BeZero()) - Ω(state).Should(Equal(types.SpecStatePassed)) - }) - }) - - Describe("Fail", func() { - It("should handle failures", func() { - failer.Fail("something failed", codeLocationA) - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "something failed", - Location: codeLocationA, - ForwardedPanic: "", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStateFailed)) - }) - }) - - Describe("Panic", func() { - It("should handle panics", func() { - failer.Panic(codeLocationA, "some forwarded panic") - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "Test Panicked", - Location: codeLocationA, - ForwardedPanic: "some forwarded panic", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStatePanicked)) - }) - }) - - Describe("Timeout", func() { - It("should handle timeouts", func() { - failer.Timeout(codeLocationA) - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "Timed out", - Location: codeLocationA, - ForwardedPanic: "", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStateTimedOut)) - }) - }) - - Context("when multiple failures are registered", func() { - BeforeEach(func() { - failer.Fail("something failed", codeLocationA) - failer.Fail("something else failed", codeLocationA) - }) - - It("should only report the first one when drained", func() { - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "something failed", - Location: codeLocationA, - ForwardedPanic: "", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStateFailed)) - }) - - It("should report subsequent failures after being drained", func() { - failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - failer.Fail("yet another thing failed", codeLocationA) - - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "yet another thing failed", - Location: codeLocationA, - ForwardedPanic: "", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStateFailed)) - }) - - It("should report sucess on subsequent drains if no errors occur", func() { - failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(BeZero()) - Ω(state).Should(Equal(types.SpecStatePassed)) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/it_node_test.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/it_node_test.go deleted file mode 100644 index 29fa0c6e..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/it_node_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("It Nodes", func() { - It("should report the correct type, text, flag, and code location", func() { - codeLocation := codelocation.New(0) - it := NewItNode("my it node", func() {}, types.FlagTypeFocused, codeLocation, 0, nil, 3) - Ω(it.Type()).Should(Equal(types.SpecComponentTypeIt)) - Ω(it.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(it.Text()).Should(Equal("my it node")) - Ω(it.CodeLocation()).Should(Equal(codeLocation)) - Ω(it.Samples()).Should(Equal(1)) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/leaf_node_suite_test.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/leaf_node_suite_test.go deleted file mode 100644 index a7ba9e00..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/leaf_node_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestLeafNode(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "LeafNode Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/measure_node_test.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/measure_node_test.go deleted file mode 100644 index ee4f70bf..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/measure_node_test.go +++ /dev/null @@ -1,109 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - . "github.com/onsi/gomega" - - "time" - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("Measure Nodes", func() { - It("should report the correct type, text, flag, and code location", func() { - codeLocation := codelocation.New(0) - measure := NewMeasureNode("my measure node", func(b Benchmarker) {}, types.FlagTypeFocused, codeLocation, 10, nil, 3) - Ω(measure.Type()).Should(Equal(types.SpecComponentTypeMeasure)) - Ω(measure.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(measure.Text()).Should(Equal("my measure node")) - Ω(measure.CodeLocation()).Should(Equal(codeLocation)) - Ω(measure.Samples()).Should(Equal(10)) - }) - - Describe("benchmarking", func() { - var measure *MeasureNode - - Describe("Value", func() { - BeforeEach(func() { - measure = NewMeasureNode("the measurement", func(b Benchmarker) { - b.RecordValue("foo", 7, "info!") - b.RecordValue("foo", 2) - b.RecordValue("foo", 3) - b.RecordValue("bar", 0.3) - b.RecordValue("bar", 0.1) - b.RecordValue("bar", 0.5) - b.RecordValue("bar", 0.7) - }, types.FlagTypeFocused, codelocation.New(0), 1, Failer.New(), 3) - Ω(measure.Run()).Should(Equal(types.SpecStatePassed)) - }) - - It("records passed in values and reports on them", func() { - report := measure.MeasurementsReport() - Ω(report).Should(HaveLen(2)) - Ω(report["foo"].Name).Should(Equal("foo")) - Ω(report["foo"].Info).Should(Equal("info!")) - Ω(report["foo"].Order).Should(Equal(0)) - Ω(report["foo"].SmallestLabel).Should(Equal("Smallest")) - Ω(report["foo"].LargestLabel).Should(Equal(" Largest")) - Ω(report["foo"].AverageLabel).Should(Equal(" Average")) - Ω(report["foo"].Units).Should(Equal("")) - Ω(report["foo"].Results).Should(Equal([]float64{7, 2, 3})) - Ω(report["foo"].Smallest).Should(BeNumerically("==", 2)) - Ω(report["foo"].Largest).Should(BeNumerically("==", 7)) - Ω(report["foo"].Average).Should(BeNumerically("==", 4)) - Ω(report["foo"].StdDeviation).Should(BeNumerically("~", 2.16, 0.01)) - - Ω(report["bar"].Name).Should(Equal("bar")) - Ω(report["bar"].Info).Should(BeNil()) - Ω(report["bar"].SmallestLabel).Should(Equal("Smallest")) - Ω(report["bar"].Order).Should(Equal(1)) - Ω(report["bar"].LargestLabel).Should(Equal(" Largest")) - Ω(report["bar"].AverageLabel).Should(Equal(" Average")) - Ω(report["bar"].Units).Should(Equal("")) - Ω(report["bar"].Results).Should(Equal([]float64{0.3, 0.1, 0.5, 0.7})) - Ω(report["bar"].Smallest).Should(BeNumerically("==", 0.1)) - Ω(report["bar"].Largest).Should(BeNumerically("==", 0.7)) - Ω(report["bar"].Average).Should(BeNumerically("==", 0.4)) - Ω(report["bar"].StdDeviation).Should(BeNumerically("~", 0.22, 0.01)) - }) - }) - - Describe("Time", func() { - BeforeEach(func() { - measure = NewMeasureNode("the measurement", func(b Benchmarker) { - b.Time("foo", func() { - time.Sleep(100 * time.Millisecond) - }, "info!") - b.Time("foo", func() { - time.Sleep(200 * time.Millisecond) - }) - b.Time("foo", func() { - time.Sleep(170 * time.Millisecond) - }) - }, types.FlagTypeFocused, codelocation.New(0), 1, Failer.New(), 3) - Ω(measure.Run()).Should(Equal(types.SpecStatePassed)) - }) - - It("records passed in values and reports on them", func() { - report := measure.MeasurementsReport() - Ω(report).Should(HaveLen(1)) - Ω(report["foo"].Name).Should(Equal("foo")) - Ω(report["foo"].Info).Should(Equal("info!")) - Ω(report["foo"].SmallestLabel).Should(Equal("Fastest Time")) - Ω(report["foo"].LargestLabel).Should(Equal("Slowest Time")) - Ω(report["foo"].AverageLabel).Should(Equal("Average Time")) - Ω(report["foo"].Units).Should(Equal("s")) - Ω(report["foo"].Results).Should(HaveLen(3)) - Ω(report["foo"].Results[0]).Should(BeNumerically("~", 0.1, 0.01)) - Ω(report["foo"].Results[1]).Should(BeNumerically("~", 0.2, 0.01)) - Ω(report["foo"].Results[2]).Should(BeNumerically("~", 0.17, 0.01)) - Ω(report["foo"].Smallest).Should(BeNumerically("~", 0.1, 0.01)) - Ω(report["foo"].Largest).Should(BeNumerically("~", 0.2, 0.01)) - Ω(report["foo"].Average).Should(BeNumerically("~", 0.16, 0.01)) - Ω(report["foo"].StdDeviation).Should(BeNumerically("~", 0.04, 0.01)) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes_test.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes_test.go deleted file mode 100644 index d5b9251f..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - - . "github.com/onsi/ginkgo/internal/leafnodes" - - "github.com/onsi/ginkgo/internal/codelocation" -) - -var _ = Describe("Setup Nodes", func() { - Describe("BeforeEachNodes", func() { - It("should report the correct type and code location", func() { - codeLocation := codelocation.New(0) - beforeEach := NewBeforeEachNode(func() {}, codeLocation, 0, nil, 3) - Ω(beforeEach.Type()).Should(Equal(types.SpecComponentTypeBeforeEach)) - Ω(beforeEach.CodeLocation()).Should(Equal(codeLocation)) - }) - }) - - Describe("AfterEachNodes", func() { - It("should report the correct type and code location", func() { - codeLocation := codelocation.New(0) - afterEach := NewAfterEachNode(func() {}, codeLocation, 0, nil, 3) - Ω(afterEach.Type()).Should(Equal(types.SpecComponentTypeAfterEach)) - Ω(afterEach.CodeLocation()).Should(Equal(codeLocation)) - }) - }) - - Describe("JustBeforeEachNodes", func() { - It("should report the correct type and code location", func() { - codeLocation := codelocation.New(0) - justBeforeEach := NewJustBeforeEachNode(func() {}, codeLocation, 0, nil, 3) - Ω(justBeforeEach.Type()).Should(Equal(types.SpecComponentTypeJustBeforeEach)) - Ω(justBeforeEach.CodeLocation()).Should(Equal(codeLocation)) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/shared_runner_test.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/shared_runner_test.go deleted file mode 100644 index 9007d1ba..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/shared_runner_test.go +++ /dev/null @@ -1,326 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - . "github.com/onsi/gomega" - - "reflect" - "runtime" - "time" - - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" -) - -type runnable interface { - Run() (outcome types.SpecState, failure types.SpecFailure) - CodeLocation() types.CodeLocation -} - -func SynchronousSharedRunnerBehaviors(build func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable, componentType types.SpecComponentType, componentIndex int) { - var ( - outcome types.SpecState - failure types.SpecFailure - - failer *Failer.Failer - - componentCodeLocation types.CodeLocation - innerCodeLocation types.CodeLocation - - didRun bool - ) - - BeforeEach(func() { - failer = Failer.New() - componentCodeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - - didRun = false - }) - - Describe("synchronous functions", func() { - Context("when the function passes", func() { - BeforeEach(func() { - outcome, failure = build(func() { - didRun = true - }, 0, failer, componentCodeLocation).Run() - }) - - It("should have a succesful outcome", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStatePassed)) - Ω(failure).Should(BeZero()) - }) - }) - - Context("when a failure occurs", func() { - BeforeEach(func() { - outcome, failure = build(func() { - didRun = true - failer.Fail("bam", innerCodeLocation) - panic("should not matter") - }, 0, failer, componentCodeLocation).Run() - }) - - It("should return the failure", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStateFailed)) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "bam", - Location: innerCodeLocation, - ForwardedPanic: "", - ComponentIndex: componentIndex, - ComponentType: componentType, - ComponentCodeLocation: componentCodeLocation, - })) - }) - }) - - Context("when a panic occurs", func() { - BeforeEach(func() { - outcome, failure = build(func() { - didRun = true - innerCodeLocation = codelocation.New(0) - panic("ack!") - }, 0, failer, componentCodeLocation).Run() - }) - - It("should return the panic", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStatePanicked)) - Ω(failure.ForwardedPanic).Should(Equal("ack!")) - }) - }) - }) -} - -func AsynchronousSharedRunnerBehaviors(build func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable, componentType types.SpecComponentType, componentIndex int) { - var ( - outcome types.SpecState - failure types.SpecFailure - - failer *Failer.Failer - - componentCodeLocation types.CodeLocation - innerCodeLocation types.CodeLocation - - didRun bool - ) - - BeforeEach(func() { - failer = Failer.New() - componentCodeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - - didRun = false - }) - - Describe("asynchronous functions", func() { - var timeoutDuration time.Duration - - BeforeEach(func() { - timeoutDuration = time.Duration(1 * float64(time.Second)) - }) - - Context("when running", func() { - It("should run the function as a goroutine, and block until it's done", func() { - initialNumberOfGoRoutines := runtime.NumGoroutine() - numberOfGoRoutines := 0 - - build(func(done Done) { - didRun = true - numberOfGoRoutines = runtime.NumGoroutine() - close(done) - }, timeoutDuration, failer, componentCodeLocation).Run() - - Ω(didRun).Should(BeTrue()) - Ω(numberOfGoRoutines).Should(BeNumerically(">=", initialNumberOfGoRoutines+1)) - }) - }) - - Context("when the function passes", func() { - BeforeEach(func() { - outcome, failure = build(func(done Done) { - didRun = true - close(done) - }, timeoutDuration, failer, componentCodeLocation).Run() - }) - - It("should have a succesful outcome", func() { - Ω(didRun).Should(BeTrue()) - Ω(outcome).Should(Equal(types.SpecStatePassed)) - Ω(failure).Should(BeZero()) - }) - }) - - Context("when the function fails", func() { - BeforeEach(func() { - outcome, failure = build(func(done Done) { - didRun = true - failer.Fail("bam", innerCodeLocation) - time.Sleep(20 * time.Millisecond) - panic("doesn't matter") - close(done) - }, 10*time.Millisecond, failer, componentCodeLocation).Run() - }) - - It("should return the failure", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStateFailed)) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "bam", - Location: innerCodeLocation, - ForwardedPanic: "", - ComponentIndex: componentIndex, - ComponentType: componentType, - ComponentCodeLocation: componentCodeLocation, - })) - }) - }) - - Context("when the function times out", func() { - var guard chan struct{} - - BeforeEach(func() { - guard = make(chan struct{}) - outcome, failure = build(func(done Done) { - didRun = true - time.Sleep(20 * time.Millisecond) - close(guard) - panic("doesn't matter") - close(done) - }, 10*time.Millisecond, failer, componentCodeLocation).Run() - }) - - It("should return the timeout", func() { - <-guard - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStateTimedOut)) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "Timed out", - Location: componentCodeLocation, - ForwardedPanic: "", - ComponentIndex: componentIndex, - ComponentType: componentType, - ComponentCodeLocation: componentCodeLocation, - })) - }) - }) - - Context("when the function panics", func() { - BeforeEach(func() { - outcome, failure = build(func(done Done) { - didRun = true - innerCodeLocation = codelocation.New(0) - panic("ack!") - }, 100*time.Millisecond, failer, componentCodeLocation).Run() - }) - - It("should return the panic", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStatePanicked)) - Ω(failure.ForwardedPanic).Should(Equal("ack!")) - }) - }) - }) -} - -func InvalidSharedRunnerBehaviors(build func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable, componentType types.SpecComponentType) { - var ( - failer *Failer.Failer - componentCodeLocation types.CodeLocation - innerCodeLocation types.CodeLocation - ) - - BeforeEach(func() { - failer = Failer.New() - componentCodeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - }) - - Describe("invalid functions", func() { - Context("when passed something that's not a function", func() { - It("should panic", func() { - Ω(func() { - build("not a function", 0, failer, componentCodeLocation) - }).Should(Panic()) - }) - }) - - Context("when the function takes the wrong kind of argument", func() { - It("should panic", func() { - Ω(func() { - build(func(oops string) {}, 0, failer, componentCodeLocation) - }).Should(Panic()) - }) - }) - - Context("when the function takes more than one argument", func() { - It("should panic", func() { - Ω(func() { - build(func(done Done, oops string) {}, 0, failer, componentCodeLocation) - }).Should(Panic()) - }) - }) - }) -} - -var _ = Describe("Shared RunnableNode behavior", func() { - Describe("It Nodes", func() { - build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewItNode("", body, types.FlagTypeFocused, componentCodeLocation, timeout, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeIt, 3) - AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeIt, 3) - InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeIt) - }) - - Describe("Measure Nodes", func() { - build := func(body interface{}, _ time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewMeasureNode("", func(Benchmarker) { - reflect.ValueOf(body).Call([]reflect.Value{}) - }, types.FlagTypeFocused, componentCodeLocation, 10, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeMeasure, 3) - }) - - Describe("BeforeEach Nodes", func() { - build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewBeforeEachNode(body, componentCodeLocation, timeout, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeBeforeEach, 3) - AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeBeforeEach, 3) - InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeBeforeEach) - }) - - Describe("AfterEach Nodes", func() { - build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewAfterEachNode(body, componentCodeLocation, timeout, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeAfterEach, 3) - AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeAfterEach, 3) - InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeAfterEach) - }) - - Describe("JustBeforeEach Nodes", func() { - build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewJustBeforeEachNode(body, componentCodeLocation, timeout, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeJustBeforeEach, 3) - AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeJustBeforeEach, 3) - InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeJustBeforeEach) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes_test.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes_test.go deleted file mode 100644 index 246b329f..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes_test.go +++ /dev/null @@ -1,230 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - . "github.com/onsi/ginkgo/internal/leafnodes" - - "time" - - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("SuiteNodes", func() { - Describe("BeforeSuite nodes", func() { - var befSuite SuiteNode - var failer *Failer.Failer - var codeLocation types.CodeLocation - var innerCodeLocation types.CodeLocation - var outcome bool - - BeforeEach(func() { - failer = Failer.New() - codeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - }) - - Context("when the body passes", func() { - BeforeEach(func() { - befSuite = NewBeforeSuiteNode(func() { - time.Sleep(10 * time.Millisecond) - }, codeLocation, 0, failer) - outcome = befSuite.Run(0, 0, "") - }) - - It("should return true when run and report as passed", func() { - Ω(outcome).Should(BeTrue()) - Ω(befSuite.Passed()).Should(BeTrue()) - }) - - It("should have the correct summary", func() { - summary := befSuite.Summary() - Ω(summary.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.CodeLocation).Should(Equal(codeLocation)) - Ω(summary.State).Should(Equal(types.SpecStatePassed)) - Ω(summary.RunTime).Should(BeNumerically(">=", 10*time.Millisecond)) - Ω(summary.Failure).Should(BeZero()) - }) - }) - - Context("when the body fails", func() { - BeforeEach(func() { - befSuite = NewBeforeSuiteNode(func() { - failer.Fail("oops", innerCodeLocation) - }, codeLocation, 0, failer) - outcome = befSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(befSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := befSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStateFailed)) - Ω(summary.Failure.Message).Should(Equal("oops")) - Ω(summary.Failure.Location).Should(Equal(innerCodeLocation)) - Ω(summary.Failure.ForwardedPanic).Should(BeEmpty()) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when the body times out", func() { - BeforeEach(func() { - befSuite = NewBeforeSuiteNode(func(done Done) { - }, codeLocation, time.Millisecond, failer) - outcome = befSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(befSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := befSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStateTimedOut)) - Ω(summary.Failure.ForwardedPanic).Should(BeEmpty()) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when the body panics", func() { - BeforeEach(func() { - befSuite = NewBeforeSuiteNode(func() { - panic("bam") - }, codeLocation, 0, failer) - outcome = befSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(befSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := befSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStatePanicked)) - Ω(summary.Failure.ForwardedPanic).Should(Equal("bam")) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - }) - - Describe("AfterSuite nodes", func() { - var aftSuite SuiteNode - var failer *Failer.Failer - var codeLocation types.CodeLocation - var innerCodeLocation types.CodeLocation - var outcome bool - - BeforeEach(func() { - failer = Failer.New() - codeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - }) - - Context("when the body passes", func() { - BeforeEach(func() { - aftSuite = NewAfterSuiteNode(func() { - time.Sleep(10 * time.Millisecond) - }, codeLocation, 0, failer) - outcome = aftSuite.Run(0, 0, "") - }) - - It("should return true when run and report as passed", func() { - Ω(outcome).Should(BeTrue()) - Ω(aftSuite.Passed()).Should(BeTrue()) - }) - - It("should have the correct summary", func() { - summary := aftSuite.Summary() - Ω(summary.ComponentType).Should(Equal(types.SpecComponentTypeAfterSuite)) - Ω(summary.CodeLocation).Should(Equal(codeLocation)) - Ω(summary.State).Should(Equal(types.SpecStatePassed)) - Ω(summary.RunTime).Should(BeNumerically(">=", 10*time.Millisecond)) - Ω(summary.Failure).Should(BeZero()) - }) - }) - - Context("when the body fails", func() { - BeforeEach(func() { - aftSuite = NewAfterSuiteNode(func() { - failer.Fail("oops", innerCodeLocation) - }, codeLocation, 0, failer) - outcome = aftSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(aftSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := aftSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStateFailed)) - Ω(summary.Failure.Message).Should(Equal("oops")) - Ω(summary.Failure.Location).Should(Equal(innerCodeLocation)) - Ω(summary.Failure.ForwardedPanic).Should(BeEmpty()) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeAfterSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when the body times out", func() { - BeforeEach(func() { - aftSuite = NewAfterSuiteNode(func(done Done) { - }, codeLocation, time.Millisecond, failer) - outcome = aftSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(aftSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := aftSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStateTimedOut)) - Ω(summary.Failure.ForwardedPanic).Should(BeEmpty()) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeAfterSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when the body panics", func() { - BeforeEach(func() { - aftSuite = NewAfterSuiteNode(func() { - panic("bam") - }, codeLocation, 0, failer) - outcome = aftSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(aftSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := aftSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStatePanicked)) - Ω(summary.Failure.ForwardedPanic).Should(Equal("bam")) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeAfterSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node_test.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node_test.go deleted file mode 100644 index 4266a4bc..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node_test.go +++ /dev/null @@ -1,196 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - "sync" - - "github.com/onsi/gomega/ghttp" - "net/http" - - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "time" -) - -var _ = Describe("SynchronizedAfterSuiteNode", func() { - var failer *Failer.Failer - var node SuiteNode - var codeLocation types.CodeLocation - var innerCodeLocation types.CodeLocation - var outcome bool - var server *ghttp.Server - var things []string - var lock *sync.Mutex - - BeforeEach(func() { - things = []string{} - server = ghttp.NewServer() - codeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - failer = Failer.New() - lock = &sync.Mutex{} - }) - - AfterEach(func() { - server.Close() - }) - - newNode := func(bodyA interface{}, bodyB interface{}) SuiteNode { - return NewSynchronizedAfterSuiteNode(bodyA, bodyB, codeLocation, time.Millisecond, failer) - } - - ranThing := func(thing string) { - lock.Lock() - defer lock.Unlock() - things = append(things, thing) - } - - thingsThatRan := func() []string { - lock.Lock() - defer lock.Unlock() - return things - } - - Context("when not running in parallel", func() { - Context("when all is well", func() { - BeforeEach(func() { - node = newNode(func() { - ranThing("A") - }, func() { - ranThing("B") - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should run A, then B", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A", "B"})) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - Ω(node.Summary().State).Should(Equal(types.SpecStatePassed)) - }) - }) - - Context("when A fails", func() { - BeforeEach(func() { - node = newNode(func() { - ranThing("A") - failer.Fail("bam", innerCodeLocation) - }, func() { - ranThing("B") - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should still run B", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A", "B"})) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateFailed)) - }) - }) - - Context("when B fails", func() { - BeforeEach(func() { - node = newNode(func() { - ranThing("A") - }, func() { - ranThing("B") - failer.Fail("bam", innerCodeLocation) - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should run all the things", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A", "B"})) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateFailed)) - }) - }) - }) - - Context("when running in parallel", func() { - Context("as the first node", func() { - BeforeEach(func() { - server.AppendHandlers(ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/RemoteAfterSuiteData"), - func(writer http.ResponseWriter, request *http.Request) { - ranThing("Request1") - }, - ghttp.RespondWithJSONEncoded(200, types.RemoteAfterSuiteData{false}), - ), ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/RemoteAfterSuiteData"), - func(writer http.ResponseWriter, request *http.Request) { - ranThing("Request2") - }, - ghttp.RespondWithJSONEncoded(200, types.RemoteAfterSuiteData{false}), - ), ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/RemoteAfterSuiteData"), - func(writer http.ResponseWriter, request *http.Request) { - ranThing("Request3") - }, - ghttp.RespondWithJSONEncoded(200, types.RemoteAfterSuiteData{true}), - )) - - node = newNode(func() { - ranThing("A") - }, func() { - ranThing("B") - }) - - outcome = node.Run(1, 3, server.URL()) - }) - - It("should run A and, when the server says its time, run B", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A", "Request1", "Request2", "Request3", "B"})) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - Ω(node.Summary().State).Should(Equal(types.SpecStatePassed)) - }) - }) - - Context("as any other node", func() { - BeforeEach(func() { - node = newNode(func() { - ranThing("A") - }, func() { - ranThing("B") - }) - - outcome = node.Run(2, 3, server.URL()) - }) - - It("should run A, and not run B", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A"})) - }) - - It("should not talk to the server", func() { - Ω(server.ReceivedRequests()).Should(BeEmpty()) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - Ω(node.Summary().State).Should(Equal(types.SpecStatePassed)) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node_test.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node_test.go deleted file mode 100644 index dbf24267..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node_test.go +++ /dev/null @@ -1,445 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - . "github.com/onsi/gomega" - - "github.com/onsi/gomega/ghttp" - "net/http" - - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "time" -) - -var _ = Describe("SynchronizedBeforeSuiteNode", func() { - var failer *Failer.Failer - var node SuiteNode - var codeLocation types.CodeLocation - var innerCodeLocation types.CodeLocation - var outcome bool - var server *ghttp.Server - - BeforeEach(func() { - server = ghttp.NewServer() - codeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - failer = Failer.New() - }) - - AfterEach(func() { - server.Close() - }) - - newNode := func(bodyA interface{}, bodyB interface{}) SuiteNode { - return NewSynchronizedBeforeSuiteNode(bodyA, bodyB, codeLocation, time.Millisecond, failer) - } - - Describe("when not running in parallel", func() { - Context("when all is well", func() { - var data []byte - BeforeEach(func() { - data = nil - - node = newNode(func() []byte { - return []byte("my data") - }, func(d []byte) { - data = d - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should run A, then B passing the output from A to B", func() { - Ω(data).Should(Equal([]byte("my data"))) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - Ω(node.Summary().State).Should(Equal(types.SpecStatePassed)) - }) - }) - - Context("when A fails", func() { - var ranB bool - BeforeEach(func() { - ranB = false - node = newNode(func() []byte { - failer.Fail("boom", innerCodeLocation) - return nil - }, func([]byte) { - ranB = true - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should not run B", func() { - Ω(ranB).Should(BeFalse()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateFailed)) - }) - }) - - Context("when B fails", func() { - BeforeEach(func() { - node = newNode(func() []byte { - return nil - }, func([]byte) { - failer.Fail("boom", innerCodeLocation) - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateFailed)) - }) - }) - - Context("when A times out", func() { - var ranB bool - BeforeEach(func() { - ranB = false - node = newNode(func(Done) []byte { - time.Sleep(time.Second) - return nil - }, func([]byte) { - ranB = true - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should not run B", func() { - Ω(ranB).Should(BeFalse()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateTimedOut)) - }) - }) - - Context("when B times out", func() { - BeforeEach(func() { - node = newNode(func() []byte { - return nil - }, func([]byte, Done) { - time.Sleep(time.Second) - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateTimedOut)) - }) - }) - }) - - Describe("when running in parallel", func() { - var ranB bool - var parallelNode, parallelTotal int - BeforeEach(func() { - ranB = false - parallelNode, parallelTotal = 1, 3 - }) - - Context("as the first node, it runs A", func() { - var expectedState types.RemoteBeforeSuiteData - - BeforeEach(func() { - parallelNode, parallelTotal = 1, 3 - }) - - JustBeforeEach(func() { - server.AppendHandlers(ghttp.CombineHandlers( - ghttp.VerifyRequest("POST", "/BeforeSuiteState"), - ghttp.VerifyJSONRepresenting(expectedState), - )) - - outcome = node.Run(parallelNode, parallelTotal, server.URL()) - }) - - Context("when A succeeds", func() { - BeforeEach(func() { - expectedState = types.RemoteBeforeSuiteData{[]byte("my data"), types.RemoteBeforeSuiteStatePassed} - - node = newNode(func() []byte { - return []byte("my data") - }, func([]byte) { - ranB = true - }) - }) - - It("should post about A succeeding", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(1)) - }) - - It("should run B", func() { - Ω(ranB).Should(BeTrue()) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - }) - }) - - Context("when A fails", func() { - BeforeEach(func() { - expectedState = types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStateFailed} - - node = newNode(func() []byte { - panic("BAM") - return []byte("my data") - }, func([]byte) { - ranB = true - }) - }) - - It("should post about A failing", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(1)) - }) - - It("should not run B", func() { - Ω(ranB).Should(BeFalse()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - }) - }) - }) - - Context("as the Nth node", func() { - var statusCode int - var response interface{} - var ranA bool - var bData []byte - - BeforeEach(func() { - ranA = false - bData = nil - - statusCode = http.StatusOK - - server.AppendHandlers(ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/BeforeSuiteState"), - ghttp.RespondWith(http.StatusOK, string((types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending}).ToJSON())), - ), ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/BeforeSuiteState"), - ghttp.RespondWith(http.StatusOK, string((types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending}).ToJSON())), - ), ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/BeforeSuiteState"), - ghttp.RespondWithJSONEncodedPtr(&statusCode, &response), - )) - - node = newNode(func() []byte { - ranA = true - return nil - }, func(data []byte) { - bData = data - }) - - parallelNode, parallelTotal = 2, 3 - }) - - Context("when A on node1 succeeds", func() { - BeforeEach(func() { - response = types.RemoteBeforeSuiteData{[]byte("my data"), types.RemoteBeforeSuiteStatePassed} - outcome = node.Run(parallelNode, parallelTotal, server.URL()) - }) - - It("should not run A", func() { - Ω(ranA).Should(BeFalse()) - }) - - It("should poll for A", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(3)) - }) - - It("should run B when the polling succeeds", func() { - Ω(bData).Should(Equal([]byte("my data"))) - }) - - It("should succeed", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - }) - }) - - Context("when A on node1 fails", func() { - BeforeEach(func() { - response = types.RemoteBeforeSuiteData{[]byte("my data"), types.RemoteBeforeSuiteStateFailed} - outcome = node.Run(parallelNode, parallelTotal, server.URL()) - }) - - It("should not run A", func() { - Ω(ranA).Should(BeFalse()) - }) - - It("should poll for A", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(3)) - }) - - It("should not run B", func() { - Ω(bData).Should(BeNil()) - }) - - It("should fail", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - - summary := node.Summary() - Ω(summary.State).Should(Equal(types.SpecStateFailed)) - Ω(summary.Failure.Message).Should(Equal("BeforeSuite on Node 1 failed")) - Ω(summary.Failure.Location).Should(Equal(codeLocation)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when node1 disappears", func() { - BeforeEach(func() { - response = types.RemoteBeforeSuiteData{[]byte("my data"), types.RemoteBeforeSuiteStateDisappeared} - outcome = node.Run(parallelNode, parallelTotal, server.URL()) - }) - - It("should not run A", func() { - Ω(ranA).Should(BeFalse()) - }) - - It("should poll for A", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(3)) - }) - - It("should not run B", func() { - Ω(bData).Should(BeNil()) - }) - - It("should fail", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - - summary := node.Summary() - Ω(summary.State).Should(Equal(types.SpecStateFailed)) - Ω(summary.Failure.Message).Should(Equal("Node 1 disappeared before completing BeforeSuite")) - Ω(summary.Failure.Location).Should(Equal(codeLocation)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - }) - }) - - Describe("construction", func() { - Describe("the first function", func() { - Context("when the first function returns a byte array", func() { - Context("and takes nothing", func() { - It("should be fine", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte) {}) - }).ShouldNot(Panic()) - }) - }) - - Context("and takes a done function", func() { - It("should be fine", func() { - Ω(func() { - newNode(func(Done) []byte { return nil }, func([]byte) {}) - }).ShouldNot(Panic()) - }) - }) - - Context("and takes more than one thing", func() { - It("should panic", func() { - Ω(func() { - newNode(func(Done, Done) []byte { return nil }, func([]byte) {}) - }).Should(Panic()) - }) - }) - - Context("and takes something else", func() { - It("should panic", func() { - Ω(func() { - newNode(func(bool) []byte { return nil }, func([]byte) {}) - }).Should(Panic()) - }) - }) - }) - - Context("when the first function does not return a byte array", func() { - It("should panic", func() { - Ω(func() { - newNode(func() {}, func([]byte) {}) - }).Should(Panic()) - - Ω(func() { - newNode(func() []int { return nil }, func([]byte) {}) - }).Should(Panic()) - }) - }) - }) - - Describe("the second function", func() { - Context("when the second function takes a byte array", func() { - It("should be fine", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte) {}) - }).ShouldNot(Panic()) - }) - }) - - Context("when it also takes a done channel", func() { - It("should be fine", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte, Done) {}) - }).ShouldNot(Panic()) - }) - }) - - Context("if it takes anything else", func() { - It("should panic", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte, chan bool) {}) - }).Should(Panic()) - - Ω(func() { - newNode(func() []byte { return nil }, func(string) {}) - }).Should(Panic()) - }) - }) - - Context("if it takes nothing at all", func() { - It("should panic", func() { - Ω(func() { - newNode(func() []byte { return nil }, func() {}) - }).Should(Panic()) - }) - }) - - Context("if it returns something", func() { - It("should panic", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte) []byte { return nil }) - }).Should(Panic()) - }) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/aggregator_test.go b/vendor/github.com/onsi/ginkgo/internal/remote/aggregator_test.go deleted file mode 100644 index d8499cf3..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/aggregator_test.go +++ /dev/null @@ -1,311 +0,0 @@ -package remote_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "time" - "github.com/onsi/ginkgo/config" - . "github.com/onsi/ginkgo/internal/remote" - st "github.com/onsi/ginkgo/reporters/stenographer" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("Aggregator", func() { - var ( - aggregator *Aggregator - reporterConfig config.DefaultReporterConfigType - stenographer *st.FakeStenographer - result chan bool - - ginkgoConfig1 config.GinkgoConfigType - ginkgoConfig2 config.GinkgoConfigType - - suiteSummary1 *types.SuiteSummary - suiteSummary2 *types.SuiteSummary - - beforeSummary *types.SetupSummary - afterSummary *types.SetupSummary - specSummary *types.SpecSummary - - suiteDescription string - ) - - BeforeEach(func() { - reporterConfig = config.DefaultReporterConfigType{ - NoColor: false, - SlowSpecThreshold: 0.1, - NoisyPendings: true, - Succinct: false, - Verbose: true, - } - stenographer = st.NewFakeStenographer() - result = make(chan bool, 1) - aggregator = NewAggregator(2, result, reporterConfig, stenographer) - - // - // now set up some fixture data - // - - ginkgoConfig1 = config.GinkgoConfigType{ - RandomSeed: 1138, - RandomizeAllSpecs: true, - ParallelNode: 1, - ParallelTotal: 2, - } - - ginkgoConfig2 = config.GinkgoConfigType{ - RandomSeed: 1138, - RandomizeAllSpecs: true, - ParallelNode: 2, - ParallelTotal: 2, - } - - suiteDescription = "My Parallel Suite" - - suiteSummary1 = &types.SuiteSummary{ - SuiteDescription: suiteDescription, - - NumberOfSpecsBeforeParallelization: 30, - NumberOfTotalSpecs: 17, - NumberOfSpecsThatWillBeRun: 15, - NumberOfPendingSpecs: 1, - NumberOfSkippedSpecs: 1, - } - - suiteSummary2 = &types.SuiteSummary{ - SuiteDescription: suiteDescription, - - NumberOfSpecsBeforeParallelization: 30, - NumberOfTotalSpecs: 13, - NumberOfSpecsThatWillBeRun: 8, - NumberOfPendingSpecs: 2, - NumberOfSkippedSpecs: 3, - } - - beforeSummary = &types.SetupSummary{ - State: types.SpecStatePassed, - CapturedOutput: "BeforeSuiteOutput", - } - - afterSummary = &types.SetupSummary{ - State: types.SpecStatePassed, - CapturedOutput: "AfterSuiteOutput", - } - - specSummary = &types.SpecSummary{ - State: types.SpecStatePassed, - CapturedOutput: "SpecOutput", - } - }) - - call := func(method string, args ...interface{}) st.FakeStenographerCall { - return st.NewFakeStenographerCall(method, args...) - } - - beginSuite := func() { - stenographer.Reset() - aggregator.SpecSuiteWillBegin(ginkgoConfig2, suiteSummary2) - aggregator.SpecSuiteWillBegin(ginkgoConfig1, suiteSummary1) - Eventually(func() interface{} { - return len(stenographer.Calls()) - }).Should(BeNumerically(">=", 3)) - } - - Describe("Announcing the beginning of the suite", func() { - Context("When one of the parallel-suites starts", func() { - BeforeEach(func() { - aggregator.SpecSuiteWillBegin(ginkgoConfig2, suiteSummary2) - }) - - It("should be silent", func() { - Consistently(func() interface{} { return stenographer.Calls() }).Should(BeEmpty()) - }) - }) - - Context("once all of the parallel-suites have started", func() { - BeforeEach(func() { - aggregator.SpecSuiteWillBegin(ginkgoConfig2, suiteSummary2) - aggregator.SpecSuiteWillBegin(ginkgoConfig1, suiteSummary1) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(3)) - }) - - It("should announce the beginning of the suite", func() { - Ω(stenographer.Calls()).Should(HaveLen(3)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuite", suiteDescription, ginkgoConfig1.RandomSeed, true, false))) - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceNumberOfSpecs", 23, 30, false))) - Ω(stenographer.Calls()[2]).Should(Equal(call("AnnounceAggregatedParallelRun", 2, false))) - }) - }) - }) - - Describe("Announcing specs and before suites", func() { - Context("when the parallel-suites have not all started", func() { - BeforeEach(func() { - aggregator.BeforeSuiteDidRun(beforeSummary) - aggregator.AfterSuiteDidRun(afterSummary) - aggregator.SpecDidComplete(specSummary) - }) - - It("should not announce any specs", func() { - Consistently(func() interface{} { return stenographer.Calls() }).Should(BeEmpty()) - }) - - Context("when the parallel-suites subsequently start", func() { - BeforeEach(func() { - beginSuite() - }) - - It("should announce the specs, the before suites and the after suites", func() { - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(ContainElement(call("AnnounceSuccesfulSpec", specSummary))) - - Ω(stenographer.Calls()).Should(ContainElement(call("AnnounceCapturedOutput", beforeSummary.CapturedOutput))) - Ω(stenographer.Calls()).Should(ContainElement(call("AnnounceCapturedOutput", afterSummary.CapturedOutput))) - }) - }) - }) - - Context("When the parallel-suites have all started", func() { - BeforeEach(func() { - beginSuite() - stenographer.Reset() - }) - - Context("When a spec completes", func() { - BeforeEach(func() { - aggregator.BeforeSuiteDidRun(beforeSummary) - aggregator.SpecDidComplete(specSummary) - aggregator.AfterSuiteDidRun(afterSummary) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(5)) - }) - - It("should announce the captured output of the BeforeSuite", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceCapturedOutput", beforeSummary.CapturedOutput))) - }) - - It("should announce that the spec will run (when in verbose mode)", func() { - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceSpecWillRun", specSummary))) - }) - - It("should announce the captured stdout of the spec", func() { - Ω(stenographer.Calls()[2]).Should(Equal(call("AnnounceCapturedOutput", specSummary.CapturedOutput))) - }) - - It("should announce completion", func() { - Ω(stenographer.Calls()[3]).Should(Equal(call("AnnounceSuccesfulSpec", specSummary))) - }) - - It("should announce the captured output of the AfterSuite", func() { - Ω(stenographer.Calls()[4]).Should(Equal(call("AnnounceCapturedOutput", afterSummary.CapturedOutput))) - }) - }) - }) - }) - - Describe("Announcing the end of the suite", func() { - BeforeEach(func() { - beginSuite() - stenographer.Reset() - }) - - Context("When one of the parallel-suites ends", func() { - BeforeEach(func() { - aggregator.SpecSuiteDidEnd(suiteSummary2) - }) - - It("should be silent", func() { - Consistently(func() interface{} { return stenographer.Calls() }).Should(BeEmpty()) - }) - - It("should not notify the channel", func() { - Ω(result).Should(BeEmpty()) - }) - }) - - Context("once all of the parallel-suites end", func() { - BeforeEach(func() { - time.Sleep(200 * time.Millisecond) - - suiteSummary1.SuiteSucceeded = true - suiteSummary1.NumberOfPassedSpecs = 15 - suiteSummary1.NumberOfFailedSpecs = 0 - suiteSummary2.SuiteSucceeded = false - suiteSummary2.NumberOfPassedSpecs = 5 - suiteSummary2.NumberOfFailedSpecs = 3 - - aggregator.SpecSuiteDidEnd(suiteSummary2) - aggregator.SpecSuiteDidEnd(suiteSummary1) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(2)) - }) - - It("should announce the end of the suite", func() { - compositeSummary := stenographer.Calls()[1].Args[0].(*types.SuiteSummary) - - Ω(compositeSummary.SuiteSucceeded).Should(BeFalse()) - Ω(compositeSummary.NumberOfSpecsThatWillBeRun).Should(Equal(23)) - Ω(compositeSummary.NumberOfTotalSpecs).Should(Equal(30)) - Ω(compositeSummary.NumberOfPassedSpecs).Should(Equal(20)) - Ω(compositeSummary.NumberOfFailedSpecs).Should(Equal(3)) - Ω(compositeSummary.NumberOfPendingSpecs).Should(Equal(3)) - Ω(compositeSummary.NumberOfSkippedSpecs).Should(Equal(4)) - Ω(compositeSummary.RunTime.Seconds()).Should(BeNumerically(">", 0.2)) - }) - }) - - Context("when all the parallel-suites pass", func() { - BeforeEach(func() { - suiteSummary1.SuiteSucceeded = true - suiteSummary2.SuiteSucceeded = true - - aggregator.SpecSuiteDidEnd(suiteSummary2) - aggregator.SpecSuiteDidEnd(suiteSummary1) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(2)) - }) - - It("should report success", func() { - compositeSummary := stenographer.Calls()[1].Args[0].(*types.SuiteSummary) - - Ω(compositeSummary.SuiteSucceeded).Should(BeTrue()) - }) - - It("should notify the channel that it succeded", func(done Done) { - Ω(<-result).Should(BeTrue()) - close(done) - }) - }) - - Context("when one of the parallel-suites fails", func() { - BeforeEach(func() { - suiteSummary1.SuiteSucceeded = true - suiteSummary2.SuiteSucceeded = false - - aggregator.SpecSuiteDidEnd(suiteSummary2) - aggregator.SpecSuiteDidEnd(suiteSummary1) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(2)) - }) - - It("should report failure", func() { - compositeSummary := stenographer.Calls()[1].Args[0].(*types.SuiteSummary) - - Ω(compositeSummary.SuiteSucceeded).Should(BeFalse()) - }) - - It("should notify the channel that it failed", func(done Done) { - Ω(<-result).Should(BeFalse()) - close(done) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/fake_output_interceptor_test.go b/vendor/github.com/onsi/ginkgo/internal/remote/fake_output_interceptor_test.go deleted file mode 100644 index a928f93d..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/fake_output_interceptor_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package remote_test - -type fakeOutputInterceptor struct { - DidStartInterceptingOutput bool - DidStopInterceptingOutput bool - InterceptedOutput string -} - -func (interceptor *fakeOutputInterceptor) StartInterceptingOutput() error { - interceptor.DidStartInterceptingOutput = true - return nil -} - -func (interceptor *fakeOutputInterceptor) StopInterceptingAndReturnOutput() (string, error) { - interceptor.DidStopInterceptingOutput = true - return interceptor.InterceptedOutput, nil -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/fake_poster_test.go b/vendor/github.com/onsi/ginkgo/internal/remote/fake_poster_test.go deleted file mode 100644 index 3543c59c..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/fake_poster_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package remote_test - -import ( - "io" - "io/ioutil" - "net/http" -) - -type post struct { - url string - bodyType string - bodyContent []byte -} - -type fakePoster struct { - posts []post -} - -func newFakePoster() *fakePoster { - return &fakePoster{ - posts: make([]post, 0), - } -} - -func (poster *fakePoster) Post(url string, bodyType string, body io.Reader) (resp *http.Response, err error) { - bodyContent, _ := ioutil.ReadAll(body) - poster.posts = append(poster.posts, post{ - url: url, - bodyType: bodyType, - bodyContent: bodyContent, - }) - return nil, nil -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/forwarding_reporter_test.go b/vendor/github.com/onsi/ginkgo/internal/remote/forwarding_reporter_test.go deleted file mode 100644 index e5f3b1e3..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/forwarding_reporter_test.go +++ /dev/null @@ -1,180 +0,0 @@ -package remote_test - -import ( - "encoding/json" - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/config" - . "github.com/onsi/ginkgo/internal/remote" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" -) - -var _ = Describe("ForwardingReporter", func() { - var ( - reporter *ForwardingReporter - interceptor *fakeOutputInterceptor - poster *fakePoster - suiteSummary *types.SuiteSummary - specSummary *types.SpecSummary - setupSummary *types.SetupSummary - serverHost string - ) - - BeforeEach(func() { - serverHost = "http://127.0.0.1:7788" - - poster = newFakePoster() - - interceptor = &fakeOutputInterceptor{ - InterceptedOutput: "The intercepted output!", - } - - reporter = NewForwardingReporter(serverHost, poster, interceptor) - - suiteSummary = &types.SuiteSummary{ - SuiteDescription: "My Test Suite", - } - - setupSummary = &types.SetupSummary{ - State: types.SpecStatePassed, - } - - specSummary = &types.SpecSummary{ - ComponentTexts: []string{"My", "Spec"}, - State: types.SpecStatePassed, - } - }) - - Context("When a suite begins", func() { - BeforeEach(func() { - reporter.SpecSuiteWillBegin(config.GinkgoConfig, suiteSummary) - }) - - It("should start intercepting output", func() { - Ω(interceptor.DidStartInterceptingOutput).Should(BeTrue()) - }) - - It("should POST the SuiteSummary and Ginkgo Config to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/SpecSuiteWillBegin")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var sentData struct { - SentConfig config.GinkgoConfigType `json:"config"` - SentSuiteSummary *types.SuiteSummary `json:"suite-summary"` - } - - err := json.Unmarshal(poster.posts[0].bodyContent, &sentData) - Ω(err).ShouldNot(HaveOccurred()) - - Ω(sentData.SentConfig).Should(Equal(config.GinkgoConfig)) - Ω(sentData.SentSuiteSummary).Should(Equal(suiteSummary)) - }) - }) - - Context("when a BeforeSuite completes", func() { - BeforeEach(func() { - reporter.BeforeSuiteDidRun(setupSummary) - }) - - It("should stop, then start intercepting output", func() { - Ω(interceptor.DidStopInterceptingOutput).Should(BeTrue()) - Ω(interceptor.DidStartInterceptingOutput).Should(BeTrue()) - }) - - It("should POST the SetupSummary to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/BeforeSuiteDidRun")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var summary *types.SetupSummary - err := json.Unmarshal(poster.posts[0].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - setupSummary.CapturedOutput = interceptor.InterceptedOutput - Ω(summary).Should(Equal(setupSummary)) - }) - }) - - Context("when an AfterSuite completes", func() { - BeforeEach(func() { - reporter.AfterSuiteDidRun(setupSummary) - }) - - It("should stop, then start intercepting output", func() { - Ω(interceptor.DidStopInterceptingOutput).Should(BeTrue()) - Ω(interceptor.DidStartInterceptingOutput).Should(BeTrue()) - }) - - It("should POST the SetupSummary to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/AfterSuiteDidRun")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var summary *types.SetupSummary - err := json.Unmarshal(poster.posts[0].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - setupSummary.CapturedOutput = interceptor.InterceptedOutput - Ω(summary).Should(Equal(setupSummary)) - }) - }) - - Context("When a spec will run", func() { - BeforeEach(func() { - reporter.SpecWillRun(specSummary) - }) - - It("should POST the SpecSummary to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/SpecWillRun")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var summary *types.SpecSummary - err := json.Unmarshal(poster.posts[0].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - Ω(summary).Should(Equal(specSummary)) - }) - - Context("When a spec completes", func() { - BeforeEach(func() { - specSummary.State = types.SpecStatePanicked - reporter.SpecDidComplete(specSummary) - }) - - It("should POST the SpecSummary to the Ginkgo server and include any intercepted output", func() { - Ω(poster.posts).Should(HaveLen(2)) - Ω(poster.posts[1].url).Should(Equal("http://127.0.0.1:7788/SpecDidComplete")) - Ω(poster.posts[1].bodyType).Should(Equal("application/json")) - - var summary *types.SpecSummary - err := json.Unmarshal(poster.posts[1].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - specSummary.CapturedOutput = interceptor.InterceptedOutput - Ω(summary).Should(Equal(specSummary)) - }) - - It("should stop, then start intercepting output", func() { - Ω(interceptor.DidStopInterceptingOutput).Should(BeTrue()) - Ω(interceptor.DidStartInterceptingOutput).Should(BeTrue()) - }) - }) - }) - - Context("When a suite ends", func() { - BeforeEach(func() { - reporter.SpecSuiteDidEnd(suiteSummary) - }) - - It("should POST the SuiteSummary to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/SpecSuiteDidEnd")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var summary *types.SuiteSummary - - err := json.Unmarshal(poster.posts[0].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - - Ω(summary).Should(Equal(suiteSummary)) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor_test.go b/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor_test.go deleted file mode 100644 index 014fdf1a..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package remote_test - -import ( - "fmt" - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/remote" - . "github.com/onsi/gomega" - "os" -) - -var _ = Describe("OutputInterceptor", func() { - var interceptor OutputInterceptor - - BeforeEach(func() { - interceptor = NewOutputInterceptor() - }) - - It("should capture all stdout/stderr output", func() { - err := interceptor.StartInterceptingOutput() - Ω(err).ShouldNot(HaveOccurred()) - - fmt.Fprint(os.Stdout, "STDOUT") - fmt.Fprint(os.Stderr, "STDERR") - print("PRINT") - - output, err := interceptor.StopInterceptingAndReturnOutput() - - Ω(output).Should(Equal("STDOUTSTDERRPRINT")) - Ω(err).ShouldNot(HaveOccurred()) - }) - - It("should error if told to intercept output twice", func() { - err := interceptor.StartInterceptingOutput() - Ω(err).ShouldNot(HaveOccurred()) - - print("A") - - err = interceptor.StartInterceptingOutput() - Ω(err).Should(HaveOccurred()) - - print("B") - - output, err := interceptor.StopInterceptingAndReturnOutput() - - Ω(output).Should(Equal("AB")) - Ω(err).ShouldNot(HaveOccurred()) - }) - - It("should allow multiple interception sessions", func() { - err := interceptor.StartInterceptingOutput() - Ω(err).ShouldNot(HaveOccurred()) - print("A") - output, err := interceptor.StopInterceptingAndReturnOutput() - Ω(output).Should(Equal("A")) - Ω(err).ShouldNot(HaveOccurred()) - - err = interceptor.StartInterceptingOutput() - Ω(err).ShouldNot(HaveOccurred()) - print("B") - output, err = interceptor.StopInterceptingAndReturnOutput() - Ω(output).Should(Equal("B")) - Ω(err).ShouldNot(HaveOccurred()) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/remote_suite_test.go b/vendor/github.com/onsi/ginkgo/internal/remote/remote_suite_test.go deleted file mode 100644 index e6b4e9f3..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/remote_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package remote_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestRemote(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Remote Spec Forwarding Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/server_test.go b/vendor/github.com/onsi/ginkgo/internal/remote/server_test.go deleted file mode 100644 index eb2eefeb..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/server_test.go +++ /dev/null @@ -1,269 +0,0 @@ -package remote_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/remote" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" - - "bytes" - "encoding/json" - "net/http" -) - -var _ = Describe("Server", func() { - var ( - server *Server - ) - - BeforeEach(func() { - var err error - server, err = NewServer(3) - Ω(err).ShouldNot(HaveOccurred()) - - server.Start() - }) - - AfterEach(func() { - server.Close() - }) - - Describe("Streaming endpoints", func() { - var ( - reporterA, reporterB *reporters.FakeReporter - forwardingReporter *ForwardingReporter - - suiteSummary *types.SuiteSummary - setupSummary *types.SetupSummary - specSummary *types.SpecSummary - ) - - BeforeEach(func() { - reporterA = reporters.NewFakeReporter() - reporterB = reporters.NewFakeReporter() - - server.RegisterReporters(reporterA, reporterB) - - forwardingReporter = NewForwardingReporter(server.Address(), &http.Client{}, &fakeOutputInterceptor{}) - - suiteSummary = &types.SuiteSummary{ - SuiteDescription: "My Test Suite", - } - - setupSummary = &types.SetupSummary{ - State: types.SpecStatePassed, - } - - specSummary = &types.SpecSummary{ - ComponentTexts: []string{"My", "Spec"}, - State: types.SpecStatePassed, - } - }) - - It("should make its address available", func() { - Ω(server.Address()).Should(MatchRegexp(`http://127.0.0.1:\d{2,}`)) - }) - - Describe("/SpecSuiteWillBegin", func() { - It("should decode and forward the Ginkgo config and suite summary", func(done Done) { - forwardingReporter.SpecSuiteWillBegin(config.GinkgoConfig, suiteSummary) - Ω(reporterA.Config).Should(Equal(config.GinkgoConfig)) - Ω(reporterB.Config).Should(Equal(config.GinkgoConfig)) - Ω(reporterA.BeginSummary).Should(Equal(suiteSummary)) - Ω(reporterB.BeginSummary).Should(Equal(suiteSummary)) - close(done) - }) - }) - - Describe("/BeforeSuiteDidRun", func() { - It("should decode and forward the setup summary", func() { - forwardingReporter.BeforeSuiteDidRun(setupSummary) - Ω(reporterA.BeforeSuiteSummary).Should(Equal(setupSummary)) - Ω(reporterB.BeforeSuiteSummary).Should(Equal(setupSummary)) - }) - }) - - Describe("/AfterSuiteDidRun", func() { - It("should decode and forward the setup summary", func() { - forwardingReporter.AfterSuiteDidRun(setupSummary) - Ω(reporterA.AfterSuiteSummary).Should(Equal(setupSummary)) - Ω(reporterB.AfterSuiteSummary).Should(Equal(setupSummary)) - }) - }) - - Describe("/SpecWillRun", func() { - It("should decode and forward the spec summary", func(done Done) { - forwardingReporter.SpecWillRun(specSummary) - Ω(reporterA.SpecWillRunSummaries[0]).Should(Equal(specSummary)) - Ω(reporterB.SpecWillRunSummaries[0]).Should(Equal(specSummary)) - close(done) - }) - }) - - Describe("/SpecDidComplete", func() { - It("should decode and forward the spec summary", func(done Done) { - forwardingReporter.SpecDidComplete(specSummary) - Ω(reporterA.SpecSummaries[0]).Should(Equal(specSummary)) - Ω(reporterB.SpecSummaries[0]).Should(Equal(specSummary)) - close(done) - }) - }) - - Describe("/SpecSuiteDidEnd", func() { - It("should decode and forward the suite summary", func(done Done) { - forwardingReporter.SpecSuiteDidEnd(suiteSummary) - Ω(reporterA.EndSummary).Should(Equal(suiteSummary)) - Ω(reporterB.EndSummary).Should(Equal(suiteSummary)) - close(done) - }) - }) - }) - - Describe("Synchronization endpoints", func() { - Describe("GETting and POSTing BeforeSuiteState", func() { - getBeforeSuite := func() types.RemoteBeforeSuiteData { - resp, err := http.Get(server.Address() + "/BeforeSuiteState") - Ω(err).ShouldNot(HaveOccurred()) - Ω(resp.StatusCode).Should(Equal(http.StatusOK)) - - r := types.RemoteBeforeSuiteData{} - decoder := json.NewDecoder(resp.Body) - err = decoder.Decode(&r) - Ω(err).ShouldNot(HaveOccurred()) - - return r - } - - postBeforeSuite := func(r types.RemoteBeforeSuiteData) { - resp, err := http.Post(server.Address()+"/BeforeSuiteState", "application/json", bytes.NewReader(r.ToJSON())) - Ω(err).ShouldNot(HaveOccurred()) - Ω(resp.StatusCode).Should(Equal(http.StatusOK)) - } - - Context("when the first node's Alive has not been registered yet", func() { - It("should return pending", func() { - state := getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending})) - - state = getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending})) - }) - }) - - Context("when the first node is Alive but has not responded yet", func() { - BeforeEach(func() { - server.RegisterAlive(1, func() bool { - return true - }) - }) - - It("should return pending", func() { - state := getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending})) - - state = getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending})) - }) - }) - - Context("when the first node has responded", func() { - var state types.RemoteBeforeSuiteData - BeforeEach(func() { - server.RegisterAlive(1, func() bool { - return false - }) - - state = types.RemoteBeforeSuiteData{ - Data: []byte("my data"), - State: types.RemoteBeforeSuiteStatePassed, - } - postBeforeSuite(state) - }) - - It("should return the passed in state", func() { - returnedState := getBeforeSuite() - Ω(returnedState).Should(Equal(state)) - }) - }) - - Context("when the first node is no longer Alive and has not responded yet", func() { - BeforeEach(func() { - server.RegisterAlive(1, func() bool { - return false - }) - }) - - It("should return disappeared", func() { - state := getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStateDisappeared})) - - state = getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStateDisappeared})) - }) - }) - }) - - Describe("GETting RemoteAfterSuiteData", func() { - getRemoteAfterSuiteData := func() bool { - resp, err := http.Get(server.Address() + "/RemoteAfterSuiteData") - Ω(err).ShouldNot(HaveOccurred()) - Ω(resp.StatusCode).Should(Equal(http.StatusOK)) - - a := types.RemoteAfterSuiteData{} - decoder := json.NewDecoder(resp.Body) - err = decoder.Decode(&a) - Ω(err).ShouldNot(HaveOccurred()) - - return a.CanRun - } - - Context("when there are unregistered nodes", func() { - BeforeEach(func() { - server.RegisterAlive(2, func() bool { - return false - }) - }) - - It("should return false", func() { - Ω(getRemoteAfterSuiteData()).Should(BeFalse()) - }) - }) - - Context("when all none-node-1 nodes are still running", func() { - BeforeEach(func() { - server.RegisterAlive(2, func() bool { - return true - }) - - server.RegisterAlive(3, func() bool { - return false - }) - }) - - It("should return false", func() { - Ω(getRemoteAfterSuiteData()).Should(BeFalse()) - }) - }) - - Context("when all none-1 nodes are done", func() { - BeforeEach(func() { - server.RegisterAlive(2, func() bool { - return false - }) - - server.RegisterAlive(3, func() bool { - return false - }) - }) - - It("should return true", func() { - Ω(getRemoteAfterSuiteData()).Should(BeTrue()) - }) - - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/spec/index_computer_test.go b/vendor/github.com/onsi/ginkgo/internal/spec/index_computer_test.go deleted file mode 100644 index 0396d7bd..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec/index_computer_test.go +++ /dev/null @@ -1,149 +0,0 @@ -package spec_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/spec" - . "github.com/onsi/gomega" -) - -var _ = Describe("ParallelizedIndexRange", func() { - var startIndex, count int - - It("should return the correct index range for 4 tests on 2 nodes", func() { - startIndex, count = ParallelizedIndexRange(4, 2, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(4, 2, 2) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(2)) - }) - - It("should return the correct index range for 5 tests on 2 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 2, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(3)) - - startIndex, count = ParallelizedIndexRange(5, 2, 2) - Ω(startIndex).Should(Equal(3)) - Ω(count).Should(Equal(2)) - }) - - It("should return the correct index range for 5 tests on 3 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 3, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(5, 3, 2) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(5, 3, 3) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(1)) - }) - - It("should return the correct index range for 5 tests on 4 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 4, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(5, 4, 2) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 4, 3) - Ω(startIndex).Should(Equal(3)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 4, 4) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(1)) - }) - - It("should return the correct index range for 5 tests on 5 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 5, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 5, 2) - Ω(startIndex).Should(Equal(1)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 5, 3) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 5, 4) - Ω(startIndex).Should(Equal(3)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 5, 5) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(1)) - }) - - It("should return the correct index range for 5 tests on 6 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 6, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 2) - Ω(startIndex).Should(Equal(1)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 3) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 4) - Ω(startIndex).Should(Equal(3)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 5) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 6) - Ω(count).Should(Equal(0)) - }) - - It("should return the correct index range for 5 tests on 7 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 7, 6) - Ω(count).Should(Equal(0)) - - startIndex, count = ParallelizedIndexRange(5, 7, 7) - Ω(count).Should(Equal(0)) - }) - - It("should return the correct index range for 11 tests on 7 nodes", func() { - startIndex, count = ParallelizedIndexRange(11, 7, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(11, 7, 2) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(11, 7, 3) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(11, 7, 4) - Ω(startIndex).Should(Equal(6)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(11, 7, 5) - Ω(startIndex).Should(Equal(8)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(11, 7, 6) - Ω(startIndex).Should(Equal(9)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(11, 7, 7) - Ω(startIndex).Should(Equal(10)) - Ω(count).Should(Equal(1)) - }) - -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/spec/spec_suite_test.go b/vendor/github.com/onsi/ginkgo/internal/spec/spec_suite_test.go deleted file mode 100644 index 8681a720..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec/spec_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package spec_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestSpec(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Spec Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/internal/spec/spec_test.go b/vendor/github.com/onsi/ginkgo/internal/spec/spec_test.go deleted file mode 100644 index 6d0f58cb..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec/spec_test.go +++ /dev/null @@ -1,626 +0,0 @@ -package spec_test - -import ( - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" - - . "github.com/onsi/ginkgo/internal/spec" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/containernode" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/types" -) - -var noneFlag = types.FlagTypeNone -var focusedFlag = types.FlagTypeFocused -var pendingFlag = types.FlagTypePending - -var _ = Describe("Spec", func() { - var ( - failer *Failer.Failer - codeLocation types.CodeLocation - nodesThatRan []string - spec *Spec - buffer *gbytes.Buffer - ) - - newBody := func(text string, fail bool) func() { - return func() { - nodesThatRan = append(nodesThatRan, text) - if fail { - failer.Fail(text, codeLocation) - } - } - } - - newIt := func(text string, flag types.FlagType, fail bool) *leafnodes.ItNode { - return leafnodes.NewItNode(text, newBody(text, fail), flag, codeLocation, 0, failer, 0) - } - - newItWithBody := func(text string, body interface{}) *leafnodes.ItNode { - return leafnodes.NewItNode(text, body, noneFlag, codeLocation, 0, failer, 0) - } - - newMeasure := func(text string, flag types.FlagType, fail bool, samples int) *leafnodes.MeasureNode { - return leafnodes.NewMeasureNode(text, func(Benchmarker) { - nodesThatRan = append(nodesThatRan, text) - if fail { - failer.Fail(text, codeLocation) - } - }, flag, codeLocation, samples, failer, 0) - } - - newBef := func(text string, fail bool) leafnodes.BasicNode { - return leafnodes.NewBeforeEachNode(newBody(text, fail), codeLocation, 0, failer, 0) - } - - newAft := func(text string, fail bool) leafnodes.BasicNode { - return leafnodes.NewAfterEachNode(newBody(text, fail), codeLocation, 0, failer, 0) - } - - newJusBef := func(text string, fail bool) leafnodes.BasicNode { - return leafnodes.NewJustBeforeEachNode(newBody(text, fail), codeLocation, 0, failer, 0) - } - - newContainer := func(text string, flag types.FlagType, setupNodes ...leafnodes.BasicNode) *containernode.ContainerNode { - c := containernode.New(text, flag, codeLocation) - for _, node := range setupNodes { - c.PushSetupNode(node) - } - return c - } - - containers := func(containers ...*containernode.ContainerNode) []*containernode.ContainerNode { - return containers - } - - BeforeEach(func() { - buffer = gbytes.NewBuffer() - failer = Failer.New() - codeLocation = codelocation.New(0) - nodesThatRan = []string{} - }) - - Describe("marking specs focused and pending", func() { - It("should satisfy various caes", func() { - cases := []struct { - ContainerFlags []types.FlagType - SubjectFlag types.FlagType - Pending bool - Focused bool - }{ - {[]types.FlagType{}, noneFlag, false, false}, - {[]types.FlagType{}, focusedFlag, false, true}, - {[]types.FlagType{}, pendingFlag, true, false}, - {[]types.FlagType{noneFlag}, noneFlag, false, false}, - {[]types.FlagType{focusedFlag}, noneFlag, false, true}, - {[]types.FlagType{pendingFlag}, noneFlag, true, false}, - {[]types.FlagType{noneFlag}, focusedFlag, false, true}, - {[]types.FlagType{focusedFlag}, focusedFlag, false, true}, - {[]types.FlagType{pendingFlag}, focusedFlag, true, true}, - {[]types.FlagType{noneFlag}, pendingFlag, true, false}, - {[]types.FlagType{focusedFlag}, pendingFlag, true, true}, - {[]types.FlagType{pendingFlag}, pendingFlag, true, false}, - {[]types.FlagType{focusedFlag, noneFlag}, noneFlag, false, true}, - {[]types.FlagType{noneFlag, focusedFlag}, noneFlag, false, true}, - {[]types.FlagType{pendingFlag, noneFlag}, noneFlag, true, false}, - {[]types.FlagType{noneFlag, pendingFlag}, noneFlag, true, false}, - {[]types.FlagType{focusedFlag, pendingFlag}, noneFlag, true, true}, - } - - for i, c := range cases { - subject := newIt("it node", c.SubjectFlag, false) - containers := []*containernode.ContainerNode{} - for _, flag := range c.ContainerFlags { - containers = append(containers, newContainer("container", flag)) - } - - spec := New(subject, containers, false) - Ω(spec.Pending()).Should(Equal(c.Pending), "Case %d: %#v", i, c) - Ω(spec.Focused()).Should(Equal(c.Focused), "Case %d: %#v", i, c) - - if c.Pending { - Ω(spec.Summary("").State).Should(Equal(types.SpecStatePending)) - } - } - }) - }) - - Describe("Skip", func() { - It("should be skipped", func() { - spec := New(newIt("it node", noneFlag, false), containers(newContainer("container", noneFlag)), false) - Ω(spec.Skipped()).Should(BeFalse()) - spec.Skip() - Ω(spec.Skipped()).Should(BeTrue()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStateSkipped)) - }) - }) - - Describe("IsMeasurement", func() { - It("should be true if the subject is a measurement node", func() { - spec := New(newIt("it node", noneFlag, false), containers(newContainer("container", noneFlag)), false) - Ω(spec.IsMeasurement()).Should(BeFalse()) - Ω(spec.Summary("").IsMeasurement).Should(BeFalse()) - Ω(spec.Summary("").NumberOfSamples).Should(Equal(1)) - - spec = New(newMeasure("measure node", noneFlag, false, 10), containers(newContainer("container", noneFlag)), false) - Ω(spec.IsMeasurement()).Should(BeTrue()) - Ω(spec.Summary("").IsMeasurement).Should(BeTrue()) - Ω(spec.Summary("").NumberOfSamples).Should(Equal(10)) - }) - }) - - Describe("Passed", func() { - It("should pass when the subject passed", func() { - spec := New(newIt("it node", noneFlag, false), containers(), false) - spec.Run(buffer) - - Ω(spec.Passed()).Should(BeTrue()) - Ω(spec.Failed()).Should(BeFalse()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStatePassed)) - Ω(spec.Summary("").Failure).Should(BeZero()) - }) - }) - - Describe("Failed", func() { - It("should be failed if the failure was panic", func() { - spec := New(newItWithBody("panicky it", func() { - panic("bam") - }), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStatePanicked)) - Ω(spec.Summary("").Failure.Message).Should(Equal("Test Panicked")) - Ω(spec.Summary("").Failure.ForwardedPanic).Should(Equal("bam")) - }) - - It("should be failed if the failure was a timeout", func() { - spec := New(newItWithBody("sleepy it", func(done Done) {}), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStateTimedOut)) - Ω(spec.Summary("").Failure.Message).Should(Equal("Timed out")) - }) - - It("should be failed if the failure was... a failure", func() { - spec := New(newItWithBody("failing it", func() { - failer.Fail("bam", codeLocation) - }), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStateFailed)) - Ω(spec.Summary("").Failure.Message).Should(Equal("bam")) - }) - }) - - Describe("Concatenated string", func() { - It("should concatenate the texts of the containers and the subject", func() { - spec := New( - newIt("it node", noneFlag, false), - containers( - newContainer("outer container", noneFlag), - newContainer("inner container", noneFlag), - ), - false, - ) - - Ω(spec.ConcatenatedString()).Should(Equal("outer container inner container it node")) - }) - }) - - Describe("running it specs", func() { - Context("with just an it", func() { - Context("that succeeds", func() { - It("should run the it and report on its success", func() { - spec := New(newIt("it node", noneFlag, false), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeTrue()) - Ω(spec.Failed()).Should(BeFalse()) - Ω(nodesThatRan).Should(Equal([]string{"it node"})) - }) - }) - - Context("that fails", func() { - It("should run the it and report on its success", func() { - spec := New(newIt("it node", noneFlag, true), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(spec.Summary("").Failure.Message).Should(Equal("it node")) - Ω(nodesThatRan).Should(Equal([]string{"it node"})) - }) - }) - }) - - Context("with a full set of setup nodes", func() { - var failingNodes map[string]bool - - BeforeEach(func() { - failingNodes = map[string]bool{} - }) - - JustBeforeEach(func() { - spec = New( - newIt("it node", noneFlag, failingNodes["it node"]), - containers( - newContainer("outer container", noneFlag, - newBef("outer bef A", failingNodes["outer bef A"]), - newBef("outer bef B", failingNodes["outer bef B"]), - newJusBef("outer jusbef A", failingNodes["outer jusbef A"]), - newJusBef("outer jusbef B", failingNodes["outer jusbef B"]), - newAft("outer aft A", failingNodes["outer aft A"]), - newAft("outer aft B", failingNodes["outer aft B"]), - ), - newContainer("inner container", noneFlag, - newBef("inner bef A", failingNodes["inner bef A"]), - newBef("inner bef B", failingNodes["inner bef B"]), - newJusBef("inner jusbef A", failingNodes["inner jusbef A"]), - newJusBef("inner jusbef B", failingNodes["inner jusbef B"]), - newAft("inner aft A", failingNodes["inner aft A"]), - newAft("inner aft B", failingNodes["inner aft B"]), - ), - ), - false, - ) - spec.Run(buffer) - }) - - Context("that all pass", func() { - It("should walk through the nodes in the correct order", func() { - Ω(spec.Passed()).Should(BeTrue()) - Ω(spec.Failed()).Should(BeFalse()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner jusbef A", - "inner jusbef B", - "it node", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - }) - }) - - Context("when the subject fails", func() { - BeforeEach(func() { - failingNodes["it node"] = true - }) - - It("should run the afters", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner jusbef A", - "inner jusbef B", - "it node", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("it node")) - }) - }) - - Context("when an inner before fails", func() { - BeforeEach(func() { - failingNodes["inner bef A"] = true - }) - - It("should not run any other befores, but it should run the subsequent afters", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("inner bef A")) - }) - }) - - Context("when an outer before fails", func() { - BeforeEach(func() { - failingNodes["outer bef B"] = true - }) - - It("should not run any other befores, but it should run the subsequent afters", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("outer bef B")) - }) - }) - - Context("when an after fails", func() { - BeforeEach(func() { - failingNodes["inner aft B"] = true - }) - - It("should run all other afters, but mark the test as failed", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner jusbef A", - "inner jusbef B", - "it node", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("inner aft B")) - }) - }) - - Context("when a just before each fails", func() { - BeforeEach(func() { - failingNodes["outer jusbef B"] = true - }) - - It("should run the afters, but not the subject", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("outer jusbef B")) - }) - }) - - Context("when an after fails after an earlier node has failed", func() { - BeforeEach(func() { - failingNodes["it node"] = true - failingNodes["inner aft B"] = true - }) - - It("should record the earlier failure", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner jusbef A", - "inner jusbef B", - "it node", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("it node")) - }) - }) - }) - }) - - Describe("running measurement specs", func() { - Context("when the measurement succeeds", func() { - It("should run N samples", func() { - spec = New( - newMeasure("measure node", noneFlag, false, 3), - containers( - newContainer("container", noneFlag, - newBef("bef A", false), - newJusBef("jusbef A", false), - newAft("aft A", false), - ), - ), - false, - ) - spec.Run(buffer) - - Ω(spec.Passed()).Should(BeTrue()) - Ω(spec.Failed()).Should(BeFalse()) - Ω(nodesThatRan).Should(Equal([]string{ - "bef A", - "jusbef A", - "measure node", - "aft A", - "bef A", - "jusbef A", - "measure node", - "aft A", - "bef A", - "jusbef A", - "measure node", - "aft A", - })) - }) - }) - - Context("when the measurement fails", func() { - It("should bail after the failure occurs", func() { - spec = New( - newMeasure("measure node", noneFlag, true, 3), - containers( - newContainer("container", noneFlag, - newBef("bef A", false), - newJusBef("jusbef A", false), - newAft("aft A", false), - ), - ), - false, - ) - spec.Run(buffer) - - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "bef A", - "jusbef A", - "measure node", - "aft A", - })) - }) - }) - }) - - Describe("Summary", func() { - var ( - subjectCodeLocation types.CodeLocation - outerContainerCodeLocation types.CodeLocation - innerContainerCodeLocation types.CodeLocation - summary *types.SpecSummary - ) - - BeforeEach(func() { - subjectCodeLocation = codelocation.New(0) - outerContainerCodeLocation = codelocation.New(0) - innerContainerCodeLocation = codelocation.New(0) - - spec = New( - leafnodes.NewItNode("it node", func() { - time.Sleep(10 * time.Millisecond) - }, noneFlag, subjectCodeLocation, 0, failer, 0), - containers( - containernode.New("outer container", noneFlag, outerContainerCodeLocation), - containernode.New("inner container", noneFlag, innerContainerCodeLocation), - ), - false, - ) - - spec.Run(buffer) - Ω(spec.Passed()).Should(BeTrue()) - summary = spec.Summary("suite id") - }) - - It("should have the suite id", func() { - Ω(summary.SuiteID).Should(Equal("suite id")) - }) - - It("should have the component texts and code locations", func() { - Ω(summary.ComponentTexts).Should(Equal([]string{"outer container", "inner container", "it node"})) - Ω(summary.ComponentCodeLocations).Should(Equal([]types.CodeLocation{outerContainerCodeLocation, innerContainerCodeLocation, subjectCodeLocation})) - }) - - It("should have a runtime", func() { - Ω(summary.RunTime).Should(BeNumerically(">=", 10*time.Millisecond)) - }) - - It("should not be a measurement, or have a measurement summary", func() { - Ω(summary.IsMeasurement).Should(BeFalse()) - Ω(summary.Measurements).Should(BeEmpty()) - }) - }) - - Describe("Summaries for measurements", func() { - var summary *types.SpecSummary - - BeforeEach(func() { - spec = New(leafnodes.NewMeasureNode("measure node", func(b Benchmarker) { - b.RecordValue("a value", 7, "some info") - }, noneFlag, codeLocation, 4, failer, 0), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeTrue()) - summary = spec.Summary("suite id") - }) - - It("should include the number of samples", func() { - Ω(summary.NumberOfSamples).Should(Equal(4)) - }) - - It("should be a measurement", func() { - Ω(summary.IsMeasurement).Should(BeTrue()) - }) - - It("should have the measurements report", func() { - Ω(summary.Measurements).Should(HaveKey("a value")) - - report := summary.Measurements["a value"] - Ω(report.Name).Should(Equal("a value")) - Ω(report.Info).Should(Equal("some info")) - Ω(report.Results).Should(Equal([]float64{7, 7, 7, 7})) - }) - }) - - Describe("When told to emit progress", func() { - It("should emit progress to the writer as it runs Befores, JustBefores, Afters, and Its", func() { - spec = New( - newIt("it node", noneFlag, false), - containers( - newContainer("outer container", noneFlag, - newBef("outer bef A", false), - newJusBef("outer jusbef A", false), - newAft("outer aft A", false), - ), - newContainer("inner container", noneFlag, - newBef("inner bef A", false), - newJusBef("inner jusbef A", false), - newAft("inner aft A", false), - ), - ), - true, - ) - spec.Run(buffer) - - Ω(buffer).Should(gbytes.Say(`\[BeforeEach\] outer container`)) - Ω(buffer).Should(gbytes.Say(`\[BeforeEach\] inner container`)) - Ω(buffer).Should(gbytes.Say(`\[JustBeforeEach\] outer container`)) - Ω(buffer).Should(gbytes.Say(`\[JustBeforeEach\] inner container`)) - Ω(buffer).Should(gbytes.Say(`\[It\] it node`)) - Ω(buffer).Should(gbytes.Say(`\[AfterEach\] inner container`)) - Ω(buffer).Should(gbytes.Say(`\[AfterEach\] outer container`)) - }) - - It("should emit progress to the writer as it runs Befores, JustBefores, Afters, and Measures", func() { - spec = New( - newMeasure("measure node", noneFlag, false, 2), - containers(), - true, - ) - spec.Run(buffer) - - Ω(buffer).Should(gbytes.Say(`\[Measure\] measure node`)) - Ω(buffer).Should(gbytes.Say(`\[Measure\] measure node`)) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/spec/specs_test.go b/vendor/github.com/onsi/ginkgo/internal/spec/specs_test.go deleted file mode 100644 index b58a3074..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec/specs_test.go +++ /dev/null @@ -1,305 +0,0 @@ -package spec_test - -import ( - "math/rand" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/spec" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/containernode" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("Specs", func() { - var specs *Specs - - newSpec := func(text string, flag types.FlagType) *Spec { - subject := leafnodes.NewItNode(text, func() {}, flag, codelocation.New(0), 0, nil, 0) - return New(subject, []*containernode.ContainerNode{}, false) - } - - newMeasureSpec := func(text string, flag types.FlagType) *Spec { - subject := leafnodes.NewMeasureNode(text, func(Benchmarker) {}, flag, codelocation.New(0), 0, nil, 0) - return New(subject, []*containernode.ContainerNode{}, false) - } - - newSpecs := func(args ...interface{}) *Specs { - specs := []*Spec{} - for index := 0; index < len(args)-1; index += 2 { - specs = append(specs, newSpec(args[index].(string), args[index+1].(types.FlagType))) - } - return NewSpecs(specs) - } - - specTexts := func(specs *Specs) []string { - texts := []string{} - for _, spec := range specs.Specs() { - texts = append(texts, spec.ConcatenatedString()) - } - return texts - } - - willRunTexts := func(specs *Specs) []string { - texts := []string{} - for _, spec := range specs.Specs() { - if !(spec.Skipped() || spec.Pending()) { - texts = append(texts, spec.ConcatenatedString()) - } - } - return texts - } - - skippedTexts := func(specs *Specs) []string { - texts := []string{} - for _, spec := range specs.Specs() { - if spec.Skipped() { - texts = append(texts, spec.ConcatenatedString()) - } - } - return texts - } - - pendingTexts := func(specs *Specs) []string { - texts := []string{} - for _, spec := range specs.Specs() { - if spec.Pending() { - texts = append(texts, spec.ConcatenatedString()) - } - } - return texts - } - - Describe("Shuffling specs", func() { - It("should shuffle the specs using the passed in randomizer", func() { - specs17 := newSpecs("C", noneFlag, "A", noneFlag, "B", noneFlag) - specs17.Shuffle(rand.New(rand.NewSource(17))) - texts17 := specTexts(specs17) - - specs17Again := newSpecs("C", noneFlag, "A", noneFlag, "B", noneFlag) - specs17Again.Shuffle(rand.New(rand.NewSource(17))) - texts17Again := specTexts(specs17Again) - - specs15 := newSpecs("C", noneFlag, "A", noneFlag, "B", noneFlag) - specs15.Shuffle(rand.New(rand.NewSource(15))) - texts15 := specTexts(specs15) - - specsUnshuffled := newSpecs("C", noneFlag, "A", noneFlag, "B", noneFlag) - textsUnshuffled := specTexts(specsUnshuffled) - - Ω(textsUnshuffled).Should(Equal([]string{"C", "A", "B"})) - - Ω(texts17).Should(Equal(texts17Again)) - Ω(texts17).ShouldNot(Equal(texts15)) - Ω(texts17).ShouldNot(Equal(textsUnshuffled)) - Ω(texts15).ShouldNot(Equal(textsUnshuffled)) - - Ω(texts17).Should(HaveLen(3)) - Ω(texts17).Should(ContainElement("A")) - Ω(texts17).Should(ContainElement("B")) - Ω(texts17).Should(ContainElement("C")) - - Ω(texts15).Should(HaveLen(3)) - Ω(texts15).Should(ContainElement("A")) - Ω(texts15).Should(ContainElement("B")) - Ω(texts15).Should(ContainElement("C")) - }) - }) - - Describe("with no programmatic focus", func() { - BeforeEach(func() { - specs = newSpecs("A1", noneFlag, "A2", noneFlag, "B1", noneFlag, "B2", pendingFlag) - specs.ApplyFocus("", "", "") - }) - - It("should not report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeFalse()) - }) - }) - - Describe("Applying focus/skip", func() { - var description, focusString, skipString string - - BeforeEach(func() { - description, focusString, skipString = "", "", "" - }) - - JustBeforeEach(func() { - specs = newSpecs("A1", focusedFlag, "A2", noneFlag, "B1", focusedFlag, "B2", pendingFlag) - specs.ApplyFocus(description, focusString, skipString) - }) - - Context("with neither a focus string nor a skip string", func() { - It("should apply the programmatic focus", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A1", "B1"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"A2", "B2"})) - Ω(pendingTexts(specs)).Should(BeEmpty()) - }) - - It("should report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeTrue()) - }) - }) - - Context("with a focus regexp", func() { - BeforeEach(func() { - focusString = "A" - }) - - It("should override the programmatic focus", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A1", "A2"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"B1", "B2"})) - Ω(pendingTexts(specs)).Should(BeEmpty()) - }) - - It("should not report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeFalse()) - }) - }) - - Context("with a focus regexp", func() { - BeforeEach(func() { - focusString = "B" - }) - - It("should not override any pendings", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"B1"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"A1", "A2"})) - Ω(pendingTexts(specs)).Should(Equal([]string{"B2"})) - }) - }) - - Context("with a description", func() { - BeforeEach(func() { - description = "C" - focusString = "C" - }) - - It("should include the description in the focus determination", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A1", "A2", "B1"})) - Ω(skippedTexts(specs)).Should(BeEmpty()) - Ω(pendingTexts(specs)).Should(Equal([]string{"B2"})) - }) - }) - - Context("with a description", func() { - BeforeEach(func() { - description = "C" - skipString = "C" - }) - - It("should include the description in the focus determination", func() { - Ω(willRunTexts(specs)).Should(BeEmpty()) - Ω(skippedTexts(specs)).Should(Equal([]string{"A1", "A2", "B1", "B2"})) - Ω(pendingTexts(specs)).Should(BeEmpty()) - }) - }) - - Context("with a skip regexp", func() { - BeforeEach(func() { - skipString = "A" - }) - - It("should override the programmatic focus", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"B1"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"A1", "A2"})) - Ω(pendingTexts(specs)).Should(Equal([]string{"B2"})) - }) - - It("should not report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeFalse()) - }) - }) - - Context("with both a focus and a skip regexp", func() { - BeforeEach(func() { - focusString = "1" - skipString = "B" - }) - - It("should AND the two", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A1"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"A2", "B1", "B2"})) - Ω(pendingTexts(specs)).Should(BeEmpty()) - }) - - It("should not report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeFalse()) - }) - }) - }) - - Describe("skipping measurements", func() { - BeforeEach(func() { - specs = NewSpecs([]*Spec{ - newSpec("A", noneFlag), - newSpec("B", noneFlag), - newSpec("C", pendingFlag), - newMeasureSpec("measurementA", noneFlag), - newMeasureSpec("measurementB", pendingFlag), - }) - }) - - It("should skip measurements", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A", "B", "measurementA"})) - Ω(skippedTexts(specs)).Should(BeEmpty()) - Ω(pendingTexts(specs)).Should(Equal([]string{"C", "measurementB"})) - - specs.SkipMeasurements() - - Ω(willRunTexts(specs)).Should(Equal([]string{"A", "B"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"measurementA", "measurementB"})) - Ω(pendingTexts(specs)).Should(Equal([]string{"C"})) - }) - }) - - Describe("when running tests in parallel", func() { - It("should select out a subset of the tests", func() { - specsNode1 := newSpecs("A", noneFlag, "B", noneFlag, "C", noneFlag, "D", noneFlag, "E", noneFlag) - specsNode2 := newSpecs("A", noneFlag, "B", noneFlag, "C", noneFlag, "D", noneFlag, "E", noneFlag) - specsNode3 := newSpecs("A", noneFlag, "B", noneFlag, "C", noneFlag, "D", noneFlag, "E", noneFlag) - - specsNode1.TrimForParallelization(3, 1) - specsNode2.TrimForParallelization(3, 2) - specsNode3.TrimForParallelization(3, 3) - - Ω(willRunTexts(specsNode1)).Should(Equal([]string{"A", "B"})) - Ω(willRunTexts(specsNode2)).Should(Equal([]string{"C", "D"})) - Ω(willRunTexts(specsNode3)).Should(Equal([]string{"E"})) - - Ω(specsNode1.Specs()).Should(HaveLen(2)) - Ω(specsNode2.Specs()).Should(HaveLen(2)) - Ω(specsNode3.Specs()).Should(HaveLen(1)) - - Ω(specsNode1.NumberOfOriginalSpecs()).Should(Equal(5)) - Ω(specsNode2.NumberOfOriginalSpecs()).Should(Equal(5)) - Ω(specsNode3.NumberOfOriginalSpecs()).Should(Equal(5)) - }) - - Context("when way too many nodes are used", func() { - It("should return 0 specs", func() { - specsNode1 := newSpecs("A", noneFlag, "B", noneFlag) - specsNode2 := newSpecs("A", noneFlag, "B", noneFlag) - specsNode3 := newSpecs("A", noneFlag, "B", noneFlag) - - specsNode1.TrimForParallelization(3, 1) - specsNode2.TrimForParallelization(3, 2) - specsNode3.TrimForParallelization(3, 3) - - Ω(willRunTexts(specsNode1)).Should(Equal([]string{"A"})) - Ω(willRunTexts(specsNode2)).Should(Equal([]string{"B"})) - Ω(willRunTexts(specsNode3)).Should(BeEmpty()) - - Ω(specsNode1.Specs()).Should(HaveLen(1)) - Ω(specsNode2.Specs()).Should(HaveLen(1)) - Ω(specsNode3.Specs()).Should(HaveLen(0)) - - Ω(specsNode1.NumberOfOriginalSpecs()).Should(Equal(2)) - Ω(specsNode2.NumberOfOriginalSpecs()).Should(Equal(2)) - Ω(specsNode3.NumberOfOriginalSpecs()).Should(Equal(2)) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner_suite_test.go b/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner_suite_test.go deleted file mode 100644 index c8388fb6..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package specrunner_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestSpecRunner(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Spec Runner Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner_test.go b/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner_test.go deleted file mode 100644 index 99686d3e..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner_test.go +++ /dev/null @@ -1,623 +0,0 @@ -package specrunner_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/specrunner" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/containernode" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/internal/spec" - Writer "github.com/onsi/ginkgo/internal/writer" - "github.com/onsi/ginkgo/reporters" -) - -var noneFlag = types.FlagTypeNone -var focusedFlag = types.FlagTypeFocused -var pendingFlag = types.FlagTypePending - -var _ = Describe("Spec Runner", func() { - var ( - reporter1 *reporters.FakeReporter - reporter2 *reporters.FakeReporter - failer *Failer.Failer - writer *Writer.FakeGinkgoWriter - - thingsThatRan []string - - runner *SpecRunner - ) - - newBefSuite := func(text string, fail bool) leafnodes.SuiteNode { - return leafnodes.NewBeforeSuiteNode(func() { - writer.AddEvent(text) - thingsThatRan = append(thingsThatRan, text) - if fail { - failer.Fail(text, codelocation.New(0)) - } - }, codelocation.New(0), 0, failer) - } - - newAftSuite := func(text string, fail bool) leafnodes.SuiteNode { - return leafnodes.NewAfterSuiteNode(func() { - writer.AddEvent(text) - thingsThatRan = append(thingsThatRan, text) - if fail { - failer.Fail(text, codelocation.New(0)) - } - }, codelocation.New(0), 0, failer) - } - - newSpec := func(text string, flag types.FlagType, fail bool) *spec.Spec { - subject := leafnodes.NewItNode(text, func() { - writer.AddEvent(text) - thingsThatRan = append(thingsThatRan, text) - if fail { - failer.Fail(text, codelocation.New(0)) - } - }, flag, codelocation.New(0), 0, failer, 0) - - return spec.New(subject, []*containernode.ContainerNode{}, false) - } - - newSpecWithBody := func(text string, body interface{}) *spec.Spec { - subject := leafnodes.NewItNode(text, body, noneFlag, codelocation.New(0), 0, failer, 0) - - return spec.New(subject, []*containernode.ContainerNode{}, false) - } - - newRunner := func(config config.GinkgoConfigType, beforeSuiteNode leafnodes.SuiteNode, afterSuiteNode leafnodes.SuiteNode, specs ...*spec.Spec) *SpecRunner { - return New("description", beforeSuiteNode, spec.NewSpecs(specs), afterSuiteNode, []reporters.Reporter{reporter1, reporter2}, writer, config) - } - - BeforeEach(func() { - reporter1 = reporters.NewFakeReporter() - reporter2 = reporters.NewFakeReporter() - writer = Writer.NewFake() - failer = Failer.New() - - thingsThatRan = []string{} - }) - - Describe("Running and Reporting", func() { - var specA, pendingSpec, anotherPendingSpec, failedSpec, specB, skippedSpec *spec.Spec - var willRunCalls, didCompleteCalls []string - var conf config.GinkgoConfigType - - JustBeforeEach(func() { - willRunCalls = []string{} - didCompleteCalls = []string{} - specA = newSpec("spec A", noneFlag, false) - pendingSpec = newSpec("pending spec", pendingFlag, false) - anotherPendingSpec = newSpec("another pending spec", pendingFlag, false) - failedSpec = newSpec("failed spec", noneFlag, true) - specB = newSpec("spec B", noneFlag, false) - skippedSpec = newSpec("skipped spec", noneFlag, false) - skippedSpec.Skip() - - reporter1.SpecWillRunStub = func(specSummary *types.SpecSummary) { - willRunCalls = append(willRunCalls, "Reporter1") - } - reporter2.SpecWillRunStub = func(specSummary *types.SpecSummary) { - willRunCalls = append(willRunCalls, "Reporter2") - } - - reporter1.SpecDidCompleteStub = func(specSummary *types.SpecSummary) { - didCompleteCalls = append(didCompleteCalls, "Reporter1") - } - reporter2.SpecDidCompleteStub = func(specSummary *types.SpecSummary) { - didCompleteCalls = append(didCompleteCalls, "Reporter2") - } - - runner = newRunner(conf, newBefSuite("BefSuite", false), newAftSuite("AftSuite", false), specA, pendingSpec, anotherPendingSpec, failedSpec, specB, skippedSpec) - runner.Run() - }) - - BeforeEach(func() { - conf = config.GinkgoConfigType{RandomSeed: 17} - }) - - It("should skip skipped/pending tests", func() { - Ω(thingsThatRan).Should(Equal([]string{"BefSuite", "spec A", "failed spec", "spec B", "AftSuite"})) - }) - - It("should report to any attached reporters", func() { - Ω(reporter1.Config).Should(Equal(reporter2.Config)) - Ω(reporter1.BeforeSuiteSummary).Should(Equal(reporter2.BeforeSuiteSummary)) - Ω(reporter1.BeginSummary).Should(Equal(reporter2.BeginSummary)) - Ω(reporter1.SpecWillRunSummaries).Should(Equal(reporter2.SpecWillRunSummaries)) - Ω(reporter1.SpecSummaries).Should(Equal(reporter2.SpecSummaries)) - Ω(reporter1.AfterSuiteSummary).Should(Equal(reporter2.AfterSuiteSummary)) - Ω(reporter1.EndSummary).Should(Equal(reporter2.EndSummary)) - }) - - It("should report that a spec did end in reverse order", func() { - Ω(willRunCalls[0:4]).Should(Equal([]string{"Reporter1", "Reporter2", "Reporter1", "Reporter2"})) - Ω(didCompleteCalls[0:4]).Should(Equal([]string{"Reporter2", "Reporter1", "Reporter2", "Reporter1"})) - }) - - It("should report the passed in config", func() { - Ω(reporter1.Config.RandomSeed).Should(BeNumerically("==", 17)) - }) - - It("should report the beginning of the suite", func() { - Ω(reporter1.BeginSummary.SuiteDescription).Should(Equal("description")) - Ω(reporter1.BeginSummary.SuiteID).Should(MatchRegexp("[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}")) - Ω(reporter1.BeginSummary.NumberOfSpecsBeforeParallelization).Should(Equal(6)) - Ω(reporter1.BeginSummary.NumberOfTotalSpecs).Should(Equal(6)) - Ω(reporter1.BeginSummary.NumberOfSpecsThatWillBeRun).Should(Equal(3)) - Ω(reporter1.BeginSummary.NumberOfPendingSpecs).Should(Equal(2)) - Ω(reporter1.BeginSummary.NumberOfSkippedSpecs).Should(Equal(1)) - }) - - It("should report the end of the suite", func() { - Ω(reporter1.EndSummary.SuiteDescription).Should(Equal("description")) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteID).Should(MatchRegexp("[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}")) - Ω(reporter1.EndSummary.NumberOfSpecsBeforeParallelization).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfTotalSpecs).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(3)) - Ω(reporter1.EndSummary.NumberOfPendingSpecs).Should(Equal(2)) - Ω(reporter1.EndSummary.NumberOfSkippedSpecs).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfPassedSpecs).Should(Equal(2)) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(1)) - }) - - Context("when told to perform a dry run", func() { - BeforeEach(func() { - conf.DryRun = true - }) - - It("should report to the reporters", func() { - Ω(reporter1.Config).Should(Equal(reporter2.Config)) - Ω(reporter1.BeforeSuiteSummary).Should(Equal(reporter2.BeforeSuiteSummary)) - Ω(reporter1.BeginSummary).Should(Equal(reporter2.BeginSummary)) - Ω(reporter1.SpecWillRunSummaries).Should(Equal(reporter2.SpecWillRunSummaries)) - Ω(reporter1.SpecSummaries).Should(Equal(reporter2.SpecSummaries)) - Ω(reporter1.AfterSuiteSummary).Should(Equal(reporter2.AfterSuiteSummary)) - Ω(reporter1.EndSummary).Should(Equal(reporter2.EndSummary)) - }) - - It("should not actually run anything", func() { - Ω(thingsThatRan).Should(BeEmpty()) - }) - - It("report before and after suites as passed", func() { - Ω(reporter1.BeforeSuiteSummary.State).Should(Equal(types.SpecStatePassed)) - Ω(reporter1.AfterSuiteSummary.State).Should(Equal(types.SpecStatePassed)) - }) - - It("should report specs as passed", func() { - summaries := reporter1.SpecSummaries - Ω(summaries).Should(HaveLen(6)) - Ω(summaries[0].ComponentTexts).Should(ContainElement("spec A")) - Ω(summaries[0].State).Should(Equal(types.SpecStatePassed)) - Ω(summaries[1].ComponentTexts).Should(ContainElement("pending spec")) - Ω(summaries[1].State).Should(Equal(types.SpecStatePending)) - Ω(summaries[2].ComponentTexts).Should(ContainElement("another pending spec")) - Ω(summaries[2].State).Should(Equal(types.SpecStatePending)) - Ω(summaries[3].ComponentTexts).Should(ContainElement("failed spec")) - Ω(summaries[3].State).Should(Equal(types.SpecStatePassed)) - Ω(summaries[4].ComponentTexts).Should(ContainElement("spec B")) - Ω(summaries[4].State).Should(Equal(types.SpecStatePassed)) - Ω(summaries[5].ComponentTexts).Should(ContainElement("skipped spec")) - Ω(summaries[5].State).Should(Equal(types.SpecStateSkipped)) - }) - - It("should report the end of the suite", func() { - Ω(reporter1.EndSummary.SuiteDescription).Should(Equal("description")) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeTrue()) - Ω(reporter1.EndSummary.SuiteID).Should(MatchRegexp("[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}")) - Ω(reporter1.EndSummary.NumberOfSpecsBeforeParallelization).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfTotalSpecs).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(3)) - Ω(reporter1.EndSummary.NumberOfPendingSpecs).Should(Equal(2)) - Ω(reporter1.EndSummary.NumberOfSkippedSpecs).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfPassedSpecs).Should(Equal(0)) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(0)) - }) - }) - }) - - Describe("reporting on specs", func() { - var proceed chan bool - var ready chan bool - var finished chan bool - BeforeEach(func() { - ready = make(chan bool) - proceed = make(chan bool) - finished = make(chan bool) - skippedSpec := newSpec("SKIP", noneFlag, false) - skippedSpec.Skip() - - runner = newRunner( - config.GinkgoConfigType{}, - newBefSuite("BefSuite", false), - newAftSuite("AftSuite", false), - skippedSpec, - newSpec("PENDING", pendingFlag, false), - newSpecWithBody("RUN", func() { - close(ready) - <-proceed - }), - ) - go func() { - runner.Run() - close(finished) - }() - }) - - It("should report about pending/skipped specs", func() { - <-ready - Ω(reporter1.SpecWillRunSummaries).Should(HaveLen(3)) - - Ω(reporter1.SpecWillRunSummaries[0].ComponentTexts[0]).Should(Equal("SKIP")) - Ω(reporter1.SpecWillRunSummaries[1].ComponentTexts[0]).Should(Equal("PENDING")) - Ω(reporter1.SpecWillRunSummaries[2].ComponentTexts[0]).Should(Equal("RUN")) - - Ω(reporter1.SpecSummaries[0].ComponentTexts[0]).Should(Equal("SKIP")) - Ω(reporter1.SpecSummaries[1].ComponentTexts[0]).Should(Equal("PENDING")) - Ω(reporter1.SpecSummaries).Should(HaveLen(2)) - - close(proceed) - <-finished - - Ω(reporter1.SpecSummaries).Should(HaveLen(3)) - Ω(reporter1.SpecSummaries[2].ComponentTexts[0]).Should(Equal("RUN")) - }) - }) - - Describe("Running BeforeSuite & AfterSuite", func() { - var success bool - var befSuite leafnodes.SuiteNode - var aftSuite leafnodes.SuiteNode - Context("with a nil BeforeSuite & AfterSuite", func() { - BeforeEach(func() { - runner = newRunner( - config.GinkgoConfigType{}, - nil, - nil, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, false), - ) - success = runner.Run() - }) - - It("should not report about the BeforeSuite", func() { - Ω(reporter1.BeforeSuiteSummary).Should(BeNil()) - }) - - It("should not report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(BeNil()) - }) - - It("should run the specs", func() { - Ω(thingsThatRan).Should(Equal([]string{"A", "B"})) - }) - }) - - Context("when the BeforeSuite & AfterSuite pass", func() { - BeforeEach(func() { - befSuite = newBefSuite("BefSuite", false) - aftSuite = newBefSuite("AftSuite", false) - runner = newRunner( - config.GinkgoConfigType{}, - befSuite, - aftSuite, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, false), - ) - success = runner.Run() - }) - - It("should run the BeforeSuite, the AfterSuite and the specs", func() { - Ω(thingsThatRan).Should(Equal([]string{"BefSuite", "A", "B", "AftSuite"})) - }) - - It("should report about the BeforeSuite", func() { - Ω(reporter1.BeforeSuiteSummary).Should(Equal(befSuite.Summary())) - }) - - It("should report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(Equal(aftSuite.Summary())) - }) - - It("should report success", func() { - Ω(success).Should(BeTrue()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeTrue()) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(0)) - }) - - It("should not dump the writer", func() { - Ω(writer.EventStream).ShouldNot(ContainElement("DUMP")) - }) - }) - - Context("when the BeforeSuite fails", func() { - BeforeEach(func() { - befSuite = newBefSuite("BefSuite", true) - aftSuite = newBefSuite("AftSuite", false) - - skipped := newSpec("Skipped", noneFlag, false) - skipped.Skip() - - runner = newRunner( - config.GinkgoConfigType{}, - befSuite, - aftSuite, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, false), - newSpec("Pending", pendingFlag, false), - skipped, - ) - success = runner.Run() - }) - - It("should not run the specs, but it should run the AfterSuite", func() { - Ω(thingsThatRan).Should(Equal([]string{"BefSuite", "AftSuite"})) - }) - - It("should report about the BeforeSuite", func() { - Ω(reporter1.BeforeSuiteSummary).Should(Equal(befSuite.Summary())) - }) - - It("should report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(Equal(aftSuite.Summary())) - }) - - It("should report failure", func() { - Ω(success).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(2)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(2)) - }) - - It("should dump the writer", func() { - Ω(writer.EventStream).Should(ContainElement("DUMP")) - }) - }) - - Context("when some other test fails", func() { - BeforeEach(func() { - aftSuite = newBefSuite("AftSuite", false) - - runner = newRunner( - config.GinkgoConfigType{}, - nil, - aftSuite, - newSpec("A", noneFlag, true), - ) - success = runner.Run() - }) - - It("should still run the AfterSuite", func() { - Ω(thingsThatRan).Should(Equal([]string{"A", "AftSuite"})) - }) - - It("should report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(Equal(aftSuite.Summary())) - }) - - It("should report failure", func() { - Ω(success).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(1)) - }) - }) - - Context("when the AfterSuite fails", func() { - BeforeEach(func() { - befSuite = newBefSuite("BefSuite", false) - aftSuite = newBefSuite("AftSuite", true) - runner = newRunner( - config.GinkgoConfigType{}, - befSuite, - aftSuite, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, false), - ) - success = runner.Run() - }) - - It("should run everything", func() { - Ω(thingsThatRan).Should(Equal([]string{"BefSuite", "A", "B", "AftSuite"})) - }) - - It("should report about the BeforeSuite", func() { - Ω(reporter1.BeforeSuiteSummary).Should(Equal(befSuite.Summary())) - }) - - It("should report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(Equal(aftSuite.Summary())) - }) - - It("should report failure", func() { - Ω(success).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(0)) - }) - - It("should dump the writer", func() { - Ω(writer.EventStream).Should(ContainElement("DUMP")) - }) - }) - }) - - Describe("When instructed to fail fast", func() { - BeforeEach(func() { - conf := config.GinkgoConfigType{ - FailFast: true, - } - runner = newRunner(conf, nil, newAftSuite("after-suite", false), newSpec("passing", noneFlag, false), newSpec("failing", noneFlag, true), newSpec("dont-see", noneFlag, true), newSpec("dont-see", noneFlag, true)) - }) - - It("should return false, report failure, and not run anything past the failing test", func() { - Ω(runner.Run()).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(thingsThatRan).Should(Equal([]string{"passing", "failing", "after-suite"})) - }) - - It("should announce the subsequent specs as skipped", func() { - runner.Run() - Ω(reporter1.SpecSummaries).Should(HaveLen(4)) - Ω(reporter1.SpecSummaries[2].State).Should(Equal(types.SpecStateSkipped)) - Ω(reporter1.SpecSummaries[3].State).Should(Equal(types.SpecStateSkipped)) - }) - - It("should mark all subsequent specs as skipped", func() { - runner.Run() - Ω(reporter1.EndSummary.NumberOfSkippedSpecs).Should(Equal(2)) - }) - }) - - Describe("Marking failure and success", func() { - Context("when all tests pass", func() { - BeforeEach(func() { - runner = newRunner(config.GinkgoConfigType{}, nil, nil, newSpec("passing", noneFlag, false), newSpec("pending", pendingFlag, false)) - }) - - It("should return true and report success", func() { - Ω(runner.Run()).Should(BeTrue()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeTrue()) - }) - }) - - Context("when a test fails", func() { - BeforeEach(func() { - runner = newRunner(config.GinkgoConfigType{}, nil, nil, newSpec("failing", noneFlag, true), newSpec("pending", pendingFlag, false)) - }) - - It("should return false and report failure", func() { - Ω(runner.Run()).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - }) - }) - - Context("when there is a pending test, but pendings count as failures", func() { - BeforeEach(func() { - runner = newRunner(config.GinkgoConfigType{FailOnPending: true}, nil, nil, newSpec("passing", noneFlag, false), newSpec("pending", pendingFlag, false)) - }) - - It("should return false and report failure", func() { - Ω(runner.Run()).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - }) - }) - }) - - Describe("Managing the writer", func() { - BeforeEach(func() { - runner = newRunner( - config.GinkgoConfigType{}, - nil, - nil, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, true), - newSpec("C", noneFlag, false), - ) - reporter1.SpecWillRunStub = func(specSummary *types.SpecSummary) { - writer.AddEvent("R1.WillRun") - } - reporter2.SpecWillRunStub = func(specSummary *types.SpecSummary) { - writer.AddEvent("R2.WillRun") - } - reporter1.SpecDidCompleteStub = func(specSummary *types.SpecSummary) { - writer.AddEvent("R1.DidComplete") - } - reporter2.SpecDidCompleteStub = func(specSummary *types.SpecSummary) { - writer.AddEvent("R2.DidComplete") - } - runner.Run() - }) - - It("should truncate between tests, but only dump if a test fails", func() { - Ω(writer.EventStream).Should(Equal([]string{ - "TRUNCATE", - "R1.WillRun", - "R2.WillRun", - "A", - "R2.DidComplete", - "R1.DidComplete", - "TRUNCATE", - "R1.WillRun", - "R2.WillRun", - "B", - "R2.DidComplete", - "DUMP", - "R1.DidComplete", - "TRUNCATE", - "R1.WillRun", - "R2.WillRun", - "C", - "R2.DidComplete", - "R1.DidComplete", - })) - }) - }) - - Describe("CurrentSpecSummary", func() { - It("should return the spec summary for the currently running spec", func() { - var summary *types.SpecSummary - runner = newRunner( - config.GinkgoConfigType{}, - nil, - nil, - newSpec("A", noneFlag, false), - newSpecWithBody("B", func() { - var ok bool - summary, ok = runner.CurrentSpecSummary() - Ω(ok).Should(BeTrue()) - }), - newSpec("C", noneFlag, false), - ) - runner.Run() - - Ω(summary.ComponentTexts).Should(Equal([]string{"B"})) - - summary, ok := runner.CurrentSpecSummary() - Ω(summary).Should(BeNil()) - Ω(ok).Should(BeFalse()) - }) - }) - - Context("When running tests in parallel", func() { - It("reports the correct number of specs before parallelization", func() { - specs := spec.NewSpecs([]*spec.Spec{ - newSpec("A", noneFlag, false), - newSpec("B", pendingFlag, false), - newSpec("C", noneFlag, false), - }) - specs.TrimForParallelization(2, 1) - runner = New("description", nil, specs, nil, []reporters.Reporter{reporter1, reporter2}, writer, config.GinkgoConfigType{}) - runner.Run() - - Ω(reporter1.EndSummary.NumberOfSpecsBeforeParallelization).Should(Equal(3)) - Ω(reporter1.EndSummary.NumberOfTotalSpecs).Should(Equal(2)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfPendingSpecs).Should(Equal(1)) - }) - }) - - Describe("generating a suite id", func() { - It("should generate an id randomly", func() { - runnerA := newRunner(config.GinkgoConfigType{}, nil, nil) - runnerA.Run() - IDA := reporter1.BeginSummary.SuiteID - - runnerB := newRunner(config.GinkgoConfigType{}, nil, nil) - runnerB.Run() - IDB := reporter1.BeginSummary.SuiteID - - IDRegexp := "[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}" - Ω(IDA).Should(MatchRegexp(IDRegexp)) - Ω(IDB).Should(MatchRegexp(IDRegexp)) - - Ω(IDA).ShouldNot(Equal(IDB)) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/suite/suite_suite_test.go b/vendor/github.com/onsi/ginkgo/internal/suite/suite_suite_test.go deleted file mode 100644 index 06fe1d12..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/suite/suite_suite_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package suite_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func Test(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Suite") -} - -var numBeforeSuiteRuns = 0 -var numAfterSuiteRuns = 0 - -var _ = BeforeSuite(func() { - numBeforeSuiteRuns++ -}) - -var _ = AfterSuite(func() { - numAfterSuiteRuns++ - Ω(numBeforeSuiteRuns).Should(Equal(1)) - Ω(numAfterSuiteRuns).Should(Equal(1)) -}) - -//Fakes -type fakeTestingT struct { - didFail bool -} - -func (fakeT *fakeTestingT) Fail() { - fakeT.didFail = true -} diff --git a/vendor/github.com/onsi/ginkgo/internal/suite/suite_test.go b/vendor/github.com/onsi/ginkgo/internal/suite/suite_test.go deleted file mode 100644 index 334211a0..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/suite/suite_test.go +++ /dev/null @@ -1,398 +0,0 @@ -package suite_test - -import ( - "bytes" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/suite" - . "github.com/onsi/gomega" - - "math/rand" - "time" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - Writer "github.com/onsi/ginkgo/internal/writer" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("Suite", func() { - var ( - specSuite *Suite - fakeT *fakeTestingT - fakeR *reporters.FakeReporter - writer *Writer.FakeGinkgoWriter - failer *Failer.Failer - ) - - BeforeEach(func() { - writer = Writer.NewFake() - fakeT = &fakeTestingT{} - fakeR = reporters.NewFakeReporter() - failer = Failer.New() - specSuite = New(failer) - }) - - Describe("running a suite", func() { - var ( - runOrder []string - randomizeAllSpecs bool - randomSeed int64 - focusString string - parallelNode int - parallelTotal int - runResult bool - hasProgrammaticFocus bool - ) - - var f = func(runText string) func() { - return func() { - runOrder = append(runOrder, runText) - } - } - - BeforeEach(func() { - randomizeAllSpecs = false - randomSeed = 11 - parallelNode = 1 - parallelTotal = 1 - focusString = "" - - runOrder = make([]string, 0) - specSuite.SetBeforeSuiteNode(f("BeforeSuite"), codelocation.New(0), 0) - specSuite.PushBeforeEachNode(f("top BE"), codelocation.New(0), 0) - specSuite.PushJustBeforeEachNode(f("top JBE"), codelocation.New(0), 0) - specSuite.PushAfterEachNode(f("top AE"), codelocation.New(0), 0) - - specSuite.PushContainerNode("container", func() { - specSuite.PushBeforeEachNode(f("BE"), codelocation.New(0), 0) - specSuite.PushJustBeforeEachNode(f("JBE"), codelocation.New(0), 0) - specSuite.PushAfterEachNode(f("AE"), codelocation.New(0), 0) - specSuite.PushItNode("it", f("IT"), types.FlagTypeNone, codelocation.New(0), 0) - - specSuite.PushContainerNode("inner container", func() { - specSuite.PushItNode("inner it", f("inner IT"), types.FlagTypeNone, codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0)) - }, types.FlagTypeNone, codelocation.New(0)) - - specSuite.PushContainerNode("container 2", func() { - specSuite.PushBeforeEachNode(f("BE 2"), codelocation.New(0), 0) - specSuite.PushItNode("it 2", f("IT 2"), types.FlagTypeNone, codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0)) - - specSuite.PushItNode("top level it", f("top IT"), types.FlagTypeNone, codelocation.New(0), 0) - - specSuite.SetAfterSuiteNode(f("AfterSuite"), codelocation.New(0), 0) - }) - - JustBeforeEach(func() { - runResult, hasProgrammaticFocus = specSuite.Run(fakeT, "suite description", []reporters.Reporter{fakeR}, writer, config.GinkgoConfigType{ - RandomSeed: randomSeed, - RandomizeAllSpecs: randomizeAllSpecs, - FocusString: focusString, - ParallelNode: parallelNode, - ParallelTotal: parallelTotal, - }) - }) - - It("provides the config and suite description to the reporter", func() { - Ω(fakeR.Config.RandomSeed).Should(Equal(int64(randomSeed))) - Ω(fakeR.Config.RandomizeAllSpecs).Should(Equal(randomizeAllSpecs)) - Ω(fakeR.BeginSummary.SuiteDescription).Should(Equal("suite description")) - }) - - It("reports that the BeforeSuite node ran", func() { - Ω(fakeR.BeforeSuiteSummary).ShouldNot(BeNil()) - }) - - It("reports that the AfterSuite node ran", func() { - Ω(fakeR.AfterSuiteSummary).ShouldNot(BeNil()) - }) - - It("provides information about the current test", func() { - description := CurrentGinkgoTestDescription() - Ω(description.ComponentTexts).Should(Equal([]string{"Suite", "running a suite", "provides information about the current test"})) - Ω(description.FullTestText).Should(Equal("Suite running a suite provides information about the current test")) - Ω(description.TestText).Should(Equal("provides information about the current test")) - Ω(description.IsMeasurement).Should(BeFalse()) - Ω(description.FileName).Should(ContainSubstring("suite_test.go")) - Ω(description.LineNumber).Should(BeNumerically(">", 50)) - Ω(description.LineNumber).Should(BeNumerically("<", 150)) - }) - - Measure("should run measurements", func(b Benchmarker) { - r := rand.New(rand.NewSource(time.Now().UnixNano())) - - runtime := b.Time("sleeping", func() { - sleepTime := time.Duration(r.Float64() * 0.01 * float64(time.Second)) - time.Sleep(sleepTime) - }) - Ω(runtime.Seconds()).Should(BeNumerically("<=", 0.015)) - Ω(runtime.Seconds()).Should(BeNumerically(">=", 0)) - - randomValue := r.Float64() * 10.0 - b.RecordValue("random value", randomValue) - Ω(randomValue).Should(BeNumerically("<=", 10.0)) - Ω(randomValue).Should(BeNumerically(">=", 0.0)) - }, 10) - - It("creates a node hierarchy, converts it to a spec collection, and runs it", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "BE", "top JBE", "JBE", "IT", "AE", "top AE", - "top BE", "BE", "top JBE", "JBE", "inner IT", "AE", "top AE", - "top BE", "BE 2", "top JBE", "IT 2", "top AE", - "top BE", "top JBE", "top IT", "top AE", - "AfterSuite", - })) - }) - - Context("when told to randomize all specs", func() { - BeforeEach(func() { - randomizeAllSpecs = true - }) - - It("does", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "top JBE", "top IT", "top AE", - "top BE", "BE", "top JBE", "JBE", "inner IT", "AE", "top AE", - "top BE", "BE", "top JBE", "JBE", "IT", "AE", "top AE", - "top BE", "BE 2", "top JBE", "IT 2", "top AE", - "AfterSuite", - })) - }) - }) - - Describe("with ginkgo.parallel.total > 1", func() { - BeforeEach(func() { - parallelTotal = 2 - randomizeAllSpecs = true - }) - - Context("for one worker", func() { - BeforeEach(func() { - parallelNode = 1 - }) - - It("should run a subset of tests", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "top JBE", "top IT", "top AE", - "top BE", "BE", "top JBE", "JBE", "inner IT", "AE", "top AE", - "AfterSuite", - })) - }) - }) - - Context("for another worker", func() { - BeforeEach(func() { - parallelNode = 2 - }) - - It("should run a (different) subset of tests", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "BE", "top JBE", "JBE", "IT", "AE", "top AE", - "top BE", "BE 2", "top JBE", "IT 2", "top AE", - "AfterSuite", - })) - }) - }) - }) - - Context("when provided with a filter", func() { - BeforeEach(func() { - focusString = `inner|\d` - }) - - It("converts the filter to a regular expression and uses it to filter the running specs", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "BE", "top JBE", "JBE", "inner IT", "AE", "top AE", - "top BE", "BE 2", "top JBE", "IT 2", "top AE", - "AfterSuite", - })) - }) - - It("should not report a programmatic focus", func() { - Ω(hasProgrammaticFocus).Should(BeFalse()) - }) - }) - - Context("with a programatically focused spec", func() { - BeforeEach(func() { - specSuite.PushItNode("focused it", f("focused it"), types.FlagTypeFocused, codelocation.New(0), 0) - - specSuite.PushContainerNode("focused container", func() { - specSuite.PushItNode("inner focused it", f("inner focused it"), types.FlagTypeFocused, codelocation.New(0), 0) - specSuite.PushItNode("inner unfocused it", f("inner unfocused it"), types.FlagTypeNone, codelocation.New(0), 0) - }, types.FlagTypeFocused, codelocation.New(0)) - - }) - - It("should only run the focused test, applying backpropagation to favor most deeply focused leaf nodes", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "top JBE", "focused it", "top AE", - "top BE", "top JBE", "inner focused it", "top AE", - "AfterSuite", - })) - }) - - It("should report a programmatic focus", func() { - Ω(hasProgrammaticFocus).Should(BeTrue()) - }) - }) - - Context("when the specs pass", func() { - It("doesn't report a failure", func() { - Ω(fakeT.didFail).Should(BeFalse()) - }) - - It("should return true", func() { - Ω(runResult).Should(BeTrue()) - }) - }) - - Context("when a spec fails", func() { - var location types.CodeLocation - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - location = codelocation.New(0) - failer.Fail("oops!", location) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should return false", func() { - Ω(runResult).Should(BeFalse()) - }) - - It("reports a failure", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - - It("generates the correct failure data", func() { - Ω(fakeR.SpecSummaries[0].Failure.Message).Should(Equal("oops!")) - Ω(fakeR.SpecSummaries[0].Failure.Location).Should(Equal(location)) - }) - }) - - Context("when runnable nodes are nested within other runnable nodes", func() { - Context("when an It is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushItNode("nested it", f("oops"), types.FlagTypeNone, codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - - Context("when a Measure is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushMeasureNode("nested measure", func(Benchmarker) {}, types.FlagTypeNone, codelocation.New(0), 10) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - - Context("when a BeforeEach is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushBeforeEachNode(f("nested bef"), codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - - Context("when a JustBeforeEach is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushJustBeforeEachNode(f("nested jbef"), codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - - Context("when a AfterEach is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushAfterEachNode(f("nested aft"), codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - }) - }) - - Describe("BeforeSuite", func() { - Context("when setting BeforeSuite more than once", func() { - It("should panic", func() { - specSuite.SetBeforeSuiteNode(func() {}, codelocation.New(0), 0) - - Ω(func() { - specSuite.SetBeforeSuiteNode(func() {}, codelocation.New(0), 0) - }).Should(Panic()) - - }) - }) - }) - - Describe("AfterSuite", func() { - Context("when setting AfterSuite more than once", func() { - It("should panic", func() { - specSuite.SetAfterSuiteNode(func() {}, codelocation.New(0), 0) - - Ω(func() { - specSuite.SetAfterSuiteNode(func() {}, codelocation.New(0), 0) - }).Should(Panic()) - }) - }) - }) - - Describe("By", func() { - It("writes to the GinkgoWriter", func() { - originalGinkgoWriter := GinkgoWriter - buffer := &bytes.Buffer{} - - GinkgoWriter = buffer - By("Saying Hello GinkgoWriter") - GinkgoWriter = originalGinkgoWriter - - Ω(buffer.String()).Should(ContainSubstring("STEP")) - Ω(buffer.String()).Should(ContainSubstring(": Saying Hello GinkgoWriter\n")) - }) - - It("calls the passed-in callback if present", func() { - a := 0 - By("calling the callback", func() { - a = 1 - }) - Ω(a).Should(Equal(1)) - }) - - It("panics if there is more than one callback", func() { - Ω(func() { - By("registering more than one callback", func() {}, func() {}) - }).Should(Panic()) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/writer/writer_suite_test.go b/vendor/github.com/onsi/ginkgo/internal/writer/writer_suite_test.go deleted file mode 100644 index e2065779..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/writer/writer_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package writer_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestWriter(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Writer Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/internal/writer/writer_test.go b/vendor/github.com/onsi/ginkgo/internal/writer/writer_test.go deleted file mode 100644 index 3e1d17c6..00000000 --- a/vendor/github.com/onsi/ginkgo/internal/writer/writer_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package writer_test - -import ( - "github.com/onsi/gomega/gbytes" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/writer" - . "github.com/onsi/gomega" -) - -var _ = Describe("Writer", func() { - var writer *Writer - var out *gbytes.Buffer - - BeforeEach(func() { - out = gbytes.NewBuffer() - writer = New(out) - }) - - It("should stream directly to the outbuffer by default", func() { - writer.Write([]byte("foo")) - Ω(out).Should(gbytes.Say("foo")) - }) - - It("should not emit the header when asked to DumpOutWitHeader", func() { - writer.Write([]byte("foo")) - writer.DumpOutWithHeader("my header") - Ω(out).ShouldNot(gbytes.Say("my header")) - Ω(out).Should(gbytes.Say("foo")) - }) - - Context("when told not to stream", func() { - BeforeEach(func() { - writer.SetStream(false) - }) - - It("should only write to the buffer when told to DumpOut", func() { - writer.Write([]byte("foo")) - Ω(out).ShouldNot(gbytes.Say("foo")) - writer.DumpOut() - Ω(out).Should(gbytes.Say("foo")) - }) - - It("should truncate the internal buffer when told to truncate", func() { - writer.Write([]byte("foo")) - writer.Truncate() - writer.DumpOut() - Ω(out).ShouldNot(gbytes.Say("foo")) - - writer.Write([]byte("bar")) - writer.DumpOut() - Ω(out).Should(gbytes.Say("bar")) - }) - - Describe("emitting a header", func() { - Context("when the buffer has content", func() { - It("should emit the header followed by the content", func() { - writer.Write([]byte("foo")) - writer.DumpOutWithHeader("my header") - - Ω(out).Should(gbytes.Say("my header")) - Ω(out).Should(gbytes.Say("foo")) - }) - }) - - Context("when the buffer has no content", func() { - It("should not emit the header", func() { - writer.DumpOutWithHeader("my header") - - Ω(out).ShouldNot(gbytes.Say("my header")) - }) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/reporters/default_reporter_test.go b/vendor/github.com/onsi/ginkgo/reporters/default_reporter_test.go deleted file mode 100644 index 3b719a1e..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/default_reporter_test.go +++ /dev/null @@ -1,397 +0,0 @@ -package reporters_test - -import ( - "time" - - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/reporters" - st "github.com/onsi/ginkgo/reporters/stenographer" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" -) - -var _ = Describe("DefaultReporter", func() { - var ( - reporter *reporters.DefaultReporter - reporterConfig config.DefaultReporterConfigType - stenographer *st.FakeStenographer - - ginkgoConfig config.GinkgoConfigType - suite *types.SuiteSummary - spec *types.SpecSummary - ) - - BeforeEach(func() { - stenographer = st.NewFakeStenographer() - reporterConfig = config.DefaultReporterConfigType{ - NoColor: false, - SlowSpecThreshold: 0.1, - NoisyPendings: true, - Verbose: true, - FullTrace: true, - } - - reporter = reporters.NewDefaultReporter(reporterConfig, stenographer) - }) - - call := func(method string, args ...interface{}) st.FakeStenographerCall { - return st.NewFakeStenographerCall(method, args...) - } - - Describe("SpecSuiteWillBegin", func() { - BeforeEach(func() { - suite = &types.SuiteSummary{ - SuiteDescription: "A Sweet Suite", - NumberOfTotalSpecs: 10, - NumberOfSpecsThatWillBeRun: 8, - } - - ginkgoConfig = config.GinkgoConfigType{ - RandomSeed: 1138, - RandomizeAllSpecs: true, - } - }) - - Context("when a serial (non-parallel) suite begins", func() { - BeforeEach(func() { - ginkgoConfig.ParallelTotal = 1 - - reporter.SpecSuiteWillBegin(ginkgoConfig, suite) - }) - - It("should announce the suite, then announce the number of specs", func() { - Ω(stenographer.Calls()).Should(HaveLen(2)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuite", "A Sweet Suite", ginkgoConfig.RandomSeed, true, false))) - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceNumberOfSpecs", 8, 10, false))) - }) - }) - - Context("when a parallel suite begins", func() { - BeforeEach(func() { - ginkgoConfig.ParallelTotal = 2 - ginkgoConfig.ParallelNode = 1 - suite.NumberOfSpecsBeforeParallelization = 20 - - reporter.SpecSuiteWillBegin(ginkgoConfig, suite) - }) - - It("should announce the suite, announce that it's a parallel run, then announce the number of specs", func() { - Ω(stenographer.Calls()).Should(HaveLen(3)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuite", "A Sweet Suite", ginkgoConfig.RandomSeed, true, false))) - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceParallelRun", 1, 2, 10, 20, false))) - Ω(stenographer.Calls()[2]).Should(Equal(call("AnnounceNumberOfSpecs", 8, 10, false))) - }) - }) - }) - - Describe("BeforeSuiteDidRun", func() { - Context("when the BeforeSuite passes", func() { - It("should announce nothing", func() { - reporter.BeforeSuiteDidRun(&types.SetupSummary{ - State: types.SpecStatePassed, - }) - - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - - Context("when the BeforeSuite fails", func() { - It("should announce the failure", func() { - summary := &types.SetupSummary{ - State: types.SpecStateFailed, - } - reporter.BeforeSuiteDidRun(summary) - - Ω(stenographer.Calls()).Should(HaveLen(1)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceBeforeSuiteFailure", summary, false, true))) - }) - }) - }) - - Describe("AfterSuiteDidRun", func() { - Context("when the AfterSuite passes", func() { - It("should announce nothing", func() { - reporter.AfterSuiteDidRun(&types.SetupSummary{ - State: types.SpecStatePassed, - }) - - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - - Context("when the AfterSuite fails", func() { - It("should announce the failure", func() { - summary := &types.SetupSummary{ - State: types.SpecStateFailed, - } - reporter.AfterSuiteDidRun(summary) - - Ω(stenographer.Calls()).Should(HaveLen(1)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceAfterSuiteFailure", summary, false, true))) - }) - }) - }) - - Describe("SpecWillRun", func() { - Context("When running in verbose mode", func() { - Context("and the spec will run", func() { - BeforeEach(func() { - spec = &types.SpecSummary{} - reporter.SpecWillRun(spec) - }) - - It("should announce that the spec will run", func() { - Ω(stenographer.Calls()).Should(HaveLen(1)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecWillRun", spec))) - }) - }) - - Context("and the spec will not run", func() { - Context("because it is pending", func() { - BeforeEach(func() { - spec = &types.SpecSummary{ - State: types.SpecStatePending, - } - reporter.SpecWillRun(spec) - }) - - It("should announce nothing", func() { - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - - Context("because it is skipped", func() { - BeforeEach(func() { - spec = &types.SpecSummary{ - State: types.SpecStateSkipped, - } - reporter.SpecWillRun(spec) - }) - - It("should announce nothing", func() { - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - }) - }) - - Context("When running in verbose & succinct mode", func() { - BeforeEach(func() { - reporterConfig.Succinct = true - reporter = reporters.NewDefaultReporter(reporterConfig, stenographer) - spec = &types.SpecSummary{} - reporter.SpecWillRun(spec) - }) - - It("should announce nothing", func() { - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - - Context("When not running in verbose mode", func() { - BeforeEach(func() { - reporterConfig.Verbose = false - reporter = reporters.NewDefaultReporter(reporterConfig, stenographer) - spec = &types.SpecSummary{} - reporter.SpecWillRun(spec) - }) - - It("should announce nothing", func() { - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - }) - - Describe("SpecDidComplete", func() { - JustBeforeEach(func() { - reporter.SpecDidComplete(spec) - }) - - BeforeEach(func() { - spec = &types.SpecSummary{} - }) - - Context("When the spec passed", func() { - BeforeEach(func() { - spec.State = types.SpecStatePassed - }) - - Context("When the spec was a measurement", func() { - BeforeEach(func() { - spec.IsMeasurement = true - }) - - It("should announce the measurement", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulMeasurement", spec, false))) - }) - }) - - Context("When the spec is slow", func() { - BeforeEach(func() { - spec.RunTime = time.Second - }) - - It("should announce that it was slow", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulSlowSpec", spec, false))) - }) - }) - - Context("Otherwise", func() { - It("should announce the succesful spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulSpec", spec))) - }) - }) - }) - - Context("When the spec is pending", func() { - BeforeEach(func() { - spec.State = types.SpecStatePending - }) - - It("should announce the pending spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnouncePendingSpec", spec, true))) - }) - }) - - Context("When the spec is skipped", func() { - BeforeEach(func() { - spec.State = types.SpecStateSkipped - }) - - It("should announce the skipped spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSkippedSpec", spec))) - }) - }) - - Context("When the spec timed out", func() { - BeforeEach(func() { - spec.State = types.SpecStateTimedOut - }) - - It("should announce the timedout spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecTimedOut", spec, false, true))) - }) - }) - - Context("When the spec panicked", func() { - BeforeEach(func() { - spec.State = types.SpecStatePanicked - }) - - It("should announce the panicked spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecPanicked", spec, false, true))) - }) - }) - - Context("When the spec failed", func() { - BeforeEach(func() { - spec.State = types.SpecStateFailed - }) - - It("should announce the failed spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecFailed", spec, false, true))) - }) - }) - - Context("in succinct mode", func() { - BeforeEach(func() { - reporterConfig.Succinct = true - reporter = reporters.NewDefaultReporter(reporterConfig, stenographer) - }) - - Context("When the spec passed", func() { - BeforeEach(func() { - spec.State = types.SpecStatePassed - }) - - Context("When the spec was a measurement", func() { - BeforeEach(func() { - spec.IsMeasurement = true - }) - - It("should announce the measurement", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulMeasurement", spec, true))) - }) - }) - - Context("When the spec is slow", func() { - BeforeEach(func() { - spec.RunTime = time.Second - }) - - It("should announce that it was slow", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulSlowSpec", spec, true))) - }) - }) - - Context("Otherwise", func() { - It("should announce the succesful spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulSpec", spec))) - }) - }) - }) - - Context("When the spec is pending", func() { - BeforeEach(func() { - spec.State = types.SpecStatePending - }) - - It("should announce the pending spec, but never noisily", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnouncePendingSpec", spec, false))) - }) - }) - - Context("When the spec is skipped", func() { - BeforeEach(func() { - spec.State = types.SpecStateSkipped - }) - - It("should announce the skipped spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSkippedSpec", spec))) - }) - }) - - Context("When the spec timed out", func() { - BeforeEach(func() { - spec.State = types.SpecStateTimedOut - }) - - It("should announce the timedout spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecTimedOut", spec, true, true))) - }) - }) - - Context("When the spec panicked", func() { - BeforeEach(func() { - spec.State = types.SpecStatePanicked - }) - - It("should announce the panicked spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecPanicked", spec, true, true))) - }) - }) - - Context("When the spec failed", func() { - BeforeEach(func() { - spec.State = types.SpecStateFailed - }) - - It("should announce the failed spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecFailed", spec, true, true))) - }) - }) - }) - }) - - Describe("SpecSuiteDidEnd", func() { - BeforeEach(func() { - suite = &types.SuiteSummary{} - reporter.SpecSuiteDidEnd(suite) - }) - - It("should announce the spec run's completion", func() { - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceSpecRunCompletion", suite, false))) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/reporters/junit_reporter_test.go b/vendor/github.com/onsi/ginkgo/reporters/junit_reporter_test.go deleted file mode 100644 index 744f383a..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/junit_reporter_test.go +++ /dev/null @@ -1,241 +0,0 @@ -package reporters_test - -import ( - "encoding/xml" - "io/ioutil" - "os" - "time" - - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" -) - -var _ = Describe("JUnit Reporter", func() { - var ( - outputFile string - reporter Reporter - ) - - readOutputFile := func() reporters.JUnitTestSuite { - bytes, err := ioutil.ReadFile(outputFile) - Ω(err).ShouldNot(HaveOccurred()) - var suite reporters.JUnitTestSuite - err = xml.Unmarshal(bytes, &suite) - Ω(err).ShouldNot(HaveOccurred()) - return suite - } - - BeforeEach(func() { - f, err := ioutil.TempFile("", "output") - Ω(err).ShouldNot(HaveOccurred()) - f.Close() - outputFile = f.Name() - - reporter = reporters.NewJUnitReporter(outputFile) - - reporter.SpecSuiteWillBegin(config.GinkgoConfigType{}, &types.SuiteSummary{ - SuiteDescription: "My test suite", - NumberOfSpecsThatWillBeRun: 1, - }) - }) - - AfterEach(func() { - os.RemoveAll(outputFile) - }) - - Describe("a passing test", func() { - BeforeEach(func() { - beforeSuite := &types.SetupSummary{ - State: types.SpecStatePassed, - } - reporter.BeforeSuiteDidRun(beforeSuite) - - afterSuite := &types.SetupSummary{ - State: types.SpecStatePassed, - } - reporter.AfterSuiteDidRun(afterSuite) - - spec := &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: types.SpecStatePassed, - RunTime: 5 * time.Second, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 0, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as passing", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(0)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases).Should(HaveLen(1)) - Ω(output.TestCases[0].Name).Should(Equal("A B C")) - Ω(output.TestCases[0].ClassName).Should(Equal("My test suite")) - Ω(output.TestCases[0].FailureMessage).Should(BeNil()) - Ω(output.TestCases[0].Skipped).Should(BeNil()) - Ω(output.TestCases[0].Time).Should(Equal(5.0)) - }) - }) - - Describe("when the BeforeSuite fails", func() { - var beforeSuite *types.SetupSummary - - BeforeEach(func() { - beforeSuite = &types.SetupSummary{ - State: types.SpecStateFailed, - RunTime: 3 * time.Second, - Failure: types.SpecFailure{ - Message: "failed to setup", - ComponentCodeLocation: codelocation.New(0), - }, - } - reporter.BeforeSuiteDidRun(beforeSuite) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as having failed", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(1)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases[0].Name).Should(Equal("BeforeSuite")) - Ω(output.TestCases[0].Time).Should(Equal(3.0)) - Ω(output.TestCases[0].ClassName).Should(Equal("My test suite")) - Ω(output.TestCases[0].FailureMessage.Type).Should(Equal("Failure")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring("failed to setup")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring(beforeSuite.Failure.ComponentCodeLocation.String())) - Ω(output.TestCases[0].Skipped).Should(BeNil()) - }) - }) - - Describe("when the AfterSuite fails", func() { - var afterSuite *types.SetupSummary - - BeforeEach(func() { - afterSuite = &types.SetupSummary{ - State: types.SpecStateFailed, - RunTime: 3 * time.Second, - Failure: types.SpecFailure{ - Message: "failed to setup", - ComponentCodeLocation: codelocation.New(0), - }, - } - reporter.AfterSuiteDidRun(afterSuite) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as having failed", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(1)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases[0].Name).Should(Equal("AfterSuite")) - Ω(output.TestCases[0].Time).Should(Equal(3.0)) - Ω(output.TestCases[0].ClassName).Should(Equal("My test suite")) - Ω(output.TestCases[0].FailureMessage.Type).Should(Equal("Failure")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring("failed to setup")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring(afterSuite.Failure.ComponentCodeLocation.String())) - Ω(output.TestCases[0].Skipped).Should(BeNil()) - }) - }) - - specStateCases := []struct { - state types.SpecState - message string - }{ - {types.SpecStateFailed, "Failure"}, - {types.SpecStateTimedOut, "Timeout"}, - {types.SpecStatePanicked, "Panic"}, - } - - for _, specStateCase := range specStateCases { - specStateCase := specStateCase - Describe("a failing test", func() { - var spec *types.SpecSummary - BeforeEach(func() { - spec = &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: specStateCase.state, - RunTime: 5 * time.Second, - Failure: types.SpecFailure{ - ComponentCodeLocation: codelocation.New(0), - Message: "I failed", - }, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record test as failing", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(1)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases[0].Name).Should(Equal("A B C")) - Ω(output.TestCases[0].ClassName).Should(Equal("My test suite")) - Ω(output.TestCases[0].FailureMessage.Type).Should(Equal(specStateCase.message)) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring("I failed")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring(spec.Failure.ComponentCodeLocation.String())) - Ω(output.TestCases[0].Skipped).Should(BeNil()) - }) - }) - } - - for _, specStateCase := range []types.SpecState{types.SpecStatePending, types.SpecStateSkipped} { - specStateCase := specStateCase - Describe("a skipped test", func() { - var spec *types.SpecSummary - BeforeEach(func() { - spec = &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: specStateCase, - RunTime: 5 * time.Second, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 0, - RunTime: 10 * time.Second, - }) - }) - - It("should record test as failing", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(0)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases[0].Name).Should(Equal("A B C")) - Ω(output.TestCases[0].Skipped).ShouldNot(BeNil()) - }) - }) - } -}) diff --git a/vendor/github.com/onsi/ginkgo/reporters/reporters_suite_test.go b/vendor/github.com/onsi/ginkgo/reporters/reporters_suite_test.go deleted file mode 100644 index cec5a4db..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/reporters_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package reporters_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestReporters(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Reporters Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/teamcity_reporter_test.go b/vendor/github.com/onsi/ginkgo/reporters/teamcity_reporter_test.go deleted file mode 100644 index de877321..00000000 --- a/vendor/github.com/onsi/ginkgo/reporters/teamcity_reporter_test.go +++ /dev/null @@ -1,213 +0,0 @@ -package reporters_test - -import ( - "bytes" - "fmt" - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - "time" -) - -var _ = Describe("TeamCity Reporter", func() { - var ( - buffer bytes.Buffer - reporter Reporter - ) - - BeforeEach(func() { - buffer.Truncate(0) - reporter = reporters.NewTeamCityReporter(&buffer) - reporter.SpecSuiteWillBegin(config.GinkgoConfigType{}, &types.SuiteSummary{ - SuiteDescription: "Foo's test suite", - NumberOfSpecsThatWillBeRun: 1, - }) - }) - - Describe("a passing test", func() { - BeforeEach(func() { - beforeSuite := &types.SetupSummary{ - State: types.SpecStatePassed, - } - reporter.BeforeSuiteDidRun(beforeSuite) - - afterSuite := &types.SetupSummary{ - State: types.SpecStatePassed, - } - reporter.AfterSuiteDidRun(afterSuite) - - spec := &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: types.SpecStatePassed, - RunTime: 5 * time.Second, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 0, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as passing", func() { - actual := buffer.String() - expected := - "##teamcity[testSuiteStarted name='Foo|'s test suite']" + - "##teamcity[testStarted name='A B C']" + - "##teamcity[testFinished name='A B C' duration='5000']" + - "##teamcity[testSuiteFinished name='Foo|'s test suite']" - Ω(actual).Should(Equal(expected)) - }) - }) - - Describe("when the BeforeSuite fails", func() { - var beforeSuite *types.SetupSummary - - BeforeEach(func() { - beforeSuite = &types.SetupSummary{ - State: types.SpecStateFailed, - RunTime: 3 * time.Second, - Failure: types.SpecFailure{ - Message: "failed to setup\n", - ComponentCodeLocation: codelocation.New(0), - }, - } - reporter.BeforeSuiteDidRun(beforeSuite) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as having failed", func() { - actual := buffer.String() - expected := fmt.Sprintf( - "##teamcity[testSuiteStarted name='Foo|'s test suite']"+ - "##teamcity[testStarted name='BeforeSuite']"+ - "##teamcity[testFailed name='BeforeSuite' message='%s' details='failed to setup|n']"+ - "##teamcity[testFinished name='BeforeSuite' duration='3000']"+ - "##teamcity[testSuiteFinished name='Foo|'s test suite']", beforeSuite.Failure.ComponentCodeLocation.String(), - ) - Ω(actual).Should(Equal(expected)) - }) - }) - - Describe("when the AfterSuite fails", func() { - var afterSuite *types.SetupSummary - - BeforeEach(func() { - afterSuite = &types.SetupSummary{ - State: types.SpecStateFailed, - RunTime: 3 * time.Second, - Failure: types.SpecFailure{ - Message: "failed to setup\n", - ComponentCodeLocation: codelocation.New(0), - }, - } - reporter.AfterSuiteDidRun(afterSuite) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as having failed", func() { - actual := buffer.String() - expected := fmt.Sprintf( - "##teamcity[testSuiteStarted name='Foo|'s test suite']"+ - "##teamcity[testStarted name='AfterSuite']"+ - "##teamcity[testFailed name='AfterSuite' message='%s' details='failed to setup|n']"+ - "##teamcity[testFinished name='AfterSuite' duration='3000']"+ - "##teamcity[testSuiteFinished name='Foo|'s test suite']", afterSuite.Failure.ComponentCodeLocation.String(), - ) - Ω(actual).Should(Equal(expected)) - }) - }) - specStateCases := []struct { - state types.SpecState - message string - }{ - {types.SpecStateFailed, "Failure"}, - {types.SpecStateTimedOut, "Timeout"}, - {types.SpecStatePanicked, "Panic"}, - } - - for _, specStateCase := range specStateCases { - specStateCase := specStateCase - Describe("a failing test", func() { - var spec *types.SpecSummary - BeforeEach(func() { - spec = &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: specStateCase.state, - RunTime: 5 * time.Second, - Failure: types.SpecFailure{ - ComponentCodeLocation: codelocation.New(0), - Message: "I failed", - }, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record test as failing", func() { - actual := buffer.String() - expected := - fmt.Sprintf("##teamcity[testSuiteStarted name='Foo|'s test suite']"+ - "##teamcity[testStarted name='A B C']"+ - "##teamcity[testFailed name='A B C' message='%s' details='I failed']"+ - "##teamcity[testFinished name='A B C' duration='5000']"+ - "##teamcity[testSuiteFinished name='Foo|'s test suite']", spec.Failure.ComponentCodeLocation.String()) - Ω(actual).Should(Equal(expected)) - }) - }) - } - - for _, specStateCase := range []types.SpecState{types.SpecStatePending, types.SpecStateSkipped} { - specStateCase := specStateCase - Describe("a skipped test", func() { - var spec *types.SpecSummary - BeforeEach(func() { - spec = &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: specStateCase, - RunTime: 5 * time.Second, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 0, - RunTime: 10 * time.Second, - }) - }) - - It("should record test as ignored", func() { - actual := buffer.String() - expected := - "##teamcity[testSuiteStarted name='Foo|'s test suite']" + - "##teamcity[testStarted name='A B C']" + - "##teamcity[testIgnored name='A B C']" + - "##teamcity[testFinished name='A B C' duration='5000']" + - "##teamcity[testSuiteFinished name='Foo|'s test suite']" - Ω(actual).Should(Equal(expected)) - }) - }) - } -}) diff --git a/vendor/github.com/onsi/ginkgo/types/types_suite_test.go b/vendor/github.com/onsi/ginkgo/types/types_suite_test.go deleted file mode 100644 index b026169c..00000000 --- a/vendor/github.com/onsi/ginkgo/types/types_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package types_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestTypes(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Types Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/types/types_test.go b/vendor/github.com/onsi/ginkgo/types/types_test.go deleted file mode 100644 index 124b216e..00000000 --- a/vendor/github.com/onsi/ginkgo/types/types_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package types_test - -import ( - . "github.com/onsi/ginkgo/types" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var specStates = []SpecState{ - SpecStatePassed, - SpecStateTimedOut, - SpecStatePanicked, - SpecStateFailed, - SpecStatePending, - SpecStateSkipped, -} - -func verifySpecSummary(caller func(SpecSummary) bool, trueStates ...SpecState) { - summary := SpecSummary{} - trueStateLookup := map[SpecState]bool{} - for _, state := range trueStates { - trueStateLookup[state] = true - summary.State = state - Ω(caller(summary)).Should(BeTrue()) - } - - for _, state := range specStates { - if trueStateLookup[state] { - continue - } - summary.State = state - Ω(caller(summary)).Should(BeFalse()) - } -} - -var _ = Describe("Types", func() { - Describe("SpecSummary", func() { - It("knows when it is in a failure-like state", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.HasFailureState() - }, SpecStateTimedOut, SpecStatePanicked, SpecStateFailed) - }) - - It("knows when it passed", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Passed() - }, SpecStatePassed) - }) - - It("knows when it has failed", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Failed() - }, SpecStateFailed) - }) - - It("knows when it has panicked", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Panicked() - }, SpecStatePanicked) - }) - - It("knows when it has timed out", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.TimedOut() - }, SpecStateTimedOut) - }) - - It("knows when it is pending", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Pending() - }, SpecStatePending) - }) - - It("knows when it is skipped", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Skipped() - }, SpecStateSkipped) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/format/format_suite_test.go b/vendor/github.com/onsi/gomega/format/format_suite_test.go deleted file mode 100644 index 8e65a952..00000000 --- a/vendor/github.com/onsi/gomega/format/format_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package format_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestFormat(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Format Suite") -} diff --git a/vendor/github.com/onsi/gomega/format/format_test.go b/vendor/github.com/onsi/gomega/format/format_test.go deleted file mode 100644 index fd926f58..00000000 --- a/vendor/github.com/onsi/gomega/format/format_test.go +++ /dev/null @@ -1,449 +0,0 @@ -package format_test - -import ( - "fmt" - "strings" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/format" - "github.com/onsi/gomega/types" -) - -//recursive struct - -type StringAlias string -type ByteAlias []byte -type IntAlias int - -type AStruct struct { - Exported string -} - -type SimpleStruct struct { - Name string - Enumeration int - Veritas bool - Data []byte - secret uint32 -} - -type ComplexStruct struct { - Strings []string - SimpleThings []*SimpleStruct - DataMaps map[int]ByteAlias -} - -type SecretiveStruct struct { - boolValue bool - intValue int - uintValue uint - uintptrValue uintptr - floatValue float32 - complexValue complex64 - chanValue chan bool - funcValue func() - pointerValue *int - sliceValue []string - byteSliceValue []byte - stringValue string - arrValue [3]int - byteArrValue [3]byte - mapValue map[string]int - structValue AStruct - interfaceValue interface{} -} - -type GoStringer struct { -} - -func (g GoStringer) GoString() string { - return "go-string" -} - -func (g GoStringer) String() string { - return "string" -} - -type Stringer struct { -} - -func (g Stringer) String() string { - return "string" -} - -var _ = Describe("Format", func() { - match := func(typeRepresentation string, valueRepresentation string, args ...interface{}) types.GomegaMatcher { - if len(args) > 0 { - valueRepresentation = fmt.Sprintf(valueRepresentation, args...) - } - return Equal(fmt.Sprintf("%s<%s>: %s", Indent, typeRepresentation, valueRepresentation)) - } - - matchRegexp := func(typeRepresentation string, valueRepresentation string, args ...interface{}) types.GomegaMatcher { - if len(args) > 0 { - valueRepresentation = fmt.Sprintf(valueRepresentation, args...) - } - return MatchRegexp(fmt.Sprintf("%s<%s>: %s", Indent, typeRepresentation, valueRepresentation)) - } - - hashMatchingRegexp := func(entries ...string) string { - entriesSwitch := "(" + strings.Join(entries, "|") + ")" - arr := make([]string, len(entries)) - for i := range arr { - arr[i] = entriesSwitch - } - return "{" + strings.Join(arr, ", ") + "}" - } - - Describe("Message", func() { - Context("with only an actual value", func() { - It("should print out an indented formatted representation of the value and the message", func() { - Ω(Message(3, "to be three.")).Should(Equal("Expected\n : 3\nto be three.")) - }) - }) - - Context("with an actual and an expected value", func() { - It("should print out an indented formatted representatino of both values, and the message", func() { - Ω(Message(3, "to equal", 4)).Should(Equal("Expected\n : 3\nto equal\n : 4")) - }) - }) - }) - - Describe("IndentString", func() { - It("should indent the string", func() { - Ω(IndentString("foo\n bar\nbaz", 2)).Should(Equal(" foo\n bar\n baz")) - }) - }) - - Describe("Object", func() { - Describe("formatting boolean values", func() { - It("should give the type and format values correctly", func() { - Ω(Object(true, 1)).Should(match("bool", "true")) - Ω(Object(false, 1)).Should(match("bool", "false")) - }) - }) - - Describe("formatting numbers", func() { - It("should give the type and format values correctly", func() { - Ω(Object(int(3), 1)).Should(match("int", "3")) - Ω(Object(int8(3), 1)).Should(match("int8", "3")) - Ω(Object(int16(3), 1)).Should(match("int16", "3")) - Ω(Object(int32(3), 1)).Should(match("int32", "3")) - Ω(Object(int64(3), 1)).Should(match("int64", "3")) - - Ω(Object(uint(3), 1)).Should(match("uint", "3")) - Ω(Object(uint8(3), 1)).Should(match("uint8", "3")) - Ω(Object(uint16(3), 1)).Should(match("uint16", "3")) - Ω(Object(uint32(3), 1)).Should(match("uint32", "3")) - Ω(Object(uint64(3), 1)).Should(match("uint64", "3")) - }) - - It("should handle uintptr differently", func() { - Ω(Object(uintptr(3), 1)).Should(match("uintptr", "0x3")) - }) - }) - - Describe("formatting channels", func() { - It("should give the type and format values correctly", func() { - c := make(chan<- bool, 3) - c <- true - c <- false - Ω(Object(c, 1)).Should(match("chan<- bool | len:2, cap:3", "%v", c)) - }) - }) - - Describe("formatting strings", func() { - It("should give the type and format values correctly", func() { - s := "a\nb\nc" - Ω(Object(s, 1)).Should(match("string", `a - b - c`)) - }) - }) - - Describe("formatting []byte slices", func() { - It("should present them as strings", func() { - b := []byte("a\nb\nc") - Ω(Object(b, 1)).Should(matchRegexp(`\[\]uint8 \| len:5, cap:\d+`, `a - b - c`)) - }) - }) - - Describe("formatting functions", func() { - It("should give the type and format values correctly", func() { - f := func(a string, b []int) ([]byte, error) { - return []byte("abc"), nil - } - Ω(Object(f, 1)).Should(match("func(string, []int) ([]uint8, error)", "%v", f)) - }) - }) - - Describe("formatting pointers", func() { - It("should give the type and dereference the value to format it correctly", func() { - a := 3 - Ω(Object(&a, 1)).Should(match(fmt.Sprintf("*int | %p", &a), "3")) - }) - - Context("when there are pointers to pointers...", func() { - It("should recursively deference the pointer until it gets to a value", func() { - a := 3 - var b *int - var c **int - var d ***int - b = &a - c = &b - d = &c - - Ω(Object(d, 1)).Should(match(fmt.Sprintf("***int | %p", d), "3")) - }) - }) - - Context("when the pointer points to nil", func() { - It("should say nil and not explode", func() { - var a *AStruct - Ω(Object(a, 1)).Should(match("*format_test.AStruct | 0x0", "nil")) - }) - }) - }) - - Describe("formatting arrays", func() { - It("should give the type and format values correctly", func() { - w := [3]string{"Jed Bartlet", "Toby Ziegler", "CJ Cregg"} - Ω(Object(w, 1)).Should(match("[3]string", `["Jed Bartlet", "Toby Ziegler", "CJ Cregg"]`)) - }) - - Context("with byte arrays", func() { - It("should give the type and format values correctly", func() { - w := [3]byte{17, 28, 19} - Ω(Object(w, 1)).Should(match("[3]uint8", `[17, 28, 19]`)) - }) - }) - }) - - Describe("formatting slices", func() { - It("should include the length and capacity in the type information", func() { - s := make([]bool, 3, 4) - Ω(Object(s, 1)).Should(match("[]bool | len:3, cap:4", "[false, false, false]")) - }) - - Context("when the slice contains long entries", func() { - It("should format the entries with newlines", func() { - w := []string{"Josiah Edward Bartlet", "Toby Ziegler", "CJ Cregg"} - expected := `[ - "Josiah Edward Bartlet", - "Toby Ziegler", - "CJ Cregg", - ]` - Ω(Object(w, 1)).Should(match("[]string | len:3, cap:3", expected)) - }) - }) - }) - - Describe("formatting maps", func() { - It("should include the length in the type information", func() { - m := make(map[int]bool, 5) - m[3] = true - m[4] = false - Ω(Object(m, 1)).Should(matchRegexp(`map\[int\]bool \| len:2`, hashMatchingRegexp("3: true", "4: false"))) - }) - - Context("when the slice contains long entries", func() { - It("should format the entries with newlines", func() { - m := map[string][]byte{} - m["Josiah Edward Bartlet"] = []byte("Martin Sheen") - m["Toby Ziegler"] = []byte("Richard Schiff") - m["CJ Cregg"] = []byte("Allison Janney") - expected := `{ - ("Josiah Edward Bartlet": "Martin Sheen"|"Toby Ziegler": "Richard Schiff"|"CJ Cregg": "Allison Janney"), - ("Josiah Edward Bartlet": "Martin Sheen"|"Toby Ziegler": "Richard Schiff"|"CJ Cregg": "Allison Janney"), - ("Josiah Edward Bartlet": "Martin Sheen"|"Toby Ziegler": "Richard Schiff"|"CJ Cregg": "Allison Janney"), - }` - Ω(Object(m, 1)).Should(matchRegexp(`map\[string\]\[\]uint8 \| len:3`, expected)) - }) - }) - }) - - Describe("formatting structs", func() { - It("should include the struct name and the field names", func() { - s := SimpleStruct{ - Name: "Oswald", - Enumeration: 17, - Veritas: true, - Data: []byte("datum"), - secret: 1983, - } - - Ω(Object(s, 1)).Should(match("format_test.SimpleStruct", `{Name: "Oswald", Enumeration: 17, Veritas: true, Data: "datum", secret: 1983}`)) - }) - - Context("when the struct contains long entries", func() { - It("should format the entries with new lines", func() { - s := &SimpleStruct{ - Name: "Mithrandir Gandalf Greyhame", - Enumeration: 2021, - Veritas: true, - Data: []byte("wizard"), - secret: 3, - } - - Ω(Object(s, 1)).Should(match(fmt.Sprintf("*format_test.SimpleStruct | %p", s), `{ - Name: "Mithrandir Gandalf Greyhame", - Enumeration: 2021, - Veritas: true, - Data: "wizard", - secret: 3, - }`)) - }) - }) - }) - - Describe("formatting nil values", func() { - It("should print out nil", func() { - Ω(Object(nil, 1)).Should(match("nil", "nil")) - var typedNil *AStruct - Ω(Object(typedNil, 1)).Should(match("*format_test.AStruct | 0x0", "nil")) - var c chan<- bool - Ω(Object(c, 1)).Should(match("chan<- bool | len:0, cap:0", "nil")) - var s []string - Ω(Object(s, 1)).Should(match("[]string | len:0, cap:0", "nil")) - var m map[string]bool - Ω(Object(m, 1)).Should(match("map[string]bool | len:0", "nil")) - }) - }) - - Describe("formatting aliased types", func() { - It("should print out the correct alias type", func() { - Ω(Object(StringAlias("alias"), 1)).Should(match("format_test.StringAlias", `alias`)) - Ω(Object(ByteAlias("alias"), 1)).Should(matchRegexp(`format_test\.ByteAlias \| len:5, cap:\d+`, `alias`)) - Ω(Object(IntAlias(3), 1)).Should(match("format_test.IntAlias", "3")) - }) - }) - - Describe("handling nested things", func() { - It("should produce a correctly nested representation", func() { - s := ComplexStruct{ - Strings: []string{"lots", "of", "short", "strings"}, - SimpleThings: []*SimpleStruct{ - {"short", 7, true, []byte("succinct"), 17}, - {"something longer", 427, true, []byte("designed to wrap around nicely"), 30}, - }, - DataMaps: map[int]ByteAlias{ - 17: ByteAlias("some substantially longer chunks of data"), - 1138: ByteAlias("that should make things wrap"), - }, - } - expected := `{ - Strings: \["lots", "of", "short", "strings"\], - SimpleThings: \[ - {Name: "short", Enumeration: 7, Veritas: true, Data: "succinct", secret: 17}, - { - Name: "something longer", - Enumeration: 427, - Veritas: true, - Data: "designed to wrap around nicely", - secret: 30, - }, - \], - DataMaps: { - (17: "some substantially longer chunks of data"|1138: "that should make things wrap"), - (17: "some substantially longer chunks of data"|1138: "that should make things wrap"), - }, - }` - Ω(Object(s, 1)).Should(matchRegexp(`format_test\.ComplexStruct`, expected)) - }) - }) - }) - - Describe("Handling unexported fields in structs", func() { - It("should handle all the various types correctly", func() { - a := int(5) - s := SecretiveStruct{ - boolValue: true, - intValue: 3, - uintValue: 4, - uintptrValue: 5, - floatValue: 6.0, - complexValue: complex(5.0, 3.0), - chanValue: make(chan bool, 2), - funcValue: func() {}, - pointerValue: &a, - sliceValue: []string{"string", "slice"}, - byteSliceValue: []byte("bytes"), - stringValue: "a string", - arrValue: [3]int{11, 12, 13}, - byteArrValue: [3]byte{17, 20, 32}, - mapValue: map[string]int{"a key": 20, "b key": 30}, - structValue: AStruct{"exported"}, - interfaceValue: map[string]int{"a key": 17}, - } - - expected := fmt.Sprintf(`{ - boolValue: true, - intValue: 3, - uintValue: 4, - uintptrValue: 0x5, - floatValue: 6, - complexValue: \(5\+3i\), - chanValue: %p, - funcValue: %p, - pointerValue: 5, - sliceValue: \["string", "slice"\], - byteSliceValue: "bytes", - stringValue: "a string", - arrValue: \[11, 12, 13\], - byteArrValue: \[17, 20, 32\], - mapValue: %s, - structValue: {Exported: "exported"}, - interfaceValue: {"a key": 17}, - }`, s.chanValue, s.funcValue, hashMatchingRegexp(`"a key": 20`, `"b key": 30`)) - - Ω(Object(s, 1)).Should(matchRegexp(`format_test\.SecretiveStruct`, expected)) - }) - }) - - Describe("Handling interfaces", func() { - It("should unpack the interface", func() { - outerHash := map[string]interface{}{} - innerHash := map[string]int{} - - innerHash["inner"] = 3 - outerHash["integer"] = 2 - outerHash["map"] = innerHash - - expected := hashMatchingRegexp(`"integer": 2`, `"map": {"inner": 3}`) - Ω(Object(outerHash, 1)).Should(matchRegexp(`map\[string\]interface {} \| len:2`, expected)) - }) - }) - - Describe("Handling recursive things", func() { - It("should not go crazy...", func() { - m := map[string]interface{}{} - m["integer"] = 2 - m["map"] = m - Ω(Object(m, 1)).Should(ContainSubstring("...")) - }) - }) - - Describe("When instructed to use the Stringer representation", func() { - BeforeEach(func() { - UseStringerRepresentation = true - }) - - AfterEach(func() { - UseStringerRepresentation = false - }) - - Context("when passed a GoStringer", func() { - It("should use what GoString() returns", func() { - Ω(Object(GoStringer{}, 1)).Should(ContainSubstring(": go-string")) - }) - }) - - Context("when passed a stringer", func() { - It("should use what String() returns", func() { - Ω(Object(Stringer{}, 1)).Should(ContainSubstring(": string")) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/internal/assertion/assertion_suite_test.go b/vendor/github.com/onsi/gomega/internal/assertion/assertion_suite_test.go deleted file mode 100644 index dae47a48..00000000 --- a/vendor/github.com/onsi/gomega/internal/assertion/assertion_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package assertion_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestAssertion(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Assertion Suite") -} diff --git a/vendor/github.com/onsi/gomega/internal/assertion/assertion_test.go b/vendor/github.com/onsi/gomega/internal/assertion/assertion_test.go deleted file mode 100644 index de9eff2d..00000000 --- a/vendor/github.com/onsi/gomega/internal/assertion/assertion_test.go +++ /dev/null @@ -1,252 +0,0 @@ -package assertion_test - -import ( - "errors" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/internal/assertion" - "github.com/onsi/gomega/internal/fakematcher" -) - -var _ = Describe("Assertion", func() { - var ( - a *Assertion - failureMessage string - failureCallerSkip int - matcher *fakematcher.FakeMatcher - ) - - input := "The thing I'm testing" - - var fakeFailHandler = func(message string, callerSkip ...int) { - failureMessage = message - if len(callerSkip) == 1 { - failureCallerSkip = callerSkip[0] - } - } - - BeforeEach(func() { - matcher = &fakematcher.FakeMatcher{} - failureMessage = "" - failureCallerSkip = 0 - a = New(input, fakeFailHandler, 1) - }) - - Context("when called", func() { - It("should pass the provided input value to the matcher", func() { - a.Should(matcher) - - Ω(matcher.ReceivedActual).Should(Equal(input)) - matcher.ReceivedActual = "" - - a.ShouldNot(matcher) - - Ω(matcher.ReceivedActual).Should(Equal(input)) - matcher.ReceivedActual = "" - - a.To(matcher) - - Ω(matcher.ReceivedActual).Should(Equal(input)) - matcher.ReceivedActual = "" - - a.ToNot(matcher) - - Ω(matcher.ReceivedActual).Should(Equal(input)) - matcher.ReceivedActual = "" - - a.NotTo(matcher) - - Ω(matcher.ReceivedActual).Should(Equal(input)) - }) - }) - - Context("when the matcher succeeds", func() { - BeforeEach(func() { - matcher.MatchesToReturn = true - matcher.ErrToReturn = nil - }) - - Context("and a positive assertion is being made", func() { - It("should not call the failure callback", func() { - a.Should(matcher) - Ω(failureMessage).Should(Equal("")) - }) - - It("should be true", func() { - Ω(a.Should(matcher)).Should(BeTrue()) - }) - }) - - Context("and a negative assertion is being made", func() { - It("should call the failure callback", func() { - a.ShouldNot(matcher) - Ω(failureMessage).Should(Equal("negative: The thing I'm testing")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - - It("should be false", func() { - Ω(a.ShouldNot(matcher)).Should(BeFalse()) - }) - }) - }) - - Context("when the matcher fails", func() { - BeforeEach(func() { - matcher.MatchesToReturn = false - matcher.ErrToReturn = nil - }) - - Context("and a positive assertion is being made", func() { - It("should call the failure callback", func() { - a.Should(matcher) - Ω(failureMessage).Should(Equal("positive: The thing I'm testing")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - - It("should be false", func() { - Ω(a.Should(matcher)).Should(BeFalse()) - }) - }) - - Context("and a negative assertion is being made", func() { - It("should not call the failure callback", func() { - a.ShouldNot(matcher) - Ω(failureMessage).Should(Equal("")) - }) - - It("should be true", func() { - Ω(a.ShouldNot(matcher)).Should(BeTrue()) - }) - }) - }) - - Context("When reporting a failure", func() { - BeforeEach(func() { - matcher.MatchesToReturn = false - matcher.ErrToReturn = nil - }) - - Context("and there is an optional description", func() { - It("should append the description to the failure message", func() { - a.Should(matcher, "A description") - Ω(failureMessage).Should(Equal("A description\npositive: The thing I'm testing")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - }) - - Context("and there are multiple arguments to the optional description", func() { - It("should append the formatted description to the failure message", func() { - a.Should(matcher, "A description of [%d]", 3) - Ω(failureMessage).Should(Equal("A description of [3]\npositive: The thing I'm testing")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - }) - }) - - Context("When the matcher returns an error", func() { - BeforeEach(func() { - matcher.ErrToReturn = errors.New("Kaboom!") - }) - - Context("and a positive assertion is being made", func() { - It("should call the failure callback", func() { - matcher.MatchesToReturn = true - a.Should(matcher) - Ω(failureMessage).Should(Equal("Kaboom!")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - }) - - Context("and a negative assertion is being made", func() { - It("should call the failure callback", func() { - matcher.MatchesToReturn = false - a.ShouldNot(matcher) - Ω(failureMessage).Should(Equal("Kaboom!")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - }) - - It("should always be false", func() { - Ω(a.Should(matcher)).Should(BeFalse()) - Ω(a.ShouldNot(matcher)).Should(BeFalse()) - }) - }) - - Context("when there are extra parameters", func() { - It("(a simple example)", func() { - Ω(func() (string, int, error) { - return "foo", 0, nil - }()).Should(Equal("foo")) - }) - - Context("when the parameters are all nil or zero", func() { - It("should invoke the matcher", func() { - matcher.MatchesToReturn = true - matcher.ErrToReturn = nil - - var typedNil []string - a = New(input, fakeFailHandler, 1, 0, nil, typedNil) - - result := a.Should(matcher) - Ω(result).Should(BeTrue()) - Ω(matcher.ReceivedActual).Should(Equal(input)) - - Ω(failureMessage).Should(BeZero()) - }) - }) - - Context("when any of the parameters are not nil or zero", func() { - It("should call the failure callback", func() { - matcher.MatchesToReturn = false - matcher.ErrToReturn = nil - - a = New(input, fakeFailHandler, 1, errors.New("foo")) - result := a.Should(matcher) - Ω(result).Should(BeFalse()) - Ω(matcher.ReceivedActual).Should(BeZero(), "The matcher doesn't even get called") - Ω(failureMessage).Should(ContainSubstring("foo")) - failureMessage = "" - - a = New(input, fakeFailHandler, 1, nil, 1) - result = a.ShouldNot(matcher) - Ω(result).Should(BeFalse()) - Ω(failureMessage).Should(ContainSubstring("1")) - failureMessage = "" - - a = New(input, fakeFailHandler, 1, nil, 0, []string{"foo"}) - result = a.To(matcher) - Ω(result).Should(BeFalse()) - Ω(failureMessage).Should(ContainSubstring("foo")) - failureMessage = "" - - a = New(input, fakeFailHandler, 1, nil, 0, []string{"foo"}) - result = a.ToNot(matcher) - Ω(result).Should(BeFalse()) - Ω(failureMessage).Should(ContainSubstring("foo")) - failureMessage = "" - - a = New(input, fakeFailHandler, 1, nil, 0, []string{"foo"}) - result = a.NotTo(matcher) - Ω(result).Should(BeFalse()) - Ω(failureMessage).Should(ContainSubstring("foo")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - }) - }) - - Context("Making an assertion without a registered fail handler", func() { - It("should panic", func() { - defer func() { - e := recover() - RegisterFailHandler(Fail) - if e == nil { - Fail("expected a panic to have occured") - } - }() - - RegisterFailHandler(nil) - Ω(true).Should(BeTrue()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion_suite_test.go b/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion_suite_test.go deleted file mode 100644 index bdb0c3d2..00000000 --- a/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package asyncassertion_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestAsyncAssertion(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "AsyncAssertion Suite") -} diff --git a/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion_test.go b/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion_test.go deleted file mode 100644 index 4288d4da..00000000 --- a/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion_test.go +++ /dev/null @@ -1,345 +0,0 @@ -package asyncassertion_test - -import ( - "errors" - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/internal/asyncassertion" -) - -var _ = Describe("Async Assertion", func() { - var ( - failureMessage string - callerSkip int - ) - - var fakeFailHandler = func(message string, skip ...int) { - failureMessage = message - callerSkip = skip[0] - } - - BeforeEach(func() { - failureMessage = "" - callerSkip = 0 - }) - - Describe("Eventually", func() { - Context("the positive case", func() { - It("should poll the function and matcher", func() { - counter := 0 - a := New(AsyncAssertionTypeEventually, func() int { - counter++ - return counter - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.Should(BeNumerically("==", 5)) - Ω(failureMessage).Should(BeZero()) - }) - - It("should continue when the matcher errors", func() { - counter := 0 - a := New(AsyncAssertionTypeEventually, func() interface{} { - counter++ - if counter == 5 { - return "not-a-number" //this should cause the matcher to error - } - return counter - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.Should(BeNumerically("==", 5), "My description %d", 2) - - Ω(failureMessage).Should(ContainSubstring("Timed out after")) - Ω(failureMessage).Should(ContainSubstring("My description 2")) - Ω(callerSkip).Should(Equal(4)) - }) - - It("should be able to timeout", func() { - counter := 0 - a := New(AsyncAssertionTypeEventually, func() int { - counter++ - return counter - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.Should(BeNumerically(">", 100), "My description %d", 2) - - Ω(counter).Should(BeNumerically(">", 8)) - Ω(counter).Should(BeNumerically("<=", 10)) - Ω(failureMessage).Should(ContainSubstring("Timed out after")) - Ω(failureMessage).Should(MatchRegexp(`\: \d`), "Should pass the correct value to the matcher message formatter.") - Ω(failureMessage).Should(ContainSubstring("My description 2")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - - Context("the negative case", func() { - It("should poll the function and matcher", func() { - counter := 0 - a := New(AsyncAssertionTypeEventually, func() int { - counter += 1 - return counter - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.ShouldNot(BeNumerically("<", 3)) - - Ω(counter).Should(Equal(3)) - Ω(failureMessage).Should(BeZero()) - }) - - It("should timeout when the matcher errors", func() { - a := New(AsyncAssertionTypeEventually, func() interface{} { - return 0 //this should cause the matcher to error - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.ShouldNot(HaveLen(0), "My description %d", 2) - - Ω(failureMessage).Should(ContainSubstring("Timed out after")) - Ω(failureMessage).Should(ContainSubstring("Error:")) - Ω(failureMessage).Should(ContainSubstring("My description 2")) - Ω(callerSkip).Should(Equal(4)) - }) - - It("should be able to timeout", func() { - a := New(AsyncAssertionTypeEventually, func() int { - return 0 - }, fakeFailHandler, time.Duration(0.1*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.ShouldNot(Equal(0), "My description %d", 2) - - Ω(failureMessage).Should(ContainSubstring("Timed out after")) - Ω(failureMessage).Should(ContainSubstring(": 0"), "Should pass the correct value to the matcher message formatter.") - Ω(failureMessage).Should(ContainSubstring("My description 2")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - - Context("with a function that returns multiple values", func() { - It("should eventually succeed if the additional arguments are nil", func() { - i := 0 - Eventually(func() (int, error) { - i++ - return i, nil - }).Should(Equal(10)) - }) - - It("should eventually timeout if the additional arguments are not nil", func() { - i := 0 - a := New(AsyncAssertionTypeEventually, func() (int, error) { - i++ - return i, errors.New("bam") - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - a.Should(Equal(2)) - - Ω(failureMessage).Should(ContainSubstring("Timed out after")) - Ω(failureMessage).Should(ContainSubstring("Error:")) - Ω(failureMessage).Should(ContainSubstring("bam")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - - Context("Making an assertion without a registered fail handler", func() { - It("should panic", func() { - defer func() { - e := recover() - RegisterFailHandler(Fail) - if e == nil { - Fail("expected a panic to have occured") - } - }() - - RegisterFailHandler(nil) - c := make(chan bool, 1) - c <- true - Eventually(c).Should(Receive()) - }) - }) - }) - - Describe("Consistently", func() { - Describe("The positive case", func() { - Context("when the matcher consistently passes for the duration", func() { - It("should pass", func() { - calls := 0 - a := New(AsyncAssertionTypeConsistently, func() string { - calls++ - return "foo" - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.Should(Equal("foo")) - Ω(calls).Should(BeNumerically(">", 8)) - Ω(calls).Should(BeNumerically("<=", 10)) - Ω(failureMessage).Should(BeZero()) - }) - }) - - Context("when the matcher fails at some point", func() { - It("should fail", func() { - calls := 0 - a := New(AsyncAssertionTypeConsistently, func() interface{} { - calls++ - if calls > 5 { - return "bar" - } - return "foo" - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.Should(Equal("foo")) - Ω(failureMessage).Should(ContainSubstring("to equal")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - - Context("when the matcher errors at some point", func() { - It("should fail", func() { - calls := 0 - a := New(AsyncAssertionTypeConsistently, func() interface{} { - calls++ - if calls > 5 { - return 3 - } - return []int{1, 2, 3} - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.Should(HaveLen(3)) - Ω(failureMessage).Should(ContainSubstring("HaveLen matcher expects")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - }) - - Describe("The negative case", func() { - Context("when the matcher consistently passes for the duration", func() { - It("should pass", func() { - c := make(chan bool) - a := New(AsyncAssertionTypeConsistently, c, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.ShouldNot(Receive()) - Ω(failureMessage).Should(BeZero()) - }) - }) - - Context("when the matcher fails at some point", func() { - It("should fail", func() { - c := make(chan bool) - go func() { - time.Sleep(time.Duration(100 * time.Millisecond)) - c <- true - }() - - a := New(AsyncAssertionTypeConsistently, c, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.ShouldNot(Receive()) - Ω(failureMessage).Should(ContainSubstring("not to receive anything")) - }) - }) - - Context("when the matcher errors at some point", func() { - It("should fail", func() { - calls := 0 - a := New(AsyncAssertionTypeConsistently, func() interface{} { - calls++ - return calls - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.ShouldNot(BeNumerically(">", 5)) - Ω(failureMessage).Should(ContainSubstring("not to be >")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - }) - - Context("with a function that returns multiple values", func() { - It("should consistently succeed if the additional arguments are nil", func() { - i := 2 - Consistently(func() (int, error) { - i++ - return i, nil - }).Should(BeNumerically(">=", 2)) - }) - - It("should eventually timeout if the additional arguments are not nil", func() { - i := 2 - a := New(AsyncAssertionTypeEventually, func() (int, error) { - i++ - return i, errors.New("bam") - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - a.Should(BeNumerically(">=", 2)) - - Ω(failureMessage).Should(ContainSubstring("Error:")) - Ω(failureMessage).Should(ContainSubstring("bam")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - - Context("Making an assertion without a registered fail handler", func() { - It("should panic", func() { - defer func() { - e := recover() - RegisterFailHandler(Fail) - if e == nil { - Fail("expected a panic to have occured") - } - }() - - RegisterFailHandler(nil) - c := make(chan bool) - Consistently(c).ShouldNot(Receive()) - }) - }) - }) - - Context("when passed a function with the wrong # or arguments & returns", func() { - It("should panic", func() { - Ω(func() { - New(AsyncAssertionTypeEventually, func() {}, fakeFailHandler, 0, 0, 1) - }).Should(Panic()) - - Ω(func() { - New(AsyncAssertionTypeEventually, func(a string) int { return 0 }, fakeFailHandler, 0, 0, 1) - }).Should(Panic()) - - Ω(func() { - New(AsyncAssertionTypeEventually, func() int { return 0 }, fakeFailHandler, 0, 0, 1) - }).ShouldNot(Panic()) - - Ω(func() { - New(AsyncAssertionTypeEventually, func() (int, error) { return 0, nil }, fakeFailHandler, 0, 0, 1) - }).ShouldNot(Panic()) - }) - }) - - Describe("bailing early", func() { - Context("when actual is a value", func() { - It("Eventually should bail out and fail early if the matcher says to", func() { - c := make(chan bool) - close(c) - - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(c, 0.1).Should(Receive()) - }) - Ω(time.Since(t)).Should(BeNumerically("<", 90*time.Millisecond)) - - Ω(failures).Should(HaveLen(1)) - }) - }) - - Context("when actual is a function", func() { - It("should never bail early", func() { - c := make(chan bool) - close(c) - - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(func() chan bool { - return c - }, 0.1).Should(Receive()) - }) - Ω(time.Since(t)).Should(BeNumerically(">=", 90*time.Millisecond)) - - Ω(failures).Should(HaveLen(1)) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support_test.go b/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support_test.go deleted file mode 100644 index b9fbd6c6..00000000 --- a/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support_test.go +++ /dev/null @@ -1,12 +0,0 @@ -package testingtsupport_test - -import ( - . "github.com/onsi/gomega" - - "testing" -) - -func TestTestingT(t *testing.T) { - RegisterTestingT(t) - Ω(true).Should(BeTrue()) -} diff --git a/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher_test.go deleted file mode 100644 index d2280e05..00000000 --- a/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("AssignableToTypeOf", func() { - Context("When asserting assignability between types", func() { - It("should do the right thing", func() { - Ω(0).Should(BeAssignableToTypeOf(0)) - Ω(5).Should(BeAssignableToTypeOf(-1)) - Ω("foo").Should(BeAssignableToTypeOf("bar")) - Ω(struct{ Foo string }{}).Should(BeAssignableToTypeOf(struct{ Foo string }{})) - - Ω(0).ShouldNot(BeAssignableToTypeOf("bar")) - Ω(5).ShouldNot(BeAssignableToTypeOf(struct{ Foo string }{})) - Ω("foo").ShouldNot(BeAssignableToTypeOf(42)) - }) - }) - - Context("When asserting nil values", func() { - It("should error", func() { - success, err := (&AssignableToTypeOfMatcher{Expected: nil}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_a_directory_test.go b/vendor/github.com/onsi/gomega/matchers/be_a_directory_test.go deleted file mode 100644 index e59d7699..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_a_directory_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package matchers_test - -import ( - "io/ioutil" - "os" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeADirectoryMatcher", func() { - Context("when passed a string", func() { - It("should do the right thing", func() { - Ω("/dne/test").ShouldNot(BeADirectory()) - - tmpFile, err := ioutil.TempFile("", "gomega-test-tempfile") - Ω(err).ShouldNot(HaveOccurred()) - defer os.Remove(tmpFile.Name()) - Ω(tmpFile.Name()).ShouldNot(BeADirectory()) - - tmpDir, err := ioutil.TempDir("", "gomega-test-tempdir") - Ω(err).ShouldNot(HaveOccurred()) - defer os.Remove(tmpDir) - Ω(tmpDir).Should(BeADirectory()) - }) - }) - - Context("when passed something else", func() { - It("should error", func() { - success, err := (&BeADirectoryMatcher{}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeADirectoryMatcher{}).Match(true) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_a_regular_file_test.go b/vendor/github.com/onsi/gomega/matchers/be_a_regular_file_test.go deleted file mode 100644 index 951e750d..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_a_regular_file_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package matchers_test - -import ( - "io/ioutil" - "os" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeARegularFileMatcher", func() { - Context("when passed a string", func() { - It("should do the right thing", func() { - Ω("/dne/test").ShouldNot(BeARegularFile()) - - tmpFile, err := ioutil.TempFile("", "gomega-test-tempfile") - Ω(err).ShouldNot(HaveOccurred()) - defer os.Remove(tmpFile.Name()) - Ω(tmpFile.Name()).Should(BeARegularFile()) - - tmpDir, err := ioutil.TempDir("", "gomega-test-tempdir") - Ω(err).ShouldNot(HaveOccurred()) - defer os.Remove(tmpDir) - Ω(tmpDir).ShouldNot(BeARegularFile()) - }) - }) - - Context("when passed something else", func() { - It("should error", func() { - success, err := (&BeARegularFileMatcher{}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeARegularFileMatcher{}).Match(true) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_an_existing_file_test.go b/vendor/github.com/onsi/gomega/matchers/be_an_existing_file_test.go deleted file mode 100644 index 775f7b6a..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_an_existing_file_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package matchers_test - -import ( - "io/ioutil" - "os" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeAnExistingFileMatcher", func() { - Context("when passed a string", func() { - It("should do the right thing", func() { - Ω("/dne/test").ShouldNot(BeAnExistingFile()) - - tmpFile, err := ioutil.TempFile("", "gomega-test-tempfile") - Ω(err).ShouldNot(HaveOccurred()) - defer os.Remove(tmpFile.Name()) - Ω(tmpFile.Name()).Should(BeAnExistingFile()) - - tmpDir, err := ioutil.TempDir("", "gomega-test-tempdir") - Ω(err).ShouldNot(HaveOccurred()) - defer os.Remove(tmpDir) - Ω(tmpDir).Should(BeAnExistingFile()) - }) - }) - - Context("when passed something else", func() { - It("should error", func() { - success, err := (&BeAnExistingFileMatcher{}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeAnExistingFileMatcher{}).Match(true) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_closed_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_closed_matcher_test.go deleted file mode 100644 index b2c40c91..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_closed_matcher_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeClosedMatcher", func() { - Context("when passed a channel", func() { - It("should do the right thing", func() { - openChannel := make(chan bool) - Ω(openChannel).ShouldNot(BeClosed()) - - var openReaderChannel <-chan bool - openReaderChannel = openChannel - Ω(openReaderChannel).ShouldNot(BeClosed()) - - closedChannel := make(chan bool) - close(closedChannel) - - Ω(closedChannel).Should(BeClosed()) - - var closedReaderChannel <-chan bool - closedReaderChannel = closedChannel - Ω(closedReaderChannel).Should(BeClosed()) - }) - }) - - Context("when passed a send-only channel", func() { - It("should error", func() { - openChannel := make(chan bool) - var openWriterChannel chan<- bool - openWriterChannel = openChannel - - success, err := (&BeClosedMatcher{}).Match(openWriterChannel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - closedChannel := make(chan bool) - close(closedChannel) - - var closedWriterChannel chan<- bool - closedWriterChannel = closedChannel - - success, err = (&BeClosedMatcher{}).Match(closedWriterChannel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - }) - }) - - Context("when passed something else", func() { - It("should error", func() { - var nilChannel chan bool - - success, err := (&BeClosedMatcher{}).Match(nilChannel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeClosedMatcher{}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeClosedMatcher{}).Match(7) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_empty_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_empty_matcher_test.go deleted file mode 100644 index 541c1b95..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_empty_matcher_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeEmpty", func() { - Context("when passed a supported type", func() { - It("should do the right thing", func() { - Ω("").Should(BeEmpty()) - Ω(" ").ShouldNot(BeEmpty()) - - Ω([0]int{}).Should(BeEmpty()) - Ω([1]int{1}).ShouldNot(BeEmpty()) - - Ω([]int{}).Should(BeEmpty()) - Ω([]int{1}).ShouldNot(BeEmpty()) - - Ω(map[string]int{}).Should(BeEmpty()) - Ω(map[string]int{"a": 1}).ShouldNot(BeEmpty()) - - c := make(chan bool, 1) - Ω(c).Should(BeEmpty()) - c <- true - Ω(c).ShouldNot(BeEmpty()) - }) - }) - - Context("when passed a correctly typed nil", func() { - It("should be true", func() { - var nilSlice []int - Ω(nilSlice).Should(BeEmpty()) - - var nilMap map[int]string - Ω(nilMap).Should(BeEmpty()) - }) - }) - - Context("when passed an unsupported type", func() { - It("should error", func() { - success, err := (&BeEmptyMatcher{}).Match(0) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeEmptyMatcher{}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher_test.go deleted file mode 100644 index def5104f..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeEquivalentTo", func() { - Context("when asserting that nil is equivalent to nil", func() { - It("should error", func() { - success, err := (&BeEquivalentToMatcher{Expected: nil}).Match(nil) - - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("When asserting on nil", func() { - It("should do the right thing", func() { - Ω("foo").ShouldNot(BeEquivalentTo(nil)) - Ω(nil).ShouldNot(BeEquivalentTo(3)) - Ω([]int{1, 2}).ShouldNot(BeEquivalentTo(nil)) - }) - }) - - Context("When asserting on type aliases", func() { - It("should the right thing", func() { - Ω(StringAlias("foo")).Should(BeEquivalentTo("foo")) - Ω("foo").Should(BeEquivalentTo(StringAlias("foo"))) - Ω(StringAlias("foo")).ShouldNot(BeEquivalentTo("bar")) - Ω("foo").ShouldNot(BeEquivalentTo(StringAlias("bar"))) - }) - }) - - Context("When asserting on numbers", func() { - It("should convert actual to expected and do the right thing", func() { - Ω(5).Should(BeEquivalentTo(5)) - Ω(5.0).Should(BeEquivalentTo(5.0)) - Ω(5).Should(BeEquivalentTo(5.0)) - - Ω(5).ShouldNot(BeEquivalentTo("5")) - Ω(5).ShouldNot(BeEquivalentTo(3)) - - //Here be dragons! - Ω(5.1).Should(BeEquivalentTo(5)) - Ω(5).ShouldNot(BeEquivalentTo(5.1)) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_false_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_false_matcher_test.go deleted file mode 100644 index 3965a2c5..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_false_matcher_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeFalse", func() { - It("should handle true and false correctly", func() { - Ω(true).ShouldNot(BeFalse()) - Ω(false).Should(BeFalse()) - }) - - It("should only support booleans", func() { - success, err := (&BeFalseMatcher{}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_nil_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_nil_matcher_test.go deleted file mode 100644 index 75332536..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_nil_matcher_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("BeNil", func() { - It("should succeed when passed nil", func() { - Ω(nil).Should(BeNil()) - }) - - It("should succeed when passed a typed nil", func() { - var a []int - Ω(a).Should(BeNil()) - }) - - It("should succeed when passing nil pointer", func() { - var f *struct{} - Ω(f).Should(BeNil()) - }) - - It("should not succeed when not passed nil", func() { - Ω(0).ShouldNot(BeNil()) - Ω(false).ShouldNot(BeNil()) - Ω("").ShouldNot(BeNil()) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher_test.go deleted file mode 100644 index 43fdb1fe..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher_test.go +++ /dev/null @@ -1,148 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeNumerically", func() { - Context("when passed a number", func() { - It("should support ==", func() { - Ω(uint32(5)).Should(BeNumerically("==", 5)) - Ω(float64(5.0)).Should(BeNumerically("==", 5)) - Ω(int8(5)).Should(BeNumerically("==", 5)) - }) - - It("should not have false positives", func() { - Ω(5.1).ShouldNot(BeNumerically("==", 5)) - Ω(5).ShouldNot(BeNumerically("==", 5.1)) - }) - - It("should support >", func() { - Ω(uint32(5)).Should(BeNumerically(">", 4)) - Ω(float64(5.0)).Should(BeNumerically(">", 4.9)) - Ω(int8(5)).Should(BeNumerically(">", 4)) - - Ω(uint32(5)).ShouldNot(BeNumerically(">", 5)) - Ω(float64(5.0)).ShouldNot(BeNumerically(">", 5.0)) - Ω(int8(5)).ShouldNot(BeNumerically(">", 5)) - }) - - It("should support <", func() { - Ω(uint32(5)).Should(BeNumerically("<", 6)) - Ω(float64(5.0)).Should(BeNumerically("<", 5.1)) - Ω(int8(5)).Should(BeNumerically("<", 6)) - - Ω(uint32(5)).ShouldNot(BeNumerically("<", 5)) - Ω(float64(5.0)).ShouldNot(BeNumerically("<", 5.0)) - Ω(int8(5)).ShouldNot(BeNumerically("<", 5)) - }) - - It("should support >=", func() { - Ω(uint32(5)).Should(BeNumerically(">=", 4)) - Ω(float64(5.0)).Should(BeNumerically(">=", 4.9)) - Ω(int8(5)).Should(BeNumerically(">=", 4)) - - Ω(uint32(5)).Should(BeNumerically(">=", 5)) - Ω(float64(5.0)).Should(BeNumerically(">=", 5.0)) - Ω(int8(5)).Should(BeNumerically(">=", 5)) - - Ω(uint32(5)).ShouldNot(BeNumerically(">=", 6)) - Ω(float64(5.0)).ShouldNot(BeNumerically(">=", 5.1)) - Ω(int8(5)).ShouldNot(BeNumerically(">=", 6)) - }) - - It("should support <=", func() { - Ω(uint32(5)).Should(BeNumerically("<=", 6)) - Ω(float64(5.0)).Should(BeNumerically("<=", 5.1)) - Ω(int8(5)).Should(BeNumerically("<=", 6)) - - Ω(uint32(5)).Should(BeNumerically("<=", 5)) - Ω(float64(5.0)).Should(BeNumerically("<=", 5.0)) - Ω(int8(5)).Should(BeNumerically("<=", 5)) - - Ω(uint32(5)).ShouldNot(BeNumerically("<=", 4)) - Ω(float64(5.0)).ShouldNot(BeNumerically("<=", 4.9)) - Ω(int8(5)).Should(BeNumerically("<=", 5)) - }) - - Context("when passed ~", func() { - Context("when passed a float", func() { - Context("and there is no precision parameter", func() { - It("should default to 1e-8", func() { - Ω(5.00000001).Should(BeNumerically("~", 5.00000002)) - Ω(5.00000001).ShouldNot(BeNumerically("~", 5.0000001)) - }) - }) - - Context("and there is a precision parameter", func() { - It("should use the precision parameter", func() { - Ω(5.1).Should(BeNumerically("~", 5.19, 0.1)) - Ω(5.1).Should(BeNumerically("~", 5.01, 0.1)) - Ω(5.1).ShouldNot(BeNumerically("~", 5.22, 0.1)) - Ω(5.1).ShouldNot(BeNumerically("~", 4.98, 0.1)) - }) - }) - }) - - Context("when passed an int/uint", func() { - Context("and there is no precision parameter", func() { - It("should just do strict equality", func() { - Ω(5).Should(BeNumerically("~", 5)) - Ω(5).ShouldNot(BeNumerically("~", 6)) - Ω(uint(5)).ShouldNot(BeNumerically("~", 6)) - }) - }) - - Context("and there is a precision parameter", func() { - It("should use precision paramter", func() { - Ω(5).Should(BeNumerically("~", 6, 2)) - Ω(5).ShouldNot(BeNumerically("~", 8, 2)) - Ω(uint(5)).Should(BeNumerically("~", 6, 1)) - }) - }) - }) - }) - }) - - Context("when passed a non-number", func() { - It("should error", func() { - success, err := (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{5}}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeNumericallyMatcher{Comparator: "=="}).Match(5) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeNumericallyMatcher{Comparator: "~", CompareTo: []interface{}{3.0, "foo"}}).Match(5.0) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{"bar"}}).Match(5) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{"bar"}}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{nil}}).Match(0) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{0}}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed an unsupported comparator", func() { - It("should error", func() { - success, err := (&BeNumericallyMatcher{Comparator: "!=", CompareTo: []interface{}{5}}).Match(4) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_sent_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_sent_matcher_test.go deleted file mode 100644 index 381c2b40..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_sent_matcher_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package matchers_test - -import ( - "time" - . "github.com/onsi/gomega/matchers" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("BeSent", func() { - Context("when passed a channel and a matching type", func() { - Context("when the channel is ready to receive", func() { - It("should succeed and send the value down the channel", func() { - c := make(chan string) - d := make(chan string) - go func() { - val := <-c - d <- val - }() - - time.Sleep(10 * time.Millisecond) - - Ω(c).Should(BeSent("foo")) - Eventually(d).Should(Receive(Equal("foo"))) - }) - - It("should succeed (with a buffered channel)", func() { - c := make(chan string, 1) - Ω(c).Should(BeSent("foo")) - Ω(<-c).Should(Equal("foo")) - }) - }) - - Context("when the channel is not ready to receive", func() { - It("should fail and not send down the channel", func() { - c := make(chan string) - Ω(c).ShouldNot(BeSent("foo")) - Consistently(c).ShouldNot(Receive()) - }) - }) - - Context("when the channel is eventually ready to receive", func() { - It("should succeed", func() { - c := make(chan string) - d := make(chan string) - go func() { - time.Sleep(30 * time.Millisecond) - val := <-c - d <- val - }() - - Eventually(c).Should(BeSent("foo")) - Eventually(d).Should(Receive(Equal("foo"))) - }) - }) - - Context("when the channel is closed", func() { - It("should error", func() { - c := make(chan string) - close(c) - success, err := (&BeSentMatcher{Arg: "foo"}).Match(c) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - - It("should short-circuit Eventually", func() { - c := make(chan string) - close(c) - - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(c, 10.0).Should(BeSent("foo")) - }) - Ω(failures).Should(HaveLen(1)) - Ω(time.Since(t)).Should(BeNumerically("<", time.Second)) - }) - }) - }) - - Context("when passed a channel and a non-matching type", func() { - It("should error", func() { - success, err := (&BeSentMatcher{Arg: "foo"}).Match(make(chan int, 1)) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed a receive-only channel", func() { - It("should error", func() { - var c <-chan string - c = make(chan string, 1) - success, err := (&BeSentMatcher{Arg: "foo"}).Match(c) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed a nonchannel", func() { - It("should error", func() { - success, err := (&BeSentMatcher{Arg: "foo"}).Match("bar") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher_test.go deleted file mode 100644 index feb33e5d..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" - "time" -) - -var _ = Describe("BeTemporally", func() { - - var t0, t1, t2 time.Time - BeforeEach(func() { - t0 = time.Now() - t1 = t0.Add(time.Second) - t2 = t0.Add(-time.Second) - }) - - Context("When comparing times", func() { - - It("should support ==", func() { - Ω(t0).Should(BeTemporally("==", t0)) - Ω(t1).ShouldNot(BeTemporally("==", t0)) - Ω(t0).ShouldNot(BeTemporally("==", t1)) - Ω(t0).ShouldNot(BeTemporally("==", time.Time{})) - }) - - It("should support >", func() { - Ω(t0).Should(BeTemporally(">", t2)) - Ω(t0).ShouldNot(BeTemporally(">", t0)) - Ω(t2).ShouldNot(BeTemporally(">", t0)) - }) - - It("should support <", func() { - Ω(t0).Should(BeTemporally("<", t1)) - Ω(t0).ShouldNot(BeTemporally("<", t0)) - Ω(t1).ShouldNot(BeTemporally("<", t0)) - }) - - It("should support >=", func() { - Ω(t0).Should(BeTemporally(">=", t2)) - Ω(t0).Should(BeTemporally(">=", t0)) - Ω(t0).ShouldNot(BeTemporally(">=", t1)) - }) - - It("should support <=", func() { - Ω(t0).Should(BeTemporally("<=", t1)) - Ω(t0).Should(BeTemporally("<=", t0)) - Ω(t0).ShouldNot(BeTemporally("<=", t2)) - }) - - Context("when passed ~", func() { - Context("and there is no precision parameter", func() { - BeforeEach(func() { - t1 = t0.Add(time.Millisecond / 2) - t2 = t0.Add(-2 * time.Millisecond) - }) - It("should approximate", func() { - Ω(t0).Should(BeTemporally("~", t0)) - Ω(t0).Should(BeTemporally("~", t1)) - Ω(t0).ShouldNot(BeTemporally("~", t2)) - }) - }) - - Context("and there is a precision parameter", func() { - BeforeEach(func() { - t2 = t0.Add(3 * time.Second) - }) - It("should use precision paramter", func() { - d := 2 * time.Second - Ω(t0).Should(BeTemporally("~", t0, d)) - Ω(t0).Should(BeTemporally("~", t1, d)) - Ω(t0).ShouldNot(BeTemporally("~", t2, d)) - }) - }) - }) - }) - - Context("when passed a non-time", func() { - It("should error", func() { - success, err := (&BeTemporallyMatcher{Comparator: "==", CompareTo: t0}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeTemporallyMatcher{Comparator: "=="}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed an unsupported comparator", func() { - It("should error", func() { - success, err := (&BeTemporallyMatcher{Comparator: "!=", CompareTo: t0}).Match(t2) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_true_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_true_matcher_test.go deleted file mode 100644 index ca32e56b..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_true_matcher_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeTrue", func() { - It("should handle true and false correctly", func() { - Ω(true).Should(BeTrue()) - Ω(false).ShouldNot(BeTrue()) - }) - - It("should only support booleans", func() { - success, err := (&BeTrueMatcher{}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_zero_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_zero_matcher_test.go deleted file mode 100644 index 8ec3643c..00000000 --- a/vendor/github.com/onsi/gomega/matchers/be_zero_matcher_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("BeZero", func() { - It("should succeed if the passed in object is the zero value for its type", func() { - Ω(nil).Should(BeZero()) - - Ω("").Should(BeZero()) - Ω(" ").ShouldNot(BeZero()) - - Ω(0).Should(BeZero()) - Ω(1).ShouldNot(BeZero()) - - Ω(0.0).Should(BeZero()) - Ω(0.1).ShouldNot(BeZero()) - - // Ω([]int{}).Should(BeZero()) - Ω([]int{1}).ShouldNot(BeZero()) - - // Ω(map[string]int{}).Should(BeZero()) - Ω(map[string]int{"a": 1}).ShouldNot(BeZero()) - - Ω(myCustomType{}).Should(BeZero()) - Ω(myCustomType{s: "a"}).ShouldNot(BeZero()) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/consist_of_test.go b/vendor/github.com/onsi/gomega/matchers/consist_of_test.go deleted file mode 100644 index 0b230e39..00000000 --- a/vendor/github.com/onsi/gomega/matchers/consist_of_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("ConsistOf", func() { - Context("with a slice", func() { - It("should do the right thing", func() { - Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", "bar", "baz")) - Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", "bar", "baz")) - Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("baz", "bar", "foo")) - Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("baz", "bar", "foo", "foo")) - Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("baz", "foo")) - }) - }) - - Context("with an array", func() { - It("should do the right thing", func() { - Ω([3]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", "bar", "baz")) - Ω([3]string{"foo", "bar", "baz"}).Should(ConsistOf("baz", "bar", "foo")) - Ω([3]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("baz", "bar", "foo", "foo")) - Ω([3]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("baz", "foo")) - }) - }) - - Context("with a map", func() { - It("should apply to the values", func() { - Ω(map[int]string{1: "foo", 2: "bar", 3: "baz"}).Should(ConsistOf("foo", "bar", "baz")) - Ω(map[int]string{1: "foo", 2: "bar", 3: "baz"}).Should(ConsistOf("baz", "bar", "foo")) - Ω(map[int]string{1: "foo", 2: "bar", 3: "baz"}).ShouldNot(ConsistOf("baz", "bar", "foo", "foo")) - Ω(map[int]string{1: "foo", 2: "bar", 3: "baz"}).ShouldNot(ConsistOf("baz", "foo")) - }) - - }) - - Context("with anything else", func() { - It("should error", func() { - failures := InterceptGomegaFailures(func() { - Ω("foo").Should(ConsistOf("f", "o", "o")) - }) - - Ω(failures).Should(HaveLen(1)) - }) - }) - - Context("when passed matchers", func() { - It("should pass if the matchers pass", func() { - Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", MatchRegexp("^ba"), "baz")) - Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("foo", MatchRegexp("^ba"))) - Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("foo", MatchRegexp("^ba"), MatchRegexp("foo"))) - Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", MatchRegexp("^ba"), MatchRegexp("^ba"))) - Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("foo", MatchRegexp("^ba"), MatchRegexp("turducken"))) - }) - - It("should not depend on the order of the matchers", func() { - Ω([][]int{[]int{1, 2}, []int{2}}).Should(ConsistOf(ContainElement(1), ContainElement(2))) - Ω([][]int{[]int{1, 2}, []int{2}}).Should(ConsistOf(ContainElement(2), ContainElement(1))) - }) - - Context("when a matcher errors", func() { - It("should soldier on", func() { - Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf(BeFalse(), "foo", "bar")) - Ω([]interface{}{"foo", "bar", false}).Should(ConsistOf(BeFalse(), ContainSubstring("foo"), "bar")) - }) - }) - }) - - Context("when passed exactly one argument, and that argument is a slice", func() { - It("should match against the elements of that argument", func() { - Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf([]string{"foo", "bar", "baz"})) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/contain_element_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/contain_element_matcher_test.go deleted file mode 100644 index 38ee518f..00000000 --- a/vendor/github.com/onsi/gomega/matchers/contain_element_matcher_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("ContainElement", func() { - Context("when passed a supported type", func() { - Context("and expecting a non-matcher", func() { - It("should do the right thing", func() { - Ω([2]int{1, 2}).Should(ContainElement(2)) - Ω([2]int{1, 2}).ShouldNot(ContainElement(3)) - - Ω([]int{1, 2}).Should(ContainElement(2)) - Ω([]int{1, 2}).ShouldNot(ContainElement(3)) - - Ω(map[string]int{"foo": 1, "bar": 2}).Should(ContainElement(2)) - Ω(map[int]int{3: 1, 4: 2}).ShouldNot(ContainElement(3)) - - arr := make([]myCustomType, 2) - arr[0] = myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}} - arr[1] = myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "c"}} - Ω(arr).Should(ContainElement(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}})) - Ω(arr).ShouldNot(ContainElement(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"b", "c"}})) - }) - }) - - Context("and expecting a matcher", func() { - It("should pass each element through the matcher", func() { - Ω([]int{1, 2, 3}).Should(ContainElement(BeNumerically(">=", 3))) - Ω([]int{1, 2, 3}).ShouldNot(ContainElement(BeNumerically(">", 3))) - Ω(map[string]int{"foo": 1, "bar": 2}).Should(ContainElement(BeNumerically(">=", 2))) - Ω(map[string]int{"foo": 1, "bar": 2}).ShouldNot(ContainElement(BeNumerically(">", 2))) - }) - - It("should power through even if the matcher ever fails", func() { - Ω([]interface{}{1, 2, "3", 4}).Should(ContainElement(BeNumerically(">=", 3))) - }) - - It("should fail if the matcher fails", func() { - actual := []interface{}{1, 2, "3", "4"} - success, err := (&ContainElementMatcher{Element: BeNumerically(">=", 3)}).Match(actual) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - }) - - Context("when passed a correctly typed nil", func() { - It("should operate succesfully on the passed in value", func() { - var nilSlice []int - Ω(nilSlice).ShouldNot(ContainElement(1)) - - var nilMap map[int]string - Ω(nilMap).ShouldNot(ContainElement("foo")) - }) - }) - - Context("when passed an unsupported type", func() { - It("should error", func() { - success, err := (&ContainElementMatcher{Element: 0}).Match(0) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&ContainElementMatcher{Element: 0}).Match("abc") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&ContainElementMatcher{Element: 0}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher_test.go deleted file mode 100644 index 6935168e..00000000 --- a/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("ContainSubstringMatcher", func() { - Context("when actual is a string", func() { - It("should match against the string", func() { - Ω("Marvelous").Should(ContainSubstring("rve")) - Ω("Marvelous").ShouldNot(ContainSubstring("boo")) - }) - }) - - Context("when the matcher is called with multiple arguments", func() { - It("should pass the string and arguments to sprintf", func() { - Ω("Marvelous3").Should(ContainSubstring("velous%d", 3)) - }) - }) - - Context("when actual is a stringer", func() { - It("should call the stringer and match agains the returned string", func() { - Ω(&myStringer{a: "Abc3"}).Should(ContainSubstring("bc3")) - }) - }) - - Context("when actual is neither a string nor a stringer", func() { - It("should error", func() { - success, err := (&ContainSubstringMatcher{Substr: "2"}).Match(2) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/equal_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/equal_matcher_test.go deleted file mode 100644 index ef0d137d..00000000 --- a/vendor/github.com/onsi/gomega/matchers/equal_matcher_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package matchers_test - -import ( - "errors" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("Equal", func() { - Context("when asserting that nil equals nil", func() { - It("should error", func() { - success, err := (&EqualMatcher{Expected: nil}).Match(nil) - - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("When asserting equality between objects", func() { - It("should do the right thing", func() { - Ω(5).Should(Equal(5)) - Ω(5.0).Should(Equal(5.0)) - - Ω(5).ShouldNot(Equal("5")) - Ω(5).ShouldNot(Equal(5.0)) - Ω(5).ShouldNot(Equal(3)) - - Ω("5").Should(Equal("5")) - Ω([]int{1, 2}).Should(Equal([]int{1, 2})) - Ω([]int{1, 2}).ShouldNot(Equal([]int{2, 1})) - Ω(map[string]string{"a": "b", "c": "d"}).Should(Equal(map[string]string{"a": "b", "c": "d"})) - Ω(map[string]string{"a": "b", "c": "d"}).ShouldNot(Equal(map[string]string{"a": "b", "c": "e"})) - Ω(errors.New("foo")).Should(Equal(errors.New("foo"))) - Ω(errors.New("foo")).ShouldNot(Equal(errors.New("bar"))) - - Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).Should(Equal(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}})) - Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).ShouldNot(Equal(myCustomType{s: "bar", n: 3, f: 2.0, arr: []string{"a", "b"}})) - Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).ShouldNot(Equal(myCustomType{s: "foo", n: 2, f: 2.0, arr: []string{"a", "b"}})) - Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).ShouldNot(Equal(myCustomType{s: "foo", n: 3, f: 3.0, arr: []string{"a", "b"}})) - Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).ShouldNot(Equal(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b", "c"}})) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/have_key_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/have_key_matcher_test.go deleted file mode 100644 index c663e302..00000000 --- a/vendor/github.com/onsi/gomega/matchers/have_key_matcher_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("HaveKey", func() { - var ( - stringKeys map[string]int - intKeys map[int]string - objKeys map[*myCustomType]string - - customA *myCustomType - customB *myCustomType - ) - BeforeEach(func() { - stringKeys = map[string]int{"foo": 2, "bar": 3} - intKeys = map[int]string{2: "foo", 3: "bar"} - - customA = &myCustomType{s: "a", n: 2, f: 2.3, arr: []string{"ice", "cream"}} - customB = &myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"cake"}} - objKeys = map[*myCustomType]string{customA: "aardvark", customB: "kangaroo"} - }) - - Context("when passed a map", func() { - It("should do the right thing", func() { - Ω(stringKeys).Should(HaveKey("foo")) - Ω(stringKeys).ShouldNot(HaveKey("baz")) - - Ω(intKeys).Should(HaveKey(2)) - Ω(intKeys).ShouldNot(HaveKey(4)) - - Ω(objKeys).Should(HaveKey(customA)) - Ω(objKeys).Should(HaveKey(&myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"cake"}})) - Ω(objKeys).ShouldNot(HaveKey(&myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"apple", "pie"}})) - }) - }) - - Context("when passed a correctly typed nil", func() { - It("should operate succesfully on the passed in value", func() { - var nilMap map[int]string - Ω(nilMap).ShouldNot(HaveKey("foo")) - }) - }) - - Context("when the passed in key is actually a matcher", func() { - It("should pass each element through the matcher", func() { - Ω(stringKeys).Should(HaveKey(ContainSubstring("oo"))) - Ω(stringKeys).ShouldNot(HaveKey(ContainSubstring("foobar"))) - }) - - It("should fail if the matcher ever fails", func() { - actual := map[int]string{1: "a", 3: "b", 2: "c"} - success, err := (&HaveKeyMatcher{Key: ContainSubstring("ar")}).Match(actual) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed something that is not a map", func() { - It("should error", func() { - success, err := (&HaveKeyMatcher{Key: "foo"}).Match([]string{"foo"}) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&HaveKeyMatcher{Key: "foo"}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher_test.go deleted file mode 100644 index 06a2242a..00000000 --- a/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher_test.go +++ /dev/null @@ -1,82 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("HaveKeyWithValue", func() { - var ( - stringKeys map[string]int - intKeys map[int]string - objKeys map[*myCustomType]*myCustomType - - customA *myCustomType - customB *myCustomType - ) - BeforeEach(func() { - stringKeys = map[string]int{"foo": 2, "bar": 3} - intKeys = map[int]string{2: "foo", 3: "bar"} - - customA = &myCustomType{s: "a", n: 2, f: 2.3, arr: []string{"ice", "cream"}} - customB = &myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"cake"}} - objKeys = map[*myCustomType]*myCustomType{customA: customA, customB: customA} - }) - - Context("when passed a map", func() { - It("should do the right thing", func() { - Ω(stringKeys).Should(HaveKeyWithValue("foo", 2)) - Ω(stringKeys).ShouldNot(HaveKeyWithValue("foo", 1)) - Ω(stringKeys).ShouldNot(HaveKeyWithValue("baz", 2)) - Ω(stringKeys).ShouldNot(HaveKeyWithValue("baz", 1)) - - Ω(intKeys).Should(HaveKeyWithValue(2, "foo")) - Ω(intKeys).ShouldNot(HaveKeyWithValue(4, "foo")) - Ω(intKeys).ShouldNot(HaveKeyWithValue(2, "baz")) - - Ω(objKeys).Should(HaveKeyWithValue(customA, customA)) - Ω(objKeys).Should(HaveKeyWithValue(&myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"cake"}}, &myCustomType{s: "a", n: 2, f: 2.3, arr: []string{"ice", "cream"}})) - Ω(objKeys).ShouldNot(HaveKeyWithValue(&myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"apple", "pie"}}, customA)) - }) - }) - - Context("when passed a correctly typed nil", func() { - It("should operate succesfully on the passed in value", func() { - var nilMap map[int]string - Ω(nilMap).ShouldNot(HaveKeyWithValue("foo", "bar")) - }) - }) - - Context("when the passed in key or value is actually a matcher", func() { - It("should pass each element through the matcher", func() { - Ω(stringKeys).Should(HaveKeyWithValue(ContainSubstring("oo"), 2)) - Ω(intKeys).Should(HaveKeyWithValue(2, ContainSubstring("oo"))) - Ω(stringKeys).ShouldNot(HaveKeyWithValue(ContainSubstring("foobar"), 2)) - }) - - It("should fail if the matcher ever fails", func() { - actual := map[int]string{1: "a", 3: "b", 2: "c"} - success, err := (&HaveKeyWithValueMatcher{Key: ContainSubstring("ar"), Value: 2}).Match(actual) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - otherActual := map[string]int{"a": 1, "b": 2, "c": 3} - success, err = (&HaveKeyWithValueMatcher{Key: "a", Value: ContainSubstring("1")}).Match(otherActual) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed something that is not a map", func() { - It("should error", func() { - success, err := (&HaveKeyWithValueMatcher{Key: "foo", Value: "bar"}).Match([]string{"foo"}) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&HaveKeyWithValueMatcher{Key: "foo", Value: "bar"}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/have_len_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/have_len_matcher_test.go deleted file mode 100644 index 1e6aa69d..00000000 --- a/vendor/github.com/onsi/gomega/matchers/have_len_matcher_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("HaveLen", func() { - Context("when passed a supported type", func() { - It("should do the right thing", func() { - Ω("").Should(HaveLen(0)) - Ω("AA").Should(HaveLen(2)) - - Ω([0]int{}).Should(HaveLen(0)) - Ω([2]int{1, 2}).Should(HaveLen(2)) - - Ω([]int{}).Should(HaveLen(0)) - Ω([]int{1, 2, 3}).Should(HaveLen(3)) - - Ω(map[string]int{}).Should(HaveLen(0)) - Ω(map[string]int{"a": 1, "b": 2, "c": 3, "d": 4}).Should(HaveLen(4)) - - c := make(chan bool, 3) - Ω(c).Should(HaveLen(0)) - c <- true - c <- true - Ω(c).Should(HaveLen(2)) - }) - }) - - Context("when passed a correctly typed nil", func() { - It("should operate succesfully on the passed in value", func() { - var nilSlice []int - Ω(nilSlice).Should(HaveLen(0)) - - var nilMap map[int]string - Ω(nilMap).Should(HaveLen(0)) - }) - }) - - Context("when passed an unsupported type", func() { - It("should error", func() { - success, err := (&HaveLenMatcher{Count: 0}).Match(0) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&HaveLenMatcher{Count: 0}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/have_occurred_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/have_occurred_matcher_test.go deleted file mode 100644 index 0fc35a98..00000000 --- a/vendor/github.com/onsi/gomega/matchers/have_occurred_matcher_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package matchers_test - -import ( - "errors" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -type CustomErr struct { - msg string -} - -func (e *CustomErr) Error() string { - return e.msg -} - -var _ = Describe("HaveOccurred", func() { - It("should succeed if matching an error", func() { - Ω(errors.New("Foo")).Should(HaveOccurred()) - }) - - It("should not succeed with nil", func() { - Ω(nil).ShouldNot(HaveOccurred()) - }) - - It("should only support errors and nil", func() { - success, err := (&HaveOccurredMatcher{}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&HaveOccurredMatcher{}).Match("") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - - It("should succeed with pointer types that conform to error interface", func() { - err := &CustomErr{"ohai"} - Ω(err).Should(HaveOccurred()) - }) - - It("should not succeed with nil pointers to types that conform to error interface", func() { - var err *CustomErr = nil - Ω(err).ShouldNot(HaveOccurred()) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher_test.go deleted file mode 100644 index bec3f975..00000000 --- a/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("HavePrefixMatcher", func() { - Context("when actual is a string", func() { - It("should match a string prefix", func() { - Ω("Ab").Should(HavePrefix("A")) - Ω("A").ShouldNot(HavePrefix("Ab")) - }) - }) - - Context("when the matcher is called with multiple arguments", func() { - It("should pass the string and arguments to sprintf", func() { - Ω("C3PO").Should(HavePrefix("C%dP", 3)) - }) - }) - - Context("when actual is a stringer", func() { - It("should call the stringer and match against the returned string", func() { - Ω(&myStringer{a: "Ab"}).Should(HavePrefix("A")) - }) - }) - - Context("when actual is neither a string nor a stringer", func() { - It("should error", func() { - success, err := (&HavePrefixMatcher{Prefix: "2"}).Match(2) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher_test.go deleted file mode 100644 index 72e8975b..00000000 --- a/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("HaveSuffixMatcher", func() { - Context("when actual is a string", func() { - It("should match a string suffix", func() { - Ω("Ab").Should(HaveSuffix("b")) - Ω("A").ShouldNot(HaveSuffix("Ab")) - }) - }) - - Context("when the matcher is called with multiple arguments", func() { - It("should pass the string and arguments to sprintf", func() { - Ω("C3PO").Should(HaveSuffix("%dPO", 3)) - }) - }) - - Context("when actual is a stringer", func() { - It("should call the stringer and match against the returned string", func() { - Ω(&myStringer{a: "Ab"}).Should(HaveSuffix("b")) - }) - }) - - Context("when actual is neither a string nor a stringer", func() { - It("should error", func() { - success, err := (&HaveSuffixMatcher{Suffix: "2"}).Match(2) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/match_error_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/match_error_matcher_test.go deleted file mode 100644 index 338b5129..00000000 --- a/vendor/github.com/onsi/gomega/matchers/match_error_matcher_test.go +++ /dev/null @@ -1,93 +0,0 @@ -package matchers_test - -import ( - "errors" - "fmt" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -type CustomError struct { -} - -func (c CustomError) Error() string { - return "an error" -} - -var _ = Describe("MatchErrorMatcher", func() { - Context("When asserting against an error", func() { - It("should succeed when matching with an error", func() { - err := errors.New("an error") - fmtErr := fmt.Errorf("an error") - customErr := CustomError{} - - Ω(err).Should(MatchError(errors.New("an error"))) - Ω(err).ShouldNot(MatchError(errors.New("another error"))) - - Ω(fmtErr).Should(MatchError(errors.New("an error"))) - Ω(customErr).Should(MatchError(CustomError{})) - }) - - It("should succeed when matching with a string", func() { - err := errors.New("an error") - fmtErr := fmt.Errorf("an error") - customErr := CustomError{} - - Ω(err).Should(MatchError("an error")) - Ω(err).ShouldNot(MatchError("another error")) - - Ω(fmtErr).Should(MatchError("an error")) - Ω(customErr).Should(MatchError("an error")) - }) - - Context("when passed a matcher", func() { - It("should pass if the matcher passes against the error string", func() { - err := errors.New("error 123 abc") - - Ω(err).Should(MatchError(MatchRegexp(`\d{3}`))) - }) - - It("should fail if the matcher fails against the error string", func() { - err := errors.New("no digits") - Ω(err).ShouldNot(MatchError(MatchRegexp(`\d`))) - }) - }) - - It("should fail when passed anything else", func() { - actualErr := errors.New("an error") - _, err := (&MatchErrorMatcher{ - Expected: []byte("an error"), - }).Match(actualErr) - Ω(err).Should(HaveOccurred()) - - _, err = (&MatchErrorMatcher{ - Expected: 3, - }).Match(actualErr) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed nil", func() { - It("should fail", func() { - _, err := (&MatchErrorMatcher{ - Expected: "an error", - }).Match(nil) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed a non-error", func() { - It("should fail", func() { - _, err := (&MatchErrorMatcher{ - Expected: "an error", - }).Match("an error") - Ω(err).Should(HaveOccurred()) - - _, err = (&MatchErrorMatcher{ - Expected: "an error", - }).Match(3) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/match_json_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/match_json_matcher_test.go deleted file mode 100644 index c1924baa..00000000 --- a/vendor/github.com/onsi/gomega/matchers/match_json_matcher_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("MatchJSONMatcher", func() { - Context("When passed stringifiables", func() { - It("should succeed if the JSON matches", func() { - Ω("{}").Should(MatchJSON("{}")) - Ω(`{"a":1}`).Should(MatchJSON(`{"a":1}`)) - Ω(`{ - "a":1 - }`).Should(MatchJSON(`{"a":1}`)) - Ω(`{"a":1, "b":2}`).Should(MatchJSON(`{"b":2, "a":1}`)) - Ω(`{"a":1}`).ShouldNot(MatchJSON(`{"b":2, "a":1}`)) - }) - - It("should work with byte arrays", func() { - Ω([]byte("{}")).Should(MatchJSON([]byte("{}"))) - Ω("{}").Should(MatchJSON([]byte("{}"))) - Ω([]byte("{}")).Should(MatchJSON("{}")) - }) - }) - - Context("when either side is not valid JSON", func() { - It("should error", func() { - success, err := (&MatchJSONMatcher{JSONToMatch: `oops`}).Match(`{}`) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&MatchJSONMatcher{JSONToMatch: `{}`}).Match(`oops`) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when either side is neither a string nor a stringer", func() { - It("should error", func() { - success, err := (&MatchJSONMatcher{JSONToMatch: "{}"}).Match(2) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&MatchJSONMatcher{JSONToMatch: 2}).Match("{}") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&MatchJSONMatcher{JSONToMatch: nil}).Match("{}") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&MatchJSONMatcher{JSONToMatch: 2}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher_test.go deleted file mode 100644 index bb521cce..00000000 --- a/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("MatchRegexp", func() { - Context("when actual is a string", func() { - It("should match against the string", func() { - Ω(" a2!bla").Should(MatchRegexp(`\d!`)) - Ω(" a2!bla").ShouldNot(MatchRegexp(`[A-Z]`)) - }) - }) - - Context("when actual is a stringer", func() { - It("should call the stringer and match agains the returned string", func() { - Ω(&myStringer{a: "Abc3"}).Should(MatchRegexp(`[A-Z][a-z]+\d`)) - }) - }) - - Context("when the matcher is called with multiple arguments", func() { - It("should pass the string and arguments to sprintf", func() { - Ω(" a23!bla").Should(MatchRegexp(`\d%d!`, 3)) - }) - }) - - Context("when actual is neither a string nor a stringer", func() { - It("should error", func() { - success, err := (&MatchRegexpMatcher{Regexp: `\d`}).Match(2) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when the passed in regexp fails to compile", func() { - It("should error", func() { - success, err := (&MatchRegexpMatcher{Regexp: "("}).Match("Foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/matcher_tests_suite_test.go b/vendor/github.com/onsi/gomega/matchers/matcher_tests_suite_test.go deleted file mode 100644 index 4bc6d9d0..00000000 --- a/vendor/github.com/onsi/gomega/matchers/matcher_tests_suite_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package matchers_test - -import ( - "testing" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type myStringer struct { - a string -} - -func (s *myStringer) String() string { - return s.a -} - -type StringAlias string - -type myCustomType struct { - s string - n int - f float32 - arr []string -} - -func Test(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Gomega") -} diff --git a/vendor/github.com/onsi/gomega/matchers/panic_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/panic_matcher_test.go deleted file mode 100644 index 17f3935e..00000000 --- a/vendor/github.com/onsi/gomega/matchers/panic_matcher_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("Panic", func() { - Context("when passed something that's not a function that takes zero arguments and returns nothing", func() { - It("should error", func() { - success, err := (&PanicMatcher{}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&PanicMatcher{}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&PanicMatcher{}).Match(func(foo string) {}) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&PanicMatcher{}).Match(func() string { return "bar" }) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed a function of the correct type", func() { - It("should call the function and pass if the function panics", func() { - Ω(func() { panic("ack!") }).Should(Panic()) - Ω(func() {}).ShouldNot(Panic()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/receive_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/receive_matcher_test.go deleted file mode 100644 index 938c078e..00000000 --- a/vendor/github.com/onsi/gomega/matchers/receive_matcher_test.go +++ /dev/null @@ -1,280 +0,0 @@ -package matchers_test - -import ( - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -type kungFuActor interface { - DrunkenMaster() bool -} - -type jackie struct { - name string -} - -func (j *jackie) DrunkenMaster() bool { - return true -} - -var _ = Describe("ReceiveMatcher", func() { - Context("with no argument", func() { - Context("for a buffered channel", func() { - It("should succeed", func() { - channel := make(chan bool, 1) - - Ω(channel).ShouldNot(Receive()) - - channel <- true - - Ω(channel).Should(Receive()) - }) - }) - - Context("for an unbuffered channel", func() { - It("should succeed (eventually)", func() { - channel := make(chan bool) - - Ω(channel).ShouldNot(Receive()) - - go func() { - time.Sleep(10 * time.Millisecond) - channel <- true - }() - - Eventually(channel).Should(Receive()) - }) - }) - }) - - Context("with a pointer argument", func() { - Context("of the correct type", func() { - It("should write the value received on the channel to the pointer", func() { - channel := make(chan int, 1) - - var value int - - Ω(channel).ShouldNot(Receive(&value)) - Ω(value).Should(BeZero()) - - channel <- 17 - - Ω(channel).Should(Receive(&value)) - Ω(value).Should(Equal(17)) - }) - }) - - Context("to various types of objects", func() { - It("should work", func() { - //channels of strings - stringChan := make(chan string, 1) - stringChan <- "foo" - - var s string - Ω(stringChan).Should(Receive(&s)) - Ω(s).Should(Equal("foo")) - - //channels of slices - sliceChan := make(chan []bool, 1) - sliceChan <- []bool{true, true, false} - - var sl []bool - Ω(sliceChan).Should(Receive(&sl)) - Ω(sl).Should(Equal([]bool{true, true, false})) - - //channels of channels - chanChan := make(chan chan bool, 1) - c := make(chan bool) - chanChan <- c - - var receivedC chan bool - Ω(chanChan).Should(Receive(&receivedC)) - Ω(receivedC).Should(Equal(c)) - - //channels of interfaces - jackieChan := make(chan kungFuActor, 1) - aJackie := &jackie{name: "Jackie Chan"} - jackieChan <- aJackie - - var theJackie kungFuActor - Ω(jackieChan).Should(Receive(&theJackie)) - Ω(theJackie).Should(Equal(aJackie)) - }) - }) - - Context("of the wrong type", func() { - It("should error", func() { - channel := make(chan int) - var incorrectType bool - - success, err := (&ReceiveMatcher{Arg: &incorrectType}).Match(channel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - var notAPointer int - success, err = (&ReceiveMatcher{Arg: notAPointer}).Match(channel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - }) - - Context("with a matcher", func() { - It("should defer to the underlying matcher", func() { - intChannel := make(chan int, 1) - intChannel <- 3 - Ω(intChannel).Should(Receive(Equal(3))) - - intChannel <- 2 - Ω(intChannel).ShouldNot(Receive(Equal(3))) - - stringChannel := make(chan []string, 1) - stringChannel <- []string{"foo", "bar", "baz"} - Ω(stringChannel).Should(Receive(ContainElement(ContainSubstring("fo")))) - - stringChannel <- []string{"foo", "bar", "baz"} - Ω(stringChannel).ShouldNot(Receive(ContainElement(ContainSubstring("archipelago")))) - }) - - It("should defer to the underlying matcher for the message", func() { - matcher := Receive(Equal(3)) - channel := make(chan int, 1) - channel <- 2 - matcher.Match(channel) - Ω(matcher.FailureMessage(channel)).Should(MatchRegexp(`Expected\s+: 2\s+to equal\s+: 3`)) - - channel <- 3 - matcher.Match(channel) - Ω(matcher.NegatedFailureMessage(channel)).Should(MatchRegexp(`Expected\s+: 3\s+not to equal\s+: 3`)) - }) - - It("should work just fine with Eventually", func() { - stringChannel := make(chan string) - - go func() { - time.Sleep(5 * time.Millisecond) - stringChannel <- "A" - time.Sleep(5 * time.Millisecond) - stringChannel <- "B" - }() - - Eventually(stringChannel).Should(Receive(Equal("B"))) - }) - - Context("if the matcher errors", func() { - It("should error", func() { - channel := make(chan int, 1) - channel <- 3 - success, err := (&ReceiveMatcher{Arg: ContainSubstring("three")}).Match(channel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("if nothing is received", func() { - It("should fail", func() { - channel := make(chan int, 1) - success, err := (&ReceiveMatcher{Arg: Equal(1)}).Match(channel) - Ω(success).Should(BeFalse()) - Ω(err).ShouldNot(HaveOccurred()) - }) - }) - }) - - Context("When actual is a *closed* channel", func() { - Context("for a buffered channel", func() { - It("should work until it hits the end of the buffer", func() { - channel := make(chan bool, 1) - channel <- true - - close(channel) - - Ω(channel).Should(Receive()) - Ω(channel).ShouldNot(Receive()) - }) - }) - - Context("for an unbuffered channel", func() { - It("should always fail", func() { - channel := make(chan bool) - close(channel) - - Ω(channel).ShouldNot(Receive()) - }) - }) - }) - - Context("When actual is a send-only channel", func() { - It("should error", func() { - channel := make(chan bool) - - var writerChannel chan<- bool - writerChannel = channel - - success, err := (&ReceiveMatcher{}).Match(writerChannel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when acutal is a non-channel", func() { - It("should error", func() { - var nilChannel chan bool - - success, err := (&ReceiveMatcher{}).Match(nilChannel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&ReceiveMatcher{}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&ReceiveMatcher{}).Match(3) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Describe("when used with eventually and a custom matcher", func() { - It("should return the matcher's error when a failing value is received on the channel, instead of the must receive something failure", func() { - failures := InterceptGomegaFailures(func() { - c := make(chan string, 0) - Eventually(c, 0.01).Should(Receive(Equal("hello"))) - }) - Ω(failures[0]).Should(ContainSubstring("When passed a matcher, ReceiveMatcher's channel *must* receive something.")) - - failures = InterceptGomegaFailures(func() { - c := make(chan string, 1) - c <- "hi" - Eventually(c, 0.01).Should(Receive(Equal("hello"))) - }) - Ω(failures[0]).Should(ContainSubstring(": hello")) - }) - }) - - Describe("Bailing early", func() { - It("should bail early when passed a closed channel", func() { - c := make(chan bool) - close(c) - - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(c).Should(Receive()) - }) - Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) - Ω(failures).Should(HaveLen(1)) - }) - - It("should bail early when passed a non-channel", func() { - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(3).Should(Receive()) - }) - Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) - Ω(failures).Should(HaveLen(1)) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/succeed_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/succeed_matcher_test.go deleted file mode 100644 index 3562e704..00000000 --- a/vendor/github.com/onsi/gomega/matchers/succeed_matcher_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package matchers_test - -import ( - "errors" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -func Erroring() error { - return errors.New("bam") -} - -func NotErroring() error { - return nil -} - -type AnyType struct{} - -func Invalid() *AnyType { - return nil -} - -var _ = Describe("Succeed", func() { - It("should succeed if the function succeeds", func() { - Ω(NotErroring()).Should(Succeed()) - }) - - It("should succeed (in the negated) if the function errored", func() { - Ω(Erroring()).ShouldNot(Succeed()) - }) - - It("should not if passed a non-error", func() { - success, err := (&SucceedMatcher{}).Match(Invalid()) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) -}) diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/create_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/create_handler.go deleted file mode 100644 index 312cbedc..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/create_handler.go +++ /dev/null @@ -1,51 +0,0 @@ -package clients - -import ( - "encoding/json" - "net/http" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/documents" - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type createHandler struct { - clients *domain.Clients - tokens *domain.Tokens -} - -func (h createHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - token := req.Header.Get("Authorization") - token = strings.TrimPrefix(token, "Bearer ") - token = strings.TrimPrefix(token, "bearer ") - if len(token) == 0 { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - if ok := h.tokens.Validate(token, domain.Token{ - Authorities: []string{"clients.write"}, - Audiences: []string{"clients"}, - }); !ok { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - - var document documents.CreateUpdateClientRequest - err := json.NewDecoder(req.Body).Decode(&document) - if err != nil { - common.HTMLError(w, http.StatusBadRequest, "The request sent by the client was syntactically incorrect.", "") - return - } - - client := domain.NewClientFromDocument(document) - if err := client.Validate(); err != nil { - common.JSONError(w, http.StatusBadRequest, err.Error(), "invalid_client") - return - } - - h.clients.Add(client) - - w.WriteHeader(http.StatusCreated) - json.NewEncoder(w).Encode(client.ToDocument()) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/create_handler_test.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/create_handler_test.go deleted file mode 100644 index 470a08b8..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/create_handler_test.go +++ /dev/null @@ -1,147 +0,0 @@ -package clients_test - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/server/clients" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("createHandler", func() { - var ( - router http.Handler - recorder *httptest.ResponseRecorder - request *http.Request - clientsCollection *domain.Clients - tokensCollection *domain.Tokens - ) - - BeforeEach(func() { - clientsCollection = domain.NewClients() - tokensCollection = NewTokens() - router = clients.NewRouter(clientsCollection, tokensCollection) - recorder = httptest.NewRecorder() - - requestBody, err := json.Marshal(map[string]interface{}{ - "client_id": "some-client", - "client_secret": "some-client-secret", - "name": "banana", - "scope": []string{"some.scope"}, - "resource_ids": []string{"resource"}, - "authorities": []string{"cloud_controller.read"}, - "authorized_grant_types": []string{"client_credentials"}, - "access_token_validity": 43200, - }) - Expect(err).NotTo(HaveOccurred()) - - request, err = http.NewRequest("POST", "/oauth/clients", bytes.NewBuffer(requestBody)) - Expect(err).NotTo(HaveOccurred()) - - authorization := tokensCollection.Encrypt(domain.Token{ - ClientID: "the-client", - Authorities: []string{"clients.write"}, - Audiences: []string{"clients"}, - }) - request.Header.Set("Authorization", fmt.Sprintf("bearer %s", authorization)) - }) - - It("creates a client", func() { - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusCreated)) - Expect(recorder.Body).To(MatchJSON(`{ - "client_id": "some-client", - "name": "banana", - "scope": ["some.scope"], - "resource_ids": ["resource"], - "authorities": ["cloud_controller.read"], - "authorized_grant_types": ["client_credentials"], - "access_token_validity": 43200, - "redirect_uri": null, - "autoapprove": [] - }`)) - }) - - It("stores the client in the collection", func() { - router.ServeHTTP(recorder, request) - client, ok := clientsCollection.Get("some-client") - Expect(ok).To(BeTrue()) - Expect(client).To(Equal(domain.Client{ - ID: "some-client", - Secret: "some-client-secret", - Name: "banana", - Scope: []string{"some.scope"}, - ResourceIDs: []string{"resource"}, - Authorities: []string{"cloud_controller.read"}, - AuthorizedGrantTypes: []string{"client_credentials"}, - AccessTokenValidity: 43200, - RedirectURI: nil, - Autoapprove: nil, - })) - }) - - It("requires an authorization token", func() { - request.Header.Del("Authorization") - - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusUnauthorized)) - Expect(recorder.Body).To(MatchJSON(`{ - "error": "unauthorized", - "error_description":"Full authentication is required to access this resource" - }`)) - }) - - It("requires an authorization token with the correct authorities", func() { - authorization := tokensCollection.Encrypt(domain.Token{ - ClientID: "the-client", - Authorities: []string{"banana.write"}, - Audiences: []string{"banana"}, - }) - request.Header.Set("Authorization", fmt.Sprintf("bearer %s", authorization)) - - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusUnauthorized)) - Expect(recorder.Body).To(MatchJSON(`{ - "error": "unauthorized", - "error_description":"Full authentication is required to access this resource" - }`)) - }) - - It("validates the client create request", func() { - requestBody, err := json.Marshal(map[string]interface{}{ - "client_id": "some-client", - "client_secret": "some-client-secret", - "name": "banana", - "scope": []string{"some.scope"}, - "resource_ids": []string{"resource"}, - "authorities": []string{"cloud_controller.read"}, - "authorized_grant_types": []string{"bananas"}, - "access_token_validity": 43200, - }) - Expect(err).NotTo(HaveOccurred()) - request.Body = ioutil.NopCloser(bytes.NewBuffer(requestBody)) - - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusBadRequest)) - Expect(recorder.Body).To(MatchJSON(`{ - "error_description": "bananas is not an allowed grant type. Must be one of: [implicit refresh_token authorization_code client_credentials password]", - "error": "invalid_client" - }`)) - }) - - It("returns an error response when the request cannot be unmarshalled", func() { - request.Body = ioutil.NopCloser(strings.NewReader("%%%")) - - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusBadRequest)) - Expect(recorder.Body).To(ContainSubstring("The request sent by the client was syntactically incorrect.")) - }) -}) diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/delete_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/delete_handler.go deleted file mode 100644 index 3cafe101..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/delete_handler.go +++ /dev/null @@ -1,39 +0,0 @@ -package clients - -import ( - "net/http" - "regexp" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type deleteHandler struct { - clients *domain.Clients - tokens *domain.Tokens -} - -func (h deleteHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - token := req.Header.Get("Authorization") - token = strings.TrimPrefix(token, "Bearer ") - token = strings.TrimPrefix(token, "bearer ") - - if len(token) == 0 { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - - if ok := h.tokens.Validate(token, domain.Token{ - Authorities: []string{"clients.write"}, - Audiences: []string{"clients"}, - }); !ok { - common.JSONError(w, http.StatusForbidden, "Invalid token does not contain resource id (clients)", "access_denied") - return - } - - matches := regexp.MustCompile(`/oauth/clients/(.*)$`).FindStringSubmatch(req.URL.Path) - id := matches[1] - - h.clients.Delete(id) // TODO: should return a 404 if the client does not exist -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/delete_handler_test.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/delete_handler_test.go deleted file mode 100644 index 6a2cb536..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/delete_handler_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package clients_test - -import ( - "fmt" - "net/http" - "net/http/httptest" - - "github.com/pivotal-cf-experimental/warrant/internal/server/clients" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("deleteHandler", func() { - var ( - router http.Handler - recorder *httptest.ResponseRecorder - request *http.Request - clientsCollection *domain.Clients - tokensCollection *domain.Tokens - ) - - BeforeEach(func() { - clientsCollection = domain.NewClients() - tokensCollection = NewTokens() - router = clients.NewRouter(clientsCollection, tokensCollection) - recorder = httptest.NewRecorder() - - clientsCollection.Add(domain.Client{ - ID: "some-client", - }) - - var err error - request, err = http.NewRequest("DELETE", "/oauth/clients/some-client", nil) - Expect(err).NotTo(HaveOccurred()) - - token := tokensCollection.Encrypt(domain.Token{ - Authorities: []string{"clients.write"}, - Audiences: []string{"clients"}, - }) - request.Header.Set("Authorization", fmt.Sprintf("bearer %s", token)) - }) - - It("deletes the client", func() { - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusOK)) - - _, ok := clientsCollection.Get("some-client") - Expect(ok).To(BeFalse()) - }) - - It("requires an Authorization header", func() { - request.Header.Del("Authorization") - - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusUnauthorized)) - Expect(recorder.Body).To(MatchJSON(`{ - "error": "unauthorized", - "error_description": "Full authentication is required to access this resource" - }`)) - }) - - It("requires a token with valid permissions", func() { - token := tokensCollection.Encrypt(domain.Token{ - Authorities: []string{"bananas.eat"}, - Audiences: []string{"bananas"}, - }) - request.Header.Set("Authorization", fmt.Sprintf("bearer %s", token)) - - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusForbidden)) - Expect(recorder.Body).To(MatchJSON(`{ - "error": "access_denied", - "error_description": "Invalid token does not contain resource id (clients)" - }`)) - }) -}) diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/get_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/get_handler.go deleted file mode 100644 index 76eac141..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/get_handler.go +++ /dev/null @@ -1,47 +0,0 @@ -package clients - -import ( - "encoding/json" - "fmt" - "net/http" - "regexp" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type getHandler struct { - clients *domain.Clients - tokens *domain.Tokens -} - -func (h getHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - token := req.Header.Get("Authorization") - token = strings.TrimPrefix(token, "Bearer ") - token = strings.TrimPrefix(token, "bearer ") - - if len(token) == 0 { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - if ok := h.tokens.Validate(token, domain.Token{ - Authorities: []string{"clients.read"}, - Audiences: []string{"clients"}, - }); !ok { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - - matches := regexp.MustCompile(`/oauth/clients/(.*)$`).FindStringSubmatch(req.URL.Path) - id := matches[1] - - client, ok := h.clients.Get(id) - if !ok { - common.NotFound(w, fmt.Sprintf("Client %s does not exist", id)) - return - } - - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(client.ToDocument()) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/get_handler_test.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/get_handler_test.go deleted file mode 100644 index 3cb3e2ac..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/get_handler_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package clients_test - -import ( - "fmt" - "net/http" - "net/http/httptest" - - "github.com/pivotal-cf-experimental/warrant/internal/server/clients" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("getHandler", func() { - var ( - router http.Handler - recorder *httptest.ResponseRecorder - request *http.Request - tokensCollection *domain.Tokens - ) - - BeforeEach(func() { - tokensCollection = NewTokens() - token := tokensCollection.Encrypt(domain.Token{ - ClientID: "my-client-id", - Authorities: []string{"clients.read"}, - Audiences: []string{"clients"}, - }) - - clientsCollection := domain.NewClients() - clientsCollection.Add(domain.Client{ - ID: "some-client-id", - Name: "banana", - Scope: []string{"some-scope"}, - ResourceIDs: []string{"some-resource-id"}, - Authorities: []string{"some-authority"}, - AuthorizedGrantTypes: []string{"some-grant-type"}, - AccessTokenValidity: 3600, - RedirectURI: []string{"https://example.com/sessions/create"}, - Autoapprove: []string{"some-approval"}, - }) - - var err error - request, err = http.NewRequest("GET", "/oauth/clients/some-client-id", nil) - Expect(err).NotTo(HaveOccurred()) - request.Header.Set("Authorization", fmt.Sprintf("bearer %s", token)) - - recorder = httptest.NewRecorder() - router = clients.NewRouter(clientsCollection, tokensCollection) - }) - - It("gets the requested client", func() { - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusOK)) - Expect(recorder.Body).To(MatchJSON(`{ - "client_id": "some-client-id", - "name": "banana", - "scope": ["some-scope"], - "resource_ids": ["some-resource-id"], - "authorities": ["some-authority"], - "authorized_grant_types": ["some-grant-type"], - "autoapprove": ["some-approval"], - "access_token_validity": 3600, - "redirect_uri": ["https://example.com/sessions/create"] - }`)) - }) - - It("returns a 404 if the client cannot be found", func() { - request.URL.Path = "/oauth/clients/missing-client" - - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusNotFound)) - Expect(recorder.Body).To(MatchJSON(`{ - "error_description": "Client missing-client does not exist", - "error": "scim_resource_not_found" - }`)) - }) - - It("requires a token", func() { - request.Header.Del("Authorization") - - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusUnauthorized)) - Expect(recorder.Body).To(MatchJSON(`{ - "error_description": "Full authentication is required to access this resource", - "error": "unauthorized" - }`)) - }) - - It("requires a token with the correct scopes", func() { - token := tokensCollection.Encrypt(domain.Token{ - ClientID: "my-client-id", - Authorities: []string{"bananas.read"}, - Audiences: []string{"bananas"}, - }) - request.Header.Set("Authorization", fmt.Sprintf("bearer %s", token)) - - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusUnauthorized)) - Expect(recorder.Body).To(MatchJSON(`{ - "error_description": "Full authentication is required to access this resource", - "error": "unauthorized" - }`)) - }) -}) diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/init_test.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/init_test.go deleted file mode 100644 index 8f728c68..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/init_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package clients_test - -import ( - "testing" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -func TestClientsSuite(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "internal/server/clients") -} - -func NewTokens() *domain.Tokens { - return domain.NewTokens(common.TestPublicKey, common.TestPrivateKey, []string{}) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/list_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/list_handler.go deleted file mode 100644 index 1e1f8ce0..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/list_handler.go +++ /dev/null @@ -1,105 +0,0 @@ -package clients - -import ( - "encoding/json" - "fmt" - "net/http" - "net/url" - "regexp" - "sort" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type listHandler struct { - clients *domain.Clients - tokens *domain.Tokens -} - -// TODO: check for client.admin scope -func (h listHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - token := req.Header.Get("Authorization") - token = strings.TrimPrefix(token, "Bearer ") - token = strings.TrimPrefix(token, "bearer ") - - if len(token) == 0 { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - if ok := h.tokens.Validate(token, domain.Token{ - Authorities: []string{"clients.read"}, - Audiences: []string{"clients"}, - }); !ok { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - - query, err := url.ParseQuery(req.URL.RawQuery) - if err != nil { - panic(err) - } - - list := domain.ClientsList{} - - filter := query.Get("filter") - if filter != "" { - matches := regexp.MustCompile(`(.*) (.*) ['"](.*)['"]$`).FindStringSubmatch(filter) - parameter := matches[1] - operator := matches[2] - value := matches[3] - - if !validParameter(parameter) { - common.JSONError(w, http.StatusBadRequest, fmt.Sprintf("Invalid filter expression: [%s]", filter), "scim") - return - } - - if !validOperator(operator) { - common.JSONError(w, http.StatusBadRequest, fmt.Sprintf("Invalid filter expression: [%s]", filter), "scim") - return - } - - client, found := h.clients.Get(value) - if found { - list = append(list, client) - } - } else { - list = append(list, h.clients.All()...) - } - - switch by := query.Get("sortBy"); by { - case "name": - sort.Sort(domain.ByName(list)) - default: - sort.Sort(domain.ByID(list)) - } - - response, err := json.Marshal(list.ToDocument()) - if err != nil { - panic(err) - } - - w.WriteHeader(http.StatusOK) - w.Write([]byte(response)) -} - -func validParameter(parameter string) bool { - for _, p := range []string{"id"} { - if strings.ToLower(parameter) == p { - return true - } - } - - return false -} - -func validOperator(operator string) bool { - for _, o := range []string{"eq"} { - if strings.ToLower(operator) == o { - return true - } - } - - return false -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/list_handler_test.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/list_handler_test.go deleted file mode 100644 index 8f647e53..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/list_handler_test.go +++ /dev/null @@ -1,113 +0,0 @@ -package clients_test - -import ( - "fmt" - "net/http" - "net/http/httptest" - - "github.com/pivotal-cf-experimental/warrant/internal/server/clients" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("listHandler", func() { - var ( - router http.Handler - recorder *httptest.ResponseRecorder - request *http.Request - tokensCollection *domain.Tokens - ) - - BeforeEach(func() { - tokensCollection = NewTokens() - token := tokensCollection.Encrypt(domain.Token{ - ClientID: "my-client-id", - Authorities: []string{"clients.read"}, - Audiences: []string{"clients"}, - }) - - clientsCollection := domain.NewClients() - clientsCollection.Add(domain.Client{ - ID: "some-client-id", - Name: "banana", - Scope: []string{"some-scope"}, - ResourceIDs: []string{"some-resource-id"}, - Authorities: []string{"some-authority"}, - AuthorizedGrantTypes: []string{"some-grant-type"}, - AccessTokenValidity: 3600, - RedirectURI: []string{"https://example.com/sessions/create"}, - Autoapprove: []string{"some-approval"}, - }) - - var err error - request, err = http.NewRequest("GET", "/oauth/clients", nil) - Expect(err).NotTo(HaveOccurred()) - request.Header.Set("Authorization", fmt.Sprintf("bearer %s", token)) - - recorder = httptest.NewRecorder() - router = clients.NewRouter(clientsCollection, tokensCollection) - }) - - It("lists the clients", func() { - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusOK)) - Expect(recorder.Body).To(MatchJSON(`{ - "schemas": [ - "urn:scim:schemas:core:1.0" - ], - "resources": [{ - "client_id": "admin", - "name": "admin", - "scope": [], - "resource_ids": ["clients", "password", "scim"], - "authorities": ["clients.read", "clients.write", "clients.secret", "password.write", "uaa.admin", "scim.read", "scim.write"], - "authorized_grant_types": ["client_credentials"], - "autoapprove": [], - "access_token_validity": 3600, - "redirect_uri": [] - },{ - "client_id": "some-client-id", - "name": "banana", - "scope": ["some-scope"], - "resource_ids": ["some-resource-id"], - "authorities": ["some-authority"], - "authorized_grant_types": ["some-grant-type"], - "autoapprove": ["some-approval"], - "access_token_validity": 3600, - "redirect_uri": ["https://example.com/sessions/create"] - }], - "startIndex": 1, - "itemsPerPage": 100, - "totalResults": 2 - }`)) - }) - - It("requires a token", func() { - request.Header.Del("Authorization") - - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusUnauthorized)) - Expect(recorder.Body).To(MatchJSON(`{ - "error_description": "Full authentication is required to access this resource", - "error": "unauthorized" - }`)) - }) - - It("requires a token with the correct scopes", func() { - token := tokensCollection.Encrypt(domain.Token{ - ClientID: "my-client-id", - Authorities: []string{"bananas.read"}, - Audiences: []string{"bananas"}, - }) - request.Header.Set("Authorization", fmt.Sprintf("bearer %s", token)) - - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusUnauthorized)) - Expect(recorder.Body).To(MatchJSON(`{ - "error_description": "Full authentication is required to access this resource", - "error": "unauthorized" - }`)) - }) -}) diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/router.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/router.go deleted file mode 100644 index 87237a05..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/router.go +++ /dev/null @@ -1,18 +0,0 @@ -package clients - -import ( - "github.com/gorilla/mux" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -func NewRouter(clients *domain.Clients, tokens *domain.Tokens) *mux.Router { - router := mux.NewRouter() - - router.Handle("/oauth/clients", createHandler{clients, tokens}).Methods("POST") - router.Handle("/oauth/clients", listHandler{clients, tokens}).Methods("GET") - router.Handle("/oauth/clients/{guid}", getHandler{clients, tokens}).Methods("GET") - router.Handle("/oauth/clients/{guid}", updateHandler{clients, tokens}).Methods("PUT") - router.Handle("/oauth/clients/{guid}", deleteHandler{clients, tokens}).Methods("DELETE") - - return router -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/update_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/update_handler.go deleted file mode 100644 index d148f25e..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/update_handler.go +++ /dev/null @@ -1,56 +0,0 @@ -package clients - -import ( - "encoding/json" - "net/http" - "regexp" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/documents" - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type updateHandler struct { - clients *domain.Clients - tokens *domain.Tokens -} - -func (h updateHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - token := req.Header.Get("Authorization") - token = strings.TrimPrefix(token, "Bearer ") - token = strings.TrimPrefix(token, "bearer ") - if len(token) == 0 { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - - if ok := h.tokens.Validate(token, domain.Token{ - Authorities: []string{"clients.write"}, - Audiences: []string{"clients"}, - }); !ok { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - - var document documents.CreateUpdateClientRequest - err := json.NewDecoder(req.Body).Decode(&document) - if err != nil { - panic(err) - } - - client := domain.NewClientFromDocument(document) - if err := client.Validate(); err != nil { - common.JSONError(w, http.StatusBadRequest, err.Error(), "invalid_client") - return - } - - matches := regexp.MustCompile(`/oauth/clients/(.*)$`).FindStringSubmatch(req.URL.Path) - id := matches[1] - - h.clients.Delete(id) - h.clients.Add(client) - - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(client.ToDocument()) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/update_handler_test.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/update_handler_test.go deleted file mode 100644 index adafe1ba..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/clients/update_handler_test.go +++ /dev/null @@ -1,155 +0,0 @@ -package clients_test - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - - "github.com/pivotal-cf-experimental/warrant/internal/server/clients" - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("updateHandler", func() { - var ( - router http.Handler - recorder *httptest.ResponseRecorder - request *http.Request - tokensCollection *domain.Tokens - clientsCollection *domain.Clients - ) - - BeforeEach(func() { - tokensCollection = domain.NewTokens(common.TestPublicKey, common.TestPrivateKey, []string{}) - - clientsCollection = domain.NewClients() - clientsCollection.Add(domain.Client{ - ID: "some-client-id", - Name: "banana", - Scope: []string{"some-scope"}, - ResourceIDs: []string{"some-resource-id"}, - Authorities: []string{"some-authority"}, - AuthorizedGrantTypes: []string{"some-grant-type"}, - AccessTokenValidity: 3600, - RedirectURI: []string{"https://example.com/sessions/create"}, - Autoapprove: []string{"some-approval"}, - }) - - requestBody, err := json.Marshal(map[string]interface{}{ - "client_id": "updated-client-id", - "name": "banana", - "scope": []string{"updated-scope"}, - "resource_ids": []string{"updated-resource-id"}, - "authorities": []string{"updated-authority"}, - "authorized_grant_types": []string{"authorization_code"}, - "autoapprove": []string{"updated-approval"}, - "access_token_validity": 7200, - "redirect_uri": []string{"https://example.com/sessions/update"}, - }) - Expect(err).NotTo(HaveOccurred()) - - request, err = http.NewRequest("PUT", "/oauth/clients/some-client-id", bytes.NewBuffer(requestBody)) - Expect(err).NotTo(HaveOccurred()) - token := tokensCollection.Encrypt(domain.Token{ - ClientID: "my-client-id", - Authorities: []string{"clients.write"}, - Audiences: []string{"clients"}, - }) - request.Header.Set("Authorization", fmt.Sprintf("bearer %s", token)) - - recorder = httptest.NewRecorder() - router = clients.NewRouter(clientsCollection, tokensCollection) - }) - - It("updates the requested client", func() { - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusOK)) - Expect(recorder.Body).To(MatchJSON(`{ - "client_id": "updated-client-id", - "name": "banana", - "scope": ["updated-scope"], - "resource_ids": ["updated-resource-id"], - "authorities": ["updated-authority"], - "authorized_grant_types": ["authorization_code"], - "autoapprove": ["updated-approval"], - "access_token_validity": 7200, - "redirect_uri": ["https://example.com/sessions/update"] - }`)) - }) - - It("requires a token", func() { - request.Header.Del("Authorization") - - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusUnauthorized)) - Expect(recorder.Body).To(MatchJSON(`{ - "error_description": "Full authentication is required to access this resource", - "error": "unauthorized" - }`)) - }) - - It("requires a token with the correct permissions", func() { - token := tokensCollection.Encrypt(domain.Token{ - ClientID: "my-client-id", - Authorities: []string{"bananas.read"}, - Audiences: []string{"bananas"}, - }) - request.Header.Set("Authorization", fmt.Sprintf("bearer %s", token)) - - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusUnauthorized)) - Expect(recorder.Body).To(MatchJSON(`{ - "error_description": "Full authentication is required to access this resource", - "error": "unauthorized" - }`)) - }) - - It("validates the client updates", func() { - requestBody, err := json.Marshal(map[string]interface{}{ - "client_id": "updated-client-id", - "name": "banana", - "scope": []string{"updated-scope"}, - "resource_ids": []string{"updated-resource-id"}, - "authorities": []string{"updated-authority"}, - "authorized_grant_types": []string{"invalid-grant-type"}, - "autoapprove": []string{"updated-approval"}, - "access_token_validity": 7200, - "redirect_uri": []string{"https://example.com/sessions/update"}, - }) - Expect(err).NotTo(HaveOccurred()) - request.Body = ioutil.NopCloser(bytes.NewBuffer(requestBody)) - - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusBadRequest)) - Expect(recorder.Body).To(MatchJSON(`{ - "error_description": "invalid-grant-type is not an allowed grant type. Must be one of: [implicit refresh_token authorization_code client_credentials password]", - "error": "invalid_client" - }`)) - }) - - It("stores the update client in the clients collection", func() { - router.ServeHTTP(recorder, request) - client, ok := clientsCollection.Get("updated-client-id") - Expect(ok).To(BeTrue()) - Expect(client).To(Equal(domain.Client{ - ID: "updated-client-id", - Name: "banana", - Scope: []string{"updated-scope"}, - ResourceIDs: []string{"updated-resource-id"}, - Authorities: []string{"updated-authority"}, - AuthorizedGrantTypes: []string{"authorization_code"}, - AccessTokenValidity: 7200, - RedirectURI: []string{"https://example.com/sessions/update"}, - Autoapprove: []string{"updated-approval"}, - })) - - _, ok = clientsCollection.Get("some-client-id") - Expect(ok).To(BeFalse()) - }) -}) diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/common/error.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/common/error.go deleted file mode 100644 index 769dbc17..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/common/error.go +++ /dev/null @@ -1,25 +0,0 @@ -package common - -import ( - "fmt" - "net/http" -) - -const ( - JSONErrorMessageTemplate = `{"error_description":%q,"error":%q}` - HTMLErrorMessageTemplate = `Apache Tomcat/7.0.61 - Error report

HTTP Status %d -


type Status report

message %s

description %s


Apache Tomcat/7.0.61

` -) - -func JSONError(w http.ResponseWriter, status int, message, errorType string) { - output := fmt.Sprintf(JSONErrorMessageTemplate, message, errorType) - - w.WriteHeader(status) - w.Write([]byte(output)) -} - -func HTMLError(w http.ResponseWriter, status int, message, errorType string) { - output := fmt.Sprintf(HTMLErrorMessageTemplate, status, message, errorType) - - w.WriteHeader(status) - w.Write([]byte(output)) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/common/keys.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/common/keys.go deleted file mode 100644 index 0129cbd2..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/common/keys.go +++ /dev/null @@ -1,26 +0,0 @@ -package common - -const ( - TestPrivateKey = `-----BEGIN RSA PRIVATE KEY----- -MIICXQIBAAKBgQDUs2bXYN4JOKrWjQXkGKxGY2BrsJdEU3zevaUbGLhZlQiA51Om -KlC777I4QjnHGPQGRWstxnzFvIdo/LgXqRxPyTEhpoP5/Bk/j1oCwRCCq8yyd2jR -ulVgHwvXtwC0m3X66Onf9hnerQX/HYQEdAQt/bsdemhpSxlDhKIldybeBwIDAQAB -AoGAPNfw1C1udl7SZ7tBcyUnqp7kxwlly/LB5omDQEQK//0kyJLjl8XFAG2ponQ3 -SN+3dk/HP/nmWT370ilwk7wZT6fqQSBd8tFSR/FbpubYidhBxpien0XrZbsprLR/ -Sb6ghQhMxO0sfLjRNLvLfKfzazPD9reuYn/UhgJAJexArbkCQQDueS9H0nfzwlD7 -XUkkAnBWw/HQtewFzO2b30bM5eAy4exhqes/G9HH2OSbUlk+7kimMCrHB9JsLgFN -8foHhshlAkEA5FVP+FEjb+bUhz0NepiY7/mR0izNMybGL45JaW3PndhMS3D9YwhZ -Gj4VX8P0RaYOGeZFAeGoqTYl0DANHYUn+wJBAJF6RCmgb6S4qgZuBix9gGKt7lrQ -YEe5mEo6j0p4AamIwVdi/SvmoLc1zWAjgGYvnwoi4DXCw89S0WDneQwWYTECQQCn -oJ4aDe83Kr5iHocztq2ol47fPrbS06dxqELq3IwsNGwmgmfzeWB4rJVifehp7XOy -veNxcyowN6lhArXOM0BbAkB45oND59QSGHgFdDsdwrsmeZH5wsA1ufwgyBP6uw0y -+IKqC/Ye6/4xBsQ2eQOzBgIG+wscrHgP4ZYzr6D50PsN ------END RSA PRIVATE KEY-----` - - TestPublicKey = `-----BEGIN PUBLIC KEY----- -MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDUs2bXYN4JOKrWjQXkGKxGY2Br -sJdEU3zevaUbGLhZlQiA51OmKlC777I4QjnHGPQGRWstxnzFvIdo/LgXqRxPyTEh -poP5/Bk/j1oCwRCCq8yyd2jRulVgHwvXtwC0m3X66Onf9hnerQX/HYQEdAQt/bsd -emhpSxlDhKIldybeBwIDAQAB ------END PUBLIC KEY-----` -) diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/common/not_found.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/common/not_found.go deleted file mode 100644 index 43619d61..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/common/not_found.go +++ /dev/null @@ -1,13 +0,0 @@ -package common - -import ( - "fmt" - "net/http" -) - -func NotFound(w http.ResponseWriter, message string) { - output := fmt.Sprintf(`{"error_description":"%s","error":"scim_resource_not_found"}`, message) - - w.WriteHeader(http.StatusNotFound) - w.Write([]byte(output)) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/common/uuid.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/common/uuid.go deleted file mode 100644 index 5cda6c8b..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/common/uuid.go +++ /dev/null @@ -1,16 +0,0 @@ -package common - -import ( - "crypto/rand" - "fmt" -) - -func NewUUID() (string, error) { - u := [16]byte{} - _, err := rand.Read(u[:]) - if err != nil { - return "", err - } - - return fmt.Sprintf("%x-%x-%x-%x-%x", u[0:4], u[4:6], u[6:8], u[8:10], u[10:]), nil -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/client.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/client.go deleted file mode 100644 index 3d729047..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/client.go +++ /dev/null @@ -1,81 +0,0 @@ -package domain - -import ( - "errors" - "fmt" - - "github.com/pivotal-cf-experimental/warrant/internal/documents" -) - -var validGrantTypes = []string{ - "implicit", - "refresh_token", - "authorization_code", - "client_credentials", - "password", -} - -type Client struct { - ID string - Name string - Secret string - Scope []string - ResourceIDs []string - Authorities []string - AuthorizedGrantTypes []string - AccessTokenValidity int - RedirectURI []string - Autoapprove []string -} - -func NewClientFromDocument(document documents.CreateUpdateClientRequest) Client { - return Client{ - ID: document.ClientID, - Name: document.Name, - Secret: document.ClientSecret, - Scope: document.Scope, - ResourceIDs: document.ResourceIDs, - Authorities: document.Authorities, - AuthorizedGrantTypes: document.AuthorizedGrantTypes, - AccessTokenValidity: document.AccessTokenValidity, - RedirectURI: document.RedirectURI, - Autoapprove: document.Autoapprove, - } -} - -func (c Client) ToDocument() documents.ClientResponse { - return documents.ClientResponse{ - ClientID: c.ID, - Name: c.Name, - Scope: shuffle(c.Scope), - ResourceIDs: c.ResourceIDs, - Authorities: c.Authorities, - AuthorizedGrantTypes: shuffle(c.AuthorizedGrantTypes), - Autoapprove: shuffle(c.Autoapprove), - AccessTokenValidity: c.AccessTokenValidity, - RedirectURI: c.RedirectURI, - } -} - -func (c Client) Validate() error { - for _, grantType := range c.AuthorizedGrantTypes { - if !contains(validGrantTypes, grantType) { - msg := fmt.Sprintf("%s is not an allowed grant type. Must be one of: %v", grantType, validGrantTypes) - return errors.New(msg) - } - } - - if len(c.RedirectURI) > 0 { - if !contains(c.AuthorizedGrantTypes, "implicit") && !contains(c.AuthorizedGrantTypes, "authorization_code") { - msg := "A redirect_uri can only be used by implicit or authorization_code grant types." - return errors.New(msg) - } - } - - if contains(c.AuthorizedGrantTypes, "implicit") && c.Secret != "" { - msg := "Implicit grant should not have a client_secret" - return errors.New(msg) - } - - return nil -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/clients.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/clients.go deleted file mode 100644 index f2f0bcf5..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/clients.go +++ /dev/null @@ -1,97 +0,0 @@ -package domain - -var ADMIN_CLIENT = Client{ - ID: "admin", - Name: "admin", - Secret: "admin", - Scope: []string{}, - ResourceIDs: []string{ - "clients", //TODO: This is not needed, but checked in some handlers incorrectly - "password", - "scim", - }, - Authorities: []string{ - "clients.read", - "clients.write", - "clients.secret", - "password.write", - "uaa.admin", - "scim.read", - "scim.write", - }, - AuthorizedGrantTypes: []string{ - "client_credentials", //TODO: we aren't checking that the client has this value when we generate tokens in the handlers - }, - AccessTokenValidity: 3600, - RedirectURI: []string{}, - Autoapprove: []string{}, -} - -type Clients struct { - store map[string]Client -} - -func NewClients() *Clients { - return &Clients{ - store: map[string]Client{ - "admin": ADMIN_CLIENT, - }, - } -} - -func (collection Clients) All() []Client { - var clients []Client - for _, c := range collection.store { - clients = append(clients, c) - } - return clients -} - -func (collection Clients) Add(c Client) { - collection.store[c.ID] = c -} - -func (collection Clients) Get(id string) (Client, bool) { - c, ok := collection.store[id] - return c, ok -} - -func (collection *Clients) Clear() { - collection.store = map[string]Client{ - "admin": ADMIN_CLIENT, - } -} - -func (collection Clients) Delete(id string) bool { - _, ok := collection.store[id] - delete(collection.store, id) - return ok -} - -type ByName ClientsList - -func (clients ByName) Len() int { - return len(clients) -} - -func (clients ByName) Swap(i, j int) { - clients[i], clients[j] = clients[j], clients[i] -} - -func (clients ByName) Less(i, j int) bool { - return clients[i].Name < clients[j].Name -} - -type ByID ClientsList - -func (clients ByID) Len() int { - return len(clients) -} - -func (clients ByID) Swap(i, j int) { - clients[i], clients[j] = clients[j], clients[i] -} - -func (clients ByID) Less(i, j int) bool { - return clients[i].ID < clients[j].ID -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/clients_list.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/clients_list.go deleted file mode 100644 index f61f4f50..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/clients_list.go +++ /dev/null @@ -1,21 +0,0 @@ -package domain - -import "github.com/pivotal-cf-experimental/warrant/internal/documents" - -type ClientsList []Client - -func (cl ClientsList) ToDocument() documents.ClientListResponse { - doc := documents.ClientListResponse{ - ItemsPerPage: 100, - StartIndex: 1, - TotalResults: len(cl), - Schemas: schemas, - Resources: []documents.ClientResponse{}, - } - - for _, client := range cl { - doc.Resources = append(doc.Resources, client.ToDocument()) - } - - return doc -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/clients_list_test.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/clients_list_test.go deleted file mode 100644 index f8ad3486..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/clients_list_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package domain_test - -import ( - "github.com/pivotal-cf-experimental/warrant/internal/documents" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("ClientsList", func() { - Describe("ToDocument", func() { - It("returns a list of resources when there is a client in the list", func() { - list := domain.ClientsList{domain.Client{}} - - doc := list.ToDocument() - Expect(doc.Resources).To(HaveLen(1)) - }) - - It("returns an empty resources array when there are no clients", func() { - list := domain.ClientsList{} - - doc := list.ToDocument() - Expect(doc.Resources).To(Equal([]documents.ClientResponse{})) - }) - }) -}) diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/common.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/common.go deleted file mode 100644 index b70eae3e..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/common.go +++ /dev/null @@ -1,24 +0,0 @@ -package domain - -import ( - "math/rand" - "time" -) - -const ( - origin = "uaa" - schema = "urn:scim:schemas:core:1.0" -) - -var schemas = []string{schema} - -func shuffle(src []string) []string { - final := make([]string, len(src)) - rand.Seed(time.Now().UTC().UnixNano()) - perm := rand.Perm(len(src)) - - for i, v := range perm { - final[v] = src[i] - } - return final -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/errors.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/errors.go deleted file mode 100644 index 2f29616b..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/errors.go +++ /dev/null @@ -1,7 +0,0 @@ -package domain - -type validationError string - -func (e validationError) Error() string { - return string(e) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/group.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/group.go deleted file mode 100644 index b2aeb513..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/group.go +++ /dev/null @@ -1,90 +0,0 @@ -package domain - -import ( - "time" - - "github.com/pivotal-cf-experimental/warrant/internal/documents" - "github.com/pivotal-cf-experimental/warrant/internal/server/common" -) - -type group struct { - ID string - DisplayName string - Description string - Members []Member - CreatedAt time.Time - UpdatedAt time.Time - Version int -} - -func NewGroupFromCreateDocument(request documents.CreateGroupRequest) group { - var members []Member - for _, member := range request.Members { - members = append(members, Member{ - Value: member.Value, - Type: member.Type, - Origin: member.Origin, - }) - } - - now := time.Now().UTC() - id, err := common.NewUUID() - if err != nil { - panic(err) - } - - return group{ - ID: id, - DisplayName: request.DisplayName, - Description: request.Description, - Members: members, - CreatedAt: now, - UpdatedAt: now, - Version: 0, - } -} - -func NewGroupFromUpdateDocument(request documents.CreateUpdateGroupRequest) group { - var members []Member - for _, member := range request.Members { - members = append(members, Member{ - Value: member.Value, - Type: member.Type, - Origin: member.Origin, - }) - } - - return group{ - ID: request.ID, - DisplayName: request.DisplayName, - Description: request.Description, - Members: members, - CreatedAt: request.Meta.Created, - UpdatedAt: request.Meta.LastModified, - Version: request.Meta.Version, - } -} - -func (g group) ToDocument() documents.GroupResponse { - var members []documents.MemberResponse - for _, member := range g.Members { - members = append(members, documents.MemberResponse{ - Value: member.Value, - Type: member.Type, - Origin: member.Origin, - }) - } - - return documents.GroupResponse{ - Schemas: schemas, - ID: g.ID, - Description: g.Description, - DisplayName: g.DisplayName, - Members: members, - Meta: documents.Meta{ - Version: g.Version, - Created: g.CreatedAt, - LastModified: g.UpdatedAt, - }, - } -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/groups.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/groups.go deleted file mode 100644 index eebb8edb..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/groups.go +++ /dev/null @@ -1,94 +0,0 @@ -package domain - -type Groups struct { - store map[string]group -} - -func NewGroups() *Groups { - return &Groups{ - store: make(map[string]group), - } -} - -func (collection Groups) Add(g group) { - collection.store[g.ID] = g -} - -func (collection Groups) Get(id string) (group, bool) { - g, ok := collection.store[id] - return g, ok -} - -func (collection Groups) Update(g group) { - collection.store[g.ID] = g -} - -func (collection Groups) All() []group { - var groups []group - for _, g := range collection.store { - groups = append(groups, g) - } - - return groups -} - -func (collection Groups) Delete(id string) bool { - _, ok := collection.store[id] - delete(collection.store, id) - return ok -} - -func (collection *Groups) Clear() { - collection.store = make(map[string]group) -} - -func (collection Groups) AddMember(id string, member Member) (Member, bool) { - group, ok := collection.store[id] - if !ok { - return Member{}, false - } - - group.Members = append(group.Members, member) - collection.store[id] = group - - return member, true -} - -func (collection Groups) ListMembers(id string) ([]Member, bool) { - group, ok := collection.store[id] - if !ok { - return []Member{}, false - } - - var members []Member - for _, m := range group.Members { - members = append(members, m) - } - - return members, true -} - -func (collection Groups) CheckMembership(id, memberID string) (Member, bool) { - g, ok := collection.store[id] - if !ok { - return Member{}, false - } - - for _, member := range g.Members { - if member.Value == memberID { - return member, true - } - } - - return Member{}, false -} - -func (collection Groups) GetByName(name string) (group, bool) { - for _, g := range collection.store { - if g.DisplayName == name { - return g, true - } - } - - return group{}, false -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/groups_list.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/groups_list.go deleted file mode 100644 index ca709177..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/groups_list.go +++ /dev/null @@ -1,48 +0,0 @@ -package domain - -import "github.com/pivotal-cf-experimental/warrant/internal/documents" - -type GroupsList []group - -func (gl GroupsList) ToDocument() documents.GroupListResponse { - doc := documents.GroupListResponse{ - ItemsPerPage: 100, - StartIndex: 1, - TotalResults: len(gl), - Schemas: schemas, - } - - for _, group := range gl { - doc.Resources = append(doc.Resources, group.ToDocument()) - } - - return doc -} - -type GroupsByDisplayName GroupsList - -func (g GroupsByDisplayName) Len() int { - return len(g) -} - -func (g GroupsByDisplayName) Swap(i, j int) { - g[i], g[j] = g[j], g[i] -} - -func (g GroupsByDisplayName) Less(i, j int) bool { - return g[i].DisplayName < g[j].DisplayName -} - -type GroupsByCreatedAt GroupsList - -func (g GroupsByCreatedAt) Len() int { - return len(g) -} - -func (g GroupsByCreatedAt) Swap(i, j int) { - g[i], g[j] = g[j], g[i] -} - -func (g GroupsByCreatedAt) Less(i, j int) bool { - return g[i].CreatedAt.Before(g[j].CreatedAt) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/init_test.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/init_test.go deleted file mode 100644 index 3563b992..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/init_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package domain_test - -import ( - "testing" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -func TestDomainSuite(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "internal/server/domain") -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/member.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/member.go deleted file mode 100644 index 7751f3be..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/member.go +++ /dev/null @@ -1,27 +0,0 @@ -package domain - -import ( - "github.com/pivotal-cf-experimental/warrant/internal/documents" -) - -type Member struct { - Origin string - Type string - Value string -} - -func NewMemberFromDocument(document documents.CreateMemberRequest) Member { - return Member{ - Type: document.Type, - Value: document.Value, - Origin: document.Origin, - } -} - -func (m Member) ToDocument() documents.MemberResponse { - return documents.MemberResponse{ - Type: m.Type, - Value: m.Value, - Origin: m.Origin, - } -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/members_list.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/members_list.go deleted file mode 100644 index f48f12f2..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/members_list.go +++ /dev/null @@ -1,15 +0,0 @@ -package domain - -import "github.com/pivotal-cf-experimental/warrant/internal/documents" - -type MembersList []Member - -func (ml MembersList) ToDocument() []documents.MemberResponse { - members := []documents.MemberResponse{} - - for _, member := range ml { - members = append(members, member.ToDocument()) - } - - return members -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/token.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/token.go deleted file mode 100644 index fbb847d7..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/token.go +++ /dev/null @@ -1,130 +0,0 @@ -package domain - -import ( - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/documents" - "github.com/pivotal-cf-experimental/warrant/internal/server/common" -) - -type Token struct { - UserID string - ClientID string - Scopes []string - Authorities []string - Audiences []string - Issuer string -} - -func newTokenFromClaims(claims map[string]interface{}) Token { - t := Token{} - - if userID, ok := claims["user_id"].(string); ok { - t.UserID = userID - } - - if clientID, ok := claims["client_id"].(string); ok { - t.ClientID = clientID - } - - if scopes, ok := claims["scope"].([]interface{}); ok { - s := []string{} - for _, scope := range scopes { - s = append(s, scope.(string)) - } - - t.Scopes = s - } - - if authorities, ok := claims["authorities"].([]interface{}); ok { - a := []string{} - for _, authority := range authorities { - a = append(a, authority.(string)) - } - - t.Authorities = a - } - - if audiences, ok := claims["aud"].(string); ok { - t.Audiences = strings.Split(audiences, " ") - } - - return t -} - -func (t Token) ToDocument(privateKey string) documents.TokenResponse { - id, err := common.NewUUID() - if err != nil { - panic(err) - } - - return documents.TokenResponse{ - AccessToken: Tokens{ - PrivateKey: privateKey, - }.Encrypt(t), - TokenType: "bearer", - ExpiresIn: 5000, - Scope: strings.Join(t.Scopes, " "), - JTI: id, - Issuer: t.Issuer, - } -} - -func (t Token) toClaims() map[string]interface{} { - claims := make(map[string]interface{}) - - if len(t.UserID) > 0 { - claims["user_id"] = t.UserID - } - - if len(t.ClientID) > 0 { - claims["client_id"] = t.ClientID - } - - if len(t.Authorities) > 0 { - claims["authorities"] = t.Authorities - } - - claims["scope"] = t.Scopes - claims["aud"] = strings.Join(t.Audiences, " ") - claims["iss"] = t.Issuer - - return claims -} - -func (t Token) hasScopes(scopes []string) bool { - for _, scope := range scopes { - if !contains(t.Scopes, scope) { - return false - } - } - return true -} - -func (t Token) hasAudiences(audiences []string) bool { - for _, audience := range audiences { - if !contains(t.Audiences, audience) { - return false - } - } - return true -} - -func (t Token) hasAuthorities(authorities []string) bool { - for _, authority := range authorities { - if !contains(t.Authorities, authority) { - return false - } - } - return true -} - -func contains(collection []string, item string) bool { - for _, elem := range collection { - if elem == item { - return true - } - } - - return false -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/tokens.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/tokens.go deleted file mode 100644 index 93354d12..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/tokens.go +++ /dev/null @@ -1,74 +0,0 @@ -package domain - -import ( - "errors" - - "github.com/dgrijalva/jwt-go" -) - -type Tokens struct { - DefaultScopes []string - PublicKey string - PrivateKey string -} - -func NewTokens(publicKey, privateKey string, defaultScopes []string) *Tokens { - return &Tokens{ - DefaultScopes: defaultScopes, - PublicKey: publicKey, - PrivateKey: privateKey, - } -} - -func (t Tokens) Encrypt(token Token) string { - crypt := jwt.New(jwt.SigningMethodRS256) - crypt.Claims = token.toClaims() - crypt.Header["kid"] = "legacy-token-key" - encrypted, err := crypt.SignedString([]byte(t.PrivateKey)) - if err != nil { - panic(err) - } - - return encrypted -} - -func (t Tokens) Decrypt(encryptedToken string) (Token, error) { - tok, err := jwt.Parse(encryptedToken, jwt.Keyfunc(func(token *jwt.Token) (interface{}, error) { - switch token.Method { - case jwt.SigningMethodRS256, jwt.SigningMethodRS384, jwt.SigningMethodRS512: - return []byte(t.PublicKey), nil - default: - return nil, errors.New("Unsupported signing method") - } - })) - if err != nil { - return Token{}, err - } - - return newTokenFromClaims(tok.Claims), nil -} - -func (t Tokens) Validate(encryptedToken string, expectedToken Token) bool { - decryptedToken, err := t.Decrypt(encryptedToken) - if err != nil { - return false - } - - return t.validate(decryptedToken, expectedToken) -} - -func (t Tokens) validate(tok, expected Token) bool { - if ok := tok.hasAudiences(expected.Audiences); !ok { - return false - } - - if ok := tok.hasScopes(expected.Scopes); !ok { - return false - } - - if ok := tok.hasAuthorities(expected.Authorities); !ok { - return false - } - - return true -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/user.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/user.go deleted file mode 100644 index 93439dd7..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/user.go +++ /dev/null @@ -1,129 +0,0 @@ -package domain - -import ( - "time" - - "github.com/pivotal-cf-experimental/warrant/internal/documents" - "github.com/pivotal-cf-experimental/warrant/internal/server/common" -) - -type User struct { - ID string - ExternalID string - UserName string - FormattedName string - FamilyName string - GivenName string - MiddleName string - CreatedAt time.Time - UpdatedAt time.Time - Version int - Emails []string - Groups []group - Active bool - Verified bool - Origin string - Password string -} - -func NewUserFromCreateDocument(request documents.CreateUserRequest) User { - var emails []string - for _, email := range request.Emails { - emails = append(emails, email.Value) - } - - now := time.Now().UTC() - id, err := common.NewUUID() - if err != nil { - panic(err) - } - - return User{ - ID: id, - UserName: request.UserName, - CreatedAt: now, - UpdatedAt: now, - Version: 0, - Emails: emails, - Groups: make([]group, 0), - Active: true, - Verified: false, - Origin: origin, - } -} - -func NewUserFromUpdateDocument(request documents.UpdateUserRequest) User { - var emails []string - for _, email := range request.Emails { - emails = append(emails, email.Value) - } - - return User{ - ID: request.ID, - ExternalID: request.ExternalID, - UserName: request.UserName, - FormattedName: request.Name.Formatted, - FamilyName: request.Name.FamilyName, - GivenName: request.Name.GivenName, - MiddleName: request.Name.MiddleName, - CreatedAt: request.Meta.Created, - UpdatedAt: request.Meta.LastModified, - Version: request.Meta.Version, - Emails: emails, - Groups: make([]group, 0), - Active: true, - Verified: false, - Origin: origin, - } -} - -func (u User) ToDocument() documents.UserResponse { - var emails []documents.Email - for _, email := range u.Emails { - emails = append(emails, documents.Email{ - Value: email, - }) - } - - var groups []documents.GroupAssociation - for i := 0; i < len(u.Groups); i++ { - groups = append(groups, documents.GroupAssociation{}) - } - - return documents.UserResponse{ - Schemas: schemas, - ID: u.ID, - ExternalID: u.ExternalID, - UserName: u.UserName, - Name: documents.UserName{ - Formatted: u.FormattedName, - FamilyName: u.FamilyName, - GivenName: u.GivenName, - MiddleName: u.MiddleName, - }, - Meta: documents.Meta{ - Version: u.Version, - Created: u.CreatedAt, - LastModified: u.UpdatedAt, - }, - Emails: emails, - Groups: groups, - Active: u.Active, - Verified: u.Verified, - Origin: u.Origin, - } -} - -func (u User) Validate() error { - if len(u.Emails) == 0 { - return validationError("An email must be provided.") - } - - for _, email := range u.Emails { - if email == "" { - return validationError("[Assertion failed] - this String argument must have text; it must not be null, empty, or blank") - } - } - - return nil -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/users.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/users.go deleted file mode 100644 index fb21a440..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/users.go +++ /dev/null @@ -1,80 +0,0 @@ -package domain - -type Users struct { - store map[string]User -} - -func NewUsers() *Users { - return &Users{ - store: make(map[string]User), - } -} - -func (collection Users) All() []User { - var users []User - for _, u := range collection.store { - users = append(users, u) - } - return users -} - -func (collection Users) Add(u User) { - collection.store[u.ID] = u -} - -func (collection Users) Update(u User) { - collection.store[u.ID] = u -} - -func (collection Users) Get(id string) (User, bool) { - u, ok := collection.store[id] - return u, ok -} - -func (collection Users) GetByName(name string) (User, bool) { - for _, u := range collection.store { - if u.UserName == name { - return u, true - } - } - - return User{}, false -} - -func (collection Users) Delete(id string) bool { - _, ok := collection.store[id] - delete(collection.store, id) - return ok -} - -func (collection *Users) Clear() { - collection.store = make(map[string]User) -} - -type ByEmail UsersList - -func (users ByEmail) Len() int { - return len(users) -} - -func (users ByEmail) Swap(i, j int) { - users[i], users[j] = users[j], users[i] -} - -func (users ByEmail) Less(i, j int) bool { - return users[i].Emails[0] < users[j].Emails[0] -} - -type ByCreated UsersList - -func (users ByCreated) Len() int { - return len(users) -} - -func (users ByCreated) Swap(i, j int) { - users[i], users[j] = users[j], users[i] -} - -func (users ByCreated) Less(i, j int) bool { - return users[i].CreatedAt.Before(users[j].CreatedAt) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/users_list.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/users_list.go deleted file mode 100644 index 364bdbf1..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/users_list.go +++ /dev/null @@ -1,21 +0,0 @@ -package domain - -import "github.com/pivotal-cf-experimental/warrant/internal/documents" - -type UsersList []User - -func (ul UsersList) ToDocument() documents.UserListResponse { - doc := documents.UserListResponse{ - ItemsPerPage: 100, - StartIndex: 1, - TotalResults: len(ul), - Schemas: schemas, - Resources: []documents.UserResponse{}, - } - - for _, user := range ul { - doc.Resources = append(doc.Resources, user.ToDocument()) - } - - return doc -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/users_list_test.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/users_list_test.go deleted file mode 100644 index 95404039..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/domain/users_list_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package domain_test - -import ( - "github.com/pivotal-cf-experimental/warrant/internal/documents" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("UsersList", func() { - Describe("ToDocument", func() { - It("returns a list of resources when there is a user in the list", func() { - list := domain.UsersList{domain.User{}} - - doc := list.ToDocument() - Expect(doc.Resources).To(HaveLen(1)) - }) - - It("returns an empty resources array when there are no users", func() { - list := domain.UsersList{} - - doc := list.ToDocument() - Expect(doc.Resources).To(Equal([]documents.UserResponse{})) - }) - }) -}) diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/add_member_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/add_member_handler.go deleted file mode 100644 index 306bbf13..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/add_member_handler.go +++ /dev/null @@ -1,67 +0,0 @@ -package groups - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "regexp" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/documents" - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type addMemberHandler struct { - groups *domain.Groups - tokens *domain.Tokens -} - -func (h addMemberHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - token := strings.TrimPrefix(req.Header.Get("Authorization"), "Bearer ") - if ok := h.tokens.Validate(token, domain.Token{ - Audiences: []string{"scim"}, - Authorities: []string{"scim.read"}, - }); !ok { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - - matches := regexp.MustCompile(`/Groups/(.*)/members$`).FindStringSubmatch(req.URL.Path) - id := matches[1] - - requestBody, err := ioutil.ReadAll(req.Body) - if err != nil { - panic(err) - } - - contentType := req.Header.Get("Content-Type") - if contentType != "application/json" { - if contentType == "" { - contentType = http.DetectContentType(requestBody) - } - common.JSONError(w, http.StatusBadRequest, fmt.Sprintf("Content type '%s' not supported", contentType), "scim") - return - } - - var document documents.CreateMemberRequest - err = json.Unmarshal(requestBody, &document) - if err != nil { - panic(err) - } - - member, ok := h.groups.AddMember(id, domain.NewMemberFromDocument(document)) - if !ok { - common.JSONError(w, http.StatusNotFound, fmt.Sprintf("Group %s does not exist", id), "scim_resource_not_found") - return - } - - response, err := json.Marshal(member.ToDocument()) - if err != nil { - panic(err) - } - - w.WriteHeader(http.StatusCreated) - w.Write(response) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/check_membership_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/check_membership_handler.go deleted file mode 100644 index b49fac36..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/check_membership_handler.go +++ /dev/null @@ -1,46 +0,0 @@ -package groups - -import ( - "encoding/json" - "fmt" - "net/http" - "regexp" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type checkMembershipHandler struct { - groups *domain.Groups - tokens *domain.Tokens -} - -func (h checkMembershipHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - token := strings.TrimPrefix(req.Header.Get("Authorization"), "Bearer ") - if ok := h.tokens.Validate(token, domain.Token{ - Audiences: []string{"scim"}, - Authorities: []string{"scim.read"}, - }); !ok { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - - matches := regexp.MustCompile(`/Groups/(.*)/members/(.*)$`).FindStringSubmatch(req.URL.Path) - groupID := matches[1] - memberID := matches[2] - - member, ok := h.groups.CheckMembership(groupID, memberID) - if !ok { - common.NotFound(w, fmt.Sprintf("Group %s does not exist or entity %s is not a member", groupID, memberID)) - return - } - - response, err := json.Marshal(member.ToDocument()) - if err != nil { - panic(err) - } - - w.WriteHeader(http.StatusOK) - w.Write(response) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/create_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/create_handler.go deleted file mode 100644 index 44c7715f..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/create_handler.go +++ /dev/null @@ -1,56 +0,0 @@ -package groups - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/documents" - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type createHandler struct { - groups *domain.Groups - tokens *domain.Tokens -} - -func (h createHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - token := strings.TrimPrefix(req.Header.Get("Authorization"), "Bearer ") - if ok := h.tokens.Validate(token, domain.Token{ - Audiences: []string{"scim"}, - Authorities: []string{"scim.write"}, - }); !ok { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - - requestBody, err := ioutil.ReadAll(req.Body) - if err != nil { - panic(err) - } - - var document documents.CreateGroupRequest - err = json.Unmarshal(requestBody, &document) - if err != nil { - panic(err) - } - - if _, ok := h.groups.GetByName(document.DisplayName); ok { - common.JSONError(w, http.StatusConflict, fmt.Sprintf("A group with displayName: %s already exists.", document.DisplayName), "scim_resource_already_exists") - return - } - - group := domain.NewGroupFromCreateDocument(document) - h.groups.Add(group) - - response, err := json.Marshal(group.ToDocument()) - if err != nil { - panic(err) - } - - w.WriteHeader(http.StatusCreated) - w.Write(response) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/delete_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/delete_handler.go deleted file mode 100644 index f2624835..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/delete_handler.go +++ /dev/null @@ -1,37 +0,0 @@ -package groups - -import ( - "fmt" - "net/http" - "regexp" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type deleteHandler struct { - groups *domain.Groups - tokens *domain.Tokens -} - -func (h deleteHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - token := strings.TrimPrefix(req.Header.Get("Authorization"), "Bearer ") - if ok := h.tokens.Validate(token, domain.Token{ - Audiences: []string{"scim"}, - Authorities: []string{"scim.write"}, - }); !ok { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - - matches := regexp.MustCompile(`/Groups/(.*)$`).FindStringSubmatch(req.URL.Path) - id := matches[1] - - if ok := h.groups.Delete(id); !ok { - common.JSONError(w, http.StatusNotFound, fmt.Sprintf("Group %s does not exist", id), "scim_resource_not_found") - return - } - - w.WriteHeader(http.StatusOK) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/get_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/get_handler.go deleted file mode 100644 index 92f11bba..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/get_handler.go +++ /dev/null @@ -1,45 +0,0 @@ -package groups - -import ( - "encoding/json" - "fmt" - "net/http" - "regexp" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type getHandler struct { - groups *domain.Groups - tokens *domain.Tokens -} - -func (h getHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - token := strings.TrimPrefix(req.Header.Get("Authorization"), "Bearer ") - if ok := h.tokens.Validate(token, domain.Token{ - Audiences: []string{"scim"}, - Authorities: []string{"scim.read"}, - }); !ok { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - - matches := regexp.MustCompile(`/Groups/(.*)$`).FindStringSubmatch(req.URL.Path) - id := matches[1] - - group, ok := h.groups.Get(id) - if !ok { - common.NotFound(w, fmt.Sprintf("Group %s does not exist", id)) - return - } - - response, err := json.Marshal(group.ToDocument()) - if err != nil { - panic(err) - } - - w.WriteHeader(http.StatusOK) - w.Write(response) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/list_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/list_handler.go deleted file mode 100644 index 7ffa35ce..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/list_handler.go +++ /dev/null @@ -1,111 +0,0 @@ -package groups - -import ( - "encoding/json" - "fmt" - "net/http" - "net/url" - "regexp" - "sort" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type listHandler struct { - groups *domain.Groups - tokens *domain.Tokens -} - -func (h listHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - token := req.Header.Get("Authorization") - token = strings.TrimPrefix(token, "Bearer ") - token = strings.TrimPrefix(token, "bearer ") - - if len(token) == 0 { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - if ok := h.tokens.Validate(token, domain.Token{ - Authorities: []string{"scim.read"}, - Audiences: []string{"scim"}, - }); !ok { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - - query, err := url.ParseQuery(req.URL.RawQuery) - if err != nil { - panic(err) - } - - list := domain.GroupsList{} - - filter := query.Get("filter") - if filter != "" { - matches := regexp.MustCompile(`(.*) (.*) ['"](.*)['"]$`).FindStringSubmatch(filter) - parameter := matches[1] - operator := matches[2] - value := matches[3] - - if !validParameter(parameter) { - common.JSONError(w, http.StatusBadRequest, fmt.Sprintf("Invalid parameter in filter expression: [%s]", filter), "scim") - return - } - - if !validOperator(operator) { - common.JSONError(w, http.StatusBadRequest, fmt.Sprintf("Invalid operator in filter expression: [%s]", filter), "scim") - return - } - - if strings.ToLower(parameter) == "displayname" { - group, found := h.groups.GetByName(value) - if found { - list = append(list, group) - } - } else { - group, found := h.groups.Get(value) - if found { - list = append(list, group) - } - } - } else { - list = h.groups.All() - } - - by := strings.ToLower(query.Get("sortBy")) - if by == "displayname" { - sort.Sort(domain.GroupsByDisplayName(list)) - } else { - sort.Sort(domain.GroupsByCreatedAt(list)) - } - - response, err := json.Marshal(list.ToDocument()) - if err != nil { - panic(err) - } - - w.WriteHeader(http.StatusOK) - w.Write([]byte(response)) -} - -func validParameter(parameter string) bool { - for _, p := range []string{"id", "displayname"} { - if strings.ToLower(parameter) == p { - return true - } - } - - return false -} - -func validOperator(operator string) bool { - for _, o := range []string{"eq"} { - if strings.ToLower(operator) == o { - return true - } - } - - return false -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/list_members_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/list_members_handler.go deleted file mode 100644 index e974129d..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/list_members_handler.go +++ /dev/null @@ -1,46 +0,0 @@ -package groups - -import ( - "encoding/json" - "fmt" - "net/http" - "regexp" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type listMembersHandler struct { - groups *domain.Groups - tokens *domain.Tokens -} - -func (h listMembersHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - token := strings.TrimPrefix(req.Header.Get("Authorization"), "Bearer ") - if ok := h.tokens.Validate(token, domain.Token{ - Audiences: []string{"scim"}, - Authorities: []string{"scim.read"}, - }); !ok { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - - matches := regexp.MustCompile(`/Groups/(.*)/members$`).FindStringSubmatch(req.URL.Path) - id := matches[1] - - list := domain.MembersList{} - list, ok := h.groups.ListMembers(id) - if !ok { - common.NotFound(w, fmt.Sprintf("Group %s does not exist", id)) - return - } - - response, err := json.Marshal(list.ToDocument()) - if err != nil { - panic(err) - } - - w.WriteHeader(http.StatusOK) - w.Write([]byte(response)) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/router.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/router.go deleted file mode 100644 index edccb685..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/router.go +++ /dev/null @@ -1,21 +0,0 @@ -package groups - -import ( - "github.com/gorilla/mux" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -func NewRouter(groups *domain.Groups, tokens *domain.Tokens) *mux.Router { - router := mux.NewRouter() - - router.Handle("/Groups", createHandler{groups, tokens}).Methods("POST") - router.Handle("/Groups", listHandler{groups, tokens}).Methods("GET") - router.Handle("/Groups/{guid}", updateHandler{groups, tokens}).Methods("PUT") - router.Handle("/Groups/{guid}", getHandler{groups, tokens}).Methods("GET") - router.Handle("/Groups/{guid}", deleteHandler{groups, tokens}).Methods("DELETE") - router.Handle("/Groups/{guid}/members", listMembersHandler{groups, tokens}).Methods("GET") - router.Handle("/Groups/{guid}/members", addMemberHandler{groups, tokens}).Methods("POST") - router.Handle("/Groups/{guid}/members/{guid}", checkMembershipHandler{groups, tokens}).Methods("GET") - - return router -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/update_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/update_handler.go deleted file mode 100644 index 81931710..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/groups/update_handler.go +++ /dev/null @@ -1,78 +0,0 @@ -package groups - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "regexp" - "strconv" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/documents" - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type updateHandler struct { - groups *domain.Groups - tokens *domain.Tokens -} - -func (h updateHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - token := strings.TrimPrefix(req.Header.Get("Authorization"), "Bearer ") - if ok := h.tokens.Validate(token, domain.Token{ - Audiences: []string{"scim"}, - Authorities: []string{"scim.write"}, - }); !ok { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - - requestBody, err := ioutil.ReadAll(req.Body) - if err != nil { - panic(err) - } - - contentType := req.Header.Get("Content-Type") - if contentType != "application/json" { - if contentType == "" { - contentType = http.DetectContentType(requestBody) - } - common.JSONError(w, http.StatusBadRequest, fmt.Sprintf("Content type '%s' not supported", contentType), "scim") - return - } - - var document documents.CreateUpdateGroupRequest - err = json.Unmarshal(requestBody, &document) - if err != nil { - panic(err) - } - - group := domain.NewGroupFromUpdateDocument(document) - - matches := regexp.MustCompile(`/Groups/(.*)$`).FindStringSubmatch(req.URL.Path) - id := matches[1] - - existingGroup, ok := h.groups.Get(id) - if !ok { - common.JSONError(w, http.StatusNotFound, fmt.Sprintf("Group %s does not exist", group.ID), "scim_resource_not_found") - return - } - - version, err := strconv.ParseInt(req.Header.Get("If-Match"), 10, 64) - if err != nil || existingGroup.Version != int(version) { - common.JSONError(w, http.StatusBadRequest, "Missing If-Match for PUT", "scim") - return - } - - h.groups.Update(group) - - response, err := json.Marshal(group.ToDocument()) - if err != nil { - panic(err) - } - - w.WriteHeader(http.StatusOK) - w.Write(response) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/authorize_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/authorize_handler.go deleted file mode 100644 index 7df2003a..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/authorize_handler.go +++ /dev/null @@ -1,114 +0,0 @@ -package tokens - -import ( - "fmt" - "net/http" - "net/url" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type authorizeHandler struct { - tokens *domain.Tokens - users *domain.Users - clients *domain.Clients -} - -func (h authorizeHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - if req.Header.Get("Accept") != "application/json" { - h.redirectToLogin(w) - return - } - - requestQuery := req.URL.Query() - clientID := requestQuery.Get("client_id") - responseType := requestQuery.Get("response_type") - - if responseType != "token" { - h.redirectToLogin(w) - return - } - - client, ok := h.clients.Get(clientID) - if !ok { - common.JSONError(w, http.StatusUnauthorized, fmt.Sprintf("No client with requested id: %s", clientID), "invalid_client") - return - } - - req.ParseForm() - userName := req.Form.Get("username") - - user, ok := h.users.GetByName(userName) - if !ok { - common.JSONError(w, http.StatusNotFound, fmt.Sprintf("User %s does not exist", userName), "scim_resource_not_found") - return - } - - if req.Form.Get("source") != "credentials" { - h.redirectToLogin(w) - return - } - - if req.Form.Get("password") != user.Password { - h.redirectToLogin(w) - return - } - - scopes := []string{} - requestedScopes := strings.Split(req.Form.Get("scope"), " ") - for _, requestedScope := range requestedScopes { - if contains(h.tokens.DefaultScopes, requestedScope) { - scopes = append(scopes, requestedScope) - } - } - - for _, approvedScope := range scopes { - if !contains(client.Autoapprove, approvedScope) { - // TODO: when the scopes requested are not contained - // in the autoapprove list, the correct behavior is - // to return a 200 with some JSON explaining to the - // requestor that the scopes need to be approved by - // the user. We are obviously not doing this. This - // needs to be implemented. - w.WriteHeader(http.StatusOK) - return - } - } - - t := h.tokens.Encrypt(domain.Token{ - UserID: user.ID, - Scopes: scopes, - Audiences: []string{}, - }) - - redirectURI := requestQuery.Get("redirect_uri") - - query := url.Values{ - "token_type": []string{"bearer"}, - "access_token": []string{t}, - "expires_in": []string{"599"}, - "scope": []string{strings.Join(scopes, " ")}, - "jti": []string{"ad0efc96-ed29-43ef-be75-85a4b4f105b5"}, - } - location := fmt.Sprintf("%s#%s", redirectURI, query.Encode()) - - w.Header().Set("Location", location) - w.WriteHeader(http.StatusFound) -} - -func contains(scopeList []string, requestedScope string) bool { - for _, scope := range scopeList { - if scope == requestedScope { - return true - } - } - - return false -} - -func (h authorizeHandler) redirectToLogin(w http.ResponseWriter) { - w.Header().Set("Location", "/login") - w.WriteHeader(http.StatusFound) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/authorize_handler_test.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/authorize_handler_test.go deleted file mode 100644 index 5630a896..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/authorize_handler_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package tokens_test - -import ( - "net/http" - "net/http/httptest" - "net/url" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/documents" - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" - "github.com/pivotal-cf-experimental/warrant/internal/server/tokens" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type hasURL struct{} - -func (hasURL) URL() string { - return "https://uaa.example.com" -} - -var _ = Describe("authorizeHandler", func() { - var ( - router http.Handler - recorder *httptest.ResponseRecorder - request *http.Request - tokensCollection *domain.Tokens - ) - - BeforeEach(func() { - recorder = httptest.NewRecorder() - - values := url.Values{ - "client_id": {"some-client-id"}, - "scope": {"openid"}, - "response_type": {"token"}, - "redirect_uri": {"https://uaa.example.com"}, - } - u := &url.URL{ - Path: "/oauth/authorize", - RawQuery: values.Encode(), - } - - var err error - request, err = http.NewRequest("POST", u.String(), strings.NewReader(url.Values{ - "username": {"some-user"}, - "password": {"password"}, - "source": {"credentials"}, - }.Encode())) - Expect(err).NotTo(HaveOccurred()) - - request.Header.Set("Accept", "application/json") - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - tokensCollection = domain.NewTokens(common.TestPublicKey, common.TestPrivateKey, []string{}) - usersCollection := domain.NewUsers() - clientsCollection := domain.NewClients() - - clientsCollection.Add(domain.NewClientFromDocument(documents.CreateUpdateClientRequest{ - ClientID: "some-client-id", - })) - - usersCollection.Add(domain.NewUserFromUpdateDocument(documents.UpdateUserRequest{ - ID: "some-user", - UserName: "some-user", - })) - - user, ok := usersCollection.Get("some-user") - Expect(ok).To(BeTrue()) - - user.Password = "password" - usersCollection.Add(user) - - router = tokens.NewRouter(tokensCollection, - usersCollection, clientsCollection, common.TestPublicKey, common.TestPrivateKey, hasURL{}) - }) - - It("returns a valid token when there is no overlap between client and user scopes", func() { - router.ServeHTTP(recorder, request) - Expect(recorder.Code).To(Equal(http.StatusFound)) - - location, err := url.Parse(recorder.HeaderMap.Get("Location")) - Expect(err).NotTo(HaveOccurred()) - - query, err := url.ParseQuery(location.Fragment) - Expect(err).NotTo(HaveOccurred()) - Expect(query.Get("scope")).To(Equal("")) - - token, err := tokensCollection.Decrypt(query.Get("access_token")) - Expect(err).NotTo(HaveOccurred()) - Expect(token.Scopes).NotTo(BeNil()) - }) -}) diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/init_test.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/init_test.go deleted file mode 100644 index eecc7558..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/init_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package tokens_test - -import ( - "testing" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -func TestTokensSuite(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "internal/server/tokens") -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/key_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/key_handler.go deleted file mode 100644 index a4fd13fc..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/key_handler.go +++ /dev/null @@ -1,58 +0,0 @@ -package tokens - -import ( - "crypto/x509" - "encoding/base64" - "encoding/json" - "encoding/pem" - "math/big" - "net/http" - - "crypto/rsa" - - "github.com/pivotal-cf-experimental/warrant/internal/documents" -) - -type keyHandler struct { - publicKey string -} - -func (h keyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - pem, _ := pem.Decode([]byte(h.publicKey)) - - if pem == nil { - panic("No PEM data was included in the public key") - } - - publicKey, err := x509.ParsePKIXPublicKey(pem.Bytes) - - if err != nil { - panic(err) - } - - rsaPublicKey, ok := publicKey.(*rsa.PublicKey) - - if !ok { - panic("public key is not rsa") - } - - exponentBytes := big.NewInt(int64(rsaPublicKey.E)).Bytes() - modulusBytes := rsaPublicKey.N.Bytes() - - response, err := json.Marshal(documents.TokenKeyResponse{ - Kid: "legacy-token-key", - Alg: "SHA256withRSA", - Value: h.publicKey, - Kty: "RSA", - Use: "sig", - N: base64.RawURLEncoding.EncodeToString(modulusBytes), - E: base64.RawURLEncoding.EncodeToString(exponentBytes), - }) - - if err != nil { - panic(err) - } - - w.WriteHeader(http.StatusOK) - w.Write(response) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/keys_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/keys_handler.go deleted file mode 100644 index 2bc62a1b..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/keys_handler.go +++ /dev/null @@ -1,70 +0,0 @@ -package tokens - -import ( - "crypto/rsa" - "crypto/x509" - "encoding/base64" - "encoding/json" - "encoding/pem" - "math/big" - "net/http" - - "github.com/pivotal-cf-experimental/warrant/internal/documents" -) - -type keysHandler struct { - publicKey string -} - -func (h keysHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - pem, _ := pem.Decode([]byte(h.publicKey)) - - if pem == nil { - panic("No PEM data was included in the public key") - } - - publicKey, err := x509.ParsePKIXPublicKey(pem.Bytes) - - if err != nil { - panic(err) - } - - rsaPublicKey, ok := publicKey.(*rsa.PublicKey) - - if !ok { - panic("public key is not rsa") - } - - exponentBytes := big.NewInt(int64(rsaPublicKey.E)).Bytes() - modulusBytes := rsaPublicKey.N.Bytes() - - response, err := json.Marshal(documents.TokenKeysResponse{ - Keys: []documents.TokenKeyResponse{ - { - Kid: "legacy-token-key", - Alg: "SHA256withRSA", - Value: h.publicKey, - Kty: "RSA", - Use: "sig", - N: base64.RawURLEncoding.EncodeToString(modulusBytes), - E: base64.RawURLEncoding.EncodeToString(exponentBytes), - }, - { - Kid: "token-key", - Alg: "SHA256withRSA", - Value: h.publicKey, - Kty: "RSA", - Use: "sig", - N: base64.RawURLEncoding.EncodeToString(modulusBytes), - E: base64.RawURLEncoding.EncodeToString(exponentBytes), - }, - }, - }) - - if err != nil { - panic(err) - } - - w.WriteHeader(http.StatusOK) - w.Write(response) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/router.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/router.go deleted file mode 100644 index 2a30f8e3..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/router.go +++ /dev/null @@ -1,24 +0,0 @@ -package tokens - -import ( - "github.com/gorilla/mux" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -func NewRouter( - tokens *domain.Tokens, - users *domain.Users, - clients *domain.Clients, - publicKey string, - privateKey string, - urlFinder urlFinder) *mux.Router { - - router := mux.NewRouter() - - router.Handle("/oauth/token", tokenHandler{clients, users, urlFinder, privateKey}).Methods("POST") - router.Handle("/oauth/authorize", authorizeHandler{tokens, users, clients}).Methods("POST") - router.Handle("/token_key", keyHandler{publicKey}).Methods("GET") - router.Handle("/token_keys", keysHandler{publicKey}).Methods("GET") - - return router -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/token_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/token_handler.go deleted file mode 100644 index 22342996..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/tokens/token_handler.go +++ /dev/null @@ -1,67 +0,0 @@ -package tokens - -import ( - "encoding/json" - "fmt" - "net/http" - - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type urlFinder interface { - URL() string -} - -type tokenHandler struct { - clients *domain.Clients - users *domain.Users - urlFinder urlFinder - privateKey string -} - -func (h tokenHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - // TODO: actually check the basic auth values - clientID, _, ok := req.BasicAuth() - if !ok { - common.JSONError(w, http.StatusUnauthorized, "An Authentication object was not found in the SecurityContext", "unauthorized") - return - } - - client, ok := h.clients.Get(clientID) - if !ok { - common.JSONError(w, http.StatusUnauthorized, fmt.Sprintf("No client with requested id: %s", clientID), "invalid_client") - return - } - - err := req.ParseForm() - if err != nil { - panic(err) - } - - var t domain.Token - if req.Form.Get("grant_type") == "client_credentials" { - t.ClientID = clientID - t.Scopes = client.Scope - t.Authorities = client.Authorities - t.Audiences = client.ResourceIDs - t.Issuer = fmt.Sprintf("%s/oauth/token", h.urlFinder.URL()) - } else { - user, ok := h.users.GetByName(req.Form.Get("username")) - if !ok { - common.JSONError(w, http.StatusNotFound, fmt.Sprintf("User %s does not exist", req.Form.Get("username")), "scim_resource_not_found") - return - } - - t.ClientID = clientID - t.Scopes = client.Scope - t.UserID = user.ID - } - - response, err := json.Marshal(t.ToDocument(h.privateKey)) - if err != nil { - panic(err) - } - - w.Write(response) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/create_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/create_handler.go deleted file mode 100644 index 62b183d9..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/create_handler.go +++ /dev/null @@ -1,69 +0,0 @@ -package users - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/documents" - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type createHandler struct { - users *domain.Users - tokens *domain.Tokens -} - -func (h createHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - token := strings.TrimPrefix(req.Header.Get("Authorization"), "Bearer ") - if ok := h.tokens.Validate(token, domain.Token{ - Audiences: []string{"scim"}, - Authorities: []string{"scim.write"}, - }); !ok { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - - requestBody, err := ioutil.ReadAll(req.Body) - if err != nil { - panic(err) - } - - contentType := req.Header.Get("Content-Type") - if contentType != "application/json" { - if contentType == "" { - contentType = http.DetectContentType(requestBody) - } - common.JSONError(w, http.StatusBadRequest, fmt.Sprintf("Content type '%s' not supported", contentType), "scim") - return - } - - var document documents.CreateUserRequest - err = json.Unmarshal(requestBody, &document) - if err != nil { - panic(err) - } - - if _, ok := h.users.GetByName(document.UserName); ok { - common.JSONError(w, http.StatusConflict, fmt.Sprintf("Username already in use: %s", document.UserName), "scim_resource_already_exists") - return - } - - user := domain.NewUserFromCreateDocument(document) - if err := user.Validate(); err != nil { - common.JSONError(w, http.StatusBadRequest, err.Error(), "invalid_scim_resource") - return - } - h.users.Add(user) - - response, err := json.Marshal(user.ToDocument()) - if err != nil { - panic(err) - } - - w.WriteHeader(http.StatusCreated) - w.Write(response) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/delete_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/delete_handler.go deleted file mode 100644 index da4c2e12..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/delete_handler.go +++ /dev/null @@ -1,36 +0,0 @@ -package users - -import ( - "net/http" - "regexp" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type deleteHandler struct { - users *domain.Users - tokens *domain.Tokens -} - -func (h deleteHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - token := strings.TrimPrefix(req.Header.Get("Authorization"), "Bearer ") - if ok := h.tokens.Validate(token, domain.Token{ - Audiences: []string{"scim"}, - Authorities: []string{"scim.write"}, - }); !ok { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - - matches := regexp.MustCompile(`/Users/(.*)$`).FindStringSubmatch(req.URL.Path) - id := matches[1] - - if ok := h.users.Delete(id); !ok { - common.JSONError(w, http.StatusNotFound, "User non-existant-user-guid does not exist", "scim_resource_not_found") - return - } - - w.WriteHeader(http.StatusOK) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/get_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/get_handler.go deleted file mode 100644 index 0d77c310..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/get_handler.go +++ /dev/null @@ -1,45 +0,0 @@ -package users - -import ( - "encoding/json" - "fmt" - "net/http" - "regexp" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type getHandler struct { - users *domain.Users - tokens *domain.Tokens -} - -func (h getHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - token := strings.TrimPrefix(req.Header.Get("Authorization"), "Bearer ") - if ok := h.tokens.Validate(token, domain.Token{ - Audiences: []string{"scim"}, - Authorities: []string{"scim.read"}, - }); !ok { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - - matches := regexp.MustCompile(`/Users/(.*)$`).FindStringSubmatch(req.URL.Path) - id := matches[1] - - user, ok := h.users.Get(id) - if !ok { - common.NotFound(w, fmt.Sprintf("User %s does not exist", id)) - return - } - - response, err := json.Marshal(user.ToDocument()) - if err != nil { - panic(err) - } - - w.WriteHeader(http.StatusOK) - w.Write(response) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/list_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/list_handler.go deleted file mode 100644 index 80b06cf9..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/list_handler.go +++ /dev/null @@ -1,105 +0,0 @@ -package users - -import ( - "encoding/json" - "fmt" - "net/http" - "net/url" - "regexp" - "sort" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type listHandler struct { - users *domain.Users - tokens *domain.Tokens -} - -//TODO: check scim.read scope (or uaa.admin) and scim audience - -func (h listHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - token := req.Header.Get("Authorization") - token = strings.TrimPrefix(token, "Bearer ") - token = strings.TrimPrefix(token, "bearer ") - - if len(token) == 0 { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - if ok := h.tokens.Validate(token, domain.Token{ - Authorities: []string{"scim.read"}, - Audiences: []string{"scim"}, - }); !ok { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - - query, err := url.ParseQuery(req.URL.RawQuery) - if err != nil { - panic(err) - } - - list := domain.UsersList{} - - filter := query.Get("filter") - if filter != "" { - matches := regexp.MustCompile(`(.*) (.*) ['"](.*)['"]$`).FindStringSubmatch(filter) - parameter := matches[1] - operator := matches[2] - value := matches[3] - - if !validParameter(parameter) { - common.JSONError(w, http.StatusBadRequest, fmt.Sprintf("Invalid filter expression: [%s]", filter), "scim") - return - } - - if !validOperator(operator) { - common.JSONError(w, http.StatusBadRequest, fmt.Sprintf("Invalid filter expression: [%s]", filter), "scim") - return - } - user, found := h.users.Get(value) - if found { - list = append(list, user) - } - } else { - list = append(list, h.users.All()...) - } - - switch by := query.Get("sortBy"); by { - case "email": - sort.Sort(domain.ByEmail(list)) - default: - sort.Sort(domain.ByCreated(list)) - } - - response, err := json.Marshal(list.ToDocument()) - if err != nil { - panic(err) - } - - w.WriteHeader(http.StatusOK) - w.Write([]byte(response)) -} - -func validParameter(parameter string) bool { - for _, p := range []string{"id"} { - if strings.ToLower(parameter) == p { - return true - } - } - - return false -} - -func validOperator(operator string) bool { - for _, o := range []string{"eq"} { - if strings.ToLower(operator) == o { - return true - } - } - - return false -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/password_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/password_handler.go deleted file mode 100644 index 39d4c5d7..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/password_handler.go +++ /dev/null @@ -1,63 +0,0 @@ -package users - -import ( - "encoding/json" - "net/http" - "regexp" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/documents" - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type passwordHandler struct { - users *domain.Users - tokens *domain.Tokens -} - -func (h passwordHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - token := strings.TrimPrefix(req.Header.Get("Authorization"), "Bearer ") - matches := regexp.MustCompile(`/Users/(.*)/password$`).FindStringSubmatch(req.URL.Path) - id := matches[1] - - user, ok := h.users.Get(id) - if !ok { - common.JSONError(w, http.StatusUnauthorized, "Not authorized", "access_denied") - return - } - - var document documents.ChangePasswordRequest - err := json.NewDecoder(req.Body).Decode(&document) - if err != nil { - panic(err) - } - - if !h.canUpdateUserPassword(id, token, user.Password, document.OldPassword) { - common.JSONError(w, http.StatusUnauthorized, "Not authorized", "access_denied") - return - } - - user.Password = document.Password - h.users.Update(user) -} - -func (h passwordHandler) canUpdateUserPassword(userID, tokenHeader, existingPassword, givenPassword string) bool { - if h.tokens.Validate(tokenHeader, domain.Token{ - Audiences: []string{"password"}, - Authorities: []string{"password.write"}, - }) { - return true - } - - t, err := h.tokens.Decrypt(tokenHeader) - if err != nil { - return false - } - - if t.UserID == userID && existingPassword == givenPassword { - return true - } - - return false -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/router.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/router.go deleted file mode 100644 index 8a7ff963..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/router.go +++ /dev/null @@ -1,19 +0,0 @@ -package users - -import ( - "github.com/gorilla/mux" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -func NewRouter(users *domain.Users, tokens *domain.Tokens) *mux.Router { - router := mux.NewRouter() - - router.Handle("/Users", createHandler{users, tokens}).Methods("POST") - router.Handle("/Users", listHandler{users, tokens}).Methods("GET") - router.Handle("/Users/{guid}", getHandler{users, tokens}).Methods("GET") - router.Handle("/Users/{guid}", deleteHandler{users, tokens}).Methods("DELETE") - router.Handle("/Users/{guid}", updateHandler{users, tokens}).Methods("PUT") - router.Handle("/Users/{guid}/password", passwordHandler{users, tokens}).Methods("PUT") - - return router -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/update_handler.go b/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/update_handler.go deleted file mode 100644 index 0f683485..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/internal/server/users/update_handler.go +++ /dev/null @@ -1,78 +0,0 @@ -package users - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "regexp" - "strconv" - "strings" - - "github.com/pivotal-cf-experimental/warrant/internal/documents" - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" -) - -type updateHandler struct { - users *domain.Users - tokens *domain.Tokens -} - -func (h updateHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - token := strings.TrimPrefix(req.Header.Get("Authorization"), "Bearer ") - if ok := h.tokens.Validate(token, domain.Token{ - Audiences: []string{"scim"}, - Authorities: []string{"scim.write"}, - }); !ok { - common.JSONError(w, http.StatusUnauthorized, "Full authentication is required to access this resource", "unauthorized") - return - } - - requestBody, err := ioutil.ReadAll(req.Body) - if err != nil { - panic(err) - } - - contentType := req.Header.Get("Content-Type") - if contentType != "application/json" { - if contentType == "" { - contentType = http.DetectContentType(requestBody) - } - common.JSONError(w, http.StatusBadRequest, fmt.Sprintf("Content type '%s' not supported", contentType), "scim") - return - } - - var document documents.UpdateUserRequest - err = json.Unmarshal(requestBody, &document) - if err != nil { - panic(err) - } - - user := domain.NewUserFromUpdateDocument(document) - - matches := regexp.MustCompile(`/Users/(.*)$`).FindStringSubmatch(req.URL.Path) - id := matches[1] - - existingUser, ok := h.users.Get(id) - if !ok { - common.JSONError(w, http.StatusNotFound, fmt.Sprintf("User %s does not exist", user.ID), "scim_resource_not_found") - return - } - - version, err := strconv.ParseInt(req.Header.Get("If-Match"), 10, 64) - if err != nil || existingUser.Version != int(version) { - common.JSONError(w, http.StatusBadRequest, "Missing If-Match for PUT", "scim") - return - } - - h.users.Update(user) - - response, err := json.Marshal(user.ToDocument()) - if err != nil { - panic(err) - } - - w.WriteHeader(http.StatusOK) - w.Write(response) -} diff --git a/vendor/github.com/pivotal-cf-experimental/warrant/testserver/uaa.go b/vendor/github.com/pivotal-cf-experimental/warrant/testserver/uaa.go deleted file mode 100644 index 06b5363b..00000000 --- a/vendor/github.com/pivotal-cf-experimental/warrant/testserver/uaa.go +++ /dev/null @@ -1,134 +0,0 @@ -package testserver - -import ( - "net/http/httptest" - - "github.com/gorilla/mux" - "github.com/pivotal-cf-experimental/warrant/internal/server/clients" - "github.com/pivotal-cf-experimental/warrant/internal/server/common" - "github.com/pivotal-cf-experimental/warrant/internal/server/domain" - "github.com/pivotal-cf-experimental/warrant/internal/server/groups" - "github.com/pivotal-cf-experimental/warrant/internal/server/tokens" - "github.com/pivotal-cf-experimental/warrant/internal/server/users" -) - -var defaultScopes = []string{ - "scim.read", - "cloudcontroller.admin", - "password.write", - "scim.write", - "openid", - "cloud_controller.write", - "cloud_controller.read", - "doppler.firehose", - "notification_preferences.write", - "notification_preferences.read", -} - -// UAA is a fake implementation of the UAA HTTP service. -type UAA struct { - server *httptest.Server - users *domain.Users - clients *domain.Clients - groups *domain.Groups - tokens *domain.Tokens - - publicKey string - privateKey string -} - -// NewUAA returns a new UAA initialized with the given Config. -func NewUAA() *UAA { - privateKey := common.TestPrivateKey - publicKey := common.TestPublicKey - - tokensCollection := domain.NewTokens(publicKey, privateKey, defaultScopes) - usersCollection := domain.NewUsers() - clientsCollection := domain.NewClients() - groupsCollection := domain.NewGroups() - - router := mux.NewRouter() - uaa := &UAA{ - server: httptest.NewUnstartedServer(router), - tokens: tokensCollection, - users: usersCollection, - clients: clientsCollection, - groups: groupsCollection, - publicKey: publicKey, - } - - tokenRouter := tokens.NewRouter( - tokensCollection, - usersCollection, - clientsCollection, - publicKey, - privateKey, - uaa) - - router.Handle("/Users{a:.*}", users.NewRouter(usersCollection, tokensCollection)) - router.Handle("/Groups{a:.*}", groups.NewRouter(groupsCollection, tokensCollection)) - router.Handle("/oauth/clients{a:.*}", clients.NewRouter(clientsCollection, tokensCollection)) - router.Handle("/oauth{a:.*}", tokenRouter) - router.Handle("/token_key{a:.*}", tokenRouter) - - return uaa -} - -func (s *UAA) PublicKey() string { - return s.publicKey -} - -func (s *UAA) PrivateKey() string { - return s.privateKey -} - -// Start will cause the HTTP server to bind to a port -// and start serving requests. -func (s *UAA) Start() { - s.server.Start() -} - -// Close will cause the HTTP server to stop serving -// requests and close its connection. -func (s *UAA) Close() { - s.server.Close() -} - -// Reset will clear all internal resource state within -// the server. This means that all users, clients, and -// groups will be deleted. -func (s *UAA) Reset() { - s.users.Clear() - s.clients.Clear() - s.groups.Clear() -} - -// URL returns the url that the server is hosted on. -func (s *UAA) URL() string { - return s.server.URL -} - -// SetDefaultScopes allows the default scopes applied to a -// user to be configured. -func (s *UAA) SetDefaultScopes(scopes []string) { - s.tokens.DefaultScopes = scopes -} // TODO: move this configuration onto the Config - -// ResetDefaultScopes resets the default scopes back to their -// original values. -func (s *UAA) ResetDefaultScopes() { - s.tokens.DefaultScopes = defaultScopes -} - -// UserTokenFor returns a user token with the given id, -// scopes, and audiences. -func (s *UAA) UserTokenFor(userID string, scopes, audiences []string) string { - // TODO: remove from API so that tokens are fetched like - // they would be with a real UAA server. - - return s.tokens.Encrypt(domain.Token{ - UserID: userID, - Scopes: scopes, - Audiences: audiences, - }) -} diff --git a/vendor/github.com/rcrowley/go-metrics/validate.sh b/vendor/github.com/rcrowley/go-metrics/validate.sh old mode 100755 new mode 100644 diff --git a/vendor/golang.org/x/net/html/atom/atom.go b/vendor/golang.org/x/net/html/atom/atom.go index 227404bd..cd0a8ac1 100644 --- a/vendor/golang.org/x/net/html/atom/atom.go +++ b/vendor/golang.org/x/net/html/atom/atom.go @@ -15,7 +15,7 @@ // whether atom.H1 < atom.H2 may also change. The codes are not guaranteed to // be dense. The only guarantees are that e.g. looking up "div" will yield // atom.Div, calling atom.Div.String will return "div", and atom.Div != 0. -package atom +package atom // import "golang.org/x/net/html/atom" // Atom is an integer code for a string. The zero value maps to "". type Atom uint32 diff --git a/vendor/golang.org/x/net/html/doc.go b/vendor/golang.org/x/net/html/doc.go index b453fe1e..94f49687 100644 --- a/vendor/golang.org/x/net/html/doc.go +++ b/vendor/golang.org/x/net/html/doc.go @@ -93,7 +93,7 @@ The relevant specifications include: https://html.spec.whatwg.org/multipage/syntax.html and https://html.spec.whatwg.org/multipage/syntax.html#tokenization */ -package html +package html // import "golang.org/x/net/html" // The tokenization algorithm implemented by this package is not a line-by-line // transliteration of the relatively verbose state-machine in the WHATWG diff --git a/vendor/gopkg.in/gorp.v1/test_all.sh b/vendor/gopkg.in/gorp.v1/test_all.sh old mode 100755 new mode 100644 diff --git a/vendor/modules.txt b/vendor/modules.txt new file mode 100644 index 00000000..246a1e4a --- /dev/null +++ b/vendor/modules.txt @@ -0,0 +1,78 @@ +# github.com/DATA-DOG/go-sqlmock v0.0.0-20180221072120-a6b4b164c6d1 +github.com/DATA-DOG/go-sqlmock +# github.com/PuerkitoBio/goquery v0.0.0-20150328133056-269246d9e7d4 +github.com/PuerkitoBio/goquery +# github.com/andybalholm/cascadia v0.0.0-20150328005534-54abbbf07a45 +github.com/andybalholm/cascadia +# github.com/chrj/smtpd v0.0.0-20140720195347-c6fe39d4dcdd +github.com/chrj/smtpd +# github.com/dgrijalva/jwt-go v0.0.0-20141103211122-47b263f02057 +github.com/dgrijalva/jwt-go +# github.com/go-sql-driver/mysql v1.2.0 +github.com/go-sql-driver/mysql +# github.com/gorilla/context v0.0.0-20140306180640-1be7a086a5fd +github.com/gorilla/context +# github.com/gorilla/mux v0.0.0-20131205071822-9ede152210fa +github.com/gorilla/mux +# github.com/onsi/ginkgo v0.0.0-20141213001613-291f28e66dd2 +github.com/onsi/ginkgo +github.com/onsi/ginkgo/config +github.com/onsi/ginkgo/internal/codelocation +github.com/onsi/ginkgo/internal/failer +github.com/onsi/ginkgo/internal/remote +github.com/onsi/ginkgo/internal/suite +github.com/onsi/ginkgo/internal/testingtproxy +github.com/onsi/ginkgo/internal/writer +github.com/onsi/ginkgo/reporters +github.com/onsi/ginkgo/reporters/stenographer +github.com/onsi/ginkgo/types +github.com/onsi/ginkgo/internal/containernode +github.com/onsi/ginkgo/internal/leafnodes +github.com/onsi/ginkgo/internal/spec +github.com/onsi/ginkgo/internal/specrunner +# github.com/onsi/gomega v0.0.0-20150530211311-d6c945f9fdbf +github.com/onsi/gomega +github.com/onsi/gomega/internal/assertion +github.com/onsi/gomega/internal/asyncassertion +github.com/onsi/gomega/internal/testingtsupport +github.com/onsi/gomega/matchers +github.com/onsi/gomega/types +github.com/onsi/gomega/format +github.com/onsi/gomega/matchers/support/goraph/bipartitegraph +github.com/onsi/gomega/matchers/support/goraph/edge +github.com/onsi/gomega/matchers/support/goraph/node +github.com/onsi/gomega/matchers/support/goraph/util +# github.com/pivotal-cf-experimental/rainmaker v0.0.0-20160401052143-d533d01b7c52 +github.com/pivotal-cf-experimental/rainmaker +github.com/pivotal-cf-experimental/rainmaker/internal/documents +github.com/pivotal-cf-experimental/rainmaker/internal/network +# github.com/pivotal-cf-experimental/warrant v0.0.0-20170119140040-e3c3c7f4dbd0 +github.com/pivotal-cf-experimental/warrant +github.com/pivotal-cf-experimental/warrant/internal/documents +github.com/pivotal-cf-experimental/warrant/internal/network +# github.com/pivotal-cf/uaa-sso-golang v0.0.0-20141119184546-0b91e8ad4bb6 +github.com/pivotal-cf/uaa-sso-golang/uaa +# github.com/pivotal-golang/conceal v0.0.0-20141120010127-31656578115c +github.com/pivotal-golang/conceal +# github.com/pivotal-golang/lager v0.0.0-20150428205713-c88fa6d6c4d2 +github.com/pivotal-golang/lager +# github.com/rcrowley/go-metrics v0.0.0-20180125231941-8732c616f529 +github.com/rcrowley/go-metrics +github.com/rcrowley/go-metrics/exp +# github.com/rubenv/sql-migrate v0.0.0-20150713140751-53184e1edfb4 +github.com/rubenv/sql-migrate +github.com/rubenv/sql-migrate/sqlparse +# github.com/ryanmoran/stack v0.0.0-20140916210556-3debe7a5953a +github.com/ryanmoran/stack +# github.com/ryanmoran/viron v0.0.0-20150922192335-f3865b4826c8 +github.com/ryanmoran/viron +# golang.org/x/net v0.0.0-20150320034621-7dbad50ab5b3 +golang.org/x/net/html +golang.org/x/net/html/atom +# gopkg.in/alexcesaro/quotedprintable.v1 v1.0.0-20141111223934-dacd4576c5aa +gopkg.in/alexcesaro/quotedprintable.v1 +gopkg.in/alexcesaro/quotedprintable.v1/internal +# gopkg.in/gomail.v1 v1.0.0-20150120141108-d7294067b867 +gopkg.in/gomail.v1 +# gopkg.in/gorp.v1 v1.7.1 +gopkg.in/gorp.v1