diff --git a/vendor/github.com/DATA-DOG/godog/CHANGELOG.md b/vendor/github.com/DATA-DOG/godog/CHANGELOG.md deleted file mode 100644 index 7ff33be69e1..00000000000 --- a/vendor/github.com/DATA-DOG/godog/CHANGELOG.md +++ /dev/null @@ -1,42 +0,0 @@ -# Change LOG - -**2016-06-14** - **v0.5.0** -- godog now uses **go tool compile** and **go tool link** to support - vendor directory dependencies. It also compiles test executable the same - way as standard **go test** utility. With this change, only go - versions from **1.5** are now supported. - -**2016-06-01** -- parse flags in main command, to show version and help without needing - to compile test package and buildable go sources. - -**2016-05-28** -- show nicely formatted called step func name and file path - -**2016-05-26** -- pack gherkin dependency in a subpackage to prevent compatibility - conflicts in the future. If recently upgraded, probably you will need to - reference gherkin as `github.com/DATA-DOG/godog/gherkin` instead. - -**2016-05-25** -- refactored test suite build tooling in order to use standard **go test** - tool. Which allows to compile package with godog runner script in **go** - idiomatic way. It also supports all build environment options as usual. -- **godog.Run** now returns an **int** exit status. It was not returning - anything before, so there is no compatibility breaks. - -**2016-03-04** -- added **junit** compatible output formatter, which prints **xml** - results to **os.Stdout** -- fixed #14 which skipped printing background steps when there was - scenario outline in feature. - -**2015-07-03** -- changed **godog.Suite** from interface to struct. Context registration should be updated accordingly. The reason -for change: since it exports the same methods and there is no need to mock a function in tests, there is no -obvious reason to keep an interface. -- in order to support running suite concurrently, needed to refactor an entry point of application. The **Run** method -now is a func of godog package which initializes and run the suite (or more suites). Method **New** is removed. This -change made godog a little cleaner. -- renamed **RegisterFormatter** func to **Format** to be more consistent. - diff --git a/vendor/github.com/DATA-DOG/godog/LICENSE b/vendor/github.com/DATA-DOG/godog/LICENSE deleted file mode 100644 index 3da144716dd..00000000000 --- a/vendor/github.com/DATA-DOG/godog/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -The three clause BSD license (http://en.wikipedia.org/wiki/BSD_licenses) - -Copyright (c) 2015-2016, DataDog.lt team -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -* The name DataDog.lt may not be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT, -INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY -OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/DATA-DOG/godog/Makefile b/vendor/github.com/DATA-DOG/godog/Makefile deleted file mode 100644 index 042067df4c3..00000000000 --- a/vendor/github.com/DATA-DOG/godog/Makefile +++ /dev/null @@ -1,27 +0,0 @@ -.PHONY: test gherkin bump - -VERS := $(shell grep 'const Version' -m 1 godog.go | awk -F\" '{print $$2}') - -test: - @echo "running all tests" - @go install ./... - @go fmt ./... - @golint github.com/DATA-DOG/godog - @golint github.com/DATA-DOG/godog/cmd/godog - go vet ./... - go test - godog -f progress -c 4 - -gherkin: - @if [ -z "$(VERS)" ]; then echo "Provide gherkin version like: 'VERS=commit-hash'"; exit 1; fi - @rm -rf gherkin - @mkdir gherkin - @curl -s -L https://github.com/cucumber/gherkin-go/tarball/$(VERS) | tar -C gherkin -zx --strip-components 1 - @rm -rf gherkin/{.travis.yml,.gitignore,*_test.go,gherkin-generate*,*.razor,*.jq,Makefile,CONTRIBUTING.md} - -bump: - @if [ -z "$(VERSION)" ]; then echo "Provide version like: 'VERSION=$(VERS) make bump'"; exit 1; fi - @echo "bumping version from: $(VERS) to $(VERSION)" - @sed -i.bak 's/$(VERS)/$(VERSION)/g' godog.go - @sed -i.bak 's/$(VERS)/$(VERSION)/g' examples/api/version.feature - @find . -name '*.bak' | xargs rm diff --git a/vendor/github.com/DATA-DOG/godog/README.md b/vendor/github.com/DATA-DOG/godog/README.md deleted file mode 100644 index cc3149bb604..00000000000 --- a/vendor/github.com/DATA-DOG/godog/README.md +++ /dev/null @@ -1,277 +0,0 @@ -[![Build Status](https://travis-ci.org/DATA-DOG/godog.svg?branch=master)](https://travis-ci.org/DATA-DOG/godog) -[![GoDoc](https://godoc.org/github.com/DATA-DOG/godog?status.svg)](https://godoc.org/github.com/DATA-DOG/godog) - -# Godog - -

Godog logo

