diff --git a/.gitignore b/.gitignore index 76085a7b49d6e19d33f48651ea3fc3576d586a13..10229c5e189ad53882f4ef45fbdfa6106cb312f3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ dist *.swp *.swo +nvidia-container-runtime + diff --git a/docker/Dockerfile.amazonlinux b/docker/Dockerfile.amazonlinux index dcb219ab903c59b777000259f1ae1119da2c3ee4..578521cbf235806abfd06fcbff7825b9d10b5ab8 100644 --- a/docker/Dockerfile.amazonlinux +++ b/docker/Dockerfile.amazonlinux @@ -33,8 +33,6 @@ RUN yum install -y curl WORKDIR $GOPATH/src/gitlab.com/nvidia/container-toolkit/nvidia-container-runtime RUN mkdir -p ${GOPATH}/bin -RUN curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh - COPY src . RUN make build diff --git a/docker/Dockerfile.centos b/docker/Dockerfile.centos index 396d8f1f8613f640849839400293ce65932e5f7a..74cfbf8c4081fe32b0e5f4eae428a2c178019568 100644 --- a/docker/Dockerfile.centos +++ b/docker/Dockerfile.centos @@ -30,8 +30,6 @@ RUN go get -u golang.org/x/lint/golint github.com/gordonklaus/ineffassign WORKDIR $GOPATH/src/gitlab.com/nvidia/container-toolkit/nvidia-container-runtime RUN mkdir -p ${GOPATH}/bin -RUN curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh - COPY src . RUN make build diff --git a/docker/Dockerfile.debian b/docker/Dockerfile.debian index 117e5f316c029a8b632dab41cd6859a1c0378e10..c4255c84f8083ade985b59f3906e2cc53f524e0d 100644 --- a/docker/Dockerfile.debian +++ b/docker/Dockerfile.debian @@ -42,8 +42,6 @@ RUN apt-get update && \ WORKDIR $GOPATH/src/gitlab.com/nvidia/container-toolkit/nvidia-container-runtime RUN mkdir -p ${GOPATH}/bin -RUN curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh - COPY src . RUN make build diff --git a/docker/Dockerfile.opensuse-leap b/docker/Dockerfile.opensuse-leap index beabbf87dbc984efc1fb4f8b54666f634ebf581e..868d68060d21c8803eb86a89891906c4672a86b5 100644 --- a/docker/Dockerfile.opensuse-leap +++ b/docker/Dockerfile.opensuse-leap @@ -33,8 +33,6 @@ RUN zypper install -y curl make && \ WORKDIR $GOPATH/src/gitlab.com/nvidia/container-toolkit/nvidia-container-runtime RUN mkdir -p ${GOPATH}/bin -RUN curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh - COPY src . RUN make build diff --git a/docker/Dockerfile.ubuntu b/docker/Dockerfile.ubuntu index 9256cf4c1f62a012f381fee36d0648e9a459f9fe..eb3921c5dbfcd136f8feb905a96096d03d6af958 100644 --- a/docker/Dockerfile.ubuntu +++ b/docker/Dockerfile.ubuntu @@ -39,8 +39,6 @@ RUN apt-get update && \ WORKDIR $GOPATH/src/gitlab.com/nvidia/container-toolkit/nvidia-container-runtime RUN mkdir -p ${GOPATH}/bin -RUN curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh - COPY src . RUN make build diff --git a/src/Gopkg.lock b/src/Gopkg.lock deleted file mode 100644 index 1f7d497f58712651e713cdd4da9b0aa678e9dba4..0000000000000000000000000000000000000000 --- a/src/Gopkg.lock +++ /dev/null @@ -1,56 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - digest = "1:0deddd908b6b4b768cfc272c16ee61e7088a60f7fe2f06c547bd3d8e1f8b8e77" - name = "github.com/davecgh/go-spew" - packages = ["spew"] - pruneopts = "" - revision = "8991bc29aa16c548c550c7ff78260e27b9ab7c73" - version = "v1.1.1" - -[[projects]] - digest = "1:531ba73ef0f436a52f4b11ff915505ae92e0cca7eb110088e3ecc23fb7ba4b4f" - name = "github.com/opencontainers/runtime-spec" - packages = ["specs-go"] - pruneopts = "" - revision = "4e3b9264a330d094b0386c3703c5f379119711e8" - version = "v1.0.1" - -[[projects]] - digest = "1:3d2c33720d4255686b9f4a7e4d3b94938ee36063f14705c5eb0f73347ed4c496" - name = "github.com/pelletier/go-toml" - packages = ["."] - pruneopts = "" - revision = "728039f679cbcd4f6a54e080d2219a4c4928c546" - version = "v1.4.0" - -[[projects]] - digest = "1:256484dbbcd271f9ecebc6795b2df8cad4c458dd0f5fd82a8c2fa0c29f233411" - name = "github.com/pmezard/go-difflib" - packages = ["difflib"] - pruneopts = "" - revision = "792786c7400a136282c1664665ae0a8db921c6c2" - version = "v1.0.0" - -[[projects]] - digest = "1:381bcbeb112a51493d9d998bbba207a529c73dbb49b3fd789e48c63fac1f192c" - name = "github.com/stretchr/testify" - packages = [ - "assert", - "require", - ] - pruneopts = "" - revision = "ffdc059bfe9ce6a4e144ba849dbedead332c6053" - version = "v1.3.0" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - input-imports = [ - "github.com/opencontainers/runtime-spec/specs-go", - "github.com/pelletier/go-toml", - "github.com/stretchr/testify/require", - ] - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/src/Gopkg.toml b/src/Gopkg.toml deleted file mode 100644 index e03d9aa4ab655103f6a76155e83a2f0f70c8bc9c..0000000000000000000000000000000000000000 --- a/src/Gopkg.toml +++ /dev/null @@ -1,26 +0,0 @@ - -# Gopkg.toml example -# -# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" - - -[[constraint]] - name = "github.com/opencontainers/runtime-spec" - version = "1.0.1" diff --git a/src/go.mod b/src/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..24def800897883fecb4d4503b009e2ae7974989f --- /dev/null +++ b/src/go.mod @@ -0,0 +1,9 @@ +module gitlab.com/nvidia/container-toolkit/container-runtime/src + +go 1.15 + +require ( + github.com/opencontainers/runtime-spec v1.0.1 + github.com/pelletier/go-toml v1.4.0 + github.com/stretchr/testify v1.3.0 +) diff --git a/src/go.sum b/src/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..46a4213440ff49348a46564d8dd0723e67843594 --- /dev/null +++ b/src/go.sum @@ -0,0 +1,18 @@ +github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/opencontainers/runtime-spec v1.0.1 h1:wY4pOY8fBdSIvs9+IDHC55thBuEulhzfSgKeC1yFvzQ= +github.com/opencontainers/runtime-spec v1.0.1/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= +github.com/pelletier/go-toml v1.4.0 h1:u3Z1r+oOXJIkxqw34zVhyPgjBsm6X2wn21NWs/HfSeg= +github.com/pelletier/go-toml v1.4.0/go.mod h1:PN7xzY2wHTK0K9p34ErDQMlFxa51Fk0OUruD3k1mMwo= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/src/vendor/github.com/davecgh/go-spew/.gitignore b/src/vendor/github.com/davecgh/go-spew/.gitignore deleted file mode 100644 index 00268614f04567605359c96e714e834db9cebab6..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/davecgh/go-spew/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe diff --git a/src/vendor/github.com/davecgh/go-spew/.travis.yml b/src/vendor/github.com/davecgh/go-spew/.travis.yml deleted file mode 100644 index 1f4cbf5425dc0804b9ca1112e8a54a5e1346db25..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/davecgh/go-spew/.travis.yml +++ /dev/null @@ -1,28 +0,0 @@ -language: go -go_import_path: github.com/davecgh/go-spew -go: - - 1.6.x - - 1.7.x - - 1.8.x - - 1.9.x - - 1.10.x - - tip -sudo: false -install: - - go get -v github.com/alecthomas/gometalinter - - gometalinter --install -script: - - export PATH=$PATH:$HOME/gopath/bin - - export GORACE="halt_on_error=1" - - test -z "$(gometalinter --disable-all - --enable=gofmt - --enable=golint - --enable=vet - --enable=gosimple - --enable=unconvert - --deadline=4m ./spew | tee /dev/stderr)" - - go test -v -race -tags safe ./spew - - go test -v -race -tags testcgo ./spew -covermode=atomic -coverprofile=profile.cov -after_success: - - go get -v github.com/mattn/goveralls - - goveralls -coverprofile=profile.cov -service=travis-ci diff --git a/src/vendor/github.com/davecgh/go-spew/README.md b/src/vendor/github.com/davecgh/go-spew/README.md deleted file mode 100644 index f6ed02c3b672fa9c70ce790bc7f34bb957e61643..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/davecgh/go-spew/README.md +++ /dev/null @@ -1,201 +0,0 @@ -go-spew -======= - -[![Build Status](https://img.shields.io/travis/davecgh/go-spew.svg)](https://travis-ci.org/davecgh/go-spew) -[![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) -[![Coverage Status](https://img.shields.io/coveralls/davecgh/go-spew.svg)](https://coveralls.io/r/davecgh/go-spew?branch=master) - -Go-spew implements a deep pretty printer for Go data structures to aid in -debugging. A comprehensive suite of tests with 100% test coverage is provided -to ensure proper functionality. See `test_coverage.txt` for the gocov coverage -report. Go-spew is licensed under the liberal ISC license, so it may be used in -open source or commercial projects. - -If you're interested in reading about how this package came to life and some -of the challenges involved in providing a deep pretty printer, there is a blog -post about it -[here](https://web.archive.org/web/20160304013555/https://blog.cyphertite.com/go-spew-a-journey-into-dumping-go-data-structures/). - -## Documentation - -[![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](http://godoc.org/github.com/davecgh/go-spew/spew) - -Full `go doc` style documentation for the project can be viewed online without -installing this package by using the excellent GoDoc site here: -http://godoc.org/github.com/davecgh/go-spew/spew - -You can also view the documentation locally once the package is installed with -the `godoc` tool by running `godoc -http=":6060"` and pointing your browser to -http://localhost:6060/pkg/github.com/davecgh/go-spew/spew - -## Installation - -```bash -$ go get -u github.com/davecgh/go-spew/spew -``` - -## Quick Start - -Add this import line to the file you're working in: - -```Go -import "github.com/davecgh/go-spew/spew" -``` - -To dump a variable with full newlines, indentation, type, and pointer -information use Dump, Fdump, or Sdump: - -```Go -spew.Dump(myVar1, myVar2, ...) -spew.Fdump(someWriter, myVar1, myVar2, ...) -str := spew.Sdump(myVar1, myVar2, ...) -``` - -Alternatively, if you would prefer to use format strings with a compacted inline -printing style, use the convenience wrappers Printf, Fprintf, etc with %v (most -compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types -and pointer addresses): - -```Go -spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) -spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) -spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) -spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) -``` - -## Debugging a Web Application Example - -Here is an example of how you can use `spew.Sdump()` to help debug a web application. Please be sure to wrap your output using the `html.EscapeString()` function for safety reasons. You should also only use this debugging technique in a development environment, never in production. - -```Go -package main - -import ( - "fmt" - "html" - "net/http" - - "github.com/davecgh/go-spew/spew" -) - -func handler(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/html") - fmt.Fprintf(w, "Hi there, %s!", r.URL.Path[1:]) - fmt.Fprintf(w, "") -} - -func main() { - http.HandleFunc("/", handler) - http.ListenAndServe(":8080", nil) -} -``` - -## Sample Dump Output - -``` -(main.Foo) { - unexportedField: (*main.Bar)(0xf84002e210)({ - flag: (main.Flag) flagTwo, - data: (uintptr) - }), - ExportedField: (map[interface {}]interface {}) { - (string) "one": (bool) true - } -} -([]uint8) { - 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | - 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| - 00000020 31 32 |12| -} -``` - -## Sample Formatter Output - -Double pointer to a uint8: -``` - %v: <**>5 - %+v: <**>(0xf8400420d0->0xf8400420c8)5 - %#v: (**uint8)5 - %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5 -``` - -Pointer to circular struct with a uint8 field and a pointer to itself: -``` - %v: <*>{1 <*>} - %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)} - %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)} - %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)} -``` - -## Configuration Options - -Configuration of spew is handled by fields in the ConfigState type. For -convenience, all of the top-level functions use a global state available via the -spew.Config global. - -It is also possible to create a ConfigState instance that provides methods -equivalent to the top-level functions. This allows concurrent configuration -options. See the ConfigState documentation for more details. - -``` -* Indent - String to use for each indentation level for Dump functions. - It is a single space by default. A popular alternative is "\t". - -* MaxDepth - Maximum number of levels to descend into nested data structures. - There is no limit by default. - -* DisableMethods - Disables invocation of error and Stringer interface methods. - Method invocation is enabled by default. - -* DisablePointerMethods - Disables invocation of error and Stringer interface methods on types - which only accept pointer receivers from non-pointer variables. This option - relies on access to the unsafe package, so it will not have any effect when - running in environments without access to the unsafe package such as Google - App Engine or with the "safe" build tag specified. - Pointer method invocation is enabled by default. - -* DisablePointerAddresses - DisablePointerAddresses specifies whether to disable the printing of - pointer addresses. This is useful when diffing data structures in tests. - -* DisableCapacities - DisableCapacities specifies whether to disable the printing of capacities - for arrays, slices, maps and channels. This is useful when diffing data - structures in tests. - -* ContinueOnMethod - Enables recursion into types after invoking error and Stringer interface - methods. Recursion after method invocation is disabled by default. - -* SortKeys - Specifies map keys should be sorted before being printed. Use - this to have a more deterministic, diffable output. Note that - only native types (bool, int, uint, floats, uintptr and string) - and types which implement error or Stringer interfaces are supported, - with other types sorted according to the reflect.Value.String() output - which guarantees display stability. Natural map order is used by - default. - -* SpewKeys - SpewKeys specifies that, as a last resort attempt, map keys should be - spewed to strings and sorted by those strings. This is only considered - if SortKeys is true. - -``` - -## Unsafe Package Dependency - -This package relies on the unsafe package to perform some of the more advanced -features, however it also supports a "limited" mode which allows it to work in -environments where the unsafe package is not available. By default, it will -operate in this mode on Google App Engine and when compiled with GopherJS. The -"safe" build tag may also be specified to force the package to build without -using the unsafe package. - -## License - -Go-spew is licensed under the [copyfree](http://copyfree.org) ISC License. diff --git a/src/vendor/github.com/davecgh/go-spew/cov_report.sh b/src/vendor/github.com/davecgh/go-spew/cov_report.sh deleted file mode 100644 index 9579497e4115f7e90e1adf99417ddb65d113e532..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/davecgh/go-spew/cov_report.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/sh - -# This script uses gocov to generate a test coverage report. -# The gocov tool my be obtained with the following command: -# go get github.com/axw/gocov/gocov -# -# It will be installed to $GOPATH/bin, so ensure that location is in your $PATH. - -# Check for gocov. -if ! type gocov >/dev/null 2>&1; then - echo >&2 "This script requires the gocov tool." - echo >&2 "You may obtain it with the following command:" - echo >&2 "go get github.com/axw/gocov/gocov" - exit 1 -fi - -# Only run the cgo tests if gcc is installed. -if type gcc >/dev/null 2>&1; then - (cd spew && gocov test -tags testcgo | gocov report) -else - (cd spew && gocov test | gocov report) -fi diff --git a/src/vendor/github.com/davecgh/go-spew/spew/common_test.go b/src/vendor/github.com/davecgh/go-spew/spew/common_test.go deleted file mode 100644 index 0f5ce47dcaf6c4fa8768a6655340a381195d691c..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/davecgh/go-spew/spew/common_test.go +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew_test - -import ( - "fmt" - "reflect" - "testing" - - "github.com/davecgh/go-spew/spew" -) - -// custom type to test Stinger interface on non-pointer receiver. -type stringer string - -// String implements the Stringer interface for testing invocation of custom -// stringers on types with non-pointer receivers. -func (s stringer) String() string { - return "stringer " + string(s) -} - -// custom type to test Stinger interface on pointer receiver. -type pstringer string - -// String implements the Stringer interface for testing invocation of custom -// stringers on types with only pointer receivers. -func (s *pstringer) String() string { - return "stringer " + string(*s) -} - -// xref1 and xref2 are cross referencing structs for testing circular reference -// detection. -type xref1 struct { - ps2 *xref2 -} -type xref2 struct { - ps1 *xref1 -} - -// indirCir1, indirCir2, and indirCir3 are used to generate an indirect circular -// reference for testing detection. -type indirCir1 struct { - ps2 *indirCir2 -} -type indirCir2 struct { - ps3 *indirCir3 -} -type indirCir3 struct { - ps1 *indirCir1 -} - -// embed is used to test embedded structures. -type embed struct { - a string -} - -// embedwrap is used to test embedded structures. -type embedwrap struct { - *embed - e *embed -} - -// panicer is used to intentionally cause a panic for testing spew properly -// handles them -type panicer int - -func (p panicer) String() string { - panic("test panic") -} - -// customError is used to test custom error interface invocation. -type customError int - -func (e customError) Error() string { - return fmt.Sprintf("error: %d", int(e)) -} - -// stringizeWants converts a slice of wanted test output into a format suitable -// for a test error message. -func stringizeWants(wants []string) string { - s := "" - for i, want := range wants { - if i > 0 { - s += fmt.Sprintf("want%d: %s", i+1, want) - } else { - s += "want: " + want - } - } - return s -} - -// testFailed returns whether or not a test failed by checking if the result -// of the test is in the slice of wanted strings. -func testFailed(result string, wants []string) bool { - for _, want := range wants { - if result == want { - return false - } - } - return true -} - -type sortableStruct struct { - x int -} - -func (ss sortableStruct) String() string { - return fmt.Sprintf("ss.%d", ss.x) -} - -type unsortableStruct struct { - x int -} - -type sortTestCase struct { - input []reflect.Value - expected []reflect.Value -} - -func helpTestSortValues(tests []sortTestCase, cs *spew.ConfigState, t *testing.T) { - getInterfaces := func(values []reflect.Value) []interface{} { - interfaces := []interface{}{} - for _, v := range values { - interfaces = append(interfaces, v.Interface()) - } - return interfaces - } - - for _, test := range tests { - spew.SortValues(test.input, cs) - // reflect.DeepEqual cannot really make sense of reflect.Value, - // probably because of all the pointer tricks. For instance, - // v(2.0) != v(2.0) on a 32-bits system. Turn them into interface{} - // instead. - input := getInterfaces(test.input) - expected := getInterfaces(test.expected) - if !reflect.DeepEqual(input, expected) { - t.Errorf("Sort mismatch:\n %v != %v", input, expected) - } - } -} - -// TestSortValues ensures the sort functionality for relect.Value based sorting -// works as intended. -func TestSortValues(t *testing.T) { - v := reflect.ValueOf - - a := v("a") - b := v("b") - c := v("c") - embedA := v(embed{"a"}) - embedB := v(embed{"b"}) - embedC := v(embed{"c"}) - tests := []sortTestCase{ - // No values. - { - []reflect.Value{}, - []reflect.Value{}, - }, - // Bools. - { - []reflect.Value{v(false), v(true), v(false)}, - []reflect.Value{v(false), v(false), v(true)}, - }, - // Ints. - { - []reflect.Value{v(2), v(1), v(3)}, - []reflect.Value{v(1), v(2), v(3)}, - }, - // Uints. - { - []reflect.Value{v(uint8(2)), v(uint8(1)), v(uint8(3))}, - []reflect.Value{v(uint8(1)), v(uint8(2)), v(uint8(3))}, - }, - // Floats. - { - []reflect.Value{v(2.0), v(1.0), v(3.0)}, - []reflect.Value{v(1.0), v(2.0), v(3.0)}, - }, - // Strings. - { - []reflect.Value{b, a, c}, - []reflect.Value{a, b, c}, - }, - // Array - { - []reflect.Value{v([3]int{3, 2, 1}), v([3]int{1, 3, 2}), v([3]int{1, 2, 3})}, - []reflect.Value{v([3]int{1, 2, 3}), v([3]int{1, 3, 2}), v([3]int{3, 2, 1})}, - }, - // Uintptrs. - { - []reflect.Value{v(uintptr(2)), v(uintptr(1)), v(uintptr(3))}, - []reflect.Value{v(uintptr(1)), v(uintptr(2)), v(uintptr(3))}, - }, - // SortableStructs. - { - // Note: not sorted - DisableMethods is set. - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - }, - // UnsortableStructs. - { - // Note: not sorted - SpewKeys is false. - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - }, - // Invalid. - { - []reflect.Value{embedB, embedA, embedC}, - []reflect.Value{embedB, embedA, embedC}, - }, - } - cs := spew.ConfigState{DisableMethods: true, SpewKeys: false} - helpTestSortValues(tests, &cs, t) -} - -// TestSortValuesWithMethods ensures the sort functionality for relect.Value -// based sorting works as intended when using string methods. -func TestSortValuesWithMethods(t *testing.T) { - v := reflect.ValueOf - - a := v("a") - b := v("b") - c := v("c") - tests := []sortTestCase{ - // Ints. - { - []reflect.Value{v(2), v(1), v(3)}, - []reflect.Value{v(1), v(2), v(3)}, - }, - // Strings. - { - []reflect.Value{b, a, c}, - []reflect.Value{a, b, c}, - }, - // SortableStructs. - { - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})}, - }, - // UnsortableStructs. - { - // Note: not sorted - SpewKeys is false. - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - }, - } - cs := spew.ConfigState{DisableMethods: false, SpewKeys: false} - helpTestSortValues(tests, &cs, t) -} - -// TestSortValuesWithSpew ensures the sort functionality for relect.Value -// based sorting works as intended when using spew to stringify keys. -func TestSortValuesWithSpew(t *testing.T) { - v := reflect.ValueOf - - a := v("a") - b := v("b") - c := v("c") - tests := []sortTestCase{ - // Ints. - { - []reflect.Value{v(2), v(1), v(3)}, - []reflect.Value{v(1), v(2), v(3)}, - }, - // Strings. - { - []reflect.Value{b, a, c}, - []reflect.Value{a, b, c}, - }, - // SortableStructs. - { - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})}, - }, - // UnsortableStructs. - { - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - []reflect.Value{v(unsortableStruct{1}), v(unsortableStruct{2}), v(unsortableStruct{3})}, - }, - } - cs := spew.ConfigState{DisableMethods: true, SpewKeys: true} - helpTestSortValues(tests, &cs, t) -} diff --git a/src/vendor/github.com/davecgh/go-spew/spew/dump_test.go b/src/vendor/github.com/davecgh/go-spew/spew/dump_test.go deleted file mode 100644 index 4a31a2ee37fe536c16666e01b405a83a1760e7fa..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/davecgh/go-spew/spew/dump_test.go +++ /dev/null @@ -1,1042 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -Test Summary: -NOTE: For each test, a nil pointer, a single pointer and double pointer to the -base test element are also tested to ensure proper indirection across all types. - -- Max int8, int16, int32, int64, int -- Max uint8, uint16, uint32, uint64, uint -- Boolean true and false -- Standard complex64 and complex128 -- Array containing standard ints -- Array containing type with custom formatter on pointer receiver only -- Array containing interfaces -- Array containing bytes -- Slice containing standard float32 values -- Slice containing type with custom formatter on pointer receiver only -- Slice containing interfaces -- Slice containing bytes -- Nil slice -- Standard string -- Nil interface -- Sub-interface -- Map with string keys and int vals -- Map with custom formatter type on pointer receiver only keys and vals -- Map with interface keys and values -- Map with nil interface value -- Struct with primitives -- Struct that contains another struct -- Struct that contains custom type with Stringer pointer interface via both - exported and unexported fields -- Struct that contains embedded struct and field to same struct -- Uintptr to 0 (null pointer) -- Uintptr address of real variable -- Unsafe.Pointer to 0 (null pointer) -- Unsafe.Pointer to address of real variable -- Nil channel -- Standard int channel -- Function with no params and no returns -- Function with param and no returns -- Function with multiple params and multiple returns -- Struct that is circular through self referencing -- Structs that are circular through cross referencing -- Structs that are indirectly circular -- Type that panics in its Stringer interface -*/ - -package spew_test - -import ( - "bytes" - "fmt" - "testing" - "unsafe" - - "github.com/davecgh/go-spew/spew" -) - -// dumpTest is used to describe a test to be performed against the Dump method. -type dumpTest struct { - in interface{} - wants []string -} - -// dumpTests houses all of the tests to be performed against the Dump method. -var dumpTests = make([]dumpTest, 0) - -// addDumpTest is a helper method to append the passed input and desired result -// to dumpTests -func addDumpTest(in interface{}, wants ...string) { - test := dumpTest{in, wants} - dumpTests = append(dumpTests, test) -} - -func addIntDumpTests() { - // Max int8. - v := int8(127) - nv := (*int8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "int8" - vs := "127" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Max int16. - v2 := int16(32767) - nv2 := (*int16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "int16" - v2s := "32767" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Max int32. - v3 := int32(2147483647) - nv3 := (*int32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "int32" - v3s := "2147483647" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Max int64. - v4 := int64(9223372036854775807) - nv4 := (*int64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "int64" - v4s := "9223372036854775807" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") - - // Max int. - v5 := int(2147483647) - nv5 := (*int)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "int" - v5s := "2147483647" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") - addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") - addDumpTest(nv5, "(*"+v5t+")()\n") -} - -func addUintDumpTests() { - // Max uint8. - v := uint8(255) - nv := (*uint8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uint8" - vs := "255" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Max uint16. - v2 := uint16(65535) - nv2 := (*uint16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Max uint32. - v3 := uint32(4294967295) - nv3 := (*uint32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "uint32" - v3s := "4294967295" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Max uint64. - v4 := uint64(18446744073709551615) - nv4 := (*uint64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "uint64" - v4s := "18446744073709551615" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") - - // Max uint. - v5 := uint(4294967295) - nv5 := (*uint)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "uint" - v5s := "4294967295" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") - addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") - addDumpTest(nv5, "(*"+v5t+")()\n") -} - -func addBoolDumpTests() { - // Boolean true. - v := bool(true) - nv := (*bool)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "bool" - vs := "true" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Boolean false. - v2 := bool(false) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "bool" - v2s := "false" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") -} - -func addFloatDumpTests() { - // Standard float32. - v := float32(3.1415) - nv := (*float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "float32" - vs := "3.1415" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Standard float64. - v2 := float64(3.1415926) - nv2 := (*float64)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "float64" - v2s := "3.1415926" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") -} - -func addComplexDumpTests() { - // Standard complex64. - v := complex(float32(6), -2) - nv := (*complex64)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "complex64" - vs := "(6-2i)" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Standard complex128. - v2 := complex(float64(-6), 2) - nv2 := (*complex128)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "complex128" - v2s := "(-6+2i)" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") -} - -func addArrayDumpTests() { - // Array containing standard ints. - v := [3]int{1, 2, 3} - vLen := fmt.Sprintf("%d", len(v)) - vCap := fmt.Sprintf("%d", cap(v)) - nv := (*[3]int)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "int" - vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 1,\n (" + - vt + ") 2,\n (" + vt + ") 3\n}" - addDumpTest(v, "([3]"+vt+") "+vs+"\n") - addDumpTest(pv, "(*[3]"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**[3]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*[3]"+vt+")()\n") - - // Array containing type with custom formatter on pointer receiver only. - v2i0 := pstringer("1") - v2i1 := pstringer("2") - v2i2 := pstringer("3") - v2 := [3]pstringer{v2i0, v2i1, v2i2} - v2i0Len := fmt.Sprintf("%d", len(v2i0)) - v2i1Len := fmt.Sprintf("%d", len(v2i1)) - v2i2Len := fmt.Sprintf("%d", len(v2i2)) - v2Len := fmt.Sprintf("%d", len(v2)) - v2Cap := fmt.Sprintf("%d", cap(v2)) - nv2 := (*[3]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.pstringer" - v2sp := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + - ") (len=" + v2i0Len + ") stringer 1,\n (" + v2t + - ") (len=" + v2i1Len + ") stringer 2,\n (" + v2t + - ") (len=" + v2i2Len + ") " + "stringer 3\n}" - v2s := v2sp - if spew.UnsafeDisabled { - v2s = "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + - ") (len=" + v2i0Len + ") \"1\",\n (" + v2t + ") (len=" + - v2i1Len + ") \"2\",\n (" + v2t + ") (len=" + v2i2Len + - ") " + "\"3\"\n}" - } - addDumpTest(v2, "([3]"+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*[3]"+v2t+")("+v2Addr+")("+v2sp+")\n") - addDumpTest(&pv2, "(**[3]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2sp+")\n") - addDumpTest(nv2, "(*[3]"+v2t+")()\n") - - // Array containing interfaces. - v3i0 := "one" - v3 := [3]interface{}{v3i0, int(2), uint(3)} - v3i0Len := fmt.Sprintf("%d", len(v3i0)) - v3Len := fmt.Sprintf("%d", len(v3)) - v3Cap := fmt.Sprintf("%d", cap(v3)) - nv3 := (*[3]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[3]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " + - "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" + - v3t4 + ") 3\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Array containing bytes. - v4 := [34]byte{ - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, - } - v4Len := fmt.Sprintf("%d", len(v4)) - v4Cap := fmt.Sprintf("%d", cap(v4)) - nv4 := (*[34]byte)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "[34]uint8" - v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + - "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" + - " |............... |\n" + - " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" + - " |!\"#$%&'()*+,-./0|\n" + - " 00000020 31 32 " + - " |12|\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") -} - -func addSliceDumpTests() { - // Slice containing standard float32 values. - v := []float32{3.14, 6.28, 12.56} - vLen := fmt.Sprintf("%d", len(v)) - vCap := fmt.Sprintf("%d", cap(v)) - nv := (*[]float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "float32" - vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 3.14,\n (" + - vt + ") 6.28,\n (" + vt + ") 12.56\n}" - addDumpTest(v, "([]"+vt+") "+vs+"\n") - addDumpTest(pv, "(*[]"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**[]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*[]"+vt+")()\n") - - // Slice containing type with custom formatter on pointer receiver only. - v2i0 := pstringer("1") - v2i1 := pstringer("2") - v2i2 := pstringer("3") - v2 := []pstringer{v2i0, v2i1, v2i2} - v2i0Len := fmt.Sprintf("%d", len(v2i0)) - v2i1Len := fmt.Sprintf("%d", len(v2i1)) - v2i2Len := fmt.Sprintf("%d", len(v2i2)) - v2Len := fmt.Sprintf("%d", len(v2)) - v2Cap := fmt.Sprintf("%d", cap(v2)) - nv2 := (*[]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.pstringer" - v2s := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + ") (len=" + - v2i0Len + ") stringer 1,\n (" + v2t + ") (len=" + v2i1Len + - ") stringer 2,\n (" + v2t + ") (len=" + v2i2Len + ") " + - "stringer 3\n}" - addDumpTest(v2, "([]"+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*[]"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**[]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*[]"+v2t+")()\n") - - // Slice containing interfaces. - v3i0 := "one" - v3 := []interface{}{v3i0, int(2), uint(3), nil} - v3i0Len := fmt.Sprintf("%d", len(v3i0)) - v3Len := fmt.Sprintf("%d", len(v3)) - v3Cap := fmt.Sprintf("%d", cap(v3)) - nv3 := (*[]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3t5 := "interface {}" - v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " + - "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" + - v3t4 + ") 3,\n (" + v3t5 + ") \n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Slice containing bytes. - v4 := []byte{ - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, - } - v4Len := fmt.Sprintf("%d", len(v4)) - v4Cap := fmt.Sprintf("%d", cap(v4)) - nv4 := (*[]byte)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "[]uint8" - v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + - "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" + - " |............... |\n" + - " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" + - " |!\"#$%&'()*+,-./0|\n" + - " 00000020 31 32 " + - " |12|\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") - - // Nil slice. - v5 := []int(nil) - nv5 := (*[]int)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "[]int" - v5s := "" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") - addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") - addDumpTest(nv5, "(*"+v5t+")()\n") -} - -func addStringDumpTests() { - // Standard string. - v := "test" - vLen := fmt.Sprintf("%d", len(v)) - nv := (*string)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "string" - vs := "(len=" + vLen + ") \"test\"" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -func addInterfaceDumpTests() { - // Nil interface. - var v interface{} - nv := (*interface{})(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "interface {}" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Sub-interface. - v2 := interface{}(uint16(65535)) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") -} - -func addMapDumpTests() { - // Map with string keys and int vals. - k := "one" - kk := "two" - m := map[string]int{k: 1, kk: 2} - klen := fmt.Sprintf("%d", len(k)) // not kLen to shut golint up - kkLen := fmt.Sprintf("%d", len(kk)) - mLen := fmt.Sprintf("%d", len(m)) - nilMap := map[string]int(nil) - nm := (*map[string]int)(nil) - pm := &m - mAddr := fmt.Sprintf("%p", pm) - pmAddr := fmt.Sprintf("%p", &pm) - mt := "map[string]int" - mt1 := "string" - mt2 := "int" - ms := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + klen + ") " + - "\"one\": (" + mt2 + ") 1,\n (" + mt1 + ") (len=" + kkLen + - ") \"two\": (" + mt2 + ") 2\n}" - ms2 := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + kkLen + ") " + - "\"two\": (" + mt2 + ") 2,\n (" + mt1 + ") (len=" + klen + - ") \"one\": (" + mt2 + ") 1\n}" - addDumpTest(m, "("+mt+") "+ms+"\n", "("+mt+") "+ms2+"\n") - addDumpTest(pm, "(*"+mt+")("+mAddr+")("+ms+")\n", - "(*"+mt+")("+mAddr+")("+ms2+")\n") - addDumpTest(&pm, "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms+")\n", - "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms2+")\n") - addDumpTest(nm, "(*"+mt+")()\n") - addDumpTest(nilMap, "("+mt+") \n") - - // Map with custom formatter type on pointer receiver only keys and vals. - k2 := pstringer("one") - v2 := pstringer("1") - m2 := map[pstringer]pstringer{k2: v2} - k2Len := fmt.Sprintf("%d", len(k2)) - v2Len := fmt.Sprintf("%d", len(v2)) - m2Len := fmt.Sprintf("%d", len(m2)) - nilMap2 := map[pstringer]pstringer(nil) - nm2 := (*map[pstringer]pstringer)(nil) - pm2 := &m2 - m2Addr := fmt.Sprintf("%p", pm2) - pm2Addr := fmt.Sprintf("%p", &pm2) - m2t := "map[spew_test.pstringer]spew_test.pstringer" - m2t1 := "spew_test.pstringer" - m2t2 := "spew_test.pstringer" - m2s := "(len=" + m2Len + ") {\n (" + m2t1 + ") (len=" + k2Len + ") " + - "stringer one: (" + m2t2 + ") (len=" + v2Len + ") stringer 1\n}" - if spew.UnsafeDisabled { - m2s = "(len=" + m2Len + ") {\n (" + m2t1 + ") (len=" + k2Len + - ") " + "\"one\": (" + m2t2 + ") (len=" + v2Len + - ") \"1\"\n}" - } - addDumpTest(m2, "("+m2t+") "+m2s+"\n") - addDumpTest(pm2, "(*"+m2t+")("+m2Addr+")("+m2s+")\n") - addDumpTest(&pm2, "(**"+m2t+")("+pm2Addr+"->"+m2Addr+")("+m2s+")\n") - addDumpTest(nm2, "(*"+m2t+")()\n") - addDumpTest(nilMap2, "("+m2t+") \n") - - // Map with interface keys and values. - k3 := "one" - k3Len := fmt.Sprintf("%d", len(k3)) - m3 := map[interface{}]interface{}{k3: 1} - m3Len := fmt.Sprintf("%d", len(m3)) - nilMap3 := map[interface{}]interface{}(nil) - nm3 := (*map[interface{}]interface{})(nil) - pm3 := &m3 - m3Addr := fmt.Sprintf("%p", pm3) - pm3Addr := fmt.Sprintf("%p", &pm3) - m3t := "map[interface {}]interface {}" - m3t1 := "string" - m3t2 := "int" - m3s := "(len=" + m3Len + ") {\n (" + m3t1 + ") (len=" + k3Len + ") " + - "\"one\": (" + m3t2 + ") 1\n}" - addDumpTest(m3, "("+m3t+") "+m3s+"\n") - addDumpTest(pm3, "(*"+m3t+")("+m3Addr+")("+m3s+")\n") - addDumpTest(&pm3, "(**"+m3t+")("+pm3Addr+"->"+m3Addr+")("+m3s+")\n") - addDumpTest(nm3, "(*"+m3t+")()\n") - addDumpTest(nilMap3, "("+m3t+") \n") - - // Map with nil interface value. - k4 := "nil" - k4Len := fmt.Sprintf("%d", len(k4)) - m4 := map[string]interface{}{k4: nil} - m4Len := fmt.Sprintf("%d", len(m4)) - nilMap4 := map[string]interface{}(nil) - nm4 := (*map[string]interface{})(nil) - pm4 := &m4 - m4Addr := fmt.Sprintf("%p", pm4) - pm4Addr := fmt.Sprintf("%p", &pm4) - m4t := "map[string]interface {}" - m4t1 := "string" - m4t2 := "interface {}" - m4s := "(len=" + m4Len + ") {\n (" + m4t1 + ") (len=" + k4Len + ")" + - " \"nil\": (" + m4t2 + ") \n}" - addDumpTest(m4, "("+m4t+") "+m4s+"\n") - addDumpTest(pm4, "(*"+m4t+")("+m4Addr+")("+m4s+")\n") - addDumpTest(&pm4, "(**"+m4t+")("+pm4Addr+"->"+m4Addr+")("+m4s+")\n") - addDumpTest(nm4, "(*"+m4t+")()\n") - addDumpTest(nilMap4, "("+m4t+") \n") -} - -func addStructDumpTests() { - // Struct with primitives. - type s1 struct { - a int8 - b uint8 - } - v := s1{127, 255} - nv := (*s1)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.s1" - vt2 := "int8" - vt3 := "uint8" - vs := "{\n a: (" + vt2 + ") 127,\n b: (" + vt3 + ") 255\n}" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Struct that contains another struct. - type s2 struct { - s1 s1 - b bool - } - v2 := s2{s1{127, 255}, true} - nv2 := (*s2)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.s2" - v2t2 := "spew_test.s1" - v2t3 := "int8" - v2t4 := "uint8" - v2t5 := "bool" - v2s := "{\n s1: (" + v2t2 + ") {\n a: (" + v2t3 + ") 127,\n b: (" + - v2t4 + ") 255\n },\n b: (" + v2t5 + ") true\n}" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Struct that contains custom type with Stringer pointer interface via both - // exported and unexported fields. - type s3 struct { - s pstringer - S pstringer - } - v3 := s3{"test", "test2"} - nv3 := (*s3)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.s3" - v3t2 := "spew_test.pstringer" - v3s := "{\n s: (" + v3t2 + ") (len=4) stringer test,\n S: (" + v3t2 + - ") (len=5) stringer test2\n}" - v3sp := v3s - if spew.UnsafeDisabled { - v3s = "{\n s: (" + v3t2 + ") (len=4) \"test\",\n S: (" + - v3t2 + ") (len=5) \"test2\"\n}" - v3sp = "{\n s: (" + v3t2 + ") (len=4) \"test\",\n S: (" + - v3t2 + ") (len=5) stringer test2\n}" - } - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3sp+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3sp+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Struct that contains embedded struct and field to same struct. - e := embed{"embedstr"} - eLen := fmt.Sprintf("%d", len("embedstr")) - v4 := embedwrap{embed: &e, e: &e} - nv4 := (*embedwrap)(nil) - pv4 := &v4 - eAddr := fmt.Sprintf("%p", &e) - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "spew_test.embedwrap" - v4t2 := "spew_test.embed" - v4t3 := "string" - v4s := "{\n embed: (*" + v4t2 + ")(" + eAddr + ")({\n a: (" + v4t3 + - ") (len=" + eLen + ") \"embedstr\"\n }),\n e: (*" + v4t2 + - ")(" + eAddr + ")({\n a: (" + v4t3 + ") (len=" + eLen + ")" + - " \"embedstr\"\n })\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") -} - -func addUintptrDumpTests() { - // Null pointer. - v := uintptr(0) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uintptr" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - - // Address of real variable. - i := 1 - v2 := uintptr(unsafe.Pointer(&i)) - nv2 := (*uintptr)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uintptr" - v2s := fmt.Sprintf("%p", &i) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") -} - -func addUnsafePointerDumpTests() { - // Null pointer. - v := unsafe.Pointer(nil) - nv := (*unsafe.Pointer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "unsafe.Pointer" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Address of real variable. - i := 1 - v2 := unsafe.Pointer(&i) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "unsafe.Pointer" - v2s := fmt.Sprintf("%p", &i) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -func addChanDumpTests() { - // Nil channel. - var v chan int - pv := &v - nv := (*chan int)(nil) - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "chan int" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Real channel. - v2 := make(chan int) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "chan int" - v2s := fmt.Sprintf("%p", v2) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") -} - -func addFuncDumpTests() { - // Function with no params and no returns. - v := addIntDumpTests - nv := (*func())(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "func()" - vs := fmt.Sprintf("%p", v) - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Function with param and no returns. - v2 := TestDump - nv2 := (*func(*testing.T))(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "func(*testing.T)" - v2s := fmt.Sprintf("%p", v2) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Function with multiple params and multiple returns. - var v3 = func(i int, s string) (b bool, err error) { - return true, nil - } - nv3 := (*func(int, string) (bool, error))(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "func(int, string) (bool, error)" - v3s := fmt.Sprintf("%p", v3) - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") -} - -func addCircularDumpTests() { - // Struct that is circular through self referencing. - type circular struct { - c *circular - } - v := circular{nil} - v.c = &v - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.circular" - vs := "{\n c: (*" + vt + ")(" + vAddr + ")({\n c: (*" + vt + ")(" + - vAddr + ")()\n })\n}" - vs2 := "{\n c: (*" + vt + ")(" + vAddr + ")()\n}" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs2+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs2+")\n") - - // Structs that are circular through cross referencing. - v2 := xref1{nil} - ts2 := xref2{&v2} - v2.ps2 = &ts2 - pv2 := &v2 - ts2Addr := fmt.Sprintf("%p", &ts2) - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.xref1" - v2t2 := "spew_test.xref2" - v2s := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t + - ")(" + v2Addr + ")({\n ps2: (*" + v2t2 + ")(" + ts2Addr + - ")()\n })\n })\n}" - v2s2 := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t + - ")(" + v2Addr + ")()\n })\n}" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s2+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s2+")\n") - - // Structs that are indirectly circular. - v3 := indirCir1{nil} - tic2 := indirCir2{nil} - tic3 := indirCir3{&v3} - tic2.ps3 = &tic3 - v3.ps2 = &tic2 - pv3 := &v3 - tic2Addr := fmt.Sprintf("%p", &tic2) - tic3Addr := fmt.Sprintf("%p", &tic3) - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.indirCir1" - v3t2 := "spew_test.indirCir2" - v3t3 := "spew_test.indirCir3" - v3s := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 + - ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr + - ")({\n ps2: (*" + v3t2 + ")(" + tic2Addr + - ")()\n })\n })\n })\n}" - v3s2 := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 + - ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr + - ")()\n })\n })\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s2+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s2+")\n") -} - -func addPanicDumpTests() { - // Type that panics in its Stringer interface. - v := panicer(127) - nv := (*panicer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.panicer" - vs := "(PANIC=test panic)127" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -func addErrorDumpTests() { - // Type that has a custom Error interface. - v := customError(127) - nv := (*customError)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.customError" - vs := "error: 127" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -// TestDump executes all of the tests described by dumpTests. -func TestDump(t *testing.T) { - // Setup tests. - addIntDumpTests() - addUintDumpTests() - addBoolDumpTests() - addFloatDumpTests() - addComplexDumpTests() - addArrayDumpTests() - addSliceDumpTests() - addStringDumpTests() - addInterfaceDumpTests() - addMapDumpTests() - addStructDumpTests() - addUintptrDumpTests() - addUnsafePointerDumpTests() - addChanDumpTests() - addFuncDumpTests() - addCircularDumpTests() - addPanicDumpTests() - addErrorDumpTests() - addCgoDumpTests() - - t.Logf("Running %d tests", len(dumpTests)) - for i, test := range dumpTests { - buf := new(bytes.Buffer) - spew.Fdump(buf, test.in) - s := buf.String() - if testFailed(s, test.wants) { - t.Errorf("Dump #%d\n got: %s %s", i, s, stringizeWants(test.wants)) - continue - } - } -} - -func TestDumpSortedKeys(t *testing.T) { - cfg := spew.ConfigState{SortKeys: true} - s := cfg.Sdump(map[int]string{1: "1", 3: "3", 2: "2"}) - expected := "(map[int]string) (len=3) {\n(int) 1: (string) (len=1) " + - "\"1\",\n(int) 2: (string) (len=1) \"2\",\n(int) 3: (string) " + - "(len=1) \"3\"\n" + - "}\n" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sdump(map[stringer]int{"1": 1, "3": 3, "2": 2}) - expected = "(map[spew_test.stringer]int) (len=3) {\n" + - "(spew_test.stringer) (len=1) stringer 1: (int) 1,\n" + - "(spew_test.stringer) (len=1) stringer 2: (int) 2,\n" + - "(spew_test.stringer) (len=1) stringer 3: (int) 3\n" + - "}\n" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sdump(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2}) - expected = "(map[spew_test.pstringer]int) (len=3) {\n" + - "(spew_test.pstringer) (len=1) stringer 1: (int) 1,\n" + - "(spew_test.pstringer) (len=1) stringer 2: (int) 2,\n" + - "(spew_test.pstringer) (len=1) stringer 3: (int) 3\n" + - "}\n" - if spew.UnsafeDisabled { - expected = "(map[spew_test.pstringer]int) (len=3) {\n" + - "(spew_test.pstringer) (len=1) \"1\": (int) 1,\n" + - "(spew_test.pstringer) (len=1) \"2\": (int) 2,\n" + - "(spew_test.pstringer) (len=1) \"3\": (int) 3\n" + - "}\n" - } - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sdump(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2}) - expected = "(map[spew_test.customError]int) (len=3) {\n" + - "(spew_test.customError) error: 1: (int) 1,\n" + - "(spew_test.customError) error: 2: (int) 2,\n" + - "(spew_test.customError) error: 3: (int) 3\n" + - "}\n" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - -} diff --git a/src/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go b/src/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go deleted file mode 100644 index 108baa55f1db47eddda32520e97d8a10c405ca5a..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) 2013-2016 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when both cgo is supported and "-tags testcgo" is added to the go test -// command line. This means the cgo tests are only added (and hence run) when -// specifially requested. This configuration is used because spew itself -// does not require cgo to run even though it does handle certain cgo types -// specially. Rather than forcing all clients to require cgo and an external -// C compiler just to run the tests, this scheme makes them optional. -// +build cgo,testcgo - -package spew_test - -import ( - "fmt" - - "github.com/davecgh/go-spew/spew/testdata" -) - -func addCgoDumpTests() { - // C char pointer. - v := testdata.GetCgoCharPointer() - nv := testdata.GetCgoNullCharPointer() - pv := &v - vcAddr := fmt.Sprintf("%p", v) - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "*testdata._Ctype_char" - vs := "116" - addDumpTest(v, "("+vt+")("+vcAddr+")("+vs+")\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+"->"+vcAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+"->"+vcAddr+")("+vs+")\n") - addDumpTest(nv, "("+vt+")()\n") - - // C char array. - v2, v2l, v2c := testdata.GetCgoCharArray() - v2Len := fmt.Sprintf("%d", v2l) - v2Cap := fmt.Sprintf("%d", v2c) - v2t := "[6]testdata._Ctype_char" - v2s := "(len=" + v2Len + " cap=" + v2Cap + ") " + - "{\n 00000000 74 65 73 74 32 00 " + - " |test2.|\n}" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - - // C unsigned char array. - v3, v3l, v3c := testdata.GetCgoUnsignedCharArray() - v3Len := fmt.Sprintf("%d", v3l) - v3Cap := fmt.Sprintf("%d", v3c) - v3t := "[6]testdata._Ctype_unsignedchar" - v3t2 := "[6]testdata._Ctype_uchar" - v3s := "(len=" + v3Len + " cap=" + v3Cap + ") " + - "{\n 00000000 74 65 73 74 33 00 " + - " |test3.|\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n", "("+v3t2+") "+v3s+"\n") - - // C signed char array. - v4, v4l, v4c := testdata.GetCgoSignedCharArray() - v4Len := fmt.Sprintf("%d", v4l) - v4Cap := fmt.Sprintf("%d", v4c) - v4t := "[6]testdata._Ctype_schar" - v4t2 := "testdata._Ctype_schar" - v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + - "{\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 101,\n (" + v4t2 + - ") 115,\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 52,\n (" + v4t2 + - ") 0\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - - // C uint8_t array. - v5, v5l, v5c := testdata.GetCgoUint8tArray() - v5Len := fmt.Sprintf("%d", v5l) - v5Cap := fmt.Sprintf("%d", v5c) - v5t := "[6]testdata._Ctype_uint8_t" - v5t2 := "[6]testdata._Ctype_uchar" - v5s := "(len=" + v5Len + " cap=" + v5Cap + ") " + - "{\n 00000000 74 65 73 74 35 00 " + - " |test5.|\n}" - addDumpTest(v5, "("+v5t+") "+v5s+"\n", "("+v5t2+") "+v5s+"\n") - - // C typedefed unsigned char array. - v6, v6l, v6c := testdata.GetCgoTypdefedUnsignedCharArray() - v6Len := fmt.Sprintf("%d", v6l) - v6Cap := fmt.Sprintf("%d", v6c) - v6t := "[6]testdata._Ctype_custom_uchar_t" - v6t2 := "[6]testdata._Ctype_uchar" - v6s := "(len=" + v6Len + " cap=" + v6Cap + ") " + - "{\n 00000000 74 65 73 74 36 00 " + - " |test6.|\n}" - addDumpTest(v6, "("+v6t+") "+v6s+"\n", "("+v6t2+") "+v6s+"\n") -} diff --git a/src/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go b/src/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go deleted file mode 100644 index 52a0971fb3f1f4c712d485ddc64f918567d508ab..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2013 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when either cgo is not supported or "-tags testcgo" is not added to the go -// test command line. This file intentionally does not setup any cgo tests in -// this scenario. -// +build !cgo !testcgo - -package spew_test - -func addCgoDumpTests() { - // Don't add any tests for cgo since this file is only compiled when - // there should not be any cgo tests. -} diff --git a/src/vendor/github.com/davecgh/go-spew/spew/example_test.go b/src/vendor/github.com/davecgh/go-spew/spew/example_test.go deleted file mode 100644 index c6ec8c6d59e0169f58fec1c92ce1b2a3205c4bf5..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/davecgh/go-spew/spew/example_test.go +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew_test - -import ( - "fmt" - - "github.com/davecgh/go-spew/spew" -) - -type Flag int - -const ( - flagOne Flag = iota - flagTwo -) - -var flagStrings = map[Flag]string{ - flagOne: "flagOne", - flagTwo: "flagTwo", -} - -func (f Flag) String() string { - if s, ok := flagStrings[f]; ok { - return s - } - return fmt.Sprintf("Unknown flag (%d)", int(f)) -} - -type Bar struct { - data uintptr -} - -type Foo struct { - unexportedField Bar - ExportedField map[interface{}]interface{} -} - -// This example demonstrates how to use Dump to dump variables to stdout. -func ExampleDump() { - // The following package level declarations are assumed for this example: - /* - type Flag int - - const ( - flagOne Flag = iota - flagTwo - ) - - var flagStrings = map[Flag]string{ - flagOne: "flagOne", - flagTwo: "flagTwo", - } - - func (f Flag) String() string { - if s, ok := flagStrings[f]; ok { - return s - } - return fmt.Sprintf("Unknown flag (%d)", int(f)) - } - - type Bar struct { - data uintptr - } - - type Foo struct { - unexportedField Bar - ExportedField map[interface{}]interface{} - } - */ - - // Setup some sample data structures for the example. - bar := Bar{uintptr(0)} - s1 := Foo{bar, map[interface{}]interface{}{"one": true}} - f := Flag(5) - b := []byte{ - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, - } - - // Dump! - spew.Dump(s1, f, b) - - // Output: - // (spew_test.Foo) { - // unexportedField: (spew_test.Bar) { - // data: (uintptr) - // }, - // ExportedField: (map[interface {}]interface {}) (len=1) { - // (string) (len=3) "one": (bool) true - // } - // } - // (spew_test.Flag) Unknown flag (5) - // ([]uint8) (len=34 cap=34) { - // 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | - // 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| - // 00000020 31 32 |12| - // } - // -} - -// This example demonstrates how to use Printf to display a variable with a -// format string and inline formatting. -func ExamplePrintf() { - // Create a double pointer to a uint 8. - ui8 := uint8(5) - pui8 := &ui8 - ppui8 := &pui8 - - // Create a circular data type. - type circular struct { - ui8 uint8 - c *circular - } - c := circular{ui8: 1} - c.c = &c - - // Print! - spew.Printf("ppui8: %v\n", ppui8) - spew.Printf("circular: %v\n", c) - - // Output: - // ppui8: <**>5 - // circular: {1 <*>{1 <*>}} -} - -// This example demonstrates how to use a ConfigState. -func ExampleConfigState() { - // Modify the indent level of the ConfigState only. The global - // configuration is not modified. - scs := spew.ConfigState{Indent: "\t"} - - // Output using the ConfigState instance. - v := map[string]int{"one": 1} - scs.Printf("v: %v\n", v) - scs.Dump(v) - - // Output: - // v: map[one:1] - // (map[string]int) (len=1) { - // (string) (len=3) "one": (int) 1 - // } -} - -// This example demonstrates how to use ConfigState.Dump to dump variables to -// stdout -func ExampleConfigState_Dump() { - // See the top-level Dump example for details on the types used in this - // example. - - // Create two ConfigState instances with different indentation. - scs := spew.ConfigState{Indent: "\t"} - scs2 := spew.ConfigState{Indent: " "} - - // Setup some sample data structures for the example. - bar := Bar{uintptr(0)} - s1 := Foo{bar, map[interface{}]interface{}{"one": true}} - - // Dump using the ConfigState instances. - scs.Dump(s1) - scs2.Dump(s1) - - // Output: - // (spew_test.Foo) { - // unexportedField: (spew_test.Bar) { - // data: (uintptr) - // }, - // ExportedField: (map[interface {}]interface {}) (len=1) { - // (string) (len=3) "one": (bool) true - // } - // } - // (spew_test.Foo) { - // unexportedField: (spew_test.Bar) { - // data: (uintptr) - // }, - // ExportedField: (map[interface {}]interface {}) (len=1) { - // (string) (len=3) "one": (bool) true - // } - // } - // -} - -// This example demonstrates how to use ConfigState.Printf to display a variable -// with a format string and inline formatting. -func ExampleConfigState_Printf() { - // See the top-level Dump example for details on the types used in this - // example. - - // Create two ConfigState instances and modify the method handling of the - // first ConfigState only. - scs := spew.NewDefaultConfig() - scs2 := spew.NewDefaultConfig() - scs.DisableMethods = true - - // Alternatively - // scs := spew.ConfigState{Indent: " ", DisableMethods: true} - // scs2 := spew.ConfigState{Indent: " "} - - // This is of type Flag which implements a Stringer and has raw value 1. - f := flagTwo - - // Dump using the ConfigState instances. - scs.Printf("f: %v\n", f) - scs2.Printf("f: %v\n", f) - - // Output: - // f: 1 - // f: flagTwo -} diff --git a/src/vendor/github.com/davecgh/go-spew/spew/format_test.go b/src/vendor/github.com/davecgh/go-spew/spew/format_test.go deleted file mode 100644 index 87ee9651e363b2872cdbf57ed225d5143b6c3a04..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/davecgh/go-spew/spew/format_test.go +++ /dev/null @@ -1,1558 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -Test Summary: -NOTE: For each test, a nil pointer, a single pointer and double pointer to the -base test element are also tested to ensure proper indirection across all types. - -- Max int8, int16, int32, int64, int -- Max uint8, uint16, uint32, uint64, uint -- Boolean true and false -- Standard complex64 and complex128 -- Array containing standard ints -- Array containing type with custom formatter on pointer receiver only -- Array containing interfaces -- Slice containing standard float32 values -- Slice containing type with custom formatter on pointer receiver only -- Slice containing interfaces -- Nil slice -- Standard string -- Nil interface -- Sub-interface -- Map with string keys and int vals -- Map with custom formatter type on pointer receiver only keys and vals -- Map with interface keys and values -- Map with nil interface value -- Struct with primitives -- Struct that contains another struct -- Struct that contains custom type with Stringer pointer interface via both - exported and unexported fields -- Struct that contains embedded struct and field to same struct -- Uintptr to 0 (null pointer) -- Uintptr address of real variable -- Unsafe.Pointer to 0 (null pointer) -- Unsafe.Pointer to address of real variable -- Nil channel -- Standard int channel -- Function with no params and no returns -- Function with param and no returns -- Function with multiple params and multiple returns -- Struct that is circular through self referencing -- Structs that are circular through cross referencing -- Structs that are indirectly circular -- Type that panics in its Stringer interface -- Type that has a custom Error interface -- %x passthrough with uint -- %#x passthrough with uint -- %f passthrough with precision -- %f passthrough with width and precision -- %d passthrough with width -- %q passthrough with string -*/ - -package spew_test - -import ( - "bytes" - "fmt" - "testing" - "unsafe" - - "github.com/davecgh/go-spew/spew" -) - -// formatterTest is used to describe a test to be performed against NewFormatter. -type formatterTest struct { - format string - in interface{} - wants []string -} - -// formatterTests houses all of the tests to be performed against NewFormatter. -var formatterTests = make([]formatterTest, 0) - -// addFormatterTest is a helper method to append the passed input and desired -// result to formatterTests. -func addFormatterTest(format string, in interface{}, wants ...string) { - test := formatterTest{format, in, wants} - formatterTests = append(formatterTests, test) -} - -func addIntFormatterTests() { - // Max int8. - v := int8(127) - nv := (*int8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "int8" - vs := "127" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Max int16. - v2 := int16(32767) - nv2 := (*int16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "int16" - v2s := "32767" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Max int32. - v3 := int32(2147483647) - nv3 := (*int32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "int32" - v3s := "2147483647" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - - // Max int64. - v4 := int64(9223372036854775807) - nv4 := (*int64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "int64" - v4s := "9223372036854775807" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") - - // Max int. - v5 := int(2147483647) - nv5 := (*int)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "int" - v5s := "2147483647" - addFormatterTest("%v", v5, v5s) - addFormatterTest("%v", pv5, "<*>"+v5s) - addFormatterTest("%v", &pv5, "<**>"+v5s) - addFormatterTest("%v", nv5, "") - addFormatterTest("%+v", v5, v5s) - addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s) - addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%+v", nv5, "") - addFormatterTest("%#v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s) - addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s) - addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") - addFormatterTest("%#+v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s) - addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%#+v", nv5, "(*"+v5t+")"+"") -} - -func addUintFormatterTests() { - // Max uint8. - v := uint8(255) - nv := (*uint8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uint8" - vs := "255" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Max uint16. - v2 := uint16(65535) - nv2 := (*uint16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Max uint32. - v3 := uint32(4294967295) - nv3 := (*uint32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "uint32" - v3s := "4294967295" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - - // Max uint64. - v4 := uint64(18446744073709551615) - nv4 := (*uint64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "uint64" - v4s := "18446744073709551615" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") - - // Max uint. - v5 := uint(4294967295) - nv5 := (*uint)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "uint" - v5s := "4294967295" - addFormatterTest("%v", v5, v5s) - addFormatterTest("%v", pv5, "<*>"+v5s) - addFormatterTest("%v", &pv5, "<**>"+v5s) - addFormatterTest("%v", nv5, "") - addFormatterTest("%+v", v5, v5s) - addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s) - addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%+v", nv5, "") - addFormatterTest("%#v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s) - addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s) - addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") - addFormatterTest("%#+v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s) - addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") -} - -func addBoolFormatterTests() { - // Boolean true. - v := bool(true) - nv := (*bool)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "bool" - vs := "true" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Boolean false. - v2 := bool(false) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "bool" - v2s := "false" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addFloatFormatterTests() { - // Standard float32. - v := float32(3.1415) - nv := (*float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "float32" - vs := "3.1415" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Standard float64. - v2 := float64(3.1415926) - nv2 := (*float64)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "float64" - v2s := "3.1415926" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") -} - -func addComplexFormatterTests() { - // Standard complex64. - v := complex(float32(6), -2) - nv := (*complex64)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "complex64" - vs := "(6-2i)" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Standard complex128. - v2 := complex(float64(-6), 2) - nv2 := (*complex128)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "complex128" - v2s := "(-6+2i)" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") -} - -func addArrayFormatterTests() { - // Array containing standard ints. - v := [3]int{1, 2, 3} - nv := (*[3]int)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "[3]int" - vs := "[1 2 3]" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Array containing type with custom formatter on pointer receiver only. - v2 := [3]pstringer{"1", "2", "3"} - nv2 := (*[3]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "[3]spew_test.pstringer" - v2sp := "[stringer 1 stringer 2 stringer 3]" - v2s := v2sp - if spew.UnsafeDisabled { - v2s = "[1 2 3]" - } - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2sp) - addFormatterTest("%v", &pv2, "<**>"+v2sp) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2sp) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2sp) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2sp) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2sp) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2sp) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2sp) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Array containing interfaces. - v3 := [3]interface{}{"one", int(2), uint(3)} - nv3 := (*[3]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[3]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3s := "[one 2 3]" - v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3]" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") -} - -func addSliceFormatterTests() { - // Slice containing standard float32 values. - v := []float32{3.14, 6.28, 12.56} - nv := (*[]float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "[]float32" - vs := "[3.14 6.28 12.56]" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Slice containing type with custom formatter on pointer receiver only. - v2 := []pstringer{"1", "2", "3"} - nv2 := (*[]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "[]spew_test.pstringer" - v2s := "[stringer 1 stringer 2 stringer 3]" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Slice containing interfaces. - v3 := []interface{}{"one", int(2), uint(3), nil} - nv3 := (*[]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3t5 := "interface {}" - v3s := "[one 2 3 ]" - v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3 (" + v3t5 + - ")]" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") - - // Nil slice. - var v4 []int - nv4 := (*[]int)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "[]int" - v4s := "" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") -} - -func addStringFormatterTests() { - // Standard string. - v := "test" - nv := (*string)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "string" - vs := "test" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") -} - -func addInterfaceFormatterTests() { - // Nil interface. - var v interface{} - nv := (*interface{})(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "interface {}" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Sub-interface. - v2 := interface{}(uint16(65535)) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addMapFormatterTests() { - // Map with string keys and int vals. - v := map[string]int{"one": 1, "two": 2} - nilMap := map[string]int(nil) - nv := (*map[string]int)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "map[string]int" - vs := "map[one:1 two:2]" - vs2 := "map[two:2 one:1]" - addFormatterTest("%v", v, vs, vs2) - addFormatterTest("%v", pv, "<*>"+vs, "<*>"+vs2) - addFormatterTest("%v", &pv, "<**>"+vs, "<**>"+vs2) - addFormatterTest("%+v", nilMap, "") - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs, vs2) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs, "<*>("+vAddr+")"+vs2) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs, - "<**>("+pvAddr+"->"+vAddr+")"+vs2) - addFormatterTest("%+v", nilMap, "") - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs, "("+vt+")"+vs2) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs, "(*"+vt+")"+vs2) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs, "(**"+vt+")"+vs2) - addFormatterTest("%#v", nilMap, "("+vt+")"+"") - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs, "("+vt+")"+vs2) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs, - "(*"+vt+")("+vAddr+")"+vs2) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs, - "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs2) - addFormatterTest("%#+v", nilMap, "("+vt+")"+"") - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Map with custom formatter type on pointer receiver only keys and vals. - v2 := map[pstringer]pstringer{"one": "1"} - nv2 := (*map[pstringer]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "map[spew_test.pstringer]spew_test.pstringer" - v2s := "map[stringer one:stringer 1]" - if spew.UnsafeDisabled { - v2s = "map[one:1]" - } - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Map with interface keys and values. - v3 := map[interface{}]interface{}{"one": 1} - nv3 := (*map[interface{}]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "map[interface {}]interface {}" - v3t1 := "string" - v3t2 := "int" - v3s := "map[one:1]" - v3s2 := "map[(" + v3t1 + ")one:(" + v3t2 + ")1]" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") - - // Map with nil interface value - v4 := map[string]interface{}{"nil": nil} - nv4 := (*map[string]interface{})(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "map[string]interface {}" - v4t1 := "interface {}" - v4s := "map[nil:]" - v4s2 := "map[nil:(" + v4t1 + ")]" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s2) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s2) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s2) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s2) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s2) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s2) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") -} - -func addStructFormatterTests() { - // Struct with primitives. - type s1 struct { - a int8 - b uint8 - } - v := s1{127, 255} - nv := (*s1)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.s1" - vt2 := "int8" - vt3 := "uint8" - vs := "{127 255}" - vs2 := "{a:127 b:255}" - vs3 := "{a:(" + vt2 + ")127 b:(" + vt3 + ")255}" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs2) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs2) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs2) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs3) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs3) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs3) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs3) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs3) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs3) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Struct that contains another struct. - type s2 struct { - s1 s1 - b bool - } - v2 := s2{s1{127, 255}, true} - nv2 := (*s2)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.s2" - v2t2 := "spew_test.s1" - v2t3 := "int8" - v2t4 := "uint8" - v2t5 := "bool" - v2s := "{{127 255} true}" - v2s2 := "{s1:{a:127 b:255} b:true}" - v2s3 := "{s1:(" + v2t2 + "){a:(" + v2t3 + ")127 b:(" + v2t4 + ")255} b:(" + - v2t5 + ")true}" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s2) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s2) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s2) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s3) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s3) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s3) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s3) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s3) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s3) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Struct that contains custom type with Stringer pointer interface via both - // exported and unexported fields. - type s3 struct { - s pstringer - S pstringer - } - v3 := s3{"test", "test2"} - nv3 := (*s3)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.s3" - v3t2 := "spew_test.pstringer" - v3s := "{stringer test stringer test2}" - v3sp := v3s - v3s2 := "{s:stringer test S:stringer test2}" - v3s2p := v3s2 - v3s3 := "{s:(" + v3t2 + ")stringer test S:(" + v3t2 + ")stringer test2}" - v3s3p := v3s3 - if spew.UnsafeDisabled { - v3s = "{test test2}" - v3sp = "{test stringer test2}" - v3s2 = "{s:test S:test2}" - v3s2p = "{s:test S:stringer test2}" - v3s3 = "{s:(" + v3t2 + ")test S:(" + v3t2 + ")test2}" - v3s3p = "{s:(" + v3t2 + ")test S:(" + v3t2 + ")stringer test2}" - } - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3sp) - addFormatterTest("%v", &pv3, "<**>"+v3sp) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s2) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s2p) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s2p) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s3) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s3p) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s3p) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s3) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s3p) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s3p) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") - - // Struct that contains embedded struct and field to same struct. - e := embed{"embedstr"} - v4 := embedwrap{embed: &e, e: &e} - nv4 := (*embedwrap)(nil) - pv4 := &v4 - eAddr := fmt.Sprintf("%p", &e) - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "spew_test.embedwrap" - v4t2 := "spew_test.embed" - v4t3 := "string" - v4s := "{<*>{embedstr} <*>{embedstr}}" - v4s2 := "{embed:<*>(" + eAddr + "){a:embedstr} e:<*>(" + eAddr + - "){a:embedstr}}" - v4s3 := "{embed:(*" + v4t2 + "){a:(" + v4t3 + ")embedstr} e:(*" + v4t2 + - "){a:(" + v4t3 + ")embedstr}}" - v4s4 := "{embed:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 + - ")embedstr} e:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 + ")embedstr}}" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%+v", v4, v4s2) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s2) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s2) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s3) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s3) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s3) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s4) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s4) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s4) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") -} - -func addUintptrFormatterTests() { - // Null pointer. - v := uintptr(0) - nv := (*uintptr)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uintptr" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Address of real variable. - i := 1 - v2 := uintptr(unsafe.Pointer(&i)) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uintptr" - v2s := fmt.Sprintf("%p", &i) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addUnsafePointerFormatterTests() { - // Null pointer. - v := unsafe.Pointer(nil) - nv := (*unsafe.Pointer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "unsafe.Pointer" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Address of real variable. - i := 1 - v2 := unsafe.Pointer(&i) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "unsafe.Pointer" - v2s := fmt.Sprintf("%p", &i) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addChanFormatterTests() { - // Nil channel. - var v chan int - pv := &v - nv := (*chan int)(nil) - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "chan int" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Real channel. - v2 := make(chan int) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "chan int" - v2s := fmt.Sprintf("%p", v2) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addFuncFormatterTests() { - // Function with no params and no returns. - v := addIntFormatterTests - nv := (*func())(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "func()" - vs := fmt.Sprintf("%p", v) - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Function with param and no returns. - v2 := TestFormatter - nv2 := (*func(*testing.T))(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "func(*testing.T)" - v2s := fmt.Sprintf("%p", v2) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Function with multiple params and multiple returns. - var v3 = func(i int, s string) (b bool, err error) { - return true, nil - } - nv3 := (*func(int, string) (bool, error))(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "func(int, string) (bool, error)" - v3s := fmt.Sprintf("%p", v3) - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") -} - -func addCircularFormatterTests() { - // Struct that is circular through self referencing. - type circular struct { - c *circular - } - v := circular{nil} - v.c = &v - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.circular" - vs := "{<*>{<*>}}" - vs2 := "{<*>}" - vs3 := "{c:<*>(" + vAddr + "){c:<*>(" + vAddr + ")}}" - vs4 := "{c:<*>(" + vAddr + ")}" - vs5 := "{c:(*" + vt + "){c:(*" + vt + ")}}" - vs6 := "{c:(*" + vt + ")}" - vs7 := "{c:(*" + vt + ")(" + vAddr + "){c:(*" + vt + ")(" + vAddr + - ")}}" - vs8 := "{c:(*" + vt + ")(" + vAddr + ")}" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs2) - addFormatterTest("%v", &pv, "<**>"+vs2) - addFormatterTest("%+v", v, vs3) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs4) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs4) - addFormatterTest("%#v", v, "("+vt+")"+vs5) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs6) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs6) - addFormatterTest("%#+v", v, "("+vt+")"+vs7) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs8) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs8) - - // Structs that are circular through cross referencing. - v2 := xref1{nil} - ts2 := xref2{&v2} - v2.ps2 = &ts2 - pv2 := &v2 - ts2Addr := fmt.Sprintf("%p", &ts2) - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.xref1" - v2t2 := "spew_test.xref2" - v2s := "{<*>{<*>{<*>}}}" - v2s2 := "{<*>{<*>}}" - v2s3 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + "){ps2:<*>(" + - ts2Addr + ")}}}" - v2s4 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + ")}}" - v2s5 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + "){ps2:(*" + v2t2 + - ")}}}" - v2s6 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + ")}}" - v2s7 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t + - ")(" + v2Addr + "){ps2:(*" + v2t2 + ")(" + ts2Addr + - ")}}}" - v2s8 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t + - ")(" + v2Addr + ")}}" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s2) - addFormatterTest("%v", &pv2, "<**>"+v2s2) - addFormatterTest("%+v", v2, v2s3) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s4) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s4) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s5) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s6) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s6) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s7) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s8) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s8) - - // Structs that are indirectly circular. - v3 := indirCir1{nil} - tic2 := indirCir2{nil} - tic3 := indirCir3{&v3} - tic2.ps3 = &tic3 - v3.ps2 = &tic2 - pv3 := &v3 - tic2Addr := fmt.Sprintf("%p", &tic2) - tic3Addr := fmt.Sprintf("%p", &tic3) - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.indirCir1" - v3t2 := "spew_test.indirCir2" - v3t3 := "spew_test.indirCir3" - v3s := "{<*>{<*>{<*>{<*>}}}}" - v3s2 := "{<*>{<*>{<*>}}}" - v3s3 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" + - v3Addr + "){ps2:<*>(" + tic2Addr + ")}}}}" - v3s4 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" + - v3Addr + ")}}}" - v3s5 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t + - "){ps2:(*" + v3t2 + ")}}}}" - v3s6 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t + - ")}}}" - v3s7 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" + - tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + "){ps2:(*" + v3t2 + - ")(" + tic2Addr + ")}}}}" - v3s8 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" + - tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + ")}}}" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s2) - addFormatterTest("%v", &pv3, "<**>"+v3s2) - addFormatterTest("%+v", v3, v3s3) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s4) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s4) - addFormatterTest("%#v", v3, "("+v3t+")"+v3s5) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s6) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s6) - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s7) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s8) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s8) -} - -func addPanicFormatterTests() { - // Type that panics in its Stringer interface. - v := panicer(127) - nv := (*panicer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.panicer" - vs := "(PANIC=test panic)127" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") -} - -func addErrorFormatterTests() { - // Type that has a custom Error interface. - v := customError(127) - nv := (*customError)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.customError" - vs := "error: 127" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") -} - -func addPassthroughFormatterTests() { - // %x passthrough with uint. - v := uint(4294967295) - pv := &v - vAddr := fmt.Sprintf("%x", pv) - pvAddr := fmt.Sprintf("%x", &pv) - vs := "ffffffff" - addFormatterTest("%x", v, vs) - addFormatterTest("%x", pv, vAddr) - addFormatterTest("%x", &pv, pvAddr) - - // %#x passthrough with uint. - v2 := int(2147483647) - pv2 := &v2 - v2Addr := fmt.Sprintf("%#x", pv2) - pv2Addr := fmt.Sprintf("%#x", &pv2) - v2s := "0x7fffffff" - addFormatterTest("%#x", v2, v2s) - addFormatterTest("%#x", pv2, v2Addr) - addFormatterTest("%#x", &pv2, pv2Addr) - - // %f passthrough with precision. - addFormatterTest("%.2f", 3.1415, "3.14") - addFormatterTest("%.3f", 3.1415, "3.142") - addFormatterTest("%.4f", 3.1415, "3.1415") - - // %f passthrough with width and precision. - addFormatterTest("%5.2f", 3.1415, " 3.14") - addFormatterTest("%6.3f", 3.1415, " 3.142") - addFormatterTest("%7.4f", 3.1415, " 3.1415") - - // %d passthrough with width. - addFormatterTest("%3d", 127, "127") - addFormatterTest("%4d", 127, " 127") - addFormatterTest("%5d", 127, " 127") - - // %q passthrough with string. - addFormatterTest("%q", "test", "\"test\"") -} - -// TestFormatter executes all of the tests described by formatterTests. -func TestFormatter(t *testing.T) { - // Setup tests. - addIntFormatterTests() - addUintFormatterTests() - addBoolFormatterTests() - addFloatFormatterTests() - addComplexFormatterTests() - addArrayFormatterTests() - addSliceFormatterTests() - addStringFormatterTests() - addInterfaceFormatterTests() - addMapFormatterTests() - addStructFormatterTests() - addUintptrFormatterTests() - addUnsafePointerFormatterTests() - addChanFormatterTests() - addFuncFormatterTests() - addCircularFormatterTests() - addPanicFormatterTests() - addErrorFormatterTests() - addPassthroughFormatterTests() - - t.Logf("Running %d tests", len(formatterTests)) - for i, test := range formatterTests { - buf := new(bytes.Buffer) - spew.Fprintf(buf, test.format, test.in) - s := buf.String() - if testFailed(s, test.wants) { - t.Errorf("Formatter #%d format: %s got: %s %s", i, test.format, s, - stringizeWants(test.wants)) - continue - } - } -} - -type testStruct struct { - x int -} - -func (ts testStruct) String() string { - return fmt.Sprintf("ts.%d", ts.x) -} - -type testStructP struct { - x int -} - -func (ts *testStructP) String() string { - return fmt.Sprintf("ts.%d", ts.x) -} - -func TestPrintSortedKeys(t *testing.T) { - cfg := spew.ConfigState{SortKeys: true} - s := cfg.Sprint(map[int]string{1: "1", 3: "3", 2: "2"}) - expected := "map[1:1 2:2 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 1:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[stringer]int{"1": 1, "3": 3, "2": 2}) - expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 2:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2}) - expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]" - if spew.UnsafeDisabled { - expected = "map[1:1 2:2 3:3]" - } - if s != expected { - t.Errorf("Sorted keys mismatch 3:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[testStruct]int{{1}: 1, {3}: 3, {2}: 2}) - expected = "map[ts.1:1 ts.2:2 ts.3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 4:\n %v %v", s, expected) - } - - if !spew.UnsafeDisabled { - s = cfg.Sprint(map[testStructP]int{{1}: 1, {3}: 3, {2}: 2}) - expected = "map[ts.1:1 ts.2:2 ts.3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 5:\n %v %v", s, expected) - } - } - - s = cfg.Sprint(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2}) - expected = "map[error: 1:1 error: 2:2 error: 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 6:\n %v %v", s, expected) - } -} diff --git a/src/vendor/github.com/davecgh/go-spew/spew/internal_test.go b/src/vendor/github.com/davecgh/go-spew/spew/internal_test.go deleted file mode 100644 index e312b4fadc070b6c9cffa98a2666a6d61d146470..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/davecgh/go-spew/spew/internal_test.go +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -This test file is part of the spew package rather than than the spew_test -package because it needs access to internals to properly test certain cases -which are not possible via the public interface since they should never happen. -*/ - -package spew - -import ( - "bytes" - "reflect" - "testing" -) - -// dummyFmtState implements a fake fmt.State to use for testing invalid -// reflect.Value handling. This is necessary because the fmt package catches -// invalid values before invoking the formatter on them. -type dummyFmtState struct { - bytes.Buffer -} - -func (dfs *dummyFmtState) Flag(f int) bool { - return f == int('+') -} - -func (dfs *dummyFmtState) Precision() (int, bool) { - return 0, false -} - -func (dfs *dummyFmtState) Width() (int, bool) { - return 0, false -} - -// TestInvalidReflectValue ensures the dump and formatter code handles an -// invalid reflect value properly. This needs access to internal state since it -// should never happen in real code and therefore can't be tested via the public -// API. -func TestInvalidReflectValue(t *testing.T) { - i := 1 - - // Dump invalid reflect value. - v := new(reflect.Value) - buf := new(bytes.Buffer) - d := dumpState{w: buf, cs: &Config} - d.dump(*v) - s := buf.String() - want := "" - if s != want { - t.Errorf("InvalidReflectValue #%d\n got: %s want: %s", i, s, want) - } - i++ - - // Formatter invalid reflect value. - buf2 := new(dummyFmtState) - f := formatState{value: *v, cs: &Config, fs: buf2} - f.format(*v) - s = buf2.String() - want = "" - if s != want { - t.Errorf("InvalidReflectValue #%d got: %s want: %s", i, s, want) - } -} - -// SortValues makes the internal sortValues function available to the test -// package. -func SortValues(values []reflect.Value, cs *ConfigState) { - sortValues(values, cs) -} diff --git a/src/vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go b/src/vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go deleted file mode 100644 index 80dc22177db25720abc48df563ed6053c11dce5f..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) 2013-2016 Dave Collins - -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. - -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when the code is not running on Google App Engine, compiled by GopherJS, and -// "-tags safe" is not added to the go build command line. The "disableunsafe" -// tag is deprecated and thus should not be used. -// +build !js,!appengine,!safe,!disableunsafe,go1.4 - -/* -This test file is part of the spew package rather than than the spew_test -package because it needs access to internals to properly test certain cases -which are not possible via the public interface since they should never happen. -*/ - -package spew - -import ( - "bytes" - "reflect" - "testing" -) - -// changeKind uses unsafe to intentionally change the kind of a reflect.Value to -// the maximum kind value which does not exist. This is needed to test the -// fallback code which punts to the standard fmt library for new types that -// might get added to the language. -func changeKind(v *reflect.Value, readOnly bool) { - flags := flagField(v) - if readOnly { - *flags |= flagRO - } else { - *flags &^= flagRO - } - *flags |= flagKindMask -} - -// TestAddedReflectValue tests functionaly of the dump and formatter code which -// falls back to the standard fmt library for new types that might get added to -// the language. -func TestAddedReflectValue(t *testing.T) { - i := 1 - - // Dump using a reflect.Value that is exported. - v := reflect.ValueOf(int8(5)) - changeKind(&v, false) - buf := new(bytes.Buffer) - d := dumpState{w: buf, cs: &Config} - d.dump(v) - s := buf.String() - want := "(int8) 5" - if s != want { - t.Errorf("TestAddedReflectValue #%d\n got: %s want: %s", i, s, want) - } - i++ - - // Dump using a reflect.Value that is not exported. - changeKind(&v, true) - buf.Reset() - d.dump(v) - s = buf.String() - want = "(int8) " - if s != want { - t.Errorf("TestAddedReflectValue #%d\n got: %s want: %s", i, s, want) - } - i++ - - // Formatter using a reflect.Value that is exported. - changeKind(&v, false) - buf2 := new(dummyFmtState) - f := formatState{value: v, cs: &Config, fs: buf2} - f.format(v) - s = buf2.String() - want = "5" - if s != want { - t.Errorf("TestAddedReflectValue #%d got: %s want: %s", i, s, want) - } - i++ - - // Formatter using a reflect.Value that is not exported. - changeKind(&v, true) - buf2.Reset() - f = formatState{value: v, cs: &Config, fs: buf2} - f.format(v) - s = buf2.String() - want = "" - if s != want { - t.Errorf("TestAddedReflectValue #%d got: %s want: %s", i, s, want) - } -} diff --git a/src/vendor/github.com/davecgh/go-spew/spew/spew_test.go b/src/vendor/github.com/davecgh/go-spew/spew/spew_test.go deleted file mode 100644 index b70466c69f8e6443d35c9454f1222ddf3d279777..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/davecgh/go-spew/spew/spew_test.go +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew_test - -import ( - "bytes" - "fmt" - "io/ioutil" - "os" - "testing" - - "github.com/davecgh/go-spew/spew" -) - -// spewFunc is used to identify which public function of the spew package or -// ConfigState a test applies to. -type spewFunc int - -const ( - fCSFdump spewFunc = iota - fCSFprint - fCSFprintf - fCSFprintln - fCSPrint - fCSPrintln - fCSSdump - fCSSprint - fCSSprintf - fCSSprintln - fCSErrorf - fCSNewFormatter - fErrorf - fFprint - fFprintln - fPrint - fPrintln - fSdump - fSprint - fSprintf - fSprintln -) - -// Map of spewFunc values to names for pretty printing. -var spewFuncStrings = map[spewFunc]string{ - fCSFdump: "ConfigState.Fdump", - fCSFprint: "ConfigState.Fprint", - fCSFprintf: "ConfigState.Fprintf", - fCSFprintln: "ConfigState.Fprintln", - fCSSdump: "ConfigState.Sdump", - fCSPrint: "ConfigState.Print", - fCSPrintln: "ConfigState.Println", - fCSSprint: "ConfigState.Sprint", - fCSSprintf: "ConfigState.Sprintf", - fCSSprintln: "ConfigState.Sprintln", - fCSErrorf: "ConfigState.Errorf", - fCSNewFormatter: "ConfigState.NewFormatter", - fErrorf: "spew.Errorf", - fFprint: "spew.Fprint", - fFprintln: "spew.Fprintln", - fPrint: "spew.Print", - fPrintln: "spew.Println", - fSdump: "spew.Sdump", - fSprint: "spew.Sprint", - fSprintf: "spew.Sprintf", - fSprintln: "spew.Sprintln", -} - -func (f spewFunc) String() string { - if s, ok := spewFuncStrings[f]; ok { - return s - } - return fmt.Sprintf("Unknown spewFunc (%d)", int(f)) -} - -// spewTest is used to describe a test to be performed against the public -// functions of the spew package or ConfigState. -type spewTest struct { - cs *spew.ConfigState - f spewFunc - format string - in interface{} - want string -} - -// spewTests houses the tests to be performed against the public functions of -// the spew package and ConfigState. -// -// These tests are only intended to ensure the public functions are exercised -// and are intentionally not exhaustive of types. The exhaustive type -// tests are handled in the dump and format tests. -var spewTests []spewTest - -// redirStdout is a helper function to return the standard output from f as a -// byte slice. -func redirStdout(f func()) ([]byte, error) { - tempFile, err := ioutil.TempFile("", "ss-test") - if err != nil { - return nil, err - } - fileName := tempFile.Name() - defer os.Remove(fileName) // Ignore error - - origStdout := os.Stdout - os.Stdout = tempFile - f() - os.Stdout = origStdout - tempFile.Close() - - return ioutil.ReadFile(fileName) -} - -func initSpewTests() { - // Config states with various settings. - scsDefault := spew.NewDefaultConfig() - scsNoMethods := &spew.ConfigState{Indent: " ", DisableMethods: true} - scsNoPmethods := &spew.ConfigState{Indent: " ", DisablePointerMethods: true} - scsMaxDepth := &spew.ConfigState{Indent: " ", MaxDepth: 1} - scsContinue := &spew.ConfigState{Indent: " ", ContinueOnMethod: true} - scsNoPtrAddr := &spew.ConfigState{DisablePointerAddresses: true} - scsNoCap := &spew.ConfigState{DisableCapacities: true} - - // Variables for tests on types which implement Stringer interface with and - // without a pointer receiver. - ts := stringer("test") - tps := pstringer("test") - - type ptrTester struct { - s *struct{} - } - tptr := &ptrTester{s: &struct{}{}} - - // depthTester is used to test max depth handling for structs, array, slices - // and maps. - type depthTester struct { - ic indirCir1 - arr [1]string - slice []string - m map[string]int - } - dt := depthTester{indirCir1{nil}, [1]string{"arr"}, []string{"slice"}, - map[string]int{"one": 1}} - - // Variable for tests on types which implement error interface. - te := customError(10) - - spewTests = []spewTest{ - {scsDefault, fCSFdump, "", int8(127), "(int8) 127\n"}, - {scsDefault, fCSFprint, "", int16(32767), "32767"}, - {scsDefault, fCSFprintf, "%v", int32(2147483647), "2147483647"}, - {scsDefault, fCSFprintln, "", int(2147483647), "2147483647\n"}, - {scsDefault, fCSPrint, "", int64(9223372036854775807), "9223372036854775807"}, - {scsDefault, fCSPrintln, "", uint8(255), "255\n"}, - {scsDefault, fCSSdump, "", uint8(64), "(uint8) 64\n"}, - {scsDefault, fCSSprint, "", complex(1, 2), "(1+2i)"}, - {scsDefault, fCSSprintf, "%v", complex(float32(3), 4), "(3+4i)"}, - {scsDefault, fCSSprintln, "", complex(float64(5), 6), "(5+6i)\n"}, - {scsDefault, fCSErrorf, "%#v", uint16(65535), "(uint16)65535"}, - {scsDefault, fCSNewFormatter, "%v", uint32(4294967295), "4294967295"}, - {scsDefault, fErrorf, "%v", uint64(18446744073709551615), "18446744073709551615"}, - {scsDefault, fFprint, "", float32(3.14), "3.14"}, - {scsDefault, fFprintln, "", float64(6.28), "6.28\n"}, - {scsDefault, fPrint, "", true, "true"}, - {scsDefault, fPrintln, "", false, "false\n"}, - {scsDefault, fSdump, "", complex(-10, -20), "(complex128) (-10-20i)\n"}, - {scsDefault, fSprint, "", complex(-1, -2), "(-1-2i)"}, - {scsDefault, fSprintf, "%v", complex(float32(-3), -4), "(-3-4i)"}, - {scsDefault, fSprintln, "", complex(float64(-5), -6), "(-5-6i)\n"}, - {scsNoMethods, fCSFprint, "", ts, "test"}, - {scsNoMethods, fCSFprint, "", &ts, "<*>test"}, - {scsNoMethods, fCSFprint, "", tps, "test"}, - {scsNoMethods, fCSFprint, "", &tps, "<*>test"}, - {scsNoPmethods, fCSFprint, "", ts, "stringer test"}, - {scsNoPmethods, fCSFprint, "", &ts, "<*>stringer test"}, - {scsNoPmethods, fCSFprint, "", tps, "test"}, - {scsNoPmethods, fCSFprint, "", &tps, "<*>stringer test"}, - {scsMaxDepth, fCSFprint, "", dt, "{{} [] [] map[]}"}, - {scsMaxDepth, fCSFdump, "", dt, "(spew_test.depthTester) {\n" + - " ic: (spew_test.indirCir1) {\n \n },\n" + - " arr: ([1]string) (len=1 cap=1) {\n \n },\n" + - " slice: ([]string) (len=1 cap=1) {\n \n },\n" + - " m: (map[string]int) (len=1) {\n \n }\n}\n"}, - {scsContinue, fCSFprint, "", ts, "(stringer test) test"}, - {scsContinue, fCSFdump, "", ts, "(spew_test.stringer) " + - "(len=4) (stringer test) \"test\"\n"}, - {scsContinue, fCSFprint, "", te, "(error: 10) 10"}, - {scsContinue, fCSFdump, "", te, "(spew_test.customError) " + - "(error: 10) 10\n"}, - {scsNoPtrAddr, fCSFprint, "", tptr, "<*>{<*>{}}"}, - {scsNoPtrAddr, fCSSdump, "", tptr, "(*spew_test.ptrTester)({\ns: (*struct {})({\n})\n})\n"}, - {scsNoCap, fCSSdump, "", make([]string, 0, 10), "([]string) {\n}\n"}, - {scsNoCap, fCSSdump, "", make([]string, 1, 10), "([]string) (len=1) {\n(string) \"\"\n}\n"}, - } -} - -// TestSpew executes all of the tests described by spewTests. -func TestSpew(t *testing.T) { - initSpewTests() - - t.Logf("Running %d tests", len(spewTests)) - for i, test := range spewTests { - buf := new(bytes.Buffer) - switch test.f { - case fCSFdump: - test.cs.Fdump(buf, test.in) - - case fCSFprint: - test.cs.Fprint(buf, test.in) - - case fCSFprintf: - test.cs.Fprintf(buf, test.format, test.in) - - case fCSFprintln: - test.cs.Fprintln(buf, test.in) - - case fCSPrint: - b, err := redirStdout(func() { test.cs.Print(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fCSPrintln: - b, err := redirStdout(func() { test.cs.Println(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fCSSdump: - str := test.cs.Sdump(test.in) - buf.WriteString(str) - - case fCSSprint: - str := test.cs.Sprint(test.in) - buf.WriteString(str) - - case fCSSprintf: - str := test.cs.Sprintf(test.format, test.in) - buf.WriteString(str) - - case fCSSprintln: - str := test.cs.Sprintln(test.in) - buf.WriteString(str) - - case fCSErrorf: - err := test.cs.Errorf(test.format, test.in) - buf.WriteString(err.Error()) - - case fCSNewFormatter: - fmt.Fprintf(buf, test.format, test.cs.NewFormatter(test.in)) - - case fErrorf: - err := spew.Errorf(test.format, test.in) - buf.WriteString(err.Error()) - - case fFprint: - spew.Fprint(buf, test.in) - - case fFprintln: - spew.Fprintln(buf, test.in) - - case fPrint: - b, err := redirStdout(func() { spew.Print(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fPrintln: - b, err := redirStdout(func() { spew.Println(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fSdump: - str := spew.Sdump(test.in) - buf.WriteString(str) - - case fSprint: - str := spew.Sprint(test.in) - buf.WriteString(str) - - case fSprintf: - str := spew.Sprintf(test.format, test.in) - buf.WriteString(str) - - case fSprintln: - str := spew.Sprintln(test.in) - buf.WriteString(str) - - default: - t.Errorf("%v #%d unrecognized function", test.f, i) - continue - } - s := buf.String() - if test.want != s { - t.Errorf("ConfigState #%d\n got: %s want: %s", i, s, test.want) - continue - } - } -} diff --git a/src/vendor/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go b/src/vendor/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go deleted file mode 100644 index 5c87dd456ed031deaca010e64a7ed55168df66b3..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) 2013 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when both cgo is supported and "-tags testcgo" is added to the go test -// command line. This code should really only be in the dumpcgo_test.go file, -// but unfortunately Go will not allow cgo in test files, so this is a -// workaround to allow cgo types to be tested. This configuration is used -// because spew itself does not require cgo to run even though it does handle -// certain cgo types specially. Rather than forcing all clients to require cgo -// and an external C compiler just to run the tests, this scheme makes them -// optional. -// +build cgo,testcgo - -package testdata - -/* -#include -typedef unsigned char custom_uchar_t; - -char *ncp = 0; -char *cp = "test"; -char ca[6] = {'t', 'e', 's', 't', '2', '\0'}; -unsigned char uca[6] = {'t', 'e', 's', 't', '3', '\0'}; -signed char sca[6] = {'t', 'e', 's', 't', '4', '\0'}; -uint8_t ui8ta[6] = {'t', 'e', 's', 't', '5', '\0'}; -custom_uchar_t tuca[6] = {'t', 'e', 's', 't', '6', '\0'}; -*/ -import "C" - -// GetCgoNullCharPointer returns a null char pointer via cgo. This is only -// used for tests. -func GetCgoNullCharPointer() interface{} { - return C.ncp -} - -// GetCgoCharPointer returns a char pointer via cgo. This is only used for -// tests. -func GetCgoCharPointer() interface{} { - return C.cp -} - -// GetCgoCharArray returns a char array via cgo and the array's len and cap. -// This is only used for tests. -func GetCgoCharArray() (interface{}, int, int) { - return C.ca, len(C.ca), cap(C.ca) -} - -// GetCgoUnsignedCharArray returns an unsigned char array via cgo and the -// array's len and cap. This is only used for tests. -func GetCgoUnsignedCharArray() (interface{}, int, int) { - return C.uca, len(C.uca), cap(C.uca) -} - -// GetCgoSignedCharArray returns a signed char array via cgo and the array's len -// and cap. This is only used for tests. -func GetCgoSignedCharArray() (interface{}, int, int) { - return C.sca, len(C.sca), cap(C.sca) -} - -// GetCgoUint8tArray returns a uint8_t array via cgo and the array's len and -// cap. This is only used for tests. -func GetCgoUint8tArray() (interface{}, int, int) { - return C.ui8ta, len(C.ui8ta), cap(C.ui8ta) -} - -// GetCgoTypdefedUnsignedCharArray returns a typedefed unsigned char array via -// cgo and the array's len and cap. This is only used for tests. -func GetCgoTypdefedUnsignedCharArray() (interface{}, int, int) { - return C.tuca, len(C.tuca), cap(C.tuca) -} diff --git a/src/vendor/github.com/davecgh/go-spew/test_coverage.txt b/src/vendor/github.com/davecgh/go-spew/test_coverage.txt deleted file mode 100644 index 2cd087a2a1273c5446897521ae85658fb8e66def..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/davecgh/go-spew/test_coverage.txt +++ /dev/null @@ -1,61 +0,0 @@ - -github.com/davecgh/go-spew/spew/dump.go dumpState.dump 100.00% (88/88) -github.com/davecgh/go-spew/spew/format.go formatState.format 100.00% (82/82) -github.com/davecgh/go-spew/spew/format.go formatState.formatPtr 100.00% (52/52) -github.com/davecgh/go-spew/spew/dump.go dumpState.dumpPtr 100.00% (44/44) -github.com/davecgh/go-spew/spew/dump.go dumpState.dumpSlice 100.00% (39/39) -github.com/davecgh/go-spew/spew/common.go handleMethods 100.00% (30/30) -github.com/davecgh/go-spew/spew/common.go printHexPtr 100.00% (18/18) -github.com/davecgh/go-spew/spew/common.go unsafeReflectValue 100.00% (13/13) -github.com/davecgh/go-spew/spew/format.go formatState.constructOrigFormat 100.00% (12/12) -github.com/davecgh/go-spew/spew/dump.go fdump 100.00% (11/11) -github.com/davecgh/go-spew/spew/format.go formatState.Format 100.00% (11/11) -github.com/davecgh/go-spew/spew/common.go init 100.00% (10/10) -github.com/davecgh/go-spew/spew/common.go printComplex 100.00% (9/9) -github.com/davecgh/go-spew/spew/common.go valuesSorter.Less 100.00% (8/8) -github.com/davecgh/go-spew/spew/format.go formatState.buildDefaultFormat 100.00% (7/7) -github.com/davecgh/go-spew/spew/format.go formatState.unpackValue 100.00% (5/5) -github.com/davecgh/go-spew/spew/dump.go dumpState.indent 100.00% (4/4) -github.com/davecgh/go-spew/spew/common.go catchPanic 100.00% (4/4) -github.com/davecgh/go-spew/spew/config.go ConfigState.convertArgs 100.00% (4/4) -github.com/davecgh/go-spew/spew/spew.go convertArgs 100.00% (4/4) -github.com/davecgh/go-spew/spew/format.go newFormatter 100.00% (3/3) -github.com/davecgh/go-spew/spew/dump.go Sdump 100.00% (3/3) -github.com/davecgh/go-spew/spew/common.go printBool 100.00% (3/3) -github.com/davecgh/go-spew/spew/common.go sortValues 100.00% (3/3) -github.com/davecgh/go-spew/spew/config.go ConfigState.Sdump 100.00% (3/3) -github.com/davecgh/go-spew/spew/dump.go dumpState.unpackValue 100.00% (3/3) -github.com/davecgh/go-spew/spew/spew.go Printf 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Println 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Sprint 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Sprintf 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Sprintln 100.00% (1/1) -github.com/davecgh/go-spew/spew/common.go printFloat 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go NewDefaultConfig 100.00% (1/1) -github.com/davecgh/go-spew/spew/common.go printInt 100.00% (1/1) -github.com/davecgh/go-spew/spew/common.go printUint 100.00% (1/1) -github.com/davecgh/go-spew/spew/common.go valuesSorter.Len 100.00% (1/1) -github.com/davecgh/go-spew/spew/common.go valuesSorter.Swap 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Errorf 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Fprint 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Fprintf 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Fprintln 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Print 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Printf 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Println 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Sprint 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Sprintf 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Sprintln 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.NewFormatter 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Fdump 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Dump 100.00% (1/1) -github.com/davecgh/go-spew/spew/dump.go Fdump 100.00% (1/1) -github.com/davecgh/go-spew/spew/dump.go Dump 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Fprintln 100.00% (1/1) -github.com/davecgh/go-spew/spew/format.go NewFormatter 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Errorf 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Fprint 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Fprintf 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Print 100.00% (1/1) -github.com/davecgh/go-spew/spew ------------------------------- 100.00% (505/505) - diff --git a/src/vendor/github.com/opencontainers/runtime-spec/.gitattributes b/src/vendor/github.com/opencontainers/runtime-spec/.gitattributes deleted file mode 100644 index 558b67f89bd81a16a4481efcb72fc8705fbfbcb5..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -# https://tools.ietf.org/html/rfc5545#section-3.1 -*.ics text eol=crlf diff --git a/src/vendor/github.com/opencontainers/runtime-spec/.gitignore b/src/vendor/github.com/opencontainers/runtime-spec/.gitignore deleted file mode 100644 index f9663c923f1e26e76466ade4e96a1a1b3ca265e8..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -output -schema/validate -version.md diff --git a/src/vendor/github.com/opencontainers/runtime-spec/.mailmap b/src/vendor/github.com/opencontainers/runtime-spec/.mailmap deleted file mode 100644 index 346194c50c7b4a8fe213c718ab3e91d4d1f30463..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/.mailmap +++ /dev/null @@ -1,21 +0,0 @@ -Aleksa Sarai -Alexander Morozov -Amit Saha -Antonio Murdaca -Brandon Philips -Brandon Philips -ChengTiesheng -Daniel, Dao Quang Minh -Doug Davis -James O. D. Hunt -John Howard -LinZhinan(Zen Lin) -Mrunal Patel -Mrunal Patel -Mrunal Patel -Vincent Batts -Vincent Batts -Vishnu Kannan -Vishnu Kannan -Zefan Li -梁辰晔 (Liang Chenye) diff --git a/src/vendor/github.com/opencontainers/runtime-spec/.pullapprove.yml b/src/vendor/github.com/opencontainers/runtime-spec/.pullapprove.yml deleted file mode 100644 index a7efacfe70c9759c282a5367ac59772cf261f5b3..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/.pullapprove.yml +++ /dev/null @@ -1,27 +0,0 @@ -version: 2 - -requirements: - signed_off_by: - required: true - -group_defaults: - required: 2 - approve_by_comment: - enabled: true - approve_regex: ^LGTM - reject_regex: ^Rejected - reset_on_push: - enabled: true - author_approval: - ignored: true - always_pending: - title_regex: ^WIP - explanation: 'Work in progress...' - conditions: - branches: - - master - -groups: - runtime-spec: - teams: - - runtime-spec-maintainers diff --git a/src/vendor/github.com/opencontainers/runtime-spec/.tool/version-doc.go b/src/vendor/github.com/opencontainers/runtime-spec/.tool/version-doc.go deleted file mode 100644 index f36bfe4c36f296ccad91c4083cc12fe8b960d2ca..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/.tool/version-doc.go +++ /dev/null @@ -1,25 +0,0 @@ -// +build ignore - -package main - -import ( - "fmt" - "html/template" - "os" - - "github.com/opencontainers/runtime-spec/specs-go" -) - -var markdownTemplateString = ` - -**Specification Version:** *{{.}}* - -` - -var markdownTemplate = template.Must(template.New("markdown").Parse(markdownTemplateString)) - -func main() { - if err := markdownTemplate.Execute(os.Stdout, specs.Version); err != nil { - fmt.Fprintln(os.Stderr, err) - } -} diff --git a/src/vendor/github.com/opencontainers/runtime-spec/.travis.yml b/src/vendor/github.com/opencontainers/runtime-spec/.travis.yml deleted file mode 100644 index 7c2de7e718d202fc6af9fe22468283425df25d37..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/.travis.yml +++ /dev/null @@ -1,25 +0,0 @@ -language: go -go: - - 1.7 - - 1.6.3 - - 1.5.4 - -sudo: required - -services: - - docker - -before_install: - - make install.tools - - docker pull vbatts/pandoc - -install: true - -script: - - env | grep TRAVIS_ - - make .govet - - make .golint - - echo "${TRAVIS_COMMIT_RANGE} -> ${TRAVIS_COMMIT_RANGE/.../..} (travis-ci/travis-ci#4596)" - - TRAVIS_COMMIT_RANGE="${TRAVIS_COMMIT_RANGE/.../..}" make .gitvalidation - - make docs - - make -C schema test diff --git a/src/vendor/github.com/opencontainers/runtime-spec/ChangeLog b/src/vendor/github.com/opencontainers/runtime-spec/ChangeLog deleted file mode 100644 index 9849dc715355535483a4be216cb4bef5140a9b05..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/ChangeLog +++ /dev/null @@ -1,684 +0,0 @@ -OpenContainers Specifications - -Changes with v1.0.1: - - Minor fixes and documentation: - - * spec: Expand "OCI" in spec-title reference and add "Initiative" - (#900) - * config: Simplify title to "Configuration" (#901) - * config: Fix "procfs_2" -> "proc_2" link label (#906) - * config: Fix IEEE Std 1003.1-2008 exec link markup (#913) - * config: Add a trailing period to the "cannot be mapped" rlimits - line (#915) - * config-linux: RFC 2119 MUST for absolute linux.namespaces[].path - (#925). This is technically a breaking change, because a config - with a relative namespace path would have been compliant before, - but will be non compliant with this change. However, the previous - "an absolute path to namespace file" wording was clear enough that - config authors are unlikely to be relying on relative namespace - paths in configs. - * config-linux: More specific documentation for weightDevice and - throttle* (#825) - * config-linux: Modify procfs to proc (#905) - * config-linux: Fix "psuedo" -> "pseudo" typo (#921) - * config-windows: Make maximum a uint16 (was a uint) (#891) - * runtime: Change "process in the container" -> "container - process" (#907) - * schema/config-schema: Use ArrayOfStrings in capabilities - properties. (#886) - * schema/config-linux: - s/throttleWriteIopsDevice/throttleWriteIOPSDevice/ (#899) - * schema/config-linux: add intelRdt field (#889) - * schema/config-solaris: Replaced refs with some fields - (cappedCPU.ncpus, etc.) (#892) - -Changes with v1.0.0: - - Breaking changes: - - * config: Shift disableOOMKiller from linux.resources to - linux.resources.memory (#896) - - Decreased restrictions: - - * runtime: Make the state JSON's pid optional on non-Linux platforms - (#897) - - Minor fixes and documentation: - - * schema/defs-linux: Require Syscall.action (#885) - * specs-go/config: Fix 'omiempty' -> 'omitempty' typo for - LinuxSeccompArg.ValueTwo (#884) - * ROAMAP: remove the pre-v1.0.0 roadmap (#890) - -Changes with v1.0.0-rc6: - - Breaking changes: - - * config: Shift oomScoreAdj to process and add RFC 2119 requirements - for the runtime (#781, #789, #836) - * config: Forbid 'root' on Hyper-V (#820, #838). - * config: process.capabilities and process.noNewPrivileges are - Linux-only again (#880). This partially reverses #673, which had - landed in v1.0.0-rc5. - * config: Remove process.rlimits from Windows (#880). It is now - POSIX-only, while in v1.0.0-rc5 it was cross-platform (because of - #673). Before #673 (in v1.0.0-rc4 and earlier), it was - Linux-only. - * config-linux: Drop redundant 'blkio' prefix from blockIO - properties (#860) - * config-linux: Make memory limits int64 instead of uint64 (#876). - This partially reverses #704, which had landed in v1.0.0-rc5. - * config-windows: Change CPU 'percent' to 'maximum' (#777) - * config-windows: Remove memory 'reservation' (#788) - * config-windows: Remove 'resources.network' and add 'network' (#801) - - Additions: - - * config: Windows runtimes MUST support the 'ro' mount option (#868) - * config-linux: Add Intel RDT/CAT Linux support (#630, #787) - * config-linux: Add Markdown specification for syscalls (#706) - * config-linux: Add 'unbindable' rootfsPropagation value (#770, #775) - * config-windows: Add 'credentialSpec' (#814, #859) - * config-windows: Add 'servicing' (#815) - * config-windows: Add 'ignoreFlushesDuringBoot' (#816, #859) - * config-windows: Add 'hyperv' (#818, #849, #859) - * config-windows: Add 'layerFolders' (#828) - - Removals and increased restrictions: - - * config: Remove 'platform' (#850) - * config: Require strictly-postitive 'timeout' values (#764) - * config: Strengthen punt to kernel for valid capabilities strings - (#766, #790) - * config: Require volume GUID paths for root.path (#849) - * config: Forbid setting 'readonly' true on Windows (#819) - * config: Forbid setting mount 'type' entirely on Windows and forbid - UNC paths and mapped drives in 'source' on Windows (#821) - * config: Remove 'hooks' from Windows spec (#855, #869, #870) - * config-linux: Clearly require absolute path for namespace (#720) - * config-linux: RFC 2119 tightening for namespaces (#767) - * config-linux: Require at least one entry in - linux.seccomp.syscalls[].names (#769) - * config-linux: Remove syscall.comment (#714) - * config-linux: Use MUST and MAY for weight and leafWeight (#751) - * config-linux: Remove explicit 'null' from device cgroup values - (#804) - * runtime: Remove "features the runtime chooses to support" (#732) - * runtime: Drop "not supported by the base OS" loophole (#733) - * runtime-linux: Condition /proc/self/fd symlinks on source - existence (#736) - - Decreased restrictions: - - * config: Make 'process' optional (#701, #805) - * config-linux: Make linux.seccomp.syscalls optional (#768) - * config-linux: valueTwo is now optional in - `linux.seccomp.syscalls[].args` entries (#877) - * config-linux: Remove local range restrictions for blkioWeight, - blkioLeafWeight, weight, leafWeight, and shares (#780) - * config-linux: Explicitly allow symlinks for providing devices (#873) - - Minor fixes and documentation: - - * config: Remove "MAY support any valid values" sentence (#851) - * config: Remove the previously-forbidden mounts[].type from the - Windows spec (#854) - * config: Clarify mounts[].source relative path anchor (#735) - * config: Explicitly make consoleSize ignored if terminal is false or - unset (#863) - * config: Specify height/width units (characters) for consoleSize (#761) - * config: Use "POSIX platforms" instead of "Linux and Solaris" (#838) - * config-linux: Explicit namespace for interface names (#713) - * config-linux: Explicitly list cgroupsPath as optional (#823) - * runtime: Clarify valid container states for 'start', 'kill', and - 'delete' (#875) - * runtime: Explicitly make process.* timing implementation-defined (#700) - * specs-go/config: Remove range restrictions from Windows comments (#783) - * specs-go/config: Add omitempty to LinuxSyscall.Args (#763) - * specs-go/config: Use a pointer for Process.ConsoleSize (#792) - * schema/README: Use v1.0.0 URL in examples to prepare for the 1.0.0 - release (#881) - * schema/Makefile: Make 'validate' the default target (#750) - * schema/Makefile: Add 'clean' target (#774) - * schema: Add 'test' target to the Makefile (#785) - * *: Remove unnecessary .PHONY entries (#750, #778, #802) - * *: Typo fixes and polishing (#681, #708, #702, #703, #709, #711, - #712, #721, #722, #723, #724, #730, #737, #738, #741, #744, #749, - #753, #756, #765, #773, #776, #784, #786, #793, #794, #796, #798, - #799, #800, #803, #807, #809, #811, #812, #822, #824, #826, #827, - #832, #839, #840, #846, #847, #848, #852, #856, #858, #862, #865, - #871, #874) - -Changes with v1.0.0-rc5: - - Breaking changes: - - * config: Explicitly require `platform` (#695). - * config: The platform-specific sections (`linux`, `solaris`, and - `windows`) MUST NOT be set unless they match `platform.os` (#673). - * config: `process.capabilities` is now an object instead of an - array of strings (#675). - * config-linux: No longer allow negative values for some resources, - partially reversing #648 from v1.0.0-rc4 (#704). - * config-linux: `linux.seccomp.syscalls` entries have `names` - instead of `name` (#657). - * runtime: Rename the state `bundlePath` property to `bundle` - (#674). - - Additions: - - * config: `process.capabilities` is no longer Linux-only (#673). - * config-linux: `linux.seccomp.syscalls` entries have a new - `comment` property (#657). - * config-linux: Add new architectures from libseccomp 2.3.2 (#705) - * runtime: Add a `creating` state `status` (#507, #694). - - Removals and increased restrictions: - - * runtime: Document hook timing and exit code handling (#532). - * schema/config-linux: Explicit `null` values are no longer - compliant (#662). - - Decreased restrictions: - - * config: `type` and `source` properties are now optional for - `mounts` entries (#699). - * config: `args` property is now optional for hooks (#685). - * config-linux: Runtimes no longer need to provide `/proc` and - other filesystems unless they are explicitly requested in the - configuration JSON (#666). - - Minor fixes and documentation: - - * spec: Add OCI Runtime Abstract (#691). - * config: Document the Go `platform` tag (#570). - * config-linux: Remove local uid/gid mapping limit and punt to the - kernel (#693). - * schema: Fix broken `string` and similar `$ref`s (#684). - * schema: Remove `mounts` from required properties (#696). - * schema: Remove `major` and `minor` from `linux.devices` entries - (#688). - * schema: Check for the required `type`, `hard`, and `soft` in - `process.rlimits` entries (#696). - * schema/validate: Gained usage documentation and fixed - `schemaPath` logic when the argument did not contain `://` (#552). - * *: Add anchor tags to a number of spec locations (#707). - * *: Consistent link syntax (#687). - * *: Minor cleanup and rewording (#697). - -Changes with v1.0.0-rc4: - Additions: - - * config-linux: Allow negative values for some resources (#648) - * config-linux: Lift no-tweaking namespace restriction (#649) - - Removals and increased restrictions: - - * config: Rlimit types must be unique (#607) - * config: Forbid empty-string keys in 'annotations' (#645, #654) - * config-linux: Require runtime errors for pre-existing devices - (#647) - * runtime: Only require 'pid' in the state for created/running - statuses (#664) - * schema: Add 'consoleSize' and update requirements (#646) - * schema: Remove string pointers (#656) - * schema/config-linux: Remove blockIODeviceThrottle and other - pointers (#545) - - Breaking Go changes: - - * specs-go/config: Remove string pointers (#653) - * specs-go/config: Make Spec.Hooks a pointer (#427) - * specs-go/config: Convert some resources from unsigned integers - to signed integers (#648) - - Minor fixes and documentation: - - * config: Explicitly list 'hooks' as optional and cite POSIX for - 'env' and 'args' (#427) - * runtime: Replace "process is stopped" with "process exits" - (#465) - * schema/config-linux: Add missing kernelTCP (#655) - * schema/validate: Allow schema identifiers to contain a URL - scheme (#490) - * .travis: Fix git-validation commit ranges (#216) - * *: Add anchor tags to a number of spec locations (#612, #636, - #637, #638, #639, #640) - * *: Typo fixes and polishing (#643, #650, #652, #656, #660, #665) - -Changes with v1.0.0-rc3: - Additions: - - * config: Add support for Windows-based containers (#565, #573) - * config: Add process.consoleSize (#563) - * config: Explicitly allow unknown extensions and document - annotations key conventions (#510) - * config: Define mounts entries for Solaris (#588) - - Removals and increased restrictions: - - * config: Require absolute paths for mount destinations (#609) - * config-linux: Require absolute path for maskedPaths and - readonlyPaths (#587) - * config-linux: Only require /dev/console when process.terminal is - true. Also require /dev/console to be provided by a bind mount - (#518) - * runtime: Require runtimes to generate errors when the container - specified in config.json cannot be created (#559) - - Breaking Go changes: - - * specs-go/config: Aggressive namespacing (#567) - * specs-go/config: Remove pointers from LinuxHugepageLimit, - LinuxInterfacePriority, and LinuxPids properties (#586) - * specs-go/state: Rename version to ociVersion (#633) - LinuxInterfacePriority, and LinuxPids properties (#586) - - Minor fixes and documentation: - - * spec: Separate the spec from project scaffolding (#626) - * README: Define "unspecified", "undefined", and - "implementation-defined" (#575) - * config: Clarify absolue and relative values for root.path (#558) - * config: Clarify ociVersion covering the configuration <-> - runtime API (#523) - * config-linux: Forbid duplicated namespaces with same `type` - (#597) - * glossary: Make objects explicitly unordered and forbid duplicate - names (#584) - * specs-go/config: Add platform tags to Rlimits and - NoNewPRivileges (#564) - * schema/defs-linux: Use int64 for major/minor types (#610) - * Makefile: Add support for Go 1.7 (#547) - * Makefile: Require Go >= 1.6 for golint (#589) - * Makefile: Use a POSIX-compatible test ('==' -> '=') (#542) - * implementations: Rename ocitools -> runtime-tools (#585) - * *: Typo fixes and polishing (#556, #566, #568, #569, #571, #572, - #574, #595, #596, #599, #600, #601, #603, #605, #608, #613, #617, - #619, #621, #622, #623, #624, #625, #627, #629) - -Changes with v1.0.0-rc2: - Additions: - - * config-linux: Add new architectures from libseccomp 2.3.0 (#505) - * schema: Add JSON Schema for state JSON and move schema.json to - config-schema.json and similar (#481, #498, #519) - - Minor fixes and documentation: - - * Add compliance language for platforms and architectures (#527) - * Remove "unconditionally compliant" language (#553) - * bundle: Remove distribution references (#487) - * runtime: Fix sub-bullet indentation (#495) - * config: Replace Arch fstab reference with mount(8) (#443) - * config: Synchronize comments between Markdown and Go (#525) - * config: Drop v0.x compatibility statement (#488) - * config-linux: RFC 2119 wording for cgroupsPath (#493) - * config-linux: Make linux.devices and linux.resources.devices - optional (#526) - * config-linux: Extend no-tweak requirement to runtime namespaces (#538) - * schema: Add hook.timeout (#544) - * schema: Add missing '"type": "object"' (#528) - * schema: Run 'make fmt' and remove duplicates (#546, #551) - * schema/config: Make 'hostname' optional (#491) - * schema/config-linux: Add linux.resources.devices (#550) - * specs-go/config: Add Solaris tags to User properties (#496) - * specs-go/config: Make Linux and Solaris omitempty again (#502) - * specs-go/config: Make KernelTCP and ClassID omitempty (#531) - * specs-go/config: Fix "specified" typo for ApparmorProfile (#503) - * Makefile: Remove code-of-conduct.md and version.md when clean (#541) - * implementations: Mention cc-oci-runtime (#539) - * Use filesystem instead of file system (#529) - * .pullapprove: Add DCO check via PullApprove - * GOVERNANCE: Add governance and release process docs (#521) - * README: Change meeting time from 10am to 2pm Pacific (#524) - * README: Update conference-call phone number (#512, #515) - -Changes with v1.0.0-rc1: - Breaking changes: - - * runtime: Split create and start, #384, #450, #463, #464, #467, - #468 - * runtime: Remove exec, #388 - * runtime: Enviroment MUST match the configuration, #397 - * config: Runtime MUST generate errors for unsupported platforms, - #441 - * config: Windows mount destinations MUST NOT be nested, #437 - - Additions: - - * solaris: Added platform-specific configuration, #411, #424, #431, - #436 - * runtime: Add 'annotations' and 'status' to the state structure, - #462, #484, #485 - * runtime: State no longer needs to be serialized as JSON, #446 - * runtime-linux: Add /dev symbolic links, #449 - * config: Allow absolute paths for root.path (which previously - required relative paths), #394 - * config-linux: Add linux.mountLabel, #393 - * config-linux: Add suport for cgroup namespace, #397 - * config-linux: Runtime SHOULD NOT modify ownership of any - referenced filesystem (previously the restriction only applied to - the root filesystem), #452 - * specs-go/seccomp: Add ppc and s390x to specs-go/config.go, #475 - - Minor fixes and documentation: - - * README: Add project.md to the Table of Contents, #376 - * README: Consistenly indent the Table of Contents, #400 - * README: Link to LICENSE, #442 - * README: Weekly call is OCI-wide, #378 - * config: Explicit runtime namespace for hooks, #415 - * config: Explicit container namespace for uid, gid, and - additionalGids, #412 - * config: Fix 'string' -> 'array of strings' typo for process.args, - #416 - * runtime: The runtime MAY validate config.json, #418 - * runtime: Move errors section out of operations, #445 - * runtime: MAY -> SHOULD for post-stop error logging, #410 - * schema/README: Document JSON Schema usage, #360, #385 - * schema: Minor description updates, #456, #461 - * schema/validate: Support reading documents via stdin, #482 - * .pullapprove: Automate review approval, #458, #474 - * .gitignore: Hide more auto-generated files, #386, #392 - * .travis: git-validation detects Travis now, #366 - * .travis: Regress on failure to produce docs, #479 - * Makefile: Filename docs.* -> oci-runtime-spec.*, #478 - * Makefile: Add install.tools target, #349 - * Makefile: Allow native pandoc implementations, #428, #448 - * Makefile: Prefer Bash, #455 - * Makefile: Travis support for .gitvalidation, #422 - * specs-go/config: Add missing omitempties for Process.Terminal, - Root.Readonly, Spec.Linux, and Spec.Mounts, #408, #429, #430, #431 - * specs-go/config: Remove incorrect omitempties for User.UID and - User.GID, #425 - * specs-go/config: Drop platform-independent comment, #451 - * version: Include version in generated documentation, #406 - * *: Anchor examples, #348 - * *: Fix remnants from SelinuxProcessLabel to SelinuxLabel rename, - #396 - * *: Outsource code-of-conduct to TOB repository, #375, #413 - * *: RFC 2119 consistency, #407, #409, #438, #444, #449 - * *: Typo fixes, #390, #401 - * *: Whitespace fixes and validation, #380, #381, #426 - * ROADMAP: Remove stale targets, #435 - -Changes with v0.5.0: - Breaking changes: - - * specs-go: Renamed the repository from opencontainers/specs to - opencontainers/runtime-spec, #365 - - Additions: - - * config: Add 'timeout' for hooks, #346 - * config-linux: Add 'maskedPaths' and 'readonlyPaths', #364 - - Minor fixes and documentation: - - * JSON Schema bug-fixes and improved examples, #370 - * README: Define "unconditionally compliant", #374 - * config: Make Markdown canonical, #342 - * config: Explicitly list mapping from symbolic names to UID/GIDs as - out-of-scope, #347 - * config-linux: Require the runtime mount namespace for namespace - 'path' values, #275 - * config-linux: Reword kernelTCP docs, #377 - * specs-go: Add omitempty to 'Device' and 'Namespace', #340 - * .travis.yml: Use built-in 'go vet' and current 'go lint', dropping - Go < 1.5, #372, #352 - * implementations: Expand ocitools scope to include testing, #328 - * style: Move one-sentence-per-line rule from the README, #369 - * style: Remove dangling parenthesis, #359 - * README: Add a link to the IRC logs, #358 - * Fix "manadate", "exmaple", "paramters", and "preferrably" typos, - #353, #354 - -Changes with v0.4.0: - Breaking changes: - - * config: Move capabilities, selinuxProcessLabel, apparmorProfile, - and noNewPrivileges from the linux setting to the process setting - and make them optional, renaming selinuxProcessLabel to - selinuxLabel, #329, #330, #339 - * runtime: Rename version to ociVerison in the state JSON, #225 - * runtime: Remove the directory requirement for storing state, now - that there is a 'state' operation, #225, #334 - * go: Shift *.go to specs-go/*.go, #276 - * config: Move rlimits to process, #341 - * go: Move config_linux.go content into config.go, removing - LinuxSpec, #310 - - Additions: - - * schema: Add JSON Schema (and validator) for `config.json`, #313 - * config: Add annotations for opaque-to-the-runtime data, #331 - * config-linux: Make seccomp optional, #333 - * runtime: Added additional operations: state, stop, and exec. - #225 - - Minor fixes and documentation: - - * config-linux: Change mount type from *rune to *string and fix - octal fileMode examples, #323 - * runtime: RFC 2119 phrasing for the lifecycle, #225 - * README: Add a full example of config.json, #276 - * README: Replace BlueJeans with UberConference, #326, #338 - * style: Document Go-pointer exceptions, #317 - -Changes with v0.3.0: - Breaking changes: - - * config: Single, unified config file, #284 - * config: cwd is a required default, and must be absolute, #286, - #307, #308, #312 - * config: qualify the name of the version field, #309 - * config-linux: Convert classID from hex to uint32, #296 - * config-linux: Separate mknod from cgroups, #298 - - Additions: - - * config-linux: Add NoNewPrivileges setting for linux, #290 - - Minor fixes and documentation: - - * config-linux: clarify oom_score_adj, #236, #292 - * config-linux: Update links to cgroups documentation, #318 - * config-linux: Remove pointers for slices preferring omitempty - tag instead, #316 - * README: add runtime, bundle, and hook author user, #280 - * ROADMAP: reshuffled and split into GitHub issues, #300, #301, - #304, #306 - * style: Collect established styles in a discoverable location, #287, #311 - -Changes with v0.2.0: - * Add Apparmor, Selinux and Seccomp - * Add Apparmor, Selinux and Seccomp sections - * Add bind mount example - * Add fd section for linux container process - * Add Go types for specification - * *: adding a code of conduct - * Adding cgroups path to the Spec. - * .: Adding listing of implementations - * .: adding travis file for future CI - * Add license and DCO information for contributions - * Add linux spec description - * Add MAINTAINERS file - * Add memory swappiness to linux spec - * Add runtime state configuration and structs - * Adds a section for user namespace mappings - * Adds link to kernel cgroups documentation - * Adds section for Linux Rlimits - * Adds section for Linux Sysctl. - * Adds user namespace to the list of namespaces - * bundle: add initial run use case - * bundle: Fix 'and any number of and other related' typo - * bundle.md: clarify arbitrary/conventional dirnames - * bundle.md: fix link formatting - * bundle.md: fix off-by-one error - * bundle.md: various updates to latest spec - * bundle: Move 'Linux sysctl' header to its own line - * Change commiter to committer - * Change Device field order in spec_linux.go, 'Path' should be top of the 'Type' field, according to the different of the config-linux.md, 'Path' field is the unique key. - * Change layout of mountpoints and mounts - * Change the rlimit type to string instead of int - * Clarify behavior around namespaces paths. - * config: Add example additionalGids - * config: Add example cwd - * config: cleanup language on readonly parameter - * config: fix links to go files - * config-linux: specify the default devices/filesystems available - * config.md: clarify destination for mounts - * config.md: make the version a semver - * config.md: make the version field example a semver - * config.md: minor clean up of process specification - * config.md: reformat into a standard style - * config.md: update links to spec schema code - * config.md: various cleanup/consistency fixes - * config: minor cleanup - * Deduplicate the field of RootfsPropagation - * Define constants for Linux Namespace names - * Fix LinuxRuntime field - * Fix root object keys - * Fix typos in config.md - * Fix typos in the "Namespace types" section - * Fix typos in the rlimits section - * Fix Windows path escaping in example mount JSON - * JSON objects are easier to parse/manipulate - * made repo public. Added warning in README - * Make namespaces match runc - * make rootfs mount propagation mode settable - * Makes namespaces description linux specific - * *.md: markdown formatting - * Modify the capabilities constants to match header files like other constants - * Move linux specific options to linux spec - * README: add a rule for paragraph formatting in markdown - * README: Document BlueJeans and wiki archive for meetings - * README: Document pre-meeting agenda alteration - * README: Document YouTube and IRC backchannel for meetings - * README: Focus on local runtime (create/start/stop) - * README.md: Add a git commit style guide - * README.md: contribution about discussion - * README: releases section - * README: Remove blank line from infrastructure-agnostic paragraph - * removed boilerplate file - * *: remove superfluous comma in code-of-conduct - * Remove trailing whitespace - * Rename SystemProperties to Sysctl - * Rename the header "Access to devices" to "Devices" to fit with the config - * *: re-org the spec - * Replace Linux.Device with more specific config - * restore formatting - * Return golang compliant names for UID and GID in User - * Return golint-compliant naming for mappings - * runtime: Add prestart/poststop hooks - * runtime_config: comments for golint - * runtime-config-linux: Drop 'Linux' from headers - * runtime_config_linux: Fix 'LinuxSpec' -> 'LinuxRuntimeSpec' in comment - * runtime-config-linux: One sentence per line for opening two paragraphs - * runtime-config: Remove blank lines from the end of files - * runtime-config: Remove 'destination' docs from mounts - * runtime.md: convert oc to runc - * runtime: use opencontainer vs oci - * *: small spelling fixes - * Specific platform specific user struct for spec - * spec: linux: add support for the PIDs cgroup - * spec_linux: conform to `golint` - * spec_linux.go: Rename IDMapping fields to follow syscall.SysProcIDMap - * spec_linux: remove ending periods on one-line comments - * spec: rename ocp to oci and add a link - * specs: add json notation - * specs: align the ascii graph - * specs: fix the description for the [ug]idMappings - * specs: introduce the concept of a runtime.json - * .tools: cleanup the commit entry - * .tools: repo validation tool - * travis: fix DCO validation for merges - * typo: containers -> container's - * typo: the -> for - * Update config-linux for better formatting on values - * Update README.md - * Update readme with weekly call and mailing list - * Update runtime.md - * Update runtime.md - * Update runtime.md - * version: more explicit version for comparison - -Changes with v0.1.0: - * Add Architecture field to Seccomp configuration in Linux runtime - * Add @hqhq as maintainer - * Add hyphen for host specific - * Adding Vishnu Kannan as a Maintainer. - * Add initial roadmap - * Add lifecycle for containers - * Add oom_score_adj to the runtime Spec. - * Add post-start hooks - * Add Seccomp constants to description of Linux runtime spec - * Add Seccomp constants to Linux runtime config - * Add some clarity around the state.json file - * adds text describing the upper-case keywords used in the spec - * add testing framework to ROADMAP - * Appropriately mark optional fields as omitempty - * cgroup: Add support for memory.kmem.tcp.limit_in_bytes - * Change HugepageLimit.Limit type to uint64 - * Change the behavior when cgroupsPath is absent - * Change version from 0.1.0 to 0.2.0 - * Clarify the semantics of hook elements - * Cleanup bundle.md - * Cleanup principles - * config: linux: update description of PidsLimit - * config: Require a new UTS namespace for config.json's hostname - * config: Require the runtime to mount Spec.Mounts in order - * convert **name** to **`name`** - * Example lists "root' but text mentions "bundlePath" - * Fix an extra space in VersionMinor - * Fix golint warnings - * Fix typo in BlockIO struct comment - * Fix typo in Filesystem Bundle - * Fix value of swappiness - * glossary: Provide a quick overview of important terms - * glossary: Specify UTF-8 for all our JSON - * hooks: deduplicate the hooks docs - * implementations: Link to kunalkushwaha/octool - * implementations: Link to mrunalp/ocitools - * lifecycle: Don't require /run/opencontainer//containers - * lifecycle: Mention runtime.json - * lifecycle: no hypens - * MAINTAINERS: add tianon per the charter - * MAINTAINERS: correct Vish's github account - * Makefile: Add glossary to DOC_FILES - * Make optional Cgroup related config params pointers along with `omitempty` json tag. - * Mark RootfsPropagation as omitempty - * *.md: update TOC and links - * move the description of Rlimits before example - * move the description of user ns mapping to proper file - * principles: Give principles their own home - * *: printable documents - * Project: document release process - * README: Fix some headers - * README: make header more concise - * remove blank char from blank line - * Remove the unneeded build tag from the config_linux.go - * Remove trailing comma in hooks json example - * Rename State's Root to Bundle - * ROADMAP.md: remove the tail spaces - * roadmap: update links and add wiki reference - * runtime: Add 'version' to the state.json example - * runtime-config: add example label before json example - * runtime-config: add section about Hooks - * runtime: config: linux: add cgroups information - * runtime: config: linux: Edit BlockIO struct - * runtime: config: linux: Fix typo and trailing commas in json example - * runtime_config_linux.go: add missing pointer - * runtime-config-linux.md: fix the type of cpus and mems - * runtime.md: fix spacing - * Talk about host specific/independent instead of mutability - * .tools: commit validator is a separate project - * .tools: make GetFetchHeadCommit do what it says - * .travis.yml: add go 1.5.1, update from 1.4.2 to 1.4.3 - * Update readme with wiki link to minutes - * Update Typo in ROADMAP.md - * Use unsigned for IDs - * version: introduce a string for dev indication diff --git a/src/vendor/github.com/opencontainers/runtime-spec/GOVERNANCE.md b/src/vendor/github.com/opencontainers/runtime-spec/GOVERNANCE.md deleted file mode 100644 index 92c8609491297d95574275e7a34b64b1b20e871c..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/GOVERNANCE.md +++ /dev/null @@ -1,70 +0,0 @@ -# Project governance - -The [OCI charter][charter] §5.b.viii tasks an OCI Project's maintainers (listed in the repository's MAINTAINERS file and sometimes referred to as "the TDC", [§5.e][charter]) with: - -> Creating, maintaining and enforcing governance guidelines for the TDC, approved by the maintainers, and which shall be posted visibly for the TDC. - -This section describes generic rules and procedures for fulfilling that mandate. - -## Proposing a motion - -A maintainer SHOULD propose a motion on the dev@opencontainers.org mailing list (except [security issues](#security-issues)) with another maintainer as a co-sponsor. - -## Voting - -Voting on a proposed motion SHOULD happen on the dev@opencontainers.org mailing list (except [security issues](#security-issues)) with maintainers posting LGTM or REJECT. -Maintainers MAY also explicitly not vote by posting ABSTAIN (which is useful to revert a previous vote). -Maintainers MAY post multiple times (e.g. as they revise their position based on feedback), but only their final post counts in the tally. -A proposed motion is adopted if two-thirds of votes cast, a quorum having voted, are in favor of the release. - -Voting SHOULD remain open for a week to collect feedback from the wider community and allow the maintainers to digest the proposed motion. -Under exceptional conditions (e.g. non-major security fix releases) proposals which reach quorum with unanimous support MAY be adopted earlier. - -A maintainer MAY choose to reply with REJECT. -A maintainer posting a REJECT MUST include a list of concerns or links to written documentation for those concerns (e.g. GitHub issues or mailing-list threads). -The maintainers SHOULD try to resolve the concerns and wait for the rejecting maintainer to change their opinion to LGTM. -However, a motion MAY be adopted with REJECTs, as outlined in the previous paragraphs. - -## Quorum - -A quorum is established when at least two-thirds of maintainers have voted. - -For projects that are not specifications, a [motion to release](#release-approval) MAY be adopted if the tally is at least three LGTMs and no REJECTs, even if three votes does not meet the usual two-thirds quorum. - -## Security issues - -Motions with sensitive security implications MUST be proposed on the security@opencontainers.org mailing list instead of dev@opencontainers.org, but should otherwise follow the standard [proposal](#proposing-a-motion) process. -The security@opencontainers.org mailing list includes all members of the TOB. -The TOB will contact the project maintainers and provide a channel for discussing and voting on the motion, but voting will otherwise follow the standard [voting](#voting) and [quorum](#quorum) rules. -The TOB and project maintainers will work together to notify affected parties before making an adopted motion public. - -## Amendments - -The [project governance](#project-governance) rules and procedures MAY be amended or replaced using the procedures themselves. -The MAINTAINERS of this project governance document is the total set of MAINTAINERS from all Open Containers projects (runC, runtime-spec, and image-spec). - -## Subject templates - -Maintainers are busy and get lots of email. -To make project proposals recognizable, proposed motions SHOULD use the following subject templates. - -### Proposing a motion - -> [{project} VOTE]: {motion description} (closes {end of voting window}) - -For example: - -> [runtime-spec VOTE]: Tag 0647920 as 1.0.0-rc (closes 2016-06-03 20:00 UTC) - -### Tallying results - -After voting closes, a maintainer SHOULD post a tally to the motion thread with a subject template like: - -> [{project} {status}]: {motion description} (+{LGTMs} -{REJECTs} #{ABSTAINs}) - -Where `{status}` is either `adopted` or `rejected`. -For example: - -> [runtime-spec adopted]: Tag 0647920 as 1.0.0-rc (+6 -0 #3) - -[charter]: https://www.opencontainers.org/about/governance diff --git a/src/vendor/github.com/opencontainers/runtime-spec/MAINTAINERS b/src/vendor/github.com/opencontainers/runtime-spec/MAINTAINERS deleted file mode 100644 index d3fe235d9bad23cfe7aa4379db8d98b0365d6d5d..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/MAINTAINERS +++ /dev/null @@ -1,8 +0,0 @@ -Michael Crosby (@crosbymichael) -Vishnu Kannan (@vishh) -Mrunal Patel (@mrunalp) -Vincent Batts (@vbatts) -Daniel, Dao Quang Minh (@dqminh) -Brandon Philips (@philips) -Tianon Gravi (@tianon) -Qiang Huang (@hqhq) diff --git a/src/vendor/github.com/opencontainers/runtime-spec/Makefile b/src/vendor/github.com/opencontainers/runtime-spec/Makefile deleted file mode 100644 index 770834b7cea62ca1b2e1bdfa8b50ab0997627c1a..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/Makefile +++ /dev/null @@ -1,94 +0,0 @@ - -EPOCH_TEST_COMMIT := 78e6667ae2d67aad100b28ee9580b41b7a24e667 -OUTPUT_DIRNAME ?= output -DOC_FILENAME ?= oci-runtime-spec -DOCKER ?= $(shell command -v docker 2>/dev/null) -PANDOC ?= $(shell command -v pandoc 2>/dev/null) -ifeq "$(strip $(PANDOC))" '' - ifneq "$(strip $(DOCKER))" '' - PANDOC = $(DOCKER) run \ - -it \ - --rm \ - -v $(shell pwd)/:/input/:ro \ - -v $(shell pwd)/$(OUTPUT_DIRNAME)/:/$(OUTPUT_DIRNAME)/ \ - -u $(shell id -u) \ - vbatts/pandoc - PANDOC_SRC := /input/ - PANDOC_DST := / - endif -endif - -# These docs are in an order that determines how they show up in the PDF/HTML docs. -DOC_FILES := \ - version.md \ - spec.md \ - principles.md \ - bundle.md \ - runtime.md \ - runtime-linux.md \ - config.md \ - config-linux.md \ - config-solaris.md \ - glossary.md - -default: docs - -docs: $(OUTPUT_DIRNAME)/$(DOC_FILENAME).pdf $(OUTPUT_DIRNAME)/$(DOC_FILENAME).html - -ifeq "$(strip $(PANDOC))" '' -$(OUTPUT_DIRNAME)/$(DOC_FILENAME).pdf $(OUTPUT_DIRNAME)/$(DOC_FILENAME).html: - $(error cannot build $@ without either pandoc or docker) -else -$(OUTPUT_DIRNAME)/$(DOC_FILENAME).pdf: $(DOC_FILES) - mkdir -p $(OUTPUT_DIRNAME)/ && \ - $(PANDOC) -f markdown_github -t latex -o $(PANDOC_DST)$@ $(patsubst %,$(PANDOC_SRC)%,$(DOC_FILES)) - -$(OUTPUT_DIRNAME)/$(DOC_FILENAME).html: $(DOC_FILES) - mkdir -p $(OUTPUT_DIRNAME)/ && \ - $(PANDOC) -f markdown_github -t html5 -o $(PANDOC_DST)$@ $(patsubst %,$(PANDOC_SRC)%,$(DOC_FILES)) -endif - -version.md: ./specs-go/version.go - go run ./.tool/version-doc.go > $@ - -HOST_GOLANG_VERSION = $(shell go version | cut -d ' ' -f3 | cut -c 3-) -# this variable is used like a function. First arg is the minimum version, Second arg is the version to be checked. -ALLOWED_GO_VERSION = $(shell test '$(shell /bin/echo -e "$(1)\n$(2)" | sort -V | head -n1)' = '$(1)' && echo 'true') - -test: .govet .golint .gitvalidation - -.govet: - go vet -x ./... - -# `go get github.com/golang/lint/golint` -.golint: -ifeq ($(call ALLOWED_GO_VERSION,1.6,$(HOST_GOLANG_VERSION)),true) - @which golint > /dev/null 2>/dev/null || (echo "ERROR: golint not found. Consider 'make install.tools' target" && false) - golint ./... -endif - - -# When this is running in travis, it will only check the travis commit range -.gitvalidation: - @which git-validation > /dev/null 2>/dev/null || (echo "ERROR: git-validation not found. Consider 'make install.tools' target" && false) -ifdef TRAVIS_COMMIT_RANGE - git-validation -q -run DCO,short-subject,dangling-whitespace -else - git-validation -v -run DCO,short-subject,dangling-whitespace -range $(EPOCH_TEST_COMMIT)..HEAD -endif - -install.tools: .install.golint .install.gitvalidation - -# golint does not even build for - -using your real name (sorry, no pseudonyms or anonymous contributions.) - -You can add the sign off when creating the git commit via `git commit -s`. - -#### Commit Style - -Simple house-keeping for clean git history. -Read more on [How to Write a Git Commit Message][how-to-git-commit] or the Discussion section of [git-commit(1)][git-commit.1]. - -1. Separate the subject from body with a blank line -2. Limit the subject line to 50 characters -3. Capitalize the subject line -4. Do not end the subject line with a period -5. Use the imperative mood in the subject line -6. Wrap the body at 72 characters -7. Use the body to explain what and why vs. how - * If there was important/useful/essential conversation or information, copy or include a reference -8. When possible, one keyword to scope the change in the subject (i.e. "README: ...", "runtime: ...") - - -[charter]: https://www.opencontainers.org/about/governance -[code-of-conduct]: https://github.com/opencontainers/tob/blob/master/code-of-conduct.md -[dev-list]: https://groups.google.com/a/opencontainers.org/forum/#!forum/dev -[how-to-git-commit]: http://chris.beams.io/posts/git-commit -[irc-logs]: http://ircbot.wl.linuxfoundation.org/eavesdrop/%23opencontainers/ -[iso-week]: https://en.wikipedia.org/wiki/ISO_week_date#Calculating_the_week_number_of_a_given_date -[minutes]: http://ircbot.wl.linuxfoundation.org/meetings/opencontainers/ -[oci]: https://www.opencontainers.org -[rfc5545]: https://tools.ietf.org/html/rfc5545 -[runtime-wiki]: https://github.com/opencontainers/runtime-spec/wiki -[uberconference]: https://www.uberconference.com/opencontainers - -[git-commit.1]: http://git-scm.com/docs/git-commit diff --git a/src/vendor/github.com/opencontainers/runtime-spec/RELEASES.md b/src/vendor/github.com/opencontainers/runtime-spec/RELEASES.md deleted file mode 100644 index a28e086a7ca3009d099a4e81027d5a084e578bc6..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/RELEASES.md +++ /dev/null @@ -1,51 +0,0 @@ -# Releases - -The release process hopes to encourage early, consistent consensus-building during project development. -The mechanisms used are regular community communication on the mailing list about progress, scheduled meetings for issue resolution and release triage, and regularly paced and communicated releases. -Releases are proposed and adopted or rejected using the usual [project governance](GOVERNANCE.md) rules and procedures. - -An anti-pattern that we want to avoid is heavy development or discussions "late cycle" around major releases. -We want to build a community that is involved and communicates consistently through all releases instead of relying on "silent periods" as a judge of stability. - -## Parallel releases - -A single project MAY consider several motions to release in parallel. -However each motion to release after the initial 0.1.0 MUST be based on a previous release that has already landed. - -For example, runtime-spec maintainers may propose a v1.0.0-rc2 on the 1st of the month and a v0.9.1 bugfix on the 2nd of the month. -They may not propose a v1.0.0-rc3 until the v1.0.0-rc2 is accepted (on the 7th if the vote initiated on the 1st passes). - -## Specifications - -The OCI maintains three categories of projects: specifications, applications, and conformance-testing tools. -However, specification releases have special restrictions in the [OCI charter][charter]: - -* They are the target of backwards compatibility (§7.g), and -* They are subject to the OFWa patent grant (§8.d and e). - -To avoid unfortunate side effects (onerous backwards compatibity requirements or Member resignations), the following additional procedures apply to specification releases: - -### Planning a release - -Every OCI specification project SHOULD hold meetings that involve maintainers reviewing pull requests, debating outstanding issues, and planning releases. -This meeting MUST be advertised on the project README and MAY happen on a phone call, video conference, or on IRC. -Maintainers MUST send updates to the dev@opencontainers.org with results of these meetings. - -Before the specification reaches v1.0.0, the meetings SHOULD be weekly. -Once a specification has reached v1.0.0, the maintainers may alter the cadence, but a meeting MUST be held within four weeks of the previous meeting. - -The release plans, corresponding milestones and estimated due dates MUST be published on GitHub (e.g. https://github.com/opencontainers/runtime-spec/milestones). -GitHub milestones and issues are only used for community organization and all releases MUST follow the [project governance](GOVERNANCE.md) rules and procedures. - -### Timelines - -Specifications have a variety of different timelines in their lifecycle. - -* Pre-v1.0.0 specifications SHOULD release on a monthly cadence to garner feedback. -* Major specification releases MUST release at least three release candidates spaced a minimum of one week apart. - This means a major release like a v1.0.0 or v2.0.0 release will take 1 month at minimum: one week for rc1, one week for rc2, one week for rc3, and one week for the major release itself. - Maintainers SHOULD strive to make zero breaking changes during this cycle of release candidates and SHOULD restart the three-candidate count when a breaking change is introduced. - For example if a breaking change is introduced in v1.0.0-rc2 then the series would end with v1.0.0-rc4 and v1.0.0. -- Minor and patch releases SHOULD be made on an as-needed basis. - -[charter]: https://www.opencontainers.org/about/governance diff --git a/src/vendor/github.com/opencontainers/runtime-spec/bundle.md b/src/vendor/github.com/opencontainers/runtime-spec/bundle.md deleted file mode 100644 index 0924ad9fe7d6afabb3cd721423e961b3f4288c3b..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/bundle.md +++ /dev/null @@ -1,22 +0,0 @@ -# Filesystem Bundle - -## Container Format - -This section defines a format for encoding a container as a *filesystem bundle* - a set of files organized in a certain way, and containing all the necessary data and metadata for any compliant runtime to perform all standard operations against it. -See also [MacOS application bundles][macos_bundle] for a similar use of the term *bundle*. - -The definition of a bundle is only concerned with how a container, and its configuration data, are stored on a local filesystem so that it can be consumed by a compliant runtime. - -A Standard Container bundle contains all the information needed to load and run a container. -This includes the following artifacts: - -1. `config.json`: contains configuration data. - This REQUIRED file MUST reside in the root of the bundle directory and MUST be named `config.json`. - See [`config.json`](config.md) for more details. - -2. container's root filesystem: the directory referenced by [`root.path`](config.md#root), if that property is set in `config.json`. - -When supplied, while these artifacts MUST all be present in a single directory on the local filesystem, that directory itself is not part of the bundle. -In other words, a tar archive of a *bundle* will have these artifacts at the root of the archive, not nested within a top-level directory. - -[macos_bundle]: https://en.wikipedia.org/wiki/Bundle_%28macOS%29 diff --git a/src/vendor/github.com/opencontainers/runtime-spec/config-linux.md b/src/vendor/github.com/opencontainers/runtime-spec/config-linux.md deleted file mode 100644 index f73d893c99511df05a98832a1e3ff3cb4dd9df1e..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/config-linux.md +++ /dev/null @@ -1,673 +0,0 @@ -# Linux Container Configuration - -This document describes the schema for the [Linux-specific section](config.md#platform-specific-configuration) of the [container configuration](config.md). -The Linux container specification uses various kernel features like namespaces, cgroups, capabilities, LSM, and filesystem jails to fulfill the spec. - -## Default Filesystems - -The Linux ABI includes both syscalls and several special file paths. -Applications expecting a Linux environment will very likely expect these file paths to be set up correctly. - -The following filesystems SHOULD be made available in each container's filesystem: - -| Path | Type | -| -------- | ------ | -| /proc | [proc][] | -| /sys | [sysfs][] | -| /dev/pts | [devpts][] | -| /dev/shm | [tmpfs][] | - -## Namespaces - -A namespace wraps a global system resource in an abstraction that makes it appear to the processes within the namespace that they have their own isolated instance of the global resource. -Changes to the global resource are visible to other processes that are members of the namespace, but are invisible to other processes. -For more information, see the [namespaces(7)][namespaces.7_2] man page. - -Namespaces are specified as an array of entries inside the `namespaces` root field. -The following parameters can be specified to set up namespaces: - -* **`type`** *(string, REQUIRED)* - namespace type. The following namespace types are supported: - * **`pid`** processes inside the container will only be able to see other processes inside the same container. - * **`network`** the container will have its own network stack. - * **`mount`** the container will have an isolated mount table. - * **`ipc`** processes inside the container will only be able to communicate to other processes inside the same container via system level IPC. - * **`uts`** the container will be able to have its own hostname and domain name. - * **`user`** the container will be able to remap user and group IDs from the host to local users and groups within the container. - * **`cgroup`** the container will have an isolated view of the cgroup hierarchy. - -* **`path`** *(string, OPTIONAL)* - namespace file. - This value MUST be an absolute path in the [runtime mount namespace](glossary.md#runtime-namespace). - The runtime MUST place the container process in the namespace associated with that `path`. - The runtime MUST [generate an error](runtime.md#errors) if `path` is not associated with a namespace of type `type`. - - If `path` is not specified, the runtime MUST create a new [container namespace](glossary.md#container-namespace) of type `type`. - -If a namespace type is not specified in the `namespaces` array, the container MUST inherit the [runtime namespace](glossary.md#runtime-namespace) of that type. -If a `namespaces` field contains duplicated namespaces with same `type`, the runtime MUST [generate an error](runtime.md#errors). - -### Example - -```json - "namespaces": [ - { - "type": "pid", - "path": "/proc/1234/ns/pid" - }, - { - "type": "network", - "path": "/var/run/netns/neta" - }, - { - "type": "mount" - }, - { - "type": "ipc" - }, - { - "type": "uts" - }, - { - "type": "user" - }, - { - "type": "cgroup" - } - ] -``` - -## User namespace mappings - -**`uidMappings`** (array of objects, OPTIONAL) describes the user namespace uid mappings from the host to the container. -**`gidMappings`** (array of objects, OPTIONAL) describes the user namespace gid mappings from the host to the container. - -Each entry has the following structure: - -* **`hostID`** *(uint32, REQUIRED)* - is the starting uid/gid on the host to be mapped to *containerID*. -* **`containerID`** *(uint32, REQUIRED)* - is the starting uid/gid in the container. -* **`size`** *(uint32, REQUIRED)* - is the number of ids to be mapped. - -The runtime SHOULD NOT modify the ownership of referenced filesystems to realize the mapping. -Note that the number of mapping entries MAY be limited by the [kernel][user-namespaces]. - -### Example - -```json - "uidMappings": [ - { - "hostID": 1000, - "containerID": 0, - "size": 32000 - } - ], - "gidMappings": [ - { - "hostID": 1000, - "containerID": 0, - "size": 32000 - } - ] -``` - -## Devices - -**`devices`** (array of objects, OPTIONAL) lists devices that MUST be available in the container. -The runtime MAY supply them however it likes (with [`mknod`][mknod.2], by bind mounting from the runtime mount namespace, using symlinks, etc.). - -Each entry has the following structure: - -* **`type`** *(string, REQUIRED)* - type of device: `c`, `b`, `u` or `p`. - More info in [mknod(1)][mknod.1]. -* **`path`** *(string, REQUIRED)* - full path to device inside container. - If a [file][] already exists at `path` that does not match the requested device, the runtime MUST generate an error. -* **`major, minor`** *(int64, REQUIRED unless `type` is `p`)* - [major, minor numbers][devices] for the device. -* **`fileMode`** *(uint32, OPTIONAL)* - file mode for the device. - You can also control access to devices [with cgroups](#device-whitelist). -* **`uid`** *(uint32, OPTIONAL)* - id of device owner. -* **`gid`** *(uint32, OPTIONAL)* - id of device group. - -The same `type`, `major` and `minor` SHOULD NOT be used for multiple devices. - -### Example - -```json - "devices": [ - { - "path": "/dev/fuse", - "type": "c", - "major": 10, - "minor": 229, - "fileMode": 438, - "uid": 0, - "gid": 0 - }, - { - "path": "/dev/sda", - "type": "b", - "major": 8, - "minor": 0, - "fileMode": 432, - "uid": 0, - "gid": 0 - } - ] -``` - -### Default Devices - -In addition to any devices configured with this setting, the runtime MUST also supply: - -* [`/dev/null`][null.4] -* [`/dev/zero`][zero.4] -* [`/dev/full`][full.4] -* [`/dev/random`][random.4] -* [`/dev/urandom`][random.4] -* [`/dev/tty`][tty.4] -* [`/dev/console`][console.4] is set up if terminal is enabled in the config by bind mounting the pseudoterminal slave to /dev/console. -* [`/dev/ptmx`][pts.4]. - A [bind-mount or symlink of the container's `/dev/pts/ptmx`][devpts]. - -## Control groups - -Also known as cgroups, they are used to restrict resource usage for a container and handle device access. -cgroups provide controls (through controllers) to restrict cpu, memory, IO, pids and network for the container. -For more information, see the [kernel cgroups documentation][cgroup-v1]. - -### Cgroups Path - -**`cgroupsPath`** (string, OPTIONAL) path to the cgroups. -It can be used to either control the cgroups hierarchy for containers or to run a new process in an existing container. - -The value of `cgroupsPath` MUST be either an absolute path or a relative path. -* In the case of an absolute path (starting with `/`), the runtime MUST take the path to be relative to the cgroups mount point. -* In the case of a relative path (not starting with `/`), the runtime MAY interpret the path relative to a runtime-determined location in the cgroups hierarchy. - -If the value is specified, the runtime MUST consistently attach to the same place in the cgroups hierarchy given the same value of `cgroupsPath`. -If the value is not specified, the runtime MAY define the default cgroups path. -Runtimes MAY consider certain `cgroupsPath` values to be invalid, and MUST generate an error if this is the case. - -Implementations of the Spec can choose to name cgroups in any manner. -The Spec does not include naming schema for cgroups. -The Spec does not support per-controller paths for the reasons discussed in the [cgroupv2 documentation][cgroup-v2]. -The cgroups will be created if they don't exist. - -You can configure a container's cgroups via the `resources` field of the Linux configuration. -Do not specify `resources` unless limits have to be updated. -For example, to run a new process in an existing container without updating limits, `resources` need not be specified. - -Runtimes MAY attach the container process to additional cgroup controllers beyond those necessary to fulfill the `resources` settings. - -### Example - -```json - "cgroupsPath": "/myRuntime/myContainer", - "resources": { - "memory": { - "limit": 100000, - "reservation": 200000 - }, - "devices": [ - { - "allow": false, - "access": "rwm" - } - ] - } -``` - -### Device whitelist - -**`devices`** (array of objects, OPTIONAL) configures the [device whitelist][cgroup-v1-devices]. -The runtime MUST apply entries in the listed order. - -Each entry has the following structure: - -* **`allow`** *(boolean, REQUIRED)* - whether the entry is allowed or denied. -* **`type`** *(string, OPTIONAL)* - type of device: `a` (all), `c` (char), or `b` (block). - Unset values mean "all", mapping to `a`. -* **`major, minor`** *(int64, OPTIONAL)* - [major, minor numbers][devices] for the device. - Unset values mean "all", mapping to [`*` in the filesystem API][cgroup-v1-devices]. -* **`access`** *(string, OPTIONAL)* - cgroup permissions for device. - A composition of `r` (read), `w` (write), and `m` (mknod). - -#### Example - -```json - "devices": [ - { - "allow": false, - "access": "rwm" - }, - { - "allow": true, - "type": "c", - "major": 10, - "minor": 229, - "access": "rw" - }, - { - "allow": true, - "type": "b", - "major": 8, - "minor": 0, - "access": "r" - } - ] -``` - -### Memory - -**`memory`** (object, OPTIONAL) represents the cgroup subsystem `memory` and it's used to set limits on the container's memory usage. -For more information, see the kernel cgroups documentation about [memory][cgroup-v1-memory]. - -Values for memory specify the limit in bytes, or `-1` for unlimited memory. - -* **`limit`** *(int64, OPTIONAL)* - sets limit of memory usage -* **`reservation`** *(int64, OPTIONAL)* - sets soft limit of memory usage -* **`swap`** *(int64, OPTIONAL)* - sets limit of memory+Swap usage -* **`kernel`** *(int64, OPTIONAL)* - sets hard limit for kernel memory -* **`kernelTCP`** *(int64, OPTIONAL)* - sets hard limit for kernel TCP buffer memory - -The following properties do not specify memory limits, but are covered by the `memory` controller: - -* **`swappiness`** *(uint64, OPTIONAL)* - sets swappiness parameter of vmscan (See sysctl's vm.swappiness) - The values are from 0 to 100. Higher means more swappy. -* **`disableOOMKiller`** *(bool, OPTIONAL)* - enables or disables the OOM killer. - If enabled (`false`), tasks that attempt to consume more memory than they are allowed are immediately killed by the OOM killer. - The OOM killer is enabled by default in every cgroup using the `memory` subsystem. - To disable it, specify a value of `true`. - -#### Example - -```json - "memory": { - "limit": 536870912, - "reservation": 536870912, - "swap": 536870912, - "kernel": -1, - "kernelTCP": -1, - "swappiness": 0, - "disableOOMKiller": false - } -``` - -### CPU - -**`cpu`** (object, OPTIONAL) represents the cgroup subsystems `cpu` and `cpusets`. -For more information, see the kernel cgroups documentation about [cpusets][cgroup-v1-cpusets]. - -The following parameters can be specified to set up the controller: - -* **`shares`** *(uint64, OPTIONAL)* - specifies a relative share of CPU time available to the tasks in a cgroup -* **`quota`** *(int64, OPTIONAL)* - specifies the total amount of time in microseconds for which all tasks in a cgroup can run during one period (as defined by **`period`** below) -* **`period`** *(uint64, OPTIONAL)* - specifies a period of time in microseconds for how regularly a cgroup's access to CPU resources should be reallocated (CFS scheduler only) -* **`realtimeRuntime`** *(int64, OPTIONAL)* - specifies a period of time in microseconds for the longest continuous period in which the tasks in a cgroup have access to CPU resources -* **`realtimePeriod`** *(uint64, OPTIONAL)* - same as **`period`** but applies to realtime scheduler only -* **`cpus`** *(string, OPTIONAL)* - list of CPUs the container will run in -* **`mems`** *(string, OPTIONAL)* - list of Memory Nodes the container will run in - -#### Example - -```json - "cpu": { - "shares": 1024, - "quota": 1000000, - "period": 500000, - "realtimeRuntime": 950000, - "realtimePeriod": 1000000, - "cpus": "2-3", - "mems": "0-7" - } -``` - -### Block IO - -**`blockIO`** (object, OPTIONAL) represents the cgroup subsystem `blkio` which implements the block IO controller. -For more information, see the kernel cgroups documentation about [blkio][cgroup-v1-blkio]. - -The following parameters can be specified to set up the controller: - -* **`weight`** *(uint16, OPTIONAL)* - specifies per-cgroup weight. This is default weight of the group on all devices until and unless overridden by per-device rules. -* **`leafWeight`** *(uint16, OPTIONAL)* - equivalents of `weight` for the purpose of deciding how much weight tasks in the given cgroup has while competing with the cgroup's child cgroups. -* **`weightDevice`** *(array of objects, OPTIONAL)* - an array of per-device bandwidth weights. - Each entry has the following structure: - * **`major, minor`** *(int64, REQUIRED)* - major, minor numbers for device. - For more information, see the [mknod(1)][mknod.1] man page. - * **`weight`** *(uint16, OPTIONAL)* - bandwidth weight for the device. - * **`leafWeight`** *(uint16, OPTIONAL)* - bandwidth weight for the device while competing with the cgroup's child cgroups, CFQ scheduler only - - You MUST specify at least one of `weight` or `leafWeight` in a given entry, and MAY specify both. - -* **`throttleReadBpsDevice`**, **`throttleWriteBpsDevice`** *(array of objects, OPTIONAL)* - an array of per-device bandwidth rate limits. - Each entry has the following structure: - * **`major, minor`** *(int64, REQUIRED)* - major, minor numbers for device. - For more information, see the [mknod(1)][mknod.1] man page. - * **`rate`** *(uint64, REQUIRED)* - bandwidth rate limit in bytes per second for the device - -* **`throttleReadIOPSDevice`**, **`throttleWriteIOPSDevice`** *(array of objects, OPTIONAL)* - an array of per-device IO rate limits. - Each entry has the following structure: - * **`major, minor`** *(int64, REQUIRED)* - major, minor numbers for device. - For more information, see the [mknod(1)][mknod.1] man page. - * **`rate`** *(uint64, REQUIRED)* - IO rate limit for the device - -#### Example - -```json - "blockIO": { - "weight": 10, - "leafWeight": 10, - "weightDevice": [ - { - "major": 8, - "minor": 0, - "weight": 500, - "leafWeight": 300 - }, - { - "major": 8, - "minor": 16, - "weight": 500 - } - ], - "throttleReadBpsDevice": [ - { - "major": 8, - "minor": 0, - "rate": 600 - } - ], - "throttleWriteIOPSDevice": [ - { - "major": 8, - "minor": 16, - "rate": 300 - } - ] - } -``` - -### Huge page limits - -**`hugepageLimits`** (array of objects, OPTIONAL) represents the `hugetlb` controller which allows to limit the -HugeTLB usage per control group and enforces the controller limit during page fault. -For more information, see the kernel cgroups documentation about [HugeTLB][cgroup-v1-hugetlb]. - -Each entry has the following structure: - -* **`pageSize`** *(string, REQUIRED)* - hugepage size -* **`limit`** *(uint64, REQUIRED)* - limit in bytes of *hugepagesize* HugeTLB usage - -#### Example - -```json - "hugepageLimits": [ - { - "pageSize": "2MB", - "limit": 209715200 - } - ] -``` - -### Network - -**`network`** (object, OPTIONAL) represents the cgroup subsystems `net_cls` and `net_prio`. -For more information, see the kernel cgroups documentations about [net\_cls cgroup][cgroup-v1-net-cls] and [net\_prio cgroup][cgroup-v1-net-prio]. - -The following parameters can be specified to set up the controller: - -* **`classID`** *(uint32, OPTIONAL)* - is the network class identifier the cgroup's network packets will be tagged with -* **`priorities`** *(array of objects, OPTIONAL)* - specifies a list of objects of the priorities assigned to traffic originating from processes in the group and egressing the system on various interfaces. - The following parameters can be specified per-priority: - * **`name`** *(string, REQUIRED)* - interface name in [runtime network namespace](glossary.md#runtime-namespace) - * **`priority`** *(uint32, REQUIRED)* - priority applied to the interface - -#### Example - -```json - "network": { - "classID": 1048577, - "priorities": [ - { - "name": "eth0", - "priority": 500 - }, - { - "name": "eth1", - "priority": 1000 - } - ] - } -``` - -### PIDs - -**`pids`** (object, OPTIONAL) represents the cgroup subsystem `pids`. -For more information, see the kernel cgroups documentation about [pids][cgroup-v1-pids]. - -The following parameters can be specified to set up the controller: - -* **`limit`** *(int64, REQUIRED)* - specifies the maximum number of tasks in the cgroup - -#### Example - -```json - "pids": { - "limit": 32771 - } -``` - -## IntelRdt - -**`intelRdt`** (object, OPTIONAL) represents the [Intel Resource Director Technology][intel-rdt-cat-kernel-interface]. - If `intelRdt` is set, the runtime MUST write the container process ID to the `/tasks` file in a mounted `resctrl` pseudo-filesystem, using the container ID from [`start`](runtime.md#start) and creating the `` directory if necessary. - If no mounted `resctrl` pseudo-filesystem is available in the [runtime mount namespace](glossary.md#runtime-namespace), the runtime MUST [generate an error](runtime.md#errors). - - If `intelRdt` is not set, the runtime MUST NOT manipulate any `resctrl` pseudo-filesystems. - -The following parameters can be specified for the container: - -* **`l3CacheSchema`** *(string, OPTIONAL)* - specifies the schema for L3 cache id and capacity bitmask (CBM). - If `l3CacheSchema` is set, runtimes MUST write the value to the `schemata` file in the `` directory discussed in `intelRdt`. - - If `l3CacheSchema` is not set, runtimes MUST NOT write to `schemata` files in any `resctrl` pseudo-filesystems. - -### Example - -Consider a two-socket machine with two L3 caches where the default CBM is 0xfffff and the max CBM length is 20 bits. -Tasks inside the container only have access to the "upper" 80% of L3 cache id 0 and the "lower" 50% L3 cache id 1: - -```json -"linux": { - "intelRdt": { - "l3CacheSchema": "L3:0=ffff0;1=3ff" - } -} -``` - -## Sysctl - -**`sysctl`** (object, OPTIONAL) allows kernel parameters to be modified at runtime for the container. -For more information, see the [sysctl(8)][sysctl.8] man page. - -### Example - -```json - "sysctl": { - "net.ipv4.ip_forward": "1", - "net.core.somaxconn": "256" - } -``` - -## Seccomp - -Seccomp provides application sandboxing mechanism in the Linux kernel. -Seccomp configuration allows one to configure actions to take for matched syscalls and furthermore also allows matching on values passed as arguments to syscalls. -For more information about Seccomp, see [Seccomp][seccomp] kernel documentation. -The actions, architectures, and operators are strings that match the definitions in seccomp.h from [libseccomp][] and are translated to corresponding values. - -**`seccomp`** (object, OPTIONAL) - -The following parameters can be specified to set up seccomp: - -* **`defaultAction`** *(string, REQUIRED)* - the default action for seccomp. Allowed values are the same as `syscalls[].action`. - -* **`architectures`** *(array of strings, OPTIONAL)* - the architecture used for system calls. - A valid list of constants as of libseccomp v2.3.2 is shown below. - - * `SCMP_ARCH_X86` - * `SCMP_ARCH_X86_64` - * `SCMP_ARCH_X32` - * `SCMP_ARCH_ARM` - * `SCMP_ARCH_AARCH64` - * `SCMP_ARCH_MIPS` - * `SCMP_ARCH_MIPS64` - * `SCMP_ARCH_MIPS64N32` - * `SCMP_ARCH_MIPSEL` - * `SCMP_ARCH_MIPSEL64` - * `SCMP_ARCH_MIPSEL64N32` - * `SCMP_ARCH_PPC` - * `SCMP_ARCH_PPC64` - * `SCMP_ARCH_PPC64LE` - * `SCMP_ARCH_S390` - * `SCMP_ARCH_S390X` - * `SCMP_ARCH_PARISC` - * `SCMP_ARCH_PARISC64` - -* **`syscalls`** *(array of objects, OPTIONAL)* - match a syscall in seccomp. - - While this property is OPTIONAL, some values of `defaultAction` are not useful without `syscalls` entries. - For example, if `defaultAction` is `SCMP_ACT_KILL` and `syscalls` is empty or unset, the kernel will kill the container process on its first syscall. - - Each entry has the following structure: - - * **`names`** *(array of strings, REQUIRED)* - the names of the syscalls. - `names` MUST contain at least one entry. - * **`action`** *(string, REQUIRED)* - the action for seccomp rules. - A valid list of constants as of libseccomp v2.3.2 is shown below. - - * `SCMP_ACT_KILL` - * `SCMP_ACT_TRAP` - * `SCMP_ACT_ERRNO` - * `SCMP_ACT_TRACE` - * `SCMP_ACT_ALLOW` - - * **`args`** *(array of objects, OPTIONAL)* - the specific syscall in seccomp. - - Each entry has the following structure: - - * **`index`** *(uint, REQUIRED)* - the index for syscall arguments in seccomp. - * **`value`** *(uint64, REQUIRED)* - the value for syscall arguments in seccomp. - * **`valueTwo`** *(uint64, OPTIONAL)* - the value for syscall arguments in seccomp. - * **`op`** *(string, REQUIRED)* - the operator for syscall arguments in seccomp. - A valid list of constants as of libseccomp v2.3.2 is shown below. - - * `SCMP_CMP_NE` - * `SCMP_CMP_LT` - * `SCMP_CMP_LE` - * `SCMP_CMP_EQ` - * `SCMP_CMP_GE` - * `SCMP_CMP_GT` - * `SCMP_CMP_MASKED_EQ` - -### Example - -```json - "seccomp": { - "defaultAction": "SCMP_ACT_ALLOW", - "architectures": [ - "SCMP_ARCH_X86", - "SCMP_ARCH_X32" - ], - "syscalls": [ - { - "names": [ - "getcwd", - "chmod" - ], - "action": "SCMP_ACT_ERRNO" - } - ] - } -``` - -## Rootfs Mount Propagation - -**`rootfsPropagation`** (string, OPTIONAL) sets the rootfs's mount propagation. - Its value is either slave, private, shared or unbindable. - The [Shared Subtrees][sharedsubtree] article in the kernel documentation has more information about mount propagation. - -### Example - -```json - "rootfsPropagation": "slave", -``` - -## Masked Paths - -**`maskedPaths`** (array of strings, OPTIONAL) will mask over the provided paths inside the container so that they cannot be read. - The values MUST be absolute paths in the [container namespace](glossary.md#container_namespace). - -### Example - -```json - "maskedPaths": [ - "/proc/kcore" - ] -``` - -## Readonly Paths - -**`readonlyPaths`** (array of strings, OPTIONAL) will set the provided paths as readonly inside the container. - The values MUST be absolute paths in the [container namespace](glossary.md#container-namespace). - -### Example - -```json - "readonlyPaths": [ - "/proc/sys" - ] -``` - -## Mount Label - -**`mountLabel`** (string, OPTIONAL) will set the Selinux context for the mounts in the container. - -### Example - -```json - "mountLabel": "system_u:object_r:svirt_sandbox_file_t:s0:c715,c811" -``` - - -[cgroup-v1]: https://www.kernel.org/doc/Documentation/cgroup-v1/cgroups.txt -[cgroup-v1-blkio]: https://www.kernel.org/doc/Documentation/cgroup-v1/blkio-controller.txt -[cgroup-v1-cpusets]: https://www.kernel.org/doc/Documentation/cgroup-v1/cpusets.txt -[cgroup-v1-devices]: https://www.kernel.org/doc/Documentation/cgroup-v1/devices.txt -[cgroup-v1-hugetlb]: https://www.kernel.org/doc/Documentation/cgroup-v1/hugetlb.txt -[cgroup-v1-memory]: https://www.kernel.org/doc/Documentation/cgroup-v1/memory.txt -[cgroup-v1-net-cls]: https://www.kernel.org/doc/Documentation/cgroup-v1/net_cls.txt -[cgroup-v1-net-prio]: https://www.kernel.org/doc/Documentation/cgroup-v1/net_prio.txt -[cgroup-v1-pids]: https://www.kernel.org/doc/Documentation/cgroup-v1/pids.txt -[cgroup-v2]: https://www.kernel.org/doc/Documentation/cgroup-v2.txt -[devices]: https://www.kernel.org/doc/Documentation/admin-guide/devices.txt -[devpts]: https://www.kernel.org/doc/Documentation/filesystems/devpts.txt -[file]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_164 -[libseccomp]: https://github.com/seccomp/libseccomp -[proc]: https://www.kernel.org/doc/Documentation/filesystems/proc.txt -[seccomp]: https://www.kernel.org/doc/Documentation/prctl/seccomp_filter.txt -[sharedsubtree]: https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt -[sysfs]: https://www.kernel.org/doc/Documentation/filesystems/sysfs.txt -[tmpfs]: https://www.kernel.org/doc/Documentation/filesystems/tmpfs.txt - -[console.4]: http://man7.org/linux/man-pages/man4/console.4.html -[full.4]: http://man7.org/linux/man-pages/man4/full.4.html -[mknod.1]: http://man7.org/linux/man-pages/man1/mknod.1.html -[mknod.2]: http://man7.org/linux/man-pages/man2/mknod.2.html -[namespaces.7_2]: http://man7.org/linux/man-pages/man7/namespaces.7.html -[null.4]: http://man7.org/linux/man-pages/man4/null.4.html -[pts.4]: http://man7.org/linux/man-pages/man4/pts.4.html -[random.4]: http://man7.org/linux/man-pages/man4/random.4.html -[sysctl.8]: http://man7.org/linux/man-pages/man8/sysctl.8.html -[tty.4]: http://man7.org/linux/man-pages/man4/tty.4.html -[zero.4]: http://man7.org/linux/man-pages/man4/zero.4.html -[user-namespaces]: http://man7.org/linux/man-pages/man7/user_namespaces.7.html -[intel-rdt-cat-kernel-interface]: https://www.kernel.org/doc/Documentation/x86/intel_rdt_ui.txt diff --git a/src/vendor/github.com/opencontainers/runtime-spec/config-solaris.md b/src/vendor/github.com/opencontainers/runtime-spec/config-solaris.md deleted file mode 100644 index 4446a166a0aed26f037d079f59eb91c053f60151..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/config-solaris.md +++ /dev/null @@ -1,120 +0,0 @@ -# Solaris Application Container Configuration - -Solaris application containers can be configured using the following properties, all of the below properties have mappings to properties specified under [zonecfg(1M)][zonecfg.1m_2] man page, except milestone. - -## milestone -The SMF(Service Management Facility) FMRI which should go to "online" state before we start the desired process within the container. - -**`milestone`** *(string, OPTIONAL)* - -### Example -```json -"milestone": "svc:/milestone/container:default" -``` - -## limitpriv -The maximum set of privileges any process in this container can obtain. -The property should consist of a comma-separated privilege set specification as described in [priv_str_to_set(3C)][priv-str-to-set.3c] man page for the respective release of Solaris. - -**`limitpriv`** *(string, OPTIONAL)* - -### Example -```json -"limitpriv": "default" -``` - -## maxShmMemory -The maximum amount of shared memory allowed for this application container. -A scale (K, M, G, T) can be applied to the value for each of these numbers (for example, 1M is one megabyte). -Mapped to `max-shm-memory` in [zonecfg(1M)][zonecfg.1m_2] man page. - -**`maxShmMemory`** *(string, OPTIONAL)* - -### Example -```json -"maxShmMemory": "512m" -``` - -## cappedCPU -Sets a limit on the amount of CPU time that can be used by a container. -The unit used translates to the percentage of a single CPU that can be used by all user threads in a container, expressed as a fraction (for example, .75) or a mixed number (whole number and fraction, for example, 1.25). -An ncpu value of 1 means 100% of a CPU, a value of 1.25 means 125%, .75 mean 75%, and so forth. -When projects within a capped container have their own caps, the minimum value takes precedence. -cappedCPU is mapped to `capped-cpu` in [zonecfg(1M)][zonecfg.1m_2] man page. - -* **`ncpus`** *(string, OPTIONAL)* - -### Example -```json -"cappedCPU": { - "ncpus": "8" -} -``` - -## cappedMemory -The physical and swap caps on the memory that can be used by this application container. -A scale (K, M, G, T) can be applied to the value for each of these numbers (for example, 1M is one megabyte). -cappedMemory is mapped to `capped-memory` in [zonecfg(1M)][zonecfg.1m_2] man page. - -* **`physical`** *(string, OPTIONAL)* -* **`swap`** *(string, OPTIONAL)* - -### Example -```json -"cappedMemory": { - "physical": "512m", - "swap": "512m" -} -``` - -## Network - -### Automatic Network (anet) -anet is specified as an array that is used to set up networking for Solaris application containers. -The anet resource represents the automatic creation of a network resource for an application container. -The zones administration daemon, zoneadmd, is the primary process for managing the container's virtual platform. -One of the daemon's responsibilities is creation and teardown of the networks for the container. -For more information on the daemon see the [zoneadmd(1M)][zoneadmd.1m] man page. -When such a container is started, a temporary VNIC(Virtual NIC) is automatically created for the container. -The VNIC is deleted when the container is torn down. -The following properties can be used to set up automatic networks. -For additional information on properties, check the [zonecfg(1M)][zonecfg.1m_2] man page for the respective release of Solaris. - -* **`linkname`** *(string, OPTIONAL)* Specify a name for the automatically created VNIC datalink. -* **`lowerLink`** *(string, OPTIONAL)* Specify the link over which the VNIC will be created. -Mapped to `lower-link` in the [zonecfg(1M)][zonecfg.1m_2] man page. -* **`allowedAddress`** *(string, OPTIONAL)* The set of IP addresses that the container can use might be constrained by specifying the `allowedAddress` property. - If `allowedAddress` has not been specified, then they can use any IP address on the associated physical interface for the network resource. - Otherwise, when `allowedAddress` is specified, the container cannot use IP addresses that are not in the `allowedAddress` list for the physical address. - Mapped to `allowed-address` in the [zonecfg(1M)][zonecfg.1m_2] man page. -* **`configureAllowedAddress`** *(string, OPTIONAL)* If `configureAllowedAddress` is set to true, the addresses specified by `allowedAddress` are automatically configured on the interface each time the container starts. - When it is set to false, the `allowedAddress` will not be configured on container start. - Mapped to `configure-allowed-address` in the [zonecfg(1M)][zonecfg.1m_2] man page. -* **`defrouter`** *(string, OPTIONAL)* The value for the OPTIONAL default router. -* **`macAddress`** *(string, OPTIONAL)* Set the VNIC's MAC addresses based on the specified value or keyword. - If not a keyword, it is interpreted as a unicast MAC address. - For a list of the supported keywords please refer to the [zonecfg(1M)][zonecfg.1m_2] man page of the respective Solaris release. - Mapped to `mac-address` in the [zonecfg(1M)][zonecfg.1m_2] man page. -* **`linkProtection`** *(string, OPTIONAL)* Enables one or more types of link protection using comma-separated values. - See the protection property in dladm(8) for supported values in respective release of Solaris. - Mapped to `link-protection` in the [zonecfg(1M)][zonecfg.1m_2] man page. - -#### Example -```json -"anet": [ - { - "allowedAddress": "172.17.0.2/16", - "configureAllowedAddress": "true", - "defrouter": "172.17.0.1/16", - "linkProtection": "mac-nospoof, ip-nospoof", - "linkname": "net0", - "lowerLink": "net2", - "macAddress": "02:42:f8:52:c7:16" - } -] -``` - - -[priv-str-to-set.3c]: http://docs.oracle.com/cd/E86824_01/html/E54766/priv-str-to-set-3c.html -[zoneadmd.1m]: http://docs.oracle.com/cd/E86824_01/html/E54764/zoneadmd-1m.html -[zonecfg.1m_2]: http://docs.oracle.com/cd/E86824_01/html/E54764/zonecfg-1m.html diff --git a/src/vendor/github.com/opencontainers/runtime-spec/config-windows.md b/src/vendor/github.com/opencontainers/runtime-spec/config-windows.md deleted file mode 100644 index a2e5e53392dd531fdac7afdde61eaa323ca6dd7f..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/config-windows.md +++ /dev/null @@ -1,175 +0,0 @@ -# Windows-specific Container Configuration - -This document describes the schema for the [Windows-specific section](config.md#platform-specific-configuration) of the [container configuration](config.md). -The Windows container specification uses APIs provided by the Windows Host Compute Service (HCS) to fulfill the spec. - -## LayerFolders - -**`layerFolders`** (array of strings, REQUIRED) specifies a list of layer folders the container image relies on. The list is ordered from topmost layer to base layer. - `layerFolders` MUST contain at least one entry. - -### Example - -```json - "windows": { - "layerFolders": [ - "C:\\Layers\\layer1", - "C:\\Layers\\layer2" - ] - } -``` - -## Resources - -You can configure a container's resource limits via the OPTIONAL `resources` field of the Windows configuration. - -### Memory - -`memory` is an OPTIONAL configuration for the container's memory usage. - -The following parameters can be specified: - -* **`limit`** *(uint64, OPTIONAL)* - sets limit of memory usage in bytes. - -#### Example - -```json - "windows": { - "resources": { - "memory": { - "limit": 2097152 - } - } - } -``` - -### CPU - -`cpu` is an OPTIONAL configuration for the container's CPU usage. - -The following parameters can be specified: - -* **`count`** *(uint64, OPTIONAL)* - specifies the number of CPUs available to the container. -* **`shares`** *(uint16, OPTIONAL)* - specifies the relative weight to other containers with CPU shares. -* **`maximum`** *(uint16, OPTIONAL)* - specifies the portion of processor cycles that this container can use as a percentage times 100. - -#### Example - -```json - "windows": { - "resources": { - "cpu": { - "maximum": 5000 - } - } - } -``` - -### Storage - -`storage` is an OPTIONAL configuration for the container's storage usage. - -The following parameters can be specified: - -* **`iops`** *(uint64, OPTIONAL)* - specifies the maximum IO operations per second for the system drive of the container. -* **`bps`** *(uint64, OPTIONAL)* - specifies the maximum bytes per second for the system drive of the container. -* **`sandboxSize`** *(uint64, OPTIONAL)* - specifies the minimum size of the system drive in bytes. - -#### Example - -```json - "windows": { - "resources": { - "storage": { - "iops": 50 - } - } - } -``` - -## Network - -You can configure a container's networking options via the OPTIONAL `network` field of the Windows configuration. - -The following parameters can be specified: - -* **`endpointList`** *(array of strings, OPTIONAL)* - list of HNS (Host Network Service) endpoints that the container should connect to. -* **`allowUnqualifiedDNSQuery`** *(bool, OPTIONAL)* - specifies if unqualified DNS name resolution is allowed. -* **`DNSSearchList`** *(array of strings, OPTIONAL)* - comma separated list of DNS suffixes to use for name resolution. -* **`networkSharedContainerName`** *(string, OPTIONAL)* - name (ID) of the container that we will share with the network stack. - -### Example - -```json - "windows": { - "network": { - "endpointList": [ - "7a010682-17e0-4455-a838-02e5d9655fe6" - ], - "allowUnqualifiedDNSQuery": true, - "DNSSearchList": [ - "a.com", - "b.com" - ], - "networkSharedContainerName": "containerName" - } - } -``` - -## Credential Spec - -You can configure a container's group Managed Service Account (gMSA) via the OPTIONAL `credentialSpec` field of the Windows configuration. -The `credentialSpec` is a JSON object whose properties are implementation-defined. -For more information about gMSAs, see [Active Directory Service Accounts for Windows Containers][gMSAOverview]. -For more information about tooling to generate a gMSA, see [Deployment Overview][gMSATooling]. - - -[gMSAOverview]: https://aka.ms/windowscontainers/manage-serviceaccounts -[gMSATooling]: https://aka.ms/windowscontainers/credentialspec-tools - -## Servicing - -When a container terminates, the Host Compute Service indicates if a Windows update servicing operation is pending. -You can indicate that a container should be started in a mode to apply pending servicing operations via the OPTIONAL `servicing` field of the Windows configuration. - -### Example - -```json - "windows": { - "servicing": true - } -``` - -## IgnoreFlushesDuringBoot - -You can indicate that a container should be started in an a mode where disk flushes are not performed during container boot via the OPTIONAL `ignoreFlushesDuringBoot` field of the Windows configuration. - -### Example - -```json - "windows": { - "ignoreFlushesDuringBoot": true - } -``` - -## HyperV - -`hyperv` is an OPTIONAL field of the Windows configuration. -If present, the container MUST be run with Hyper-V isolation. -If omitted, the container MUST be run as a Windows Server container. - -The following parameters can be specified: - -* **`utilityVMPath`** *(string, OPTIONAL)* - specifies the path to the image used for the utility VM. - This would be specified if using a base image which does not contain a utility VM image. - If not supplied, the runtime will search the container filesystem layers from the bottom-most layer upwards, until it locates "UtilityVM", and default to that path. - -### Example - -```json - "windows": { - "hyperv": { - "utilityVMPath": "C:\\path\\to\\utilityvm" - } - } -``` diff --git a/src/vendor/github.com/opencontainers/runtime-spec/config.md b/src/vendor/github.com/opencontainers/runtime-spec/config.md deleted file mode 100644 index 65d80cdb86d4b1920d988bba7f1c19cbe25c5d44..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/config.md +++ /dev/null @@ -1,860 +0,0 @@ -# Configuration - -This configuration file contains metadata necessary to implement [standard operations](runtime.md#operations) against the container. -This includes the process to run, environment variables to inject, sandboxing features to use, etc. - -The canonical schema is defined in this document, but there is a JSON Schema in [`schema/config-schema.json`](schema/config-schema.json) and Go bindings in [`specs-go/config.go`](specs-go/config.go). -[Platform](spec.md#platforms)-specific configuration schema are defined in the [platform-specific documents](#platform-specific-configuration) linked below. -For properties that are only defined for some [platforms](spec.md#platforms), the Go property has a `platform` tag listing those protocols (e.g. `platform:"linux,solaris"`). - -Below is a detailed description of each field defined in the configuration format and valid values are specified. -Platform-specific fields are identified as such. -For all platform-specific configuration values, the scope defined below in the [Platform-specific configuration](#platform-specific-configuration) section applies. - - -## Specification version - -* **`ociVersion`** (string, REQUIRED) MUST be in [SemVer v2.0.0][semver-v2.0.0] format and specifies the version of the Open Container Initiative Runtime Specification with which the bundle complies. - The Open Container Initiative Runtime Specification follows semantic versioning and retains forward and backward compatibility within major versions. - For example, if a configuration is compliant with version 1.1 of this specification, it is compatible with all runtimes that support any 1.1 or later release of this specification, but is not compatible with a runtime that supports 1.0 and not 1.1. - -### Example - -```json - "ociVersion": "0.1.0" -``` - -## Root - -**`root`** (object, OPTIONAL) specifies the container's root filesystem. - On Windows, for Windows Server Containers, this field is REQUIRED. - For [Hyper-V Containers](config-windows.md#hyperv), this field MUST NOT be set. - - On all other platforms, this field is REQUIRED. - -* **`path`** (string, REQUIRED) Specifies the path to the root filesystem for the container. - - * On Windows, `path` MUST be a [volume GUID path][naming-a-volume]. - - * On POSIX platforms, `path` is either an absolute path or a relative path to the bundle. - For example, with a bundle at `/to/bundle` and a root filesystem at `/to/bundle/rootfs`, the `path` value can be either `/to/bundle/rootfs` or `rootfs`. - The value SHOULD be the conventional `rootfs`. - - A directory MUST exist at the path declared by the field. - -* **`readonly`** (bool, OPTIONAL) If true then the root filesystem MUST be read-only inside the container, defaults to false. - * On Windows, this field MUST be omitted or false. - -### Example (POSIX platforms) - -```json -"root": { - "path": "rootfs", - "readonly": true -} -``` - -### Example (Windows) - -```json -"root": { - "path": "\\\\?\\Volume{ec84d99e-3f02-11e7-ac6c-00155d7682cf}\\" -} -``` - -## Mounts - -**`mounts`** (array of objects, OPTIONAL) specifies additional mounts beyond [`root`](#root). - The runtime MUST mount entries in the listed order. - For Linux, the parameters are as documented in [mount(2)][mount.2] system call man page. - For Solaris, the mount entry corresponds to the 'fs' resource in the [zonecfg(1M)][zonecfg.1m] man page. - -* **`destination`** (string, REQUIRED) Destination of mount point: path inside container. - This value MUST be an absolute path. - * Windows: one mount destination MUST NOT be nested within another mount (e.g., c:\\foo and c:\\foo\\bar). - * Solaris: corresponds to "dir" of the fs resource in [zonecfg(1M)][zonecfg.1m]. -* **`source`** (string, OPTIONAL) A device name, but can also be a directory name or a dummy. - Path values are either absolute or relative to the bundle. - * Windows: a local directory on the filesystem of the container host. UNC paths and mapped drives are not supported. - * Solaris: corresponds to "special" of the fs resource in [zonecfg(1M)][zonecfg.1m]. -* **`options`** (array of strings, OPTIONAL) Mount options of the filesystem to be used. - * Linux: supported options are listed in the [mount(8)][mount.8] man page. - Note both [filesystem-independent][mount.8-filesystem-independent] and [filesystem-specific][mount.8-filesystem-specific] options are listed. - * Solaris: corresponds to "options" of the fs resource in [zonecfg(1M)][zonecfg.1m]. - * Windows: runtimes MUST support `ro`, mounting the filesystem read-only when `ro` is given. - -### Example (Windows) - -```json -"mounts": [ - { - "destination": "C:\\folder-inside-container", - "source": "C:\\folder-on-host", - "options": ["ro"] - } -] -``` - -### POSIX-platform Mounts - -For POSIX platforms the `mounts` structure has the following fields: - -* **`type`** (string, OPTIONAL) The type of the filesystem to be mounted. - * Linux: filesystem types supported by the kernel as listed in */proc/filesystems* (e.g., "minix", "ext2", "ext3", "jfs", "xfs", "reiserfs", "msdos", "proc", "nfs", "iso9660"). - * Solaris: corresponds to "type" of the fs resource in [zonecfg(1M)][zonecfg.1m]. - -### Example (Linux) - -```json -"mounts": [ - { - "destination": "/tmp", - "type": "tmpfs", - "source": "tmpfs", - "options": ["nosuid","strictatime","mode=755","size=65536k"] - }, - { - "destination": "/data", - "type": "bind", - "source": "/volumes/testing", - "options": ["rbind","rw"] - } -] -``` - -### Example (Solaris) - -```json -"mounts": [ - { - "destination": "/opt/local", - "type": "lofs", - "source": "/usr/local", - "options": ["ro","nodevices"] - }, - { - "destination": "/opt/sfw", - "type": "lofs", - "source": "/opt/sfw" - } -] -``` - -## Process - -**`process`** (object, OPTIONAL) specifies the container process. - This property is REQUIRED when [`start`](runtime.md#start) is called. - -* **`terminal`** (bool, OPTIONAL) specifies whether a terminal is attached to the process, defaults to false. - As an example, if set to true on Linux a pseudoterminal pair is allocated for the process and the pseudoterminal slave is duplicated on the process's [standard streams][stdin.3]. -* **`consoleSize`** (object, OPTIONAL) specifies the console size in characters of the terminal. - Runtimes MUST ignore `consoleSize` if `terminal` is `false` or unset. - * **`height`** (uint, REQUIRED) - * **`width`** (uint, REQUIRED) -* **`cwd`** (string, REQUIRED) is the working directory that will be set for the executable. - This value MUST be an absolute path. -* **`env`** (array of strings, OPTIONAL) with the same semantics as [IEEE Std 1003.1-2008's `environ`][ieee-1003.1-2008-xbd-c8.1]. -* **`args`** (array of strings, REQUIRED) with similar semantics to [IEEE Std 1003.1-2008 `execvp`'s *argv*][ieee-1003.1-2008-functions-exec]. - This specification extends the IEEE standard in that at least one entry is REQUIRED, and that entry is used with the same semantics as `execvp`'s *file*. - -### POSIX process - -For systems that support POSIX rlimits (for example Linux and Solaris), the `process` object supports the following process-specific properties: - -* **`rlimits`** (array of objects, OPTIONAL) allows setting resource limits for the process. - Each entry has the following structure: - - * **`type`** (string, REQUIRED) the platform resource being limited. - * Linux: valid values are defined in the [`getrlimit(2)`][getrlimit.2] man page, such as `RLIMIT_MSGQUEUE`. - * Solaris: valid values are defined in the [`getrlimit(3)`][getrlimit.3] man page, such as `RLIMIT_CORE`. - - The runtime MUST [generate an error](runtime.md#errors) for any values which cannot be mapped to a relevant kernel interface. - For each entry in `rlimits`, a [`getrlimit(3)`][getrlimit.3] on `type` MUST succeed. - For the following properties, `rlim` refers to the status returned by the `getrlimit(3)` call. - - * **`soft`** (uint64, REQUIRED) the value of the limit enforced for the corresponding resource. - `rlim.rlim_cur` MUST match the configured value. - * **`hard`** (uint64, REQUIRED) the ceiling for the soft limit that could be set by an unprivileged process. - `rlim.rlim_max` MUST match the configured value. - Only a privileged process (e.g. one with the `CAP_SYS_RESOURCE` capability) can raise a hard limit. - - If `rlimits` contains duplicated entries with same `type`, the runtime MUST [generate an error](runtime.md#errors). - -### Linux Process - -For Linux-based systems, the `process` object supports the following process-specific properties. - -* **`apparmorProfile`** (string, OPTIONAL) specifies the name of the AppArmor profile for the process. - For more information about AppArmor, see [AppArmor documentation][apparmor]. -* **`capabilities`** (object, OPTIONAL) is an object containing arrays that specifies the sets of capabilities for the process. - Valid values are defined in the [capabilities(7)][capabilities.7] man page, such as `CAP_CHOWN`. - Any value which cannot be mapped to a relevant kernel interface MUST cause an error. - `capabilities` contains the following properties: - - * **`effective`** (array of strings, OPTIONAL) the `effective` field is an array of effective capabilities that are kept for the process. - * **`bounding`** (array of strings, OPTIONAL) the `bounding` field is an array of bounding capabilities that are kept for the process. - * **`inheritable`** (array of strings, OPTIONAL) the `inheritable` field is an array of inheritable capabilities that are kept for the process. - * **`permitted`** (array of strings, OPTIONAL) the `permitted` field is an array of permitted capabilities that are kept for the process. - * **`ambient`** (array of strings, OPTIONAL) the `ambient` field is an array of ambient capabilities that are kept for the process. -* **`noNewPrivileges`** (bool, OPTIONAL) setting `noNewPrivileges` to true prevents the process from gaining additional privileges. - As an example, the [`no_new_privs`][no-new-privs] article in the kernel documentation has information on how this is achieved using a `prctl` system call on Linux. -* **`oomScoreAdj`** *(int, OPTIONAL)* adjusts the oom-killer score in `[pid]/oom_score_adj` for the process's `[pid]` in a [proc pseudo-filesystem][proc_2]. - If `oomScoreAdj` is set, the runtime MUST set `oom_score_adj` to the given value. - If `oomScoreAdj` is not set, the runtime MUST NOT change the value of `oom_score_adj`. - - This is a per-process setting, where as [`disableOOMKiller`](config-linux.md#memory) is scoped for a memory cgroup. - For more information on how these two settings work together, see [the memory cgroup documentation section 10. OOM Contol][cgroup-v1-memory_2]. -* **`selinuxLabel`** (string, OPTIONAL) specifies the SELinux label for the process. - For more information about SELinux, see [SELinux documentation][selinux]. - -### User - -The user for the process is a platform-specific structure that allows specific control over which user the process runs as. - -#### POSIX-platform User - -For POSIX platforms the `user` structure has the following fields: - -* **`uid`** (int, REQUIRED) specifies the user ID in the [container namespace](glossary.md#container-namespace). -* **`gid`** (int, REQUIRED) specifies the group ID in the [container namespace](glossary.md#container-namespace). -* **`additionalGids`** (array of ints, OPTIONAL) specifies additional group IDs in the [container namespace](glossary.md#container-namespace) to be added to the process. - -_Note: symbolic name for uid and gid, such as uname and gname respectively, are left to upper levels to derive (i.e. `/etc/passwd` parsing, NSS, etc)_ - -### Example (Linux) - -```json -"process": { - "terminal": true, - "consoleSize": { - "height": 25, - "width": 80 - }, - "user": { - "uid": 1, - "gid": 1, - "additionalGids": [5, 6] - }, - "env": [ - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", - "TERM=xterm" - ], - "cwd": "/root", - "args": [ - "sh" - ], - "apparmorProfile": "acme_secure_profile", - "selinuxLabel": "system_u:system_r:svirt_lxc_net_t:s0:c124,c675", - "noNewPrivileges": true, - "capabilities": { - "bounding": [ - "CAP_AUDIT_WRITE", - "CAP_KILL", - "CAP_NET_BIND_SERVICE" - ], - "permitted": [ - "CAP_AUDIT_WRITE", - "CAP_KILL", - "CAP_NET_BIND_SERVICE" - ], - "inheritable": [ - "CAP_AUDIT_WRITE", - "CAP_KILL", - "CAP_NET_BIND_SERVICE" - ], - "effective": [ - "CAP_AUDIT_WRITE", - "CAP_KILL" - ], - "ambient": [ - "CAP_NET_BIND_SERVICE" - ] - }, - "rlimits": [ - { - "type": "RLIMIT_NOFILE", - "hard": 1024, - "soft": 1024 - } - ] -} -``` -### Example (Solaris) - -```json -"process": { - "terminal": true, - "consoleSize": { - "height": 25, - "width": 80 - }, - "user": { - "uid": 1, - "gid": 1, - "additionalGids": [2, 8] - }, - "env": [ - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", - "TERM=xterm" - ], - "cwd": "/root", - "args": [ - "/usr/bin/bash" - ] -} -``` - -#### Windows User - -For Windows based systems the user structure has the following fields: - -* **`username`** (string, OPTIONAL) specifies the user name for the process. - -### Example (Windows) - -```json -"process": { - "terminal": true, - "user": { - "username": "containeradministrator" - }, - "env": [ - "VARIABLE=1" - ], - "cwd": "c:\\foo", - "args": [ - "someapp.exe", - ] -} -``` - - -## Hostname - -* **`hostname`** (string, OPTIONAL) specifies the container's hostname as seen by processes running inside the container. - On Linux, for example, this will change the hostname in the [container](glossary.md#container-namespace) [UTS namespace][uts-namespace.7]. - Depending on your [namespace configuration](config-linux.md#namespaces), the container UTS namespace may be the [runtime](glossary.md#runtime-namespace) [UTS namespace][uts-namespace.7]. - -### Example - -```json -"hostname": "mrsdalloway" -``` - -## Platform-specific configuration - -* **`linux`** (object, OPTIONAL) [Linux-specific configuration](config-linux.md). - This MAY be set if the target platform of this spec is `linux`. -* **`windows`** (object, OPTIONAL) [Windows-specific configuration](config-windows.md). - This MUST be set if the target platform of this spec is `windows`. -* **`solaris`** (object, OPTIONAL) [Solaris-specific configuration](config-solaris.md). - This MAY be set if the target platform of this spec is `solaris`. - -### Example (Linux) - -```json -{ - "linux": { - "namespaces": [ - { - "type": "pid" - } - ] - } -} -``` - -## POSIX-platform Hooks - -For POSIX platforms, the configuration structure supports `hooks` for configuring custom actions related to the [lifecycle](runtime.md#lifecycle) of the container. - -* **`hooks`** (object, OPTIONAL) MAY contain any of the following properties: - * **`prestart`** (array of objects, OPTIONAL) is an array of [pre-start hooks](#prestart). - Entries in the array contain the following properties: - * **`path`** (string, REQUIRED) with similar semantics to [IEEE Std 1003.1-2008 `execv`'s *path*][ieee-1003.1-2008-functions-exec]. - This specification extends the IEEE standard in that **`path`** MUST be absolute. - * **`args`** (array of strings, OPTIONAL) with the same semantics as [IEEE Std 1003.1-2008 `execv`'s *argv*][ieee-1003.1-2008-functions-exec]. - * **`env`** (array of strings, OPTIONAL) with the same semantics as [IEEE Std 1003.1-2008's `environ`][ieee-1003.1-2008-xbd-c8.1]. - * **`timeout`** (int, OPTIONAL) is the number of seconds before aborting the hook. - If set, `timeout` MUST be greater than zero. - * **`poststart`** (array of objects, OPTIONAL) is an array of [post-start hooks](#poststart). - Entries in the array have the same schema as pre-start entries. - * **`poststop`** (array of objects, OPTIONAL) is an array of [post-stop hooks](#poststop). - Entries in the array have the same schema as pre-start entries. - -Hooks allow users to specify programs to run before or after various lifecycle events. -Hooks MUST be called in the listed order. -The [state](runtime.md#state) of the container MUST be passed to hooks over stdin so that they may do work appropriate to the current state of the container. - -### Prestart - -The pre-start hooks MUST be called after the [`start`](runtime.md#start) operation is called but [before the user-specified program command is executed](runtime.md#lifecycle). -On Linux, for example, they are called after the container namespaces are created, so they provide an opportunity to customize the container (e.g. the network namespace could be specified in this hook). - -### Poststart - -The post-start hooks MUST be called [after the user-specified process is executed](runtime.md#lifecycle) but before the [`start`](runtime.md#start) operation returns. -For example, this hook can notify the user that the container process is spawned. - -### Poststop - -The post-stop hooks MUST be called [after the container is deleted](runtime.md#lifecycle) but before the [`delete`](runtime.md#delete) operation returns. -Cleanup or debugging functions are examples of such a hook. - -### Example - -```json - "hooks": { - "prestart": [ - { - "path": "/usr/bin/fix-mounts", - "args": ["fix-mounts", "arg1", "arg2"], - "env": [ "key1=value1"] - }, - { - "path": "/usr/bin/setup-network" - } - ], - "poststart": [ - { - "path": "/usr/bin/notify-start", - "timeout": 5 - } - ], - "poststop": [ - { - "path": "/usr/sbin/cleanup.sh", - "args": ["cleanup.sh", "-f"] - } - ] - } -``` - -## Annotations - -**`annotations`** (object, OPTIONAL) contains arbitrary metadata for the container. - This information MAY be structured or unstructured. - Annotations MUST be a key-value map. - If there are no annotations then this property MAY either be absent or an empty map. - - Keys MUST be strings. - Keys MUST NOT be an empty string. - Keys SHOULD be named using a reverse domain notation - e.g. `com.example.myKey`. - Keys using the `org.opencontainers` namespace are reserved and MUST NOT be used by subsequent specifications. - Implementations that are reading/processing this configuration file MUST NOT generate an error if they encounter an unknown annotation key. - - Values MUST be strings. - Values MAY be an empty string. - -```json -"annotations": { - "com.example.gpu-cores": "2" -} -``` - -## Extensibility - -Runtimes that are reading or processing this configuration file MUST NOT generate an error if they encounter an unknown property. -Instead they MUST ignore unknown properties. - -## Valid values - -Runtimes that are reading or processing this configuration file MUST generate an error when invalid or unsupported values are encountered. -Unless support for a valid value is explicitly required, runtimes MAY choose which subset of the valid values it will support. - -## Configuration Schema Example - -Here is a full example `config.json` for reference. - -```json -{ - "ociVersion": "0.5.0-dev", - "process": { - "terminal": true, - "user": { - "uid": 1, - "gid": 1, - "additionalGids": [ - 5, - 6 - ] - }, - "args": [ - "sh" - ], - "env": [ - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", - "TERM=xterm" - ], - "cwd": "/", - "capabilities": { - "bounding": [ - "CAP_AUDIT_WRITE", - "CAP_KILL", - "CAP_NET_BIND_SERVICE" - ], - "permitted": [ - "CAP_AUDIT_WRITE", - "CAP_KILL", - "CAP_NET_BIND_SERVICE" - ], - "inheritable": [ - "CAP_AUDIT_WRITE", - "CAP_KILL", - "CAP_NET_BIND_SERVICE" - ], - "effective": [ - "CAP_AUDIT_WRITE", - "CAP_KILL" - ], - "ambient": [ - "CAP_NET_BIND_SERVICE" - ] - }, - "rlimits": [ - { - "type": "RLIMIT_CORE", - "hard": 1024, - "soft": 1024 - }, - { - "type": "RLIMIT_NOFILE", - "hard": 1024, - "soft": 1024 - } - ], - "apparmorProfile": "acme_secure_profile", - "oomScoreAdj": 100, - "selinuxLabel": "system_u:system_r:svirt_lxc_net_t:s0:c124,c675", - "noNewPrivileges": true - }, - "root": { - "path": "rootfs", - "readonly": true - }, - "hostname": "slartibartfast", - "mounts": [ - { - "destination": "/proc", - "type": "proc", - "source": "proc" - }, - { - "destination": "/dev", - "type": "tmpfs", - "source": "tmpfs", - "options": [ - "nosuid", - "strictatime", - "mode=755", - "size=65536k" - ] - }, - { - "destination": "/dev/pts", - "type": "devpts", - "source": "devpts", - "options": [ - "nosuid", - "noexec", - "newinstance", - "ptmxmode=0666", - "mode=0620", - "gid=5" - ] - }, - { - "destination": "/dev/shm", - "type": "tmpfs", - "source": "shm", - "options": [ - "nosuid", - "noexec", - "nodev", - "mode=1777", - "size=65536k" - ] - }, - { - "destination": "/dev/mqueue", - "type": "mqueue", - "source": "mqueue", - "options": [ - "nosuid", - "noexec", - "nodev" - ] - }, - { - "destination": "/sys", - "type": "sysfs", - "source": "sysfs", - "options": [ - "nosuid", - "noexec", - "nodev" - ] - }, - { - "destination": "/sys/fs/cgroup", - "type": "cgroup", - "source": "cgroup", - "options": [ - "nosuid", - "noexec", - "nodev", - "relatime", - "ro" - ] - } - ], - "hooks": { - "prestart": [ - { - "path": "/usr/bin/fix-mounts", - "args": [ - "fix-mounts", - "arg1", - "arg2" - ], - "env": [ - "key1=value1" - ] - }, - { - "path": "/usr/bin/setup-network" - } - ], - "poststart": [ - { - "path": "/usr/bin/notify-start", - "timeout": 5 - } - ], - "poststop": [ - { - "path": "/usr/sbin/cleanup.sh", - "args": [ - "cleanup.sh", - "-f" - ] - } - ] - }, - "linux": { - "devices": [ - { - "path": "/dev/fuse", - "type": "c", - "major": 10, - "minor": 229, - "fileMode": 438, - "uid": 0, - "gid": 0 - }, - { - "path": "/dev/sda", - "type": "b", - "major": 8, - "minor": 0, - "fileMode": 432, - "uid": 0, - "gid": 0 - } - ], - "uidMappings": [ - { - "hostID": 1000, - "containerID": 0, - "size": 32000 - } - ], - "gidMappings": [ - { - "hostID": 1000, - "containerID": 0, - "size": 32000 - } - ], - "sysctl": { - "net.ipv4.ip_forward": "1", - "net.core.somaxconn": "256" - }, - "cgroupsPath": "/myRuntime/myContainer", - "resources": { - "network": { - "classID": 1048577, - "priorities": [ - { - "name": "eth0", - "priority": 500 - }, - { - "name": "eth1", - "priority": 1000 - } - ] - }, - "pids": { - "limit": 32771 - }, - "hugepageLimits": [ - { - "pageSize": "2MB", - "limit": 9223372036854772000 - } - ], - "memory": { - "limit": 536870912, - "reservation": 536870912, - "swap": 536870912, - "kernel": -1, - "kernelTCP": -1, - "swappiness": 0, - "disableOOMKiller": false - }, - "cpu": { - "shares": 1024, - "quota": 1000000, - "period": 500000, - "realtimeRuntime": 950000, - "realtimePeriod": 1000000, - "cpus": "2-3", - "mems": "0-7" - }, - "devices": [ - { - "allow": false, - "access": "rwm" - }, - { - "allow": true, - "type": "c", - "major": 10, - "minor": 229, - "access": "rw" - }, - { - "allow": true, - "type": "b", - "major": 8, - "minor": 0, - "access": "r" - } - ], - "blockIO": { - "weight": 10, - "leafWeight": 10, - "weightDevice": [ - { - "major": 8, - "minor": 0, - "weight": 500, - "leafWeight": 300 - }, - { - "major": 8, - "minor": 16, - "weight": 500 - } - ], - "throttleReadBpsDevice": [ - { - "major": 8, - "minor": 0, - "rate": 600 - } - ], - "throttleWriteIOPSDevice": [ - { - "major": 8, - "minor": 16, - "rate": 300 - } - ] - } - }, - "rootfsPropagation": "slave", - "seccomp": { - "defaultAction": "SCMP_ACT_ALLOW", - "architectures": [ - "SCMP_ARCH_X86", - "SCMP_ARCH_X32" - ], - "syscalls": [ - { - "names": [ - "getcwd", - "chmod" - ], - "action": "SCMP_ACT_ERRNO" - } - ] - }, - "namespaces": [ - { - "type": "pid" - }, - { - "type": "network" - }, - { - "type": "ipc" - }, - { - "type": "uts" - }, - { - "type": "mount" - }, - { - "type": "user" - }, - { - "type": "cgroup" - } - ], - "maskedPaths": [ - "/proc/kcore", - "/proc/latency_stats", - "/proc/timer_stats", - "/proc/sched_debug" - ], - "readonlyPaths": [ - "/proc/asound", - "/proc/bus", - "/proc/fs", - "/proc/irq", - "/proc/sys", - "/proc/sysrq-trigger" - ], - "mountLabel": "system_u:object_r:svirt_sandbox_file_t:s0:c715,c811" - }, - "annotations": { - "com.example.key1": "value1", - "com.example.key2": "value2" - } -} -``` - - -[apparmor]: https://wiki.ubuntu.com/AppArmor -[cgroup-v1-memory_2]: https://www.kernel.org/doc/Documentation/cgroup-v1/memory.txt -[selinux]:http://selinuxproject.org/page/Main_Page -[no-new-privs]: https://www.kernel.org/doc/Documentation/prctl/no_new_privs.txt -[proc_2]: https://www.kernel.org/doc/Documentation/filesystems/proc.txt -[semver-v2.0.0]: http://semver.org/spec/v2.0.0.html -[ieee-1003.1-2008-xbd-c8.1]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_01 -[ieee-1003.1-2008-functions-exec]: http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html -[naming-a-volume]: https://aka.ms/nb3hqb - -[capabilities.7]: http://man7.org/linux/man-pages/man7/capabilities.7.html -[mount.2]: http://man7.org/linux/man-pages/man2/mount.2.html -[mount.8]: http://man7.org/linux/man-pages/man8/mount.8.html -[mount.8-filesystem-independent]: http://man7.org/linux/man-pages/man8/mount.8.html#FILESYSTEM-INDEPENDENT_MOUNT%20OPTIONS -[mount.8-filesystem-specific]: http://man7.org/linux/man-pages/man8/mount.8.html#FILESYSTEM-SPECIFIC_MOUNT%20OPTIONS -[getrlimit.2]: http://man7.org/linux/man-pages/man2/getrlimit.2.html -[getrlimit.3]: http://pubs.opengroup.org/onlinepubs/9699919799/functions/getrlimit.html -[stdin.3]: http://man7.org/linux/man-pages/man3/stdin.3.html -[uts-namespace.7]: http://man7.org/linux/man-pages/man7/namespaces.7.html -[zonecfg.1m]: http://docs.oracle.com/cd/E86824_01/html/E54764/zonecfg-1m.html diff --git a/src/vendor/github.com/opencontainers/runtime-spec/glossary.md b/src/vendor/github.com/opencontainers/runtime-spec/glossary.md deleted file mode 100644 index 6180db4c54b0d7c9c4d7d99c8963ae02cbebf7be..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/glossary.md +++ /dev/null @@ -1,38 +0,0 @@ -# Glossary - -## Bundle - -A [directory structure](bundle.md) that is written ahead of time, distributed, and used to seed the runtime for creating a [container](#container) and launching a process within it. - -## Configuration - -The [`config.json`](config.md) file in a [bundle](#bundle) which defines the intended [container](#container) and container process. - -## Container - -An environment for executing processes with configurable isolation and resource limitations. -For example, namespaces, resource limits, and mounts are all part of the container environment. - -## Container namespace - -On Linux,the [namespaces][namespaces.7] in which the [configured process](config.md#process) executes. - -## JSON - -All configuration [JSON][] MUST be encoded in [UTF-8][]. -JSON objects MUST NOT include duplicate names. -The order of entries in JSON objects is not significant. - -## Runtime - -An implementation of this specification. -It reads the [configuration files](#configuration) from a [bundle](#bundle), uses that information to create a [container](#container), launches a process inside the container, and performs other [lifecycle actions](runtime.md). - -## Runtime namespace - -On Linux, the namespaces from which new [container namespaces](#container-namespace) are [created](config-linux.md#namespaces) and from which some configured resources are accessed. - -[JSON]: https://tools.ietf.org/html/rfc7159 -[UTF-8]: http://www.unicode.org/versions/Unicode8.0.0/ch03.pdf - -[namespaces.7]: http://man7.org/linux/man-pages/man7/namespaces.7.html diff --git a/src/vendor/github.com/opencontainers/runtime-spec/implementations.md b/src/vendor/github.com/opencontainers/runtime-spec/implementations.md deleted file mode 100644 index b447e386e14f010f85773b9dbd07b91e9d0fc279..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/implementations.md +++ /dev/null @@ -1,33 +0,0 @@ -# Implementations - -The following sections link to associated projects, some of which are maintained by the OCI and some of which are maintained by external organizations. -If you know of any associated projects that are not listed here, please file a pull request adding a link to that project. - -## Runtime (Container) - -* [opencontainers/runc][runc] - Reference implementation of OCI runtime -* [projectatomic/bwrap-oci][bwrap-oci] - Convert the OCI spec file to a command line for [bubblewrap][bubblewrap] -* [giuseppe/crun][crun] - Runtime implementation in C - -## Runtime (Virtual Machine) - -* [hyperhq/runv][runv] - Hypervisor-based runtime for OCI -* [clearcontainers/runtime][cc-runtime] - Hypervisor-based OCI runtime utilising [virtcontainers][virtcontainers] by Intel®. - -## Testing & Tools - -* [kunalkushwaha/octool][octool] - A config linter and validator. -* [huawei-openlab/oct][oct] - Open Container Testing framework for OCI configuration and runtime -* [opencontainers/runtime-tools][runtime-tools] - A config generator and runtime/bundle testing framework. - - -[runc]: https://github.com/opencontainers/runc -[runv]: https://github.com/hyperhq/runv -[cc-runtime]: https://github.com/clearcontainers/runtime -[virtcontainers]: https://github.com/containers/virtcontainers -[octool]: https://github.com/kunalkushwaha/octool -[oct]: https://github.com/huawei-openlab/oct -[runtime-tools]: https://github.com/opencontainers/runtime-tools -[bwrap-oci]: https://github.com/projectatomic/bwrap-oci -[bubblewrap]: https://github.com/projectatomic/bubblewrap -[crun]: https://github.com/giuseppe/crun diff --git a/src/vendor/github.com/opencontainers/runtime-spec/meeting.ics b/src/vendor/github.com/opencontainers/runtime-spec/meeting.ics deleted file mode 100644 index aab560a15f2299e683784d8a3e16b3539bf3449f..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/meeting.ics +++ /dev/null @@ -1,37 +0,0 @@ -BEGIN:VCALENDAR -VERSION:2.0 -PRODID:-//Open Containers Initiative//Developer Meeting//EN -BEGIN:VTIMEZONE -TZID:America/Los_Angeles -LAST-MODIFIED:20050809T050000Z -BEGIN:STANDARD -DTSTART:20071104T020000 -RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU -TZOFFSETFROM:-0700 -TZOFFSETTO:-0800 -TZNAME:PST -END:STANDARD -BEGIN:DAYLIGHT -DTSTART:20070311T020000 -RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU -TZOFFSETFROM:-0800 -TZOFFSETTO:-0700 -TZNAME:PDT -END:DAYLIGHT -END:VTIMEZONE -BEGIN:VEVENT -UID:tdc-meeting@opencontainers.org -DTSTAMP:20170821T200000Z -DTSTART;TZID=America/Los_Angeles:20170906T140000 -RRULE:FREQ=MONTHLY;INTERVAL=1;BYDAY=1WE -DURATION:PT1H -SUMMARY:OCI TDC Meeting -DESCRIPTION;ALTREP="https://github.com/opencontainers/runtime-spec# - meetings":Open Containers Initiative Developer Meeting\n - https://github.com/opencontainers/runtime-spec#meetings\n - Web: https://www.uberconference.com/opencontainers\n - Audio-only: +1 415 968 0849 (no PIN needed) -LOCATION:https://www.uberconference.com/opencontainers -URL:https://github.com/opencontainers/runtime-spec/blob/master/meeting.ics -END:VEVENT -END:VCALENDAR diff --git a/src/vendor/github.com/opencontainers/runtime-spec/principles.md b/src/vendor/github.com/opencontainers/runtime-spec/principles.md deleted file mode 100644 index 6c7696302eb2d58e64c697435cef4b14e31223e8..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/principles.md +++ /dev/null @@ -1,46 +0,0 @@ -# The 5 principles of Standard Containers - -Define a unit of software delivery called a Standard Container. -The goal of a Standard Container is to encapsulate a software component and all its dependencies in a format that is self-describing and portable, so that any compliant runtime can run it without extra dependencies, regardless of the underlying machine and the contents of the container. - -The specification for Standard Containers defines: - -1. configuration file formats -2. a set of standard operations -3. an execution environment. - -A great analogy for this is the physical shipping container used by the transportation industry. -Shipping containers are a fundamental unit of delivery, they can be lifted, stacked, locked, loaded, unloaded and labelled. -Irrespective of their contents, by standardizing the container itself it allowed for a consistent, more streamlined and efficient set of processes to be defined. -For software Standard Containers offer similar functionality by being the fundamental, standardized, unit of delivery for a software package. - -## 1. Standard operations - -Standard Containers define a set of STANDARD OPERATIONS. -They can be created, started, and stopped using standard container tools; copied and snapshotted using standard filesystem tools; and downloaded and uploaded using standard network tools. - -## 2. Content-agnostic - -Standard Containers are CONTENT-AGNOSTIC: all standard operations have the same effect regardless of the contents. -They are started in the same way whether they contain a postgres database, a php application with its dependencies and application server, or Java build artifacts. - -## 3. Infrastructure-agnostic - -Standard Containers are INFRASTRUCTURE-AGNOSTIC: they can be run in any OCI supported infrastructure. -For example, a standard container can be bundled on a laptop, uploaded to cloud storage, downloaded, run and snapshotted by a build server at a fiber hotel in Virginia, uploaded to 10 staging servers in a home-made private cloud cluster, then sent to 30 production instances across 3 public cloud regions. - -## 4. Designed for automation - -Standard Containers are DESIGNED FOR AUTOMATION: because they offer the same standard operations regardless of content and infrastructure, Standard Containers, are extremely well-suited for automation. -In fact, you could say automation is their secret weapon. - -Many things that once required time-consuming and error-prone human effort can now be programmed. -Before Standard Containers, by the time a software component ran in production, it had been individually built, configured, bundled, documented, patched, vendored, templated, tweaked and instrumented by 10 different people on 10 different computers. -Builds failed, libraries conflicted, mirrors crashed, post-it notes were lost, logs were misplaced, cluster updates were half-broken. -The process was slow, inefficient and cost a fortune - and was entirely different depending on the language and infrastructure provider. - -## 5. Industrial-grade delivery - -Standard Containers make INDUSTRIAL-GRADE DELIVERY of software a reality. -Leveraging all of the properties listed above, Standard Containers are enabling large and small enterprises to streamline and automate their software delivery pipelines. -Whether it is in-house devOps flows, or external customer-based software delivery mechanisms, Standard Containers are changing the way the community thinks about software packaging and delivery. diff --git a/src/vendor/github.com/opencontainers/runtime-spec/project.md b/src/vendor/github.com/opencontainers/runtime-spec/project.md deleted file mode 100644 index 3f8a09b9d4dc5d87f6d58fe55fd12f3707eaec40..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/project.md +++ /dev/null @@ -1,12 +0,0 @@ -# Project docs - -## Release Process - -* Increment version in [`specs-go/version.go`](specs-go/version.go) -* `git commit` version increment -* `git tag` the prior commit (preferably signed tag) -* `make docs` to produce PDF and HTML copies of the spec -* Make a [release][releases] for the version. Attach the produced docs. - - -[releases]: https://github.com/opencontainers/runtime-spec/releases diff --git a/src/vendor/github.com/opencontainers/runtime-spec/runtime-linux.md b/src/vendor/github.com/opencontainers/runtime-spec/runtime-linux.md deleted file mode 100644 index 16c6dbebbdc260ed45461e234a326a94296c1d84..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/runtime-linux.md +++ /dev/null @@ -1,21 +0,0 @@ -# Linux Runtime - -## File descriptors - -By default, only the `stdin`, `stdout` and `stderr` file descriptors are kept open for the application by the runtime. -The runtime MAY pass additional file descriptors to the application to support features such as [socket activation][socket-activated-containers]. -Some of the file descriptors MAY be redirected to `/dev/null` even though they are open. - -## Dev symbolic links - -While creating the container (step 2 in the [lifecycle](runtime.md#lifecycle)), runtimes MUST create the following symlinks if the source file exists after processing [`mounts`](config.md#mounts): - -| Source | Destination | -| --------------- | ----------- | -| /proc/self/fd | /dev/fd | -| /proc/self/fd/0 | /dev/stdin | -| /proc/self/fd/1 | /dev/stdout | -| /proc/self/fd/2 | /dev/stderr | - - -[socket-activated-containers]: http://0pointer.de/blog/projects/socket-activated-containers.html diff --git a/src/vendor/github.com/opencontainers/runtime-spec/runtime.md b/src/vendor/github.com/opencontainers/runtime-spec/runtime.md deleted file mode 100644 index 3e14a083582907f756a9cf507ffc69d7c246a617..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/runtime.md +++ /dev/null @@ -1,140 +0,0 @@ -# Runtime and Lifecycle - -## Scope of a Container - -The entity using a runtime to create a container MUST be able to use the operations defined in this specification against that same container. -Whether other entities using the same, or other, instance of the runtime can see that container is out of scope of this specification. - -## State - -The state of a container includes the following properties: - -* **`ociVersion`** (string, REQUIRED) is the OCI specification version used when creating the container. -* **`id`** (string, REQUIRED) is the container's ID. - This MUST be unique across all containers on this host. - There is no requirement that it be unique across hosts. -* **`status`** (string, REQUIRED) is the runtime state of the container. - The value MAY be one of: - - * `creating`: the container is being created (step 2 in the [lifecycle](#lifecycle)) - * `created`: the runtime has finished the [create operation](#create) (after step 2 in the [lifecycle](#lifecycle)), and the container process has neither exited nor executed the user-specified program - * `running`: the container process has executed the user-specified program but has not exited (after step 5 in the [lifecycle](#lifecycle)) - * `stopped`: the container process has exited (step 7 in the [lifecycle](#lifecycle)) - - Additional values MAY be defined by the runtime, however, they MUST be used to represent new runtime states not defined above. -* **`pid`** (int, REQUIRED when `status` is `created` or `running` on Linux, OPTIONAL on other platforms) is the ID of the container process, as seen by the host. -* **`bundle`** (string, REQUIRED) is the absolute path to the container's bundle directory. - This is provided so that consumers can find the container's configuration and root filesystem on the host. -* **`annotations`** (map, OPTIONAL) contains the list of annotations associated with the container. - If no annotations were provided then this property MAY either be absent or an empty map. - -The state MAY include additional properties. - -When serialized in JSON, the format MUST adhere to the following pattern: - -```json -{ - "ociVersion": "0.2.0", - "id": "oci-container1", - "status": "running", - "pid": 4422, - "bundle": "/containers/redis", - "annotations": { - "myKey": "myValue" - } -} -``` - -See [Query State](#query-state) for information on retrieving the state of a container. - -## Lifecycle -The lifecycle describes the timeline of events that happen from when a container is created to when it ceases to exist. - -1. OCI compliant runtime's [`create`](runtime.md#create) command is invoked with a reference to the location of the bundle and a unique identifier. -2. The container's runtime environment MUST be created according to the configuration in [`config.json`](config.md). - If the runtime is unable to create the environment specified in the [`config.json`](config.md), it MUST [generate an error](#errors). - While the resources requested in the [`config.json`](config.md) MUST be created, the user-specified program (from [`process`](config.md#process)) MUST NOT be run at this time. - Any updates to [`config.json`](config.md) after this step MUST NOT affect the container. -3. Runtime's [`start`](runtime.md#start) command is invoked with the unique identifier of the container. -4. The [prestart hooks](config.md#prestart) MUST be invoked by the runtime. - If any prestart hook fails, the runtime MUST [generate an error](#errors), stop the container, and continue the lifecycle at step 9. -5. The runtime MUST run the user-specified program, as specified by [`process`](config.md#process). -6. The [poststart hooks](config.md#poststart) MUST be invoked by the runtime. - If any poststart hook fails, the runtime MUST [log a warning](#warnings), but the remaining hooks and lifecycle continue as if the hook had succeeded. -7. The container process exits. - This MAY happen due to erroring out, exiting, crashing or the runtime's [`kill`](runtime.md#kill) operation being invoked. -8. Runtime's [`delete`](runtime.md#delete) command is invoked with the unique identifier of the container. -9. The container MUST be destroyed by undoing the steps performed during create phase (step 2). -10. The [poststop hooks](config.md#poststop) MUST be invoked by the runtime. - If any poststop hook fails, the runtime MUST [log a warning](#warnings), but the remaining hooks and lifecycle continue as if the hook had succeeded. - -## Errors - -In cases where the specified operation generates an error, this specification does not mandate how, or even if, that error is returned or exposed to the user of an implementation. -Unless otherwise stated, generating an error MUST leave the state of the environment as if the operation were never attempted - modulo any possible trivial ancillary changes such as logging. - -## Warnings - -In cases where the specified operation logs a warning, this specification does not mandate how, or even if, that warning is returned or exposed to the user of an implementation. -Unless otherwise stated, logging a warning does not change the flow of the operation; it MUST continue as if the warning had not been logged. - -## Operations - -Unless otherwise stated, runtimes MUST support the following operations. - -Note: these operations are not specifying any command-line APIs, and the parameters are inputs for general operations. - -### Query State - -`state ` - -This operation MUST [generate an error](#errors) if it is not provided the ID of a container. -Attempting to query a container that does not exist MUST [generate an error](#errors). -This operation MUST return the state of a container as specified in the [State](#state) section. - -### Create - -`create ` - -This operation MUST [generate an error](#errors) if it is not provided a path to the bundle and the container ID to associate with the container. -If the ID provided is not unique across all containers within the scope of the runtime, or is not valid in any other way, the implementation MUST [generate an error](#errors) and a new container MUST NOT be created. -This operation MUST create a new container. - -All of the properties configured in [`config.json`](config.md) except for [`process`](config.md#process) MUST be applied. -[`process.args`](config.md#process) MUST NOT be applied until triggered by the [`start`](#start) operation. -The remaining `process` properties MAY be applied by this operation. -If the runtime cannot apply a property as specified in the [configuration](config.md), it MUST [generate an error](#errors) and a new container MUST NOT be created. - -The runtime MAY validate `config.json` against this spec, either generically or with respect to the local system capabilities, before creating the container ([step 2](#lifecycle)). -Runtime callers who are interested in pre-create validation can run [bundle-validation tools](implementations.md#testing--tools) before invoking the create operation. - -Any changes made to the [`config.json`](config.md) file after this operation will not have an effect on the container. - -### Start -`start ` - -This operation MUST [generate an error](#errors) if it is not provided the container ID. -Attempting to `start` a container that is not [`created`](#state) MUST have no effect on the container and MUST [generate an error](#errors). -This operation MUST run the user-specified program as specified by [`process`](config.md#process). -This operation MUST generate an error if `process` was not set. - -### Kill -`kill ` - -This operation MUST [generate an error](#errors) if it is not provided the container ID. -Attempting to send a signal to a container that is neither [`created` nor `running`](#state) MUST have no effect on the container and MUST [generate an error](#errors). -This operation MUST send the specified signal to the container process. - -### Delete -`delete ` - -This operation MUST [generate an error](#errors) if it is not provided the container ID. -Attempting to `delete` a container that is not [`stopped`](#state) MUST have no effect on the container and MUST [generate an error](#errors). -Deleting a container MUST delete the resources that were created during the `create` step. -Note that resources associated with the container, but not created by this container, MUST NOT be deleted. -Once a container is deleted its ID MAY be used by a subsequent container. - - -## Hooks -Many of the operations specified in this specification have "hooks" that allow for additional actions to be taken before or after each operation. -See [runtime configuration for hooks](./config.md#hooks) for more information. diff --git a/src/vendor/github.com/opencontainers/runtime-spec/schema/Makefile b/src/vendor/github.com/opencontainers/runtime-spec/schema/Makefile deleted file mode 100644 index 620cb68492ce7e273c6494af663aa67da36d8cad..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/schema/Makefile +++ /dev/null @@ -1,50 +0,0 @@ -GOOD_TESTS = $(wildcard test/good/*.json) -BAD_TESTS = $(wildcard test/bad/*.json) - -default: validate - -help: - @echo "Usage: make [target]" - @echo - @echo " * 'fmt' - format the json with indentation" - @echo " * 'help' - show this help information" - @echo " * 'validate' - build the validation tool" - -fmt: - find . -name '*.json' -exec bash -c 'jq --indent 4 -M . {} > xx && mv xx {} || echo "skipping invalid {}"' \; - -.PHONY: validate -validate: validate.go - go get -d ./... - go build ./validate.go - -test: validate $(TESTS) - for TYPE in $$(ls test); \ - do \ - echo "testing $${TYPE}"; \ - for FILE in $$(ls "test/$${TYPE}/good"); \ - do \ - echo " testing test/$${TYPE}/good/$${FILE}"; \ - if ./validate "$${TYPE}-schema.json" "test/$${TYPE}/good/$${FILE}" ; \ - then \ - echo " received expected validation success" ; \ - else \ - echo " received unexpected validation failure" ; \ - exit 1; \ - fi \ - done; \ - for FILE in $$(ls "test/$${TYPE}/bad"); \ - do \ - echo " testing test/$${TYPE}/bad/$${FILE}"; \ - if ./validate "$${TYPE}-schema.json" "test/$${TYPE}/good/$${FILE}" ; \ - then \ - echo " received unexpected validation success" ; \ - exit 1; \ - else \ - echo " received expected validation failure" ; \ - fi \ - done; \ - done - -clean: - rm -f validate diff --git a/src/vendor/github.com/opencontainers/runtime-spec/schema/README.md b/src/vendor/github.com/opencontainers/runtime-spec/schema/README.md deleted file mode 100644 index 95f3c549eff502cc2df528df6e39eebe44ee4c0c..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/schema/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# JSON schema - -## Overview - -This directory contains the [JSON Schema](http://json-schema.org/) for validating JSON covered by this specification. - -The layout of the files is as follows: - -* [config-schema.json](config-schema.json) - the primary entrypoint for the [configuration](../config.md) schema -* [config-linux.json](config-linux.json) - the [Linux-specific configuration sub-structure](../config-linux.md) -* [config-solaris.json](config-solaris.json) - the [Solaris-specific configuration sub-structure](../config-solaris.md) -* [config-windows.json](config-windows.json) - the [Windows-specific configuration sub-structure](../config-windows.md) -* [state-schema.json](state-schema.json) - the primary entrypoint for the [state JSON](../runtime.md#state) schema -* [defs.json](defs.json) - definitions for general types -* [defs-linux.json](defs-linux.json) - definitions for Linux-specific types -* [validate.go](validate.go) - validation utility source code - - -## Utility - -There is also included a simple utility for facilitating validation. -To build it: - -```bash -export GOPATH=`mktemp -d` -go get -d ./... -go build ./validate.go -rm -rf $GOPATH -``` - -Or you can just use make command to create the utility: - -```bash -make validate -``` - -Then use it like: - -```bash -./validate config-schema.json /config.json -``` - -Or like: - -```bash -./validate https://raw.githubusercontent.com/opencontainers/runtime-spec/v1.0.0/schema/schema.json /config.json -``` diff --git a/src/vendor/github.com/opencontainers/runtime-spec/schema/config-linux.json b/src/vendor/github.com/opencontainers/runtime-spec/schema/config-linux.json deleted file mode 100644 index 83a56267712cf71187ba77111caa4c4486e82ce8..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/schema/config-linux.json +++ /dev/null @@ -1,281 +0,0 @@ -{ - "linux": { - "description": "Linux platform-specific configurations", - "id": "https://opencontainers.org/schema/bundle/linux", - "type": "object", - "properties": { - "devices": { - "id": "https://opencontainers.org/schema/bundle/linux/devices", - "type": "array", - "items": { - "$ref": "defs-linux.json#/definitions/Device" - } - }, - "uidMappings": { - "id": "https://opencontainers.org/schema/bundle/linux/uidMappings", - "type": "array", - "items": { - "$ref": "defs.json#/definitions/IDMapping" - } - }, - "gidMappings": { - "id": "https://opencontainers.org/schema/bundle/linux/gidMappings", - "type": "array", - "items": { - "$ref": "defs.json#/definitions/IDMapping" - } - }, - "namespaces": { - "id": "https://opencontainers.org/schema/bundle/linux/namespaces", - "type": "array", - "items": { - "anyOf": [ - { - "$ref": "defs-linux.json#/definitions/NamespaceReference" - } - ] - } - }, - "resources": { - "id": "https://opencontainers.org/schema/bundle/linux/resources", - "type": "object", - "properties": { - "devices": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/devices", - "type": "array", - "items": { - "$ref": "defs-linux.json#/definitions/DeviceCgroup" - } - }, - "pids": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/pids", - "type": "object", - "properties": { - "limit": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/pids/limit", - "$ref": "defs.json#/definitions/int64" - } - }, - "required": [ - "limit" - ] - }, - "blockIO": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/blockIO", - "type": "object", - "properties": { - "weight": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/blockIO/weight", - "$ref": "defs-linux.json#/definitions/weight" - }, - "leafWeight": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/blockIO/leafWeight", - "$ref": "defs-linux.json#/definitions/weight" - }, - "throttleReadBpsDevice": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/blockIO/throttleReadBpsDevice", - "type": "array", - "items": { - "$ref": "defs-linux.json#/definitions/blockIODeviceThrottle" - } - }, - "throttleWriteBpsDevice": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/blockIO/throttleWriteBpsDevice", - "type": "array", - "items": { - "$ref": "defs-linux.json#/definitions/blockIODeviceThrottle" - } - }, - "throttleReadIOPSDevice": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/blockIO/throttleReadIOPSDevice", - "type": "array", - "items": { - "$ref": "defs-linux.json#/definitions/blockIODeviceThrottle" - } - }, - "throttleWriteIOPSDevice": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/blockIO/throttleWriteIOPSDevice", - "type": "array", - "items": { - "$ref": "defs-linux.json#/definitions/blockIODeviceThrottle" - } - }, - "weightDevice": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/blockIO/weightDevice", - "type": "array", - "items": { - "$ref": "defs-linux.json#/definitions/blockIODeviceWeight" - } - } - } - }, - "cpu": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/cpu", - "type": "object", - "properties": { - "cpus": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/cpu/cpus", - "type": "string" - }, - "mems": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/cpu/mems", - "type": "string" - }, - "period": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/cpu/period", - "$ref": "defs.json#/definitions/uint64" - }, - "quota": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/cpu/quota", - "$ref": "defs.json#/definitions/int64" - }, - "realtimePeriod": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/cpu/realtimePeriod", - "$ref": "defs.json#/definitions/uint64" - }, - "realtimeRuntime": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/cpu/realtimeRuntime", - "$ref": "defs.json#/definitions/int64" - }, - "shares": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/cpu/shares", - "$ref": "defs.json#/definitions/uint64" - } - } - }, - "hugepageLimits": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/hugepageLimits", - "type": "array", - "items": { - "type": "object", - "properties": { - "pageSize": { - "type": "string" - }, - "limit": { - "$ref": "defs.json#/definitions/uint64" - } - }, - "required": [ - "pageSize", - "limit" - ] - } - }, - "memory": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/memory", - "type": "object", - "properties": { - "kernel": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/memory/kernel", - "$ref": "defs.json#/definitions/int64" - }, - "kernelTCP": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/memory/kernelTCP", - "$ref": "defs.json#/definitions/int64" - }, - "limit": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/memory/limit", - "$ref": "defs.json#/definitions/int64" - }, - "reservation": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/memory/reservation", - "$ref": "defs.json#/definitions/int64" - }, - "swap": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/memory/swap", - "$ref": "defs.json#/definitions/int64" - }, - "swappiness": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/memory/swappiness", - "$ref": "defs.json#/definitions/uint64" - }, - "disableOOMKiller": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/memory/disableOOMKiller", - "type": "boolean" - } - } - }, - "network": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/network", - "type": "object", - "properties": { - "classID": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/network/classId", - "$ref": "defs.json#/definitions/uint32" - }, - "priorities": { - "id": "https://opencontainers.org/schema/bundle/linux/resources/network/priorities", - "type": "array", - "items": { - "$ref": "defs-linux.json#/definitions/NetworkInterfacePriority" - } - } - } - } - } - }, - "cgroupsPath": { - "id": "https://opencontainers.org/schema/bundle/linux/cgroupsPath", - "type": "string" - }, - "rootfsPropagation": { - "id": "https://opencontainers.org/schema/bundle/linux/rootfsPropagation", - "$ref": "defs-linux.json#/definitions/RootfsPropagation" - }, - "seccomp": { - "id": "https://opencontainers.org/schema/bundle/linux/seccomp", - "type": "object", - "properties": { - "defaultAction": { - "id": "https://opencontainers.org/schema/bundle/linux/seccomp/defaultAction", - "type": "string" - }, - "architectures": { - "id": "https://opencontainers.org/schema/bundle/linux/seccomp/architectures", - "type": "array", - "items": { - "$ref": "defs-linux.json#/definitions/SeccompArch" - } - }, - "syscalls": { - "id": "https://opencontainers.org/schema/bundle/linux/seccomp/syscalls", - "type": "array", - "items": { - "$ref": "defs-linux.json#/definitions/Syscall" - } - } - }, - "required": [ - "defaultAction" - ] - }, - "sysctl": { - "id": "https://opencontainers.org/schema/bundle/linux/sysctl", - "$ref": "defs.json#/definitions/mapStringString" - }, - "maskedPaths": { - "id": "https://opencontainers.org/schema/bundle/linux/maskedPaths", - "$ref": "defs.json#/definitions/ArrayOfStrings" - }, - "readonlyPaths": { - "id": "https://opencontainers.org/schema/bundle/linux/readonlyPaths", - "$ref": "defs.json#/definitions/ArrayOfStrings" - }, - "mountLabel": { - "id": "https://opencontainers.org/schema/bundle/linux/mountLabel", - "type": "string" - }, - "intelRdt": { - "id": "https://opencontainers.org/schema/bundle/linux/intelRdt", - "type": "object", - "properties": { - "l3CacheSchema": { - "id": "https://opencontainers.org/schema/bundle/linux/intelRdt/l3CacheSchema", - "type": "string" - } - } - } - } - } -} diff --git a/src/vendor/github.com/opencontainers/runtime-spec/schema/config-schema.json b/src/vendor/github.com/opencontainers/runtime-spec/schema/config-schema.json deleted file mode 100644 index 8fe1896ded7f501d7a68ab43afd813e534baff24..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/schema/config-schema.json +++ /dev/null @@ -1,207 +0,0 @@ -{ - "description": "Open Container Initiative Runtime Specification Container Configuration Schema", - "$schema": "http://json-schema.org/draft-04/schema#", - "id": "https://opencontainers.org/schema/bundle", - "type": "object", - "properties": { - "ociVersion": { - "id": "https://opencontainers.org/schema/bundle/ociVersion", - "$ref": "defs.json#/definitions/ociVersion" - }, - "hooks": { - "id": "https://opencontainers.org/schema/bundle/hooks", - "type": "object", - "properties": { - "prestart": { - "$ref": "defs.json#/definitions/ArrayOfHooks" - }, - "poststart": { - "$ref": "defs.json#/definitions/ArrayOfHooks" - }, - "poststop": { - "$ref": "defs.json#/definitions/ArrayOfHooks" - } - } - }, - "annotations": { - "$ref": "defs.json#/definitions/annotations" - }, - "hostname": { - "id": "https://opencontainers.org/schema/bundle/hostname", - "type": "string" - }, - "mounts": { - "id": "https://opencontainers.org/schema/bundle/mounts", - "type": "array", - "items": { - "$ref": "defs.json#/definitions/Mount" - } - }, - "root": { - "description": "Configures the container's root filesystem.", - "id": "https://opencontainers.org/schema/bundle/root", - "type": "object", - "required": [ - "path" - ], - "properties": { - "path": { - "id": "https://opencontainers.org/schema/bundle/root/path", - "$ref": "defs.json#/definitions/FilePath" - }, - "readonly": { - "id": "https://opencontainers.org/schema/bundle/root/readonly", - "type": "boolean" - } - } - }, - "process": { - "id": "https://opencontainers.org/schema/bundle/process", - "type": "object", - "required": [ - "cwd", - "args" - ], - "properties": { - "args": { - "id": "https://opencontainers.org/schema/bundle/process/args", - "$ref": "defs.json#/definitions/ArrayOfStrings" - }, - "consoleSize": { - "id": "https://opencontainers.org/schema/bundle/process/consoleSize", - "type": "object", - "required": [ - "height", - "width" - ], - "properties": { - "height": { - "id": "https://opencontainers.org/schema/bundle/process/consoleSize/height", - "$ref": "defs.json#/definitions/uint64" - }, - "width": { - "id": "https://opencontainers.org/schema/bundle/process/consoleSize/width", - "$ref": "defs.json#/definitions/uint64" - } - } - }, - "cwd": { - "id": "https://opencontainers.org/schema/bundle/process/cwd", - "type": "string" - }, - "env": { - "id": "https://opencontainers.org/schema/bundle/process/env", - "$ref": "defs.json#/definitions/Env" - }, - "terminal": { - "id": "https://opencontainers.org/schema/bundle/process/terminal", - "type": "boolean" - }, - "user": { - "id": "https://opencontainers.org/schema/bundle/process/user", - "type": "object", - "properties": { - "uid": { - "id": "https://opencontainers.org/schema/bundle/process/user/uid", - "$ref": "defs.json#/definitions/UID" - }, - "gid": { - "id": "https://opencontainers.org/schema/bundle/process/user/gid", - "$ref": "defs.json#/definitions/GID" - }, - "additionalGids": { - "id": "https://opencontainers.org/schema/bundle/process/user/additionalGids", - "$ref": "defs.json#/definitions/ArrayOfGIDs" - }, - "username": { - "id": "https://opencontainers.org/schema/bundle/process/user/username", - "type": "string" - } - } - }, - "capabilities": { - "id": "https://opencontainers.org/schema/bundle/process/linux/capabilities", - "type": "object", - "properties": { - "bounding": { - "id": "https://opencontainers.org/schema/bundle/process/linux/capabilities/bounding", - "$ref": "defs.json#/definitions/ArrayOfStrings" - }, - "permitted": { - "id": "https://opencontainers.org/schema/bundle/process/linux/capabilities/permitted", - "$ref": "defs.json#/definitions/ArrayOfStrings" - }, - "effective": { - "id": "https://opencontainers.org/schema/bundle/process/linux/capabilities/effective", - "$ref": "defs.json#/definitions/ArrayOfStrings" - }, - "inheritable": { - "id": "https://opencontainers.org/schema/bundle/process/linux/capabilities/inheritable", - "$ref": "defs.json#/definitions/ArrayOfStrings" - }, - "ambient": { - "id": "https://opencontainers.org/schema/bundle/process/linux/capabilities/ambient", - "$ref": "defs.json#/definitions/ArrayOfStrings" - } - } - }, - "apparmorProfile": { - "id": "https://opencontainers.org/schema/bundle/process/linux/apparmorProfile", - "type": "string" - }, - "oomScoreAdj": { - "id": "https://opencontainers.org/schema/bundle/process/linux/oomScoreAdj", - "type": "integer" - }, - "selinuxLabel": { - "id": "https://opencontainers.org/schema/bundle/process/linux/selinuxLabel", - "type": "string" - }, - "noNewPrivileges": { - "id": "https://opencontainers.org/schema/bundle/process/linux/noNewPrivileges", - "type": "boolean" - }, - "rlimits": { - "id": "https://opencontainers.org/schema/bundle/linux/rlimits", - "type": "array", - "items": { - "id": "https://opencontainers.org/schema/bundle/linux/rlimits/0", - "type": "object", - "required": [ - "type", - "soft", - "hard" - ], - "properties": { - "hard": { - "id": "https://opencontainers.org/schema/bundle/linux/rlimits/0/hard", - "$ref": "defs.json#/definitions/uint64" - }, - "soft": { - "id": "https://opencontainers.org/schema/bundle/linux/rlimits/0/soft", - "$ref": "defs.json#/definitions/uint64" - }, - "type": { - "id": "https://opencontainers.org/schema/bundle/linux/rlimits/0/type", - "type": "string", - "pattern": "^RLIMIT_[A-Z]+$" - } - } - } - } - } - }, - "linux": { - "$ref": "config-linux.json#/linux" - }, - "solaris": { - "$ref": "config-solaris.json#/solaris" - }, - "windows": { - "$ref": "config-windows.json#/windows" - } - }, - "required": [ - "ociVersion" - ] -} diff --git a/src/vendor/github.com/opencontainers/runtime-spec/schema/config-solaris.json b/src/vendor/github.com/opencontainers/runtime-spec/schema/config-solaris.json deleted file mode 100644 index b38a939d47f9bd131502c50f5ab430ff390a6fad..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/schema/config-solaris.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "solaris": { - "description": "Solaris platform-specific configurations", - "id": "https://opencontainers.org/schema/bundle/solaris", - "type": "object", - "properties": { - "milestone": { - "id": "https://opencontainers.org/schema/bundle/solaris/milestone", - "type": "string" - }, - "limitpriv": { - "id": "https://opencontainers.org/schema/bundle/solaris/limitpriv", - "type": "string" - }, - "maxShmMemory": { - "id": "https://opencontainers.org/schema/bundle/solaris/maxShmMemory", - "type": "string" - }, - "cappedCPU": { - "id": "https://opencontainers.org/schema/bundle/solaris/cappedCPU", - "type": "object", - "properties": { - "ncpus": { - "id": "https://opencontainers.org/schema/bundle/solaris/cappedCPU/ncpus", - "type": "string" - } - } - }, - "cappedMemory": { - "id": "https://opencontainers.org/schema/bundle/solaris/cappedMemory", - "type": "object", - "properties": { - "physical": { - "id": "https://opencontainers.org/schema/bundle/solaris/cappedMemory/physical", - "type": "string" - }, - "swap": { - "id": "https://opencontainers.org/schema/bundle/solaris/cappedMemory/swap", - "type": "string" - } - } - }, - "anet": { - "id": "https://opencontainers.org/schema/bundle/solaris/anet", - "type": "array", - "items": { - "type": "object", - "properties": { - "linkname": { - "type": "string" - }, - "lowerLink": { - "type": "string" - }, - "allowedAddress": { - "type": "string" - }, - "configureAllowedAddress": { - "type": "string" - }, - "defrouter": { - "type": "string" - }, - "macAddress": { - "type": "string" - }, - "linkProtection": { - "type": "string" - } - } - } - } - } - } -} diff --git a/src/vendor/github.com/opencontainers/runtime-spec/schema/config-windows.json b/src/vendor/github.com/opencontainers/runtime-spec/schema/config-windows.json deleted file mode 100644 index 8929d9f3f4c6c971824f37d36ed43eeb55f34271..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/schema/config-windows.json +++ /dev/null @@ -1,116 +0,0 @@ -{ - "windows": { - "description": "Windows platform-specific configurations", - "id": "https://opencontainers.org/schema/bundle/windows", - "type": "object", - "properties": { - "layerFolders": { - "id": "https://opencontainers.org/schema/bundle/windows/layerFolders", - "type": "array", - "items": { - "$ref": "defs.json#/definitions/FilePath" - }, - "minItems": 1 - }, - "resources": { - "id": "https://opencontainers.org/schema/bundle/windows/resources", - "type": "object", - "properties": { - "memory": { - "id": "https://opencontainers.org/schema/bundle/windows/resources/memory", - "type": "object", - "properties": { - "limit": { - "id": "https://opencontainers.org/schema/bundle/windows/resources/memory/limit", - "$ref": "defs.json#/definitions/uint64" - } - } - }, - "cpu": { - "id": "https://opencontainers.org/schema/bundle/windows/resources/cpu", - "type": "object", - "properties": { - "count": { - "id": "https://opencontainers.org/schema/bundle/windows/resources/cpu/count", - "$ref": "defs.json#/definitions/uint64" - }, - "shares": { - "id": "https://opencontainers.org/schema/bundle/windows/resources/cpu/shares", - "$ref": "defs.json#/definitions/uint16" - }, - "maximum": { - "id": "https://opencontainers.org/schema/bundle/windows/resources/cpu/maximum", - "$ref": "defs.json#/definitions/uint16" - } - } - }, - "storage": { - "id": "https://opencontainers.org/schema/bundle/windows/resources/storage", - "type": "object", - "properties": { - "iops": { - "id": "https://opencontainers.org/schema/bundle/windows/resources/storage/iops", - "$ref": "defs.json#/definitions/uint64" - }, - "bps": { - "id": "https://opencontainers.org/schema/bundle/windows/resources/storage/bps", - "$ref": "defs.json#/definitions/uint64" - }, - "sandboxSize": { - "id": "https://opencontainers.org/schema/bundle/windows/resources/storage/sandboxSize", - "$ref": "defs.json#/definitions/uint64" - } - } - } - } - }, - "network": { - "id": "https://opencontainers.org/schema/bundle/windows/network", - "type": "object", - "properties": { - "endpointList": { - "id": "https://opencontainers.org/schema/bundle/windows/network/endpointList", - "$ref": "defs.json#/definitions/ArrayOfStrings" - }, - "allowUnqualifiedDNSQuery": { - "id": "https://opencontainers.org/schema/bundle/windows/network/allowUnqualifiedDNSQuery", - "type": "boolean" - }, - "DNSSearchList": { - "id": "https://opencontainers.org/schema/bundle/windows/network/DNSSearchList", - "$ref": "defs.json#/definitions/ArrayOfStrings" - }, - "networkSharedContainerName": { - "id": "https://opencontainers.org/schema/bundle/windows/network/networkSharedContainerName", - "type": "string" - } - } - }, - "credentialSpec": { - "id": "https://opencontainers.org/schema/bundle/windows/credentialSpec", - "type": "object" - }, - "servicing": { - "id": "https://opencontainers.org/schema/bundle/windows/servicing", - "type": "boolean" - }, - "ignoreFlushesDuringBoot": { - "id": "https://opencontainers.org/schema/bundle/windows/ignoreFlushesDuringBoot", - "type": "boolean" - }, - "hyperv": { - "id": "https://opencontainers.org/schema/bundle/windows/hyperv", - "type": "object", - "properties": { - "utilityVMPath": { - "id": "https://opencontainers.org/schema/bundle/windows/hyperv/utilityVMPath", - "type": "string" - } - } - } - }, - "required": [ - "layerFolders" - ] - } -} diff --git a/src/vendor/github.com/opencontainers/runtime-spec/schema/defs-linux.json b/src/vendor/github.com/opencontainers/runtime-spec/schema/defs-linux.json deleted file mode 100644 index 4d9620a4a2155acb715e021c9cf01ea05153bf48..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/schema/defs-linux.json +++ /dev/null @@ -1,270 +0,0 @@ -{ - "definitions": { - "RootfsPropagation": { - "type": "string", - "enum": [ - "private", - "shared", - "slave", - "unbindable" - ] - }, - "SeccompArch": { - "type": "string", - "enum": [ - "SCMP_ARCH_X86", - "SCMP_ARCH_X86_64", - "SCMP_ARCH_X32", - "SCMP_ARCH_ARM", - "SCMP_ARCH_AARCH64", - "SCMP_ARCH_MIPS", - "SCMP_ARCH_MIPS64", - "SCMP_ARCH_MIPS64N32", - "SCMP_ARCH_MIPSEL", - "SCMP_ARCH_MIPSEL64", - "SCMP_ARCH_MIPSEL64N32", - "SCMP_ARCH_PPC", - "SCMP_ARCH_PPC64", - "SCMP_ARCH_PPC64LE", - "SCMP_ARCH_S390", - "SCMP_ARCH_S390X", - "SCMP_ARCH_PARISC", - "SCMP_ARCH_PARISC64" - ] - }, - "SeccompAction": { - "type": "string", - "enum": [ - "SCMP_ACT_KILL", - "SCMP_ACT_TRAP", - "SCMP_ACT_ERRNO", - "SCMP_ACT_TRACE", - "SCMP_ACT_ALLOW" - ] - }, - "SeccompOperators": { - "type": "string", - "enum": [ - "SCMP_CMP_NE", - "SCMP_CMP_LT", - "SCMP_CMP_LE", - "SCMP_CMP_EQ", - "SCMP_CMP_GE", - "SCMP_CMP_GT", - "SCMP_CMP_MASKED_EQ" - ] - }, - "SyscallArg": { - "type": "object", - "properties": { - "index": { - "$ref": "defs.json#/definitions/uint32" - }, - "value": { - "$ref": "defs.json#/definitions/uint64" - }, - "valueTwo": { - "$ref": "defs.json#/definitions/uint64" - }, - "op": { - "$ref": "#/definitions/SeccompOperators" - } - }, - "required": [ - "index", - "value", - "op" - ] - }, - "Syscall": { - "type": "object", - "properties": { - "names": { - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1 - }, - "action": { - "$ref": "#/definitions/SeccompAction" - }, - "args": { - "type": "array", - "items": { - "$ref": "#/definitions/SyscallArg" - } - } - }, - "required": [ - "names", - "action" - ] - }, - "Major": { - "description": "major device number", - "$ref": "defs.json#/definitions/int64" - }, - "Minor": { - "description": "minor device number", - "$ref": "defs.json#/definitions/int64" - }, - "FileMode": { - "description": "File permissions mode (typically an octal value)", - "type": "integer", - "minimum": 0, - "maximum": 512 - }, - "FileType": { - "description": "Type of a block or special character device", - "type": "string", - "pattern": "^[cbup]$" - }, - "Device": { - "type": "object", - "required": [ - "type", - "path" - ], - "properties": { - "type": { - "$ref": "#/definitions/FileType" - }, - "path": { - "$ref": "defs.json#/definitions/FilePath" - }, - "fileMode": { - "$ref": "#/definitions/FileMode" - }, - "major": { - "$ref": "#/definitions/Major" - }, - "minor": { - "$ref": "#/definitions/Minor" - }, - "uid": { - "$ref": "defs.json#/definitions/UID" - }, - "gid": { - "$ref": "defs.json#/definitions/GID" - } - } - }, - "weight": { - "type": "integer" - }, - "blockIODevice": { - "type": "object", - "properties": { - "major": { - "$ref": "#/definitions/Major" - }, - "minor": { - "$ref": "#/definitions/Minor" - } - }, - "required": [ - "major", - "minor" - ] - }, - "blockIODeviceWeight": { - "type": "object", - "allOf": [ - { - "$ref": "#/definitions/blockIODevice" - }, - { - "type": "object", - "properties": { - "weight": { - "$ref": "#/definitions/weight" - }, - "leafWeight": { - "$ref": "#/definitions/weight" - } - } - } - ] - }, - "blockIODeviceThrottle": { - "allOf": [ - { - "$ref": "#/definitions/blockIODevice" - }, - { - "type": "object", - "properties": { - "rate": { - "$ref": "defs.json#/definitions/uint64" - } - } - } - ] - }, - "DeviceCgroup": { - "type": "object", - "properties": { - "allow": { - "type": "boolean" - }, - "type": { - "type": "string" - }, - "major": { - "$ref": "#/definitions/Major" - }, - "minor": { - "$ref": "#/definitions/Minor" - }, - "access": { - "type": "string" - } - }, - "required": [ - "allow" - ] - }, - "NetworkInterfacePriority": { - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "priority": { - "$ref": "defs.json#/definitions/uint32" - } - }, - "required": [ - "name", - "priority" - ] - }, - "NamespaceType": { - "type": "string", - "enum": [ - "mount", - "pid", - "network", - "uts", - "ipc", - "user", - "cgroup" - ] - }, - "NamespaceReference": { - "type": "object", - "properties": { - "type": { - "$ref": "#/definitions/NamespaceType" - }, - "path": { - "$ref": "defs.json#/definitions/FilePath" - } - }, - "required": [ - "type" - ] - } - } -} diff --git a/src/vendor/github.com/opencontainers/runtime-spec/schema/defs.json b/src/vendor/github.com/opencontainers/runtime-spec/schema/defs.json deleted file mode 100644 index 377ec6d9f9a44baaa116bc9203ab173fce8d921f..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/schema/defs.json +++ /dev/null @@ -1,155 +0,0 @@ -{ - "description": "Definitions used throughout the Open Container Initiative Runtime Specification", - "definitions": { - "int8": { - "type": "integer", - "minimum": -128, - "maximum": 127 - }, - "int16": { - "type": "integer", - "minimum": -32768, - "maximum": 32767 - }, - "int32": { - "type": "integer", - "minimum": -2147483648, - "maximum": 2147483647 - }, - "int64": { - "type": "integer", - "minimum": -9223372036854776000, - "maximum": 9223372036854776000 - }, - "uint8": { - "type": "integer", - "minimum": 0, - "maximum": 255 - }, - "uint16": { - "type": "integer", - "minimum": 0, - "maximum": 65535 - }, - "uint32": { - "type": "integer", - "minimum": 0, - "maximum": 4294967295 - }, - "uint64": { - "type": "integer", - "minimum": 0, - "maximum": 18446744073709552000 - }, - "percent": { - "type": "integer", - "minimum": 0, - "maximum": 100 - }, - "mapStringString": { - "type": "object", - "patternProperties": { - ".{1,}": { - "type": "string" - } - } - }, - "UID": { - "$ref": "#/definitions/uint32" - }, - "GID": { - "$ref": "#/definitions/uint32" - }, - "ArrayOfGIDs": { - "type": "array", - "items": { - "$ref": "#/definitions/GID" - } - }, - "ArrayOfStrings": { - "type": "array", - "items": { - "type": "string" - } - }, - "FilePath": { - "type": "string" - }, - "Env": { - "$ref": "#/definitions/ArrayOfStrings" - }, - "Hook": { - "type": "object", - "properties": { - "path": { - "$ref": "#/definitions/FilePath" - }, - "args": { - "$ref": "#/definitions/ArrayOfStrings" - }, - "env": { - "$ref": "#/definitions/Env" - }, - "timeout": { - "type": "integer", - "minimum": 1 - } - }, - "required": [ - "path" - ] - }, - "ArrayOfHooks": { - "type": "array", - "items": { - "$ref": "#/definitions/Hook" - } - }, - "IDMapping": { - "type": "object", - "properties": { - "hostID": { - "$ref": "#/definitions/uint32" - }, - "containerID": { - "$ref": "#/definitions/uint32" - }, - "size": { - "$ref": "#/definitions/uint32" - } - }, - "required": [ - "hostID", - "containerID", - "size" - ] - }, - "Mount": { - "type": "object", - "properties": { - "source": { - "$ref": "#/definitions/FilePath" - }, - "destination": { - "$ref": "#/definitions/FilePath" - }, - "options": { - "$ref": "#/definitions/ArrayOfStrings" - }, - "type": { - "type": "string" - } - }, - "required": [ - "destination" - ] - }, - "ociVersion": { - "description": "The version of Open Container Initiative Runtime Specification that the document complies with", - "type": "string" - }, - "annotations": { - "$ref": "#/definitions/mapStringString" - } - } -} diff --git a/src/vendor/github.com/opencontainers/runtime-spec/schema/state-schema.json b/src/vendor/github.com/opencontainers/runtime-spec/schema/state-schema.json deleted file mode 100644 index 563a619f024b056c14c1005809b5b81b7d27304e..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/schema/state-schema.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "description": "Open Container Runtime State Schema", - "$schema": "http://json-schema.org/draft-04/schema#", - "id": "https://opencontainers.org/schema/state", - "type": "object", - "properties": { - "ociVersion": { - "id": "https://opencontainers.org/schema/runtime/state/ociVersion", - "$ref": "defs.json#/definitions/ociVersion" - }, - "id": { - "id": "https://opencontainers.org/schema/runtime/state/id", - "description": "the container's ID", - "type": "string" - }, - "status": { - "id": "https://opencontainers.org/schema/runtime/state/status", - "type": "string", - "enum": [ - "creating", - "created", - "running", - "stopped" - ] - }, - "pid": { - "id": "https://opencontainers.org/schema/runtime/state/pid", - "type": "integer", - "minimum": 0 - }, - "bundle": { - "id": "https://opencontainers.org/schema/runtime/state/bundle", - "type": "string" - }, - "annotations": { - "$ref": "defs.json#/definitions/annotations" - } - }, - "required": [ - "ociVersion", - "id", - "status", - "bundle" - ] -} diff --git a/src/vendor/github.com/opencontainers/runtime-spec/schema/test/config/bad/invalid-json.json b/src/vendor/github.com/opencontainers/runtime-spec/schema/test/config/bad/invalid-json.json deleted file mode 100644 index 8e935283062b59c17a4aac3b068d23076f2fd9c3..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/schema/test/config/bad/invalid-json.json +++ /dev/null @@ -1 +0,0 @@ -{] diff --git a/src/vendor/github.com/opencontainers/runtime-spec/schema/test/config/good/minimal-for-start.json b/src/vendor/github.com/opencontainers/runtime-spec/schema/test/config/good/minimal-for-start.json deleted file mode 100644 index 766d2d38059862387a9ce7784b0f191d13d4f6fe..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/schema/test/config/good/minimal-for-start.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "ociVersion": "1.0.0", - "root": { - "path": "rootfs" - }, - "process": { - "cwd": "/", - "args": [ - "sh" - ], - "user": { - "uid": 0, - "gid": 0 - } - } -} diff --git a/src/vendor/github.com/opencontainers/runtime-spec/schema/test/config/good/minimal.json b/src/vendor/github.com/opencontainers/runtime-spec/schema/test/config/good/minimal.json deleted file mode 100644 index e26e9d746dd41069a4a6b8c48c1378248a72e1f8..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/schema/test/config/good/minimal.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "ociVersion": "1.0.0", - "root": { - "path": "rootfs" - } -} diff --git a/src/vendor/github.com/opencontainers/runtime-spec/schema/test/config/good/spec-example.json b/src/vendor/github.com/opencontainers/runtime-spec/schema/test/config/good/spec-example.json deleted file mode 100644 index c7db729bd29a40f471d564357fd8de84801e018f..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/schema/test/config/good/spec-example.json +++ /dev/null @@ -1,368 +0,0 @@ -{ - "ociVersion": "0.5.0-dev", - "process": { - "terminal": true, - "user": { - "uid": 1, - "gid": 1, - "additionalGids": [ - 5, - 6 - ] - }, - "args": [ - "sh" - ], - "env": [ - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", - "TERM=xterm" - ], - "cwd": "/", - "capabilities": { - "bounding": [ - "CAP_AUDIT_WRITE", - "CAP_KILL", - "CAP_NET_BIND_SERVICE" - ], - "permitted": [ - "CAP_AUDIT_WRITE", - "CAP_KILL", - "CAP_NET_BIND_SERVICE" - ], - "inheritable": [ - "CAP_AUDIT_WRITE", - "CAP_KILL", - "CAP_NET_BIND_SERVICE" - ], - "effective": [ - "CAP_AUDIT_WRITE", - "CAP_KILL" - ], - "ambient": [ - "CAP_NET_BIND_SERVICE" - ] - }, - "rlimits": [ - { - "type": "RLIMIT_CORE", - "hard": 1024, - "soft": 1024 - }, - { - "type": "RLIMIT_NOFILE", - "hard": 1024, - "soft": 1024 - } - ], - "apparmorProfile": "acme_secure_profile", - "selinuxLabel": "system_u:system_r:svirt_lxc_net_t:s0:c124,c675", - "noNewPrivileges": true - }, - "root": { - "path": "rootfs", - "readonly": true - }, - "hostname": "slartibartfast", - "mounts": [ - { - "destination": "/proc", - "type": "proc", - "source": "proc" - }, - { - "destination": "/dev", - "type": "tmpfs", - "source": "tmpfs", - "options": [ - "nosuid", - "strictatime", - "mode=755", - "size=65536k" - ] - }, - { - "destination": "/dev/pts", - "type": "devpts", - "source": "devpts", - "options": [ - "nosuid", - "noexec", - "newinstance", - "ptmxmode=0666", - "mode=0620", - "gid=5" - ] - }, - { - "destination": "/dev/shm", - "type": "tmpfs", - "source": "shm", - "options": [ - "nosuid", - "noexec", - "nodev", - "mode=1777", - "size=65536k" - ] - }, - { - "destination": "/dev/mqueue", - "type": "mqueue", - "source": "mqueue", - "options": [ - "nosuid", - "noexec", - "nodev" - ] - }, - { - "destination": "/sys", - "type": "sysfs", - "source": "sysfs", - "options": [ - "nosuid", - "noexec", - "nodev" - ] - }, - { - "destination": "/sys/fs/cgroup", - "type": "cgroup", - "source": "cgroup", - "options": [ - "nosuid", - "noexec", - "nodev", - "relatime", - "ro" - ] - } - ], - "hooks": { - "prestart": [ - { - "path": "/usr/bin/fix-mounts", - "args": [ - "fix-mounts", - "arg1", - "arg2" - ], - "env": [ - "key1=value1" - ] - }, - { - "path": "/usr/bin/setup-network" - } - ], - "poststart": [ - { - "path": "/usr/bin/notify-start", - "timeout": 5 - } - ], - "poststop": [ - { - "path": "/usr/sbin/cleanup.sh", - "args": [ - "cleanup.sh", - "-f" - ] - } - ] - }, - "linux": { - "devices": [ - { - "path": "/dev/fuse", - "type": "c", - "major": 10, - "minor": 229, - "fileMode": 438, - "uid": 0, - "gid": 0 - }, - { - "path": "/dev/sda", - "type": "b", - "major": 8, - "minor": 0, - "fileMode": 432, - "uid": 0, - "gid": 0 - } - ], - "uidMappings": [ - { - "hostID": 1000, - "containerID": 0, - "size": 32000 - } - ], - "gidMappings": [ - { - "hostID": 1000, - "containerID": 0, - "size": 32000 - } - ], - "sysctl": { - "net.ipv4.ip_forward": "1", - "net.core.somaxconn": "256" - }, - "cgroupsPath": "/myRuntime/myContainer", - "resources": { - "network": { - "classID": 1048577, - "priorities": [ - { - "name": "eth0", - "priority": 500 - }, - { - "name": "eth1", - "priority": 1000 - } - ] - }, - "pids": { - "limit": 32771 - }, - "hugepageLimits": [ - { - "pageSize": "2MB", - "limit": 9223372036854772000 - } - ], - "oomScoreAdj": 100, - "memory": { - "limit": 536870912, - "reservation": 536870912, - "swap": 536870912, - "kernel": -1, - "kernelTCP": -1, - "swappiness": 0, - "disableOOMKiller": false - }, - "cpu": { - "shares": 1024, - "quota": 1000000, - "period": 500000, - "realtimeRuntime": 950000, - "realtimePeriod": 1000000, - "cpus": "2-3", - "mems": "0-7" - }, - "devices": [ - { - "allow": false, - "access": "rwm" - }, - { - "allow": true, - "type": "c", - "major": 10, - "minor": 229, - "access": "rw" - }, - { - "allow": true, - "type": "b", - "major": 8, - "minor": 0, - "access": "r" - } - ], - "blockIO": { - "weight": 10, - "leafWeight": 10, - "weightDevice": [ - { - "major": 8, - "minor": 0, - "weight": 500, - "leafWeight": 300 - }, - { - "major": 8, - "minor": 16, - "weight": 500 - } - ], - "throttleReadBpsDevice": [ - { - "major": 8, - "minor": 0, - "rate": 600 - } - ], - "throttleWriteIOPSDevice": [ - { - "major": 8, - "minor": 16, - "rate": 300 - } - ] - } - }, - "rootfsPropagation": "slave", - "seccomp": { - "defaultAction": "SCMP_ACT_ALLOW", - "architectures": [ - "SCMP_ARCH_X86", - "SCMP_ARCH_X32" - ], - "syscalls": [ - { - "names": [ - "getcwd", - "chmod" - ], - "action": "SCMP_ACT_ERRNO" - } - ] - }, - "namespaces": [ - { - "type": "pid" - }, - { - "type": "network" - }, - { - "type": "ipc" - }, - { - "type": "uts" - }, - { - "type": "mount" - }, - { - "type": "user" - }, - { - "type": "cgroup" - } - ], - "maskedPaths": [ - "/proc/kcore", - "/proc/latency_stats", - "/proc/timer_stats", - "/proc/sched_debug" - ], - "readonlyPaths": [ - "/proc/asound", - "/proc/bus", - "/proc/fs", - "/proc/irq", - "/proc/sys", - "/proc/sysrq-trigger" - ], - "mountLabel": "system_u:object_r:svirt_sandbox_file_t:s0:c715,c811" - }, - "annotations": { - "com.example.key1": "value1", - "com.example.key2": "value2" - } -} diff --git a/src/vendor/github.com/opencontainers/runtime-spec/schema/test/state/bad/invalid-json.json b/src/vendor/github.com/opencontainers/runtime-spec/schema/test/state/bad/invalid-json.json deleted file mode 100644 index 8e935283062b59c17a4aac3b068d23076f2fd9c3..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/schema/test/state/bad/invalid-json.json +++ /dev/null @@ -1 +0,0 @@ -{] diff --git a/src/vendor/github.com/opencontainers/runtime-spec/schema/test/state/good/spec-example.json b/src/vendor/github.com/opencontainers/runtime-spec/schema/test/state/good/spec-example.json deleted file mode 100644 index a49faee56675fbe771bad50498de2d889a852020..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/schema/test/state/good/spec-example.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "ociVersion": "0.2.0", - "id": "oci-container1", - "status": "running", - "pid": 4422, - "bundle": "/containers/redis", - "annotations": { - "myKey": "myValue" - } -} diff --git a/src/vendor/github.com/opencontainers/runtime-spec/schema/validate.go b/src/vendor/github.com/opencontainers/runtime-spec/schema/validate.go deleted file mode 100644 index 847d20540866067420831f1cdf95fd7e3e4751fd..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/schema/validate.go +++ /dev/null @@ -1,100 +0,0 @@ -package main - -import ( - "fmt" - "io/ioutil" - "os" - "path/filepath" - "strings" - - "github.com/xeipuuv/gojsonschema" -) - -const usage = `Validate is used to check document with specified schema. -You can use validate in following ways: - - 1.specify document file as an argument - validate - - 2.pass document content through a pipe - cat | validate - - 3.input document content manually, ended with ctrl+d(or your self-defined EOF keys) - validate - [INPUT DOCUMENT CONTENT HERE] -` - -func main() { - nargs := len(os.Args[1:]) - if nargs == 0 || nargs > 2 { - fmt.Printf("ERROR: invalid arguments number\n\n%s\n", usage) - os.Exit(1) - } - - if os.Args[1] == "help" || - os.Args[1] == "--help" || - os.Args[1] == "-h" { - fmt.Printf("%s\n", usage) - os.Exit(1) - } - - schemaPath := os.Args[1] - if !strings.Contains(schemaPath, "://") { - var err error - schemaPath, err = formatFilePath(schemaPath) - if err != nil { - fmt.Printf("ERROR: invalid schema-file path: %s\n", err) - os.Exit(1) - } - schemaPath = "file://" + schemaPath - } - - schemaLoader := gojsonschema.NewReferenceLoader(schemaPath) - - var documentLoader gojsonschema.JSONLoader - - if nargs > 1 { - documentPath, err := formatFilePath(os.Args[2]) - if err != nil { - fmt.Printf("ERROR: invalid document-file path: %s\n", err) - os.Exit(1) - } - documentLoader = gojsonschema.NewReferenceLoader("file://" + documentPath) - } else { - documentBytes, err := ioutil.ReadAll(os.Stdin) - if err != nil { - fmt.Println(err) - os.Exit(1) - } - documentString := string(documentBytes) - documentLoader = gojsonschema.NewStringLoader(documentString) - } - - result, err := gojsonschema.Validate(schemaLoader, documentLoader) - if err != nil { - fmt.Println(err) - os.Exit(1) - } - - if result.Valid() { - fmt.Printf("The document is valid\n") - } else { - fmt.Printf("The document is not valid. see errors :\n") - for _, desc := range result.Errors() { - fmt.Printf("- %s\n", desc) - } - os.Exit(1) - } -} - -func formatFilePath(path string) (string, error) { - if _, err := os.Stat(path); err != nil { - return "", err - } - - absPath, err := filepath.Abs(path) - if err != nil { - return "", err - } - return absPath, nil -} diff --git a/src/vendor/github.com/opencontainers/runtime-spec/spec.md b/src/vendor/github.com/opencontainers/runtime-spec/spec.md deleted file mode 100644 index 8bbe2203dc7660b1afac592df3216001e897f56a..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/spec.md +++ /dev/null @@ -1,46 +0,0 @@ -# Open Container Initiative Runtime Specification - -The [Open Container Initiative][oci] develops specifications for standards on Operating System process and application containers. - -# Abstract - -The Open Container Initiative Runtime Specification aims to specify the configuration, execution environment, and lifecycle of a container. - -A container's configuration is specified as the `config.json` for the supported platforms and details the fields that enable the creation of a container. -The execution environment is specified to ensure that applications running inside a container have a consistent environment between runtimes along with common actions defined for the container's lifecycle. - -# Platforms - -Platforms defined by this specification are: - -* `linux`: [runtime.md](runtime.md), [config.md](config.md), [config-linux.md](config-linux.md), and [runtime-linux.md](runtime-linux.md). -* `solaris`: [runtime.md](runtime.md), [config.md](config.md), and [config-solaris.md](config-solaris.md). -* `windows`: [runtime.md](runtime.md), [config.md](config.md), and [config-windows.md](config-windows.md). - -# Table of Contents - -- [Introduction](spec.md) - - [Notational Conventions](#notational-conventions) - - [Container Principles](principles.md) -- [Filesystem Bundle](bundle.md) -- [Runtime and Lifecycle](runtime.md) - - [Linux-specific Runtime and Lifecycle](runtime-linux.md) -- [Configuration](config.md) - - [Linux-specific Configuration](config-linux.md) - - [Solaris-specific Configuration](config-solaris.md) - - [Windows-specific Configuration](config-windows.md) -- [Glossary](glossary.md) - -# Notational Conventions - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" are to be interpreted as described in [RFC 2119][rfc2119]. - -The key words "unspecified", "undefined", and "implementation-defined" are to be interpreted as described in the [rationale for the C99 standard][c99-unspecified]. - -An implementation is not compliant for a given CPU architecture if it fails to satisfy one or more of the MUST, REQUIRED, or SHALL requirements for the [platforms](#platforms) it implements. -An implementation is compliant for a given CPU architecture if it satisfies all the MUST, REQUIRED, and SHALL requirements for the [platforms](#platforms) it implements. - - -[c99-unspecified]: http://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf#page=18 -[oci]: http://www.opencontainers.org -[rfc2119]: http://tools.ietf.org/html/rfc2119 diff --git a/src/vendor/github.com/opencontainers/runtime-spec/style.md b/src/vendor/github.com/opencontainers/runtime-spec/style.md deleted file mode 100644 index 1d42043e7c96f67c774a0a1befa8688bf5ffb6c3..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/opencontainers/runtime-spec/style.md +++ /dev/null @@ -1,131 +0,0 @@ -# Style and conventions - -## One sentence per line - -To keep consistency throughout the Markdown files in the Open Container spec all files should be formatted one sentence per line. -This fixes two things: it makes diffing easier with git and it resolves fights about line wrapping length. -For example, this paragraph will span three lines in the Markdown source. - -## Traditionally hex settings should use JSON integers, not JSON strings - -For example, [`"classID": 1048577`](config-linux.md#network) instead of `"classID": "0x100001"`. -The config JSON isn't enough of a UI to be worth jumping through string <-> integer hoops to support an 0x… form ([source][integer-over-hex]). - -## Constant names should keep redundant prefixes - -For example, `CAP_KILL` instead of `KILL` in [**`process.capabilities`**](config.md#process). -The redundancy reduction from removing the namespacing prefix is not useful enough to be worth trimming the upstream identifier ([source][keep-prefix]). - -## Optional settings should not have pointer Go types - -Because in many cases the Go default for the type is a no-op in the spec (sources [here][no-pointer-for-strings], [here][no-pointer-for-slices], and [here][no-pointer-for-boolean]). -The exceptions are entries where we need to distinguish between “not set” and “set to the Go default for that type” ([source][pointer-when-updates-require-changes]), and this decision should be made on a per-setting case. - -## Links - -Internal links should be [relative links][markdown-relative-links] when linking to content within the repository. -Internal links should be used inline. - -External links should be collected at the bottom of a markdown file and used as referenced links. -See 'Referenced Links' in this [markdown quick reference][markdown-quick-reference]. -The use of referenced links in the markdown body helps to keep files clean and organized. -This also facilitates updates of external link targets on a per-file basis. - -Referenced links should be kept in two alphabetically sorted sets, a general reference section followed by a man page section. -To keep Pandoc happy, duplicate naming of links within pages listed in the Makefile's `DOC_FILES` variable should be avoided by appending an `_N` to the link tagname, where `N` is some number not currently in use. -The organization and style of an existing reference section should be maintained unless it violates these style guidelines. - -An exception to these rules is when a URL is needed contextually, for example when showing an explicit link to the reader. - -## Examples - -### Anchoring - -For any given section that provides a notable example, it is ideal to have it denoted with [markdown headers][markdown-headers]. -The level of header should be such that it is a subheader of the header it is an example of. - -#### Example - -```markdown -## Some Topic - -### Some Subheader - -#### Further Subheader - -##### Example - -To use Further Subheader, ... - -### Example - -To use Some Topic, ... - -``` - -### Content - -Where necessary, the values in the example can be empty or unset, but accommodate with comments regarding this intention. - -Where feasible, the content and values used in an example should convey the fullest use of the data structures concerned. -Most commonly onlookers will intend to copy-and-paste a "working example". -If the intention of the example is to be a fully utilized example, rather than a copy-and-paste example, perhaps add a comment as such. - -```markdown -### Example -``` -```json -{ - "foo": null, - "bar": "" -} -``` - -**vs.** - -```markdown -### Example - -Following is a fully populated example (not necessarily for copy/paste use) -``` -```json -{ - "foo": [ - 1, - 2, - 3 - ], - "bar": "waffles", - "bif": { - "baz": "potatoes" - } -} -``` - -### Links - -The following is an example of different types of links. -This is shown as a complete markdown file, where the referenced links are at the bottom. - -```markdown -The specification repository's [glossary](glossary.md) is where readers can find definitions of commonly used terms. - -Readers may click through to the [Open Containers namespace][open-containers] on [GitHub][github]. - -The URL for the Open Containers link above is: https://github.com/opencontainers - - -[github]: https://github.com -[open-containers]: https://github.com/opencontainers -``` - - -[integer-over-hex]: https://github.com/opencontainers/runtime-spec/pull/267#r48360013 -[keep-prefix]: https://github.com/opencontainers/runtime-spec/pull/159#issuecomment-138728337 -[no-pointer-for-boolean]: https://github.com/opencontainers/runtime-spec/pull/290#r50296396 -[no-pointer-for-slices]: https://github.com/opencontainers/runtime-spec/pull/316#r50782982 -[no-pointer-for-strings]: https://github.com/opencontainers/runtime-spec/pull/653#issue-200439192 -[pointer-when-updates-require-changes]: https://github.com/opencontainers/runtime-spec/pull/317#r50932706 -[markdown-headers]: https://help.github.com/articles/basic-writing-and-formatting-syntax/#headings -[markdown-quick-reference]: https://en.support.wordpress.com/markdown-quick-reference -[markdown-relative-links]: https://help.github.com/articles/basic-writing-and-formatting-syntax/#relative-links diff --git a/src/vendor/github.com/pelletier/go-toml/.circleci/config.yml b/src/vendor/github.com/pelletier/go-toml/.circleci/config.yml deleted file mode 100644 index 0c13c8ed6adb3717cab7e0d5ac7211ef79528a7a..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/.circleci/config.yml +++ /dev/null @@ -1,170 +0,0 @@ -version: 2.1 - -executors: - golang: - parameters: - version: - type: string - docker: - - image: circleci/golang:<< parameters.version >> - -commands: - get_deps: - description: "Get go dependencies" - steps: - - run: go get github.com/jstemmer/go-junit-report - - run_test: - description: "Run unit tests for a go module" - parameters: - test_name: - type: string - module: - type: string - coverage: - default: false - type: boolean - allow_fail: - type: boolean - default: false - steps: - - run: - name: "Run tests for <>" - command: | - TEST_DIR="/tmp/test-results/<>" - mkdir -p ${TEST_DIR} - trap "go-junit-report ${TEST_DIR}/go-test-report.xml" EXIT - go test <> -race -v \ - <<# parameters.coverage >>-coverprofile=/tmp/workspace/coverage.txt -covermode=atomic<> \ - | tee /tmp/test-results/go-test.out <<# parameters.allow_fail >>|| true<> - -jobs: - go: - parameters: - version: - type: string - allow_fail: - type: boolean - default: false - executor: - name: golang - version: "<>" - working_directory: /go/src/github.com/pelletier/go-toml - environment: - GO111MODULE: "on" - steps: - - checkout - - run: mkdir -p /tmp/workspace - - run: go fmt ./... <<# parameters.allow_fail >>|| true<> - - get_deps - - run_test: - test_name: "go-toml" - module: "github.com/pelletier/go-toml" - coverage: true - allow_fail: <> - - run_test: - test_name: "tomljson" - module: "github.com/pelletier/go-toml/cmd/tomljson" - allow_fail: <> - - run_test: - test_name: "tomll" - module: "github.com/pelletier/go-toml/cmd/tomll" - allow_fail: <> - - run_test: - test_name: "query" - module: "github.com/pelletier/go-toml/query" - allow_fail: <> - - store_test_results: - path: /tmp/test-results - codecov: - docker: - - image: "circleci/golang:1.12" - steps: - - attach_workspace: - at: /tmp/workspace - - run: - name: "upload to codecov" - working_directory: /tmp/workspace - command: | - curl https://codecov.io/bash > codecov.sh - bash codecov.sh -v - docker: - docker: - - image: "circleci/golang:1.12" - steps: - - checkout - - setup_remote_docker: - docker_layer_caching: true - - run: docker build -t pelletier/go-toml:$CIRCLE_SHA1 . - - run: - name: "Publish docker image" - command: | - if [ "${CIRCLE_PR_REPONAME}" == "" ]; then - IMAGE_NAME="pelletier/go-toml" - IMAGE_SHA_TAG="${IMAGE_NAME}:$CIRCLE_SHA1" - if [ "${CIRCLE_BRANCH}" = "master" ]; then - docker login -u $DOCKER_USER -p $DOCKER_PASS - docker tag ${IMAGE_SHA_TAG} ${IMAGE_NAME}:latest - docker push ${IMAGE_NAME}:latest - fi - if [ "${CIRCLE_TAG}" != "" ]; then - docker login -u $DOCKER_USER -p $DOCKER_PASS - docker tag ${IMAGE_SHA_TAG} ${IMAGE_NAME}:${CIRCLE_TAG} - docker push ${IMAGE_NAME}:${CIRCLE_TAG} - fi - else - echo "not pushing docker image for forked repo" - fi - -workflows: - version: 2.1 - build: - jobs: - - go: - name: "go1_11" - version: "1.11" - - go: - name: "go1_12" - version: "1.12" - post-steps: - - run: go tool cover -html=/tmp/workspace/coverage.txt -o coverage.html - - store_artifacts: - path: /tmp/workspace/coverage.txt - - store_artifacts: - path: coverage.html - - persist_to_workspace: - root: /tmp/workspace - paths: - - coverage.txt - - go: - name: "gotip" - version: "1.12" # use as base - allow_fail: true - pre-steps: - - restore_cache: - keys: - - go-tip-source - - run: - name: "Compile go tip" - command: | - if [ ! -d "/tmp/go" ]; then - git clone https://go.googlesource.com/go /tmp/go - fi - cd /tmp/go - git checkout master - git pull - cd src - ./make.bash - echo 'export PATH="/tmp/go/bin:$PATH"' >> $BASH_ENV - - run: go version - - save_cache: - key: go-tip-source - paths: - - "/tmp/go" - - codecov: - requires: - - go1_11 - - go1_12 - - docker: - requires: - - codecov diff --git a/src/vendor/github.com/pelletier/go-toml/.github/ISSUE_TEMPLATE/bug_report.md b/src/vendor/github.com/pelletier/go-toml/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index 815b604178f610eda010d4f158e5107f09ddd0cd..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve - ---- - -**Describe the bug** -A clear and concise description of what the bug is. - -**To Reproduce** -Steps to reproduce the behavior. Including TOML files. - -**Expected behavior** -A clear and concise description of what you expected to happen, if other than "should work". - -**Versions** - - go-toml: version (git sha) - - go: version - - operating system: e.g. macOS, Windows, Linux - -**Additional context** -Add any other context about the problem here that you think may help to diagnose. diff --git a/src/vendor/github.com/pelletier/go-toml/.github/ISSUE_TEMPLATE/feature_request.md b/src/vendor/github.com/pelletier/go-toml/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index 066b2d920a28db73b4ba3a0b35e6905eeeef5772..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for this project - ---- - -**Is your feature request related to a problem? Please describe.** -A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - -**Describe the solution you'd like** -A clear and concise description of what you want to happen. - -**Describe alternatives you've considered** -A clear and concise description of any alternative solutions or features you've considered. - -**Additional context** -Add any other context or screenshots about the feature request here. diff --git a/src/vendor/github.com/pelletier/go-toml/benchmark.sh b/src/vendor/github.com/pelletier/go-toml/benchmark.sh old mode 100755 new mode 100644 diff --git a/src/vendor/github.com/pelletier/go-toml/benchmark_test.go b/src/vendor/github.com/pelletier/go-toml/benchmark_test.go deleted file mode 100644 index e1f209dfac185d5a489c7e92a2949d45479bf551..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/benchmark_test.go +++ /dev/null @@ -1,192 +0,0 @@ -package toml - -import ( - "bytes" - "encoding/json" - "io/ioutil" - "testing" - "time" - - burntsushi "github.com/BurntSushi/toml" - yaml "gopkg.in/yaml.v2" -) - -type benchmarkDoc struct { - Table struct { - Key string - Subtable struct { - Key string - } - Inline struct { - Name struct { - First string - Last string - } - Point struct { - X int64 - U int64 - } - } - } - String struct { - Basic struct { - Basic string - } - Multiline struct { - Key1 string - Key2 string - Key3 string - Continued struct { - Key1 string - Key2 string - Key3 string - } - } - Literal struct { - Winpath string - Winpath2 string - Quoted string - Regex string - Multiline struct { - Regex2 string - Lines string - } - } - } - Integer struct { - Key1 int64 - Key2 int64 - Key3 int64 - Key4 int64 - Underscores struct { - Key1 int64 - Key2 int64 - Key3 int64 - } - } - Float struct { - Fractional struct { - Key1 float64 - Key2 float64 - Key3 float64 - } - Exponent struct { - Key1 float64 - Key2 float64 - Key3 float64 - } - Both struct { - Key float64 - } - Underscores struct { - Key1 float64 - Key2 float64 - } - } - Boolean struct { - True bool - False bool - } - Datetime struct { - Key1 time.Time - Key2 time.Time - Key3 time.Time - } - Array struct { - Key1 []int64 - Key2 []string - Key3 [][]int64 - // TODO: Key4 not supported by go-toml's Unmarshal - Key5 []int64 - Key6 []int64 - } - Products []struct { - Name string - Sku int64 - Color string - } - Fruit []struct { - Name string - Physical struct { - Color string - Shape string - Variety []struct { - Name string - } - } - } -} - -func BenchmarkParseToml(b *testing.B) { - fileBytes, err := ioutil.ReadFile("benchmark.toml") - if err != nil { - b.Fatal(err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, err := LoadReader(bytes.NewReader(fileBytes)) - if err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkUnmarshalToml(b *testing.B) { - bytes, err := ioutil.ReadFile("benchmark.toml") - if err != nil { - b.Fatal(err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - target := benchmarkDoc{} - err := Unmarshal(bytes, &target) - if err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkUnmarshalBurntSushiToml(b *testing.B) { - bytes, err := ioutil.ReadFile("benchmark.toml") - if err != nil { - b.Fatal(err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - target := benchmarkDoc{} - err := burntsushi.Unmarshal(bytes, &target) - if err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkUnmarshalJson(b *testing.B) { - bytes, err := ioutil.ReadFile("benchmark.json") - if err != nil { - b.Fatal(err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - target := benchmarkDoc{} - err := json.Unmarshal(bytes, &target) - if err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkUnmarshalYaml(b *testing.B) { - bytes, err := ioutil.ReadFile("benchmark.yml") - if err != nil { - b.Fatal(err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - target := benchmarkDoc{} - err := yaml.Unmarshal(bytes, &target) - if err != nil { - b.Fatal(err) - } - } -} diff --git a/src/vendor/github.com/pelletier/go-toml/cmd/tomljson/main.go b/src/vendor/github.com/pelletier/go-toml/cmd/tomljson/main.go deleted file mode 100644 index 322315b531593875152db71472ae0cb94aa3c5d9..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/cmd/tomljson/main.go +++ /dev/null @@ -1,71 +0,0 @@ -// Tomljson reads TOML and converts to JSON. -// -// Usage: -// cat file.toml | tomljson > file.json -// tomljson file1.toml > file.json -package main - -import ( - "encoding/json" - "flag" - "fmt" - "io" - "os" - - "github.com/pelletier/go-toml" -) - -func main() { - flag.Usage = func() { - fmt.Fprintln(os.Stderr, "tomljson can be used in two ways:") - fmt.Fprintln(os.Stderr, "Writing to STDIN and reading from STDOUT:") - fmt.Fprintln(os.Stderr, " cat file.toml | tomljson > file.json") - fmt.Fprintln(os.Stderr, "") - fmt.Fprintln(os.Stderr, "Reading from a file name:") - fmt.Fprintln(os.Stderr, " tomljson file.toml") - } - flag.Parse() - os.Exit(processMain(flag.Args(), os.Stdin, os.Stdout, os.Stderr)) -} - -func processMain(files []string, defaultInput io.Reader, output io.Writer, errorOutput io.Writer) int { - // read from stdin and print to stdout - inputReader := defaultInput - - if len(files) > 0 { - var err error - inputReader, err = os.Open(files[0]) - if err != nil { - printError(err, errorOutput) - return -1 - } - } - s, err := reader(inputReader) - if err != nil { - printError(err, errorOutput) - return -1 - } - io.WriteString(output, s+"\n") - return 0 -} - -func printError(err error, output io.Writer) { - io.WriteString(output, err.Error()+"\n") -} - -func reader(r io.Reader) (string, error) { - tree, err := toml.LoadReader(r) - if err != nil { - return "", err - } - return mapToJSON(tree) -} - -func mapToJSON(tree *toml.Tree) (string, error) { - treeMap := tree.ToMap() - bytes, err := json.MarshalIndent(treeMap, "", " ") - if err != nil { - return "", err - } - return string(bytes[:]), nil -} diff --git a/src/vendor/github.com/pelletier/go-toml/cmd/tomljson/main_test.go b/src/vendor/github.com/pelletier/go-toml/cmd/tomljson/main_test.go deleted file mode 100644 index d515ee02be7b1222280f5e25c7235122a012e0a8..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/cmd/tomljson/main_test.go +++ /dev/null @@ -1,90 +0,0 @@ -package main - -import ( - "bytes" - "io/ioutil" - "os" - "runtime" - "strings" - "testing" -) - -func expectBufferEquality(t *testing.T, name string, buffer *bytes.Buffer, expected string) { - output := buffer.String() - if output != expected { - t.Errorf("incorrect %s:\n%s\n\nexpected %s:\n%s", name, output, name, expected) - t.Log([]rune(output)) - t.Log([]rune(expected)) - } -} - -func expectProcessMainResults(t *testing.T, input string, args []string, exitCode int, expectedOutput string, expectedError string) { - inputReader := strings.NewReader(input) - outputBuffer := new(bytes.Buffer) - errorBuffer := new(bytes.Buffer) - - returnCode := processMain(args, inputReader, outputBuffer, errorBuffer) - - expectBufferEquality(t, "output", outputBuffer, expectedOutput) - expectBufferEquality(t, "error", errorBuffer, expectedError) - - if returnCode != exitCode { - t.Error("incorrect return code:", returnCode, "expected", exitCode) - } -} - -func TestProcessMainReadFromStdin(t *testing.T) { - input := ` - [mytoml] - a = 42` - expectedOutput := `{ - "mytoml": { - "a": 42 - } -} -` - expectedError := `` - expectedExitCode := 0 - - expectProcessMainResults(t, input, []string{}, expectedExitCode, expectedOutput, expectedError) -} - -func TestProcessMainReadFromFile(t *testing.T) { - input := ` - [mytoml] - a = 42` - - tmpfile, err := ioutil.TempFile("", "example.toml") - if err != nil { - t.Fatal(err) - } - if _, err := tmpfile.Write([]byte(input)); err != nil { - t.Fatal(err) - } - - defer os.Remove(tmpfile.Name()) - - expectedOutput := `{ - "mytoml": { - "a": 42 - } -} -` - expectedError := `` - expectedExitCode := 0 - - expectProcessMainResults(t, ``, []string{tmpfile.Name()}, expectedExitCode, expectedOutput, expectedError) -} - -func TestProcessMainReadFromMissingFile(t *testing.T) { - var expectedError string - if runtime.GOOS == "windows" { - expectedError = `open /this/file/does/not/exist: The system cannot find the path specified. -` - } else { - expectedError = `open /this/file/does/not/exist: no such file or directory -` - } - - expectProcessMainResults(t, ``, []string{"/this/file/does/not/exist"}, -1, ``, expectedError) -} diff --git a/src/vendor/github.com/pelletier/go-toml/cmd/tomll/main.go b/src/vendor/github.com/pelletier/go-toml/cmd/tomll/main.go deleted file mode 100644 index 93ab0c962829bd972f4aa4e765b1afd8c72513aa..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/cmd/tomll/main.go +++ /dev/null @@ -1,65 +0,0 @@ -// Tomll is a linter for TOML -// -// Usage: -// cat file.toml | tomll > file_linted.toml -// tomll file1.toml file2.toml # lint the two files in place -package main - -import ( - "flag" - "fmt" - "io" - "io/ioutil" - "os" - - "github.com/pelletier/go-toml" -) - -func main() { - flag.Usage = func() { - fmt.Fprintln(os.Stderr, "tomll can be used in two ways:") - fmt.Fprintln(os.Stderr, "Writing to STDIN and reading from STDOUT:") - fmt.Fprintln(os.Stderr, " cat file.toml | tomll > file.toml") - fmt.Fprintln(os.Stderr, "") - fmt.Fprintln(os.Stderr, "Reading and updating a list of files:") - fmt.Fprintln(os.Stderr, " tomll a.toml b.toml c.toml") - fmt.Fprintln(os.Stderr, "") - fmt.Fprintln(os.Stderr, "When given a list of files, tomll will modify all files in place without asking.") - } - flag.Parse() - // read from stdin and print to stdout - if flag.NArg() == 0 { - s, err := lintReader(os.Stdin) - if err != nil { - io.WriteString(os.Stderr, err.Error()) - os.Exit(-1) - } - io.WriteString(os.Stdout, s) - } else { - // otherwise modify a list of files - for _, filename := range flag.Args() { - s, err := lintFile(filename) - if err != nil { - io.WriteString(os.Stderr, err.Error()) - os.Exit(-1) - } - ioutil.WriteFile(filename, []byte(s), 0644) - } - } -} - -func lintFile(filename string) (string, error) { - tree, err := toml.LoadFile(filename) - if err != nil { - return "", err - } - return tree.String(), nil -} - -func lintReader(r io.Reader) (string, error) { - tree, err := toml.LoadReader(r) - if err != nil { - return "", err - } - return tree.String(), nil -} diff --git a/src/vendor/github.com/pelletier/go-toml/cmd/tomltestgen/main.go b/src/vendor/github.com/pelletier/go-toml/cmd/tomltestgen/main.go deleted file mode 100644 index cd9bdd77bfc5d450d0c2093e90cfaae139899655..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/cmd/tomltestgen/main.go +++ /dev/null @@ -1,219 +0,0 @@ -// Tomltestgen is a program that retrieves a given version of -// https://github.com/BurntSushi/toml-test and generates go code for go-toml's unit tests -// based on the test files. -// -// Usage: go run github.com/pelletier/go-toml/cmd/tomltestgen > toml_testgen_test.go -package main - -import ( - "archive/zip" - "bytes" - "flag" - "fmt" - "go/format" - "io" - "io/ioutil" - "log" - "net/http" - "os" - "regexp" - "strconv" - "strings" - "text/template" - "time" -) - -type invalid struct { - Name string - Input string -} - -type valid struct { - Name string - Input string - JsonRef string -} - -type testsCollection struct { - Ref string - Timestamp string - Invalid []invalid - Valid []valid - Count int -} - -const srcTemplate = "// Generated by tomltestgen for toml-test ref {{.Ref}} on {{.Timestamp}}\n" + - "package toml\n" + - " import (\n" + - " \"testing\"\n" + - ")\n" + - - "{{range .Invalid}}\n" + - "func TestInvalid{{.Name}}(t *testing.T) {\n" + - " input := {{.Input|gostr}}\n" + - " testgenInvalid(t, input)\n" + - "}\n" + - "{{end}}\n" + - "\n" + - "{{range .Valid}}\n" + - "func TestValid{{.Name}}(t *testing.T) {\n" + - " input := {{.Input|gostr}}\n" + - " jsonRef := {{.JsonRef|gostr}}\n" + - " testgenValid(t, input, jsonRef)\n" + - "}\n" + - "{{end}}\n" - -func downloadTmpFile(url string) string { - log.Println("starting to download file from", url) - resp, err := http.Get(url) - if err != nil { - panic(err) - } - defer resp.Body.Close() - - tmpfile, err := ioutil.TempFile("", "toml-test-*.zip") - if err != nil { - panic(err) - } - defer tmpfile.Close() - - copiedLen, err := io.Copy(tmpfile, resp.Body) - if err != nil { - panic(err) - } - if resp.ContentLength > 0 && copiedLen != resp.ContentLength { - panic(fmt.Errorf("copied %d bytes, request body had %d", copiedLen, resp.ContentLength)) - } - return tmpfile.Name() -} - -func kebabToCamel(kebab string) string { - camel := "" - nextUpper := true - for _, c := range kebab { - if nextUpper { - camel += strings.ToUpper(string(c)) - nextUpper = false - } else if c == '-' { - nextUpper = true - } else { - camel += string(c) - } - } - return camel -} - -func readFileFromZip(f *zip.File) string { - reader, err := f.Open() - if err != nil { - panic(err) - } - defer reader.Close() - bytes, err := ioutil.ReadAll(reader) - if err != nil { - panic(err) - } - return string(bytes) -} - -func templateGoStr(input string) string { - if len(input) > 0 && input[len(input)-1] == '\n' { - input = input[0 : len(input)-1] - } - if strings.Contains(input, "`") { - lines := strings.Split(input, "\n") - for idx, line := range lines { - lines[idx] = strconv.Quote(line + "\n") - } - return strings.Join(lines, " + \n") - } - return "`" + input + "`" -} - -var ( - ref = flag.String("r", "master", "git reference") -) - -func usage() { - _, _ = fmt.Fprintf(os.Stderr, "usage: tomltestgen [flags]\n") - flag.PrintDefaults() -} - -func main() { - flag.Usage = usage - flag.Parse() - - url := "https://codeload.github.com/BurntSushi/toml-test/zip/" + *ref - resultFile := downloadTmpFile(url) - defer os.Remove(resultFile) - log.Println("file written to", resultFile) - - zipReader, err := zip.OpenReader(resultFile) - if err != nil { - panic(err) - } - defer zipReader.Close() - - collection := testsCollection{ - Ref: *ref, - Timestamp: time.Now().Format(time.RFC3339), - } - - zipFilesMap := map[string]*zip.File{} - - for _, f := range zipReader.File { - zipFilesMap[f.Name] = f - } - - testFileRegexp := regexp.MustCompile(`([^/]+/tests/(valid|invalid)/(.+))\.(toml)`) - for _, f := range zipReader.File { - groups := testFileRegexp.FindStringSubmatch(f.Name) - if len(groups) > 0 { - name := kebabToCamel(groups[3]) - testType := groups[2] - - log.Printf("> [%s] %s\n", testType, name) - - tomlContent := readFileFromZip(f) - - switch testType { - case "invalid": - collection.Invalid = append(collection.Invalid, invalid{ - Name: name, - Input: tomlContent, - }) - collection.Count++ - case "valid": - baseFilePath := groups[1] - jsonFilePath := baseFilePath + ".json" - jsonContent := readFileFromZip(zipFilesMap[jsonFilePath]) - - collection.Valid = append(collection.Valid, valid{ - Name: name, - Input: tomlContent, - JsonRef: jsonContent, - }) - collection.Count++ - default: - panic(fmt.Sprintf("unknown test type: %s", testType)) - } - } - } - - log.Printf("Collected %d tests from toml-test\n", collection.Count) - - funcMap := template.FuncMap{ - "gostr": templateGoStr, - } - t := template.Must(template.New("src").Funcs(funcMap).Parse(srcTemplate)) - buf := new(bytes.Buffer) - err = t.Execute(buf, collection) - if err != nil { - panic(err) - } - outputBytes, err := format.Source(buf.Bytes()) - if err != nil { - panic(err) - } - fmt.Println(string(outputBytes)) -} diff --git a/src/vendor/github.com/pelletier/go-toml/doc_test.go b/src/vendor/github.com/pelletier/go-toml/doc_test.go deleted file mode 100644 index d64414ce6299fc44b2e08982fd9807b789e202a3..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/doc_test.go +++ /dev/null @@ -1,106 +0,0 @@ -// code examples for godoc - -package toml_test - -import ( - "fmt" - "log" - - toml "github.com/pelletier/go-toml" -) - -func Example_tree() { - config, err := toml.LoadFile("config.toml") - - if err != nil { - fmt.Println("Error ", err.Error()) - } else { - // retrieve data directly - directUser := config.Get("postgres.user").(string) - directPassword := config.Get("postgres.password").(string) - fmt.Println("User is", directUser, " and password is", directPassword) - - // or using an intermediate object - configTree := config.Get("postgres").(*toml.Tree) - user := configTree.Get("user").(string) - password := configTree.Get("password").(string) - fmt.Println("User is", user, " and password is", password) - - // show where elements are in the file - fmt.Printf("User position: %v\n", configTree.GetPosition("user")) - fmt.Printf("Password position: %v\n", configTree.GetPosition("password")) - } -} - -func Example_unmarshal() { - type Employer struct { - Name string - Phone string - } - type Person struct { - Name string - Age int64 - Employer Employer - } - - document := []byte(` - name = "John" - age = 30 - [employer] - name = "Company Inc." - phone = "+1 234 567 89012" - `) - - person := Person{} - toml.Unmarshal(document, &person) - fmt.Println(person.Name, "is", person.Age, "and works at", person.Employer.Name) - // Output: - // John is 30 and works at Company Inc. -} - -func ExampleMarshal() { - type Postgres struct { - User string `toml:"user"` - Password string `toml:"password"` - Database string `toml:"db" commented:"true" comment:"not used anymore"` - } - type Config struct { - Postgres Postgres `toml:"postgres" comment:"Postgres configuration"` - } - - config := Config{Postgres{User: "pelletier", Password: "mypassword", Database: "old_database"}} - b, err := toml.Marshal(config) - if err != nil { - log.Fatal(err) - } - fmt.Println(string(b)) - // Output: - // # Postgres configuration - // [postgres] - // - // # not used anymore - // # db = "old_database" - // password = "mypassword" - // user = "pelletier" -} - -func ExampleUnmarshal() { - type Postgres struct { - User string - Password string - } - type Config struct { - Postgres Postgres - } - - doc := []byte(` - [postgres] - user = "pelletier" - password = "mypassword"`) - - config := Config{} - toml.Unmarshal(doc, &config) - fmt.Println("user=", config.Postgres.User) - // Output: - // user= pelletier -} diff --git a/src/vendor/github.com/pelletier/go-toml/fuzz.sh b/src/vendor/github.com/pelletier/go-toml/fuzz.sh old mode 100755 new mode 100644 diff --git a/src/vendor/github.com/pelletier/go-toml/keysparsing_test.go b/src/vendor/github.com/pelletier/go-toml/keysparsing_test.go deleted file mode 100644 index 3858259fdd4fa55cd733ee06d323d7d5d32579e0..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/keysparsing_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package toml - -import ( - "fmt" - "testing" -) - -func testResult(t *testing.T, key string, expected []string) { - parsed, err := parseKey(key) - t.Logf("key=%s expected=%s parsed=%s", key, expected, parsed) - if err != nil { - t.Fatal("Unexpected error:", err) - } - if len(expected) != len(parsed) { - t.Fatal("Expected length", len(expected), "but", len(parsed), "parsed") - } - for index, expectedKey := range expected { - if expectedKey != parsed[index] { - t.Fatal("Expected", expectedKey, "at index", index, "but found", parsed[index]) - } - } -} - -func testError(t *testing.T, key string, expectedError string) { - res, err := parseKey(key) - if err == nil { - t.Fatalf("Expected error, but successfully parsed key %s", res) - } - if fmt.Sprintf("%s", err) != expectedError { - t.Fatalf("Expected error \"%s\", but got \"%s\".", expectedError, err) - } -} - -func TestBareKeyBasic(t *testing.T) { - testResult(t, "test", []string{"test"}) -} - -func TestBareKeyDotted(t *testing.T) { - testResult(t, "this.is.a.key", []string{"this", "is", "a", "key"}) -} - -func TestDottedKeyBasic(t *testing.T) { - testResult(t, "\"a.dotted.key\"", []string{"a.dotted.key"}) -} - -func TestBaseKeyPound(t *testing.T) { - testError(t, "hello#world", "invalid bare key character: #") -} - -func TestUnclosedSingleQuotedKey(t *testing.T) { - testError(t, "'", "unclosed single-quoted key") -} - -func TestUnclosedDoubleQuotedKey(t *testing.T) { - testError(t, "\"", "unclosed double-quoted key") -} - -func TestInvalidStartKeyCharacter(t *testing.T) { - testError(t, "/", "invalid key character: /") -} - -func TestInvalidSpaceInKey(t *testing.T) { - testError(t, "invalid key", "invalid key character after whitespace: k") -} - -func TestQuotedKeys(t *testing.T) { - testResult(t, `hello."foo".bar`, []string{"hello", "foo", "bar"}) - testResult(t, `"hello!"`, []string{"hello!"}) - testResult(t, `foo."ba.r".baz`, []string{"foo", "ba.r", "baz"}) - - // escape sequences must not be converted - testResult(t, `"hello\tworld"`, []string{`hello\tworld`}) -} - -func TestEmptyKey(t *testing.T) { - testError(t, ``, "empty key") - testError(t, ` `, "empty key") - testResult(t, `""`, []string{""}) -} diff --git a/src/vendor/github.com/pelletier/go-toml/lexer_test.go b/src/vendor/github.com/pelletier/go-toml/lexer_test.go deleted file mode 100644 index 313b83c5d11a523ea9a34f4a2efa9d16ac1f4901..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/lexer_test.go +++ /dev/null @@ -1,750 +0,0 @@ -package toml - -import ( - "reflect" - "testing" -) - -func testFlow(t *testing.T, input string, expectedFlow []token) { - tokens := lexToml([]byte(input)) - if !reflect.DeepEqual(tokens, expectedFlow) { - t.Fatal("Different flows. Expected\n", expectedFlow, "\nGot:\n", tokens) - } -} - -func TestValidKeyGroup(t *testing.T) { - testFlow(t, "[hello world]", []token{ - {Position{1, 1}, tokenLeftBracket, "["}, - {Position{1, 2}, tokenKeyGroup, "hello world"}, - {Position{1, 13}, tokenRightBracket, "]"}, - {Position{1, 14}, tokenEOF, ""}, - }) -} - -func TestNestedQuotedUnicodeKeyGroup(t *testing.T) { - testFlow(t, `[ j . "ʞ" . l ]`, []token{ - {Position{1, 1}, tokenLeftBracket, "["}, - {Position{1, 2}, tokenKeyGroup, ` j . "ʞ" . l `}, - {Position{1, 15}, tokenRightBracket, "]"}, - {Position{1, 16}, tokenEOF, ""}, - }) -} - -func TestUnclosedKeyGroup(t *testing.T) { - testFlow(t, "[hello world", []token{ - {Position{1, 1}, tokenLeftBracket, "["}, - {Position{1, 2}, tokenError, "unclosed table key"}, - }) -} - -func TestComment(t *testing.T) { - testFlow(t, "# blahblah", []token{ - {Position{1, 11}, tokenEOF, ""}, - }) -} - -func TestKeyGroupComment(t *testing.T) { - testFlow(t, "[hello world] # blahblah", []token{ - {Position{1, 1}, tokenLeftBracket, "["}, - {Position{1, 2}, tokenKeyGroup, "hello world"}, - {Position{1, 13}, tokenRightBracket, "]"}, - {Position{1, 25}, tokenEOF, ""}, - }) -} - -func TestMultipleKeyGroupsComment(t *testing.T) { - testFlow(t, "[hello world] # blahblah\n[test]", []token{ - {Position{1, 1}, tokenLeftBracket, "["}, - {Position{1, 2}, tokenKeyGroup, "hello world"}, - {Position{1, 13}, tokenRightBracket, "]"}, - {Position{2, 1}, tokenLeftBracket, "["}, - {Position{2, 2}, tokenKeyGroup, "test"}, - {Position{2, 6}, tokenRightBracket, "]"}, - {Position{2, 7}, tokenEOF, ""}, - }) -} - -func TestSimpleWindowsCRLF(t *testing.T) { - testFlow(t, "a=4\r\nb=2", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 2}, tokenEqual, "="}, - {Position{1, 3}, tokenInteger, "4"}, - {Position{2, 1}, tokenKey, "b"}, - {Position{2, 2}, tokenEqual, "="}, - {Position{2, 3}, tokenInteger, "2"}, - {Position{2, 4}, tokenEOF, ""}, - }) -} - -func TestBasicKey(t *testing.T) { - testFlow(t, "hello", []token{ - {Position{1, 1}, tokenKey, "hello"}, - {Position{1, 6}, tokenEOF, ""}, - }) -} - -func TestBasicKeyWithUnderscore(t *testing.T) { - testFlow(t, "hello_hello", []token{ - {Position{1, 1}, tokenKey, "hello_hello"}, - {Position{1, 12}, tokenEOF, ""}, - }) -} - -func TestBasicKeyWithDash(t *testing.T) { - testFlow(t, "hello-world", []token{ - {Position{1, 1}, tokenKey, "hello-world"}, - {Position{1, 12}, tokenEOF, ""}, - }) -} - -func TestBasicKeyWithUppercaseMix(t *testing.T) { - testFlow(t, "helloHELLOHello", []token{ - {Position{1, 1}, tokenKey, "helloHELLOHello"}, - {Position{1, 16}, tokenEOF, ""}, - }) -} - -func TestBasicKeyWithInternationalCharacters(t *testing.T) { - testFlow(t, "héllÖ", []token{ - {Position{1, 1}, tokenKey, "héllÖ"}, - {Position{1, 6}, tokenEOF, ""}, - }) -} - -func TestBasicKeyAndEqual(t *testing.T) { - testFlow(t, "hello =", []token{ - {Position{1, 1}, tokenKey, "hello"}, - {Position{1, 7}, tokenEqual, "="}, - {Position{1, 8}, tokenEOF, ""}, - }) -} - -func TestKeyWithSharpAndEqual(t *testing.T) { - testFlow(t, "key#name = 5", []token{ - {Position{1, 1}, tokenError, "keys cannot contain # character"}, - }) -} - -func TestKeyWithSymbolsAndEqual(t *testing.T) { - testFlow(t, "~!@$^&*()_+-`1234567890[]\\|/?><.,;:' = 5", []token{ - {Position{1, 1}, tokenError, "keys cannot contain ~ character"}, - }) -} - -func TestKeyEqualStringEscape(t *testing.T) { - testFlow(t, `foo = "hello\""`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "hello\""}, - {Position{1, 16}, tokenEOF, ""}, - }) -} - -func TestKeyEqualStringUnfinished(t *testing.T) { - testFlow(t, `foo = "bar`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenError, "unclosed string"}, - }) -} - -func TestKeyEqualString(t *testing.T) { - testFlow(t, `foo = "bar"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "bar"}, - {Position{1, 12}, tokenEOF, ""}, - }) -} - -func TestKeyEqualTrue(t *testing.T) { - testFlow(t, "foo = true", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenTrue, "true"}, - {Position{1, 11}, tokenEOF, ""}, - }) -} - -func TestKeyEqualFalse(t *testing.T) { - testFlow(t, "foo = false", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenFalse, "false"}, - {Position{1, 12}, tokenEOF, ""}, - }) -} - -func TestArrayNestedString(t *testing.T) { - testFlow(t, `a = [ ["hello", "world"] ]`, []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenLeftBracket, "["}, - {Position{1, 7}, tokenLeftBracket, "["}, - {Position{1, 9}, tokenString, "hello"}, - {Position{1, 15}, tokenComma, ","}, - {Position{1, 18}, tokenString, "world"}, - {Position{1, 24}, tokenRightBracket, "]"}, - {Position{1, 26}, tokenRightBracket, "]"}, - {Position{1, 27}, tokenEOF, ""}, - }) -} - -func TestArrayNestedInts(t *testing.T) { - testFlow(t, "a = [ [42, 21], [10] ]", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenLeftBracket, "["}, - {Position{1, 7}, tokenLeftBracket, "["}, - {Position{1, 8}, tokenInteger, "42"}, - {Position{1, 10}, tokenComma, ","}, - {Position{1, 12}, tokenInteger, "21"}, - {Position{1, 14}, tokenRightBracket, "]"}, - {Position{1, 15}, tokenComma, ","}, - {Position{1, 17}, tokenLeftBracket, "["}, - {Position{1, 18}, tokenInteger, "10"}, - {Position{1, 20}, tokenRightBracket, "]"}, - {Position{1, 22}, tokenRightBracket, "]"}, - {Position{1, 23}, tokenEOF, ""}, - }) -} - -func TestArrayInts(t *testing.T) { - testFlow(t, "a = [ 42, 21, 10, ]", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenLeftBracket, "["}, - {Position{1, 7}, tokenInteger, "42"}, - {Position{1, 9}, tokenComma, ","}, - {Position{1, 11}, tokenInteger, "21"}, - {Position{1, 13}, tokenComma, ","}, - {Position{1, 15}, tokenInteger, "10"}, - {Position{1, 17}, tokenComma, ","}, - {Position{1, 19}, tokenRightBracket, "]"}, - {Position{1, 20}, tokenEOF, ""}, - }) -} - -func TestMultilineArrayComments(t *testing.T) { - testFlow(t, "a = [1, # wow\n2, # such items\n3, # so array\n]", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenLeftBracket, "["}, - {Position{1, 6}, tokenInteger, "1"}, - {Position{1, 7}, tokenComma, ","}, - {Position{2, 1}, tokenInteger, "2"}, - {Position{2, 2}, tokenComma, ","}, - {Position{3, 1}, tokenInteger, "3"}, - {Position{3, 2}, tokenComma, ","}, - {Position{4, 1}, tokenRightBracket, "]"}, - {Position{4, 2}, tokenEOF, ""}, - }) -} - -func TestNestedArraysComment(t *testing.T) { - toml := ` -someArray = [ -# does not work -["entry1"] -]` - testFlow(t, toml, []token{ - {Position{2, 1}, tokenKey, "someArray"}, - {Position{2, 11}, tokenEqual, "="}, - {Position{2, 13}, tokenLeftBracket, "["}, - {Position{4, 1}, tokenLeftBracket, "["}, - {Position{4, 3}, tokenString, "entry1"}, - {Position{4, 10}, tokenRightBracket, "]"}, - {Position{5, 1}, tokenRightBracket, "]"}, - {Position{5, 2}, tokenEOF, ""}, - }) -} - -func TestKeyEqualArrayBools(t *testing.T) { - testFlow(t, "foo = [true, false, true]", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenLeftBracket, "["}, - {Position{1, 8}, tokenTrue, "true"}, - {Position{1, 12}, tokenComma, ","}, - {Position{1, 14}, tokenFalse, "false"}, - {Position{1, 19}, tokenComma, ","}, - {Position{1, 21}, tokenTrue, "true"}, - {Position{1, 25}, tokenRightBracket, "]"}, - {Position{1, 26}, tokenEOF, ""}, - }) -} - -func TestKeyEqualArrayBoolsWithComments(t *testing.T) { - testFlow(t, "foo = [true, false, true] # YEAH", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenLeftBracket, "["}, - {Position{1, 8}, tokenTrue, "true"}, - {Position{1, 12}, tokenComma, ","}, - {Position{1, 14}, tokenFalse, "false"}, - {Position{1, 19}, tokenComma, ","}, - {Position{1, 21}, tokenTrue, "true"}, - {Position{1, 25}, tokenRightBracket, "]"}, - {Position{1, 33}, tokenEOF, ""}, - }) -} - -func TestDateRegexp(t *testing.T) { - if dateRegexp.FindString("1979-05-27T07:32:00Z") == "" { - t.Error("basic lexing") - } - if dateRegexp.FindString("1979-05-27T00:32:00-07:00") == "" { - t.Error("offset lexing") - } - if dateRegexp.FindString("1979-05-27T00:32:00.999999-07:00") == "" { - t.Error("nano precision lexing") - } -} - -func TestKeyEqualDate(t *testing.T) { - testFlow(t, "foo = 1979-05-27T07:32:00Z", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenDate, "1979-05-27T07:32:00Z"}, - {Position{1, 27}, tokenEOF, ""}, - }) - testFlow(t, "foo = 1979-05-27T00:32:00-07:00", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenDate, "1979-05-27T00:32:00-07:00"}, - {Position{1, 32}, tokenEOF, ""}, - }) - testFlow(t, "foo = 1979-05-27T00:32:00.999999-07:00", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenDate, "1979-05-27T00:32:00.999999-07:00"}, - {Position{1, 39}, tokenEOF, ""}, - }) -} - -func TestFloatEndingWithDot(t *testing.T) { - testFlow(t, "foo = 42.", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenError, "float cannot end with a dot"}, - }) -} - -func TestFloatWithTwoDots(t *testing.T) { - testFlow(t, "foo = 4.2.", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenError, "cannot have two dots in one float"}, - }) -} - -func TestFloatWithExponent1(t *testing.T) { - testFlow(t, "a = 5e+22", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenFloat, "5e+22"}, - {Position{1, 10}, tokenEOF, ""}, - }) -} - -func TestFloatWithExponent2(t *testing.T) { - testFlow(t, "a = 5E+22", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenFloat, "5E+22"}, - {Position{1, 10}, tokenEOF, ""}, - }) -} - -func TestFloatWithExponent3(t *testing.T) { - testFlow(t, "a = -5e+22", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenFloat, "-5e+22"}, - {Position{1, 11}, tokenEOF, ""}, - }) -} - -func TestFloatWithExponent4(t *testing.T) { - testFlow(t, "a = -5e-22", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenFloat, "-5e-22"}, - {Position{1, 11}, tokenEOF, ""}, - }) -} - -func TestFloatWithExponent5(t *testing.T) { - testFlow(t, "a = 6.626e-34", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenFloat, "6.626e-34"}, - {Position{1, 14}, tokenEOF, ""}, - }) -} - -func TestInvalidEsquapeSequence(t *testing.T) { - testFlow(t, `foo = "\x"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenError, "invalid escape sequence: \\x"}, - }) -} - -func TestNestedArrays(t *testing.T) { - testFlow(t, "foo = [[[]]]", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenLeftBracket, "["}, - {Position{1, 8}, tokenLeftBracket, "["}, - {Position{1, 9}, tokenLeftBracket, "["}, - {Position{1, 10}, tokenRightBracket, "]"}, - {Position{1, 11}, tokenRightBracket, "]"}, - {Position{1, 12}, tokenRightBracket, "]"}, - {Position{1, 13}, tokenEOF, ""}, - }) -} - -func TestKeyEqualNumber(t *testing.T) { - testFlow(t, "foo = 42", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenInteger, "42"}, - {Position{1, 9}, tokenEOF, ""}, - }) - - testFlow(t, "foo = +42", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenInteger, "+42"}, - {Position{1, 10}, tokenEOF, ""}, - }) - - testFlow(t, "foo = -42", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenInteger, "-42"}, - {Position{1, 10}, tokenEOF, ""}, - }) - - testFlow(t, "foo = 4.2", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenFloat, "4.2"}, - {Position{1, 10}, tokenEOF, ""}, - }) - - testFlow(t, "foo = +4.2", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenFloat, "+4.2"}, - {Position{1, 11}, tokenEOF, ""}, - }) - - testFlow(t, "foo = -4.2", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenFloat, "-4.2"}, - {Position{1, 11}, tokenEOF, ""}, - }) - - testFlow(t, "foo = 1_000", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenInteger, "1_000"}, - {Position{1, 12}, tokenEOF, ""}, - }) - - testFlow(t, "foo = 5_349_221", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenInteger, "5_349_221"}, - {Position{1, 16}, tokenEOF, ""}, - }) - - testFlow(t, "foo = 1_2_3_4_5", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenInteger, "1_2_3_4_5"}, - {Position{1, 16}, tokenEOF, ""}, - }) - - testFlow(t, "flt8 = 9_224_617.445_991_228_313", []token{ - {Position{1, 1}, tokenKey, "flt8"}, - {Position{1, 6}, tokenEqual, "="}, - {Position{1, 8}, tokenFloat, "9_224_617.445_991_228_313"}, - {Position{1, 33}, tokenEOF, ""}, - }) - - testFlow(t, "foo = +", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenError, "no digit in that number"}, - }) -} - -func TestMultiline(t *testing.T) { - testFlow(t, "foo = 42\nbar=21", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenInteger, "42"}, - {Position{2, 1}, tokenKey, "bar"}, - {Position{2, 4}, tokenEqual, "="}, - {Position{2, 5}, tokenInteger, "21"}, - {Position{2, 7}, tokenEOF, ""}, - }) -} - -func TestKeyEqualStringUnicodeEscape(t *testing.T) { - testFlow(t, `foo = "hello \u2665"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "hello ♥"}, - {Position{1, 21}, tokenEOF, ""}, - }) - testFlow(t, `foo = "hello \U000003B4"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "hello δ"}, - {Position{1, 25}, tokenEOF, ""}, - }) - testFlow(t, `foo = "\uabcd"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "\uabcd"}, - {Position{1, 15}, tokenEOF, ""}, - }) - testFlow(t, `foo = "\uABCD"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "\uABCD"}, - {Position{1, 15}, tokenEOF, ""}, - }) - testFlow(t, `foo = "\U000bcdef"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "\U000bcdef"}, - {Position{1, 19}, tokenEOF, ""}, - }) - testFlow(t, `foo = "\U000BCDEF"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "\U000BCDEF"}, - {Position{1, 19}, tokenEOF, ""}, - }) - testFlow(t, `foo = "\u2"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenError, "unfinished unicode escape"}, - }) - testFlow(t, `foo = "\U2"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenError, "unfinished unicode escape"}, - }) -} - -func TestKeyEqualStringNoEscape(t *testing.T) { - testFlow(t, "foo = \"hello \u0002\"", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenError, "unescaped control character U+0002"}, - }) - testFlow(t, "foo = \"hello \u001F\"", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenError, "unescaped control character U+001F"}, - }) -} - -func TestLiteralString(t *testing.T) { - testFlow(t, `foo = 'C:\Users\nodejs\templates'`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, `C:\Users\nodejs\templates`}, - {Position{1, 34}, tokenEOF, ""}, - }) - testFlow(t, `foo = '\\ServerX\admin$\system32\'`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, `\\ServerX\admin$\system32\`}, - {Position{1, 35}, tokenEOF, ""}, - }) - testFlow(t, `foo = 'Tom "Dubs" Preston-Werner'`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, `Tom "Dubs" Preston-Werner`}, - {Position{1, 34}, tokenEOF, ""}, - }) - testFlow(t, `foo = '<\i\c*\s*>'`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, `<\i\c*\s*>`}, - {Position{1, 19}, tokenEOF, ""}, - }) - testFlow(t, `foo = 'C:\Users\nodejs\unfinis`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenError, "unclosed string"}, - }) -} - -func TestMultilineLiteralString(t *testing.T) { - testFlow(t, `foo = '''hello 'literal' world'''`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 10}, tokenString, `hello 'literal' world`}, - {Position{1, 34}, tokenEOF, ""}, - }) - - testFlow(t, "foo = '''\nhello\n'literal'\nworld'''", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{2, 1}, tokenString, "hello\n'literal'\nworld"}, - {Position{4, 9}, tokenEOF, ""}, - }) - testFlow(t, "foo = '''\r\nhello\r\n'literal'\r\nworld'''", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{2, 1}, tokenString, "hello\r\n'literal'\r\nworld"}, - {Position{4, 9}, tokenEOF, ""}, - }) -} - -func TestMultilineString(t *testing.T) { - testFlow(t, `foo = """hello "literal" world"""`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 10}, tokenString, `hello "literal" world`}, - {Position{1, 34}, tokenEOF, ""}, - }) - - testFlow(t, "foo = \"\"\"\r\nhello\\\r\n\"literal\"\\\nworld\"\"\"", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{2, 1}, tokenString, "hello\"literal\"world"}, - {Position{4, 9}, tokenEOF, ""}, - }) - - testFlow(t, "foo = \"\"\"\\\n \\\n \\\n hello\\\nmultiline\\\nworld\"\"\"", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 10}, tokenString, "hellomultilineworld"}, - {Position{6, 9}, tokenEOF, ""}, - }) - - testFlow(t, "key2 = \"\"\"\nThe quick brown \\\n\n\n fox jumps over \\\n the lazy dog.\"\"\"", []token{ - {Position{1, 1}, tokenKey, "key2"}, - {Position{1, 6}, tokenEqual, "="}, - {Position{2, 1}, tokenString, "The quick brown fox jumps over the lazy dog."}, - {Position{6, 21}, tokenEOF, ""}, - }) - - testFlow(t, "key2 = \"\"\"\\\n The quick brown \\\n fox jumps over \\\n the lazy dog.\\\n \"\"\"", []token{ - {Position{1, 1}, tokenKey, "key2"}, - {Position{1, 6}, tokenEqual, "="}, - {Position{1, 11}, tokenString, "The quick brown fox jumps over the lazy dog."}, - {Position{5, 11}, tokenEOF, ""}, - }) - - testFlow(t, `key2 = "Roses are red\nViolets are blue"`, []token{ - {Position{1, 1}, tokenKey, "key2"}, - {Position{1, 6}, tokenEqual, "="}, - {Position{1, 9}, tokenString, "Roses are red\nViolets are blue"}, - {Position{1, 41}, tokenEOF, ""}, - }) - - testFlow(t, "key2 = \"\"\"\nRoses are red\nViolets are blue\"\"\"", []token{ - {Position{1, 1}, tokenKey, "key2"}, - {Position{1, 6}, tokenEqual, "="}, - {Position{2, 1}, tokenString, "Roses are red\nViolets are blue"}, - {Position{3, 20}, tokenEOF, ""}, - }) -} - -func TestUnicodeString(t *testing.T) { - testFlow(t, `foo = "hello ♥ world"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "hello ♥ world"}, - {Position{1, 22}, tokenEOF, ""}, - }) -} -func TestEscapeInString(t *testing.T) { - testFlow(t, `foo = "\b\f\/"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "\b\f/"}, - {Position{1, 15}, tokenEOF, ""}, - }) -} - -func TestKeyGroupArray(t *testing.T) { - testFlow(t, "[[foo]]", []token{ - {Position{1, 1}, tokenDoubleLeftBracket, "[["}, - {Position{1, 3}, tokenKeyGroupArray, "foo"}, - {Position{1, 6}, tokenDoubleRightBracket, "]]"}, - {Position{1, 8}, tokenEOF, ""}, - }) -} - -func TestQuotedKey(t *testing.T) { - testFlow(t, "\"a b\" = 42", []token{ - {Position{1, 1}, tokenKey, "\"a b\""}, - {Position{1, 7}, tokenEqual, "="}, - {Position{1, 9}, tokenInteger, "42"}, - {Position{1, 11}, tokenEOF, ""}, - }) -} - -func TestKeyNewline(t *testing.T) { - testFlow(t, "a\n= 4", []token{ - {Position{1, 1}, tokenError, "keys cannot contain new lines"}, - }) -} - -func TestInvalidFloat(t *testing.T) { - testFlow(t, "a=7e1_", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 2}, tokenEqual, "="}, - {Position{1, 3}, tokenFloat, "7e1_"}, - {Position{1, 7}, tokenEOF, ""}, - }) -} - -func TestLexUnknownRvalue(t *testing.T) { - testFlow(t, `a = !b`, []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenError, "no value can start with !"}, - }) - - testFlow(t, `a = \b`, []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenError, `no value can start with \`}, - }) -} - -func BenchmarkLexer(b *testing.B) { - sample := `title = "Hugo: A Fast and Flexible Website Generator" -baseurl = "http://gohugo.io/" -MetaDataFormat = "yaml" -pluralizeListTitles = false - -[params] - description = "Documentation of Hugo, a fast and flexible static site generator built with love by spf13, bep and friends in Go" - author = "Steve Francia (spf13) and friends" - release = "0.22-DEV" - -[[menu.main]] - name = "Download Hugo" - pre = "" - url = "https://github.com/spf13/hugo/releases" - weight = -200 -` - b.ResetTimer() - for i := 0; i < b.N; i++ { - lexToml([]byte(sample)) - } -} diff --git a/src/vendor/github.com/pelletier/go-toml/marshal_test.go b/src/vendor/github.com/pelletier/go-toml/marshal_test.go deleted file mode 100644 index cc23dcafc313f0ce691fa87e5b6199588867e90a..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/marshal_test.go +++ /dev/null @@ -1,1419 +0,0 @@ -package toml - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "reflect" - "strings" - "testing" - "time" -) - -type basicMarshalTestStruct struct { - String string `toml:"Zstring"` - StringList []string `toml:"Ystrlist"` - Sub basicMarshalTestSubStruct `toml:"Xsubdoc"` - SubList []basicMarshalTestSubStruct `toml:"Wsublist"` -} - -type basicMarshalTestSubStruct struct { - String2 string -} - -var basicTestData = basicMarshalTestStruct{ - String: "Hello", - StringList: []string{"Howdy", "Hey There"}, - Sub: basicMarshalTestSubStruct{"One"}, - SubList: []basicMarshalTestSubStruct{{"Two"}, {"Three"}}, -} - -var basicTestToml = []byte(`Ystrlist = ["Howdy","Hey There"] -Zstring = "Hello" - -[[Wsublist]] - String2 = "Two" - -[[Wsublist]] - String2 = "Three" - -[Xsubdoc] - String2 = "One" -`) - -var basicTestTomlOrdered = []byte(`Zstring = "Hello" -Ystrlist = ["Howdy","Hey There"] - -[Xsubdoc] - String2 = "One" - -[[Wsublist]] - String2 = "Two" - -[[Wsublist]] - String2 = "Three" -`) - -func TestBasicMarshal(t *testing.T) { - result, err := Marshal(basicTestData) - if err != nil { - t.Fatal(err) - } - expected := basicTestToml - if !bytes.Equal(result, expected) { - t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -func TestBasicMarshalOrdered(t *testing.T) { - var result bytes.Buffer - err := NewEncoder(&result).Order(OrderPreserve).Encode(basicTestData) - if err != nil { - t.Fatal(err) - } - expected := basicTestTomlOrdered - if !bytes.Equal(result.Bytes(), expected) { - t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result.Bytes()) - } -} - -func TestBasicMarshalWithPointer(t *testing.T) { - result, err := Marshal(&basicTestData) - if err != nil { - t.Fatal(err) - } - expected := basicTestToml - if !bytes.Equal(result, expected) { - t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -func TestBasicMarshalOrderedWithPointer(t *testing.T) { - var result bytes.Buffer - err := NewEncoder(&result).Order(OrderPreserve).Encode(&basicTestData) - if err != nil { - t.Fatal(err) - } - expected := basicTestTomlOrdered - if !bytes.Equal(result.Bytes(), expected) { - t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result.Bytes()) - } -} - -func TestBasicUnmarshal(t *testing.T) { - result := basicMarshalTestStruct{} - err := Unmarshal(basicTestToml, &result) - expected := basicTestData - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(result, expected) { - t.Errorf("Bad unmarshal: expected %v, got %v", expected, result) - } -} - -type testDoc struct { - Title string `toml:"title"` - BasicLists testDocBasicLists `toml:"basic_lists"` - SubDocPtrs []*testSubDoc `toml:"subdocptrs"` - BasicMap map[string]string `toml:"basic_map"` - Subdocs testDocSubs `toml:"subdoc"` - Basics testDocBasics `toml:"basic"` - SubDocList []testSubDoc `toml:"subdoclist"` - err int `toml:"shouldntBeHere"` - unexported int `toml:"shouldntBeHere"` - Unexported2 int `toml:"-"` -} - -type testMapDoc struct { - Title string `toml:"title"` - BasicMap map[string]string `toml:"basic_map"` - LongMap map[string]string `toml:"long_map"` -} - -type testDocBasics struct { - Uint uint `toml:"uint"` - Bool bool `toml:"bool"` - Float float32 `toml:"float"` - Int int `toml:"int"` - String *string `toml:"string"` - Date time.Time `toml:"date"` - unexported int `toml:"shouldntBeHere"` -} - -type testDocBasicLists struct { - Floats []*float32 `toml:"floats"` - Bools []bool `toml:"bools"` - Dates []time.Time `toml:"dates"` - Ints []int `toml:"ints"` - UInts []uint `toml:"uints"` - Strings []string `toml:"strings"` -} - -type testDocSubs struct { - Second *testSubDoc `toml:"second"` - First testSubDoc `toml:"first"` -} - -type testSubDoc struct { - Name string `toml:"name"` - unexported int `toml:"shouldntBeHere"` -} - -var biteMe = "Bite me" -var float1 float32 = 12.3 -var float2 float32 = 45.6 -var float3 float32 = 78.9 -var subdoc = testSubDoc{"Second", 0} - -var docData = testDoc{ - Title: "TOML Marshal Testing", - unexported: 0, - Unexported2: 0, - Basics: testDocBasics{ - Bool: true, - Date: time.Date(1979, 5, 27, 7, 32, 0, 0, time.UTC), - Float: 123.4, - Int: 5000, - Uint: 5001, - String: &biteMe, - unexported: 0, - }, - BasicLists: testDocBasicLists{ - Bools: []bool{true, false, true}, - Dates: []time.Time{ - time.Date(1979, 5, 27, 7, 32, 0, 0, time.UTC), - time.Date(1980, 5, 27, 7, 32, 0, 0, time.UTC), - }, - Floats: []*float32{&float1, &float2, &float3}, - Ints: []int{8001, 8001, 8002}, - Strings: []string{"One", "Two", "Three"}, - UInts: []uint{5002, 5003}, - }, - BasicMap: map[string]string{ - "one": "one", - "two": "two", - }, - Subdocs: testDocSubs{ - First: testSubDoc{"First", 0}, - Second: &subdoc, - }, - SubDocList: []testSubDoc{ - {"List.First", 0}, - {"List.Second", 0}, - }, - SubDocPtrs: []*testSubDoc{&subdoc}, -} - -var mapTestDoc = testMapDoc{ - Title: "TOML Marshal Testing", - BasicMap: map[string]string{ - "one": "one", - "two": "two", - }, - LongMap: map[string]string{ - "h1": "8", - "i2": "9", - "b3": "2", - "d4": "4", - "f5": "6", - "e6": "5", - "a7": "1", - "c8": "3", - "j9": "10", - "g10": "7", - }, -} - -func TestDocMarshal(t *testing.T) { - result, err := Marshal(docData) - if err != nil { - t.Fatal(err) - } - expected, _ := ioutil.ReadFile("marshal_test.toml") - if !bytes.Equal(result, expected) { - t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -func TestDocMarshalOrdered(t *testing.T) { - var result bytes.Buffer - err := NewEncoder(&result).Order(OrderPreserve).Encode(docData) - if err != nil { - t.Fatal(err) - } - expected, _ := ioutil.ReadFile("marshal_OrderPreserve_test.toml") - if !bytes.Equal(result.Bytes(), expected) { - t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result.Bytes()) - } -} - -func TestDocMarshalMaps(t *testing.T) { - result, err := Marshal(mapTestDoc) - if err != nil { - t.Fatal(err) - } - expected, _ := ioutil.ReadFile("marshal_OrderPreserve_Map_test.toml") - if !bytes.Equal(result, expected) { - t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -func TestDocMarshalOrderedMaps(t *testing.T) { - var result bytes.Buffer - err := NewEncoder(&result).Order(OrderPreserve).Encode(mapTestDoc) - if err != nil { - t.Fatal(err) - } - expected, _ := ioutil.ReadFile("marshal_OrderPreserve_Map_test.toml") - if !bytes.Equal(result.Bytes(), expected) { - t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result.Bytes()) - } -} - -func TestDocMarshalPointer(t *testing.T) { - result, err := Marshal(&docData) - if err != nil { - t.Fatal(err) - } - expected, _ := ioutil.ReadFile("marshal_test.toml") - if !bytes.Equal(result, expected) { - t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -func TestDocUnmarshal(t *testing.T) { - result := testDoc{} - tomlData, _ := ioutil.ReadFile("marshal_test.toml") - err := Unmarshal(tomlData, &result) - expected := docData - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(result, expected) { - resStr, _ := json.MarshalIndent(result, "", " ") - expStr, _ := json.MarshalIndent(expected, "", " ") - t.Errorf("Bad unmarshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expStr, resStr) - } -} - -func TestDocPartialUnmarshal(t *testing.T) { - result := testDocSubs{} - - tree, _ := LoadFile("marshal_test.toml") - subTree := tree.Get("subdoc").(*Tree) - err := subTree.Unmarshal(&result) - expected := docData.Subdocs - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(result, expected) { - resStr, _ := json.MarshalIndent(result, "", " ") - expStr, _ := json.MarshalIndent(expected, "", " ") - t.Errorf("Bad partial unmartial: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expStr, resStr) - } -} - -type tomlTypeCheckTest struct { - name string - item interface{} - typ int //0=primitive, 1=otherslice, 2=treeslice, 3=tree -} - -func TestTypeChecks(t *testing.T) { - tests := []tomlTypeCheckTest{ - {"integer", 2, 0}, - {"time", time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC), 0}, - {"stringlist", []string{"hello", "hi"}, 1}, - {"timelist", []time.Time{time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)}, 1}, - {"objectlist", []tomlTypeCheckTest{}, 2}, - {"object", tomlTypeCheckTest{}, 3}, - } - - for _, test := range tests { - expected := []bool{false, false, false, false} - expected[test.typ] = true - result := []bool{ - isPrimitive(reflect.TypeOf(test.item)), - isOtherSlice(reflect.TypeOf(test.item)), - isTreeSlice(reflect.TypeOf(test.item)), - isTree(reflect.TypeOf(test.item)), - } - if !reflect.DeepEqual(expected, result) { - t.Errorf("Bad type check on %q: expected %v, got %v", test.name, expected, result) - } - } -} - -type unexportedMarshalTestStruct struct { - String string `toml:"string"` - StringList []string `toml:"strlist"` - Sub basicMarshalTestSubStruct `toml:"subdoc"` - SubList []basicMarshalTestSubStruct `toml:"sublist"` - unexported int `toml:"shouldntBeHere"` - Unexported2 int `toml:"-"` -} - -var unexportedTestData = unexportedMarshalTestStruct{ - String: "Hello", - StringList: []string{"Howdy", "Hey There"}, - Sub: basicMarshalTestSubStruct{"One"}, - SubList: []basicMarshalTestSubStruct{{"Two"}, {"Three"}}, - unexported: 0, - Unexported2: 0, -} - -var unexportedTestToml = []byte(`string = "Hello" -strlist = ["Howdy","Hey There"] -unexported = 1 -shouldntBeHere = 2 - -[subdoc] - String2 = "One" - -[[sublist]] - String2 = "Two" - -[[sublist]] - String2 = "Three" -`) - -func TestUnexportedUnmarshal(t *testing.T) { - result := unexportedMarshalTestStruct{} - err := Unmarshal(unexportedTestToml, &result) - expected := unexportedTestData - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(result, expected) { - t.Errorf("Bad unexported unmarshal: expected %v, got %v", expected, result) - } -} - -type errStruct struct { - Bool bool `toml:"bool"` - Date time.Time `toml:"date"` - Float float64 `toml:"float"` - Int int16 `toml:"int"` - String *string `toml:"string"` -} - -var errTomls = []string{ - "bool = truly\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = 5000\nstring = \"Bite me\"", - "bool = true\ndate = 1979-05-27T07:3200Z\nfloat = 123.4\nint = 5000\nstring = \"Bite me\"", - "bool = true\ndate = 1979-05-27T07:32:00Z\nfloat = 123a4\nint = 5000\nstring = \"Bite me\"", - "bool = true\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = j000\nstring = \"Bite me\"", - "bool = true\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = 5000\nstring = Bite me", - "bool = true\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = 5000\nstring = Bite me", - "bool = 1\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = 5000\nstring = \"Bite me\"", - "bool = true\ndate = 1\nfloat = 123.4\nint = 5000\nstring = \"Bite me\"", - "bool = true\ndate = 1979-05-27T07:32:00Z\n\"sorry\"\nint = 5000\nstring = \"Bite me\"", - "bool = true\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = \"sorry\"\nstring = \"Bite me\"", - "bool = true\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = 5000\nstring = 1", -} - -type mapErr struct { - Vals map[string]float64 -} - -type intErr struct { - Int1 int - Int2 int8 - Int3 int16 - Int4 int32 - Int5 int64 - UInt1 uint - UInt2 uint8 - UInt3 uint16 - UInt4 uint32 - UInt5 uint64 - Flt1 float32 - Flt2 float64 -} - -var intErrTomls = []string{ - "Int1 = []\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = []\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = []\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = []\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = []\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = []\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = []\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = []\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = []\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = []\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = []\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = []", -} - -func TestErrUnmarshal(t *testing.T) { - for ind, toml := range errTomls { - result := errStruct{} - err := Unmarshal([]byte(toml), &result) - if err == nil { - t.Errorf("Expected err from case %d\n", ind) - } - } - result2 := mapErr{} - err := Unmarshal([]byte("[Vals]\nfred=\"1.2\""), &result2) - if err == nil { - t.Errorf("Expected err from map") - } - for ind, toml := range intErrTomls { - result3 := intErr{} - err := Unmarshal([]byte(toml), &result3) - if err == nil { - t.Errorf("Expected int err from case %d\n", ind) - } - } -} - -type emptyMarshalTestStruct struct { - Title string `toml:"title"` - Bool bool `toml:"bool"` - Int int `toml:"int"` - String string `toml:"string"` - StringList []string `toml:"stringlist"` - Ptr *basicMarshalTestStruct `toml:"ptr"` - Map map[string]string `toml:"map"` -} - -var emptyTestData = emptyMarshalTestStruct{ - Title: "Placeholder", - Bool: false, - Int: 0, - String: "", - StringList: []string{}, - Ptr: nil, - Map: map[string]string{}, -} - -var emptyTestToml = []byte(`bool = false -int = 0 -string = "" -stringlist = [] -title = "Placeholder" - -[map] -`) - -type emptyMarshalTestStruct2 struct { - Title string `toml:"title"` - Bool bool `toml:"bool,omitempty"` - Int int `toml:"int, omitempty"` - String string `toml:"string,omitempty "` - StringList []string `toml:"stringlist,omitempty"` - Ptr *basicMarshalTestStruct `toml:"ptr,omitempty"` - Map map[string]string `toml:"map,omitempty"` -} - -var emptyTestData2 = emptyMarshalTestStruct2{ - Title: "Placeholder", - Bool: false, - Int: 0, - String: "", - StringList: []string{}, - Ptr: nil, - Map: map[string]string{}, -} - -var emptyTestToml2 = []byte(`title = "Placeholder" -`) - -func TestEmptyMarshal(t *testing.T) { - result, err := Marshal(emptyTestData) - if err != nil { - t.Fatal(err) - } - expected := emptyTestToml - if !bytes.Equal(result, expected) { - t.Errorf("Bad empty marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -func TestEmptyMarshalOmit(t *testing.T) { - result, err := Marshal(emptyTestData2) - if err != nil { - t.Fatal(err) - } - expected := emptyTestToml2 - if !bytes.Equal(result, expected) { - t.Errorf("Bad empty omit marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -func TestEmptyUnmarshal(t *testing.T) { - result := emptyMarshalTestStruct{} - err := Unmarshal(emptyTestToml, &result) - expected := emptyTestData - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(result, expected) { - t.Errorf("Bad empty unmarshal: expected %v, got %v", expected, result) - } -} - -func TestEmptyUnmarshalOmit(t *testing.T) { - result := emptyMarshalTestStruct2{} - err := Unmarshal(emptyTestToml, &result) - expected := emptyTestData2 - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(result, expected) { - t.Errorf("Bad empty omit unmarshal: expected %v, got %v", expected, result) - } -} - -type pointerMarshalTestStruct struct { - Str *string - List *[]string - ListPtr *[]*string - Map *map[string]string - MapPtr *map[string]*string - EmptyStr *string - EmptyList *[]string - EmptyMap *map[string]string - DblPtr *[]*[]*string -} - -var pointerStr = "Hello" -var pointerList = []string{"Hello back"} -var pointerListPtr = []*string{&pointerStr} -var pointerMap = map[string]string{"response": "Goodbye"} -var pointerMapPtr = map[string]*string{"alternate": &pointerStr} -var pointerTestData = pointerMarshalTestStruct{ - Str: &pointerStr, - List: &pointerList, - ListPtr: &pointerListPtr, - Map: &pointerMap, - MapPtr: &pointerMapPtr, - EmptyStr: nil, - EmptyList: nil, - EmptyMap: nil, -} - -var pointerTestToml = []byte(`List = ["Hello back"] -ListPtr = ["Hello"] -Str = "Hello" - -[Map] - response = "Goodbye" - -[MapPtr] - alternate = "Hello" -`) - -func TestPointerMarshal(t *testing.T) { - result, err := Marshal(pointerTestData) - if err != nil { - t.Fatal(err) - } - expected := pointerTestToml - if !bytes.Equal(result, expected) { - t.Errorf("Bad pointer marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -func TestPointerUnmarshal(t *testing.T) { - result := pointerMarshalTestStruct{} - err := Unmarshal(pointerTestToml, &result) - expected := pointerTestData - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(result, expected) { - t.Errorf("Bad pointer unmarshal: expected %v, got %v", expected, result) - } -} - -func TestUnmarshalTypeMismatch(t *testing.T) { - result := pointerMarshalTestStruct{} - err := Unmarshal([]byte("List = 123"), &result) - if !strings.HasPrefix(err.Error(), "(1, 1): Can't convert 123(int64) to []string(slice)") { - t.Errorf("Type mismatch must be reported: got %v", err.Error()) - } -} - -type nestedMarshalTestStruct struct { - String [][]string - //Struct [][]basicMarshalTestSubStruct - StringPtr *[]*[]*string - // StructPtr *[]*[]*basicMarshalTestSubStruct -} - -var str1 = "Three" -var str2 = "Four" -var strPtr = []*string{&str1, &str2} -var strPtr2 = []*[]*string{&strPtr} - -var nestedTestData = nestedMarshalTestStruct{ - String: [][]string{{"Five", "Six"}, {"One", "Two"}}, - StringPtr: &strPtr2, -} - -var nestedTestToml = []byte(`String = [["Five","Six"],["One","Two"]] -StringPtr = [["Three","Four"]] -`) - -func TestNestedMarshal(t *testing.T) { - result, err := Marshal(nestedTestData) - if err != nil { - t.Fatal(err) - } - expected := nestedTestToml - if !bytes.Equal(result, expected) { - t.Errorf("Bad nested marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -func TestNestedUnmarshal(t *testing.T) { - result := nestedMarshalTestStruct{} - err := Unmarshal(nestedTestToml, &result) - expected := nestedTestData - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(result, expected) { - t.Errorf("Bad nested unmarshal: expected %v, got %v", expected, result) - } -} - -type customMarshalerParent struct { - Self customMarshaler `toml:"me"` - Friends []customMarshaler `toml:"friends"` -} - -type customMarshaler struct { - FirsName string - LastName string -} - -func (c customMarshaler) MarshalTOML() ([]byte, error) { - fullName := fmt.Sprintf("%s %s", c.FirsName, c.LastName) - return []byte(fullName), nil -} - -var customMarshalerData = customMarshaler{FirsName: "Sally", LastName: "Fields"} -var customMarshalerToml = []byte(`Sally Fields`) -var nestedCustomMarshalerData = customMarshalerParent{ - Self: customMarshaler{FirsName: "Maiku", LastName: "Suteda"}, - Friends: []customMarshaler{customMarshalerData}, -} -var nestedCustomMarshalerToml = []byte(`friends = ["Sally Fields"] -me = "Maiku Suteda" -`) - -func TestCustomMarshaler(t *testing.T) { - result, err := Marshal(customMarshalerData) - if err != nil { - t.Fatal(err) - } - expected := customMarshalerToml - if !bytes.Equal(result, expected) { - t.Errorf("Bad custom marshaler: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -func TestNestedCustomMarshaler(t *testing.T) { - result, err := Marshal(nestedCustomMarshalerData) - if err != nil { - t.Fatal(err) - } - expected := nestedCustomMarshalerToml - if !bytes.Equal(result, expected) { - t.Errorf("Bad nested custom marshaler: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -var commentTestToml = []byte(` -# it's a comment on type -[postgres] - # isCommented = "dvalue" - noComment = "cvalue" - - # A comment on AttrB with a - # break line - password = "bvalue" - - # A comment on AttrA - user = "avalue" - - [[postgres.My]] - - # a comment on my on typeC - My = "Foo" - - [[postgres.My]] - - # a comment on my on typeC - My = "Baar" -`) - -func TestMarshalComment(t *testing.T) { - type TypeC struct { - My string `comment:"a comment on my on typeC"` - } - type TypeB struct { - AttrA string `toml:"user" comment:"A comment on AttrA"` - AttrB string `toml:"password" comment:"A comment on AttrB with a\n break line"` - AttrC string `toml:"noComment"` - AttrD string `toml:"isCommented" commented:"true"` - My []TypeC - } - type TypeA struct { - TypeB TypeB `toml:"postgres" comment:"it's a comment on type"` - } - - ta := []TypeC{{My: "Foo"}, {My: "Baar"}} - config := TypeA{TypeB{AttrA: "avalue", AttrB: "bvalue", AttrC: "cvalue", AttrD: "dvalue", My: ta}} - result, err := Marshal(config) - if err != nil { - t.Fatal(err) - } - expected := commentTestToml - if !bytes.Equal(result, expected) { - t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -type mapsTestStruct struct { - Simple map[string]string - Paths map[string]string - Other map[string]float64 - X struct { - Y struct { - Z map[string]bool - } - } -} - -var mapsTestData = mapsTestStruct{ - Simple: map[string]string{ - "one plus one": "two", - "next": "three", - }, - Paths: map[string]string{ - "/this/is/a/path": "/this/is/also/a/path", - "/heloo.txt": "/tmp/lololo.txt", - }, - Other: map[string]float64{ - "testing": 3.9999, - }, - X: struct{ Y struct{ Z map[string]bool } }{ - Y: struct{ Z map[string]bool }{ - Z: map[string]bool{ - "is.Nested": true, - }, - }, - }, -} -var mapsTestToml = []byte(` -[Other] - "testing" = 3.9999 - -[Paths] - "/heloo.txt" = "/tmp/lololo.txt" - "/this/is/a/path" = "/this/is/also/a/path" - -[Simple] - "next" = "three" - "one plus one" = "two" - -[X] - - [X.Y] - - [X.Y.Z] - "is.Nested" = true -`) - -func TestEncodeQuotedMapKeys(t *testing.T) { - var buf bytes.Buffer - if err := NewEncoder(&buf).QuoteMapKeys(true).Encode(mapsTestData); err != nil { - t.Fatal(err) - } - result := buf.Bytes() - expected := mapsTestToml - if !bytes.Equal(result, expected) { - t.Errorf("Bad maps marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -func TestDecodeQuotedMapKeys(t *testing.T) { - result := mapsTestStruct{} - err := NewDecoder(bytes.NewBuffer(mapsTestToml)).Decode(&result) - expected := mapsTestData - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(result, expected) { - t.Errorf("Bad maps unmarshal: expected %v, got %v", expected, result) - } -} - -type structArrayNoTag struct { - A struct { - B []int64 - C []int64 - } -} - -func TestMarshalArray(t *testing.T) { - expected := []byte(` -[A] - B = [1,2,3] - C = [1] -`) - - m := structArrayNoTag{ - A: struct { - B []int64 - C []int64 - }{ - B: []int64{1, 2, 3}, - C: []int64{1}, - }, - } - - b, err := Marshal(m) - - if err != nil { - t.Fatal(err) - } - - if !bytes.Equal(b, expected) { - t.Errorf("Bad arrays marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, b) - } -} - -func TestMarshalArrayOnePerLine(t *testing.T) { - expected := []byte(` -[A] - B = [ - 1, - 2, - 3, - ] - C = [1] -`) - - m := structArrayNoTag{ - A: struct { - B []int64 - C []int64 - }{ - B: []int64{1, 2, 3}, - C: []int64{1}, - }, - } - - var buf bytes.Buffer - encoder := NewEncoder(&buf).ArraysWithOneElementPerLine(true) - err := encoder.Encode(m) - - if err != nil { - t.Fatal(err) - } - - b := buf.Bytes() - - if !bytes.Equal(b, expected) { - t.Errorf("Bad arrays marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, b) - } -} - -var customTagTestToml = []byte(` -[postgres] - password = "bvalue" - user = "avalue" - - [[postgres.My]] - My = "Foo" - - [[postgres.My]] - My = "Baar" -`) - -func TestMarshalCustomTag(t *testing.T) { - type TypeC struct { - My string - } - type TypeB struct { - AttrA string `file:"user"` - AttrB string `file:"password"` - My []TypeC - } - type TypeA struct { - TypeB TypeB `file:"postgres"` - } - - ta := []TypeC{{My: "Foo"}, {My: "Baar"}} - config := TypeA{TypeB{AttrA: "avalue", AttrB: "bvalue", My: ta}} - var buf bytes.Buffer - err := NewEncoder(&buf).SetTagName("file").Encode(config) - if err != nil { - t.Fatal(err) - } - expected := customTagTestToml - result := buf.Bytes() - if !bytes.Equal(result, expected) { - t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -var customCommentTagTestToml = []byte(` -# db connection -[postgres] - - # db pass - password = "bvalue" - - # db user - user = "avalue" -`) - -func TestMarshalCustomComment(t *testing.T) { - type TypeB struct { - AttrA string `toml:"user" descr:"db user"` - AttrB string `toml:"password" descr:"db pass"` - } - type TypeA struct { - TypeB TypeB `toml:"postgres" descr:"db connection"` - } - - config := TypeA{TypeB{AttrA: "avalue", AttrB: "bvalue"}} - var buf bytes.Buffer - err := NewEncoder(&buf).SetTagComment("descr").Encode(config) - if err != nil { - t.Fatal(err) - } - expected := customCommentTagTestToml - result := buf.Bytes() - if !bytes.Equal(result, expected) { - t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -var customCommentedTagTestToml = []byte(` -[postgres] - # password = "bvalue" - # user = "avalue" -`) - -func TestMarshalCustomCommented(t *testing.T) { - type TypeB struct { - AttrA string `toml:"user" disable:"true"` - AttrB string `toml:"password" disable:"true"` - } - type TypeA struct { - TypeB TypeB `toml:"postgres"` - } - - config := TypeA{TypeB{AttrA: "avalue", AttrB: "bvalue"}} - var buf bytes.Buffer - err := NewEncoder(&buf).SetTagCommented("disable").Encode(config) - if err != nil { - t.Fatal(err) - } - expected := customCommentedTagTestToml - result := buf.Bytes() - if !bytes.Equal(result, expected) { - t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -var customMultilineTagTestToml = []byte(`int_slice = [ - 1, - 2, - 3, -] -`) - -func TestMarshalCustomMultiline(t *testing.T) { - type TypeA struct { - AttrA []int `toml:"int_slice" mltln:"true"` - } - - config := TypeA{AttrA: []int{1, 2, 3}} - var buf bytes.Buffer - err := NewEncoder(&buf).ArraysWithOneElementPerLine(true).SetTagMultiline("mltln").Encode(config) - if err != nil { - t.Fatal(err) - } - expected := customMultilineTagTestToml - result := buf.Bytes() - if !bytes.Equal(result, expected) { - t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -var testDocBasicToml = []byte(` -[document] - bool_val = true - date_val = 1979-05-27T07:32:00Z - float_val = 123.4 - int_val = 5000 - string_val = "Bite me" - uint_val = 5001 -`) - -type testDocCustomTag struct { - Doc testDocBasicsCustomTag `file:"document"` -} -type testDocBasicsCustomTag struct { - Bool bool `file:"bool_val"` - Date time.Time `file:"date_val"` - Float float32 `file:"float_val"` - Int int `file:"int_val"` - Uint uint `file:"uint_val"` - String *string `file:"string_val"` - unexported int `file:"shouldntBeHere"` -} - -var testDocCustomTagData = testDocCustomTag{ - Doc: testDocBasicsCustomTag{ - Bool: true, - Date: time.Date(1979, 5, 27, 7, 32, 0, 0, time.UTC), - Float: 123.4, - Int: 5000, - Uint: 5001, - String: &biteMe, - unexported: 0, - }, -} - -func TestUnmarshalCustomTag(t *testing.T) { - buf := bytes.NewBuffer(testDocBasicToml) - - result := testDocCustomTag{} - err := NewDecoder(buf).SetTagName("file").Decode(&result) - if err != nil { - t.Fatal(err) - } - expected := testDocCustomTagData - if !reflect.DeepEqual(result, expected) { - resStr, _ := json.MarshalIndent(result, "", " ") - expStr, _ := json.MarshalIndent(expected, "", " ") - t.Errorf("Bad unmarshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expStr, resStr) - - } -} - -func TestUnmarshalMap(t *testing.T) { - testToml := []byte(` - a = 1 - b = 2 - c = 3 - `) - var result map[string]int - err := Unmarshal(testToml, &result) - if err != nil { - t.Errorf("Received unexpected error: %s", err) - return - } - - expected := map[string]int{ - "a": 1, - "b": 2, - "c": 3, - } - - if !reflect.DeepEqual(result, expected) { - t.Errorf("Bad unmarshal: expected %v, got %v", expected, result) - } -} - -func TestUnmarshalMapWithTypedKey(t *testing.T) { - testToml := []byte(` - a = 1 - b = 2 - c = 3 - `) - - type letter string - var result map[letter]int - err := Unmarshal(testToml, &result) - if err != nil { - t.Errorf("Received unexpected error: %s", err) - return - } - - expected := map[letter]int{ - "a": 1, - "b": 2, - "c": 3, - } - - if !reflect.DeepEqual(result, expected) { - t.Errorf("Bad unmarshal: expected %v, got %v", expected, result) - } -} - -func TestUnmarshalNonPointer(t *testing.T) { - a := 1 - err := Unmarshal([]byte{}, a) - if err == nil { - t.Fatal("unmarshal should err when given a non pointer") - } -} - -func TestUnmarshalInvalidPointerKind(t *testing.T) { - a := 1 - err := Unmarshal([]byte{}, &a) - if err == nil { - t.Fatal("unmarshal should err when given an invalid pointer type") - } -} - -func TestMarshalSlice(t *testing.T) { - m := make([]int, 1) - m[0] = 1 - - var buf bytes.Buffer - err := NewEncoder(&buf).Encode(&m) - if err == nil { - t.Error("expected error, got nil") - return - } - if err.Error() != "Only pointer to struct can be marshaled to TOML" { - t.Fail() - } -} - -func TestMarshalSlicePointer(t *testing.T) { - m := make([]int, 1) - m[0] = 1 - - var buf bytes.Buffer - err := NewEncoder(&buf).Encode(m) - if err == nil { - t.Error("expected error, got nil") - return - } - if err.Error() != "Only a struct or map can be marshaled to TOML" { - t.Fail() - } -} - -type testDuration struct { - Nanosec time.Duration `toml:"nanosec"` - Microsec1 time.Duration `toml:"microsec1"` - Microsec2 *time.Duration `toml:"microsec2"` - Millisec time.Duration `toml:"millisec"` - Sec time.Duration `toml:"sec"` - Min time.Duration `toml:"min"` - Hour time.Duration `toml:"hour"` - Mixed time.Duration `toml:"mixed"` - AString string `toml:"a_string"` -} - -var testDurationToml = []byte(` -nanosec = "1ns" -microsec1 = "1us" -microsec2 = "1µs" -millisec = "1ms" -sec = "1s" -min = "1m" -hour = "1h" -mixed = "1h1m1s1ms1µs1ns" -a_string = "15s" -`) - -func TestUnmarshalDuration(t *testing.T) { - buf := bytes.NewBuffer(testDurationToml) - - result := testDuration{} - err := NewDecoder(buf).Decode(&result) - if err != nil { - t.Fatal(err) - } - ms := time.Duration(1) * time.Microsecond - expected := testDuration{ - Nanosec: 1, - Microsec1: time.Microsecond, - Microsec2: &ms, - Millisec: time.Millisecond, - Sec: time.Second, - Min: time.Minute, - Hour: time.Hour, - Mixed: time.Hour + - time.Minute + - time.Second + - time.Millisecond + - time.Microsecond + - time.Nanosecond, - AString: "15s", - } - if !reflect.DeepEqual(result, expected) { - resStr, _ := json.MarshalIndent(result, "", " ") - expStr, _ := json.MarshalIndent(expected, "", " ") - t.Errorf("Bad unmarshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expStr, resStr) - - } -} - -var testDurationToml2 = []byte(`a_string = "15s" -hour = "1h0m0s" -microsec1 = "1µs" -microsec2 = "1µs" -millisec = "1ms" -min = "1m0s" -mixed = "1h1m1.001001001s" -nanosec = "1ns" -sec = "1s" -`) - -func TestMarshalDuration(t *testing.T) { - ms := time.Duration(1) * time.Microsecond - data := testDuration{ - Nanosec: 1, - Microsec1: time.Microsecond, - Microsec2: &ms, - Millisec: time.Millisecond, - Sec: time.Second, - Min: time.Minute, - Hour: time.Hour, - Mixed: time.Hour + - time.Minute + - time.Second + - time.Millisecond + - time.Microsecond + - time.Nanosecond, - AString: "15s", - } - - var buf bytes.Buffer - err := NewEncoder(&buf).Encode(data) - if err != nil { - t.Fatal(err) - } - expected := testDurationToml2 - result := buf.Bytes() - if !bytes.Equal(result, expected) { - t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -type testBadDuration struct { - Val time.Duration `toml:"val"` -} - -var testBadDurationToml = []byte(`val = "1z"`) - -func TestUnmarshalBadDuration(t *testing.T) { - buf := bytes.NewBuffer(testBadDurationToml) - - result := testBadDuration{} - err := NewDecoder(buf).Decode(&result) - if err == nil { - t.Fatal() - } - if err.Error() != "(1, 1): Can't convert 1z(string) to time.Duration. time: unknown unit z in duration 1z" { - t.Fatalf("unexpected error: %s", err) - } -} - -var testCamelCaseKeyToml = []byte(`fooBar = 10`) - -func TestUnmarshalCamelCaseKey(t *testing.T) { - var x struct { - FooBar int - B int - } - - if err := Unmarshal(testCamelCaseKeyToml, &x); err != nil { - t.Fatal(err) - } - - if x.FooBar != 10 { - t.Fatal("Did not set camelCase'd key") - } -} - -func TestUnmarshalDefault(t *testing.T) { - var doc struct { - StringField string `default:"a"` - BoolField bool `default:"true"` - IntField int `default:"1"` - Int64Field int64 `default:"2"` - Float64Field float64 `default:"3.1"` - } - - err := Unmarshal([]byte(``), &doc) - if err != nil { - t.Fatal(err) - } - if doc.BoolField != true { - t.Errorf("BoolField should be true, not %t", doc.BoolField) - } - if doc.StringField != "a" { - t.Errorf("StringField should be \"a\", not %s", doc.StringField) - } - if doc.IntField != 1 { - t.Errorf("IntField should be 1, not %d", doc.IntField) - } - if doc.Int64Field != 2 { - t.Errorf("Int64Field should be 2, not %d", doc.Int64Field) - } - if doc.Float64Field != 3.1 { - t.Errorf("Float64Field should be 3.1, not %f", doc.Float64Field) - } -} - -func TestUnmarshalDefaultFailureBool(t *testing.T) { - var doc struct { - Field bool `default:"blah"` - } - - err := Unmarshal([]byte(``), &doc) - if err == nil { - t.Fatal("should error") - } -} - -func TestUnmarshalDefaultFailureInt(t *testing.T) { - var doc struct { - Field int `default:"blah"` - } - - err := Unmarshal([]byte(``), &doc) - if err == nil { - t.Fatal("should error") - } -} - -func TestUnmarshalDefaultFailureInt64(t *testing.T) { - var doc struct { - Field int64 `default:"blah"` - } - - err := Unmarshal([]byte(``), &doc) - if err == nil { - t.Fatal("should error") - } -} - -func TestUnmarshalDefaultFailureFloat64(t *testing.T) { - var doc struct { - Field float64 `default:"blah"` - } - - err := Unmarshal([]byte(``), &doc) - if err == nil { - t.Fatal("should error") - } -} - -func TestUnmarshalDefaultFailureUnsupported(t *testing.T) { - var doc struct { - Field struct{} `default:"blah"` - } - - err := Unmarshal([]byte(``), &doc) - if err == nil { - t.Fatal("should error") - } -} diff --git a/src/vendor/github.com/pelletier/go-toml/parser_test.go b/src/vendor/github.com/pelletier/go-toml/parser_test.go deleted file mode 100644 index 78345755bdee0e5bbcd3eaf7159ace6f6997d999..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/parser_test.go +++ /dev/null @@ -1,939 +0,0 @@ -package toml - -import ( - "fmt" - "math" - "reflect" - "testing" - "time" - - "github.com/davecgh/go-spew/spew" -) - -func assertSubTree(t *testing.T, path []string, tree *Tree, err error, ref map[string]interface{}) { - if err != nil { - t.Error("Non-nil error:", err.Error()) - return - } - for k, v := range ref { - nextPath := append(path, k) - t.Log("asserting path", nextPath) - // NOTE: directly access key instead of resolve by path - // NOTE: see TestSpecialKV - switch node := tree.GetPath([]string{k}).(type) { - case []*Tree: - t.Log("\tcomparing key", nextPath, "by array iteration") - for idx, item := range node { - assertSubTree(t, nextPath, item, err, v.([]map[string]interface{})[idx]) - } - case *Tree: - t.Log("\tcomparing key", nextPath, "by subtree assestion") - assertSubTree(t, nextPath, node, err, v.(map[string]interface{})) - default: - t.Log("\tcomparing key", nextPath, "by string representation because it's of type", reflect.TypeOf(node)) - if fmt.Sprintf("%v", node) != fmt.Sprintf("%v", v) { - t.Errorf("was expecting %v at %v but got %v", v, k, node) - } - } - } -} - -func assertTree(t *testing.T, tree *Tree, err error, ref map[string]interface{}) { - t.Log("Asserting tree:\n", spew.Sdump(tree)) - assertSubTree(t, []string{}, tree, err, ref) - t.Log("Finished tree assertion.") -} - -func TestCreateSubTree(t *testing.T) { - tree := newTree() - tree.createSubTree([]string{"a", "b", "c"}, Position{}) - tree.Set("a.b.c", 42) - if tree.Get("a.b.c") != 42 { - t.Fail() - } -} - -func TestSimpleKV(t *testing.T) { - tree, err := Load("a = 42") - assertTree(t, tree, err, map[string]interface{}{ - "a": int64(42), - }) - - tree, _ = Load("a = 42\nb = 21") - assertTree(t, tree, err, map[string]interface{}{ - "a": int64(42), - "b": int64(21), - }) -} - -func TestNumberInKey(t *testing.T) { - tree, err := Load("hello2 = 42") - assertTree(t, tree, err, map[string]interface{}{ - "hello2": int64(42), - }) -} - -func TestIncorrectKeyExtraSquareBracket(t *testing.T) { - _, err := Load(`[a]b] -zyx = 42`) - if err == nil { - t.Error("Error should have been returned.") - } - if err.Error() != "(1, 4): parsing error: keys cannot contain ] character" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestSimpleNumbers(t *testing.T) { - tree, err := Load("a = +42\nb = -21\nc = +4.2\nd = -2.1") - assertTree(t, tree, err, map[string]interface{}{ - "a": int64(42), - "b": int64(-21), - "c": float64(4.2), - "d": float64(-2.1), - }) -} - -func TestSpecialFloats(t *testing.T) { - tree, err := Load(` -normalinf = inf -plusinf = +inf -minusinf = -inf -normalnan = nan -plusnan = +nan -minusnan = -nan -`) - assertTree(t, tree, err, map[string]interface{}{ - "normalinf": math.Inf(1), - "plusinf": math.Inf(1), - "minusinf": math.Inf(-1), - "normalnan": math.NaN(), - "plusnan": math.NaN(), - "minusnan": math.NaN(), - }) -} - -func TestHexIntegers(t *testing.T) { - tree, err := Load(`a = 0xDEADBEEF`) - assertTree(t, tree, err, map[string]interface{}{"a": int64(3735928559)}) - - tree, err = Load(`a = 0xdeadbeef`) - assertTree(t, tree, err, map[string]interface{}{"a": int64(3735928559)}) - - tree, err = Load(`a = 0xdead_beef`) - assertTree(t, tree, err, map[string]interface{}{"a": int64(3735928559)}) - - _, err = Load(`a = 0x_1`) - if err.Error() != "(1, 5): invalid use of _ in hex number" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestOctIntegers(t *testing.T) { - tree, err := Load(`a = 0o01234567`) - assertTree(t, tree, err, map[string]interface{}{"a": int64(342391)}) - - tree, err = Load(`a = 0o755`) - assertTree(t, tree, err, map[string]interface{}{"a": int64(493)}) - - _, err = Load(`a = 0o_1`) - if err.Error() != "(1, 5): invalid use of _ in number" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestBinIntegers(t *testing.T) { - tree, err := Load(`a = 0b11010110`) - assertTree(t, tree, err, map[string]interface{}{"a": int64(214)}) - - _, err = Load(`a = 0b_1`) - if err.Error() != "(1, 5): invalid use of _ in number" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestBadIntegerBase(t *testing.T) { - _, err := Load(`a = 0k1`) - if err.Error() != "(1, 5): unknown number base: k. possible options are x (hex) o (octal) b (binary)" { - t.Error("Error should have been returned.") - } -} - -func TestIntegerNoDigit(t *testing.T) { - _, err := Load(`a = 0b`) - if err.Error() != "(1, 5): number needs at least one digit" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestNumbersWithUnderscores(t *testing.T) { - tree, err := Load("a = 1_000") - assertTree(t, tree, err, map[string]interface{}{ - "a": int64(1000), - }) - - tree, err = Load("a = 5_349_221") - assertTree(t, tree, err, map[string]interface{}{ - "a": int64(5349221), - }) - - tree, err = Load("a = 1_2_3_4_5") - assertTree(t, tree, err, map[string]interface{}{ - "a": int64(12345), - }) - - tree, err = Load("flt8 = 9_224_617.445_991_228_313") - assertTree(t, tree, err, map[string]interface{}{ - "flt8": float64(9224617.445991228313), - }) - - tree, err = Load("flt9 = 1e1_00") - assertTree(t, tree, err, map[string]interface{}{ - "flt9": float64(1e100), - }) -} - -func TestFloatsWithExponents(t *testing.T) { - tree, err := Load("a = 5e+22\nb = 5E+22\nc = -5e+22\nd = -5e-22\ne = 6.626e-34") - assertTree(t, tree, err, map[string]interface{}{ - "a": float64(5e+22), - "b": float64(5E+22), - "c": float64(-5e+22), - "d": float64(-5e-22), - "e": float64(6.626e-34), - }) -} - -func TestSimpleDate(t *testing.T) { - tree, err := Load("a = 1979-05-27T07:32:00Z") - assertTree(t, tree, err, map[string]interface{}{ - "a": time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC), - }) -} - -func TestDateOffset(t *testing.T) { - tree, err := Load("a = 1979-05-27T00:32:00-07:00") - assertTree(t, tree, err, map[string]interface{}{ - "a": time.Date(1979, time.May, 27, 0, 32, 0, 0, time.FixedZone("", -7*60*60)), - }) -} - -func TestDateNano(t *testing.T) { - tree, err := Load("a = 1979-05-27T00:32:00.999999999-07:00") - assertTree(t, tree, err, map[string]interface{}{ - "a": time.Date(1979, time.May, 27, 0, 32, 0, 999999999, time.FixedZone("", -7*60*60)), - }) -} - -func TestSimpleString(t *testing.T) { - tree, err := Load("a = \"hello world\"") - assertTree(t, tree, err, map[string]interface{}{ - "a": "hello world", - }) -} - -func TestSpaceKey(t *testing.T) { - tree, err := Load("\"a b\" = \"hello world\"") - assertTree(t, tree, err, map[string]interface{}{ - "a b": "hello world", - }) -} - -func TestDoubleQuotedKey(t *testing.T) { - tree, err := Load(` - "key" = "a" - "\t" = "b" - "\U0001F914" = "c" - "\u2764" = "d" - `) - assertTree(t, tree, err, map[string]interface{}{ - "key": "a", - "\t": "b", - "\U0001F914": "c", - "\u2764": "d", - }) -} - -func TestSingleQuotedKey(t *testing.T) { - tree, err := Load(` - 'key' = "a" - '\t' = "b" - '\U0001F914' = "c" - '\u2764' = "d" - `) - assertTree(t, tree, err, map[string]interface{}{ - `key`: "a", - `\t`: "b", - `\U0001F914`: "c", - `\u2764`: "d", - }) -} - -func TestStringEscapables(t *testing.T) { - tree, err := Load("a = \"a \\n b\"") - assertTree(t, tree, err, map[string]interface{}{ - "a": "a \n b", - }) - - tree, err = Load("a = \"a \\t b\"") - assertTree(t, tree, err, map[string]interface{}{ - "a": "a \t b", - }) - - tree, err = Load("a = \"a \\r b\"") - assertTree(t, tree, err, map[string]interface{}{ - "a": "a \r b", - }) - - tree, err = Load("a = \"a \\\\ b\"") - assertTree(t, tree, err, map[string]interface{}{ - "a": "a \\ b", - }) -} - -func TestEmptyQuotedString(t *testing.T) { - tree, err := Load(`[""] -"" = 1`) - assertTree(t, tree, err, map[string]interface{}{ - "": map[string]interface{}{ - "": int64(1), - }, - }) -} - -func TestBools(t *testing.T) { - tree, err := Load("a = true\nb = false") - assertTree(t, tree, err, map[string]interface{}{ - "a": true, - "b": false, - }) -} - -func TestNestedKeys(t *testing.T) { - tree, err := Load("[a.b.c]\nd = 42") - assertTree(t, tree, err, map[string]interface{}{ - "a": map[string]interface{}{ - "b": map[string]interface{}{ - "c": map[string]interface{}{ - "d": int64(42), - }, - }, - }, - }) -} - -func TestNestedQuotedUnicodeKeys(t *testing.T) { - tree, err := Load("[ j . \"ʞ\" . l ]\nd = 42") - assertTree(t, tree, err, map[string]interface{}{ - "j": map[string]interface{}{ - "ʞ": map[string]interface{}{ - "l": map[string]interface{}{ - "d": int64(42), - }, - }, - }, - }) - - tree, err = Load("[ g . h . i ]\nd = 42") - assertTree(t, tree, err, map[string]interface{}{ - "g": map[string]interface{}{ - "h": map[string]interface{}{ - "i": map[string]interface{}{ - "d": int64(42), - }, - }, - }, - }) - - tree, err = Load("[ d.e.f ]\nk = 42") - assertTree(t, tree, err, map[string]interface{}{ - "d": map[string]interface{}{ - "e": map[string]interface{}{ - "f": map[string]interface{}{ - "k": int64(42), - }, - }, - }, - }) -} - -func TestArrayOne(t *testing.T) { - tree, err := Load("a = [1]") - assertTree(t, tree, err, map[string]interface{}{ - "a": []int64{int64(1)}, - }) -} - -func TestArrayZero(t *testing.T) { - tree, err := Load("a = []") - assertTree(t, tree, err, map[string]interface{}{ - "a": []interface{}{}, - }) -} - -func TestArraySimple(t *testing.T) { - tree, err := Load("a = [42, 21, 10]") - assertTree(t, tree, err, map[string]interface{}{ - "a": []int64{int64(42), int64(21), int64(10)}, - }) - - tree, _ = Load("a = [42, 21, 10,]") - assertTree(t, tree, err, map[string]interface{}{ - "a": []int64{int64(42), int64(21), int64(10)}, - }) -} - -func TestArrayMultiline(t *testing.T) { - tree, err := Load("a = [42,\n21, 10,]") - assertTree(t, tree, err, map[string]interface{}{ - "a": []int64{int64(42), int64(21), int64(10)}, - }) -} - -func TestArrayNested(t *testing.T) { - tree, err := Load("a = [[42, 21], [10]]") - assertTree(t, tree, err, map[string]interface{}{ - "a": [][]int64{{int64(42), int64(21)}, {int64(10)}}, - }) -} - -func TestNestedArrayComment(t *testing.T) { - tree, err := Load(` -someArray = [ -# does not work -["entry1"] -]`) - assertTree(t, tree, err, map[string]interface{}{ - "someArray": [][]string{{"entry1"}}, - }) -} - -func TestNestedEmptyArrays(t *testing.T) { - tree, err := Load("a = [[[]]]") - assertTree(t, tree, err, map[string]interface{}{ - "a": [][][]interface{}{{{}}}, - }) -} - -func TestArrayMixedTypes(t *testing.T) { - _, err := Load("a = [42, 16.0]") - if err.Error() != "(1, 10): mixed types in array" { - t.Error("Bad error message:", err.Error()) - } - - _, err = Load("a = [42, \"hello\"]") - if err.Error() != "(1, 11): mixed types in array" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestArrayNestedStrings(t *testing.T) { - tree, err := Load("data = [ [\"gamma\", \"delta\"], [\"Foo\"] ]") - assertTree(t, tree, err, map[string]interface{}{ - "data": [][]string{{"gamma", "delta"}, {"Foo"}}, - }) -} - -func TestParseUnknownRvalue(t *testing.T) { - _, err := Load("a = !bssss") - if err == nil { - t.Error("Expecting a parse error") - } - - _, err = Load("a = /b") - if err == nil { - t.Error("Expecting a parse error") - } -} - -func TestMissingValue(t *testing.T) { - _, err := Load("a = ") - if err.Error() != "(1, 5): expecting a value" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestUnterminatedArray(t *testing.T) { - _, err := Load("a = [1,") - if err.Error() != "(1, 8): unterminated array" { - t.Error("Bad error message:", err.Error()) - } - - _, err = Load("a = [1") - if err.Error() != "(1, 7): unterminated array" { - t.Error("Bad error message:", err.Error()) - } - - _, err = Load("a = [1 2") - if err.Error() != "(1, 8): missing comma" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestNewlinesInArrays(t *testing.T) { - tree, err := Load("a = [1,\n2,\n3]") - assertTree(t, tree, err, map[string]interface{}{ - "a": []int64{int64(1), int64(2), int64(3)}, - }) -} - -func TestArrayWithExtraComma(t *testing.T) { - tree, err := Load("a = [1,\n2,\n3,\n]") - assertTree(t, tree, err, map[string]interface{}{ - "a": []int64{int64(1), int64(2), int64(3)}, - }) -} - -func TestArrayWithExtraCommaComment(t *testing.T) { - tree, err := Load("a = [1, # wow\n2, # such items\n3, # so array\n]") - assertTree(t, tree, err, map[string]interface{}{ - "a": []int64{int64(1), int64(2), int64(3)}, - }) -} - -func TestSimpleInlineGroup(t *testing.T) { - tree, err := Load("key = {a = 42}") - assertTree(t, tree, err, map[string]interface{}{ - "key": map[string]interface{}{ - "a": int64(42), - }, - }) -} - -func TestDoubleInlineGroup(t *testing.T) { - tree, err := Load("key = {a = 42, b = \"foo\"}") - assertTree(t, tree, err, map[string]interface{}{ - "key": map[string]interface{}{ - "a": int64(42), - "b": "foo", - }, - }) -} - -func TestExampleInlineGroup(t *testing.T) { - tree, err := Load(`name = { first = "Tom", last = "Preston-Werner" } -point = { x = 1, y = 2 }`) - assertTree(t, tree, err, map[string]interface{}{ - "name": map[string]interface{}{ - "first": "Tom", - "last": "Preston-Werner", - }, - "point": map[string]interface{}{ - "x": int64(1), - "y": int64(2), - }, - }) -} - -func TestExampleInlineGroupInArray(t *testing.T) { - tree, err := Load(`points = [{ x = 1, y = 2 }]`) - assertTree(t, tree, err, map[string]interface{}{ - "points": []map[string]interface{}{ - { - "x": int64(1), - "y": int64(2), - }, - }, - }) -} - -func TestInlineTableUnterminated(t *testing.T) { - _, err := Load("foo = {") - if err.Error() != "(1, 8): unterminated inline table" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestInlineTableCommaExpected(t *testing.T) { - _, err := Load("foo = {hello = 53 test = foo}") - if err.Error() != "(1, 19): comma expected between fields in inline table" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestInlineTableCommaStart(t *testing.T) { - _, err := Load("foo = {, hello = 53}") - if err.Error() != "(1, 8): inline table cannot start with a comma" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestInlineTableDoubleComma(t *testing.T) { - _, err := Load("foo = {hello = 53,, foo = 17}") - if err.Error() != "(1, 19): need field between two commas in inline table" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestDuplicateGroups(t *testing.T) { - _, err := Load("[foo]\na=2\n[foo]b=3") - if err.Error() != "(3, 2): duplicated tables" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestDuplicateKeys(t *testing.T) { - _, err := Load("foo = 2\nfoo = 3") - if err.Error() != "(2, 1): The following key was defined twice: foo" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestEmptyIntermediateTable(t *testing.T) { - _, err := Load("[foo..bar]") - if err.Error() != "(1, 2): invalid table array key: expecting key part after dot" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestImplicitDeclarationBefore(t *testing.T) { - tree, err := Load("[a.b.c]\nanswer = 42\n[a]\nbetter = 43") - assertTree(t, tree, err, map[string]interface{}{ - "a": map[string]interface{}{ - "b": map[string]interface{}{ - "c": map[string]interface{}{ - "answer": int64(42), - }, - }, - "better": int64(43), - }, - }) -} - -func TestFloatsWithoutLeadingZeros(t *testing.T) { - _, err := Load("a = .42") - if err.Error() != "(1, 5): cannot start float with a dot" { - t.Error("Bad error message:", err.Error()) - } - - _, err = Load("a = -.42") - if err.Error() != "(1, 5): cannot start float with a dot" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestMissingFile(t *testing.T) { - _, err := LoadFile("foo.toml") - if err.Error() != "open foo.toml: no such file or directory" && - err.Error() != "open foo.toml: The system cannot find the file specified." { - t.Error("Bad error message:", err.Error()) - } -} - -func TestParseFile(t *testing.T) { - tree, err := LoadFile("example.toml") - - assertTree(t, tree, err, map[string]interface{}{ - "title": "TOML Example", - "owner": map[string]interface{}{ - "name": "Tom Preston-Werner", - "organization": "GitHub", - "bio": "GitHub Cofounder & CEO\nLikes tater tots and beer.", - "dob": time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC), - }, - "database": map[string]interface{}{ - "server": "192.168.1.1", - "ports": []int64{8001, 8001, 8002}, - "connection_max": 5000, - "enabled": true, - }, - "servers": map[string]interface{}{ - "alpha": map[string]interface{}{ - "ip": "10.0.0.1", - "dc": "eqdc10", - }, - "beta": map[string]interface{}{ - "ip": "10.0.0.2", - "dc": "eqdc10", - }, - }, - "clients": map[string]interface{}{ - "data": []interface{}{ - []string{"gamma", "delta"}, - []int64{1, 2}, - }, - }, - }) -} - -func TestParseFileCRLF(t *testing.T) { - tree, err := LoadFile("example-crlf.toml") - - assertTree(t, tree, err, map[string]interface{}{ - "title": "TOML Example", - "owner": map[string]interface{}{ - "name": "Tom Preston-Werner", - "organization": "GitHub", - "bio": "GitHub Cofounder & CEO\nLikes tater tots and beer.", - "dob": time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC), - }, - "database": map[string]interface{}{ - "server": "192.168.1.1", - "ports": []int64{8001, 8001, 8002}, - "connection_max": 5000, - "enabled": true, - }, - "servers": map[string]interface{}{ - "alpha": map[string]interface{}{ - "ip": "10.0.0.1", - "dc": "eqdc10", - }, - "beta": map[string]interface{}{ - "ip": "10.0.0.2", - "dc": "eqdc10", - }, - }, - "clients": map[string]interface{}{ - "data": []interface{}{ - []string{"gamma", "delta"}, - []int64{1, 2}, - }, - }, - }) -} - -func TestParseKeyGroupArray(t *testing.T) { - tree, err := Load("[[foo.bar]] a = 42\n[[foo.bar]] a = 69") - assertTree(t, tree, err, map[string]interface{}{ - "foo": map[string]interface{}{ - "bar": []map[string]interface{}{ - {"a": int64(42)}, - {"a": int64(69)}, - }, - }, - }) -} - -func TestParseKeyGroupArrayUnfinished(t *testing.T) { - _, err := Load("[[foo.bar]\na = 42") - if err.Error() != "(1, 10): was expecting token [[, but got unclosed table array key instead" { - t.Error("Bad error message:", err.Error()) - } - - _, err = Load("[[foo.[bar]\na = 42") - if err.Error() != "(1, 3): unexpected token table array key cannot contain ']', was expecting a table array key" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestParseKeyGroupArrayQueryExample(t *testing.T) { - tree, err := Load(` - [[book]] - title = "The Stand" - author = "Stephen King" - [[book]] - title = "For Whom the Bell Tolls" - author = "Ernest Hemmingway" - [[book]] - title = "Neuromancer" - author = "William Gibson" - `) - - assertTree(t, tree, err, map[string]interface{}{ - "book": []map[string]interface{}{ - {"title": "The Stand", "author": "Stephen King"}, - {"title": "For Whom the Bell Tolls", "author": "Ernest Hemmingway"}, - {"title": "Neuromancer", "author": "William Gibson"}, - }, - }) -} - -func TestParseKeyGroupArraySpec(t *testing.T) { - tree, err := Load("[[fruit]]\n name=\"apple\"\n [fruit.physical]\n color=\"red\"\n shape=\"round\"\n [[fruit]]\n name=\"banana\"") - assertTree(t, tree, err, map[string]interface{}{ - "fruit": []map[string]interface{}{ - {"name": "apple", "physical": map[string]interface{}{"color": "red", "shape": "round"}}, - {"name": "banana"}, - }, - }) -} - -func TestTomlValueStringRepresentation(t *testing.T) { - for idx, item := range []struct { - Value interface{} - Expect string - }{ - {int64(12345), "12345"}, - {uint64(50), "50"}, - {float64(123.45), "123.45"}, - {true, "true"}, - {"hello world", "\"hello world\""}, - {"\b\t\n\f\r\"\\", "\"\\b\\t\\n\\f\\r\\\"\\\\\""}, - {"\x05", "\"\\u0005\""}, - {time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC), - "1979-05-27T07:32:00Z"}, - {[]interface{}{"gamma", "delta"}, - "[\"gamma\",\"delta\"]"}, - {nil, ""}, - } { - result, err := tomlValueStringRepresentation(item.Value, "", false) - if err != nil { - t.Errorf("Test %d - unexpected error: %s", idx, err) - } - if result != item.Expect { - t.Errorf("Test %d - got '%s', expected '%s'", idx, result, item.Expect) - } - } -} - -func TestToStringMapStringString(t *testing.T) { - tree, err := TreeFromMap(map[string]interface{}{"m": map[string]interface{}{"v": "abc"}}) - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - want := "\n[m]\n v = \"abc\"\n" - got := tree.String() - - if got != want { - t.Errorf("want:\n%q\ngot:\n%q", want, got) - } -} - -func assertPosition(t *testing.T, text string, ref map[string]Position) { - tree, err := Load(text) - if err != nil { - t.Errorf("Error loading document text: `%v`", text) - t.Errorf("Error: %v", err) - } - for path, pos := range ref { - testPos := tree.GetPosition(path) - if testPos.Invalid() { - t.Errorf("Failed to query tree path or path has invalid position: %s", path) - } else if pos != testPos { - t.Errorf("Expected position %v, got %v instead", pos, testPos) - } - } -} - -func TestDocumentPositions(t *testing.T) { - assertPosition(t, - "[foo]\nbar=42\nbaz=69", - map[string]Position{ - "": {1, 1}, - "foo": {1, 1}, - "foo.bar": {2, 1}, - "foo.baz": {3, 1}, - }) -} - -func TestDocumentPositionsWithSpaces(t *testing.T) { - assertPosition(t, - " [foo]\n bar=42\n baz=69", - map[string]Position{ - "": {1, 1}, - "foo": {1, 3}, - "foo.bar": {2, 3}, - "foo.baz": {3, 3}, - }) -} - -func TestDocumentPositionsWithGroupArray(t *testing.T) { - assertPosition(t, - "[[foo]]\nbar=42\nbaz=69", - map[string]Position{ - "": {1, 1}, - "foo": {1, 1}, - "foo.bar": {2, 1}, - "foo.baz": {3, 1}, - }) -} - -func TestNestedTreePosition(t *testing.T) { - assertPosition(t, - "[foo.bar]\na=42\nb=69", - map[string]Position{ - "": {1, 1}, - "foo": {1, 1}, - "foo.bar": {1, 1}, - "foo.bar.a": {2, 1}, - "foo.bar.b": {3, 1}, - }) -} - -func TestInvalidGroupArray(t *testing.T) { - _, err := Load("[table#key]\nanswer = 42") - if err == nil { - t.Error("Should error") - } - - _, err = Load("[foo.[bar]\na = 42") - if err.Error() != "(1, 2): unexpected token table key cannot contain ']', was expecting a table key" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestDoubleEqual(t *testing.T) { - _, err := Load("foo= = 2") - if err.Error() != "(1, 6): cannot have multiple equals for the same key" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestGroupArrayReassign(t *testing.T) { - _, err := Load("[hello]\n[[hello]]") - if err.Error() != "(2, 3): key \"hello\" is already assigned and not of type table array" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestInvalidFloatParsing(t *testing.T) { - _, err := Load("a=1e_2") - if err.Error() != "(1, 3): invalid use of _ in number" { - t.Error("Bad error message:", err.Error()) - } - - _, err = Load("a=1e2_") - if err.Error() != "(1, 3): invalid use of _ in number" { - t.Error("Bad error message:", err.Error()) - } - - _, err = Load("a=1__2") - if err.Error() != "(1, 3): invalid use of _ in number" { - t.Error("Bad error message:", err.Error()) - } - - _, err = Load("a=_1_2") - if err.Error() != "(1, 3): cannot start number with underscore" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestMapKeyIsNum(t *testing.T) { - _, err := Load("table={2018=1,2019=2}") - if err != nil { - t.Error("should be passed") - } - _, err = Load(`table={"2018"=1,"2019"=2}`) - if err != nil { - t.Error("should be passed") - } -} - -func TestDottedKeys(t *testing.T) { - tree, err := Load(` -name = "Orange" -physical.color = "orange" -physical.shape = "round" -site."google.com" = true`) - - assertTree(t, tree, err, map[string]interface{}{ - "name": "Orange", - "physical": map[string]interface{}{ - "color": "orange", - "shape": "round", - }, - "site": map[string]interface{}{ - "google.com": true, - }, - }) -} - -func TestInvalidDottedKeyEmptyGroup(t *testing.T) { - _, err := Load(`a..b = true`) - if err == nil { - t.Fatal("should return an error") - } - if err.Error() != "(1, 1): invalid key: expecting key part after dot" { - t.Fatalf("invalid error message: %s", err) - } -} diff --git a/src/vendor/github.com/pelletier/go-toml/position_test.go b/src/vendor/github.com/pelletier/go-toml/position_test.go deleted file mode 100644 index 63ad1afc86fd94bdc22e86ed4ce93e2fab5dbb72..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/position_test.go +++ /dev/null @@ -1,29 +0,0 @@ -// Testing support for go-toml - -package toml - -import ( - "testing" -) - -func TestPositionString(t *testing.T) { - p := Position{123, 456} - expected := "(123, 456)" - value := p.String() - - if value != expected { - t.Errorf("Expected %v, got %v instead", expected, value) - } -} - -func TestInvalid(t *testing.T) { - for i, v := range []Position{ - {0, 1234}, - {1234, 0}, - {0, 0}, - } { - if !v.Invalid() { - t.Errorf("Position at %v is valid: %v", i, v) - } - } -} diff --git a/src/vendor/github.com/pelletier/go-toml/query/doc.go b/src/vendor/github.com/pelletier/go-toml/query/doc.go deleted file mode 100644 index ed63c11096a28b803f0d695043fbd69367a67cad..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/query/doc.go +++ /dev/null @@ -1,175 +0,0 @@ -// Package query performs JSONPath-like queries on a TOML document. -// -// The query path implementation is based loosely on the JSONPath specification: -// http://goessner.net/articles/JsonPath/. -// -// The idea behind a query path is to allow quick access to any element, or set -// of elements within TOML document, with a single expression. -// -// result, err := query.CompileAndExecute("$.foo.bar.baz", tree) -// -// This is roughly equivalent to: -// -// next := tree.Get("foo") -// if next != nil { -// next = next.Get("bar") -// if next != nil { -// next = next.Get("baz") -// } -// } -// result := next -// -// err is nil if any parsing exception occurs. -// -// If no node in the tree matches the query, result will simply contain an empty list of -// items. -// -// As illustrated above, the query path is much more efficient, especially since -// the structure of the TOML file can vary. Rather than making assumptions about -// a document's structure, a query allows the programmer to make structured -// requests into the document, and get zero or more values as a result. -// -// Query syntax -// -// The syntax of a query begins with a root token, followed by any number -// sub-expressions: -// -// $ -// Root of the TOML tree. This must always come first. -// .name -// Selects child of this node, where 'name' is a TOML key -// name. -// ['name'] -// Selects child of this node, where 'name' is a string -// containing a TOML key name. -// [index] -// Selcts child array element at 'index'. -// ..expr -// Recursively selects all children, filtered by an a union, -// index, or slice expression. -// ..* -// Recursive selection of all nodes at this point in the -// tree. -// .* -// Selects all children of the current node. -// [expr,expr] -// Union operator - a logical 'or' grouping of two or more -// sub-expressions: index, key name, or filter. -// [start:end:step] -// Slice operator - selects array elements from start to -// end-1, at the given step. All three arguments are -// optional. -// [?(filter)] -// Named filter expression - the function 'filter' is -// used to filter children at this node. -// -// Query Indexes And Slices -// -// Index expressions perform no bounds checking, and will contribute no -// values to the result set if the provided index or index range is invalid. -// Negative indexes represent values from the end of the array, counting backwards. -// -// // select the last index of the array named 'foo' -// query.CompileAndExecute("$.foo[-1]", tree) -// -// Slice expressions are supported, by using ':' to separate a start/end index pair. -// -// // select up to the first five elements in the array -// query.CompileAndExecute("$.foo[0:5]", tree) -// -// Slice expressions also allow negative indexes for the start and stop -// arguments. -// -// // select all array elements. -// query.CompileAndExecute("$.foo[0:-1]", tree) -// -// Slice expressions may have an optional stride/step parameter: -// -// // select every other element -// query.CompileAndExecute("$.foo[0:-1:2]", tree) -// -// Slice start and end parameters are also optional: -// -// // these are all equivalent and select all the values in the array -// query.CompileAndExecute("$.foo[:]", tree) -// query.CompileAndExecute("$.foo[0:]", tree) -// query.CompileAndExecute("$.foo[:-1]", tree) -// query.CompileAndExecute("$.foo[0:-1:]", tree) -// query.CompileAndExecute("$.foo[::1]", tree) -// query.CompileAndExecute("$.foo[0::1]", tree) -// query.CompileAndExecute("$.foo[:-1:1]", tree) -// query.CompileAndExecute("$.foo[0:-1:1]", tree) -// -// Query Filters -// -// Query filters are used within a Union [,] or single Filter [] expression. -// A filter only allows nodes that qualify through to the next expression, -// and/or into the result set. -// -// // returns children of foo that are permitted by the 'bar' filter. -// query.CompileAndExecute("$.foo[?(bar)]", tree) -// -// There are several filters provided with the library: -// -// tree -// Allows nodes of type Tree. -// int -// Allows nodes of type int64. -// float -// Allows nodes of type float64. -// string -// Allows nodes of type string. -// time -// Allows nodes of type time.Time. -// bool -// Allows nodes of type bool. -// -// Query Results -// -// An executed query returns a Result object. This contains the nodes -// in the TOML tree that qualify the query expression. Position information -// is also available for each value in the set. -// -// // display the results of a query -// results := query.CompileAndExecute("$.foo.bar.baz", tree) -// for idx, value := results.Values() { -// fmt.Println("%v: %v", results.Positions()[idx], value) -// } -// -// Compiled Queries -// -// Queries may be executed directly on a Tree object, or compiled ahead -// of time and executed discretely. The former is more convenient, but has the -// penalty of having to recompile the query expression each time. -// -// // basic query -// results := query.CompileAndExecute("$.foo.bar.baz", tree) -// -// // compiled query -// query, err := toml.Compile("$.foo.bar.baz") -// results := query.Execute(tree) -// -// // run the compiled query again on a different tree -// moreResults := query.Execute(anotherTree) -// -// User Defined Query Filters -// -// Filter expressions may also be user defined by using the SetFilter() -// function on the Query object. The function must return true/false, which -// signifies if the passed node is kept or discarded, respectively. -// -// // create a query that references a user-defined filter -// query, _ := query.Compile("$[?(bazOnly)]") -// -// // define the filter, and assign it to the query -// query.SetFilter("bazOnly", func(node interface{}) bool{ -// if tree, ok := node.(*Tree); ok { -// return tree.Has("baz") -// } -// return false // reject all other node types -// }) -// -// // run the query -// query.Execute(tree) -// -package query diff --git a/src/vendor/github.com/pelletier/go-toml/query/lexer.go b/src/vendor/github.com/pelletier/go-toml/query/lexer.go deleted file mode 100644 index 2dc319408e73a050e2b10a60bfebeabbd0d59026..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/query/lexer.go +++ /dev/null @@ -1,357 +0,0 @@ -// TOML JSONPath lexer. -// -// Written using the principles developed by Rob Pike in -// http://www.youtube.com/watch?v=HxaD_trXwRE - -package query - -import ( - "fmt" - "github.com/pelletier/go-toml" - "strconv" - "strings" - "unicode/utf8" -) - -// Lexer state function -type queryLexStateFn func() queryLexStateFn - -// Lexer definition -type queryLexer struct { - input string - start int - pos int - width int - tokens chan token - depth int - line int - col int - stringTerm string -} - -func (l *queryLexer) run() { - for state := l.lexVoid; state != nil; { - state = state() - } - close(l.tokens) -} - -func (l *queryLexer) nextStart() { - // iterate by runes (utf8 characters) - // search for newlines and advance line/col counts - for i := l.start; i < l.pos; { - r, width := utf8.DecodeRuneInString(l.input[i:]) - if r == '\n' { - l.line++ - l.col = 1 - } else { - l.col++ - } - i += width - } - // advance start position to next token - l.start = l.pos -} - -func (l *queryLexer) emit(t tokenType) { - l.tokens <- token{ - Position: toml.Position{Line: l.line, Col: l.col}, - typ: t, - val: l.input[l.start:l.pos], - } - l.nextStart() -} - -func (l *queryLexer) emitWithValue(t tokenType, value string) { - l.tokens <- token{ - Position: toml.Position{Line: l.line, Col: l.col}, - typ: t, - val: value, - } - l.nextStart() -} - -func (l *queryLexer) next() rune { - if l.pos >= len(l.input) { - l.width = 0 - return eof - } - var r rune - r, l.width = utf8.DecodeRuneInString(l.input[l.pos:]) - l.pos += l.width - return r -} - -func (l *queryLexer) ignore() { - l.nextStart() -} - -func (l *queryLexer) backup() { - l.pos -= l.width -} - -func (l *queryLexer) errorf(format string, args ...interface{}) queryLexStateFn { - l.tokens <- token{ - Position: toml.Position{Line: l.line, Col: l.col}, - typ: tokenError, - val: fmt.Sprintf(format, args...), - } - return nil -} - -func (l *queryLexer) peek() rune { - r := l.next() - l.backup() - return r -} - -func (l *queryLexer) accept(valid string) bool { - if strings.ContainsRune(valid, l.next()) { - return true - } - l.backup() - return false -} - -func (l *queryLexer) follow(next string) bool { - return strings.HasPrefix(l.input[l.pos:], next) -} - -func (l *queryLexer) lexVoid() queryLexStateFn { - for { - next := l.peek() - switch next { - case '$': - l.pos++ - l.emit(tokenDollar) - continue - case '.': - if l.follow("..") { - l.pos += 2 - l.emit(tokenDotDot) - } else { - l.pos++ - l.emit(tokenDot) - } - continue - case '[': - l.pos++ - l.emit(tokenLeftBracket) - continue - case ']': - l.pos++ - l.emit(tokenRightBracket) - continue - case ',': - l.pos++ - l.emit(tokenComma) - continue - case '*': - l.pos++ - l.emit(tokenStar) - continue - case '(': - l.pos++ - l.emit(tokenLeftParen) - continue - case ')': - l.pos++ - l.emit(tokenRightParen) - continue - case '?': - l.pos++ - l.emit(tokenQuestion) - continue - case ':': - l.pos++ - l.emit(tokenColon) - continue - case '\'': - l.ignore() - l.stringTerm = string(next) - return l.lexString - case '"': - l.ignore() - l.stringTerm = string(next) - return l.lexString - } - - if isSpace(next) { - l.next() - l.ignore() - continue - } - - if isAlphanumeric(next) { - return l.lexKey - } - - if next == '+' || next == '-' || isDigit(next) { - return l.lexNumber - } - - if l.next() == eof { - break - } - - return l.errorf("unexpected char: '%v'", next) - } - l.emit(tokenEOF) - return nil -} - -func (l *queryLexer) lexKey() queryLexStateFn { - for { - next := l.peek() - if !isAlphanumeric(next) { - l.emit(tokenKey) - return l.lexVoid - } - - if l.next() == eof { - break - } - } - l.emit(tokenEOF) - return nil -} - -func (l *queryLexer) lexString() queryLexStateFn { - l.pos++ - l.ignore() - growingString := "" - - for { - if l.follow(l.stringTerm) { - l.emitWithValue(tokenString, growingString) - l.pos++ - l.ignore() - return l.lexVoid - } - - if l.follow("\\\"") { - l.pos++ - growingString += "\"" - } else if l.follow("\\'") { - l.pos++ - growingString += "'" - } else if l.follow("\\n") { - l.pos++ - growingString += "\n" - } else if l.follow("\\b") { - l.pos++ - growingString += "\b" - } else if l.follow("\\f") { - l.pos++ - growingString += "\f" - } else if l.follow("\\/") { - l.pos++ - growingString += "/" - } else if l.follow("\\t") { - l.pos++ - growingString += "\t" - } else if l.follow("\\r") { - l.pos++ - growingString += "\r" - } else if l.follow("\\\\") { - l.pos++ - growingString += "\\" - } else if l.follow("\\u") { - l.pos += 2 - code := "" - for i := 0; i < 4; i++ { - c := l.peek() - l.pos++ - if !isHexDigit(c) { - return l.errorf("unfinished unicode escape") - } - code = code + string(c) - } - l.pos-- - intcode, err := strconv.ParseInt(code, 16, 32) - if err != nil { - return l.errorf("invalid unicode escape: \\u" + code) - } - growingString += string(rune(intcode)) - } else if l.follow("\\U") { - l.pos += 2 - code := "" - for i := 0; i < 8; i++ { - c := l.peek() - l.pos++ - if !isHexDigit(c) { - return l.errorf("unfinished unicode escape") - } - code = code + string(c) - } - l.pos-- - intcode, err := strconv.ParseInt(code, 16, 32) - if err != nil { - return l.errorf("invalid unicode escape: \\u" + code) - } - growingString += string(rune(intcode)) - } else if l.follow("\\") { - l.pos++ - return l.errorf("invalid escape sequence: \\" + string(l.peek())) - } else { - growingString += string(l.peek()) - } - - if l.next() == eof { - break - } - } - - return l.errorf("unclosed string") -} - -func (l *queryLexer) lexNumber() queryLexStateFn { - l.ignore() - if !l.accept("+") { - l.accept("-") - } - pointSeen := false - digitSeen := false - for { - next := l.next() - if next == '.' { - if pointSeen { - return l.errorf("cannot have two dots in one float") - } - if !isDigit(l.peek()) { - return l.errorf("float cannot end with a dot") - } - pointSeen = true - } else if isDigit(next) { - digitSeen = true - } else { - l.backup() - break - } - if pointSeen && !digitSeen { - return l.errorf("cannot start float with a dot") - } - } - - if !digitSeen { - return l.errorf("no digit in that number") - } - if pointSeen { - l.emit(tokenFloat) - } else { - l.emit(tokenInteger) - } - return l.lexVoid -} - -// Entry point -func lexQuery(input string) chan token { - l := &queryLexer{ - input: input, - tokens: make(chan token), - line: 1, - col: 1, - } - go l.run() - return l.tokens -} diff --git a/src/vendor/github.com/pelletier/go-toml/query/lexer_test.go b/src/vendor/github.com/pelletier/go-toml/query/lexer_test.go deleted file mode 100644 index 8ce0501fed54128b76d713daf6d917c527302d83..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/query/lexer_test.go +++ /dev/null @@ -1,179 +0,0 @@ -package query - -import ( - "github.com/pelletier/go-toml" - "testing" -) - -func testQLFlow(t *testing.T, input string, expectedFlow []token) { - ch := lexQuery(input) - for idx, expected := range expectedFlow { - token := <-ch - if token != expected { - t.Log("While testing #", idx, ":", input) - t.Log("compared (got)", token, "to (expected)", expected) - t.Log("\tvalue:", token.val, "<->", expected.val) - t.Log("\tvalue as bytes:", []byte(token.val), "<->", []byte(expected.val)) - t.Log("\ttype:", token.typ.String(), "<->", expected.typ.String()) - t.Log("\tline:", token.Line, "<->", expected.Line) - t.Log("\tcolumn:", token.Col, "<->", expected.Col) - t.Log("compared", token, "to", expected) - t.FailNow() - } - } - - tok, ok := <-ch - if ok { - t.Log("channel is not closed!") - t.Log(len(ch)+1, "tokens remaining:") - - t.Log("token ->", tok) - for token := range ch { - t.Log("token ->", token) - } - t.FailNow() - } -} - -func TestLexSpecialChars(t *testing.T) { - testQLFlow(t, " .$[]..()?*", []token{ - {toml.Position{1, 2}, tokenDot, "."}, - {toml.Position{1, 3}, tokenDollar, "$"}, - {toml.Position{1, 4}, tokenLeftBracket, "["}, - {toml.Position{1, 5}, tokenRightBracket, "]"}, - {toml.Position{1, 6}, tokenDotDot, ".."}, - {toml.Position{1, 8}, tokenLeftParen, "("}, - {toml.Position{1, 9}, tokenRightParen, ")"}, - {toml.Position{1, 10}, tokenQuestion, "?"}, - {toml.Position{1, 11}, tokenStar, "*"}, - {toml.Position{1, 12}, tokenEOF, ""}, - }) -} - -func TestLexString(t *testing.T) { - testQLFlow(t, "'foo\n'", []token{ - {toml.Position{1, 2}, tokenString, "foo\n"}, - {toml.Position{2, 2}, tokenEOF, ""}, - }) -} - -func TestLexDoubleString(t *testing.T) { - testQLFlow(t, `"bar"`, []token{ - {toml.Position{1, 2}, tokenString, "bar"}, - {toml.Position{1, 6}, tokenEOF, ""}, - }) -} - -func TestLexStringEscapes(t *testing.T) { - testQLFlow(t, `"foo \" \' \b \f \/ \t \r \\ \u03A9 \U00012345 \n bar"`, []token{ - {toml.Position{1, 2}, tokenString, "foo \" ' \b \f / \t \r \\ \u03A9 \U00012345 \n bar"}, - {toml.Position{1, 55}, tokenEOF, ""}, - }) -} - -func TestLexStringUnfinishedUnicode4(t *testing.T) { - testQLFlow(t, `"\u000"`, []token{ - {toml.Position{1, 2}, tokenError, "unfinished unicode escape"}, - }) -} - -func TestLexStringUnfinishedUnicode8(t *testing.T) { - testQLFlow(t, `"\U0000"`, []token{ - {toml.Position{1, 2}, tokenError, "unfinished unicode escape"}, - }) -} - -func TestLexStringInvalidEscape(t *testing.T) { - testQLFlow(t, `"\x"`, []token{ - {toml.Position{1, 2}, tokenError, "invalid escape sequence: \\x"}, - }) -} - -func TestLexStringUnfinished(t *testing.T) { - testQLFlow(t, `"bar`, []token{ - {toml.Position{1, 2}, tokenError, "unclosed string"}, - }) -} - -func TestLexKey(t *testing.T) { - testQLFlow(t, "foo", []token{ - {toml.Position{1, 1}, tokenKey, "foo"}, - {toml.Position{1, 4}, tokenEOF, ""}, - }) -} - -func TestLexRecurse(t *testing.T) { - testQLFlow(t, "$..*", []token{ - {toml.Position{1, 1}, tokenDollar, "$"}, - {toml.Position{1, 2}, tokenDotDot, ".."}, - {toml.Position{1, 4}, tokenStar, "*"}, - {toml.Position{1, 5}, tokenEOF, ""}, - }) -} - -func TestLexBracketKey(t *testing.T) { - testQLFlow(t, "$[foo]", []token{ - {toml.Position{1, 1}, tokenDollar, "$"}, - {toml.Position{1, 2}, tokenLeftBracket, "["}, - {toml.Position{1, 3}, tokenKey, "foo"}, - {toml.Position{1, 6}, tokenRightBracket, "]"}, - {toml.Position{1, 7}, tokenEOF, ""}, - }) -} - -func TestLexSpace(t *testing.T) { - testQLFlow(t, "foo bar baz", []token{ - {toml.Position{1, 1}, tokenKey, "foo"}, - {toml.Position{1, 5}, tokenKey, "bar"}, - {toml.Position{1, 9}, tokenKey, "baz"}, - {toml.Position{1, 12}, tokenEOF, ""}, - }) -} - -func TestLexInteger(t *testing.T) { - testQLFlow(t, "100 +200 -300", []token{ - {toml.Position{1, 1}, tokenInteger, "100"}, - {toml.Position{1, 5}, tokenInteger, "+200"}, - {toml.Position{1, 10}, tokenInteger, "-300"}, - {toml.Position{1, 14}, tokenEOF, ""}, - }) -} - -func TestLexFloat(t *testing.T) { - testQLFlow(t, "100.0 +200.0 -300.0", []token{ - {toml.Position{1, 1}, tokenFloat, "100.0"}, - {toml.Position{1, 7}, tokenFloat, "+200.0"}, - {toml.Position{1, 14}, tokenFloat, "-300.0"}, - {toml.Position{1, 20}, tokenEOF, ""}, - }) -} - -func TestLexFloatWithMultipleDots(t *testing.T) { - testQLFlow(t, "4.2.", []token{ - {toml.Position{1, 1}, tokenError, "cannot have two dots in one float"}, - }) -} - -func TestLexFloatLeadingDot(t *testing.T) { - testQLFlow(t, "+.1", []token{ - {toml.Position{1, 1}, tokenError, "cannot start float with a dot"}, - }) -} - -func TestLexFloatWithTrailingDot(t *testing.T) { - testQLFlow(t, "42.", []token{ - {toml.Position{1, 1}, tokenError, "float cannot end with a dot"}, - }) -} - -func TestLexNumberWithoutDigit(t *testing.T) { - testQLFlow(t, "+", []token{ - {toml.Position{1, 1}, tokenError, "no digit in that number"}, - }) -} - -func TestLexUnknown(t *testing.T) { - testQLFlow(t, "^", []token{ - {toml.Position{1, 1}, tokenError, "unexpected char: '94'"}, - }) -} diff --git a/src/vendor/github.com/pelletier/go-toml/query/match.go b/src/vendor/github.com/pelletier/go-toml/query/match.go deleted file mode 100644 index d7bb15a45ab24e64ed9d373f45457d9c291b97ff..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/query/match.go +++ /dev/null @@ -1,232 +0,0 @@ -package query - -import ( - "fmt" - "github.com/pelletier/go-toml" -) - -// base match -type matchBase struct { - next pathFn -} - -func (f *matchBase) setNext(next pathFn) { - f.next = next -} - -// terminating functor - gathers results -type terminatingFn struct { - // empty -} - -func newTerminatingFn() *terminatingFn { - return &terminatingFn{} -} - -func (f *terminatingFn) setNext(next pathFn) { - // do nothing -} - -func (f *terminatingFn) call(node interface{}, ctx *queryContext) { - ctx.result.appendResult(node, ctx.lastPosition) -} - -// match single key -type matchKeyFn struct { - matchBase - Name string -} - -func newMatchKeyFn(name string) *matchKeyFn { - return &matchKeyFn{Name: name} -} - -func (f *matchKeyFn) call(node interface{}, ctx *queryContext) { - if array, ok := node.([]*toml.Tree); ok { - for _, tree := range array { - item := tree.Get(f.Name) - if item != nil { - ctx.lastPosition = tree.GetPosition(f.Name) - f.next.call(item, ctx) - } - } - } else if tree, ok := node.(*toml.Tree); ok { - item := tree.Get(f.Name) - if item != nil { - ctx.lastPosition = tree.GetPosition(f.Name) - f.next.call(item, ctx) - } - } -} - -// match single index -type matchIndexFn struct { - matchBase - Idx int -} - -func newMatchIndexFn(idx int) *matchIndexFn { - return &matchIndexFn{Idx: idx} -} - -func (f *matchIndexFn) call(node interface{}, ctx *queryContext) { - if arr, ok := node.([]interface{}); ok { - if f.Idx < len(arr) && f.Idx >= 0 { - if treesArray, ok := node.([]*toml.Tree); ok { - if len(treesArray) > 0 { - ctx.lastPosition = treesArray[0].Position() - } - } - f.next.call(arr[f.Idx], ctx) - } - } -} - -// filter by slicing -type matchSliceFn struct { - matchBase - Start, End, Step int -} - -func newMatchSliceFn(start, end, step int) *matchSliceFn { - return &matchSliceFn{Start: start, End: end, Step: step} -} - -func (f *matchSliceFn) call(node interface{}, ctx *queryContext) { - if arr, ok := node.([]interface{}); ok { - // adjust indexes for negative values, reverse ordering - realStart, realEnd := f.Start, f.End - if realStart < 0 { - realStart = len(arr) + realStart - } - if realEnd < 0 { - realEnd = len(arr) + realEnd - } - if realEnd < realStart { - realEnd, realStart = realStart, realEnd // swap - } - // loop and gather - for idx := realStart; idx < realEnd; idx += f.Step { - if treesArray, ok := node.([]*toml.Tree); ok { - if len(treesArray) > 0 { - ctx.lastPosition = treesArray[0].Position() - } - } - f.next.call(arr[idx], ctx) - } - } -} - -// match anything -type matchAnyFn struct { - matchBase -} - -func newMatchAnyFn() *matchAnyFn { - return &matchAnyFn{} -} - -func (f *matchAnyFn) call(node interface{}, ctx *queryContext) { - if tree, ok := node.(*toml.Tree); ok { - for _, k := range tree.Keys() { - v := tree.Get(k) - ctx.lastPosition = tree.GetPosition(k) - f.next.call(v, ctx) - } - } -} - -// filter through union -type matchUnionFn struct { - Union []pathFn -} - -func (f *matchUnionFn) setNext(next pathFn) { - for _, fn := range f.Union { - fn.setNext(next) - } -} - -func (f *matchUnionFn) call(node interface{}, ctx *queryContext) { - for _, fn := range f.Union { - fn.call(node, ctx) - } -} - -// match every single last node in the tree -type matchRecursiveFn struct { - matchBase -} - -func newMatchRecursiveFn() *matchRecursiveFn { - return &matchRecursiveFn{} -} - -func (f *matchRecursiveFn) call(node interface{}, ctx *queryContext) { - originalPosition := ctx.lastPosition - if tree, ok := node.(*toml.Tree); ok { - var visit func(tree *toml.Tree) - visit = func(tree *toml.Tree) { - for _, k := range tree.Keys() { - v := tree.Get(k) - ctx.lastPosition = tree.GetPosition(k) - f.next.call(v, ctx) - switch node := v.(type) { - case *toml.Tree: - visit(node) - case []*toml.Tree: - for _, subtree := range node { - visit(subtree) - } - } - } - } - ctx.lastPosition = originalPosition - f.next.call(tree, ctx) - visit(tree) - } -} - -// match based on an externally provided functional filter -type matchFilterFn struct { - matchBase - Pos toml.Position - Name string -} - -func newMatchFilterFn(name string, pos toml.Position) *matchFilterFn { - return &matchFilterFn{Name: name, Pos: pos} -} - -func (f *matchFilterFn) call(node interface{}, ctx *queryContext) { - fn, ok := (*ctx.filters)[f.Name] - if !ok { - panic(fmt.Sprintf("%s: query context does not have filter '%s'", - f.Pos.String(), f.Name)) - } - switch castNode := node.(type) { - case *toml.Tree: - for _, k := range castNode.Keys() { - v := castNode.Get(k) - if fn(v) { - ctx.lastPosition = castNode.GetPosition(k) - f.next.call(v, ctx) - } - } - case []*toml.Tree: - for _, v := range castNode { - if fn(v) { - if len(castNode) > 0 { - ctx.lastPosition = castNode[0].Position() - } - f.next.call(v, ctx) - } - } - case []interface{}: - for _, v := range castNode { - if fn(v) { - f.next.call(v, ctx) - } - } - } -} diff --git a/src/vendor/github.com/pelletier/go-toml/query/match_test.go b/src/vendor/github.com/pelletier/go-toml/query/match_test.go deleted file mode 100644 index 429b8f6b9ab85c7d24c67a6c59e00b7d8c115021..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/query/match_test.go +++ /dev/null @@ -1,202 +0,0 @@ -package query - -import ( - "fmt" - "github.com/pelletier/go-toml" - "testing" -) - -// dump path tree to a string -func pathString(root pathFn) string { - result := fmt.Sprintf("%T:", root) - switch fn := root.(type) { - case *terminatingFn: - result += "{}" - case *matchKeyFn: - result += fmt.Sprintf("{%s}", fn.Name) - result += pathString(fn.next) - case *matchIndexFn: - result += fmt.Sprintf("{%d}", fn.Idx) - result += pathString(fn.next) - case *matchSliceFn: - result += fmt.Sprintf("{%d:%d:%d}", - fn.Start, fn.End, fn.Step) - result += pathString(fn.next) - case *matchAnyFn: - result += "{}" - result += pathString(fn.next) - case *matchUnionFn: - result += "{[" - for _, v := range fn.Union { - result += pathString(v) + ", " - } - result += "]}" - case *matchRecursiveFn: - result += "{}" - result += pathString(fn.next) - case *matchFilterFn: - result += fmt.Sprintf("{%s}", fn.Name) - result += pathString(fn.next) - } - return result -} - -func assertPathMatch(t *testing.T, path, ref *Query) bool { - pathStr := pathString(path.root) - refStr := pathString(ref.root) - if pathStr != refStr { - t.Errorf("paths do not match") - t.Log("test:", pathStr) - t.Log("ref: ", refStr) - return false - } - return true -} - -func assertPath(t *testing.T, query string, ref *Query) { - path, _ := parseQuery(lexQuery(query)) - assertPathMatch(t, path, ref) -} - -func buildPath(parts ...pathFn) *Query { - query := newQuery() - for _, v := range parts { - query.appendPath(v) - } - return query -} - -func TestPathRoot(t *testing.T) { - assertPath(t, - "$", - buildPath( - // empty - )) -} - -func TestPathKey(t *testing.T) { - assertPath(t, - "$.foo", - buildPath( - newMatchKeyFn("foo"), - )) -} - -func TestPathBracketKey(t *testing.T) { - assertPath(t, - "$[foo]", - buildPath( - newMatchKeyFn("foo"), - )) -} - -func TestPathBracketStringKey(t *testing.T) { - assertPath(t, - "$['foo']", - buildPath( - newMatchKeyFn("foo"), - )) -} - -func TestPathIndex(t *testing.T) { - assertPath(t, - "$[123]", - buildPath( - newMatchIndexFn(123), - )) -} - -func TestPathSliceStart(t *testing.T) { - assertPath(t, - "$[123:]", - buildPath( - newMatchSliceFn(123, maxInt, 1), - )) -} - -func TestPathSliceStartEnd(t *testing.T) { - assertPath(t, - "$[123:456]", - buildPath( - newMatchSliceFn(123, 456, 1), - )) -} - -func TestPathSliceStartEndColon(t *testing.T) { - assertPath(t, - "$[123:456:]", - buildPath( - newMatchSliceFn(123, 456, 1), - )) -} - -func TestPathSliceStartStep(t *testing.T) { - assertPath(t, - "$[123::7]", - buildPath( - newMatchSliceFn(123, maxInt, 7), - )) -} - -func TestPathSliceEndStep(t *testing.T) { - assertPath(t, - "$[:456:7]", - buildPath( - newMatchSliceFn(0, 456, 7), - )) -} - -func TestPathSliceStep(t *testing.T) { - assertPath(t, - "$[::7]", - buildPath( - newMatchSliceFn(0, maxInt, 7), - )) -} - -func TestPathSliceAll(t *testing.T) { - assertPath(t, - "$[123:456:7]", - buildPath( - newMatchSliceFn(123, 456, 7), - )) -} - -func TestPathAny(t *testing.T) { - assertPath(t, - "$.*", - buildPath( - newMatchAnyFn(), - )) -} - -func TestPathUnion(t *testing.T) { - assertPath(t, - "$[foo, bar, baz]", - buildPath( - &matchUnionFn{[]pathFn{ - newMatchKeyFn("foo"), - newMatchKeyFn("bar"), - newMatchKeyFn("baz"), - }}, - )) -} - -func TestPathRecurse(t *testing.T) { - assertPath(t, - "$..*", - buildPath( - newMatchRecursiveFn(), - )) -} - -func TestPathFilterExpr(t *testing.T) { - assertPath(t, - "$[?('foo'),?(bar)]", - buildPath( - &matchUnionFn{[]pathFn{ - newMatchFilterFn("foo", toml.Position{}), - newMatchFilterFn("bar", toml.Position{}), - }}, - )) -} diff --git a/src/vendor/github.com/pelletier/go-toml/query/parser.go b/src/vendor/github.com/pelletier/go-toml/query/parser.go deleted file mode 100644 index 5f69b70d453f91b3b21b6f4d45dea6927d6e10a0..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/query/parser.go +++ /dev/null @@ -1,275 +0,0 @@ -/* - Based on the "jsonpath" spec/concept. - - http://goessner.net/articles/JsonPath/ - https://code.google.com/p/json-path/ -*/ - -package query - -import ( - "fmt" -) - -const maxInt = int(^uint(0) >> 1) - -type queryParser struct { - flow chan token - tokensBuffer []token - query *Query - union []pathFn - err error -} - -type queryParserStateFn func() queryParserStateFn - -// Formats and panics an error message based on a token -func (p *queryParser) parseError(tok *token, msg string, args ...interface{}) queryParserStateFn { - p.err = fmt.Errorf(tok.Position.String()+": "+msg, args...) - return nil // trigger parse to end -} - -func (p *queryParser) run() { - for state := p.parseStart; state != nil; { - state = state() - } -} - -func (p *queryParser) backup(tok *token) { - p.tokensBuffer = append(p.tokensBuffer, *tok) -} - -func (p *queryParser) peek() *token { - if len(p.tokensBuffer) != 0 { - return &(p.tokensBuffer[0]) - } - - tok, ok := <-p.flow - if !ok { - return nil - } - p.backup(&tok) - return &tok -} - -func (p *queryParser) lookahead(types ...tokenType) bool { - result := true - buffer := []token{} - - for _, typ := range types { - tok := p.getToken() - if tok == nil { - result = false - break - } - buffer = append(buffer, *tok) - if tok.typ != typ { - result = false - break - } - } - // add the tokens back to the buffer, and return - p.tokensBuffer = append(p.tokensBuffer, buffer...) - return result -} - -func (p *queryParser) getToken() *token { - if len(p.tokensBuffer) != 0 { - tok := p.tokensBuffer[0] - p.tokensBuffer = p.tokensBuffer[1:] - return &tok - } - tok, ok := <-p.flow - if !ok { - return nil - } - return &tok -} - -func (p *queryParser) parseStart() queryParserStateFn { - tok := p.getToken() - - if tok == nil || tok.typ == tokenEOF { - return nil - } - - if tok.typ != tokenDollar { - return p.parseError(tok, "Expected '$' at start of expression") - } - - return p.parseMatchExpr -} - -// handle '.' prefix, '[]', and '..' -func (p *queryParser) parseMatchExpr() queryParserStateFn { - tok := p.getToken() - switch tok.typ { - case tokenDotDot: - p.query.appendPath(&matchRecursiveFn{}) - // nested parse for '..' - tok := p.getToken() - switch tok.typ { - case tokenKey: - p.query.appendPath(newMatchKeyFn(tok.val)) - return p.parseMatchExpr - case tokenLeftBracket: - return p.parseBracketExpr - case tokenStar: - // do nothing - the recursive predicate is enough - return p.parseMatchExpr - } - - case tokenDot: - // nested parse for '.' - tok := p.getToken() - switch tok.typ { - case tokenKey: - p.query.appendPath(newMatchKeyFn(tok.val)) - return p.parseMatchExpr - case tokenStar: - p.query.appendPath(&matchAnyFn{}) - return p.parseMatchExpr - } - - case tokenLeftBracket: - return p.parseBracketExpr - - case tokenEOF: - return nil // allow EOF at this stage - } - return p.parseError(tok, "expected match expression") -} - -func (p *queryParser) parseBracketExpr() queryParserStateFn { - if p.lookahead(tokenInteger, tokenColon) { - return p.parseSliceExpr - } - if p.peek().typ == tokenColon { - return p.parseSliceExpr - } - return p.parseUnionExpr -} - -func (p *queryParser) parseUnionExpr() queryParserStateFn { - var tok *token - - // this state can be traversed after some sub-expressions - // so be careful when setting up state in the parser - if p.union == nil { - p.union = []pathFn{} - } - -loop: // labeled loop for easy breaking - for { - if len(p.union) > 0 { - // parse delimiter or terminator - tok = p.getToken() - switch tok.typ { - case tokenComma: - // do nothing - case tokenRightBracket: - break loop - default: - return p.parseError(tok, "expected ',' or ']', not '%s'", tok.val) - } - } - - // parse sub expression - tok = p.getToken() - switch tok.typ { - case tokenInteger: - p.union = append(p.union, newMatchIndexFn(tok.Int())) - case tokenKey: - p.union = append(p.union, newMatchKeyFn(tok.val)) - case tokenString: - p.union = append(p.union, newMatchKeyFn(tok.val)) - case tokenQuestion: - return p.parseFilterExpr - default: - return p.parseError(tok, "expected union sub expression, not '%s', %d", tok.val, len(p.union)) - } - } - - // if there is only one sub-expression, use that instead - if len(p.union) == 1 { - p.query.appendPath(p.union[0]) - } else { - p.query.appendPath(&matchUnionFn{p.union}) - } - - p.union = nil // clear out state - return p.parseMatchExpr -} - -func (p *queryParser) parseSliceExpr() queryParserStateFn { - // init slice to grab all elements - start, end, step := 0, maxInt, 1 - - // parse optional start - tok := p.getToken() - if tok.typ == tokenInteger { - start = tok.Int() - tok = p.getToken() - } - if tok.typ != tokenColon { - return p.parseError(tok, "expected ':'") - } - - // parse optional end - tok = p.getToken() - if tok.typ == tokenInteger { - end = tok.Int() - tok = p.getToken() - } - if tok.typ == tokenRightBracket { - p.query.appendPath(newMatchSliceFn(start, end, step)) - return p.parseMatchExpr - } - if tok.typ != tokenColon { - return p.parseError(tok, "expected ']' or ':'") - } - - // parse optional step - tok = p.getToken() - if tok.typ == tokenInteger { - step = tok.Int() - if step < 0 { - return p.parseError(tok, "step must be a positive value") - } - tok = p.getToken() - } - if tok.typ != tokenRightBracket { - return p.parseError(tok, "expected ']'") - } - - p.query.appendPath(newMatchSliceFn(start, end, step)) - return p.parseMatchExpr -} - -func (p *queryParser) parseFilterExpr() queryParserStateFn { - tok := p.getToken() - if tok.typ != tokenLeftParen { - return p.parseError(tok, "expected left-parenthesis for filter expression") - } - tok = p.getToken() - if tok.typ != tokenKey && tok.typ != tokenString { - return p.parseError(tok, "expected key or string for filter function name") - } - name := tok.val - tok = p.getToken() - if tok.typ != tokenRightParen { - return p.parseError(tok, "expected right-parenthesis for filter expression") - } - p.union = append(p.union, newMatchFilterFn(name, tok.Position)) - return p.parseUnionExpr -} - -func parseQuery(flow chan token) (*Query, error) { - parser := &queryParser{ - flow: flow, - tokensBuffer: []token{}, - query: newQuery(), - } - parser.run() - return parser.query, parser.err -} diff --git a/src/vendor/github.com/pelletier/go-toml/query/parser_test.go b/src/vendor/github.com/pelletier/go-toml/query/parser_test.go deleted file mode 100644 index 312f51ab5a2a2510abb5940ae8e565a76936ca50..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/query/parser_test.go +++ /dev/null @@ -1,482 +0,0 @@ -package query - -import ( - "fmt" - "io/ioutil" - "sort" - "strings" - "testing" - "time" - - "github.com/pelletier/go-toml" -) - -type queryTestNode struct { - value interface{} - position toml.Position -} - -func valueString(root interface{}) string { - result := "" //fmt.Sprintf("%T:", root) - switch node := root.(type) { - case *Result: - items := []string{} - for i, v := range node.Values() { - items = append(items, fmt.Sprintf("%s:%s", - node.Positions()[i].String(), valueString(v))) - } - sort.Strings(items) - result = "[" + strings.Join(items, ", ") + "]" - case queryTestNode: - result = fmt.Sprintf("%s:%s", - node.position.String(), valueString(node.value)) - case []interface{}: - items := []string{} - for _, v := range node { - items = append(items, valueString(v)) - } - sort.Strings(items) - result = "[" + strings.Join(items, ", ") + "]" - case *toml.Tree: - // workaround for unreliable map key ordering - items := []string{} - for _, k := range node.Keys() { - v := node.GetPath([]string{k}) - items = append(items, k+":"+valueString(v)) - } - sort.Strings(items) - result = "{" + strings.Join(items, ", ") + "}" - case map[string]interface{}: - // workaround for unreliable map key ordering - items := []string{} - for k, v := range node { - items = append(items, k+":"+valueString(v)) - } - sort.Strings(items) - result = "{" + strings.Join(items, ", ") + "}" - case int64: - result += fmt.Sprintf("%d", node) - case string: - result += "'" + node + "'" - case float64: - result += fmt.Sprintf("%f", node) - case bool: - result += fmt.Sprintf("%t", node) - case time.Time: - result += fmt.Sprintf("'%v'", node) - } - return result -} - -func assertValue(t *testing.T, result, ref interface{}) { - pathStr := valueString(result) - refStr := valueString(ref) - if pathStr != refStr { - t.Errorf("values do not match") - t.Log("test:", pathStr) - t.Log("ref: ", refStr) - } -} - -func assertQueryPositions(t *testing.T, tomlDoc string, query string, ref []interface{}) { - tree, err := toml.Load(tomlDoc) - if err != nil { - t.Errorf("Non-nil toml parse error: %v", err) - return - } - q, err := Compile(query) - if err != nil { - t.Error(err) - return - } - results := q.Execute(tree) - assertValue(t, results, ref) -} - -func TestQueryRoot(t *testing.T) { - assertQueryPositions(t, - "a = 42", - "$", - []interface{}{ - queryTestNode{ - map[string]interface{}{ - "a": int64(42), - }, toml.Position{1, 1}, - }, - }) -} - -func TestQueryKey(t *testing.T) { - assertQueryPositions(t, - "[foo]\na = 42", - "$.foo.a", - []interface{}{ - queryTestNode{ - int64(42), toml.Position{2, 1}, - }, - }) -} - -func TestQueryKeyString(t *testing.T) { - assertQueryPositions(t, - "[foo]\na = 42", - "$.foo['a']", - []interface{}{ - queryTestNode{ - int64(42), toml.Position{2, 1}, - }, - }) -} - -func TestQueryIndex(t *testing.T) { - assertQueryPositions(t, - "[foo]\na = [1,2,3,4,5,6,7,8,9,0]", - "$.foo.a[5]", - []interface{}{ - queryTestNode{ - int64(6), toml.Position{2, 1}, - }, - }) -} - -func TestQuerySliceRange(t *testing.T) { - assertQueryPositions(t, - "[foo]\na = [1,2,3,4,5,6,7,8,9,0]", - "$.foo.a[0:5]", - []interface{}{ - queryTestNode{ - int64(1), toml.Position{2, 1}, - }, - queryTestNode{ - int64(2), toml.Position{2, 1}, - }, - queryTestNode{ - int64(3), toml.Position{2, 1}, - }, - queryTestNode{ - int64(4), toml.Position{2, 1}, - }, - queryTestNode{ - int64(5), toml.Position{2, 1}, - }, - }) -} - -func TestQuerySliceStep(t *testing.T) { - assertQueryPositions(t, - "[foo]\na = [1,2,3,4,5,6,7,8,9,0]", - "$.foo.a[0:5:2]", - []interface{}{ - queryTestNode{ - int64(1), toml.Position{2, 1}, - }, - queryTestNode{ - int64(3), toml.Position{2, 1}, - }, - queryTestNode{ - int64(5), toml.Position{2, 1}, - }, - }) -} - -func TestQueryAny(t *testing.T) { - assertQueryPositions(t, - "[foo.bar]\na=1\nb=2\n[foo.baz]\na=3\nb=4", - "$.foo.*", - []interface{}{ - queryTestNode{ - map[string]interface{}{ - "a": int64(1), - "b": int64(2), - }, toml.Position{1, 1}, - }, - queryTestNode{ - map[string]interface{}{ - "a": int64(3), - "b": int64(4), - }, toml.Position{4, 1}, - }, - }) -} -func TestQueryUnionSimple(t *testing.T) { - assertQueryPositions(t, - "[foo.bar]\na=1\nb=2\n[baz.foo]\na=3\nb=4\n[gorf.foo]\na=5\nb=6", - "$.*[bar,foo]", - []interface{}{ - queryTestNode{ - map[string]interface{}{ - "a": int64(1), - "b": int64(2), - }, toml.Position{1, 1}, - }, - queryTestNode{ - map[string]interface{}{ - "a": int64(3), - "b": int64(4), - }, toml.Position{4, 1}, - }, - queryTestNode{ - map[string]interface{}{ - "a": int64(5), - "b": int64(6), - }, toml.Position{7, 1}, - }, - }) -} - -func TestQueryRecursionAll(t *testing.T) { - assertQueryPositions(t, - "[foo.bar]\na=1\nb=2\n[baz.foo]\na=3\nb=4\n[gorf.foo]\na=5\nb=6", - "$..*", - []interface{}{ - queryTestNode{ - map[string]interface{}{ - "foo": map[string]interface{}{ - "bar": map[string]interface{}{ - "a": int64(1), - "b": int64(2), - }, - }, - "baz": map[string]interface{}{ - "foo": map[string]interface{}{ - "a": int64(3), - "b": int64(4), - }, - }, - "gorf": map[string]interface{}{ - "foo": map[string]interface{}{ - "a": int64(5), - "b": int64(6), - }, - }, - }, toml.Position{1, 1}, - }, - queryTestNode{ - map[string]interface{}{ - "bar": map[string]interface{}{ - "a": int64(1), - "b": int64(2), - }, - }, toml.Position{1, 1}, - }, - queryTestNode{ - map[string]interface{}{ - "a": int64(1), - "b": int64(2), - }, toml.Position{1, 1}, - }, - queryTestNode{ - int64(1), toml.Position{2, 1}, - }, - queryTestNode{ - int64(2), toml.Position{3, 1}, - }, - queryTestNode{ - map[string]interface{}{ - "foo": map[string]interface{}{ - "a": int64(3), - "b": int64(4), - }, - }, toml.Position{4, 1}, - }, - queryTestNode{ - map[string]interface{}{ - "a": int64(3), - "b": int64(4), - }, toml.Position{4, 1}, - }, - queryTestNode{ - int64(3), toml.Position{5, 1}, - }, - queryTestNode{ - int64(4), toml.Position{6, 1}, - }, - queryTestNode{ - map[string]interface{}{ - "foo": map[string]interface{}{ - "a": int64(5), - "b": int64(6), - }, - }, toml.Position{7, 1}, - }, - queryTestNode{ - map[string]interface{}{ - "a": int64(5), - "b": int64(6), - }, toml.Position{7, 1}, - }, - queryTestNode{ - int64(5), toml.Position{8, 1}, - }, - queryTestNode{ - int64(6), toml.Position{9, 1}, - }, - }) -} - -func TestQueryRecursionUnionSimple(t *testing.T) { - assertQueryPositions(t, - "[foo.bar]\na=1\nb=2\n[baz.foo]\na=3\nb=4\n[gorf.foo]\na=5\nb=6", - "$..['foo','bar']", - []interface{}{ - queryTestNode{ - map[string]interface{}{ - "bar": map[string]interface{}{ - "a": int64(1), - "b": int64(2), - }, - }, toml.Position{1, 1}, - }, - queryTestNode{ - map[string]interface{}{ - "a": int64(3), - "b": int64(4), - }, toml.Position{4, 1}, - }, - queryTestNode{ - map[string]interface{}{ - "a": int64(1), - "b": int64(2), - }, toml.Position{1, 1}, - }, - queryTestNode{ - map[string]interface{}{ - "a": int64(5), - "b": int64(6), - }, toml.Position{7, 1}, - }, - }) -} - -func TestQueryFilterFn(t *testing.T) { - buff, err := ioutil.ReadFile("../example.toml") - if err != nil { - t.Error(err) - return - } - - assertQueryPositions(t, string(buff), - "$..[?(int)]", - []interface{}{ - queryTestNode{ - int64(8001), toml.Position{13, 1}, - }, - queryTestNode{ - int64(8001), toml.Position{13, 1}, - }, - queryTestNode{ - int64(8002), toml.Position{13, 1}, - }, - queryTestNode{ - int64(5000), toml.Position{14, 1}, - }, - }) - - assertQueryPositions(t, string(buff), - "$..[?(string)]", - []interface{}{ - queryTestNode{ - "TOML Example", toml.Position{3, 1}, - }, - queryTestNode{ - "Tom Preston-Werner", toml.Position{6, 1}, - }, - queryTestNode{ - "GitHub", toml.Position{7, 1}, - }, - queryTestNode{ - "GitHub Cofounder & CEO\nLikes tater tots and beer.", - toml.Position{8, 1}, - }, - queryTestNode{ - "192.168.1.1", toml.Position{12, 1}, - }, - queryTestNode{ - "10.0.0.1", toml.Position{21, 3}, - }, - queryTestNode{ - "eqdc10", toml.Position{22, 3}, - }, - queryTestNode{ - "10.0.0.2", toml.Position{25, 3}, - }, - queryTestNode{ - "eqdc10", toml.Position{26, 3}, - }, - }) - - assertQueryPositions(t, string(buff), - "$..[?(float)]", - []interface{}{ // no float values in document - }) - - tv, _ := time.Parse(time.RFC3339, "1979-05-27T07:32:00Z") - assertQueryPositions(t, string(buff), - "$..[?(tree)]", - []interface{}{ - queryTestNode{ - map[string]interface{}{ - "name": "Tom Preston-Werner", - "organization": "GitHub", - "bio": "GitHub Cofounder & CEO\nLikes tater tots and beer.", - "dob": tv, - }, toml.Position{5, 1}, - }, - queryTestNode{ - map[string]interface{}{ - "server": "192.168.1.1", - "ports": []interface{}{int64(8001), int64(8001), int64(8002)}, - "connection_max": int64(5000), - "enabled": true, - }, toml.Position{11, 1}, - }, - queryTestNode{ - map[string]interface{}{ - "alpha": map[string]interface{}{ - "ip": "10.0.0.1", - "dc": "eqdc10", - }, - "beta": map[string]interface{}{ - "ip": "10.0.0.2", - "dc": "eqdc10", - }, - }, toml.Position{17, 1}, - }, - queryTestNode{ - map[string]interface{}{ - "ip": "10.0.0.1", - "dc": "eqdc10", - }, toml.Position{20, 3}, - }, - queryTestNode{ - map[string]interface{}{ - "ip": "10.0.0.2", - "dc": "eqdc10", - }, toml.Position{24, 3}, - }, - queryTestNode{ - map[string]interface{}{ - "data": []interface{}{ - []interface{}{"gamma", "delta"}, - []interface{}{int64(1), int64(2)}, - }, - }, toml.Position{28, 1}, - }, - }) - - assertQueryPositions(t, string(buff), - "$..[?(time)]", - []interface{}{ - queryTestNode{ - tv, toml.Position{9, 1}, - }, - }) - - assertQueryPositions(t, string(buff), - "$..[?(bool)]", - []interface{}{ - queryTestNode{ - true, toml.Position{15, 1}, - }, - }) -} diff --git a/src/vendor/github.com/pelletier/go-toml/query/query.go b/src/vendor/github.com/pelletier/go-toml/query/query.go deleted file mode 100644 index 1c6cd801434e26ff7b26d8b203b4b85183d6ce31..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/query/query.go +++ /dev/null @@ -1,158 +0,0 @@ -package query - -import ( - "time" - - "github.com/pelletier/go-toml" -) - -// NodeFilterFn represents a user-defined filter function, for use with -// Query.SetFilter(). -// -// The return value of the function must indicate if 'node' is to be included -// at this stage of the TOML path. Returning true will include the node, and -// returning false will exclude it. -// -// NOTE: Care should be taken to write script callbacks such that they are safe -// to use from multiple goroutines. -type NodeFilterFn func(node interface{}) bool - -// Result is the result of Executing a Query. -type Result struct { - items []interface{} - positions []toml.Position -} - -// appends a value/position pair to the result set. -func (r *Result) appendResult(node interface{}, pos toml.Position) { - r.items = append(r.items, node) - r.positions = append(r.positions, pos) -} - -// Values is a set of values within a Result. The order of values is not -// guaranteed to be in document order, and may be different each time a query is -// executed. -func (r Result) Values() []interface{} { - return r.items -} - -// Positions is a set of positions for values within a Result. Each index -// in Positions() corresponds to the entry in Value() of the same index. -func (r Result) Positions() []toml.Position { - return r.positions -} - -// runtime context for executing query paths -type queryContext struct { - result *Result - filters *map[string]NodeFilterFn - lastPosition toml.Position -} - -// generic path functor interface -type pathFn interface { - setNext(next pathFn) - // it is the caller's responsibility to set the ctx.lastPosition before invoking call() - // node can be one of: *toml.Tree, []*toml.Tree, or a scalar - call(node interface{}, ctx *queryContext) -} - -// A Query is the representation of a compiled TOML path. A Query is safe -// for concurrent use by multiple goroutines. -type Query struct { - root pathFn - tail pathFn - filters *map[string]NodeFilterFn -} - -func newQuery() *Query { - return &Query{ - root: nil, - tail: nil, - filters: &defaultFilterFunctions, - } -} - -func (q *Query) appendPath(next pathFn) { - if q.root == nil { - q.root = next - } else { - q.tail.setNext(next) - } - q.tail = next - next.setNext(newTerminatingFn()) // init the next functor -} - -// Compile compiles a TOML path expression. The returned Query can be used -// to match elements within a Tree and its descendants. See Execute. -func Compile(path string) (*Query, error) { - return parseQuery(lexQuery(path)) -} - -// Execute executes a query against a Tree, and returns the result of the query. -func (q *Query) Execute(tree *toml.Tree) *Result { - result := &Result{ - items: []interface{}{}, - positions: []toml.Position{}, - } - if q.root == nil { - result.appendResult(tree, tree.GetPosition("")) - } else { - ctx := &queryContext{ - result: result, - filters: q.filters, - } - ctx.lastPosition = tree.Position() - q.root.call(tree, ctx) - } - return result -} - -// CompileAndExecute is a shorthand for Compile(path) followed by Execute(tree). -func CompileAndExecute(path string, tree *toml.Tree) (*Result, error) { - query, err := Compile(path) - if err != nil { - return nil, err - } - return query.Execute(tree), nil -} - -// SetFilter sets a user-defined filter function. These may be used inside -// "?(..)" query expressions to filter TOML document elements within a query. -func (q *Query) SetFilter(name string, fn NodeFilterFn) { - if q.filters == &defaultFilterFunctions { - // clone the static table - q.filters = &map[string]NodeFilterFn{} - for k, v := range defaultFilterFunctions { - (*q.filters)[k] = v - } - } - (*q.filters)[name] = fn -} - -var defaultFilterFunctions = map[string]NodeFilterFn{ - "tree": func(node interface{}) bool { - _, ok := node.(*toml.Tree) - return ok - }, - "int": func(node interface{}) bool { - _, ok := node.(int64) - return ok - }, - "float": func(node interface{}) bool { - _, ok := node.(float64) - return ok - }, - "string": func(node interface{}) bool { - _, ok := node.(string) - return ok - }, - "time": func(node interface{}) bool { - _, ok := node.(time.Time) - return ok - }, - "bool": func(node interface{}) bool { - _, ok := node.(bool) - return ok - }, -} diff --git a/src/vendor/github.com/pelletier/go-toml/query/query_test.go b/src/vendor/github.com/pelletier/go-toml/query/query_test.go deleted file mode 100644 index 903a8dc731b32e9d117fc0f4ab18c6a98712293e..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/query/query_test.go +++ /dev/null @@ -1,157 +0,0 @@ -package query - -import ( - "fmt" - "testing" - - "github.com/pelletier/go-toml" -) - -func assertArrayContainsInAnyOrder(t *testing.T, array []interface{}, objects ...interface{}) { - if len(array) != len(objects) { - t.Fatalf("array contains %d objects but %d are expected", len(array), len(objects)) - } - - for _, o := range objects { - found := false - for _, a := range array { - if a == o { - found = true - break - } - } - if !found { - t.Fatal(o, "not found in array", array) - } - } -} - -func TestQueryExample(t *testing.T) { - config, _ := toml.Load(` - [[book]] - title = "The Stand" - author = "Stephen King" - [[book]] - title = "For Whom the Bell Tolls" - author = "Ernest Hemmingway" - [[book]] - title = "Neuromancer" - author = "William Gibson" - `) - authors, err := CompileAndExecute("$.book.author", config) - if err != nil { - t.Fatal("unexpected error:", err) - } - names := authors.Values() - if len(names) != 3 { - t.Fatalf("query should return 3 names but returned %d", len(names)) - } - assertArrayContainsInAnyOrder(t, names, "Stephen King", "Ernest Hemmingway", "William Gibson") -} - -func TestQueryReadmeExample(t *testing.T) { - config, _ := toml.Load(` -[postgres] -user = "pelletier" -password = "mypassword" -`) - - query, err := Compile("$..[user,password]") - if err != nil { - t.Fatal("unexpected error:", err) - } - results := query.Execute(config) - values := results.Values() - if len(values) != 2 { - t.Fatalf("query should return 2 values but returned %d", len(values)) - } - assertArrayContainsInAnyOrder(t, values, "pelletier", "mypassword") -} - -func TestQueryPathNotPresent(t *testing.T) { - config, _ := toml.Load(`a = "hello"`) - query, err := Compile("$.foo.bar") - if err != nil { - t.Fatal("unexpected error:", err) - } - results := query.Execute(config) - if err != nil { - t.Fatalf("err should be nil. got %s instead", err) - } - if len(results.items) != 0 { - t.Fatalf("no items should be matched. %d matched instead", len(results.items)) - } -} - -func ExampleNodeFilterFn_filterExample() { - tree, _ := toml.Load(` - [struct_one] - foo = "foo" - bar = "bar" - - [struct_two] - baz = "baz" - gorf = "gorf" - `) - - // create a query that references a user-defined-filter - query, _ := Compile("$[?(bazOnly)]") - - // define the filter, and assign it to the query - query.SetFilter("bazOnly", func(node interface{}) bool { - if tree, ok := node.(*toml.Tree); ok { - return tree.Has("baz") - } - return false // reject all other node types - }) - - // results contain only the 'struct_two' Tree - query.Execute(tree) -} - -func ExampleQuery_queryExample() { - config, _ := toml.Load(` - [[book]] - title = "The Stand" - author = "Stephen King" - [[book]] - title = "For Whom the Bell Tolls" - author = "Ernest Hemmingway" - [[book]] - title = "Neuromancer" - author = "William Gibson" - `) - - // find and print all the authors in the document - query, _ := Compile("$.book.author") - authors := query.Execute(config) - for _, name := range authors.Values() { - fmt.Println(name) - } -} - -func TestTomlQuery(t *testing.T) { - tree, err := toml.Load("[foo.bar]\na=1\nb=2\n[baz.foo]\na=3\nb=4\n[gorf.foo]\na=5\nb=6") - if err != nil { - t.Error(err) - return - } - query, err := Compile("$.foo.bar") - if err != nil { - t.Error(err) - return - } - result := query.Execute(tree) - values := result.Values() - if len(values) != 1 { - t.Errorf("Expected resultset of 1, got %d instead: %v", len(values), values) - } - - if tt, ok := values[0].(*toml.Tree); !ok { - t.Errorf("Expected type of Tree: %T", values[0]) - } else if tt.Get("a") != int64(1) { - t.Errorf("Expected 'a' with a value 1: %v", tt.Get("a")) - } else if tt.Get("b") != int64(2) { - t.Errorf("Expected 'b' with a value 2: %v", tt.Get("b")) - } -} diff --git a/src/vendor/github.com/pelletier/go-toml/query/tokens.go b/src/vendor/github.com/pelletier/go-toml/query/tokens.go deleted file mode 100644 index 9ae579de2d46a199663ad329bf2a411023613375..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/query/tokens.go +++ /dev/null @@ -1,106 +0,0 @@ -package query - -import ( - "fmt" - "github.com/pelletier/go-toml" - "strconv" - "unicode" -) - -// Define tokens -type tokenType int - -const ( - eof = -(iota + 1) -) - -const ( - tokenError tokenType = iota - tokenEOF - tokenKey - tokenString - tokenInteger - tokenFloat - tokenLeftBracket - tokenRightBracket - tokenLeftParen - tokenRightParen - tokenComma - tokenColon - tokenDollar - tokenStar - tokenQuestion - tokenDot - tokenDotDot -) - -var tokenTypeNames = []string{ - "Error", - "EOF", - "Key", - "String", - "Integer", - "Float", - "[", - "]", - "(", - ")", - ",", - ":", - "$", - "*", - "?", - ".", - "..", -} - -type token struct { - toml.Position - typ tokenType - val string -} - -func (tt tokenType) String() string { - idx := int(tt) - if idx < len(tokenTypeNames) { - return tokenTypeNames[idx] - } - return "Unknown" -} - -func (t token) Int() int { - if result, err := strconv.Atoi(t.val); err != nil { - panic(err) - } else { - return result - } -} - -func (t token) String() string { - switch t.typ { - case tokenEOF: - return "EOF" - case tokenError: - return t.val - } - - return fmt.Sprintf("%q", t.val) -} - -func isSpace(r rune) bool { - return r == ' ' || r == '\t' -} - -func isAlphanumeric(r rune) bool { - return unicode.IsLetter(r) || r == '_' -} - -func isDigit(r rune) bool { - return unicode.IsNumber(r) -} - -func isHexDigit(r rune) bool { - return isDigit(r) || - (r >= 'a' && r <= 'f') || - (r >= 'A' && r <= 'F') -} diff --git a/src/vendor/github.com/pelletier/go-toml/token_test.go b/src/vendor/github.com/pelletier/go-toml/token_test.go deleted file mode 100644 index 20b560d510b934c5c70530d1277d2cc0a45c97ad..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/token_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package toml - -import "testing" - -func TestTokenStringer(t *testing.T) { - var tests = []struct { - tt tokenType - expect string - }{ - {tokenError, "Error"}, - {tokenEOF, "EOF"}, - {tokenComment, "Comment"}, - {tokenKey, "Key"}, - {tokenString, "String"}, - {tokenInteger, "Integer"}, - {tokenTrue, "True"}, - {tokenFalse, "False"}, - {tokenFloat, "Float"}, - {tokenEqual, "="}, - {tokenLeftBracket, "["}, - {tokenRightBracket, "]"}, - {tokenLeftCurlyBrace, "{"}, - {tokenRightCurlyBrace, "}"}, - {tokenLeftParen, "("}, - {tokenRightParen, ")"}, - {tokenDoubleLeftBracket, "]]"}, - {tokenDoubleRightBracket, "[["}, - {tokenDate, "Date"}, - {tokenKeyGroup, "KeyGroup"}, - {tokenKeyGroupArray, "KeyGroupArray"}, - {tokenComma, ","}, - {tokenColon, ":"}, - {tokenDollar, "$"}, - {tokenStar, "*"}, - {tokenQuestion, "?"}, - {tokenDot, "."}, - {tokenDotDot, ".."}, - {tokenEOL, "EOL"}, - {tokenEOL + 1, "Unknown"}, - } - - for i, test := range tests { - got := test.tt.String() - if got != test.expect { - t.Errorf("[%d] invalid string of token type; got %q, expected %q", i, got, test.expect) - } - } -} - -func TestTokenString(t *testing.T) { - var tests = []struct { - tok token - expect string - }{ - {token{Position{1, 1}, tokenEOF, ""}, "EOF"}, - {token{Position{1, 1}, tokenError, "Δt"}, "Δt"}, - {token{Position{1, 1}, tokenString, "bar"}, `"bar"`}, - {token{Position{1, 1}, tokenString, "123456789012345"}, `"123456789012345"`}, - } - - for i, test := range tests { - got := test.tok.String() - if got != test.expect { - t.Errorf("[%d] invalid of string token; got %q, expected %q", i, got, test.expect) - } - } -} diff --git a/src/vendor/github.com/pelletier/go-toml/toml_test.go b/src/vendor/github.com/pelletier/go-toml/toml_test.go deleted file mode 100644 index 81c395413152c59bfa4169a13b90d9d6804c91ed..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/toml_test.go +++ /dev/null @@ -1,180 +0,0 @@ -// Testing support for go-toml - -package toml - -import ( - "testing" -) - -func TestTomlHas(t *testing.T) { - tree, _ := Load(` - [test] - key = "value" - `) - - if !tree.Has("test.key") { - t.Errorf("Has - expected test.key to exists") - } - - if tree.Has("") { - t.Errorf("Should return false if the key is not provided") - } -} - -func TestTomlGet(t *testing.T) { - tree, _ := Load(` - [test] - key = "value" - `) - - if tree.Get("") != tree { - t.Errorf("Get should return the tree itself when given an empty path") - } - - if tree.Get("test.key") != "value" { - t.Errorf("Get should return the value") - } - if tree.Get(`\`) != nil { - t.Errorf("should return nil when the key is malformed") - } -} - -func TestTomlGetDefault(t *testing.T) { - tree, _ := Load(` - [test] - key = "value" - `) - - if tree.GetDefault("", "hello") != tree { - t.Error("GetDefault should return the tree itself when given an empty path") - } - - if tree.GetDefault("test.key", "hello") != "value" { - t.Error("Get should return the value") - } - - if tree.GetDefault("whatever", "hello") != "hello" { - t.Error("GetDefault should return the default value if the key does not exist") - } -} - -func TestTomlHasPath(t *testing.T) { - tree, _ := Load(` - [test] - key = "value" - `) - - if !tree.HasPath([]string{"test", "key"}) { - t.Errorf("HasPath - expected test.key to exists") - } -} - -func TestTomlDelete(t *testing.T) { - tree, _ := Load(` - key = "value" - `) - err := tree.Delete("key") - if err != nil { - t.Errorf("Delete - unexpected error while deleting key: %s", err.Error()) - } - - if tree.Get("key") != nil { - t.Errorf("Delete should have removed key but did not.") - } - -} - -func TestTomlDeleteUnparsableKey(t *testing.T) { - tree, _ := Load(` - key = "value" - `) - err := tree.Delete(".") - if err == nil { - t.Errorf("Delete should error") - } -} - -func TestTomlDeleteNestedKey(t *testing.T) { - tree, _ := Load(` - [foo] - [foo.bar] - key = "value" - `) - err := tree.Delete("foo.bar.key") - if err != nil { - t.Errorf("Error while deleting nested key: %s", err.Error()) - } - - if tree.Get("key") != nil { - t.Errorf("Delete should have removed nested key but did not.") - } - -} - -func TestTomlDeleteNonexistentNestedKey(t *testing.T) { - tree, _ := Load(` - [foo] - [foo.bar] - key = "value" - `) - err := tree.Delete("foo.not.there.key") - if err == nil { - t.Errorf("Delete should have thrown an error trying to delete key in nonexistent tree") - } -} - -func TestTomlGetPath(t *testing.T) { - node := newTree() - //TODO: set other node data - - for idx, item := range []struct { - Path []string - Expected *Tree - }{ - { // empty path test - []string{}, - node, - }, - } { - result := node.GetPath(item.Path) - if result != item.Expected { - t.Errorf("GetPath[%d] %v - expected %v, got %v instead.", idx, item.Path, item.Expected, result) - } - } - - tree, _ := Load("[foo.bar]\na=1\nb=2\n[baz.foo]\na=3\nb=4\n[gorf.foo]\na=5\nb=6") - if tree.GetPath([]string{"whatever"}) != nil { - t.Error("GetPath should return nil when the key does not exist") - } -} - -func TestTomlFromMap(t *testing.T) { - simpleMap := map[string]interface{}{"hello": 42} - tree, err := TreeFromMap(simpleMap) - if err != nil { - t.Fatal("unexpected error:", err) - } - if tree.Get("hello") != int64(42) { - t.Fatal("hello should be 42, not", tree.Get("hello")) - } -} - -func TestLoadBytesBOM(t *testing.T) { - payloads := [][]byte{ - []byte("\xFE\xFFhello=1"), - []byte("\xFF\xFEhello=1"), - []byte("\xEF\xBB\xBFhello=1"), - []byte("\x00\x00\xFE\xFFhello=1"), - []byte("\xFF\xFE\x00\x00hello=1"), - } - for _, data := range payloads { - tree, err := LoadBytes(data) - if err != nil { - t.Fatal("unexpected error:", err, "for:", data) - } - v := tree.Get("hello") - if v != int64(1) { - t.Fatal("hello should be 1, not", v) - } - } -} diff --git a/src/vendor/github.com/pelletier/go-toml/toml_testgen_support_test.go b/src/vendor/github.com/pelletier/go-toml/toml_testgen_support_test.go deleted file mode 100644 index eef9b9faa892e306fdd5b77f32a3b17b5df29f8d..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/toml_testgen_support_test.go +++ /dev/null @@ -1,119 +0,0 @@ -// This is a support file for toml_testgen_test.go -package toml - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "testing" - "time" - - "github.com/davecgh/go-spew/spew" -) - -func testgenInvalid(t *testing.T, input string) { - t.Logf("Input TOML:\n%s", input) - tree, err := Load(input) - if err != nil { - return - } - - typedTree := testgenTranslate(*tree) - - buf := new(bytes.Buffer) - if err := json.NewEncoder(buf).Encode(typedTree); err != nil { - return - } - - t.Fatalf("test did not fail. resulting tree:\n%s", buf.String()) -} - -func testgenValid(t *testing.T, input string, jsonRef string) { - t.Logf("Input TOML:\n%s", input) - tree, err := Load(input) - if err != nil { - t.Fatalf("failed parsing toml: %s", err) - } - - typedTree := testgenTranslate(*tree) - - buf := new(bytes.Buffer) - if err := json.NewEncoder(buf).Encode(typedTree); err != nil { - t.Fatalf("failed translating to JSON: %s", err) - } - - var jsonTest interface{} - if err := json.NewDecoder(buf).Decode(&jsonTest); err != nil { - t.Logf("translated JSON:\n%s", buf.String()) - t.Fatalf("failed decoding translated JSON: %s", err) - } - - var jsonExpected interface{} - if err := json.NewDecoder(bytes.NewBufferString(jsonRef)).Decode(&jsonExpected); err != nil { - t.Logf("reference JSON:\n%s", jsonRef) - t.Fatalf("failed decoding reference JSON: %s", err) - } - - if !reflect.DeepEqual(jsonExpected, jsonTest) { - t.Logf("Diff:\n%s", spew.Sdump(jsonExpected, jsonTest)) - t.Fatal("parsed TOML tree is different than expected structure") - } -} - -func testgenTranslate(tomlData interface{}) interface{} { - switch orig := tomlData.(type) { - case map[string]interface{}: - typed := make(map[string]interface{}, len(orig)) - for k, v := range orig { - typed[k] = testgenTranslate(v) - } - return typed - case *Tree: - return testgenTranslate(*orig) - case Tree: - keys := orig.Keys() - typed := make(map[string]interface{}, len(keys)) - for _, k := range keys { - typed[k] = testgenTranslate(orig.GetPath([]string{k})) - } - return typed - case []*Tree: - typed := make([]map[string]interface{}, len(orig)) - for i, v := range orig { - typed[i] = testgenTranslate(v).(map[string]interface{}) - } - return typed - case []map[string]interface{}: - typed := make([]map[string]interface{}, len(orig)) - for i, v := range orig { - typed[i] = testgenTranslate(v).(map[string]interface{}) - } - return typed - case []interface{}: - typed := make([]interface{}, len(orig)) - for i, v := range orig { - typed[i] = testgenTranslate(v) - } - return testgenTag("array", typed) - case time.Time: - return testgenTag("datetime", orig.Format("2006-01-02T15:04:05Z")) - case bool: - return testgenTag("bool", fmt.Sprintf("%v", orig)) - case int64: - return testgenTag("integer", fmt.Sprintf("%d", orig)) - case float64: - return testgenTag("float", fmt.Sprintf("%v", orig)) - case string: - return testgenTag("string", orig) - } - - panic(fmt.Sprintf("Unknown type: %T", tomlData)) -} - -func testgenTag(typeName string, data interface{}) map[string]interface{} { - return map[string]interface{}{ - "type": typeName, - "value": data, - } -} diff --git a/src/vendor/github.com/pelletier/go-toml/toml_testgen_test.go b/src/vendor/github.com/pelletier/go-toml/toml_testgen_test.go deleted file mode 100644 index 688ae513e2b020c9b7d4c8b2d7e147810f75ba85..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/toml_testgen_test.go +++ /dev/null @@ -1,943 +0,0 @@ -// Generated by tomltestgen for toml-test ref 39e37e6 on 2019-03-19T23:58:45-07:00 -package toml - -import ( - "testing" -) - -func TestInvalidArrayMixedTypesArraysAndInts(t *testing.T) { - input := `arrays-and-ints = [1, ["Arrays are not integers."]]` - testgenInvalid(t, input) -} - -func TestInvalidArrayMixedTypesIntsAndFloats(t *testing.T) { - input := `ints-and-floats = [1, 1.1]` - testgenInvalid(t, input) -} - -func TestInvalidArrayMixedTypesStringsAndInts(t *testing.T) { - input := `strings-and-ints = ["hi", 42]` - testgenInvalid(t, input) -} - -func TestInvalidDatetimeMalformedNoLeads(t *testing.T) { - input := `no-leads = 1987-7-05T17:45:00Z` - testgenInvalid(t, input) -} - -func TestInvalidDatetimeMalformedNoSecs(t *testing.T) { - input := `no-secs = 1987-07-05T17:45Z` - testgenInvalid(t, input) -} - -func TestInvalidDatetimeMalformedNoT(t *testing.T) { - input := `no-t = 1987-07-0517:45:00Z` - testgenInvalid(t, input) -} - -func TestInvalidDatetimeMalformedWithMilli(t *testing.T) { - input := `with-milli = 1987-07-5T17:45:00.12Z` - testgenInvalid(t, input) -} - -func TestInvalidDuplicateKeyTable(t *testing.T) { - input := `[fruit] -type = "apple" - -[fruit.type] -apple = "yes"` - testgenInvalid(t, input) -} - -func TestInvalidDuplicateKeys(t *testing.T) { - input := `dupe = false -dupe = true` - testgenInvalid(t, input) -} - -func TestInvalidDuplicateTables(t *testing.T) { - input := `[a] -[a]` - testgenInvalid(t, input) -} - -func TestInvalidEmptyImplicitTable(t *testing.T) { - input := `[naughty..naughty]` - testgenInvalid(t, input) -} - -func TestInvalidEmptyTable(t *testing.T) { - input := `[]` - testgenInvalid(t, input) -} - -func TestInvalidFloatNoLeadingZero(t *testing.T) { - input := `answer = .12345 -neganswer = -.12345` - testgenInvalid(t, input) -} - -func TestInvalidFloatNoTrailingDigits(t *testing.T) { - input := `answer = 1. -neganswer = -1.` - testgenInvalid(t, input) -} - -func TestInvalidKeyEmpty(t *testing.T) { - input := ` = 1` - testgenInvalid(t, input) -} - -func TestInvalidKeyHash(t *testing.T) { - input := `a# = 1` - testgenInvalid(t, input) -} - -func TestInvalidKeyNewline(t *testing.T) { - input := `a -= 1` - testgenInvalid(t, input) -} - -func TestInvalidKeyOpenBracket(t *testing.T) { - input := `[abc = 1` - testgenInvalid(t, input) -} - -func TestInvalidKeySingleOpenBracket(t *testing.T) { - input := `[` - testgenInvalid(t, input) -} - -func TestInvalidKeySpace(t *testing.T) { - input := `a b = 1` - testgenInvalid(t, input) -} - -func TestInvalidKeyStartBracket(t *testing.T) { - input := `[a] -[xyz = 5 -[b]` - testgenInvalid(t, input) -} - -func TestInvalidKeyTwoEquals(t *testing.T) { - input := `key= = 1` - testgenInvalid(t, input) -} - -func TestInvalidStringBadByteEscape(t *testing.T) { - input := `naughty = "\xAg"` - testgenInvalid(t, input) -} - -func TestInvalidStringBadEscape(t *testing.T) { - input := `invalid-escape = "This string has a bad \a escape character."` - testgenInvalid(t, input) -} - -func TestInvalidStringByteEscapes(t *testing.T) { - input := `answer = "\x33"` - testgenInvalid(t, input) -} - -func TestInvalidStringNoClose(t *testing.T) { - input := `no-ending-quote = "One time, at band camp` - testgenInvalid(t, input) -} - -func TestInvalidTableArrayImplicit(t *testing.T) { - input := "# This test is a bit tricky. It should fail because the first use of\n" + - "# `[[albums.songs]]` without first declaring `albums` implies that `albums`\n" + - "# must be a table. The alternative would be quite weird. Namely, it wouldn't\n" + - "# comply with the TOML spec: \"Each double-bracketed sub-table will belong to \n" + - "# the most *recently* defined table element *above* it.\"\n" + - "#\n" + - "# This is in contrast to the *valid* test, table-array-implicit where\n" + - "# `[[albums.songs]]` works by itself, so long as `[[albums]]` isn't declared\n" + - "# later. (Although, `[albums]` could be.)\n" + - "[[albums.songs]]\n" + - "name = \"Glory Days\"\n" + - "\n" + - "[[albums]]\n" + - "name = \"Born in the USA\"\n" - testgenInvalid(t, input) -} - -func TestInvalidTableArrayMalformedBracket(t *testing.T) { - input := `[[albums] -name = "Born to Run"` - testgenInvalid(t, input) -} - -func TestInvalidTableArrayMalformedEmpty(t *testing.T) { - input := `[[]] -name = "Born to Run"` - testgenInvalid(t, input) -} - -func TestInvalidTableEmpty(t *testing.T) { - input := `[]` - testgenInvalid(t, input) -} - -func TestInvalidTableNestedBracketsClose(t *testing.T) { - input := `[a]b] -zyx = 42` - testgenInvalid(t, input) -} - -func TestInvalidTableNestedBracketsOpen(t *testing.T) { - input := `[a[b] -zyx = 42` - testgenInvalid(t, input) -} - -func TestInvalidTableWhitespace(t *testing.T) { - input := `[invalid key]` - testgenInvalid(t, input) -} - -func TestInvalidTableWithPound(t *testing.T) { - input := `[key#group] -answer = 42` - testgenInvalid(t, input) -} - -func TestInvalidTextAfterArrayEntries(t *testing.T) { - input := `array = [ - "Is there life after an array separator?", No - "Entry" -]` - testgenInvalid(t, input) -} - -func TestInvalidTextAfterInteger(t *testing.T) { - input := `answer = 42 the ultimate answer?` - testgenInvalid(t, input) -} - -func TestInvalidTextAfterString(t *testing.T) { - input := `string = "Is there life after strings?" No.` - testgenInvalid(t, input) -} - -func TestInvalidTextAfterTable(t *testing.T) { - input := `[error] this shouldn't be here` - testgenInvalid(t, input) -} - -func TestInvalidTextBeforeArraySeparator(t *testing.T) { - input := `array = [ - "Is there life before an array separator?" No, - "Entry" -]` - testgenInvalid(t, input) -} - -func TestInvalidTextInArray(t *testing.T) { - input := `array = [ - "Entry 1", - I don't belong, - "Entry 2", -]` - testgenInvalid(t, input) -} - -func TestValidArrayEmpty(t *testing.T) { - input := `thevoid = [[[[[]]]]]` - jsonRef := `{ - "thevoid": { "type": "array", "value": [ - {"type": "array", "value": [ - {"type": "array", "value": [ - {"type": "array", "value": [ - {"type": "array", "value": []} - ]} - ]} - ]} - ]} -}` - testgenValid(t, input, jsonRef) -} - -func TestValidArrayNospaces(t *testing.T) { - input := `ints = [1,2,3]` - jsonRef := `{ - "ints": { - "type": "array", - "value": [ - {"type": "integer", "value": "1"}, - {"type": "integer", "value": "2"}, - {"type": "integer", "value": "3"} - ] - } -}` - testgenValid(t, input, jsonRef) -} - -func TestValidArraysHetergeneous(t *testing.T) { - input := `mixed = [[1, 2], ["a", "b"], [1.1, 2.1]]` - jsonRef := `{ - "mixed": { - "type": "array", - "value": [ - {"type": "array", "value": [ - {"type": "integer", "value": "1"}, - {"type": "integer", "value": "2"} - ]}, - {"type": "array", "value": [ - {"type": "string", "value": "a"}, - {"type": "string", "value": "b"} - ]}, - {"type": "array", "value": [ - {"type": "float", "value": "1.1"}, - {"type": "float", "value": "2.1"} - ]} - ] - } -}` - testgenValid(t, input, jsonRef) -} - -func TestValidArraysNested(t *testing.T) { - input := `nest = [["a"], ["b"]]` - jsonRef := `{ - "nest": { - "type": "array", - "value": [ - {"type": "array", "value": [ - {"type": "string", "value": "a"} - ]}, - {"type": "array", "value": [ - {"type": "string", "value": "b"} - ]} - ] - } -}` - testgenValid(t, input, jsonRef) -} - -func TestValidArrays(t *testing.T) { - input := `ints = [1, 2, 3] -floats = [1.1, 2.1, 3.1] -strings = ["a", "b", "c"] -dates = [ - 1987-07-05T17:45:00Z, - 1979-05-27T07:32:00Z, - 2006-06-01T11:00:00Z, -]` - jsonRef := `{ - "ints": { - "type": "array", - "value": [ - {"type": "integer", "value": "1"}, - {"type": "integer", "value": "2"}, - {"type": "integer", "value": "3"} - ] - }, - "floats": { - "type": "array", - "value": [ - {"type": "float", "value": "1.1"}, - {"type": "float", "value": "2.1"}, - {"type": "float", "value": "3.1"} - ] - }, - "strings": { - "type": "array", - "value": [ - {"type": "string", "value": "a"}, - {"type": "string", "value": "b"}, - {"type": "string", "value": "c"} - ] - }, - "dates": { - "type": "array", - "value": [ - {"type": "datetime", "value": "1987-07-05T17:45:00Z"}, - {"type": "datetime", "value": "1979-05-27T07:32:00Z"}, - {"type": "datetime", "value": "2006-06-01T11:00:00Z"} - ] - } -}` - testgenValid(t, input, jsonRef) -} - -func TestValidBool(t *testing.T) { - input := `t = true -f = false` - jsonRef := `{ - "f": {"type": "bool", "value": "false"}, - "t": {"type": "bool", "value": "true"} -}` - testgenValid(t, input, jsonRef) -} - -func TestValidCommentsEverywhere(t *testing.T) { - input := `# Top comment. - # Top comment. -# Top comment. - -# [no-extraneous-groups-please] - -[group] # Comment -answer = 42 # Comment -# no-extraneous-keys-please = 999 -# Inbetween comment. -more = [ # Comment - # What about multiple # comments? - # Can you handle it? - # - # Evil. -# Evil. - 42, 42, # Comments within arrays are fun. - # What about multiple # comments? - # Can you handle it? - # - # Evil. -# Evil. -# ] Did I fool you? -] # Hopefully not.` - jsonRef := `{ - "group": { - "answer": {"type": "integer", "value": "42"}, - "more": { - "type": "array", - "value": [ - {"type": "integer", "value": "42"}, - {"type": "integer", "value": "42"} - ] - } - } -}` - testgenValid(t, input, jsonRef) -} - -func TestValidDatetime(t *testing.T) { - input := `bestdayever = 1987-07-05T17:45:00Z` - jsonRef := `{ - "bestdayever": {"type": "datetime", "value": "1987-07-05T17:45:00Z"} -}` - testgenValid(t, input, jsonRef) -} - -func TestValidEmpty(t *testing.T) { - input := `` - jsonRef := `{}` - testgenValid(t, input, jsonRef) -} - -func TestValidExample(t *testing.T) { - input := `best-day-ever = 1987-07-05T17:45:00Z - -[numtheory] -boring = false -perfection = [6, 28, 496]` - jsonRef := `{ - "best-day-ever": {"type": "datetime", "value": "1987-07-05T17:45:00Z"}, - "numtheory": { - "boring": {"type": "bool", "value": "false"}, - "perfection": { - "type": "array", - "value": [ - {"type": "integer", "value": "6"}, - {"type": "integer", "value": "28"}, - {"type": "integer", "value": "496"} - ] - } - } -}` - testgenValid(t, input, jsonRef) -} - -func TestValidFloat(t *testing.T) { - input := `pi = 3.14 -negpi = -3.14` - jsonRef := `{ - "pi": {"type": "float", "value": "3.14"}, - "negpi": {"type": "float", "value": "-3.14"} -}` - testgenValid(t, input, jsonRef) -} - -func TestValidImplicitAndExplicitAfter(t *testing.T) { - input := `[a.b.c] -answer = 42 - -[a] -better = 43` - jsonRef := `{ - "a": { - "better": {"type": "integer", "value": "43"}, - "b": { - "c": { - "answer": {"type": "integer", "value": "42"} - } - } - } -}` - testgenValid(t, input, jsonRef) -} - -func TestValidImplicitAndExplicitBefore(t *testing.T) { - input := `[a] -better = 43 - -[a.b.c] -answer = 42` - jsonRef := `{ - "a": { - "better": {"type": "integer", "value": "43"}, - "b": { - "c": { - "answer": {"type": "integer", "value": "42"} - } - } - } -}` - testgenValid(t, input, jsonRef) -} - -func TestValidImplicitGroups(t *testing.T) { - input := `[a.b.c] -answer = 42` - jsonRef := `{ - "a": { - "b": { - "c": { - "answer": {"type": "integer", "value": "42"} - } - } - } -}` - testgenValid(t, input, jsonRef) -} - -func TestValidInteger(t *testing.T) { - input := `answer = 42 -neganswer = -42` - jsonRef := `{ - "answer": {"type": "integer", "value": "42"}, - "neganswer": {"type": "integer", "value": "-42"} -}` - testgenValid(t, input, jsonRef) -} - -func TestValidKeyEqualsNospace(t *testing.T) { - input := `answer=42` - jsonRef := `{ - "answer": {"type": "integer", "value": "42"} -}` - testgenValid(t, input, jsonRef) -} - -func TestValidKeySpace(t *testing.T) { - input := `"a b" = 1` - jsonRef := `{ - "a b": {"type": "integer", "value": "1"} -}` - testgenValid(t, input, jsonRef) -} - -func TestValidKeySpecialChars(t *testing.T) { - input := "\"~!@$^&*()_+-`1234567890[]|/?><.,;:'\" = 1\n" - jsonRef := "{\n" + - " \"~!@$^&*()_+-`1234567890[]|/?><.,;:'\": {\n" + - " \"type\": \"integer\", \"value\": \"1\"\n" + - " }\n" + - "}\n" - testgenValid(t, input, jsonRef) -} - -func TestValidLongFloat(t *testing.T) { - input := `longpi = 3.141592653589793 -neglongpi = -3.141592653589793` - jsonRef := `{ - "longpi": {"type": "float", "value": "3.141592653589793"}, - "neglongpi": {"type": "float", "value": "-3.141592653589793"} -}` - testgenValid(t, input, jsonRef) -} - -func TestValidLongInteger(t *testing.T) { - input := `answer = 9223372036854775807 -neganswer = -9223372036854775808` - jsonRef := `{ - "answer": {"type": "integer", "value": "9223372036854775807"}, - "neganswer": {"type": "integer", "value": "-9223372036854775808"} -}` - testgenValid(t, input, jsonRef) -} - -func TestValidMultilineString(t *testing.T) { - input := `multiline_empty_one = """""" -multiline_empty_two = """ -""" -multiline_empty_three = """\ - """ -multiline_empty_four = """\ - \ - \ - """ - -equivalent_one = "The quick brown fox jumps over the lazy dog." -equivalent_two = """ -The quick brown \ - - - fox jumps over \ - the lazy dog.""" - -equivalent_three = """\ - The quick brown \ - fox jumps over \ - the lazy dog.\ - """` - jsonRef := `{ - "multiline_empty_one": { - "type": "string", - "value": "" - }, - "multiline_empty_two": { - "type": "string", - "value": "" - }, - "multiline_empty_three": { - "type": "string", - "value": "" - }, - "multiline_empty_four": { - "type": "string", - "value": "" - }, - "equivalent_one": { - "type": "string", - "value": "The quick brown fox jumps over the lazy dog." - }, - "equivalent_two": { - "type": "string", - "value": "The quick brown fox jumps over the lazy dog." - }, - "equivalent_three": { - "type": "string", - "value": "The quick brown fox jumps over the lazy dog." - } -}` - testgenValid(t, input, jsonRef) -} - -func TestValidRawMultilineString(t *testing.T) { - input := `oneline = '''This string has a ' quote character.''' -firstnl = ''' -This string has a ' quote character.''' -multiline = ''' -This string -has ' a quote character -and more than -one newline -in it.'''` - jsonRef := `{ - "oneline": { - "type": "string", - "value": "This string has a ' quote character." - }, - "firstnl": { - "type": "string", - "value": "This string has a ' quote character." - }, - "multiline": { - "type": "string", - "value": "This string\nhas ' a quote character\nand more than\none newline\nin it." - } -}` - testgenValid(t, input, jsonRef) -} - -func TestValidRawString(t *testing.T) { - input := `backspace = 'This string has a \b backspace character.' -tab = 'This string has a \t tab character.' -newline = 'This string has a \n new line character.' -formfeed = 'This string has a \f form feed character.' -carriage = 'This string has a \r carriage return character.' -slash = 'This string has a \/ slash character.' -backslash = 'This string has a \\ backslash character.'` - jsonRef := `{ - "backspace": { - "type": "string", - "value": "This string has a \\b backspace character." - }, - "tab": { - "type": "string", - "value": "This string has a \\t tab character." - }, - "newline": { - "type": "string", - "value": "This string has a \\n new line character." - }, - "formfeed": { - "type": "string", - "value": "This string has a \\f form feed character." - }, - "carriage": { - "type": "string", - "value": "This string has a \\r carriage return character." - }, - "slash": { - "type": "string", - "value": "This string has a \\/ slash character." - }, - "backslash": { - "type": "string", - "value": "This string has a \\\\ backslash character." - } -}` - testgenValid(t, input, jsonRef) -} - -func TestValidStringEmpty(t *testing.T) { - input := `answer = ""` - jsonRef := `{ - "answer": { - "type": "string", - "value": "" - } -}` - testgenValid(t, input, jsonRef) -} - -func TestValidStringEscapes(t *testing.T) { - input := `backspace = "This string has a \b backspace character." -tab = "This string has a \t tab character." -newline = "This string has a \n new line character." -formfeed = "This string has a \f form feed character." -carriage = "This string has a \r carriage return character." -quote = "This string has a \" quote character." -backslash = "This string has a \\ backslash character." -notunicode1 = "This string does not have a unicode \\u escape." -notunicode2 = "This string does not have a unicode \u005Cu escape." -notunicode3 = "This string does not have a unicode \\u0075 escape." -notunicode4 = "This string does not have a unicode \\\u0075 escape."` - jsonRef := `{ - "backspace": { - "type": "string", - "value": "This string has a \u0008 backspace character." - }, - "tab": { - "type": "string", - "value": "This string has a \u0009 tab character." - }, - "newline": { - "type": "string", - "value": "This string has a \u000A new line character." - }, - "formfeed": { - "type": "string", - "value": "This string has a \u000C form feed character." - }, - "carriage": { - "type": "string", - "value": "This string has a \u000D carriage return character." - }, - "quote": { - "type": "string", - "value": "This string has a \u0022 quote character." - }, - "backslash": { - "type": "string", - "value": "This string has a \u005C backslash character." - }, - "notunicode1": { - "type": "string", - "value": "This string does not have a unicode \\u escape." - }, - "notunicode2": { - "type": "string", - "value": "This string does not have a unicode \u005Cu escape." - }, - "notunicode3": { - "type": "string", - "value": "This string does not have a unicode \\u0075 escape." - }, - "notunicode4": { - "type": "string", - "value": "This string does not have a unicode \\\u0075 escape." - } -}` - testgenValid(t, input, jsonRef) -} - -func TestValidStringSimple(t *testing.T) { - input := `answer = "You are not drinking enough whisky."` - jsonRef := `{ - "answer": { - "type": "string", - "value": "You are not drinking enough whisky." - } -}` - testgenValid(t, input, jsonRef) -} - -func TestValidStringWithPound(t *testing.T) { - input := `pound = "We see no # comments here." -poundcomment = "But there are # some comments here." # Did I # mess you up?` - jsonRef := `{ - "pound": {"type": "string", "value": "We see no # comments here."}, - "poundcomment": { - "type": "string", - "value": "But there are # some comments here." - } -}` - testgenValid(t, input, jsonRef) -} - -func TestValidTableArrayImplicit(t *testing.T) { - input := `[[albums.songs]] -name = "Glory Days"` - jsonRef := `{ - "albums": { - "songs": [ - {"name": {"type": "string", "value": "Glory Days"}} - ] - } -}` - testgenValid(t, input, jsonRef) -} - -func TestValidTableArrayMany(t *testing.T) { - input := `[[people]] -first_name = "Bruce" -last_name = "Springsteen" - -[[people]] -first_name = "Eric" -last_name = "Clapton" - -[[people]] -first_name = "Bob" -last_name = "Seger"` - jsonRef := `{ - "people": [ - { - "first_name": {"type": "string", "value": "Bruce"}, - "last_name": {"type": "string", "value": "Springsteen"} - }, - { - "first_name": {"type": "string", "value": "Eric"}, - "last_name": {"type": "string", "value": "Clapton"} - }, - { - "first_name": {"type": "string", "value": "Bob"}, - "last_name": {"type": "string", "value": "Seger"} - } - ] -}` - testgenValid(t, input, jsonRef) -} - -func TestValidTableArrayNest(t *testing.T) { - input := `[[albums]] -name = "Born to Run" - - [[albums.songs]] - name = "Jungleland" - - [[albums.songs]] - name = "Meeting Across the River" - -[[albums]] -name = "Born in the USA" - - [[albums.songs]] - name = "Glory Days" - - [[albums.songs]] - name = "Dancing in the Dark"` - jsonRef := `{ - "albums": [ - { - "name": {"type": "string", "value": "Born to Run"}, - "songs": [ - {"name": {"type": "string", "value": "Jungleland"}}, - {"name": {"type": "string", "value": "Meeting Across the River"}} - ] - }, - { - "name": {"type": "string", "value": "Born in the USA"}, - "songs": [ - {"name": {"type": "string", "value": "Glory Days"}}, - {"name": {"type": "string", "value": "Dancing in the Dark"}} - ] - } - ] -}` - testgenValid(t, input, jsonRef) -} - -func TestValidTableArrayOne(t *testing.T) { - input := `[[people]] -first_name = "Bruce" -last_name = "Springsteen"` - jsonRef := `{ - "people": [ - { - "first_name": {"type": "string", "value": "Bruce"}, - "last_name": {"type": "string", "value": "Springsteen"} - } - ] -}` - testgenValid(t, input, jsonRef) -} - -func TestValidTableEmpty(t *testing.T) { - input := `[a]` - jsonRef := `{ - "a": {} -}` - testgenValid(t, input, jsonRef) -} - -func TestValidTableSubEmpty(t *testing.T) { - input := `[a] -[a.b]` - jsonRef := `{ - "a": { "b": {} } -}` - testgenValid(t, input, jsonRef) -} - -func TestValidTableWhitespace(t *testing.T) { - input := `["valid key"]` - jsonRef := `{ - "valid key": {} -}` - testgenValid(t, input, jsonRef) -} - -func TestValidTableWithPound(t *testing.T) { - input := `["key#group"] -answer = 42` - jsonRef := `{ - "key#group": { - "answer": {"type": "integer", "value": "42"} - } -}` - testgenValid(t, input, jsonRef) -} - -func TestValidUnicodeEscape(t *testing.T) { - input := `answer4 = "\u03B4" -answer8 = "\U000003B4"` - jsonRef := `{ - "answer4": {"type": "string", "value": "\u03B4"}, - "answer8": {"type": "string", "value": "\u03B4"} -}` - testgenValid(t, input, jsonRef) -} - -func TestValidUnicodeLiteral(t *testing.T) { - input := `answer = "δ"` - jsonRef := `{ - "answer": {"type": "string", "value": "δ"} -}` - testgenValid(t, input, jsonRef) -} diff --git a/src/vendor/github.com/pelletier/go-toml/tomltree_create_test.go b/src/vendor/github.com/pelletier/go-toml/tomltree_create_test.go deleted file mode 100644 index 3465a1066f50037663246c2be82654914179117e..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/tomltree_create_test.go +++ /dev/null @@ -1,126 +0,0 @@ -package toml - -import ( - "strconv" - "testing" - "time" -) - -type customString string - -type stringer struct{} - -func (s stringer) String() string { - return "stringer" -} - -func validate(t *testing.T, path string, object interface{}) { - switch o := object.(type) { - case *Tree: - for key, tree := range o.values { - validate(t, path+"."+key, tree) - } - case []*Tree: - for index, tree := range o { - validate(t, path+"."+strconv.Itoa(index), tree) - } - case *tomlValue: - switch o.value.(type) { - case int64, uint64, bool, string, float64, time.Time, - []int64, []uint64, []bool, []string, []float64, []time.Time: - default: - t.Fatalf("tomlValue at key %s containing incorrect type %T", path, o.value) - } - default: - t.Fatalf("value at key %s is of incorrect type %T", path, object) - } - t.Logf("validation ok %s as %T", path, object) -} - -func validateTree(t *testing.T, tree *Tree) { - validate(t, "", tree) -} - -func TestTreeCreateToTree(t *testing.T) { - data := map[string]interface{}{ - "a_string": "bar", - "an_int": 42, - "time": time.Now(), - "int8": int8(2), - "int16": int16(2), - "int32": int32(2), - "uint8": uint8(2), - "uint16": uint16(2), - "uint32": uint32(2), - "float32": float32(2), - "a_bool": false, - "stringer": stringer{}, - "nested": map[string]interface{}{ - "foo": "bar", - }, - "array": []string{"a", "b", "c"}, - "array_uint": []uint{uint(1), uint(2)}, - "array_table": []map[string]interface{}{{"sub_map": 52}}, - "array_times": []time.Time{time.Now(), time.Now()}, - "map_times": map[string]time.Time{"now": time.Now()}, - "custom_string_map_key": map[customString]interface{}{customString("custom"): "custom"}, - } - tree, err := TreeFromMap(data) - if err != nil { - t.Fatal("unexpected error:", err) - } - validateTree(t, tree) -} - -func TestTreeCreateToTreeInvalidLeafType(t *testing.T) { - _, err := TreeFromMap(map[string]interface{}{"foo": t}) - expected := "cannot convert type *testing.T to Tree" - if err.Error() != expected { - t.Fatalf("expected error %s, got %s", expected, err.Error()) - } -} - -func TestTreeCreateToTreeInvalidMapKeyType(t *testing.T) { - _, err := TreeFromMap(map[string]interface{}{"foo": map[int]interface{}{2: 1}}) - expected := "map key needs to be a string, not int (int)" - if err.Error() != expected { - t.Fatalf("expected error %s, got %s", expected, err.Error()) - } -} - -func TestTreeCreateToTreeInvalidArrayMemberType(t *testing.T) { - _, err := TreeFromMap(map[string]interface{}{"foo": []*testing.T{t}}) - expected := "cannot convert type *testing.T to Tree" - if err.Error() != expected { - t.Fatalf("expected error %s, got %s", expected, err.Error()) - } -} - -func TestTreeCreateToTreeInvalidTableGroupType(t *testing.T) { - _, err := TreeFromMap(map[string]interface{}{"foo": []map[string]interface{}{{"hello": t}}}) - expected := "cannot convert type *testing.T to Tree" - if err.Error() != expected { - t.Fatalf("expected error %s, got %s", expected, err.Error()) - } -} - -func TestRoundTripArrayOfTables(t *testing.T) { - orig := "\n[[stuff]]\n name = \"foo\"\n things = [\"a\",\"b\"]\n" - tree, err := Load(orig) - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - - m := tree.ToMap() - - tree, err = TreeFromMap(m) - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - want := orig - got := tree.String() - - if got != want { - t.Errorf("want:\n%s\ngot:\n%s", want, got) - } -} diff --git a/src/vendor/github.com/pelletier/go-toml/tomltree_write_test.go b/src/vendor/github.com/pelletier/go-toml/tomltree_write_test.go deleted file mode 100644 index 206203b88e7bd7e5354b0a73ab34989b8e9db10e..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pelletier/go-toml/tomltree_write_test.go +++ /dev/null @@ -1,376 +0,0 @@ -package toml - -import ( - "bytes" - "errors" - "fmt" - "reflect" - "strings" - "testing" - "time" -) - -type failingWriter struct { - failAt int - written int - buffer bytes.Buffer -} - -func (f *failingWriter) Write(p []byte) (n int, err error) { - count := len(p) - toWrite := f.failAt - (count + f.written) - if toWrite < 0 { - toWrite = 0 - } - if toWrite > count { - f.written += count - f.buffer.Write(p) - return count, nil - } - - f.buffer.Write(p[:toWrite]) - f.written = f.failAt - return toWrite, fmt.Errorf("failingWriter failed after writing %d bytes", f.written) -} - -func assertErrorString(t *testing.T, expected string, err error) { - expectedErr := errors.New(expected) - if err == nil || err.Error() != expectedErr.Error() { - t.Errorf("expecting error %s, but got %s instead", expected, err) - } -} - -func TestTreeWriteToEmptyTable(t *testing.T) { - doc := `[[empty-tables]] -[[empty-tables]]` - - toml, err := Load(doc) - if err != nil { - t.Fatal("Unexpected Load error:", err) - } - tomlString, err := toml.ToTomlString() - if err != nil { - t.Fatal("Unexpected ToTomlString error:", err) - } - - expected := ` -[[empty-tables]] - -[[empty-tables]] -` - - if tomlString != expected { - t.Fatalf("Expected:\n%s\nGot:\n%s", expected, tomlString) - } -} - -func TestTreeWriteToTomlString(t *testing.T) { - toml, err := Load(`name = { first = "Tom", last = "Preston-Werner" } -points = { x = 1, y = 2 }`) - - if err != nil { - t.Fatal("Unexpected error:", err) - } - - tomlString, _ := toml.ToTomlString() - reparsedTree, err := Load(tomlString) - - assertTree(t, reparsedTree, err, map[string]interface{}{ - "name": map[string]interface{}{ - "first": "Tom", - "last": "Preston-Werner", - }, - "points": map[string]interface{}{ - "x": int64(1), - "y": int64(2), - }, - }) -} - -func TestTreeWriteToTomlStringSimple(t *testing.T) { - tree, err := Load("[foo]\n\n[[foo.bar]]\na = 42\n\n[[foo.bar]]\na = 69\n") - if err != nil { - t.Errorf("Test failed to parse: %v", err) - return - } - result, err := tree.ToTomlString() - if err != nil { - t.Errorf("Unexpected error: %s", err) - } - expected := "\n[foo]\n\n [[foo.bar]]\n a = 42\n\n [[foo.bar]]\n a = 69\n" - if result != expected { - t.Errorf("Expected got '%s', expected '%s'", result, expected) - } -} - -func TestTreeWriteToTomlStringKeysOrders(t *testing.T) { - for i := 0; i < 100; i++ { - tree, _ := Load(` - foobar = true - bar = "baz" - foo = 1 - [qux] - foo = 1 - bar = "baz2"`) - - stringRepr, _ := tree.ToTomlString() - - t.Log("Intermediate string representation:") - t.Log(stringRepr) - - r := strings.NewReader(stringRepr) - toml, err := LoadReader(r) - - if err != nil { - t.Fatal("Unexpected error:", err) - } - - assertTree(t, toml, err, map[string]interface{}{ - "foobar": true, - "bar": "baz", - "foo": 1, - "qux": map[string]interface{}{ - "foo": 1, - "bar": "baz2", - }, - }) - } -} - -func testMaps(t *testing.T, actual, expected map[string]interface{}) { - if !reflect.DeepEqual(actual, expected) { - t.Fatal("trees aren't equal.\n", "Expected:\n", expected, "\nActual:\n", actual) - } -} - -func TestTreeWriteToMapSimple(t *testing.T) { - tree, _ := Load("a = 42\nb = 17") - - expected := map[string]interface{}{ - "a": int64(42), - "b": int64(17), - } - - testMaps(t, tree.ToMap(), expected) -} - -func TestTreeWriteToInvalidTreeSimpleValue(t *testing.T) { - tree := Tree{values: map[string]interface{}{"foo": int8(1)}} - _, err := tree.ToTomlString() - assertErrorString(t, "invalid value type at foo: int8", err) -} - -func TestTreeWriteToInvalidTreeTomlValue(t *testing.T) { - tree := Tree{values: map[string]interface{}{"foo": &tomlValue{value: int8(1), comment: "", position: Position{}}}} - _, err := tree.ToTomlString() - assertErrorString(t, "unsupported value type int8: 1", err) -} - -func TestTreeWriteToInvalidTreeTomlValueArray(t *testing.T) { - tree := Tree{values: map[string]interface{}{"foo": &tomlValue{value: int8(1), comment: "", position: Position{}}}} - _, err := tree.ToTomlString() - assertErrorString(t, "unsupported value type int8: 1", err) -} - -func TestTreeWriteToFailingWriterInSimpleValue(t *testing.T) { - toml, _ := Load(`a = 2`) - writer := failingWriter{failAt: 0, written: 0} - _, err := toml.WriteTo(&writer) - assertErrorString(t, "failingWriter failed after writing 0 bytes", err) -} - -func TestTreeWriteToFailingWriterInTable(t *testing.T) { - toml, _ := Load(` -[b] -a = 2`) - writer := failingWriter{failAt: 2, written: 0} - _, err := toml.WriteTo(&writer) - assertErrorString(t, "failingWriter failed after writing 2 bytes", err) - - writer = failingWriter{failAt: 13, written: 0} - _, err = toml.WriteTo(&writer) - assertErrorString(t, "failingWriter failed after writing 13 bytes", err) -} - -func TestTreeWriteToFailingWriterInArray(t *testing.T) { - toml, _ := Load(` -[[b]] -a = 2`) - writer := failingWriter{failAt: 2, written: 0} - _, err := toml.WriteTo(&writer) - assertErrorString(t, "failingWriter failed after writing 2 bytes", err) - - writer = failingWriter{failAt: 15, written: 0} - _, err = toml.WriteTo(&writer) - assertErrorString(t, "failingWriter failed after writing 15 bytes", err) -} - -func TestTreeWriteToMapExampleFile(t *testing.T) { - tree, _ := LoadFile("example.toml") - expected := map[string]interface{}{ - "title": "TOML Example", - "owner": map[string]interface{}{ - "name": "Tom Preston-Werner", - "organization": "GitHub", - "bio": "GitHub Cofounder & CEO\nLikes tater tots and beer.", - "dob": time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC), - }, - "database": map[string]interface{}{ - "server": "192.168.1.1", - "ports": []interface{}{int64(8001), int64(8001), int64(8002)}, - "connection_max": int64(5000), - "enabled": true, - }, - "servers": map[string]interface{}{ - "alpha": map[string]interface{}{ - "ip": "10.0.0.1", - "dc": "eqdc10", - }, - "beta": map[string]interface{}{ - "ip": "10.0.0.2", - "dc": "eqdc10", - }, - }, - "clients": map[string]interface{}{ - "data": []interface{}{ - []interface{}{"gamma", "delta"}, - []interface{}{int64(1), int64(2)}, - }, - }, - } - testMaps(t, tree.ToMap(), expected) -} - -func TestTreeWriteToMapWithTablesInMultipleChunks(t *testing.T) { - tree, _ := Load(` - [[menu.main]] - a = "menu 1" - b = "menu 2" - [[menu.main]] - c = "menu 3" - d = "menu 4"`) - expected := map[string]interface{}{ - "menu": map[string]interface{}{ - "main": []interface{}{ - map[string]interface{}{"a": "menu 1", "b": "menu 2"}, - map[string]interface{}{"c": "menu 3", "d": "menu 4"}, - }, - }, - } - treeMap := tree.ToMap() - - testMaps(t, treeMap, expected) -} - -func TestTreeWriteToMapWithArrayOfInlineTables(t *testing.T) { - tree, _ := Load(` - [params] - language_tabs = [ - { key = "shell", name = "Shell" }, - { key = "ruby", name = "Ruby" }, - { key = "python", name = "Python" } - ]`) - - expected := map[string]interface{}{ - "params": map[string]interface{}{ - "language_tabs": []interface{}{ - map[string]interface{}{ - "key": "shell", - "name": "Shell", - }, - map[string]interface{}{ - "key": "ruby", - "name": "Ruby", - }, - map[string]interface{}{ - "key": "python", - "name": "Python", - }, - }, - }, - } - - treeMap := tree.ToMap() - testMaps(t, treeMap, expected) -} - -func TestTreeWriteToFloat(t *testing.T) { - tree, err := Load(`a = 3.0`) - if err != nil { - t.Fatal(err) - } - str, err := tree.ToTomlString() - if err != nil { - t.Fatal(err) - } - expected := `a = 3.0` - if strings.TrimSpace(str) != strings.TrimSpace(expected) { - t.Fatalf("Expected:\n%s\nGot:\n%s", expected, str) - } -} - -func TestTreeWriteToSpecialFloat(t *testing.T) { - expected := `a = +inf -b = -inf -c = nan` - - tree, err := Load(expected) - if err != nil { - t.Fatal(err) - } - str, err := tree.ToTomlString() - if err != nil { - t.Fatal(err) - } - if strings.TrimSpace(str) != strings.TrimSpace(expected) { - t.Fatalf("Expected:\n%s\nGot:\n%s", expected, str) - } -} - -func BenchmarkTreeToTomlString(b *testing.B) { - toml, err := Load(sampleHard) - if err != nil { - b.Fatal("Unexpected error:", err) - } - - for i := 0; i < b.N; i++ { - _, err := toml.ToTomlString() - if err != nil { - b.Fatal(err) - } - } -} - -var sampleHard = `# Test file for TOML -# Only this one tries to emulate a TOML file written by a user of the kind of parser writers probably hate -# This part you'll really hate - -[the] -test_string = "You'll hate me after this - #" # " Annoying, isn't it? - - [the.hard] - test_array = [ "] ", " # "] # ] There you go, parse this! - test_array2 = [ "Test #11 ]proved that", "Experiment #9 was a success" ] - # You didn't think it'd as easy as chucking out the last #, did you? - another_test_string = " Same thing, but with a string #" - harder_test_string = " And when \"'s are in the string, along with # \"" # "and comments are there too" - # Things will get harder - - [the.hard."bit#"] - "what?" = "You don't think some user won't do that?" - multi_line_array = [ - "]", - # ] Oh yes I did - ] - -# Each of the following keygroups/key value pairs should produce an error. Uncomment to them to test - -#[error] if you didn't catch this, your parser is broken -#string = "Anything other than tabs, spaces and newline after a keygroup or key value pair has ended should produce an error unless it is a comment" like this -#array = [ -# "This might most likely happen in multiline arrays", -# Like here, -# "or here, -# and here" -# ] End of array comment, forgot the # -#number = 3.14 pi <--again forgot the # ` diff --git a/src/vendor/github.com/pmezard/go-difflib/.travis.yml b/src/vendor/github.com/pmezard/go-difflib/.travis.yml deleted file mode 100644 index 90c9c6f917fb5c8d7bbb79db79b8ac168941553d..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pmezard/go-difflib/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: go -go: - - 1.5 - - tip - diff --git a/src/vendor/github.com/pmezard/go-difflib/README.md b/src/vendor/github.com/pmezard/go-difflib/README.md deleted file mode 100644 index e87f307ed44fe4d73874eda51cb780c2b62bf611..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pmezard/go-difflib/README.md +++ /dev/null @@ -1,50 +0,0 @@ -go-difflib -========== - -[![Build Status](https://travis-ci.org/pmezard/go-difflib.png?branch=master)](https://travis-ci.org/pmezard/go-difflib) -[![GoDoc](https://godoc.org/github.com/pmezard/go-difflib/difflib?status.svg)](https://godoc.org/github.com/pmezard/go-difflib/difflib) - -Go-difflib is a partial port of python 3 difflib package. Its main goal -was to make unified and context diff available in pure Go, mostly for -testing purposes. - -The following class and functions (and related tests) have be ported: - -* `SequenceMatcher` -* `unified_diff()` -* `context_diff()` - -## Installation - -```bash -$ go get github.com/pmezard/go-difflib/difflib -``` - -### Quick Start - -Diffs are configured with Unified (or ContextDiff) structures, and can -be output to an io.Writer or returned as a string. - -```Go -diff := UnifiedDiff{ - A: difflib.SplitLines("foo\nbar\n"), - B: difflib.SplitLines("foo\nbaz\n"), - FromFile: "Original", - ToFile: "Current", - Context: 3, -} -text, _ := GetUnifiedDiffString(diff) -fmt.Printf(text) -``` - -would output: - -``` ---- Original -+++ Current -@@ -1,3 +1,3 @@ - foo --bar -+baz -``` - diff --git a/src/vendor/github.com/pmezard/go-difflib/difflib/difflib_test.go b/src/vendor/github.com/pmezard/go-difflib/difflib/difflib_test.go deleted file mode 100644 index d725119620740eaaa4adfb3f3b927bb4c02907db..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/pmezard/go-difflib/difflib/difflib_test.go +++ /dev/null @@ -1,426 +0,0 @@ -package difflib - -import ( - "bytes" - "fmt" - "math" - "reflect" - "strings" - "testing" -) - -func assertAlmostEqual(t *testing.T, a, b float64, places int) { - if math.Abs(a-b) > math.Pow10(-places) { - t.Errorf("%.7f != %.7f", a, b) - } -} - -func assertEqual(t *testing.T, a, b interface{}) { - if !reflect.DeepEqual(a, b) { - t.Errorf("%v != %v", a, b) - } -} - -func splitChars(s string) []string { - chars := make([]string, 0, len(s)) - // Assume ASCII inputs - for i := 0; i != len(s); i++ { - chars = append(chars, string(s[i])) - } - return chars -} - -func TestSequenceMatcherRatio(t *testing.T) { - s := NewMatcher(splitChars("abcd"), splitChars("bcde")) - assertEqual(t, s.Ratio(), 0.75) - assertEqual(t, s.QuickRatio(), 0.75) - assertEqual(t, s.RealQuickRatio(), 1.0) -} - -func TestGetOptCodes(t *testing.T) { - a := "qabxcd" - b := "abycdf" - s := NewMatcher(splitChars(a), splitChars(b)) - w := &bytes.Buffer{} - for _, op := range s.GetOpCodes() { - fmt.Fprintf(w, "%s a[%d:%d], (%s) b[%d:%d] (%s)\n", string(op.Tag), - op.I1, op.I2, a[op.I1:op.I2], op.J1, op.J2, b[op.J1:op.J2]) - } - result := string(w.Bytes()) - expected := `d a[0:1], (q) b[0:0] () -e a[1:3], (ab) b[0:2] (ab) -r a[3:4], (x) b[2:3] (y) -e a[4:6], (cd) b[3:5] (cd) -i a[6:6], () b[5:6] (f) -` - if expected != result { - t.Errorf("unexpected op codes: \n%s", result) - } -} - -func TestGroupedOpCodes(t *testing.T) { - a := []string{} - for i := 0; i != 39; i++ { - a = append(a, fmt.Sprintf("%02d", i)) - } - b := []string{} - b = append(b, a[:8]...) - b = append(b, " i") - b = append(b, a[8:19]...) - b = append(b, " x") - b = append(b, a[20:22]...) - b = append(b, a[27:34]...) - b = append(b, " y") - b = append(b, a[35:]...) - s := NewMatcher(a, b) - w := &bytes.Buffer{} - for _, g := range s.GetGroupedOpCodes(-1) { - fmt.Fprintf(w, "group\n") - for _, op := range g { - fmt.Fprintf(w, " %s, %d, %d, %d, %d\n", string(op.Tag), - op.I1, op.I2, op.J1, op.J2) - } - } - result := string(w.Bytes()) - expected := `group - e, 5, 8, 5, 8 - i, 8, 8, 8, 9 - e, 8, 11, 9, 12 -group - e, 16, 19, 17, 20 - r, 19, 20, 20, 21 - e, 20, 22, 21, 23 - d, 22, 27, 23, 23 - e, 27, 30, 23, 26 -group - e, 31, 34, 27, 30 - r, 34, 35, 30, 31 - e, 35, 38, 31, 34 -` - if expected != result { - t.Errorf("unexpected op codes: \n%s", result) - } -} - -func ExampleGetUnifiedDiffCode() { - a := `one -two -three -four -fmt.Printf("%s,%T",a,b)` - b := `zero -one -three -four` - diff := UnifiedDiff{ - A: SplitLines(a), - B: SplitLines(b), - FromFile: "Original", - FromDate: "2005-01-26 23:30:50", - ToFile: "Current", - ToDate: "2010-04-02 10:20:52", - Context: 3, - } - result, _ := GetUnifiedDiffString(diff) - fmt.Println(strings.Replace(result, "\t", " ", -1)) - // Output: - // --- Original 2005-01-26 23:30:50 - // +++ Current 2010-04-02 10:20:52 - // @@ -1,5 +1,4 @@ - // +zero - // one - // -two - // three - // four - // -fmt.Printf("%s,%T",a,b) -} - -func ExampleGetContextDiffCode() { - a := `one -two -three -four -fmt.Printf("%s,%T",a,b)` - b := `zero -one -tree -four` - diff := ContextDiff{ - A: SplitLines(a), - B: SplitLines(b), - FromFile: "Original", - ToFile: "Current", - Context: 3, - Eol: "\n", - } - result, _ := GetContextDiffString(diff) - fmt.Print(strings.Replace(result, "\t", " ", -1)) - // Output: - // *** Original - // --- Current - // *************** - // *** 1,5 **** - // one - // ! two - // ! three - // four - // - fmt.Printf("%s,%T",a,b) - // --- 1,4 ---- - // + zero - // one - // ! tree - // four -} - -func ExampleGetContextDiffString() { - a := `one -two -three -four` - b := `zero -one -tree -four` - diff := ContextDiff{ - A: SplitLines(a), - B: SplitLines(b), - FromFile: "Original", - ToFile: "Current", - Context: 3, - Eol: "\n", - } - result, _ := GetContextDiffString(diff) - fmt.Printf(strings.Replace(result, "\t", " ", -1)) - // Output: - // *** Original - // --- Current - // *************** - // *** 1,4 **** - // one - // ! two - // ! three - // four - // --- 1,4 ---- - // + zero - // one - // ! tree - // four -} - -func rep(s string, count int) string { - return strings.Repeat(s, count) -} - -func TestWithAsciiOneInsert(t *testing.T) { - sm := NewMatcher(splitChars(rep("b", 100)), - splitChars("a"+rep("b", 100))) - assertAlmostEqual(t, sm.Ratio(), 0.995, 3) - assertEqual(t, sm.GetOpCodes(), - []OpCode{{'i', 0, 0, 0, 1}, {'e', 0, 100, 1, 101}}) - assertEqual(t, len(sm.bPopular), 0) - - sm = NewMatcher(splitChars(rep("b", 100)), - splitChars(rep("b", 50)+"a"+rep("b", 50))) - assertAlmostEqual(t, sm.Ratio(), 0.995, 3) - assertEqual(t, sm.GetOpCodes(), - []OpCode{{'e', 0, 50, 0, 50}, {'i', 50, 50, 50, 51}, {'e', 50, 100, 51, 101}}) - assertEqual(t, len(sm.bPopular), 0) -} - -func TestWithAsciiOnDelete(t *testing.T) { - sm := NewMatcher(splitChars(rep("a", 40)+"c"+rep("b", 40)), - splitChars(rep("a", 40)+rep("b", 40))) - assertAlmostEqual(t, sm.Ratio(), 0.994, 3) - assertEqual(t, sm.GetOpCodes(), - []OpCode{{'e', 0, 40, 0, 40}, {'d', 40, 41, 40, 40}, {'e', 41, 81, 40, 80}}) -} - -func TestWithAsciiBJunk(t *testing.T) { - isJunk := func(s string) bool { - return s == " " - } - sm := NewMatcherWithJunk(splitChars(rep("a", 40)+rep("b", 40)), - splitChars(rep("a", 44)+rep("b", 40)), true, isJunk) - assertEqual(t, sm.bJunk, map[string]struct{}{}) - - sm = NewMatcherWithJunk(splitChars(rep("a", 40)+rep("b", 40)), - splitChars(rep("a", 44)+rep("b", 40)+rep(" ", 20)), false, isJunk) - assertEqual(t, sm.bJunk, map[string]struct{}{" ": struct{}{}}) - - isJunk = func(s string) bool { - return s == " " || s == "b" - } - sm = NewMatcherWithJunk(splitChars(rep("a", 40)+rep("b", 40)), - splitChars(rep("a", 44)+rep("b", 40)+rep(" ", 20)), false, isJunk) - assertEqual(t, sm.bJunk, map[string]struct{}{" ": struct{}{}, "b": struct{}{}}) -} - -func TestSFBugsRatioForNullSeqn(t *testing.T) { - sm := NewMatcher(nil, nil) - assertEqual(t, sm.Ratio(), 1.0) - assertEqual(t, sm.QuickRatio(), 1.0) - assertEqual(t, sm.RealQuickRatio(), 1.0) -} - -func TestSFBugsComparingEmptyLists(t *testing.T) { - groups := NewMatcher(nil, nil).GetGroupedOpCodes(-1) - assertEqual(t, len(groups), 0) - diff := UnifiedDiff{ - FromFile: "Original", - ToFile: "Current", - Context: 3, - } - result, err := GetUnifiedDiffString(diff) - assertEqual(t, err, nil) - assertEqual(t, result, "") -} - -func TestOutputFormatRangeFormatUnified(t *testing.T) { - // Per the diff spec at http://www.unix.org/single_unix_specification/ - // - // Each field shall be of the form: - // %1d", if the range contains exactly one line, - // and: - // "%1d,%1d", , otherwise. - // If a range is empty, its beginning line number shall be the number of - // the line just before the range, or 0 if the empty range starts the file. - fm := formatRangeUnified - assertEqual(t, fm(3, 3), "3,0") - assertEqual(t, fm(3, 4), "4") - assertEqual(t, fm(3, 5), "4,2") - assertEqual(t, fm(3, 6), "4,3") - assertEqual(t, fm(0, 0), "0,0") -} - -func TestOutputFormatRangeFormatContext(t *testing.T) { - // Per the diff spec at http://www.unix.org/single_unix_specification/ - // - // The range of lines in file1 shall be written in the following format - // if the range contains two or more lines: - // "*** %d,%d ****\n", , - // and the following format otherwise: - // "*** %d ****\n", - // The ending line number of an empty range shall be the number of the preceding line, - // or 0 if the range is at the start of the file. - // - // Next, the range of lines in file2 shall be written in the following format - // if the range contains two or more lines: - // "--- %d,%d ----\n", , - // and the following format otherwise: - // "--- %d ----\n", - fm := formatRangeContext - assertEqual(t, fm(3, 3), "3") - assertEqual(t, fm(3, 4), "4") - assertEqual(t, fm(3, 5), "4,5") - assertEqual(t, fm(3, 6), "4,6") - assertEqual(t, fm(0, 0), "0") -} - -func TestOutputFormatTabDelimiter(t *testing.T) { - diff := UnifiedDiff{ - A: splitChars("one"), - B: splitChars("two"), - FromFile: "Original", - FromDate: "2005-01-26 23:30:50", - ToFile: "Current", - ToDate: "2010-04-12 10:20:52", - Eol: "\n", - } - ud, err := GetUnifiedDiffString(diff) - assertEqual(t, err, nil) - assertEqual(t, SplitLines(ud)[:2], []string{ - "--- Original\t2005-01-26 23:30:50\n", - "+++ Current\t2010-04-12 10:20:52\n", - }) - cd, err := GetContextDiffString(ContextDiff(diff)) - assertEqual(t, err, nil) - assertEqual(t, SplitLines(cd)[:2], []string{ - "*** Original\t2005-01-26 23:30:50\n", - "--- Current\t2010-04-12 10:20:52\n", - }) -} - -func TestOutputFormatNoTrailingTabOnEmptyFiledate(t *testing.T) { - diff := UnifiedDiff{ - A: splitChars("one"), - B: splitChars("two"), - FromFile: "Original", - ToFile: "Current", - Eol: "\n", - } - ud, err := GetUnifiedDiffString(diff) - assertEqual(t, err, nil) - assertEqual(t, SplitLines(ud)[:2], []string{"--- Original\n", "+++ Current\n"}) - - cd, err := GetContextDiffString(ContextDiff(diff)) - assertEqual(t, err, nil) - assertEqual(t, SplitLines(cd)[:2], []string{"*** Original\n", "--- Current\n"}) -} - -func TestOmitFilenames(t *testing.T) { - diff := UnifiedDiff{ - A: SplitLines("o\nn\ne\n"), - B: SplitLines("t\nw\no\n"), - Eol: "\n", - } - ud, err := GetUnifiedDiffString(diff) - assertEqual(t, err, nil) - assertEqual(t, SplitLines(ud), []string{ - "@@ -0,0 +1,2 @@\n", - "+t\n", - "+w\n", - "@@ -2,2 +3,0 @@\n", - "-n\n", - "-e\n", - "\n", - }) - - cd, err := GetContextDiffString(ContextDiff(diff)) - assertEqual(t, err, nil) - assertEqual(t, SplitLines(cd), []string{ - "***************\n", - "*** 0 ****\n", - "--- 1,2 ----\n", - "+ t\n", - "+ w\n", - "***************\n", - "*** 2,3 ****\n", - "- n\n", - "- e\n", - "--- 3 ----\n", - "\n", - }) -} - -func TestSplitLines(t *testing.T) { - allTests := []struct { - input string - want []string - }{ - {"foo", []string{"foo\n"}}, - {"foo\nbar", []string{"foo\n", "bar\n"}}, - {"foo\nbar\n", []string{"foo\n", "bar\n", "\n"}}, - } - for _, test := range allTests { - assertEqual(t, SplitLines(test.input), test.want) - } -} - -func benchmarkSplitLines(b *testing.B, count int) { - str := strings.Repeat("foo\n", count) - - b.ResetTimer() - - n := 0 - for i := 0; i < b.N; i++ { - n += len(SplitLines(str)) - } -} - -func BenchmarkSplitLines100(b *testing.B) { - benchmarkSplitLines(b, 100) -} - -func BenchmarkSplitLines10000(b *testing.B) { - benchmarkSplitLines(b, 10000) -} diff --git a/src/vendor/github.com/stretchr/testify/.gitignore b/src/vendor/github.com/stretchr/testify/.gitignore deleted file mode 100644 index 5aacdb7cca624915c6d0770d5b92405d006e9fd1..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe - -.DS_Store diff --git a/src/vendor/github.com/stretchr/testify/.travis.gofmt.sh b/src/vendor/github.com/stretchr/testify/.travis.gofmt.sh deleted file mode 100755 index bfffdca8bcac92c89c4cae43ad914e4660c0a3cb..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/.travis.gofmt.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/bash - -if [ -n "$(gofmt -l .)" ]; then - echo "Go code is not formatted:" - gofmt -d . - exit 1 -fi diff --git a/src/vendor/github.com/stretchr/testify/.travis.gogenerate.sh b/src/vendor/github.com/stretchr/testify/.travis.gogenerate.sh deleted file mode 100755 index 161b449cd8dcac9b54ec59131bae412e43f71d4b..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/.travis.gogenerate.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -if [[ "$TRAVIS_GO_VERSION" =~ ^1\.[45](\..*)?$ ]]; then - exit 0 -fi - -go get github.com/ernesto-jimenez/gogen/imports -go generate ./... -if [ -n "$(git diff)" ]; then - echo "Go generate had not been run" - git diff - exit 1 -fi diff --git a/src/vendor/github.com/stretchr/testify/.travis.govet.sh b/src/vendor/github.com/stretchr/testify/.travis.govet.sh deleted file mode 100755 index f8fbba7a1be1cd455f75175502cf018308db0820..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/.travis.govet.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash - -cd "$(dirname $0)" -DIRS=". assert require mock _codegen" -set -e -for subdir in $DIRS; do - pushd $subdir - go vet - popd -done diff --git a/src/vendor/github.com/stretchr/testify/.travis.yml b/src/vendor/github.com/stretchr/testify/.travis.yml deleted file mode 100644 index da6ba0d017ec5ad7e7fe7bd4d86ae0e410c22e30..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/.travis.yml +++ /dev/null @@ -1,19 +0,0 @@ -language: go - -sudo: false - -matrix: - include: - - go: "1.8.x" - - go: "1.9.x" - - go: "1.10.x" - - go: "1.11.x" - env: GO111MODULE=off - - go: "1.11.x" - env: GO111MODULE=on - - go: tip - script: - - ./.travis.gogenerate.sh - - ./.travis.gofmt.sh - - ./.travis.govet.sh - - go test -v -race $(go list ./... | grep -v vendor) diff --git a/src/vendor/github.com/stretchr/testify/Gopkg.lock b/src/vendor/github.com/stretchr/testify/Gopkg.lock deleted file mode 100644 index 294cda0930df7db316c022db1cab65c48fdff638..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/Gopkg.lock +++ /dev/null @@ -1,27 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - name = "github.com/davecgh/go-spew" - packages = ["spew"] - revision = "346938d642f2ec3594ed81d874461961cd0faa76" - version = "v1.1.0" - -[[projects]] - name = "github.com/pmezard/go-difflib" - packages = ["difflib"] - revision = "792786c7400a136282c1664665ae0a8db921c6c2" - version = "v1.0.0" - -[[projects]] - name = "github.com/stretchr/objx" - packages = ["."] - revision = "facf9a85c22f48d2f52f2380e4efce1768749a89" - version = "v0.1" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - inputs-digest = "448ddae4702c6aded2555faafd390c537789bb1c483f70b0431e6634f73f2090" - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/src/vendor/github.com/stretchr/testify/Gopkg.toml b/src/vendor/github.com/stretchr/testify/Gopkg.toml deleted file mode 100644 index a16374c8b44b30881940340a566d0fea1b90f56c..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/Gopkg.toml +++ /dev/null @@ -1,16 +0,0 @@ -[prune] - unused-packages = true - non-go = true - go-tests = true - -[[constraint]] - name = "github.com/davecgh/go-spew" - version = "~1.1.0" - -[[constraint]] - name = "github.com/pmezard/go-difflib" - version = "~1.0.0" - -[[constraint]] - name = "github.com/stretchr/objx" - version = "~0.1.0" diff --git a/src/vendor/github.com/stretchr/testify/README.md b/src/vendor/github.com/stretchr/testify/README.md deleted file mode 100644 index 11951d4a555e700c5bf5e60a5dd3f83bd872290a..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/README.md +++ /dev/null @@ -1,340 +0,0 @@ -Testify - Thou Shalt Write Tests -================================ - -[![Build Status](https://travis-ci.org/stretchr/testify.svg)](https://travis-ci.org/stretchr/testify) [![Go Report Card](https://goreportcard.com/badge/github.com/stretchr/testify)](https://goreportcard.com/report/github.com/stretchr/testify) [![GoDoc](https://godoc.org/github.com/stretchr/testify?status.svg)](https://godoc.org/github.com/stretchr/testify) - -Go code (golang) set of packages that provide many tools for testifying that your code will behave as you intend. - -Features include: - - * [Easy assertions](#assert-package) - * [Mocking](#mock-package) - * [Testing suite interfaces and functions](#suite-package) - -Get started: - - * Install testify with [one line of code](#installation), or [update it with another](#staying-up-to-date) - * For an introduction to writing test code in Go, see http://golang.org/doc/code.html#Testing - * Check out the API Documentation http://godoc.org/github.com/stretchr/testify - * To make your testing life easier, check out our other project, [gorc](http://github.com/stretchr/gorc) - * A little about [Test-Driven Development (TDD)](http://en.wikipedia.org/wiki/Test-driven_development) - - - -[`assert`](http://godoc.org/github.com/stretchr/testify/assert "API documentation") package -------------------------------------------------------------------------------------------- - -The `assert` package provides some helpful methods that allow you to write better test code in Go. - - * Prints friendly, easy to read failure descriptions - * Allows for very readable code - * Optionally annotate each assertion with a message - -See it in action: - -```go -package yours - -import ( - "testing" - "github.com/stretchr/testify/assert" -) - -func TestSomething(t *testing.T) { - - // assert equality - assert.Equal(t, 123, 123, "they should be equal") - - // assert inequality - assert.NotEqual(t, 123, 456, "they should not be equal") - - // assert for nil (good for errors) - assert.Nil(t, object) - - // assert for not nil (good when you expect something) - if assert.NotNil(t, object) { - - // now we know that object isn't nil, we are safe to make - // further assertions without causing any errors - assert.Equal(t, "Something", object.Value) - - } - -} -``` - - * Every assert func takes the `testing.T` object as the first argument. This is how it writes the errors out through the normal `go test` capabilities. - * Every assert func returns a bool indicating whether the assertion was successful or not, this is useful for if you want to go on making further assertions under certain conditions. - -if you assert many times, use the below: - -```go -package yours - -import ( - "testing" - "github.com/stretchr/testify/assert" -) - -func TestSomething(t *testing.T) { - assert := assert.New(t) - - // assert equality - assert.Equal(123, 123, "they should be equal") - - // assert inequality - assert.NotEqual(123, 456, "they should not be equal") - - // assert for nil (good for errors) - assert.Nil(object) - - // assert for not nil (good when you expect something) - if assert.NotNil(object) { - - // now we know that object isn't nil, we are safe to make - // further assertions without causing any errors - assert.Equal("Something", object.Value) - } -} -``` - -[`require`](http://godoc.org/github.com/stretchr/testify/require "API documentation") package ---------------------------------------------------------------------------------------------- - -The `require` package provides same global functions as the `assert` package, but instead of returning a boolean result they terminate current test. - -See [t.FailNow](http://golang.org/pkg/testing/#T.FailNow) for details. - -[`mock`](http://godoc.org/github.com/stretchr/testify/mock "API documentation") package ----------------------------------------------------------------------------------------- - -The `mock` package provides a mechanism for easily writing mock objects that can be used in place of real objects when writing test code. - -An example test function that tests a piece of code that relies on an external object `testObj`, can setup expectations (testify) and assert that they indeed happened: - -```go -package yours - -import ( - "testing" - "github.com/stretchr/testify/mock" -) - -/* - Test objects -*/ - -// MyMockedObject is a mocked object that implements an interface -// that describes an object that the code I am testing relies on. -type MyMockedObject struct{ - mock.Mock -} - -// DoSomething is a method on MyMockedObject that implements some interface -// and just records the activity, and returns what the Mock object tells it to. -// -// In the real object, this method would do something useful, but since this -// is a mocked object - we're just going to stub it out. -// -// NOTE: This method is not being tested here, code that uses this object is. -func (m *MyMockedObject) DoSomething(number int) (bool, error) { - - args := m.Called(number) - return args.Bool(0), args.Error(1) - -} - -/* - Actual test functions -*/ - -// TestSomething is an example of how to use our test object to -// make assertions about some target code we are testing. -func TestSomething(t *testing.T) { - - // create an instance of our test object - testObj := new(MyMockedObject) - - // setup expectations - testObj.On("DoSomething", 123).Return(true, nil) - - // call the code we are testing - targetFuncThatDoesSomethingWithObj(testObj) - - // assert that the expectations were met - testObj.AssertExpectations(t) - - -} - -// TestSomethingElse is a second example of how to use our test object to -// make assertions about some target code we are testing. -// This time using a placeholder. Placeholders might be used when the -// data being passed in is normally dynamically generated and cannot be -// predicted beforehand (eg. containing hashes that are time sensitive) -func TestSomethingElse(t *testing.T) { - - // create an instance of our test object - testObj := new(MyMockedObject) - - // setup expectations with a placeholder in the argument list - testObj.On("DoSomething", mock.Anything).Return(true, nil) - - // call the code we are testing - targetFuncThatDoesSomethingWithObj(testObj) - - // assert that the expectations were met - testObj.AssertExpectations(t) - - -} -``` - -For more information on how to write mock code, check out the [API documentation for the `mock` package](http://godoc.org/github.com/stretchr/testify/mock). - -You can use the [mockery tool](http://github.com/vektra/mockery) to autogenerate the mock code against an interface as well, making using mocks much quicker. - -[`suite`](http://godoc.org/github.com/stretchr/testify/suite "API documentation") package ------------------------------------------------------------------------------------------ - -The `suite` package provides functionality that you might be used to from more common object oriented languages. With it, you can build a testing suite as a struct, build setup/teardown methods and testing methods on your struct, and run them with 'go test' as per normal. - -An example suite is shown below: - -```go -// Basic imports -import ( - "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" -) - -// Define the suite, and absorb the built-in basic suite -// functionality from testify - including a T() method which -// returns the current testing context -type ExampleTestSuite struct { - suite.Suite - VariableThatShouldStartAtFive int -} - -// Make sure that VariableThatShouldStartAtFive is set to five -// before each test -func (suite *ExampleTestSuite) SetupTest() { - suite.VariableThatShouldStartAtFive = 5 -} - -// All methods that begin with "Test" are run as tests within a -// suite. -func (suite *ExampleTestSuite) TestExample() { - assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) -} - -// In order for 'go test' to run this suite, we need to create -// a normal test function and pass our suite to suite.Run -func TestExampleTestSuite(t *testing.T) { - suite.Run(t, new(ExampleTestSuite)) -} -``` - -For a more complete example, using all of the functionality provided by the suite package, look at our [example testing suite](https://github.com/stretchr/testify/blob/master/suite/suite_test.go) - -For more information on writing suites, check out the [API documentation for the `suite` package](http://godoc.org/github.com/stretchr/testify/suite). - -`Suite` object has assertion methods: - -```go -// Basic imports -import ( - "testing" - "github.com/stretchr/testify/suite" -) - -// Define the suite, and absorb the built-in basic suite -// functionality from testify - including assertion methods. -type ExampleTestSuite struct { - suite.Suite - VariableThatShouldStartAtFive int -} - -// Make sure that VariableThatShouldStartAtFive is set to five -// before each test -func (suite *ExampleTestSuite) SetupTest() { - suite.VariableThatShouldStartAtFive = 5 -} - -// All methods that begin with "Test" are run as tests within a -// suite. -func (suite *ExampleTestSuite) TestExample() { - suite.Equal(suite.VariableThatShouldStartAtFive, 5) -} - -// In order for 'go test' to run this suite, we need to create -// a normal test function and pass our suite to suite.Run -func TestExampleTestSuite(t *testing.T) { - suite.Run(t, new(ExampleTestSuite)) -} -``` - ------- - -Installation -============ - -To install Testify, use `go get`: - - go get github.com/stretchr/testify - -This will then make the following packages available to you: - - github.com/stretchr/testify/assert - github.com/stretchr/testify/require - github.com/stretchr/testify/mock - github.com/stretchr/testify/suite - github.com/stretchr/testify/http (deprecated) - -Import the `testify/assert` package into your code using this template: - -```go -package yours - -import ( - "testing" - "github.com/stretchr/testify/assert" -) - -func TestSomething(t *testing.T) { - - assert.True(t, true, "True is true!") - -} -``` - ------- - -Staying up to date -================== - -To update Testify to the latest version, use `go get -u github.com/stretchr/testify`. - ------- - -Supported go versions -================== - -We support the three major Go versions, which are 1.9, 1.10, and 1.11 at the moment. - ------- - -Contributing -============ - -Please feel free to submit issues, fork the repository and send pull requests! - -When submitting an issue, we ask that you please include a complete test function that demonstrates the issue. Extra credit for those using Testify to write the test code that demonstrates it. - ------- - -License -======= - -This project is licensed under the terms of the MIT license. diff --git a/src/vendor/github.com/stretchr/testify/_codegen/main.go b/src/vendor/github.com/stretchr/testify/_codegen/main.go deleted file mode 100644 index 2e5e8124ff17c8eae9e317e09e58ff4246f941b6..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/_codegen/main.go +++ /dev/null @@ -1,316 +0,0 @@ -// This program reads all assertion functions from the assert package and -// automatically generates the corresponding requires and forwarded assertions - -package main - -import ( - "bytes" - "flag" - "fmt" - "go/ast" - "go/build" - "go/doc" - "go/format" - "go/importer" - "go/parser" - "go/token" - "go/types" - "io" - "io/ioutil" - "log" - "os" - "path" - "regexp" - "strings" - "text/template" - - "github.com/ernesto-jimenez/gogen/imports" -) - -var ( - pkg = flag.String("assert-path", "github.com/stretchr/testify/assert", "Path to the assert package") - includeF = flag.Bool("include-format-funcs", false, "include format functions such as Errorf and Equalf") - outputPkg = flag.String("output-package", "", "package for the resulting code") - tmplFile = flag.String("template", "", "What file to load the function template from") - out = flag.String("out", "", "What file to write the source code to") -) - -func main() { - flag.Parse() - - scope, docs, err := parsePackageSource(*pkg) - if err != nil { - log.Fatal(err) - } - - importer, funcs, err := analyzeCode(scope, docs) - if err != nil { - log.Fatal(err) - } - - if err := generateCode(importer, funcs); err != nil { - log.Fatal(err) - } -} - -func generateCode(importer imports.Importer, funcs []testFunc) error { - buff := bytes.NewBuffer(nil) - - tmplHead, tmplFunc, err := parseTemplates() - if err != nil { - return err - } - - // Generate header - if err := tmplHead.Execute(buff, struct { - Name string - Imports map[string]string - }{ - *outputPkg, - importer.Imports(), - }); err != nil { - return err - } - - // Generate funcs - for _, fn := range funcs { - buff.Write([]byte("\n\n")) - if err := tmplFunc.Execute(buff, &fn); err != nil { - return err - } - } - - code, err := format.Source(buff.Bytes()) - if err != nil { - return err - } - - // Write file - output, err := outputFile() - if err != nil { - return err - } - defer output.Close() - _, err = io.Copy(output, bytes.NewReader(code)) - return err -} - -func parseTemplates() (*template.Template, *template.Template, error) { - tmplHead, err := template.New("header").Parse(headerTemplate) - if err != nil { - return nil, nil, err - } - if *tmplFile != "" { - f, err := ioutil.ReadFile(*tmplFile) - if err != nil { - return nil, nil, err - } - funcTemplate = string(f) - } - tmpl, err := template.New("function").Parse(funcTemplate) - if err != nil { - return nil, nil, err - } - return tmplHead, tmpl, nil -} - -func outputFile() (*os.File, error) { - filename := *out - if filename == "-" || (filename == "" && *tmplFile == "") { - return os.Stdout, nil - } - if filename == "" { - filename = strings.TrimSuffix(strings.TrimSuffix(*tmplFile, ".tmpl"), ".go") + ".go" - } - return os.Create(filename) -} - -// analyzeCode takes the types scope and the docs and returns the import -// information and information about all the assertion functions. -func analyzeCode(scope *types.Scope, docs *doc.Package) (imports.Importer, []testFunc, error) { - testingT := scope.Lookup("TestingT").Type().Underlying().(*types.Interface) - - importer := imports.New(*outputPkg) - var funcs []testFunc - // Go through all the top level functions - for _, fdocs := range docs.Funcs { - // Find the function - obj := scope.Lookup(fdocs.Name) - - fn, ok := obj.(*types.Func) - if !ok { - continue - } - // Check function signature has at least two arguments - sig := fn.Type().(*types.Signature) - if sig.Params().Len() < 2 { - continue - } - // Check first argument is of type testingT - first, ok := sig.Params().At(0).Type().(*types.Named) - if !ok { - continue - } - firstType, ok := first.Underlying().(*types.Interface) - if !ok { - continue - } - if !types.Implements(firstType, testingT) { - continue - } - - // Skip functions ending with f - if strings.HasSuffix(fdocs.Name, "f") && !*includeF { - continue - } - - funcs = append(funcs, testFunc{*outputPkg, fdocs, fn}) - importer.AddImportsFrom(sig.Params()) - } - return importer, funcs, nil -} - -// parsePackageSource returns the types scope and the package documentation from the package -func parsePackageSource(pkg string) (*types.Scope, *doc.Package, error) { - pd, err := build.Import(pkg, ".", 0) - if err != nil { - return nil, nil, err - } - - fset := token.NewFileSet() - files := make(map[string]*ast.File) - fileList := make([]*ast.File, len(pd.GoFiles)) - for i, fname := range pd.GoFiles { - src, err := ioutil.ReadFile(path.Join(pd.SrcRoot, pd.ImportPath, fname)) - if err != nil { - return nil, nil, err - } - f, err := parser.ParseFile(fset, fname, src, parser.ParseComments|parser.AllErrors) - if err != nil { - return nil, nil, err - } - files[fname] = f - fileList[i] = f - } - - cfg := types.Config{ - Importer: importer.Default(), - } - info := types.Info{ - Defs: make(map[*ast.Ident]types.Object), - } - tp, err := cfg.Check(pkg, fset, fileList, &info) - if err != nil { - return nil, nil, err - } - - scope := tp.Scope() - - ap, _ := ast.NewPackage(fset, files, nil, nil) - docs := doc.New(ap, pkg, 0) - - return scope, docs, nil -} - -type testFunc struct { - CurrentPkg string - DocInfo *doc.Func - TypeInfo *types.Func -} - -func (f *testFunc) Qualifier(p *types.Package) string { - if p == nil || p.Name() == f.CurrentPkg { - return "" - } - return p.Name() -} - -func (f *testFunc) Params() string { - sig := f.TypeInfo.Type().(*types.Signature) - params := sig.Params() - p := "" - comma := "" - to := params.Len() - var i int - - if sig.Variadic() { - to-- - } - for i = 1; i < to; i++ { - param := params.At(i) - p += fmt.Sprintf("%s%s %s", comma, param.Name(), types.TypeString(param.Type(), f.Qualifier)) - comma = ", " - } - if sig.Variadic() { - param := params.At(params.Len() - 1) - p += fmt.Sprintf("%s%s ...%s", comma, param.Name(), types.TypeString(param.Type().(*types.Slice).Elem(), f.Qualifier)) - } - return p -} - -func (f *testFunc) ForwardedParams() string { - sig := f.TypeInfo.Type().(*types.Signature) - params := sig.Params() - p := "" - comma := "" - to := params.Len() - var i int - - if sig.Variadic() { - to-- - } - for i = 1; i < to; i++ { - param := params.At(i) - p += fmt.Sprintf("%s%s", comma, param.Name()) - comma = ", " - } - if sig.Variadic() { - param := params.At(params.Len() - 1) - p += fmt.Sprintf("%s%s...", comma, param.Name()) - } - return p -} - -func (f *testFunc) ParamsFormat() string { - return strings.Replace(f.Params(), "msgAndArgs", "msg string, args", 1) -} - -func (f *testFunc) ForwardedParamsFormat() string { - return strings.Replace(f.ForwardedParams(), "msgAndArgs", "append([]interface{}{msg}, args...)", 1) -} - -func (f *testFunc) Comment() string { - return "// " + strings.Replace(strings.TrimSpace(f.DocInfo.Doc), "\n", "\n// ", -1) -} - -func (f *testFunc) CommentFormat() string { - search := fmt.Sprintf("%s", f.DocInfo.Name) - replace := fmt.Sprintf("%sf", f.DocInfo.Name) - comment := strings.Replace(f.Comment(), search, replace, -1) - exp := regexp.MustCompile(replace + `\(((\(\)|[^)])+)\)`) - return exp.ReplaceAllString(comment, replace+`($1, "error message %s", "formatted")`) -} - -func (f *testFunc) CommentWithoutT(receiver string) string { - search := fmt.Sprintf("assert.%s(t, ", f.DocInfo.Name) - replace := fmt.Sprintf("%s.%s(", receiver, f.DocInfo.Name) - return strings.Replace(f.Comment(), search, replace, -1) -} - -var headerTemplate = `/* -* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen -* THIS FILE MUST NOT BE EDITED BY HAND -*/ - -package {{.Name}} - -import ( -{{range $path, $name := .Imports}} - {{$name}} "{{$path}}"{{end}} -) -` - -var funcTemplate = `{{.Comment}} -func (fwd *AssertionsForwarder) {{.DocInfo.Name}}({{.Params}}) bool { - return assert.{{.DocInfo.Name}}({{.ForwardedParams}}) -}` diff --git a/src/vendor/github.com/stretchr/testify/assert/assertions_test.go b/src/vendor/github.com/stretchr/testify/assert/assertions_test.go deleted file mode 100644 index 00e2d21fc858b4e0e64fbed05fea6348daf15179..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/assert/assertions_test.go +++ /dev/null @@ -1,1803 +0,0 @@ -package assert - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "math" - "os" - "reflect" - "regexp" - "runtime" - "strings" - "testing" - "time" -) - -var ( - i interface{} - zeros = []interface{}{ - false, - byte(0), - complex64(0), - complex128(0), - float32(0), - float64(0), - int(0), - int8(0), - int16(0), - int32(0), - int64(0), - rune(0), - uint(0), - uint8(0), - uint16(0), - uint32(0), - uint64(0), - uintptr(0), - "", - [0]interface{}{}, - []interface{}(nil), - struct{ x int }{}, - (*interface{})(nil), - (func())(nil), - nil, - interface{}(nil), - map[interface{}]interface{}(nil), - (chan interface{})(nil), - (<-chan interface{})(nil), - (chan<- interface{})(nil), - } - nonZeros = []interface{}{ - true, - byte(1), - complex64(1), - complex128(1), - float32(1), - float64(1), - int(1), - int8(1), - int16(1), - int32(1), - int64(1), - rune(1), - uint(1), - uint8(1), - uint16(1), - uint32(1), - uint64(1), - uintptr(1), - "s", - [1]interface{}{1}, - []interface{}{}, - struct{ x int }{1}, - (*interface{})(&i), - (func())(func() {}), - interface{}(1), - map[interface{}]interface{}{}, - (chan interface{})(make(chan interface{})), - (<-chan interface{})(make(chan interface{})), - (chan<- interface{})(make(chan interface{})), - } -) - -// AssertionTesterInterface defines an interface to be used for testing assertion methods -type AssertionTesterInterface interface { - TestMethod() -} - -// AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface -type AssertionTesterConformingObject struct { -} - -func (a *AssertionTesterConformingObject) TestMethod() { -} - -// AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface -type AssertionTesterNonConformingObject struct { -} - -func TestObjectsAreEqual(t *testing.T) { - - if !ObjectsAreEqual("Hello World", "Hello World") { - t.Error("objectsAreEqual should return true") - } - if !ObjectsAreEqual(123, 123) { - t.Error("objectsAreEqual should return true") - } - if !ObjectsAreEqual(123.5, 123.5) { - t.Error("objectsAreEqual should return true") - } - if !ObjectsAreEqual([]byte("Hello World"), []byte("Hello World")) { - t.Error("objectsAreEqual should return true") - } - if !ObjectsAreEqual(nil, nil) { - t.Error("objectsAreEqual should return true") - } - if ObjectsAreEqual(map[int]int{5: 10}, map[int]int{10: 20}) { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual('x', "x") { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual("x", 'x') { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual(0, 0.1) { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual(0.1, 0) { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual(uint32(10), int32(10)) { - t.Error("objectsAreEqual should return false") - } - if !ObjectsAreEqualValues(uint32(10), int32(10)) { - t.Error("ObjectsAreEqualValues should return true") - } - if ObjectsAreEqualValues(0, nil) { - t.Fail() - } - if ObjectsAreEqualValues(nil, 0) { - t.Fail() - } - -} - -func TestImplements(t *testing.T) { - - mockT := new(testing.T) - - if !Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) { - t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface") - } - if Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) { - t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface") - } - if Implements(mockT, (*AssertionTesterInterface)(nil), nil) { - t.Error("Implements method should return false: nil does not implement AssertionTesterInterface") - } - -} - -func TestIsType(t *testing.T) { - - mockT := new(testing.T) - - if !IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { - t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject") - } - if IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) { - t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject") - } - -} - -type myType string - -func TestEqual(t *testing.T) { - - mockT := new(testing.T) - - if !Equal(mockT, "Hello World", "Hello World") { - t.Error("Equal should return true") - } - if !Equal(mockT, 123, 123) { - t.Error("Equal should return true") - } - if !Equal(mockT, 123.5, 123.5) { - t.Error("Equal should return true") - } - if !Equal(mockT, []byte("Hello World"), []byte("Hello World")) { - t.Error("Equal should return true") - } - if !Equal(mockT, nil, nil) { - t.Error("Equal should return true") - } - if !Equal(mockT, int32(123), int32(123)) { - t.Error("Equal should return true") - } - if !Equal(mockT, uint64(123), uint64(123)) { - t.Error("Equal should return true") - } - if !Equal(mockT, myType("1"), myType("1")) { - t.Error("Equal should return true") - } - if !Equal(mockT, &struct{}{}, &struct{}{}) { - t.Error("Equal should return true (pointer equality is based on equality of underlying value)") - } - var m map[string]interface{} - if Equal(mockT, m["bar"], "something") { - t.Error("Equal should return false") - } - if Equal(mockT, myType("1"), myType("2")) { - t.Error("Equal should return false") - } -} - -// bufferT implements TestingT. Its implementation of Errorf writes the output that would be produced by -// testing.T.Errorf to an internal bytes.Buffer. -type bufferT struct { - buf bytes.Buffer -} - -func (t *bufferT) Errorf(format string, args ...interface{}) { - // implementation of decorate is copied from testing.T - decorate := func(s string) string { - _, file, line, ok := runtime.Caller(3) // decorate + log + public function. - if ok { - // Truncate file name at last file name separator. - if index := strings.LastIndex(file, "/"); index >= 0 { - file = file[index+1:] - } else if index = strings.LastIndex(file, "\\"); index >= 0 { - file = file[index+1:] - } - } else { - file = "???" - line = 1 - } - buf := new(bytes.Buffer) - // Every line is indented at least one tab. - buf.WriteByte('\t') - fmt.Fprintf(buf, "%s:%d: ", file, line) - lines := strings.Split(s, "\n") - if l := len(lines); l > 1 && lines[l-1] == "" { - lines = lines[:l-1] - } - for i, line := range lines { - if i > 0 { - // Second and subsequent lines are indented an extra tab. - buf.WriteString("\n\t\t") - } - buf.WriteString(line) - } - buf.WriteByte('\n') - return buf.String() - } - t.buf.WriteString(decorate(fmt.Sprintf(format, args...))) -} - -func TestStringEqual(t *testing.T) { - for i, currCase := range []struct { - equalWant string - equalGot string - msgAndArgs []interface{} - want string - }{ - {equalWant: "hi, \nmy name is", equalGot: "what,\nmy name is", want: "\tassertions.go:\\d+: \n\t+Error Trace:\t\n\t+Error:\\s+Not equal:\\s+\n\\s+expected: \"hi, \\\\nmy name is\"\n\\s+actual\\s+: \"what,\\\\nmy name is\"\n\\s+Diff:\n\\s+-+ Expected\n\\s+\\++ Actual\n\\s+@@ -1,2 \\+1,2 @@\n\\s+-hi, \n\\s+\\+what,\n\\s+my name is"}, - } { - mockT := &bufferT{} - Equal(mockT, currCase.equalWant, currCase.equalGot, currCase.msgAndArgs...) - Regexp(t, regexp.MustCompile(currCase.want), mockT.buf.String(), "Case %d", i) - } -} - -func TestEqualFormatting(t *testing.T) { - for i, currCase := range []struct { - equalWant string - equalGot string - msgAndArgs []interface{} - want string - }{ - {equalWant: "want", equalGot: "got", want: "\tassertions.go:\\d+: \n\t+Error Trace:\t\n\t+Error:\\s+Not equal:\\s+\n\\s+expected: \"want\"\n\\s+actual\\s+: \"got\"\n\\s+Diff:\n\\s+-+ Expected\n\\s+\\++ Actual\n\\s+@@ -1 \\+1 @@\n\\s+-want\n\\s+\\+got\n"}, - {equalWant: "want", equalGot: "got", msgAndArgs: []interface{}{"hello, %v!", "world"}, want: "\tassertions.go:[0-9]+: \n\t+Error Trace:\t\n\t+Error:\\s+Not equal:\\s+\n\\s+expected: \"want\"\n\\s+actual\\s+: \"got\"\n\\s+Diff:\n\\s+-+ Expected\n\\s+\\++ Actual\n\\s+@@ -1 \\+1 @@\n\\s+-want\n\\s+\\+got\n\\s+Messages:\\s+hello, world!\n"}, - {equalWant: "want", equalGot: "got", msgAndArgs: []interface{}{123}, want: "\tassertions.go:[0-9]+: \n\t+Error Trace:\t\n\t+Error:\\s+Not equal:\\s+\n\\s+expected: \"want\"\n\\s+actual\\s+: \"got\"\n\\s+Diff:\n\\s+-+ Expected\n\\s+\\++ Actual\n\\s+@@ -1 \\+1 @@\n\\s+-want\n\\s+\\+got\n\\s+Messages:\\s+123\n"}, - {equalWant: "want", equalGot: "got", msgAndArgs: []interface{}{struct{ a string }{"hello"}}, want: "\tassertions.go:[0-9]+: \n\t+Error Trace:\t\n\t+Error:\\s+Not equal:\\s+\n\\s+expected: \"want\"\n\\s+actual\\s+: \"got\"\n\\s+Diff:\n\\s+-+ Expected\n\\s+\\++ Actual\n\\s+@@ -1 \\+1 @@\n\\s+-want\n\\s+\\+got\n\\s+Messages:\\s+{a:hello}\n"}, - } { - mockT := &bufferT{} - Equal(mockT, currCase.equalWant, currCase.equalGot, currCase.msgAndArgs...) - Regexp(t, regexp.MustCompile(currCase.want), mockT.buf.String(), "Case %d", i) - } -} - -func TestFormatUnequalValues(t *testing.T) { - expected, actual := formatUnequalValues("foo", "bar") - Equal(t, `"foo"`, expected, "value should not include type") - Equal(t, `"bar"`, actual, "value should not include type") - - expected, actual = formatUnequalValues(123, 123) - Equal(t, `123`, expected, "value should not include type") - Equal(t, `123`, actual, "value should not include type") - - expected, actual = formatUnequalValues(int64(123), int32(123)) - Equal(t, `int64(123)`, expected, "value should include type") - Equal(t, `int32(123)`, actual, "value should include type") - - expected, actual = formatUnequalValues(int64(123), nil) - Equal(t, `int64(123)`, expected, "value should include type") - Equal(t, `()`, actual, "value should include type") - - type testStructType struct { - Val string - } - - expected, actual = formatUnequalValues(&testStructType{Val: "test"}, &testStructType{Val: "test"}) - Equal(t, `&assert.testStructType{Val:"test"}`, expected, "value should not include type annotation") - Equal(t, `&assert.testStructType{Val:"test"}`, actual, "value should not include type annotation") -} - -func TestNotNil(t *testing.T) { - - mockT := new(testing.T) - - if !NotNil(mockT, new(AssertionTesterConformingObject)) { - t.Error("NotNil should return true: object is not nil") - } - if NotNil(mockT, nil) { - t.Error("NotNil should return false: object is nil") - } - if NotNil(mockT, (*struct{})(nil)) { - t.Error("NotNil should return false: object is (*struct{})(nil)") - } - -} - -func TestNil(t *testing.T) { - - mockT := new(testing.T) - - if !Nil(mockT, nil) { - t.Error("Nil should return true: object is nil") - } - if !Nil(mockT, (*struct{})(nil)) { - t.Error("Nil should return true: object is (*struct{})(nil)") - } - if Nil(mockT, new(AssertionTesterConformingObject)) { - t.Error("Nil should return false: object is not nil") - } - -} - -func TestTrue(t *testing.T) { - - mockT := new(testing.T) - - if !True(mockT, true) { - t.Error("True should return true") - } - if True(mockT, false) { - t.Error("True should return false") - } - -} - -func TestFalse(t *testing.T) { - - mockT := new(testing.T) - - if !False(mockT, false) { - t.Error("False should return true") - } - if False(mockT, true) { - t.Error("False should return false") - } - -} - -func TestExactly(t *testing.T) { - - mockT := new(testing.T) - - a := float32(1) - b := float64(1) - c := float32(1) - d := float32(2) - - if Exactly(mockT, a, b) { - t.Error("Exactly should return false") - } - if Exactly(mockT, a, d) { - t.Error("Exactly should return false") - } - if !Exactly(mockT, a, c) { - t.Error("Exactly should return true") - } - - if Exactly(mockT, nil, a) { - t.Error("Exactly should return false") - } - if Exactly(mockT, a, nil) { - t.Error("Exactly should return false") - } - -} - -func TestNotEqual(t *testing.T) { - - mockT := new(testing.T) - - if !NotEqual(mockT, "Hello World", "Hello World!") { - t.Error("NotEqual should return true") - } - if !NotEqual(mockT, 123, 1234) { - t.Error("NotEqual should return true") - } - if !NotEqual(mockT, 123.5, 123.55) { - t.Error("NotEqual should return true") - } - if !NotEqual(mockT, []byte("Hello World"), []byte("Hello World!")) { - t.Error("NotEqual should return true") - } - if !NotEqual(mockT, nil, new(AssertionTesterConformingObject)) { - t.Error("NotEqual should return true") - } - funcA := func() int { return 23 } - funcB := func() int { return 42 } - if NotEqual(mockT, funcA, funcB) { - t.Error("NotEqual should return false") - } - - if NotEqual(mockT, "Hello World", "Hello World") { - t.Error("NotEqual should return false") - } - if NotEqual(mockT, 123, 123) { - t.Error("NotEqual should return false") - } - if NotEqual(mockT, 123.5, 123.5) { - t.Error("NotEqual should return false") - } - if NotEqual(mockT, []byte("Hello World"), []byte("Hello World")) { - t.Error("NotEqual should return false") - } - if NotEqual(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { - t.Error("NotEqual should return false") - } - if NotEqual(mockT, &struct{}{}, &struct{}{}) { - t.Error("NotEqual should return false") - } -} - -type A struct { - Name, Value string -} - -func TestContains(t *testing.T) { - - mockT := new(testing.T) - list := []string{"Foo", "Bar"} - complexList := []*A{ - {"b", "c"}, - {"d", "e"}, - {"g", "h"}, - {"j", "k"}, - } - simpleMap := map[interface{}]interface{}{"Foo": "Bar"} - - if !Contains(mockT, "Hello World", "Hello") { - t.Error("Contains should return true: \"Hello World\" contains \"Hello\"") - } - if Contains(mockT, "Hello World", "Salut") { - t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"") - } - - if !Contains(mockT, list, "Bar") { - t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Bar\"") - } - if Contains(mockT, list, "Salut") { - t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"") - } - if !Contains(mockT, complexList, &A{"g", "h"}) { - t.Error("Contains should return true: complexList contains {\"g\", \"h\"}") - } - if Contains(mockT, complexList, &A{"g", "e"}) { - t.Error("Contains should return false: complexList contains {\"g\", \"e\"}") - } - if Contains(mockT, complexList, &A{"g", "e"}) { - t.Error("Contains should return false: complexList contains {\"g\", \"e\"}") - } - if !Contains(mockT, simpleMap, "Foo") { - t.Error("Contains should return true: \"{\"Foo\": \"Bar\"}\" contains \"Foo\"") - } - if Contains(mockT, simpleMap, "Bar") { - t.Error("Contains should return false: \"{\"Foo\": \"Bar\"}\" does not contains \"Bar\"") - } -} - -func TestNotContains(t *testing.T) { - - mockT := new(testing.T) - list := []string{"Foo", "Bar"} - simpleMap := map[interface{}]interface{}{"Foo": "Bar"} - - if !NotContains(mockT, "Hello World", "Hello!") { - t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"") - } - if NotContains(mockT, "Hello World", "Hello") { - t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"") - } - - if !NotContains(mockT, list, "Foo!") { - t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"") - } - if NotContains(mockT, list, "Foo") { - t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") - } - if NotContains(mockT, simpleMap, "Foo") { - t.Error("Contains should return true: \"{\"Foo\": \"Bar\"}\" contains \"Foo\"") - } - if !NotContains(mockT, simpleMap, "Bar") { - t.Error("Contains should return false: \"{\"Foo\": \"Bar\"}\" does not contains \"Bar\"") - } -} - -func TestSubset(t *testing.T) { - mockT := new(testing.T) - - if !Subset(mockT, []int{1, 2, 3}, nil) { - t.Error("Subset should return true: given subset is nil") - } - if !Subset(mockT, []int{1, 2, 3}, []int{}) { - t.Error("Subset should return true: any set contains the nil set") - } - if !Subset(mockT, []int{1, 2, 3}, []int{1, 2}) { - t.Error("Subset should return true: [1, 2, 3] contains [1, 2]") - } - if !Subset(mockT, []int{1, 2, 3}, []int{1, 2, 3}) { - t.Error("Subset should return true: [1, 2, 3] contains [1, 2, 3]") - } - if !Subset(mockT, []string{"hello", "world"}, []string{"hello"}) { - t.Error("Subset should return true: [\"hello\", \"world\"] contains [\"hello\"]") - } - - if Subset(mockT, []string{"hello", "world"}, []string{"hello", "testify"}) { - t.Error("Subset should return false: [\"hello\", \"world\"] does not contain [\"hello\", \"testify\"]") - } - if Subset(mockT, []int{1, 2, 3}, []int{4, 5}) { - t.Error("Subset should return false: [1, 2, 3] does not contain [4, 5]") - } - if Subset(mockT, []int{1, 2, 3}, []int{1, 5}) { - t.Error("Subset should return false: [1, 2, 3] does not contain [1, 5]") - } -} - -func TestNotSubset(t *testing.T) { - mockT := new(testing.T) - - if NotSubset(mockT, []int{1, 2, 3}, nil) { - t.Error("NotSubset should return false: given subset is nil") - } - if NotSubset(mockT, []int{1, 2, 3}, []int{}) { - t.Error("NotSubset should return false: any set contains the nil set") - } - if NotSubset(mockT, []int{1, 2, 3}, []int{1, 2}) { - t.Error("NotSubset should return false: [1, 2, 3] contains [1, 2]") - } - if NotSubset(mockT, []int{1, 2, 3}, []int{1, 2, 3}) { - t.Error("NotSubset should return false: [1, 2, 3] contains [1, 2, 3]") - } - if NotSubset(mockT, []string{"hello", "world"}, []string{"hello"}) { - t.Error("NotSubset should return false: [\"hello\", \"world\"] contains [\"hello\"]") - } - - if !NotSubset(mockT, []string{"hello", "world"}, []string{"hello", "testify"}) { - t.Error("NotSubset should return true: [\"hello\", \"world\"] does not contain [\"hello\", \"testify\"]") - } - if !NotSubset(mockT, []int{1, 2, 3}, []int{4, 5}) { - t.Error("NotSubset should return true: [1, 2, 3] does not contain [4, 5]") - } - if !NotSubset(mockT, []int{1, 2, 3}, []int{1, 5}) { - t.Error("NotSubset should return true: [1, 2, 3] does not contain [1, 5]") - } -} - -func TestNotSubsetNil(t *testing.T) { - mockT := new(testing.T) - NotSubset(mockT, []string{"foo"}, nil) - if !mockT.Failed() { - t.Error("NotSubset on nil set should have failed the test") - } -} - -func Test_includeElement(t *testing.T) { - - list1 := []string{"Foo", "Bar"} - list2 := []int{1, 2} - simpleMap := map[interface{}]interface{}{"Foo": "Bar"} - - ok, found := includeElement("Hello World", "World") - True(t, ok) - True(t, found) - - ok, found = includeElement(list1, "Foo") - True(t, ok) - True(t, found) - - ok, found = includeElement(list1, "Bar") - True(t, ok) - True(t, found) - - ok, found = includeElement(list2, 1) - True(t, ok) - True(t, found) - - ok, found = includeElement(list2, 2) - True(t, ok) - True(t, found) - - ok, found = includeElement(list1, "Foo!") - True(t, ok) - False(t, found) - - ok, found = includeElement(list2, 3) - True(t, ok) - False(t, found) - - ok, found = includeElement(list2, "1") - True(t, ok) - False(t, found) - - ok, found = includeElement(simpleMap, "Foo") - True(t, ok) - True(t, found) - - ok, found = includeElement(simpleMap, "Bar") - True(t, ok) - False(t, found) - - ok, found = includeElement(1433, "1") - False(t, ok) - False(t, found) -} - -func TestElementsMatch(t *testing.T) { - mockT := new(testing.T) - - if !ElementsMatch(mockT, nil, nil) { - t.Error("ElementsMatch should return true") - } - if !ElementsMatch(mockT, []int{}, []int{}) { - t.Error("ElementsMatch should return true") - } - if !ElementsMatch(mockT, []int{1}, []int{1}) { - t.Error("ElementsMatch should return true") - } - if !ElementsMatch(mockT, []int{1, 1}, []int{1, 1}) { - t.Error("ElementsMatch should return true") - } - if !ElementsMatch(mockT, []int{1, 2}, []int{1, 2}) { - t.Error("ElementsMatch should return true") - } - if !ElementsMatch(mockT, []int{1, 2}, []int{2, 1}) { - t.Error("ElementsMatch should return true") - } - if !ElementsMatch(mockT, [2]int{1, 2}, [2]int{2, 1}) { - t.Error("ElementsMatch should return true") - } - if !ElementsMatch(mockT, []string{"hello", "world"}, []string{"world", "hello"}) { - t.Error("ElementsMatch should return true") - } - if !ElementsMatch(mockT, []string{"hello", "hello"}, []string{"hello", "hello"}) { - t.Error("ElementsMatch should return true") - } - if !ElementsMatch(mockT, []string{"hello", "hello", "world"}, []string{"hello", "world", "hello"}) { - t.Error("ElementsMatch should return true") - } - if !ElementsMatch(mockT, [3]string{"hello", "hello", "world"}, [3]string{"hello", "world", "hello"}) { - t.Error("ElementsMatch should return true") - } - if !ElementsMatch(mockT, []int{}, nil) { - t.Error("ElementsMatch should return true") - } - - if ElementsMatch(mockT, []int{1}, []int{1, 1}) { - t.Error("ElementsMatch should return false") - } - if ElementsMatch(mockT, []int{1, 2}, []int{2, 2}) { - t.Error("ElementsMatch should return false") - } - if ElementsMatch(mockT, []string{"hello", "hello"}, []string{"hello"}) { - t.Error("ElementsMatch should return false") - } -} - -func TestCondition(t *testing.T) { - mockT := new(testing.T) - - if !Condition(mockT, func() bool { return true }, "Truth") { - t.Error("Condition should return true") - } - - if Condition(mockT, func() bool { return false }, "Lie") { - t.Error("Condition should return false") - } - -} - -func TestDidPanic(t *testing.T) { - - if funcDidPanic, _ := didPanic(func() { - panic("Panic!") - }); !funcDidPanic { - t.Error("didPanic should return true") - } - - if funcDidPanic, _ := didPanic(func() { - }); funcDidPanic { - t.Error("didPanic should return false") - } - -} - -func TestPanics(t *testing.T) { - - mockT := new(testing.T) - - if !Panics(mockT, func() { - panic("Panic!") - }) { - t.Error("Panics should return true") - } - - if Panics(mockT, func() { - }) { - t.Error("Panics should return false") - } - -} - -func TestPanicsWithValue(t *testing.T) { - - mockT := new(testing.T) - - if !PanicsWithValue(mockT, "Panic!", func() { - panic("Panic!") - }) { - t.Error("PanicsWithValue should return true") - } - - if PanicsWithValue(mockT, "Panic!", func() { - }) { - t.Error("PanicsWithValue should return false") - } - - if PanicsWithValue(mockT, "at the disco", func() { - panic("Panic!") - }) { - t.Error("PanicsWithValue should return false") - } -} - -func TestNotPanics(t *testing.T) { - - mockT := new(testing.T) - - if !NotPanics(mockT, func() { - }) { - t.Error("NotPanics should return true") - } - - if NotPanics(mockT, func() { - panic("Panic!") - }) { - t.Error("NotPanics should return false") - } - -} - -func TestNoError(t *testing.T) { - - mockT := new(testing.T) - - // start with a nil error - var err error - - True(t, NoError(mockT, err), "NoError should return True for nil arg") - - // now set an error - err = errors.New("some error") - - False(t, NoError(mockT, err), "NoError with error should return False") - - // returning an empty error interface - err = func() error { - var err *customError - if err != nil { - t.Fatal("err should be nil here") - } - return err - }() - - if err == nil { // err is not nil here! - t.Errorf("Error should be nil due to empty interface: %s", err) - } - - False(t, NoError(mockT, err), "NoError should fail with empty error interface") -} - -type customError struct{} - -func (*customError) Error() string { return "fail" } - -func TestError(t *testing.T) { - - mockT := new(testing.T) - - // start with a nil error - var err error - - False(t, Error(mockT, err), "Error should return False for nil arg") - - // now set an error - err = errors.New("some error") - - True(t, Error(mockT, err), "Error with error should return True") - - // go vet check - True(t, Errorf(mockT, err, "example with %s", "formatted message"), "Errorf with error should rturn True") - - // returning an empty error interface - err = func() error { - var err *customError - if err != nil { - t.Fatal("err should be nil here") - } - return err - }() - - if err == nil { // err is not nil here! - t.Errorf("Error should be nil due to empty interface: %s", err) - } - - True(t, Error(mockT, err), "Error should pass with empty error interface") -} - -func TestEqualError(t *testing.T) { - mockT := new(testing.T) - - // start with a nil error - var err error - False(t, EqualError(mockT, err, ""), - "EqualError should return false for nil arg") - - // now set an error - err = errors.New("some error") - False(t, EqualError(mockT, err, "Not some error"), - "EqualError should return false for different error string") - True(t, EqualError(mockT, err, "some error"), - "EqualError should return true") -} - -func Test_isEmpty(t *testing.T) { - - chWithValue := make(chan struct{}, 1) - chWithValue <- struct{}{} - - True(t, isEmpty("")) - True(t, isEmpty(nil)) - True(t, isEmpty([]string{})) - True(t, isEmpty(0)) - True(t, isEmpty(int32(0))) - True(t, isEmpty(int64(0))) - True(t, isEmpty(false)) - True(t, isEmpty(map[string]string{})) - True(t, isEmpty(new(time.Time))) - True(t, isEmpty(time.Time{})) - True(t, isEmpty(make(chan struct{}))) - False(t, isEmpty("something")) - False(t, isEmpty(errors.New("something"))) - False(t, isEmpty([]string{"something"})) - False(t, isEmpty(1)) - False(t, isEmpty(true)) - False(t, isEmpty(map[string]string{"Hello": "World"})) - False(t, isEmpty(chWithValue)) - -} - -func TestEmpty(t *testing.T) { - - mockT := new(testing.T) - chWithValue := make(chan struct{}, 1) - chWithValue <- struct{}{} - var tiP *time.Time - var tiNP time.Time - var s *string - var f *os.File - sP := &s - x := 1 - xP := &x - - type TString string - type TStruct struct { - x int - s []int - } - - True(t, Empty(mockT, ""), "Empty string is empty") - True(t, Empty(mockT, nil), "Nil is empty") - True(t, Empty(mockT, []string{}), "Empty string array is empty") - True(t, Empty(mockT, 0), "Zero int value is empty") - True(t, Empty(mockT, false), "False value is empty") - True(t, Empty(mockT, make(chan struct{})), "Channel without values is empty") - True(t, Empty(mockT, s), "Nil string pointer is empty") - True(t, Empty(mockT, f), "Nil os.File pointer is empty") - True(t, Empty(mockT, tiP), "Nil time.Time pointer is empty") - True(t, Empty(mockT, tiNP), "time.Time is empty") - True(t, Empty(mockT, TStruct{}), "struct with zero values is empty") - True(t, Empty(mockT, TString("")), "empty aliased string is empty") - True(t, Empty(mockT, sP), "ptr to nil value is empty") - - False(t, Empty(mockT, "something"), "Non Empty string is not empty") - False(t, Empty(mockT, errors.New("something")), "Non nil object is not empty") - False(t, Empty(mockT, []string{"something"}), "Non empty string array is not empty") - False(t, Empty(mockT, 1), "Non-zero int value is not empty") - False(t, Empty(mockT, true), "True value is not empty") - False(t, Empty(mockT, chWithValue), "Channel with values is not empty") - False(t, Empty(mockT, TStruct{x: 1}), "struct with initialized values is empty") - False(t, Empty(mockT, TString("abc")), "non-empty aliased string is empty") - False(t, Empty(mockT, xP), "ptr to non-nil value is not empty") -} - -func TestNotEmpty(t *testing.T) { - - mockT := new(testing.T) - chWithValue := make(chan struct{}, 1) - chWithValue <- struct{}{} - - False(t, NotEmpty(mockT, ""), "Empty string is empty") - False(t, NotEmpty(mockT, nil), "Nil is empty") - False(t, NotEmpty(mockT, []string{}), "Empty string array is empty") - False(t, NotEmpty(mockT, 0), "Zero int value is empty") - False(t, NotEmpty(mockT, false), "False value is empty") - False(t, NotEmpty(mockT, make(chan struct{})), "Channel without values is empty") - - True(t, NotEmpty(mockT, "something"), "Non Empty string is not empty") - True(t, NotEmpty(mockT, errors.New("something")), "Non nil object is not empty") - True(t, NotEmpty(mockT, []string{"something"}), "Non empty string array is not empty") - True(t, NotEmpty(mockT, 1), "Non-zero int value is not empty") - True(t, NotEmpty(mockT, true), "True value is not empty") - True(t, NotEmpty(mockT, chWithValue), "Channel with values is not empty") -} - -func Test_getLen(t *testing.T) { - falseCases := []interface{}{ - nil, - 0, - true, - false, - 'A', - struct{}{}, - } - for _, v := range falseCases { - ok, l := getLen(v) - False(t, ok, "Expected getLen fail to get length of %#v", v) - Equal(t, 0, l, "getLen should return 0 for %#v", v) - } - - ch := make(chan int, 5) - ch <- 1 - ch <- 2 - ch <- 3 - trueCases := []struct { - v interface{} - l int - }{ - {[]int{1, 2, 3}, 3}, - {[...]int{1, 2, 3}, 3}, - {"ABC", 3}, - {map[int]int{1: 2, 2: 4, 3: 6}, 3}, - {ch, 3}, - - {[]int{}, 0}, - {map[int]int{}, 0}, - {make(chan int), 0}, - - {[]int(nil), 0}, - {map[int]int(nil), 0}, - {(chan int)(nil), 0}, - } - - for _, c := range trueCases { - ok, l := getLen(c.v) - True(t, ok, "Expected getLen success to get length of %#v", c.v) - Equal(t, c.l, l) - } -} - -func TestLen(t *testing.T) { - mockT := new(testing.T) - - False(t, Len(mockT, nil, 0), "nil does not have length") - False(t, Len(mockT, 0, 0), "int does not have length") - False(t, Len(mockT, true, 0), "true does not have length") - False(t, Len(mockT, false, 0), "false does not have length") - False(t, Len(mockT, 'A', 0), "Rune does not have length") - False(t, Len(mockT, struct{}{}, 0), "Struct does not have length") - - ch := make(chan int, 5) - ch <- 1 - ch <- 2 - ch <- 3 - - cases := []struct { - v interface{} - l int - }{ - {[]int{1, 2, 3}, 3}, - {[...]int{1, 2, 3}, 3}, - {"ABC", 3}, - {map[int]int{1: 2, 2: 4, 3: 6}, 3}, - {ch, 3}, - - {[]int{}, 0}, - {map[int]int{}, 0}, - {make(chan int), 0}, - - {[]int(nil), 0}, - {map[int]int(nil), 0}, - {(chan int)(nil), 0}, - } - - for _, c := range cases { - True(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l) - } - - cases = []struct { - v interface{} - l int - }{ - {[]int{1, 2, 3}, 4}, - {[...]int{1, 2, 3}, 2}, - {"ABC", 2}, - {map[int]int{1: 2, 2: 4, 3: 6}, 4}, - {ch, 2}, - - {[]int{}, 1}, - {map[int]int{}, 1}, - {make(chan int), 1}, - - {[]int(nil), 1}, - {map[int]int(nil), 1}, - {(chan int)(nil), 1}, - } - - for _, c := range cases { - False(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l) - } -} - -func TestWithinDuration(t *testing.T) { - - mockT := new(testing.T) - a := time.Now() - b := a.Add(10 * time.Second) - - True(t, WithinDuration(mockT, a, b, 10*time.Second), "A 10s difference is within a 10s time difference") - True(t, WithinDuration(mockT, b, a, 10*time.Second), "A 10s difference is within a 10s time difference") - - False(t, WithinDuration(mockT, a, b, 9*time.Second), "A 10s difference is not within a 9s time difference") - False(t, WithinDuration(mockT, b, a, 9*time.Second), "A 10s difference is not within a 9s time difference") - - False(t, WithinDuration(mockT, a, b, -9*time.Second), "A 10s difference is not within a 9s time difference") - False(t, WithinDuration(mockT, b, a, -9*time.Second), "A 10s difference is not within a 9s time difference") - - False(t, WithinDuration(mockT, a, b, -11*time.Second), "A 10s difference is not within a 9s time difference") - False(t, WithinDuration(mockT, b, a, -11*time.Second), "A 10s difference is not within a 9s time difference") -} - -func TestInDelta(t *testing.T) { - mockT := new(testing.T) - - True(t, InDelta(mockT, 1.001, 1, 0.01), "|1.001 - 1| <= 0.01") - True(t, InDelta(mockT, 1, 1.001, 0.01), "|1 - 1.001| <= 0.01") - True(t, InDelta(mockT, 1, 2, 1), "|1 - 2| <= 1") - False(t, InDelta(mockT, 1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail") - False(t, InDelta(mockT, 2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail") - False(t, InDelta(mockT, "", nil, 1), "Expected non numerals to fail") - False(t, InDelta(mockT, 42, math.NaN(), 0.01), "Expected NaN for actual to fail") - False(t, InDelta(mockT, math.NaN(), 42, 0.01), "Expected NaN for expected to fail") - - cases := []struct { - a, b interface{} - delta float64 - }{ - {uint8(2), uint8(1), 1}, - {uint16(2), uint16(1), 1}, - {uint32(2), uint32(1), 1}, - {uint64(2), uint64(1), 1}, - - {int(2), int(1), 1}, - {int8(2), int8(1), 1}, - {int16(2), int16(1), 1}, - {int32(2), int32(1), 1}, - {int64(2), int64(1), 1}, - - {float32(2), float32(1), 1}, - {float64(2), float64(1), 1}, - } - - for _, tc := range cases { - True(t, InDelta(mockT, tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta) - } -} - -func TestInDeltaSlice(t *testing.T) { - mockT := new(testing.T) - - True(t, InDeltaSlice(mockT, - []float64{1.001, 0.999}, - []float64{1, 1}, - 0.1), "{1.001, 0.009} is element-wise close to {1, 1} in delta=0.1") - - True(t, InDeltaSlice(mockT, - []float64{1, 2}, - []float64{0, 3}, - 1), "{1, 2} is element-wise close to {0, 3} in delta=1") - - False(t, InDeltaSlice(mockT, - []float64{1, 2}, - []float64{0, 3}, - 0.1), "{1, 2} is not element-wise close to {0, 3} in delta=0.1") - - False(t, InDeltaSlice(mockT, "", nil, 1), "Expected non numeral slices to fail") -} - -func TestInDeltaMapValues(t *testing.T) { - mockT := new(testing.T) - - for _, tc := range []struct { - title string - expect interface{} - actual interface{} - f func(TestingT, bool, ...interface{}) bool - delta float64 - }{ - { - title: "Within delta", - expect: map[string]float64{ - "foo": 1.0, - "bar": 2.0, - }, - actual: map[string]float64{ - "foo": 1.01, - "bar": 1.99, - }, - delta: 0.1, - f: True, - }, - { - title: "Within delta", - expect: map[int]float64{ - 1: 1.0, - 2: 2.0, - }, - actual: map[int]float64{ - 1: 1.0, - 2: 1.99, - }, - delta: 0.1, - f: True, - }, - { - title: "Different number of keys", - expect: map[int]float64{ - 1: 1.0, - 2: 2.0, - }, - actual: map[int]float64{ - 1: 1.0, - }, - delta: 0.1, - f: False, - }, - { - title: "Within delta with zero value", - expect: map[string]float64{ - "zero": 0.0, - }, - actual: map[string]float64{ - "zero": 0.0, - }, - delta: 0.1, - f: True, - }, - { - title: "With missing key with zero value", - expect: map[string]float64{ - "zero": 0.0, - "foo": 0.0, - }, - actual: map[string]float64{ - "zero": 0.0, - "bar": 0.0, - }, - f: False, - }, - } { - tc.f(t, InDeltaMapValues(mockT, tc.expect, tc.actual, tc.delta), tc.title+"\n"+diff(tc.expect, tc.actual)) - } -} - -func TestInEpsilon(t *testing.T) { - mockT := new(testing.T) - - cases := []struct { - a, b interface{} - epsilon float64 - }{ - {uint8(2), uint16(2), .001}, - {2.1, 2.2, 0.1}, - {2.2, 2.1, 0.1}, - {-2.1, -2.2, 0.1}, - {-2.2, -2.1, 0.1}, - {uint64(100), uint8(101), 0.01}, - {0.1, -0.1, 2}, - {0.1, 0, 2}, - {time.Second, time.Second + time.Millisecond, 0.002}, - } - - for _, tc := range cases { - True(t, InEpsilon(t, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon), "test: %q", tc) - } - - cases = []struct { - a, b interface{} - epsilon float64 - }{ - {uint8(2), int16(-2), .001}, - {uint64(100), uint8(102), 0.01}, - {2.1, 2.2, 0.001}, - {2.2, 2.1, 0.001}, - {2.1, -2.2, 1}, - {2.1, "bla-bla", 0}, - {0.1, -0.1, 1.99}, - {0, 0.1, 2}, // expected must be different to zero - {time.Second, time.Second + 10*time.Millisecond, 0.002}, - } - - for _, tc := range cases { - False(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) - } - -} - -func TestInEpsilonSlice(t *testing.T) { - mockT := new(testing.T) - - True(t, InEpsilonSlice(mockT, - []float64{2.2, 2.0}, - []float64{2.1, 2.1}, - 0.06), "{2.2, 2.0} is element-wise close to {2.1, 2.1} in espilon=0.06") - - False(t, InEpsilonSlice(mockT, - []float64{2.2, 2.0}, - []float64{2.1, 2.1}, - 0.04), "{2.2, 2.0} is not element-wise close to {2.1, 2.1} in espilon=0.04") - - False(t, InEpsilonSlice(mockT, "", nil, 1), "Expected non numeral slices to fail") -} - -func TestRegexp(t *testing.T) { - mockT := new(testing.T) - - cases := []struct { - rx, str string - }{ - {"^start", "start of the line"}, - {"end$", "in the end"}, - {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"}, - } - - for _, tc := range cases { - True(t, Regexp(mockT, tc.rx, tc.str)) - True(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str)) - False(t, NotRegexp(mockT, tc.rx, tc.str)) - False(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str)) - } - - cases = []struct { - rx, str string - }{ - {"^asdfastart", "Not the start of the line"}, - {"end$", "in the end."}, - {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"}, - } - - for _, tc := range cases { - False(t, Regexp(mockT, tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str) - False(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str)) - True(t, NotRegexp(mockT, tc.rx, tc.str)) - True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str)) - } -} - -func testAutogeneratedFunction() { - defer func() { - if err := recover(); err == nil { - panic("did not panic") - } - CallerInfo() - }() - t := struct { - io.Closer - }{} - var c io.Closer - c = t - c.Close() -} - -func TestCallerInfoWithAutogeneratedFunctions(t *testing.T) { - NotPanics(t, func() { - testAutogeneratedFunction() - }) -} - -func TestZero(t *testing.T) { - mockT := new(testing.T) - - for _, test := range zeros { - True(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) - } - - for _, test := range nonZeros { - False(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) - } -} - -func TestNotZero(t *testing.T) { - mockT := new(testing.T) - - for _, test := range zeros { - False(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) - } - - for _, test := range nonZeros { - True(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) - } -} - -func TestFileExists(t *testing.T) { - mockT := new(testing.T) - True(t, FileExists(mockT, "assertions.go")) - - mockT = new(testing.T) - False(t, FileExists(mockT, "random_file")) - - mockT = new(testing.T) - False(t, FileExists(mockT, "../_codegen")) -} - -func TestDirExists(t *testing.T) { - mockT := new(testing.T) - False(t, DirExists(mockT, "assertions.go")) - - mockT = new(testing.T) - False(t, DirExists(mockT, "random_dir")) - - mockT = new(testing.T) - True(t, DirExists(mockT, "../_codegen")) -} - -func TestJSONEq_EqualSONString(t *testing.T) { - mockT := new(testing.T) - True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`)) -} - -func TestJSONEq_EquivalentButNotEqual(t *testing.T) { - mockT := new(testing.T) - True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)) -} - -func TestJSONEq_HashOfArraysAndHashes(t *testing.T) { - mockT := new(testing.T) - True(t, JSONEq(mockT, "{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}", - "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}")) -} - -func TestJSONEq_Array(t *testing.T) { - mockT := new(testing.T) - True(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`)) -} - -func TestJSONEq_HashAndArrayNotEquivalent(t *testing.T) { - mockT := new(testing.T) - False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`)) -} - -func TestJSONEq_HashesNotEquivalent(t *testing.T) { - mockT := new(testing.T) - False(t, JSONEq(mockT, `{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)) -} - -func TestJSONEq_ActualIsNotJSON(t *testing.T) { - mockT := new(testing.T) - False(t, JSONEq(mockT, `{"foo": "bar"}`, "Not JSON")) -} - -func TestJSONEq_ExpectedIsNotJSON(t *testing.T) { - mockT := new(testing.T) - False(t, JSONEq(mockT, "Not JSON", `{"foo": "bar", "hello": "world"}`)) -} - -func TestJSONEq_ExpectedAndActualNotJSON(t *testing.T) { - mockT := new(testing.T) - False(t, JSONEq(mockT, "Not JSON", "Not JSON")) -} - -func TestJSONEq_ArraysOfDifferentOrder(t *testing.T) { - mockT := new(testing.T) - False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`)) -} - -func TestDiff(t *testing.T) { - expected := ` - -Diff: ---- Expected -+++ Actual -@@ -1,3 +1,3 @@ - (struct { foo string }) { -- foo: (string) (len=5) "hello" -+ foo: (string) (len=3) "bar" - } -` - actual := diff( - struct{ foo string }{"hello"}, - struct{ foo string }{"bar"}, - ) - Equal(t, expected, actual) - - expected = ` - -Diff: ---- Expected -+++ Actual -@@ -2,5 +2,5 @@ - (int) 1, -- (int) 2, - (int) 3, -- (int) 4 -+ (int) 5, -+ (int) 7 - } -` - actual = diff( - []int{1, 2, 3, 4}, - []int{1, 3, 5, 7}, - ) - Equal(t, expected, actual) - - expected = ` - -Diff: ---- Expected -+++ Actual -@@ -2,4 +2,4 @@ - (int) 1, -- (int) 2, -- (int) 3 -+ (int) 3, -+ (int) 5 - } -` - actual = diff( - []int{1, 2, 3, 4}[0:3], - []int{1, 3, 5, 7}[0:3], - ) - Equal(t, expected, actual) - - expected = ` - -Diff: ---- Expected -+++ Actual -@@ -1,6 +1,6 @@ - (map[string]int) (len=4) { -- (string) (len=4) "four": (int) 4, -+ (string) (len=4) "five": (int) 5, - (string) (len=3) "one": (int) 1, -- (string) (len=5) "three": (int) 3, -- (string) (len=3) "two": (int) 2 -+ (string) (len=5) "seven": (int) 7, -+ (string) (len=5) "three": (int) 3 - } -` - - actual = diff( - map[string]int{"one": 1, "two": 2, "three": 3, "four": 4}, - map[string]int{"one": 1, "three": 3, "five": 5, "seven": 7}, - ) - Equal(t, expected, actual) -} - -func TestDiffEmptyCases(t *testing.T) { - Equal(t, "", diff(nil, nil)) - Equal(t, "", diff(struct{ foo string }{}, nil)) - Equal(t, "", diff(nil, struct{ foo string }{})) - Equal(t, "", diff(1, 2)) - Equal(t, "", diff(1, 2)) - Equal(t, "", diff([]int{1}, []bool{true})) -} - -// Ensure there are no data races -func TestDiffRace(t *testing.T) { - t.Parallel() - - expected := map[string]string{ - "a": "A", - "b": "B", - "c": "C", - } - - actual := map[string]string{ - "d": "D", - "e": "E", - "f": "F", - } - - // run diffs in parallel simulating tests with t.Parallel() - numRoutines := 10 - rChans := make([]chan string, numRoutines) - for idx := range rChans { - rChans[idx] = make(chan string) - go func(ch chan string) { - defer close(ch) - ch <- diff(expected, actual) - }(rChans[idx]) - } - - for _, ch := range rChans { - for msg := range ch { - NotZero(t, msg) // dummy assert - } - } -} - -type mockTestingT struct { -} - -func (m *mockTestingT) Errorf(format string, args ...interface{}) {} - -func TestFailNowWithPlainTestingT(t *testing.T) { - mockT := &mockTestingT{} - - Panics(t, func() { - FailNow(mockT, "failed") - }, "should panic since mockT is missing FailNow()") -} - -type mockFailNowTestingT struct { -} - -func (m *mockFailNowTestingT) Errorf(format string, args ...interface{}) {} - -func (m *mockFailNowTestingT) FailNow() {} - -func TestFailNowWithFullTestingT(t *testing.T) { - mockT := &mockFailNowTestingT{} - - NotPanics(t, func() { - FailNow(mockT, "failed") - }, "should call mockT.FailNow() rather than panicking") -} - -func TestBytesEqual(t *testing.T) { - var cases = []struct { - a, b []byte - }{ - {make([]byte, 2), make([]byte, 2)}, - {make([]byte, 2), make([]byte, 2, 3)}, - {nil, make([]byte, 0)}, - } - for i, c := range cases { - Equal(t, reflect.DeepEqual(c.a, c.b), ObjectsAreEqual(c.a, c.b), "case %d failed", i+1) - } -} - -func BenchmarkBytesEqual(b *testing.B) { - const size = 1024 * 8 - s := make([]byte, size) - for i := range s { - s[i] = byte(i % 255) - } - s2 := make([]byte, size) - copy(s2, s) - - mockT := &mockFailNowTestingT{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - Equal(mockT, s, s2) - } -} - -func TestEqualArgsValidation(t *testing.T) { - err := validateEqualArgs(time.Now, time.Now) - EqualError(t, err, "cannot take func type as argument") -} - -func ExampleComparisonAssertionFunc() { - t := &testing.T{} // provided by test - - adder := func(x, y int) int { - return x + y - } - - type args struct { - x int - y int - } - - tests := []struct { - name string - args args - expect int - assertion ComparisonAssertionFunc - }{ - {"2+2=4", args{2, 2}, 4, Equal}, - {"2+2!=5", args{2, 2}, 5, NotEqual}, - {"2+3==5", args{2, 3}, 5, Exactly}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - tt.assertion(t, tt.expect, adder(tt.args.x, tt.args.y)) - }) - } -} - -func TestComparisonAssertionFunc(t *testing.T) { - type iface interface { - Name() string - } - - tests := []struct { - name string - expect interface{} - got interface{} - assertion ComparisonAssertionFunc - }{ - {"implements", (*iface)(nil), t, Implements}, - {"isType", (*testing.T)(nil), t, IsType}, - {"equal", t, t, Equal}, - {"equalValues", t, t, EqualValues}, - {"exactly", t, t, Exactly}, - {"notEqual", t, nil, NotEqual}, - {"notContains", []int{1, 2, 3}, 4, NotContains}, - {"subset", []int{1, 2, 3, 4}, []int{2, 3}, Subset}, - {"notSubset", []int{1, 2, 3, 4}, []int{0, 3}, NotSubset}, - {"elementsMatch", []byte("abc"), []byte("bac"), ElementsMatch}, - {"regexp", "^t.*y$", "testify", Regexp}, - {"notRegexp", "^t.*y$", "Testify", NotRegexp}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - tt.assertion(t, tt.expect, tt.got) - }) - } -} - -func ExampleValueAssertionFunc() { - t := &testing.T{} // provided by test - - dumbParse := func(input string) interface{} { - var x interface{} - json.Unmarshal([]byte(input), &x) - return x - } - - tests := []struct { - name string - arg string - assertion ValueAssertionFunc - }{ - {"true is not nil", "true", NotNil}, - {"empty string is nil", "", Nil}, - {"zero is not nil", "0", NotNil}, - {"zero is zero", "0", Zero}, - {"false is zero", "false", Zero}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - tt.assertion(t, dumbParse(tt.arg)) - }) - } -} - -func TestValueAssertionFunc(t *testing.T) { - tests := []struct { - name string - value interface{} - assertion ValueAssertionFunc - }{ - {"notNil", true, NotNil}, - {"nil", nil, Nil}, - {"empty", []int{}, Empty}, - {"notEmpty", []int{1}, NotEmpty}, - {"zero", false, Zero}, - {"notZero", 42, NotZero}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - tt.assertion(t, tt.value) - }) - } -} - -func ExampleBoolAssertionFunc() { - t := &testing.T{} // provided by test - - isOkay := func(x int) bool { - return x >= 42 - } - - tests := []struct { - name string - arg int - assertion BoolAssertionFunc - }{ - {"-1 is bad", -1, False}, - {"42 is good", 42, True}, - {"41 is bad", 41, False}, - {"45 is cool", 45, True}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - tt.assertion(t, isOkay(tt.arg)) - }) - } -} - -func TestBoolAssertionFunc(t *testing.T) { - tests := []struct { - name string - value bool - assertion BoolAssertionFunc - }{ - {"true", true, True}, - {"false", false, False}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - tt.assertion(t, tt.value) - }) - } -} - -func ExampleErrorAssertionFunc() { - t := &testing.T{} // provided by test - - dumbParseNum := func(input string, v interface{}) error { - return json.Unmarshal([]byte(input), v) - } - - tests := []struct { - name string - arg string - assertion ErrorAssertionFunc - }{ - {"1.2 is number", "1.2", NoError}, - {"1.2.3 not number", "1.2.3", Error}, - {"true is not number", "true", Error}, - {"3 is number", "3", NoError}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - var x float64 - tt.assertion(t, dumbParseNum(tt.arg, &x)) - }) - } -} - -func TestErrorAssertionFunc(t *testing.T) { - tests := []struct { - name string - err error - assertion ErrorAssertionFunc - }{ - {"noError", nil, NoError}, - {"error", errors.New("whoops"), Error}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - tt.assertion(t, tt.err) - }) - } -} diff --git a/src/vendor/github.com/stretchr/testify/assert/forward_assertions_test.go b/src/vendor/github.com/stretchr/testify/assert/forward_assertions_test.go deleted file mode 100644 index 22e1df1d9619c6528be93d126444299c8ba27fd9..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/assert/forward_assertions_test.go +++ /dev/null @@ -1,611 +0,0 @@ -package assert - -import ( - "errors" - "regexp" - "testing" - "time" -) - -func TestImplementsWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) { - t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface") - } - if assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) { - t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface") - } -} - -func TestIsTypeWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { - t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject") - } - if assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) { - t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject") - } - -} - -func TestEqualWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.Equal("Hello World", "Hello World") { - t.Error("Equal should return true") - } - if !assert.Equal(123, 123) { - t.Error("Equal should return true") - } - if !assert.Equal(123.5, 123.5) { - t.Error("Equal should return true") - } - if !assert.Equal([]byte("Hello World"), []byte("Hello World")) { - t.Error("Equal should return true") - } - if !assert.Equal(nil, nil) { - t.Error("Equal should return true") - } -} - -func TestEqualValuesWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.EqualValues(uint32(10), int32(10)) { - t.Error("EqualValues should return true") - } -} - -func TestNotNilWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.NotNil(new(AssertionTesterConformingObject)) { - t.Error("NotNil should return true: object is not nil") - } - if assert.NotNil(nil) { - t.Error("NotNil should return false: object is nil") - } - -} - -func TestNilWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.Nil(nil) { - t.Error("Nil should return true: object is nil") - } - if assert.Nil(new(AssertionTesterConformingObject)) { - t.Error("Nil should return false: object is not nil") - } - -} - -func TestTrueWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.True(true) { - t.Error("True should return true") - } - if assert.True(false) { - t.Error("True should return false") - } - -} - -func TestFalseWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.False(false) { - t.Error("False should return true") - } - if assert.False(true) { - t.Error("False should return false") - } - -} - -func TestExactlyWrapper(t *testing.T) { - assert := New(new(testing.T)) - - a := float32(1) - b := float64(1) - c := float32(1) - d := float32(2) - - if assert.Exactly(a, b) { - t.Error("Exactly should return false") - } - if assert.Exactly(a, d) { - t.Error("Exactly should return false") - } - if !assert.Exactly(a, c) { - t.Error("Exactly should return true") - } - - if assert.Exactly(nil, a) { - t.Error("Exactly should return false") - } - if assert.Exactly(a, nil) { - t.Error("Exactly should return false") - } - -} - -func TestNotEqualWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - if !assert.NotEqual("Hello World", "Hello World!") { - t.Error("NotEqual should return true") - } - if !assert.NotEqual(123, 1234) { - t.Error("NotEqual should return true") - } - if !assert.NotEqual(123.5, 123.55) { - t.Error("NotEqual should return true") - } - if !assert.NotEqual([]byte("Hello World"), []byte("Hello World!")) { - t.Error("NotEqual should return true") - } - if !assert.NotEqual(nil, new(AssertionTesterConformingObject)) { - t.Error("NotEqual should return true") - } -} - -func TestContainsWrapper(t *testing.T) { - - assert := New(new(testing.T)) - list := []string{"Foo", "Bar"} - - if !assert.Contains("Hello World", "Hello") { - t.Error("Contains should return true: \"Hello World\" contains \"Hello\"") - } - if assert.Contains("Hello World", "Salut") { - t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"") - } - - if !assert.Contains(list, "Foo") { - t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") - } - if assert.Contains(list, "Salut") { - t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"") - } - -} - -func TestNotContainsWrapper(t *testing.T) { - - assert := New(new(testing.T)) - list := []string{"Foo", "Bar"} - - if !assert.NotContains("Hello World", "Hello!") { - t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"") - } - if assert.NotContains("Hello World", "Hello") { - t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"") - } - - if !assert.NotContains(list, "Foo!") { - t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"") - } - if assert.NotContains(list, "Foo") { - t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") - } - -} - -func TestConditionWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - if !assert.Condition(func() bool { return true }, "Truth") { - t.Error("Condition should return true") - } - - if assert.Condition(func() bool { return false }, "Lie") { - t.Error("Condition should return false") - } - -} - -func TestDidPanicWrapper(t *testing.T) { - - if funcDidPanic, _ := didPanic(func() { - panic("Panic!") - }); !funcDidPanic { - t.Error("didPanic should return true") - } - - if funcDidPanic, _ := didPanic(func() { - }); funcDidPanic { - t.Error("didPanic should return false") - } - -} - -func TestPanicsWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - if !assert.Panics(func() { - panic("Panic!") - }) { - t.Error("Panics should return true") - } - - if assert.Panics(func() { - }) { - t.Error("Panics should return false") - } - -} - -func TestNotPanicsWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - if !assert.NotPanics(func() { - }) { - t.Error("NotPanics should return true") - } - - if assert.NotPanics(func() { - panic("Panic!") - }) { - t.Error("NotPanics should return false") - } - -} - -func TestNoErrorWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - // start with a nil error - var err error - - assert.True(mockAssert.NoError(err), "NoError should return True for nil arg") - - // now set an error - err = errors.New("Some error") - - assert.False(mockAssert.NoError(err), "NoError with error should return False") - -} - -func TestErrorWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - // start with a nil error - var err error - - assert.False(mockAssert.Error(err), "Error should return False for nil arg") - - // now set an error - err = errors.New("Some error") - - assert.True(mockAssert.Error(err), "Error with error should return True") - -} - -func TestEqualErrorWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - // start with a nil error - var err error - assert.False(mockAssert.EqualError(err, ""), - "EqualError should return false for nil arg") - - // now set an error - err = errors.New("some error") - assert.False(mockAssert.EqualError(err, "Not some error"), - "EqualError should return false for different error string") - assert.True(mockAssert.EqualError(err, "some error"), - "EqualError should return true") -} - -func TestEmptyWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.True(mockAssert.Empty(""), "Empty string is empty") - assert.True(mockAssert.Empty(nil), "Nil is empty") - assert.True(mockAssert.Empty([]string{}), "Empty string array is empty") - assert.True(mockAssert.Empty(0), "Zero int value is empty") - assert.True(mockAssert.Empty(false), "False value is empty") - - assert.False(mockAssert.Empty("something"), "Non Empty string is not empty") - assert.False(mockAssert.Empty(errors.New("something")), "Non nil object is not empty") - assert.False(mockAssert.Empty([]string{"something"}), "Non empty string array is not empty") - assert.False(mockAssert.Empty(1), "Non-zero int value is not empty") - assert.False(mockAssert.Empty(true), "True value is not empty") - -} - -func TestNotEmptyWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.False(mockAssert.NotEmpty(""), "Empty string is empty") - assert.False(mockAssert.NotEmpty(nil), "Nil is empty") - assert.False(mockAssert.NotEmpty([]string{}), "Empty string array is empty") - assert.False(mockAssert.NotEmpty(0), "Zero int value is empty") - assert.False(mockAssert.NotEmpty(false), "False value is empty") - - assert.True(mockAssert.NotEmpty("something"), "Non Empty string is not empty") - assert.True(mockAssert.NotEmpty(errors.New("something")), "Non nil object is not empty") - assert.True(mockAssert.NotEmpty([]string{"something"}), "Non empty string array is not empty") - assert.True(mockAssert.NotEmpty(1), "Non-zero int value is not empty") - assert.True(mockAssert.NotEmpty(true), "True value is not empty") - -} - -func TestLenWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.False(mockAssert.Len(nil, 0), "nil does not have length") - assert.False(mockAssert.Len(0, 0), "int does not have length") - assert.False(mockAssert.Len(true, 0), "true does not have length") - assert.False(mockAssert.Len(false, 0), "false does not have length") - assert.False(mockAssert.Len('A', 0), "Rune does not have length") - assert.False(mockAssert.Len(struct{}{}, 0), "Struct does not have length") - - ch := make(chan int, 5) - ch <- 1 - ch <- 2 - ch <- 3 - - cases := []struct { - v interface{} - l int - }{ - {[]int{1, 2, 3}, 3}, - {[...]int{1, 2, 3}, 3}, - {"ABC", 3}, - {map[int]int{1: 2, 2: 4, 3: 6}, 3}, - {ch, 3}, - - {[]int{}, 0}, - {map[int]int{}, 0}, - {make(chan int), 0}, - - {[]int(nil), 0}, - {map[int]int(nil), 0}, - {(chan int)(nil), 0}, - } - - for _, c := range cases { - assert.True(mockAssert.Len(c.v, c.l), "%#v have %d items", c.v, c.l) - } -} - -func TestWithinDurationWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - a := time.Now() - b := a.Add(10 * time.Second) - - assert.True(mockAssert.WithinDuration(a, b, 10*time.Second), "A 10s difference is within a 10s time difference") - assert.True(mockAssert.WithinDuration(b, a, 10*time.Second), "A 10s difference is within a 10s time difference") - - assert.False(mockAssert.WithinDuration(a, b, 9*time.Second), "A 10s difference is not within a 9s time difference") - assert.False(mockAssert.WithinDuration(b, a, 9*time.Second), "A 10s difference is not within a 9s time difference") - - assert.False(mockAssert.WithinDuration(a, b, -9*time.Second), "A 10s difference is not within a 9s time difference") - assert.False(mockAssert.WithinDuration(b, a, -9*time.Second), "A 10s difference is not within a 9s time difference") - - assert.False(mockAssert.WithinDuration(a, b, -11*time.Second), "A 10s difference is not within a 9s time difference") - assert.False(mockAssert.WithinDuration(b, a, -11*time.Second), "A 10s difference is not within a 9s time difference") -} - -func TestInDeltaWrapper(t *testing.T) { - assert := New(new(testing.T)) - - True(t, assert.InDelta(1.001, 1, 0.01), "|1.001 - 1| <= 0.01") - True(t, assert.InDelta(1, 1.001, 0.01), "|1 - 1.001| <= 0.01") - True(t, assert.InDelta(1, 2, 1), "|1 - 2| <= 1") - False(t, assert.InDelta(1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail") - False(t, assert.InDelta(2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail") - False(t, assert.InDelta("", nil, 1), "Expected non numerals to fail") - - cases := []struct { - a, b interface{} - delta float64 - }{ - {uint8(2), uint8(1), 1}, - {uint16(2), uint16(1), 1}, - {uint32(2), uint32(1), 1}, - {uint64(2), uint64(1), 1}, - - {int(2), int(1), 1}, - {int8(2), int8(1), 1}, - {int16(2), int16(1), 1}, - {int32(2), int32(1), 1}, - {int64(2), int64(1), 1}, - - {float32(2), float32(1), 1}, - {float64(2), float64(1), 1}, - } - - for _, tc := range cases { - True(t, assert.InDelta(tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta) - } -} - -func TestInEpsilonWrapper(t *testing.T) { - assert := New(new(testing.T)) - - cases := []struct { - a, b interface{} - epsilon float64 - }{ - {uint8(2), uint16(2), .001}, - {2.1, 2.2, 0.1}, - {2.2, 2.1, 0.1}, - {-2.1, -2.2, 0.1}, - {-2.2, -2.1, 0.1}, - {uint64(100), uint8(101), 0.01}, - {0.1, -0.1, 2}, - } - - for _, tc := range cases { - True(t, assert.InEpsilon(tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) - } - - cases = []struct { - a, b interface{} - epsilon float64 - }{ - {uint8(2), int16(-2), .001}, - {uint64(100), uint8(102), 0.01}, - {2.1, 2.2, 0.001}, - {2.2, 2.1, 0.001}, - {2.1, -2.2, 1}, - {2.1, "bla-bla", 0}, - {0.1, -0.1, 1.99}, - } - - for _, tc := range cases { - False(t, assert.InEpsilon(tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) - } -} - -func TestRegexpWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - cases := []struct { - rx, str string - }{ - {"^start", "start of the line"}, - {"end$", "in the end"}, - {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"}, - } - - for _, tc := range cases { - True(t, assert.Regexp(tc.rx, tc.str)) - True(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str)) - False(t, assert.NotRegexp(tc.rx, tc.str)) - False(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str)) - } - - cases = []struct { - rx, str string - }{ - {"^asdfastart", "Not the start of the line"}, - {"end$", "in the end."}, - {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"}, - } - - for _, tc := range cases { - False(t, assert.Regexp(tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str) - False(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str)) - True(t, assert.NotRegexp(tc.rx, tc.str)) - True(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str)) - } -} - -func TestZeroWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - for _, test := range zeros { - assert.True(mockAssert.Zero(test), "Zero should return true for %v", test) - } - - for _, test := range nonZeros { - assert.False(mockAssert.Zero(test), "Zero should return false for %v", test) - } -} - -func TestNotZeroWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - for _, test := range zeros { - assert.False(mockAssert.NotZero(test), "Zero should return true for %v", test) - } - - for _, test := range nonZeros { - assert.True(mockAssert.NotZero(test), "Zero should return false for %v", test) - } -} - -func TestJSONEqWrapper_EqualSONString(t *testing.T) { - assert := New(new(testing.T)) - if !assert.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`) { - t.Error("JSONEq should return true") - } - -} - -func TestJSONEqWrapper_EquivalentButNotEqual(t *testing.T) { - assert := New(new(testing.T)) - if !assert.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) { - t.Error("JSONEq should return true") - } - -} - -func TestJSONEqWrapper_HashOfArraysAndHashes(t *testing.T) { - assert := New(new(testing.T)) - if !assert.JSONEq("{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}", - "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}") { - t.Error("JSONEq should return true") - } -} - -func TestJSONEqWrapper_Array(t *testing.T) { - assert := New(new(testing.T)) - if !assert.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`) { - t.Error("JSONEq should return true") - } - -} - -func TestJSONEqWrapper_HashAndArrayNotEquivalent(t *testing.T) { - assert := New(new(testing.T)) - if assert.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`) { - t.Error("JSONEq should return false") - } -} - -func TestJSONEqWrapper_HashesNotEquivalent(t *testing.T) { - assert := New(new(testing.T)) - if assert.JSONEq(`{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) { - t.Error("JSONEq should return false") - } -} - -func TestJSONEqWrapper_ActualIsNotJSON(t *testing.T) { - assert := New(new(testing.T)) - if assert.JSONEq(`{"foo": "bar"}`, "Not JSON") { - t.Error("JSONEq should return false") - } -} - -func TestJSONEqWrapper_ExpectedIsNotJSON(t *testing.T) { - assert := New(new(testing.T)) - if assert.JSONEq("Not JSON", `{"foo": "bar", "hello": "world"}`) { - t.Error("JSONEq should return false") - } -} - -func TestJSONEqWrapper_ExpectedAndActualNotJSON(t *testing.T) { - assert := New(new(testing.T)) - if assert.JSONEq("Not JSON", "Not JSON") { - t.Error("JSONEq should return false") - } -} - -func TestJSONEqWrapper_ArraysOfDifferentOrder(t *testing.T) { - assert := New(new(testing.T)) - if assert.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`) { - t.Error("JSONEq should return false") - } -} diff --git a/src/vendor/github.com/stretchr/testify/assert/http_assertions_test.go b/src/vendor/github.com/stretchr/testify/assert/http_assertions_test.go deleted file mode 100644 index 112beaf6429b3d8f435f744f240e1bc0ca6c5486..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/assert/http_assertions_test.go +++ /dev/null @@ -1,146 +0,0 @@ -package assert - -import ( - "fmt" - "net/http" - "net/url" - "testing" -) - -func httpOK(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) -} - -func httpRedirect(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusTemporaryRedirect) -} - -func httpError(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusInternalServerError) -} - -func TestHTTPSuccess(t *testing.T) { - assert := New(t) - - mockT1 := new(testing.T) - assert.Equal(HTTPSuccess(mockT1, httpOK, "GET", "/", nil), true) - assert.False(mockT1.Failed()) - - mockT2 := new(testing.T) - assert.Equal(HTTPSuccess(mockT2, httpRedirect, "GET", "/", nil), false) - assert.True(mockT2.Failed()) - - mockT3 := new(testing.T) - assert.Equal(HTTPSuccess(mockT3, httpError, "GET", "/", nil), false) - assert.True(mockT3.Failed()) -} - -func TestHTTPRedirect(t *testing.T) { - assert := New(t) - - mockT1 := new(testing.T) - assert.Equal(HTTPRedirect(mockT1, httpOK, "GET", "/", nil), false) - assert.True(mockT1.Failed()) - - mockT2 := new(testing.T) - assert.Equal(HTTPRedirect(mockT2, httpRedirect, "GET", "/", nil), true) - assert.False(mockT2.Failed()) - - mockT3 := new(testing.T) - assert.Equal(HTTPRedirect(mockT3, httpError, "GET", "/", nil), false) - assert.True(mockT3.Failed()) -} - -func TestHTTPError(t *testing.T) { - assert := New(t) - - mockT1 := new(testing.T) - assert.Equal(HTTPError(mockT1, httpOK, "GET", "/", nil), false) - assert.True(mockT1.Failed()) - - mockT2 := new(testing.T) - assert.Equal(HTTPError(mockT2, httpRedirect, "GET", "/", nil), false) - assert.True(mockT2.Failed()) - - mockT3 := new(testing.T) - assert.Equal(HTTPError(mockT3, httpError, "GET", "/", nil), true) - assert.False(mockT3.Failed()) -} - -func TestHTTPStatusesWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.Equal(mockAssert.HTTPSuccess(httpOK, "GET", "/", nil), true) - assert.Equal(mockAssert.HTTPSuccess(httpRedirect, "GET", "/", nil), false) - assert.Equal(mockAssert.HTTPSuccess(httpError, "GET", "/", nil), false) - - assert.Equal(mockAssert.HTTPRedirect(httpOK, "GET", "/", nil), false) - assert.Equal(mockAssert.HTTPRedirect(httpRedirect, "GET", "/", nil), true) - assert.Equal(mockAssert.HTTPRedirect(httpError, "GET", "/", nil), false) - - assert.Equal(mockAssert.HTTPError(httpOK, "GET", "/", nil), false) - assert.Equal(mockAssert.HTTPError(httpRedirect, "GET", "/", nil), false) - assert.Equal(mockAssert.HTTPError(httpError, "GET", "/", nil), true) -} - -func httpHelloName(w http.ResponseWriter, r *http.Request) { - name := r.FormValue("name") - w.Write([]byte(fmt.Sprintf("Hello, %s!", name))) -} - -func TestHTTPRequestWithNoParams(t *testing.T) { - var got *http.Request - handler := func(w http.ResponseWriter, r *http.Request) { - got = r - w.WriteHeader(http.StatusOK) - } - - True(t, HTTPSuccess(t, handler, "GET", "/url", nil)) - - Empty(t, got.URL.Query()) - Equal(t, "/url", got.URL.RequestURI()) -} - -func TestHTTPRequestWithParams(t *testing.T) { - var got *http.Request - handler := func(w http.ResponseWriter, r *http.Request) { - got = r - w.WriteHeader(http.StatusOK) - } - params := url.Values{} - params.Add("id", "12345") - - True(t, HTTPSuccess(t, handler, "GET", "/url", params)) - - Equal(t, url.Values{"id": []string{"12345"}}, got.URL.Query()) - Equal(t, "/url?id=12345", got.URL.String()) - Equal(t, "/url?id=12345", got.URL.RequestURI()) -} - -func TestHttpBody(t *testing.T) { - assert := New(t) - mockT := new(testing.T) - - assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) - assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) - assert.False(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) - - assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) - assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) - assert.True(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) -} - -func TestHttpBodyWrappers(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) - assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) - assert.False(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) - - assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) - assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) - assert.True(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) - -} diff --git a/src/vendor/github.com/stretchr/testify/doc.go b/src/vendor/github.com/stretchr/testify/doc.go deleted file mode 100644 index 377d5cc56ad1d54472e5333600306dcf5e5797fa..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/doc.go +++ /dev/null @@ -1,22 +0,0 @@ -// Package testify is a set of packages that provide many tools for testifying that your code will behave as you intend. -// -// testify contains the following packages: -// -// The assert package provides a comprehensive set of assertion functions that tie in to the Go testing system. -// -// The http package contains tools to make it easier to test http activity using the Go testing system. -// -// The mock package provides a system by which it is possible to mock your objects and verify calls are happening as expected. -// -// The suite package provides a basic structure for using structs as testing suites, and methods on those structs as tests. It includes setup/teardown functionality in the way of interfaces. -package testify - -// blank imports help docs. -import ( - // assert package - _ "github.com/stretchr/testify/assert" - // http package - _ "github.com/stretchr/testify/http" - // mock package - _ "github.com/stretchr/testify/mock" -) diff --git a/src/vendor/github.com/stretchr/testify/go.mod b/src/vendor/github.com/stretchr/testify/go.mod deleted file mode 100644 index 90e5dbe25a0ef02682b62accc98a273d1a18eabf..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/go.mod +++ /dev/null @@ -1,7 +0,0 @@ -module github.com/stretchr/testify - -require ( - github.com/davecgh/go-spew v1.1.0 - github.com/pmezard/go-difflib v1.0.0 - github.com/stretchr/objx v0.1.0 -) diff --git a/src/vendor/github.com/stretchr/testify/go.sum b/src/vendor/github.com/stretchr/testify/go.sum deleted file mode 100644 index 5b98bf3ac91d0adcc2b96009e2039f3ca0ad9359..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/go.sum +++ /dev/null @@ -1,6 +0,0 @@ -github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= diff --git a/src/vendor/github.com/stretchr/testify/http/doc.go b/src/vendor/github.com/stretchr/testify/http/doc.go deleted file mode 100644 index 695167c6de1986d439f27ded95d720c106f71a83..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/http/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package http DEPRECATED USE net/http/httptest -package http diff --git a/src/vendor/github.com/stretchr/testify/http/test_response_writer.go b/src/vendor/github.com/stretchr/testify/http/test_response_writer.go deleted file mode 100644 index 5c3f813fae321adb776416c43aed60f8fe142b1e..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/http/test_response_writer.go +++ /dev/null @@ -1,49 +0,0 @@ -package http - -import ( - "net/http" -) - -// TestResponseWriter DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. -type TestResponseWriter struct { - - // StatusCode is the last int written by the call to WriteHeader(int) - StatusCode int - - // Output is a string containing the written bytes using the Write([]byte) func. - Output string - - // header is the internal storage of the http.Header object - header http.Header -} - -// Header DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. -func (rw *TestResponseWriter) Header() http.Header { - - if rw.header == nil { - rw.header = make(http.Header) - } - - return rw.header -} - -// Write DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. -func (rw *TestResponseWriter) Write(bytes []byte) (int, error) { - - // assume 200 success if no header has been set - if rw.StatusCode == 0 { - rw.WriteHeader(200) - } - - // add these bytes to the output string - rw.Output = rw.Output + string(bytes) - - // return normal values - return 0, nil - -} - -// WriteHeader DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. -func (rw *TestResponseWriter) WriteHeader(i int) { - rw.StatusCode = i -} diff --git a/src/vendor/github.com/stretchr/testify/http/test_round_tripper.go b/src/vendor/github.com/stretchr/testify/http/test_round_tripper.go deleted file mode 100644 index b1e32f1d86b57e4d1026ca92b96ce044810ae996..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/http/test_round_tripper.go +++ /dev/null @@ -1,17 +0,0 @@ -package http - -import ( - "github.com/stretchr/testify/mock" - "net/http" -) - -// TestRoundTripper DEPRECATED USE net/http/httptest -type TestRoundTripper struct { - mock.Mock -} - -// RoundTrip DEPRECATED USE net/http/httptest -func (t *TestRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - args := t.Called(req) - return args.Get(0).(*http.Response), args.Error(1) -} diff --git a/src/vendor/github.com/stretchr/testify/mock/doc.go b/src/vendor/github.com/stretchr/testify/mock/doc.go deleted file mode 100644 index 7324128ef19c51d1cc74cd2cae8c886b2a71e7df..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/mock/doc.go +++ /dev/null @@ -1,44 +0,0 @@ -// Package mock provides a system by which it is possible to mock your objects -// and verify calls are happening as expected. -// -// Example Usage -// -// The mock package provides an object, Mock, that tracks activity on another object. It is usually -// embedded into a test object as shown below: -// -// type MyTestObject struct { -// // add a Mock object instance -// mock.Mock -// -// // other fields go here as normal -// } -// -// When implementing the methods of an interface, you wire your functions up -// to call the Mock.Called(args...) method, and return the appropriate values. -// -// For example, to mock a method that saves the name and age of a person and returns -// the year of their birth or an error, you might write this: -// -// func (o *MyTestObject) SavePersonDetails(firstname, lastname string, age int) (int, error) { -// args := o.Called(firstname, lastname, age) -// return args.Int(0), args.Error(1) -// } -// -// The Int, Error and Bool methods are examples of strongly typed getters that take the argument -// index position. Given this argument list: -// -// (12, true, "Something") -// -// You could read them out strongly typed like this: -// -// args.Int(0) -// args.Bool(1) -// args.String(2) -// -// For objects of your own type, use the generic Arguments.Get(index) method and make a type assertion: -// -// return args.Get(0).(*MyObject), args.Get(1).(*AnotherObjectOfMine) -// -// This may cause a panic if the object you are getting is nil (the type assertion will fail), in those -// cases you should check for nil first. -package mock diff --git a/src/vendor/github.com/stretchr/testify/mock/mock.go b/src/vendor/github.com/stretchr/testify/mock/mock.go deleted file mode 100644 index d6694ed78a1010668ddeb58c51f61a2c7edbc065..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/mock/mock.go +++ /dev/null @@ -1,886 +0,0 @@ -package mock - -import ( - "errors" - "fmt" - "reflect" - "regexp" - "runtime" - "strings" - "sync" - "time" - - "github.com/davecgh/go-spew/spew" - "github.com/pmezard/go-difflib/difflib" - "github.com/stretchr/objx" - "github.com/stretchr/testify/assert" -) - -// TestingT is an interface wrapper around *testing.T -type TestingT interface { - Logf(format string, args ...interface{}) - Errorf(format string, args ...interface{}) - FailNow() -} - -/* - Call -*/ - -// Call represents a method call and is used for setting expectations, -// as well as recording activity. -type Call struct { - Parent *Mock - - // The name of the method that was or will be called. - Method string - - // Holds the arguments of the method. - Arguments Arguments - - // Holds the arguments that should be returned when - // this method is called. - ReturnArguments Arguments - - // Holds the caller info for the On() call - callerInfo []string - - // The number of times to return the return arguments when setting - // expectations. 0 means to always return the value. - Repeatability int - - // Amount of times this call has been called - totalCalls int - - // Call to this method can be optional - optional bool - - // Holds a channel that will be used to block the Return until it either - // receives a message or is closed. nil means it returns immediately. - WaitFor <-chan time.Time - - waitTime time.Duration - - // Holds a handler used to manipulate arguments content that are passed by - // reference. It's useful when mocking methods such as unmarshalers or - // decoders. - RunFn func(Arguments) -} - -func newCall(parent *Mock, methodName string, callerInfo []string, methodArguments ...interface{}) *Call { - return &Call{ - Parent: parent, - Method: methodName, - Arguments: methodArguments, - ReturnArguments: make([]interface{}, 0), - callerInfo: callerInfo, - Repeatability: 0, - WaitFor: nil, - RunFn: nil, - } -} - -func (c *Call) lock() { - c.Parent.mutex.Lock() -} - -func (c *Call) unlock() { - c.Parent.mutex.Unlock() -} - -// Return specifies the return arguments for the expectation. -// -// Mock.On("DoSomething").Return(errors.New("failed")) -func (c *Call) Return(returnArguments ...interface{}) *Call { - c.lock() - defer c.unlock() - - c.ReturnArguments = returnArguments - - return c -} - -// Once indicates that that the mock should only return the value once. -// -// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Once() -func (c *Call) Once() *Call { - return c.Times(1) -} - -// Twice indicates that that the mock should only return the value twice. -// -// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Twice() -func (c *Call) Twice() *Call { - return c.Times(2) -} - -// Times indicates that that the mock should only return the indicated number -// of times. -// -// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Times(5) -func (c *Call) Times(i int) *Call { - c.lock() - defer c.unlock() - c.Repeatability = i - return c -} - -// WaitUntil sets the channel that will block the mock's return until its closed -// or a message is received. -// -// Mock.On("MyMethod", arg1, arg2).WaitUntil(time.After(time.Second)) -func (c *Call) WaitUntil(w <-chan time.Time) *Call { - c.lock() - defer c.unlock() - c.WaitFor = w - return c -} - -// After sets how long to block until the call returns -// -// Mock.On("MyMethod", arg1, arg2).After(time.Second) -func (c *Call) After(d time.Duration) *Call { - c.lock() - defer c.unlock() - c.waitTime = d - return c -} - -// Run sets a handler to be called before returning. It can be used when -// mocking a method such as unmarshalers that takes a pointer to a struct and -// sets properties in such struct -// -// Mock.On("Unmarshal", AnythingOfType("*map[string]interface{}").Return().Run(func(args Arguments) { -// arg := args.Get(0).(*map[string]interface{}) -// arg["foo"] = "bar" -// }) -func (c *Call) Run(fn func(args Arguments)) *Call { - c.lock() - defer c.unlock() - c.RunFn = fn - return c -} - -// Maybe allows the method call to be optional. Not calling an optional method -// will not cause an error while asserting expectations -func (c *Call) Maybe() *Call { - c.lock() - defer c.unlock() - c.optional = true - return c -} - -// On chains a new expectation description onto the mocked interface. This -// allows syntax like. -// -// Mock. -// On("MyMethod", 1).Return(nil). -// On("MyOtherMethod", 'a', 'b', 'c').Return(errors.New("Some Error")) -//go:noinline -func (c *Call) On(methodName string, arguments ...interface{}) *Call { - return c.Parent.On(methodName, arguments...) -} - -// Mock is the workhorse used to track activity on another object. -// For an example of its usage, refer to the "Example Usage" section at the top -// of this document. -type Mock struct { - // Represents the calls that are expected of - // an object. - ExpectedCalls []*Call - - // Holds the calls that were made to this mocked object. - Calls []Call - - // test is An optional variable that holds the test struct, to be used when an - // invalid mock call was made. - test TestingT - - // TestData holds any data that might be useful for testing. Testify ignores - // this data completely allowing you to do whatever you like with it. - testData objx.Map - - mutex sync.Mutex -} - -// TestData holds any data that might be useful for testing. Testify ignores -// this data completely allowing you to do whatever you like with it. -func (m *Mock) TestData() objx.Map { - - if m.testData == nil { - m.testData = make(objx.Map) - } - - return m.testData -} - -/* - Setting expectations -*/ - -// Test sets the test struct variable of the mock object -func (m *Mock) Test(t TestingT) { - m.mutex.Lock() - defer m.mutex.Unlock() - m.test = t -} - -// fail fails the current test with the given formatted format and args. -// In case that a test was defined, it uses the test APIs for failing a test, -// otherwise it uses panic. -func (m *Mock) fail(format string, args ...interface{}) { - m.mutex.Lock() - defer m.mutex.Unlock() - - if m.test == nil { - panic(fmt.Sprintf(format, args...)) - } - m.test.Errorf(format, args...) - m.test.FailNow() -} - -// On starts a description of an expectation of the specified method -// being called. -// -// Mock.On("MyMethod", arg1, arg2) -func (m *Mock) On(methodName string, arguments ...interface{}) *Call { - for _, arg := range arguments { - if v := reflect.ValueOf(arg); v.Kind() == reflect.Func { - panic(fmt.Sprintf("cannot use Func in expectations. Use mock.AnythingOfType(\"%T\")", arg)) - } - } - - m.mutex.Lock() - defer m.mutex.Unlock() - c := newCall(m, methodName, assert.CallerInfo(), arguments...) - m.ExpectedCalls = append(m.ExpectedCalls, c) - return c -} - -// /* -// Recording and responding to activity -// */ - -func (m *Mock) findExpectedCall(method string, arguments ...interface{}) (int, *Call) { - for i, call := range m.ExpectedCalls { - if call.Method == method && call.Repeatability > -1 { - - _, diffCount := call.Arguments.Diff(arguments) - if diffCount == 0 { - return i, call - } - - } - } - return -1, nil -} - -func (m *Mock) findClosestCall(method string, arguments ...interface{}) (*Call, string) { - var diffCount int - var closestCall *Call - var err string - - for _, call := range m.expectedCalls() { - if call.Method == method { - - errInfo, tempDiffCount := call.Arguments.Diff(arguments) - if tempDiffCount < diffCount || diffCount == 0 { - diffCount = tempDiffCount - closestCall = call - err = errInfo - } - - } - } - - return closestCall, err -} - -func callString(method string, arguments Arguments, includeArgumentValues bool) string { - - var argValsString string - if includeArgumentValues { - var argVals []string - for argIndex, arg := range arguments { - argVals = append(argVals, fmt.Sprintf("%d: %#v", argIndex, arg)) - } - argValsString = fmt.Sprintf("\n\t\t%s", strings.Join(argVals, "\n\t\t")) - } - - return fmt.Sprintf("%s(%s)%s", method, arguments.String(), argValsString) -} - -// Called tells the mock object that a method has been called, and gets an array -// of arguments to return. Panics if the call is unexpected (i.e. not preceded by -// appropriate .On .Return() calls) -// If Call.WaitFor is set, blocks until the channel is closed or receives a message. -func (m *Mock) Called(arguments ...interface{}) Arguments { - // get the calling function's name - pc, _, _, ok := runtime.Caller(1) - if !ok { - panic("Couldn't get the caller information") - } - functionPath := runtime.FuncForPC(pc).Name() - //Next four lines are required to use GCCGO function naming conventions. - //For Ex: github_com_docker_libkv_store_mock.WatchTree.pN39_github_com_docker_libkv_store_mock.Mock - //uses interface information unlike golang github.com/docker/libkv/store/mock.(*Mock).WatchTree - //With GCCGO we need to remove interface information starting from pN
. - re := regexp.MustCompile("\\.pN\\d+_") - if re.MatchString(functionPath) { - functionPath = re.Split(functionPath, -1)[0] - } - parts := strings.Split(functionPath, ".") - functionName := parts[len(parts)-1] - return m.MethodCalled(functionName, arguments...) -} - -// MethodCalled tells the mock object that the given method has been called, and gets -// an array of arguments to return. Panics if the call is unexpected (i.e. not preceded -// by appropriate .On .Return() calls) -// If Call.WaitFor is set, blocks until the channel is closed or receives a message. -func (m *Mock) MethodCalled(methodName string, arguments ...interface{}) Arguments { - m.mutex.Lock() - //TODO: could combine expected and closes in single loop - found, call := m.findExpectedCall(methodName, arguments...) - - if found < 0 { - // we have to fail here - because we don't know what to do - // as the return arguments. This is because: - // - // a) this is a totally unexpected call to this method, - // b) the arguments are not what was expected, or - // c) the developer has forgotten to add an accompanying On...Return pair. - - closestCall, mismatch := m.findClosestCall(methodName, arguments...) - m.mutex.Unlock() - - if closestCall != nil { - m.fail("\n\nmock: Unexpected Method Call\n-----------------------------\n\n%s\n\nThe closest call I have is: \n\n%s\n\n%s\nDiff: %s", - callString(methodName, arguments, true), - callString(methodName, closestCall.Arguments, true), - diffArguments(closestCall.Arguments, arguments), - strings.TrimSpace(mismatch), - ) - } else { - m.fail("\nassert: mock: I don't know what to return because the method call was unexpected.\n\tEither do Mock.On(\"%s\").Return(...) first, or remove the %s() call.\n\tThis method was unexpected:\n\t\t%s\n\tat: %s", methodName, methodName, callString(methodName, arguments, true), assert.CallerInfo()) - } - } - - if call.Repeatability == 1 { - call.Repeatability = -1 - } else if call.Repeatability > 1 { - call.Repeatability-- - } - call.totalCalls++ - - // add the call - m.Calls = append(m.Calls, *newCall(m, methodName, assert.CallerInfo(), arguments...)) - m.mutex.Unlock() - - // block if specified - if call.WaitFor != nil { - <-call.WaitFor - } else { - time.Sleep(call.waitTime) - } - - m.mutex.Lock() - runFn := call.RunFn - m.mutex.Unlock() - - if runFn != nil { - runFn(arguments) - } - - m.mutex.Lock() - returnArgs := call.ReturnArguments - m.mutex.Unlock() - - return returnArgs -} - -/* - Assertions -*/ - -type assertExpectationser interface { - AssertExpectations(TestingT) bool -} - -// AssertExpectationsForObjects asserts that everything specified with On and Return -// of the specified objects was in fact called as expected. -// -// Calls may have occurred in any order. -func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - for _, obj := range testObjects { - if m, ok := obj.(Mock); ok { - t.Logf("Deprecated mock.AssertExpectationsForObjects(myMock.Mock) use mock.AssertExpectationsForObjects(myMock)") - obj = &m - } - m := obj.(assertExpectationser) - if !m.AssertExpectations(t) { - t.Logf("Expectations didn't match for Mock: %+v", reflect.TypeOf(m)) - return false - } - } - return true -} - -// AssertExpectations asserts that everything specified with On and Return was -// in fact called as expected. Calls may have occurred in any order. -func (m *Mock) AssertExpectations(t TestingT) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - m.mutex.Lock() - defer m.mutex.Unlock() - var somethingMissing bool - var failedExpectations int - - // iterate through each expectation - expectedCalls := m.expectedCalls() - for _, expectedCall := range expectedCalls { - if !expectedCall.optional && !m.methodWasCalled(expectedCall.Method, expectedCall.Arguments) && expectedCall.totalCalls == 0 { - somethingMissing = true - failedExpectations++ - t.Logf("FAIL:\t%s(%s)\n\t\tat: %s", expectedCall.Method, expectedCall.Arguments.String(), expectedCall.callerInfo) - } else { - if expectedCall.Repeatability > 0 { - somethingMissing = true - failedExpectations++ - t.Logf("FAIL:\t%s(%s)\n\t\tat: %s", expectedCall.Method, expectedCall.Arguments.String(), expectedCall.callerInfo) - } else { - t.Logf("PASS:\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String()) - } - } - } - - if somethingMissing { - t.Errorf("FAIL: %d out of %d expectation(s) were met.\n\tThe code you are testing needs to make %d more call(s).\n\tat: %s", len(expectedCalls)-failedExpectations, len(expectedCalls), failedExpectations, assert.CallerInfo()) - } - - return !somethingMissing -} - -// AssertNumberOfCalls asserts that the method was called expectedCalls times. -func (m *Mock) AssertNumberOfCalls(t TestingT, methodName string, expectedCalls int) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - m.mutex.Lock() - defer m.mutex.Unlock() - var actualCalls int - for _, call := range m.calls() { - if call.Method == methodName { - actualCalls++ - } - } - return assert.Equal(t, expectedCalls, actualCalls, fmt.Sprintf("Expected number of calls (%d) does not match the actual number of calls (%d).", expectedCalls, actualCalls)) -} - -// AssertCalled asserts that the method was called. -// It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method. -func (m *Mock) AssertCalled(t TestingT, methodName string, arguments ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - m.mutex.Lock() - defer m.mutex.Unlock() - if !m.methodWasCalled(methodName, arguments) { - var calledWithArgs []string - for _, call := range m.calls() { - calledWithArgs = append(calledWithArgs, fmt.Sprintf("%v", call.Arguments)) - } - if len(calledWithArgs) == 0 { - return assert.Fail(t, "Should have called with given arguments", - fmt.Sprintf("Expected %q to have been called with:\n%v\nbut no actual calls happened", methodName, arguments)) - } - return assert.Fail(t, "Should have called with given arguments", - fmt.Sprintf("Expected %q to have been called with:\n%v\nbut actual calls were:\n %v", methodName, arguments, strings.Join(calledWithArgs, "\n"))) - } - return true -} - -// AssertNotCalled asserts that the method was not called. -// It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method. -func (m *Mock) AssertNotCalled(t TestingT, methodName string, arguments ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - m.mutex.Lock() - defer m.mutex.Unlock() - if m.methodWasCalled(methodName, arguments) { - return assert.Fail(t, "Should not have called with given arguments", - fmt.Sprintf("Expected %q to not have been called with:\n%v\nbut actually it was.", methodName, arguments)) - } - return true -} - -func (m *Mock) methodWasCalled(methodName string, expected []interface{}) bool { - for _, call := range m.calls() { - if call.Method == methodName { - - _, differences := Arguments(expected).Diff(call.Arguments) - - if differences == 0 { - // found the expected call - return true - } - - } - } - // we didn't find the expected call - return false -} - -func (m *Mock) expectedCalls() []*Call { - return append([]*Call{}, m.ExpectedCalls...) -} - -func (m *Mock) calls() []Call { - return append([]Call{}, m.Calls...) -} - -/* - Arguments -*/ - -// Arguments holds an array of method arguments or return values. -type Arguments []interface{} - -const ( - // Anything is used in Diff and Assert when the argument being tested - // shouldn't be taken into consideration. - Anything = "mock.Anything" -) - -// AnythingOfTypeArgument is a string that contains the type of an argument -// for use when type checking. Used in Diff and Assert. -type AnythingOfTypeArgument string - -// AnythingOfType returns an AnythingOfTypeArgument object containing the -// name of the type to check for. Used in Diff and Assert. -// -// For example: -// Assert(t, AnythingOfType("string"), AnythingOfType("int")) -func AnythingOfType(t string) AnythingOfTypeArgument { - return AnythingOfTypeArgument(t) -} - -// argumentMatcher performs custom argument matching, returning whether or -// not the argument is matched by the expectation fixture function. -type argumentMatcher struct { - // fn is a function which accepts one argument, and returns a bool. - fn reflect.Value -} - -func (f argumentMatcher) Matches(argument interface{}) bool { - expectType := f.fn.Type().In(0) - expectTypeNilSupported := false - switch expectType.Kind() { - case reflect.Interface, reflect.Chan, reflect.Func, reflect.Map, reflect.Slice, reflect.Ptr: - expectTypeNilSupported = true - } - - argType := reflect.TypeOf(argument) - var arg reflect.Value - if argType == nil { - arg = reflect.New(expectType).Elem() - } else { - arg = reflect.ValueOf(argument) - } - - if argType == nil && !expectTypeNilSupported { - panic(errors.New("attempting to call matcher with nil for non-nil expected type")) - } - if argType == nil || argType.AssignableTo(expectType) { - result := f.fn.Call([]reflect.Value{arg}) - return result[0].Bool() - } - return false -} - -func (f argumentMatcher) String() string { - return fmt.Sprintf("func(%s) bool", f.fn.Type().In(0).Name()) -} - -// MatchedBy can be used to match a mock call based on only certain properties -// from a complex struct or some calculation. It takes a function that will be -// evaluated with the called argument and will return true when there's a match -// and false otherwise. -// -// Example: -// m.On("Do", MatchedBy(func(req *http.Request) bool { return req.Host == "example.com" })) -// -// |fn|, must be a function accepting a single argument (of the expected type) -// which returns a bool. If |fn| doesn't match the required signature, -// MatchedBy() panics. -func MatchedBy(fn interface{}) argumentMatcher { - fnType := reflect.TypeOf(fn) - - if fnType.Kind() != reflect.Func { - panic(fmt.Sprintf("assert: arguments: %s is not a func", fn)) - } - if fnType.NumIn() != 1 { - panic(fmt.Sprintf("assert: arguments: %s does not take exactly one argument", fn)) - } - if fnType.NumOut() != 1 || fnType.Out(0).Kind() != reflect.Bool { - panic(fmt.Sprintf("assert: arguments: %s does not return a bool", fn)) - } - - return argumentMatcher{fn: reflect.ValueOf(fn)} -} - -// Get Returns the argument at the specified index. -func (args Arguments) Get(index int) interface{} { - if index+1 > len(args) { - panic(fmt.Sprintf("assert: arguments: Cannot call Get(%d) because there are %d argument(s).", index, len(args))) - } - return args[index] -} - -// Is gets whether the objects match the arguments specified. -func (args Arguments) Is(objects ...interface{}) bool { - for i, obj := range args { - if obj != objects[i] { - return false - } - } - return true -} - -// Diff gets a string describing the differences between the arguments -// and the specified objects. -// -// Returns the diff string and number of differences found. -func (args Arguments) Diff(objects []interface{}) (string, int) { - //TODO: could return string as error and nil for No difference - - var output = "\n" - var differences int - - var maxArgCount = len(args) - if len(objects) > maxArgCount { - maxArgCount = len(objects) - } - - for i := 0; i < maxArgCount; i++ { - var actual, expected interface{} - var actualFmt, expectedFmt string - - if len(objects) <= i { - actual = "(Missing)" - actualFmt = "(Missing)" - } else { - actual = objects[i] - actualFmt = fmt.Sprintf("(%[1]T=%[1]v)", actual) - } - - if len(args) <= i { - expected = "(Missing)" - expectedFmt = "(Missing)" - } else { - expected = args[i] - expectedFmt = fmt.Sprintf("(%[1]T=%[1]v)", expected) - } - - if matcher, ok := expected.(argumentMatcher); ok { - if matcher.Matches(actual) { - output = fmt.Sprintf("%s\t%d: PASS: %s matched by %s\n", output, i, actualFmt, matcher) - } else { - differences++ - output = fmt.Sprintf("%s\t%d: FAIL: %s not matched by %s\n", output, i, actualFmt, matcher) - } - } else if reflect.TypeOf(expected) == reflect.TypeOf((*AnythingOfTypeArgument)(nil)).Elem() { - - // type checking - if reflect.TypeOf(actual).Name() != string(expected.(AnythingOfTypeArgument)) && reflect.TypeOf(actual).String() != string(expected.(AnythingOfTypeArgument)) { - // not match - differences++ - output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, expected, reflect.TypeOf(actual).Name(), actualFmt) - } - - } else { - - // normal checking - - if assert.ObjectsAreEqual(expected, Anything) || assert.ObjectsAreEqual(actual, Anything) || assert.ObjectsAreEqual(actual, expected) { - // match - output = fmt.Sprintf("%s\t%d: PASS: %s == %s\n", output, i, actualFmt, expectedFmt) - } else { - // not match - differences++ - output = fmt.Sprintf("%s\t%d: FAIL: %s != %s\n", output, i, actualFmt, expectedFmt) - } - } - - } - - if differences == 0 { - return "No differences.", differences - } - - return output, differences - -} - -// Assert compares the arguments with the specified objects and fails if -// they do not exactly match. -func (args Arguments) Assert(t TestingT, objects ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - // get the differences - diff, diffCount := args.Diff(objects) - - if diffCount == 0 { - return true - } - - // there are differences... report them... - t.Logf(diff) - t.Errorf("%sArguments do not match.", assert.CallerInfo()) - - return false - -} - -// String gets the argument at the specified index. Panics if there is no argument, or -// if the argument is of the wrong type. -// -// If no index is provided, String() returns a complete string representation -// of the arguments. -func (args Arguments) String(indexOrNil ...int) string { - - if len(indexOrNil) == 0 { - // normal String() method - return a string representation of the args - var argsStr []string - for _, arg := range args { - argsStr = append(argsStr, fmt.Sprintf("%s", reflect.TypeOf(arg))) - } - return strings.Join(argsStr, ",") - } else if len(indexOrNil) == 1 { - // Index has been specified - get the argument at that index - var index = indexOrNil[0] - var s string - var ok bool - if s, ok = args.Get(index).(string); !ok { - panic(fmt.Sprintf("assert: arguments: String(%d) failed because object wasn't correct type: %s", index, args.Get(index))) - } - return s - } - - panic(fmt.Sprintf("assert: arguments: Wrong number of arguments passed to String. Must be 0 or 1, not %d", len(indexOrNil))) - -} - -// Int gets the argument at the specified index. Panics if there is no argument, or -// if the argument is of the wrong type. -func (args Arguments) Int(index int) int { - var s int - var ok bool - if s, ok = args.Get(index).(int); !ok { - panic(fmt.Sprintf("assert: arguments: Int(%d) failed because object wasn't correct type: %v", index, args.Get(index))) - } - return s -} - -// Error gets the argument at the specified index. Panics if there is no argument, or -// if the argument is of the wrong type. -func (args Arguments) Error(index int) error { - obj := args.Get(index) - var s error - var ok bool - if obj == nil { - return nil - } - if s, ok = obj.(error); !ok { - panic(fmt.Sprintf("assert: arguments: Error(%d) failed because object wasn't correct type: %v", index, args.Get(index))) - } - return s -} - -// Bool gets the argument at the specified index. Panics if there is no argument, or -// if the argument is of the wrong type. -func (args Arguments) Bool(index int) bool { - var s bool - var ok bool - if s, ok = args.Get(index).(bool); !ok { - panic(fmt.Sprintf("assert: arguments: Bool(%d) failed because object wasn't correct type: %v", index, args.Get(index))) - } - return s -} - -func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) { - t := reflect.TypeOf(v) - k := t.Kind() - - if k == reflect.Ptr { - t = t.Elem() - k = t.Kind() - } - return t, k -} - -func diffArguments(expected Arguments, actual Arguments) string { - if len(expected) != len(actual) { - return fmt.Sprintf("Provided %v arguments, mocked for %v arguments", len(expected), len(actual)) - } - - for x := range expected { - if diffString := diff(expected[x], actual[x]); diffString != "" { - return fmt.Sprintf("Difference found in argument %v:\n\n%s", x, diffString) - } - } - - return "" -} - -// diff returns a diff of both values as long as both are of the same type and -// are a struct, map, slice or array. Otherwise it returns an empty string. -func diff(expected interface{}, actual interface{}) string { - if expected == nil || actual == nil { - return "" - } - - et, ek := typeAndKind(expected) - at, _ := typeAndKind(actual) - - if et != at { - return "" - } - - if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array { - return "" - } - - e := spewConfig.Sdump(expected) - a := spewConfig.Sdump(actual) - - diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ - A: difflib.SplitLines(e), - B: difflib.SplitLines(a), - FromFile: "Expected", - FromDate: "", - ToFile: "Actual", - ToDate: "", - Context: 1, - }) - - return diff -} - -var spewConfig = spew.ConfigState{ - Indent: " ", - DisablePointerAddresses: true, - DisableCapacities: true, - SortKeys: true, -} - -type tHelper interface { - Helper() -} diff --git a/src/vendor/github.com/stretchr/testify/mock/mock_test.go b/src/vendor/github.com/stretchr/testify/mock/mock_test.go deleted file mode 100644 index 2608f5a36e1a5a32aa7b6988c30e7ccf43a08796..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/mock/mock_test.go +++ /dev/null @@ -1,1499 +0,0 @@ -package mock - -import ( - "errors" - "fmt" - "regexp" - "runtime" - "sync" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -/* - Test objects -*/ - -// ExampleInterface represents an example interface. -type ExampleInterface interface { - TheExampleMethod(a, b, c int) (int, error) -} - -// TestExampleImplementation is a test implementation of ExampleInterface -type TestExampleImplementation struct { - Mock -} - -func (i *TestExampleImplementation) TheExampleMethod(a, b, c int) (int, error) { - args := i.Called(a, b, c) - return args.Int(0), errors.New("Whoops") -} - -//go:noinline -func (i *TestExampleImplementation) TheExampleMethod2(yesorno bool) { - i.Called(yesorno) -} - -type ExampleType struct { - ran bool -} - -func (i *TestExampleImplementation) TheExampleMethod3(et *ExampleType) error { - args := i.Called(et) - return args.Error(0) -} - -func (i *TestExampleImplementation) TheExampleMethod4(v ExampleInterface) error { - args := i.Called(v) - return args.Error(0) -} - -func (i *TestExampleImplementation) TheExampleMethod5(ch chan struct{}) error { - args := i.Called(ch) - return args.Error(0) -} - -func (i *TestExampleImplementation) TheExampleMethod6(m map[string]bool) error { - args := i.Called(m) - return args.Error(0) -} - -func (i *TestExampleImplementation) TheExampleMethod7(slice []bool) error { - args := i.Called(slice) - return args.Error(0) -} - -func (i *TestExampleImplementation) TheExampleMethodFunc(fn func(string) error) error { - args := i.Called(fn) - return args.Error(0) -} - -func (i *TestExampleImplementation) TheExampleMethodVariadic(a ...int) error { - args := i.Called(a) - return args.Error(0) -} - -func (i *TestExampleImplementation) TheExampleMethodVariadicInterface(a ...interface{}) error { - args := i.Called(a) - return args.Error(0) -} - -func (i *TestExampleImplementation) TheExampleMethodMixedVariadic(a int, b ...int) error { - args := i.Called(a, b) - return args.Error(0) -} - -type ExampleFuncType func(string) error - -func (i *TestExampleImplementation) TheExampleMethodFuncType(fn ExampleFuncType) error { - args := i.Called(fn) - return args.Error(0) -} - -// MockTestingT mocks a test struct -type MockTestingT struct { - logfCount, errorfCount, failNowCount int -} - -const mockTestingTFailNowCalled = "FailNow was called" - -func (m *MockTestingT) Logf(string, ...interface{}) { - m.logfCount++ -} - -func (m *MockTestingT) Errorf(string, ...interface{}) { - m.errorfCount++ -} - -// FailNow mocks the FailNow call. -// It panics in order to mimic the FailNow behavior in the sense that -// the execution stops. -// When expecting this method, the call that invokes it should use the following code: -// -// assert.PanicsWithValue(t, mockTestingTFailNowCalled, func() {...}) -func (m *MockTestingT) FailNow() { - m.failNowCount++ - - // this function should panic now to stop the execution as expected - panic(mockTestingTFailNowCalled) -} - -/* - Mock -*/ - -func Test_Mock_TestData(t *testing.T) { - - var mockedService = new(TestExampleImplementation) - - if assert.NotNil(t, mockedService.TestData()) { - - mockedService.TestData().Set("something", 123) - assert.Equal(t, 123, mockedService.TestData().Get("something").Data()) - } -} - -func Test_Mock_On(t *testing.T) { - - // make a test impl object - var mockedService = new(TestExampleImplementation) - - c := mockedService.On("TheExampleMethod") - assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) - assert.Equal(t, "TheExampleMethod", c.Method) -} - -func Test_Mock_Chained_On(t *testing.T) { - // make a test impl object - var mockedService = new(TestExampleImplementation) - - // determine our current line number so we can assert the expected calls callerInfo properly - _, _, line, _ := runtime.Caller(0) - mockedService. - On("TheExampleMethod", 1, 2, 3). - Return(0). - On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")). - Return(nil) - - expectedCalls := []*Call{ - { - Parent: &mockedService.Mock, - Method: "TheExampleMethod", - Arguments: []interface{}{1, 2, 3}, - ReturnArguments: []interface{}{0}, - callerInfo: []string{fmt.Sprintf("mock_test.go:%d", line+2)}, - }, - { - Parent: &mockedService.Mock, - Method: "TheExampleMethod3", - Arguments: []interface{}{AnythingOfType("*mock.ExampleType")}, - ReturnArguments: []interface{}{nil}, - callerInfo: []string{fmt.Sprintf("mock_test.go:%d", line+4)}, - }, - } - assert.Equal(t, expectedCalls, mockedService.ExpectedCalls) -} - -func Test_Mock_On_WithArgs(t *testing.T) { - - // make a test impl object - var mockedService = new(TestExampleImplementation) - - c := mockedService.On("TheExampleMethod", 1, 2, 3, 4) - - assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) - assert.Equal(t, "TheExampleMethod", c.Method) - assert.Equal(t, Arguments{1, 2, 3, 4}, c.Arguments) -} - -func Test_Mock_On_WithFuncArg(t *testing.T) { - - // make a test impl object - var mockedService = new(TestExampleImplementation) - - c := mockedService. - On("TheExampleMethodFunc", AnythingOfType("func(string) error")). - Return(nil) - - assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) - assert.Equal(t, "TheExampleMethodFunc", c.Method) - assert.Equal(t, 1, len(c.Arguments)) - assert.Equal(t, AnythingOfType("func(string) error"), c.Arguments[0]) - - fn := func(string) error { return nil } - - assert.NotPanics(t, func() { - mockedService.TheExampleMethodFunc(fn) - }) -} - -func Test_Mock_On_WithIntArgMatcher(t *testing.T) { - var mockedService TestExampleImplementation - - mockedService.On("TheExampleMethod", - MatchedBy(func(a int) bool { - return a == 1 - }), MatchedBy(func(b int) bool { - return b == 2 - }), MatchedBy(func(c int) bool { - return c == 3 - })).Return(0, nil) - - assert.Panics(t, func() { - mockedService.TheExampleMethod(1, 2, 4) - }) - assert.Panics(t, func() { - mockedService.TheExampleMethod(2, 2, 3) - }) - assert.NotPanics(t, func() { - mockedService.TheExampleMethod(1, 2, 3) - }) -} - -func TestMock_WithTest(t *testing.T) { - var ( - mockedService TestExampleImplementation - mockedTest MockTestingT - ) - - mockedService.Test(&mockedTest) - mockedService.On("TheExampleMethod", 1, 2, 3).Return(0, nil) - - // Test that on an expected call, the test was not failed - - mockedService.TheExampleMethod(1, 2, 3) - - // Assert that Errorf and FailNow were not called - assert.Equal(t, 0, mockedTest.errorfCount) - assert.Equal(t, 0, mockedTest.failNowCount) - - // Test that on unexpected call, the mocked test was called to fail the test - - assert.PanicsWithValue(t, mockTestingTFailNowCalled, func() { - mockedService.TheExampleMethod(1, 1, 1) - }) - - // Assert that Errorf and FailNow were called once - assert.Equal(t, 1, mockedTest.errorfCount) - assert.Equal(t, 1, mockedTest.failNowCount) -} - -func Test_Mock_On_WithPtrArgMatcher(t *testing.T) { - var mockedService TestExampleImplementation - - mockedService.On("TheExampleMethod3", - MatchedBy(func(a *ExampleType) bool { return a != nil && a.ran == true }), - ).Return(nil) - - mockedService.On("TheExampleMethod3", - MatchedBy(func(a *ExampleType) bool { return a != nil && a.ran == false }), - ).Return(errors.New("error")) - - mockedService.On("TheExampleMethod3", - MatchedBy(func(a *ExampleType) bool { return a == nil }), - ).Return(errors.New("error2")) - - assert.Equal(t, mockedService.TheExampleMethod3(&ExampleType{true}), nil) - assert.EqualError(t, mockedService.TheExampleMethod3(&ExampleType{false}), "error") - assert.EqualError(t, mockedService.TheExampleMethod3(nil), "error2") -} - -func Test_Mock_On_WithFuncArgMatcher(t *testing.T) { - var mockedService TestExampleImplementation - - fixture1, fixture2 := errors.New("fixture1"), errors.New("fixture2") - - mockedService.On("TheExampleMethodFunc", - MatchedBy(func(a func(string) error) bool { return a != nil && a("string") == fixture1 }), - ).Return(errors.New("fixture1")) - - mockedService.On("TheExampleMethodFunc", - MatchedBy(func(a func(string) error) bool { return a != nil && a("string") == fixture2 }), - ).Return(errors.New("fixture2")) - - mockedService.On("TheExampleMethodFunc", - MatchedBy(func(a func(string) error) bool { return a == nil }), - ).Return(errors.New("fixture3")) - - assert.EqualError(t, mockedService.TheExampleMethodFunc( - func(string) error { return fixture1 }), "fixture1") - assert.EqualError(t, mockedService.TheExampleMethodFunc( - func(string) error { return fixture2 }), "fixture2") - assert.EqualError(t, mockedService.TheExampleMethodFunc(nil), "fixture3") -} - -func Test_Mock_On_WithInterfaceArgMatcher(t *testing.T) { - var mockedService TestExampleImplementation - - mockedService.On("TheExampleMethod4", - MatchedBy(func(a ExampleInterface) bool { return a == nil }), - ).Return(errors.New("fixture1")) - - assert.EqualError(t, mockedService.TheExampleMethod4(nil), "fixture1") -} - -func Test_Mock_On_WithChannelArgMatcher(t *testing.T) { - var mockedService TestExampleImplementation - - mockedService.On("TheExampleMethod5", - MatchedBy(func(ch chan struct{}) bool { return ch == nil }), - ).Return(errors.New("fixture1")) - - assert.EqualError(t, mockedService.TheExampleMethod5(nil), "fixture1") -} - -func Test_Mock_On_WithMapArgMatcher(t *testing.T) { - var mockedService TestExampleImplementation - - mockedService.On("TheExampleMethod6", - MatchedBy(func(m map[string]bool) bool { return m == nil }), - ).Return(errors.New("fixture1")) - - assert.EqualError(t, mockedService.TheExampleMethod6(nil), "fixture1") -} - -func Test_Mock_On_WithSliceArgMatcher(t *testing.T) { - var mockedService TestExampleImplementation - - mockedService.On("TheExampleMethod7", - MatchedBy(func(slice []bool) bool { return slice == nil }), - ).Return(errors.New("fixture1")) - - assert.EqualError(t, mockedService.TheExampleMethod7(nil), "fixture1") -} - -func Test_Mock_On_WithVariadicFunc(t *testing.T) { - - // make a test impl object - var mockedService = new(TestExampleImplementation) - - c := mockedService. - On("TheExampleMethodVariadic", []int{1, 2, 3}). - Return(nil) - - assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) - assert.Equal(t, 1, len(c.Arguments)) - assert.Equal(t, []int{1, 2, 3}, c.Arguments[0]) - - assert.NotPanics(t, func() { - mockedService.TheExampleMethodVariadic(1, 2, 3) - }) - assert.Panics(t, func() { - mockedService.TheExampleMethodVariadic(1, 2) - }) - -} - -func Test_Mock_On_WithMixedVariadicFunc(t *testing.T) { - - // make a test impl object - var mockedService = new(TestExampleImplementation) - - c := mockedService. - On("TheExampleMethodMixedVariadic", 1, []int{2, 3, 4}). - Return(nil) - - assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) - assert.Equal(t, 2, len(c.Arguments)) - assert.Equal(t, 1, c.Arguments[0]) - assert.Equal(t, []int{2, 3, 4}, c.Arguments[1]) - - assert.NotPanics(t, func() { - mockedService.TheExampleMethodMixedVariadic(1, 2, 3, 4) - }) - assert.Panics(t, func() { - mockedService.TheExampleMethodMixedVariadic(1, 2, 3, 5) - }) - -} - -func Test_Mock_On_WithVariadicFuncWithInterface(t *testing.T) { - - // make a test impl object - var mockedService = new(TestExampleImplementation) - - c := mockedService.On("TheExampleMethodVariadicInterface", []interface{}{1, 2, 3}). - Return(nil) - - assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) - assert.Equal(t, 1, len(c.Arguments)) - assert.Equal(t, []interface{}{1, 2, 3}, c.Arguments[0]) - - assert.NotPanics(t, func() { - mockedService.TheExampleMethodVariadicInterface(1, 2, 3) - }) - assert.Panics(t, func() { - mockedService.TheExampleMethodVariadicInterface(1, 2) - }) - -} - -func Test_Mock_On_WithVariadicFuncWithEmptyInterfaceArray(t *testing.T) { - - // make a test impl object - var mockedService = new(TestExampleImplementation) - - var expected []interface{} - c := mockedService. - On("TheExampleMethodVariadicInterface", expected). - Return(nil) - - assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) - assert.Equal(t, 1, len(c.Arguments)) - assert.Equal(t, expected, c.Arguments[0]) - - assert.NotPanics(t, func() { - mockedService.TheExampleMethodVariadicInterface() - }) - assert.Panics(t, func() { - mockedService.TheExampleMethodVariadicInterface(1, 2) - }) - -} - -func Test_Mock_On_WithFuncPanics(t *testing.T) { - // make a test impl object - var mockedService = new(TestExampleImplementation) - - assert.Panics(t, func() { - mockedService.On("TheExampleMethodFunc", func(string) error { return nil }) - }) -} - -func Test_Mock_On_WithFuncTypeArg(t *testing.T) { - - // make a test impl object - var mockedService = new(TestExampleImplementation) - - c := mockedService. - On("TheExampleMethodFuncType", AnythingOfType("mock.ExampleFuncType")). - Return(nil) - - assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) - assert.Equal(t, 1, len(c.Arguments)) - assert.Equal(t, AnythingOfType("mock.ExampleFuncType"), c.Arguments[0]) - - fn := func(string) error { return nil } - assert.NotPanics(t, func() { - mockedService.TheExampleMethodFuncType(fn) - }) -} - -func Test_Mock_Return(t *testing.T) { - - // make a test impl object - var mockedService = new(TestExampleImplementation) - - c := mockedService. - On("TheExampleMethod", "A", "B", true). - Return(1, "two", true) - - require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) - - call := mockedService.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod", call.Method) - assert.Equal(t, "A", call.Arguments[0]) - assert.Equal(t, "B", call.Arguments[1]) - assert.Equal(t, true, call.Arguments[2]) - assert.Equal(t, 1, call.ReturnArguments[0]) - assert.Equal(t, "two", call.ReturnArguments[1]) - assert.Equal(t, true, call.ReturnArguments[2]) - assert.Equal(t, 0, call.Repeatability) - assert.Nil(t, call.WaitFor) -} - -func Test_Mock_Return_WaitUntil(t *testing.T) { - - // make a test impl object - var mockedService = new(TestExampleImplementation) - ch := time.After(time.Second) - - c := mockedService.Mock. - On("TheExampleMethod", "A", "B", true). - WaitUntil(ch). - Return(1, "two", true) - - // assert that the call was created - require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) - - call := mockedService.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod", call.Method) - assert.Equal(t, "A", call.Arguments[0]) - assert.Equal(t, "B", call.Arguments[1]) - assert.Equal(t, true, call.Arguments[2]) - assert.Equal(t, 1, call.ReturnArguments[0]) - assert.Equal(t, "two", call.ReturnArguments[1]) - assert.Equal(t, true, call.ReturnArguments[2]) - assert.Equal(t, 0, call.Repeatability) - assert.Equal(t, ch, call.WaitFor) -} - -func Test_Mock_Return_After(t *testing.T) { - - // make a test impl object - var mockedService = new(TestExampleImplementation) - - c := mockedService.Mock. - On("TheExampleMethod", "A", "B", true). - Return(1, "two", true). - After(time.Second) - - require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) - - call := mockedService.Mock.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod", call.Method) - assert.Equal(t, "A", call.Arguments[0]) - assert.Equal(t, "B", call.Arguments[1]) - assert.Equal(t, true, call.Arguments[2]) - assert.Equal(t, 1, call.ReturnArguments[0]) - assert.Equal(t, "two", call.ReturnArguments[1]) - assert.Equal(t, true, call.ReturnArguments[2]) - assert.Equal(t, 0, call.Repeatability) - assert.NotEqual(t, nil, call.WaitFor) - -} - -func Test_Mock_Return_Run(t *testing.T) { - - // make a test impl object - var mockedService = new(TestExampleImplementation) - - fn := func(args Arguments) { - arg := args.Get(0).(*ExampleType) - arg.ran = true - } - - c := mockedService.Mock. - On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")). - Return(nil). - Run(fn) - - require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) - - call := mockedService.Mock.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod3", call.Method) - assert.Equal(t, AnythingOfType("*mock.ExampleType"), call.Arguments[0]) - assert.Equal(t, nil, call.ReturnArguments[0]) - assert.Equal(t, 0, call.Repeatability) - assert.NotEqual(t, nil, call.WaitFor) - assert.NotNil(t, call.Run) - - et := ExampleType{} - assert.Equal(t, false, et.ran) - mockedService.TheExampleMethod3(&et) - assert.Equal(t, true, et.ran) -} - -func Test_Mock_Return_Run_Out_Of_Order(t *testing.T) { - // make a test impl object - var mockedService = new(TestExampleImplementation) - f := func(args Arguments) { - arg := args.Get(0).(*ExampleType) - arg.ran = true - } - - c := mockedService.Mock. - On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")). - Run(f). - Return(nil) - - require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) - - call := mockedService.Mock.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod3", call.Method) - assert.Equal(t, AnythingOfType("*mock.ExampleType"), call.Arguments[0]) - assert.Equal(t, nil, call.ReturnArguments[0]) - assert.Equal(t, 0, call.Repeatability) - assert.NotEqual(t, nil, call.WaitFor) - assert.NotNil(t, call.Run) -} - -func Test_Mock_Return_Once(t *testing.T) { - - // make a test impl object - var mockedService = new(TestExampleImplementation) - - c := mockedService.On("TheExampleMethod", "A", "B", true). - Return(1, "two", true). - Once() - - require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) - - call := mockedService.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod", call.Method) - assert.Equal(t, "A", call.Arguments[0]) - assert.Equal(t, "B", call.Arguments[1]) - assert.Equal(t, true, call.Arguments[2]) - assert.Equal(t, 1, call.ReturnArguments[0]) - assert.Equal(t, "two", call.ReturnArguments[1]) - assert.Equal(t, true, call.ReturnArguments[2]) - assert.Equal(t, 1, call.Repeatability) - assert.Nil(t, call.WaitFor) -} - -func Test_Mock_Return_Twice(t *testing.T) { - - // make a test impl object - var mockedService = new(TestExampleImplementation) - - c := mockedService. - On("TheExampleMethod", "A", "B", true). - Return(1, "two", true). - Twice() - - require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) - - call := mockedService.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod", call.Method) - assert.Equal(t, "A", call.Arguments[0]) - assert.Equal(t, "B", call.Arguments[1]) - assert.Equal(t, true, call.Arguments[2]) - assert.Equal(t, 1, call.ReturnArguments[0]) - assert.Equal(t, "two", call.ReturnArguments[1]) - assert.Equal(t, true, call.ReturnArguments[2]) - assert.Equal(t, 2, call.Repeatability) - assert.Nil(t, call.WaitFor) -} - -func Test_Mock_Return_Times(t *testing.T) { - - // make a test impl object - var mockedService = new(TestExampleImplementation) - - c := mockedService. - On("TheExampleMethod", "A", "B", true). - Return(1, "two", true). - Times(5) - - require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) - - call := mockedService.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod", call.Method) - assert.Equal(t, "A", call.Arguments[0]) - assert.Equal(t, "B", call.Arguments[1]) - assert.Equal(t, true, call.Arguments[2]) - assert.Equal(t, 1, call.ReturnArguments[0]) - assert.Equal(t, "two", call.ReturnArguments[1]) - assert.Equal(t, true, call.ReturnArguments[2]) - assert.Equal(t, 5, call.Repeatability) - assert.Nil(t, call.WaitFor) -} - -func Test_Mock_Return_Nothing(t *testing.T) { - - // make a test impl object - var mockedService = new(TestExampleImplementation) - - c := mockedService. - On("TheExampleMethod", "A", "B", true). - Return() - - require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) - - call := mockedService.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod", call.Method) - assert.Equal(t, "A", call.Arguments[0]) - assert.Equal(t, "B", call.Arguments[1]) - assert.Equal(t, true, call.Arguments[2]) - assert.Equal(t, 0, len(call.ReturnArguments)) -} - -func Test_Mock_findExpectedCall(t *testing.T) { - - m := new(Mock) - m.On("One", 1).Return("one") - m.On("Two", 2).Return("two") - m.On("Two", 3).Return("three") - - f, c := m.findExpectedCall("Two", 3) - - if assert.Equal(t, 2, f) { - if assert.NotNil(t, c) { - assert.Equal(t, "Two", c.Method) - assert.Equal(t, 3, c.Arguments[0]) - assert.Equal(t, "three", c.ReturnArguments[0]) - } - } - -} - -func Test_Mock_findExpectedCall_For_Unknown_Method(t *testing.T) { - - m := new(Mock) - m.On("One", 1).Return("one") - m.On("Two", 2).Return("two") - m.On("Two", 3).Return("three") - - f, _ := m.findExpectedCall("Two") - - assert.Equal(t, -1, f) - -} - -func Test_Mock_findExpectedCall_Respects_Repeatability(t *testing.T) { - - m := new(Mock) - m.On("One", 1).Return("one") - m.On("Two", 2).Return("two").Once() - m.On("Two", 3).Return("three").Twice() - m.On("Two", 3).Return("three").Times(8) - - f, c := m.findExpectedCall("Two", 3) - - if assert.Equal(t, 2, f) { - if assert.NotNil(t, c) { - assert.Equal(t, "Two", c.Method) - assert.Equal(t, 3, c.Arguments[0]) - assert.Equal(t, "three", c.ReturnArguments[0]) - } - } - -} - -func Test_callString(t *testing.T) { - - assert.Equal(t, `Method(int,bool,string)`, callString("Method", []interface{}{1, true, "something"}, false)) - -} - -func Test_Mock_Called(t *testing.T) { - - var mockedService = new(TestExampleImplementation) - - mockedService.On("Test_Mock_Called", 1, 2, 3).Return(5, "6", true) - - returnArguments := mockedService.Called(1, 2, 3) - - if assert.Equal(t, 1, len(mockedService.Calls)) { - assert.Equal(t, "Test_Mock_Called", mockedService.Calls[0].Method) - assert.Equal(t, 1, mockedService.Calls[0].Arguments[0]) - assert.Equal(t, 2, mockedService.Calls[0].Arguments[1]) - assert.Equal(t, 3, mockedService.Calls[0].Arguments[2]) - } - - if assert.Equal(t, 3, len(returnArguments)) { - assert.Equal(t, 5, returnArguments[0]) - assert.Equal(t, "6", returnArguments[1]) - assert.Equal(t, true, returnArguments[2]) - } - -} - -func asyncCall(m *Mock, ch chan Arguments) { - ch <- m.Called(1, 2, 3) -} - -func Test_Mock_Called_blocks(t *testing.T) { - - var mockedService = new(TestExampleImplementation) - - mockedService.Mock.On("asyncCall", 1, 2, 3).Return(5, "6", true).After(2 * time.Millisecond) - - ch := make(chan Arguments) - - go asyncCall(&mockedService.Mock, ch) - - select { - case <-ch: - t.Fatal("should have waited") - case <-time.After(1 * time.Millisecond): - } - - returnArguments := <-ch - - if assert.Equal(t, 1, len(mockedService.Mock.Calls)) { - assert.Equal(t, "asyncCall", mockedService.Mock.Calls[0].Method) - assert.Equal(t, 1, mockedService.Mock.Calls[0].Arguments[0]) - assert.Equal(t, 2, mockedService.Mock.Calls[0].Arguments[1]) - assert.Equal(t, 3, mockedService.Mock.Calls[0].Arguments[2]) - } - - if assert.Equal(t, 3, len(returnArguments)) { - assert.Equal(t, 5, returnArguments[0]) - assert.Equal(t, "6", returnArguments[1]) - assert.Equal(t, true, returnArguments[2]) - } - -} - -func Test_Mock_Called_For_Bounded_Repeatability(t *testing.T) { - - var mockedService = new(TestExampleImplementation) - - mockedService. - On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3). - Return(5, "6", true). - Once() - mockedService. - On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3). - Return(-1, "hi", false) - - returnArguments1 := mockedService.Called(1, 2, 3) - returnArguments2 := mockedService.Called(1, 2, 3) - - if assert.Equal(t, 2, len(mockedService.Calls)) { - assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[0].Method) - assert.Equal(t, 1, mockedService.Calls[0].Arguments[0]) - assert.Equal(t, 2, mockedService.Calls[0].Arguments[1]) - assert.Equal(t, 3, mockedService.Calls[0].Arguments[2]) - - assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[1].Method) - assert.Equal(t, 1, mockedService.Calls[1].Arguments[0]) - assert.Equal(t, 2, mockedService.Calls[1].Arguments[1]) - assert.Equal(t, 3, mockedService.Calls[1].Arguments[2]) - } - - if assert.Equal(t, 3, len(returnArguments1)) { - assert.Equal(t, 5, returnArguments1[0]) - assert.Equal(t, "6", returnArguments1[1]) - assert.Equal(t, true, returnArguments1[2]) - } - - if assert.Equal(t, 3, len(returnArguments2)) { - assert.Equal(t, -1, returnArguments2[0]) - assert.Equal(t, "hi", returnArguments2[1]) - assert.Equal(t, false, returnArguments2[2]) - } - -} - -func Test_Mock_Called_For_SetTime_Expectation(t *testing.T) { - - var mockedService = new(TestExampleImplementation) - - mockedService.On("TheExampleMethod", 1, 2, 3).Return(5, "6", true).Times(4) - - mockedService.TheExampleMethod(1, 2, 3) - mockedService.TheExampleMethod(1, 2, 3) - mockedService.TheExampleMethod(1, 2, 3) - mockedService.TheExampleMethod(1, 2, 3) - assert.Panics(t, func() { - mockedService.TheExampleMethod(1, 2, 3) - }) - -} - -func Test_Mock_Called_Unexpected(t *testing.T) { - - var mockedService = new(TestExampleImplementation) - - // make sure it panics if no expectation was made - assert.Panics(t, func() { - mockedService.Called(1, 2, 3) - }, "Calling unexpected method should panic") - -} - -func Test_AssertExpectationsForObjects_Helper(t *testing.T) { - - var mockedService1 = new(TestExampleImplementation) - var mockedService2 = new(TestExampleImplementation) - var mockedService3 = new(TestExampleImplementation) - - mockedService1.On("Test_AssertExpectationsForObjects_Helper", 1).Return() - mockedService2.On("Test_AssertExpectationsForObjects_Helper", 2).Return() - mockedService3.On("Test_AssertExpectationsForObjects_Helper", 3).Return() - - mockedService1.Called(1) - mockedService2.Called(2) - mockedService3.Called(3) - - assert.True(t, AssertExpectationsForObjects(t, &mockedService1.Mock, &mockedService2.Mock, &mockedService3.Mock)) - assert.True(t, AssertExpectationsForObjects(t, mockedService1, mockedService2, mockedService3)) - -} - -func Test_AssertExpectationsForObjects_Helper_Failed(t *testing.T) { - - var mockedService1 = new(TestExampleImplementation) - var mockedService2 = new(TestExampleImplementation) - var mockedService3 = new(TestExampleImplementation) - - mockedService1.On("Test_AssertExpectationsForObjects_Helper_Failed", 1).Return() - mockedService2.On("Test_AssertExpectationsForObjects_Helper_Failed", 2).Return() - mockedService3.On("Test_AssertExpectationsForObjects_Helper_Failed", 3).Return() - - mockedService1.Called(1) - mockedService3.Called(3) - - tt := new(testing.T) - assert.False(t, AssertExpectationsForObjects(tt, &mockedService1.Mock, &mockedService2.Mock, &mockedService3.Mock)) - assert.False(t, AssertExpectationsForObjects(tt, mockedService1, mockedService2, mockedService3)) - -} - -func Test_Mock_AssertExpectations(t *testing.T) { - - var mockedService = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertExpectations", 1, 2, 3).Return(5, 6, 7) - - tt := new(testing.T) - assert.False(t, mockedService.AssertExpectations(tt)) - - // make the call now - mockedService.Called(1, 2, 3) - - // now assert expectations - assert.True(t, mockedService.AssertExpectations(tt)) - -} - -func Test_Mock_AssertExpectations_Placeholder_NoArgs(t *testing.T) { - - var mockedService = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertExpectations_Placeholder_NoArgs").Return(5, 6, 7).Once() - mockedService.On("Test_Mock_AssertExpectations_Placeholder_NoArgs").Return(7, 6, 5) - - tt := new(testing.T) - assert.False(t, mockedService.AssertExpectations(tt)) - - // make the call now - mockedService.Called() - - // now assert expectations - assert.True(t, mockedService.AssertExpectations(tt)) - -} - -func Test_Mock_AssertExpectations_Placeholder(t *testing.T) { - - var mockedService = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertExpectations_Placeholder", 1, 2, 3).Return(5, 6, 7).Once() - mockedService.On("Test_Mock_AssertExpectations_Placeholder", 3, 2, 1).Return(7, 6, 5) - - tt := new(testing.T) - assert.False(t, mockedService.AssertExpectations(tt)) - - // make the call now - mockedService.Called(1, 2, 3) - - // now assert expectations - assert.False(t, mockedService.AssertExpectations(tt)) - - // make call to the second expectation - mockedService.Called(3, 2, 1) - - // now assert expectations again - assert.True(t, mockedService.AssertExpectations(tt)) -} - -func Test_Mock_AssertExpectations_With_Pointers(t *testing.T) { - - var mockedService = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertExpectations_With_Pointers", &struct{ Foo int }{1}).Return(1) - mockedService.On("Test_Mock_AssertExpectations_With_Pointers", &struct{ Foo int }{2}).Return(2) - - tt := new(testing.T) - assert.False(t, mockedService.AssertExpectations(tt)) - - s := struct{ Foo int }{1} - // make the calls now - mockedService.Called(&s) - s.Foo = 2 - mockedService.Called(&s) - - // now assert expectations - assert.True(t, mockedService.AssertExpectations(tt)) - -} - -func Test_Mock_AssertExpectationsCustomType(t *testing.T) { - - var mockedService = new(TestExampleImplementation) - - mockedService.On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).Return(nil).Once() - - tt := new(testing.T) - assert.False(t, mockedService.AssertExpectations(tt)) - - // make the call now - mockedService.TheExampleMethod3(&ExampleType{}) - - // now assert expectations - assert.True(t, mockedService.AssertExpectations(tt)) - -} - -func Test_Mock_AssertExpectations_With_Repeatability(t *testing.T) { - - var mockedService = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertExpectations_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Twice() - - tt := new(testing.T) - assert.False(t, mockedService.AssertExpectations(tt)) - - // make the call now - mockedService.Called(1, 2, 3) - - assert.False(t, mockedService.AssertExpectations(tt)) - - mockedService.Called(1, 2, 3) - - // now assert expectations - assert.True(t, mockedService.AssertExpectations(tt)) - -} - -func Test_Mock_TwoCallsWithDifferentArguments(t *testing.T) { - - var mockedService = new(TestExampleImplementation) - - mockedService.On("Test_Mock_TwoCallsWithDifferentArguments", 1, 2, 3).Return(5, 6, 7) - mockedService.On("Test_Mock_TwoCallsWithDifferentArguments", 4, 5, 6).Return(5, 6, 7) - - args1 := mockedService.Called(1, 2, 3) - assert.Equal(t, 5, args1.Int(0)) - assert.Equal(t, 6, args1.Int(1)) - assert.Equal(t, 7, args1.Int(2)) - - args2 := mockedService.Called(4, 5, 6) - assert.Equal(t, 5, args2.Int(0)) - assert.Equal(t, 6, args2.Int(1)) - assert.Equal(t, 7, args2.Int(2)) - -} - -func Test_Mock_AssertNumberOfCalls(t *testing.T) { - - var mockedService = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertNumberOfCalls", 1, 2, 3).Return(5, 6, 7) - - mockedService.Called(1, 2, 3) - assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 1)) - - mockedService.Called(1, 2, 3) - assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 2)) - -} - -func Test_Mock_AssertCalled(t *testing.T) { - - var mockedService = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertCalled", 1, 2, 3).Return(5, 6, 7) - - mockedService.Called(1, 2, 3) - - assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled", 1, 2, 3)) - -} - -func Test_Mock_AssertCalled_WithAnythingOfTypeArgument(t *testing.T) { - - var mockedService = new(TestExampleImplementation) - - mockedService. - On("Test_Mock_AssertCalled_WithAnythingOfTypeArgument", Anything, Anything, Anything). - Return() - - mockedService.Called(1, "two", []uint8("three")) - - assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled_WithAnythingOfTypeArgument", AnythingOfType("int"), AnythingOfType("string"), AnythingOfType("[]uint8"))) - -} - -func Test_Mock_AssertCalled_WithArguments(t *testing.T) { - - var mockedService = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertCalled_WithArguments", 1, 2, 3).Return(5, 6, 7) - - mockedService.Called(1, 2, 3) - - tt := new(testing.T) - assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 1, 2, 3)) - assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 2, 3, 4)) - -} - -func Test_Mock_AssertCalled_WithArguments_With_Repeatability(t *testing.T) { - - var mockedService = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Once() - mockedService.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4).Return(5, 6, 7).Once() - - mockedService.Called(1, 2, 3) - mockedService.Called(2, 3, 4) - - tt := new(testing.T) - assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3)) - assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4)) - assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 3, 4, 5)) - -} - -func Test_Mock_AssertNotCalled(t *testing.T) { - - var mockedService = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertNotCalled", 1, 2, 3).Return(5, 6, 7) - - mockedService.Called(1, 2, 3) - - assert.True(t, mockedService.AssertNotCalled(t, "Test_Mock_NotCalled")) - -} - -func Test_Mock_AssertOptional(t *testing.T) { - // Optional called - var ms1 = new(TestExampleImplementation) - ms1.On("TheExampleMethod", 1, 2, 3).Maybe().Return(4, nil) - ms1.TheExampleMethod(1, 2, 3) - - tt1 := new(testing.T) - assert.Equal(t, true, ms1.AssertExpectations(tt1)) - - // Optional not called - var ms2 = new(TestExampleImplementation) - ms2.On("TheExampleMethod", 1, 2, 3).Maybe().Return(4, nil) - - tt2 := new(testing.T) - assert.Equal(t, true, ms2.AssertExpectations(tt2)) - - // Non-optional called - var ms3 = new(TestExampleImplementation) - ms3.On("TheExampleMethod", 1, 2, 3).Return(4, nil) - ms3.TheExampleMethod(1, 2, 3) - - tt3 := new(testing.T) - assert.Equal(t, true, ms3.AssertExpectations(tt3)) -} - -/* - Arguments helper methods -*/ -func Test_Arguments_Get(t *testing.T) { - - var args = Arguments([]interface{}{"string", 123, true}) - - assert.Equal(t, "string", args.Get(0).(string)) - assert.Equal(t, 123, args.Get(1).(int)) - assert.Equal(t, true, args.Get(2).(bool)) - -} - -func Test_Arguments_Is(t *testing.T) { - - var args = Arguments([]interface{}{"string", 123, true}) - - assert.True(t, args.Is("string", 123, true)) - assert.False(t, args.Is("wrong", 456, false)) - -} - -func Test_Arguments_Diff(t *testing.T) { - - var args = Arguments([]interface{}{"Hello World", 123, true}) - var diff string - var count int - diff, count = args.Diff([]interface{}{"Hello World", 456, "false"}) - - assert.Equal(t, 2, count) - assert.Contains(t, diff, `(int=456) != (int=123)`) - assert.Contains(t, diff, `(string=false) != (bool=true)`) - -} - -func Test_Arguments_Diff_DifferentNumberOfArgs(t *testing.T) { - - var args = Arguments([]interface{}{"string", 123, true}) - var diff string - var count int - diff, count = args.Diff([]interface{}{"string", 456, "false", "extra"}) - - assert.Equal(t, 3, count) - assert.Contains(t, diff, `(string=extra) != (Missing)`) - -} - -func Test_Arguments_Diff_WithAnythingArgument(t *testing.T) { - - var args = Arguments([]interface{}{"string", 123, true}) - var count int - _, count = args.Diff([]interface{}{"string", Anything, true}) - - assert.Equal(t, 0, count) - -} - -func Test_Arguments_Diff_WithAnythingArgument_InActualToo(t *testing.T) { - - var args = Arguments([]interface{}{"string", Anything, true}) - var count int - _, count = args.Diff([]interface{}{"string", 123, true}) - - assert.Equal(t, 0, count) - -} - -func Test_Arguments_Diff_WithAnythingOfTypeArgument(t *testing.T) { - - var args = Arguments([]interface{}{"string", AnythingOfType("int"), true}) - var count int - _, count = args.Diff([]interface{}{"string", 123, true}) - - assert.Equal(t, 0, count) - -} - -func Test_Arguments_Diff_WithAnythingOfTypeArgument_Failing(t *testing.T) { - - var args = Arguments([]interface{}{"string", AnythingOfType("string"), true}) - var count int - var diff string - diff, count = args.Diff([]interface{}{"string", 123, true}) - - assert.Equal(t, 1, count) - assert.Contains(t, diff, `string != type int - (int=123)`) - -} - -func Test_Arguments_Diff_WithArgMatcher(t *testing.T) { - matchFn := func(a int) bool { - return a == 123 - } - var args = Arguments([]interface{}{"string", MatchedBy(matchFn), true}) - - diff, count := args.Diff([]interface{}{"string", 124, true}) - assert.Equal(t, 1, count) - assert.Contains(t, diff, `(int=124) not matched by func(int) bool`) - - diff, count = args.Diff([]interface{}{"string", false, true}) - assert.Equal(t, 1, count) - assert.Contains(t, diff, `(bool=false) not matched by func(int) bool`) - - diff, count = args.Diff([]interface{}{"string", 123, false}) - assert.Contains(t, diff, `(int=123) matched by func(int) bool`) - - diff, count = args.Diff([]interface{}{"string", 123, true}) - assert.Equal(t, 0, count) - assert.Contains(t, diff, `No differences.`) -} - -func Test_Arguments_Assert(t *testing.T) { - - var args = Arguments([]interface{}{"string", 123, true}) - - assert.True(t, args.Assert(t, "string", 123, true)) - -} - -func Test_Arguments_String_Representation(t *testing.T) { - - var args = Arguments([]interface{}{"string", 123, true}) - assert.Equal(t, `string,int,bool`, args.String()) - -} - -func Test_Arguments_String(t *testing.T) { - - var args = Arguments([]interface{}{"string", 123, true}) - assert.Equal(t, "string", args.String(0)) - -} - -func Test_Arguments_Error(t *testing.T) { - - var err = errors.New("An Error") - var args = Arguments([]interface{}{"string", 123, true, err}) - assert.Equal(t, err, args.Error(3)) - -} - -func Test_Arguments_Error_Nil(t *testing.T) { - - var args = Arguments([]interface{}{"string", 123, true, nil}) - assert.Equal(t, nil, args.Error(3)) - -} - -func Test_Arguments_Int(t *testing.T) { - - var args = Arguments([]interface{}{"string", 123, true}) - assert.Equal(t, 123, args.Int(1)) - -} - -func Test_Arguments_Bool(t *testing.T) { - - var args = Arguments([]interface{}{"string", 123, true}) - assert.Equal(t, true, args.Bool(2)) - -} - -func Test_WaitUntil_Parallel(t *testing.T) { - - // make a test impl object - var mockedService = new(TestExampleImplementation) - - ch1 := make(chan time.Time) - ch2 := make(chan time.Time) - - mockedService.Mock.On("TheExampleMethod2", true).Return().WaitUntil(ch2).Run(func(args Arguments) { - ch1 <- time.Now() - }) - - mockedService.Mock.On("TheExampleMethod2", false).Return().WaitUntil(ch1) - - // Lock both goroutines on the .WaitUntil method - go func() { - mockedService.TheExampleMethod2(false) - }() - go func() { - mockedService.TheExampleMethod2(true) - }() - - // Allow the first call to execute, so the second one executes afterwards - ch2 <- time.Now() -} - -func Test_MockMethodCalled(t *testing.T) { - m := new(Mock) - m.On("foo", "hello").Return("world") - - retArgs := m.MethodCalled("foo", "hello") - require.True(t, len(retArgs) == 1) - require.Equal(t, "world", retArgs[0]) - m.AssertExpectations(t) -} - -// Test to validate fix for racy concurrent call access in MethodCalled() -func Test_MockReturnAndCalledConcurrent(t *testing.T) { - iterations := 1000 - m := &Mock{} - call := m.On("ConcurrencyTestMethod") - - wg := sync.WaitGroup{} - wg.Add(2) - - go func() { - for i := 0; i < iterations; i++ { - call.Return(10) - } - wg.Done() - }() - go func() { - for i := 0; i < iterations; i++ { - ConcurrencyTestMethod(m) - } - wg.Done() - }() - wg.Wait() -} - -type timer struct{ Mock } - -func (s *timer) GetTime(i int) string { - return s.Called(i).Get(0).(string) -} - -type tCustomLogger struct { - *testing.T - logs []string - errs []string -} - -func (tc *tCustomLogger) Logf(format string, args ...interface{}) { - tc.T.Logf(format, args...) - tc.logs = append(tc.logs, fmt.Sprintf(format, args...)) -} - -func (tc *tCustomLogger) Errorf(format string, args ...interface{}) { - tc.errs = append(tc.errs, fmt.Sprintf(format, args...)) -} - -func (tc *tCustomLogger) FailNow() {} - -func TestLoggingAssertExpectations(t *testing.T) { - m := new(timer) - m.On("GetTime", 0).Return("") - tcl := &tCustomLogger{t, []string{}, []string{}} - - AssertExpectationsForObjects(tcl, m, new(TestExampleImplementation)) - - require.Equal(t, 1, len(tcl.errs)) - assert.Regexp(t, regexp.MustCompile("(?s)FAIL: 0 out of 1 expectation\\(s\\) were met.*The code you are testing needs to make 1 more call\\(s\\).*"), tcl.errs[0]) - require.Equal(t, 2, len(tcl.logs)) - assert.Regexp(t, regexp.MustCompile("(?s)FAIL:\tGetTime\\(int\\).*"), tcl.logs[0]) - require.Equal(t, "Expectations didn't match for Mock: *mock.timer", tcl.logs[1]) -} - -func TestAfterTotalWaitTimeWhileExecution(t *testing.T) { - waitDuration := 1 - total, waitMs := 5, time.Millisecond*time.Duration(waitDuration) - aTimer := new(timer) - for i := 0; i < total; i++ { - aTimer.On("GetTime", i).After(waitMs).Return(fmt.Sprintf("Time%d", i)).Once() - } - time.Sleep(waitMs) - start := time.Now() - var results []string - - for i := 0; i < total; i++ { - results = append(results, aTimer.GetTime(i)) - } - - end := time.Now() - elapsedTime := end.Sub(start) - assert.True(t, elapsedTime > waitMs, fmt.Sprintf("Total elapsed time:%v should be atleast greater than %v", elapsedTime, waitMs)) - assert.Equal(t, total, len(results)) - for i := range results { - assert.Equal(t, fmt.Sprintf("Time%d", i), results[i], "Return value of method should be same") - } -} - -func TestArgumentMatcherToPrintMismatch(t *testing.T) { - defer func() { - if r := recover(); r != nil { - matchingExp := regexp.MustCompile( - `\s+mock: Unexpected Method Call\s+-*\s+GetTime\(int\)\s+0: 1\s+The closest call I have is:\s+GetTime\(mock.argumentMatcher\)\s+0: mock.argumentMatcher\{.*?\}\s+Diff:.*\(int=1\) not matched by func\(int\) bool`) - assert.Regexp(t, matchingExp, r) - } - }() - - m := new(timer) - m.On("GetTime", MatchedBy(func(i int) bool { return false })).Return("SomeTime").Once() - - res := m.GetTime(1) - require.Equal(t, "SomeTime", res) - m.AssertExpectations(t) -} - -func TestClosestCallMismatchedArgumentInformationShowsTheClosest(t *testing.T) { - defer func() { - if r := recover(); r != nil { - matchingExp := regexp.MustCompile(unexpectedCallRegex(`TheExampleMethod(int,int,int)`, `0: 1\s+1: 1\s+2: 2`, `0: 1\s+1: 1\s+2: 1`, `0: PASS: \(int=1\) == \(int=1\)\s+1: PASS: \(int=1\) == \(int=1\)\s+2: FAIL: \(int=2\) != \(int=1\)`)) - assert.Regexp(t, matchingExp, r) - } - }() - - m := new(TestExampleImplementation) - m.On("TheExampleMethod", 1, 1, 1).Return(1, nil).Once() - m.On("TheExampleMethod", 2, 2, 2).Return(2, nil).Once() - - m.TheExampleMethod(1, 1, 2) -} - -func TestClosestCallMismatchedArgumentValueInformation(t *testing.T) { - defer func() { - if r := recover(); r != nil { - matchingExp := regexp.MustCompile(unexpectedCallRegex(`GetTime(int)`, "0: 1", "0: 999", `0: FAIL: \(int=1\) != \(int=999\)`)) - assert.Regexp(t, matchingExp, r) - } - }() - - m := new(timer) - m.On("GetTime", 999).Return("SomeTime").Once() - - _ = m.GetTime(1) -} - -func unexpectedCallRegex(method, calledArg, expectedArg, diff string) string { - rMethod := regexp.QuoteMeta(method) - return fmt.Sprintf(`\s+mock: Unexpected Method Call\s+-*\s+%s\s+%s\s+The closest call I have is:\s+%s\s+%s\s+Diff: %s`, - rMethod, calledArg, rMethod, expectedArg, diff) -} - -//go:noinline -func ConcurrencyTestMethod(m *Mock) { - m.Called() -} diff --git a/src/vendor/github.com/stretchr/testify/package_test.go b/src/vendor/github.com/stretchr/testify/package_test.go deleted file mode 100644 index 7ac5d6d8edb0c08a8118206212eab5b9147da5ca..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/package_test.go +++ /dev/null @@ -1,12 +0,0 @@ -package testify - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestImports(t *testing.T) { - if assert.Equal(t, 1, 1) != true { - t.Error("Something is wrong.") - } -} diff --git a/src/vendor/github.com/stretchr/testify/require/forward_requirements_test.go b/src/vendor/github.com/stretchr/testify/require/forward_requirements_test.go deleted file mode 100644 index b120ae3b8f7e1830d7ef529448bb2cd14089fe22..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/require/forward_requirements_test.go +++ /dev/null @@ -1,385 +0,0 @@ -package require - -import ( - "errors" - "testing" - "time" -) - -func TestImplementsWrapper(t *testing.T) { - require := New(t) - - require.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestIsTypeWrapper(t *testing.T) { - require := New(t) - require.IsType(new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.IsType(new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestEqualWrapper(t *testing.T) { - require := New(t) - require.Equal(1, 1) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Equal(1, 2) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotEqualWrapper(t *testing.T) { - require := New(t) - require.NotEqual(1, 2) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.NotEqual(2, 2) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestExactlyWrapper(t *testing.T) { - require := New(t) - - a := float32(1) - b := float32(1) - c := float64(1) - - require.Exactly(a, b) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Exactly(a, c) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotNilWrapper(t *testing.T) { - require := New(t) - require.NotNil(t, new(AssertionTesterConformingObject)) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.NotNil(nil) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNilWrapper(t *testing.T) { - require := New(t) - require.Nil(nil) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Nil(new(AssertionTesterConformingObject)) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestTrueWrapper(t *testing.T) { - require := New(t) - require.True(true) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.True(false) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestFalseWrapper(t *testing.T) { - require := New(t) - require.False(false) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.False(true) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestContainsWrapper(t *testing.T) { - require := New(t) - require.Contains("Hello World", "Hello") - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Contains("Hello World", "Salut") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotContainsWrapper(t *testing.T) { - require := New(t) - require.NotContains("Hello World", "Hello!") - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.NotContains("Hello World", "Hello") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestPanicsWrapper(t *testing.T) { - require := New(t) - require.Panics(func() { - panic("Panic!") - }) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Panics(func() {}) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotPanicsWrapper(t *testing.T) { - require := New(t) - require.NotPanics(func() {}) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.NotPanics(func() { - panic("Panic!") - }) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNoErrorWrapper(t *testing.T) { - require := New(t) - require.NoError(nil) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.NoError(errors.New("some error")) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestErrorWrapper(t *testing.T) { - require := New(t) - require.Error(errors.New("some error")) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Error(nil) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestEqualErrorWrapper(t *testing.T) { - require := New(t) - require.EqualError(errors.New("some error"), "some error") - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.EqualError(errors.New("some error"), "Not some error") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestEmptyWrapper(t *testing.T) { - require := New(t) - require.Empty("") - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Empty("x") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotEmptyWrapper(t *testing.T) { - require := New(t) - require.NotEmpty("x") - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.NotEmpty("") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestWithinDurationWrapper(t *testing.T) { - require := New(t) - a := time.Now() - b := a.Add(10 * time.Second) - - require.WithinDuration(a, b, 15*time.Second) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.WithinDuration(a, b, 5*time.Second) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestInDeltaWrapper(t *testing.T) { - require := New(t) - require.InDelta(1.001, 1, 0.01) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.InDelta(1, 2, 0.5) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestZeroWrapper(t *testing.T) { - require := New(t) - require.Zero(0) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Zero(1) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotZeroWrapper(t *testing.T) { - require := New(t) - require.NotZero(1) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.NotZero(0) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestJSONEqWrapper_EqualSONString(t *testing.T) { - mockT := new(MockT) - mockRequire := New(mockT) - - mockRequire.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`) - if mockT.Failed { - t.Error("Check should pass") - } -} - -func TestJSONEqWrapper_EquivalentButNotEqual(t *testing.T) { - mockT := new(MockT) - mockRequire := New(mockT) - - mockRequire.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) - if mockT.Failed { - t.Error("Check should pass") - } -} - -func TestJSONEqWrapper_HashOfArraysAndHashes(t *testing.T) { - mockT := new(MockT) - mockRequire := New(mockT) - - mockRequire.JSONEq("{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}", - "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}") - if mockT.Failed { - t.Error("Check should pass") - } -} - -func TestJSONEqWrapper_Array(t *testing.T) { - mockT := new(MockT) - mockRequire := New(mockT) - - mockRequire.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`) - if mockT.Failed { - t.Error("Check should pass") - } -} - -func TestJSONEqWrapper_HashAndArrayNotEquivalent(t *testing.T) { - mockT := new(MockT) - mockRequire := New(mockT) - - mockRequire.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestJSONEqWrapper_HashesNotEquivalent(t *testing.T) { - mockT := new(MockT) - mockRequire := New(mockT) - - mockRequire.JSONEq(`{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestJSONEqWrapper_ActualIsNotJSON(t *testing.T) { - mockT := new(MockT) - mockRequire := New(mockT) - - mockRequire.JSONEq(`{"foo": "bar"}`, "Not JSON") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestJSONEqWrapper_ExpectedIsNotJSON(t *testing.T) { - mockT := new(MockT) - mockRequire := New(mockT) - - mockRequire.JSONEq("Not JSON", `{"foo": "bar", "hello": "world"}`) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestJSONEqWrapper_ExpectedAndActualNotJSON(t *testing.T) { - mockT := new(MockT) - mockRequire := New(mockT) - - mockRequire.JSONEq("Not JSON", "Not JSON") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestJSONEqWrapper_ArraysOfDifferentOrder(t *testing.T) { - mockT := new(MockT) - mockRequire := New(mockT) - - mockRequire.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`) - if !mockT.Failed { - t.Error("Check should fail") - } -} diff --git a/src/vendor/github.com/stretchr/testify/require/requirements_test.go b/src/vendor/github.com/stretchr/testify/require/requirements_test.go deleted file mode 100644 index 39467d9a51f2b20319855662982d8d0e601cf2e3..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/require/requirements_test.go +++ /dev/null @@ -1,566 +0,0 @@ -package require - -import ( - "encoding/json" - "errors" - "testing" - "time" -) - -// AssertionTesterInterface defines an interface to be used for testing assertion methods -type AssertionTesterInterface interface { - TestMethod() -} - -// AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface -type AssertionTesterConformingObject struct { -} - -func (a *AssertionTesterConformingObject) TestMethod() { -} - -// AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface -type AssertionTesterNonConformingObject struct { -} - -type MockT struct { - Failed bool -} - -func (t *MockT) FailNow() { - t.Failed = true -} - -func (t *MockT) Errorf(format string, args ...interface{}) { - _, _ = format, args -} - -func TestImplements(t *testing.T) { - - Implements(t, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) - - mockT := new(MockT) - Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestIsType(t *testing.T) { - - IsType(t, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) - - mockT := new(MockT) - IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestEqual(t *testing.T) { - - Equal(t, 1, 1) - - mockT := new(MockT) - Equal(mockT, 1, 2) - if !mockT.Failed { - t.Error("Check should fail") - } - -} - -func TestNotEqual(t *testing.T) { - - NotEqual(t, 1, 2) - mockT := new(MockT) - NotEqual(mockT, 2, 2) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestExactly(t *testing.T) { - - a := float32(1) - b := float32(1) - c := float64(1) - - Exactly(t, a, b) - - mockT := new(MockT) - Exactly(mockT, a, c) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotNil(t *testing.T) { - - NotNil(t, new(AssertionTesterConformingObject)) - - mockT := new(MockT) - NotNil(mockT, nil) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNil(t *testing.T) { - - Nil(t, nil) - - mockT := new(MockT) - Nil(mockT, new(AssertionTesterConformingObject)) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestTrue(t *testing.T) { - - True(t, true) - - mockT := new(MockT) - True(mockT, false) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestFalse(t *testing.T) { - - False(t, false) - - mockT := new(MockT) - False(mockT, true) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestContains(t *testing.T) { - - Contains(t, "Hello World", "Hello") - - mockT := new(MockT) - Contains(mockT, "Hello World", "Salut") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotContains(t *testing.T) { - - NotContains(t, "Hello World", "Hello!") - - mockT := new(MockT) - NotContains(mockT, "Hello World", "Hello") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestPanics(t *testing.T) { - - Panics(t, func() { - panic("Panic!") - }) - - mockT := new(MockT) - Panics(mockT, func() {}) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotPanics(t *testing.T) { - - NotPanics(t, func() {}) - - mockT := new(MockT) - NotPanics(mockT, func() { - panic("Panic!") - }) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNoError(t *testing.T) { - - NoError(t, nil) - - mockT := new(MockT) - NoError(mockT, errors.New("some error")) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestError(t *testing.T) { - - Error(t, errors.New("some error")) - - mockT := new(MockT) - Error(mockT, nil) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestEqualError(t *testing.T) { - - EqualError(t, errors.New("some error"), "some error") - - mockT := new(MockT) - EqualError(mockT, errors.New("some error"), "Not some error") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestEmpty(t *testing.T) { - - Empty(t, "") - - mockT := new(MockT) - Empty(mockT, "x") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotEmpty(t *testing.T) { - - NotEmpty(t, "x") - - mockT := new(MockT) - NotEmpty(mockT, "") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestWithinDuration(t *testing.T) { - - a := time.Now() - b := a.Add(10 * time.Second) - - WithinDuration(t, a, b, 15*time.Second) - - mockT := new(MockT) - WithinDuration(mockT, a, b, 5*time.Second) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestInDelta(t *testing.T) { - - InDelta(t, 1.001, 1, 0.01) - - mockT := new(MockT) - InDelta(mockT, 1, 2, 0.5) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestZero(t *testing.T) { - - Zero(t, "") - - mockT := new(MockT) - Zero(mockT, "x") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotZero(t *testing.T) { - - NotZero(t, "x") - - mockT := new(MockT) - NotZero(mockT, "") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestJSONEq_EqualSONString(t *testing.T) { - mockT := new(MockT) - JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`) - if mockT.Failed { - t.Error("Check should pass") - } -} - -func TestJSONEq_EquivalentButNotEqual(t *testing.T) { - mockT := new(MockT) - JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) - if mockT.Failed { - t.Error("Check should pass") - } -} - -func TestJSONEq_HashOfArraysAndHashes(t *testing.T) { - mockT := new(MockT) - JSONEq(mockT, "{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}", - "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}") - if mockT.Failed { - t.Error("Check should pass") - } -} - -func TestJSONEq_Array(t *testing.T) { - mockT := new(MockT) - JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`) - if mockT.Failed { - t.Error("Check should pass") - } -} - -func TestJSONEq_HashAndArrayNotEquivalent(t *testing.T) { - mockT := new(MockT) - JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestJSONEq_HashesNotEquivalent(t *testing.T) { - mockT := new(MockT) - JSONEq(mockT, `{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestJSONEq_ActualIsNotJSON(t *testing.T) { - mockT := new(MockT) - JSONEq(mockT, `{"foo": "bar"}`, "Not JSON") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestJSONEq_ExpectedIsNotJSON(t *testing.T) { - mockT := new(MockT) - JSONEq(mockT, "Not JSON", `{"foo": "bar", "hello": "world"}`) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestJSONEq_ExpectedAndActualNotJSON(t *testing.T) { - mockT := new(MockT) - JSONEq(mockT, "Not JSON", "Not JSON") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestJSONEq_ArraysOfDifferentOrder(t *testing.T) { - mockT := new(MockT) - JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func ExampleComparisonAssertionFunc() { - t := &testing.T{} // provided by test - - adder := func(x, y int) int { - return x + y - } - - type args struct { - x int - y int - } - - tests := []struct { - name string - args args - expect int - assertion ComparisonAssertionFunc - }{ - {"2+2=4", args{2, 2}, 4, Equal}, - {"2+2!=5", args{2, 2}, 5, NotEqual}, - {"2+3==5", args{2, 3}, 5, Exactly}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - tt.assertion(t, tt.expect, adder(tt.args.x, tt.args.y)) - }) - } -} - -func TestComparisonAssertionFunc(t *testing.T) { - type iface interface { - Name() string - } - - tests := []struct { - name string - expect interface{} - got interface{} - assertion ComparisonAssertionFunc - }{ - {"implements", (*iface)(nil), t, Implements}, - {"isType", (*testing.T)(nil), t, IsType}, - {"equal", t, t, Equal}, - {"equalValues", t, t, EqualValues}, - {"exactly", t, t, Exactly}, - {"notEqual", t, nil, NotEqual}, - {"notContains", []int{1, 2, 3}, 4, NotContains}, - {"subset", []int{1, 2, 3, 4}, []int{2, 3}, Subset}, - {"notSubset", []int{1, 2, 3, 4}, []int{0, 3}, NotSubset}, - {"elementsMatch", []byte("abc"), []byte("bac"), ElementsMatch}, - {"regexp", "^t.*y$", "testify", Regexp}, - {"notRegexp", "^t.*y$", "Testify", NotRegexp}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - tt.assertion(t, tt.expect, tt.got) - }) - } -} - -func ExampleValueAssertionFunc() { - t := &testing.T{} // provided by test - - dumbParse := func(input string) interface{} { - var x interface{} - json.Unmarshal([]byte(input), &x) - return x - } - - tests := []struct { - name string - arg string - assertion ValueAssertionFunc - }{ - {"true is not nil", "true", NotNil}, - {"empty string is nil", "", Nil}, - {"zero is not nil", "0", NotNil}, - {"zero is zero", "0", Zero}, - {"false is zero", "false", Zero}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - tt.assertion(t, dumbParse(tt.arg)) - }) - } -} - -func TestValueAssertionFunc(t *testing.T) { - tests := []struct { - name string - value interface{} - assertion ValueAssertionFunc - }{ - {"notNil", true, NotNil}, - {"nil", nil, Nil}, - {"empty", []int{}, Empty}, - {"notEmpty", []int{1}, NotEmpty}, - {"zero", false, Zero}, - {"notZero", 42, NotZero}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - tt.assertion(t, tt.value) - }) - } -} - -func ExampleBoolAssertionFunc() { - t := &testing.T{} // provided by test - - isOkay := func(x int) bool { - return x >= 42 - } - - tests := []struct { - name string - arg int - assertion BoolAssertionFunc - }{ - {"-1 is bad", -1, False}, - {"42 is good", 42, True}, - {"41 is bad", 41, False}, - {"45 is cool", 45, True}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - tt.assertion(t, isOkay(tt.arg)) - }) - } -} - -func TestBoolAssertionFunc(t *testing.T) { - tests := []struct { - name string - value bool - assertion BoolAssertionFunc - }{ - {"true", true, True}, - {"false", false, False}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - tt.assertion(t, tt.value) - }) - } -} - -func ExampleErrorAssertionFunc() { - t := &testing.T{} // provided by test - - dumbParseNum := func(input string, v interface{}) error { - return json.Unmarshal([]byte(input), v) - } - - tests := []struct { - name string - arg string - assertion ErrorAssertionFunc - }{ - {"1.2 is number", "1.2", NoError}, - {"1.2.3 not number", "1.2.3", Error}, - {"true is not number", "true", Error}, - {"3 is number", "3", NoError}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - var x float64 - tt.assertion(t, dumbParseNum(tt.arg, &x)) - }) - } -} - -func TestErrorAssertionFunc(t *testing.T) { - tests := []struct { - name string - err error - assertion ErrorAssertionFunc - }{ - {"noError", nil, NoError}, - {"error", errors.New("whoops"), Error}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - tt.assertion(t, tt.err) - }) - } -} diff --git a/src/vendor/github.com/stretchr/testify/suite/doc.go b/src/vendor/github.com/stretchr/testify/suite/doc.go deleted file mode 100644 index f91a245d3f8b4e191df196634960c06d882d0c9e..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/suite/doc.go +++ /dev/null @@ -1,65 +0,0 @@ -// Package suite contains logic for creating testing suite structs -// and running the methods on those structs as tests. The most useful -// piece of this package is that you can create setup/teardown methods -// on your testing suites, which will run before/after the whole suite -// or individual tests (depending on which interface(s) you -// implement). -// -// A testing suite is usually built by first extending the built-in -// suite functionality from suite.Suite in testify. Alternatively, -// you could reproduce that logic on your own if you wanted (you -// just need to implement the TestingSuite interface from -// suite/interfaces.go). -// -// After that, you can implement any of the interfaces in -// suite/interfaces.go to add setup/teardown functionality to your -// suite, and add any methods that start with "Test" to add tests. -// Methods that do not match any suite interfaces and do not begin -// with "Test" will not be run by testify, and can safely be used as -// helper methods. -// -// Once you've built your testing suite, you need to run the suite -// (using suite.Run from testify) inside any function that matches the -// identity that "go test" is already looking for (i.e. -// func(*testing.T)). -// -// Regular expression to select test suites specified command-line -// argument "-run". Regular expression to select the methods -// of test suites specified command-line argument "-m". -// Suite object has assertion methods. -// -// A crude example: -// // Basic imports -// import ( -// "testing" -// "github.com/stretchr/testify/assert" -// "github.com/stretchr/testify/suite" -// ) -// -// // Define the suite, and absorb the built-in basic suite -// // functionality from testify - including a T() method which -// // returns the current testing context -// type ExampleTestSuite struct { -// suite.Suite -// VariableThatShouldStartAtFive int -// } -// -// // Make sure that VariableThatShouldStartAtFive is set to five -// // before each test -// func (suite *ExampleTestSuite) SetupTest() { -// suite.VariableThatShouldStartAtFive = 5 -// } -// -// // All methods that begin with "Test" are run as tests within a -// // suite. -// func (suite *ExampleTestSuite) TestExample() { -// assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) -// suite.Equal(5, suite.VariableThatShouldStartAtFive) -// } -// -// // In order for 'go test' to run this suite, we need to create -// // a normal test function and pass our suite to suite.Run -// func TestExampleTestSuite(t *testing.T) { -// suite.Run(t, new(ExampleTestSuite)) -// } -package suite diff --git a/src/vendor/github.com/stretchr/testify/suite/interfaces.go b/src/vendor/github.com/stretchr/testify/suite/interfaces.go deleted file mode 100644 index b37cb0409879c28d8548a195f4257c4129ef6066..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/suite/interfaces.go +++ /dev/null @@ -1,46 +0,0 @@ -package suite - -import "testing" - -// TestingSuite can store and return the current *testing.T context -// generated by 'go test'. -type TestingSuite interface { - T() *testing.T - SetT(*testing.T) -} - -// SetupAllSuite has a SetupSuite method, which will run before the -// tests in the suite are run. -type SetupAllSuite interface { - SetupSuite() -} - -// SetupTestSuite has a SetupTest method, which will run before each -// test in the suite. -type SetupTestSuite interface { - SetupTest() -} - -// TearDownAllSuite has a TearDownSuite method, which will run after -// all the tests in the suite have been run. -type TearDownAllSuite interface { - TearDownSuite() -} - -// TearDownTestSuite has a TearDownTest method, which will run after -// each test in the suite. -type TearDownTestSuite interface { - TearDownTest() -} - -// BeforeTest has a function to be executed right before the test -// starts and receives the suite and test names as input -type BeforeTest interface { - BeforeTest(suiteName, testName string) -} - -// AfterTest has a function to be executed right after the test -// finishes and receives the suite and test names as input -type AfterTest interface { - AfterTest(suiteName, testName string) -} diff --git a/src/vendor/github.com/stretchr/testify/suite/suite.go b/src/vendor/github.com/stretchr/testify/suite/suite.go deleted file mode 100644 index 5cea8f8c757f95ff9e3cd863a5d43996f8ae4e18..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/suite/suite.go +++ /dev/null @@ -1,160 +0,0 @@ -package suite - -import ( - "flag" - "fmt" - "os" - "reflect" - "regexp" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var allTestsFilter = func(_, _ string) (bool, error) { return true, nil } -var matchMethod = flag.String("testify.m", "", "regular expression to select tests of the testify suite to run") - -// Suite is a basic testing suite with methods for storing and -// retrieving the current *testing.T context. -type Suite struct { - *assert.Assertions - require *require.Assertions - t *testing.T -} - -// T retrieves the current *testing.T context. -func (suite *Suite) T() *testing.T { - return suite.t -} - -// SetT sets the current *testing.T context. -func (suite *Suite) SetT(t *testing.T) { - suite.t = t - suite.Assertions = assert.New(t) - suite.require = require.New(t) -} - -// Require returns a require context for suite. -func (suite *Suite) Require() *require.Assertions { - if suite.require == nil { - suite.require = require.New(suite.T()) - } - return suite.require -} - -// Assert returns an assert context for suite. Normally, you can call -// `suite.NoError(expected, actual)`, but for situations where the embedded -// methods are overridden (for example, you might want to override -// assert.Assertions with require.Assertions), this method is provided so you -// can call `suite.Assert().NoError()`. -func (suite *Suite) Assert() *assert.Assertions { - if suite.Assertions == nil { - suite.Assertions = assert.New(suite.T()) - } - return suite.Assertions -} - -func failOnPanic(t *testing.T) { - r := recover() - if r != nil { - t.Errorf("test panicked: %v", r) - t.FailNow() - } -} - -// Run provides suite functionality around golang subtests. It should be -// called in place of t.Run(name, func(t *testing.T)) in test suite code. -// The passed-in func will be executed as a subtest with a fresh instance of t. -// Provides compatibility with go test pkg -run TestSuite/TestName/SubTestName. -func (suite *Suite) Run(name string, subtest func()) bool { - oldT := suite.T() - defer suite.SetT(oldT) - return oldT.Run(name, func(t *testing.T) { - suite.SetT(t) - subtest() - }) -} - -// Run takes a testing suite and runs all of the tests attached -// to it. -func Run(t *testing.T, suite TestingSuite) { - suite.SetT(t) - defer failOnPanic(t) - - if setupAllSuite, ok := suite.(SetupAllSuite); ok { - setupAllSuite.SetupSuite() - } - defer func() { - if tearDownAllSuite, ok := suite.(TearDownAllSuite); ok { - tearDownAllSuite.TearDownSuite() - } - }() - - methodFinder := reflect.TypeOf(suite) - tests := []testing.InternalTest{} - for index := 0; index < methodFinder.NumMethod(); index++ { - method := methodFinder.Method(index) - ok, err := methodFilter(method.Name) - if err != nil { - fmt.Fprintf(os.Stderr, "testify: invalid regexp for -m: %s\n", err) - os.Exit(1) - } - if ok { - test := testing.InternalTest{ - Name: method.Name, - F: func(t *testing.T) { - parentT := suite.T() - suite.SetT(t) - defer failOnPanic(t) - - if setupTestSuite, ok := suite.(SetupTestSuite); ok { - setupTestSuite.SetupTest() - } - if beforeTestSuite, ok := suite.(BeforeTest); ok { - beforeTestSuite.BeforeTest(methodFinder.Elem().Name(), method.Name) - } - defer func() { - if afterTestSuite, ok := suite.(AfterTest); ok { - afterTestSuite.AfterTest(methodFinder.Elem().Name(), method.Name) - } - if tearDownTestSuite, ok := suite.(TearDownTestSuite); ok { - tearDownTestSuite.TearDownTest() - } - suite.SetT(parentT) - }() - method.Func.Call([]reflect.Value{reflect.ValueOf(suite)}) - }, - } - tests = append(tests, test) - } - } - runTests(t, tests) -} - -func runTests(t testing.TB, tests []testing.InternalTest) { - r, ok := t.(runner) - if !ok { // backwards compatibility with Go 1.6 and below - if !testing.RunTests(allTestsFilter, tests) { - t.Fail() - } - return - } - - for _, test := range tests { - r.Run(test.Name, test.F) - } -} - -// Filtering method according to set regular expression -// specified command-line argument -m -func methodFilter(name string) (bool, error) { - if ok, _ := regexp.MatchString("^Test", name); !ok { - return false, nil - } - return regexp.MatchString(*matchMethod, name) -} - -type runner interface { - Run(name string, f func(t *testing.T)) bool -} diff --git a/src/vendor/github.com/stretchr/testify/suite/suite_test.go b/src/vendor/github.com/stretchr/testify/suite/suite_test.go deleted file mode 100644 index 6dfba08cd17f3e97743e60913545c92cf5e377ea..0000000000000000000000000000000000000000 --- a/src/vendor/github.com/stretchr/testify/suite/suite_test.go +++ /dev/null @@ -1,412 +0,0 @@ -package suite - -import ( - "errors" - "io/ioutil" - "os" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// SuiteRequireTwice is intended to test the usage of suite.Require in two -// different tests -type SuiteRequireTwice struct{ Suite } - -// TestSuiteRequireTwice checks for regressions of issue #149 where -// suite.requirements was not initialised in suite.SetT() -// A regression would result on these tests panicking rather than failing. -func TestSuiteRequireTwice(t *testing.T) { - ok := testing.RunTests( - allTestsFilter, - []testing.InternalTest{{ - Name: "TestSuiteRequireTwice", - F: func(t *testing.T) { - suite := new(SuiteRequireTwice) - Run(t, suite) - }, - }}, - ) - assert.Equal(t, false, ok) -} - -func (s *SuiteRequireTwice) TestRequireOne() { - r := s.Require() - r.Equal(1, 2) -} - -func (s *SuiteRequireTwice) TestRequireTwo() { - r := s.Require() - r.Equal(1, 2) -} - -type panickingSuite struct { - Suite - panicInSetupSuite bool - panicInSetupTest bool - panicInBeforeTest bool - panicInTest bool - panicInAfterTest bool - panicInTearDownTest bool - panicInTearDownSuite bool -} - -func (s *panickingSuite) SetupSuite() { - if s.panicInSetupSuite { - panic("oops in setup suite") - } -} - -func (s *panickingSuite) SetupTest() { - if s.panicInSetupTest { - panic("oops in setup test") - } -} - -func (s *panickingSuite) BeforeTest(_, _ string) { - if s.panicInBeforeTest { - panic("oops in before test") - } -} - -func (s *panickingSuite) Test() { - if s.panicInTest { - panic("oops in test") - } -} - -func (s *panickingSuite) AfterTest(_, _ string) { - if s.panicInAfterTest { - panic("oops in after test") - } -} - -func (s *panickingSuite) TearDownTest() { - if s.panicInTearDownTest { - panic("oops in tear down test") - } -} - -func (s *panickingSuite) TearDownSuite() { - if s.panicInTearDownSuite { - panic("oops in tear down suite") - } -} - -func TestSuiteRecoverPanic(t *testing.T) { - ok := true - panickingTests := []testing.InternalTest{ - { - Name: "TestPanicInSetupSuite", - F: func(t *testing.T) { Run(t, &panickingSuite{panicInSetupSuite: true}) }, - }, - { - Name: "TestPanicInSetupTest", - F: func(t *testing.T) { Run(t, &panickingSuite{panicInSetupTest: true}) }, - }, - { - Name: "TestPanicInBeforeTest", - F: func(t *testing.T) { Run(t, &panickingSuite{panicInBeforeTest: true}) }, - }, - { - Name: "TestPanicInTest", - F: func(t *testing.T) { Run(t, &panickingSuite{panicInTest: true}) }, - }, - { - Name: "TestPanicInAfterTest", - F: func(t *testing.T) { Run(t, &panickingSuite{panicInAfterTest: true}) }, - }, - { - Name: "TestPanicInTearDownTest", - F: func(t *testing.T) { Run(t, &panickingSuite{panicInTearDownTest: true}) }, - }, - { - Name: "TestPanicInTearDownSuite", - F: func(t *testing.T) { Run(t, &panickingSuite{panicInTearDownSuite: true}) }, - }, - } - - require.NotPanics(t, func() { - ok = testing.RunTests(allTestsFilter, panickingTests) - }) - - assert.False(t, ok) -} - -// This suite is intended to store values to make sure that only -// testing-suite-related methods are run. It's also a fully -// functional example of a testing suite, using setup/teardown methods -// and a helper method that is ignored by testify. To make this look -// more like a real world example, all tests in the suite perform some -// type of assertion. -type SuiteTester struct { - // Include our basic suite logic. - Suite - - // Keep counts of how many times each method is run. - SetupSuiteRunCount int - TearDownSuiteRunCount int - SetupTestRunCount int - TearDownTestRunCount int - TestOneRunCount int - TestTwoRunCount int - TestSubtestRunCount int - NonTestMethodRunCount int - - SuiteNameBefore []string - TestNameBefore []string - - SuiteNameAfter []string - TestNameAfter []string - - TimeBefore []time.Time - TimeAfter []time.Time -} - -type SuiteSkipTester struct { - // Include our basic suite logic. - Suite - - // Keep counts of how many times each method is run. - SetupSuiteRunCount int - TearDownSuiteRunCount int -} - -// The SetupSuite method will be run by testify once, at the very -// start of the testing suite, before any tests are run. -func (suite *SuiteTester) SetupSuite() { - suite.SetupSuiteRunCount++ -} - -func (suite *SuiteTester) BeforeTest(suiteName, testName string) { - suite.SuiteNameBefore = append(suite.SuiteNameBefore, suiteName) - suite.TestNameBefore = append(suite.TestNameBefore, testName) - suite.TimeBefore = append(suite.TimeBefore, time.Now()) -} - -func (suite *SuiteTester) AfterTest(suiteName, testName string) { - suite.SuiteNameAfter = append(suite.SuiteNameAfter, suiteName) - suite.TestNameAfter = append(suite.TestNameAfter, testName) - suite.TimeAfter = append(suite.TimeAfter, time.Now()) -} - -func (suite *SuiteSkipTester) SetupSuite() { - suite.SetupSuiteRunCount++ - suite.T().Skip() -} - -// The TearDownSuite method will be run by testify once, at the very -// end of the testing suite, after all tests have been run. -func (suite *SuiteTester) TearDownSuite() { - suite.TearDownSuiteRunCount++ -} - -func (suite *SuiteSkipTester) TearDownSuite() { - suite.TearDownSuiteRunCount++ -} - -// The SetupTest method will be run before every test in the suite. -func (suite *SuiteTester) SetupTest() { - suite.SetupTestRunCount++ -} - -// The TearDownTest method will be run after every test in the suite. -func (suite *SuiteTester) TearDownTest() { - suite.TearDownTestRunCount++ -} - -// Every method in a testing suite that begins with "Test" will be run -// as a test. TestOne is an example of a test. For the purposes of -// this example, we've included assertions in the tests, since most -// tests will issue assertions. -func (suite *SuiteTester) TestOne() { - beforeCount := suite.TestOneRunCount - suite.TestOneRunCount++ - assert.Equal(suite.T(), suite.TestOneRunCount, beforeCount+1) - suite.Equal(suite.TestOneRunCount, beforeCount+1) -} - -// TestTwo is another example of a test. -func (suite *SuiteTester) TestTwo() { - beforeCount := suite.TestTwoRunCount - suite.TestTwoRunCount++ - assert.NotEqual(suite.T(), suite.TestTwoRunCount, beforeCount) - suite.NotEqual(suite.TestTwoRunCount, beforeCount) -} - -func (suite *SuiteTester) TestSkip() { - suite.T().Skip() -} - -// NonTestMethod does not begin with "Test", so it will not be run by -// testify as a test in the suite. This is useful for creating helper -// methods for your tests. -func (suite *SuiteTester) NonTestMethod() { - suite.NonTestMethodRunCount++ -} - -func (suite *SuiteTester) TestSubtest() { - suite.TestSubtestRunCount++ - - for _, t := range []struct { - testName string - }{ - {"first"}, - {"second"}, - } { - suiteT := suite.T() - suite.Run(t.testName, func() { - // We should get a different *testing.T for subtests, so that - // go test recognizes them as proper subtests for output formatting - // and running individual subtests - subTestT := suite.T() - suite.NotEqual(subTestT, suiteT) - }) - suite.Equal(suiteT, suite.T()) - } -} - -// TestRunSuite will be run by the 'go test' command, so within it, we -// can run our suite using the Run(*testing.T, TestingSuite) function. -func TestRunSuite(t *testing.T) { - suiteTester := new(SuiteTester) - Run(t, suiteTester) - - // Normally, the test would end here. The following are simply - // some assertions to ensure that the Run function is working as - // intended - they are not part of the example. - - // The suite was only run once, so the SetupSuite and TearDownSuite - // methods should have each been run only once. - assert.Equal(t, suiteTester.SetupSuiteRunCount, 1) - assert.Equal(t, suiteTester.TearDownSuiteRunCount, 1) - - assert.Equal(t, len(suiteTester.SuiteNameAfter), 4) - assert.Equal(t, len(suiteTester.SuiteNameBefore), 4) - assert.Equal(t, len(suiteTester.TestNameAfter), 4) - assert.Equal(t, len(suiteTester.TestNameBefore), 4) - - assert.Contains(t, suiteTester.TestNameAfter, "TestOne") - assert.Contains(t, suiteTester.TestNameAfter, "TestTwo") - assert.Contains(t, suiteTester.TestNameAfter, "TestSkip") - assert.Contains(t, suiteTester.TestNameAfter, "TestSubtest") - - assert.Contains(t, suiteTester.TestNameBefore, "TestOne") - assert.Contains(t, suiteTester.TestNameBefore, "TestTwo") - assert.Contains(t, suiteTester.TestNameBefore, "TestSkip") - assert.Contains(t, suiteTester.TestNameBefore, "TestSubtest") - - for _, suiteName := range suiteTester.SuiteNameAfter { - assert.Equal(t, "SuiteTester", suiteName) - } - - for _, suiteName := range suiteTester.SuiteNameBefore { - assert.Equal(t, "SuiteTester", suiteName) - } - - for _, when := range suiteTester.TimeAfter { - assert.False(t, when.IsZero()) - } - - for _, when := range suiteTester.TimeBefore { - assert.False(t, when.IsZero()) - } - - // There are four test methods (TestOne, TestTwo, TestSkip, and TestSubtest), so - // the SetupTest and TearDownTest methods (which should be run once for - // each test) should have been run four times. - assert.Equal(t, suiteTester.SetupTestRunCount, 4) - assert.Equal(t, suiteTester.TearDownTestRunCount, 4) - - // Each test should have been run once. - assert.Equal(t, suiteTester.TestOneRunCount, 1) - assert.Equal(t, suiteTester.TestTwoRunCount, 1) - assert.Equal(t, suiteTester.TestSubtestRunCount, 1) - - // Methods that don't match the test method identifier shouldn't - // have been run at all. - assert.Equal(t, suiteTester.NonTestMethodRunCount, 0) - - suiteSkipTester := new(SuiteSkipTester) - Run(t, suiteSkipTester) - - // The suite was only run once, so the SetupSuite and TearDownSuite - // methods should have each been run only once, even though SetupSuite - // called Skip() - assert.Equal(t, suiteSkipTester.SetupSuiteRunCount, 1) - assert.Equal(t, suiteSkipTester.TearDownSuiteRunCount, 1) - -} - -func TestSuiteGetters(t *testing.T) { - suite := new(SuiteTester) - suite.SetT(t) - assert.NotNil(t, suite.Assert()) - assert.Equal(t, suite.Assertions, suite.Assert()) - assert.NotNil(t, suite.Require()) - assert.Equal(t, suite.require, suite.Require()) -} - -type SuiteLoggingTester struct { - Suite -} - -func (s *SuiteLoggingTester) TestLoggingPass() { - s.T().Log("TESTLOGPASS") -} - -func (s *SuiteLoggingTester) TestLoggingFail() { - s.T().Log("TESTLOGFAIL") - assert.NotNil(s.T(), nil) // expected to fail -} - -type StdoutCapture struct { - oldStdout *os.File - readPipe *os.File -} - -func (sc *StdoutCapture) StartCapture() { - sc.oldStdout = os.Stdout - sc.readPipe, os.Stdout, _ = os.Pipe() -} - -func (sc *StdoutCapture) StopCapture() (string, error) { - if sc.oldStdout == nil || sc.readPipe == nil { - return "", errors.New("StartCapture not called before StopCapture") - } - os.Stdout.Close() - os.Stdout = sc.oldStdout - bytes, err := ioutil.ReadAll(sc.readPipe) - if err != nil { - return "", err - } - return string(bytes), nil -} - -func TestSuiteLogging(t *testing.T) { - suiteLoggingTester := new(SuiteLoggingTester) - capture := StdoutCapture{} - internalTest := testing.InternalTest{ - Name: "SomeTest", - F: func(subT *testing.T) { - Run(subT, suiteLoggingTester) - }, - } - capture.StartCapture() - testing.RunTests(allTestsFilter, []testing.InternalTest{internalTest}) - output, err := capture.StopCapture() - require.NoError(t, err, "Got an error trying to capture stdout and stderr!") - require.NotEmpty(t, output, "output content must not be empty") - - // Failed tests' output is always printed - assert.Contains(t, output, "TESTLOGFAIL") - - if testing.Verbose() { - // In verbose mode, output from successful tests is also printed - assert.Contains(t, output, "TESTLOGPASS") - } else { - assert.NotContains(t, output, "TESTLOGPASS") - } -} diff --git a/src/vendor/modules.txt b/src/vendor/modules.txt new file mode 100644 index 0000000000000000000000000000000000000000..36b99b9e6a2f52b2ed518887b76ab3f1a40f2ccc --- /dev/null +++ b/src/vendor/modules.txt @@ -0,0 +1,14 @@ +# github.com/davecgh/go-spew v1.1.1 +github.com/davecgh/go-spew/spew +# github.com/opencontainers/runtime-spec v1.0.1 +## explicit +github.com/opencontainers/runtime-spec/specs-go +# github.com/pelletier/go-toml v1.4.0 +## explicit +github.com/pelletier/go-toml +# github.com/pmezard/go-difflib v1.0.0 +github.com/pmezard/go-difflib/difflib +# github.com/stretchr/testify v1.3.0 +## explicit +github.com/stretchr/testify/assert +github.com/stretchr/testify/require