- -**The API is likely to change a few times before we reach 1.0.0** - -Package godog is the official Cucumber BDD framework for Golang, it merges -specification and test documentation into one cohesive whole. The author -is a core member of [cucumber team](https://github.com/cucumber). - -What is behavior-driven development, you ask? It’s the idea that you start -by writing human-readable sentences that describe a feature of your -application and how it should work, and only then implement this behavior -in software. - -The project is inspired by [behat][behat] and [cucumber][cucumber] and is -based on cucumber [gherkin3 parser][gherkin]. - -**Godog** does not intervene with the standard **go test** command and its -behavior. You can leverage both frameworks to functionally test your -application while maintaining all test related source code in **_test.go** -files. - -**Godog** acts similar compared to **go test** command. It uses go -compiler and linker tool in order to produce test executable. Godog -contexts needs to be exported same as Test functions for go test. - -**Godog** ships gherkin parser dependency as a subpackage. This will -ensure that it is always compatible with the installed version of godog. -So in general there are no vendor dependencies needed for installation. - -The following about section was taken from -[cucumber](https://cucumber.io/) homepage. - -## About - -#### A single source of truth - -Cucumber merges specification and test documentation into one cohesive whole. - -#### Living documentation - -Because they're automatically tested by Cucumber, your specifications are -always bang up-to-date. - -#### Focus on the customer - -Business and IT don't always understand each other. Cucumber's executable -specifications encourage closer collaboration, helping teams keep the -business goal in mind at all times. - -#### Less rework - -When automated testing is this much fun, teams can easily protect -themselves from costly regressions. - -### Install - - go get github.com/DATA-DOG/godog/cmd/godog - -### Example - -The following example can be [found -here](/examples/godogs). - -#### Step 1 - -Given we create a new go package **$GOPATH/src/godogs**. From now on, this -is our work directory `cd $GOPATH/src/godogs`. - -Imagine we have a **godog cart** to serve godogs for lunch. First of all, -we describe our feature in plain text - `vim -$GOPATH/src/godogs/features/godogs.feature`: - -``` gherkin -# file: $GOPATH/src/godogs/features/godogs.feature -Feature: eat godogs - In order to be happy - As a hungry gopher - I need to be able to eat godogs - - Scenario: Eat 5 out of 12 - Given there are 12 godogs - When I eat 5 - Then there should be 7 remaining -``` - -As a developer, your work is done as soon as you’ve made the program behave as -described in the Scenario. - -**NOTE:** same as **go test** godog respects package level isolation. All -your step definitions should be in your tested package root directory. In -this case - `$GOPATH/src/godogs` - -#### Step 2 - -If godog is installed in your GOPATH. We can run `godog` inside the -**$GOPATH/src/godogs** directory. You should see that the steps are -undefined: - -![Undefined step snippets](/screenshots/undefined.png?raw=true) - -If we wish to vendor godog dependency, we can do it as usual, using tools -you prefer: - - git clone https://github.com/DATA-DOG/godog.git $GOPATH/src/godogs/vendor/github.com/DATA-DOG/godog - -It gives you undefined step snippets to implement in your test context. -You may copy these snippets into your `godogs_test.go` file. - -Our directory structure should now look like: - -![Directory layout](/screenshots/dir-tree.png?raw=true) - -If you copy the snippets into our test file and run godog again. We should -see the step definition is now pending: - -![Pending step definition](/screenshots/pending.png?raw=true) - -You may change **ErrPending** to **nil** and the scenario will -pass successfully. - -Since we need a working implementation, we may start by implementing only what is necessary. - -#### Step 3 - -We only need a number of **godogs** for now. Lets keep it simple. - -``` go -/* file: $GOPATH/src/godogs/godogs.go */ -package main - -// Godogs available to eat -var Godogs int - -func main() { /* usual main func */ } -``` - -#### Step 4 - -Now lets implement our step definitions, which we can copy from generated -console output snippets in order to test our feature requirements: - -``` go -/* file: $GOPATH/src/godogs/godogs_test.go */ -package main - -import ( - "fmt" - - "github.com/DATA-DOG/godog" -) - -func thereAreGodogs(available int) error { - Godogs = available - return nil -} - -func iEat(num int) error { - if Godogs < num { - return fmt.Errorf("you cannot eat %d godogs, there are %d available", num, Godogs) - } - Godogs -= num - return nil -} - -func thereShouldBeRemaining(remaining int) error { - if Godogs != remaining { - return fmt.Errorf("expected %d godogs to be remaining, but there is %d", remaining, Godogs) - } - return nil -} - -func FeatureContext(s *godog.Suite) { - s.Step(`^there are (\d+) godogs$`, thereAreGodogs) - s.Step(`^I eat (\d+)$`, iEat) - s.Step(`^there should be (\d+) remaining$`, thereShouldBeRemaining) - - s.BeforeScenario(func(interface{}) { - Godogs = 0 // clean the state before every scenario - }) -} -``` - -Now when you run the `godog` again, you should see: - -![Passed suite](/screenshots/passed.png?raw=true) - -**Note:** we have hooked to **BeforeScenario** event in order to reset state. You may hook into -more events, like **AfterStep** to test against an error and print more details about the error -or state before failure. Or **BeforeSuite** to prepare a database. - -#### Running Godog with go test - -There was a question asked whether it is possible to run **godog** from -**go test** command. And the answer is yes. You can run it using go -[TestMain](https://golang.org/pkg/testing/#hdr-Main) func available since -go 1.4. In this case it is not necessary to have **godog** command -installed. See the following example: - -``` go -/* file: $GOPATH/src/godogs/godogs_test.go */ -package main - -import ( - "flag" - "os" - "testing" - - "github.com/DATA-DOG/godog" -) - -func TestMain(m *testing.M) { - args := os.Args - // args for godog - os.Args = []string{ - args[0], - "-f", "progress", - "features", - } - - status := godog.Run(func(s *godog.Suite) { - FeatureContext(s) - }) - - os.Args = args - flag.Parse() - - if st := m.Run(); st > status { - status = st - } - os.Exit(status) -} -``` - -### References and Tutorials - -- [how to use godog by semaphoreci](https://semaphoreci.com/community/tutorials/how-to-use-godog-for-behavior-driven-development-in-go) - -### Documentation - -See [godoc][godoc] for general API details. -See **.travis.yml** for supported **go** versions. -See `godog -h` for general command options. - -See implementation examples: - -- [rest API server](/examples/api) -- [rest API with Database](/examples/db) -- [godogs](/examples/godogs) - -### FAQ - -**Q:** Where can I configure common options globally? -**A:** You can't. Alias your common or project based commands: `alias godog-wip="godog --format=progress --tags=@wip"` - -### Contributions - -Feel free to open a pull request. Note, if you wish to contribute an extension to public (exported methods or types) - -please open an issue before to discuss whether these changes can be accepted. All backward incompatible changes are -and will be treated cautiously. - -### License - -All package dependencies are **MIT** or **BSD** licensed. - -**Godog** is licensed under the [three clause BSD license][license] - -[godoc]: http://godoc.org/github.com/DATA-DOG/godog "Documentation on godoc" -[golang]: https://golang.org/ "GO programming language" -[behat]: http://docs.behat.org/ "Behavior driven development framework for PHP" -[cucumber]: https://cucumber.io/ "Behavior driven development framework for Ruby" -[gherkin]: https://github.com/cucumber/gherkin-go "Gherkin3 parser for GO" -[license]: http://en.wikipedia.org/wiki/BSD_licenses "The three clause BSD license" diff --git a/vendor/github.com/DATA-DOG/godog/ast.go b/vendor/github.com/DATA-DOG/godog/ast.go deleted file mode 100644 index fe275e039c3..00000000000 --- a/vendor/github.com/DATA-DOG/godog/ast.go +++ /dev/null @@ -1,31 +0,0 @@ -package godog - -import "go/ast" - -func astContexts(f *ast.File) []string { - var contexts []string - for _, d := range f.Decls { - switch fun := d.(type) { - case *ast.FuncDecl: - for _, param := range fun.Type.Params.List { - switch expr := param.Type.(type) { - case *ast.StarExpr: - switch x := expr.X.(type) { - case *ast.Ident: - if x.Name == "Suite" { - contexts = append(contexts, fun.Name.Name) - } - case *ast.SelectorExpr: - switch t := x.X.(type) { - case *ast.Ident: - if t.Name == "godog" && x.Sel.Name == "Suite" { - contexts = append(contexts, fun.Name.Name) - } - } - } - } - } - } - } - return contexts -} diff --git a/vendor/github.com/DATA-DOG/godog/builder.go b/vendor/github.com/DATA-DOG/godog/builder.go deleted file mode 100644 index 6686e027a28..00000000000 --- a/vendor/github.com/DATA-DOG/godog/builder.go +++ /dev/null @@ -1,332 +0,0 @@ -package godog - -import ( - "bytes" - "fmt" - "go/build" - "go/parser" - "go/token" - "io/ioutil" - "os" - "os/exec" - "path" - "path/filepath" - "strings" - "text/template" - "time" - "unicode" -) - -var compiler = filepath.Join(build.ToolDir, "compile") -var linker = filepath.Join(build.ToolDir, "link") -var gopaths = filepath.SplitList(build.Default.GOPATH) -var goarch = build.Default.GOARCH -var goos = build.Default.GOOS - -var godogImportPath = "github.com/DATA-DOG/godog" -var runnerTemplate = template.Must(template.New("testmain").Parse(`package main - -import ( - "github.com/DATA-DOG/godog" - {{if .Contexts}}_test "{{.ImportPath}}"{{end}} - "os" -) - -func main() { - status := godog.Run(func (suite *godog.Suite) { - {{range .Contexts}} - _test.{{ . }}(suite) - {{end}} - }) - os.Exit(status) -}`)) - -// Build creates a test package like go test command. -// If there are no go files in tested directory, then -// it simply builds a godog executable to scan features. -// -// If there are go test files, it first builds a test -// package with standard go test command. -// -// Finally it generates godog suite executable which -// registers exported godog contexts from the test files -// of tested package. -// -// Returns the path to generated executable -func Build() (string, error) { - abs, err := filepath.Abs(".") - if err != nil { - return "", err - } - - bin := filepath.Join(abs, "godog.test") - // suffix with .exe for windows - if goos == "windows" { - bin += ".exe" - } - - // we allow package to be nil, if godog is run only when - // there is a feature file in empty directory - pkg := importPackage(abs) - src, anyContexts, err := buildTestMain(pkg) - if err != nil { - return bin, err - } - - workdir := fmt.Sprintf(filepath.Join("%s", "godog-%d"), os.TempDir(), time.Now().UnixNano()) - testdir := workdir - - // if none of test files exist, or there are no contexts found - // we will skip test package compilation, since it is useless - if anyContexts { - // first of all compile test package dependencies - // that will save was many compilations for dependencies - // go does it better - out, err := exec.Command("go", "test", "-i").CombinedOutput() - if err != nil { - return bin, fmt.Errorf("failed to compile package %s:\n%s", pkg.Name, string(out)) - } - - // let go do the dirty work and compile test - // package with it's dependencies. Older go - // versions does not accept existing file output - // so we create a temporary executable which will - // removed. - temp := fmt.Sprintf(filepath.Join("%s", "temp-%d.test"), os.TempDir(), time.Now().UnixNano()) - - // builds and compile the tested package. - // generated test executable will be removed - // since we do not need it for godog suite. - // we also print back the temp WORK directory - // go has built. We will reuse it for our suite workdir. - out, err = exec.Command("go", "test", "-c", "-work", "-o", temp).CombinedOutput() - if err != nil { - return bin, fmt.Errorf("failed to compile tested package %s:\n%s", pkg.Name, string(out)) - } - defer os.Remove(temp) - - // extract go-build temporary directory as our workdir - workdir = strings.TrimSpace(string(out)) - if !strings.HasPrefix(workdir, "WORK=") { - return bin, fmt.Errorf("expected WORK dir path, but got: %s", workdir) - } - workdir = strings.Replace(workdir, "WORK=", "", 1) - testdir = filepath.Join(workdir, pkg.ImportPath, "_test") - } else { - // still need to create temporary workdir - if err = os.MkdirAll(testdir, 0755); err != nil { - return bin, err - } - } - defer os.RemoveAll(workdir) - - // replace _testmain.go file with our own - testmain := filepath.Join(testdir, "_testmain.go") - err = ioutil.WriteFile(testmain, src, 0644) - if err != nil { - return bin, err - } - - // godog library may not be imported in tested package - // but we need it for our testmain package. - // So we look it up in available source paths - // including vendor directory, supported since 1.5. - try := maybeVendorPaths(abs) - for _, d := range build.Default.SrcDirs() { - try = append(try, filepath.Join(d, godogImportPath)) - } - godogPkg, err := locatePackage(try) - if err != nil { - return bin, err - } - - // make sure godog package archive is installed, gherkin - // will be installed as dependency of godog - cmd := exec.Command("go", "install", godogPkg.ImportPath) - cmd.Env = os.Environ() - out, err := cmd.CombinedOutput() - if err != nil { - return bin, fmt.Errorf("failed to install godog package:\n%s", string(out)) - } - - // collect all possible package dirs, will be - // used for includes and linker - pkgDirs := []string{workdir, testdir} - for _, gopath := range gopaths { - pkgDirs = append(pkgDirs, filepath.Join(gopath, "pkg", goos+"_"+goarch)) - } - pkgDirs = uniqStringList(pkgDirs) - - // compile godog testmain package archive - // we do not depend on CGO so a lot of checks are not necessary - testMainPkgOut := filepath.Join(testdir, "main.a") - args := []string{ - "-o", testMainPkgOut, - // "-trimpath", workdir, - "-p", "main", - "-complete", - } - // if godog library is in vendor directory - // link it with import map - if i := strings.LastIndex(godogPkg.ImportPath, "vendor/"); i != -1 { - args = append(args, "-importmap", godogImportPath+"="+godogPkg.ImportPath) - } - for _, inc := range pkgDirs { - args = append(args, "-I", inc) - } - args = append(args, "-pack", testmain) - cmd = exec.Command(compiler, args...) - cmd.Env = os.Environ() - out, err = cmd.CombinedOutput() - if err != nil { - return bin, fmt.Errorf("failed to compile testmain package:\n%s", string(out)) - } - - // link test suite executable - args = []string{ - "-o", bin, - "-buildmode=exe", - } - for _, link := range pkgDirs { - args = append(args, "-L", link) - } - args = append(args, testMainPkgOut) - cmd = exec.Command(linker, args...) - cmd.Env = os.Environ() - - out, err = cmd.CombinedOutput() - if err != nil { - msg := `failed to link test executable: - reason: %s - command: %s` - return bin, fmt.Errorf(msg, string(out), linker+" '"+strings.Join(args, "' '")+"'") - } - - return bin, nil -} - -func locatePackage(try []string) (*build.Package, error) { - for _, p := range try { - abs, err := filepath.Abs(p) - if err != nil { - continue - } - pkg, err := build.ImportDir(abs, 0) - if err != nil { - continue - } - return pkg, nil - } - return nil, fmt.Errorf("failed to find godog package in any of:\n%s", strings.Join(try, "\n")) -} - -func importPackage(dir string) *build.Package { - pkg, _ := build.ImportDir(dir, 0) - - // normalize import path for local import packages - // taken from go source code - // see: https://github.com/golang/go/blob/go1.7rc5/src/cmd/go/pkg.go#L279 - if pkg != nil && pkg.ImportPath == "." { - pkg.ImportPath = path.Join("_", strings.Map(makeImportValid, filepath.ToSlash(dir))) - } - - return pkg -} - -// from go src -func makeImportValid(r rune) rune { - // Should match Go spec, compilers, and ../../go/parser/parser.go:/isValidImport. - const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD" - if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) { - return '_' - } - return r -} - -func uniqStringList(strs []string) (unique []string) { - uniq := make(map[string]void, len(strs)) - for _, s := range strs { - if _, ok := uniq[s]; !ok { - uniq[s] = void{} - unique = append(unique, s) - } - } - return -} - -// buildTestMain if given package is valid -// it scans test files for contexts -// and produces a testmain source code. -func buildTestMain(pkg *build.Package) ([]byte, bool, error) { - var contexts []string - var importPath string - name := "main" - if nil != pkg { - ctxs, err := processPackageTestFiles( - pkg.TestGoFiles, - pkg.XTestGoFiles, - ) - if err != nil { - return nil, false, err - } - contexts = ctxs - importPath = pkg.ImportPath - name = pkg.Name - } - - data := struct { - Name string - Contexts []string - ImportPath string - }{name, contexts, importPath} - - var buf bytes.Buffer - if err := runnerTemplate.Execute(&buf, data); err != nil { - return nil, len(contexts) > 0, err - } - return buf.Bytes(), len(contexts) > 0, nil -} - -// maybeVendorPaths determines possible vendor paths -// which goes levels down from given directory -// until it reaches GOPATH source dir -func maybeVendorPaths(dir string) (paths []string) { - for _, gopath := range gopaths { - gopath = filepath.Join(gopath, "src") - for strings.HasPrefix(dir, gopath) && dir != gopath { - paths = append(paths, filepath.Join(dir, "vendor", godogImportPath)) - dir = filepath.Dir(dir) - } - } - return -} - -// processPackageTestFiles runs through ast of each test -// file pack and looks for godog suite contexts to register -// on run -func processPackageTestFiles(packs ...[]string) ([]string, error) { - var ctxs []string - fset := token.NewFileSet() - for _, pack := range packs { - for _, testFile := range pack { - node, err := parser.ParseFile(fset, testFile, nil, 0) - if err != nil { - return ctxs, err - } - - ctxs = append(ctxs, astContexts(node)...) - } - } - var failed []string - for _, ctx := range ctxs { - runes := []rune(ctx) - if unicode.IsLower(runes[0]) { - expected := append([]rune{unicode.ToUpper(runes[0])}, runes[1:]...) - failed = append(failed, fmt.Sprintf("%s - should be: %s", ctx, string(expected))) - } - } - if len(failed) > 0 { - return ctxs, fmt.Errorf("godog contexts must be exported:\n\t%s", strings.Join(failed, "\n\t")) - } - return ctxs, nil -} diff --git a/vendor/github.com/DATA-DOG/godog/flags.go b/vendor/github.com/DATA-DOG/godog/flags.go deleted file mode 100644 index 69687263b7a..00000000000 --- a/vendor/github.com/DATA-DOG/godog/flags.go +++ /dev/null @@ -1,133 +0,0 @@ -package godog - -import ( - "flag" - "fmt" - "strings" -) - -var descFeaturesArgument = "Optional feature(s) to run. Can be:\n" + - s(4) + "- dir " + cl("(features/)", yellow) + "\n" + - s(4) + "- feature " + cl("(*.feature)", yellow) + "\n" + - s(4) + "- scenario at specific line " + cl("(*.feature:10)", yellow) + "\n" + - "If no feature paths are listed, suite tries " + cl("features", yellow) + " path by default.\n" - -var descConcurrencyOption = "Run the test suite with concurrency level:\n" + - s(4) + "- " + cl(`= 1`, yellow) + ": supports all types of formats.\n" + - s(4) + "- " + cl(`>= 2`, yellow) + ": only supports " + cl("progress", yellow) + ". Note, that\n" + - s(4) + "your context needs to support parallel execution." - -var descTagsOption = "Filter scenarios by tags. Expression can be:\n" + - s(4) + "- " + cl(`"@wip"`, yellow) + ": run all scenarios with wip tag\n" + - s(4) + "- " + cl(`"~@wip"`, yellow) + ": exclude all scenarios with wip tag\n" + - s(4) + "- " + cl(`"@wip && ~@new"`, yellow) + ": run wip scenarios, but exclude new\n" + - s(4) + "- " + cl(`"@wip,@undone"`, yellow) + ": run wip or undone scenarios" - -// FlagSet allows to manage flags by external suite runner -func FlagSet(format, tags *string, defs, sof, noclr *bool, cr *int) *flag.FlagSet { - descFormatOption := "How to format tests output. Available formats:\n" - for _, f := range formatters { - descFormatOption += s(4) + "- " + cl(f.name, yellow) + ": " + f.description + "\n" - } - descFormatOption = strings.TrimSpace(descFormatOption) - - set := flag.NewFlagSet("godog", flag.ExitOnError) - set.StringVar(format, "format", "pretty", descFormatOption) - set.StringVar(format, "f", "pretty", descFormatOption) - set.StringVar(tags, "tags", "", descTagsOption) - set.StringVar(tags, "t", "", descTagsOption) - set.IntVar(cr, "concurrency", 1, descConcurrencyOption) - set.IntVar(cr, "c", 1, descConcurrencyOption) - set.BoolVar(defs, "definitions", false, "Print all available step definitions.") - set.BoolVar(defs, "d", false, "Print all available step definitions.") - set.BoolVar(sof, "stop-on-failure", false, "Stop processing on first failed scenario.") - set.BoolVar(noclr, "no-colors", false, "Disable ansi colors.") - set.Usage = usage(set) - return set -} - -type flagged struct { - short, long, descr, dflt string -} - -func (f *flagged) name() string { - var name string - switch { - case len(f.short) > 0 && len(f.long) > 0: - name = fmt.Sprintf("-%s, --%s", f.short, f.long) - case len(f.long) > 0: - name = fmt.Sprintf("--%s", f.long) - case len(f.short) > 0: - name = fmt.Sprintf("-%s", f.short) - } - if f.dflt != "true" && f.dflt != "false" { - name += "=" + f.dflt - } - return name -} - -func usage(set *flag.FlagSet) func() { - return func() { - var list []*flagged - var longest int - set.VisitAll(func(f *flag.Flag) { - var fl *flagged - for _, flg := range list { - if flg.descr == f.Usage { - fl = flg - break - } - } - if nil == fl { - fl = &flagged{ - dflt: f.DefValue, - descr: f.Usage, - } - list = append(list, fl) - } - if len(f.Name) > 2 { - fl.long = f.Name - } else { - fl.short = f.Name - } - }) - - for _, f := range list { - if len(f.name()) > longest { - longest = len(f.name()) - } - } - - // prints an option or argument with a description, or only description - opt := func(name, desc string) string { - var ret []string - lines := strings.Split(desc, "\n") - ret = append(ret, s(2)+cl(name, green)+s(longest+2-len(name))+lines[0]) - if len(lines) > 1 { - for _, ln := range lines[1:] { - ret = append(ret, s(2)+s(longest+2)+ln) - } - } - return strings.Join(ret, "\n") - } - - // --- GENERAL --- - fmt.Println(cl("Usage:", yellow)) - fmt.Printf(s(2) + "godog [options] []\n\n") - // description - fmt.Println("Builds a test package and runs given feature files.") - fmt.Printf("Command should be run from the directory of tested package and contain buildable go source.\n\n") - - // --- ARGUMENTS --- - fmt.Println(cl("Arguments:", yellow)) - // --> features - fmt.Println(opt("features", descFeaturesArgument)) - - // --- OPTIONS --- - fmt.Println(cl("Options:", yellow)) - for _, f := range list { - fmt.Println(opt(f.name(), f.descr)) - } - fmt.Println("") - } -} diff --git a/vendor/github.com/DATA-DOG/godog/fmt.go b/vendor/github.com/DATA-DOG/godog/fmt.go deleted file mode 100644 index 172d10ff0c1..00000000000 --- a/vendor/github.com/DATA-DOG/godog/fmt.go +++ /dev/null @@ -1,387 +0,0 @@ -package godog - -import ( - "bytes" - "fmt" - "reflect" - "regexp" - "strings" - "text/template" - "time" - "unicode" - - "github.com/DATA-DOG/godog/gherkin" -) - -// some snippet formatting regexps -var snippetExprCleanup = regexp.MustCompile("([\\/\\[\\]\\(\\)\\\\^\\$\\.\\|\\?\\*\\+\\'])") -var snippetExprQuoted = regexp.MustCompile("(\\s*|^)\"(?:[^\"]*)\"(\\s+|$)") -var snippetMethodName = regexp.MustCompile("[^a-zA-Z\\_\\ ]") -var snippetNumbers = regexp.MustCompile("(\\d+)") - -var snippetHelperFuncs = template.FuncMap{ - "backticked": func(s string) string { - return "`" + s + "`" - }, -} - -var undefinedSnippetsTpl = template.Must(template.New("snippets").Funcs(snippetHelperFuncs).Parse(` -{{ range . }}func {{ .Method }}({{ .Args }}) error { - return godog.ErrPending -} - -{{end}}func FeatureContext(s *godog.Suite) { {{ range . }} - s.Step({{ backticked .Expr }}, {{ .Method }}){{end}} -} -`)) - -type undefinedSnippet struct { - Method string - Expr string - argument interface{} // gherkin step argument -} - -type registeredFormatter struct { - name string - fmt Formatter - description string -} - -var formatters []*registeredFormatter - -func findFmt(format string) (f Formatter, err error) { - var names []string - for _, el := range formatters { - if el.name == format { - f = el.fmt - break - } - names = append(names, el.name) - } - - if f == nil { - err = fmt.Errorf(`unregistered formatter name: "%s", use one of: %s`, format, strings.Join(names, ", ")) - } - return -} - -// Format registers a feature suite output -// Formatter as the name and descriptiongiven. -// Formatter is used to represent suite output -func Format(name, description string, f Formatter) { - formatters = append(formatters, ®isteredFormatter{ - name: name, - fmt: f, - description: description, - }) -} - -// Formatter is an interface for feature runner -// output summary presentation. -// -// New formatters may be created to represent -// suite results in different ways. These new -// formatters needs to be registered with a -// godog.Format function call -type Formatter interface { - Feature(*gherkin.Feature, string) - Node(interface{}) - Failed(*gherkin.Step, *StepDef, error) - Passed(*gherkin.Step, *StepDef) - Skipped(*gherkin.Step) - Undefined(*gherkin.Step) - Pending(*gherkin.Step, *StepDef) - Summary() -} - -type stepType int - -const ( - passed stepType = iota - failed - skipped - undefined - pending -) - -func (st stepType) clr() color { - switch st { - case passed: - return green - case failed: - return red - case skipped: - return cyan - default: - return yellow - } -} - -type stepResult struct { - typ stepType - feature *feature - owner interface{} - step *gherkin.Step - def *StepDef - err error -} - -func (f stepResult) line() string { - return fmt.Sprintf("%s:%d", f.feature.Path, f.step.Location.Line) -} - -type basefmt struct { - owner interface{} - indent int - - started time.Time - features []*feature - failed []*stepResult - passed []*stepResult - skipped []*stepResult - undefined []*stepResult - pending []*stepResult -} - -func (f *basefmt) Node(n interface{}) { - switch t := n.(type) { - case *gherkin.TableRow: - f.owner = t - case *gherkin.Scenario: - f.owner = t - } -} - -func (f *basefmt) Feature(ft *gherkin.Feature, p string) { - f.features = append(f.features, &feature{Path: p, Feature: ft}) -} - -func (f *basefmt) Passed(step *gherkin.Step, match *StepDef) { - s := &stepResult{ - owner: f.owner, - feature: f.features[len(f.features)-1], - step: step, - def: match, - typ: passed, - } - f.passed = append(f.passed, s) -} - -func (f *basefmt) Skipped(step *gherkin.Step) { - s := &stepResult{ - owner: f.owner, - feature: f.features[len(f.features)-1], - step: step, - typ: skipped, - } - f.skipped = append(f.skipped, s) -} - -func (f *basefmt) Undefined(step *gherkin.Step) { - s := &stepResult{ - owner: f.owner, - feature: f.features[len(f.features)-1], - step: step, - typ: undefined, - } - f.undefined = append(f.undefined, s) -} - -func (f *basefmt) Failed(step *gherkin.Step, match *StepDef, err error) { - s := &stepResult{ - owner: f.owner, - feature: f.features[len(f.features)-1], - step: step, - def: match, - err: err, - typ: failed, - } - f.failed = append(f.failed, s) -} - -func (f *basefmt) Pending(step *gherkin.Step, match *StepDef) { - s := &stepResult{ - owner: f.owner, - feature: f.features[len(f.features)-1], - step: step, - def: match, - typ: pending, - } - f.pending = append(f.pending, s) -} - -func (f *basefmt) Summary() { - var total, passed, undefined int - for _, ft := range f.features { - for _, def := range ft.ScenarioDefinitions { - switch t := def.(type) { - case *gherkin.Scenario: - total++ - case *gherkin.ScenarioOutline: - for _, ex := range t.Examples { - if examples, hasExamples := examples(ex); hasExamples { - total += len(examples.TableBody) - } - } - } - } - } - passed = total - var owner interface{} - for _, undef := range f.undefined { - if owner != undef.owner { - undefined++ - owner = undef.owner - } - } - - var steps, parts, scenarios []string - nsteps := len(f.passed) + len(f.failed) + len(f.skipped) + len(f.undefined) + len(f.pending) - if len(f.passed) > 0 { - steps = append(steps, cl(fmt.Sprintf("%d passed", len(f.passed)), green)) - } - if len(f.failed) > 0 { - passed -= len(f.failed) - parts = append(parts, cl(fmt.Sprintf("%d failed", len(f.failed)), red)) - steps = append(steps, parts[len(parts)-1]) - } - if len(f.pending) > 0 { - passed -= len(f.pending) - parts = append(parts, cl(fmt.Sprintf("%d pending", len(f.pending)), yellow)) - steps = append(steps, cl(fmt.Sprintf("%d pending", len(f.pending)), yellow)) - } - if len(f.undefined) > 0 { - passed -= undefined - parts = append(parts, cl(fmt.Sprintf("%d undefined", undefined), yellow)) - steps = append(steps, cl(fmt.Sprintf("%d undefined", len(f.undefined)), yellow)) - } - if len(f.skipped) > 0 { - steps = append(steps, cl(fmt.Sprintf("%d skipped", len(f.skipped)), cyan)) - } - if passed > 0 { - scenarios = append(scenarios, cl(fmt.Sprintf("%d passed", passed), green)) - } - scenarios = append(scenarios, parts...) - elapsed := time.Since(f.started) - - fmt.Println("") - if total == 0 { - fmt.Println("No scenarios") - } else { - fmt.Println(fmt.Sprintf("%d scenarios (%s)", total, strings.Join(scenarios, ", "))) - } - - if nsteps == 0 { - fmt.Println("No steps") - } else { - fmt.Println(fmt.Sprintf("%d steps (%s)", nsteps, strings.Join(steps, ", "))) - } - fmt.Println(elapsed) - - if text := f.snippets(); text != "" { - fmt.Println(cl("\nYou can implement step definitions for undefined steps with these snippets:", yellow)) - fmt.Println(cl(text, yellow)) - } -} - -func (s *undefinedSnippet) Args() (ret string) { - var args []string - var pos, idx int - var breakLoop bool - for !breakLoop { - part := s.Expr[pos:] - ipos := strings.Index(part, "(\\d+)") - spos := strings.Index(part, "\"([^\"]*)\"") - switch { - case spos == -1 && ipos == -1: - breakLoop = true - case spos == -1: - idx++ - pos += ipos + len("(\\d+)") - args = append(args, reflect.Int.String()) - case ipos == -1: - idx++ - pos += spos + len("\"([^\"]*)\"") - args = append(args, reflect.String.String()) - case ipos < spos: - idx++ - pos += ipos + len("(\\d+)") - args = append(args, reflect.Int.String()) - case spos < ipos: - idx++ - pos += spos + len("\"([^\"]*)\"") - args = append(args, reflect.String.String()) - } - } - if s.argument != nil { - idx++ - switch s.argument.(type) { - case *gherkin.DocString: - args = append(args, "*gherkin.DocString") - case *gherkin.DataTable: - args = append(args, "*gherkin.DataTable") - } - } - - var last string - for i, arg := range args { - if last == "" || last == arg { - ret += fmt.Sprintf("arg%d, ", i+1) - } else { - ret = strings.TrimRight(ret, ", ") + fmt.Sprintf(" %s, arg%d, ", last, i+1) - } - last = arg - } - return strings.TrimSpace(strings.TrimRight(ret, ", ") + " " + last) -} - -func (f *basefmt) snippets() string { - if len(f.undefined) == 0 { - return "" - } - - var index int - var snips []*undefinedSnippet - // build snippets - for _, u := range f.undefined { - expr := snippetExprCleanup.ReplaceAllString(u.step.Text, "\\$1") - expr = snippetNumbers.ReplaceAllString(expr, "(\\d+)") - expr = snippetExprQuoted.ReplaceAllString(expr, " \"([^\"]*)\" ") - expr = "^" + strings.TrimSpace(expr) + "$" - - name := snippetNumbers.ReplaceAllString(u.step.Text, " ") - name = snippetExprQuoted.ReplaceAllString(name, " ") - name = snippetMethodName.ReplaceAllString(name, "") - var words []string - for i, w := range strings.Split(name, " ") { - if i != 0 { - w = strings.Title(w) - } else { - w = string(unicode.ToLower(rune(w[0]))) + w[1:] - } - words = append(words, w) - } - name = strings.Join(words, "") - if len(name) == 0 { - index++ - name = fmt.Sprintf("stepDefinition%d", index) - } - - var found bool - for _, snip := range snips { - if snip.Expr == expr { - found = true - break - } - } - if !found { - snips = append(snips, &undefinedSnippet{Method: name, Expr: expr, argument: u.step.Argument}) - } - } - - var buf bytes.Buffer - if err := undefinedSnippetsTpl.Execute(&buf, snips); err != nil { - panic(err) - } - return buf.String() -} diff --git a/vendor/github.com/DATA-DOG/godog/fmt_junit.go b/vendor/github.com/DATA-DOG/godog/fmt_junit.go deleted file mode 100644 index d0130ddbaee..00000000000 --- a/vendor/github.com/DATA-DOG/godog/fmt_junit.go +++ /dev/null @@ -1,185 +0,0 @@ -package godog - -import ( - "encoding/xml" - "fmt" - "io" - "os" - "time" - - "github.com/DATA-DOG/godog/gherkin" -) - -func init() { - Format("junit", "Prints junit compatible xml to stdout", &junitFormatter{ - suite: &junitPackageSuite{ - Name: "main", // @TODO: it should extract package name - TestSuites: make([]*junitTestSuite, 0), - }, - started: time.Now(), - }) -} - -type junitFormatter struct { - suite *junitPackageSuite - - // timing - started time.Time - caseStarted time.Time - featStarted time.Time - - outline *gherkin.ScenarioOutline - outlineExample int -} - -func (j *junitFormatter) Feature(feature *gherkin.Feature, path string) { - testSuite := &junitTestSuite{ - TestCases: make([]*junitTestCase, 0), - Name: feature.Name, - } - - if len(j.suite.TestSuites) > 0 { - j.current().Time = time.Since(j.featStarted).String() - } - j.featStarted = time.Now() - j.suite.TestSuites = append(j.suite.TestSuites, testSuite) -} - -func (j *junitFormatter) Node(node interface{}) { - suite := j.current() - tcase := &junitTestCase{} - - switch t := node.(type) { - case *gherkin.ScenarioOutline: - j.outline = t - return - case *gherkin.Scenario: - tcase.Name = t.Name - suite.Tests++ - j.suite.Tests++ - case *gherkin.Examples: - j.outlineExample = 0 - return - case *gherkin.TableRow: - j.outlineExample++ - tcase.Name = fmt.Sprintf("%s #%d", j.outline.Name, j.outlineExample) - suite.Tests++ - j.suite.Tests++ - default: - return - } - if len(suite.TestCases) > 0 { - suite.current().Time = time.Since(j.caseStarted).String() - } - j.caseStarted = time.Now() - suite.TestCases = append(suite.TestCases, tcase) -} - -func (j *junitFormatter) Failed(step *gherkin.Step, match *StepDef, err error) { - suite := j.current() - suite.Failures++ - j.suite.Failures++ - - tcase := suite.current() - tcase.Status = "failed" - tcase.Failure = &junitFailure{ - Message: fmt.Sprintf("%s %s: %s", step.Type, step.Text, err.Error()), - } -} - -func (j *junitFormatter) Passed(step *gherkin.Step, match *StepDef) { - suite := j.current() - - tcase := suite.current() - tcase.Status = "passed" -} - -func (j *junitFormatter) Skipped(step *gherkin.Step) { -} - -func (j *junitFormatter) Undefined(step *gherkin.Step) { - suite := j.current() - suite.Errors++ - j.suite.Errors++ - - tcase := suite.current() - tcase.Status = "undefined" - tcase.Error = append(tcase.Error, &junitError{ - Type: "undefined", - Message: fmt.Sprintf("%s %s", step.Type, step.Text), - }) -} - -func (j *junitFormatter) Pending(step *gherkin.Step, match *StepDef) { - suite := j.current() - suite.Errors++ - j.suite.Errors++ - - tcase := suite.current() - tcase.Status = "pending" - tcase.Error = append(tcase.Error, &junitError{ - Type: "pending", - Message: fmt.Sprintf("%s %s: TODO: write pending definition", step.Type, step.Text), - }) -} - -func (j *junitFormatter) Summary() { - j.suite.Time = time.Since(j.started).String() - io.WriteString(os.Stdout, xml.Header) - - enc := xml.NewEncoder(os.Stdout) - enc.Indent("", s(2)) - if err := enc.Encode(j.suite); err != nil { - fmt.Println("failed to write junit xml:", err) - } -} - -type junitFailure struct { - Message string `xml:"message,attr"` - Type string `xml:"type,attr,omitempty"` -} - -type junitError struct { - XMLName xml.Name `xml:"error,omitempty"` - Message string `xml:"message,attr"` - Type string `xml:"type,attr"` -} - -type junitTestCase struct { - XMLName xml.Name `xml:"testcase"` - Name string `xml:"name,attr"` - Status string `xml:"status,attr"` - Time string `xml:"time,attr"` - Failure *junitFailure `xml:"failure,omitempty"` - Error []*junitError -} - -type junitTestSuite struct { - XMLName xml.Name `xml:"testsuite"` - Name string `xml:"name,attr"` - Tests int `xml:"tests,attr"` - Skipped int `xml:"skipped,attr"` - Failures int `xml:"failures,attr"` - Errors int `xml:"errors,attr"` - Time string `xml:"time,attr"` - TestCases []*junitTestCase -} - -func (ts *junitTestSuite) current() *junitTestCase { - return ts.TestCases[len(ts.TestCases)-1] -} - -type junitPackageSuite struct { - XMLName xml.Name `xml:"testsuites"` - Name string `xml:"name,attr"` - Tests int `xml:"tests,attr"` - Skipped int `xml:"skipped,attr"` - Failures int `xml:"failures,attr"` - Errors int `xml:"errors,attr"` - Time string `xml:"time,attr"` - TestSuites []*junitTestSuite -} - -func (j *junitFormatter) current() *junitTestSuite { - return j.suite.TestSuites[len(j.suite.TestSuites)-1] -} diff --git a/vendor/github.com/DATA-DOG/godog/fmt_pretty.go b/vendor/github.com/DATA-DOG/godog/fmt_pretty.go deleted file mode 100644 index 8889ce89e5a..00000000000 --- a/vendor/github.com/DATA-DOG/godog/fmt_pretty.go +++ /dev/null @@ -1,395 +0,0 @@ -package godog - -import ( - "fmt" - "math" - "regexp" - "strings" - "time" - "unicode/utf8" - - "github.com/DATA-DOG/godog/gherkin" -) - -func init() { - Format("pretty", "Prints every feature with runtime statuses.", &pretty{ - basefmt: basefmt{ - started: time.Now(), - indent: 2, - }, - }) -} - -var outlinePlaceholderRegexp = regexp.MustCompile("<[^>]+>") - -// a built in default pretty formatter -type pretty struct { - basefmt - - // currently processed - feature *gherkin.Feature - scenario *gherkin.Scenario - outline *gherkin.ScenarioOutline - - // state - bgSteps int - steps int - commentPos int - - // whether scenario or scenario outline keyword was printed - scenarioKeyword bool - - // outline - outlineSteps []*stepResult - outlineNumExample int - outlineNumExamples int -} - -func (f *pretty) Feature(ft *gherkin.Feature, p string) { - if len(f.features) != 0 { - // not a first feature, add a newline - fmt.Println("") - } - f.features = append(f.features, &feature{Path: p, Feature: ft}) - fmt.Println(bcl(ft.Keyword+": ", white) + ft.Name) - if strings.TrimSpace(ft.Description) != "" { - for _, line := range strings.Split(ft.Description, "\n") { - fmt.Println(s(f.indent) + strings.TrimSpace(line)) - } - } - - f.feature = ft - f.scenario = nil - f.outline = nil - f.bgSteps = 0 - if ft.Background != nil { - f.bgSteps = len(ft.Background.Steps) - } -} - -// Node takes a gherkin node for formatting -func (f *pretty) Node(node interface{}) { - f.basefmt.Node(node) - - switch t := node.(type) { - case *gherkin.Examples: - f.outlineNumExamples = len(t.TableBody) - f.outlineNumExample++ - case *gherkin.Scenario: - f.scenario = t - f.outline = nil - f.steps = len(t.Steps) + f.bgSteps - f.scenarioKeyword = false - case *gherkin.ScenarioOutline: - f.outline = t - f.scenario = nil - f.outlineNumExample = -1 - f.scenarioKeyword = false - case *gherkin.TableRow: - f.steps = len(f.outline.Steps) + f.bgSteps - f.outlineSteps = []*stepResult{} - } -} - -// Summary sumarize the feature formatter output -func (f *pretty) Summary() { - // failed steps on background are not scenarios - var failedScenarios []*stepResult - for _, fail := range f.failed { - switch fail.owner.(type) { - case *gherkin.Scenario: - failedScenarios = append(failedScenarios, fail) - case *gherkin.ScenarioOutline: - failedScenarios = append(failedScenarios, fail) - } - } - if len(failedScenarios) > 0 { - fmt.Println("\n--- " + cl("Failed scenarios:", red) + "\n") - var unique []string - for _, fail := range failedScenarios { - var found bool - for _, in := range unique { - if in == fail.line() { - found = true - break - } - } - if !found { - unique = append(unique, fail.line()) - } - } - - for _, fail := range unique { - fmt.Println(" " + cl(fail, red)) - } - } - f.basefmt.Summary() -} - -func (f *pretty) printOutlineExample(outline *gherkin.ScenarioOutline) { - var msg string - clr := green - - ex := outline.Examples[f.outlineNumExample] - example, hasExamples := examples(ex) - if !hasExamples { - // do not print empty examples - return - } - - firstExample := f.outlineNumExamples == len(example.TableBody) - printSteps := firstExample && f.outlineNumExample == 0 - - for i, res := range f.outlineSteps { - // determine example row status - switch { - case res.typ == failed: - msg = res.err.Error() - clr = res.typ.clr() - case res.typ == undefined || res.typ == pending: - clr = res.typ.clr() - case res.typ == skipped && clr == green: - clr = cyan - } - if printSteps { - // in first example, we need to print steps - var text string - ostep := outline.Steps[i] - if res.def != nil { - if m := outlinePlaceholderRegexp.FindAllStringIndex(ostep.Text, -1); len(m) > 0 { - var pos int - for i := 0; i < len(m); i++ { - pair := m[i] - text += cl(ostep.Text[pos:pair[0]], cyan) - text += bcl(ostep.Text[pair[0]:pair[1]], cyan) - pos = pair[1] - } - text += cl(ostep.Text[pos:len(ostep.Text)], cyan) - } else { - text = cl(ostep.Text, cyan) - } - text += s(f.commentPos-f.length(ostep)+1) + cl(fmt.Sprintf("# %s", res.def.funcName()), black) - } else { - text = cl(ostep.Text, cyan) - } - // print the step outline - fmt.Println(s(f.indent*2) + cl(strings.TrimSpace(ostep.Keyword), cyan) + " " + text) - } - } - - cells := make([]string, len(example.TableHeader.Cells)) - max := longest(example) - // an example table header - if firstExample { - fmt.Println("") - fmt.Println(s(f.indent*2) + bcl(example.Keyword+": ", white) + example.Name) - - for i, cell := range example.TableHeader.Cells { - cells[i] = cl(cell.Value, cyan) + s(max[i]-len(cell.Value)) - } - fmt.Println(s(f.indent*3) + "| " + strings.Join(cells, " | ") + " |") - } - - // an example table row - row := example.TableBody[len(example.TableBody)-f.outlineNumExamples] - for i, cell := range row.Cells { - cells[i] = cl(cell.Value, clr) + s(max[i]-len(cell.Value)) - } - fmt.Println(s(f.indent*3) + "| " + strings.Join(cells, " | ") + " |") - - // if there is an error - if msg != "" { - fmt.Println(s(f.indent*4) + bcl(msg, red)) - } -} - -func (f *pretty) printStep(step *gherkin.Step, def *StepDef, c color) { - text := s(f.indent*2) + cl(strings.TrimSpace(step.Keyword), c) + " " - switch { - case def != nil: - if m := (def.Expr.FindStringSubmatchIndex(step.Text))[2:]; len(m) > 0 { - var pos, i int - for pos, i = 0, 0; i < len(m); i++ { - if math.Mod(float64(i), 2) == 0 { - text += cl(step.Text[pos:m[i]], c) - } else { - text += bcl(step.Text[pos:m[i]], c) - } - pos = m[i] - } - text += cl(step.Text[pos:len(step.Text)], c) - } else { - text += cl(step.Text, c) - } - text += s(f.commentPos-f.length(step)+1) + cl(fmt.Sprintf("# %s", def.funcName()), black) - default: - text += cl(step.Text, c) - } - - fmt.Println(text) - switch t := step.Argument.(type) { - case *gherkin.DataTable: - f.printTable(t, c) - case *gherkin.DocString: - var ct string - if len(t.ContentType) > 0 { - ct = " " + cl(t.ContentType, c) - } - fmt.Println(s(f.indent*3) + cl(t.Delimitter, c) + ct) - for _, ln := range strings.Split(t.Content, "\n") { - fmt.Println(s(f.indent*3) + cl(ln, c)) - } - fmt.Println(s(f.indent*3) + cl(t.Delimitter, c)) - } -} - -func (f *pretty) printStepKind(res *stepResult) { - // if has not printed background yet - switch { - // first background step - case f.bgSteps > 0 && f.bgSteps == len(f.feature.Background.Steps): - f.commentPos = f.longestStep(f.feature.Background.Steps, f.length(f.feature.Background)) - fmt.Println("\n" + s(f.indent) + bcl(f.feature.Background.Keyword+": "+f.feature.Background.Name, white)) - f.bgSteps-- - // subsequent background steps - case f.bgSteps > 0: - f.bgSteps-- - // first step of scenario, print header and calculate comment position - case f.scenario != nil: - // print scenario keyword and value if first example - if !f.scenarioKeyword { - f.commentPos = f.longestStep(f.scenario.Steps, f.length(f.scenario)) - if f.feature.Background != nil { - if bgLen := f.longestStep(f.feature.Background.Steps, f.length(f.feature.Background)); bgLen > f.commentPos { - f.commentPos = bgLen - } - } - text := s(f.indent) + bcl(f.scenario.Keyword+": ", white) + f.scenario.Name - text += s(f.commentPos-f.length(f.scenario)+1) + f.line(f.scenario.Location) - fmt.Println("\n" + text) - f.scenarioKeyword = true - } - f.steps-- - // first step of outline scenario, print header and calculate comment position - case f.outline != nil: - f.outlineSteps = append(f.outlineSteps, res) - f.steps-- - - // print scenario keyword and value if first example - if !f.scenarioKeyword { - f.commentPos = f.longestStep(f.outline.Steps, f.length(f.outline)) - if f.feature.Background != nil { - if bgLen := f.longestStep(f.feature.Background.Steps, f.length(f.feature.Background)); bgLen > f.commentPos { - f.commentPos = bgLen - } - } - text := s(f.indent) + bcl(f.outline.Keyword+": ", white) + f.outline.Name - text += s(f.commentPos-f.length(f.outline)+1) + f.line(f.outline.Location) - fmt.Println("\n" + text) - f.scenarioKeyword = true - } - if len(f.outlineSteps) == len(f.outline.Steps)+f.bgSteps { - // an outline example steps has went through - f.printOutlineExample(f.outline) - f.outlineNumExamples-- - } - return - } - - f.printStep(res.step, res.def, res.typ.clr()) - if res.err != nil { - fmt.Println(s(f.indent*2) + bcl(res.err, red)) - } - if res.typ == pending { - fmt.Println(s(f.indent*3) + cl("TODO: write pending definition", yellow)) - } -} - -// print table with aligned table cells -func (f *pretty) printTable(t *gherkin.DataTable, c color) { - var l = longest(t) - var cols = make([]string, len(t.Rows[0].Cells)) - for _, row := range t.Rows { - for i, cell := range row.Cells { - cols[i] = cell.Value + s(l[i]-len(cell.Value)) - } - fmt.Println(s(f.indent*3) + cl("| "+strings.Join(cols, " | ")+" |", c)) - } -} - -func (f *pretty) Passed(step *gherkin.Step, match *StepDef) { - f.basefmt.Passed(step, match) - f.printStepKind(f.passed[len(f.passed)-1]) -} - -func (f *pretty) Skipped(step *gherkin.Step) { - f.basefmt.Skipped(step) - f.printStepKind(f.skipped[len(f.skipped)-1]) -} - -func (f *pretty) Undefined(step *gherkin.Step) { - f.basefmt.Undefined(step) - f.printStepKind(f.undefined[len(f.undefined)-1]) -} - -func (f *pretty) Failed(step *gherkin.Step, match *StepDef, err error) { - f.basefmt.Failed(step, match, err) - f.printStepKind(f.failed[len(f.failed)-1]) -} - -func (f *pretty) Pending(step *gherkin.Step, match *StepDef) { - f.basefmt.Pending(step, match) - f.printStepKind(f.pending[len(f.pending)-1]) -} - -// longest gives a list of longest columns of all rows in Table -func longest(tbl interface{}) []int { - var rows []*gherkin.TableRow - switch t := tbl.(type) { - case *gherkin.Examples: - rows = append(rows, t.TableHeader) - rows = append(rows, t.TableBody...) - case *gherkin.DataTable: - rows = append(rows, t.Rows...) - } - - longest := make([]int, len(rows[0].Cells)) - for _, row := range rows { - for i, cell := range row.Cells { - if longest[i] < len(cell.Value) { - longest[i] = len(cell.Value) - } - } - } - return longest -} - -func (f *pretty) longestStep(steps []*gherkin.Step, base int) int { - ret := base - for _, step := range steps { - length := f.length(step) - if length > ret { - ret = length - } - } - return ret -} - -// a line number representation in feature file -func (f *pretty) line(loc *gherkin.Location) string { - return cl(fmt.Sprintf("# %s:%d", f.features[len(f.features)-1].Path, loc.Line), black) -} - -func (f *pretty) length(node interface{}) int { - switch t := node.(type) { - case *gherkin.Background: - return f.indent + utf8.RuneCountInString(strings.TrimSpace(t.Keyword)+": "+t.Name) - case *gherkin.Step: - return f.indent*2 + utf8.RuneCountInString(strings.TrimSpace(t.Keyword)+" "+t.Text) - case *gherkin.Scenario: - return f.indent + utf8.RuneCountInString(strings.TrimSpace(t.Keyword)+": "+t.Name) - case *gherkin.ScenarioOutline: - return f.indent + utf8.RuneCountInString(strings.TrimSpace(t.Keyword)+": "+t.Name) - } - panic(fmt.Sprintf("unexpected node %T to determine length", node)) -} diff --git a/vendor/github.com/DATA-DOG/godog/fmt_progress.go b/vendor/github.com/DATA-DOG/godog/fmt_progress.go deleted file mode 100644 index 36c8b128034..00000000000 --- a/vendor/github.com/DATA-DOG/godog/fmt_progress.go +++ /dev/null @@ -1,114 +0,0 @@ -package godog - -import ( - "fmt" - "math" - "sync" - "time" - - "github.com/DATA-DOG/godog/gherkin" -) - -func init() { - Format("progress", "Prints a character per step.", &progress{ - basefmt: basefmt{ - started: time.Now(), - indent: 2, - }, - stepsPerRow: 70, - }) -} - -type progress struct { - basefmt - sync.Mutex - stepsPerRow int - steps int -} - -func (f *progress) Node(n interface{}) { - f.Lock() - defer f.Unlock() - f.basefmt.Node(n) -} - -func (f *progress) Feature(ft *gherkin.Feature, p string) { - f.Lock() - defer f.Unlock() - f.basefmt.Feature(ft, p) -} - -func (f *progress) Summary() { - left := math.Mod(float64(f.steps), float64(f.stepsPerRow)) - if left != 0 { - if int(f.steps) > f.stepsPerRow { - fmt.Printf(s(f.stepsPerRow-int(left)) + fmt.Sprintf(" %d\n", f.steps)) - } else { - fmt.Printf(" %d\n", f.steps) - } - } - fmt.Println("") - - if len(f.failed) > 0 { - fmt.Println("\n--- " + cl("Failed steps:", red) + "\n") - for _, fail := range f.failed { - fmt.Println(s(4) + cl(fail.step.Keyword+" "+fail.step.Text, red) + cl(" # "+fail.line(), black)) - fmt.Println(s(6) + cl("Error: ", red) + bcl(fail.err, red) + "\n") - } - } - f.basefmt.Summary() -} - -func (f *progress) step(res *stepResult) { - switch res.typ { - case passed: - fmt.Print(cl(".", green)) - case skipped: - fmt.Print(cl("-", cyan)) - case failed: - fmt.Print(cl("F", red)) - case undefined: - fmt.Print(cl("U", yellow)) - case pending: - fmt.Print(cl("P", yellow)) - } - f.steps++ - if math.Mod(float64(f.steps), float64(f.stepsPerRow)) == 0 { - fmt.Printf(" %d\n", f.steps) - } -} - -func (f *progress) Passed(step *gherkin.Step, match *StepDef) { - f.Lock() - defer f.Unlock() - f.basefmt.Passed(step, match) - f.step(f.passed[len(f.passed)-1]) -} - -func (f *progress) Skipped(step *gherkin.Step) { - f.Lock() - defer f.Unlock() - f.basefmt.Skipped(step) - f.step(f.skipped[len(f.skipped)-1]) -} - -func (f *progress) Undefined(step *gherkin.Step) { - f.Lock() - defer f.Unlock() - f.basefmt.Undefined(step) - f.step(f.undefined[len(f.undefined)-1]) -} - -func (f *progress) Failed(step *gherkin.Step, match *StepDef, err error) { - f.Lock() - defer f.Unlock() - f.basefmt.Failed(step, match, err) - f.step(f.failed[len(f.failed)-1]) -} - -func (f *progress) Pending(step *gherkin.Step, match *StepDef) { - f.Lock() - defer f.Unlock() - f.basefmt.Pending(step, match) - f.step(f.pending[len(f.pending)-1]) -} diff --git a/vendor/github.com/DATA-DOG/godog/gherkin.go b/vendor/github.com/DATA-DOG/godog/gherkin.go deleted file mode 100644 index 4280eae9dcd..00000000000 --- a/vendor/github.com/DATA-DOG/godog/gherkin.go +++ /dev/null @@ -1,11 +0,0 @@ -package godog - -import "github.com/DATA-DOG/godog/gherkin" - -// examples is a helper func to cast gherkin.Examples -// or gherkin.BaseExamples if its empty -// @TODO: this should go away with gherkin update -func examples(ex interface{}) (*gherkin.Examples, bool) { - t, ok := ex.(*gherkin.Examples) - return t, ok -} diff --git a/vendor/github.com/DATA-DOG/godog/godog.go b/vendor/github.com/DATA-DOG/godog/godog.go deleted file mode 100644 index 5da8d34e0fb..00000000000 --- a/vendor/github.com/DATA-DOG/godog/godog.go +++ /dev/null @@ -1,45 +0,0 @@ -/* -Package godog is the official Cucumber BDD framework for Golang, it merges specification -and test documentation into one cohesive whole. - -Godog does not intervene with the standard "go test" command and it's behavior. -You can leverage both frameworks to functionally test your application while -maintaining all test related source code in *_test.go files. - -Godog acts similar compared to go test command. It uses go -compiler and linker tool in order to produce test executable. Godog -contexts needs to be exported same as Test functions for go test. - -For example, imagine you’re about to create the famous UNIX ls command. -Before you begin, you describe how the feature should work, see the example below.. - -Example: - Feature: ls - In order to see the directory structure - As a UNIX user - I need to be able to list the current directory's contents - - Scenario: - Given I am in a directory "test" - And I have a file named "foo" - And I have a file named "bar" - When I run ls - Then I should get output: - """ - bar - foo - """ - -As a developer, your work is done as soon as you’ve made the ls command behave as -described in the Scenario. - -Now, wouldn’t it be cool if something could read this sentence and use it to actually -run a test against the ls command? Hey, that’s exactly what this package does! -As you’ll see, Godog is easy to learn, quick to use, and will put the fun back into tests. - -Godog was inspired by Behat and Cucumber the above description is taken from it's documentation. -*/ -package godog - -// Version of package - based on Semantic Versioning 2.0.0 http://semver.org/ -const Version = "v0.5.4" diff --git a/vendor/github.com/DATA-DOG/godog/logo.png b/vendor/github.com/DATA-DOG/godog/logo.png deleted file mode 100644 index 079509f5688..00000000000 Binary files a/vendor/github.com/DATA-DOG/godog/logo.png and /dev/null differ diff --git a/vendor/github.com/DATA-DOG/godog/run.go b/vendor/github.com/DATA-DOG/godog/run.go deleted file mode 100644 index 4f3257382c5..00000000000 --- a/vendor/github.com/DATA-DOG/godog/run.go +++ /dev/null @@ -1,124 +0,0 @@ -package godog - -import ( - "fmt" - "os" -) - -type initializer func(*Suite) - -type runner struct { - stopOnFailure bool - features []*feature - fmt Formatter // needs to support concurrency - initializer initializer -} - -func (r *runner) concurrent(rate int) (failed bool) { - queue := make(chan int, rate) - for i, ft := range r.features { - queue <- i // reserve space in queue - go func(fail *bool, feat *feature) { - defer func() { - <-queue // free a space in queue - }() - if r.stopOnFailure && *fail { - return - } - suite := &Suite{ - fmt: r.fmt, - stopOnFailure: r.stopOnFailure, - features: []*feature{feat}, - } - r.initializer(suite) - suite.run() - if suite.failed { - *fail = true - } - }(&failed, ft) - } - // wait until last are processed - for i := 0; i < rate; i++ { - queue <- i - } - close(queue) - - // print summary - r.fmt.Summary() - return -} - -func (r *runner) run() (failed bool) { - suite := &Suite{ - fmt: r.fmt, - stopOnFailure: r.stopOnFailure, - features: r.features, - } - r.initializer(suite) - suite.run() - - r.fmt.Summary() - return suite.failed -} - -// Run creates and runs the feature suite. -// uses contextInitializer to register contexts -// -// the concurrency option allows runner to -// initialize a number of suites to be run -// separately. Only progress formatter -// is supported when concurrency level is -// higher than 1 -// -// contextInitializer must be able to register -// the step definitions and event handlers. -func Run(contextInitializer func(suite *Suite)) int { - var defs, sof, noclr bool - var tags, format string - var concurrency int - flagSet := FlagSet(&format, &tags, &defs, &sof, &noclr, &concurrency) - err := flagSet.Parse(os.Args[1:]) - fatal(err) - - if defs { - s := &Suite{} - contextInitializer(s) - s.printStepDefinitions() - return 0 - } - - paths := flagSet.Args() - if len(paths) == 0 { - inf, err := os.Stat("features") - if err == nil && inf.IsDir() { - paths = []string{"features"} - } - } - - if concurrency > 1 && format != "progress" { - fatal(fmt.Errorf("when concurrency level is higher than 1, only progress format is supported")) - } - formatter, err := findFmt(format) - fatal(err) - - features, err := parseFeatures(tags, paths) - fatal(err) - - r := runner{ - fmt: formatter, - initializer: contextInitializer, - features: features, - stopOnFailure: sof, - } - - var failed bool - if concurrency > 1 { - failed = r.concurrent(concurrency) - } else { - failed = r.run() - } - if failed { - return 1 - } - return 0 -} diff --git a/vendor/github.com/DATA-DOG/godog/stepdef.go b/vendor/github.com/DATA-DOG/godog/stepdef.go deleted file mode 100644 index 6ce06cee961..00000000000 --- a/vendor/github.com/DATA-DOG/godog/stepdef.go +++ /dev/null @@ -1,189 +0,0 @@ -package godog - -import ( - "fmt" - "path/filepath" - "reflect" - "regexp" - "runtime" - "strconv" - "strings" - - "github.com/DATA-DOG/godog/gherkin" -) - -var matchFuncDefRef = regexp.MustCompile(`\(([^\)]+)\)`) - -// StepDef is a registered step definition -// contains a StepHandler and regexp which -// is used to match a step. Args which -// were matched by last executed step -// -// This structure is passed to the formatter -// when step is matched and is either failed -// or successful -type StepDef struct { - args []interface{} - hv reflect.Value - Expr *regexp.Regexp - Handler interface{} -} - -func (sd *StepDef) funcName() string { - ptr := sd.hv.Pointer() - f := runtime.FuncForPC(ptr) - file, line := f.FileLine(ptr) - dir := filepath.Dir(file) - - fn := strings.Replace(f.Name(), dir, "", -1) - var parts []string - for _, gr := range matchFuncDefRef.FindAllStringSubmatch(fn, -1) { - parts = append(parts, strings.Trim(gr[1], "_.")) - } - if len(parts) > 0 { - // case when suite is a structure with methods - fn = strings.Join(parts, ".") - } else { - // case when steps are just plain funcs - fn = strings.Trim(fn, "_.") - } - - return fmt.Sprintf("%s:%d -> %s", filepath.Base(file), line, fn) -} - -// run a step with the matched arguments using -// reflect -func (sd *StepDef) run() error { - typ := sd.hv.Type() - if len(sd.args) < typ.NumIn() { - return fmt.Errorf("func expects %d arguments, which is more than %d matched from step", typ.NumIn(), len(sd.args)) - } - var values []reflect.Value - for i := 0; i < typ.NumIn(); i++ { - param := typ.In(i) - switch param.Kind() { - case reflect.Int: - s, err := sd.shouldBeString(i) - if err != nil { - return err - } - v, err := strconv.ParseInt(s, 10, 0) - if err != nil { - return fmt.Errorf(`cannot convert argument %d: "%s" to int: %s`, i, s, err) - } - values = append(values, reflect.ValueOf(int(v))) - case reflect.Int64: - s, err := sd.shouldBeString(i) - if err != nil { - return err - } - v, err := strconv.ParseInt(s, 10, 64) - if err != nil { - return fmt.Errorf(`cannot convert argument %d: "%s" to int64: %s`, i, s, err) - } - values = append(values, reflect.ValueOf(int64(v))) - case reflect.Int32: - s, err := sd.shouldBeString(i) - if err != nil { - return err - } - v, err := strconv.ParseInt(s, 10, 32) - if err != nil { - return fmt.Errorf(`cannot convert argument %d: "%s" to int32: %s`, i, s, err) - } - values = append(values, reflect.ValueOf(int32(v))) - case reflect.Int16: - s, err := sd.shouldBeString(i) - if err != nil { - return err - } - v, err := strconv.ParseInt(s, 10, 16) - if err != nil { - return fmt.Errorf(`cannot convert argument %d: "%s" to int16: %s`, i, s, err) - } - values = append(values, reflect.ValueOf(int16(v))) - case reflect.Int8: - s, err := sd.shouldBeString(i) - if err != nil { - return err - } - v, err := strconv.ParseInt(s, 10, 8) - if err != nil { - return fmt.Errorf(`cannot convert argument %d: "%s" to int8: %s`, i, s, err) - } - values = append(values, reflect.ValueOf(int8(v))) - case reflect.String: - s, err := sd.shouldBeString(i) - if err != nil { - return err - } - values = append(values, reflect.ValueOf(s)) - case reflect.Float64: - s, err := sd.shouldBeString(i) - if err != nil { - return err - } - v, err := strconv.ParseFloat(s, 64) - if err != nil { - return fmt.Errorf(`cannot convert argument %d: "%s" to float64: %s`, i, s, err) - } - values = append(values, reflect.ValueOf(v)) - case reflect.Float32: - s, err := sd.shouldBeString(i) - if err != nil { - return err - } - v, err := strconv.ParseFloat(s, 32) - if err != nil { - return fmt.Errorf(`cannot convert argument %d: "%s" to float32: %s`, i, s, err) - } - values = append(values, reflect.ValueOf(float32(v))) - case reflect.Ptr: - arg := sd.args[i] - switch param.Elem().String() { - case "gherkin.DocString": - v, ok := arg.(*gherkin.DocString) - if !ok { - return fmt.Errorf(`cannot convert argument %d: "%v" of type "%T" to *gherkin.DocString`, i, arg, arg) - } - values = append(values, reflect.ValueOf(v)) - case "gherkin.DataTable": - v, ok := arg.(*gherkin.DataTable) - if !ok { - return fmt.Errorf(`cannot convert argument %d: "%v" of type "%T" to *gherkin.DocString`, i, arg, arg) - } - values = append(values, reflect.ValueOf(v)) - default: - return fmt.Errorf("the argument %d type %T is not supported", i, arg) - } - case reflect.Slice: - switch param { - case typeOfBytes: - s, err := sd.shouldBeString(i) - if err != nil { - return err - } - values = append(values, reflect.ValueOf([]byte(s))) - default: - return fmt.Errorf("the slice argument %d type %s is not supported", i, param.Kind()) - } - default: - return fmt.Errorf("the argument %d type %s is not supported", i, param.Kind()) - } - } - ret := sd.hv.Call(values)[0].Interface() - if nil == ret { - return nil - } - - return ret.(error) -} - -func (sd *StepDef) shouldBeString(idx int) (string, error) { - arg := sd.args[idx] - s, ok := arg.(string) - if !ok { - return "", fmt.Errorf(`cannot convert argument %d: "%v" of type "%T" to string`, idx, arg, arg) - } - return s, nil -} diff --git a/vendor/github.com/DATA-DOG/godog/suite.go b/vendor/github.com/DATA-DOG/godog/suite.go deleted file mode 100644 index 3ceaba5f18c..00000000000 --- a/vendor/github.com/DATA-DOG/godog/suite.go +++ /dev/null @@ -1,535 +0,0 @@ -package godog - -import ( - "fmt" - "os" - "path/filepath" - "reflect" - "regexp" - "sort" - "strconv" - "strings" - "unicode/utf8" - - "github.com/DATA-DOG/godog/gherkin" -) - -var errorInterface = reflect.TypeOf((*error)(nil)).Elem() -var typeOfBytes = reflect.TypeOf([]byte(nil)) - -type feature struct { - *gherkin.Feature - Path string `json:"path"` -} - -// ErrUndefined is returned in case if step definition was not found -var ErrUndefined = fmt.Errorf("step is undefined") - -// ErrPending should be returned by step definition if -// step implementation is pending -var ErrPending = fmt.Errorf("step implementation is pending") - -// Suite allows various contexts -// to register steps and event handlers. -// -// When running a test suite, the instance of Suite -// is passed to all functions (contexts), which -// have it as a first and only argument. -// -// Note that all event hooks does not catch panic errors -// in order to have a trace information. Only step -// executions are catching panic error since it may -// be a context specific error. -type Suite struct { - steps []*StepDef - features []*feature - fmt Formatter - - failed bool - stopOnFailure bool - - // suite event handlers - beforeSuiteHandlers []func() - beforeScenarioHandlers []func(interface{}) - beforeStepHandlers []func(*gherkin.Step) - afterStepHandlers []func(*gherkin.Step, error) - afterScenarioHandlers []func(interface{}, error) - afterSuiteHandlers []func() -} - -// Step allows to register a *StepDef in Godog -// feature suite, the definition will be applied -// to all steps matching the given Regexp expr. -// -// It will panic if expr is not a valid regular -// expression or stepFunc is not a valid step -// handler. -// -// Note that if there are two definitions which may match -// the same step, then only the first matched handler -// will be applied. -// -// If none of the *StepDef is matched, then -// ErrUndefined error will be returned when -// running steps. -func (s *Suite) Step(expr interface{}, stepFunc interface{}) { - var regex *regexp.Regexp - - switch t := expr.(type) { - case *regexp.Regexp: - regex = t - case string: - regex = regexp.MustCompile(t) - case []byte: - regex = regexp.MustCompile(string(t)) - default: - panic(fmt.Sprintf("expecting expr to be a *regexp.Regexp or a string, got type: %T", expr)) - } - - v := reflect.ValueOf(stepFunc) - typ := v.Type() - if typ.Kind() != reflect.Func { - panic(fmt.Sprintf("expected handler to be func, but got: %T", stepFunc)) - } - if typ.NumOut() != 1 { - panic(fmt.Sprintf("expected handler to return an error, but it has more values in return: %d", typ.NumOut())) - } - if typ.Out(0).Kind() != reflect.Interface || !typ.Out(0).Implements(errorInterface) { - panic(fmt.Sprintf("expected handler to return an error interface, but we have: %s", typ.Out(0).Kind())) - } - s.steps = append(s.steps, &StepDef{ - Handler: stepFunc, - Expr: regex, - hv: v, - }) -} - -// BeforeSuite registers a function or method -// to be run once before suite runner. -// -// Use it to prepare the test suite for a spin. -// Connect and prepare database for instance... -func (s *Suite) BeforeSuite(f func()) { - s.beforeSuiteHandlers = append(s.beforeSuiteHandlers, f) -} - -// BeforeScenario registers a function or method -// to be run before every scenario or scenario outline. -// -// The interface argument may be *gherkin.Scenario -// or *gherkin.ScenarioOutline -// -// It is a good practice to restore the default state -// before every scenario so it would be isolated from -// any kind of state. -func (s *Suite) BeforeScenario(f func(interface{})) { - s.beforeScenarioHandlers = append(s.beforeScenarioHandlers, f) -} - -// BeforeStep registers a function or method -// to be run before every scenario -func (s *Suite) BeforeStep(f func(*gherkin.Step)) { - s.beforeStepHandlers = append(s.beforeStepHandlers, f) -} - -// AfterStep registers an function or method -// to be run after every scenario -// -// It may be convenient to return a different kind of error -// in order to print more state details which may help -// in case of step failure -// -// In some cases, for example when running a headless -// browser, to take a screenshot after failure. -func (s *Suite) AfterStep(f func(*gherkin.Step, error)) { - s.afterStepHandlers = append(s.afterStepHandlers, f) -} - -// AfterScenario registers an function or method -// to be run after every scenario or scenario outline -// -// The interface argument may be *gherkin.Scenario -// or *gherkin.ScenarioOutline -func (s *Suite) AfterScenario(f func(interface{}, error)) { - s.afterScenarioHandlers = append(s.afterScenarioHandlers, f) -} - -// AfterSuite registers a function or method -// to be run once after suite runner -func (s *Suite) AfterSuite(f func()) { - s.afterSuiteHandlers = append(s.afterSuiteHandlers, f) -} - -func (s *Suite) run() { - // run before suite handlers - for _, f := range s.beforeSuiteHandlers { - f() - } - // run features - for _, f := range s.features { - s.runFeature(f) - if s.failed && s.stopOnFailure { - // stop on first failure - break - } - } - // run after suite handlers - for _, f := range s.afterSuiteHandlers { - f() - } -} - -func (s *Suite) matchStep(step *gherkin.Step) *StepDef { - for _, h := range s.steps { - if m := h.Expr.FindStringSubmatch(step.Text); len(m) > 0 { - var args []interface{} - for _, m := range m[1:] { - args = append(args, m) - } - if step.Argument != nil { - args = append(args, step.Argument) - } - h.args = args - return h - } - } - return nil -} - -func (s *Suite) runStep(step *gherkin.Step, prevStepErr error) (err error) { - match := s.matchStep(step) - if match == nil { - s.fmt.Undefined(step) - return ErrUndefined - } - - if prevStepErr != nil { - s.fmt.Skipped(step) - return nil - } - - // run before step handlers - for _, f := range s.beforeStepHandlers { - f(step) - } - - defer func() { - if e := recover(); e != nil { - var ok bool - err, ok = e.(error) - if !ok { - err = fmt.Errorf("%v", e) - } - } - switch err { - case nil: - s.fmt.Passed(step, match) - case ErrPending: - s.fmt.Pending(step, match) - default: - s.fmt.Failed(step, match, err) - } - - // run after step handlers - for _, f := range s.afterStepHandlers { - f(step, err) - } - }() - - err = match.run() - return -} - -func (s *Suite) runSteps(steps []*gherkin.Step, prevErr error) (err error) { - err = prevErr - for _, step := range steps { - stepErr := s.runStep(step, err) - switch stepErr { - case ErrUndefined: - err = stepErr - case ErrPending: - err = stepErr - case nil: - default: - err = stepErr - } - } - return -} - -func (s *Suite) skipSteps(steps []*gherkin.Step) { - for _, step := range steps { - s.fmt.Skipped(step) - } -} - -func (s *Suite) runOutline(outline *gherkin.ScenarioOutline, b *gherkin.Background) (failErr error) { - s.fmt.Node(outline) - - for _, ex := range outline.Examples { - example, hasExamples := examples(ex) - if !hasExamples { - // @TODO: may need to print empty example node, but - // for backward compatibility, cannot cast to *gherkin.ExamplesBase - // at the moment - continue - } - - s.fmt.Node(example) - placeholders := example.TableHeader.Cells - groups := example.TableBody - - for _, group := range groups { - for _, f := range s.beforeScenarioHandlers { - f(outline) - } - var steps []*gherkin.Step - for _, outlineStep := range outline.Steps { - text := outlineStep.Text - for i, placeholder := range placeholders { - text = strings.Replace(text, "<"+placeholder.Value+">", group.Cells[i].Value, -1) - } - // clone a step - step := &gherkin.Step{ - Node: outlineStep.Node, - Text: text, - Keyword: outlineStep.Keyword, - Argument: outlineStep.Argument, - } - steps = append(steps, step) - } - - // run example table row - s.fmt.Node(group) - - // run background - var err error - if b != nil { - err = s.runSteps(b.Steps, err) - } - err = s.runSteps(steps, err) - - for _, f := range s.afterScenarioHandlers { - f(outline, err) - } - - if err != nil && err != ErrUndefined && err != ErrPending { - failErr = err - if s.stopOnFailure { - return - } - } - } - } - return -} - -func (s *Suite) runFeature(f *feature) { - s.fmt.Feature(f.Feature, f.Path) - for _, scenario := range f.ScenarioDefinitions { - var err error - if f.Background != nil { - s.fmt.Node(f.Background) - } - switch t := scenario.(type) { - case *gherkin.ScenarioOutline: - err = s.runOutline(t, f.Background) - case *gherkin.Scenario: - err = s.runScenario(t, f.Background) - } - if err != nil && err != ErrUndefined && err != ErrPending { - s.failed = true - if s.stopOnFailure { - return - } - } - } -} - -func (s *Suite) runScenario(scenario *gherkin.Scenario, b *gherkin.Background) (err error) { - // run before scenario handlers - for _, f := range s.beforeScenarioHandlers { - f(scenario) - } - - s.fmt.Node(scenario) - - // background - if b != nil { - err = s.runSteps(b.Steps, err) - } - - // scenario - err = s.runSteps(scenario.Steps, err) - - // run after scenario handlers - for _, f := range s.afterScenarioHandlers { - f(scenario, err) - } - - return -} - -func (s *Suite) printStepDefinitions() { - var longest int - for _, def := range s.steps { - n := utf8.RuneCountInString(def.Expr.String()) - if longest < n { - longest = n - } - } - for _, def := range s.steps { - n := utf8.RuneCountInString(def.Expr.String()) - location := def.funcName() - spaces := strings.Repeat(" ", longest-n) - fmt.Println(cl(def.Expr.String(), yellow)+spaces, cl("# "+location, black)) - } - if len(s.steps) == 0 { - fmt.Println("there were no contexts registered, could not find any step definition..") - } -} - -func parseFeatures(filter string, paths []string) (features []*feature, err error) { - for _, pat := range paths { - // check if line number is specified - parts := strings.Split(pat, ":") - path := parts[0] - line := -1 - if len(parts) > 1 { - line, err = strconv.Atoi(parts[1]) - if err != nil { - return features, fmt.Errorf("line number should follow after colon path delimiter") - } - } - // parse features - err = filepath.Walk(path, func(p string, f os.FileInfo, err error) error { - if err == nil && !f.IsDir() && strings.HasSuffix(p, ".feature") { - reader, err := os.Open(p) - if err != nil { - return err - } - ft, err := gherkin.ParseFeature(reader) - reader.Close() - if err != nil { - return err - } - features = append(features, &feature{Path: p, Feature: ft}) - // filter scenario by line number - if line != -1 { - var scenarios []interface{} - for _, def := range ft.ScenarioDefinitions { - var ln int - switch t := def.(type) { - case *gherkin.Scenario: - ln = t.Location.Line - case *gherkin.ScenarioOutline: - ln = t.Location.Line - } - if ln == line { - scenarios = append(scenarios, def) - break - } - } - ft.ScenarioDefinitions = scenarios - } - applyTagFilter(filter, ft) - } - return err - }) - // check error - switch { - case os.IsNotExist(err): - return features, fmt.Errorf(`feature path "%s" is not available`, path) - case os.IsPermission(err): - return features, fmt.Errorf(`feature path "%s" is not accessible`, path) - case err != nil: - return features, err - } - } - sort.Sort(featuresSortedByPath(features)) - return -} - -type featuresSortedByPath []*feature - -func (s featuresSortedByPath) Len() int { return len(s) } -func (s featuresSortedByPath) Less(i, j int) bool { return s[i].Path < s[j].Path } -func (s featuresSortedByPath) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - -func applyTagFilter(tags string, ft *gherkin.Feature) { - if len(tags) == 0 { - return - } - - var scenarios []interface{} - for _, scenario := range ft.ScenarioDefinitions { - if matchesTags(tags, allTags(ft, scenario)) { - scenarios = append(scenarios, scenario) - } - } - ft.ScenarioDefinitions = scenarios -} - -func allTags(nodes ...interface{}) []string { - var tags, tmp []string - for _, node := range nodes { - var gr []*gherkin.Tag - switch t := node.(type) { - case *gherkin.Feature: - gr = t.Tags - case *gherkin.ScenarioOutline: - gr = t.Tags - case *gherkin.Scenario: - gr = t.Tags - case *gherkin.Examples: - gr = t.Tags - } - - for _, gtag := range gr { - tag := strings.TrimSpace(gtag.Name) - if tag[0] == '@' { - tag = tag[1:] - } - copy(tmp, tags) - var found bool - for _, tg := range tmp { - if tg == tag { - found = true - break - } - } - if !found { - tags = append(tags, tag) - } - } - } - return tags -} - -func hasTag(tags []string, tag string) bool { - for _, t := range tags { - if t == tag { - return true - } - } - return false -} - -// based on http://behat.readthedocs.org/en/v2.5/guides/6.cli.html#gherkin-filters -func matchesTags(filter string, tags []string) (ok bool) { - ok = true - for _, andTags := range strings.Split(filter, "&&") { - var okComma bool - for _, tag := range strings.Split(andTags, ",") { - tag = strings.Replace(strings.TrimSpace(tag), "@", "", -1) - if tag[0] == '~' { - tag = tag[1:] - okComma = !hasTag(tags, tag) || okComma - } else { - okComma = hasTag(tags, tag) || okComma - } - } - ok = (false != okComma && ok && okComma) || false - } - return -} diff --git a/vendor/github.com/DATA-DOG/godog/utils.go b/vendor/github.com/DATA-DOG/godog/utils.go deleted file mode 100644 index d51ab21d098..00000000000 --- a/vendor/github.com/DATA-DOG/godog/utils.go +++ /dev/null @@ -1,50 +0,0 @@ -package godog - -import ( - "fmt" - "os" - "strings" -) - -// empty struct value takes no space allocation -type void struct{} - -// a color code type -type color int - -const ansiEscape = "\x1b" - -// some ansi colors -const ( - black color = iota + 30 - red - green - yellow - blue - magenta - cyan - white -) - -// colorizes foreground s with color c -func cl(s interface{}, c color) string { - return fmt.Sprintf("%s[%dm%v%s[0m", ansiEscape, c, s, ansiEscape) -} - -// colorizes foreground s with bold color c -func bcl(s interface{}, c color) string { - return fmt.Sprintf("%s[1;%dm%v%s[0m", ansiEscape, c, s, ansiEscape) -} - -// repeats a space n times -func s(n int) string { - return strings.Repeat(" ", n) -} - -// checks the error and exits with error status code -func fatal(err error) { - if err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} diff --git a/vendor/vendor.json b/vendor/vendor.json index 75e990632a9..20e8d7550b7 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -7,12 +7,6 @@ "revision": "056c9bc7be7190eaa7715723883caffa5f8fa3e4", "revisionTime": "2015-05-01T06:40:42-04:00" }, - { - "checksumSHA1": "Kos2ch8973PnyyQ2JPAgWKtQV1A=", - "path": "github.com/DATA-DOG/godog", - "revision": "6e3b3f764a57d37691c0dfd007e7e586d3e452dc", - "revisionTime": "2016-08-07T16:35:39Z" - }, { "checksumSHA1": "Zi1ZEYvoDhlK2+AaxrNeqmyZ4wY=", "path": "github.com/DATA-DOG/godog/cmd/godog",